Debian Codegraph @

modules/caddyhttp/celmatcher.go

raw symbols SCIP
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 "crypto/x509/pkix"
19 "encoding/json"
20 "errors"
21 "fmt"
22 "net/http"
23 "reflect"
24 "regexp"
25 "strings"
26 "time"
27
28 "github.com/google/cel-go/cel"
29 "github.com/google/cel-go/common"
30 "github.com/google/cel-go/common/ast"
31 "github.com/google/cel-go/common/operators"
32 "github.com/google/cel-go/common/types"
33 "github.com/google/cel-go/common/types/ref"
34 "github.com/google/cel-go/common/types/traits"
35 "github.com/google/cel-go/ext"
36 "github.com/google/cel-go/interpreter"
37 "github.com/google/cel-go/interpreter/functions"
38 "github.com/google/cel-go/parser"
39 "go.uber.org/zap"
40
41 "github.com/caddyserver/caddy/v2"
42 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
43 )
44
45 func init() {
46 caddy.RegisterModule(MatchExpression{})
47 }
48
49 // MatchExpression matches requests by evaluating a
50 // [CEL](https://github.com/google/cel-spec) expression.
51 // This enables complex logic to be expressed using a comfortable,
52 // familiar syntax. Please refer to
53 // [the standard definitions of CEL functions and operators](https://github.com/google/cel-spec/blob/master/doc/langdef.md#standard-definitions).
54 //
55 // This matcher's JSON interface is actually a string, not a struct.
56 // The generated docs are not correct because this type has custom
57 // marshaling logic.
58 //
59 // COMPATIBILITY NOTE: This module is still experimental and is not
60 // subject to Caddy's compatibility guarantee.
61 type MatchExpression struct {
62 // The CEL expression to evaluate. Any Caddy placeholders
63 // will be expanded and situated into proper CEL function
64 // calls before evaluating.
65 Expr string `json:"expr,omitempty"`
66
67 // Name is an optional name for this matcher.
68 // This is used to populate the name for regexp
69 // matchers that appear in the expression.
70 Name string `json:"name,omitempty"`
71
72 expandedExpr string
73 prg cel.Program
74 ta types.Adapter
75
76 log *zap.Logger
77 }
78
79 // CaddyModule returns the Caddy module information.
80 func (MatchExpression) CaddyModule() caddy.ModuleInfo {
81 return caddy.ModuleInfo{
82 ID: "http.matchers.expression",
83 New: func() caddy.Module { return new(MatchExpression) },
84 }
85 }
86
87 // MarshalJSON marshals m's expression.
88 func (m MatchExpression) MarshalJSON() ([]byte, error) {
89 // if the name is empty, then we can marshal just the expression string
90 if m.Name == "" {
91 return json.Marshal(m.Expr)
92 }
93 // otherwise, we need to marshal the full object, using an
94 // anonymous struct to avoid infinite recursion
95 return json.Marshal(struct {
96 Expr string `json:"expr"`
97 Name string `json:"name"`
98 }{
99 Expr: m.Expr,
100 Name: m.Name,
101 })
102 }
103
104 // UnmarshalJSON unmarshals m's expression.
105 func (m *MatchExpression) UnmarshalJSON(data []byte) error {
106 // if the data is a string, then it's just the expression
107 if data[0] == '"' {
108 return json.Unmarshal(data, &m.Expr)
109 }
110 // otherwise, it's a full object, so unmarshal it,
111 // using a temp map to avoid infinite recursion
112 var tmpJson map[string]any
113 err := json.Unmarshal(data, &tmpJson)
114 *m = MatchExpression{
115 Expr: tmpJson["expr"].(string),
116 Name: tmpJson["name"].(string),
117 }
118 return err
119 }
120
121 // Provision sets up m.
122 func (m *MatchExpression) Provision(ctx caddy.Context) error {
123 m.log = ctx.Logger()
124
125 // replace placeholders with a function call - this is just some
126 // light (and possibly naïve) syntactic sugar
127 m.expandedExpr = placeholderRegexp.ReplaceAllString(m.Expr, placeholderExpansion)
128
129 // as a second pass, we'll strip the escape character from an escaped
130 // placeholder, so that it can be used as an input to other CEL functions
131 m.expandedExpr = escapedPlaceholderRegexp.ReplaceAllString(m.expandedExpr, escapedPlaceholderExpansion)
132
133 // our type adapter expands CEL's standard type support
134 m.ta = celTypeAdapter{}
135
136 // initialize the CEL libraries from the Matcher implementations which
137 // have been configured to support CEL.
138 matcherLibProducers := []CELLibraryProducer{}
139 for _, info := range caddy.GetModules("http.matchers") {
140 p, ok := info.New().(CELLibraryProducer)
141 if ok {
142 matcherLibProducers = append(matcherLibProducers, p)
143 }
144 }
145
146 // add the matcher name to the context so that the matcher name
147 // can be used by regexp matchers being provisioned
148 ctx = ctx.WithValue(MatcherNameCtxKey, m.Name)
149
150 // Assemble the compilation and program options from the different library
151 // producers into a single cel.Library implementation.
152 matcherEnvOpts := []cel.EnvOption{}
153 matcherProgramOpts := []cel.ProgramOption{}
154 for _, producer := range matcherLibProducers {
155 l, err := producer.CELLibrary(ctx)
156 if err != nil {
157 return fmt.Errorf("error initializing CEL library for %T: %v", producer, err)
158 }
159 matcherEnvOpts = append(matcherEnvOpts, l.CompileOptions()...)
160 matcherProgramOpts = append(matcherProgramOpts, l.ProgramOptions()...)
161 }
162 matcherLib := cel.Lib(NewMatcherCELLibrary(matcherEnvOpts, matcherProgramOpts))
163
164 // create the CEL environment
165 env, err := cel.NewEnv(
166 cel.Function(CELPlaceholderFuncName, cel.SingletonBinaryBinding(m.caddyPlaceholderFunc), cel.Overload(
167 CELPlaceholderFuncName+"_httpRequest_string",
168 []*cel.Type{httpRequestObjectType, cel.StringType},
169 cel.AnyType,
170 )),
171 cel.Variable(CELRequestVarName, httpRequestObjectType),
172 cel.CustomTypeAdapter(m.ta),
173 ext.Strings(),
174 ext.Bindings(),
175 ext.Lists(),
176 ext.Math(),
177 matcherLib,
178 )
179 if err != nil {
180 return fmt.Errorf("setting up CEL environment: %v", err)
181 }
182
183 // parse and type-check the expression
184 checked, issues := env.Compile(m.expandedExpr)
185 if issues.Err() != nil {
186 return fmt.Errorf("compiling CEL program: %s", issues.Err())
187 }
188
189 // request matching is a boolean operation, so we don't really know
190 // what to do if the expression returns a non-boolean type
191 if checked.OutputType() != cel.BoolType {
192 return fmt.Errorf("CEL request matcher expects return type of bool, not %s", checked.OutputType())
193 }
194
195 // compile the "program"
196 m.prg, err = env.Program(checked, cel.EvalOptions(cel.OptOptimize))
197 if err != nil {
198 return fmt.Errorf("compiling CEL program: %s", err)
199 }
200 return nil
201 }
202
203 // Match returns true if r matches m.
204 func (m MatchExpression) Match(r *http.Request) bool {
205 match, err := m.MatchWithError(r)
206 if err != nil {
207 SetVar(r.Context(), MatcherErrorVarKey, err)
208 }
209 return match
210 }
211
212 // MatchWithError returns true if r matches m.
213 func (m MatchExpression) MatchWithError(r *http.Request) (bool, error) {
214 celReq := celHTTPRequest{r}
215 out, _, err := m.prg.Eval(celReq)
216 if err != nil {
217 m.log.Error("evaluating expression", zap.Error(err))
218 return false, err
219 }
220 if outBool, ok := out.Value().(bool); ok {
221 return outBool, nil
222 }
223 return false, nil
224 }
225
226 // UnmarshalCaddyfile implements caddyfile.Unmarshaler.
227 func (m *MatchExpression) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
228 d.Next() // consume matcher name
229
230 // if there's multiple args, then we need to keep the raw
231 // tokens because the user may have used quotes within their
232 // CEL expression (e.g. strings) and we should retain that
233 if d.CountRemainingArgs() > 1 {
234 m.Expr = strings.Join(d.RemainingArgsRaw(), " ")
235 return nil
236 }
237
238 // there should at least be one arg
239 if !d.NextArg() {
240 return d.ArgErr()
241 }
242
243 // if there's only one token, then we can safely grab the
244 // cleaned token (no quotes) and use that as the expression
245 // because there's no valid CEL expression that is only a
246 // quoted string; commonly quotes are used in Caddyfile to
247 // define the expression
248 m.Expr = d.Val()
249
250 // use the named matcher's name, to fill regexp
251 // matchers names by default
252 m.Name = d.GetContextString(caddyfile.MatcherNameCtxKey)
253
254 return nil
255 }
256
257 // caddyPlaceholderFunc implements the custom CEL function that accesses the
258 // Replacer on a request and gets values from it.
259 func (m MatchExpression) caddyPlaceholderFunc(lhs, rhs ref.Val) ref.Val {
260 celReq, ok := lhs.(celHTTPRequest)
261 if !ok {
262 return types.NewErr(
263 "invalid request of type '%v' to %s(request, placeholderVarName)",
264 lhs.Type(),
265 CELPlaceholderFuncName,
266 )
267 }
268 phStr, ok := rhs.(types.String)
269 if !ok {
270 return types.NewErr(
271 "invalid placeholder variable name of type '%v' to %s(request, placeholderVarName)",
272 rhs.Type(),
273 CELPlaceholderFuncName,
274 )
275 }
276
277 repl := celReq.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
278 val, _ := repl.Get(string(phStr))
279
280 return m.ta.NativeToValue(val)
281 }
282
283 // httpRequestCELType is the type representation of a native HTTP request.
284 var httpRequestCELType = cel.ObjectType("http.Request", traits.ReceiverType)
285
286 // celHTTPRequest wraps an http.Request with ref.Val interface methods.
287 //
288 // This type also implements the interpreter.Activation interface which
289 // drops allocation costs for CEL expression evaluations by roughly half.
290 type celHTTPRequest struct{ *http.Request }
291
292 func (cr celHTTPRequest) ResolveName(name string) (any, bool) {
293 if name == CELRequestVarName {
294 return cr, true
295 }
296 return nil, false
297 }
298
299 func (cr celHTTPRequest) Parent() interpreter.Activation {
300 return nil
301 }
302
303 func (cr celHTTPRequest) ConvertToNative(typeDesc reflect.Type) (any, error) {
304 return cr.Request, nil
305 }
306
307 func (celHTTPRequest) ConvertToType(typeVal ref.Type) ref.Val {
308 panic("not implemented")
309 }
310
311 func (cr celHTTPRequest) Equal(other ref.Val) ref.Val {
312 if o, ok := other.Value().(celHTTPRequest); ok {
313 return types.Bool(o.Request == cr.Request)
314 }
315 return types.ValOrErr(other, "%v is not comparable type", other)
316 }
317 func (celHTTPRequest) Type() ref.Type { return httpRequestCELType }
318 func (cr celHTTPRequest) Value() any { return cr }
319
320 var pkixNameCELType = cel.ObjectType("pkix.Name", traits.ReceiverType)
321
322 // celPkixName wraps a pkix.Name with
323 // methods to satisfy the ref.Val interface.
324 type celPkixName struct{ *pkix.Name }
325
326 func (pn celPkixName) ConvertToNative(typeDesc reflect.Type) (any, error) {
327 return pn.Name, nil
328 }
329
330 func (pn celPkixName) ConvertToType(typeVal ref.Type) ref.Val {
331 if typeVal.TypeName() == "string" {
332 return types.String(pn.Name.String())
333 }
334 panic("not implemented")
335 }
336
337 func (pn celPkixName) Equal(other ref.Val) ref.Val {
338 if o, ok := other.Value().(string); ok {
339 return types.Bool(pn.Name.String() == o)
340 }
341 return types.ValOrErr(other, "%v is not comparable type", other)
342 }
343 func (celPkixName) Type() ref.Type { return pkixNameCELType }
344 func (pn celPkixName) Value() any { return pn }
345
346 // celTypeAdapter can adapt our custom types to a CEL value.
347 type celTypeAdapter struct{}
348
349 func (celTypeAdapter) NativeToValue(value any) ref.Val {
350 switch v := value.(type) {
351 case celHTTPRequest:
352 return v
353 case pkix.Name:
354 return celPkixName{&v}
355 case time.Time:
356 return types.Timestamp{Time: v}
357 case error:
358 return types.WrapErr(v)
359 }
360 return types.DefaultTypeAdapter.NativeToValue(value)
361 }
362
363 // CELLibraryProducer provide CEL libraries that expose a Matcher
364 // implementation as a first class function within the CEL expression
365 // matcher.
366 type CELLibraryProducer interface {
367 // CELLibrary creates a cel.Library which makes it possible to use the
368 // target object within CEL expression matchers.
369 CELLibrary(caddy.Context) (cel.Library, error)
370 }
371
372 // CELMatcherImpl creates a new cel.Library based on the following pieces of
373 // data:
374 //
375 // - macroName: the function name to be used within CEL. This will be a macro
376 // and not a function proper.
377 // - funcName: the function overload name generated by the CEL macro used to
378 // represent the matcher.
379 // - matcherDataTypes: the argument types to the macro.
380 // - fac: a matcherFactory implementation which converts from CEL constant
381 // values to a Matcher instance.
382 //
383 // Note, macro names and function names must not collide with other macros or
384 // functions exposed within CEL expressions, or an error will be produced
385 // during the expression matcher plan time.
386 //
387 // The existing CELMatcherImpl support methods are configured to support a
388 // limited set of function signatures. For strong type validation you may need
389 // to provide a custom macro which does a more detailed analysis of the CEL
390 // literal provided to the macro as an argument.
391 func CELMatcherImpl(macroName, funcName string, matcherDataTypes []*cel.Type, fac any) (cel.Library, error) {
392 requestType := cel.ObjectType("http.Request")
393 var macro parser.Macro
394 switch len(matcherDataTypes) {
395 case 1:
396 matcherDataType := matcherDataTypes[0]
397 switch matcherDataType.String() {
398 case "list(string)":
399 macro = parser.NewGlobalVarArgMacro(macroName, celMatcherStringListMacroExpander(funcName))
400 case cel.StringType.String():
401 macro = parser.NewGlobalMacro(macroName, 1, celMatcherStringMacroExpander(funcName))
402 case CELTypeJSON.String():
403 macro = parser.NewGlobalMacro(macroName, 1, celMatcherJSONMacroExpander(funcName))
404 default:
405 return nil, fmt.Errorf("unsupported matcher data type: %s", matcherDataType)
406 }
407 case 2:
408 if matcherDataTypes[0] == cel.StringType && matcherDataTypes[1] == cel.StringType {
409 macro = parser.NewGlobalMacro(macroName, 2, celMatcherStringListMacroExpander(funcName))
410 matcherDataTypes = []*cel.Type{cel.ListType(cel.StringType)}
411 } else {
412 return nil, fmt.Errorf("unsupported matcher data type: %s, %s", matcherDataTypes[0], matcherDataTypes[1])
413 }
414 case 3:
415 // nolint:gosec // false positive, impossible to be out of bounds; see: https://github.com/securego/gosec/issues/1525
416 if matcherDataTypes[0] == cel.StringType && matcherDataTypes[1] == cel.StringType && matcherDataTypes[2] == cel.StringType {
417 macro = parser.NewGlobalMacro(macroName, 3, celMatcherStringListMacroExpander(funcName))
418 matcherDataTypes = []*cel.Type{cel.ListType(cel.StringType)}
419 } else {
420 // nolint:gosec // false positive, impossible to be out of bounds; see: https://github.com/securego/gosec/issues/1525
421 return nil, fmt.Errorf("unsupported matcher data type: %s, %s, %s", matcherDataTypes[0], matcherDataTypes[1], matcherDataTypes[2])
422 }
423 }
424 envOptions := []cel.EnvOption{
425 cel.Macros(macro),
426 cel.Function(funcName,
427 cel.Overload(funcName, append([]*cel.Type{requestType}, matcherDataTypes...), cel.BoolType),
428 cel.SingletonBinaryBinding(CELMatcherRuntimeFunction(funcName, fac))),
429 }
430 programOptions := []cel.ProgramOption{
431 cel.CustomDecorator(CELMatcherDecorator(funcName, fac)),
432 }
433 return NewMatcherCELLibrary(envOptions, programOptions), nil
434 }
435
436 // CELMatcherFactory converts a constant CEL value into a RequestMatcher.
437 // Deprecated: Use CELMatcherWithErrorFactory instead.
438 type CELMatcherFactory = func(data ref.Val) (RequestMatcher, error)
439
440 // CELMatcherWithErrorFactory converts a constant CEL value into a RequestMatcherWithError.
441 type CELMatcherWithErrorFactory = func(data ref.Val) (RequestMatcherWithError, error)
442
443 // matcherCELLibrary is a simplistic configurable cel.Library implementation.
444 type matcherCELLibrary struct {
445 envOptions []cel.EnvOption
446 programOptions []cel.ProgramOption
447 }
448
449 // NewMatcherCELLibrary creates a matcherLibrary from option setes.
450 func NewMatcherCELLibrary(envOptions []cel.EnvOption, programOptions []cel.ProgramOption) cel.Library {
451 return &matcherCELLibrary{
452 envOptions: envOptions,
453 programOptions: programOptions,
454 }
455 }
456
457 func (lib *matcherCELLibrary) CompileOptions() []cel.EnvOption {
458 return lib.envOptions
459 }
460
461 func (lib *matcherCELLibrary) ProgramOptions() []cel.ProgramOption {
462 return lib.programOptions
463 }
464
465 // CELMatcherDecorator matches a call overload generated by a CEL macro
466 // that takes a single argument, and optimizes the implementation to precompile
467 // the matcher and return a function that references the precompiled and
468 // provisioned matcher.
469 func CELMatcherDecorator(funcName string, fac any) interpreter.InterpretableDecorator {
470 return func(i interpreter.Interpretable) (interpreter.Interpretable, error) {
471 call, ok := i.(interpreter.InterpretableCall)
472 if !ok {
473 return i, nil
474 }
475 if call.OverloadID() != funcName {
476 return i, nil
477 }
478 callArgs := call.Args()
479 reqAttr, ok := callArgs[0].(interpreter.InterpretableAttribute)
480 if !ok {
481 return nil, errors.New("missing 'req' argument")
482 }
483 nsAttr, ok := reqAttr.Attr().(interpreter.NamespacedAttribute)
484 if !ok {
485 return nil, errors.New("missing 'req' argument")
486 }
487 varNames := nsAttr.CandidateVariableNames()
488 if len(varNames) != 1 || len(varNames) == 1 && varNames[0] != CELRequestVarName {
489 return nil, errors.New("missing 'req' argument")
490 }
491 matcherData, ok := callArgs[1].(interpreter.InterpretableConst)
492 if !ok {
493 // If the matcher arguments are not constant, then this means
494 // they contain a Caddy placeholder reference and the evaluation
495 // and matcher provisioning should be handled at dynamically.
496 return i, nil
497 }
498
499 if factory, ok := fac.(CELMatcherWithErrorFactory); ok {
500 matcher, err := factory(matcherData.Value())
501 if err != nil {
502 return nil, err
503 }
504 return interpreter.NewCall(
505 i.ID(), funcName, funcName+"_opt",
506 []interpreter.Interpretable{reqAttr},
507 func(args ...ref.Val) ref.Val {
508 // The request value, guaranteed to be of type celHTTPRequest
509 celReq := args[0]
510 // If needed this call could be changed to convert the value
511 // to a *http.Request using CEL's ConvertToNative method.
512 httpReq := celReq.Value().(celHTTPRequest)
513 match, err := matcher.MatchWithError(httpReq.Request)
514 if err != nil {
515 return types.WrapErr(err)
516 }
517 return types.Bool(match)
518 },
519 ), nil
520 }
521
522 if factory, ok := fac.(CELMatcherFactory); ok {
523 matcher, err := factory(matcherData.Value())
524 if err != nil {
525 return nil, err
526 }
527 return interpreter.NewCall(
528 i.ID(), funcName, funcName+"_opt",
529 []interpreter.Interpretable{reqAttr},
530 func(args ...ref.Val) ref.Val {
531 // The request value, guaranteed to be of type celHTTPRequest
532 celReq := args[0]
533 // If needed this call could be changed to convert the value
534 // to a *http.Request using CEL's ConvertToNative method.
535 httpReq := celReq.Value().(celHTTPRequest)
536 if m, ok := matcher.(RequestMatcherWithError); ok {
537 match, err := m.MatchWithError(httpReq.Request)
538 if err != nil {
539 return types.WrapErr(err)
540 }
541 return types.Bool(match)
542 }
543 return types.Bool(matcher.Match(httpReq.Request))
544 },
545 ), nil
546 }
547
548 return nil, fmt.Errorf("invalid matcher factory, must be CELMatcherFactory or CELMatcherWithErrorFactory: %T", fac)
549 }
550 }
551
552 // CELMatcherRuntimeFunction creates a function binding for when the input to the matcher
553 // is dynamically resolved rather than a set of static constant values.
554 func CELMatcherRuntimeFunction(funcName string, fac any) functions.BinaryOp {
555 return func(celReq, matcherData ref.Val) ref.Val {
556 if factory, ok := fac.(CELMatcherWithErrorFactory); ok {
557 matcher, err := factory(matcherData)
558 if err != nil {
559 return types.WrapErr(err)
560 }
561 httpReq := celReq.Value().(celHTTPRequest)
562 match, err := matcher.MatchWithError(httpReq.Request)
563 if err != nil {
564 return types.WrapErr(err)
565 }
566 return types.Bool(match)
567 }
568 if factory, ok := fac.(CELMatcherFactory); ok {
569 matcher, err := factory(matcherData)
570 if err != nil {
571 return types.WrapErr(err)
572 }
573 httpReq := celReq.Value().(celHTTPRequest)
574 if m, ok := matcher.(RequestMatcherWithError); ok {
575 match, err := m.MatchWithError(httpReq.Request)
576 if err != nil {
577 return types.WrapErr(err)
578 }
579 return types.Bool(match)
580 }
581 return types.Bool(matcher.Match(httpReq.Request))
582 }
583 return types.NewErr("CELMatcherRuntimeFunction invalid matcher factory: %T", fac)
584 }
585 }
586
587 // celMatcherStringListMacroExpander validates that the macro is called
588 // with a variable number of string arguments (at least one).
589 //
590 // The arguments are collected into a single list argument the following
591 // function call returned: <funcName>(request, [args])
592 func celMatcherStringListMacroExpander(funcName string) cel.MacroFactory {
593 return func(eh cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
594 matchArgs := []ast.Expr{}
595 if len(args) == 0 {
596 return nil, eh.NewError(0, "matcher requires at least one argument")
597 }
598 for _, arg := range args {
599 if isCELStringExpr(arg) {
600 matchArgs = append(matchArgs, arg)
601 } else {
602 return nil, eh.NewError(arg.ID(), "matcher arguments must be string constants")
603 }
604 }
605 return eh.NewCall(funcName, eh.NewIdent(CELRequestVarName), eh.NewList(matchArgs...)), nil
606 }
607 }
608
609 // celMatcherStringMacroExpander validates that the macro is called a single
610 // string argument.
611 //
612 // The following function call is returned: <funcName>(request, arg)
613 func celMatcherStringMacroExpander(funcName string) parser.MacroExpander {
614 return func(eh cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
615 if len(args) != 1 {
616 return nil, eh.NewError(0, "matcher requires one argument")
617 }
618 if isCELStringExpr(args[0]) {
619 return eh.NewCall(funcName, eh.NewIdent(CELRequestVarName), args[0]), nil
620 }
621 return nil, eh.NewError(args[0].ID(), "matcher argument must be a string literal")
622 }
623 }
624
625 // celMatcherJSONMacroExpander validates that the macro is called a single
626 // map literal argument.
627 //
628 // The following function call is returned: <funcName>(request, arg)
629 func celMatcherJSONMacroExpander(funcName string) parser.MacroExpander {
630 return func(eh cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
631 if len(args) != 1 {
632 return nil, eh.NewError(0, "matcher requires a map literal argument")
633 }
634 arg := args[0]
635
636 switch arg.Kind() {
637 case ast.StructKind:
638 return nil, eh.NewError(arg.ID(),
639 fmt.Sprintf("matcher input must be a map literal, not a %s", arg.AsStruct().TypeName()))
640 case ast.MapKind:
641 mapExpr := arg.AsMap()
642 for _, entry := range mapExpr.Entries() {
643 isStringPlaceholder := isCELStringExpr(entry.AsMapEntry().Key())
644 if !isStringPlaceholder {
645 return nil, eh.NewError(entry.ID(), "matcher map keys must be string literals")
646 }
647 isStringListPlaceholder := isCELStringExpr(entry.AsMapEntry().Value()) ||
648 isCELStringListLiteral(entry.AsMapEntry().Value())
649 if !isStringListPlaceholder {
650 return nil, eh.NewError(entry.AsMapEntry().Value().ID(), "matcher map values must be string or list literals")
651 }
652 }
653 return eh.NewCall(funcName, eh.NewIdent(CELRequestVarName), arg), nil
654 case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.SelectKind:
655 // appeasing the linter :)
656 }
657
658 return nil, eh.NewError(arg.ID(), "matcher requires a map literal argument")
659 }
660 }
661
662 // CELValueToMapStrList converts a CEL value to a map[string][]string
663 //
664 // Earlier validation stages should guarantee that the value has this type
665 // at compile time, and that the runtime value type is map[string]any.
666 // The reason for the slight difference in value type is that CEL allows for
667 // map literals containing heterogeneous values, in this case string and list
668 // of string.
669 func CELValueToMapStrList(data ref.Val) (map[string][]string, error) {
670 // Prefer map[string]any, but newer cel-go versions may return map[any]any
671 mapStrType := reflect.TypeFor[map[string]any]()
672 mapStrRaw, err := data.ConvertToNative(mapStrType)
673 var mapStrIface map[string]any
674 if err != nil {
675 // Try map[any]any and convert keys to strings
676 mapAnyType := reflect.TypeFor[map[any]any]()
677 mapAnyRaw, err2 := data.ConvertToNative(mapAnyType)
678 if err2 != nil {
679 return nil, err
680 }
681 mapAnyIface := mapAnyRaw.(map[any]any)
682 mapStrIface = make(map[string]any, len(mapAnyIface))
683 for k, v := range mapAnyIface {
684 ks, ok := k.(string)
685 if !ok {
686 return nil, fmt.Errorf("unsupported map key type in header match: %T", k)
687 }
688 mapStrIface[ks] = v
689 }
690 } else {
691 mapStrIface = mapStrRaw.(map[string]any)
692 }
693 mapStrListStr := make(map[string][]string, len(mapStrIface))
694 for k, v := range mapStrIface {
695 switch val := v.(type) {
696 case string:
697 mapStrListStr[k] = []string{val}
698 case types.String:
699 mapStrListStr[k] = []string{string(val)}
700 case []string:
701 mapStrListStr[k] = val
702 case []ref.Val:
703 convVals := make([]string, len(val))
704 for i, elem := range val {
705 strVal, ok := elem.(types.String)
706 if !ok {
707 return nil, fmt.Errorf("unsupported value type in matcher input: %T", val)
708 }
709 convVals[i] = string(strVal)
710 }
711 mapStrListStr[k] = convVals
712 case []any:
713 convVals := make([]string, len(val))
714 for i, elem := range val {
715 switch e := elem.(type) {
716 case string:
717 convVals[i] = e
718 case types.String:
719 convVals[i] = string(e)
720 default:
721 return nil, fmt.Errorf("unsupported element type in matcher input list: %T", elem)
722 }
723 }
724 mapStrListStr[k] = convVals
725 default:
726 return nil, fmt.Errorf("unsupported value type in matcher input: %T", val)
727 }
728 }
729 return mapStrListStr, nil
730 }
731
732 // isCELStringExpr indicates whether the expression is a supported string expression
733 func isCELStringExpr(e ast.Expr) bool {
734 return isCELStringLiteral(e) || isCELCaddyPlaceholderCall(e) || isCELConcatCall(e)
735 }
736
737 // isCELStringLiteral returns whether the expression is a CEL string literal.
738 func isCELStringLiteral(e ast.Expr) bool {
739 switch e.Kind() {
740 case ast.LiteralKind:
741 constant := e.AsLiteral()
742 switch constant.Type() {
743 case types.StringType:
744 return true
745 }
746 case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.MapKind, ast.SelectKind, ast.StructKind:
747 // appeasing the linter :)
748 }
749 return false
750 }
751
752 // isCELCaddyPlaceholderCall returns whether the expression is a caddy placeholder call.
753 func isCELCaddyPlaceholderCall(e ast.Expr) bool {
754 switch e.Kind() {
755 case ast.CallKind:
756 call := e.AsCall()
757 if call.FunctionName() == CELPlaceholderFuncName {
758 return true
759 }
760 case ast.UnspecifiedExprKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind:
761 // appeasing the linter :)
762 }
763 return false
764 }
765
766 // isCELConcatCall tests whether the expression is a concat function (+) with string, placeholder, or
767 // other concat call arguments.
768 func isCELConcatCall(e ast.Expr) bool {
769 switch e.Kind() {
770 case ast.CallKind:
771 call := e.AsCall()
772 if call.Target().Kind() != ast.UnspecifiedExprKind {
773 return false
774 }
775 if call.FunctionName() != operators.Add {
776 return false
777 }
778 for _, arg := range call.Args() {
779 if !isCELStringExpr(arg) {
780 return false
781 }
782 }
783 return true
784 case ast.UnspecifiedExprKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind:
785 // appeasing the linter :)
786 }
787 return false
788 }
789
790 // isCELStringListLiteral returns whether the expression resolves to a list literal
791 // containing only string constants or a placeholder call.
792 func isCELStringListLiteral(e ast.Expr) bool {
793 switch e.Kind() {
794 case ast.ListKind:
795 list := e.AsList()
796 for _, elem := range list.Elements() {
797 if !isCELStringExpr(elem) {
798 return false
799 }
800 }
801 return true
802 case ast.UnspecifiedExprKind, ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind:
803 // appeasing the linter :)
804 }
805 return false
806 }
807
808 // Variables used for replacing Caddy placeholders in CEL
809 // expressions with a proper CEL function call; this is
810 // just for syntactic sugar.
811 var (
812 // The placeholder may not be preceded by a backslash; the expansion
813 // will include the preceding character if it is not a backslash.
814 placeholderRegexp = regexp.MustCompile(`([^\\]|^){([a-zA-Z][\w.-]+)}`)
815 placeholderExpansion = `${1}ph(req, "${2}")`
816
817 // As a second pass, we need to strip the escape character in front of
818 // the placeholder, if it exists.
819 escapedPlaceholderRegexp = regexp.MustCompile(`\\{([a-zA-Z][\w.-]+)}`)
820 escapedPlaceholderExpansion = `{${1}}`
821
822 CELTypeJSON = cel.MapType(cel.StringType, cel.DynType)
823 )
824
825 var httpRequestObjectType = cel.ObjectType("http.Request")
826
827 // The name of the CEL function which accesses Replacer values.
828 const CELPlaceholderFuncName = "ph"
829
830 // The name of the CEL request variable.
831 const CELRequestVarName = "req"
832
833 const MatcherNameCtxKey = "matcher_name"
834
835 // Interface guards
836 var (
837 _ caddy.Provisioner = (*MatchExpression)(nil)
838 _ RequestMatcherWithError = (*MatchExpression)(nil)
839 _ caddyfile.Unmarshaler = (*MatchExpression)(nil)
840 _ json.Marshaler = (*MatchExpression)(nil)
841 _ json.Unmarshaler = (*MatchExpression)(nil)
842 )