repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/fastcgi/reader.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/fastcgi/caddyfile.go
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" "slices" "strconv" "strings" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/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 { d.Next() // consume transport name 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 // # This redirection is automatically disabled if "{http.request.uri.path}/index.php" // # doesn't appear in the try_files list // @canonicalPath { // file {path}/index.php // not path */ // } // redir @canonicalPath {path}/ 308 // // # If the requested file does not exist, try index files and assume index.php always exists // @indexFiles file { // try_files {path} {path}/index.php index.php // try_policy first_exist_fallback // 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 var 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" { var dirRedir bool dirIndex := "{http.request.uri.path}/" + indexFile tryPolicy := "first_exist_fallback" // if tryFiles wasn't overridden, use a reasonable default if len(tryFiles) == 0 { tryFiles = []string{"{http.request.uri.path}", dirIndex, indexFile} dirRedir = true } else { if !strings.HasSuffix(tryFiles[len(tryFiles)-1], ".php") { // use first_exist strategy if the last file is not a PHP file tryPolicy = "" } dirRedir = slices.Contains(tryFiles, dirIndex) } if dirRedir { // route to redirect to canonical path if index PHP file redirMatcherSet := caddy.ModuleMap{ "file": h.JSON(fileserver.MatchFile{ TryFiles: []string{dirIndex}, }), "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}/{http.request.orig_uri.prefixed_query}"}}, } redirRoute := caddyhttp.Route{ MatcherSetsRaw: []caddy.ModuleMap{redirMatcherSet}, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(redirHandler, "handler", "static_response", nil)}, } routes = append(routes, redirRoute) } // route to rewrite to PHP index file rewriteMatcherSet := caddy.ModuleMap{ "file": h.JSON(fileserver.MatchFile{ TryFiles: tryFiles, TryPolicy: tryPolicy, 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, 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
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 } // DefaultBufferSizes enables request buffering for fastcgi if not configured. // This is because most fastcgi servers are php-fpm that require the content length to be set to read the body, golang // std has fastcgi implementation that doesn't need this value to process the body, but we can safely assume that's // not used. // http3 requests have a negative content length for GET and HEAD requests, if that header is not sent. // see: https://github.com/caddyserver/caddy/issues/6678#issuecomment-2472224182 // Though it appears even if CONTENT_LENGTH is invalid, php-fpm can handle just fine if the body is empty (no Stdin records sent). // php-fpm will hang if there is any data in the body though, https://github.com/caddyserver/caddy/issues/5420#issuecomment-2415943516 // TODO: better default buffering for fastcgi requests without content length, in theory a value of 1 should be enough, make it bigger anyway func (t Transport) DefaultBufferSizes() (int64, int64) { return 4096, 0 } // 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), ) if c := t.logger.Check(zapcore.DebugLevel, "roundtrip"); c != nil { c.Write( 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 := caddy.FastAbs(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) _ reverseproxy.BufferedTransport = (*Transport)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/fastcgi/client_test.go
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 content } 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 content } 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 content } 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 p, m } func DisabledTest(t *testing.T) { // TODO: test chunked reader globalt = t // 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/fastcgi/header.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/fastcgi/pool.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/fastcgi/record.go
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 err } if err = binary.Read(r, binary.BigEndian, &rec.h); err != nil { return err } if rec.h.Version != 1 { err = errors.New("fcgi: invalid header version") return err } if rec.h.Type == EndRequest { err = io.EOF return err } rec.lr.N = int64(rec.h.ContentLength) rec.padding = int64(rec.h.PaddingLength) return err } 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/reverseproxy/forwardauth/caddyfile.go
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" "sort" "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. We must have at least one // route in the response handler, even if it's no-op, so that the // response handling logic in reverse_proxy doesn't skip this entry. goodResponseHandler := caddyhttp.ResponseHandler{ Match: &caddyhttp.ResponseMatcher{ StatusCode: []int{2}, }, Routes: []caddyhttp.Route{ { HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject( &caddyhttp.VarsMiddleware{}, "handler", "vars", nil, )}, }, }, } // Sort the headers so that the order in the JSON output is deterministic. sortedHeadersToCopy := make([]string, 0, len(headersToCopy)) for k := range headersToCopy { sortedHeadersToCopy = append(sortedHeadersToCopy, k) } sort.Strings(sortedHeadersToCopy) // Set up handlers to copy headers from the auth response onto the // original request. We use vars matchers to test that the placeholder // values aren't empty, because the header handler would not replace // placeholders which have no value. copyHeaderRoutes := []caddyhttp.Route{} for _, from := range sortedHeadersToCopy { to := http.CanonicalHeaderKey(headersToCopy[from]) placeholderName := "http.reverse_proxy.header." + http.CanonicalHeaderKey(from) handler := &headers.Handler{ Request: &headers.HeaderOps{ Set: http.Header{ to: []string{"{" + placeholderName + "}"}, }, }, } copyHeaderRoutes = append(copyHeaderRoutes, caddyhttp.Route{ MatcherSetsRaw: []caddy.ModuleMap{{ "not": h.JSON(caddyhttp.MatchNot{MatcherSetsRaw: []caddy.ModuleMap{{ "vars": h.JSON(caddyhttp.VarsMatcher{"{" + placeholderName + "}": []string{""}}), }}}), }}, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject( handler, "handler", "headers", nil, )}, }) } goodResponseHandler.Routes = append(goodResponseHandler.Routes, copyHeaderRoutes...) // 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/caddyauth/argon2id.go
modules/caddyhttp/caddyauth/argon2id.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package caddyauth import ( "crypto/rand" "crypto/subtle" "encoding/base64" "fmt" "strconv" "strings" "golang.org/x/crypto/argon2" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(Argon2idHash{}) } const ( argon2idName = "argon2id" defaultArgon2idTime = 1 defaultArgon2idMemory = 46 * 1024 defaultArgon2idThreads = 1 defaultArgon2idKeylen = 32 defaultSaltLength = 16 ) // Argon2idHash implements the Argon2id password hashing. type Argon2idHash struct { salt []byte time uint32 memory uint32 threads uint8 keyLen uint32 } // CaddyModule returns the Caddy module information. func (Argon2idHash) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.authentication.hashes.argon2id", New: func() caddy.Module { return new(Argon2idHash) }, } } // Compare checks if the plaintext password matches the given Argon2id hash. func (Argon2idHash) Compare(hashed, plaintext []byte) (bool, error) { argHash, storedKey, err := DecodeHash(hashed) if err != nil { return false, err } computedKey := argon2.IDKey( plaintext, argHash.salt, argHash.time, argHash.memory, argHash.threads, argHash.keyLen, ) return subtle.ConstantTimeCompare(storedKey, computedKey) == 1, nil } // Hash generates an Argon2id hash of the given plaintext using the configured parameters and salt. func (b Argon2idHash) Hash(plaintext []byte) ([]byte, error) { if b.salt == nil { s, err := generateSalt(defaultSaltLength) if err != nil { return nil, err } b.salt = s } key := argon2.IDKey( plaintext, b.salt, b.time, b.memory, b.threads, b.keyLen, ) hash := fmt.Sprintf( "$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, b.memory, b.time, b.threads, base64.RawStdEncoding.EncodeToString(b.salt), base64.RawStdEncoding.EncodeToString(key), ) return []byte(hash), nil } // DecodeHash parses an Argon2id PHC string into an Argon2idHash struct and returns the struct along with the derived key. func DecodeHash(hash []byte) (*Argon2idHash, []byte, error) { parts := strings.Split(string(hash), "$") if len(parts) != 6 { return nil, nil, fmt.Errorf("invalid hash format") } if parts[1] != argon2idName { return nil, nil, fmt.Errorf("unsupported variant: %s", parts[1]) } version, err := strconv.Atoi(strings.TrimPrefix(parts[2], "v=")) if err != nil { return nil, nil, fmt.Errorf("invalid version: %w", err) } if version != argon2.Version { return nil, nil, fmt.Errorf("incompatible version: %d", version) } params := strings.Split(parts[3], ",") if len(params) != 3 { return nil, nil, fmt.Errorf("invalid parameters") } mem, err := strconv.ParseUint(strings.TrimPrefix(params[0], "m="), 10, 32) if err != nil { return nil, nil, fmt.Errorf("invalid memory parameter: %w", err) } iter, err := strconv.ParseUint(strings.TrimPrefix(params[1], "t="), 10, 32) if err != nil { return nil, nil, fmt.Errorf("invalid iterations parameter: %w", err) } threads, err := strconv.ParseUint(strings.TrimPrefix(params[2], "p="), 10, 8) if err != nil { return nil, nil, fmt.Errorf("invalid parallelism parameter: %w", err) } salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[4]) if err != nil { return nil, nil, fmt.Errorf("decode salt: %w", err) } key, err := base64.RawStdEncoding.Strict().DecodeString(parts[5]) if err != nil { return nil, nil, fmt.Errorf("decode key: %w", err) } return &Argon2idHash{ salt: salt, time: uint32(iter), memory: uint32(mem), threads: uint8(threads), keyLen: uint32(len(key)), }, key, nil } // FakeHash returns a constant fake hash for timing attacks mitigation. func (Argon2idHash) FakeHash() []byte { // hashed with the following command: // caddy hash-password --plaintext "antitiming" --algorithm "argon2id" return []byte("$argon2id$v=19$m=47104,t=1,p=1$P2nzckEdTZ3bxCiBCkRTyA$xQL3Z32eo5jKl7u5tcIsnEKObYiyNZQQf5/4sAau6Pg") } // Interface guards var ( _ Comparer = (*Argon2idHash)(nil) _ Hasher = (*Argon2idHash)(nil) ) func generateSalt(length int) ([]byte, error) { salt := make([]byte, length) if _, err := rand.Read(salt); err != nil { return nil, fmt.Errorf("failed to generate salt: %w", err) } return salt, nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/caddyauth/caddyfile.go
modules/caddyhttp/caddyauth/caddyfile.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package caddyauth import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { httpcaddyfile.RegisterHandlerDirective("basicauth", parseCaddyfile) // deprecated httpcaddyfile.RegisterHandlerDirective("basic_auth", parseCaddyfile) } // parseCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // basic_auth [<matcher>] [<hash_algorithm> [<realm>]] { // <username> <hashed_password> // ... // } // // If no hash algorithm is supplied, bcrypt will be assumed. func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { h.Next() // consume directive name // "basicauth" is deprecated, replaced by "basic_auth" if h.Val() == "basicauth" { caddy.Log().Named("config.adapter.caddyfile").Warn("the 'basicauth' directive is deprecated, please use 'basic_auth' instead!") } var ba HTTPBasicAuth ba.HashCache = new(Cache) var cmp Comparer args := h.RemainingArgs() var hashName string switch len(args) { case 0: hashName = bcryptName case 1: hashName = args[0] case 2: hashName = args[0] ba.Realm = args[1] default: return nil, h.ArgErr() } switch hashName { case bcryptName: cmp = BcryptHash{} case argon2idName: cmp = Argon2idHash{} default: return nil, h.Errf("unrecognized hash algorithm: %s", hashName) } ba.HashRaw = caddyconfig.JSONModuleObject(cmp, "algorithm", hashName, nil) for h.NextBlock(0) { username := h.Val() var b64Pwd string h.Args(&b64Pwd) if h.NextArg() { return nil, h.ArgErr() } if username == "" || b64Pwd == "" { return nil, h.Err("username and password cannot be empty or missing") } ba.AccountList = append(ba.AccountList, Account{ Username: username, Password: b64Pwd, }) } return Authentication{ ProvidersRaw: caddy.ModuleMap{ "http_basic": caddyconfig.JSON(ba, nil), }, }, nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/caddyauth/bcrypt.go
modules/caddyhttp/caddyauth/bcrypt.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package caddyauth import ( "errors" "golang.org/x/crypto/bcrypt" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(BcryptHash{}) } // defaultBcryptCost cost 14 strikes a solid balance between security, usability, and hardware performance const ( bcryptName = "bcrypt" defaultBcryptCost = 14 ) // BcryptHash implements the bcrypt hash. type BcryptHash struct { // cost is the bcrypt hashing difficulty factor (work factor). // Higher values increase computation time and security. cost int } // CaddyModule returns the Caddy module information. func (BcryptHash) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.authentication.hashes.bcrypt", New: func() caddy.Module { return new(BcryptHash) }, } } // Compare compares passwords. func (BcryptHash) Compare(hashed, plaintext []byte) (bool, error) { err := bcrypt.CompareHashAndPassword(hashed, plaintext) if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) { return false, nil } if err != nil { return false, err } return true, nil } // Hash hashes plaintext using a random salt. func (b BcryptHash) Hash(plaintext []byte) ([]byte, error) { cost := b.cost if cost < bcrypt.MinCost || cost > bcrypt.MaxCost { cost = defaultBcryptCost } return bcrypt.GenerateFromPassword(plaintext, cost) } // FakeHash returns a fake hash. func (BcryptHash) FakeHash() []byte { // hashed with the following command: // caddy hash-password --plaintext "antitiming" --algorithm "bcrypt" return []byte("$2a$14$X3ulqf/iGxnf1k6oMZ.RZeJUoqI9PX2PM4rS5lkIKJXduLGXGPrt6") } // Interface guards var ( _ Comparer = (*BcryptHash)(nil) _ Hasher = (*BcryptHash)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/caddyauth/command.go
modules/caddyhttp/caddyauth/command.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package caddyauth import ( "bufio" "bytes" "fmt" "os" "os/signal" "github.com/spf13/cobra" "golang.org/x/term" caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/caddyserver/caddy/v2" ) func init() { caddycmd.RegisterCommand(caddycmd.Command{ Name: "hash-password", Usage: "[--plaintext <password>] [--algorithm <argon2id|bcrypt>] [--bcrypt-cost <difficulty>] [--argon2id-time <iterations>] [--argon2id-memory <KiB>] [--argon2id-threads <n>] [--argon2id-keylen <bytes>]", Short: "Hashes a password and writes base64", Long: ` Convenient way to hash a plaintext password. The resulting hash is written to stdout as a base64 string. --plaintext The password to hash. If omitted, it will be read from stdin. If Caddy is attached to a controlling TTY, the input will not be echoed. --algorithm Selects the hashing algorithm. Valid options are: * 'argon2id' (recommended for modern security) * 'bcrypt' (legacy, slower, configurable cost) bcrypt-specific parameters: --bcrypt-cost Sets the bcrypt hashing difficulty. Higher values increase security by making the hash computation slower and more CPU-intensive. Must be within the valid range [bcrypt.MinCost, bcrypt.MaxCost]. If omitted or invalid, the default cost is used. Argon2id-specific parameters: --argon2id-time Number of iterations to perform. Increasing this makes hashing slower and more resistant to brute-force attacks. --argon2id-memory Amount of memory to use during hashing. Larger values increase resistance to GPU/ASIC attacks. --argon2id-threads Number of CPU threads to use. Increase for faster hashing on multi-core systems. --argon2id-keylen Length of the resulting hash in bytes. Longer keys increase security but slightly increase storage size. `, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("plaintext", "p", "", "The plaintext password") cmd.Flags().StringP("algorithm", "a", bcryptName, "Name of the hash algorithm") cmd.Flags().Int("bcrypt-cost", defaultBcryptCost, "Bcrypt hashing cost (only used with 'bcrypt' algorithm)") cmd.Flags().Uint32("argon2id-time", defaultArgon2idTime, "Number of iterations for Argon2id hashing. Increasing this makes the hash slower and more resistant to brute-force attacks.") cmd.Flags().Uint32("argon2id-memory", defaultArgon2idMemory, "Memory to use in KiB for Argon2id hashing. Larger values increase resistance to GPU/ASIC attacks.") cmd.Flags().Uint8("argon2id-threads", defaultArgon2idThreads, "Number of CPU threads to use for Argon2id hashing. Increase for faster hashing on multi-core systems.") cmd.Flags().Uint32("argon2id-keylen", defaultArgon2idKeylen, "Length of the resulting Argon2id hash in bytes. Longer hashes increase security but slightly increase storage size.") cmd.RunE = caddycmd.WrapCommandFuncForCobra(cmdHashPassword) }, }) } func cmdHashPassword(fs caddycmd.Flags) (int, error) { var err error algorithm := fs.String("algorithm") plaintext := []byte(fs.String("plaintext")) bcryptCost := fs.Int("bcrypt-cost") if len(plaintext) == 0 { fd := int(os.Stdin.Fd()) if term.IsTerminal(fd) { // ensure the terminal state is restored on SIGINT state, _ := term.GetState(fd) c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) go func() { <-c _ = term.Restore(fd, state) os.Exit(caddy.ExitCodeFailedStartup) }() defer signal.Stop(c) fmt.Fprint(os.Stderr, "Enter password: ") plaintext, err = term.ReadPassword(fd) fmt.Fprintln(os.Stderr) if err != nil { return caddy.ExitCodeFailedStartup, err } fmt.Fprint(os.Stderr, "Confirm password: ") confirmation, err := term.ReadPassword(fd) fmt.Fprintln(os.Stderr) if err != nil { return caddy.ExitCodeFailedStartup, err } if !bytes.Equal(plaintext, confirmation) { return caddy.ExitCodeFailedStartup, fmt.Errorf("password does not match") } } else { rd := bufio.NewReader(os.Stdin) plaintext, err = rd.ReadBytes('\n') if err != nil { return caddy.ExitCodeFailedStartup, err } plaintext = plaintext[:len(plaintext)-1] // Trailing newline } if len(plaintext) == 0 { return caddy.ExitCodeFailedStartup, fmt.Errorf("plaintext is required") } } var hash []byte var hashString string switch algorithm { case bcryptName: hash, err = BcryptHash{cost: bcryptCost}.Hash(plaintext) hashString = string(hash) case argon2idName: time, err := fs.GetUint32("argon2id-time") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("failed to get argon2id time parameter: %w", err) } memory, err := fs.GetUint32("argon2id-memory") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("failed to get argon2id memory parameter: %w", err) } threads, err := fs.GetUint8("argon2id-threads") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("failed to get argon2id threads parameter: %w", err) } keyLen, err := fs.GetUint32("argon2id-keylen") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("failed to get argon2id keylen parameter: %w", err) } hash, _ = Argon2idHash{ time: time, memory: memory, threads: threads, keyLen: keyLen, }.Hash(plaintext) hashString = string(hash) default: return caddy.ExitCodeFailedStartup, fmt.Errorf("unrecognized hash algorithm: %s", algorithm) } if err != nil { return caddy.ExitCodeFailedStartup, err } fmt.Println(hashString) return 0, nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/caddyauth/caddyauth.go
modules/caddyhttp/caddyauth/caddyauth.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package caddyauth import ( "fmt" "net/http" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Authentication{}) } // Authentication is a middleware which provides user authentication. // Rejects requests with HTTP 401 if the request is not authenticated. // // After a successful authentication, the placeholder // `{http.auth.user.id}` will be set to the username, and also // `{http.auth.user.*}` placeholders may be set for any authentication // modules that provide user metadata. // // In case of an error, the placeholder `{http.auth.<provider>.error}` // will be set to the error message returned by the authentication // provider. // // Its API is still experimental and may be subject to change. type Authentication struct { // A set of authentication providers. If none are specified, // all requests will always be unauthenticated. ProvidersRaw caddy.ModuleMap `json:"providers,omitempty" caddy:"namespace=http.authentication.providers"` Providers map[string]Authenticator `json:"-"` logger *zap.Logger } // CaddyModule returns the Caddy module information. func (Authentication) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.authentication", New: func() caddy.Module { return new(Authentication) }, } } // Provision sets up an Authentication module by initializing its logger, // loading and registering all configured authentication providers. func (a *Authentication) Provision(ctx caddy.Context) error { a.logger = ctx.Logger() a.Providers = make(map[string]Authenticator) mods, err := ctx.LoadModule(a, "ProvidersRaw") if err != nil { return fmt.Errorf("loading authentication providers: %v", err) } for modName, modIface := range mods.(map[string]any) { a.Providers[modName] = modIface.(Authenticator) } return nil } func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) var user User var authed bool var err error for provName, prov := range a.Providers { user, authed, err = prov.Authenticate(w, r) if err != nil { if c := a.logger.Check(zapcore.ErrorLevel, "auth provider returned error"); c != nil { c.Write(zap.String("provider", provName), zap.Error(err)) } // Set the error from the authentication provider in a placeholder, // so it can be used in the handle_errors directive. repl.Set("http.auth."+provName+".error", err.Error()) continue } if authed { break } } if !authed { return caddyhttp.Error(http.StatusUnauthorized, fmt.Errorf("not authenticated")) } repl.Set("http.auth.user.id", user.ID) for k, v := range user.Metadata { repl.Set("http.auth.user."+k, v) } return next.ServeHTTP(w, r) } // Authenticator is a type which can authenticate a request. // If a request was not authenticated, it returns false. An // error is only returned if authenticating the request fails // for a technical reason (not for bad/missing credentials). type Authenticator interface { Authenticate(http.ResponseWriter, *http.Request) (User, bool, error) } // User represents an authenticated user. type User struct { // The ID of the authenticated user. ID string // Any other relevant data about this // user. Keys should be adhere to Caddy // conventions (snake_casing), as all // keys will be made available as // placeholders. Metadata map[string]string } // Interface guards var ( _ caddy.Provisioner = (*Authentication)(nil) _ caddyhttp.MiddlewareHandler = (*Authentication)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/caddyauth/basicauth.go
modules/caddyhttp/caddyauth/basicauth.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package caddyauth import ( "encoding/base64" "encoding/hex" "encoding/json" "fmt" weakrand "math/rand" "net/http" "strings" "sync" "golang.org/x/sync/singleflight" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(HTTPBasicAuth{}) } // HTTPBasicAuth facilitates HTTP basic authentication. type HTTPBasicAuth struct { // The algorithm with which the passwords are hashed. Default: bcrypt HashRaw json.RawMessage `json:"hash,omitempty" caddy:"namespace=http.authentication.hashes inline_key=algorithm"` // The list of accounts to authenticate. AccountList []Account `json:"accounts,omitempty"` // The name of the realm. Default: restricted Realm string `json:"realm,omitempty"` // If non-nil, a mapping of plaintext passwords to their // hashes will be cached in memory (with random eviction). // This can greatly improve the performance of traffic-heavy // servers that use secure password hashing algorithms, with // the downside that plaintext passwords will be stored in // memory for a longer time (this should not be a problem // as long as your machine is not compromised, at which point // all bets are off, since basicauth necessitates plaintext // passwords being received over the wire anyway). Note that // a cache hit does not mean it is a valid password. HashCache *Cache `json:"hash_cache,omitempty"` Accounts map[string]Account `json:"-"` Hash Comparer `json:"-"` // fakePassword is used when a given user is not found, // so that timing side-channels can be mitigated: it gives // us something to hash and compare even if the user does // not exist, which should have similar timing as a user // account that does exist. fakePassword []byte } // CaddyModule returns the Caddy module information. func (HTTPBasicAuth) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.authentication.providers.http_basic", New: func() caddy.Module { return new(HTTPBasicAuth) }, } } // Provision provisions the HTTP basic auth provider. func (hba *HTTPBasicAuth) Provision(ctx caddy.Context) error { if hba.HashRaw == nil { hba.HashRaw = json.RawMessage(`{"algorithm": "bcrypt"}`) } // load password hasher hasherIface, err := ctx.LoadModule(hba, "HashRaw") if err != nil { return fmt.Errorf("loading password hasher module: %v", err) } hba.Hash = hasherIface.(Comparer) if hba.Hash == nil { return fmt.Errorf("hash is required") } // if supported, generate a fake password we can compare against if needed if hasher, ok := hba.Hash.(Hasher); ok { hba.fakePassword = hasher.FakeHash() } repl := caddy.NewReplacer() // load account list hba.Accounts = make(map[string]Account) for i, acct := range hba.AccountList { if _, ok := hba.Accounts[acct.Username]; ok { return fmt.Errorf("account %d: username is not unique: %s", i, acct.Username) } acct.Username = repl.ReplaceAll(acct.Username, "") acct.Password = repl.ReplaceAll(acct.Password, "") if acct.Username == "" || acct.Password == "" { return fmt.Errorf("account %d: username and password are required", i) } // TODO: Remove support for redundantly-encoded b64-encoded hashes // Passwords starting with '$' are likely in Modular Crypt Format, // so we don't need to base64 decode them. But historically, we // required redundant base64, so we try to decode it otherwise. if strings.HasPrefix(acct.Password, "$") { acct.password = []byte(acct.Password) } else { acct.password, err = base64.StdEncoding.DecodeString(acct.Password) if err != nil { return fmt.Errorf("base64-decoding password: %v", err) } } hba.Accounts[acct.Username] = acct } hba.AccountList = nil // allow GC to deallocate if hba.HashCache != nil { hba.HashCache.cache = make(map[string]bool) hba.HashCache.mu = new(sync.RWMutex) hba.HashCache.g = new(singleflight.Group) } return nil } // Authenticate validates the user credentials in req and returns the user, if valid. func (hba HTTPBasicAuth) Authenticate(w http.ResponseWriter, req *http.Request) (User, bool, error) { username, plaintextPasswordStr, ok := req.BasicAuth() if !ok { return hba.promptForCredentials(w, nil) } account, accountExists := hba.Accounts[username] if !accountExists { // don't return early if account does not exist; we want // to try to avoid side-channels that leak existence, so // we use a fake password to simulate realistic CPU cycles account.password = hba.fakePassword } same, err := hba.correctPassword(account, []byte(plaintextPasswordStr)) if err != nil || !same || !accountExists { return hba.promptForCredentials(w, err) } return User{ID: username}, true, nil } func (hba HTTPBasicAuth) correctPassword(account Account, plaintextPassword []byte) (bool, error) { compare := func() (bool, error) { return hba.Hash.Compare(account.password, plaintextPassword) } // if no caching is enabled, simply return the result of hashing + comparing if hba.HashCache == nil { return compare() } // compute a cache key that is unique for these input parameters cacheKey := hex.EncodeToString(append(account.password, plaintextPassword...)) // fast track: if the result of the input is already cached, use it hba.HashCache.mu.RLock() same, ok := hba.HashCache.cache[cacheKey] hba.HashCache.mu.RUnlock() if ok { return same, nil } // slow track: do the expensive op, then add it to the cache // but perform it in a singleflight group so that multiple // parallel requests using the same password don't cause a // thundering herd problem by all performing the same hashing // operation before the first one finishes and caches it. v, err, _ := hba.HashCache.g.Do(cacheKey, func() (any, error) { return compare() }) if err != nil { return false, err } same = v.(bool) hba.HashCache.mu.Lock() if len(hba.HashCache.cache) >= 1000 { hba.HashCache.makeRoom() // keep cache size under control } hba.HashCache.cache[cacheKey] = same hba.HashCache.mu.Unlock() return same, nil } func (hba HTTPBasicAuth) promptForCredentials(w http.ResponseWriter, err error) (User, bool, error) { // browsers show a message that says something like: // "The website says: <realm>" // which is kinda dumb, but whatever. realm := hba.Realm if realm == "" { realm = "restricted" } w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm)) return User{}, false, err } // Cache enables caching of basic auth results. This is especially // helpful for secure password hashes which can be expensive to // compute on every HTTP request. type Cache struct { mu *sync.RWMutex g *singleflight.Group // map of concatenated hashed password + plaintext password, to result cache map[string]bool } // makeRoom deletes about 1/10 of the items in the cache // in order to keep its size under control. It must not be // called without a lock on c.mu. func (c *Cache) makeRoom() { // we delete more than just 1 entry so that we don't have // to do this on every request; assuming the capacity of // the cache is on a long tail, we can save a lot of CPU // time by doing a whole bunch of deletions now and then // we won't have to do them again for a while numToDelete := max(len(c.cache)/10, 1) for deleted := 0; deleted <= numToDelete; deleted++ { // Go maps are "nondeterministic" not actually random, // so although we could just chop off the "front" of the // map with less code, this is a heavily skewed eviction // strategy; generating random numbers is cheap and // ensures a much better distribution. //nolint:gosec rnd := weakrand.Intn(len(c.cache)) i := 0 for key := range c.cache { if i == rnd { delete(c.cache, key) break } i++ } } } // Comparer is a type that can securely compare // a plaintext password with a hashed password // in constant-time. Comparers should hash the // plaintext password and then use constant-time // comparison. type Comparer interface { // Compare returns true if the result of hashing // plaintextPassword is hashedPassword, false // otherwise. An error is returned only if // there is a technical/configuration error. Compare(hashedPassword, plaintextPassword []byte) (bool, error) } // Hasher is a type that can generate a secure hash // given a plaintext. Hashing modules which implement // this interface can be used with the hash-password // subcommand as well as benefitting from anti-timing // features. A hasher also returns a fake hash which // can be used for timing side-channel mitigation. type Hasher interface { Hash(plaintext []byte) ([]byte, error) FakeHash() []byte } // Account contains a username and password. type Account struct { // A user's username. Username string `json:"username"` // The user's hashed password, in Modular Crypt Format (with `$` prefix) // or base64-encoded. Password string `json:"password"` password []byte } // Interface guards var ( _ caddy.Provisioner = (*HTTPBasicAuth)(nil) _ Authenticator = (*HTTPBasicAuth)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/headers/caddyfile.go
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) { h.Next() // consume directive name matcherSet, err := h.ExtractMatcherSet() if err != nil { return nil, err } h.Next() // consume the directive name again (matcher parsing resets) makeHandler := func() Handler { return Handler{ Response: &RespHeaderOps{ HeaderOps: &HeaderOps{}, }, } } handler, handlerWithRequire := makeHandler(), makeHandler() // first see if headers are in the initial line var hasArgs bool if h.NextArg() { hasArgs = true field := h.Val() var value string var replacement *string if h.NextArg() { value = h.Val() } if h.NextArg() { arg := h.Val() replacement = &arg } 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 field == "match" { responseMatchers := make(map[string]caddyhttp.ResponseMatcher) err := caddyhttp.ParseNamedResponseMatcher(h.NewFromNextSegment(), responseMatchers) if err != nil { return nil, err } matcher := responseMatchers["match"] handler.Response.Require = &matcher 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 string var replacement *string if h.NextArg() { value = h.Val() } if h.NextArg() { arg := h.Val() replacement = &arg } 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) { h.Next() // consume directive name matcherSet, err := h.ExtractMatcherSet() if err != nil { return nil, err } h.Next() // consume the directive name again (matcher parsing resets) configValues := []httpcaddyfile.ConfigValue{} 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 string var replacement *string if h.NextArg() { value = h.Val() } if h.NextArg() { arg := h.Val() replacement = &arg 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-nil, 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 string, replacement *string) error { return applyHeaderOp(ops, nil, field, value, replacement) } func applyHeaderOp(ops *HeaderOps, respHeaderOps *RespHeaderOps, field, value string, 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 != nil: // 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/headers/headers_test.go
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"}, }, }, { // same as above, but checks that response headers are left alone when "Require" conditions are unmet 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{ "Cache-Control": []string{"something"}, }, expectedRespHeader: http.Header{ "Cache-Control": []string{"something"}, }, }, { 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) } func TestContainsPlaceholders(t *testing.T) { for i, tc := range []struct { input string expected bool }{ {"static", false}, {"{placeholder}", true}, {"prefix-{placeholder}-suffix", true}, {"{}", false}, {"no-braces", false}, {"{unclosed", false}, {"unopened}", false}, } { actual := containsPlaceholders(tc.input) if actual != tc.expected { t.Errorf("Test %d: containsPlaceholders(%q) = %v, expected %v", i, tc.input, actual, tc.expected) } } } func TestHeaderProvisionSkipsPlaceholders(t *testing.T) { ops := &HeaderOps{ Replace: map[string][]Replacement{ "Static": { Replacement{SearchRegexp: ":443", Replace: "STATIC"}, }, "Dynamic": { Replacement{SearchRegexp: ":{http.request.local.port}", Replace: "DYNAMIC"}, }, }, } err := ops.Provision(caddy.Context{}) if err != nil { t.Fatalf("Provision failed: %v", err) } // Static regex should be precompiled if ops.Replace["Static"][0].re == nil { t.Error("Expected static regex to be precompiled") } // Dynamic regex with placeholder should not be precompiled if ops.Replace["Dynamic"][0].re != nil { t.Error("Expected dynamic regex with placeholder to not be precompiled") } } func TestPlaceholderInSearchRegexp(t *testing.T) { handler := Handler{ Response: &RespHeaderOps{ HeaderOps: &HeaderOps{ Replace: map[string][]Replacement{ "Test-Header": { Replacement{ SearchRegexp: ":{http.request.local.port}", Replace: "PLACEHOLDER-WORKS", }, }, }, }, }, } // Provision the handler err := handler.Provision(caddy.Context{}) if err != nil { t.Fatalf("Provision failed: %v", err) } replacement := handler.Response.HeaderOps.Replace["Test-Header"][0] t.Logf("After provision - SearchRegexp: %q, re: %v", replacement.SearchRegexp, replacement.re) rr := httptest.NewRecorder() req := httptest.NewRequest("GET", "http://localhost:443/", nil) repl := caddy.NewReplacer() repl.Set("http.request.local.port", "443") ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) rr.Header().Set("Test-Header", "prefix:443suffix") t.Logf("Initial header: %v", rr.Header()) next := nextHandler(func(w http.ResponseWriter, r *http.Request) error { w.WriteHeader(200) return nil }) err = handler.ServeHTTP(rr, req, next) if err != nil { t.Fatalf("ServeHTTP failed: %v", err) } t.Logf("Final header: %v", rr.Header()) result := rr.Header().Get("Test-Header") expected := "prefixPLACEHOLDER-WORKSsuffix" if result != expected { t.Errorf("Expected header value %q, got %q", expected, result) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/headers/headers.go
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 && h.Response.HeaderOps != 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 { if ops == nil { return nil // it's possible no ops are configured; fix #6893 } for fieldName, replacements := range ops.Replace { for i, r := range replacements { if r.SearchRegexp == "" { continue } // Check if it contains placeholders if containsPlaceholders(r.SearchRegexp) { // Contains placeholders, skips precompilation, and recompiles at runtime continue } // Does not contain placeholders, safe to precompile 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 } // containsPlaceholders checks if the string contains Caddy placeholder syntax {key} func containsPlaceholders(s string) bool { openIdx := strings.Index(s, "{") if openIdx == -1 { return false } closeIdx := strings.Index(s[openIdx+1:], "}") if closeIdx == -1 { return false } // Make sure there is content between the brackets return closeIdx > 0 } 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. Superseded 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) { if ops == nil { return } // 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 == "*" { clear(hdr) } } // 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 { // Use precompiled regular expressions hdr[fieldName][i] = r.re.ReplaceAllString(hdr[fieldName][i], replace) } else if r.SearchRegexp != "" { // Runtime compilation of regular expressions searchRegexp := repl.ReplaceKnown(r.SearchRegexp, "") if re, err := regexp.Compile(searchRegexp); err == nil { hdr[fieldName][i] = re.ReplaceAllString(hdr[fieldName][i], replace) } // If compilation fails, skip this replacement } 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 if r.SearchRegexp != "" { searchRegexp := repl.ReplaceKnown(r.SearchRegexp, "") if re, err := regexp.Compile(searchRegexp); err == nil { hdr[hdrFieldName][i] = 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/fileserver/matcher_test.go
modules/caddyhttp/fileserver/matcher_test.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fileserver import ( "context" "net/http" "net/http/httptest" "net/url" "os" "runtime" "testing" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/internal/filesystems" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func TestFileMatcher(t *testing.T) { // Windows doesn't like colons in files names isWindows := runtime.GOOS == "windows" if !isWindows { filename := "with:in-name.txt" f, err := os.Create("./testdata/" + filename) if err != nil { t.Fail() return } t.Cleanup(func() { os.Remove("./testdata/" + filename) }) f.WriteString(filename) f.Close() } for i, tc := range []struct { path string expectedPath string expectedType string matched bool }{ { path: "/foo.txt", expectedPath: "/foo.txt", expectedType: "file", matched: true, }, { path: "/foo.txt/", expectedPath: "/foo.txt", expectedType: "file", matched: true, }, { path: "/foo.txt?a=b", expectedPath: "/foo.txt", expectedType: "file", matched: true, }, { path: "/foodir", expectedPath: "/foodir/", expectedType: "directory", matched: true, }, { path: "/foodir/", expectedPath: "/foodir/", expectedType: "directory", matched: true, }, { path: "/foodir/foo.txt", expectedPath: "/foodir/foo.txt", expectedType: "file", matched: true, }, { path: "/missingfile.php", matched: false, }, { path: "ملف.txt", // the path file name is not escaped expectedPath: "/ملف.txt", expectedType: "file", matched: true, }, { path: url.PathEscape("ملف.txt"), // singly-escaped path expectedPath: "/ملف.txt", expectedType: "file", matched: true, }, { path: url.PathEscape(url.PathEscape("ملف.txt")), // doubly-escaped path expectedPath: "/%D9%85%D9%84%D9%81.txt", expectedType: "file", matched: true, }, { path: "./with:in-name.txt", // browsers send the request with the path as such expectedPath: "/with:in-name.txt", expectedType: "file", matched: !isWindows, }, } { m := &MatchFile{ fsmap: &filesystems.FileSystemMap{}, Root: "./testdata", TryFiles: []string{"{http.request.uri.path}", "{http.request.uri.path}/"}, } u, err := url.Parse(tc.path) if err != nil { t.Errorf("Test %d: parsing path: %v", i, err) } req := &http.Request{URL: u} repl := caddyhttp.NewTestReplacer(req) result, err := m.MatchWithError(req) if err != nil { t.Errorf("Test %d: unexpected error: %v", i, err) } if result != tc.matched { t.Errorf("Test %d: expected match=%t, got %t", i, tc.matched, result) } rel, ok := repl.Get("http.matchers.file.relative") if !ok && result { t.Errorf("Test %d: expected replacer value", i) } if !result { continue } if rel != tc.expectedPath { t.Errorf("Test %d: actual path: %v, expected: %v", i, rel, tc.expectedPath) } fileType, _ := repl.Get("http.matchers.file.type") if fileType != tc.expectedType { t.Errorf("Test %d: actual file type: %v, expected: %v", i, fileType, tc.expectedType) } } } func TestPHPFileMatcher(t *testing.T) { for i, tc := range []struct { path string expectedPath string expectedType string matched bool }{ { path: "/index.php", expectedPath: "/index.php", expectedType: "file", matched: true, }, { path: "/index.php/somewhere", expectedPath: "/index.php", expectedType: "file", matched: true, }, { path: "/remote.php", expectedPath: "/remote.php", expectedType: "file", matched: true, }, { path: "/remote.php/somewhere", expectedPath: "/remote.php", expectedType: "file", matched: true, }, { path: "/missingfile.php", matched: false, }, { path: "/notphp.php.txt", expectedPath: "/notphp.php.txt", expectedType: "file", matched: true, }, { path: "/notphp.php.txt/", expectedPath: "/notphp.php.txt", expectedType: "file", matched: true, }, { path: "/notphp.php.txt.suffixed", matched: false, }, { path: "/foo.php.php/index.php", expectedPath: "/foo.php.php/index.php", expectedType: "file", matched: true, }, { // See https://github.com/caddyserver/caddy/issues/3623 path: "/%E2%C3", expectedPath: "/%E2%C3", expectedType: "file", matched: false, }, { path: "/index.php?path={path}&{query}", expectedPath: "/index.php", expectedType: "file", matched: true, }, } { m := &MatchFile{ fsmap: &filesystems.FileSystemMap{}, Root: "./testdata", TryFiles: []string{"{http.request.uri.path}", "{http.request.uri.path}/index.php"}, SplitPath: []string{".php"}, } u, err := url.Parse(tc.path) if err != nil { t.Errorf("Test %d: parsing path: %v", i, err) } req := &http.Request{URL: u} repl := caddyhttp.NewTestReplacer(req) result, err := m.MatchWithError(req) if err != nil { t.Errorf("Test %d: unexpected error: %v", i, err) } if result != tc.matched { t.Errorf("Test %d: expected match=%t, got %t", i, tc.matched, result) } rel, ok := repl.Get("http.matchers.file.relative") if !ok && result { t.Errorf("Test %d: expected replacer value", i) } if !result { continue } if rel != tc.expectedPath { t.Errorf("Test %d: actual path: %v, expected: %v", i, rel, tc.expectedPath) } fileType, _ := repl.Get("http.matchers.file.type") if fileType != tc.expectedType { t.Errorf("Test %d: actual file type: %v, expected: %v", i, fileType, tc.expectedType) } } } func TestFirstSplit(t *testing.T) { m := MatchFile{ SplitPath: []string{".php"}, fsmap: &filesystems.FileSystemMap{}, } actual, remainder := m.firstSplit("index.PHP/somewhere") expected := "index.PHP" expectedRemainder := "/somewhere" if actual != expected { t.Errorf("Expected split %s but got %s", expected, actual) } if remainder != expectedRemainder { t.Errorf("Expected remainder %s but got %s", expectedRemainder, remainder) } } var expressionTests = []struct { name string expression *caddyhttp.MatchExpression urlTarget string httpMethod string httpHeader *http.Header wantErr bool wantResult bool clientCertificate []byte expectedPath string }{ { name: "file error no args (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file()`, }, urlTarget: "https://example.com/foo.txt", wantResult: true, }, { name: "file error bad try files (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({"try_file": ["bad_arg"]})`, }, urlTarget: "https://example.com/foo", wantErr: true, }, { name: "file match short pattern index.php (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file("index.php")`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "file match short pattern foo.txt (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({http.request.uri.path})`, }, urlTarget: "https://example.com/foo.txt", wantResult: true, }, { name: "file match index.php (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}, "/index.php"]})`, }, urlTarget: "https://example.com/foo", wantResult: true, }, { name: "file match long pattern foo.txt (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}]})`, }, urlTarget: "https://example.com/foo.txt", wantResult: true, }, { name: "file match long pattern foo.txt with concatenation (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({"root": ".", "try_files": ["./testdata" + {http.request.uri.path}]})`, }, urlTarget: "https://example.com/foo.txt", wantResult: true, }, { name: "file not match long pattern (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}]})`, }, urlTarget: "https://example.com/nopenope.txt", wantResult: false, }, { name: "file match long pattern foo.txt with try_policy (MatchFile)", expression: &caddyhttp.MatchExpression{ Expr: `file({"root": "./testdata", "try_policy": "largest_size", "try_files": ["foo.txt", "large.txt"]})`, }, urlTarget: "https://example.com/", wantResult: true, expectedPath: "/large.txt", }, } func TestMatchExpressionMatch(t *testing.T) { for _, tst := range expressionTests { tc := tst t.Run(tc.name, func(t *testing.T) { caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() err := tc.expression.Provision(caddyCtx) if err != nil { if !tc.wantErr { t.Errorf("MatchExpression.Provision() error = %v, wantErr %v", err, tc.wantErr) } return } req := httptest.NewRequest(tc.httpMethod, tc.urlTarget, nil) if tc.httpHeader != nil { req.Header = *tc.httpHeader } repl := caddyhttp.NewTestReplacer(req) repl.Set("http.vars.root", "./testdata") ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) req = req.WithContext(ctx) matches, err := tc.expression.MatchWithError(req) if err != nil { t.Errorf("MatchExpression.Match() error = %v", err) return } if matches != tc.wantResult { t.Errorf("MatchExpression.Match() expected to return '%t', for expression : '%s'", tc.wantResult, tc.expression.Expr) } if tc.expectedPath != "" { path, ok := repl.Get("http.matchers.file.relative") if !ok { t.Errorf("MatchExpression.Match() expected to return path '%s', but got none", tc.expectedPath) } if path != tc.expectedPath { t.Errorf("MatchExpression.Match() expected to return path '%s', but got '%s'", tc.expectedPath, path) } } }) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/fileserver/browse.go
modules/caddyhttp/fileserver/browse.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fileserver import ( "bytes" "context" _ "embed" "encoding/json" "errors" "fmt" "io" "io/fs" "net/http" "os" "path" "strings" "sync" "text/tabwriter" "text/template" "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/templates" ) // BrowseTemplate is the default template document to use for // file listings. By default, its default value is an embedded // document. You can override this value at program start, or // if you are running Caddy via config, you can specify a // custom template_file in the browse configuration. // //go:embed browse.html var BrowseTemplate string // Browse configures directory browsing. type Browse struct { // Filename of the template to use instead of the embedded browse template. TemplateFile string `json:"template_file,omitempty"` // Determines whether or not targets of symlinks should be revealed. RevealSymlinks bool `json:"reveal_symlinks,omitempty"` // Override the default sort. // It includes the following options: // - sort_by: name(default), namedirfirst, size, time // - order: asc(default), desc // eg.: // - `sort time desc` will sort by time in descending order // - `sort size` will sort by size in ascending order // The first option must be `sort_by` and the second option must be `order` (if exists). SortOptions []string `json:"sort,omitempty"` // FileLimit limits the number of up to n DirEntry values in directory order. FileLimit int `json:"file_limit,omitempty"` } const ( defaultDirEntryLimit = 10000 ) func (fsrv *FileServer) serveBrowse(fileSystem fs.FS, root, dirPath string, w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { if c := fsrv.logger.Check(zapcore.DebugLevel, "browse enabled; listing directory contents"); c != nil { c.Write(zap.String("path", dirPath), zap.String("root", root)) } // Navigation on the client-side gets messed up if the // URL doesn't end in a trailing slash because hrefs to // "b/c" at path "/a" end up going to "/b/c" instead // of "/a/b/c" - so we have to redirect in this case // so that the path is "/a/" and the client constructs // relative hrefs "b/c" to be "/a/b/c". // // Only redirect if the last element of the path (the filename) was not // rewritten; if the admin wanted to rewrite to the canonical path, they // would have, and we have to be very careful not to introduce unwanted // redirects and especially redirect loops! (Redirecting using the // original URI is necessary because that's the URI the browser knows, // we don't want to redirect from internally-rewritten URIs.) // See https://github.com/caddyserver/caddy/issues/4205. // We also redirect if the path is empty, because this implies the path // prefix was fully stripped away by a `handle_path` handler for example. // See https://github.com/caddyserver/caddy/issues/4466. origReq := r.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request) if r.URL.Path == "" || path.Base(origReq.URL.Path) == path.Base(r.URL.Path) { if !strings.HasSuffix(origReq.URL.Path, "/") { if c := fsrv.logger.Check(zapcore.DebugLevel, "redirecting to trailing slash to preserve hrefs"); c != nil { c.Write(zap.String("request_path", r.URL.Path)) } return redirect(w, r, origReq.URL.Path+"/") } } dir, err := fsrv.openFile(fileSystem, dirPath, w) if err != nil { return err } defer dir.Close() repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) // TODO: not entirely sure if path.Clean() is necessary here but seems like a safe plan (i.e. /%2e%2e%2f) - someone could verify this listing, err := fsrv.loadDirectoryContents(r.Context(), fileSystem, dir.(fs.ReadDirFile), root, path.Clean(r.URL.EscapedPath()), repl) switch { case errors.Is(err, fs.ErrPermission): return caddyhttp.Error(http.StatusForbidden, err) case errors.Is(err, fs.ErrNotExist): return fsrv.notFound(w, r, next) case err != nil: return caddyhttp.Error(http.StatusInternalServerError, err) } w.Header().Add("Vary", "Accept, Accept-Encoding") // speed up browser/client experience and caching by supporting If-Modified-Since if ifModSinceStr := r.Header.Get("If-Modified-Since"); ifModSinceStr != "" { // basically a copy of stdlib file server's handling of If-Modified-Since ifModSince, err := http.ParseTime(ifModSinceStr) if err == nil && listing.lastModified.Truncate(time.Second).Compare(ifModSince) <= 0 { w.WriteHeader(http.StatusNotModified) return nil } } fsrv.browseApplyQueryParams(w, r, listing) buf := bufPool.Get().(*bytes.Buffer) buf.Reset() defer bufPool.Put(buf) acceptHeader := strings.ToLower(strings.Join(r.Header["Accept"], ",")) w.Header().Set("Last-Modified", listing.lastModified.Format(http.TimeFormat)) switch { case strings.Contains(acceptHeader, "application/json"): if err := json.NewEncoder(buf).Encode(listing.Items); err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } w.Header().Set("Content-Type", "application/json; charset=utf-8") case strings.Contains(acceptHeader, "text/plain"): writer := tabwriter.NewWriter(buf, 0, 8, 1, '\t', tabwriter.AlignRight) // Header on top if _, err := fmt.Fprintln(writer, "Name\tSize\tModified"); err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } // Lines to separate the header if _, err := fmt.Fprintln(writer, "----\t----\t--------"); err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } // Actual files for _, item := range listing.Items { if _, err := fmt.Fprintf(writer, "%s\t%s\t%s\n", item.Name, item.HumanSize(), item.HumanModTime("January 2, 2006 at 15:04:05"), ); err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } } if err := writer.Flush(); err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } w.Header().Set("Content-Type", "text/plain; charset=utf-8") default: var fs http.FileSystem if fsrv.Root != "" { fs = http.Dir(repl.ReplaceAll(fsrv.Root, ".")) } tplCtx := &templateContext{ TemplateContext: templates.TemplateContext{ Root: fs, Req: r, RespHeader: templates.WrappedHeader{Header: w.Header()}, }, browseTemplateContext: listing, } tpl, err := fsrv.makeBrowseTemplate(tplCtx) if err != nil { return fmt.Errorf("parsing browse template: %v", err) } if err := tpl.Execute(buf, tplCtx); err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } w.Header().Set("Content-Type", "text/html; charset=utf-8") } _, _ = buf.WriteTo(w) return nil } func (fsrv *FileServer) loadDirectoryContents(ctx context.Context, fileSystem fs.FS, dir fs.ReadDirFile, root, urlPath string, repl *caddy.Replacer) (*browseTemplateContext, error) { // modTime for the directory itself stat, err := dir.Stat() if err != nil { return nil, err } dirLimit := defaultDirEntryLimit if fsrv.Browse.FileLimit != 0 { dirLimit = fsrv.Browse.FileLimit } files, err := dir.ReadDir(dirLimit) if err != nil && err != io.EOF { return nil, err } // user can presumably browse "up" to parent folder if path is longer than "/" canGoUp := len(urlPath) > 1 return fsrv.directoryListing(ctx, fileSystem, stat.ModTime(), files, canGoUp, root, urlPath, repl), nil } // browseApplyQueryParams applies query parameters to the listing. // It mutates the listing and may set cookies. func (fsrv *FileServer) browseApplyQueryParams(w http.ResponseWriter, r *http.Request, listing *browseTemplateContext) { var orderParam, sortParam string // The configs in Caddyfile have lower priority than Query params, // so put it at first. for idx, item := range fsrv.Browse.SortOptions { // Only `sort` & `order`, 2 params are allowed if idx >= 2 { break } switch item { case sortByName, sortByNameDirFirst, sortBySize, sortByTime: sortParam = item case sortOrderAsc, sortOrderDesc: orderParam = item } } layoutParam := r.URL.Query().Get("layout") limitParam := r.URL.Query().Get("limit") offsetParam := r.URL.Query().Get("offset") sortParamTmp := r.URL.Query().Get("sort") if sortParamTmp != "" { sortParam = sortParamTmp } orderParamTmp := r.URL.Query().Get("order") if orderParamTmp != "" { orderParam = orderParamTmp } switch layoutParam { case "list", "grid", "": listing.Layout = layoutParam default: listing.Layout = "list" } // figure out what to sort by switch sortParam { case "": sortParam = sortByNameDirFirst if sortCookie, sortErr := r.Cookie("sort"); sortErr == nil { sortParam = sortCookie.Value } case sortByName, sortByNameDirFirst, sortBySize, sortByTime: http.SetCookie(w, &http.Cookie{Name: "sort", Value: sortParam, Secure: r.TLS != nil}) } // then figure out the order switch orderParam { case "": orderParam = sortOrderAsc if orderCookie, orderErr := r.Cookie("order"); orderErr == nil { orderParam = orderCookie.Value } case sortOrderAsc, sortOrderDesc: http.SetCookie(w, &http.Cookie{Name: "order", Value: orderParam, Secure: r.TLS != nil}) } // finally, apply the sorting and limiting listing.applySortAndLimit(sortParam, orderParam, limitParam, offsetParam) } // makeBrowseTemplate creates the template to be used for directory listings. func (fsrv *FileServer) makeBrowseTemplate(tplCtx *templateContext) (*template.Template, error) { var tpl *template.Template var err error if fsrv.Browse.TemplateFile != "" { tpl = tplCtx.NewTemplate(path.Base(fsrv.Browse.TemplateFile)) tpl, err = tpl.ParseFiles(fsrv.Browse.TemplateFile) if err != nil { return nil, fmt.Errorf("parsing browse template file: %v", err) } } else { tpl = tplCtx.NewTemplate("default_listing") tpl, err = tpl.Parse(BrowseTemplate) if err != nil { return nil, fmt.Errorf("parsing default browse template: %v", err) } } return tpl, nil } // isSymlinkTargetDir returns true if f's symbolic link target // is a directory. func (fsrv *FileServer) isSymlinkTargetDir(fileSystem fs.FS, f fs.FileInfo, root, urlPath string) bool { if !isSymlink(f) { return false } target := caddyhttp.SanitizedPathJoin(root, path.Join(urlPath, f.Name())) targetInfo, err := fs.Stat(fileSystem, target) if err != nil { return false } return targetInfo.IsDir() } // isSymlink return true if f is a symbolic link. func isSymlink(f fs.FileInfo) bool { return f.Mode()&os.ModeSymlink != 0 } // templateContext powers the context used when evaluating the browse template. // It combines browse-specific features with the standard templates handler // features. type templateContext struct { templates.TemplateContext *browseTemplateContext } // bufPool is used to increase the efficiency of file listings. var bufPool = sync.Pool{ New: func() any { return new(bytes.Buffer) }, }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/fileserver/staticfiles_test.go
modules/caddyhttp/fileserver/staticfiles_test.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fileserver import ( "path/filepath" "runtime" "strings" "testing" ) func TestFileHidden(t *testing.T) { for i, tc := range []struct { inputHide []string inputPath string expect bool }{ { inputHide: nil, inputPath: "", expect: false, }, { inputHide: []string{".gitignore"}, inputPath: "/.gitignore", expect: true, }, { inputHide: []string{".git"}, inputPath: "/.gitignore", expect: false, }, { inputHide: []string{"/.git"}, inputPath: "/.gitignore", expect: false, }, { inputHide: []string{".git"}, inputPath: "/.git", expect: true, }, { inputHide: []string{".git"}, inputPath: "/.git/foo", expect: true, }, { inputHide: []string{".git"}, inputPath: "/foo/.git/bar", expect: true, }, { inputHide: []string{"/prefix"}, inputPath: "/prefix/foo", expect: true, }, { inputHide: []string{"/foo/*/bar"}, inputPath: "/foo/asdf/bar", expect: true, }, { inputHide: []string{"*.txt"}, inputPath: "/foo/bar.txt", expect: true, }, { inputHide: []string{"/foo/bar/*.txt"}, inputPath: "/foo/bar/baz.txt", expect: true, }, { inputHide: []string{"/foo/bar/*.txt"}, inputPath: "/foo/bar.txt", expect: false, }, { inputHide: []string{"/foo/bar/*.txt"}, inputPath: "/foo/bar/index.html", expect: false, }, { inputHide: []string{"/foo"}, inputPath: "/foo", expect: true, }, { inputHide: []string{"/foo"}, inputPath: "/foobar", expect: false, }, { inputHide: []string{"first", "second"}, inputPath: "/second", expect: true, }, } { if runtime.GOOS == "windows" { if strings.HasPrefix(tc.inputPath, "/") { tc.inputPath, _ = filepath.Abs(tc.inputPath) } tc.inputPath = filepath.FromSlash(tc.inputPath) for i := range tc.inputHide { if strings.HasPrefix(tc.inputHide[i], "/") { tc.inputHide[i], _ = filepath.Abs(tc.inputHide[i]) } tc.inputHide[i] = filepath.FromSlash(tc.inputHide[i]) } } actual := fileHidden(tc.inputPath, tc.inputHide) if actual != tc.expect { t.Errorf("Test %d: Does %v hide %s? Got %t but expected %t", i, tc.inputHide, tc.inputPath, actual, tc.expect) } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/fileserver/staticfiles.go
modules/caddyhttp/fileserver/staticfiles.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fileserver import ( "bytes" "errors" "fmt" "io" "io/fs" weakrand "math/rand" "mime" "net/http" "os" "path" "path/filepath" "runtime" "strconv" "strings" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(FileServer{}) } // FileServer implements a handler that serves static files. // // The path of the file to serve is constructed by joining the site root // and the sanitized request path. Any and all files within the root and // links with targets outside the site root may therefore be accessed. // For example, with a site root of `/www`, requests to `/foo/bar.txt` // will serve the file at `/www/foo/bar.txt`. // // The request path is sanitized using the Go standard library's // path.Clean() function (https://pkg.go.dev/path#Clean) before being // joined to the root. Request paths must be valid and well-formed. // // For requests that access directories instead of regular files, // Caddy will attempt to serve an index file if present. For example, // a request to `/dir/` will attempt to serve `/dir/index.html` if // it exists. The index file names to try are configurable. If a // requested directory does not have an index file, Caddy writes a // 404 response. Alternatively, file browsing can be enabled with // the "browse" parameter which shows a list of files when directories // are requested if no index file is present. If "browse" is enabled, // Caddy may serve a JSON array of the directory listing when the `Accept` // header mentions `application/json` with the following structure: // // [{ // "name": "", // "size": 0, // "url": "", // "mod_time": "", // "mode": 0, // "is_dir": false, // "is_symlink": false // }] // // with the `url` being relative to the request path and `mod_time` in the RFC 3339 format // with sub-second precision. For any other value for the `Accept` header, the // respective browse template is executed with `Content-Type: text/html`. // // By default, this handler will canonicalize URIs so that requests to // directories end with a slash, but requests to regular files do not. // This is enforced with HTTP redirects automatically and can be disabled. // Canonicalization redirects are not issued, however, if a URI rewrite // modified the last component of the path (the filename). // // This handler sets the Etag and Last-Modified headers for static files. // It does not perform MIME sniffing to determine Content-Type based on // contents, but does use the extension (if known); see the Go docs for // details: https://pkg.go.dev/mime#TypeByExtension // // The file server properly handles requests with If-Match, // If-Unmodified-Since, If-Modified-Since, If-None-Match, Range, and // If-Range headers. It includes the file's modification time in the // Last-Modified header of the response. type FileServer struct { // The file system implementation to use. By default, Caddy uses the local // disk file system. // // if a non default filesystem is used, it must be first be registered in the globals section. FileSystem string `json:"fs,omitempty"` // The path to the root of the site. Default is `{http.vars.root}` if set, // or current working directory otherwise. This should be a trusted value. // // Note that a site root is not a sandbox. Although the file server does // sanitize the request URI to prevent directory traversal, files (including // links) within the site root may be directly accessed based on the request // path. Files and folders within the root should be secure and trustworthy. Root string `json:"root,omitempty"` // A list of files or folders to hide; the file server will pretend as if // they don't exist. Accepts globular patterns like `*.ext` or `/foo/*/bar` // as well as placeholders. Because site roots can be dynamic, this list // uses file system paths, not request paths. To clarify, the base of // relative paths is the current working directory, NOT the site root. // // Entries without a path separator (`/` or `\` depending on OS) will match // any file or directory of that name regardless of its path. To hide only a // specific file with a name that may not be unique, always use a path // separator. For example, to hide all files or folder trees named "hidden", // put "hidden" in the list. To hide only ./hidden, put "./hidden" in the list. // // When possible, all paths are resolved to their absolute form before // comparisons are made. For maximum clarity and explictness, use complete, // absolute paths; or, for greater portability, use relative paths instead. Hide []string `json:"hide,omitempty"` // The names of files to try as index files if a folder is requested. // Default: index.html, index.txt. IndexNames []string `json:"index_names,omitempty"` // Enables file listings if a directory was requested and no index // file is present. Browse *Browse `json:"browse,omitempty"` // Use redirects to enforce trailing slashes for directories, or to // remove trailing slash from URIs for files. Default is true. // // Canonicalization will not happen if the last element of the request's // path (the filename) is changed in an internal rewrite, to avoid // clobbering the explicit rewrite with implicit behavior. CanonicalURIs *bool `json:"canonical_uris,omitempty"` // Override the status code written when successfully serving a file. // Particularly useful when explicitly serving a file as display for // an error, like a 404 page. A placeholder may be used. By default, // the status code will typically be 200, or 206 for partial content. StatusCode caddyhttp.WeakString `json:"status_code,omitempty"` // If pass-thru mode is enabled and a requested file is not found, // it will invoke the next handler in the chain instead of returning // a 404 error. By default, this is false (disabled). PassThru bool `json:"pass_thru,omitempty"` // Selection of encoders to use to check for precompressed files. PrecompressedRaw caddy.ModuleMap `json:"precompressed,omitempty" caddy:"namespace=http.precompressed"` // If the client has no strong preference (q-factor), choose these encodings in order. // If no order specified here, the first encoding from the Accept-Encoding header // that both client and server support is used PrecompressedOrder []string `json:"precompressed_order,omitempty"` precompressors map[string]encode.Precompressed // List of file extensions to try to read Etags from. // If set, file Etags will be read from sidecar files // with any of these suffixes, instead of generating // our own Etag. // Keep in mind that the Etag values in the files have to be quoted as per RFC7232. // See https://datatracker.ietf.org/doc/html/rfc7232#section-2.3 for a few examples. EtagFileExtensions []string `json:"etag_file_extensions,omitempty"` fsmap caddy.FileSystems logger *zap.Logger } // CaddyModule returns the Caddy module information. func (FileServer) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.file_server", New: func() caddy.Module { return new(FileServer) }, } } // Provision sets up the static files responder. func (fsrv *FileServer) Provision(ctx caddy.Context) error { fsrv.logger = ctx.Logger() fsrv.fsmap = ctx.FileSystems() if fsrv.FileSystem == "" { fsrv.FileSystem = "{http.vars.fs}" } if fsrv.Root == "" { fsrv.Root = "{http.vars.root}" } if fsrv.IndexNames == nil { fsrv.IndexNames = defaultIndexNames } // for hide paths that are static (i.e. no placeholders), we can transform them into // absolute paths before the server starts for very slight performance improvement for i, h := range fsrv.Hide { if !strings.Contains(h, "{") && strings.Contains(h, separator) { if abs, err := caddy.FastAbs(h); err == nil { fsrv.Hide[i] = abs } } } // support precompressed sidecar files mods, err := ctx.LoadModule(fsrv, "PrecompressedRaw") if err != nil { return fmt.Errorf("loading encoder modules: %v", err) } for modName, modIface := range mods.(map[string]any) { p, ok := modIface.(encode.Precompressed) if !ok { return fmt.Errorf("module %s is not precompressor", modName) } ae := p.AcceptEncoding() if ae == "" { return fmt.Errorf("precompressor does not specify an Accept-Encoding value") } suffix := p.Suffix() if suffix == "" { return fmt.Errorf("precompressor does not specify a Suffix value") } if _, ok := fsrv.precompressors[ae]; ok { return fmt.Errorf("precompressor already added: %s", ae) } if fsrv.precompressors == nil { fsrv.precompressors = make(map[string]encode.Precompressed) } fsrv.precompressors[ae] = p } if fsrv.Browse != nil { // check sort options for idx, sortOption := range fsrv.Browse.SortOptions { switch idx { case 0: if sortOption != sortByName && sortOption != sortByNameDirFirst && sortOption != sortBySize && sortOption != sortByTime { return fmt.Errorf("the first option must be one of the following: %s, %s, %s, %s, but got %s", sortByName, sortByNameDirFirst, sortBySize, sortByTime, sortOption) } case 1: if sortOption != sortOrderAsc && sortOption != sortOrderDesc { return fmt.Errorf("the second option must be one of the following: %s, %s, but got %s", sortOrderAsc, sortOrderDesc, sortOption) } default: return fmt.Errorf("only max 2 sort options are allowed, but got %d", idx+1) } } } return nil } func (fsrv *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if runtime.GOOS == "windows" { // reject paths with Alternate Data Streams (ADS) if strings.Contains(r.URL.Path, ":") { return caddyhttp.Error(http.StatusBadRequest, fmt.Errorf("illegal ADS path")) } // reject paths with "8.3" short names trimmedPath := strings.TrimRight(r.URL.Path, ". ") // Windows ignores trailing dots and spaces, sigh if len(path.Base(trimmedPath)) <= 12 && strings.Contains(trimmedPath, "~") { return caddyhttp.Error(http.StatusBadRequest, fmt.Errorf("illegal short name")) } // both of those could bypass file hiding or possibly leak information even if the file is not hidden } filesToHide := fsrv.transformHidePaths(repl) root := repl.ReplaceAll(fsrv.Root, ".") fsName := repl.ReplaceAll(fsrv.FileSystem, "") fileSystem, ok := fsrv.fsmap.Get(fsName) if !ok { return caddyhttp.Error(http.StatusNotFound, fmt.Errorf("filesystem not found")) } // remove any trailing `/` as it breaks fs.ValidPath() in the stdlib filename := strings.TrimSuffix(caddyhttp.SanitizedPathJoin(root, r.URL.Path), "/") if c := fsrv.logger.Check(zapcore.DebugLevel, "sanitized path join"); c != nil { c.Write( zap.String("site_root", root), zap.String("fs", fsName), zap.String("request_path", r.URL.Path), zap.String("result", filename), ) } // get information about the file info, err := fs.Stat(fileSystem, filename) if err != nil { err = fsrv.mapDirOpenError(fileSystem, err, filename) if errors.Is(err, fs.ErrNotExist) { return fsrv.notFound(w, r, next) } else if errors.Is(err, fs.ErrInvalid) { return caddyhttp.Error(http.StatusBadRequest, err) } else if errors.Is(err, fs.ErrPermission) { return caddyhttp.Error(http.StatusForbidden, err) } return caddyhttp.Error(http.StatusInternalServerError, err) } // if the request mapped to a directory, see if // there is an index file we can serve var implicitIndexFile bool if info.IsDir() && len(fsrv.IndexNames) > 0 { for _, indexPage := range fsrv.IndexNames { indexPage := repl.ReplaceAll(indexPage, "") indexPath := caddyhttp.SanitizedPathJoin(filename, indexPage) if fileHidden(indexPath, filesToHide) { // pretend this file doesn't exist if c := fsrv.logger.Check(zapcore.DebugLevel, "hiding index file"); c != nil { c.Write( zap.String("filename", indexPath), zap.Strings("files_to_hide", filesToHide), ) } continue } indexInfo, err := fs.Stat(fileSystem, indexPath) if err != nil { continue } // don't rewrite the request path to append // the index file, because we might need to // do a canonical-URL redirect below based // on the URL as-is // we've chosen to use this index file, // so replace the last file info and path // with that of the index file info = indexInfo filename = indexPath implicitIndexFile = true if c := fsrv.logger.Check(zapcore.DebugLevel, "located index file"); c != nil { c.Write(zap.String("filename", filename)) } break } } // if still referencing a directory, delegate // to browse or return an error if info.IsDir() { if c := fsrv.logger.Check(zapcore.DebugLevel, "no index file in directory"); c != nil { c.Write( zap.String("path", filename), zap.Strings("index_filenames", fsrv.IndexNames), ) } if fsrv.Browse != nil && !fileHidden(filename, filesToHide) { return fsrv.serveBrowse(fileSystem, root, filename, w, r, next) } return fsrv.notFound(w, r, next) } // one last check to ensure the file isn't hidden (we might // have changed the filename from when we last checked) if fileHidden(filename, filesToHide) { if c := fsrv.logger.Check(zapcore.DebugLevel, "hiding file"); c != nil { c.Write( zap.String("filename", filename), zap.Strings("files_to_hide", filesToHide), ) } return fsrv.notFound(w, r, next) } // if URL canonicalization is enabled, we need to enforce trailing // slash convention: if a directory, trailing slash; if a file, no // trailing slash - not enforcing this can break relative hrefs // in HTML (see https://github.com/caddyserver/caddy/issues/2741) if fsrv.CanonicalURIs == nil || *fsrv.CanonicalURIs { // Only redirect if the last element of the path (the filename) was not // rewritten; if the admin wanted to rewrite to the canonical path, they // would have, and we have to be very careful not to introduce unwanted // redirects and especially redirect loops! // See https://github.com/caddyserver/caddy/issues/4205. origReq := r.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request) if path.Base(origReq.URL.Path) == path.Base(r.URL.Path) { if implicitIndexFile && !strings.HasSuffix(origReq.URL.Path, "/") { to := origReq.URL.Path + "/" if c := fsrv.logger.Check(zapcore.DebugLevel, "redirecting to canonical URI (adding trailing slash for directory"); c != nil { c.Write( zap.String("from_path", origReq.URL.Path), zap.String("to_path", to), ) } return redirect(w, r, to) } else if !implicitIndexFile && strings.HasSuffix(origReq.URL.Path, "/") { to := origReq.URL.Path[:len(origReq.URL.Path)-1] if c := fsrv.logger.Check(zapcore.DebugLevel, "redirecting to canonical URI (removing trailing slash for file"); c != nil { c.Write( zap.String("from_path", origReq.URL.Path), zap.String("to_path", to), ) } return redirect(w, r, to) } } } var file fs.File respHeader := w.Header() // etag is usually unset, but if the user knows what they're doing, let them override it etag := respHeader.Get("Etag") // static file responses are often compressed, either on-the-fly // or with precompressed sidecar files; in any case, the headers // should contain "Vary: Accept-Encoding" even when not compressed // so caches can craft a reliable key (according to REDbot results) // see #5849 respHeader.Add("Vary", "Accept-Encoding") // check for precompressed files for _, ae := range encode.AcceptedEncodings(r, fsrv.PrecompressedOrder) { precompress, ok := fsrv.precompressors[ae] if !ok { continue } compressedFilename := filename + precompress.Suffix() compressedInfo, err := fs.Stat(fileSystem, compressedFilename) if err != nil || compressedInfo.IsDir() { if c := fsrv.logger.Check(zapcore.DebugLevel, "precompressed file not accessible"); c != nil { c.Write(zap.String("filename", compressedFilename), zap.Error(err)) } continue } if c := fsrv.logger.Check(zapcore.DebugLevel, "opening compressed sidecar file"); c != nil { c.Write(zap.String("filename", compressedFilename), zap.Error(err)) } file, err = fsrv.openFile(fileSystem, compressedFilename, w) if err != nil { if c := fsrv.logger.Check(zapcore.WarnLevel, "opening precompressed file failed"); c != nil { c.Write(zap.String("filename", compressedFilename), zap.Error(err)) } if caddyErr, ok := err.(caddyhttp.HandlerError); ok && caddyErr.StatusCode == http.StatusServiceUnavailable { return err } file = nil continue } defer file.Close() respHeader.Set("Content-Encoding", ae) // stdlib won't set Content-Length for non-range requests if Content-Encoding is set. // see: https://github.com/caddyserver/caddy/issues/7040 // Setting the Range header manually will result in 206 Partial Content. // see: https://github.com/caddyserver/caddy/issues/7250 if r.Header.Get("Range") == "" { respHeader.Set("Content-Length", strconv.FormatInt(compressedInfo.Size(), 10)) } // try to get the etag from pre computed files if an etag suffix list was provided if etag == "" && fsrv.EtagFileExtensions != nil { etag, err = fsrv.getEtagFromFile(fileSystem, compressedFilename) if err != nil { return err } } // don't assign info = compressedInfo because sidecars are kind // of transparent; however we do need to set the Etag: // https://caddy.community/t/gzipped-sidecar-file-wrong-same-etag/16793 if etag == "" { etag = calculateEtag(compressedInfo) } break } // no precompressed file found, use the actual file if file == nil { if c := fsrv.logger.Check(zapcore.DebugLevel, "opening file"); c != nil { c.Write(zap.String("filename", filename)) } // open the file file, err = fsrv.openFile(fileSystem, filename, w) if err != nil { if herr, ok := err.(caddyhttp.HandlerError); ok && herr.StatusCode == http.StatusNotFound { return fsrv.notFound(w, r, next) } return err // error is already structured } defer file.Close() // try to get the etag from pre computed files if an etag suffix list was provided if etag == "" && fsrv.EtagFileExtensions != nil { etag, err = fsrv.getEtagFromFile(fileSystem, filename) if err != nil { return err } } if etag == "" { etag = calculateEtag(info) } } // at this point, we're serving a file; Go std lib supports only // GET and HEAD, which is sensible for a static file server - reject // any other methods (see issue #5166) if r.Method != http.MethodGet && r.Method != http.MethodHead { // if we're in an error context, then it doesn't make sense // to repeat the error; just continue because we're probably // trying to write an error page response (see issue #5703) if _, ok := r.Context().Value(caddyhttp.ErrorCtxKey).(error); !ok { respHeader.Add("Allow", "GET, HEAD") return caddyhttp.Error(http.StatusMethodNotAllowed, nil) } } // set the Etag - note that a conditional If-None-Match request is handled // by http.ServeContent below, which checks against this Etag value if etag != "" { respHeader.Set("Etag", etag) } if respHeader.Get("Content-Type") == "" { mtyp := mime.TypeByExtension(filepath.Ext(filename)) if mtyp == "" { // do not allow Go to sniff the content-type; see https://www.youtube.com/watch?v=8t8JYpt0egE respHeader["Content-Type"] = nil } else { respHeader.Set("Content-Type", mtyp) } } var statusCodeOverride int // if this handler exists in an error context (i.e. is part of a // handler chain that is supposed to handle a previous error), // we should set status code to the one from the error instead // of letting http.ServeContent set the default (usually 200) if reqErr, ok := r.Context().Value(caddyhttp.ErrorCtxKey).(error); ok { statusCodeOverride = http.StatusInternalServerError if handlerErr, ok := reqErr.(caddyhttp.HandlerError); ok { if handlerErr.StatusCode > 0 { statusCodeOverride = handlerErr.StatusCode } } } // if a status code override is configured, run the replacer on it if codeStr := fsrv.StatusCode.String(); codeStr != "" { statusCodeOverride, err = strconv.Atoi(repl.ReplaceAll(codeStr, "")) if err != nil { return caddyhttp.Error(http.StatusInternalServerError, err) } } // if we do have an override from the previous two parts, then // we wrap the response writer to intercept the WriteHeader call if statusCodeOverride > 0 { w = statusOverrideResponseWriter{ResponseWriter: w, code: statusCodeOverride} } // let the standard library do what it does best; note, however, // that errors generated by ServeContent are written immediately // to the response, so we cannot handle them (but errors there // are rare) http.ServeContent(w, r, info.Name(), info.ModTime(), file.(io.ReadSeeker)) return nil } // openFile opens the file at the given filename. If there was an error, // the response is configured to inform the client how to best handle it // and a well-described handler error is returned (do not wrap the // returned error value). func (fsrv *FileServer) openFile(fileSystem fs.FS, filename string, w http.ResponseWriter) (fs.File, error) { file, err := fileSystem.Open(filename) if err != nil { err = fsrv.mapDirOpenError(fileSystem, err, filename) if errors.Is(err, fs.ErrNotExist) { if c := fsrv.logger.Check(zapcore.DebugLevel, "file not found"); c != nil { c.Write(zap.String("filename", filename), zap.Error(err)) } return nil, caddyhttp.Error(http.StatusNotFound, err) } else if errors.Is(err, fs.ErrPermission) { if c := fsrv.logger.Check(zapcore.DebugLevel, "permission denied"); c != nil { c.Write(zap.String("filename", filename), zap.Error(err)) } return nil, caddyhttp.Error(http.StatusForbidden, err) } // maybe the server is under load and ran out of file descriptors? // have client wait arbitrary seconds to help prevent a stampede //nolint:gosec backoff := weakrand.Intn(maxBackoff-minBackoff) + minBackoff w.Header().Set("Retry-After", strconv.Itoa(backoff)) if c := fsrv.logger.Check(zapcore.DebugLevel, "retry after backoff"); c != nil { c.Write(zap.String("filename", filename), zap.Int("backoff", backoff), zap.Error(err)) } return nil, caddyhttp.Error(http.StatusServiceUnavailable, err) } return file, nil } // mapDirOpenError maps the provided non-nil error from opening name // to a possibly better non-nil error. In particular, it turns OS-specific errors // about opening files in non-directories into os.ErrNotExist. See golang/go#18984. // Adapted from the Go standard library; originally written by Nathaniel Caza. // https://go-review.googlesource.com/c/go/+/36635/ // https://go-review.googlesource.com/c/go/+/36804/ func (fsrv *FileServer) mapDirOpenError(fileSystem fs.FS, originalErr error, name string) error { if errors.Is(originalErr, fs.ErrNotExist) || errors.Is(originalErr, fs.ErrPermission) { return originalErr } var pathErr *fs.PathError if errors.As(originalErr, &pathErr) { return fs.ErrInvalid } parts := strings.Split(name, separator) for i := range parts { if parts[i] == "" { continue } fi, err := fs.Stat(fileSystem, strings.Join(parts[:i+1], separator)) if err != nil { return originalErr } if !fi.IsDir() { return fs.ErrNotExist } } return originalErr } // transformHidePaths performs replacements for all the elements of fsrv.Hide and // makes them absolute paths (if they contain a path separator), then returns a // new list of the transformed values. func (fsrv *FileServer) transformHidePaths(repl *caddy.Replacer) []string { hide := make([]string, len(fsrv.Hide)) for i := range fsrv.Hide { hide[i] = repl.ReplaceAll(fsrv.Hide[i], "") if strings.Contains(hide[i], separator) { abs, err := caddy.FastAbs(hide[i]) if err == nil { hide[i] = abs } } } return hide } // fileHidden returns true if filename is hidden according to the hide list. // filename must be a relative or absolute file system path, not a request // URI path. It is expected that all the paths in the hide list are absolute // paths or are singular filenames (without a path separator). func fileHidden(filename string, hide []string) bool { if len(hide) == 0 { return false } // all path comparisons use the complete absolute path if possible filenameAbs, err := caddy.FastAbs(filename) if err == nil { filename = filenameAbs } var components []string for _, h := range hide { if !strings.Contains(h, separator) { // if there is no separator in h, then we assume the user // wants to hide any files or folders that match that // name; thus we have to compare against each component // of the filename, e.g. hiding "bar" would hide "/bar" // as well as "/foo/bar/baz" but not "/barstool". if len(components) == 0 { components = strings.Split(filename, separator) } for _, c := range components { if hidden, _ := filepath.Match(h, c); hidden { return true } } } else if after, ok := strings.CutPrefix(filename, h); ok { // if there is a separator in h, and filename is exactly // prefixed with h, then we can do a prefix match so that // "/foo" matches "/foo/bar" but not "/foobar". withoutPrefix := after if strings.HasPrefix(withoutPrefix, separator) { return true } } // in the general case, a glob match will suffice if hidden, _ := filepath.Match(h, filename); hidden { return true } } return false } // notFound returns a 404 error or, if pass-thru is enabled, // it calls the next handler in the chain. func (fsrv *FileServer) notFound(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { if fsrv.PassThru { return next.ServeHTTP(w, r) } return caddyhttp.Error(http.StatusNotFound, nil) } // calculateEtag computes an entity tag using a strong validator // without consuming the contents of the file. It requires the // file info contain the correct size and modification time. // It strives to implement the semantics regarding ETags as defined // by RFC 9110 section 8.8.3 and 8.8.1. See // https://www.rfc-editor.org/rfc/rfc9110.html#section-8.8.3. // // As our implementation uses file modification timestamp and size, // note the following from RFC 9110 section 8.8.1: "A representation's // modification time, if defined with only one-second resolution, // might be a weak validator if it is possible for the representation to // be modified twice during a single second and retrieved between those // modifications." The ext4 file system, which underpins the vast majority // of Caddy deployments, stores mod times with millisecond precision, // which we consider precise enough to qualify as a strong validator. func calculateEtag(d os.FileInfo) string { mtime := d.ModTime() if mtimeUnix := mtime.Unix(); mtimeUnix == 0 || mtimeUnix == 1 { return "" // not useful anyway; see issue #5548 } var sb strings.Builder sb.WriteRune('"') sb.WriteString(strconv.FormatInt(mtime.UnixNano(), 36)) sb.WriteString(strconv.FormatInt(d.Size(), 36)) sb.WriteRune('"') return sb.String() } // Finds the first corresponding etag file for a given file in the file system and return its content func (fsrv *FileServer) getEtagFromFile(fileSystem fs.FS, filename string) (string, error) { for _, suffix := range fsrv.EtagFileExtensions { etagFilename := filename + suffix etag, err := fs.ReadFile(fileSystem, etagFilename) if errors.Is(err, fs.ErrNotExist) { continue } if err != nil { return "", fmt.Errorf("cannot read etag from file %s: %v", etagFilename, err) } // Etags should not contain newline characters etag = bytes.ReplaceAll(etag, []byte("\n"), []byte{}) return string(etag), nil } return "", nil } // redirect performs a redirect to a given path. The 'toPath' parameter // MUST be solely a path, and MUST NOT include a query. func redirect(w http.ResponseWriter, r *http.Request, toPath string) error { for strings.HasPrefix(toPath, "//") { // prevent path-based open redirects toPath = strings.TrimPrefix(toPath, "/") } // preserve the query string if present if r.URL.RawQuery != "" { toPath += "?" + r.URL.RawQuery } http.Redirect(w, r, toPath, http.StatusPermanentRedirect) return nil } // statusOverrideResponseWriter intercepts WriteHeader calls // to instead write the HTTP status code we want instead // of the one http.ServeContent will use by default (usually 200) type statusOverrideResponseWriter struct { http.ResponseWriter code int } // WriteHeader intercepts calls by the stdlib to WriteHeader // to instead write the HTTP status code we want. func (wr statusOverrideResponseWriter) WriteHeader(int) { wr.ResponseWriter.WriteHeader(wr.code) } // Unwrap returns the underlying ResponseWriter, necessary for // http.ResponseController to work correctly. func (wr statusOverrideResponseWriter) Unwrap() http.ResponseWriter { return wr.ResponseWriter } var defaultIndexNames = []string{"index.html", "index.txt"} const ( minBackoff, maxBackoff = 2, 5 separator = string(filepath.Separator) ) // Interface guards var ( _ caddy.Provisioner = (*FileServer)(nil) _ caddyhttp.MiddlewareHandler = (*FileServer)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/fileserver/caddyfile.go
modules/caddyhttp/fileserver/caddyfile.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fileserver import ( "path/filepath" "strconv" "strings" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" ) func init() { httpcaddyfile.RegisterHandlerDirective("file_server", parseCaddyfile) httpcaddyfile.RegisterDirective("try_files", parseTryFiles) } // parseCaddyfile parses the file_server directive. // See UnmarshalCaddyfile for the syntax. func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { fsrv := new(FileServer) err := fsrv.UnmarshalCaddyfile(h.Dispenser) if err != nil { return fsrv, err } err = fsrv.FinalizeUnmarshalCaddyfile(h) if err != nil { return nil, err } return fsrv, err } // UnmarshalCaddyfile parses the file_server directive. It enables // the static file server and configures it with this syntax: // // file_server [<matcher>] [browse] { // fs <filesystem> // root <path> // hide <files...> // index <files...> // browse [<template_file>] // precompressed <formats...> // status <status> // disable_canonical_uris // } // // The FinalizeUnmarshalCaddyfile method should be called after this // to finalize setup of hidden Caddyfiles. func (fsrv *FileServer) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume directive name args := d.RemainingArgs() switch len(args) { case 0: case 1: if args[0] != "browse" { return d.ArgErr() } fsrv.Browse = new(Browse) default: return d.ArgErr() } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "fs": if !d.NextArg() { return d.ArgErr() } if fsrv.FileSystem != "" { return d.Err("file system already specified") } fsrv.FileSystem = d.Val() case "hide": fsrv.Hide = d.RemainingArgs() if len(fsrv.Hide) == 0 { return d.ArgErr() } case "index": fsrv.IndexNames = d.RemainingArgs() if len(fsrv.IndexNames) == 0 { return d.ArgErr() } case "root": if !d.Args(&fsrv.Root) { return d.ArgErr() } case "browse": if fsrv.Browse != nil { return d.Err("browsing is already configured") } fsrv.Browse = new(Browse) d.Args(&fsrv.Browse.TemplateFile) for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "reveal_symlinks": if fsrv.Browse.RevealSymlinks { return d.Err("Symlinks path reveal is already enabled") } fsrv.Browse.RevealSymlinks = true case "sort": for d.NextArg() { dVal := d.Val() switch dVal { case sortByName, sortByNameDirFirst, sortBySize, sortByTime, sortOrderAsc, sortOrderDesc: fsrv.Browse.SortOptions = append(fsrv.Browse.SortOptions, dVal) default: return d.Errf("unknown sort option '%s'", dVal) } } case "file_limit": fileLimit := d.RemainingArgs() if len(fileLimit) != 1 { return d.Err("file_limit should have an integer value") } val, _ := strconv.Atoi(fileLimit[0]) if fsrv.Browse.FileLimit != 0 { return d.Err("file_limit is already enabled") } fsrv.Browse.FileLimit = val default: return d.Errf("unknown subdirective '%s'", d.Val()) } } case "precompressed": fsrv.PrecompressedOrder = d.RemainingArgs() if len(fsrv.PrecompressedOrder) == 0 { fsrv.PrecompressedOrder = []string{"br", "zstd", "gzip"} } for _, format := range fsrv.PrecompressedOrder { modID := "http.precompressed." + format mod, err := caddy.GetModule(modID) if err != nil { return d.Errf("getting module named '%s': %v", modID, err) } inst := mod.New() precompress, ok := inst.(encode.Precompressed) if !ok { return d.Errf("module %s is not a precompressor; is %T", modID, inst) } if fsrv.PrecompressedRaw == nil { fsrv.PrecompressedRaw = make(caddy.ModuleMap) } fsrv.PrecompressedRaw[format] = caddyconfig.JSON(precompress, nil) } case "status": if !d.NextArg() { return d.ArgErr() } fsrv.StatusCode = caddyhttp.WeakString(d.Val()) case "disable_canonical_uris": if d.NextArg() { return d.ArgErr() } falseBool := false fsrv.CanonicalURIs = &falseBool case "pass_thru": if d.NextArg() { return d.ArgErr() } fsrv.PassThru = true case "etag_file_extensions": etagFileExtensions := d.RemainingArgs() if len(etagFileExtensions) == 0 { return d.ArgErr() } fsrv.EtagFileExtensions = etagFileExtensions default: return d.Errf("unknown subdirective '%s'", d.Val()) } } return nil } // FinalizeUnmarshalCaddyfile finalizes the Caddyfile parsing which // requires having an httpcaddyfile.Helper to function, to setup hidden Caddyfiles. func (fsrv *FileServer) FinalizeUnmarshalCaddyfile(h httpcaddyfile.Helper) error { // Hide the Caddyfile (and any imported Caddyfiles). // This needs to be done in here instead of UnmarshalCaddyfile // because UnmarshalCaddyfile only has access to the dispenser // and not the helper, and only the helper has access to the // Caddyfiles function. if configFiles := h.Caddyfiles(); len(configFiles) > 0 { for _, file := range configFiles { file = filepath.Clean(file) if !fileHidden(file, fsrv.Hide) { // if there's no path separator, the file server module will hide all // files by that name, rather than a specific one; but we want to hide // only this specific file, so ensure there's always a path separator if !strings.Contains(file, separator) { file = "." + separator + file } fsrv.Hide = append(fsrv.Hide, file) } } } return nil } // parseTryFiles parses the try_files directive. It combines a file matcher // with a rewrite directive, so this is not a standard handler directive. // A try_files directive has this syntax (notice no matcher tokens accepted): // // try_files <files...> { // policy first_exist|smallest_size|largest_size|most_recently_modified // } // // and is basically shorthand for: // // @try_files file { // try_files <files...> // policy first_exist|smallest_size|largest_size|most_recently_modified // } // rewrite @try_files {http.matchers.file.relative} // // This directive rewrites request paths only, preserving any other part // of the URI, unless the part is explicitly given in the file list. For // example, if any of the files in the list have a query string: // // try_files {path} index.php?{query}&p={path} // // then the query string will not be treated as part of the file name; and // if that file matches, the given query string will replace any query string // that already exists on the request URI. func parseTryFiles(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) { if !h.Next() { return nil, h.ArgErr() } tryFiles := h.RemainingArgs() if len(tryFiles) == 0 { return nil, h.ArgErr() } // parse out the optional try policy var tryPolicy string for h.NextBlock(0) { switch h.Val() { case "policy": if tryPolicy != "" { return nil, h.Err("try policy already configured") } if !h.NextArg() { return nil, h.ArgErr() } tryPolicy = h.Val() switch tryPolicy { case tryPolicyFirstExist, tryPolicyFirstExistFallback, tryPolicyLargestSize, tryPolicySmallestSize, tryPolicyMostRecentlyMod: default: return nil, h.Errf("unrecognized try policy: %s", tryPolicy) } } } // makeRoute returns a route that tries the files listed in try // and then rewrites to the matched file; userQueryString is // appended to the rewrite rule. makeRoute := func(try []string, userQueryString string) []httpcaddyfile.ConfigValue { handler := rewrite.Rewrite{ URI: "{http.matchers.file.relative}" + userQueryString, } matcherSet := caddy.ModuleMap{ "file": h.JSON(MatchFile{TryFiles: try, TryPolicy: tryPolicy}), } return h.NewRoute(matcherSet, handler) } var result []httpcaddyfile.ConfigValue // if there are query strings in the list, we have to split into // a separate route for each item with a query string, because // the rewrite is different for that item try := make([]string, 0, len(tryFiles)) for _, item := range tryFiles { if idx := strings.Index(item, "?"); idx >= 0 { if len(try) > 0 { result = append(result, makeRoute(try, "")...) try = []string{} } result = append(result, makeRoute([]string{item[:idx]}, item[idx:])...) continue } // accumulate consecutive non-query-string parameters try = append(try, item) } if len(try) > 0 { result = append(result, makeRoute(try, "")...) } // ensure that multiple routes (possible if rewrite targets // have query strings, for example) are grouped together // so only the first matching rewrite is performed (#2891) h.GroupRoutes(result) return result, nil } var _ caddyfile.Unmarshaler = (*FileServer)(nil)
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/fileserver/browsetplcontext.go
modules/caddyhttp/fileserver/browsetplcontext.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fileserver import ( "context" "io/fs" "net/url" "os" "path" "path/filepath" "slices" "sort" "strconv" "strings" "time" "github.com/dustin/go-humanize" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func (fsrv *FileServer) directoryListing(ctx context.Context, fileSystem fs.FS, parentModTime time.Time, entries []fs.DirEntry, canGoUp bool, root, urlPath string, repl *caddy.Replacer) *browseTemplateContext { filesToHide := fsrv.transformHidePaths(repl) name, _ := url.PathUnescape(urlPath) tplCtx := &browseTemplateContext{ Name: path.Base(name), Path: urlPath, CanGoUp: canGoUp, lastModified: parentModTime, } for _, entry := range entries { if err := ctx.Err(); err != nil { break } name := entry.Name() if fileHidden(name, filesToHide) { continue } info, err := entry.Info() if err != nil { if c := fsrv.logger.Check(zapcore.ErrorLevel, "could not get info about directory entry"); c != nil { c.Write(zap.String("name", entry.Name()), zap.String("root", root)) } continue } // keep track of the most recently modified item in the listing modTime := info.ModTime() if tplCtx.lastModified.IsZero() || modTime.After(tplCtx.lastModified) { tplCtx.lastModified = modTime } isDir := entry.IsDir() || fsrv.isSymlinkTargetDir(fileSystem, info, root, urlPath) // add the slash after the escape of path to avoid escaping the slash as well if isDir { name += "/" tplCtx.NumDirs++ } else { tplCtx.NumFiles++ } size := info.Size() if !isDir { // increase the total by the symlink's size, not the target's size, // by incrementing before we follow the symlink tplCtx.TotalFileSize += size } fileIsSymlink := isSymlink(info) symlinkPath := "" if fileIsSymlink { path := caddyhttp.SanitizedPathJoin(root, path.Join(urlPath, info.Name())) fileInfo, err := fs.Stat(fileSystem, path) if err == nil { size = fileInfo.Size() } if fsrv.Browse.RevealSymlinks { symLinkTarget, err := filepath.EvalSymlinks(path) if err == nil { symlinkPath = symLinkTarget } } // An error most likely means the symlink target doesn't exist, // which isn't entirely unusual and shouldn't fail the listing. // In this case, just use the size of the symlink itself, which // was already set above. } if !isDir { // increase the total including the symlink target's size tplCtx.TotalFileSizeFollowingSymlinks += size } u := url.URL{Path: "./" + name} // prepend with "./" to fix paths with ':' in the name tplCtx.Items = append(tplCtx.Items, fileInfo{ IsDir: isDir, IsSymlink: fileIsSymlink, Name: name, Size: size, URL: u.String(), ModTime: modTime.UTC(), Mode: info.Mode(), Tpl: tplCtx, // a reference up to the template context is useful SymlinkPath: symlinkPath, }) } // this time is used for the Last-Modified header and comparing If-Modified-Since from client // both are expected to be in UTC, so we convert to UTC here // see: https://github.com/caddyserver/caddy/issues/6828 tplCtx.lastModified = tplCtx.lastModified.UTC() return tplCtx } // browseTemplateContext provides the template context for directory listings. type browseTemplateContext struct { // The name of the directory (the last element of the path). Name string `json:"name"` // The full path of the request. Path string `json:"path"` // Whether the parent directory is browsable. CanGoUp bool `json:"can_go_up"` // The items (files and folders) in the path. Items []fileInfo `json:"items,omitempty"` // If ≠0 then Items starting from that many elements. Offset int `json:"offset,omitempty"` // If ≠0 then Items have been limited to that many elements. Limit int `json:"limit,omitempty"` // The number of directories in the listing. NumDirs int `json:"num_dirs"` // The number of files (items that aren't directories) in the listing. NumFiles int `json:"num_files"` // The total size of all files in the listing. Only includes the // size of the files themselves, not the size of symlink targets // (i.e. the calculation of this value does not follow symlinks). TotalFileSize int64 `json:"total_file_size"` // The total size of all files in the listing, including the // size of the files targeted by symlinks. TotalFileSizeFollowingSymlinks int64 `json:"total_file_size_following_symlinks"` // Sort column used Sort string `json:"sort,omitempty"` // Sorting order Order string `json:"order,omitempty"` // Display format (list or grid) Layout string `json:"layout,omitempty"` // The most recent file modification date in the listing. // Used for HTTP header purposes. lastModified time.Time } // Breadcrumbs returns l.Path where every element maps // the link to the text to display. func (l browseTemplateContext) Breadcrumbs() []crumb { if len(l.Path) == 0 { return []crumb{} } // skip trailing slash lpath := l.Path if lpath[len(lpath)-1] == '/' { lpath = lpath[:len(lpath)-1] } parts := strings.Split(lpath, "/") result := make([]crumb, len(parts)) for i, p := range parts { if i == 0 && p == "" { p = "/" } // the directory name could include an encoded slash in its path, // so the item name should be unescaped in the loop rather than unescaping the // entire path outside the loop. p, _ = url.PathUnescape(p) lnk := strings.Repeat("../", len(parts)-i-1) result[i] = crumb{Link: lnk, Text: p} } return result } func (l *browseTemplateContext) applySortAndLimit(sortParam, orderParam, limitParam string, offsetParam string) { l.Sort = sortParam l.Order = orderParam if l.Order == "desc" { switch l.Sort { case sortByName: sort.Sort(sort.Reverse(byName(*l))) case sortByNameDirFirst: sort.Sort(sort.Reverse(byNameDirFirst(*l))) case sortBySize: sort.Sort(sort.Reverse(bySize(*l))) case sortByTime: sort.Sort(sort.Reverse(byTime(*l))) } } else { switch l.Sort { case sortByName: sort.Sort(byName(*l)) case sortByNameDirFirst: sort.Sort(byNameDirFirst(*l)) case sortBySize: sort.Sort(bySize(*l)) case sortByTime: sort.Sort(byTime(*l)) } } if offsetParam != "" { offset, _ := strconv.Atoi(offsetParam) if offset > 0 && offset <= len(l.Items) { l.Items = l.Items[offset:] l.Offset = offset } } if limitParam != "" { limit, _ := strconv.Atoi(limitParam) if limit > 0 && limit <= len(l.Items) { l.Items = l.Items[:limit] l.Limit = limit } } } // crumb represents part of a breadcrumb menu, // pairing a link with the text to display. type crumb struct { Link, Text string } // fileInfo contains serializable information // about a file or directory. type fileInfo struct { Name string `json:"name"` Size int64 `json:"size"` URL string `json:"url"` ModTime time.Time `json:"mod_time"` Mode os.FileMode `json:"mode"` IsDir bool `json:"is_dir"` IsSymlink bool `json:"is_symlink"` SymlinkPath string `json:"symlink_path,omitempty"` // a pointer to the template context is useful inside nested templates Tpl *browseTemplateContext `json:"-"` } // HasExt returns true if the filename has any of the given suffixes, case-insensitive. func (fi fileInfo) HasExt(exts ...string) bool { return slices.ContainsFunc(exts, func(ext string) bool { return strings.HasSuffix(strings.ToLower(fi.Name), strings.ToLower(ext)) }) } // HumanSize returns the size of the file as a // human-readable string in IEC format (i.e. // power of 2 or base 1024). func (fi fileInfo) HumanSize() string { return humanize.IBytes(uint64(fi.Size)) } // HumanTotalFileSize returns the total size of all files // in the listing as a human-readable string in IEC format // (i.e. power of 2 or base 1024). func (btc browseTemplateContext) HumanTotalFileSize() string { return humanize.IBytes(uint64(btc.TotalFileSize)) } // HumanTotalFileSizeFollowingSymlinks is the same as HumanTotalFileSize // except the returned value reflects the size of symlink targets. func (btc browseTemplateContext) HumanTotalFileSizeFollowingSymlinks() string { return humanize.IBytes(uint64(btc.TotalFileSizeFollowingSymlinks)) } // HumanModTime returns the modified time of the file // as a human-readable string given by format. func (fi fileInfo) HumanModTime(format string) string { return fi.ModTime.Format(format) } type ( byName browseTemplateContext byNameDirFirst browseTemplateContext bySize browseTemplateContext byTime browseTemplateContext ) func (l byName) Len() int { return len(l.Items) } func (l byName) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] } func (l byName) Less(i, j int) bool { return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name) } func (l byNameDirFirst) Len() int { return len(l.Items) } func (l byNameDirFirst) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] } func (l byNameDirFirst) Less(i, j int) bool { // sort by name if both are dir or file if l.Items[i].IsDir == l.Items[j].IsDir { return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name) } // sort dir ahead of file return l.Items[i].IsDir } func (l bySize) Len() int { return len(l.Items) } func (l bySize) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] } func (l bySize) Less(i, j int) bool { const directoryOffset = -1 << 31 // = -math.MinInt32 iSize, jSize := l.Items[i].Size, l.Items[j].Size // directory sizes depend on the file system; to // provide a consistent experience, put them up front // and sort them by name if l.Items[i].IsDir { iSize = directoryOffset } if l.Items[j].IsDir { jSize = directoryOffset } if l.Items[i].IsDir && l.Items[j].IsDir { return strings.ToLower(l.Items[i].Name) < strings.ToLower(l.Items[j].Name) } return iSize < jSize } func (l byTime) Len() int { return len(l.Items) } func (l byTime) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] } func (l byTime) Less(i, j int) bool { return l.Items[i].ModTime.Before(l.Items[j].ModTime) } const ( sortByName = "name" sortByNameDirFirst = "namedirfirst" sortBySize = "size" sortByTime = "time" sortOrderAsc = "asc" sortOrderDesc = "desc" )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/fileserver/matcher.go
modules/caddyhttp/fileserver/matcher.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fileserver import ( "fmt" "io/fs" "net/http" "os" "path" "path/filepath" "runtime" "strconv" "strings" "github.com/google/cel-go/cel" "github.com/google/cel-go/common" "github.com/google/cel-go/common/ast" "github.com/google/cel-go/common/operators" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" "github.com/google/cel-go/parser" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(MatchFile{}) } // MatchFile is an HTTP request matcher that can match // requests based upon file existence. // // Upon matching, three new placeholders will be made // available: // // - `{http.matchers.file.relative}` The root-relative // path of the file. This is often useful when rewriting // requests. // - `{http.matchers.file.absolute}` The absolute path // of the matched file. // - `{http.matchers.file.type}` Set to "directory" if // the matched file is a directory, "file" otherwise. // - `{http.matchers.file.remainder}` Set to the remainder // of the path if the path was split by `split_path`. // // Even though file matching may depend on the OS path // separator, the placeholder values always use /. type MatchFile struct { // The file system implementation to use. By default, the // local disk file system will be used. FileSystem string `json:"fs,omitempty"` // The root directory, used for creating absolute // file paths, and required when working with // relative paths; if not specified, `{http.vars.root}` // will be used, if set; otherwise, the current // directory is assumed. Accepts placeholders. Root string `json:"root,omitempty"` // The list of files to try. Each path here is // considered related to Root. If nil, the request // URL's path will be assumed. Files and // directories are treated distinctly, so to match // a directory, the filepath MUST end in a forward // slash `/`. To match a regular file, there must // be no trailing slash. Accepts placeholders. If // the policy is "first_exist", then an error may // be triggered as a fallback by configuring "=" // followed by a status code number, // for example "=404". TryFiles []string `json:"try_files,omitempty"` // How to choose a file in TryFiles. Can be: // // - first_exist // - first_exist_fallback // - smallest_size // - largest_size // - most_recently_modified // // Default is first_exist. TryPolicy string `json:"try_policy,omitempty"` // A list of delimiters to use to split the path in two // when trying files. If empty, no splitting will // occur, and the path will be tried as-is. For each // split value, the left-hand side of the split, // including the split value, will be the path tried. // For example, the path `/remote.php/dav/` using the // split value `.php` would try the file `/remote.php`. // Each delimiter must appear at the end of a URI path // component in order to be used as a split delimiter. SplitPath []string `json:"split_path,omitempty"` fsmap caddy.FileSystems logger *zap.Logger } // CaddyModule returns the Caddy module information. func (MatchFile) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.matchers.file", New: func() caddy.Module { return new(MatchFile) }, } } // UnmarshalCaddyfile sets up the matcher from Caddyfile tokens. Syntax: // // file <files...> { // root <path> // try_files <files...> // try_policy first_exist|smallest_size|largest_size|most_recently_modified // } func (m *MatchFile) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // iterate to merge multiple matchers into one for d.Next() { m.TryFiles = append(m.TryFiles, d.RemainingArgs()...) for d.NextBlock(0) { switch d.Val() { case "root": if !d.NextArg() { return d.ArgErr() } m.Root = d.Val() case "try_files": m.TryFiles = append(m.TryFiles, d.RemainingArgs()...) if len(m.TryFiles) == 0 { return d.ArgErr() } case "try_policy": if !d.NextArg() { return d.ArgErr() } m.TryPolicy = d.Val() case "split_path": m.SplitPath = d.RemainingArgs() if len(m.SplitPath) == 0 { return d.ArgErr() } default: return d.Errf("unrecognized subdirective: %s", d.Val()) } } } return nil } // CELLibrary produces options that expose this matcher for use in CEL // expression matchers. // // Example: // // expression file() // expression file({http.request.uri.path}, '/index.php') // expression file({'root': '/srv', 'try_files': [{http.request.uri.path}, '/index.php'], 'try_policy': 'first_exist', 'split_path': ['.php']}) func (MatchFile) CELLibrary(ctx caddy.Context) (cel.Library, error) { requestType := cel.ObjectType("http.Request") matcherFactory := func(data ref.Val) (caddyhttp.RequestMatcherWithError, error) { values, err := caddyhttp.CELValueToMapStrList(data) if err != nil { return nil, err } var root string if len(values["root"]) > 0 { root = values["root"][0] } var fsName string if len(values["fs"]) > 0 { fsName = values["fs"][0] } var try_policy string if len(values["try_policy"]) > 0 { try_policy = values["try_policy"][0] } m := MatchFile{ Root: root, TryFiles: values["try_files"], TryPolicy: try_policy, SplitPath: values["split_path"], FileSystem: fsName, } err = m.Provision(ctx) return m, err } envOptions := []cel.EnvOption{ cel.Macros(parser.NewGlobalVarArgMacro("file", celFileMatcherMacroExpander())), cel.Function("file", cel.Overload("file_request_map", []*cel.Type{requestType, caddyhttp.CELTypeJSON}, cel.BoolType)), cel.Function("file_request_map", cel.Overload("file_request_map", []*cel.Type{requestType, caddyhttp.CELTypeJSON}, cel.BoolType), cel.SingletonBinaryBinding(caddyhttp.CELMatcherRuntimeFunction("file_request_map", matcherFactory))), } programOptions := []cel.ProgramOption{ cel.CustomDecorator(caddyhttp.CELMatcherDecorator("file_request_map", matcherFactory)), } return caddyhttp.NewMatcherCELLibrary(envOptions, programOptions), nil } func celFileMatcherMacroExpander() parser.MacroExpander { return func(eh parser.ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) { if len(args) == 0 { return eh.NewCall("file", eh.NewIdent(caddyhttp.CELRequestVarName), eh.NewMap(), ), nil } if len(args) == 1 { arg := args[0] if isCELStringLiteral(arg) || isCELCaddyPlaceholderCall(arg) { return eh.NewCall("file", eh.NewIdent(caddyhttp.CELRequestVarName), eh.NewMap(eh.NewMapEntry( eh.NewLiteral(types.String("try_files")), eh.NewList(arg), false, )), ), nil } if isCELTryFilesLiteral(arg) { return eh.NewCall("file", eh.NewIdent(caddyhttp.CELRequestVarName), arg), nil } return nil, &common.Error{ Location: eh.OffsetLocation(arg.ID()), Message: "matcher requires either a map or string literal argument", } } for _, arg := range args { if !isCELStringLiteral(arg) && !isCELCaddyPlaceholderCall(arg) { return nil, &common.Error{ Location: eh.OffsetLocation(arg.ID()), Message: "matcher only supports repeated string literal arguments", } } } return eh.NewCall("file", eh.NewIdent(caddyhttp.CELRequestVarName), eh.NewMap(eh.NewMapEntry( eh.NewLiteral(types.String("try_files")), eh.NewList(args...), false, )), ), nil } } // Provision sets up m's defaults. func (m *MatchFile) Provision(ctx caddy.Context) error { m.logger = ctx.Logger() m.fsmap = ctx.FileSystems() if m.Root == "" { m.Root = "{http.vars.root}" } if m.FileSystem == "" { m.FileSystem = "{http.vars.fs}" } // if list of files to try was omitted entirely, assume URL path // (use placeholder instead of r.URL.Path; see issue #4146) if m.TryFiles == nil { m.TryFiles = []string{"{http.request.uri.path}"} } return nil } // Validate ensures m has a valid configuration. func (m MatchFile) Validate() error { switch m.TryPolicy { case "", tryPolicyFirstExist, tryPolicyFirstExistFallback, tryPolicyLargestSize, tryPolicySmallestSize, tryPolicyMostRecentlyMod: default: return fmt.Errorf("unknown try policy %s", m.TryPolicy) } return nil } // Match returns true if r matches m. Returns true // if a file was matched. If so, four placeholders // will be available: // - http.matchers.file.relative: Path to file relative to site root // - http.matchers.file.absolute: Path to file including site root // - http.matchers.file.type: file or directory // - http.matchers.file.remainder: Portion remaining after splitting file path (if configured) func (m MatchFile) Match(r *http.Request) bool { match, err := m.selectFile(r) if err != nil { // nolint:staticcheck caddyhttp.SetVar(r.Context(), caddyhttp.MatcherErrorVarKey, err) } return match } // MatchWithError returns true if r matches m. func (m MatchFile) MatchWithError(r *http.Request) (bool, error) { return m.selectFile(r) } // selectFile chooses a file according to m.TryPolicy by appending // the paths in m.TryFiles to m.Root, with placeholder replacements. func (m MatchFile) selectFile(r *http.Request) (bool, error) { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) root := filepath.Clean(repl.ReplaceAll(m.Root, ".")) fsName := repl.ReplaceAll(m.FileSystem, "") fileSystem, ok := m.fsmap.Get(fsName) if !ok { if c := m.logger.Check(zapcore.ErrorLevel, "use of unregistered filesystem"); c != nil { c.Write(zap.String("fs", fsName)) } return false, nil } type matchCandidate struct { fullpath, relative, splitRemainder string } // makeCandidates evaluates placeholders in file and expands any glob expressions // to build a list of file candidates. Special glob characters are escaped in // placeholder replacements so globs cannot be expanded from placeholders, and // globs are not evaluated on Windows because of its path separator character: // escaping is not supported so we can't safely glob on Windows, or we can't // support placeholders on Windows (pick one). (Actually, evaluating untrusted // globs is not the end of the world since the file server will still hide any // hidden files, it just might lead to unexpected behavior.) makeCandidates := func(file string) []matchCandidate { // first, evaluate placeholders in the file pattern expandedFile, err := repl.ReplaceFunc(file, func(variable string, val any) (any, error) { if runtime.GOOS == "windows" { return val, nil } switch v := val.(type) { case string: return globSafeRepl.Replace(v), nil case fmt.Stringer: return globSafeRepl.Replace(v.String()), nil } return val, nil }) if err != nil { if c := m.logger.Check(zapcore.ErrorLevel, "evaluating placeholders"); c != nil { c.Write(zap.Error(err)) } expandedFile = file // "oh well," I guess? } // clean the path and split, if configured -- we must split before // globbing so that the file system doesn't include the remainder // ("afterSplit") in the filename; be sure to restore trailing slash beforeSplit, afterSplit := m.firstSplit(path.Clean(expandedFile)) if strings.HasSuffix(file, "/") { beforeSplit += "/" } // create the full path to the file by prepending the site root fullPattern := caddyhttp.SanitizedPathJoin(root, beforeSplit) // expand glob expressions, but not on Windows because Glob() doesn't // support escaping on Windows due to path separator) var globResults []string if runtime.GOOS == "windows" { globResults = []string{fullPattern} // precious Windows } else { globResults, err = fs.Glob(fileSystem, fullPattern) if err != nil { if c := m.logger.Check(zapcore.ErrorLevel, "expanding glob"); c != nil { c.Write(zap.Error(err)) } } } // for each glob result, combine all the forms of the path var candidates []matchCandidate for _, result := range globResults { candidates = append(candidates, matchCandidate{ fullpath: result, relative: strings.TrimPrefix(result, root), splitRemainder: afterSplit, }) } return candidates } // setPlaceholders creates the placeholders for the matched file setPlaceholders := func(candidate matchCandidate, isDir bool) { repl.Set("http.matchers.file.relative", filepath.ToSlash(candidate.relative)) repl.Set("http.matchers.file.absolute", filepath.ToSlash(candidate.fullpath)) repl.Set("http.matchers.file.remainder", filepath.ToSlash(candidate.splitRemainder)) fileType := "file" if isDir { fileType = "directory" } repl.Set("http.matchers.file.type", fileType) } // match file according to the configured policy switch m.TryPolicy { case "", tryPolicyFirstExist, tryPolicyFirstExistFallback: maxI := -1 if m.TryPolicy == tryPolicyFirstExistFallback { maxI = len(m.TryFiles) - 1 } for i, pattern := range m.TryFiles { // If the pattern is a status code, emit an error, // which short-circuits the middleware pipeline and // writes an HTTP error response. if err := parseErrorCode(pattern); err != nil { return false, err } candidates := makeCandidates(pattern) for _, c := range candidates { // Skip the IO if using fallback policy and it's the latest item if i == maxI { setPlaceholders(c, false) return true, nil } if info, exists := m.strictFileExists(fileSystem, c.fullpath); exists { setPlaceholders(c, info.IsDir()) return true, nil } } } case tryPolicyLargestSize: var largestSize int64 var largest matchCandidate var largestInfo os.FileInfo for _, pattern := range m.TryFiles { candidates := makeCandidates(pattern) for _, c := range candidates { info, err := fs.Stat(fileSystem, c.fullpath) if err == nil && info.Size() > largestSize { largestSize = info.Size() largest = c largestInfo = info } } } if largestInfo == nil { return false, nil } setPlaceholders(largest, largestInfo.IsDir()) return true, nil case tryPolicySmallestSize: var smallestSize int64 var smallest matchCandidate var smallestInfo os.FileInfo for _, pattern := range m.TryFiles { candidates := makeCandidates(pattern) for _, c := range candidates { info, err := fs.Stat(fileSystem, c.fullpath) if err == nil && (smallestSize == 0 || info.Size() < smallestSize) { smallestSize = info.Size() smallest = c smallestInfo = info } } } if smallestInfo == nil { return false, nil } setPlaceholders(smallest, smallestInfo.IsDir()) return true, nil case tryPolicyMostRecentlyMod: var recent matchCandidate var recentInfo os.FileInfo for _, pattern := range m.TryFiles { candidates := makeCandidates(pattern) for _, c := range candidates { info, err := fs.Stat(fileSystem, c.fullpath) if err == nil && (recentInfo == nil || info.ModTime().After(recentInfo.ModTime())) { recent = c recentInfo = info } } } if recentInfo == nil { return false, nil } setPlaceholders(recent, recentInfo.IsDir()) return true, nil } return false, nil } // parseErrorCode checks if the input is a status // code number, prefixed by "=", and returns an // error if so. func parseErrorCode(input string) error { if len(input) > 1 && input[0] == '=' { code, err := strconv.Atoi(input[1:]) if err != nil || code < 100 || code > 999 { return nil } return caddyhttp.Error(code, fmt.Errorf("%s", input[1:])) } return nil } // strictFileExists returns true if file exists // and matches the convention of the given file // path. If the path ends in a forward slash, // the file must also be a directory; if it does // NOT end in a forward slash, the file must NOT // be a directory. func (m MatchFile) strictFileExists(fileSystem fs.FS, file string) (os.FileInfo, bool) { info, err := fs.Stat(fileSystem, file) if err != nil { // in reality, this can be any error // such as permission or even obscure // ones like "is not a directory" (when // trying to stat a file within a file); // in those cases we can't be sure if // the file exists, so we just treat any // error as if it does not exist; see // https://stackoverflow.com/a/12518877/1048862 return nil, false } if strings.HasSuffix(file, separator) { // by convention, file paths ending // in a path separator must be a directory return info, info.IsDir() } // by convention, file paths NOT ending // in a path separator must NOT be a directory return info, !info.IsDir() } // firstSplit returns the first result where the path // can be split in two by a value in m.SplitPath. The // return values are the first piece of the path that // ends with the split substring and the remainder. // If the path cannot be split, the path is returned // as-is (with no remainder). func (m MatchFile) firstSplit(path string) (splitPart, remainder string) { for _, split := range m.SplitPath { if idx := indexFold(path, split); idx > -1 { pos := idx + len(split) // skip the split if it's not the final part of the filename if pos != len(path) && !strings.HasPrefix(path[pos:], "/") { continue } return path[:pos], path[pos:] } } return path, "" } // There is no strings.IndexFold() function like there is strings.EqualFold(), // but we can use strings.EqualFold() to build our own case-insensitive // substring search (as of Go 1.14). func indexFold(haystack, needle string) int { nlen := len(needle) for i := 0; i+nlen < len(haystack); i++ { if strings.EqualFold(haystack[i:i+nlen], needle) { return i } } return -1 } // isCELTryFilesLiteral returns whether the expression resolves to a map literal containing // only string keys with or a placeholder call. func isCELTryFilesLiteral(e ast.Expr) bool { switch e.Kind() { case ast.MapKind: mapExpr := e.AsMap() for _, entry := range mapExpr.Entries() { mapKey := entry.AsMapEntry().Key() mapVal := entry.AsMapEntry().Value() if !isCELStringLiteral(mapKey) { return false } mapKeyStr := mapKey.AsLiteral().ConvertToType(types.StringType).Value() switch mapKeyStr { case "try_files", "split_path": if !isCELStringListLiteral(mapVal) { return false } case "try_policy", "root": if !(isCELStringExpr(mapVal)) { return false } default: return false } } return true case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.SelectKind, ast.StructKind: // appeasing the linter :) } return false } // isCELStringExpr indicates whether the expression is a supported string expression func isCELStringExpr(e ast.Expr) bool { return isCELStringLiteral(e) || isCELCaddyPlaceholderCall(e) || isCELConcatCall(e) } // isCELStringLiteral returns whether the expression is a CEL string literal. func isCELStringLiteral(e ast.Expr) bool { switch e.Kind() { case ast.LiteralKind: constant := e.AsLiteral() switch constant.Type() { case types.StringType: return true } case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.MapKind, ast.SelectKind, ast.StructKind: // appeasing the linter :) } return false } // isCELCaddyPlaceholderCall returns whether the expression is a caddy placeholder call. func isCELCaddyPlaceholderCall(e ast.Expr) bool { switch e.Kind() { case ast.CallKind: call := e.AsCall() if call.FunctionName() == caddyhttp.CELPlaceholderFuncName { return true } case ast.UnspecifiedExprKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind: // appeasing the linter :) } return false } // isCELConcatCall tests whether the expression is a concat function (+) with string, placeholder, or // other concat call arguments. func isCELConcatCall(e ast.Expr) bool { switch e.Kind() { case ast.CallKind: call := e.AsCall() if call.Target().Kind() != ast.UnspecifiedExprKind { return false } if call.FunctionName() != operators.Add { return false } for _, arg := range call.Args() { if !isCELStringExpr(arg) { return false } } return true case ast.UnspecifiedExprKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind: // appeasing the linter :) } return false } // isCELStringListLiteral returns whether the expression resolves to a list literal // containing only string constants or a placeholder call. func isCELStringListLiteral(e ast.Expr) bool { switch e.Kind() { case ast.ListKind: list := e.AsList() for _, elem := range list.Elements() { if !isCELStringExpr(elem) { return false } } return true case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind: // appeasing the linter :) } return false } // globSafeRepl replaces special glob characters with escaped // equivalents. Note that the filepath godoc states that // escaping is not done on Windows because of the separator. var globSafeRepl = strings.NewReplacer( "*", "\\*", "[", "\\[", "?", "\\?", ) const ( tryPolicyFirstExist = "first_exist" tryPolicyFirstExistFallback = "first_exist_fallback" tryPolicyLargestSize = "largest_size" tryPolicySmallestSize = "smallest_size" tryPolicyMostRecentlyMod = "most_recently_modified" ) // Interface guards var ( _ caddy.Validator = (*MatchFile)(nil) _ caddyhttp.RequestMatcherWithError = (*MatchFile)(nil) _ caddyhttp.CELLibraryProducer = (*MatchFile)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/fileserver/command.go
modules/caddyhttp/fileserver/command.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fileserver import ( "encoding/json" "fmt" "io" "log" "os" "strconv" "time" "github.com/caddyserver/certmagic" "github.com/spf13/cobra" "go.uber.org/zap" caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" caddytpl "github.com/caddyserver/caddy/v2/modules/caddyhttp/templates" ) func init() { caddycmd.RegisterCommand(caddycmd.Command{ Name: "file-server", Usage: "[--domain <example.com>] [--root <path>] [--listen <addr>] [--browse] [--reveal-symlinks] [--access-log] [--precompressed]", Short: "Spins up a production-ready file server", Long: ` A simple but production-ready file server. Useful for quick deployments, demos, and development. The listener's socket address can be customized with the --listen flag. If a domain name is specified with --domain, the default listener address will be changed to the HTTPS port and the server will use HTTPS. If using a public domain, ensure A/AAAA records are properly configured before using this option. By default, Zstandard and Gzip compression are enabled. Use --no-compress to disable compression. If --browse is enabled, requests for folders without an index file will respond with a file listing.`, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("domain", "d", "", "Domain name at which to serve the files") cmd.Flags().StringP("root", "r", "", "The path to the root of the site") cmd.Flags().StringP("listen", "l", "", "The address to which to bind the listener") cmd.Flags().BoolP("browse", "b", false, "Enable directory browsing") cmd.Flags().BoolP("reveal-symlinks", "", false, "Show symlink paths when browse is enabled.") cmd.Flags().BoolP("templates", "t", false, "Enable template rendering") cmd.Flags().BoolP("access-log", "a", false, "Enable the access log") cmd.Flags().BoolP("debug", "v", false, "Enable verbose debug logs") cmd.Flags().IntP("file-limit", "f", defaultDirEntryLimit, "Max directories to read") cmd.Flags().BoolP("no-compress", "", false, "Disable Zstandard and Gzip compression") cmd.Flags().StringSliceP("precompressed", "p", []string{}, "Specify precompression file extensions. Compression preference implied from flag order.") cmd.RunE = caddycmd.WrapCommandFuncForCobra(cmdFileServer) cmd.AddCommand(&cobra.Command{ Use: "export-template", Short: "Exports the default file browser template", Example: "caddy file-server export-template > browse.html", RunE: func(cmd *cobra.Command, args []string) error { _, err := io.WriteString(os.Stdout, BrowseTemplate) return err }, }) }, }) } func cmdFileServer(fs caddycmd.Flags) (int, error) { caddy.TrapSignals() domain := fs.String("domain") root := fs.String("root") listen := fs.String("listen") browse := fs.Bool("browse") templates := fs.Bool("templates") accessLog := fs.Bool("access-log") fileLimit := fs.Int("file-limit") debug := fs.Bool("debug") revealSymlinks := fs.Bool("reveal-symlinks") compress := !fs.Bool("no-compress") precompressed, err := fs.GetStringSlice("precompressed") if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid precompressed flag: %v", err) } var handlers []json.RawMessage if compress { zstd, err := caddy.GetModule("http.encoders.zstd") if err != nil { return caddy.ExitCodeFailedStartup, err } gzip, err := caddy.GetModule("http.encoders.gzip") if err != nil { return caddy.ExitCodeFailedStartup, err } handlers = append(handlers, caddyconfig.JSONModuleObject(encode.Encode{ EncodingsRaw: caddy.ModuleMap{ "zstd": caddyconfig.JSON(zstd.New(), nil), "gzip": caddyconfig.JSON(gzip.New(), nil), }, Prefer: []string{"zstd", "gzip"}, }, "handler", "encode", nil)) } if templates { handler := caddytpl.Templates{FileRoot: root} handlers = append(handlers, caddyconfig.JSONModuleObject(handler, "handler", "templates", nil)) } handler := FileServer{Root: root} if len(precompressed) != 0 { // logic mirrors modules/caddyhttp/fileserver/caddyfile.go case "precompressed" var order []string for _, compression := range precompressed { modID := "http.precompressed." + compression mod, err := caddy.GetModule(modID) if err != nil { return caddy.ExitCodeFailedStartup, fmt.Errorf("getting module named '%s': %v", modID, err) } inst := mod.New() precompress, ok := inst.(encode.Precompressed) if !ok { return caddy.ExitCodeFailedStartup, fmt.Errorf("module %s is not a precompressor; is %T", modID, inst) } if handler.PrecompressedRaw == nil { handler.PrecompressedRaw = make(caddy.ModuleMap) } handler.PrecompressedRaw[compression] = caddyconfig.JSON(precompress, nil) order = append(order, compression) } handler.PrecompressedOrder = order } if browse { handler.Browse = &Browse{RevealSymlinks: revealSymlinks, FileLimit: fileLimit} } handlers = append(handlers, caddyconfig.JSONModuleObject(handler, "handler", "file_server", nil)) route := caddyhttp.Route{HandlersRaw: handlers} if domain != "" { route.MatcherSetsRaw = []caddy.ModuleMap{ { "host": caddyconfig.JSON(caddyhttp.MatchHost{domain}, nil), }, } } server := &caddyhttp.Server{ ReadHeaderTimeout: caddy.Duration(10 * time.Second), IdleTimeout: caddy.Duration(30 * time.Second), MaxHeaderBytes: 1024 * 10, Routes: caddyhttp.RouteList{route}, } if listen == "" { if domain == "" { listen = ":80" } else { listen = ":" + strconv.Itoa(certmagic.HTTPSPort) } } server.Listen = []string{listen} if accessLog { server.Logs = &caddyhttp.ServerLogConfig{} } httpApp := caddyhttp.App{ Servers: map[string]*caddyhttp.Server{"static": server}, } var false bool cfg := &caddy.Config{ Admin: &caddy.AdminConfig{ Disabled: true, Config: &caddy.ConfigSettings{ Persist: &false, }, }, AppsRaw: caddy.ModuleMap{ "http": caddyconfig.JSON(httpApp, nil), }, } if debug { cfg.Logging = &caddy.Logging{ Logs: map[string]*caddy.CustomLog{ "default": { BaseLog: caddy.BaseLog{Level: zap.DebugLevel.CapitalString()}, }, }, } } err = caddy.Run(cfg) if err != nil { return caddy.ExitCodeFailedStartup, err } log.Printf("Caddy serving static files on %s", listen) select {} }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/fileserver/browsetplcontext_test.go
modules/caddyhttp/fileserver/browsetplcontext_test.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fileserver import ( "testing" ) func TestBreadcrumbs(t *testing.T) { testdata := []struct { path string expected []crumb }{ {"", []crumb{}}, {"/", []crumb{{Text: "/"}}}, {"/foo/", []crumb{ {Link: "../", Text: "/"}, {Link: "", Text: "foo"}, }}, {"/foo/bar/", []crumb{ {Link: "../../", Text: "/"}, {Link: "../", Text: "foo"}, {Link: "", Text: "bar"}, }}, {"/foo bar/", []crumb{ {Link: "../", Text: "/"}, {Link: "", Text: "foo bar"}, }}, {"/foo bar/baz/", []crumb{ {Link: "../../", Text: "/"}, {Link: "../", Text: "foo bar"}, {Link: "", Text: "baz"}, }}, {"/100%25 test coverage/is a lie/", []crumb{ {Link: "../../", Text: "/"}, {Link: "../", Text: "100% test coverage"}, {Link: "", Text: "is a lie"}, }}, {"/AC%2FDC/", []crumb{ {Link: "../", Text: "/"}, {Link: "", Text: "AC/DC"}, }}, {"/foo/%2e%2e%2f/bar", []crumb{ {Link: "../../../", Text: "/"}, {Link: "../../", Text: "foo"}, {Link: "../", Text: "../"}, {Link: "", Text: "bar"}, }}, {"/foo/../bar", []crumb{ {Link: "../../../", Text: "/"}, {Link: "../../", Text: "foo"}, {Link: "../", Text: ".."}, {Link: "", Text: "bar"}, }}, {"foo/bar/baz", []crumb{ {Link: "../../", Text: "foo"}, {Link: "../", Text: "bar"}, {Link: "", Text: "baz"}, }}, {"/qux/quux/corge/", []crumb{ {Link: "../../../", Text: "/"}, {Link: "../../", Text: "qux"}, {Link: "../", Text: "quux"}, {Link: "", Text: "corge"}, }}, {"/مجلد/", []crumb{ {Link: "../", Text: "/"}, {Link: "", Text: "مجلد"}, }}, {"/مجلد-1/مجلد-2", []crumb{ {Link: "../../", Text: "/"}, {Link: "../", Text: "مجلد-1"}, {Link: "", Text: "مجلد-2"}, }}, {"/مجلد%2F1", []crumb{ {Link: "../", Text: "/"}, {Link: "", Text: "مجلد/1"}, }}, } for testNum, d := range testdata { l := browseTemplateContext{Path: d.path} actual := l.Breadcrumbs() if len(actual) != len(d.expected) { t.Errorf("Test %d: Got %d components but expected %d; got: %+v", testNum, len(actual), len(d.expected), actual) continue } for i, c := range actual { if c != d.expected[i] { t.Errorf("Test %d crumb %d: got %#v but expected %#v at index %d", testNum, i, c, d.expected[i], i) } } } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/intercept/intercept.go
modules/caddyhttp/intercept/intercept.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 intercept import ( "bytes" "fmt" "io" "net/http" "strconv" "strings" "sync" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Intercept{}) httpcaddyfile.RegisterHandlerDirective("intercept", parseCaddyfile) } // Intercept is a middleware that intercepts then replaces or modifies the original response. // It can, for instance, be used to implement X-Sendfile/X-Accel-Redirect-like features // when using modules like FrankenPHP or Caddy Snake. // // EXPERIMENTAL: Subject to change or removal. type Intercept struct { // List of handlers and their associated matchers to evaluate // after successful response generation. // The first handler that matches the original response will // be invoked. The original response body will not be // written to the client; // it is up to the handler to finish handling the response. // // Three new placeholders are available in this handler chain: // - `{http.intercept.status_code}` The status code from the response // - `{http.intercept.header.*}` The headers from the response HandleResponse []caddyhttp.ResponseHandler `json:"handle_response,omitempty"` // 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 logger *zap.Logger } // CaddyModule returns the Caddy module information. // // EXPERIMENTAL: Subject to change or removal. func (Intercept) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.intercept", New: func() caddy.Module { return new(Intercept) }, } } // Provision ensures that i is set up properly before use. // // EXPERIMENTAL: Subject to change or removal. func (irh *Intercept) Provision(ctx caddy.Context) error { // set up any response routes for i, rh := range irh.HandleResponse { err := rh.Provision(ctx) if err != nil { return fmt.Errorf("provisioning response handler %d: %w", i, err) } } irh.logger = ctx.Logger() return nil } var bufPool = sync.Pool{ New: func() any { return new(bytes.Buffer) }, } // TODO: handle status code replacement // // EXPERIMENTAL: Subject to change or removal. type interceptedResponseHandler struct { caddyhttp.ResponseRecorder replacer *caddy.Replacer handler caddyhttp.ResponseHandler handlerIndex int statusCode int } // EXPERIMENTAL: Subject to change or removal. func (irh interceptedResponseHandler) WriteHeader(statusCode int) { if irh.statusCode != 0 && (statusCode < 100 || statusCode >= 200) { irh.ResponseRecorder.WriteHeader(irh.statusCode) return } irh.ResponseRecorder.WriteHeader(statusCode) } // EXPERIMENTAL: Subject to change or removal. func (irh interceptedResponseHandler) Unwrap() http.ResponseWriter { return irh.ResponseRecorder } // EXPERIMENTAL: Subject to change or removal. func (ir Intercept) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { buf := bufPool.Get().(*bytes.Buffer) buf.Reset() defer bufPool.Put(buf) repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) rec := interceptedResponseHandler{replacer: repl} rec.ResponseRecorder = caddyhttp.NewResponseRecorder(w, buf, func(status int, header http.Header) bool { // see if any response handler is configured for this original response for i, rh := range ir.HandleResponse { if rh.Match != nil && !rh.Match.Match(status, header) { continue } rec.handler = rh rec.handlerIndex = i // if configured to only change the status code, // do that then stream if statusCodeStr := rh.StatusCode.String(); statusCodeStr != "" { sc, err := strconv.Atoi(repl.ReplaceAll(statusCodeStr, "")) if err != nil { rec.statusCode = http.StatusInternalServerError } else { rec.statusCode = sc } } return rec.statusCode == 0 } return false }) if err := next.ServeHTTP(rec, r); err != nil { return err } if !rec.Buffered() { return nil } // set up the replacer so that parts of the original response can be // used for routing decisions for field, value := range rec.Header() { repl.Set("http.intercept.header."+field, strings.Join(value, ",")) } repl.Set("http.intercept.status_code", rec.Status()) if c := ir.logger.Check(zapcore.DebugLevel, "handling response"); c != nil { c.Write(zap.Int("handler", rec.handlerIndex)) } // response recorder doesn't create a new copy of the original headers, they're // present in the original response writer // create a new recorder to see if any response body from the new handler is present, // if not, use the already buffered response body recorder := caddyhttp.NewResponseRecorder(w, nil, nil) if err := rec.handler.Routes.Compile(emptyHandler).ServeHTTP(recorder, r); err != nil { return err } // no new response status and the status is not 0 if recorder.Status() == 0 && rec.Status() != 0 { w.WriteHeader(rec.Status()) } // no new response body and there is some in the original response // TODO: what if the new response doesn't have a body by design? // see: https://github.com/caddyserver/caddy/pull/6232#issue-2235224400 if recorder.Size() == 0 && buf.Len() > 0 { _, err := io.Copy(w, buf) return err } return nil } // this handler does nothing because everything we need is already buffered var emptyHandler caddyhttp.Handler = caddyhttp.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) error { return nil }) // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // intercept [<matcher>] { // # intercept original responses // @name { // status <code...> // header <field> [<value>] // } // replace_status [<matcher>] <status_code> // handle_response [<matcher>] { // <directives...> // } // } // // The FinalizeUnmarshalCaddyfile method should be called after this // to finalize parsing of "handle_response" blocks, if possible. // // EXPERIMENTAL: Subject to change or removal. func (i *Intercept) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // collect the response matchers defined as subdirectives // prefixed with "@" for use with "handle_response" blocks i.responseMatchers = make(map[string]caddyhttp.ResponseMatcher) d.Next() // consume the directive name for d.NextBlock(0) { // if the subdirective has an "@" prefix then we // parse it as a response matcher for use with "handle_response" if strings.HasPrefix(d.Val(), matcherPrefix) { err := caddyhttp.ParseNamedResponseMatcher(d.NewFromNextSegment(), i.responseMatchers) if err != nil { return err } continue } switch d.Val() { case "handle_response": // delegate the parsing of handle_response to the caller, // since we need the httpcaddyfile.Helper to parse subroutes. // See h.FinalizeUnmarshalCaddyfile i.handleResponseSegments = append(i.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 := i.responseMatchers[args[0]] if !ok { return d.Errf("no named response matcher defined with name '%s'", args[0][1:]) } responseHandler.Match = &foundMatcher responseHandler.StatusCode = caddyhttp.WeakString(args[1]) } else if len(args) == 1 { responseHandler.StatusCode = caddyhttp.WeakString(args[0]) } // make sure there's no block, cause it doesn't make sense if nesting := d.Nesting(); d.NextBlock(nesting) { return d.Errf("cannot define routes for 'replace_status', use 'handle_response' instead.") } i.HandleResponse = append( i.HandleResponse, responseHandler, ) default: return d.Errf("unrecognized subdirective %s", d.Val()) } } return nil } // FinalizeUnmarshalCaddyfile finalizes the Caddyfile parsing which // requires having an httpcaddyfile.Helper to function, to parse subroutes. // // EXPERIMENTAL: Subject to change or removal. func (i *Intercept) FinalizeUnmarshalCaddyfile(helper httpcaddyfile.Helper) error { for _, d := range i.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 := i.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") } i.HandleResponse = append( i.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 i.HandleResponse { if hr.Match == nil { withoutMatchers = append(withoutMatchers, hr) } else { withMatchers = append(withMatchers, hr) } } i.HandleResponse = append(withMatchers, withoutMatchers...) // clean up the bits we only needed for adapting i.handleResponseSegments = nil i.responseMatchers = nil return nil } const matcherPrefix = "@" func parseCaddyfile(helper httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var ir Intercept if err := ir.UnmarshalCaddyfile(helper.Dispenser); err != nil { return nil, err } if err := ir.FinalizeUnmarshalCaddyfile(helper); err != nil { return nil, err } return ir, nil } // Interface guards var ( _ caddy.Provisioner = (*Intercept)(nil) _ caddyfile.Unmarshaler = (*Intercept)(nil) _ caddyhttp.MiddlewareHandler = (*Intercept)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/templates/tplcontext.go
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" "net/url" "os" "path" "reflect" "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" "go.uber.org/zap" "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).Option("missingkey=zero") // 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, "ph": c.funcPlaceholder, // shortcut "fileExists": c.funcFileExists, "httpError": c.funcHTTPError, "humanize": c.funcHumanize, "maybe": c.funcMaybe, "pathEscape": url.PathEscape, }) 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.RemoteAddr = "127.0.0.1:10000" // https://github.com/caddyserver/caddy/issues/5835 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) // For safety, we don't want to allow the file placeholder in // templates because it could be used to read arbitrary files // if the template contents were not trusted. repl = repl.WithoutFile() 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. 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 connection's remote IP. func (c TemplateContext) RemoteIP() string { ip, _, err := net.SplitHostPort(c.Req.RemoteAddr) if err != nil { return c.Req.RemoteAddr } return ip } // ClientIP gets the IP address of the real client making the request // if the request is trusted (see trusted_proxies), otherwise returns // the connection's remote IP. func (c TemplateContext) ClientIP() string { address := caddyhttp.GetVar(c.Req.Context(), caddyhttp.ClientIPVarKey).(string) clientIP, _, err := net.SplitHostPort(address) if err != nil { clientIP = address // no port } return clientIP } // 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 } // funcSplitFrontMatter 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) { // Delete some headers that may have been set by the underlying // handler (such as file_server) which may break the error response. c.RespHeader.Header.Del("Content-Length") c.RespHeader.Header.Del("Content-Type") c.RespHeader.Header.Del("Etag") c.RespHeader.Header.Del("Last-Modified") c.RespHeader.Header.Del("Accept-Ranges") 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") } // funcMaybe invokes the plugged-in function named functionName if it is plugged in // (is a module in the 'http.handlers.templates.functions' namespace). If it is not // available, a log message is emitted. // // The first argument is the function name, and the rest of the arguments are // passed on to the actual function. // // This function is useful for executing templates that use components that may be // considered as optional in some cases (like during local development) where you do // not want to require everyone to have a custom Caddy build to be able to execute // your template. // // NOTE: This function is EXPERIMENTAL and subject to change or removal. func (c TemplateContext) funcMaybe(functionName string, args ...any) (any, error) { for _, funcMap := range c.CustomFuncs { if fn, ok := funcMap[functionName]; ok { val := reflect.ValueOf(fn) if val.Kind() != reflect.Func { continue } argVals := make([]reflect.Value, len(args)) for i, arg := range args { argVals[i] = reflect.ValueOf(arg) } returnVals := val.Call(argVals) switch len(returnVals) { case 0: return "", nil case 1: return returnVals[0].Interface(), nil case 2: var err error if !returnVals[1].IsNil() { err = returnVals[1].Interface().(error) } return returnVals[0].Interface(), err default: return nil, fmt.Errorf("maybe %s: invalid number of return values: %d", functionName, len(returnVals)) } } } c.config.logger.Named("maybe").Warn("template function could not be found; ignoring invocation", zap.String("name", functionName)) return "", nil } // 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/templates/templates.go
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" "go.uber.org/zap" "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`](#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"}} // ``` // // As a shortcut, `ph` is an alias for `placeholder`. // // ``` // {{ph "http.request.method"}} // ``` // // ##### `.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. Use [`.Args N`](#args) to access the N-th // argument, 0-indexed. 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" "arg0" 1 "value 2"}} // 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 connection's IP address. // // ``` // {{.RemoteIP}} // ``` // // ##### `.ClientIP` // // Returns the real client's IP address, if `trusted_proxies` was configured, // otherwise returns the connection's IP address. // // ``` // {{.ClientIP}} // ``` // // ##### `.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`](#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 `+++`: // // ```toml // +++ // template = "blog" // title = "Blog Homepage" // sitename = "A Caddy site" // +++ // ``` // // **YAML** is surrounded by `---`: // // ```yaml // --- // template: blog // title: Blog Homepage // sitename: A Caddy site // --- // ``` // // **JSON** is simply `{` and `}`: // // ```json // { // "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"}} // ``` // // ##### `pathEscape` // // Passes a string through `url.PathEscape`, replacing characters that have // special meaning in URL path parameters (`?`, `&`, `%`). // // Useful e.g. to include filenames containing these characters in URL path // parameters, or use them as an `img` element's `src` attribute. // // ``` // {{pathEscape "50%_valid_filename?.jpg"}} // ``` // // ##### `maybe` // // Invokes a custom template function only if it is registered (plugged-in) // in the `http.handlers.templates.functions.*` namespace. // // The first argument is the function name, and any subsequent arguments // are forwarded to that function. If the named function is not available, // the invocation is ignored and a log message is emitted. // // This is useful for templates that optionally use components which may // not be present in every build or environment. // // NOTE: This function is EXPERIMENTAL and subject to change or removal. // // ``` // {{ maybe "myOptionalFunc" "arg1" 2 }} // ``` 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"` // Extensions adds functions to the template's func map. These often // act as components on web pages, for example. ExtensionsRaw caddy.ModuleMap `json:"match,omitempty" caddy:"namespace=http.handlers.templates.functions"` customFuncs []template.FuncMap logger *zap.Logger } // 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 { t.logger = ctx.Logger() mods, err := ctx.LoadModule(t, "ExtensionsRaw") if err != nil { return fmt.Errorf("loading template extensions: %v", err) } for _, modIface := range mods.(map[string]any) { t.customFuncs = append(t.customFuncs, modIface.(CustomFunctions).CustomTemplateFunctions()) } 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/templates/caddyfile.go
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" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { httpcaddyfile.RegisterHandlerDirective("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) { h.Next() // consume directive name t := new(Templates) 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() } case "extensions": if h.NextArg() { return nil, h.ArgErr() } if t.ExtensionsRaw != nil { return nil, h.Err("extensions already specified") } for nesting := h.Nesting(); h.NextBlock(nesting); { extensionModuleName := h.Val() modID := "http.handlers.templates.functions." + extensionModuleName unm, err := caddyfile.UnmarshalModule(h.Dispenser, modID) if err != nil { return nil, err } cf, ok := unm.(CustomFunctions) if !ok { return nil, h.Errf("module %s (%T) does not provide template functions", modID, unm) } if t.ExtensionsRaw == nil { t.ExtensionsRaw = make(caddy.ModuleMap) } t.ExtensionsRaw[extensionModuleName] = caddyconfig.JSON(cf, nil) } } } return t, nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/templates/frontmatter_fuzz.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/templates/tplcontext_test.go
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" "errors" "fmt" "io/fs" "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 && !errors.Is(err, fs.ErrNotExist) { 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 && !errors.Is(err, fs.ErrNotExist) { t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err) } } if absFilePath0 != "" { if err := os.Remove(absFilePath0); err != nil && !errors.Is(err, fs.ErrNotExist) { t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err) } } if absFilePath1 != "" { if err := os.Remove(absFilePath1); err != nil && !errors.Is(err, fs.ErrNotExist) { 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 && !errors.Is(err, fs.ErrNotExist) { 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: func(err error) bool { return errors.Is(err, fs.ErrNotExist) }, }, { // 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: func(err error) bool { return errors.Is(err, fs.ErrNotExist) }, }, } { 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 && !errors.Is(err, fs.ErrNotExist) { 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/templates/frontmatter.go
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 break } } 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/map/map_test.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/map/caddyfile.go
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) { h.Next() // consume directive name var handler Handler // 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/map/map.go
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" "slices" "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 := slices.Index(h.Destinations, 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) } // 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/requestbody/caddyfile.go
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 ( "time" "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) { h.Next() // consume directive name rb := new(RequestBody) // 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) case "read_timeout": var timeoutStr string if !h.AllArgs(&timeoutStr) { return nil, h.ArgErr() } timeout, err := time.ParseDuration(timeoutStr) if err != nil { return nil, h.Errf("parsing read_timeout: %v", err) } rb.ReadTimeout = timeout case "write_timeout": var timeoutStr string if !h.AllArgs(&timeoutStr) { return nil, h.ArgErr() } timeout, err := time.ParseDuration(timeoutStr) if err != nil { return nil, h.Errf("parsing write_timeout: %v", err) } rb.WriteTimeout = timeout case "set": var setStr string if !h.AllArgs(&setStr) { return nil, h.ArgErr() } rb.Set = setStr default: return nil, h.Errf("unrecognized request_body subdirective '%s'", h.Val()) } } return rb, nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/requestbody/requestbody.go
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 ( "errors" "io" "net/http" "strings" "time" "go.uber.org/zap" "go.uber.org/zap/zapcore" "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"` // EXPERIMENTAL. Subject to change/removal. ReadTimeout time.Duration `json:"read_timeout,omitempty"` // EXPERIMENTAL. Subject to change/removal. WriteTimeout time.Duration `json:"write_timeout,omitempty"` // This field permit to replace body on the fly // EXPERIMENTAL. Subject to change/removal. Set string `json:"set,omitempty"` logger *zap.Logger } // 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) Provision(ctx caddy.Context) error { rb.logger = ctx.Logger() return nil } func (rb RequestBody) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { if rb.Set != "" { if r.Body != nil { err := r.Body.Close() if err != nil { return err } } repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) replacedBody := repl.ReplaceAll(rb.Set, "") r.Body = io.NopCloser(strings.NewReader(replacedBody)) r.ContentLength = int64(len(replacedBody)) } if r.Body == nil { return next.ServeHTTP(w, r) } if rb.MaxSize > 0 { r.Body = errorWrapper{http.MaxBytesReader(w, r.Body, rb.MaxSize)} } if rb.ReadTimeout > 0 || rb.WriteTimeout > 0 { //nolint:bodyclose rc := http.NewResponseController(w) if rb.ReadTimeout > 0 { if err := rc.SetReadDeadline(time.Now().Add(rb.ReadTimeout)); err != nil { if c := rb.logger.Check(zapcore.ErrorLevel, "could not set read deadline"); c != nil { c.Write(zap.Error(err)) } } } if rb.WriteTimeout > 0 { if err := rc.SetWriteDeadline(time.Now().Add(rb.WriteTimeout)); err != nil { if c := rb.logger.Check(zapcore.ErrorLevel, "could not set write deadline"); c != nil { c.Write(zap.Error(err)) } } } } 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) var mbe *http.MaxBytesError if errors.As(err, &mbe) { err = caddyhttp.Error(http.StatusRequestEntityTooLarge, err) } return n, err } // Interface guard var _ caddyhttp.MiddlewareHandler = (*RequestBody)(nil)
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/rewrite/rewrite_test.go
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/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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/rewrite/caddyfile.go
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.RegisterDirective("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) ([]httpcaddyfile.ConfigValue, error) { h.Next() // consume directive name // count the tokens to determine what to do argsCount := h.CountRemainingArgs() if argsCount == 0 { return nil, h.Errf("too few arguments; must have at least a rewrite URI") } if argsCount > 2 { return nil, h.Errf("too many arguments; should only be a matcher and a URI") } // with only one arg, assume it's a rewrite URI with no matcher token if argsCount == 1 { if !h.NextArg() { return nil, h.ArgErr() } return h.NewRoute(nil, Rewrite{URI: h.Val()}), nil } // parse the matcher token into a matcher set userMatcherSet, err := h.ExtractMatcherSet() if err != nil { return nil, err } h.Next() // consume directive name again, matcher parsing does a reset h.Next() // advance to the rewrite URI return h.NewRoute(userMatcherSet, Rewrite{URI: h.Val()}), nil } // parseCaddyfileMethod sets up a basic method rewrite handler from Caddyfile tokens. Syntax: // // method [<matcher>] <method> func parseCaddyfileMethod(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { h.Next() // consume directive name if !h.NextArg() { return nil, h.ArgErr() } if h.NextArg() { return nil, h.ArgErr() } return Rewrite{Method: h.Val()}, 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) { h.Next() // consume directive name args := h.RemainingArgs() if len(args) < 1 { return nil, h.ArgErr() } var rewr Rewrite switch args[0] { case "strip_prefix": if len(args) != 2 { return nil, h.ArgErr() } rewr.StripPathPrefix = args[1] 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, }) case "query": if len(args) > 4 { return nil, h.ArgErr() } rewr.Query = &queryOps{} var hasArgs bool if len(args) > 1 { hasArgs = true err := applyQueryOps(h, rewr.Query, args[1:]) if err != nil { return nil, err } } for h.NextBlock(0) { if hasArgs { return nil, h.Err("Cannot specify uri query rewrites in both argument and block") } queryArgs := []string{h.Val()} queryArgs = append(queryArgs, h.RemainingArgs()...) err := applyQueryOps(h, rewr.Query, queryArgs) if err != nil { return nil, err } } default: return nil, h.Errf("unrecognized URI manipulation '%s'", args[0]) } return rewr, nil } func applyQueryOps(h httpcaddyfile.Helper, qo *queryOps, args []string) error { key := args[0] switch { case strings.HasPrefix(key, "-"): if len(args) != 1 { return h.ArgErr() } qo.Delete = append(qo.Delete, strings.TrimLeft(key, "-")) case strings.HasPrefix(key, "+"): if len(args) != 2 { return h.ArgErr() } param := strings.TrimLeft(key, "+") qo.Add = append(qo.Add, queryOpsArguments{Key: param, Val: args[1]}) case strings.Contains(key, ">"): if len(args) != 1 { return h.ArgErr() } renameValKey := strings.Split(key, ">") qo.Rename = append(qo.Rename, queryOpsArguments{Key: renameValKey[0], Val: renameValKey[1]}) case len(args) == 3: qo.Replace = append(qo.Replace, &queryOpsReplacement{Key: key, SearchRegexp: args[1], Replace: args[2]}) default: if len(args) != 2 { return h.ArgErr() } qo.Set = append(qo.Set, queryOpsArguments{Key: key, Val: args[1]}) } return 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) { h.Next() // consume directive name // there must be a path matcher 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/rewrite/rewrite.go
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"` // Mutates the query string of the URI. Query *queryOps `json:"query,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 } if rewr.Query != nil { for _, replacementOp := range rewr.Query.Replace { err := replacementOp.Provision(ctx) if err != nil { return fmt.Errorf("compiling regular expression %s in query rewrite replace operation: %v", replacementOp.SearchRegexp, err) } } } return nil } func (rewr Rewrite) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) const message = "rewrote request" c := rewr.logger.Check(zap.DebugLevel, message) if c == nil { rewr.Rewrite(r, repl) return next.ServeHTTP(w, r) } changed := rewr.Rewrite(r, repl) if changed { c.Write( zap.Object("request", caddyhttp.LoggableHTTPRequest{Request: r}), 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, "") if !strings.HasPrefix(prefix, "/") { prefix = "/" + prefix } 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) } // apply query operations if rewr.Query != nil { rewr.Query.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 iPath < len(escapedPath) && iPrefix < len(prefix) { 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 = "" } } // queryOps describes the operations to perform on query keys: add, set, rename and delete. type queryOps struct { // Renames a query key from Key to Val, without affecting the value. Rename []queryOpsArguments `json:"rename,omitempty"` // Sets query parameters; overwrites a query key with the given value. Set []queryOpsArguments `json:"set,omitempty"` // Adds query parameters; does not overwrite an existing query field, // and only appends an additional value for that key if any already exist. Add []queryOpsArguments `json:"add,omitempty"` // Replaces query parameters. Replace []*queryOpsReplacement `json:"replace,omitempty"` // Deletes a given query key by name. Delete []string `json:"delete,omitempty"` } // Provision compiles the query replace operation regex. func (replacement *queryOpsReplacement) Provision(_ caddy.Context) error { if replacement.SearchRegexp != "" { re, err := regexp.Compile(replacement.SearchRegexp) if err != nil { return fmt.Errorf("replacement for query field '%s': %v", replacement.Key, err) } replacement.re = re } return nil } func (q *queryOps) do(r *http.Request, repl *caddy.Replacer) { query := r.URL.Query() for _, renameParam := range q.Rename { key := repl.ReplaceAll(renameParam.Key, "") val := repl.ReplaceAll(renameParam.Val, "") if key == "" || val == "" { continue } query[val] = query[key] delete(query, key) } for _, setParam := range q.Set { key := repl.ReplaceAll(setParam.Key, "") if key == "" { continue } val := repl.ReplaceAll(setParam.Val, "") query[key] = []string{val} } for _, addParam := range q.Add { key := repl.ReplaceAll(addParam.Key, "") if key == "" { continue } val := repl.ReplaceAll(addParam.Val, "") query[key] = append(query[key], val) } for _, replaceParam := range q.Replace { key := repl.ReplaceAll(replaceParam.Key, "") search := repl.ReplaceKnown(replaceParam.Search, "") replace := repl.ReplaceKnown(replaceParam.Replace, "") // replace all query keys... if key == "*" { for fieldName, vals := range query { for i := range vals { if replaceParam.re != nil { query[fieldName][i] = replaceParam.re.ReplaceAllString(query[fieldName][i], replace) } else { query[fieldName][i] = strings.ReplaceAll(query[fieldName][i], search, replace) } } } continue } for fieldName, vals := range query { for i := range vals { if replaceParam.re != nil { query[fieldName][i] = replaceParam.re.ReplaceAllString(query[fieldName][i], replace) } else { query[fieldName][i] = strings.ReplaceAll(query[fieldName][i], search, replace) } } } } for _, deleteParam := range q.Delete { param := repl.ReplaceAll(deleteParam, "") if param == "" { continue } delete(query, param) } r.URL.RawQuery = query.Encode() } type queryOpsArguments struct { // A key in the query string. Note that query string keys may appear multiple times. Key string `json:"key,omitempty"` // The value for the given operation; for add and set, this is // simply the value of the query, and for rename this is the // query key to rename to. Val string `json:"val,omitempty"` } type queryOpsReplacement struct { // The key to replace in the query string. Key string `json:"key,omitempty"` // 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 } // Interface guard var _ caddyhttp.MiddlewareHandler = (*Rewrite)(nil)
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/encode/caddyfile.go
modules/caddyhttp/encode/caddyfile.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package encode import ( "strconv" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { httpcaddyfile.RegisterHandlerDirective("encode", parseCaddyfile) } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { enc := new(Encode) err := enc.UnmarshalCaddyfile(h.Dispenser) if err != nil { return nil, err } return enc, nil } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // encode [<matcher>] <formats...> { // gzip [<level>] // zstd // minimum_length <length> // # response matcher block // match { // status <code...> // header <field> [<value>] // } // # or response matcher single line syntax // match [header <field> [<value>]] | [status <code...>] // } // // Specifying the formats on the first line will use those formats' defaults. func (enc *Encode) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume directive name prefer := []string{} remainingArgs := d.RemainingArgs() responseMatchers := make(map[string]caddyhttp.ResponseMatcher) for d.NextBlock(0) { switch d.Val() { case "minimum_length": if !d.NextArg() { return d.ArgErr() } minLength, err := strconv.Atoi(d.Val()) if err != nil { return err } enc.MinLength = minLength case "match": err := caddyhttp.ParseNamedResponseMatcher(d.NewFromNextSegment(), responseMatchers) if err != nil { return err } matcher := responseMatchers["match"] enc.Matcher = &matcher default: name := d.Val() modID := "http.encoders." + name unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } encoding, ok := unm.(Encoding) if !ok { return d.Errf("module %s is not an HTTP encoding; is %T", modID, unm) } if enc.EncodingsRaw == nil { enc.EncodingsRaw = make(caddy.ModuleMap) } enc.EncodingsRaw[name] = caddyconfig.JSON(encoding, nil) prefer = append(prefer, name) } } if len(prefer) == 0 && len(remainingArgs) == 0 { remainingArgs = []string{"zstd", "gzip"} } for _, arg := range remainingArgs { mod, err := caddy.GetModule("http.encoders." + arg) if err != nil { return d.Errf("finding encoder module '%s': %v", mod, err) } encoding, ok := mod.New().(Encoding) if !ok { return d.Errf("module %s is not an HTTP encoding", mod) } if enc.EncodingsRaw == nil { enc.EncodingsRaw = make(caddy.ModuleMap) } enc.EncodingsRaw[arg] = caddyconfig.JSON(encoding, nil) prefer = append(prefer, arg) } // use the order in which the encoders were defined. enc.Prefer = prefer return nil } // Interface guard var _ caddyfile.Unmarshaler = (*Encode)(nil)
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/encode/encode.go
modules/caddyhttp/encode/encode.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package encode implements an encoder middleware for Caddy. The initial // enhancements related to Accept-Encoding, minimum content length, and // buffer/writer pools were adapted from https://github.com/xi2/httpgzip // then modified heavily to accommodate modular encoders and fix bugs. // Code borrowed from that repository is Copyright (c) 2015 The Httpgzip Authors. package encode import ( "fmt" "io" "math" "net/http" "slices" "sort" "strconv" "strings" "sync" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Encode{}) } // Encode is a middleware which can encode responses. type Encode struct { // Selection of compression algorithms to choose from. The best one // will be chosen based on the client's Accept-Encoding header. EncodingsRaw caddy.ModuleMap `json:"encodings,omitempty" caddy:"namespace=http.encoders"` // If the client has no strong preference, choose these encodings in order. Prefer []string `json:"prefer,omitempty"` // Only encode responses that are at least this many bytes long. MinLength int `json:"minimum_length,omitempty"` // Only encode responses that match against this ResponseMatcher. // The default is a collection of text-based Content-Type headers. Matcher *caddyhttp.ResponseMatcher `json:"match,omitempty"` writerPools map[string]*sync.Pool // TODO: these pools do not get reused through config reloads... } // CaddyModule returns the Caddy module information. func (Encode) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.encode", New: func() caddy.Module { return new(Encode) }, } } // Provision provisions enc. func (enc *Encode) Provision(ctx caddy.Context) error { mods, err := ctx.LoadModule(enc, "EncodingsRaw") if err != nil { return fmt.Errorf("loading encoder modules: %v", err) } for modName, modIface := range mods.(map[string]any) { err = enc.addEncoding(modIface.(Encoding)) if err != nil { return fmt.Errorf("adding encoding %s: %v", modName, err) } } if enc.MinLength == 0 { enc.MinLength = defaultMinLength } if enc.Matcher == nil { // common text-based content types // list based on https://developers.cloudflare.com/speed/optimization/content/brotli/content-compression/#compression-between-cloudflare-and-website-visitors enc.Matcher = &caddyhttp.ResponseMatcher{ Headers: http.Header{ "Content-Type": []string{ "application/atom+xml*", "application/eot*", "application/font*", "application/geo+json*", "application/graphql+json*", "application/graphql-response+json*", "application/javascript*", "application/json*", "application/ld+json*", "application/manifest+json*", "application/opentype*", "application/otf*", "application/rss+xml*", "application/truetype*", "application/ttf*", "application/vnd.api+json*", "application/vnd.ms-fontobject*", "application/wasm*", "application/x-httpd-cgi*", "application/x-javascript*", "application/x-opentype*", "application/x-otf*", "application/x-perl*", "application/x-protobuf*", "application/x-ttf*", "application/xhtml+xml*", "application/xml*", "font/ttf*", "font/otf*", "image/svg+xml*", "image/vnd.microsoft.icon*", "image/x-icon*", "multipart/bag*", "multipart/mixed*", "text/*", }, }, } } return nil } // Validate ensures that enc's configuration is valid. func (enc *Encode) Validate() error { check := make(map[string]bool) for _, encName := range enc.Prefer { if _, ok := enc.writerPools[encName]; !ok { return fmt.Errorf("encoding %s not enabled", encName) } if _, ok := check[encName]; ok { return fmt.Errorf("encoding %s is duplicated in prefer", encName) } check[encName] = true } return nil } func isEncodeAllowed(h http.Header) bool { return !strings.Contains(h.Get("Cache-Control"), "no-transform") } func (enc *Encode) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { if isEncodeAllowed(r.Header) { for _, encName := range AcceptedEncodings(r, enc.Prefer) { if _, ok := enc.writerPools[encName]; !ok { continue // encoding not offered } w = enc.openResponseWriter(encName, w, r.Method == http.MethodConnect) defer w.(*responseWriter).Close() // to comply with RFC 9110 section 8.8.3(.3), we modify the Etag when encoding // by appending a hyphen and the encoder name; the problem is, the client will // send back that Etag in a If-None-Match header, but upstream handlers that set // the Etag in the first place don't know that we appended to their Etag! so here // we have to strip our addition so the upstream handlers can still honor client // caches without knowing about our changes... if etag := r.Header.Get("If-None-Match"); etag != "" && !strings.HasPrefix(etag, "W/") { ourSuffix := "-" + encName + `"` if before, ok := strings.CutSuffix(etag, ourSuffix); ok { etag = before + `"` r.Header.Set("If-None-Match", etag) } } break } } err := next.ServeHTTP(w, r) // If there was an error, disable encoding completely // This prevents corruption when handle_errors processes the response if err != nil { if ew, ok := w.(*responseWriter); ok { ew.disabled = true } } return err } func (enc *Encode) addEncoding(e Encoding) error { ae := e.AcceptEncoding() if ae == "" { return fmt.Errorf("encoder does not specify an Accept-Encoding value") } if _, ok := enc.writerPools[ae]; ok { return fmt.Errorf("encoder already added: %s", ae) } if enc.writerPools == nil { enc.writerPools = make(map[string]*sync.Pool) } enc.writerPools[ae] = &sync.Pool{ New: func() any { return e.NewEncoder() }, } return nil } // openResponseWriter creates a new response writer that may (or may not) // encode the response with encodingName. The returned response writer MUST // be closed after the handler completes. func (enc *Encode) openResponseWriter(encodingName string, w http.ResponseWriter, isConnect bool) *responseWriter { var rw responseWriter return enc.initResponseWriter(&rw, encodingName, w, isConnect) } // initResponseWriter initializes the responseWriter instance // allocated in openResponseWriter, enabling mid-stack inlining. func (enc *Encode) initResponseWriter(rw *responseWriter, encodingName string, wrappedRW http.ResponseWriter, isConnect bool) *responseWriter { if rww, ok := wrappedRW.(*caddyhttp.ResponseWriterWrapper); ok { rw.ResponseWriter = rww } else { rw.ResponseWriter = &caddyhttp.ResponseWriterWrapper{ResponseWriter: wrappedRW} } rw.encodingName = encodingName rw.config = enc rw.isConnect = isConnect return rw } // responseWriter writes to an underlying response writer // using the encoding represented by encodingName and // configured by config. type responseWriter struct { http.ResponseWriter encodingName string w Encoder config *Encode statusCode int wroteHeader bool isConnect bool disabled bool // disable encoding (for error responses) } // WriteHeader stores the status to write when the time comes // to actually write the header. func (rw *responseWriter) WriteHeader(status int) { rw.statusCode = status // See #5849 and RFC 9110 section 15.4.5 (https://www.rfc-editor.org/rfc/rfc9110.html#section-15.4.5) - 304 // Not Modified must have certain headers set as if it was a 200 response, and according to the issue // we would miss the Vary header in this case when compression was also enabled; note that we set this // header in the responseWriter.init() method but that is only called if we are writing a response body if status == http.StatusNotModified && !hasVaryValue(rw.Header(), "Accept-Encoding") { rw.Header().Add("Vary", "Accept-Encoding") } // write status immediately if status is 2xx and the request is CONNECT // since it means the response is successful. // see: https://github.com/caddyserver/caddy/issues/6733#issuecomment-2525058845 if rw.isConnect && 200 <= status && status <= 299 { rw.ResponseWriter.WriteHeader(status) rw.wroteHeader = true } // write status immediately when status code is informational // see: https://caddy.community/t/disappear-103-early-hints-response-with-encode-enable-caddy-v2-7-6/23081/5 if 100 <= status && status <= 199 { rw.ResponseWriter.WriteHeader(status) } } // Match determines, if encoding should be done based on the ResponseMatcher. func (enc *Encode) Match(rw *responseWriter) bool { return enc.Matcher.Match(rw.statusCode, rw.Header()) } // FlushError is an alternative Flush returning an error. It delays the actual Flush of the underlying // ResponseWriterWrapper until headers were written. func (rw *responseWriter) FlushError() error { // WriteHeader wasn't called and is a CONNECT request, treat it as a success. // otherwise, wait until header is written. if rw.isConnect && !rw.wroteHeader && rw.statusCode == 0 { rw.WriteHeader(http.StatusOK) } if !rw.wroteHeader { // flushing the underlying ResponseWriter will write header and status code, // but we need to delay that until we can determine if we must encode and // therefore add the Content-Encoding header; this happens in the first call // to rw.Write (see bug in #4314) return nil } // also flushes the encoder, if any // see: https://github.com/jjiang-stripe/caddy-slow-gzip if rw.w != nil { err := rw.w.Flush() if err != nil { return err } } //nolint:bodyclose return http.NewResponseController(rw.ResponseWriter).Flush() } // Write writes to the response. If the response qualifies, // it is encoded using the encoder, which is initialized // if not done so already. func (rw *responseWriter) Write(p []byte) (int, error) { // ignore zero data writes, probably head request if len(p) == 0 { return 0, nil } // WriteHeader wasn't called and is a CONNECT request, treat it as a success. // otherwise, determine if the response should be compressed. if rw.isConnect && !rw.wroteHeader && rw.statusCode == 0 { rw.WriteHeader(http.StatusOK) } // sniff content-type and determine content-length if !rw.wroteHeader && rw.config.MinLength > 0 { var gtMinLength bool if len(p) > rw.config.MinLength { gtMinLength = true } else if cl, err := strconv.Atoi(rw.Header().Get("Content-Length")); err == nil && cl > rw.config.MinLength { gtMinLength = true } if gtMinLength { if rw.Header().Get("Content-Type") == "" { rw.Header().Set("Content-Type", http.DetectContentType(p)) } rw.init() } } // before we write to the response, we need to make // sure the header is written exactly once; we do // that by checking if a status code has been set, // and if so, that means we haven't written the // header OR the default status code will be written // by the standard library if !rw.wroteHeader { if rw.statusCode != 0 { rw.ResponseWriter.WriteHeader(rw.statusCode) } rw.wroteHeader = true } if rw.w != nil { return rw.w.Write(p) } else { return rw.ResponseWriter.Write(p) } } // used to mask ReadFrom method type writerOnly struct { io.Writer } // copied from stdlib const sniffLen = 512 // ReadFrom will try to use sendfile to copy from the reader to the response writer. // It's only used if the response writer implements io.ReaderFrom and the data can't be compressed. // It's based on stdlin http1.1 response writer implementation. // https://github.com/golang/go/blob/f4e3ec3dbe3b8e04a058d266adf8e048bab563f2/src/net/http/server.go#L586 func (rw *responseWriter) ReadFrom(r io.Reader) (int64, error) { rf, ok := rw.ResponseWriter.(io.ReaderFrom) // sendfile can't be used anyway if !ok { // mask ReadFrom to avoid infinite recursion return io.Copy(writerOnly{rw}, r) } var ns int64 // try to sniff the content type and determine if the response should be compressed if !rw.wroteHeader && rw.config.MinLength > 0 { var ( err error buf [sniffLen]byte ) // mask ReadFrom to let Write determine if the response should be compressed ns, err = io.CopyBuffer(writerOnly{rw}, io.LimitReader(r, sniffLen), buf[:]) if err != nil || ns < sniffLen { return ns, err } } // the response will be compressed, no sendfile support if rw.w != nil { nr, err := io.Copy(rw.w, r) return nr + ns, err } nr, err := rf.ReadFrom(r) return nr + ns, err } // Close writes any remaining buffered response and // deallocates any active resources. func (rw *responseWriter) Close() error { // didn't write, probably head request if !rw.wroteHeader { cl, err := strconv.Atoi(rw.Header().Get("Content-Length")) if err == nil && cl > rw.config.MinLength { rw.init() } // issue #5059, don't write status code if not set explicitly. if rw.statusCode != 0 { rw.ResponseWriter.WriteHeader(rw.statusCode) } rw.wroteHeader = true } var err error if rw.w != nil { err = rw.w.Close() rw.w.Reset(nil) rw.config.writerPools[rw.encodingName].Put(rw.w) rw.w = nil } return err } // Unwrap returns the underlying ResponseWriter. func (rw *responseWriter) Unwrap() http.ResponseWriter { return rw.ResponseWriter } // init should be called before we write a response, if rw.buf has contents. func (rw *responseWriter) init() { // Don't initialize encoder for error responses // This prevents response corruption when handle_errors is used if rw.disabled { return } hdr := rw.Header() if hdr.Get("Content-Encoding") == "" && isEncodeAllowed(hdr) && rw.config.Match(rw) { rw.w = rw.config.writerPools[rw.encodingName].Get().(Encoder) rw.w.Reset(rw.ResponseWriter) hdr.Del("Content-Length") // https://github.com/golang/go/issues/14975 hdr.Set("Content-Encoding", rw.encodingName) if !hasVaryValue(hdr, "Accept-Encoding") { hdr.Add("Vary", "Accept-Encoding") } hdr.Del("Accept-Ranges") // we don't know ranges for dynamically-encoded content // strong ETags need to be distinct depending on the encoding ("selected representation") // see RFC 9110 section 8.8.3.3: // https://www.rfc-editor.org/rfc/rfc9110.html#name-example-entity-tags-varying // I don't know a great way to do this... how about appending? That's a neat trick! // (We have to strip the value we append from If-None-Match headers before // sending subsequent requests back upstream, however, since upstream handlers // don't know about our appending to their Etag since they've already done their work) if etag := hdr.Get("Etag"); etag != "" && !strings.HasPrefix(etag, "W/") { etag = fmt.Sprintf(`%s-%s"`, strings.TrimSuffix(etag, `"`), rw.encodingName) hdr.Set("Etag", etag) } } } func hasVaryValue(hdr http.Header, target string) bool { for _, vary := range hdr.Values("Vary") { for val := range strings.SplitSeq(vary, ",") { if strings.EqualFold(strings.TrimSpace(val), target) { return true } } } return false } // AcceptedEncodings returns the list of encodings that the // client supports, in descending order of preference. // The client preference via q-factor and the server // preference via Prefer setting are taken into account. If // the Sec-WebSocket-Key header is present then non-identity // encodings are not considered. See // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html. func AcceptedEncodings(r *http.Request, preferredOrder []string) []string { acceptEncHeader := r.Header.Get("Accept-Encoding") websocketKey := r.Header.Get("Sec-WebSocket-Key") if acceptEncHeader == "" { return []string{} } prefs := []encodingPreference{} for accepted := range strings.SplitSeq(acceptEncHeader, ",") { parts := strings.Split(accepted, ";") encName := strings.ToLower(strings.TrimSpace(parts[0])) // determine q-factor qFactor := 1.0 if len(parts) > 1 { qFactorStr := strings.ToLower(strings.TrimSpace(parts[1])) if strings.HasPrefix(qFactorStr, "q=") { if qFactorFloat, err := strconv.ParseFloat(qFactorStr[2:], 32); err == nil { if qFactorFloat >= 0 && qFactorFloat <= 1 { qFactor = qFactorFloat } } } } // encodings with q-factor of 0 are not accepted; // use a small threshold to account for float precision if qFactor < 0.00001 { continue } // don't encode WebSocket handshakes if websocketKey != "" && encName != "identity" { continue } // set server preference prefOrder := slices.Index(preferredOrder, encName) if prefOrder > -1 { prefOrder = len(preferredOrder) - prefOrder } prefs = append(prefs, encodingPreference{ encoding: encName, q: qFactor, preferOrder: prefOrder, }) } // sort preferences by descending q-factor first, then by preferOrder sort.Slice(prefs, func(i, j int) bool { if math.Abs(prefs[i].q-prefs[j].q) < 0.00001 { return prefs[i].preferOrder > prefs[j].preferOrder } return prefs[i].q > prefs[j].q }) prefEncNames := make([]string, len(prefs)) for i := range prefs { prefEncNames[i] = prefs[i].encoding } return prefEncNames } // encodingPreference pairs an encoding with its q-factor. type encodingPreference struct { encoding string q float64 preferOrder int } // Encoder is a type which can encode a stream of data. type Encoder interface { io.WriteCloser Reset(io.Writer) Flush() error // encoder by default buffers data to maximize compressing rate } // Encoding is a type which can create encoders of its kind // and return the name used in the Accept-Encoding header. type Encoding interface { AcceptEncoding() string NewEncoder() Encoder } // Precompressed is a type which returns filename suffix of precompressed // file and Accept-Encoding header to use when serving this file. type Precompressed interface { AcceptEncoding() string Suffix() string } // defaultMinLength is the minimum length at which to compress content. const defaultMinLength = 512 // Interface guards var ( _ caddy.Provisioner = (*Encode)(nil) _ caddy.Validator = (*Encode)(nil) _ caddyhttp.MiddlewareHandler = (*Encode)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/encode/encode_test.go
modules/caddyhttp/encode/encode_test.go
package encode import ( "net/http" "slices" "sync" "testing" ) func BenchmarkOpenResponseWriter(b *testing.B) { enc := new(Encode) for b.Loop() { enc.openResponseWriter("test", nil, false) } } func TestPreferOrder(t *testing.T) { testCases := []struct { name string accept string prefer []string expected []string }{ { name: "PreferOrder(): 4 accept, 3 prefer", accept: "deflate, gzip, br, zstd", prefer: []string{"zstd", "br", "gzip"}, expected: []string{"zstd", "br", "gzip", "deflate"}, }, { name: "PreferOrder(): 2 accept, 3 prefer", accept: "deflate, zstd", prefer: []string{"zstd", "br", "gzip"}, expected: []string{"zstd", "deflate"}, }, { name: "PreferOrder(): 2 accept (1 empty), 3 prefer", accept: "gzip,,zstd", prefer: []string{"zstd", "br", "gzip"}, expected: []string{"zstd", "gzip", ""}, }, { name: "PreferOrder(): 1 accept, 2 prefer", accept: "gzip", prefer: []string{"zstd", "gzip"}, expected: []string{"gzip"}, }, { name: "PreferOrder(): 4 accept (1 duplicate), 1 prefer", accept: "deflate, gzip, br, br", prefer: []string{"br"}, expected: []string{"br", "br", "deflate", "gzip"}, }, { name: "PreferOrder(): empty accept, 0 prefer", accept: "", prefer: []string{}, expected: []string{}, }, { name: "PreferOrder(): empty accept, 1 prefer", accept: "", prefer: []string{"gzip"}, expected: []string{}, }, { name: "PreferOrder(): with q-factor", accept: "deflate;q=0.8, gzip;q=0.4, br;q=0.2, zstd", prefer: []string{"gzip"}, expected: []string{"zstd", "deflate", "gzip", "br"}, }, { name: "PreferOrder(): with q-factor, no prefer", accept: "deflate;q=0.8, gzip;q=0.4, br;q=0.2, zstd", prefer: []string{}, expected: []string{"zstd", "deflate", "gzip", "br"}, }, { name: "PreferOrder(): q-factor=0 filtered out", accept: "deflate;q=0.1, gzip;q=0.4, br;q=0.5, zstd;q=0", prefer: []string{"gzip"}, expected: []string{"br", "gzip", "deflate"}, }, { name: "PreferOrder(): q-factor=0 filtered out, no prefer", accept: "deflate;q=0.1, gzip;q=0.4, br;q=0.5, zstd;q=0", prefer: []string{}, expected: []string{"br", "gzip", "deflate"}, }, { name: "PreferOrder(): with invalid q-factor", accept: "br, deflate, gzip;q=2, zstd;q=0.1", prefer: []string{"zstd", "gzip"}, expected: []string{"gzip", "br", "deflate", "zstd"}, }, { name: "PreferOrder(): with invalid q-factor, no prefer", accept: "br, deflate, gzip;q=2, zstd;q=0.1", prefer: []string{}, expected: []string{"br", "deflate", "gzip", "zstd"}, }, } enc := new(Encode) r, _ := http.NewRequest("", "", nil) for _, test := range testCases { t.Run(test.name, func(t *testing.T) { if test.accept == "" { r.Header.Del("Accept-Encoding") } else { r.Header.Set("Accept-Encoding", test.accept) } enc.Prefer = test.prefer result := AcceptedEncodings(r, enc.Prefer) if !slices.Equal(result, test.expected) { t.Errorf("AcceptedEncodings() actual: %s expected: %s", result, test.expected) } }) } } func TestValidate(t *testing.T) { type testCase struct { name string prefer []string wantErr bool } var err error var testCases []testCase enc := new(Encode) enc.writerPools = map[string]*sync.Pool{ "zstd": nil, "gzip": nil, "br": nil, } testCases = []testCase{ { name: "ValidatePrefer (zstd, gzip & br enabled): valid order with all encoder", prefer: []string{"zstd", "br", "gzip"}, wantErr: false, }, { name: "ValidatePrefer (zstd, gzip & br enabled): valid order with 2 out of 3 encoders", prefer: []string{"br", "gzip"}, wantErr: false, }, { name: "ValidatePrefer (zstd, gzip & br enabled): valid order with 1 out of 3 encoders", prefer: []string{"gzip"}, wantErr: false, }, { name: "ValidatePrefer (zstd, gzip & br enabled): 1 duplicated (once) encoder", prefer: []string{"gzip", "zstd", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd, gzip & br enabled): 1 not enabled encoder in prefer list", prefer: []string{"br", "zstd", "gzip", "deflate"}, wantErr: true, }, { name: "ValidatePrefer (zstd, gzip & br enabled): no prefer list", prefer: []string{}, wantErr: false, }, } for _, test := range testCases { t.Run(test.name, func(t *testing.T) { enc.Prefer = test.prefer err = enc.Validate() if (err != nil) != test.wantErr { t.Errorf("Validate() error = %v, wantErr = %v", err, test.wantErr) } }) } enc.writerPools = map[string]*sync.Pool{ "zstd": nil, "gzip": nil, } testCases = []testCase{ { name: "ValidatePrefer (zstd & gzip enabled): 1 not enabled encoder in prefer list", prefer: []string{"zstd", "br", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 2 not enabled encoder in prefer list", prefer: []string{"br", "zstd", "gzip", "deflate"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): only not enabled encoder in prefer list", prefer: []string{"deflate", "br", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 1 duplicated (once) encoder in prefer list", prefer: []string{"gzip", "zstd", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 1 duplicated (twice) encoder in prefer list", prefer: []string{"gzip", "zstd", "gzip", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 1 duplicated encoder in prefer list", prefer: []string{"zstd", "zstd", "gzip", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 1 duplicated not enabled encoder in prefer list", prefer: []string{"br", "br", "gzip"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): 2 duplicated not enabled encoder in prefer list", prefer: []string{"br", "deflate", "br", "deflate"}, wantErr: true, }, { name: "ValidatePrefer (zstd & gzip enabled): valid order zstd first", prefer: []string{"zstd", "gzip"}, wantErr: false, }, { name: "ValidatePrefer (zstd & gzip enabled): valid order gzip first", prefer: []string{"gzip", "zstd"}, wantErr: false, }, } for _, test := range testCases { t.Run(test.name, func(t *testing.T) { enc.Prefer = test.prefer err = enc.Validate() if (err != nil) != test.wantErr { t.Errorf("Validate() error = %v, wantErr = %v", err, test.wantErr) } }) } } func TestIsEncodeAllowed(t *testing.T) { testCases := []struct { name string headers http.Header expected bool }{ { name: "Without any headers", headers: http.Header{}, expected: true, }, { name: "Without Cache-Control HTTP header", headers: http.Header{ "Accept-Encoding": {"gzip"}, }, expected: true, }, { name: "Cache-Control HTTP header ending with no-transform directive", headers: http.Header{ "Accept-Encoding": {"gzip"}, "Cache-Control": {"no-cache; no-transform"}, }, expected: false, }, { name: "With Cache-Control HTTP header no-transform as Cache-Extension value", headers: http.Header{ "Accept-Encoding": {"gzip"}, "Cache-Control": {`no-store; no-cache; community="no-transform"`}, }, expected: false, }, } for _, test := range testCases { t.Run(test.name, func(t *testing.T) { if result := isEncodeAllowed(test.headers); result != test.expected { t.Errorf("The headers given to the isEncodeAllowed should return %t, %t given.", result, test.expected) } }) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/encode/brotli/brotli_precompressed.go
modules/caddyhttp/encode/brotli/brotli_precompressed.go
package caddybrotli import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(BrotliPrecompressed{}) } // BrotliPrecompressed provides the file extension for files precompressed with brotli encoding. type BrotliPrecompressed struct{} // CaddyModule returns the Caddy module information. func (BrotliPrecompressed) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.precompressed.br", New: func() caddy.Module { return new(BrotliPrecompressed) }, } } // AcceptEncoding returns the name of the encoding as // used in the Accept-Encoding request headers. func (BrotliPrecompressed) AcceptEncoding() string { return "br" } // Suffix returns the filename suffix of precompressed files. func (BrotliPrecompressed) Suffix() string { return ".br" } // Interface guards var _ encode.Precompressed = (*BrotliPrecompressed)(nil)
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/encode/zstd/zstd.go
modules/caddyhttp/encode/zstd/zstd.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package caddyzstd import ( "fmt" "github.com/klauspost/compress/zstd" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(Zstd{}) } // Zstd can create Zstandard encoders. type Zstd struct { // The compression level. Accepted values: fastest, better, best, default. Level string `json:"level,omitempty"` // Compression level refer to type constants value from zstd.SpeedFastest to zstd.SpeedBestCompression level zstd.EncoderLevel } // CaddyModule returns the Caddy module information. func (Zstd) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.encoders.zstd", New: func() caddy.Module { return new(Zstd) }, } } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. func (z *Zstd) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume option name if !d.NextArg() { return nil } levelStr := d.Val() if ok, _ := zstd.EncoderLevelFromString(levelStr); !ok { return d.Errf("unexpected compression level, use one of '%s', '%s', '%s', '%s'", zstd.SpeedFastest, zstd.SpeedBetterCompression, zstd.SpeedBestCompression, zstd.SpeedDefault, ) } z.Level = levelStr return nil } // Provision provisions z's configuration. func (z *Zstd) Provision(ctx caddy.Context) error { if z.Level == "" { z.Level = zstd.SpeedDefault.String() } var ok bool if ok, z.level = zstd.EncoderLevelFromString(z.Level); !ok { return fmt.Errorf("unexpected compression level, use one of '%s', '%s', '%s', '%s'", zstd.SpeedFastest, zstd.SpeedDefault, zstd.SpeedBetterCompression, zstd.SpeedBestCompression, ) } return nil } // AcceptEncoding returns the name of the encoding as // used in the Accept-Encoding request headers. func (Zstd) AcceptEncoding() string { return "zstd" } // NewEncoder returns a new Zstandard writer. func (z Zstd) NewEncoder() encode.Encoder { // The default of 8MB for the window is // too large for many clients, so we limit // it to 128K to lighten their load. writer, _ := zstd.NewWriter( nil, zstd.WithWindowSize(128<<10), zstd.WithEncoderConcurrency(1), zstd.WithZeroFrames(true), zstd.WithEncoderLevel(z.level), ) return writer } // Interface guards var ( _ encode.Encoding = (*Zstd)(nil) _ caddyfile.Unmarshaler = (*Zstd)(nil) _ caddy.Provisioner = (*Zstd)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/encode/zstd/zstd_precompressed.go
modules/caddyhttp/encode/zstd/zstd_precompressed.go
package caddyzstd import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(ZstdPrecompressed{}) } // ZstdPrecompressed provides the file extension for files precompressed with zstandard encoding. type ZstdPrecompressed struct { Zstd } // CaddyModule returns the Caddy module information. func (ZstdPrecompressed) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.precompressed.zstd", New: func() caddy.Module { return new(ZstdPrecompressed) }, } } // Suffix returns the filename suffix of precompressed files. func (ZstdPrecompressed) Suffix() string { return ".zst" } var _ encode.Precompressed = (*ZstdPrecompressed)(nil)
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/encode/gzip/gzip.go
modules/caddyhttp/encode/gzip/gzip.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package caddygzip import ( "fmt" "strconv" "github.com/klauspost/compress/gzip" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(Gzip{}) } // Gzip can create gzip encoders. type Gzip struct { Level int `json:"level,omitempty"` } // CaddyModule returns the Caddy module information. func (Gzip) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.encoders.gzip", New: func() caddy.Module { return new(Gzip) }, } } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. func (g *Gzip) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume option name if !d.NextArg() { return nil } levelStr := d.Val() level, err := strconv.Atoi(levelStr) if err != nil { return err } g.Level = level return nil } // Provision provisions g's configuration. func (g *Gzip) Provision(ctx caddy.Context) error { if g.Level == 0 { g.Level = defaultGzipLevel } return nil } // Validate validates g's configuration. func (g Gzip) Validate() error { if g.Level < gzip.StatelessCompression { return fmt.Errorf("quality too low; must be >= %d", gzip.StatelessCompression) } if g.Level > gzip.BestCompression { return fmt.Errorf("quality too high; must be <= %d", gzip.BestCompression) } return nil } // AcceptEncoding returns the name of the encoding as // used in the Accept-Encoding request headers. func (Gzip) AcceptEncoding() string { return "gzip" } // NewEncoder returns a new gzip writer. func (g Gzip) NewEncoder() encode.Encoder { writer, _ := gzip.NewWriterLevel(nil, g.Level) return writer } // Informed from http://blog.klauspost.com/gzip-performance-for-go-webservers/ var defaultGzipLevel = 5 // Interface guards var ( _ encode.Encoding = (*Gzip)(nil) _ caddy.Provisioner = (*Gzip)(nil) _ caddy.Validator = (*Gzip)(nil) _ caddyfile.Unmarshaler = (*Gzip)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyhttp/encode/gzip/gzip_precompressed.go
modules/caddyhttp/encode/gzip/gzip_precompressed.go
package caddygzip import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" ) func init() { caddy.RegisterModule(GzipPrecompressed{}) } // GzipPrecompressed provides the file extension for files precompressed with gzip encoding. type GzipPrecompressed struct { Gzip } // CaddyModule returns the Caddy module information. func (GzipPrecompressed) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.precompressed.gzip", New: func() caddy.Module { return new(GzipPrecompressed) }, } } // Suffix returns the filename suffix of precompressed files. func (GzipPrecompressed) Suffix() string { return ".gz" } var _ encode.Precompressed = (*GzipPrecompressed)(nil)
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/pki.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/crypto_test.go
modules/caddypki/crypto_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 caddypki import ( "crypto/rand" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "os" "path/filepath" "testing" "time" "go.step.sm/crypto/keyutil" "go.step.sm/crypto/pemutil" ) func TestKeyPair_Load(t *testing.T) { rootSigner, err := keyutil.GenerateDefaultSigner() if err != nil { t.Fatalf("Failed creating signer: %v", err) } tmpl := &x509.Certificate{ Subject: pkix.Name{CommonName: "test-root"}, IsCA: true, MaxPathLen: 3, } rootBytes, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, rootSigner.Public(), rootSigner) if err != nil { t.Fatalf("Creating root certificate failed: %v", err) } root, err := x509.ParseCertificate(rootBytes) if err != nil { t.Fatalf("Parsing root certificate failed: %v", err) } intermediateSigner, err := keyutil.GenerateDefaultSigner() if err != nil { t.Fatalf("Creating intermedaite signer failed: %v", err) } intermediateBytes, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{ Subject: pkix.Name{CommonName: "test-first-intermediate"}, IsCA: true, MaxPathLen: 2, NotAfter: time.Now().Add(time.Hour), }, root, intermediateSigner.Public(), rootSigner) if err != nil { t.Fatalf("Creating intermediate certificate failed: %v", err) } intermediate, err := x509.ParseCertificate(intermediateBytes) if err != nil { t.Fatalf("Parsing intermediate certificate failed: %v", err) } var chainContents []byte chain := []*x509.Certificate{intermediate, root} for _, cert := range chain { b, err := pemutil.Serialize(cert) if err != nil { t.Fatalf("Failed serializing intermediate certificate: %v", err) } chainContents = append(chainContents, pem.EncodeToMemory(b)...) } dir := t.TempDir() rootCertFile := filepath.Join(dir, "root.pem") if _, err = pemutil.Serialize(root, pemutil.WithFilename(rootCertFile)); err != nil { t.Fatalf("Failed serializing root certificate: %v", err) } rootKeyFile := filepath.Join(dir, "root.key") if _, err = pemutil.Serialize(rootSigner, pemutil.WithFilename(rootKeyFile)); err != nil { t.Fatalf("Failed serializing root key: %v", err) } intermediateCertFile := filepath.Join(dir, "intermediate.pem") if _, err = pemutil.Serialize(intermediate, pemutil.WithFilename(intermediateCertFile)); err != nil { t.Fatalf("Failed serializing intermediate certificate: %v", err) } intermediateKeyFile := filepath.Join(dir, "intermediate.key") if _, err = pemutil.Serialize(intermediateSigner, pemutil.WithFilename(intermediateKeyFile)); err != nil { t.Fatalf("Failed serializing intermediate key: %v", err) } chainFile := filepath.Join(dir, "chain.pem") if err := os.WriteFile(chainFile, chainContents, 0644); err != nil { t.Fatalf("Failed writing intermediate chain: %v", err) } t.Run("ok/single-certificate-without-signer", func(t *testing.T) { kp := KeyPair{ Certificate: rootCertFile, } chain, signer, err := kp.Load() if err != nil { t.Fatalf("Failed loading KeyPair: %v", err) } if len(chain) != 1 { t.Errorf("Expected 1 certificate in chain; got %d", len(chain)) } if signer != nil { t.Error("Expected no signer to be returned") } }) t.Run("ok/single-certificate-with-signer", func(t *testing.T) { kp := KeyPair{ Certificate: rootCertFile, PrivateKey: rootKeyFile, } chain, signer, err := kp.Load() if err != nil { t.Fatalf("Failed loading KeyPair: %v", err) } if len(chain) != 1 { t.Errorf("Expected 1 certificate in chain; got %d", len(chain)) } if signer == nil { t.Error("Expected signer to be returned") } }) t.Run("ok/multiple-certificates-with-signer", func(t *testing.T) { kp := KeyPair{ Certificate: chainFile, PrivateKey: intermediateKeyFile, } chain, signer, err := kp.Load() if err != nil { t.Fatalf("Failed loading KeyPair: %v", err) } if len(chain) != 2 { t.Errorf("Expected 2 certificates in chain; got %d", len(chain)) } if signer == nil { t.Error("Expected signer to be returned") } }) t.Run("fail/non-matching-public-key", func(t *testing.T) { kp := KeyPair{ Certificate: intermediateCertFile, PrivateKey: rootKeyFile, } chain, signer, err := kp.Load() if err == nil { t.Error("Expected loading KeyPair to return an error") } if chain != nil { t.Error("Expected no chain to be returned") } if signer != nil { t.Error("Expected no signer to be returned") } }) } func Test_pemDecodeCertificate(t *testing.T) { signer, err := keyutil.GenerateDefaultSigner() if err != nil { t.Fatalf("Failed creating signer: %v", err) } tmpl := &x509.Certificate{ Subject: pkix.Name{CommonName: "test-cert"}, IsCA: true, MaxPathLen: 3, } derBytes, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, signer.Public(), signer) if err != nil { t.Fatalf("Creating root certificate failed: %v", err) } cert, err := x509.ParseCertificate(derBytes) if err != nil { t.Fatalf("Parsing root certificate failed: %v", err) } pemBlock, err := pemutil.Serialize(cert) if err != nil { t.Fatalf("Failed serializing certificate: %v", err) } pemData := pem.EncodeToMemory(pemBlock) t.Run("ok", func(t *testing.T) { cert, err := pemDecodeCertificate(pemData) if err != nil { t.Fatalf("Failed decoding PEM data: %v", err) } if cert == nil { t.Errorf("Expected a certificate in PEM data") } }) t.Run("fail/no-pem-data", func(t *testing.T) { cert, err := pemDecodeCertificate(nil) if err == nil { t.Fatalf("Expected pemDecodeCertificate to return an error") } if cert != nil { t.Errorf("Expected pemDecodeCertificate to return nil") } }) t.Run("fail/multiple", func(t *testing.T) { multiplePEMData := append(pemData, pemData...) cert, err := pemDecodeCertificate(multiplePEMData) if err == nil { t.Fatalf("Expected pemDecodeCertificate to return an error") } if cert != nil { t.Errorf("Expected pemDecodeCertificate to return nil") } }) t.Run("fail/no-pem-certificate", func(t *testing.T) { pkData := pem.EncodeToMemory(&pem.Block{ Type: "PRIVATE KEY", Bytes: []byte("some-bogus-private-key"), }) cert, err := pemDecodeCertificate(pkData) if err == nil { t.Fatalf("Expected pemDecodeCertificate to return an error") } if cert != nil { t.Errorf("Expected pemDecodeCertificate to return nil") } }) } func Test_pemDecodeCertificateChain(t *testing.T) { signer, err := keyutil.GenerateDefaultSigner() if err != nil { t.Fatalf("Failed creating signer: %v", err) } tmpl := &x509.Certificate{ Subject: pkix.Name{CommonName: "test-cert"}, IsCA: true, MaxPathLen: 3, } derBytes, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, signer.Public(), signer) if err != nil { t.Fatalf("Creating root certificate failed: %v", err) } cert, err := x509.ParseCertificate(derBytes) if err != nil { t.Fatalf("Parsing root certificate failed: %v", err) } pemBlock, err := pemutil.Serialize(cert) if err != nil { t.Fatalf("Failed serializing certificate: %v", err) } pemData := pem.EncodeToMemory(pemBlock) t.Run("ok/single", func(t *testing.T) { certs, err := pemDecodeCertificateChain(pemData) if err != nil { t.Fatalf("Failed decoding PEM data: %v", err) } if len(certs) != 1 { t.Errorf("Expected 1 certificate in PEM data; got %d", len(certs)) } }) t.Run("ok/multiple", func(t *testing.T) { multiplePEMData := append(pemData, pemData...) certs, err := pemDecodeCertificateChain(multiplePEMData) if err != nil { t.Fatalf("Failed decoding PEM data: %v", err) } if len(certs) != 2 { t.Errorf("Expected 2 certificates in PEM data; got %d", len(certs)) } }) t.Run("fail/no-pem-certificate", func(t *testing.T) { pkData := pem.EncodeToMemory(&pem.Block{ Type: "PRIVATE KEY", Bytes: []byte("some-bogus-private-key"), }) certs, err := pemDecodeCertificateChain(pkData) if err == nil { t.Fatalf("Expected pemDecodeCertificateChain to return an error") } if len(certs) != 0 { t.Errorf("Expected 0 certificates in PEM data; got %d", len(certs)) } }) t.Run("fail/no-der-certificate", func(t *testing.T) { certs, err := pemDecodeCertificateChain([]byte("invalid-der-data")) if err == nil { t.Fatalf("Expected pemDecodeCertificateChain to return an error") } if len(certs) != 0 { t.Errorf("Expected 0 certificates in PEM data; got %d", len(certs)) } }) }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/ca.go
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 *x509.Certificate interChain []*x509.Certificate interKey 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) } // load the certs and key that will be used for signing var rootCert *x509.Certificate var rootCertChain, interCertChain []*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 } rootCertChain, rootKey, err = ca.Root.Load() rootCert = rootCertChain[0] } else { ca.rootCertPath = "storage:" + ca.storageKeyRootCert() rootCert, rootKey, err = ca.loadOrGenRoot() } if err != nil { return err } if ca.Intermediate != nil { interCertChain, interKey, err = ca.Intermediate.Load() } else { actualRootLifetime := time.Until(rootCert.NotAfter) if time.Duration(ca.IntermediateLifetime) >= actualRootLifetime { return fmt.Errorf("intermediate certificate lifetime must be less than actual root certificate lifetime (%s)", actualRootLifetime) } interCertChain, interKey, err = ca.loadOrGenIntermediate(rootCert, rootKey) } if err != nil { return err } ca.mu.Lock() ca.root, ca.interChain, ca.interKey = rootCert, interCertChain, 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() (crypto.Signer, error) { _, rootKey, err := ca.loadOrGenRoot() return rootKey, err } // IntermediateCertificateChain returns the CA's intermediate // certificate chain. func (ca CA) IntermediateCertificateChain() []*x509.Certificate { ca.mu.RLock() defer ca.mu.RUnlock() return ca.interChain } // IntermediateKey returns the CA's intermediate private key. func (ca CA) IntermediateKey() crypto.Signer { 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 crypto.Signer 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) } 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) { issuerChain := ca.IntermediateCertificateChain() issuerCert := issuerChain[0] issuerKey := ca.IntermediateKey() 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 issuerChain, 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 { rootChain, rootSigner, err := ca.Root.Load() if err != nil { return nil, nil, err } return rootChain[0], rootSigner, nil } 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 = pemDecodeCertificate(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) (interCertChain []*x509.Certificate, interKey crypto.Signer, err error) { var interCert *x509.Certificate 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) } interCertChain = append(interCertChain, interCert) } if len(interCertChain) == 0 { interCertChain, err = pemDecodeCertificateChain(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 interCertChain, 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/certificates.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/crypto.go
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/ecdsa" "crypto/ed25519" "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "fmt" "os" "github.com/caddyserver/certmagic" "go.step.sm/crypto/pemutil" ) func pemDecodeCertificate(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 pemDecodeCertificateChain(pemDER []byte) ([]*x509.Certificate, error) { chain, err := pemutil.ParseCertificateBundle(pemDER) if err != nil { return nil, fmt.Errorf("failed parsing certificate chain: %w", err) } return chain, nil } 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 chain and (optional) private key from // the corresponding files, using the configured format. If a // private key is read, it will be verified to belong to the first // certificate in the chain. 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 } chain, err := pemDecodeCertificateChain(certData) if err != nil { return nil, nil, err } var key crypto.Signer if kp.PrivateKey != "" { keyData, err := os.ReadFile(kp.PrivateKey) if err != nil { return nil, nil, err } key, err = certmagic.PEMDecodePrivateKey(keyData) if err != nil { return nil, nil, err } if err := verifyKeysMatch(chain[0], key); err != nil { return nil, nil, err } } return chain, key, nil default: return nil, nil, fmt.Errorf("unsupported format: %s", kp.Format) } } // verifyKeysMatch verifies that the public key in the [x509.Certificate] matches // the public key of the [crypto.Signer]. func verifyKeysMatch(crt *x509.Certificate, signer crypto.Signer) error { switch pub := crt.PublicKey.(type) { case *rsa.PublicKey: pk, ok := signer.Public().(*rsa.PublicKey) if !ok { return fmt.Errorf("private key type %T does not match issuer public key type %T", signer.Public(), pub) } if !pub.Equal(pk) { return errors.New("private key does not match issuer public key") } case *ecdsa.PublicKey: pk, ok := signer.Public().(*ecdsa.PublicKey) if !ok { return fmt.Errorf("private key type %T does not match issuer public key type %T", signer.Public(), pub) } if !pub.Equal(pk) { return errors.New("private key does not match issuer public key") } case ed25519.PublicKey: pk, ok := signer.Public().(ed25519.PublicKey) if !ok { return fmt.Errorf("private key type %T does not match issuer public key type %T", signer.Public(), pub) } if !pub.Equal(pk) { return errors.New("private key does not match issuer public key") } default: return fmt.Errorf("unsupported key type: %T", pub) } return nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/maintain.go
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.interChain[0].NotAfter)), ) } } // only maintain the intermediate if it's not manually provided in the config if ca.Intermediate == nil { if needsRenewal(ca.interChain[0]) { log.Info("intermediate expires soon; renewing", zap.Duration("time_remaining", time.Until(ca.interChain[0].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.interChain, ca.interKey = []*x509.Certificate{interCert}, interKey log.Info("renewed intermediate", zap.Time("new_expiration", ca.interChain[0].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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/command.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/adminapi.go
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. // We intentionally ignore the error since it's not // fatal if the PKI app is not explicitly configured. pkiApp, err := ctx.AppIfConfigured("pki") if err == 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 root, inter, err } for _, interCert := range ca.IntermediateCertificateChain() { pemBytes, err := pemEncodeCert(interCert.Raw) if err != nil { return nil, nil, err } inter = append(inter, pemBytes...) } 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/acmeserver/policy.go
modules/caddypki/acmeserver/policy.go
package acmeserver import ( "github.com/smallstep/certificates/authority/policy" "github.com/smallstep/certificates/authority/provisioner" ) // Policy defines the criteria for the ACME server // of when to issue a certificate. Refer to the // [Certificate Issuance Policy](https://smallstep.com/docs/step-ca/policies/) // on Smallstep website for the evaluation criteria. type Policy struct { // If a rule set is configured to allow a certain type of name, // all other types of names are automatically denied. Allow *RuleSet `json:"allow,omitempty"` // If a rule set is configured to deny a certain type of name, // all other types of names are still allowed. Deny *RuleSet `json:"deny,omitempty"` // If set to true, the ACME server will allow issuing wildcard certificates. AllowWildcardNames bool `json:"allow_wildcard_names,omitempty"` } // RuleSet is the specific set of SAN criteria for a certificate // to be issued or denied. type RuleSet struct { // Domains is a list of DNS domains that are allowed to be issued. // It can be in the form of FQDN for specific domain name, or // a wildcard domain name format, e.g. *.example.com, to allow // sub-domains of a domain. Domains []string `json:"domains,omitempty"` // IP ranges in the form of CIDR notation or specific IP addresses // to be approved or denied for certificates. Non-CIDR IP addresses // are matched exactly. IPRanges []string `json:"ip_ranges,omitempty"` } // normalizeAllowRules returns `nil` if policy is nil, the `Allow` rule is `nil`, // or all rules within the `Allow` rule are empty. Otherwise, it returns the X509NameOptions // with the content of the `Allow` rule. func (p *Policy) normalizeAllowRules() *policy.X509NameOptions { if (p == nil) || (p.Allow == nil) || (len(p.Allow.Domains) == 0 && len(p.Allow.IPRanges) == 0) { return nil } return &policy.X509NameOptions{ DNSDomains: p.Allow.Domains, IPRanges: p.Allow.IPRanges, } } // normalizeDenyRules returns `nil` if policy is nil, the `Deny` rule is `nil`, // or all rules within the `Deny` rule are empty. Otherwise, it returns the X509NameOptions // with the content of the `Deny` rule. func (p *Policy) normalizeDenyRules() *policy.X509NameOptions { if (p == nil) || (p.Deny == nil) || (len(p.Deny.Domains) == 0 && len(p.Deny.IPRanges) == 0) { return nil } return &policy.X509NameOptions{ DNSDomains: p.Deny.Domains, IPRanges: p.Deny.IPRanges, } } // normalizeRules returns `nil` if policy is nil, the `Allow` and `Deny` rules are `nil`, func (p *Policy) normalizeRules() *provisioner.X509Options { if p == nil { return nil } allow := p.normalizeAllowRules() deny := p.normalizeDenyRules() if allow == nil && deny == nil && !p.AllowWildcardNames { return nil } return &provisioner.X509Options{ AllowedNames: allow, DeniedNames: deny, AllowWildcardNames: p.AllowWildcardNames, } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/acmeserver/policy_test.go
modules/caddypki/acmeserver/policy_test.go
package acmeserver import ( "reflect" "testing" "github.com/smallstep/certificates/authority/policy" "github.com/smallstep/certificates/authority/provisioner" ) func TestPolicyNormalizeAllowRules(t *testing.T) { type fields struct { Allow *RuleSet Deny *RuleSet AllowWildcardNames bool } tests := []struct { name string fields fields want *policy.X509NameOptions }{ { name: "providing no rules results in 'nil'", fields: fields{}, want: nil, }, { name: "providing 'nil' Allow rules results in 'nil', regardless of Deny rules", fields: fields{ Allow: nil, Deny: &RuleSet{}, AllowWildcardNames: true, }, want: nil, }, { name: "providing empty Allow rules results in 'nil', regardless of Deny rules", fields: fields{ Allow: &RuleSet{ Domains: []string{}, IPRanges: []string{}, }, }, want: nil, }, { name: "rules configured in Allow are returned in X509NameOptions", fields: fields{ Allow: &RuleSet{ Domains: []string{"example.com"}, IPRanges: []string{"127.0.0.1/32"}, }, }, want: &policy.X509NameOptions{ DNSDomains: []string{"example.com"}, IPRanges: []string{"127.0.0.1/32"}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { p := &Policy{ Allow: tt.fields.Allow, Deny: tt.fields.Deny, AllowWildcardNames: tt.fields.AllowWildcardNames, } if got := p.normalizeAllowRules(); !reflect.DeepEqual(got, tt.want) { t.Errorf("Policy.normalizeAllowRules() = %v, want %v", got, tt.want) } }) } } func TestPolicy_normalizeDenyRules(t *testing.T) { type fields struct { Allow *RuleSet Deny *RuleSet AllowWildcardNames bool } tests := []struct { name string fields fields want *policy.X509NameOptions }{ { name: "providing no rules results in 'nil'", fields: fields{}, want: nil, }, { name: "providing 'nil' Deny rules results in 'nil', regardless of Allow rules", fields: fields{ Deny: nil, Allow: &RuleSet{}, AllowWildcardNames: true, }, want: nil, }, { name: "providing empty Deny rules results in 'nil', regardless of Allow rules", fields: fields{ Deny: &RuleSet{ Domains: []string{}, IPRanges: []string{}, }, }, want: nil, }, { name: "rules configured in Deny are returned in X509NameOptions", fields: fields{ Deny: &RuleSet{ Domains: []string{"example.com"}, IPRanges: []string{"127.0.0.1/32"}, }, }, want: &policy.X509NameOptions{ DNSDomains: []string{"example.com"}, IPRanges: []string{"127.0.0.1/32"}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { p := &Policy{ Allow: tt.fields.Allow, Deny: tt.fields.Deny, AllowWildcardNames: tt.fields.AllowWildcardNames, } if got := p.normalizeDenyRules(); !reflect.DeepEqual(got, tt.want) { t.Errorf("Policy.normalizeDenyRules() = %v, want %v", got, tt.want) } }) } } func TestPolicy_normalizeRules(t *testing.T) { tests := []struct { name string policy *Policy want *provisioner.X509Options }{ { name: "'nil' policy results in 'nil' options", policy: nil, want: nil, }, { name: "'nil' Allow/Deny rules and disallowing wildcard names result in 'nil' X509Options", policy: &Policy{ Allow: nil, Deny: nil, AllowWildcardNames: false, }, want: nil, }, { name: "'nil' Allow/Deny rules and allowing wildcard names result in 'nil' Allow/Deny rules in X509Options but allowing wildcard names in X509Options", policy: &Policy{ Allow: nil, Deny: nil, AllowWildcardNames: true, }, want: &provisioner.X509Options{ AllowWildcardNames: true, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := tt.policy.normalizeRules(); !reflect.DeepEqual(got, tt.want) { t.Errorf("Policy.normalizeRules() = %v, want %v", got, tt.want) } }) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/acmeserver/acmeserver.go
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/v5" "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" "go.uber.org/zap/zapcore" "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"` // Specify the set of enabled ACME challenges. An empty or absent value // means all challenges are enabled. Accepted values are: // "http-01", "dns-01", "tls-alpn-01" Challenges ACMEChallenges `json:"challenges,omitempty" ` // The policy to use for issuing certificates Policy *Policy `json:"policy,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) } if len(ash.Challenges) > 0 { if err := ash.Challenges.validate(); err != nil { return err } } // 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, Challenges: ash.Challenges.toSmallstepType(), Options: &provisioner.Options{ X509: ash.Policy.normalizeRules(), }, 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 { if c := ash.logger.Check(zapcore.DebugLevel, "unloading unused CA database"); c != nil { c.Write(zap.String("db_key", key)) } } if err != nil { if c := ash.logger.Check(zapcore.ErrorLevel, "closing CA database"); c != nil { c.Write(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 { if c := ash.logger.Check(zapcore.DebugLevel, "loaded preexisting CA database"); c != nil { c.Write(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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/acmeserver/challenges.go
modules/caddypki/acmeserver/challenges.go
package acmeserver import ( "encoding/json" "fmt" "strings" "github.com/smallstep/certificates/authority/provisioner" ) // ACMEChallenge is an opaque string that represents supported ACME challenges. type ACMEChallenge string const ( HTTP_01 ACMEChallenge = "http-01" DNS_01 ACMEChallenge = "dns-01" TLS_ALPN_01 ACMEChallenge = "tls-alpn-01" ) // validate checks if the given challenge is supported. func (c ACMEChallenge) validate() error { switch c { case HTTP_01, DNS_01, TLS_ALPN_01: return nil default: return fmt.Errorf("acme challenge %q is not supported", c) } } // The unmarshaller first marshals the value into a string. Then it // trims any space around it and lowercase it for normaliztion. The // method does not and should not validate the value within accepted enums. func (c *ACMEChallenge) UnmarshalJSON(b []byte) error { var s string if err := json.Unmarshal(b, &s); err != nil { return err } *c = ACMEChallenge(strings.ToLower(strings.TrimSpace(s))) return nil } // String returns a string representation of the challenge. func (c ACMEChallenge) String() string { return strings.ToLower(string(c)) } // ACMEChallenges is a list of ACME challenges. type ACMEChallenges []ACMEChallenge // validate checks if the given challenges are supported. func (c ACMEChallenges) validate() error { for _, ch := range c { if err := ch.validate(); err != nil { return err } } return nil } func (c ACMEChallenges) toSmallstepType() []provisioner.ACMEChallenge { if len(c) == 0 { return nil } ac := make([]provisioner.ACMEChallenge, len(c)) for i, ch := range c { ac[i] = provisioner.ACMEChallenge(ch) } return ac } func stringToChallenges(chs []string) ACMEChallenges { challenges := make(ACMEChallenges, len(chs)) for i, ch := range chs { challenges[i] = ACMEChallenge(ch) } return challenges }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddypki/acmeserver/caddyfile.go
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 ( "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...> // challenges <challenges...> // allow_wildcard_names // allow { // domains <domains...> // ip_ranges <addresses...> // } // deny { // domains <domains...> // ip_ranges <addresses...> // } // sign_with_root // } func parseACMEServer(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) { h.Next() // consume directive name matcherSet, err := h.ExtractMatcherSet() if err != nil { return nil, err } h.Next() // consume the directive name again (matcher parsing resets) // no inline args allowed if h.NextArg() { return nil, h.ArgErr() } var acmeServer Handler var ca *caddypki.CA 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 } 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") } case "challenges": acmeServer.Challenges = append(acmeServer.Challenges, stringToChallenges(h.RemainingArgs())...) case "allow_wildcard_names": if acmeServer.Policy == nil { acmeServer.Policy = &Policy{} } acmeServer.Policy.AllowWildcardNames = true case "allow": r := &RuleSet{} for nesting := h.Nesting(); h.NextBlock(nesting); { if h.CountRemainingArgs() == 0 { return nil, h.ArgErr() // TODO: } switch h.Val() { case "domains": r.Domains = append(r.Domains, h.RemainingArgs()...) case "ip_ranges": r.IPRanges = append(r.IPRanges, h.RemainingArgs()...) default: return nil, h.Errf("unrecognized 'allow' subdirective: %s", h.Val()) } } if acmeServer.Policy == nil { acmeServer.Policy = &Policy{} } acmeServer.Policy.Allow = r case "deny": r := &RuleSet{} for nesting := h.Nesting(); h.NextBlock(nesting); { if h.CountRemainingArgs() == 0 { return nil, h.ArgErr() // TODO: } switch h.Val() { case "domains": r.Domains = append(r.Domains, h.RemainingArgs()...) case "ip_ranges": r.IPRanges = append(r.IPRanges, h.RemainingArgs()...) default: return nil, h.Errf("unrecognized 'deny' subdirective: %s", h.Val()) } } if acmeServer.Policy == nil { acmeServer.Policy = &Policy{} } acmeServer.Policy.Deny = r case "sign_with_root": if h.NextArg() { return nil, h.ArgErr() } acmeServer.SignWithRoot = true default: return nil, h.Errf("unrecognized ACME server directive: %s", h.Val()) } } configVals := h.NewRoute(matcherSet, acmeServer) if ca == nil { return configVals, nil } return append(configVals, httpcaddyfile.ConfigValue{ Class: "pki.ca", Value: ca, }), nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyfs/filesystem.go
modules/caddyfs/filesystem.go
package caddyfs import ( "encoding/json" "fmt" "io/fs" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" ) func init() { caddy.RegisterModule(Filesystems{}) httpcaddyfile.RegisterGlobalOption("filesystem", parseFilesystems) } type moduleEntry struct { Key string `json:"name,omitempty"` FileSystemRaw json.RawMessage `json:"file_system,omitempty" caddy:"namespace=caddy.fs inline_key=backend"` fileSystem fs.FS } // Filesystems loads caddy.fs modules into the global filesystem map type Filesystems struct { Filesystems []*moduleEntry `json:"filesystems"` defers []func() } func parseFilesystems(d *caddyfile.Dispenser, existingVal any) (any, error) { p := &Filesystems{} current, ok := existingVal.(*Filesystems) if ok { p = current } x := &moduleEntry{} err := x.UnmarshalCaddyfile(d) if err != nil { return nil, err } p.Filesystems = append(p.Filesystems, x) return p, nil } // CaddyModule returns the Caddy module information. func (Filesystems) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.filesystems", New: func() caddy.Module { return new(Filesystems) }, } } func (xs *Filesystems) Start() error { return nil } func (xs *Filesystems) Stop() error { return nil } func (xs *Filesystems) Provision(ctx caddy.Context) error { // load the filesystem module for _, f := range xs.Filesystems { if len(f.FileSystemRaw) > 0 { mod, err := ctx.LoadModule(f, "FileSystemRaw") if err != nil { return fmt.Errorf("loading file system module: %v", err) } f.fileSystem = mod.(fs.FS) } // register that module ctx.Logger().Debug("registering fs", zap.String("fs", f.Key)) ctx.FileSystems().Register(f.Key, f.fileSystem) // remember to unregister the module when we are done xs.defers = append(xs.defers, func() { ctx.Logger().Debug("unregistering fs", zap.String("fs", f.Key)) ctx.FileSystems().Unregister(f.Key) }) } return nil } func (f *Filesystems) Cleanup() error { for _, v := range f.defers { v() } return nil } func (f *moduleEntry) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { // key required for now if !d.Args(&f.Key) { return d.ArgErr() } // get the module json if !d.NextArg() { return d.ArgErr() } name := d.Val() modID := "caddy.fs." + name unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } fsys, ok := unm.(fs.FS) if !ok { return d.Errf("module %s (%T) is not a supported file system implementation (requires fs.FS)", modID, unm) } f.FileSystemRaw = caddyconfig.JSONModuleObject(fsys, "backend", name, nil) } return nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/standard/imports.go
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/caddyfs" _ "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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/internalissuer.go
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 // configured 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 { chain := iss.ca.IntermediateCertificateChain() issuerCert = chain[0] } // 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.SignWithContext(ctx, 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 { d.Next() // consume issuer name 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 default: return d.Errf("unrecognized subdirective '%s'", d.Val()) } } 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/matchers_test.go
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 TestServerNameREMatcher(t *testing.T) { for i, tc := range []struct { pattern string input string expect bool }{ { pattern: "^example\\.(com|net)$", input: "example.com", expect: true, }, { pattern: "^example\\.(com|net)$", input: "foo.com", expect: false, }, { pattern: "^example\\.(com|net)$", input: "", expect: false, }, { pattern: "", input: "", expect: true, }, { pattern: "^example\\.(com|net)$", input: "foo.example.com", expect: false, }, } { chi := &tls.ClientHelloInfo{ServerName: tc.input} mre := MatchServerNameRE{MatchRegexp{Pattern: tc.pattern}} ctx, _ := caddy.NewContext(caddy.Context{Context: context.Background()}) if mre.Provision(ctx) != nil { t.Errorf("Test %d: Failed to provision a regexp matcher (pattern=%v)", i, tc.pattern) } actual := mre.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.pattern) } } } 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) } } } func TestLocalIPMatcher(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() for i, tc := range []struct { ranges []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, }, { input: "127.0.0.1:12345", expect: true, }, { ranges: []string{"127.0.0.1"}, input: "127.0.0.1:12345", expect: true, }, { ranges: []string{"127.0.0.2"}, input: "127.0.0.3:12345", expect: false, }, { ranges: []string{"127.0.0.2"}, input: "127.0.0.2", expect: true, }, { ranges: []string{"127.0.0.2"}, input: "127.0.0.300", expect: false, }, } { matcher := MatchLocalIP{Ranges: tc.ranges} 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)", i, tc.expect, actual, tc.input, tc.ranges) } } } type testConn struct { *net.TCPConn addr testAddr } func (tc testConn) RemoteAddr() net.Addr { return tc.addr } func (tc testConn) LocalAddr() net.Addr { return tc.addr } type testAddr string func (testAddr) Network() string { return "tcp" } func (ta testAddr) String() string { return string(ta) }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/leaffileloader_test.go
modules/caddytls/leaffileloader_test.go
package caddytls import ( "context" "encoding/pem" "os" "strings" "testing" "github.com/caddyserver/caddy/v2" ) func TestLeafFileLoader(t *testing.T) { fl := LeafFileLoader{Files: []string{"../../caddytest/leafcert.pem"}} fl.Provision(caddy.Context{Context: context.Background()}) out, err := fl.LoadLeafCertificates() if err != nil { t.Errorf("Leaf certs file loading test failed: %v", err) } if len(out) != 1 { t.Errorf("Error loading leaf cert in memory struct") return } pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: out[0].Raw}) pemFileBytes, err := os.ReadFile("../../caddytest/leafcert.pem") if err != nil { t.Errorf("Unable to read the example certificate from the file") } // Remove /r because windows. pemFileString := strings.ReplaceAll(string(pemFileBytes), "\r\n", "\n") if string(pemBytes) != pemFileString { t.Errorf("Leaf Certificate File Loader: Failed to load the correct certificate") } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/leafstorageloader.go
modules/caddytls/leafstorageloader.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/x509" "encoding/json" "encoding/pem" "fmt" "github.com/caddyserver/certmagic" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(LeafStorageLoader{}) } // LeafStorageLoader loads leaf certificates from the // globally configured storage module. type LeafStorageLoader struct { // A list of certificate file names to be loaded from storage. Certificates []string `json:"certificates,omitempty"` // The storage module where the trusted leaf certificates are stored. Absent // explicit storage implies the use of Caddy default storage. StorageRaw json.RawMessage `json:"storage,omitempty" caddy:"namespace=caddy.storage inline_key=module"` // Reference to the globally configured storage module. storage certmagic.Storage ctx caddy.Context } // CaddyModule returns the Caddy module information. func (LeafStorageLoader) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.leaf_cert_loader.storage", New: func() caddy.Module { return new(LeafStorageLoader) }, } } // Provision loads the storage module for sl. func (sl *LeafStorageLoader) Provision(ctx caddy.Context) error { if sl.StorageRaw != nil { val, err := ctx.LoadModule(sl, "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) } sl.storage = cmStorage } if sl.storage == nil { sl.storage = ctx.Storage() } sl.ctx = ctx repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { repl = caddy.NewReplacer() } for k, path := range sl.Certificates { sl.Certificates[k] = repl.ReplaceKnown(path, "") } return nil } // LoadLeafCertificates returns the certificates to be loaded by sl. func (sl LeafStorageLoader) LoadLeafCertificates() ([]*x509.Certificate, error) { certificates := make([]*x509.Certificate, 0, len(sl.Certificates)) for _, path := range sl.Certificates { certData, err := sl.storage.Load(sl.ctx, path) if err != nil { return nil, err } ders, err := convertPEMToDER(certData) if err != nil { return nil, err } certs, err := x509.ParseCertificates(ders) if err != nil { return nil, err } certificates = append(certificates, certs...) } return certificates, nil } func convertPEMToDER(pemData []byte) ([]byte, error) { var ders []byte // while block is not nil, we have more certificates in the file for block, rest := pem.Decode(pemData); block != nil; block, rest = pem.Decode(rest) { if block.Type != "CERTIFICATE" { return nil, fmt.Errorf("no CERTIFICATE pem block found in the given pem data") } ders = append( ders, block.Bytes..., ) } // if we decoded nothing, return an error if len(ders) == 0 { return nil, fmt.Errorf("no CERTIFICATE pem block found in the given pem data") } return ders, nil } // Interface guard var ( _ LeafCertificateLoader = (*LeafStorageLoader)(nil) _ caddy.Provisioner = (*LeafStorageLoader)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/capools.go
modules/caddytls/capools.go
package caddytls import ( "crypto/tls" "crypto/x509" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "reflect" "github.com/caddyserver/certmagic" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddypki" ) func init() { caddy.RegisterModule(InlineCAPool{}) caddy.RegisterModule(FileCAPool{}) caddy.RegisterModule(PKIRootCAPool{}) caddy.RegisterModule(PKIIntermediateCAPool{}) caddy.RegisterModule(StoragePool{}) caddy.RegisterModule(HTTPCertPool{}) } // The interface to be implemented by all guest modules part of // the namespace 'tls.ca_pool.source.' type CA interface { CertPool() *x509.CertPool } // InlineCAPool is a certificate authority pool provider coming from // a DER-encoded certificates in the config type InlineCAPool 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"` pool *x509.CertPool } // CaddyModule implements caddy.Module. func (icp InlineCAPool) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.ca_pool.source.inline", New: func() caddy.Module { return new(InlineCAPool) }, } } // Provision implements caddy.Provisioner. func (icp *InlineCAPool) Provision(ctx caddy.Context) error { caPool := x509.NewCertPool() for i, clientCAString := range icp.TrustedCACerts { clientCA, err := decodeBase64DERCert(clientCAString) if err != nil { return fmt.Errorf("parsing certificate at index %d: %v", i, err) } caPool.AddCert(clientCA) } icp.pool = caPool return nil } // Syntax: // // trust_pool inline { // trust_der <base64_der_cert>... // } // // The 'trust_der' directive can be specified multiple times. func (icp *InlineCAPool) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume module name if d.CountRemainingArgs() > 0 { return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "trust_der": icp.TrustedCACerts = append(icp.TrustedCACerts, d.RemainingArgs()...) default: return d.Errf("unrecognized directive: %s", d.Val()) } } if len(icp.TrustedCACerts) == 0 { return d.Err("no certificates specified") } return nil } // CertPool implements CA. func (icp InlineCAPool) CertPool() *x509.CertPool { return icp.pool } // FileCAPool generates trusted root certificates pool from the designated DER and PEM file type FileCAPool struct { // 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:"pem_files,omitempty"` pool *x509.CertPool } // CaddyModule implements caddy.Module. func (FileCAPool) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.ca_pool.source.file", New: func() caddy.Module { return new(FileCAPool) }, } } // Loads and decodes the DER and pem files to generate the certificate pool func (f *FileCAPool) Provision(ctx caddy.Context) error { caPool := x509.NewCertPool() for _, pemFile := range f.TrustedCACertPEMFiles { pemContents, err := os.ReadFile(pemFile) if err != nil { return fmt.Errorf("reading %s: %v", pemFile, err) } caPool.AppendCertsFromPEM(pemContents) } f.pool = caPool return nil } // Syntax: // // trust_pool file [<pem_file>...] { // pem_file <pem_file>... // } // // The 'pem_file' directive can be specified multiple times. func (fcap *FileCAPool) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume module name fcap.TrustedCACertPEMFiles = append(fcap.TrustedCACertPEMFiles, d.RemainingArgs()...) for d.NextBlock(0) { switch d.Val() { case "pem_file": fcap.TrustedCACertPEMFiles = append(fcap.TrustedCACertPEMFiles, d.RemainingArgs()...) default: return d.Errf("unrecognized directive: %s", d.Val()) } } if len(fcap.TrustedCACertPEMFiles) == 0 { return d.Err("no certificates specified") } return nil } func (f FileCAPool) CertPool() *x509.CertPool { return f.pool } // PKIRootCAPool extracts the trusted root certificates from Caddy's native 'pki' app type PKIRootCAPool struct { // List of the Authority names that are configured in the `pki` app whose root certificates are trusted Authority []string `json:"authority,omitempty"` ca []*caddypki.CA pool *x509.CertPool } // CaddyModule implements caddy.Module. func (PKIRootCAPool) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.ca_pool.source.pki_root", New: func() caddy.Module { return new(PKIRootCAPool) }, } } // Loads the PKI app and load the root certificates into the certificate pool func (p *PKIRootCAPool) Provision(ctx caddy.Context) error { pkiApp, err := ctx.AppIfConfigured("pki") if err != nil { return fmt.Errorf("pki_root CA pool requires that a PKI app is configured: %v", err) } pki := pkiApp.(*caddypki.PKI) for _, caID := range p.Authority { c, err := pki.GetCA(ctx, caID) if err != nil || c == nil { return fmt.Errorf("getting CA %s: %v", caID, err) } p.ca = append(p.ca, c) } caPool := x509.NewCertPool() for _, ca := range p.ca { caPool.AddCert(ca.RootCertificate()) } p.pool = caPool return nil } // Syntax: // // trust_pool pki_root [<ca_name>...] { // authority <ca_name>... // } // // The 'authority' directive can be specified multiple times. func (pkir *PKIRootCAPool) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume module name pkir.Authority = append(pkir.Authority, d.RemainingArgs()...) for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "authority": pkir.Authority = append(pkir.Authority, d.RemainingArgs()...) default: return d.Errf("unrecognized directive: %s", d.Val()) } } if len(pkir.Authority) == 0 { return d.Err("no authorities specified") } return nil } // return the certificate pool generated with root certificates from the PKI app func (p PKIRootCAPool) CertPool() *x509.CertPool { return p.pool } // PKIIntermediateCAPool extracts the trusted intermediate certificates from Caddy's native 'pki' app type PKIIntermediateCAPool struct { // List of the Authority names that are configured in the `pki` app whose intermediate certificates are trusted Authority []string `json:"authority,omitempty"` ca []*caddypki.CA pool *x509.CertPool } // CaddyModule implements caddy.Module. func (PKIIntermediateCAPool) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.ca_pool.source.pki_intermediate", New: func() caddy.Module { return new(PKIIntermediateCAPool) }, } } // Loads the PKI app and loads the intermediate certificates into the certificate pool func (p *PKIIntermediateCAPool) Provision(ctx caddy.Context) error { pkiApp, err := ctx.AppIfConfigured("pki") if err != nil { return fmt.Errorf("pki_intermediate CA pool requires that a PKI app is configured: %v", err) } pki := pkiApp.(*caddypki.PKI) for _, caID := range p.Authority { c, err := pki.GetCA(ctx, caID) if err != nil || c == nil { return fmt.Errorf("getting CA %s: %v", caID, err) } p.ca = append(p.ca, c) } caPool := x509.NewCertPool() for _, ca := range p.ca { for _, c := range ca.IntermediateCertificateChain() { caPool.AddCert(c) } } p.pool = caPool return nil } // Syntax: // // trust_pool pki_intermediate [<ca_name>...] { // authority <ca_name>... // } // // The 'authority' directive can be specified multiple times. func (pic *PKIIntermediateCAPool) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume module name pic.Authority = append(pic.Authority, d.RemainingArgs()...) for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "authority": pic.Authority = append(pic.Authority, d.RemainingArgs()...) default: return d.Errf("unrecognized directive: %s", d.Val()) } } if len(pic.Authority) == 0 { return d.Err("no authorities specified") } return nil } // return the certificate pool generated with intermediate certificates from the PKI app func (p PKIIntermediateCAPool) CertPool() *x509.CertPool { return p.pool } // StoragePool extracts the trusted certificates root from Caddy storage type StoragePool struct { // The storage module where the trusted root certificates are stored. Absent // explicit storage implies the use of Caddy default storage. StorageRaw json.RawMessage `json:"storage,omitempty" caddy:"namespace=caddy.storage inline_key=module"` // The storage key/index to the location of the certificates PEMKeys []string `json:"pem_keys,omitempty"` storage certmagic.Storage pool *x509.CertPool } // CaddyModule implements caddy.Module. func (StoragePool) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.ca_pool.source.storage", New: func() caddy.Module { return new(StoragePool) }, } } // Provision implements caddy.Provisioner. func (ca *StoragePool) Provision(ctx caddy.Context) error { 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 len(ca.PEMKeys) == 0 { return fmt.Errorf("no PEM keys specified") } caPool := x509.NewCertPool() for _, caID := range ca.PEMKeys { bs, err := ca.storage.Load(ctx, caID) if err != nil { return fmt.Errorf("error loading cert '%s' from storage: %s", caID, err) } if !caPool.AppendCertsFromPEM(bs) { return fmt.Errorf("failed to add certificate '%s' to pool", caID) } } ca.pool = caPool return nil } // Syntax: // // trust_pool storage [<storage_keys>...] { // storage <storage_module> // keys <storage_keys>... // } // // The 'keys' directive can be specified multiple times. // The'storage' directive is optional and defaults to the default storage module. func (sp *StoragePool) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume module name sp.PEMKeys = append(sp.PEMKeys, d.RemainingArgs()...) for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "storage": if sp.StorageRaw != nil { return d.Err("storage module already set") } if !d.NextArg() { return d.ArgErr() } modStem := d.Val() modID := "caddy.storage." + modStem unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } storage, ok := unm.(caddy.StorageConverter) if !ok { return d.Errf("module %s is not a caddy.StorageConverter", modID) } sp.StorageRaw = caddyconfig.JSONModuleObject(storage, "module", modStem, nil) case "keys": sp.PEMKeys = append(sp.PEMKeys, d.RemainingArgs()...) default: return d.Errf("unrecognized directive: %s", d.Val()) } } return nil } func (p StoragePool) CertPool() *x509.CertPool { return p.pool } // TLSConfig holds configuration related to the TLS configuration for the // transport/client. // copied from with minor modifications: modules/caddyhttp/reverseproxy/httptransport.go type TLSConfig struct { // Provides the guest module that provides the trusted certificate authority (CA) certificates CARaw json.RawMessage `json:"ca,omitempty" caddy:"namespace=tls.ca_pool.source inline_key=provider"` // 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"` } func (t *TLSConfig) unmarshalCaddyfile(d *caddyfile.Dispenser) error { for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "ca": if !d.NextArg() { return d.ArgErr() } modStem := d.Val() modID := "tls.ca_pool.source." + modStem unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } ca, ok := unm.(CA) if !ok { return d.Errf("module %s is not a caddytls.CA", modID) } t.CARaw = caddyconfig.JSONModuleObject(ca, "provider", modStem, nil) case "insecure_skip_verify": t.InsecureSkipVerify = true case "handshake_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.HandshakeTimeout = caddy.Duration(dur) case "server_name": if !d.Args(&t.ServerName) { return d.ArgErr() } case "renegotiation": if !d.Args(&t.Renegotiation) { return d.ArgErr() } switch t.Renegotiation { case "never", "once", "freely": continue default: t.Renegotiation = "" return d.Errf("unrecognized renegotiation level: %s", t.Renegotiation) } default: return d.Errf("unrecognized directive: %s", d.Val()) } } return nil } // 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. // copied from with minor modifications: modules/caddyhttp/reverseproxy/httptransport.go func (t *TLSConfig) makeTLSClientConfig(ctx caddy.Context) (*tls.Config, error) { repl, _ := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if repl == nil { repl = caddy.NewReplacer() } cfg := new(tls.Config) if t.CARaw != nil { caRaw, err := ctx.LoadModule(t, "CARaw") if err != nil { return nil, err } ca := caRaw.(CA) cfg.RootCAs = ca.CertPool() } // Renegotiation switch t.Renegotiation { case "never", "": cfg.Renegotiation = tls.RenegotiateNever case "once": cfg.Renegotiation = tls.RenegotiateOnceAsClient case "freely": cfg.Renegotiation = tls.RenegotiateFreelyAsClient default: return nil, fmt.Errorf("invalid TLS renegotiation level: %v", t.Renegotiation) } // override for the server name used verify the TLS handshake cfg.ServerName = repl.ReplaceKnown(cfg.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 } // The HTTPCertPool fetches the trusted root certificates from HTTP(S) // endpoints. The TLS connection properties can be customized, including custom // trusted root certificate. One example usage of this module is to get the trusted // certificates from another Caddy instance that is running the PKI app and ACME server. type HTTPCertPool struct { // the list of URLs that respond with PEM-encoded certificates to trust. Endpoints []string `json:"endpoints,omitempty"` // Customize the TLS connection knobs to used during the HTTP call TLS *TLSConfig `json:"tls,omitempty"` pool *x509.CertPool } // CaddyModule implements caddy.Module. func (HTTPCertPool) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.ca_pool.source.http", New: func() caddy.Module { return new(HTTPCertPool) }, } } // Provision implements caddy.Provisioner. func (hcp *HTTPCertPool) Provision(ctx caddy.Context) error { caPool := x509.NewCertPool() customTransport := http.DefaultTransport.(*http.Transport).Clone() if hcp.TLS != nil { tlsConfig, err := hcp.TLS.makeTLSClientConfig(ctx) if err != nil { return err } customTransport.TLSClientConfig = tlsConfig } httpClient := *http.DefaultClient httpClient.Transport = customTransport for _, uri := range hcp.Endpoints { req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil) if err != nil { return err } res, err := httpClient.Do(req) if err != nil { return err } pembs, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { return err } if !caPool.AppendCertsFromPEM(pembs) { return fmt.Errorf("failed to add certs from URL: %s", uri) } } hcp.pool = caPool return nil } // Syntax: // // trust_pool http [<endpoints...>] { // endpoints <endpoints...> // tls <tls_config> // } // // tls_config: // // ca <ca_module> // insecure_skip_verify // handshake_timeout <duration> // server_name <name> // renegotiation <never|once|freely> // // <ca_module> is the name of the CA module to source the trust // // certificate pool and follows the syntax of the named CA module. func (hcp *HTTPCertPool) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume module name hcp.Endpoints = append(hcp.Endpoints, d.RemainingArgs()...) for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "endpoints": if d.CountRemainingArgs() == 0 { return d.ArgErr() } hcp.Endpoints = append(hcp.Endpoints, d.RemainingArgs()...) case "tls": if hcp.TLS != nil { return d.Err("tls block already defined") } hcp.TLS = new(TLSConfig) if err := hcp.TLS.unmarshalCaddyfile(d); err != nil { return err } default: return d.Errf("unrecognized directive: %s", d.Val()) } } return nil } // report error if the endpoints are not valid URLs func (hcp HTTPCertPool) Validate() (err error) { for _, u := range hcp.Endpoints { _, e := url.Parse(u) if e != nil { err = errors.Join(err, e) } } return err } // CertPool return the certificate pool generated from the HTTP responses func (hcp HTTPCertPool) CertPool() *x509.CertPool { return hcp.pool } var ( _ caddy.Module = (*InlineCAPool)(nil) _ caddy.Provisioner = (*InlineCAPool)(nil) _ CA = (*InlineCAPool)(nil) _ caddyfile.Unmarshaler = (*InlineCAPool)(nil) _ caddy.Module = (*FileCAPool)(nil) _ caddy.Provisioner = (*FileCAPool)(nil) _ CA = (*FileCAPool)(nil) _ caddyfile.Unmarshaler = (*FileCAPool)(nil) _ caddy.Module = (*PKIRootCAPool)(nil) _ caddy.Provisioner = (*PKIRootCAPool)(nil) _ CA = (*PKIRootCAPool)(nil) _ caddyfile.Unmarshaler = (*PKIRootCAPool)(nil) _ caddy.Module = (*PKIIntermediateCAPool)(nil) _ caddy.Provisioner = (*PKIIntermediateCAPool)(nil) _ CA = (*PKIIntermediateCAPool)(nil) _ caddyfile.Unmarshaler = (*PKIIntermediateCAPool)(nil) _ caddy.Module = (*StoragePool)(nil) _ caddy.Provisioner = (*StoragePool)(nil) _ CA = (*StoragePool)(nil) _ caddyfile.Unmarshaler = (*StoragePool)(nil) _ caddy.Module = (*HTTPCertPool)(nil) _ caddy.Provisioner = (*HTTPCertPool)(nil) _ caddy.Validator = (*HTTPCertPool)(nil) _ CA = (*HTTPCertPool)(nil) _ caddyfile.Unmarshaler = (*HTTPCertPool)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/acmeissuer.go
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" "encoding/json" "fmt" "net/http" "net/url" "os" "strconv" "strings" "time" "github.com/caddyserver/certmagic" "github.com/caddyserver/zerossl" "github.com/mholt/acmez/v3/acme" "go.uber.org/zap" "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(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"` // Optionally select an ACME profile to use for certificate // orders. Must be a profile name offered by the ACME server, // which are listed at its directory endpoint. // // EXPERIMENTAL: Subject to change. // See https://datatracker.ietf.org/doc/draft-aaron-acme-profiles/ Profile string `json:"profile,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"` // The validity period to ask the CA to issue a certificate for. // Default: 0 (CA chooses lifetime). // This value is used to compute the "notAfter" field of the ACME order; // therefore the system must have a reasonably synchronized clock. // NOTE: Not all CAs support this. Check with your CA's ACME // documentation to see if this is allowed and what values may // be used. EXPERIMENTAL: Subject to change. CertificateLifetime caddy.Duration `json:"certificate_lifetime,omitempty"` // Forward proxy module NetworkProxyRaw json.RawMessage `json:"network_proxy,omitempty" caddy:"namespace=caddy.network_proxy inline_key=from"` 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 challenge provider, if not already established if iss.Challenges != nil && iss.Challenges.DNS != nil && iss.Challenges.DNS.solver == nil { var prov certmagic.DNSProvider if iss.Challenges.DNS.ProviderRaw != nil { // a challenge provider has been locally configured - use it val, err := ctx.LoadModule(iss.Challenges.DNS, "ProviderRaw") if err != nil { return fmt.Errorf("loading DNS provider module: %v", err) } prov = val.(certmagic.DNSProvider) } else if tlsAppIface, err := ctx.AppIfConfigured("tls"); err == nil { // no locally configured DNS challenge provider, but if there is // a global DNS module configured with the TLS app, use that tlsApp := tlsAppIface.(*TLS) if tlsApp.dns != nil { prov = tlsApp.dns.(certmagic.DNSProvider) } } if prov == nil { return fmt.Errorf("DNS challenge enabled, but no DNS provider configured") } iss.Challenges.DNS.solver = &certmagic.DNS01Solver{ DNSManager: certmagic.DNSManager{ DNSProvider: prov, 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(ctx) if err != nil { return err } return nil } func (iss *ACMEIssuer) makeIssuerTemplate(ctx caddy.Context) (certmagic.ACMEIssuer, error) { template := certmagic.ACMEIssuer{ CA: iss.CA, TestCA: iss.TestCA, Email: iss.Email, Profile: iss.Profile, AccountKeyPEM: iss.AccountKey, CertObtainTimeout: time.Duration(iss.ACMETimeout), TrustedRoots: iss.rootPool, ExternalAccount: iss.ExternalAccount, NotAfter: time.Duration(iss.CertificateLifetime), Logger: iss.logger, } if len(iss.NetworkProxyRaw) != 0 { proxyMod, err := ctx.LoadModule(iss, "NetworkProxyRaw") if err != nil { return template, fmt.Errorf("failed to load network_proxy module: %v", err) } if m, ok := proxyMod.(caddy.ProxyFuncProducer); ok { template.HTTPProxy = m.ProxyFunc() } else { return template, fmt.Errorf("network_proxy module is not `(func(*http.Request) (*url.URL, error))``") } } 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.Challenges.Distributed != nil { template.DisableDistributedSolvers = !*iss.Challenges.Distributed } } if iss.PreferredChains != nil { template.PreferredChains = certmagic.ChainPreference{ Smallest: iss.PreferredChains.Smallest, AnyCommonName: iss.PreferredChains.AnyCommonName, RootCommonName: iss.PreferredChains.RootCommonName, } } // ZeroSSL requires EAB, but we can generate that automatically (requires an email address be configured) if strings.HasPrefix(iss.CA, "https://acme.zerossl.com/") { template.NewAccountFunc = func(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.generateZeroSSLEABCredentials(ctx, acct) return acct, err } } 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 } // GetRenewalInfo wraps the underlying GetRenewalInfo method and satisfies // the CertMagic interface for ARI support. func (iss *ACMEIssuer) GetRenewalInfo(ctx context.Context, cert certmagic.Certificate) (acme.RenewalInfo, error) { return iss.issuer.GetRenewalInfo(ctx, cert) } // generateZeroSSLEABCredentials generates ZeroSSL EAB credentials for the primary contact email // on the issuer. It should only be usedif the CA endpoint is ZeroSSL. An email address is required. func (iss *ACMEIssuer) generateZeroSSLEABCredentials(ctx context.Context, acct acme.Account) (*acme.EAB, acme.Account, error) { if strings.TrimSpace(iss.Email) == "" { return nil, acme.Account{}, fmt.Errorf("your email address is required to use ZeroSSL's ACME endpoint") } 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:" + iss.Email} } endpoint := zerossl.BaseURL + "/acme/eab-credentials-email" form := url.Values{"email": []string{iss.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) } 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 { // do this check first because ZeroSSL's API returns 200 on errors 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) } if c := iss.logger.Check(zapcore.InfoLevel, "generated EAB credentials"); c != nil { c.Write(zap.String("key_id", result.EABKID)) } return &acme.EAB{ KeyID: result.EABKID, MACKey: result.EABHMACKey, }, acct, nil } // UnmarshalCaddyfile deserializes Caddyfile tokens into iss. // // ... acme [<directory_url>] { // dir <directory_url> // test_dir <test_directory_url> // email <email> // profile <profile_name> // 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 { d.Next() // consume issuer name if d.NextArg() { iss.CA = d.Val() if d.NextArg() { return d.ArgErr() } } for d.NextBlock(0) { switch d.Val() { case "lifetime": var lifetimeStr string if !d.AllArgs(&lifetimeStr) { return d.ArgErr() } lifetime, err := caddy.ParseDuration(lifetimeStr) if err != nil { return d.Errf("invalid lifetime %s: %v", lifetimeStr, err) } if lifetime < 0 { return d.Errf("lifetime must be >= 0: %s", lifetime) } iss.CertificateLifetime = caddy.Duration(lifetime) 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 "profile": if !d.AllArgs(&iss.Profile) { 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 "distributed": if !d.NextArg() { return d.ArgErr() } if d.Val() != "false" { return d.Errf("only accepted value is 'false'") } if iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.Distributed == nil { iss.Challenges.Distributed = new(bool) } 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 iss.Challenges == nil { iss.Challenges = new(ChallengesConfig) } if iss.Challenges.DNS == nil { iss.Challenges.DNS = new(DNSChallengeConfig) } if d.NextArg() { provName := d.Val() 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 } 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 = append(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 = append(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"` } // Interface guards var ( _ certmagic.PreChecker = (*ACMEIssuer)(nil) _ certmagic.Issuer = (*ACMEIssuer)(nil) _ certmagic.Revoker = (*ACMEIssuer)(nil) _ certmagic.RenewalInfoGetter = (*ACMEIssuer)(nil) _ caddy.Provisioner = (*ACMEIssuer)(nil) _ ConfigSetter = (*ACMEIssuer)(nil) _ caddyfile.Unmarshaler = (*ACMEIssuer)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/automation.go
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 ( "context" "crypto/tls" "encoding/json" "errors" "fmt" "net" "slices" "strings" "github.com/caddyserver/certmagic" "github.com/mholt/acmez/v3" "go.uber.org/zap" "go.uber.org/zap/zapcore" "golang.org/x/net/idna" "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; otherwise 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"` // If true, private keys already existing in storage // will be reused. Otherwise, a new key will be // created for every new certificate to mitigate // pinning and reduce the scope of key compromise. // TEMPORARY: Key pinning is against industry best practices. // This property will likely be removed in the future. // Do not rely on it forever; watch the release notes. ReusePrivateKeys bool `json:"reuse_private_keys,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 // Whether this policy had explicit managers configured directly on it. hadExplicitManagers bool } // 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 { sub = repl.ReplaceAll(sub, "") subASCII, err := idna.ToASCII(sub) if err != nil { return fmt.Errorf("could not convert automation policy subject '%s' to punycode: %v", sub, err) } subjects[i] = subASCII } 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 { ap.hadExplicitManagers = true 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 { // permission module is now required after a number of negligence cases that allowed abuse; // but it may still be optional for explicit subjects (bounded, non-wildcard), for the // internal issuer since it doesn't cause public PKI pressure on ACME servers; subtly, it // is useful to allow on-demand TLS to be enabled so Managers can be used, but to still // prevent issuance from Issuers (when Managers don't provide a certificate) if there's no // permission module configured noProtections := ap.isWildcardOrDefault() && !ap.onlyInternalIssuer() && (tlsApp.Automation == nil || tlsApp.Automation.OnDemand == nil || tlsApp.Automation.OnDemand.permission == nil) failClosed := noProtections && !ap.hadExplicitManagers // don't allow on-demand issuance (other than implicit managers) if no managers have been explicitly configured if noProtections { if !ap.hadExplicitManagers { // no managers, no explicitly-configured permission module, this is a config error return fmt.Errorf("on-demand TLS cannot be enabled without a permission module to prevent abuse; please refer to documentation for details") } // allow on-demand to be enabled but only for the purpose of the Managers; issuance won't be allowed from Issuers tlsApp.logger.Warn("on-demand TLS can only get certificates from the configured external manager(s) because no ask endpoint / permission module is specified") } ond = &certmagic.OnDemandConfig{ DecisionFunc: func(ctx context.Context, name string) error { if failClosed { return fmt.Errorf("no permission module configured; certificates not allowed except from external Managers") } if tlsApp.Automation == nil || tlsApp.Automation.OnDemand == nil { return nil } // logging the remote IP can be useful for servers that want to count // attempts from clients to detect patterns of abuse -- it should NOT be // used solely for decision making, however var remoteIP string if hello, ok := ctx.Value(certmagic.ClientHelloInfoCtxKey).(*tls.ClientHelloInfo); ok && hello != nil { if remote := hello.Conn.RemoteAddr(); remote != nil { remoteIP, _, _ = net.SplitHostPort(remote.String()) } } if c := tlsApp.logger.Check(zapcore.DebugLevel, "asking for permission for on-demand certificate"); c != nil { c.Write( zap.String("remote_ip", remoteIP), zap.String("domain", name), ) } // ask the permission module if this cert is allowed if err := tlsApp.Automation.OnDemand.permission.CertificateAllowed(ctx, name); err != nil { // distinguish true errors from denials, because it's important to elevate actual errors if errors.Is(err, ErrPermissionDenied) { if c := tlsApp.logger.Check(zapcore.DebugLevel, "on-demand certificate issuance denied"); c != nil { c.Write( zap.String("domain", name), zap.Error(err), ) } } else { if c := tlsApp.logger.Check(zapcore.ErrorLevel, "failed to get permission for on-demand certificate"); c != nil { c.Write( zap.String("domain", name), zap.Error(err), ) } } return err } return nil }, Managers: ap.Managers, } } template := certmagic.Config{ MustStaple: ap.MustStaple, RenewalWindowRatio: ap.RenewalWindowRatio, KeySource: keySource, OnEvent: tlsApp.onEvent, OnDemand: ond, ReusePrivateKeys: ap.ReusePrivateKeys, 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 } // AllInternalSubjects returns true if all the subjects on this policy are internal. func (ap *AutomationPolicy) AllInternalSubjects() bool { return !slices.ContainsFunc(ap.subjects, func(s string) bool { return !certmagic.SubjectIsInternal(s) }) } 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 := len(ap.subjects) == 0 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(userEmail string) []certmagic.Issuer { issuers := []certmagic.Issuer{new(ACMEIssuer)} if strings.TrimSpace(userEmail) != "" { issuers = append(issuers, &ACMEIssuer{ CA: certmagic.ZeroSSLProductionCA, Email: userEmail, }) } return issuers } // 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"` // Whether distributed solving is enabled. This is // enabled by default, so this is only used to // disable it, which should only need to be done if // you cannot reliably or affordably use storage // backend for writing/distributing challenge info. // (Applies to HTTP and TLS-ALPN challenges.) // If set to false, challenges can only be solved // from the Caddy instance that initiated the // challenge, with the exception of HTTP challenges // initiated with the same ACME account that this // config uses. (Caddy can still solve those challenges // without explicitly writing the info to storage.) // // Default: true Distributed *bool `json:"distributed,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. // Required. 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 } // 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) }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/sessiontickets.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/matchers.go
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 ( "context" "crypto/tls" "fmt" "net" "net/netip" "regexp" "slices" "strconv" "strings" "github.com/caddyserver/certmagic" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/internal" ) func init() { caddy.RegisterModule(MatchServerName{}) caddy.RegisterModule(MatchServerNameRE{}) caddy.RegisterModule(MatchRemoteIP{}) caddy.RegisterModule(MatchLocalIP{}) } // 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 { var repl *caddy.Replacer // caddytls.TestServerNameMatcher calls this function without any context if ctx := hello.Context(); ctx != nil { // In some situations the existing context may have no replacer if replAny := ctx.Value(caddy.ReplacerCtxKey); replAny != nil { repl = replAny.(*caddy.Replacer) } } if repl == nil { repl = caddy.NewReplacer() } for _, name := range m { rs := repl.ReplaceAll(name, "") if certmagic.MatchWildcard(hello.ServerName, rs) { return true } } return false } // UnmarshalCaddyfile sets up the MatchServerName from Caddyfile tokens. Syntax: // // sni <domains...> func (m *MatchServerName) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { wrapper := d.Val() // At least one same-line option must be provided if d.CountRemainingArgs() == 0 { return d.ArgErr() } *m = append(*m, d.RemainingArgs()...) // No blocks are supported if d.NextBlock(d.Nesting()) { return d.Errf("malformed TLS handshake matcher '%s': blocks are not supported", wrapper) } } return nil } // MatchRegexp is an embeddable type for matching // using regular expressions. It adds placeholders // to the request's replacer. In fact, it is a copy of // caddyhttp.MatchRegexp with a local replacer prefix // and placeholders support in a regular expression pattern. type MatchRegexp struct { // A unique name for this regular expression. Optional, // but useful to prevent overwriting captures from other // regexp matchers. Name string `json:"name,omitempty"` // The regular expression to evaluate, in RE2 syntax, // which is the same general syntax used by Go, Perl, // and Python. For details, see // [Go's regexp package](https://golang.org/pkg/regexp/). // Captures are accessible via placeholders. Unnamed // capture groups are exposed as their numeric, 1-based // index, while named capture groups are available by // the capture group name. Pattern string `json:"pattern"` compiled *regexp.Regexp } // Provision compiles the regular expression which may include placeholders. func (mre *MatchRegexp) Provision(caddy.Context) error { repl := caddy.NewReplacer() re, err := regexp.Compile(repl.ReplaceAll(mre.Pattern, "")) if err != nil { return fmt.Errorf("compiling matcher regexp %s: %v", mre.Pattern, err) } mre.compiled = re return nil } // Validate ensures mre is set up correctly. func (mre *MatchRegexp) Validate() error { if mre.Name != "" && !wordRE.MatchString(mre.Name) { return fmt.Errorf("invalid regexp name (must contain only word characters): %s", mre.Name) } return nil } // Match returns true if input matches the compiled regular // expression in m. It sets values on the replacer repl // associated with capture groups, using the given scope // (namespace). func (mre *MatchRegexp) Match(input string, repl *caddy.Replacer) bool { matches := mre.compiled.FindStringSubmatch(input) if matches == nil { return false } // save all capture groups, first by index for i, match := range matches { keySuffix := "." + strconv.Itoa(i) if mre.Name != "" { repl.Set(regexpPlaceholderPrefix+"."+mre.Name+keySuffix, match) } repl.Set(regexpPlaceholderPrefix+keySuffix, match) } // then by name for i, name := range mre.compiled.SubexpNames() { // skip the first element (the full match), and empty names if i == 0 || name == "" { continue } keySuffix := "." + name if mre.Name != "" { repl.Set(regexpPlaceholderPrefix+"."+mre.Name+keySuffix, matches[i]) } repl.Set(regexpPlaceholderPrefix+keySuffix, matches[i]) } return true } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (mre *MatchRegexp) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // iterate to merge multiple matchers into one for d.Next() { // If this is the second iteration of the loop // then there's more than one *_regexp matcher, // and we would end up overwriting the old one if mre.Pattern != "" { return d.Err("regular expression can only be used once per named matcher") } args := d.RemainingArgs() switch len(args) { case 1: mre.Pattern = args[0] case 2: mre.Name = args[0] mre.Pattern = args[1] default: return d.ArgErr() } // Default to the named matcher's name, if no regexp name is provided. // Note: it requires d.SetContext(caddyfile.MatcherNameCtxKey, value) // called before this unmarshalling, otherwise it wouldn't work. if mre.Name == "" { mre.Name = d.GetContextString(caddyfile.MatcherNameCtxKey) } if d.NextBlock(0) { return d.Err("malformed regexp matcher: blocks are not supported") } } return nil } // MatchServerNameRE matches based on SNI using a regular expression. type MatchServerNameRE struct{ MatchRegexp } // CaddyModule returns the Caddy module information. func (MatchServerNameRE) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.handshake_match.sni_regexp", New: func() caddy.Module { return new(MatchServerNameRE) }, } } // Match matches hello based on SNI using a regular expression. func (m MatchServerNameRE) Match(hello *tls.ClientHelloInfo) bool { // Note: caddytls.TestServerNameMatcher calls this function without any context ctx := hello.Context() if ctx == nil { // layer4.Connection implements GetContext() to pass its context here, // since hello.Context() returns nil if mayHaveContext, ok := hello.Conn.(interface{ GetContext() context.Context }); ok { ctx = mayHaveContext.GetContext() } } var repl *caddy.Replacer if ctx != nil { // In some situations the existing context may have no replacer if replAny := ctx.Value(caddy.ReplacerCtxKey); replAny != nil { repl = replAny.(*caddy.Replacer) } } if repl == nil { repl = caddy.NewReplacer() } return m.MatchRegexp.Match(hello.ServerName, repl) } // 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 { repl := caddy.NewReplacer() m.logger = ctx.Logger() for _, str := range m.Ranges { rs := repl.ReplaceAll(str, "") cidrs, err := m.parseIPRange(rs) if err != nil { return err } m.cidrs = append(m.cidrs, cidrs...) } for _, str := range m.NotRanges { rs := repl.ReplaceAll(str, "") cidrs, err := m.parseIPRange(rs) 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 { if c := m.logger.Check(zapcore.ErrorLevel, "invalid client IP address"); c != nil { c.Write(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 { return slices.ContainsFunc(ranges, func(prefix netip.Prefix) bool { return prefix.Contains(ip) }) } // UnmarshalCaddyfile sets up the MatchRemoteIP from Caddyfile tokens. Syntax: // // remote_ip <ranges...> // // Note: IPs and CIDRs prefixed with ! symbol are treated as not_ranges func (m *MatchRemoteIP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { wrapper := d.Val() // At least one same-line option must be provided if d.CountRemainingArgs() == 0 { return d.ArgErr() } for d.NextArg() { val := d.Val() var exclamation bool if len(val) > 1 && val[0] == '!' { exclamation, val = true, val[1:] } ranges := []string{val} if val == "private_ranges" { ranges = internal.PrivateRangesCIDR() } if exclamation { m.NotRanges = append(m.NotRanges, ranges...) } else { m.Ranges = append(m.Ranges, ranges...) } } // No blocks are supported if d.NextBlock(d.Nesting()) { return d.Errf("malformed TLS handshake matcher '%s': blocks are not supported", wrapper) } } return nil } // MatchLocalIP matches based on the IP address of the interface // receiving the connection. Specific IPs or CIDR ranges can be specified. type MatchLocalIP struct { // The IPs or CIDR ranges to match. Ranges []string `json:"ranges,omitempty"` cidrs []netip.Prefix logger *zap.Logger } // CaddyModule returns the Caddy module information. func (MatchLocalIP) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.handshake_match.local_ip", New: func() caddy.Module { return new(MatchLocalIP) }, } } // Provision parses m's IP ranges, either from IP or CIDR expressions. func (m *MatchLocalIP) Provision(ctx caddy.Context) error { repl := caddy.NewReplacer() m.logger = ctx.Logger() for _, str := range m.Ranges { rs := repl.ReplaceAll(str, "") cidrs, err := m.parseIPRange(rs) if err != nil { return err } m.cidrs = append(m.cidrs, cidrs...) } return nil } // Match matches hello based on the connection's remote IP. func (m MatchLocalIP) Match(hello *tls.ClientHelloInfo) bool { localAddr := hello.Conn.LocalAddr().String() ipStr, _, err := net.SplitHostPort(localAddr) if err != nil { ipStr = localAddr // weird; maybe no port? } ipAddr, err := netip.ParseAddr(ipStr) if err != nil { if c := m.logger.Check(zapcore.ErrorLevel, "invalid local IP address"); c != nil { c.Write(zap.String("ip", ipStr)) } return false } return (len(m.cidrs) == 0 || m.matches(ipAddr, m.cidrs)) } func (MatchLocalIP) 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 (MatchLocalIP) matches(ip netip.Addr, ranges []netip.Prefix) bool { return slices.ContainsFunc(ranges, func(prefix netip.Prefix) bool { return prefix.Contains(ip) }) } // UnmarshalCaddyfile sets up the MatchLocalIP from Caddyfile tokens. Syntax: // // local_ip <ranges...> func (m *MatchLocalIP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { wrapper := d.Val() // At least one same-line option must be provided if d.CountRemainingArgs() == 0 { return d.ArgErr() } for d.NextArg() { val := d.Val() if val == "private_ranges" { m.Ranges = append(m.Ranges, internal.PrivateRangesCIDR()...) continue } m.Ranges = append(m.Ranges, val) } // No blocks are supported if d.NextBlock(d.Nesting()) { return d.Errf("malformed TLS handshake matcher '%s': blocks are not supported", wrapper) } } return nil } // Interface guards var ( _ ConnectionMatcher = (*MatchLocalIP)(nil) _ ConnectionMatcher = (*MatchRemoteIP)(nil) _ ConnectionMatcher = (*MatchServerName)(nil) _ ConnectionMatcher = (*MatchServerNameRE)(nil) _ caddy.Provisioner = (*MatchLocalIP)(nil) _ caddy.Provisioner = (*MatchRemoteIP)(nil) _ caddy.Provisioner = (*MatchServerNameRE)(nil) _ caddyfile.Unmarshaler = (*MatchLocalIP)(nil) _ caddyfile.Unmarshaler = (*MatchRemoteIP)(nil) _ caddyfile.Unmarshaler = (*MatchServerName)(nil) _ caddyfile.Unmarshaler = (*MatchServerNameRE)(nil) ) var wordRE = regexp.MustCompile(`\w+`) const regexpPlaceholderPrefix = "tls.regexp"
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/connpolicy.go
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 ( "context" "crypto/tls" "crypto/x509" "encoding/base64" "encoding/json" "encoding/pem" "fmt" "io" "os" "reflect" "slices" "strings" "github.com/mholt/acmez/v3" "go.uber.org/zap" "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(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)) } } if len(pol.HandshakeContextRaw) > 0 { modIface, err := ctx.LoadModule(pol, "HandshakeContextRaw") if err != nil { return fmt.Errorf("loading handshake context module: %v", err) } cp[i].handshakeContext = modIface.(HandshakeContext) } } return nil } // TLSConfig returns a standard-lib-compatible TLS configuration which // selects the first matching policy based on the ClientHello. func (cp ConnectionPolicies) TLSConfig(ctx 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 { // index for fast lookups during handshakes indexedBySNI[sniName] = append(indexedBySNI[sniName], p) } } } } } 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 } } if pol.Drop { return nil, fmt.Errorf("dropping connection") } return pol.TLSConfig, nil } return nil, fmt.Errorf("no server TLS configuration available for ClientHello: %+v", hello) } tlsCfg := &tls.Config{ MinVersion: tls.VersionTLS12, GetConfigForClient: getConfigForClient, } // enable ECH, if configured if tlsAppIface, err := ctx.AppIfConfigured("tls"); err == nil { tlsApp := tlsAppIface.(*TLS) if tlsApp.EncryptedClientHello != nil && len(tlsApp.EncryptedClientHello.configs) > 0 { // if no publication was configured, we apply ECH to all server names by default, // but the TLS app needs to know what they are in this case, since they don't appear // in its config (remember, TLS connection policies are used by *other* apps to // run TLS servers) -- we skip names with placeholders if tlsApp.EncryptedClientHello.Publication == nil { var echNames []string repl := caddy.NewReplacer() for _, p := range cp { for _, m := range p.matchers { if sni, ok := m.(MatchServerName); ok { for _, name := range sni { finalName := strings.ToLower(repl.ReplaceAll(name, "")) echNames = append(echNames, finalName) } } } } tlsApp.RegisterServerNames(echNames) } tlsCfg.GetEncryptedClientHelloKeys = func(chi *tls.ClientHelloInfo) ([]tls.EncryptedClientHelloKey, error) { tlsApp.EncryptedClientHello.configsMu.RLock() defer tlsApp.EncryptedClientHello.configsMu.RUnlock() return tlsApp.EncryptedClientHello.stdlibReady, nil } } } return tlsCfg } // 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"` matchers []ConnectionMatcher // 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"` // Reject TLS connections. EXPERIMENTAL: May change. Drop bool `json:"drop,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"` // A module that can manipulate the context passed into CertMagic's // certificate management functions during TLS handshakes. // EXPERIMENTAL - subject to change or removal. HandshakeContextRaw json.RawMessage `json:"handshake_context,omitempty" caddy:"namespace=tls.context inline_key=module"` handshakeContext HandshakeContext // 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:"-"` } type HandshakeContext interface { // HandshakeContext returns a context to pass into CertMagic's // GetCertificate function used to serve, load, and manage certs // during TLS handshakes. Generally you'll start with the context // from the ClientHelloInfo, but you may use other information // from it as well. Return an error to abort the handshake. HandshakeContext(*tls.ClientHelloInfo) (context.Context, error) } 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 // TODO: experimental: if a handshake context module is configured, allow it // to modify the context before passing it into CertMagic's GetCertificate ctx := hello.Context() if p.handshakeContext != nil { ctx, err = p.handshakeContext.HandshakeContext(hello) if err != nil { return nil, fmt.Errorf("handshake context: %v", err) } } return cfg.GetCertificateWithContext(ctx, 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 alpnFound := slices.Contains(p.ALPN, acmez.ACMETLS1Protocol) 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 { if err := p.ClientAuthentication.provision(ctx); err != nil { return fmt.Errorf("provisioning client CA: %v", err) } if err := p.ClientAuthentication.ConfigureTLSConfig(cfg); err != nil { return fmt.Errorf("configuring TLS client authentication: %v", err) } // Prevent privilege escalation in case multiple vhosts are configured for // this TLS server; we could potentially figure out if that's the case, but // that might be complex to get right every time. Actually, two proper // solutions could leave tickets enabled, but I am not sure how to do them // properly without significant time investment; there may be new Go // APIs that alloaw this (Wrap/UnwrapSession?) but I do not know how to use // them at this time. TODO: one of these is a possible future enhancement: // A) Prevent resumptions across server identities (certificates): binding the ticket to the // certificate we would serve in a full handshake, or even bind a ticket to the exact SNI // it was issued under (though there are proposals for session resumption across hostnames). // B) Prevent resumptions falsely authenticating a client: include the realm in the ticket, // so that it can be validated upon resumption. cfg.SessionTicketsDisabled = true } if p.InsecureSecretsLog != "" { filename, err := caddy.NewReplacer().ReplaceOrErr(p.InsecureSecretsLog, true, true) if err != nil { return err } filename, err = caddy.FastAbs(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) if c := tlsApp.logger.Check(zapcore.WarnLevel, "TLS SECURITY COMPROMISED: secrets logging is enabled!"); c != nil { c.Write(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.FallbackSNI == "" && p.InsecureSecretsLog == "" } // SettingsEqual returns true if p's settings (fields // except the matchers) are the same as q. func (p ConnectionPolicy) SettingsEqual(q ConnectionPolicy) bool { p.MatchersRaw = nil q.MatchersRaw = nil return reflect.DeepEqual(p, q) } // UnmarshalCaddyfile sets up the ConnectionPolicy from Caddyfile tokens. Syntax: // // connection_policy { // alpn <values...> // cert_selection { // ... // } // ciphers <cipher_suites...> // client_auth { // ... // } // curves <curves...> // default_sni <server_name> // match { // ... // } // protocols <min> [<max>] // # EXPERIMENTAL: // drop // fallback_sni <server_name> // insecure_secrets_log <log_file> // } func (cp *ConnectionPolicy) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { _, wrapper := d.Next(), d.Val() // No same-line options are supported if d.CountRemainingArgs() > 0 { return d.ArgErr() } var hasCertSelection, hasClientAuth, hasDefaultSNI, hasDrop, hasFallbackSNI, hasInsecureSecretsLog, hasMatch, hasProtocols bool for nesting := d.Nesting(); d.NextBlock(nesting); { optionName := d.Val() switch optionName { case "alpn": if d.CountRemainingArgs() == 0 { return d.ArgErr() } cp.ALPN = append(cp.ALPN, d.RemainingArgs()...) case "cert_selection": if hasCertSelection { return d.Errf("duplicate %s option '%s'", wrapper, optionName) } p := &CustomCertSelectionPolicy{} if err := p.UnmarshalCaddyfile(d.NewFromNextSegment()); err != nil { return err } cp.CertSelection, hasCertSelection = p, true case "client_auth": if hasClientAuth { return d.Errf("duplicate %s option '%s'", wrapper, optionName) } ca := &ClientAuthentication{} if err := ca.UnmarshalCaddyfile(d.NewFromNextSegment()); err != nil { return err } cp.ClientAuthentication, hasClientAuth = ca, true case "ciphers": if d.CountRemainingArgs() == 0 { return d.ArgErr() } cp.CipherSuites = append(cp.CipherSuites, d.RemainingArgs()...) case "curves": if d.CountRemainingArgs() == 0 { return d.ArgErr() } cp.Curves = append(cp.Curves, d.RemainingArgs()...) case "default_sni": if hasDefaultSNI { return d.Errf("duplicate %s option '%s'", wrapper, optionName) } if d.CountRemainingArgs() != 1 { return d.ArgErr() } _, cp.DefaultSNI, hasDefaultSNI = d.NextArg(), d.Val(), true case "drop": // EXPERIMENTAL if hasDrop { return d.Errf("duplicate %s option '%s'", wrapper, optionName) } cp.Drop, hasDrop = true, true case "fallback_sni": // EXPERIMENTAL if hasFallbackSNI { return d.Errf("duplicate %s option '%s'", wrapper, optionName) } if d.CountRemainingArgs() != 1 { return d.ArgErr() } _, cp.FallbackSNI, hasFallbackSNI = d.NextArg(), d.Val(), true case "insecure_secrets_log": // EXPERIMENTAL if hasInsecureSecretsLog { return d.Errf("duplicate %s option '%s'", wrapper, optionName) } if d.CountRemainingArgs() != 1 { return d.ArgErr() } _, cp.InsecureSecretsLog, hasInsecureSecretsLog = d.NextArg(), d.Val(), true case "match": if hasMatch { return d.Errf("duplicate %s option '%s'", wrapper, optionName) } matcherSet, err := ParseCaddyfileNestedMatcherSet(d) if err != nil { return err } cp.MatchersRaw, hasMatch = matcherSet, true case "protocols": if hasProtocols { return d.Errf("duplicate %s option '%s'", wrapper, optionName) } if d.CountRemainingArgs() == 0 || d.CountRemainingArgs() > 2 { return d.ArgErr() } _, cp.ProtocolMin, hasProtocols = d.NextArg(), d.Val(), true if d.NextArg() { cp.ProtocolMax = d.Val() } default: return d.ArgErr() } // No nested blocks are supported if d.NextBlock(nesting + 1) { return d.Errf("malformed %s option '%s': blocks are not supported", wrapper, optionName) } } return nil } // ClientAuthentication configures TLS client auth. type ClientAuthentication struct { // Certificate authority module which provides the certificate pool of trusted certificates CARaw json.RawMessage `json:"ca,omitempty" caddy:"namespace=tls.ca_pool.source inline_key=provider"` ca CA // Deprecated: Use the `ca` field with the `tls.ca_pool.source.inline` module instead. // 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"` // Deprecated: Use the `ca` field with the `tls.ca_pool.source.file` module instead. // 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.verifier.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.verifier 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 } // UnmarshalCaddyfile parses the Caddyfile segment to set up the client authentication. Syntax: // // client_auth { // mode [request|require|verify_if_given|require_and_verify] // trust_pool <module> { // ... // } // verifier <module> // } // // If `mode` is not provided, it defaults to `require_and_verify` if `trust_pool` is provided. // Otherwise, it defaults to `require`. func (ca *ClientAuthentication) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.NextArg() { // consume any tokens on the same line, if any. } for nesting := d.Nesting(); d.NextBlock(nesting); { subdir := d.Val() switch subdir { case "mode": if d.CountRemainingArgs() > 1 { return d.ArgErr() } if !d.Args(&ca.Mode) { return d.ArgErr() } case "trusted_ca_cert": caddy.Log().Warn("The 'trusted_ca_cert' field is deprecated. Use the 'trust_pool' field instead.") if len(ca.CARaw) != 0 { return d.Err("cannot specify both 'trust_pool' and 'trusted_ca_cert' or 'trusted_ca_cert_file'") } if !d.NextArg() { return d.ArgErr() } ca.TrustedCACerts = append(ca.TrustedCACerts, d.Val()) case "trusted_leaf_cert": if !d.NextArg() { return d.ArgErr() } ca.TrustedLeafCerts = append(ca.TrustedLeafCerts, d.Val()) case "trusted_ca_cert_file": caddy.Log().Warn("The 'trusted_ca_cert_file' field is deprecated. Use the 'trust_pool' field instead.") if len(ca.CARaw) != 0 { return d.Err("cannot specify both 'trust_pool' and 'trusted_ca_cert' or 'trusted_ca_cert_file'") } if !d.NextArg() { return d.ArgErr() } filename := d.Val() ders, err := convertPEMFilesToDER(filename) if err != nil { return d.WrapErr(err) } ca.TrustedCACerts = append(ca.TrustedCACerts, ders...) case "trusted_leaf_cert_file": if !d.NextArg() { return d.ArgErr() } filename := d.Val() ders, err := convertPEMFilesToDER(filename) if err != nil { return d.WrapErr(err) } ca.TrustedLeafCerts = append(ca.TrustedLeafCerts, ders...) case "trust_pool": if len(ca.TrustedCACerts) != 0 { return d.Err("cannot specify both 'trust_pool' and 'trusted_ca_cert' or 'trusted_ca_cert_file'") } if !d.NextArg() { return d.ArgErr() } modName := d.Val() mod, err := caddyfile.UnmarshalModule(d, "tls.ca_pool.source."+modName) if err != nil { return d.WrapErr(err) } caMod, ok := mod.(CA) if !ok { return fmt.Errorf("trust_pool module '%s' is not a certificate pool provider", caMod) } ca.CARaw = caddyconfig.JSONModuleObject(caMod, "provider", modName, nil) case "verifier": if !d.NextArg() { return d.ArgErr() } vType := d.Val() modID := "tls.client_auth.verifier." + vType unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return err } _, ok := unm.(ClientCertificateVerifier) if !ok { return d.Errf("module '%s' is not a caddytls.ClientCertificateVerifier", modID) } ca.VerifiersRaw = append(ca.VerifiersRaw, caddyconfig.JSONModuleObject(unm, "verifier", vType, nil)) default: return d.Errf("unknown subdirective for client_auth: %s", subdir) } } // only trust_ca_cert or trust_ca_cert_file was specified if len(ca.TrustedCACerts) > 0 { fileMod := &InlineCAPool{} fileMod.TrustedCACerts = append(fileMod.TrustedCACerts, ca.TrustedCACerts...) ca.CARaw = caddyconfig.JSONModuleObject(fileMod, "provider", "inline", nil) ca.TrustedCACertPEMFiles, ca.TrustedCACerts = nil, nil } return nil } func convertPEMFilesToDER(filename string) ([]string, error) { certDataPEM, err := os.ReadFile(filename) if err != nil { return nil, err } var ders []string // while block is not nil, we have more certificates in the file for block, rest := pem.Decode(certDataPEM); block != nil; block, rest = pem.Decode(rest) { if block.Type != "CERTIFICATE" { return nil, fmt.Errorf("no CERTIFICATE pem block found in %s", filename) } ders = append( ders, base64.StdEncoding.EncodeToString(block.Bytes), ) } // if we decoded nothing, return an error if len(ders) == 0 { return nil, fmt.Errorf("no CERTIFICATE pem block found in %s", filename) } return ders, nil } func (clientauth *ClientAuthentication) provision(ctx caddy.Context) error { if len(clientauth.CARaw) > 0 && (len(clientauth.TrustedCACerts) > 0 || len(clientauth.TrustedCACertPEMFiles) > 0) { return fmt.Errorf("conflicting config for client authentication trust CA") } // convert all named file paths to inline if len(clientauth.TrustedCACertPEMFiles) > 0 { for _, fpath := range clientauth.TrustedCACertPEMFiles { ders, err := convertPEMFilesToDER(fpath) if err != nil { return nil } clientauth.TrustedCACerts = append(clientauth.TrustedCACerts, ders...) } } // if we have TrustedCACerts explicitly set, create an 'inline' CA and return if len(clientauth.TrustedCACerts) > 0 { caPool := InlineCAPool{ TrustedCACerts: clientauth.TrustedCACerts, } err := caPool.Provision(ctx) if err != nil { return nil } clientauth.ca = caPool } // if we don't have any CARaw set, there's not much work to do if clientauth.CARaw == nil { return nil } caRaw, err := ctx.LoadModule(clientauth, "CARaw") if err != nil { return err } ca, ok := caRaw.(CA) if !ok { return fmt.Errorf("'ca' module '%s' is not a certificate pool provider", ca) } clientauth.ca = ca return nil } // 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 || clientauth.CARaw != nil || clientauth.ca != nil } // 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 || clientauth.CARaw != nil || clientauth.ca != nil { cfg.ClientAuth = tls.RequireAndVerifyClientCert } else { cfg.ClientAuth = tls.RequireAnyClientCert } } // enforce CA verification by adding CA certs to the ClientCAs pool if clientauth.ca != nil { cfg.ClientCAs = clientauth.ca.CertPool() } // 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() }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
true
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/pemloader.go
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 // Provision implements caddy.Provisioner. func (pl PEMLoader) Provision(ctx caddy.Context) error { repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { repl = caddy.NewReplacer() } for k, pair := range pl { for i, tag := range pair.Tags { pair.Tags[i] = repl.ReplaceKnown(tag, "") } pl[k] = CertKeyPEMPair{ CertificatePEM: repl.ReplaceKnown(pair.CertificatePEM, ""), KeyPEM: repl.ReplaceKnown(pair.KeyPEM, ""), Tags: pair.Tags, } } return nil } // 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) _ caddy.Provisioner = (PEMLoader)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/connpolicy_test.go
modules/caddytls/connpolicy_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 ( "encoding/json" "fmt" "reflect" "testing" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func TestClientAuthenticationUnmarshalCaddyfileWithDirectiveName(t *testing.T) { const test_der_1 = `MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ==` const test_cert_file_1 = "../../caddytest/caddy.ca.cer" type args struct { d *caddyfile.Dispenser } tests := []struct { name string args args expected ClientAuthentication wantErr bool }{ { name: "empty client_auth block does not error", args: args{ d: caddyfile.NewTestDispenser( `client_auth { }`, ), }, wantErr: false, }, { name: "providing both 'trust_pool' and 'trusted_ca_cert' returns an error", args: args{ d: caddyfile.NewTestDispenser( `client_auth { trust_pool inline MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ== trusted_ca_cert MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ== }`), }, wantErr: true, }, { name: "trust_pool without a module argument returns an error", args: args{ d: caddyfile.NewTestDispenser( `client_auth { trust_pool }`), }, wantErr: true, }, { name: "providing more than 1 mode produces an error", args: args{ d: caddyfile.NewTestDispenser(` client_auth { mode require request } `), }, wantErr: true, }, { name: "not providing 'mode' argument produces an error", args: args{d: caddyfile.NewTestDispenser(` client_auth { mode } `)}, wantErr: true, }, { name: "providing a single 'mode' argument sets the mode", args: args{ d: caddyfile.NewTestDispenser(` client_auth { mode require } `), }, expected: ClientAuthentication{ Mode: "require", }, wantErr: false, }, { name: "not providing an argument to 'trusted_ca_cert' produces an error", args: args{ d: caddyfile.NewTestDispenser(` client_auth { trusted_ca_cert } `), }, wantErr: true, }, { name: "not providing an argument to 'trusted_leaf_cert' produces an error", args: args{ d: caddyfile.NewTestDispenser(` client_auth { trusted_leaf_cert } `), }, wantErr: true, }, { name: "not providing an argument to 'trusted_ca_cert_file' produces an error", args: args{ d: caddyfile.NewTestDispenser(` client_auth { trusted_ca_cert_file } `), }, wantErr: true, }, { name: "not providing an argument to 'trusted_leaf_cert_file' produces an error", args: args{ d: caddyfile.NewTestDispenser(` client_auth { trusted_leaf_cert_file } `), }, wantErr: true, }, { name: "using 'trusted_ca_cert' adapts successfully", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` client_auth { trusted_ca_cert %s }`, test_der_1)), }, expected: ClientAuthentication{ CARaw: json.RawMessage(fmt.Sprintf(`{"provider":"inline","trusted_ca_certs":["%s"]}`, test_der_1)), }, }, { name: "using 'inline' trust_pool loads the module successfully", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` client_auth { trust_pool inline { trust_der %s } } `, test_der_1)), }, expected: ClientAuthentication{ CARaw: json.RawMessage(fmt.Sprintf(`{"provider":"inline","trusted_ca_certs":["%s"]}`, test_der_1)), }, }, { name: "setting 'trusted_ca_cert' and 'trust_pool' produces an error", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` client_auth { trusted_ca_cert %s trust_pool inline { trust_der %s } }`, test_der_1, test_der_1)), }, wantErr: true, }, { name: "setting 'trust_pool' and 'trusted_ca_cert' produces an error", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` client_auth { trust_pool inline { trust_der %s } trusted_ca_cert %s }`, test_der_1, test_der_1)), }, wantErr: true, }, { name: "setting 'trust_pool' and 'trusted_ca_cert' produces an error", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` client_auth { trust_pool inline { trust_der %s } trusted_ca_cert_file %s }`, test_der_1, test_cert_file_1)), }, wantErr: true, }, { name: "configuring 'trusted_ca_cert_file' without an argument is an error", args: args{ d: caddyfile.NewTestDispenser(` client_auth { trusted_ca_cert_file } `), }, wantErr: true, }, { name: "configuring 'trusted_ca_cert_file' produces config with 'inline' provider", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` client_auth { trusted_ca_cert_file %s }`, test_cert_file_1), ), }, expected: ClientAuthentication{ CARaw: json.RawMessage(fmt.Sprintf(`{"provider":"inline","trusted_ca_certs":["%s"]}`, test_der_1)), }, wantErr: false, }, { name: "configuring leaf certs does not conflict with 'trust_pool'", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` client_auth { trust_pool inline { trust_der %s } trusted_leaf_cert %s }`, test_der_1, test_der_1)), }, expected: ClientAuthentication{ CARaw: json.RawMessage(fmt.Sprintf(`{"provider":"inline","trusted_ca_certs":["%s"]}`, test_der_1)), TrustedLeafCerts: []string{test_der_1}, }, }, { name: "providing trusted leaf certificate file loads the cert successfully", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` client_auth { trusted_leaf_cert_file %s }`, test_cert_file_1)), }, expected: ClientAuthentication{ TrustedLeafCerts: []string{test_der_1}, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ca := &ClientAuthentication{} if err := ca.UnmarshalCaddyfile(tt.args.d); (err != nil) != tt.wantErr { t.Errorf("ClientAuthentication.UnmarshalCaddyfile() error = %v, wantErr %v", err, tt.wantErr) return } if !tt.wantErr && !reflect.DeepEqual(&tt.expected, ca) { t.Errorf("ClientAuthentication.UnmarshalCaddyfile() = %v, want %v", ca, tt.expected) } }) } } func TestClientAuthenticationProvision(t *testing.T) { tests := []struct { name string ca ClientAuthentication wantErr bool }{ { name: "specifying both 'CARaw' and 'TrustedCACerts' produces an error", ca: ClientAuthentication{ CARaw: json.RawMessage(`{"provider":"inline","trusted_ca_certs":["foo"]}`), TrustedCACerts: []string{"foo"}, }, wantErr: true, }, { name: "specifying both 'CARaw' and 'TrustedCACertPEMFiles' produces an error", ca: ClientAuthentication{ CARaw: json.RawMessage(`{"provider":"inline","trusted_ca_certs":["foo"]}`), TrustedCACertPEMFiles: []string{"foo"}, }, wantErr: true, }, { name: "setting 'TrustedCACerts' provisions the cert pool", ca: ClientAuthentication{ TrustedCACerts: []string{test_der_1}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := tt.ca.provision(caddy.Context{}) if (err != nil) != tt.wantErr { t.Errorf("ClientAuthentication.provision() error = %v, wantErr %v", err, tt.wantErr) return } if !tt.wantErr { if tt.ca.ca.CertPool() == nil { t.Error("CertPool is nil, expected non-nil value") } } }) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/leaffolderloader.go
modules/caddytls/leaffolderloader.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/x509" "fmt" "os" "path/filepath" "strings" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(LeafFolderLoader{}) } // LeafFolderLoader loads certificates from disk // by recursively walking the specified directories, looking for PEM // files which contain a certificate. type LeafFolderLoader struct { Folders []string `json:"folders,omitempty"` } // CaddyModule returns the Caddy module information. func (LeafFolderLoader) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.leaf_cert_loader.folder", New: func() caddy.Module { return new(LeafFolderLoader) }, } } // Provision implements caddy.Provisioner. func (fl *LeafFolderLoader) Provision(ctx caddy.Context) error { repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { repl = caddy.NewReplacer() } for k, path := range fl.Folders { fl.Folders[k] = repl.ReplaceKnown(path, "") } return nil } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (fl *LeafFolderLoader) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.NextArg() fl.Folders = append(fl.Folders, d.RemainingArgs()...) return nil } // LoadLeafCertificates loads all the leaf certificates in the directories // listed in fl from all files ending with .pem. func (fl LeafFolderLoader) LoadLeafCertificates() ([]*x509.Certificate, error) { var certs []*x509.Certificate for _, dir := range fl.Folders { 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 } certData, err := convertPEMFilesToDERBytes(fpath) if err != nil { return err } cert, err := x509.ParseCertificate(certData) if err != nil { return fmt.Errorf("%s: %w", fpath, err) } certs = append(certs, cert) return nil }) if err != nil { return nil, err } } return certs, nil } var ( _ LeafCertificateLoader = (*LeafFolderLoader)(nil) _ caddy.Provisioner = (*LeafFolderLoader)(nil) _ caddyfile.Unmarshaler = (*LeafFolderLoader)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/leaffileloader.go
modules/caddytls/leaffileloader.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/x509" "encoding/pem" "fmt" "os" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(LeafFileLoader{}) } // LeafFileLoader loads leaf certificates from disk. type LeafFileLoader struct { Files []string `json:"files,omitempty"` } // CaddyModule returns the Caddy module information. func (LeafFileLoader) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.leaf_cert_loader.file", New: func() caddy.Module { return new(LeafFileLoader) }, } } // Provision implements caddy.Provisioner. func (fl *LeafFileLoader) Provision(ctx caddy.Context) error { repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { repl = caddy.NewReplacer() } for k, path := range fl.Files { fl.Files[k] = repl.ReplaceKnown(path, "") } return nil } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (fl *LeafFileLoader) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.NextArg() fl.Files = append(fl.Files, d.RemainingArgs()...) return nil } // LoadLeafCertificates returns the certificates to be loaded by fl. func (fl LeafFileLoader) LoadLeafCertificates() ([]*x509.Certificate, error) { certificates := make([]*x509.Certificate, 0, len(fl.Files)) for _, path := range fl.Files { ders, err := convertPEMFilesToDERBytes(path) if err != nil { return nil, err } certs, err := x509.ParseCertificates(ders) if err != nil { return nil, err } certificates = append(certificates, certs...) } return certificates, nil } func convertPEMFilesToDERBytes(filename string) ([]byte, error) { certDataPEM, err := os.ReadFile(filename) if err != nil { return nil, err } var ders []byte // while block is not nil, we have more certificates in the file for block, rest := pem.Decode(certDataPEM); block != nil; block, rest = pem.Decode(rest) { if block.Type != "CERTIFICATE" { return nil, fmt.Errorf("no CERTIFICATE pem block found in %s", filename) } ders = append( ders, block.Bytes..., ) } // if we decoded nothing, return an error if len(ders) == 0 { return nil, fmt.Errorf("no CERTIFICATE pem block found in %s", filename) } return ders, nil } // Interface guard var ( _ LeafCertificateLoader = (*LeafFileLoader)(nil) _ caddy.Provisioner = (*LeafFileLoader)(nil) _ caddyfile.Unmarshaler = (*LeafFileLoader)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/values.go
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 // or key exchange mechanisms ("curves" traditionally). // https://golang.org/pkg/crypto/tls/#CurveID var SupportedCurves = map[string]tls.CurveID{ "x25519mlkem768": tls.X25519MLKEM768, "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 or key exchange // mechanisms we want to use by default. The order is irrelevant. // // This list should only include mechanisms 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.X25519MLKEM768, 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/fileloader.go
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" "strings" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(FileLoader{}) } // FileLoader loads certificates and their associated keys from disk. type FileLoader []CertKeyFilePair // Provision implements caddy.Provisioner. func (fl FileLoader) Provision(ctx caddy.Context) error { repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { repl = caddy.NewReplacer() } for k, pair := range fl { for i, tag := range pair.Tags { pair.Tags[i] = repl.ReplaceKnown(tag, "") } fl[k] = CertKeyFilePair{ Certificate: repl.ReplaceKnown(pair.Certificate, ""), Key: repl.ReplaceKnown(pair.Key, ""), Format: repl.ReplaceKnown(pair.Format, ""), Tags: pair.Tags, } } return nil } // 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": // if the start of the key file looks like an encrypted private key, // reject it with a helpful error message if strings.Contains(string(keyData[:40]), "ENCRYPTED") { return nil, fmt.Errorf("encrypted private keys are not supported; please decrypt the key first") } 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) _ caddy.Provisioner = (FileLoader)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/internalissuer_test.go
modules/caddytls/internalissuer_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 ( "crypto/rand" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "fmt" "os" "path/filepath" "testing" "time" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddypki" "go.uber.org/zap" "go.step.sm/crypto/keyutil" "go.step.sm/crypto/pemutil" ) func TestInternalIssuer_Issue(t *testing.T) { rootSigner, err := keyutil.GenerateDefaultSigner() if err != nil { t.Fatalf("Creating root signer failed: %v", err) } tmpl := &x509.Certificate{ Subject: pkix.Name{CommonName: "test-root"}, IsCA: true, MaxPathLen: 3, NotAfter: time.Now().Add(7 * 24 * time.Hour), NotBefore: time.Now().Add(-7 * 24 * time.Hour), } rootBytes, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, rootSigner.Public(), rootSigner) if err != nil { t.Fatalf("Creating root certificate failed: %v", err) } root, err := x509.ParseCertificate(rootBytes) if err != nil { t.Fatalf("Parsing root certificate failed: %v", err) } firstIntermediateSigner, err := keyutil.GenerateDefaultSigner() if err != nil { t.Fatalf("Creating intermedaite signer failed: %v", err) } firstIntermediateBytes, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{ Subject: pkix.Name{CommonName: "test-first-intermediate"}, IsCA: true, MaxPathLen: 2, NotAfter: time.Now().Add(24 * time.Hour), NotBefore: time.Now().Add(-24 * time.Hour), }, root, firstIntermediateSigner.Public(), rootSigner) if err != nil { t.Fatalf("Creating intermediate certificate failed: %v", err) } firstIntermediate, err := x509.ParseCertificate(firstIntermediateBytes) if err != nil { t.Fatalf("Parsing intermediate certificate failed: %v", err) } secondIntermediateSigner, err := keyutil.GenerateDefaultSigner() if err != nil { t.Fatalf("Creating second intermedaite signer failed: %v", err) } secondIntermediateBytes, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{ Subject: pkix.Name{CommonName: "test-second-intermediate"}, IsCA: true, MaxPathLen: 2, NotAfter: time.Now().Add(24 * time.Hour), NotBefore: time.Now().Add(-24 * time.Hour), }, firstIntermediate, secondIntermediateSigner.Public(), firstIntermediateSigner) if err != nil { t.Fatalf("Creating second intermediate certificate failed: %v", err) } secondIntermediate, err := x509.ParseCertificate(secondIntermediateBytes) if err != nil { t.Fatalf("Parsing second intermediate certificate failed: %v", err) } dir := t.TempDir() storageDir := filepath.Join(dir, "certmagic") rootCertFile := filepath.Join(dir, "root.pem") if _, err = pemutil.Serialize(root, pemutil.WithFilename(rootCertFile)); err != nil { t.Fatalf("Failed serializing root certificate: %v", err) } intermediateCertFile := filepath.Join(dir, "intermediate.pem") if _, err = pemutil.Serialize(firstIntermediate, pemutil.WithFilename(intermediateCertFile)); err != nil { t.Fatalf("Failed serializing intermediate certificate: %v", err) } intermediateKeyFile := filepath.Join(dir, "intermediate.key") if _, err = pemutil.Serialize(firstIntermediateSigner, pemutil.WithFilename(intermediateKeyFile)); err != nil { t.Fatalf("Failed serializing intermediate key: %v", err) } var intermediateChainContents []byte intermediateChain := []*x509.Certificate{secondIntermediate, firstIntermediate} for _, cert := range intermediateChain { b, err := pemutil.Serialize(cert) if err != nil { t.Fatalf("Failed serializing intermediate certificate: %v", err) } intermediateChainContents = append(intermediateChainContents, pem.EncodeToMemory(b)...) } intermediateChainFile := filepath.Join(dir, "intermediates.pem") if err := os.WriteFile(intermediateChainFile, intermediateChainContents, 0644); err != nil { t.Fatalf("Failed writing intermediate chain: %v", err) } intermediateChainKeyFile := filepath.Join(dir, "intermediates.key") if _, err = pemutil.Serialize(secondIntermediateSigner, pemutil.WithFilename(intermediateChainKeyFile)); err != nil { t.Fatalf("Failed serializing intermediate key: %v", err) } signer, err := keyutil.GenerateDefaultSigner() if err != nil { t.Fatalf("Failed creating signer: %v", err) } csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{ Subject: pkix.Name{CommonName: "test"}, }, signer) if err != nil { t.Fatalf("Failed creating CSR: %v", err) } csr, err := x509.ParseCertificateRequest(csrBytes) if err != nil { t.Fatalf("Failed parsing CSR: %v", err) } t.Run("generated-with-defaults", func(t *testing.T) { caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: t.Context()}) t.Cleanup(cancel) logger := zap.NewNop() ca := &caddypki.CA{ StorageRaw: []byte(fmt.Sprintf(`{"module": "file_system", "root": %q}`, storageDir)), } if err := ca.Provision(caddyCtx, "local-test-generated", logger); err != nil { t.Fatalf("Failed provisioning CA: %v", err) } iss := InternalIssuer{ SignWithRoot: false, ca: ca, logger: logger, } c, err := iss.Issue(t.Context(), csr) if err != nil { t.Fatalf("Failed issuing certificate: %v", err) } chain, err := pemutil.ParseCertificateBundle(c.Certificate) if err != nil { t.Errorf("Failed issuing certificate: %v", err) } if len(chain) != 2 { t.Errorf("Expected 2 certificates in chain; got %d", len(chain)) } }) t.Run("single-intermediate-from-disk", func(t *testing.T) { caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: t.Context()}) t.Cleanup(cancel) logger := zap.NewNop() ca := &caddypki.CA{ Root: &caddypki.KeyPair{ Certificate: rootCertFile, }, Intermediate: &caddypki.KeyPair{ Certificate: intermediateCertFile, PrivateKey: intermediateKeyFile, }, StorageRaw: []byte(fmt.Sprintf(`{"module": "file_system", "root": %q}`, storageDir)), } if err := ca.Provision(caddyCtx, "local-test-single-intermediate", logger); err != nil { t.Fatalf("Failed provisioning CA: %v", err) } iss := InternalIssuer{ ca: ca, SignWithRoot: false, logger: logger, } c, err := iss.Issue(t.Context(), csr) if err != nil { t.Fatalf("Failed issuing certificate: %v", err) } chain, err := pemutil.ParseCertificateBundle(c.Certificate) if err != nil { t.Errorf("Failed issuing certificate: %v", err) } if len(chain) != 2 { t.Errorf("Expected 2 certificates in chain; got %d", len(chain)) } }) t.Run("multiple-intermediates-from-disk", func(t *testing.T) { caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: t.Context()}) t.Cleanup(cancel) logger := zap.NewNop() ca := &caddypki.CA{ Root: &caddypki.KeyPair{ Certificate: rootCertFile, }, Intermediate: &caddypki.KeyPair{ Certificate: intermediateChainFile, PrivateKey: intermediateChainKeyFile, }, StorageRaw: []byte(fmt.Sprintf(`{"module": "file_system", "root": %q}`, storageDir)), } if err := ca.Provision(caddyCtx, "local-test", zap.NewNop()); err != nil { t.Fatalf("Failed provisioning CA: %v", err) } iss := InternalIssuer{ ca: ca, SignWithRoot: false, logger: logger, } c, err := iss.Issue(t.Context(), csr) if err != nil { t.Fatalf("Failed issuing certificate: %v", err) } chain, err := pemutil.ParseCertificateBundle(c.Certificate) if err != nil { t.Errorf("Failed issuing certificate: %v", err) } if len(chain) != 3 { t.Errorf("Expected 3 certificates in chain; got %d", len(chain)) } }) }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/ondemand.go
modules/caddytls/ondemand.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" "errors" "fmt" "net/http" "net/url" "time" "github.com/caddyserver/certmagic" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(PermissionByHTTP{}) } // OnDemandConfig configures on-demand TLS, for obtaining // needed certificates at handshake-time. Because this // feature can easily be abused, Caddy must ask permission // to your application whether a particular domain is allowed // to have a certificate issued for it. type OnDemandConfig struct { // Deprecated. WILL BE REMOVED SOON. Use 'permission' instead with the `http` module. Ask string `json:"ask,omitempty"` // REQUIRED. A module that will determine whether a // certificate is allowed to be loaded from storage // or obtained from an issuer on demand. PermissionRaw json.RawMessage `json:"permission,omitempty" caddy:"namespace=tls.permission inline_key=module"` permission OnDemandPermission } // OnDemandPermission is a type that can give permission for // whether a certificate should be allowed to be obtained or // loaded from storage on-demand. // EXPERIMENTAL: This API is experimental and subject to change. type OnDemandPermission interface { // CertificateAllowed returns nil if a certificate for the given // name is allowed to be either obtained from an issuer or loaded // from storage on-demand. // // The context passed in has the associated *tls.ClientHelloInfo // value available at the certmagic.ClientHelloInfoCtxKey key. // // In the worst case, this function may be called as frequently // as every TLS handshake, so it should return as quick as possible // to reduce latency. In the normal case, this function is only // called when a certificate is needed that is not already loaded // into memory ready to serve. CertificateAllowed(ctx context.Context, name string) error } // PermissionByHTTP determines permission for a TLS certificate by // making a request to an HTTP endpoint. type PermissionByHTTP struct { // The endpoint to access. It should be a full URL. // A query string parameter "domain" will be added to it, // containing the domain (or IP) for the desired certificate, // like so: `?domain=example.com`. Generally, this endpoint // is not exposed publicly to avoid a minor information leak // (which domains are serviced by your application). // // 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. Endpoint string `json:"endpoint"` logger *zap.Logger replacer *caddy.Replacer } // CaddyModule returns the Caddy module information. func (PermissionByHTTP) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.permission.http", New: func() caddy.Module { return new(PermissionByHTTP) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (p *PermissionByHTTP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { if !d.Next() { return nil } if !d.AllArgs(&p.Endpoint) { return d.ArgErr() } return nil } func (p *PermissionByHTTP) Provision(ctx caddy.Context) error { p.logger = ctx.Logger() p.replacer = caddy.NewReplacer() return nil } func (p PermissionByHTTP) CertificateAllowed(ctx context.Context, name string) error { // run replacer on endpoint URL (for environment variables) -- return errors to prevent surprises (#5036) askEndpoint, err := p.replacer.ReplaceOrErr(p.Endpoint, true, true) if err != nil { return fmt.Errorf("preparing 'ask' endpoint: %v", err) } askURL, err := url.Parse(askEndpoint) 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() var remote string if chi, ok := ctx.Value(certmagic.ClientHelloInfoCtxKey).(*tls.ClientHelloInfo); ok && chi != nil { remote = chi.Conn.RemoteAddr().String() } if c := p.logger.Check(zapcore.DebugLevel, "asking permission endpoint"); c != nil { c.Write( zap.String("remote", remote), zap.String("domain", name), zap.String("url", askURLString), ) } resp, err := onDemandAskClient.Get(askURLString) if err != nil { return fmt.Errorf("checking %v to determine if certificate for hostname '%s' should be allowed: %v", askEndpoint, name, err) } resp.Body.Close() if c := p.logger.Check(zapcore.DebugLevel, "response from permission endpoint"); c != nil { c.Write( zap.String("remote", remote), 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, ErrPermissionDenied, askEndpoint, resp.StatusCode) } return nil } // ErrPermissionDenied is an error that should be wrapped or returned when the // configured permission module does not allow a certificate to be issued, // to distinguish that from other errors such as connection failure. var ErrPermissionDenied = errors.New("certificate not allowed by permission module") // These perpetual values are used for on-demand TLS. var ( 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") }, } ) // Interface guards var ( _ OnDemandPermission = (*PermissionByHTTP)(nil) _ caddy.Provisioner = (*PermissionByHTTP)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/leaffolderloader_test.go
modules/caddytls/leaffolderloader_test.go
package caddytls import ( "context" "encoding/pem" "os" "strings" "testing" "github.com/caddyserver/caddy/v2" ) func TestLeafFolderLoader(t *testing.T) { fl := LeafFolderLoader{Folders: []string{"../../caddytest"}} fl.Provision(caddy.Context{Context: context.Background()}) out, err := fl.LoadLeafCertificates() if err != nil { t.Errorf("Leaf certs folder loading test failed: %v", err) } if len(out) != 1 { t.Errorf("Error loading leaf cert in memory struct") return } pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: out[0].Raw}) pemFileBytes, err := os.ReadFile("../../caddytest/leafcert.pem") if err != nil { t.Errorf("Unable to read the example certificate from the file") } // Remove /r because windows. pemFileString := strings.ReplaceAll(string(pemFileBytes), "\r\n", "\n") if string(pemBytes) != pemFileString { t.Errorf("Leaf Certificate Folder Loader: Failed to load the correct certificate") } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/leafpemloader.go
modules/caddytls/leafpemloader.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/x509" "fmt" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(LeafPEMLoader{}) } // LeafPEMLoader loads leaf certificates by // decoding their PEM blocks directly. This has the advantage // of not needing to store them on disk at all. type LeafPEMLoader struct { Certificates []string `json:"certificates,omitempty"` } // Provision implements caddy.Provisioner. func (pl *LeafPEMLoader) Provision(ctx caddy.Context) error { repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { repl = caddy.NewReplacer() } for i, cert := range pl.Certificates { pl.Certificates[i] = repl.ReplaceKnown(cert, "") } return nil } // CaddyModule returns the Caddy module information. func (LeafPEMLoader) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.leaf_cert_loader.pem", New: func() caddy.Module { return new(LeafPEMLoader) }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (fl *LeafPEMLoader) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.NextArg() fl.Certificates = append(fl.Certificates, d.RemainingArgs()...) return nil } // LoadLeafCertificates returns the certificates contained in pl. func (pl LeafPEMLoader) LoadLeafCertificates() ([]*x509.Certificate, error) { certs := make([]*x509.Certificate, 0, len(pl.Certificates)) for i, cert := range pl.Certificates { derBytes, err := convertPEMToDER([]byte(cert)) if err != nil { return nil, fmt.Errorf("PEM leaf certificate loader, cert %d: %v", i, err) } cert, err := x509.ParseCertificate(derBytes) if err != nil { return nil, fmt.Errorf("PEM cert %d: %v", i, err) } certs = append(certs, cert) } return certs, nil } // Interface guard var ( _ LeafCertificateLoader = (*LeafPEMLoader)(nil) _ caddy.Provisioner = (*LeafPEMLoader)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/zerosslissuer.go
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" "fmt" "strconv" "time" "github.com/caddyserver/certmagic" "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(new(ZeroSSLIssuer)) } // ZeroSSLIssuer uses the ZeroSSL API to get certificates. // Note that this is distinct from ZeroSSL's ACME endpoint. // To use ZeroSSL's ACME endpoint, use the ACMEIssuer // configured with ZeroSSL's ACME directory endpoint. type ZeroSSLIssuer struct { // The API key (or "access key") for using the ZeroSSL API. // REQUIRED. APIKey string `json:"api_key,omitempty"` // How many days the certificate should be valid for. // Only certain values are accepted; see ZeroSSL docs. ValidityDays int `json:"validity_days,omitempty"` // The host to bind to when opening a listener for // verifying domain names (or IPs). ListenHost string `json:"listen_host,omitempty"` // If HTTP is forwarded from port 80, specify the // forwarded port here. AlternateHTTPPort int `json:"alternate_http_port,omitempty"` // Use CNAME validation instead of HTTP. ZeroSSL's // API uses CNAME records for DNS validation, similar // to how Let's Encrypt uses TXT records for the // DNS challenge. CNAMEValidation *DNSChallengeConfig `json:"cname_validation,omitempty"` logger *zap.Logger storage certmagic.Storage issuer *certmagic.ZeroSSLIssuer } // 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 the issuer. func (iss *ZeroSSLIssuer) Provision(ctx caddy.Context) error { iss.logger = ctx.Logger() iss.storage = ctx.Storage() repl := caddy.NewReplacer() var dnsManager *certmagic.DNSManager if iss.CNAMEValidation != nil && len(iss.CNAMEValidation.ProviderRaw) > 0 { val, err := ctx.LoadModule(iss.CNAMEValidation, "ProviderRaw") if err != nil { return fmt.Errorf("loading DNS provider module: %v", err) } dnsManager = &certmagic.DNSManager{ DNSProvider: val.(certmagic.DNSProvider), TTL: time.Duration(iss.CNAMEValidation.TTL), PropagationDelay: time.Duration(iss.CNAMEValidation.PropagationDelay), PropagationTimeout: time.Duration(iss.CNAMEValidation.PropagationTimeout), Resolvers: iss.CNAMEValidation.Resolvers, OverrideDomain: iss.CNAMEValidation.OverrideDomain, Logger: iss.logger.Named("cname"), } } iss.issuer = &certmagic.ZeroSSLIssuer{ APIKey: repl.ReplaceAll(iss.APIKey, ""), ValidityDays: iss.ValidityDays, ListenHost: iss.ListenHost, AltHTTPPort: iss.AlternateHTTPPort, Storage: iss.storage, CNAMEValidation: dnsManager, Logger: iss.logger, } return nil } // Issue obtains a certificate for the given csr. func (iss *ZeroSSLIssuer) 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 *ZeroSSLIssuer) IssuerKey() string { return iss.issuer.IssuerKey() } // Revoke revokes the given certificate. func (iss *ZeroSSLIssuer) Revoke(ctx context.Context, cert certmagic.CertificateResource, reason int) error { return iss.issuer.Revoke(ctx, cert, reason) } // UnmarshalCaddyfile deserializes Caddyfile tokens into iss. // // ... zerossl <api_key> { // validity_days <days> // alt_http_port <port> // dns <provider_name> ... // propagation_delay <duration> // propagation_timeout <duration> // resolvers <list...> // dns_ttl <duration> // } func (iss *ZeroSSLIssuer) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume issuer name // API key is required if !d.NextArg() { return d.ArgErr() } iss.APIKey = d.Val() if d.NextArg() { return d.ArgErr() } for nesting := d.Nesting(); d.NextBlock(nesting); { switch d.Val() { case "validity_days": if iss.ValidityDays != 0 { return d.Errf("validity days is already specified: %d", iss.ValidityDays) } days, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("invalid number of days %s: %v", d.Val(), err) } iss.ValidityDays = days 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) } iss.AlternateHTTPPort = port case "dns": if !d.NextArg() { return d.ArgErr() } provName := d.Val() if iss.CNAMEValidation == nil { iss.CNAMEValidation = new(DNSChallengeConfig) } unm, err := caddyfile.UnmarshalModule(d, "dns.providers."+provName) if err != nil { return err } iss.CNAMEValidation.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.CNAMEValidation == nil { iss.CNAMEValidation = new(DNSChallengeConfig) } iss.CNAMEValidation.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.CNAMEValidation == nil { iss.CNAMEValidation = new(DNSChallengeConfig) } iss.CNAMEValidation.PropagationTimeout = caddy.Duration(timeout) case "resolvers": if iss.CNAMEValidation == nil { iss.CNAMEValidation = new(DNSChallengeConfig) } iss.CNAMEValidation.Resolvers = d.RemainingArgs() if len(iss.CNAMEValidation.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.CNAMEValidation == nil { iss.CNAMEValidation = new(DNSChallengeConfig) } iss.CNAMEValidation.TTL = caddy.Duration(ttl) default: return d.Errf("unrecognized zerossl issuer property: %s", d.Val()) } } return nil } // Interface guards var ( _ certmagic.Issuer = (*ZeroSSLIssuer)(nil) _ certmagic.Revoker = (*ZeroSSLIssuer)(nil) _ caddy.Provisioner = (*ZeroSSLIssuer)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/folderloader.go
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) }, } } // Provision implements caddy.Provisioner. func (fl FolderLoader) Provision(ctx caddy.Context) error { repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { repl = caddy.NewReplacer() } for k, path := range fl { fl[k] = repl.ReplaceKnown(path, "") } return nil } // 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") } // if the start of the key file looks like an encrypted private key, // reject it with a helpful error message if strings.HasPrefix(string(keyPEMBytes[:40]), "ENCRYPTED") { return tls.Certificate{}, fmt.Errorf("encrypted private keys are not supported; please decrypt the key first") } 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) _ caddy.Provisioner = (FolderLoader)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/certselection.go
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" "slices" "github.com/caddyserver/certmagic" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) // 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 { snInt := sn.Int // avoid taking address of iteration variable (gosec warning) if cert.Leaf.SerialNumber.Cmp(&snInt) == 0 { found = true break } } if !found { continue } } if len(p.SubjectOrganization) > 0 { found := slices.ContainsFunc(p.SubjectOrganization, func(s string) bool { return slices.Contains(cert.Leaf.Subject.Organization, s) }) if !found { continue } } if p.PublicKeyAlgorithm != PublicKeyAlgorithm(x509.UnknownPublicKeyAlgorithm) && PublicKeyAlgorithm(cert.Leaf.PublicKeyAlgorithm) != p.PublicKeyAlgorithm { continue } if len(p.AnyTag) > 0 { found := slices.ContainsFunc(p.AnyTag, cert.HasTag) 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) } // UnmarshalCaddyfile sets up the CustomCertSelectionPolicy from Caddyfile tokens. Syntax: // // cert_selection { // all_tags <values...> // any_tag <values...> // public_key_algorithm <dsa|ecdsa|rsa> // serial_number <big_integers...> // subject_organization <values...> // } func (p *CustomCertSelectionPolicy) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { _, wrapper := d.Next(), d.Val() // consume wrapper name // No same-line options are supported if d.CountRemainingArgs() > 0 { return d.ArgErr() } var hasPublicKeyAlgorithm bool for nesting := d.Nesting(); d.NextBlock(nesting); { optionName := d.Val() switch optionName { case "all_tags": if d.CountRemainingArgs() == 0 { return d.ArgErr() } p.AllTags = append(p.AllTags, d.RemainingArgs()...) case "any_tag": if d.CountRemainingArgs() == 0 { return d.ArgErr() } p.AnyTag = append(p.AnyTag, d.RemainingArgs()...) case "public_key_algorithm": if hasPublicKeyAlgorithm { return d.Errf("duplicate %s option '%s'", wrapper, optionName) } if d.CountRemainingArgs() != 1 { return d.ArgErr() } d.NextArg() if err := p.PublicKeyAlgorithm.UnmarshalJSON([]byte(d.Val())); err != nil { return d.Errf("parsing %s option '%s': %v", wrapper, optionName, err) } hasPublicKeyAlgorithm = true case "serial_number": if d.CountRemainingArgs() == 0 { return d.ArgErr() } for d.NextArg() { val, bi := d.Val(), bigInt{} _, ok := bi.SetString(val, 10) if !ok { return d.Errf("parsing %s option '%s': invalid big.int value %s", wrapper, optionName, val) } p.SerialNumber = append(p.SerialNumber, bi) } case "subject_organization": if d.CountRemainingArgs() == 0 { return d.ArgErr() } p.SubjectOrganization = append(p.SubjectOrganization, d.RemainingArgs()...) default: return d.ArgErr() } // No nested blocks are supported if d.NextBlock(nesting + 1) { return d.Errf("malformed %s option '%s': blocks are not supported", wrapper, optionName) } } return nil } // 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 } // Interface guard var _ caddyfile.Unmarshaler = (*CustomCertSelectionPolicy)(nil)
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/storageloader.go
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" "strings" "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 repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { repl = caddy.NewReplacer() } for k, pair := range sl.Pairs { for i, tag := range pair.Tags { pair.Tags[i] = repl.ReplaceKnown(tag, "") } sl.Pairs[k] = CertKeyFilePair{ Certificate: repl.ReplaceKnown(pair.Certificate, ""), Key: repl.ReplaceKnown(pair.Key, ""), Format: repl.ReplaceKnown(pair.Format, ""), Tags: pair.Tags, } } 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": // if the start of the key file looks like an encrypted private key, // reject it with a helpful error message if strings.Contains(string(keyData[:40]), "ENCRYPTED") { return nil, fmt.Errorf("encrypted private keys are not supported; please decrypt the key first") } 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/ech.go
modules/caddytls/ech.go
package caddytls import ( "context" "crypto/tls" "encoding/base64" "encoding/json" "errors" "fmt" "io/fs" weakrand "math/rand/v2" "path" "strconv" "strings" "sync" "time" "github.com/caddyserver/certmagic" "github.com/cloudflare/circl/hpke" "github.com/cloudflare/circl/kem" "github.com/libdns/libdns" "go.uber.org/zap" "golang.org/x/crypto/cryptobyte" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(ECHDNSPublisher{}) } // ECH enables Encrypted ClientHello (ECH) and configures its management. // // ECH helps protect site names (also called "server names" or "domain names" // or "SNI"), which are normally sent over plaintext when establishing a TLS // connection. With ECH, the true ClientHello is encrypted and wrapped by an // "outer" ClientHello that uses a more generic, shared server name that is // publicly known. // // Clients need to know which public name (and other parameters) to use when // connecting to a site with ECH, and the methods for this vary; however, // major browsers support reading ECH configurations from DNS records (which // is typically only secure when DNS-over-HTTPS or DNS-over-TLS is enabled in // the client). Caddy has the ability to automatically publish ECH configs to // DNS records if a DNS provider is configured either in the TLS app or with // each individual publication config object. (Requires a custom build with a // DNS provider module.) // // ECH requires at least TLS 1.3, so any TLS connection policies with ECH // applied will automatically upgrade the minimum TLS version to 1.3, even if // configured to a lower version. // // Note that, as of Caddy 2.10.0 (~March 2025), ECH keys are not automatically // rotated due to a limitation in the Go standard library (see // https://github.com/golang/go/issues/71920). This should be resolved when // Go 1.25 is released (~Aug. 2025), and Caddy will be updated to automatically // rotate ECH keys/configs at that point. // // EXPERIMENTAL: Subject to change. type ECH struct { // The list of ECH configurations for which to automatically generate // and rotate keys. At least one is required to enable ECH. // // It is strongly recommended to use as few ECH configs as possible // to maximize the size of your anonymity set (see the ECH specification // for a definition). Typically, each server should have only one public // name, i.e. one config in this list. Configs []ECHConfiguration `json:"configs,omitempty"` // Publication describes ways to publish ECH configs for clients to // discover and use. Without publication, most clients will not use // ECH at all, and those that do will suffer degraded performance. // // Most major browsers support ECH by way of publication to HTTPS // DNS RRs. (This also typically requires that they use DoH or DoT.) Publication []*ECHPublication `json:"publication,omitempty"` configsMu *sync.RWMutex // protects both configs and the list of configs/keys the standard library uses configs map[string][]echConfig // map of public_name to list of configs stdlibReady []tls.EncryptedClientHelloKey // ECH configs+keys in a format the standard library can use } // Provision loads or creates ECH configs and returns outer names (for certificate // management), but does not publish any ECH configs. The DNS module is used as // a default for later publishing if needed. func (ech *ECH) Provision(ctx caddy.Context) ([]string, error) { ech.configsMu = new(sync.RWMutex) logger := ctx.Logger().Named("ech") // set up publication modules before we need to obtain a lock in storage, // since this is strictly internal and doesn't require synchronization for i, pub := range ech.Publication { mods, err := ctx.LoadModule(pub, "PublishersRaw") if err != nil { return nil, fmt.Errorf("loading ECH publication modules: %v", err) } for _, modIface := range mods.(map[string]any) { ech.Publication[i].publishers = append(ech.Publication[i].publishers, modIface.(ECHPublisher)) } } // the rest of provisioning needs an exclusive lock so that instances aren't // stepping on each other when setting up ECH configs storage := ctx.Storage() if err := storage.Lock(ctx, echStorageLockName); err != nil { return nil, err } defer func() { if err := storage.Unlock(ctx, echStorageLockName); err != nil { logger.Error("unable to unlock ECH provisioning in storage", zap.Error(err)) } }() ech.configsMu.Lock() defer ech.configsMu.Unlock() outerNames, err := ech.setConfigsFromStorage(ctx, logger) if err != nil { return nil, fmt.Errorf("loading configs from storage: %w", err) } // see if we need to make any new ones based on the input configuration for _, cfg := range ech.Configs { publicName := strings.ToLower(strings.TrimSpace(cfg.PublicName)) if list, ok := ech.configs[publicName]; !ok || len(list) == 0 { // no config with this public name was loaded, so create one echCfg, err := generateAndStoreECHConfig(ctx, publicName) if err != nil { return nil, err } logger.Debug("generated new ECH config", zap.String("public_name", echCfg.RawPublicName), zap.Uint8("id", echCfg.ConfigID)) ech.configs[publicName] = append(ech.configs[publicName], echCfg) outerNames = append(outerNames, publicName) } } // ensure old keys are rotated out if err = ech.rotateECHKeys(ctx, logger, true); err != nil { return nil, fmt.Errorf("rotating ECH configs: %w", err) } return outerNames, nil } // setConfigsFromStorage sets the ECH configs in memory to those in storage. // It must be called in a write lock on ech.configsMu. func (ech *ECH) setConfigsFromStorage(ctx caddy.Context, logger *zap.Logger) ([]string, error) { storage := ctx.Storage() ech.configs = make(map[string][]echConfig) var outerNames []string // start by loading all the existing configs (even the older ones on the way out, // since some clients may still be using them if they haven't yet picked up on the // new configs) cfgKeys, err := storage.List(ctx, echConfigsKey, false) if err != nil && !errors.Is(err, fs.ErrNotExist) { // OK if dir doesn't exist; it will be created return nil, err } for _, cfgKey := range cfgKeys { cfg, err := loadECHConfig(ctx, path.Base(cfgKey)) if err != nil { return nil, err } // if any part of the config's folder was corrupted, the load function will // clean it up and not return an error, since configs are immutable and // fairly ephemeral... so just check that we actually got a populated config if cfg.configBin == nil || cfg.privKeyBin == nil { continue } logger.Debug("loaded ECH config", zap.String("public_name", cfg.RawPublicName), zap.Uint8("id", cfg.ConfigID)) if _, seen := ech.configs[cfg.RawPublicName]; !seen { outerNames = append(outerNames, cfg.RawPublicName) } ech.configs[cfg.RawPublicName] = append(ech.configs[cfg.RawPublicName], cfg) } return outerNames, nil } // rotateECHKeys updates the ECH keys/configs that are outdated. It should be called // in a write lock on ech.configsMu. If a lock is already obtained in storage, then // pass true for storageSynced. func (ech *ECH) rotateECHKeys(ctx caddy.Context, logger *zap.Logger, storageSynced bool) error { storage := ctx.Storage() // all existing configs are now loaded; rotate keys "regularly" as recommended by the spec // (also: "Rotating too frequently limits the client anonymity set." - but the more server // names, the more frequently rotation can be done safely) const ( rotationInterval = 24 * time.Hour * 30 deleteAfter = 24 * time.Hour * 90 ) if !ech.rotationNeeded(rotationInterval, deleteAfter) { return nil } // sync this operation across cluster if not already if !storageSynced { if err := storage.Lock(ctx, echStorageLockName); err != nil { return err } defer func() { if err := storage.Unlock(ctx, echStorageLockName); err != nil { logger.Error("unable to unlock ECH rotation in storage", zap.Error(err)) } }() } // update what storage has, in case another instance already updated things if _, err := ech.setConfigsFromStorage(ctx, logger); err != nil { return fmt.Errorf("updating ECH keys from storage: %v", err) } // iterate the updated list and do any updates as needed for publicName := range ech.configs { for i := 0; i < len(ech.configs[publicName]); i++ { cfg := ech.configs[publicName][i] if time.Since(cfg.meta.Created) >= rotationInterval && cfg.meta.Replaced.IsZero() { // key is due for rotation and it hasn't been replaced yet; do that now logger.Debug("ECH config is due for rotation", zap.String("public_name", cfg.RawPublicName), zap.Uint8("id", cfg.ConfigID), zap.Time("created", cfg.meta.Created), zap.Duration("age", time.Since(cfg.meta.Created)), zap.Duration("rotation_interval", rotationInterval)) // start by generating and storing the replacement ECH config newCfg, err := generateAndStoreECHConfig(ctx, publicName) if err != nil { return fmt.Errorf("generating and storing new replacement ECH config: %w", err) } // mark the key as replaced so we don't rotate it again, and instead delete it later ech.configs[publicName][i].meta.Replaced = time.Now() // persist the updated metadata metaBytes, err := json.Marshal(ech.configs[publicName][i].meta) if err != nil { return fmt.Errorf("marshaling updated ECH config metadata: %v", err) } if err := storage.Store(ctx, echMetaKey(cfg.ConfigID), metaBytes); err != nil { return fmt.Errorf("storing updated ECH config metadata: %v", err) } ech.configs[publicName] = append(ech.configs[publicName], newCfg) logger.Debug("rotated ECH key", zap.String("public_name", cfg.RawPublicName), zap.Uint8("old_id", cfg.ConfigID), zap.Uint8("new_id", newCfg.ConfigID)) } else if time.Since(cfg.meta.Created) >= deleteAfter && !cfg.meta.Replaced.IsZero() { // key has expired and is no longer supported; delete it from storage and memory cfgIDKey := path.Join(echConfigsKey, strconv.Itoa(int(cfg.ConfigID))) if err := storage.Delete(ctx, cfgIDKey); err != nil { return fmt.Errorf("deleting expired ECH config: %v", err) } ech.configs[publicName] = append(ech.configs[publicName][:i], ech.configs[publicName][i+1:]...) i-- logger.Debug("deleted expired ECH key", zap.String("public_name", cfg.RawPublicName), zap.Uint8("id", cfg.ConfigID), zap.Duration("age", time.Since(cfg.meta.Created))) } } } ech.updateKeyList() return nil } // rotationNeeded returns true if any ECH key needs to be replaced, or deleted. // It must be called inside a read or write lock of ech.configsMu (probably a // write lock, so that the rotation can occur correctly in the same lock).) func (ech *ECH) rotationNeeded(rotationInterval, deleteAfter time.Duration) bool { for publicName := range ech.configs { for i := 0; i < len(ech.configs[publicName]); i++ { cfg := ech.configs[publicName][i] if (time.Since(cfg.meta.Created) >= rotationInterval && cfg.meta.Replaced.IsZero()) || (time.Since(cfg.meta.Created) >= deleteAfter && !cfg.meta.Replaced.IsZero()) { return true } } } return false } // updateKeyList updates the list of ECH keys the std lib uses to serve ECH. // It must be called inside a write lock on ech.configsMu. func (ech *ECH) updateKeyList() { ech.stdlibReady = []tls.EncryptedClientHelloKey{} for _, cfgs := range ech.configs { for _, cfg := range cfgs { ech.stdlibReady = append(ech.stdlibReady, tls.EncryptedClientHelloKey{ Config: cfg.configBin, PrivateKey: cfg.privKeyBin, SendAsRetry: cfg.meta.Replaced.IsZero(), // only send during retries if key has not been rotated out }) } } } // publishECHConfigs publishes any configs that are configured for publication and which haven't been published already. func (t *TLS) publishECHConfigs(logger *zap.Logger) error { // make publication exclusive, since we don't need to repeat this unnecessarily storage := t.ctx.Storage() const echLockName = "ech_publish" if err := storage.Lock(t.ctx, echLockName); err != nil { return err } defer func() { if err := storage.Unlock(t.ctx, echLockName); err != nil { logger.Error("unable to unlock ECH provisioning in storage", zap.Error(err)) } }() // get the publication config, or use a default if not specified // (the default publication config should be to publish all ECH // configs to the app-global DNS provider; if no DNS provider is // configured, then this whole function is basically a no-op) publicationList := t.EncryptedClientHello.Publication if publicationList == nil { if dnsProv, ok := t.dns.(ECHDNSProvider); ok { publicationList = []*ECHPublication{ { publishers: []ECHPublisher{ &ECHDNSPublisher{ provider: dnsProv, logger: logger, }, }, }, } } } // for each publication config, build the list of ECH configs to // publish with it, and figure out which inner names to publish // to/for, then publish for _, publication := range publicationList { t.EncryptedClientHello.configsMu.RLock() // this publication is either configured for specific ECH configs, // or we just use an implied default of all ECH configs var echCfgList echConfigList var configIDs []uint8 // TODO: use IDs or the outer names? if publication.Configs == nil { // by default, publish all configs for _, configs := range t.EncryptedClientHello.configs { echCfgList = append(echCfgList, configs...) for _, c := range configs { configIDs = append(configIDs, c.ConfigID) } } } else { for _, cfgOuterName := range publication.Configs { if cfgList, ok := t.EncryptedClientHello.configs[cfgOuterName]; ok { echCfgList = append(echCfgList, cfgList...) for _, c := range cfgList { configIDs = append(configIDs, c.ConfigID) } } } } t.EncryptedClientHello.configsMu.RUnlock() // marshal the ECH config list as binary for publication echCfgListBin, err := echCfgList.MarshalBinary() if err != nil { return fmt.Errorf("marshaling ECH config list: %v", err) } // now we have our list of ECH configs to publish and the inner names // to publish for (i.e. the names being protected); iterate each publisher // and do the publish for any config+name that needs a publish for _, publisher := range publication.publishers { publisherKey := publisher.PublisherKey() // by default, publish for all (non-outer) server names, unless // a specific list of names is configured var serverNamesSet map[string]struct{} if publication.Domains == nil { serverNamesSet = make(map[string]struct{}, len(t.serverNames)) for name := range t.serverNames { serverNamesSet[name] = struct{}{} } } else { serverNamesSet = make(map[string]struct{}, len(publication.Domains)) for _, name := range publication.Domains { serverNamesSet[name] = struct{}{} } } // remove any domains from the set which have already had all configs in the // list published by this publisher, to avoid always re-publishing unnecessarily for configuredInnerName := range serverNamesSet { allConfigsPublished := true for _, cfg := range echCfgList { // TODO: Potentially utilize the timestamp (map value) for recent-enough publication, instead of just checking for existence if _, ok := cfg.meta.Publications[publisherKey][configuredInnerName]; !ok { allConfigsPublished = false break } } if allConfigsPublished { delete(serverNamesSet, configuredInnerName) } } // if all the (inner) domains have had this ECH config list published // by this publisher, then try the next publication config if len(serverNamesSet) == 0 { logger.Debug("ECH config list already published by publisher for associated domains (or no domains to publish for)", zap.Uint8s("config_ids", configIDs), zap.String("publisher", publisherKey)) continue } // convert the set of names to a slice dnsNamesToPublish := make([]string, 0, len(serverNamesSet)) for name := range serverNamesSet { dnsNamesToPublish = append(dnsNamesToPublish, name) } logger.Debug("publishing ECH config list", zap.String("publisher", publisherKey), zap.Strings("domains", dnsNamesToPublish), zap.Uint8s("config_ids", configIDs)) // publish this ECH config list with this publisher pubTime := time.Now() err := publisher.PublishECHConfigList(t.ctx, dnsNamesToPublish, echCfgListBin) var publishErrs PublishECHConfigListErrors if errors.As(err, &publishErrs) { // at least a partial failure, maybe a complete failure, but we can // log each error by domain for innerName, domainErr := range publishErrs { logger.Error("failed to publish ECH configuration list", zap.String("publisher", publisherKey), zap.String("domain", innerName), zap.Uint8s("config_ids", configIDs), zap.Error(domainErr)) } } else if err != nil { // generic error; assume the entire thing failed, I guess logger.Error("failed publishing ECH configuration list", zap.String("publisher", publisherKey), zap.Strings("domains", dnsNamesToPublish), zap.Uint8s("config_ids", configIDs), zap.Error(err)) } if err == nil || (len(publishErrs) > 0 && len(publishErrs) < len(dnsNamesToPublish)) { // if publication for at least some domains succeeded, we should update our publication // state for those domains to avoid unnecessarily republishing every time someAll := "all" if len(publishErrs) > 0 { someAll = "some" } // make a list of names that published successfully with this publisher // so that we update only their state in storage, not the failed ones var successNames []string for _, name := range dnsNamesToPublish { if _, ok := publishErrs[name]; !ok { successNames = append(successNames, name) } } logger.Info("successfully published ECH configuration list for "+someAll+" domains", zap.String("publisher", publisherKey), zap.Strings("domains", successNames), zap.Uint8s("config_ids", configIDs)) for _, cfg := range echCfgList { if cfg.meta.Publications == nil { cfg.meta.Publications = make(publicationHistory) } if _, ok := cfg.meta.Publications[publisherKey]; !ok { cfg.meta.Publications[publisherKey] = make(map[string]time.Time) } for _, name := range successNames { cfg.meta.Publications[publisherKey][name] = pubTime } metaBytes, err := json.Marshal(cfg.meta) if err != nil { return fmt.Errorf("marshaling ECH config metadata: %v", err) } if err := t.ctx.Storage().Store(t.ctx, echMetaKey(cfg.ConfigID), metaBytes); err != nil { return fmt.Errorf("storing updated ECH config metadata: %v", err) } } } else { logger.Error("all domains failed to publish ECH configuration list (see earlier errors)", zap.String("publisher", publisherKey), zap.Strings("domains", dnsNamesToPublish), zap.Uint8s("config_ids", configIDs)) } } } return nil } // loadECHConfig loads the config from storage with the given configID. // An error is not actually returned in some cases the config fails to // load because in some cases it just means the config ID folder has // been cleaned up in storage, maybe due to an incomplete set of keys // or corrupted contents; in any case, the only rectification is to // delete it and make new keys (an error IS returned if deleting the // corrupted keys fails, for example). Check the returned echConfig for // non-nil privKeyBin and configBin values before using. func loadECHConfig(ctx caddy.Context, configID string) (echConfig, error) { storage := ctx.Storage() logger := ctx.Logger() cfgIDKey := path.Join(echConfigsKey, configID) keyKey := path.Join(cfgIDKey, "key.bin") configKey := path.Join(cfgIDKey, "config.bin") metaKey := path.Join(cfgIDKey, "meta.json") // if loading anything fails, might as well delete this folder and free up // the config ID; spec is designed to rotate configs frequently anyway // (I consider it a more serious error if we can't clean up the folder, // since leaving stray storage keys is confusing) privKeyBytes, err := storage.Load(ctx, keyKey) if err != nil { delErr := storage.Delete(ctx, cfgIDKey) if delErr != nil { return echConfig{}, fmt.Errorf("error loading private key (%v) and cleaning up parent storage key %s: %v", err, cfgIDKey, delErr) } logger.Warn("could not load ECH private key; deleting its config folder", zap.String("config_id", configID), zap.Error(err)) return echConfig{}, nil } echConfigBytes, err := storage.Load(ctx, configKey) if err != nil { delErr := storage.Delete(ctx, cfgIDKey) if delErr != nil { return echConfig{}, fmt.Errorf("error loading ECH config (%v) and cleaning up parent storage key %s: %v", err, cfgIDKey, delErr) } logger.Warn("could not load ECH config; deleting its config folder", zap.String("config_id", configID), zap.Error(err)) return echConfig{}, nil } var cfg echConfig if err := cfg.UnmarshalBinary(echConfigBytes); err != nil { delErr := storage.Delete(ctx, cfgIDKey) if delErr != nil { return echConfig{}, fmt.Errorf("error loading ECH config (%v) and cleaning up parent storage key %s: %v", err, cfgIDKey, delErr) } logger.Warn("could not load ECH config; deleted its config folder", zap.String("config_id", configID), zap.Error(err)) return echConfig{}, nil } metaBytes, err := storage.Load(ctx, metaKey) if errors.Is(err, fs.ErrNotExist) { logger.Warn("ECH config metadata file missing; will recreate at next publication", zap.String("config_id", configID), zap.Error(err)) } else if err != nil { delErr := storage.Delete(ctx, cfgIDKey) if delErr != nil { return echConfig{}, fmt.Errorf("error loading ECH config metadata (%v) and cleaning up parent storage key %s: %v", err, cfgIDKey, delErr) } logger.Warn("could not load ECH config metadata; deleted its folder", zap.String("config_id", configID), zap.Error(err)) return echConfig{}, nil } var meta echConfigMeta if len(metaBytes) > 0 { if err := json.Unmarshal(metaBytes, &meta); err != nil { // even though it's just metadata, reset the whole config since we can't reliably maintain it delErr := storage.Delete(ctx, cfgIDKey) if delErr != nil { return echConfig{}, fmt.Errorf("error decoding ECH metadata (%v) and cleaning up parent storage key %s: %v", err, cfgIDKey, delErr) } logger.Warn("could not JSON-decode ECH metadata; deleted its config folder", zap.String("config_id", configID), zap.Error(err)) return echConfig{}, nil } } cfg.privKeyBin = privKeyBytes cfg.configBin = echConfigBytes cfg.meta = meta return cfg, nil } func generateAndStoreECHConfig(ctx caddy.Context, publicName string) (echConfig, error) { // Go currently has very strict requirements for server-side ECH configs, // to quote the Go 1.24 godoc (with typos of AEAD IDs corrected): // // "Config should be a marshalled ECHConfig associated with PrivateKey. This // must match the config provided to clients byte-for-byte. The config // should only specify the DHKEM(X25519, HKDF-SHA256) KEM ID (0x0020), the // HKDF-SHA256 KDF ID (0x0001), and a subset of the following AEAD IDs: // AES-128-GCM (0x0001), AES-256-GCM (0x0002), ChaCha20Poly1305 (0x0003)." // // So we need to be sure we generate a config within these parameters // so the Go TLS server can use it. // generate a key pair const kemChoice = hpke.KEM_X25519_HKDF_SHA256 publicKey, privateKey, err := kemChoice.Scheme().GenerateKeyPair() if err != nil { return echConfig{}, err } // find an available config ID configID, err := newECHConfigID(ctx) if err != nil { return echConfig{}, fmt.Errorf("generating unique config ID: %v", err) } echCfg := echConfig{ PublicKey: publicKey, Version: draftTLSESNI25, ConfigID: configID, RawPublicName: publicName, KEMID: kemChoice, CipherSuites: []hpkeSymmetricCipherSuite{ { KDFID: hpke.KDF_HKDF_SHA256, AEADID: hpke.AEAD_AES128GCM, }, { KDFID: hpke.KDF_HKDF_SHA256, AEADID: hpke.AEAD_AES256GCM, }, { KDFID: hpke.KDF_HKDF_SHA256, AEADID: hpke.AEAD_ChaCha20Poly1305, }, }, } meta := echConfigMeta{ Created: time.Now(), } privKeyBytes, err := privateKey.MarshalBinary() if err != nil { return echConfig{}, fmt.Errorf("marshaling ECH private key: %v", err) } echConfigBytes, err := echCfg.MarshalBinary() if err != nil { return echConfig{}, fmt.Errorf("marshaling ECH config: %v", err) } metaBytes, err := json.Marshal(meta) if err != nil { return echConfig{}, fmt.Errorf("marshaling ECH config metadata: %v", err) } parentKey := path.Join(echConfigsKey, strconv.Itoa(int(configID))) keyKey := path.Join(parentKey, "key.bin") configKey := path.Join(parentKey, "config.bin") metaKey := path.Join(parentKey, "meta.json") if err := ctx.Storage().Store(ctx, keyKey, privKeyBytes); err != nil { return echConfig{}, fmt.Errorf("storing ECH private key: %v", err) } if err := ctx.Storage().Store(ctx, configKey, echConfigBytes); err != nil { return echConfig{}, fmt.Errorf("storing ECH config: %v", err) } if err := ctx.Storage().Store(ctx, metaKey, metaBytes); err != nil { return echConfig{}, fmt.Errorf("storing ECH config metadata: %v", err) } echCfg.privKeyBin = privKeyBytes echCfg.configBin = echConfigBytes // this contains the public key echCfg.meta = meta return echCfg, nil } // ECH represents an Encrypted ClientHello configuration. // // EXPERIMENTAL: Subject to change. type ECHConfiguration struct { // The public server name (SNI) that will be used in the outer ClientHello. // This should be a domain name for which this server is authoritative, // because Caddy will try to provision a certificate for this name. As an // outer SNI, it is never used for application data (HTTPS, etc.), but it // is necessary for enabling clients to connect securely in some cases. // If this field is empty or missing, or if Caddy cannot get a certificate // for this domain (e.g. the domain's DNS records do not point to this server), // client reliability becomes brittle, and you risk coercing clients to expose // true server names in plaintext, which compromises both the privacy of the // server and makes clients more vulnerable. PublicName string `json:"public_name"` } // ECHPublication configures publication of ECH config(s). It pairs a list // of ECH configs with the list of domains they are assigned to protect, and // describes how to publish those configs for those domains. // // Most servers will have only a single publication config, unless their // domains are spread across multiple DNS providers or require different // methods of publication. // // EXPERIMENTAL: Subject to change. type ECHPublication struct { // The list of ECH configurations to publish, identified by public name. // If not set, all configs will be included for publication by default. // // It is generally advised to maximize the size of your anonymity set, // which implies using as few public names as possible for your sites. // Usually, only a single public name is used to protect all the sites // for a server // // EXPERIMENTAL: This field may be renamed or have its structure changed. Configs []string `json:"configs,omitempty"` // The list of ("inner") domain names which are protected with the associated // ECH configurations. // // If not set, all server names registered with the TLS module will be // added to this list implicitly. (This registration is done automatically // by other Caddy apps that use the TLS module. They should register their // configured server names for this purpose. For example, the HTTP server // registers the hostnames for which it applies automatic HTTPS. This is // not something you, the user, have to do.) Most servers // // Names in this list should not appear in any other publication config // object with the same publishers, since the publications will likely // overwrite each other. // // NOTE: In order to publish ECH configs for domains configured for // On-Demand TLS that are not explicitly enumerated elsewhere in the // config, those domain names will have to be listed here. The only // time Caddy knows which domains it is serving with On-Demand TLS is // handshake-time, which is too late for publishing ECH configs; it // means the first connections would not protect the server names, // revealing that information to observers, and thus defeating the // purpose of ECH. Hence the need to list them here so Caddy can // proactively publish ECH configs before clients connect with those // server names in plaintext. Domains []string `json:"domains,omitempty"` // How to publish the ECH configurations so clients can know to use // ECH to connect more securely to the server. PublishersRaw caddy.ModuleMap `json:"publishers,omitempty" caddy:"namespace=tls.ech.publishers"` publishers []ECHPublisher } // ECHDNSProvider can service DNS entries for ECH purposes. type ECHDNSProvider interface { libdns.RecordGetter libdns.RecordSetter } // ECHDNSPublisher configures how to publish an ECH configuration to // DNS records for the specified domains. // // EXPERIMENTAL: Subject to change. type ECHDNSPublisher struct { // The DNS provider module which will establish the HTTPS record(s). ProviderRaw json.RawMessage `json:"provider,omitempty" caddy:"namespace=dns.providers inline_key=name"` provider ECHDNSProvider logger *zap.Logger } // CaddyModule returns the Caddy module information. func (ECHDNSPublisher) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "tls.ech.publishers.dns", New: func() caddy.Module { return new(ECHDNSPublisher) }, } } func (dnsPub *ECHDNSPublisher) Provision(ctx caddy.Context) error { dnsProvMod, err := ctx.LoadModule(dnsPub, "ProviderRaw") if err != nil { return fmt.Errorf("loading ECH DNS provider module: %v", err) } prov, ok := dnsProvMod.(ECHDNSProvider) if !ok { return fmt.Errorf("ECH DNS provider module is not an ECH DNS Provider: %v", err) } dnsPub.provider = prov dnsPub.logger = ctx.Logger() return nil } // PublisherKey returns the name of the DNS provider module. // We intentionally omit specific provider configuration (or a hash thereof, // since the config is likely sensitive, potentially containing an API key) // because it is unlikely that specific configuration, such as an API key, // is relevant to unique key use as an ECH config publisher. func (dnsPub ECHDNSPublisher) PublisherKey() string { return string(dnsPub.provider.(caddy.Module).CaddyModule().ID) } // PublishECHConfigList publishes the given ECH config list (as binary) to the given DNS names. // If there is an error, it may be of type PublishECHConfigListErrors, detailing // potentially multiple errors keyed by associated innerName. func (dnsPub *ECHDNSPublisher) PublishECHConfigList(ctx context.Context, innerNames []string, configListBin []byte) error { nameservers := certmagic.RecursiveNameservers(nil) // TODO: we could make resolvers configurable errs := make(PublishECHConfigListErrors) nextName: for _, domain := range innerNames { zone, err := certmagic.FindZoneByFQDN(ctx, dnsPub.logger, domain, nameservers) if err != nil { errs[domain] = fmt.Errorf("could not determine zone for domain: %w (domain=%s nameservers=%v)", err, domain, nameservers) continue } relName := libdns.RelativeName(domain+".", zone) // get existing records for this domain; we need to make sure another // record exists for it so we don't accidentally trample a wildcard; we // also want to get any HTTPS record that may already exist for it so // we can augment the ech SvcParamKey with any other existing SvcParams recs, err := dnsPub.provider.GetRecords(ctx, zone) if err != nil { errs[domain] = fmt.Errorf("unable to get existing DNS records to publish ECH data to HTTPS DNS record: %w", err) continue } var httpsRec libdns.ServiceBinding var nameHasExistingRecord bool for _, rec := range recs { rr := rec.RR() if rr.Name == relName { // CNAME records are exclusive of all other records, so we cannot publish an HTTPS // record for a domain that is CNAME'd. See #6922. if rr.Type == "CNAME" { dnsPub.logger.Warn("domain has CNAME record, so unable to publish ECH data to HTTPS record",
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
true
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/leafpemloader_test.go
modules/caddytls/leafpemloader_test.go
package caddytls import ( "context" "encoding/pem" "os" "strings" "testing" "github.com/caddyserver/caddy/v2" ) func TestLeafPEMLoader(t *testing.T) { pl := LeafPEMLoader{Certificates: []string{` -----BEGIN CERTIFICATE----- MIICUTCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADBXMQswCQYDVQQGEwJDTjEL MAkGA1UECBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMC VU4xFDASBgNVBAMTC0hlcm9uZyBZYW5nMB4XDTA1MDcxNTIxMTk0N1oXDTA1MDgx NDIxMTk0N1owVzELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlBOMQswCQYDVQQHEwJD TjELMAkGA1UEChMCT04xCzAJBgNVBAsTAlVOMRQwEgYDVQQDEwtIZXJvbmcgWWFu ZzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCp5hnG7ogBhtlynpOS21cBewKE/B7j V14qeyslnr26xZUsSVko36ZnhiaO/zbMOoRcKK9vEcgMtcLFuQTWDl3RAgMBAAGj gbEwga4wHQYDVR0OBBYEFFXI70krXeQDxZgbaCQoR4jUDncEMH8GA1UdIwR4MHaA FFXI70krXeQDxZgbaCQoR4jUDncEoVukWTBXMQswCQYDVQQGEwJDTjELMAkGA1UE CBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMCVU4xFDAS BgNVBAMTC0hlcm9uZyBZYW5nggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEE BQADQQA/ugzBrjjK9jcWnDVfGHlk3icNRq0oV7Ri32z/+HQX67aRfgZu7KWdI+Ju Wm7DCfrPNGVwFWUQOmsPue9rZBgO -----END CERTIFICATE----- `}} pl.Provision(caddy.Context{Context: context.Background()}) out, err := pl.LoadLeafCertificates() if err != nil { t.Errorf("Leaf certs pem loading test failed: %v", err) } if len(out) != 1 { t.Errorf("Error loading leaf cert in memory struct") return } pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: out[0].Raw}) pemFileBytes, err := os.ReadFile("../../caddytest/leafcert.pem") if err != nil { t.Errorf("Unable to read the example certificate from the file") } // Remove /r because windows. pemFileString := strings.ReplaceAll(string(pemFileBytes), "\r\n", "\n") if string(pemBytes) != pemFileString { t.Errorf("Leaf Certificate Folder Loader: Failed to load the correct certificate") } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/certmanagers.go
modules/caddytls/certmanagers.go
package caddytls import ( "context" "crypto/tls" "fmt" "io" "net" "net/http" "net/url" "strings" "github.com/caddyserver/certmagic" "github.com/tailscale/tscert" "go.uber.org/zap" "go.uber.org/zap/zapcore" "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 { if c := ts.logger.Check(zapcore.WarnLevel, "could not get status; will try to get certificate anyway"); c != nil { c.Write(zap.Error(err)) } } return tscert.GetCertificateWithContext(ctx, 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 { d.Next() // consume cert manager name 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. // // To indicate that this manager is not managing a certificate for // the described handshake, the endpoint should return HTTP 204 // (No Content). Error statuses will indicate that the manager is // capable of providing a certificate but was unable to. 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, ",")) localIP, _, err := net.SplitHostPort(hello.Conn.LocalAddr().String()) if err == nil && localIP != "" { qs.Set("local_ip", localIP) } 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.StatusNoContent { // endpoint is not managing certs for this handshake return nil, nil } 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 { d.Next() // consume cert manager name if !d.NextArg() { return d.ArgErr() } hcg.URL = d.Val() if d.NextArg() { return d.ArgErr() } if d.NextBlock(0) { 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/tls.go
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" "net/http" "runtime/debug" "strings" "sync" "time" "github.com/caddyserver/certmagic" "github.com/libdns/libdns" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/internal" "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, including subdomains that may // already be covered by a managed wildcard certificate. // The first matching automation policy will be used // to manage automated 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"` // Disables checks in certmagic that the configured storage is ready // and able to handle writing new content to it. These checks are // intended to prevent information loss (newly issued certificates), but // can be expensive on the storage. // // Disabling these checks should only be done when the storage // can be trusted to have enough capacity and no other problems. // // EXPERIMENTAL. Subject to change. DisableStorageCheck bool `json:"disable_storage_check,omitempty"` // Disables the automatic cleanup of the storage backend. // This is useful when TLS is not being used to store certificates // and the user wants run their server in a read-only mode. // // Storage cleaning creates two files: instance.uuid and last_clean.json. // The instance.uuid file is used to identify the instance of Caddy // in a cluster. The last_clean.json file is used to store the last // time the storage was cleaned. // // EXPERIMENTAL. Subject to change. DisableStorageClean bool `json:"disable_storage_clean,omitempty"` // Enable Encrypted ClientHello (ECH). ECH protects the server name // (SNI) and other sensitive parameters of a normally-plaintext TLS // ClientHello during a handshake. // // EXPERIMENTAL: Subject to change. EncryptedClientHello *ECH `json:"encrypted_client_hello,omitempty"` // The default DNS provider module to use when a DNS module is needed. // // EXPERIMENTAL: Subject to change. DNSRaw json.RawMessage `json:"dns,omitempty" caddy:"namespace=dns.providers inline_key=name"` dns any // technically, it should be any/all of the libdns interfaces (RecordSetter, RecordAppender, etc.) certificateLoaders []CertificateLoader automateNames map[string]struct{} ctx caddy.Context storageCleanTicker *time.Ticker storageCleanStop chan struct{} logger *zap.Logger events *caddyevents.App serverNames map[string]struct{} serverNamesMu *sync.Mutex // set of subjects with managed certificates, // and hashes of manually-loaded certificates // (managing's value is an optional issuer key, for distinction) managing, loaded map[string]string } // 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]string), make(map[string]string) t.serverNames = make(map[string]struct{}) t.serverNamesMu = new(sync.Mutex) // set up default DNS module, if any, and make sure it implements all the // common libdns interfaces, since it could be used for a variety of things // (do this before provisioning other modules, since they may rely on this) if len(t.DNSRaw) > 0 { dnsMod, err := ctx.LoadModule(t, "DNSRaw") if err != nil { return fmt.Errorf("loading overall DNS provider module: %v", err) } switch dnsMod.(type) { case interface { libdns.RecordAppender libdns.RecordDeleter libdns.RecordGetter libdns.RecordSetter }: default: return fmt.Errorf("DNS module does not implement the most common libdns interfaces: %T", dnsMod) } t.dns = dnsMod } // 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 { if t.automateNames == nil { t.automateNames = make(map[string]struct{}) } repl := caddy.NewReplacer() for _, sub := range *automateNames { t.automateNames[repl.ReplaceAll(sub, "")] = struct{}{} } } else { return fmt.Errorf("loading certificates with 'automate' requires array of strings, got: %T", modIface) } continue } t.certificateLoaders = append(t.certificateLoaders, modIface.(CertificateLoader)) } // using the certificate loaders we just initialized, 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, }, DisableStorageCheck: t.DisableStorageCheck, }) 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] = "" } } // on-demand permission module if t.Automation != nil && t.Automation.OnDemand != nil && t.Automation.OnDemand.PermissionRaw != nil { if t.Automation.OnDemand.Ask != "" { return fmt.Errorf("on-demand TLS config conflict: both 'ask' endpoint and a 'permission' module are specified; 'ask' is deprecated, so use only the permission module") } val, err := ctx.LoadModule(t.Automation.OnDemand, "PermissionRaw") if err != nil { return fmt.Errorf("loading on-demand TLS permission module: %v", err) } t.Automation.OnDemand.permission = val.(OnDemandPermission) } // 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) } } // 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) } perm := PermissionByHTTP{ Endpoint: t.Automation.OnDemand.Ask, } if err := perm.Provision(ctx); err != nil { return fmt.Errorf("provisioning 'ask' module: %v", err) } t.Automation.OnDemand.permission = perm } // 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) } } // ECH (Encrypted ClientHello) initialization if t.EncryptedClientHello != nil { outerNames, err := t.EncryptedClientHello.Provision(ctx) if err != nil { return fmt.Errorf("provisioning Encrypted ClientHello components: %v", err) } // outer names should have certificates to reduce client brittleness for _, outerName := range outerNames { if outerName == "" { continue } if !t.HasCertificateForSubject(outerName) { if t.automateNames == nil { t.automateNames = make(map[string]struct{}) } t.automateNames[outerName] = 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.permission == nil) { for _, ap := range t.Automation.Policies { if ap.OnDemand && ap.isWildcardOrDefault() { if c := t.logger.Check(zapcore.WarnLevel, "YOUR SERVER MAY BE VULNERABLE TO ABUSE: on-demand TLS is enabled, but no protections are in place"); c != nil { c.Write(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) } if t.EncryptedClientHello != nil { echLogger := t.logger.Named("ech") // publish ECH configs in the background; does not need to block // server startup, as it could take a while; then keep keys rotated go func() { // publish immediately first if err := t.publishECHConfigs(echLogger); err != nil { echLogger.Error("publication(s) failed", zap.Error(err)) } // then every so often, rotate and publish if needed // (both of these functions only do something if needed) for { select { case <-time.After(1 * time.Hour): // ensure old keys are rotated out t.EncryptedClientHello.configsMu.Lock() err = t.EncryptedClientHello.rotateECHKeys(t.ctx, echLogger, false) t.EncryptedClientHello.configsMu.Unlock() if err != nil { echLogger.Error("rotating ECH configs failed", zap.Error(err)) return } err := t.publishECHConfigs(echLogger) if err != nil { echLogger.Error("publication(s) failed", zap.Error(err)) } case <-t.ctx.Done(): return } } }() } if !t.DisableStorageClean { // start the storage cleaner goroutine and ticker, // which cleans out expired certificates and more 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, err := caddy.ActiveContext().AppIfConfigured("tls"); err == nil && 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 []certmagic.SubjectIssuer var noLongerLoaded []string reManage := make(map[string]struct{}) for subj, currentIssuerKey := range t.managing { // It's a bit nuanced: managed certs can sometimes be different enough that we have to // swap them out for a different one, even if they are for the same subject/domain. // We consider "private" certs (internal CA/locally-trusted/etc) to be significantly // distinct from "public" certs (production CAs/globally-trusted/etc) because of the // implications when it comes to actual deployments: switching between an internal CA // and a production CA, for example, is quite significant. Switching from one public CA // to another, however, is not, and for our purposes we consider those to be the same. // Anyway, if the next TLS app does not manage a cert for this name at all, definitely // remove it from the cache. But if it does, and it's not the same kind of issuer/CA // as we have, also remove it, so that it can swap it out for the right one. if nextIssuerKey, ok := nextTLSApp.managing[subj]; !ok || nextIssuerKey != currentIssuerKey { // next app is not managing a cert for this domain at all or is using a different issuer, so remove it noLongerManaged = append(noLongerManaged, certmagic.SubjectIssuer{Subject: subj, IssuerKey: currentIssuerKey}) // then, if the next app is managing a cert for this name, but with a different issuer, re-manage it if ok && nextIssuerKey != currentIssuerKey { reManage[subj] = struct{}{} } } } for hash := range t.loaded { if _, ok := nextTLSApp.loaded[hash]; !ok { noLongerLoaded = append(noLongerLoaded, hash) } } // remove the certs certCacheMu.RLock() certCache.RemoveManaged(noLongerManaged) certCache.Remove(noLongerLoaded) certCacheMu.RUnlock() // give the new TLS app a "kick" to manage certs that it is configured for // with its own configuration instead of the one we just evicted if err := nextTLSApp.Manage(reManage); err != nil { if c := t.logger.Check(zapcore.ErrorLevel, "re-managing unloaded certificates with new config"); c != nil { c.Write( zap.Strings("subjects", internal.MaxSizeSubjectsListForLog(reManage, 1000)), zap.Error(err), ) } } } else { // no more TLS app running, so delete in-memory cert cache, if it was created yet certCacheMu.RLock() hasCache := certCache != nil certCacheMu.RUnlock() if hasCache { certCache.Stop() certCacheMu.Lock() certCache = nil certCacheMu.Unlock() } } return nil } // Manage immediately begins managing subjects according to the // matching automation policy. The subjects are given in a map // to prevent duplication and also because quick lookups are // needed to assess wildcard coverage, if any, depending on // certain config parameters (with lots of subjects, computing // wildcard coverage over a slice can be highly inefficient). func (t *TLS) Manage(subjects map[string]struct{}) 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 subj := range subjects { ap := t.getAutomationPolicyForName(subj) // by default, if a wildcard that covers the subj is also being // managed, either by a previous call to Manage or by this one, // prefer using that over individual certs for its subdomains; // but users can disable this and force getting a certificate for // subdomains by adding the name to the 'automate' cert loader if t.managingWildcardFor(subj, subjects) { if _, ok := t.automateNames[subj]; !ok { continue } } policyToNames[ap] = append(policyToNames[ap], subj) } // 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 { const maxNamesToDisplay = 100 if len(names) > maxNamesToDisplay { names = append(names[:maxNamesToDisplay], fmt.Sprintf("(and %d more...)", len(names)-maxNamesToDisplay)) } return fmt.Errorf("automate: manage %v: %v", names, err) } for _, name := range names { // certs that are issued solely by our internal issuer are a little bit of // a special case: if you have an initial config that manages example.com // using internal CA, then after testing it you switch to a production CA, // you wouldn't want to keep using the same self-signed cert, obviously; // so we differentiate these by associating the subject with its issuer key; // we do this because CertMagic has no notion of "InternalIssuer" like we // do, so we have to do this logic ourselves var issuerKey string if len(ap.Issuers) == 1 { if intIss, ok := ap.Issuers[0].(*InternalIssuer); ok && intIss != nil { issuerKey = intIss.IssuerKey() } } t.managing[name] = issuerKey } } return nil } // managingWildcardFor returns true if the app is managing a certificate that covers that // subject name (including consideration of wildcards), either from its internal list of // names that it IS managing certs for, or from the otherSubjsToManage which includes names // that WILL be managed. func (t *TLS) managingWildcardFor(subj string, otherSubjsToManage map[string]struct{}) bool { // TODO: we could also consider manually-loaded certs using t.HasCertificateForSubject(), // but that does not account for how manually-loaded certs may be restricted as to which // hostnames or ClientHellos they can be used with by tags, etc; I don't *think* anyone // necessarily wants this anyway, but I thought I'd note this here for now (if we did // consider manually-loaded certs, we'd probably want to rename the method since it // wouldn't be just about managed certs anymore) // IP addresses must match exactly if ip := net.ParseIP(subj); ip != nil { _, managing := t.managing[subj] return managing } // replace labels of the domain with wildcards until we get a match labels := strings.Split(subj, ".") for i := range labels { if labels[i] == "*" { continue } labels[i] = "*" candidate := strings.Join(labels, ".") if _, ok := t.managing[candidate]; ok { return true } if _, ok := otherSubjsToManage[candidate]; ok { return true } } return false } // RegisterServerNames registers the provided DNS names with the TLS app. // This is currently used to auto-publish Encrypted ClientHello (ECH) // configurations, if enabled. Use of this function by apps using the TLS // app removes the need for the user to redundantly specify domain names // in their configuration. This function separates hostname and port // (keeping only the hotsname) and filters IP addresses, which can't be // used with ECH. // // EXPERIMENTAL: This function and its semantics/behavior are subject to change. func (t *TLS) RegisterServerNames(dnsNames []string) { t.serverNamesMu.Lock() for _, name := range dnsNames { host, _, err := net.SplitHostPort(name) if err != nil { host = name } if strings.TrimSpace(host) != "" && !certmagic.SubjectIsIP(host) { t.serverNames[strings.ToLower(host)] = struct{}{} } } t.serverNamesMu.Unlock() } // HandleHTTPChallenge ensures that the ACME HTTP challenge or ZeroSSL HTTP // validation request 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 that implements GetACMEIssuer() or is a *ZeroSSLIssuer. func (t *TLS) HandleHTTPChallenge(w http.ResponseWriter, r *http.Request) bool { acmeChallenge := certmagic.LooksLikeHTTPChallenge(r) zerosslValidation := certmagic.LooksLikeZeroSSLHTTPValidation(r) // no-op if it's not an ACME challenge request if !acmeChallenge && !zerosslValidation { return false } // try all the issuers until we find the one that initiated the challenge ap := t.getAutomationPolicyForName(r.Host) if acmeChallenge { type acmeCapable interface{ GetACMEIssuer() *ACMEIssuer } for _, iss := range ap.magic.Issuers { if acmeIssuer, ok := iss.(acmeCapable); ok { if acmeIssuer.GetACMEIssuer().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) } } else if zerosslValidation { for _, iss := range ap.magic.Issuers { if ziss, ok := iss.(*ZeroSSLIssuer); ok { if ziss.issuer.HandleZeroSSLHTTPValidation(w, r) { return true } } } } 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() // TODO: This check might not be needed anymore now that CertMagic syncs // and throttles storage cleaning globally across the cluster. // The original comment below might be outdated: // // 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 } id, err := caddy.InstanceID() if err != nil { if c := t.logger.Check(zapcore.WarnLevel, "unable to get instance ID; storage clean stamps will be incomplete"); c != nil { c.Write(zap.Error(err)) } } options := certmagic.CleanStorageOptions{ Logger: t.logger, InstanceID: id.String(), Interval: t.storageCleanInterval(), OCSPStaples: true, ExpiredCerts: true, ExpiredCertGracePeriod: 24 * time.Hour * 14, } // start with the default/global storage err = certmagic.CleanStorage(t.ctx, t.ctx.Storage(), options) if err != nil { // probably don't want to return early, since we should still // see if any other storages can get cleaned up if c := t.logger.Check(zapcore.ErrorLevel, "could not clean default/global storage"); c != nil { c.Write(zap.Error(err)) } } // then clean each storage defined in ACME automation policies if t.Automation != nil { for _, ap := range t.Automation.Policies { if ap.storage == nil { continue } if err := certmagic.CleanStorage(t.ctx, ap.storage, options); err != nil { if c := t.logger.Check(zapcore.ErrorLevel, "could not clean storage configured in automation policy"); c != nil { c.Write(zap.Error(err)) } } } } // 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.
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
true
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/capools_test.go
modules/caddytls/capools_test.go
package caddytls import ( "encoding/json" "fmt" "reflect" "testing" "time" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" _ "github.com/caddyserver/caddy/v2/modules/filestorage" ) const ( test_der_1 = `MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ==` test_cert_file_1 = "../../caddytest/caddy.ca.cer" ) func TestInlineCAPoolUnmarshalCaddyfile(t *testing.T) { type args struct { d *caddyfile.Dispenser } tests := []struct { name string args args expected InlineCAPool wantErr bool }{ { name: "configuring no certificatest produces an error", args: args{ d: caddyfile.NewTestDispenser(` inline { } `), }, wantErr: true, }, { name: "configuring certificates as arguments in-line produces an error", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` inline %s `, test_der_1)), }, wantErr: true, }, { name: "single cert", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` inline { trust_der %s } `, test_der_1)), }, expected: InlineCAPool{ TrustedCACerts: []string{test_der_1}, }, wantErr: false, }, { name: "multiple certs in one line", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` inline { trust_der %s %s } `, test_der_1, test_der_1), ), }, expected: InlineCAPool{ TrustedCACerts: []string{test_der_1, test_der_1}, }, }, { name: "multiple certs in multiple lines", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` inline { trust_der %s trust_der %s } `, test_der_1, test_der_1)), }, expected: InlineCAPool{ TrustedCACerts: []string{test_der_1, test_der_1}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { icp := &InlineCAPool{} if err := icp.UnmarshalCaddyfile(tt.args.d); (err != nil) != tt.wantErr { t.Errorf("InlineCAPool.UnmarshalCaddyfile() error = %v, wantErr %v", err, tt.wantErr) } if !tt.wantErr && !reflect.DeepEqual(&tt.expected, icp) { t.Errorf("InlineCAPool.UnmarshalCaddyfile() = %v, want %v", icp, tt.expected) } }) } } func TestFileCAPoolUnmarshalCaddyfile(t *testing.T) { type args struct { d *caddyfile.Dispenser } tests := []struct { name string expected FileCAPool args args wantErr bool }{ { name: "configuring no certificatest produces an error", args: args{ d: caddyfile.NewTestDispenser(` file { } `), }, wantErr: true, }, { name: "configuring certificates as arguments in-line produces an error", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` file %s `, test_cert_file_1)), }, expected: FileCAPool{ TrustedCACertPEMFiles: []string{test_cert_file_1}, }, }, { name: "single cert", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` file { pem_file %s } `, test_cert_file_1)), }, expected: FileCAPool{ TrustedCACertPEMFiles: []string{test_cert_file_1}, }, wantErr: false, }, { name: "multiple certs inline and in-block are merged", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` file %s { pem_file %s } `, test_cert_file_1, test_cert_file_1)), }, expected: FileCAPool{ TrustedCACertPEMFiles: []string{test_cert_file_1, test_cert_file_1}, }, wantErr: false, }, { name: "multiple certs in one line", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` file { pem_file %s %s } `, test_der_1, test_der_1), ), }, expected: FileCAPool{ TrustedCACertPEMFiles: []string{test_der_1, test_der_1}, }, }, { name: "multiple certs in multiple lines", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(` file { pem_file %s pem_file %s } `, test_cert_file_1, test_cert_file_1)), }, expected: FileCAPool{ TrustedCACertPEMFiles: []string{test_cert_file_1, test_cert_file_1}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { fcap := &FileCAPool{} if err := fcap.UnmarshalCaddyfile(tt.args.d); (err != nil) != tt.wantErr { t.Errorf("FileCAPool.UnmarshalCaddyfile() error = %v, wantErr %v", err, tt.wantErr) } if !tt.wantErr && !reflect.DeepEqual(&tt.expected, fcap) { t.Errorf("FileCAPool.UnmarshalCaddyfile() = %v, want %v", fcap, tt.expected) } }) } } func TestPKIRootCAPoolUnmarshalCaddyfile(t *testing.T) { type args struct { d *caddyfile.Dispenser } tests := []struct { name string expected PKIRootCAPool args args wantErr bool }{ { name: "configuring no certificatest produces an error", args: args{ d: caddyfile.NewTestDispenser(` pki_root { } `), }, wantErr: true, }, { name: "single authority as arguments in-line", args: args{ d: caddyfile.NewTestDispenser(` pki_root ca_1 `), }, expected: PKIRootCAPool{ Authority: []string{"ca_1"}, }, }, { name: "multiple authorities as arguments in-line", args: args{ d: caddyfile.NewTestDispenser(` pki_root ca_1 ca_2 `), }, expected: PKIRootCAPool{ Authority: []string{"ca_1", "ca_2"}, }, }, { name: "single authority in block", args: args{ d: caddyfile.NewTestDispenser(` pki_root { authority ca_1 }`), }, expected: PKIRootCAPool{ Authority: []string{"ca_1"}, }, wantErr: false, }, { name: "multiple authorities in one line", args: args{ d: caddyfile.NewTestDispenser(` pki_root { authority ca_1 ca_2 }`), }, expected: PKIRootCAPool{ Authority: []string{"ca_1", "ca_2"}, }, }, { name: "multiple authorities in multiple lines", args: args{ d: caddyfile.NewTestDispenser(` pki_root { authority ca_1 authority ca_2 }`), }, expected: PKIRootCAPool{ Authority: []string{"ca_1", "ca_2"}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { pkir := &PKIRootCAPool{} if err := pkir.UnmarshalCaddyfile(tt.args.d); (err != nil) != tt.wantErr { t.Errorf("PKIRootCAPool.UnmarshalCaddyfile() error = %v, wantErr %v", err, tt.wantErr) } if !tt.wantErr && !reflect.DeepEqual(&tt.expected, pkir) { t.Errorf("PKIRootCAPool.UnmarshalCaddyfile() = %v, want %v", pkir, tt.expected) } }) } } func TestPKIIntermediateCAPoolUnmarshalCaddyfile(t *testing.T) { type args struct { d *caddyfile.Dispenser } tests := []struct { name string expected PKIIntermediateCAPool args args wantErr bool }{ { name: "configuring no certificatest produces an error", args: args{ d: caddyfile.NewTestDispenser(` pki_intermediate { }`), }, wantErr: true, }, { name: "single authority as arguments in-line", args: args{ d: caddyfile.NewTestDispenser(`pki_intermediate ca_1`), }, expected: PKIIntermediateCAPool{ Authority: []string{"ca_1"}, }, }, { name: "multiple authorities as arguments in-line", args: args{ d: caddyfile.NewTestDispenser(`pki_intermediate ca_1 ca_2`), }, expected: PKIIntermediateCAPool{ Authority: []string{"ca_1", "ca_2"}, }, }, { name: "single authority in block", args: args{ d: caddyfile.NewTestDispenser(` pki_intermediate { authority ca_1 }`), }, expected: PKIIntermediateCAPool{ Authority: []string{"ca_1"}, }, wantErr: false, }, { name: "multiple authorities in one line", args: args{ d: caddyfile.NewTestDispenser(` pki_intermediate { authority ca_1 ca_2 }`), }, expected: PKIIntermediateCAPool{ Authority: []string{"ca_1", "ca_2"}, }, }, { name: "multiple authorities in multiple lines", args: args{ d: caddyfile.NewTestDispenser(` pki_intermediate { authority ca_1 authority ca_2 }`), }, expected: PKIIntermediateCAPool{ Authority: []string{"ca_1", "ca_2"}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { pic := &PKIIntermediateCAPool{} if err := pic.UnmarshalCaddyfile(tt.args.d); (err != nil) != tt.wantErr { t.Errorf("PKIIntermediateCAPool.UnmarshalCaddyfile() error = %v, wantErr %v", err, tt.wantErr) } if !tt.wantErr && !reflect.DeepEqual(&tt.expected, pic) { t.Errorf("PKIIntermediateCAPool.UnmarshalCaddyfile() = %v, want %v", pic, tt.expected) } }) } } func TestStoragePoolUnmarshalCaddyfile(t *testing.T) { type args struct { d *caddyfile.Dispenser } tests := []struct { name string args args expected StoragePool wantErr bool }{ { name: "empty block", args: args{ d: caddyfile.NewTestDispenser(`storage { }`), }, expected: StoragePool{}, wantErr: false, }, { name: "providing single storage key inline", args: args{ d: caddyfile.NewTestDispenser(`storage key-1`), }, expected: StoragePool{ PEMKeys: []string{"key-1"}, }, wantErr: false, }, { name: "providing multiple storage keys inline", args: args{ d: caddyfile.NewTestDispenser(`storage key-1 key-2`), }, expected: StoragePool{ PEMKeys: []string{"key-1", "key-2"}, }, wantErr: false, }, { name: "providing keys inside block without specifying storage type", args: args{ d: caddyfile.NewTestDispenser(` storage { keys key-1 key-2 } `), }, expected: StoragePool{ PEMKeys: []string{"key-1", "key-2"}, }, wantErr: false, }, { name: "providing keys in-line and inside block merges them", args: args{ d: caddyfile.NewTestDispenser(`storage key-1 key-2 key-3 { keys key-4 key-5 }`), }, expected: StoragePool{ PEMKeys: []string{"key-1", "key-2", "key-3", "key-4", "key-5"}, }, wantErr: false, }, { name: "specifying storage type in block", args: args{ d: caddyfile.NewTestDispenser(`storage { storage file_system /var/caddy/storage }`), }, expected: StoragePool{ StorageRaw: json.RawMessage(`{"module":"file_system","root":"/var/caddy/storage"}`), }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { sp := &StoragePool{} if err := sp.UnmarshalCaddyfile(tt.args.d); (err != nil) != tt.wantErr { t.Errorf("StoragePool.UnmarshalCaddyfile() error = %v, wantErr %v", err, tt.wantErr) } if !tt.wantErr && !reflect.DeepEqual(&tt.expected, sp) { t.Errorf("StoragePool.UnmarshalCaddyfile() = %s, want %s", sp.StorageRaw, tt.expected.StorageRaw) } }) } } func TestTLSConfig_unmarshalCaddyfile(t *testing.T) { type args struct { d *caddyfile.Dispenser } tests := []struct { name string args args expected TLSConfig wantErr bool }{ { name: "no arguments is valid", args: args{ d: caddyfile.NewTestDispenser(` { }`), }, expected: TLSConfig{}, }, { name: "setting 'renegotiation' to 'never' is valid", args: args{ d: caddyfile.NewTestDispenser(` { renegotiation never }`), }, expected: TLSConfig{ Renegotiation: "never", }, }, { name: "setting 'renegotiation' to 'once' is valid", args: args{ d: caddyfile.NewTestDispenser(` { renegotiation once }`), }, expected: TLSConfig{ Renegotiation: "once", }, }, { name: "setting 'renegotiation' to 'freely' is valid", args: args{ d: caddyfile.NewTestDispenser(` { renegotiation freely }`), }, expected: TLSConfig{ Renegotiation: "freely", }, }, { name: "setting 'renegotiation' to other than 'none', 'once, or 'freely' is invalid", args: args{ d: caddyfile.NewTestDispenser(` { renegotiation foo }`), }, wantErr: true, }, { name: "setting 'renegotiation' without argument is invalid", args: args{ d: caddyfile.NewTestDispenser(` { renegotiation }`), }, wantErr: true, }, { name: "setting 'ca' without argument is an error", args: args{ d: caddyfile.NewTestDispenser(`{ ca }`), }, wantErr: true, }, { name: "setting 'ca' to 'file' with in-line cert is valid", args: args{ d: caddyfile.NewTestDispenser(`{ ca file /var/caddy/ca.pem }`), }, expected: TLSConfig{ CARaw: []byte(`{"pem_files":["/var/caddy/ca.pem"],"provider":"file"}`), }, }, { name: "setting 'ca' to 'file' with appropriate block is valid", args: args{ d: caddyfile.NewTestDispenser(`{ ca file /var/caddy/ca.pem { pem_file /var/caddy/ca.pem } }`), }, expected: TLSConfig{ CARaw: []byte(`{"pem_files":["/var/caddy/ca.pem","/var/caddy/ca.pem"],"provider":"file"}`), }, }, { name: "setting 'ca' multiple times is an error", args: args{ d: caddyfile.NewTestDispenser(fmt.Sprintf(`{ ca file /var/caddy/ca.pem { pem_file /var/caddy/ca.pem } ca inline %s }`, test_der_1)), }, wantErr: true, }, { name: "setting 'handshake_timeout' without value is an error", args: args{ d: caddyfile.NewTestDispenser(`{ handshake_timeout }`), }, wantErr: true, }, { name: "setting 'handshake_timeout' properly is successful", args: args{ d: caddyfile.NewTestDispenser(`{ handshake_timeout 42m }`), }, expected: TLSConfig{ HandshakeTimeout: caddy.Duration(42 * time.Minute), }, }, { name: "setting 'server_name' without value is an error", args: args{ d: caddyfile.NewTestDispenser(`{ server_name }`), }, wantErr: true, }, { name: "setting 'server_name' properly is successful", args: args{ d: caddyfile.NewTestDispenser(`{ server_name example.com }`), }, expected: TLSConfig{ ServerName: "example.com", }, }, { name: "unsupported directives are errors", args: args{ d: caddyfile.NewTestDispenser(`{ foo }`), }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tr := &TLSConfig{} if err := tr.unmarshalCaddyfile(tt.args.d); (err != nil) != tt.wantErr { t.Errorf("TLSConfig.unmarshalCaddyfile() error = %v, wantErr %v", err, tt.wantErr) } if !tt.wantErr && !reflect.DeepEqual(&tt.expected, tr) { t.Errorf("TLSConfig.UnmarshalCaddyfile() = %v, want %v", tr, tt.expected) } }) } } func TestHTTPCertPoolUnmarshalCaddyfile(t *testing.T) { type args struct { d *caddyfile.Dispenser } tests := []struct { name string args args expected HTTPCertPool wantErr bool }{ { name: "no block, inline http endpoint", args: args{ d: caddyfile.NewTestDispenser(`http http://localhost/ca-certs`), }, expected: HTTPCertPool{ Endpoints: []string{"http://localhost/ca-certs"}, }, wantErr: false, }, { name: "no block, inline https endpoint", args: args{ d: caddyfile.NewTestDispenser(`http https://localhost/ca-certs`), }, expected: HTTPCertPool{ Endpoints: []string{"https://localhost/ca-certs"}, }, wantErr: false, }, { name: "no block, mixed http and https endpoints inline", args: args{ d: caddyfile.NewTestDispenser(`http http://localhost/ca-certs https://localhost/ca-certs`), }, expected: HTTPCertPool{ Endpoints: []string{"http://localhost/ca-certs", "https://localhost/ca-certs"}, }, wantErr: false, }, { name: "multiple endpoints in separate lines in block", args: args{ d: caddyfile.NewTestDispenser(` http { endpoints http://localhost/ca-certs endpoints http://remotehost/ca-certs } `), }, expected: HTTPCertPool{ Endpoints: []string{"http://localhost/ca-certs", "http://remotehost/ca-certs"}, }, wantErr: false, }, { name: "endpoints defined inline and in block are merged", args: args{ d: caddyfile.NewTestDispenser(`http http://localhost/ca-certs { endpoints http://remotehost/ca-certs }`), }, expected: HTTPCertPool{ Endpoints: []string{"http://localhost/ca-certs", "http://remotehost/ca-certs"}, }, wantErr: false, }, { name: "multiple endpoints defined in block on the same line", args: args{ d: caddyfile.NewTestDispenser(`http { endpoints http://remotehost/ca-certs http://localhost/ca-certs }`), }, expected: HTTPCertPool{ Endpoints: []string{"http://remotehost/ca-certs", "http://localhost/ca-certs"}, }, wantErr: false, }, { name: "declaring 'endpoints' in block without argument is an error", args: args{ d: caddyfile.NewTestDispenser(`http { endpoints }`), }, wantErr: true, }, { name: "multiple endpoints in separate lines in block", args: args{ d: caddyfile.NewTestDispenser(` http { endpoints http://localhost/ca-certs endpoints http://remotehost/ca-certs tls { renegotiation freely } } `), }, expected: HTTPCertPool{ Endpoints: []string{"http://localhost/ca-certs", "http://remotehost/ca-certs"}, TLS: &TLSConfig{ Renegotiation: "freely", }, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { hcp := &HTTPCertPool{} if err := hcp.UnmarshalCaddyfile(tt.args.d); (err != nil) != tt.wantErr { t.Errorf("HTTPCertPool.UnmarshalCaddyfile() error = %v, wantErr %v", err, tt.wantErr) } if !tt.wantErr && !reflect.DeepEqual(&tt.expected, hcp) { t.Errorf("HTTPCertPool.UnmarshalCaddyfile() = %v, want %v", hcp, tt.expected) } }) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/standardstek/stek.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddytls/distributedstek/distributedstek.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/logging/filewriter.go
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 ( "encoding/json" "fmt" "io" "math" "os" "path/filepath" "strconv" "strings" "time" "github.com/DeRuina/timberjack" "github.com/dustin/go-humanize" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(FileWriter{}) } // fileMode is a string made of 1 to 4 octal digits representing // a numeric mode as specified with the `chmod` unix command. // `"0777"` and `"777"` are thus equivalent values. type fileMode os.FileMode // UnmarshalJSON satisfies json.Unmarshaler. func (m *fileMode) UnmarshalJSON(b []byte) error { if len(b) == 0 { return io.EOF } var s string if err := json.Unmarshal(b, &s); err != nil { return err } mode, err := parseFileMode(s) if err != nil { return err } *m = fileMode(mode) return err } // MarshalJSON satisfies json.Marshaler. func (m *fileMode) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("\"%04o\"", *m)), nil } // parseFileMode parses a file mode string, // adding support for `chmod` unix command like // 1 to 4 digital octal values. func parseFileMode(s string) (os.FileMode, error) { modeStr := fmt.Sprintf("%04s", s) mode, err := strconv.ParseUint(modeStr, 8, 32) if err != nil { return 0, err } return os.FileMode(mode), nil } // 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"` // The file permissions mode. // 0600 by default. Mode fileMode `json:"mode,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"` // Roll log file after some time RollInterval time.Duration `json:"roll_interval,omitempty"` // Roll log file at fix minutes // For example []int{0, 30} will roll file at xx:00 and xx:30 each hour // Invalid value are ignored with a warning on stderr // See https://github.com/DeRuina/timberjack#%EF%B8%8F-rotation-notes--warnings for caveats RollAtMinutes []int `json:"roll_minutes,omitempty"` // Roll log file at fix time // For example []string{"00:00", "12:00"} will roll file at 00:00 and 12:00 each day // Invalid value are ignored with a warning on stderr // See https://github.com/DeRuina/timberjack#%EF%B8%8F-rotation-notes--warnings for caveats RollAt []string `json:"roll_at,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"` // Rotated file will have format <logfilename>-<format>-<criterion>.log // Optional. If unset or invalid, defaults to 2006-01-02T15-04-05.000 (with fallback warning) // <format> must be a Go time compatible format, see https://pkg.go.dev/time#pkg-constants BackupTimeFormat string `json:"backup_time_format,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 := caddy.FastAbs(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) { modeIfCreating := os.FileMode(fw.Mode) if modeIfCreating == 0 { modeIfCreating = 0o600 } // roll log files as a sensible default to avoid disk space exhaustion roll := fw.Roll == nil || *fw.Roll // create the file if it does not exist; create with the configured mode, or default // to restrictive if not set. (timberjack will reuse the file mode across log rotation) if err := os.MkdirAll(filepath.Dir(fw.Filename), 0o700); err != nil { return nil, err } file, err := os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, modeIfCreating) if err != nil { return nil, err } info, err := file.Stat() if roll { file.Close() // timberjack will reopen it on its own } // Ensure already existing files have the right mode, since OpenFile will not set the mode in such case. if configuredMode := os.FileMode(fw.Mode); configuredMode != 0 { if err != nil { return nil, fmt.Errorf("unable to stat log file to see if we need to set permissions: %v", err) } // only chmod if the configured mode is different if info.Mode()&os.ModePerm != configuredMode&os.ModePerm { if err = os.Chmod(fw.Filename, configuredMode); err != nil { return nil, err } } } // if not rolling, then the plain file handle is all we need if !roll { return file, nil } // otherwise, return a rolling log 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 &timberjack.Logger{ Filename: fw.Filename, MaxSize: fw.RollSizeMB, MaxAge: fw.RollKeepDays, MaxBackups: fw.RollKeep, LocalTime: fw.RollLocalTime, Compress: *fw.RollCompress, RotationInterval: fw.RollInterval, RotateAtMinutes: fw.RollAtMinutes, RotateAt: fw.RollAt, BackupTimeFormat: fw.BackupTimeFormat, }, nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // file <filename> { // mode <mode> // 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 mode, 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 { d.Next() // consume writer name if !d.NextArg() { return d.ArgErr() } fw.Filename = d.Val() if d.NextArg() { return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "mode": var modeStr string if !d.AllArgs(&modeStr) { return d.ArgErr() } mode, err := parseFileMode(modeStr) if err != nil { return d.Errf("parsing mode: %v", err) } fw.Mode = fileMode(mode) 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)) case "roll_interval": var durationStr string if !d.AllArgs(&durationStr) { return d.ArgErr() } duration, err := time.ParseDuration(durationStr) if err != nil { return d.Errf("parsing roll_interval duration: %v", err) } fw.RollInterval = duration case "roll_minutes": var minutesArrayStr string if !d.AllArgs(&minutesArrayStr) { return d.ArgErr() } minutesStr := strings.Split(minutesArrayStr, ",") minutes := make([]int, len(minutesStr)) for i := range minutesStr { ms := strings.Trim(minutesStr[i], " ") m, err := strconv.Atoi(ms) if err != nil { return d.Errf("parsing roll_minutes number: %v", err) } minutes[i] = m } fw.RollAtMinutes = minutes case "roll_at": var timeArrayStr string if !d.AllArgs(&timeArrayStr) { return d.ArgErr() } timeStr := strings.Split(timeArrayStr, ",") times := make([]string, len(timeStr)) for i := range timeStr { times[i] = strings.Trim(timeStr[i], " ") } fw.RollAt = times case "backup_time_format": var format string if !d.AllArgs(&format) { return d.ArgErr() } fw.BackupTimeFormat = format default: return d.Errf("unrecognized subdirective '%s'", d.Val()) } } return nil } // Interface guards var ( _ caddy.Provisioner = (*FileWriter)(nil) _ caddy.WriterOpener = (*FileWriter)(nil) _ caddyfile.Unmarshaler = (*FileWriter)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/logging/netwriter.go
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 { d.Next() // consume writer name if !d.NextArg() { return d.ArgErr() } nw.Address = d.Val() if d.NextArg() { return d.ArgErr() } for d.NextBlock(0) { 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 default: return d.Errf("unrecognized subdirective '%s'", d.Val()) } } 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 n, err } } // 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 n, err } } // 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 n, err } 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 n, err } 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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/logging/filters_test.go
modules/logging/filters_test.go
package logging import ( "fmt" "strings" "testing" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) 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 TestQueryFilterSingleValue(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 TestQueryFilterMultiValue(t *testing.T) { f := QueryFilter{ Actions: []queryFilterAction{ {Type: replaceAction, Parameter: "foo", Value: "REDACTED"}, {Type: replaceAction, Parameter: "notexist", Value: "REDACTED"}, {Type: deleteAction, Parameter: "bar"}, {Type: deleteAction, Parameter: "notexist"}, {Type: hashAction, Parameter: "hash"}, }, } if f.Validate() != nil { t.Fatalf("the filter must be valid") } out := f.Filter(zapcore.Field{Interface: caddyhttp.LoggableStringArray{ "/path1?foo=a&foo=b&bar=c&bar=d&baz=e&hash=hashed", "/path2?foo=c&foo=d&bar=e&bar=f&baz=g&hash=hashed", }}) arr, ok := out.Interface.(caddyhttp.LoggableStringArray) if !ok { t.Fatalf("field is wrong type: %T", out.Interface) } expected1 := "/path1?baz=e&foo=REDACTED&foo=REDACTED&hash=e3b0c442" expected2 := "/path2?baz=g&foo=REDACTED&foo=REDACTED&hash=e3b0c442" if arr[0] != expected1 { t.Fatalf("query parameters in entry 0 have not been filtered correctly: got %s, expected %s", arr[0], expected1) } if arr[1] != expected2 { t.Fatalf("query parameters in entry 1 have not been filtered correctly: got %s, expected %s", arr[1], expected2) } } 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]) } } func TestMultiRegexpFilterSingleOperation(t *testing.T) { f := MultiRegexpFilter{ Operations: []regexpFilterOperation{ {RawRegexp: `secret`, Value: "REDACTED"}, }, } err := f.Provision(caddy.Context{}) if err != nil { t.Fatalf("unexpected error provisioning: %v", err) } 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 TestMultiRegexpFilterMultipleOperations(t *testing.T) { f := MultiRegexpFilter{ Operations: []regexpFilterOperation{ {RawRegexp: `secret`, Value: "REDACTED"}, {RawRegexp: `password`, Value: "HIDDEN"}, {RawRegexp: `token`, Value: "XXX"}, }, } err := f.Provision(caddy.Context{}) if err != nil { t.Fatalf("unexpected error provisioning: %v", err) } // Test sequential application out := f.Filter(zapcore.Field{String: "my-secret-password-token-data"}) expected := "my-REDACTED-HIDDEN-XXX-data" if out.String != expected { t.Fatalf("field has not been filtered correctly: got %s, expected %s", out.String, expected) } } func TestMultiRegexpFilterMultiValue(t *testing.T) { f := MultiRegexpFilter{ Operations: []regexpFilterOperation{ {RawRegexp: `secret`, Value: "REDACTED"}, {RawRegexp: `\d+`, Value: "NUM"}, }, } err := f.Provision(caddy.Context{}) if err != nil { t.Fatalf("unexpected error provisioning: %v", err) } out := f.Filter(zapcore.Field{Interface: caddyhttp.LoggableStringArray{ "foo-secret-123", "bar-secret-456", }}) arr, ok := out.Interface.(caddyhttp.LoggableStringArray) if !ok { t.Fatalf("field is wrong type: %T", out.Interface) } if arr[0] != "foo-REDACTED-NUM" { t.Fatalf("field entry 0 has not been filtered: %s", arr[0]) } if arr[1] != "bar-REDACTED-NUM" { t.Fatalf("field entry 1 has not been filtered: %s", arr[1]) } } func TestMultiRegexpFilterAddOperation(t *testing.T) { f := MultiRegexpFilter{} err := f.AddOperation("secret", "REDACTED") if err != nil { t.Fatalf("unexpected error adding operation: %v", err) } err = f.AddOperation("password", "HIDDEN") if err != nil { t.Fatalf("unexpected error adding operation: %v", err) } err = f.Provision(caddy.Context{}) if err != nil { t.Fatalf("unexpected error provisioning: %v", err) } if len(f.Operations) != 2 { t.Fatalf("expected 2 operations, got %d", len(f.Operations)) } out := f.Filter(zapcore.Field{String: "my-secret-password"}) expected := "my-REDACTED-HIDDEN" if out.String != expected { t.Fatalf("field has not been filtered correctly: got %s, expected %s", out.String, expected) } } func TestMultiRegexpFilterSecurityLimits(t *testing.T) { f := MultiRegexpFilter{} // Test maximum operations limit for i := 0; i < 51; i++ { err := f.AddOperation(fmt.Sprintf("pattern%d", i), "replacement") if i < 50 { if err != nil { t.Fatalf("unexpected error adding operation %d: %v", i, err) } } else { if err == nil { t.Fatalf("expected error when adding operation %d (exceeds limit)", i) } } } // Test empty pattern validation f2 := MultiRegexpFilter{} err := f2.AddOperation("", "replacement") if err == nil { t.Fatalf("expected error for empty pattern") } // Test pattern length limit f3 := MultiRegexpFilter{} longPattern := strings.Repeat("a", 1001) err = f3.AddOperation(longPattern, "replacement") if err == nil { t.Fatalf("expected error for pattern exceeding length limit") } } func TestMultiRegexpFilterValidation(t *testing.T) { // Test validation with empty operations f := MultiRegexpFilter{} err := f.Validate() if err == nil { t.Fatalf("expected validation error for empty operations") } // Test validation with valid operations err = f.AddOperation("valid", "replacement") if err != nil { t.Fatalf("unexpected error adding operation: %v", err) } err = f.Provision(caddy.Context{}) if err != nil { t.Fatalf("unexpected error provisioning: %v", err) } err = f.Validate() if err != nil { t.Fatalf("unexpected validation error: %v", err) } } func TestMultiRegexpFilterInputSizeLimit(t *testing.T) { f := MultiRegexpFilter{ Operations: []regexpFilterOperation{ {RawRegexp: `test`, Value: "REPLACED"}, }, } err := f.Provision(caddy.Context{}) if err != nil { t.Fatalf("unexpected error provisioning: %v", err) } // Test with very large input (should be truncated) largeInput := strings.Repeat("test", 300000) // Creates ~1.2MB string out := f.Filter(zapcore.Field{String: largeInput}) // The input should be truncated to 1MB and still processed if len(out.String) > 1000000 { t.Fatalf("output string not truncated: length %d", len(out.String)) } // Should still contain replacements within the truncated portion if !strings.Contains(out.String, "REPLACED") { t.Fatalf("replacements not applied to truncated input") } } func TestMultiRegexpFilterOverlappingPatterns(t *testing.T) { f := MultiRegexpFilter{ Operations: []regexpFilterOperation{ {RawRegexp: `secret.*password`, Value: "SENSITIVE"}, {RawRegexp: `password`, Value: "HIDDEN"}, }, } err := f.Provision(caddy.Context{}) if err != nil { t.Fatalf("unexpected error provisioning: %v", err) } // The first pattern should match and replace the entire "secret...password" portion // Then the second pattern should not find "password" anymore since it was already replaced out := f.Filter(zapcore.Field{String: "my-secret-data-password-end"}) expected := "my-SENSITIVE-end" if out.String != expected { t.Fatalf("field has not been filtered correctly: got %s, expected %s", out.String, expected) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/logging/nopencoder.go
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
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/logging/filewriter_test.go
modules/logging/filewriter_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. //go:build !windows package logging import ( "encoding/json" "os" "path" "path/filepath" "syscall" "testing" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func TestFileCreationMode(t *testing.T) { on := true off := false tests := []struct { name string fw FileWriter wantMode os.FileMode }{ { name: "default mode no roll", fw: FileWriter{ Roll: &off, }, wantMode: 0o600, }, { name: "default mode roll", fw: FileWriter{ Roll: &on, }, wantMode: 0o600, }, { name: "custom mode no roll", fw: FileWriter{ Roll: &off, Mode: 0o666, }, wantMode: 0o666, }, { name: "custom mode roll", fw: FileWriter{ Roll: &on, Mode: 0o666, }, wantMode: 0o666, }, } m := syscall.Umask(0o000) defer syscall.Umask(m) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { dir, err := os.MkdirTemp("", "caddytest") if err != nil { t.Fatalf("failed to create tempdir: %v", err) } defer os.RemoveAll(dir) fpath := filepath.Join(dir, "test.log") tt.fw.Filename = fpath logger, err := tt.fw.OpenWriter() if err != nil { t.Fatalf("failed to create file: %v", err) } defer logger.Close() st, err := os.Stat(fpath) if err != nil { t.Fatalf("failed to check file permissions: %v", err) } if st.Mode() != tt.wantMode { t.Errorf("%s: file mode is %v, want %v", tt.name, st.Mode(), tt.wantMode) } }) } } func TestFileRotationPreserveMode(t *testing.T) { m := syscall.Umask(0o000) defer syscall.Umask(m) dir, err := os.MkdirTemp("", "caddytest") if err != nil { t.Fatalf("failed to create tempdir: %v", err) } defer os.RemoveAll(dir) fpath := path.Join(dir, "test.log") roll := true mode := fileMode(0o640) fw := FileWriter{ Filename: fpath, Mode: mode, Roll: &roll, RollSizeMB: 1, } logger, err := fw.OpenWriter() if err != nil { t.Fatalf("failed to create file: %v", err) } defer logger.Close() b := make([]byte, 1024*1024-1000) logger.Write(b) logger.Write(b[0:2000]) files, err := os.ReadDir(dir) if err != nil { t.Fatalf("failed to read temporary log dir: %v", err) } // We might get 2 or 3 files depending // on the race between compressed log file generation, // removal of the non compressed file and reading the directory. // Ordering of the files are [ test-*.log test-*.log.gz test.log ] if len(files) < 2 || len(files) > 3 { t.Log("got files: ", files) t.Fatalf("got %v files want 2", len(files)) } wantPattern := "test-*-*-*-*-*.*.log" test_date_log := files[0] if m, _ := path.Match(wantPattern, test_date_log.Name()); m != true { t.Fatalf("got %v filename want %v", test_date_log.Name(), wantPattern) } st, err := os.Stat(path.Join(dir, test_date_log.Name())) if err != nil { t.Fatalf("failed to check file permissions: %v", err) } if st.Mode() != os.FileMode(mode) { t.Errorf("file mode is %v, want %v", st.Mode(), mode) } test_dot_log := files[len(files)-1] if test_dot_log.Name() != "test.log" { t.Fatalf("got %v filename want test.log", test_dot_log.Name()) } st, err = os.Stat(path.Join(dir, test_dot_log.Name())) if err != nil { t.Fatalf("failed to check file permissions: %v", err) } if st.Mode() != os.FileMode(mode) { t.Errorf("file mode is %v, want %v", st.Mode(), mode) } } func TestFileModeConfig(t *testing.T) { tests := []struct { name string d *caddyfile.Dispenser fw FileWriter wantErr bool }{ { name: "set mode", d: caddyfile.NewTestDispenser(` file test.log { mode 0666 } `), fw: FileWriter{ Mode: 0o666, }, wantErr: false, }, { name: "set mode 3 digits", d: caddyfile.NewTestDispenser(` file test.log { mode 666 } `), fw: FileWriter{ Mode: 0o666, }, wantErr: false, }, { name: "set mode 2 digits", d: caddyfile.NewTestDispenser(` file test.log { mode 66 } `), fw: FileWriter{ Mode: 0o066, }, wantErr: false, }, { name: "set mode 1 digits", d: caddyfile.NewTestDispenser(` file test.log { mode 6 } `), fw: FileWriter{ Mode: 0o006, }, wantErr: false, }, { name: "invalid mode", d: caddyfile.NewTestDispenser(` file test.log { mode foobar } `), fw: FileWriter{}, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { fw := &FileWriter{} if err := fw.UnmarshalCaddyfile(tt.d); (err != nil) != tt.wantErr { t.Fatalf("UnmarshalCaddyfile() error = %v, want %v", err, tt.wantErr) } if fw.Mode != tt.fw.Mode { t.Errorf("got mode %v, want %v", fw.Mode, tt.fw.Mode) } }) } } func TestFileModeJSON(t *testing.T) { tests := []struct { name string config string fw FileWriter wantErr bool }{ { name: "set mode", config: ` { "mode": "0666" } `, fw: FileWriter{ Mode: 0o666, }, wantErr: false, }, { name: "set mode invalid value", config: ` { "mode": "0x666" } `, fw: FileWriter{}, wantErr: true, }, { name: "set mode invalid string", config: ` { "mode": 777 } `, fw: FileWriter{}, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { fw := &FileWriter{} if err := json.Unmarshal([]byte(tt.config), fw); (err != nil) != tt.wantErr { t.Fatalf("UnmarshalJSON() error = %v, want %v", err, tt.wantErr) } if fw.Mode != tt.fw.Mode { t.Errorf("got mode %v, want %v", fw.Mode, tt.fw.Mode) } }) } } func TestFileModeToJSON(t *testing.T) { tests := []struct { name string mode fileMode want string wantErr bool }{ { name: "none zero", mode: 0o644, want: `"0644"`, wantErr: false, }, { name: "zero mode", mode: 0, want: `"0000"`, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var b []byte var err error if b, err = json.Marshal(&tt.mode); (err != nil) != tt.wantErr { t.Fatalf("MarshalJSON() error = %v, want %v", err, tt.wantErr) } got := string(b[:]) if got != tt.want { t.Errorf("got mode %v, want %v", got, tt.want) } }) } } func TestFileModeModification(t *testing.T) { m := syscall.Umask(0o000) defer syscall.Umask(m) dir, err := os.MkdirTemp("", "caddytest") if err != nil { t.Fatalf("failed to create tempdir: %v", err) } defer os.RemoveAll(dir) fpath := path.Join(dir, "test.log") f_tmp, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(0o600)) if err != nil { t.Fatalf("failed to create test file: %v", err) } f_tmp.Close() fw := FileWriter{ Mode: 0o666, Filename: fpath, } logger, err := fw.OpenWriter() if err != nil { t.Fatalf("failed to create file: %v", err) } defer logger.Close() st, err := os.Stat(fpath) if err != nil { t.Fatalf("failed to check file permissions: %v", err) } want := os.FileMode(fw.Mode) if st.Mode() != want { t.Errorf("file mode is %v, want %v", st.Mode(), want) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false