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