Debian Codegraph @

modules/caddyhttp/celmatcher_test.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 "context"
19 "crypto/tls"
20 "crypto/x509"
21 "encoding/pem"
22 "net/http"
23 "net/http/httptest"
24 "testing"
25
26 "github.com/caddyserver/caddy/v2"
27 )
28
29 var (
30 clientCert = []byte(`-----BEGIN CERTIFICATE-----
31 MIIB9jCCAV+gAwIBAgIBAjANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDDA1DYWRk
32 eSBUZXN0IENBMB4XDTE4MDcyNDIxMzUwNVoXDTI4MDcyMTIxMzUwNVowHTEbMBkG
33 A1UEAwwSY2xpZW50LmxvY2FsZG9tYWluMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB
34 iQKBgQDFDEpzF0ew68teT3xDzcUxVFaTII+jXH1ftHXxxP4BEYBU4q90qzeKFneF
35 z83I0nC0WAQ45ZwHfhLMYHFzHPdxr6+jkvKPASf0J2v2HDJuTM1bHBbik5Ls5eq+
36 fVZDP8o/VHKSBKxNs8Goc2NTsr5b07QTIpkRStQK+RJALk4x9QIDAQABo0swSTAJ
37 BgNVHRMEAjAAMAsGA1UdDwQEAwIHgDAaBgNVHREEEzARgglsb2NhbGhvc3SHBH8A
38 AAEwEwYDVR0lBAwwCgYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADgYEANSjz2Sk+
39 eqp31wM9il1n+guTNyxJd+FzVAH+hCZE5K+tCgVDdVFUlDEHHbS/wqb2PSIoouLV
40 3Q9fgDkiUod+uIK0IynzIKvw+Cjg+3nx6NQ0IM0zo8c7v398RzB4apbXKZyeeqUH
41 9fNwfEi+OoXR6s+upSKobCmLGLGi9Na5s5g=
42 -----END CERTIFICATE-----`)
43
44 matcherTests = []struct {
45 name string
46 expression *MatchExpression
47 urlTarget string
48 httpMethod string
49 httpHeader *http.Header
50 wantErr bool
51 wantResult bool
52 clientCertificate []byte
53 }{
54 {
55 name: "boolean matches succeed for placeholder http.request.tls.client.subject",
56 expression: &MatchExpression{
57 Expr: "{http.request.tls.client.subject} == 'CN=client.localdomain'",
58 },
59 clientCertificate: clientCert,
60 urlTarget: "https://example.com/foo",
61 wantResult: true,
62 },
63 {
64 name: "header matches (MatchHeader)",
65 expression: &MatchExpression{
66 Expr: `header({'Field': 'foo'})`,
67 },
68 urlTarget: "https://example.com/foo",
69 httpHeader: &http.Header{"Field": []string{"foo", "bar"}},
70 wantResult: true,
71 },
72 {
73 name: "header matches an escaped placeholder value (MatchHeader)",
74 expression: &MatchExpression{
75 Expr: `header({'Field': '\\\{foobar}'})`,
76 },
77 urlTarget: "https://example.com/foo",
78 httpHeader: &http.Header{"Field": []string{"{foobar}"}},
79 wantResult: true,
80 },
81 {
82 name: "header matches a placeholder replaced during the header matcher (MatchHeader)",
83 expression: &MatchExpression{
84 Expr: `header({'Field': '\{http.request.uri.path}'})`,
85 },
86 urlTarget: "https://example.com/foo",
87 httpHeader: &http.Header{"Field": []string{"/foo"}},
88 wantResult: true,
89 },
90 {
91 name: "header error, invalid escape sequence (MatchHeader)",
92 expression: &MatchExpression{
93 Expr: `header({'Field': '\\{foobar}'})`,
94 },
95 wantErr: true,
96 },
97 {
98 name: "header error, needs to be JSON syntax with field as key (MatchHeader)",
99 expression: &MatchExpression{
100 Expr: `header('foo')`,
101 },
102 wantErr: true,
103 },
104 {
105 name: "header_regexp matches (MatchHeaderRE)",
106 expression: &MatchExpression{
107 Expr: `header_regexp('Field', 'fo{2}')`,
108 },
109 urlTarget: "https://example.com/foo",
110 httpHeader: &http.Header{"Field": []string{"foo", "bar"}},
111 wantResult: true,
112 },
113 {
114 name: "header_regexp matches with name (MatchHeaderRE)",
115 expression: &MatchExpression{
116 Expr: `header_regexp('foo', 'Field', 'fo{2}')`,
117 },
118 urlTarget: "https://example.com/foo",
119 httpHeader: &http.Header{"Field": []string{"foo", "bar"}},
120 wantResult: true,
121 },
122 {
123 name: "header_regexp does not match (MatchHeaderRE)",
124 expression: &MatchExpression{
125 Expr: `header_regexp('foo', 'Nope', 'fo{2}')`,
126 },
127 urlTarget: "https://example.com/foo",
128 httpHeader: &http.Header{"Field": []string{"foo", "bar"}},
129 wantResult: false,
130 },
131 {
132 name: "header_regexp error (MatchHeaderRE)",
133 expression: &MatchExpression{
134 Expr: `header_regexp('foo')`,
135 },
136 wantErr: true,
137 },
138 {
139 name: "host matches localhost (MatchHost)",
140 expression: &MatchExpression{
141 Expr: `host('localhost')`,
142 },
143 urlTarget: "http://localhost",
144 wantResult: true,
145 },
146 {
147 name: "host matches (MatchHost)",
148 expression: &MatchExpression{
149 Expr: `host('*.example.com')`,
150 },
151 urlTarget: "https://foo.example.com",
152 wantResult: true,
153 },
154 {
155 name: "host does not match (MatchHost)",
156 expression: &MatchExpression{
157 Expr: `host('example.net', '*.example.com')`,
158 },
159 urlTarget: "https://foo.example.org",
160 wantResult: false,
161 },
162 {
163 name: "host error (MatchHost)",
164 expression: &MatchExpression{
165 Expr: `host(80)`,
166 },
167 wantErr: true,
168 },
169 {
170 name: "method does not match (MatchMethod)",
171 expression: &MatchExpression{
172 Expr: `method('PUT')`,
173 },
174 urlTarget: "https://foo.example.com",
175 httpMethod: "GET",
176 wantResult: false,
177 },
178 {
179 name: "method matches (MatchMethod)",
180 expression: &MatchExpression{
181 Expr: `method('DELETE', 'PUT', 'POST')`,
182 },
183 urlTarget: "https://foo.example.com",
184 httpMethod: "PUT",
185 wantResult: true,
186 },
187 {
188 name: "method error not enough arguments (MatchMethod)",
189 expression: &MatchExpression{
190 Expr: `method()`,
191 },
192 wantErr: true,
193 },
194 {
195 name: "path matches substring (MatchPath)",
196 expression: &MatchExpression{
197 Expr: `path('*substring*')`,
198 },
199 urlTarget: "https://example.com/foo/substring/bar.txt",
200 wantResult: true,
201 },
202 {
203 name: "path does not match (MatchPath)",
204 expression: &MatchExpression{
205 Expr: `path('/foo')`,
206 },
207 urlTarget: "https://example.com/foo/bar",
208 wantResult: false,
209 },
210 {
211 name: "path matches end url fragment (MatchPath)",
212 expression: &MatchExpression{
213 Expr: `path('/foo')`,
214 },
215 urlTarget: "https://example.com/FOO",
216 wantResult: true,
217 },
218 {
219 name: "path matches end fragment with substring prefix (MatchPath)",
220 expression: &MatchExpression{
221 Expr: `path('/foo*')`,
222 },
223 urlTarget: "https://example.com/FOOOOO",
224 wantResult: true,
225 },
226 {
227 name: "path matches one of multiple (MatchPath)",
228 expression: &MatchExpression{
229 Expr: `path('/foo', '/foo/*', '/bar', '/bar/*', '/baz', '/baz*')`,
230 },
231 urlTarget: "https://example.com/foo",
232 wantResult: true,
233 },
234 {
235 name: "path_regexp with empty regex matches empty path (MatchPathRE)",
236 expression: &MatchExpression{
237 Expr: `path_regexp('')`,
238 },
239 urlTarget: "https://example.com/",
240 wantResult: true,
241 },
242 {
243 name: "path_regexp with slash regex matches empty path (MatchPathRE)",
244 expression: &MatchExpression{
245 Expr: `path_regexp('/')`,
246 },
247 urlTarget: "https://example.com/",
248 wantResult: true,
249 },
250 {
251 name: "path_regexp matches end url fragment (MatchPathRE)",
252 expression: &MatchExpression{
253 Expr: `path_regexp('^/foo')`,
254 },
255 urlTarget: "https://example.com/foo/",
256 wantResult: true,
257 },
258 {
259 name: "path_regexp does not match fragment at end (MatchPathRE)",
260 expression: &MatchExpression{
261 Expr: `path_regexp('bar_at_start', '^/bar')`,
262 },
263 urlTarget: "https://example.com/foo/bar",
264 wantResult: false,
265 },
266 {
267 name: "protocol matches (MatchProtocol)",
268 expression: &MatchExpression{
269 Expr: `protocol('HTTPs')`,
270 },
271 urlTarget: "https://example.com",
272 wantResult: true,
273 },
274 {
275 name: "protocol does not match (MatchProtocol)",
276 expression: &MatchExpression{
277 Expr: `protocol('grpc')`,
278 },
279 urlTarget: "https://example.com",
280 wantResult: false,
281 },
282 {
283 name: "protocol invocation error no args (MatchProtocol)",
284 expression: &MatchExpression{
285 Expr: `protocol()`,
286 },
287 wantErr: true,
288 },
289 {
290 name: "protocol invocation error too many args (MatchProtocol)",
291 expression: &MatchExpression{
292 Expr: `protocol('grpc', 'https')`,
293 },
294 wantErr: true,
295 },
296 {
297 name: "protocol invocation error wrong arg type (MatchProtocol)",
298 expression: &MatchExpression{
299 Expr: `protocol(true)`,
300 },
301 wantErr: true,
302 },
303 {
304 name: "query does not match against a specific value (MatchQuery)",
305 expression: &MatchExpression{
306 Expr: `query({"debug": "1"})`,
307 },
308 urlTarget: "https://example.com/foo",
309 wantResult: false,
310 },
311 {
312 name: "query matches against a specific value (MatchQuery)",
313 expression: &MatchExpression{
314 Expr: `query({"debug": "1"})`,
315 },
316 urlTarget: "https://example.com/foo/?debug=1",
317 wantResult: true,
318 },
319 {
320 name: "query matches against multiple values (MatchQuery)",
321 expression: &MatchExpression{
322 Expr: `query({"debug": ["0", "1", {http.request.uri.query.debug}+"1"]})`,
323 },
324 urlTarget: "https://example.com/foo/?debug=1",
325 wantResult: true,
326 },
327 {
328 name: "query matches against a wildcard (MatchQuery)",
329 expression: &MatchExpression{
330 Expr: `query({"debug": ["*"]})`,
331 },
332 urlTarget: "https://example.com/foo/?debug=something",
333 wantResult: true,
334 },
335 {
336 name: "query matches against a placeholder value (MatchQuery)",
337 expression: &MatchExpression{
338 Expr: `query({"debug": {http.request.uri.query.debug}})`,
339 },
340 urlTarget: "https://example.com/foo/?debug=1",
341 wantResult: true,
342 },
343 {
344 name: "query error bad map key type (MatchQuery)",
345 expression: &MatchExpression{
346 Expr: `query({1: "1"})`,
347 },
348 wantErr: true,
349 },
350 {
351 name: "query error typed struct instead of map (MatchQuery)",
352 expression: &MatchExpression{
353 Expr: `query(Message{field: "1"})`,
354 },
355 wantErr: true,
356 },
357 {
358 name: "query error bad map value type (MatchQuery)",
359 expression: &MatchExpression{
360 Expr: `query({"debug": 1})`,
361 },
362 wantErr: true,
363 },
364 {
365 name: "query error no args (MatchQuery)",
366 expression: &MatchExpression{
367 Expr: `query()`,
368 },
369 wantErr: true,
370 },
371 {
372 name: "remote_ip error no args (MatchRemoteIP)",
373 expression: &MatchExpression{
374 Expr: `remote_ip()`,
375 },
376 wantErr: true,
377 },
378 {
379 name: "remote_ip single IP match (MatchRemoteIP)",
380 expression: &MatchExpression{
381 Expr: `remote_ip('192.0.2.1')`,
382 },
383 urlTarget: "https://example.com/foo",
384 wantResult: true,
385 },
386 {
387 name: "vars value (VarsMatcher)",
388 expression: &MatchExpression{
389 Expr: `vars({'foo': 'bar'})`,
390 },
391 urlTarget: "https://example.com/foo",
392 wantResult: true,
393 },
394 {
395 name: "vars matches placeholder, needs escape (VarsMatcher)",
396 expression: &MatchExpression{
397 Expr: `vars({'\{http.request.uri.path}': '/foo'})`,
398 },
399 urlTarget: "https://example.com/foo",
400 wantResult: true,
401 },
402 {
403 name: "vars error wrong syntax (VarsMatcher)",
404 expression: &MatchExpression{
405 Expr: `vars('foo', 'bar')`,
406 },
407 wantErr: true,
408 },
409 {
410 name: "vars error no args (VarsMatcher)",
411 expression: &MatchExpression{
412 Expr: `vars()`,
413 },
414 wantErr: true,
415 },
416 {
417 name: "vars_regexp value (MatchVarsRE)",
418 expression: &MatchExpression{
419 Expr: `vars_regexp('foo', 'ba?r')`,
420 },
421 urlTarget: "https://example.com/foo",
422 wantResult: true,
423 },
424 {
425 name: "vars_regexp value with name (MatchVarsRE)",
426 expression: &MatchExpression{
427 Expr: `vars_regexp('name', 'foo', 'ba?r')`,
428 },
429 urlTarget: "https://example.com/foo",
430 wantResult: true,
431 },
432 {
433 name: "vars_regexp matches placeholder, needs escape (MatchVarsRE)",
434 expression: &MatchExpression{
435 Expr: `vars_regexp('\{http.request.uri.path}', '/fo?o')`,
436 },
437 urlTarget: "https://example.com/foo",
438 wantResult: true,
439 },
440 {
441 name: "vars_regexp error no args (MatchVarsRE)",
442 expression: &MatchExpression{
443 Expr: `vars_regexp()`,
444 },
445 wantErr: true,
446 },
447 }
448 )
449
450 func TestMatchExpressionMatch(t *testing.T) {
451 for _, tst := range matcherTests {
452 tc := tst
453 t.Run(tc.name, func(t *testing.T) {
454 caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()})
455 defer cancel()
456 err := tc.expression.Provision(caddyCtx)
457 if err != nil {
458 if !tc.wantErr {
459 t.Errorf("MatchExpression.Provision() error = %v, wantErr %v", err, tc.wantErr)
460 }
461 return
462 }
463
464 req := httptest.NewRequest(tc.httpMethod, tc.urlTarget, nil)
465 if tc.httpHeader != nil {
466 req.Header = *tc.httpHeader
467 }
468 repl := caddy.NewReplacer()
469 ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
470 ctx = context.WithValue(ctx, VarsCtxKey, map[string]any{
471 "foo": "bar",
472 })
473 req = req.WithContext(ctx)
474 addHTTPVarsToReplacer(repl, req, httptest.NewRecorder())
475
476 if tc.clientCertificate != nil {
477 block, _ := pem.Decode(clientCert)
478 if block == nil {
479 t.Fatalf("failed to decode PEM certificate")
480 }
481
482 cert, err := x509.ParseCertificate(block.Bytes)
483 if err != nil {
484 t.Fatalf("failed to decode PEM certificate: %v", err)
485 }
486
487 req.TLS = &tls.ConnectionState{
488 PeerCertificates: []*x509.Certificate{cert},
489 }
490 }
491
492 matches, err := tc.expression.MatchWithError(req)
493 if err != nil {
494 t.Errorf("MatchExpression.Match() error = %v", err)
495 }
496 if matches != tc.wantResult {
497 t.Errorf("MatchExpression.Match() expected to return '%t', for expression : '%s'", tc.wantResult, tc.expression.Expr)
498 }
499 })
500 }
501 }
502
503 func BenchmarkMatchExpressionMatch(b *testing.B) {
504 for _, tst := range matcherTests {
505 tc := tst
506 if tc.wantErr {
507 continue
508 }
509 b.Run(tst.name, func(b *testing.B) {
510 tc.expression.Provision(caddy.Context{})
511 req := httptest.NewRequest(tc.httpMethod, tc.urlTarget, nil)
512 if tc.httpHeader != nil {
513 req.Header = *tc.httpHeader
514 }
515 repl := caddy.NewReplacer()
516 ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
517 ctx = context.WithValue(ctx, VarsCtxKey, map[string]any{
518 "foo": "bar",
519 })
520 req = req.WithContext(ctx)
521 addHTTPVarsToReplacer(repl, req, httptest.NewRecorder())
522 if tc.clientCertificate != nil {
523 block, _ := pem.Decode(clientCert)
524 if block == nil {
525 b.Fatalf("failed to decode PEM certificate")
526 }
527
528 cert, err := x509.ParseCertificate(block.Bytes)
529 if err != nil {
530 b.Fatalf("failed to decode PEM certificate: %v", err)
531 }
532
533 req.TLS = &tls.ConnectionState{
534 PeerCertificates: []*x509.Certificate{cert},
535 }
536 }
537 b.ResetTimer()
538 for b.Loop() {
539 tc.expression.MatchWithError(req)
540 }
541 })
542 }
543 }
544
545 func TestMatchExpressionProvision(t *testing.T) {
546 tests := []struct {
547 name string
548 expression *MatchExpression
549 wantErr bool
550 }{
551 {
552 name: "boolean matches succeed",
553 expression: &MatchExpression{
554 Expr: "{http.request.uri.query} != ''",
555 },
556 wantErr: false,
557 },
558 {
559 name: "reject expressions with non-boolean results",
560 expression: &MatchExpression{
561 Expr: "{http.request.uri.query}",
562 },
563 wantErr: true,
564 },
565 }
566 for _, tt := range tests {
567 t.Run(tt.name, func(t *testing.T) {
568 ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()})
569 defer cancel()
570 if err := tt.expression.Provision(ctx); (err != nil) != tt.wantErr {
571 t.Errorf("MatchExpression.Provision() error = %v, wantErr %v", err, tt.wantErr)
572 }
573 })
574 }
575 }