Debian Codegraph @

modules/caddyhttp/templates/tplcontext_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 templates
16
17 import (
18 "bytes"
19 "context"
20 "errors"
21 "fmt"
22 "io/fs"
23 "net/http"
24 "os"
25 "path/filepath"
26 "reflect"
27 "sort"
28 "strings"
29 "testing"
30 "time"
31
32 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
33 )
34
35 type handle struct{}
36
37 func (h *handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
38 if r.Header.Get("Accept-Encoding") == "identity" {
39 w.Write([]byte("good contents"))
40 } else {
41 w.Write([]byte("bad cause Accept-Encoding: " + r.Header.Get("Accept-Encoding")))
42 }
43 }
44
45 func TestHTTPInclude(t *testing.T) {
46 tplContext := getContextOrFail(t)
47 for i, test := range []struct {
48 uri string
49 handler *handle
50 expect string
51 }{
52 {
53 uri: "https://example.com/foo/bar",
54 handler: &handle{},
55 expect: "good contents",
56 },
57 } {
58 ctx := context.WithValue(tplContext.Req.Context(), caddyhttp.ServerCtxKey, test.handler)
59 tplContext.Req = tplContext.Req.WithContext(ctx)
60 tplContext.Req.Header.Add("Accept-Encoding", "gzip")
61 result, err := tplContext.funcHTTPInclude(test.uri)
62 if result != test.expect {
63 t.Errorf("Test %d: expected '%s' but got '%s'", i, test.expect, result)
64 }
65 if err != nil {
66 t.Errorf("Test %d: got error: %v", i, result)
67 }
68 }
69 }
70
71 func TestMarkdown(t *testing.T) {
72 tplContext := getContextOrFail(t)
73
74 for i, test := range []struct {
75 body string
76 expect string
77 }{
78 {
79 body: "- str1\n- str2\n",
80 expect: "<ul>\n<li>str1</li>\n<li>str2</li>\n</ul>\n",
81 },
82 } {
83 result, err := tplContext.funcMarkdown(test.body)
84 if result != test.expect {
85 t.Errorf("Test %d: expected '%s' but got '%s'", i, test.expect, result)
86 }
87 if err != nil {
88 t.Errorf("Test %d: got error: %v", i, result)
89 }
90 }
91 }
92
93 func TestCookie(t *testing.T) {
94 for i, test := range []struct {
95 cookie *http.Cookie
96 cookieName string
97 expect string
98 }{
99 {
100 // happy path
101 cookie: &http.Cookie{Name: "cookieName", Value: "cookieValue"},
102 cookieName: "cookieName",
103 expect: "cookieValue",
104 },
105 {
106 // try to get a non-existing cookie
107 cookie: &http.Cookie{Name: "cookieName", Value: "cookieValue"},
108 cookieName: "notExisting",
109 expect: "",
110 },
111 {
112 // partial name match
113 cookie: &http.Cookie{Name: "cookie", Value: "cookieValue"},
114 cookieName: "cook",
115 expect: "",
116 },
117 {
118 // cookie with optional fields
119 cookie: &http.Cookie{Name: "cookie", Value: "cookieValue", Path: "/path", Domain: "https://localhost", Expires: time.Now().Add(10 * time.Minute), MaxAge: 120},
120 cookieName: "cookie",
121 expect: "cookieValue",
122 },
123 } {
124 tplContext := getContextOrFail(t)
125 tplContext.Req.AddCookie(test.cookie)
126 actual := tplContext.Cookie(test.cookieName)
127 if actual != test.expect {
128 t.Errorf("Test %d: Expected cookie value '%s' but got '%s' for cookie with name '%s'",
129 i, test.expect, actual, test.cookieName)
130 }
131 }
132 }
133
134 func TestImport(t *testing.T) {
135 for i, test := range []struct {
136 fileContent string
137 fileName string
138 shouldErr bool
139 expect string
140 }{
141 {
142 // file exists, template is defined
143 fileContent: `{{ define "imported" }}text{{end}}`,
144 fileName: "file1",
145 shouldErr: false,
146 expect: `"imported"`,
147 },
148 {
149 // file does not exit
150 fileContent: "",
151 fileName: "",
152 shouldErr: true,
153 },
154 } {
155 tplContext := getContextOrFail(t)
156 var absFilePath string
157
158 // create files for test case
159 if test.fileName != "" {
160 absFilePath := filepath.Join(fmt.Sprintf("%s", tplContext.Root), test.fileName)
161 if err := os.WriteFile(absFilePath, []byte(test.fileContent), os.ModePerm); err != nil {
162 os.Remove(absFilePath)
163 t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error())
164 }
165 }
166
167 // perform test
168 tplContext.NewTemplate("parent")
169 actual, err := tplContext.funcImport(test.fileName)
170 templateWasDefined := strings.Contains(tplContext.tpl.DefinedTemplates(), test.expect)
171 if err != nil {
172 if !test.shouldErr {
173 t.Errorf("Test %d: Expected no error, got: '%s'", i, err)
174 }
175 } else if test.shouldErr {
176 t.Errorf("Test %d: Expected error but had none", i)
177 } else if !templateWasDefined && actual != "" {
178 // template should be defined, return value should be an empty string
179 t.Errorf("Test %d: Expected template %s to be define but got %s", i, test.expect, tplContext.tpl.DefinedTemplates())
180 }
181
182 if absFilePath != "" {
183 if err := os.Remove(absFilePath); err != nil && !errors.Is(err, fs.ErrNotExist) {
184 t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err)
185 }
186 }
187 }
188 }
189
190 func TestNestedInclude(t *testing.T) {
191 for i, test := range []struct {
192 child string
193 childFile string
194 parent string
195 parentFile string
196 shouldErr bool
197 expect string
198 child2 string
199 child2File string
200 }{
201 {
202 // include in parent
203 child: `{{ include "file1" }}`,
204 childFile: "file0",
205 parent: `{{ $content := "file2" }}{{ $p := include $content}}`,
206 parentFile: "file1",
207 shouldErr: false,
208 expect: ``,
209 child2: `This shouldn't show`,
210 child2File: "file2",
211 },
212 } {
213 context := getContextOrFail(t)
214 var absFilePath string
215 var absFilePath0 string
216 var absFilePath1 string
217 var buf *bytes.Buffer
218 var err error
219
220 // create files and for test case
221 if test.parentFile != "" {
222 absFilePath = filepath.Join(fmt.Sprintf("%s", context.Root), test.parentFile)
223 if err := os.WriteFile(absFilePath, []byte(test.parent), os.ModePerm); err != nil {
224 os.Remove(absFilePath)
225 t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error())
226 }
227 }
228 if test.childFile != "" {
229 absFilePath0 = filepath.Join(fmt.Sprintf("%s", context.Root), test.childFile)
230 if err := os.WriteFile(absFilePath0, []byte(test.child), os.ModePerm); err != nil {
231 os.Remove(absFilePath0)
232 t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error())
233 }
234 }
235 if test.child2File != "" {
236 absFilePath1 = filepath.Join(fmt.Sprintf("%s", context.Root), test.child2File)
237 if err := os.WriteFile(absFilePath1, []byte(test.child2), os.ModePerm); err != nil {
238 os.Remove(absFilePath0)
239 t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error())
240 }
241 }
242
243 buf = bufPool.Get().(*bytes.Buffer)
244 buf.Reset()
245 defer bufPool.Put(buf)
246 buf.WriteString(test.child)
247 err = context.executeTemplateInBuffer(test.childFile, buf)
248
249 if err != nil {
250 if !test.shouldErr {
251 t.Errorf("Test %d: Expected no error, got: '%s'", i, err)
252 }
253 } else if test.shouldErr {
254 t.Errorf("Test %d: Expected error but had none", i)
255 } else if buf.String() != test.expect {
256 //
257 t.Errorf("Test %d: Expected '%s' but got '%s'", i, test.expect, buf.String())
258 }
259
260 if absFilePath != "" {
261 if err := os.Remove(absFilePath); err != nil && !errors.Is(err, fs.ErrNotExist) {
262 t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err)
263 }
264 }
265 if absFilePath0 != "" {
266 if err := os.Remove(absFilePath0); err != nil && !errors.Is(err, fs.ErrNotExist) {
267 t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err)
268 }
269 }
270 if absFilePath1 != "" {
271 if err := os.Remove(absFilePath1); err != nil && !errors.Is(err, fs.ErrNotExist) {
272 t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err)
273 }
274 }
275 }
276 }
277
278 func TestInclude(t *testing.T) {
279 for i, test := range []struct {
280 fileContent string
281 fileName string
282 shouldErr bool
283 expect string
284 args string
285 }{
286 {
287 // file exists, content is text only
288 fileContent: "text",
289 fileName: "file1",
290 shouldErr: false,
291 expect: "text",
292 },
293 {
294 // file exists, content is template
295 fileContent: "{{ if . }}text{{ end }}",
296 fileName: "file1",
297 shouldErr: false,
298 expect: "text",
299 },
300 {
301 // file does not exit
302 fileContent: "",
303 fileName: "",
304 shouldErr: true,
305 },
306 {
307 // args
308 fileContent: "{{ index .Args 0 }}",
309 fileName: "file1",
310 shouldErr: false,
311 args: "text",
312 expect: "text",
313 },
314 {
315 // args, reference arg out of range
316 fileContent: "{{ index .Args 1 }}",
317 fileName: "file1",
318 shouldErr: true,
319 args: "text",
320 },
321 } {
322 tplContext := getContextOrFail(t)
323 var absFilePath string
324
325 // create files for test case
326 if test.fileName != "" {
327 absFilePath := filepath.Join(fmt.Sprintf("%s", tplContext.Root), test.fileName)
328 if err := os.WriteFile(absFilePath, []byte(test.fileContent), os.ModePerm); err != nil {
329 os.Remove(absFilePath)
330 t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error())
331 }
332 }
333
334 // perform test
335 actual, err := tplContext.funcInclude(test.fileName, test.args)
336 if err != nil {
337 if !test.shouldErr {
338 t.Errorf("Test %d: Expected no error, got: '%s'", i, err)
339 }
340 } else if test.shouldErr {
341 t.Errorf("Test %d: Expected error but had none", i)
342 } else if actual != test.expect {
343 t.Errorf("Test %d: Expected %s but got %s", i, test.expect, actual)
344 }
345
346 if absFilePath != "" {
347 if err := os.Remove(absFilePath); err != nil && !errors.Is(err, fs.ErrNotExist) {
348 t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err)
349 }
350 }
351 }
352 }
353
354 func TestCookieMultipleCookies(t *testing.T) {
355 tplContext := getContextOrFail(t)
356
357 cookieNameBase, cookieValueBase := "cookieName", "cookieValue"
358
359 for i := 0; i < 10; i++ {
360 tplContext.Req.AddCookie(&http.Cookie{
361 Name: fmt.Sprintf("%s%d", cookieNameBase, i),
362 Value: fmt.Sprintf("%s%d", cookieValueBase, i),
363 })
364 }
365
366 for i := 0; i < 10; i++ {
367 expectedCookieVal := fmt.Sprintf("%s%d", cookieValueBase, i)
368 actualCookieVal := tplContext.Cookie(fmt.Sprintf("%s%d", cookieNameBase, i))
369 if actualCookieVal != expectedCookieVal {
370 t.Errorf("Expected cookie value %s, found %s", expectedCookieVal, actualCookieVal)
371 }
372 }
373 }
374
375 func TestIP(t *testing.T) {
376 tplContext := getContextOrFail(t)
377 for i, test := range []struct {
378 inputRemoteAddr string
379 expect string
380 }{
381 {"1.1.1.1:1111", "1.1.1.1"},
382 {"1.1.1.1", "1.1.1.1"},
383 {"[::1]:11", "::1"},
384 {"[2001:db8:a0b:12f0::1]", "[2001:db8:a0b:12f0::1]"},
385 {`[fe80:1::3%eth0]:44`, `fe80:1::3%eth0`},
386 } {
387 tplContext.Req.RemoteAddr = test.inputRemoteAddr
388 if actual := tplContext.RemoteIP(); actual != test.expect {
389 t.Errorf("Test %d: Expected %s but got %s", i, test.expect, actual)
390 }
391 }
392 }
393
394 func TestStripHTML(t *testing.T) {
395 tplContext := getContextOrFail(t)
396
397 for i, test := range []struct {
398 input string
399 expect string
400 }{
401 {
402 // no tags
403 input: `h1`,
404 expect: `h1`,
405 },
406 {
407 // happy path
408 input: `<h1>h1</h1>`,
409 expect: `h1`,
410 },
411 {
412 // tag in quotes
413 input: `<h1">">h1</h1>`,
414 expect: `h1`,
415 },
416 {
417 // multiple tags
418 input: `<h1><b>h1</b></h1>`,
419 expect: `h1`,
420 },
421 {
422 // unclosed tag — trailing text must be stripped, not emitted
423 input: `<h1`,
424 expect: ``,
425 },
426 {
427 // false start — second '<' increments depth, single '>' only closes one level
428 input: `<h1<b>hi`,
429 expect: ``,
430 },
431 {
432 // XSS bypass via double opening bracket
433 input: `<<>img src=x onerror=alert('XSS')>`,
434 expect: ``,
435 },
436 {
437 // stacked angle brackets (PHP strip_tags parity)
438 input: `<<<<<>>>>><b>hello</b>`,
439 expect: `hello`,
440 },
441 {
442 // unclosed tag strips trailing text
443 input: `hello <world`,
444 expect: `hello `,
445 },
446 {
447 // '>' inside double-quoted attribute must not close tag early
448 input: `<a href="foo>bar">text</a>`,
449 expect: `text`,
450 },
451 {
452 // '>' inside single-quoted attribute must not close tag early
453 input: `<a href='foo>bar'>text</a>`,
454 expect: `text`,
455 },
456 {
457 // stray '>' with no opening '<' is preserved
458 input: `stray > bracket`,
459 expect: `stray > bracket`,
460 },
461 } {
462 actual := tplContext.funcStripHTML(test.input)
463 if actual != test.expect {
464 t.Errorf("Test %d: Expected %s, found %s. Input was StripHTML(%s)", i, test.expect, actual, test.input)
465 }
466 }
467 }
468
469 func TestFileListing(t *testing.T) {
470 for i, test := range []struct {
471 fileNames []string
472 inputBase string
473 shouldErr bool
474 verifyErr func(error) bool
475 }{
476 {
477 // directory and files exist
478 fileNames: []string{"file1", "file2"},
479 shouldErr: false,
480 },
481 {
482 // directory exists, no files
483 fileNames: []string{},
484 shouldErr: false,
485 },
486 {
487 // file or directory does not exist
488 fileNames: nil,
489 inputBase: "doesNotExist",
490 shouldErr: true,
491 verifyErr: func(err error) bool { return errors.Is(err, fs.ErrNotExist) },
492 },
493 {
494 // directory and files exist, but path to a file
495 fileNames: []string{"file1", "file2"},
496 inputBase: "file1",
497 shouldErr: true,
498 verifyErr: func(err error) bool {
499 return strings.HasSuffix(err.Error(), "is not a directory")
500 },
501 },
502 {
503 // try to escape Context Root
504 fileNames: nil,
505 inputBase: filepath.Join("..", "..", "..", "..", "..", "etc"),
506 shouldErr: true,
507 verifyErr: func(err error) bool { return errors.Is(err, fs.ErrNotExist) },
508 },
509 } {
510 tplContext := getContextOrFail(t)
511 var dirPath string
512 var err error
513
514 // create files for test case
515 if test.fileNames != nil {
516 dirPath, err = os.MkdirTemp(fmt.Sprintf("%s", tplContext.Root), "caddy_ctxtest")
517 if err != nil {
518 t.Fatalf("Test %d: Expected no error creating directory, got: '%s'", i, err.Error())
519 }
520 for _, name := range test.fileNames {
521 absFilePath := filepath.Join(dirPath, name)
522 if err = os.WriteFile(absFilePath, []byte(""), os.ModePerm); err != nil {
523 os.RemoveAll(dirPath)
524 t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error())
525 }
526 }
527 }
528
529 // perform test
530 input := filepath.ToSlash(filepath.Join(filepath.Base(dirPath), test.inputBase))
531 actual, err := tplContext.funcListFiles(input)
532 if err != nil {
533 if !test.shouldErr {
534 t.Errorf("Test %d: Expected no error, got: '%s'", i, err)
535 } else if !test.verifyErr(err) {
536 t.Errorf("Test %d: Could not verify error content, got: '%s'", i, err)
537 }
538 } else if test.shouldErr {
539 t.Errorf("Test %d: Expected error but had none", i)
540 } else {
541 numFiles := len(test.fileNames)
542 // reflect.DeepEqual does not consider two empty slices to be equal
543 if numFiles == 0 && len(actual) != 0 {
544 t.Errorf("Test %d: Expected files %v, got: %v",
545 i, test.fileNames, actual)
546 } else {
547 sort.Strings(actual)
548 if numFiles > 0 && !reflect.DeepEqual(test.fileNames, actual) {
549 t.Errorf("Test %d: Expected files %v, got: %v",
550 i, test.fileNames, actual)
551 }
552 }
553 }
554
555 if dirPath != "" {
556 if err := os.RemoveAll(dirPath); err != nil && !errors.Is(err, fs.ErrNotExist) {
557 t.Fatalf("Test %d: Expected no error removing temporary test directory, got: %v", i, err)
558 }
559 }
560 }
561 }
562
563 func TestSplitFrontMatter(t *testing.T) {
564 tplContext := getContextOrFail(t)
565
566 for i, test := range []struct {
567 input string
568 expect string
569 body string
570 }{
571 {
572 // yaml with windows newline
573 input: "---\r\ntitle: Welcome\r\n---\r\n# Test\\r\\n",
574 expect: `Welcome`,
575 body: "\r\n# Test\\r\\n",
576 },
577 {
578 // yaml
579 input: `---
580 title: Welcome
581 ---
582 ### Test`,
583 expect: `Welcome`,
584 body: "\n### Test",
585 },
586 {
587 // yaml with dots for closer
588 input: `---
589 title: Welcome
590 ...
591 ### Test`,
592 expect: `Welcome`,
593 body: "\n### Test",
594 },
595 {
596 // yaml with non-fence '...' line after closing fence (i.e. first matching closing fence should be used)
597 input: `---
598 title: Welcome
599 ---
600 ### Test
601 ...
602 yeah`,
603 expect: `Welcome`,
604 body: "\n### Test\n...\nyeah",
605 },
606 {
607 // toml
608 input: `+++
609 title = "Welcome"
610 +++
611 ### Test`,
612 expect: `Welcome`,
613 body: "\n### Test",
614 },
615 {
616 // json
617 input: `{
618 "title": "Welcome"
619 }
620 ### Test`,
621 expect: `Welcome`,
622 body: "\n### Test",
623 },
624 } {
625 result, _ := tplContext.funcSplitFrontMatter(test.input)
626 if result.Meta["title"] != test.expect {
627 t.Errorf("Test %d: Expected %s, found %s. Input was SplitFrontMatter(%s)", i, test.expect, result.Meta["title"], test.input)
628 }
629 if result.Body != test.body {
630 t.Errorf("Test %d: Expected body %s, found %s. Input was SplitFrontMatter(%s)", i, test.body, result.Body, test.input)
631 }
632 }
633 }
634
635 func TestHumanize(t *testing.T) {
636 tplContext := getContextOrFail(t)
637 for i, test := range []struct {
638 format string
639 inputData string
640 expect string
641 errorCase bool
642 verifyErr func(actual_string, substring string) bool
643 }{
644 {
645 format: "size",
646 inputData: "2048000",
647 expect: "2.0 MB",
648 errorCase: false,
649 verifyErr: strings.Contains,
650 },
651 {
652 format: "time",
653 inputData: "Fri, 05 May 2022 15:04:05 +0200",
654 expect: "ago",
655 errorCase: false,
656 verifyErr: strings.HasSuffix,
657 },
658 {
659 format: "time:2006-Jan-02",
660 inputData: "2022-May-05",
661 expect: "ago",
662 errorCase: false,
663 verifyErr: strings.HasSuffix,
664 },
665 {
666 format: "time",
667 inputData: "Fri, 05 May 2022 15:04:05 GMT+0200",
668 expect: "error:",
669 errorCase: true,
670 verifyErr: strings.HasPrefix,
671 },
672 } {
673 if actual, err := tplContext.funcHumanize(test.format, test.inputData); !test.verifyErr(actual, test.expect) {
674 if !test.errorCase {
675 t.Errorf("Test %d: Expected '%s' but got '%s'", i, test.expect, actual)
676 if err != nil {
677 t.Errorf("Test %d: error: %s", i, err.Error())
678 }
679 }
680 }
681 }
682 }
683
684 func getContextOrFail(t *testing.T) TemplateContext {
685 tplContext, err := initTestContext()
686 t.Cleanup(func() {
687 os.RemoveAll(string(tplContext.Root.(http.Dir)))
688 })
689 if err != nil {
690 t.Fatalf("failed to prepare test context: %v", err)
691 }
692 return tplContext
693 }
694
695 func initTestContext() (TemplateContext, error) {
696 body := bytes.NewBufferString("request body")
697 request, err := http.NewRequest("GET", "https://example.com/foo/bar", body)
698 if err != nil {
699 return TemplateContext{}, err
700 }
701 tmpDir, err := os.MkdirTemp(os.TempDir(), "caddy")
702 if err != nil {
703 return TemplateContext{}, err
704 }
705 return TemplateContext{
706 Root: http.Dir(tmpDir),
707 Req: request,
708 RespHeader: WrappedHeader{make(http.Header)},
709 }, nil
710 }