| 1 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package headers |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "net/http" |
| 20 | "regexp" |
| 21 | "strings" |
| 22 | |
| 23 | "github.com/caddyserver/caddy/v2" |
| 24 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" |
| 25 | ) |
| 26 | |
| 27 | func init() { |
| 28 | caddy.RegisterModule(Handler{}) |
| 29 | } |
| 30 | |
| 31 | // Handler is a middleware which modifies request and response headers. |
| 32 | // |
| 33 | // Changes to headers are applied immediately, except for the response |
| 34 | // headers when Deferred is true or when Required is set. In those cases, |
| 35 | // the changes are applied when the headers are written to the response. |
| 36 | // Note that deferred changes do not take effect if an error occurs later |
| 37 | // in the middleware chain. |
| 38 | // |
| 39 | // Properties in this module accept placeholders. |
| 40 | // |
| 41 | // Response header operations can be conditioned upon response status code |
| 42 | // and/or other header values. |
| 43 | type Handler struct { |
| 44 | Request *HeaderOps `json:"request,omitempty"` |
| 45 | Response *RespHeaderOps `json:"response,omitempty"` |
| 46 | } |
| 47 | |
| 48 | // CaddyModule returns the Caddy module information. |
| 49 | func (Handler) CaddyModule() caddy.ModuleInfo { |
| 50 | return caddy.ModuleInfo{ |
| 51 | ID: "http.handlers.headers", |
| 52 | New: func() caddy.Module { return new(Handler) }, |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // Provision sets up h's configuration. |
| 57 | func (h *Handler) Provision(ctx caddy.Context) error { |
| 58 | if h.Request != nil { |
| 59 | err := h.Request.Provision(ctx) |
| 60 | if err != nil { |
| 61 | return err |
| 62 | } |
| 63 | } |
| 64 | if h.Response != nil { |
| 65 | err := h.Response.Provision(ctx) |
| 66 | if err != nil { |
| 67 | return err |
| 68 | } |
| 69 | } |
| 70 | return nil |
| 71 | } |
| 72 | |
| 73 | // Validate ensures h's configuration is valid. |
| 74 | func (h Handler) Validate() error { |
| 75 | if h.Request != nil { |
| 76 | err := h.Request.validate() |
| 77 | if err != nil { |
| 78 | return err |
| 79 | } |
| 80 | } |
| 81 | if h.Response != nil && h.Response.HeaderOps != nil { |
| 82 | err := h.Response.validate() |
| 83 | if err != nil { |
| 84 | return err |
| 85 | } |
| 86 | } |
| 87 | return nil |
| 88 | } |
| 89 | |
| 90 | func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { |
| 91 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 92 | |
| 93 | if h.Request != nil { |
| 94 | h.Request.ApplyToRequest(r) |
| 95 | } |
| 96 | |
| 97 | if h.Response != nil { |
| 98 | if h.Response.Deferred || h.Response.Require != nil { |
| 99 | w = &responseWriterWrapper{ |
| 100 | ResponseWriterWrapper: &caddyhttp.ResponseWriterWrapper{ResponseWriter: w}, |
| 101 | replacer: repl, |
| 102 | require: h.Response.Require, |
| 103 | headerOps: h.Response.HeaderOps, |
| 104 | } |
| 105 | } else { |
| 106 | h.Response.ApplyTo(w.Header(), repl) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | return next.ServeHTTP(w, r) |
| 111 | } |
| 112 | |
| 113 | // HeaderOps defines manipulations for HTTP headers. |
| 114 | type HeaderOps struct { |
| 115 | // Adds HTTP headers; does not replace any existing header fields. |
| 116 | Add http.Header `json:"add,omitempty"` |
| 117 | |
| 118 | // Sets HTTP headers; replaces existing header fields. |
| 119 | Set http.Header `json:"set,omitempty"` |
| 120 | |
| 121 | // Names of HTTP header fields to delete. Basic wildcards are supported: |
| 122 | // |
| 123 | // - Start with `*` for all field names with the given suffix; |
| 124 | // - End with `*` for all field names with the given prefix; |
| 125 | // - Start and end with `*` for all field names containing a substring. |
| 126 | Delete []string `json:"delete,omitempty"` |
| 127 | |
| 128 | // Performs in-situ substring replacements of HTTP headers. |
| 129 | // Keys are the field names on which to perform the associated replacements. |
| 130 | // If the field name is `*`, the replacements are performed on all header fields. |
| 131 | Replace map[string][]Replacement `json:"replace,omitempty"` |
| 132 | } |
| 133 | |
| 134 | // Provision sets up the header operations. |
| 135 | func (ops *HeaderOps) Provision(_ caddy.Context) error { |
| 136 | if ops == nil { |
| 137 | return nil // it's possible no ops are configured; fix #6893 |
| 138 | } |
| 139 | for fieldName, replacements := range ops.Replace { |
| 140 | for i, r := range replacements { |
| 141 | if r.SearchRegexp == "" { |
| 142 | continue |
| 143 | } |
| 144 | |
| 145 | // Check if it contains placeholders |
| 146 | if containsPlaceholders(r.SearchRegexp) { |
| 147 | // Contains placeholders, skips precompilation, and recompiles at runtime |
| 148 | continue |
| 149 | } |
| 150 | |
| 151 | // Does not contain placeholders, safe to precompile |
| 152 | re, err := regexp.Compile(r.SearchRegexp) |
| 153 | if err != nil { |
| 154 | return fmt.Errorf("replacement %d for header field '%s': %v", i, fieldName, err) |
| 155 | } |
| 156 | replacements[i].re = re |
| 157 | } |
| 158 | } |
| 159 | return nil |
| 160 | } |
| 161 | |
| 162 | // containsPlaceholders checks if the string contains Caddy placeholder syntax {key} |
| 163 | func containsPlaceholders(s string) bool { |
| 164 | _, after, ok := strings.Cut(s, "{") |
| 165 | if !ok { |
| 166 | return false |
| 167 | } |
| 168 | closeIdx := strings.Index(after, "}") |
| 169 | if closeIdx == -1 { |
| 170 | return false |
| 171 | } |
| 172 | // Make sure there is content between the brackets |
| 173 | return closeIdx > 0 |
| 174 | } |
| 175 | |
| 176 | func (ops HeaderOps) validate() error { |
| 177 | for fieldName, replacements := range ops.Replace { |
| 178 | for _, r := range replacements { |
| 179 | if r.Search != "" && r.SearchRegexp != "" { |
| 180 | return fmt.Errorf("cannot specify both a substring search and a regular expression search for field '%s'", fieldName) |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | return nil |
| 185 | } |
| 186 | |
| 187 | // Replacement describes a string replacement, |
| 188 | // either a simple and fast substring search |
| 189 | // or a slower but more powerful regex search. |
| 190 | type Replacement struct { |
| 191 | // The substring to search for. |
| 192 | Search string `json:"search,omitempty"` |
| 193 | |
| 194 | // The regular expression to search with. |
| 195 | SearchRegexp string `json:"search_regexp,omitempty"` |
| 196 | |
| 197 | // The string with which to replace matches. |
| 198 | Replace string `json:"replace,omitempty"` |
| 199 | |
| 200 | re *regexp.Regexp |
| 201 | } |
| 202 | |
| 203 | // RespHeaderOps defines manipulations for response headers. |
| 204 | type RespHeaderOps struct { |
| 205 | *HeaderOps |
| 206 | |
| 207 | // If set, header operations will be deferred until |
| 208 | // they are written out and only performed if the |
| 209 | // response matches these criteria. |
| 210 | Require *caddyhttp.ResponseMatcher `json:"require,omitempty"` |
| 211 | |
| 212 | // If true, header operations will be deferred until |
| 213 | // they are written out. Superseded if Require is set. |
| 214 | // Usually you will need to set this to true if any |
| 215 | // fields are being deleted. |
| 216 | Deferred bool `json:"deferred,omitempty"` |
| 217 | } |
| 218 | |
| 219 | // ApplyTo applies ops to hdr using repl. |
| 220 | func (ops *HeaderOps) ApplyTo(hdr http.Header, repl *caddy.Replacer) { |
| 221 | if ops == nil { |
| 222 | return |
| 223 | } |
| 224 | // before manipulating headers in other ways, check if there |
| 225 | // is configuration to delete all headers, and do that first |
| 226 | // because if a header is to be added, we don't want to delete |
| 227 | // it also |
| 228 | for _, fieldName := range ops.Delete { |
| 229 | fieldName = repl.ReplaceKnown(fieldName, "") |
| 230 | if fieldName == "*" { |
| 231 | clear(hdr) |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | // add |
| 236 | for fieldName, vals := range ops.Add { |
| 237 | fieldName = repl.ReplaceKnown(fieldName, "") |
| 238 | for _, v := range vals { |
| 239 | hdr.Add(fieldName, repl.ReplaceKnown(v, "")) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | // set |
| 244 | for fieldName, vals := range ops.Set { |
| 245 | fieldName = repl.ReplaceKnown(fieldName, "") |
| 246 | var newVals []string |
| 247 | for i := range vals { |
| 248 | // append to new slice so we don't overwrite |
| 249 | // the original values in ops.Set |
| 250 | newVals = append(newVals, repl.ReplaceKnown(vals[i], "")) |
| 251 | } |
| 252 | hdr.Set(fieldName, strings.Join(newVals, ",")) |
| 253 | } |
| 254 | |
| 255 | // delete |
| 256 | for _, fieldName := range ops.Delete { |
| 257 | fieldName = strings.ToLower(repl.ReplaceKnown(fieldName, "")) |
| 258 | if fieldName == "*" { |
| 259 | continue // handled above |
| 260 | } |
| 261 | switch { |
| 262 | case strings.HasPrefix(fieldName, "*") && strings.HasSuffix(fieldName, "*"): |
| 263 | for existingField := range hdr { |
| 264 | if strings.Contains(strings.ToLower(existingField), fieldName[1:len(fieldName)-1]) { |
| 265 | delete(hdr, existingField) |
| 266 | } |
| 267 | } |
| 268 | case strings.HasPrefix(fieldName, "*"): |
| 269 | for existingField := range hdr { |
| 270 | if strings.HasSuffix(strings.ToLower(existingField), fieldName[1:]) { |
| 271 | delete(hdr, existingField) |
| 272 | } |
| 273 | } |
| 274 | case strings.HasSuffix(fieldName, "*"): |
| 275 | for existingField := range hdr { |
| 276 | if strings.HasPrefix(strings.ToLower(existingField), fieldName[:len(fieldName)-1]) { |
| 277 | delete(hdr, existingField) |
| 278 | } |
| 279 | } |
| 280 | default: |
| 281 | hdr.Del(fieldName) |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // replace |
| 286 | for fieldName, replacements := range ops.Replace { |
| 287 | fieldName = http.CanonicalHeaderKey(repl.ReplaceKnown(fieldName, "")) |
| 288 | |
| 289 | // all fields... |
| 290 | if fieldName == "*" { |
| 291 | for _, r := range replacements { |
| 292 | search := repl.ReplaceKnown(r.Search, "") |
| 293 | replace := repl.ReplaceKnown(r.Replace, "") |
| 294 | for fieldName, vals := range hdr { |
| 295 | for i := range vals { |
| 296 | if r.re != nil { |
| 297 | // Use precompiled regular expressions |
| 298 | hdr[fieldName][i] = r.re.ReplaceAllString(hdr[fieldName][i], replace) |
| 299 | } else if r.SearchRegexp != "" { |
| 300 | // Runtime compilation of regular expressions |
| 301 | searchRegexp := repl.ReplaceKnown(r.SearchRegexp, "") |
| 302 | if re, err := regexp.Compile(searchRegexp); err == nil { |
| 303 | hdr[fieldName][i] = re.ReplaceAllString(hdr[fieldName][i], replace) |
| 304 | } |
| 305 | // If compilation fails, skip this replacement |
| 306 | } else { |
| 307 | hdr[fieldName][i] = strings.ReplaceAll(hdr[fieldName][i], search, replace) |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | continue |
| 313 | } |
| 314 | |
| 315 | // ...or only with the named field |
| 316 | for _, r := range replacements { |
| 317 | search := repl.ReplaceKnown(r.Search, "") |
| 318 | replace := repl.ReplaceKnown(r.Replace, "") |
| 319 | for hdrFieldName, vals := range hdr { |
| 320 | // see issue #4330 for why we don't simply use hdr[fieldName] |
| 321 | if http.CanonicalHeaderKey(hdrFieldName) != fieldName { |
| 322 | continue |
| 323 | } |
| 324 | for i := range vals { |
| 325 | if r.re != nil { |
| 326 | hdr[hdrFieldName][i] = r.re.ReplaceAllString(hdr[hdrFieldName][i], replace) |
| 327 | } else if r.SearchRegexp != "" { |
| 328 | searchRegexp := repl.ReplaceKnown(r.SearchRegexp, "") |
| 329 | if re, err := regexp.Compile(searchRegexp); err == nil { |
| 330 | hdr[hdrFieldName][i] = re.ReplaceAllString(hdr[hdrFieldName][i], replace) |
| 331 | } |
| 332 | } else { |
| 333 | hdr[hdrFieldName][i] = strings.ReplaceAll(hdr[hdrFieldName][i], search, replace) |
| 334 | } |
| 335 | } |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | // ApplyToRequest applies ops to r, specially handling the Host |
| 342 | // header which the standard library does not include with the |
| 343 | // header map with all the others. This method mutates r.Host. |
| 344 | func (ops HeaderOps) ApplyToRequest(r *http.Request) { |
| 345 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 346 | |
| 347 | // capture the current Host header so we can |
| 348 | // reset to it when we're done |
| 349 | origHost, hadHost := r.Header["Host"] |
| 350 | |
| 351 | // append r.Host; this way, we know that our value |
| 352 | // was last in the list, and if an Add operation |
| 353 | // appended something else after it, that's probably |
| 354 | // fine because it's weird to have multiple Host |
| 355 | // headers anyway and presumably the one they added |
| 356 | // is the one they wanted |
| 357 | r.Header["Host"] = append(r.Header["Host"], r.Host) |
| 358 | |
| 359 | // apply header operations |
| 360 | ops.ApplyTo(r.Header, repl) |
| 361 | |
| 362 | // retrieve the last Host value (likely the one we appended) |
| 363 | if len(r.Header["Host"]) > 0 { |
| 364 | r.Host = r.Header["Host"][len(r.Header["Host"])-1] |
| 365 | } else { |
| 366 | r.Host = "" |
| 367 | } |
| 368 | |
| 369 | // reset the Host header slice |
| 370 | if hadHost { |
| 371 | r.Header["Host"] = origHost |
| 372 | } else { |
| 373 | delete(r.Header, "Host") |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | // responseWriterWrapper defers response header |
| 378 | // operations until WriteHeader is called. |
| 379 | type responseWriterWrapper struct { |
| 380 | *caddyhttp.ResponseWriterWrapper |
| 381 | replacer *caddy.Replacer |
| 382 | require *caddyhttp.ResponseMatcher |
| 383 | headerOps *HeaderOps |
| 384 | wroteHeader bool |
| 385 | } |
| 386 | |
| 387 | func (rww *responseWriterWrapper) WriteHeader(status int) { |
| 388 | if rww.wroteHeader { |
| 389 | return |
| 390 | } |
| 391 | // 1xx responses aren't final; just informational |
| 392 | if status < 100 || status > 199 { |
| 393 | rww.wroteHeader = true |
| 394 | } |
| 395 | if rww.require == nil || rww.require.Match(status, rww.ResponseWriterWrapper.Header()) { |
| 396 | if rww.headerOps != nil { |
| 397 | rww.headerOps.ApplyTo(rww.ResponseWriterWrapper.Header(), rww.replacer) |
| 398 | } |
| 399 | } |
| 400 | rww.ResponseWriterWrapper.WriteHeader(status) |
| 401 | } |
| 402 | |
| 403 | func (rww *responseWriterWrapper) Write(d []byte) (int, error) { |
| 404 | if !rww.wroteHeader { |
| 405 | rww.WriteHeader(http.StatusOK) |
| 406 | } |
| 407 | return rww.ResponseWriterWrapper.Write(d) |
| 408 | } |
| 409 | |
| 410 | // Interface guards |
| 411 | var ( |
| 412 | _ caddy.Provisioner = (*Handler)(nil) |
| 413 | _ caddyhttp.MiddlewareHandler = (*Handler)(nil) |
| 414 | _ http.ResponseWriter = (*responseWriterWrapper)(nil) |
| 415 | ) |