| 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 caddyhttp |
| 16 | |
| 17 | import ( |
| 18 | "context" |
| 19 | "fmt" |
| 20 | "net/http" |
| 21 | "reflect" |
| 22 | "strings" |
| 23 | |
| 24 | "github.com/google/cel-go/cel" |
| 25 | "github.com/google/cel-go/common/types/ref" |
| 26 | |
| 27 | "github.com/caddyserver/caddy/v2" |
| 28 | "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" |
| 29 | ) |
| 30 | |
| 31 | var stringSliceType = reflect.TypeFor[[]string]() |
| 32 | |
| 33 | func init() { |
| 34 | caddy.RegisterModule(VarsMiddleware{}) |
| 35 | caddy.RegisterModule(VarsMatcher{}) |
| 36 | caddy.RegisterModule(MatchVarsRE{}) |
| 37 | } |
| 38 | |
| 39 | // VarsMiddleware is an HTTP middleware which sets variables to |
| 40 | // have values that can be used in the HTTP request handler |
| 41 | // chain. The primary way to access variables is with placeholders, |
| 42 | // which have the form: `{http.vars.variable_name}`, or with |
| 43 | // the `vars` and `vars_regexp` request matchers. |
| 44 | // |
| 45 | // The key is the variable name, and the value is the value of the |
| 46 | // variable. Both the name and value may use or contain placeholders. |
| 47 | type VarsMiddleware map[string]any |
| 48 | |
| 49 | // CaddyModule returns the Caddy module information. |
| 50 | func (VarsMiddleware) CaddyModule() caddy.ModuleInfo { |
| 51 | return caddy.ModuleInfo{ |
| 52 | ID: "http.handlers.vars", |
| 53 | New: func() caddy.Module { return new(VarsMiddleware) }, |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | func (m VarsMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error { |
| 58 | vars := r.Context().Value(VarsCtxKey).(map[string]any) |
| 59 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 60 | for k, v := range m { |
| 61 | keyExpanded := repl.ReplaceAll(k, "") |
| 62 | if valStr, ok := v.(string); ok { |
| 63 | v = repl.ReplaceAll(valStr, "") |
| 64 | } |
| 65 | vars[keyExpanded] = v |
| 66 | |
| 67 | // Special case: the user ID is in the replacer, pulled from there |
| 68 | // for access logs. Allow users to override it with the vars handler. |
| 69 | if keyExpanded == "http.auth.user.id" { |
| 70 | repl.Set(keyExpanded, v) |
| 71 | } |
| 72 | } |
| 73 | return next.ServeHTTP(w, r) |
| 74 | } |
| 75 | |
| 76 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. Syntax: |
| 77 | // |
| 78 | // vars [<name> <val>] { |
| 79 | // <name> <val> |
| 80 | // ... |
| 81 | // } |
| 82 | func (m *VarsMiddleware) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 83 | d.Next() // consume directive name |
| 84 | |
| 85 | if *m == nil { |
| 86 | *m = make(VarsMiddleware) |
| 87 | } |
| 88 | |
| 89 | nextVar := func(headerLine bool) error { |
| 90 | if headerLine { |
| 91 | // header line is optional |
| 92 | if !d.NextArg() { |
| 93 | return nil |
| 94 | } |
| 95 | } |
| 96 | varName := d.Val() |
| 97 | |
| 98 | if !d.NextArg() { |
| 99 | return d.ArgErr() |
| 100 | } |
| 101 | varValue := d.ScalarVal() |
| 102 | |
| 103 | (*m)[varName] = varValue |
| 104 | |
| 105 | if d.NextArg() { |
| 106 | return d.ArgErr() |
| 107 | } |
| 108 | return nil |
| 109 | } |
| 110 | |
| 111 | if err := nextVar(true); err != nil { |
| 112 | return err |
| 113 | } |
| 114 | for d.NextBlock(0) { |
| 115 | if err := nextVar(false); err != nil { |
| 116 | return err |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | return nil |
| 121 | } |
| 122 | |
| 123 | // VarsMatcher is an HTTP request matcher which can match |
| 124 | // requests based on variables in the context or placeholder |
| 125 | // values. The key is the placeholder or name of the variable, |
| 126 | // and the values are possible values the variable can be in |
| 127 | // order to match (logical OR'ed). |
| 128 | // |
| 129 | // If the key is surrounded by `{ }` it is assumed to be a |
| 130 | // placeholder. Otherwise, it will be considered a variable |
| 131 | // name. |
| 132 | // |
| 133 | // Placeholders in the keys are not expanded, but |
| 134 | // placeholders in the values are. |
| 135 | type VarsMatcher map[string][]string |
| 136 | |
| 137 | // CaddyModule returns the Caddy module information. |
| 138 | func (VarsMatcher) CaddyModule() caddy.ModuleInfo { |
| 139 | return caddy.ModuleInfo{ |
| 140 | ID: "http.matchers.vars", |
| 141 | New: func() caddy.Module { return new(VarsMatcher) }, |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. |
| 146 | func (m *VarsMatcher) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 147 | if *m == nil { |
| 148 | *m = make(map[string][]string) |
| 149 | } |
| 150 | // iterate to merge multiple matchers into one |
| 151 | for d.Next() { |
| 152 | var field string |
| 153 | if !d.Args(&field) { |
| 154 | return d.Errf("malformed vars matcher: expected field name") |
| 155 | } |
| 156 | vals := d.RemainingArgs() |
| 157 | if len(vals) == 0 { |
| 158 | return d.Errf("malformed vars matcher: expected at least one value to match against") |
| 159 | } |
| 160 | (*m)[field] = append((*m)[field], vals...) |
| 161 | if d.NextBlock(0) { |
| 162 | return d.Err("malformed vars matcher: blocks are not supported") |
| 163 | } |
| 164 | } |
| 165 | return nil |
| 166 | } |
| 167 | |
| 168 | // Match matches a request based on variables in the context, |
| 169 | // or placeholders if the key is not a variable. |
| 170 | func (m VarsMatcher) Match(r *http.Request) bool { |
| 171 | match, _ := m.MatchWithError(r) |
| 172 | return match |
| 173 | } |
| 174 | |
| 175 | // MatchWithError returns true if r matches m. |
| 176 | func (m VarsMatcher) MatchWithError(r *http.Request) (bool, error) { |
| 177 | if len(m) == 0 { |
| 178 | return true, nil |
| 179 | } |
| 180 | |
| 181 | vars := r.Context().Value(VarsCtxKey).(map[string]any) |
| 182 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 183 | |
| 184 | var matcherValExpanded, varStr, v string |
| 185 | var varValue any |
| 186 | for key, vals := range m { |
| 187 | if strings.HasPrefix(key, "{") && |
| 188 | strings.HasSuffix(key, "}") && |
| 189 | strings.Count(key, "{") == 1 { |
| 190 | varValue, _ = repl.Get(strings.Trim(key, "{}")) |
| 191 | } else { |
| 192 | varValue = vars[key] |
| 193 | } |
| 194 | |
| 195 | switch vv := varValue.(type) { |
| 196 | case string: |
| 197 | varStr = vv |
| 198 | case fmt.Stringer: |
| 199 | varStr = vv.String() |
| 200 | case error: |
| 201 | varStr = vv.Error() |
| 202 | case nil: |
| 203 | varStr = "" |
| 204 | default: |
| 205 | varStr = fmt.Sprintf("%v", vv) |
| 206 | } |
| 207 | |
| 208 | // Don't expand placeholders in values from literal variable names |
| 209 | // (e.g. map outputs) or other placeholders. These values are |
| 210 | // already final and must not be re-expanded, as that would allow |
| 211 | // user input like {env.SECRET} to be evaluated. |
| 212 | |
| 213 | // see if any of the values given in the matcher match the actual value |
| 214 | for _, v = range vals { |
| 215 | matcherValExpanded = repl.ReplaceAll(v, "") |
| 216 | if varStr == matcherValExpanded { |
| 217 | return true, nil |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | return false, nil |
| 222 | } |
| 223 | |
| 224 | // CELLibrary produces options that expose this matcher for use in CEL |
| 225 | // expression matchers. |
| 226 | // |
| 227 | // Example: |
| 228 | // |
| 229 | // expression vars({'{magic_number}': ['3', '5']}) |
| 230 | // expression vars({'{foo}': 'single_value'}) |
| 231 | func (VarsMatcher) CELLibrary(_ caddy.Context) (cel.Library, error) { |
| 232 | return CELMatcherImpl( |
| 233 | "vars", |
| 234 | "vars_matcher_request_map", |
| 235 | []*cel.Type{CELTypeJSON}, |
| 236 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 237 | mapStrListStr, err := CELValueToMapStrList(data) |
| 238 | if err != nil { |
| 239 | return nil, err |
| 240 | } |
| 241 | return VarsMatcher(mapStrListStr), nil |
| 242 | }, |
| 243 | ) |
| 244 | } |
| 245 | |
| 246 | // MatchVarsRE matches the value of the context variables by a given regular expression. |
| 247 | // |
| 248 | // Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` |
| 249 | // where `name` is the regular expression's name, and `capture_group` is either |
| 250 | // the named or positional capture group from the expression itself. If no name |
| 251 | // is given, then the placeholder omits the name: `{http.regexp.capture_group}` |
| 252 | // (potentially leading to collisions). |
| 253 | type MatchVarsRE map[string]*MatchRegexp |
| 254 | |
| 255 | // CaddyModule returns the Caddy module information. |
| 256 | func (MatchVarsRE) CaddyModule() caddy.ModuleInfo { |
| 257 | return caddy.ModuleInfo{ |
| 258 | ID: "http.matchers.vars_regexp", |
| 259 | New: func() caddy.Module { return new(MatchVarsRE) }, |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | // UnmarshalCaddyfile implements caddyfile.Unmarshaler. |
| 264 | func (m *MatchVarsRE) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 265 | if *m == nil { |
| 266 | *m = make(map[string]*MatchRegexp) |
| 267 | } |
| 268 | // iterate to merge multiple matchers into one |
| 269 | for d.Next() { |
| 270 | var first, second, third string |
| 271 | if !d.Args(&first, &second) { |
| 272 | return d.ArgErr() |
| 273 | } |
| 274 | |
| 275 | var name, field, val string |
| 276 | if d.Args(&third) { |
| 277 | name = first |
| 278 | field = second |
| 279 | val = third |
| 280 | } else { |
| 281 | field = first |
| 282 | val = second |
| 283 | } |
| 284 | |
| 285 | // Default to the named matcher's name, if no regexp name is provided |
| 286 | if name == "" { |
| 287 | name = d.GetContextString(caddyfile.MatcherNameCtxKey) |
| 288 | } |
| 289 | |
| 290 | (*m)[field] = &MatchRegexp{Pattern: val, Name: name} |
| 291 | if d.NextBlock(0) { |
| 292 | return d.Err("malformed vars_regexp matcher: blocks are not supported") |
| 293 | } |
| 294 | } |
| 295 | return nil |
| 296 | } |
| 297 | |
| 298 | // Provision compiles m's regular expressions. |
| 299 | func (m MatchVarsRE) Provision(ctx caddy.Context) error { |
| 300 | for _, rm := range m { |
| 301 | err := rm.Provision(ctx) |
| 302 | if err != nil { |
| 303 | return err |
| 304 | } |
| 305 | } |
| 306 | return nil |
| 307 | } |
| 308 | |
| 309 | // Match returns true if r matches m. |
| 310 | func (m MatchVarsRE) Match(r *http.Request) bool { |
| 311 | match, _ := m.MatchWithError(r) |
| 312 | return match |
| 313 | } |
| 314 | |
| 315 | // MatchWithError returns true if r matches m. |
| 316 | func (m MatchVarsRE) MatchWithError(r *http.Request) (bool, error) { |
| 317 | vars := r.Context().Value(VarsCtxKey).(map[string]any) |
| 318 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 319 | |
| 320 | var match bool |
| 321 | var varStr string |
| 322 | var varValue any |
| 323 | for key, val := range m { |
| 324 | if strings.HasPrefix(key, "{") && |
| 325 | strings.HasSuffix(key, "}") && |
| 326 | strings.Count(key, "{") == 1 { |
| 327 | varValue, _ = repl.Get(strings.Trim(key, "{}")) |
| 328 | } else { |
| 329 | varValue = vars[key] |
| 330 | } |
| 331 | |
| 332 | switch vv := varValue.(type) { |
| 333 | case string: |
| 334 | varStr = vv |
| 335 | case fmt.Stringer: |
| 336 | varStr = vv.String() |
| 337 | case error: |
| 338 | varStr = vv.Error() |
| 339 | case nil: |
| 340 | varStr = "" |
| 341 | default: |
| 342 | varStr = fmt.Sprintf("%v", vv) |
| 343 | } |
| 344 | |
| 345 | // Don't expand placeholders in values from literal variable names |
| 346 | // (e.g. map outputs) or other placeholders. These values are |
| 347 | // already final and must not be re-expanded, as that would allow |
| 348 | // user input like {env.SECRET} to be evaluated. |
| 349 | |
| 350 | if match = val.Match(varStr, repl); match { |
| 351 | return match, nil |
| 352 | } |
| 353 | } |
| 354 | return false, nil |
| 355 | } |
| 356 | |
| 357 | // CELLibrary produces options that expose this matcher for use in CEL |
| 358 | // expression matchers. |
| 359 | // |
| 360 | // Example: |
| 361 | // |
| 362 | // expression vars_regexp('foo', '{magic_number}', '[0-9]+') |
| 363 | // expression vars_regexp('{magic_number}', '[0-9]+') |
| 364 | func (MatchVarsRE) CELLibrary(ctx caddy.Context) (cel.Library, error) { |
| 365 | unnamedPattern, err := CELMatcherImpl( |
| 366 | "vars_regexp", |
| 367 | "vars_regexp_request_string_string", |
| 368 | []*cel.Type{cel.StringType, cel.StringType}, |
| 369 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 370 | refStringList := stringSliceType |
| 371 | params, err := data.ConvertToNative(refStringList) |
| 372 | if err != nil { |
| 373 | return nil, err |
| 374 | } |
| 375 | strParams := params.([]string) |
| 376 | matcher := MatchVarsRE{} |
| 377 | matcher[strParams[0]] = &MatchRegexp{ |
| 378 | Pattern: strParams[1], |
| 379 | Name: ctx.Value(MatcherNameCtxKey).(string), |
| 380 | } |
| 381 | err = matcher.Provision(ctx) |
| 382 | return matcher, err |
| 383 | }, |
| 384 | ) |
| 385 | if err != nil { |
| 386 | return nil, err |
| 387 | } |
| 388 | namedPattern, err := CELMatcherImpl( |
| 389 | "vars_regexp", |
| 390 | "vars_regexp_request_string_string_string", |
| 391 | []*cel.Type{cel.StringType, cel.StringType, cel.StringType}, |
| 392 | func(data ref.Val) (RequestMatcherWithError, error) { |
| 393 | refStringList := stringSliceType |
| 394 | params, err := data.ConvertToNative(refStringList) |
| 395 | if err != nil { |
| 396 | return nil, err |
| 397 | } |
| 398 | strParams := params.([]string) |
| 399 | name := strParams[0] |
| 400 | if name == "" { |
| 401 | name = ctx.Value(MatcherNameCtxKey).(string) |
| 402 | } |
| 403 | matcher := MatchVarsRE{} |
| 404 | matcher[strParams[1]] = &MatchRegexp{ |
| 405 | Pattern: strParams[2], |
| 406 | Name: name, |
| 407 | } |
| 408 | err = matcher.Provision(ctx) |
| 409 | return matcher, err |
| 410 | }, |
| 411 | ) |
| 412 | if err != nil { |
| 413 | return nil, err |
| 414 | } |
| 415 | envOpts := append(unnamedPattern.CompileOptions(), namedPattern.CompileOptions()...) |
| 416 | prgOpts := append(unnamedPattern.ProgramOptions(), namedPattern.ProgramOptions()...) |
| 417 | return NewMatcherCELLibrary(envOpts, prgOpts), nil |
| 418 | } |
| 419 | |
| 420 | // Validate validates m's regular expressions. |
| 421 | func (m MatchVarsRE) Validate() error { |
| 422 | for _, rm := range m { |
| 423 | err := rm.Validate() |
| 424 | if err != nil { |
| 425 | return err |
| 426 | } |
| 427 | } |
| 428 | return nil |
| 429 | } |
| 430 | |
| 431 | // GetVar gets a value out of the context's variable table by key. |
| 432 | // If the key does not exist, the return value will be nil. |
| 433 | func GetVar(ctx context.Context, key string) any { |
| 434 | varMap, ok := ctx.Value(VarsCtxKey).(map[string]any) |
| 435 | if !ok { |
| 436 | return nil |
| 437 | } |
| 438 | return varMap[key] |
| 439 | } |
| 440 | |
| 441 | // SetVar sets a value in the context's variable table with |
| 442 | // the given key. It overwrites any previous value with the |
| 443 | // same key. |
| 444 | // |
| 445 | // If the value is nil (note: non-nil interface with nil |
| 446 | // underlying value does not count) and the key exists in |
| 447 | // the table, the key+value will be deleted from the table. |
| 448 | func SetVar(ctx context.Context, key string, value any) { |
| 449 | varMap, ok := ctx.Value(VarsCtxKey).(map[string]any) |
| 450 | if !ok { |
| 451 | return |
| 452 | } |
| 453 | if value == nil { |
| 454 | if _, ok := varMap[key]; ok { |
| 455 | delete(varMap, key) |
| 456 | return |
| 457 | } |
| 458 | } |
| 459 | varMap[key] = value |
| 460 | } |
| 461 | |
| 462 | // Interface guards |
| 463 | var ( |
| 464 | _ MiddlewareHandler = (*VarsMiddleware)(nil) |
| 465 | _ caddyfile.Unmarshaler = (*VarsMiddleware)(nil) |
| 466 | _ RequestMatcherWithError = (*VarsMatcher)(nil) |
| 467 | _ caddyfile.Unmarshaler = (*VarsMatcher)(nil) |
| 468 | _ RequestMatcherWithError = (*MatchVarsRE)(nil) |
| 469 | _ caddyfile.Unmarshaler = (*MatchVarsRE)(nil) |
| 470 | ) |