| 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 caddyfile |
| 16 | |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "os" |
| 20 | "path/filepath" |
| 21 | "strings" |
| 22 | "testing" |
| 23 | ) |
| 24 | |
| 25 | func TestParseVariadic(t *testing.T) { |
| 26 | args := make([]string, 10) |
| 27 | for i, tc := range []struct { |
| 28 | input string |
| 29 | result bool |
| 30 | }{ |
| 31 | { |
| 32 | input: "", |
| 33 | result: false, |
| 34 | }, |
| 35 | { |
| 36 | input: "{args[1", |
| 37 | result: false, |
| 38 | }, |
| 39 | { |
| 40 | input: "1]}", |
| 41 | result: false, |
| 42 | }, |
| 43 | { |
| 44 | input: "{args[:]}aaaaa", |
| 45 | result: false, |
| 46 | }, |
| 47 | { |
| 48 | input: "aaaaa{args[:]}", |
| 49 | result: false, |
| 50 | }, |
| 51 | { |
| 52 | input: "{args.}", |
| 53 | result: false, |
| 54 | }, |
| 55 | { |
| 56 | input: "{args.1}", |
| 57 | result: false, |
| 58 | }, |
| 59 | { |
| 60 | input: "{args[]}", |
| 61 | result: false, |
| 62 | }, |
| 63 | { |
| 64 | input: "{args[:]}", |
| 65 | result: true, |
| 66 | }, |
| 67 | { |
| 68 | input: "{args[:]}", |
| 69 | result: true, |
| 70 | }, |
| 71 | { |
| 72 | input: "{args[0:]}", |
| 73 | result: true, |
| 74 | }, |
| 75 | { |
| 76 | input: "{args[:0]}", |
| 77 | result: true, |
| 78 | }, |
| 79 | { |
| 80 | input: "{args[-1:]}", |
| 81 | result: false, |
| 82 | }, |
| 83 | { |
| 84 | input: "{args[:11]}", |
| 85 | result: false, |
| 86 | }, |
| 87 | { |
| 88 | input: "{args[10:0]}", |
| 89 | result: false, |
| 90 | }, |
| 91 | { |
| 92 | input: "{args[0:10]}", |
| 93 | result: true, |
| 94 | }, |
| 95 | { |
| 96 | input: "{args[0]}:{args[1]}:{args[2]}", |
| 97 | result: false, |
| 98 | }, |
| 99 | } { |
| 100 | token := Token{ |
| 101 | File: "test", |
| 102 | Line: 1, |
| 103 | Text: tc.input, |
| 104 | } |
| 105 | if v, _, _ := parseVariadic(token, len(args)); v != tc.result { |
| 106 | t.Errorf("Test %d error expectation failed Expected: %t, got %t", i, tc.result, v) |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | func TestAllTokens(t *testing.T) { |
| 112 | input := []byte("a b c\nd e") |
| 113 | expected := []string{"a", "b", "c", "d", "e"} |
| 114 | tokens, err := allTokens("TestAllTokens", input) |
| 115 | if err != nil { |
| 116 | t.Fatalf("Expected no error, got %v", err) |
| 117 | } |
| 118 | if len(tokens) != len(expected) { |
| 119 | t.Fatalf("Expected %d tokens, got %d", len(expected), len(tokens)) |
| 120 | } |
| 121 | |
| 122 | for i, val := range expected { |
| 123 | if tokens[i].Text != val { |
| 124 | t.Errorf("Token %d should be '%s' but was '%s'", i, val, tokens[i].Text) |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | func TestParseOneAndImport(t *testing.T) { |
| 130 | testParseOne := func(input string) (ServerBlock, error) { |
| 131 | p := testParser(input) |
| 132 | p.Next() // parseOne doesn't call Next() to start, so we must |
| 133 | err := p.parseOne() |
| 134 | return p.block, err |
| 135 | } |
| 136 | |
| 137 | for i, test := range []struct { |
| 138 | input string |
| 139 | shouldErr bool |
| 140 | keys []string |
| 141 | numTokens []int // number of tokens to expect in each segment |
| 142 | }{ |
| 143 | {`localhost`, false, []string{ |
| 144 | "localhost", |
| 145 | }, []int{}}, |
| 146 | |
| 147 | {`localhost |
| 148 | dir1`, false, []string{ |
| 149 | "localhost", |
| 150 | }, []int{1}}, |
| 151 | |
| 152 | { |
| 153 | `localhost:1234 |
| 154 | dir1 foo bar`, false, []string{ |
| 155 | "localhost:1234", |
| 156 | }, []int{3}, |
| 157 | }, |
| 158 | |
| 159 | {`localhost { |
| 160 | dir1 |
| 161 | }`, false, []string{ |
| 162 | "localhost", |
| 163 | }, []int{1}}, |
| 164 | |
| 165 | {`localhost:1234 { |
| 166 | dir1 foo bar |
| 167 | dir2 |
| 168 | }`, false, []string{ |
| 169 | "localhost:1234", |
| 170 | }, []int{3, 1}}, |
| 171 | |
| 172 | {`http://localhost https://localhost |
| 173 | dir1 foo bar`, false, []string{ |
| 174 | "http://localhost", |
| 175 | "https://localhost", |
| 176 | }, []int{3}}, |
| 177 | |
| 178 | {`http://localhost https://localhost { |
| 179 | dir1 foo bar |
| 180 | }`, false, []string{ |
| 181 | "http://localhost", |
| 182 | "https://localhost", |
| 183 | }, []int{3}}, |
| 184 | |
| 185 | {`http://localhost, https://localhost { |
| 186 | dir1 foo bar |
| 187 | }`, false, []string{ |
| 188 | "http://localhost", |
| 189 | "https://localhost", |
| 190 | }, []int{3}}, |
| 191 | |
| 192 | {`http://localhost, { |
| 193 | }`, true, []string{ |
| 194 | "http://localhost", |
| 195 | }, []int{}}, |
| 196 | |
| 197 | {`host1:80, http://host2.com |
| 198 | dir1 foo bar |
| 199 | dir2 baz`, false, []string{ |
| 200 | "host1:80", |
| 201 | "http://host2.com", |
| 202 | }, []int{3, 2}}, |
| 203 | |
| 204 | {`http://host1.com, |
| 205 | http://host2.com, |
| 206 | https://host3.com`, false, []string{ |
| 207 | "http://host1.com", |
| 208 | "http://host2.com", |
| 209 | "https://host3.com", |
| 210 | }, []int{}}, |
| 211 | |
| 212 | {`http://host1.com:1234, https://host2.com |
| 213 | dir1 foo { |
| 214 | bar baz |
| 215 | } |
| 216 | dir2`, false, []string{ |
| 217 | "http://host1.com:1234", |
| 218 | "https://host2.com", |
| 219 | }, []int{6, 1}}, |
| 220 | |
| 221 | {`127.0.0.1 |
| 222 | dir1 { |
| 223 | bar baz |
| 224 | } |
| 225 | dir2 { |
| 226 | foo bar |
| 227 | }`, false, []string{ |
| 228 | "127.0.0.1", |
| 229 | }, []int{5, 5}}, |
| 230 | |
| 231 | {`localhost |
| 232 | dir1 { |
| 233 | foo`, true, []string{ |
| 234 | "localhost", |
| 235 | }, []int{3}}, |
| 236 | |
| 237 | {`localhost |
| 238 | dir1 { |
| 239 | }`, false, []string{ |
| 240 | "localhost", |
| 241 | }, []int{3}}, |
| 242 | |
| 243 | {`localhost |
| 244 | dir1 { |
| 245 | } }`, true, []string{ |
| 246 | "localhost", |
| 247 | }, []int{}}, |
| 248 | |
| 249 | {`localhost{ |
| 250 | dir1 |
| 251 | }`, true, []string{}, []int{}}, |
| 252 | |
| 253 | {`localhost |
| 254 | dir1 { |
| 255 | nested { |
| 256 | foo |
| 257 | } |
| 258 | } |
| 259 | dir2 foo bar`, false, []string{ |
| 260 | "localhost", |
| 261 | }, []int{7, 3}}, |
| 262 | |
| 263 | {``, false, []string{}, []int{}}, |
| 264 | |
| 265 | {`localhost |
| 266 | dir1 arg1 |
| 267 | import testdata/import_test1.txt`, false, []string{ |
| 268 | "localhost", |
| 269 | }, []int{2, 3, 1}}, |
| 270 | |
| 271 | {`import testdata/import_test2.txt`, false, []string{ |
| 272 | "host1", |
| 273 | }, []int{1, 2}}, |
| 274 | |
| 275 | {`import testdata/not_found.txt`, true, []string{}, []int{}}, |
| 276 | |
| 277 | // empty file should just log a warning, and result in no tokens |
| 278 | {`import testdata/empty.txt`, false, []string{}, []int{}}, |
| 279 | |
| 280 | {`import testdata/only_white_space.txt`, false, []string{}, []int{}}, |
| 281 | |
| 282 | // import path/to/dir/* should skip any files that start with a . when iterating over them. |
| 283 | {`localhost |
| 284 | dir1 arg1 |
| 285 | import testdata/glob/*`, false, []string{ |
| 286 | "localhost", |
| 287 | }, []int{2, 3, 1}}, |
| 288 | |
| 289 | // import path/to/dir/.* should continue to read all dotfiles in a dir. |
| 290 | {`import testdata/glob/.*`, false, []string{ |
| 291 | "host1", |
| 292 | }, []int{1, 2}}, |
| 293 | |
| 294 | {`""`, false, []string{}, []int{}}, |
| 295 | |
| 296 | {``, false, []string{}, []int{}}, |
| 297 | |
| 298 | // Unexpected next token after '{' on same line |
| 299 | {`localhost |
| 300 | dir1 { a b }`, true, []string{"localhost"}, []int{}}, |
| 301 | |
| 302 | // Unexpected '{' on a new line |
| 303 | {`localhost |
| 304 | dir1 |
| 305 | { |
| 306 | a b |
| 307 | }`, true, []string{"localhost"}, []int{}}, |
| 308 | |
| 309 | // Workaround with quotes |
| 310 | {`localhost |
| 311 | dir1 "{" a b "}"`, false, []string{"localhost"}, []int{5}}, |
| 312 | |
| 313 | // Unexpected '{}' at end of line |
| 314 | {`localhost |
| 315 | dir1 {}`, true, []string{"localhost"}, []int{}}, |
| 316 | // Workaround with quotes |
| 317 | {`localhost |
| 318 | dir1 "{}"`, false, []string{"localhost"}, []int{2}}, |
| 319 | |
| 320 | // import with args |
| 321 | {`import testdata/import_args0.txt a`, false, []string{"a"}, []int{}}, |
| 322 | {`import testdata/import_args1.txt a b`, false, []string{"a", "b"}, []int{}}, |
| 323 | {`import testdata/import_args*.txt a b`, false, []string{"a"}, []int{2}}, |
| 324 | |
| 325 | // test cases found by fuzzing! |
| 326 | {`import }{$"`, true, []string{}, []int{}}, |
| 327 | {`import /*/*.txt`, true, []string{}, []int{}}, |
| 328 | {`import /???/?*?o`, true, []string{}, []int{}}, |
| 329 | {`import /??`, true, []string{}, []int{}}, |
| 330 | {`import /[a-z]`, true, []string{}, []int{}}, |
| 331 | {`import {$}`, true, []string{}, []int{}}, |
| 332 | {`import {%}`, true, []string{}, []int{}}, |
| 333 | {`import {$$}`, true, []string{}, []int{}}, |
| 334 | {`import {%%}`, true, []string{}, []int{}}, |
| 335 | } { |
| 336 | result, err := testParseOne(test.input) |
| 337 | |
| 338 | if test.shouldErr && err == nil { |
| 339 | t.Errorf("Test %d: Expected an error, but didn't get one", i) |
| 340 | } |
| 341 | if !test.shouldErr && err != nil { |
| 342 | t.Errorf("Test %d: Expected no error, but got: %v", i, err) |
| 343 | } |
| 344 | |
| 345 | // t.Logf("%+v\n", result) |
| 346 | if len(result.Keys) != len(test.keys) { |
| 347 | t.Errorf("Test %d: Expected %d keys, got %d", |
| 348 | i, len(test.keys), len(result.Keys)) |
| 349 | continue |
| 350 | } |
| 351 | for j, addr := range result.GetKeysText() { |
| 352 | if addr != test.keys[j] { |
| 353 | t.Errorf("Test %d, key %d: Expected '%s', but was '%s'", |
| 354 | i, j, test.keys[j], addr) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | if len(result.Segments) != len(test.numTokens) { |
| 359 | t.Errorf("Test %d: Expected %d segments, had %d", |
| 360 | i, len(test.numTokens), len(result.Segments)) |
| 361 | continue |
| 362 | } |
| 363 | |
| 364 | for j, seg := range result.Segments { |
| 365 | if len(seg) != test.numTokens[j] { |
| 366 | t.Errorf("Test %d, segment %d: Expected %d tokens, counted %d", |
| 367 | i, j, test.numTokens[j], len(seg)) |
| 368 | continue |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | func TestRecursiveImport(t *testing.T) { |
| 375 | testParseOne := func(input string) (ServerBlock, error) { |
| 376 | p := testParser(input) |
| 377 | p.Next() // parseOne doesn't call Next() to start, so we must |
| 378 | err := p.parseOne() |
| 379 | return p.block, err |
| 380 | } |
| 381 | |
| 382 | isExpected := func(got ServerBlock) bool { |
| 383 | textKeys := got.GetKeysText() |
| 384 | if len(textKeys) != 1 || textKeys[0] != "localhost" { |
| 385 | t.Errorf("got keys unexpected: expect localhost, got %v", textKeys) |
| 386 | return false |
| 387 | } |
| 388 | if len(got.Segments) != 2 { |
| 389 | t.Errorf("got wrong number of segments: expect 2, got %d", len(got.Segments)) |
| 390 | return false |
| 391 | } |
| 392 | if len(got.Segments[0]) != 1 || len(got.Segments[1]) != 2 { |
| 393 | t.Errorf("got unexpected tokens: %v", got.Segments) |
| 394 | return false |
| 395 | } |
| 396 | return true |
| 397 | } |
| 398 | |
| 399 | recursiveFile1, err := filepath.Abs("testdata/recursive_import_test1") |
| 400 | if err != nil { |
| 401 | t.Fatal(err) |
| 402 | } |
| 403 | recursiveFile2, err := filepath.Abs("testdata/recursive_import_test2") |
| 404 | if err != nil { |
| 405 | t.Fatal(err) |
| 406 | } |
| 407 | |
| 408 | // test relative recursive import |
| 409 | err = os.WriteFile(recursiveFile1, []byte( |
| 410 | `localhost |
| 411 | dir1 |
| 412 | import recursive_import_test2`), 0o644) |
| 413 | if err != nil { |
| 414 | t.Fatal(err) |
| 415 | } |
| 416 | defer os.Remove(recursiveFile1) |
| 417 | |
| 418 | err = os.WriteFile(recursiveFile2, []byte("dir2 1"), 0o644) |
| 419 | if err != nil { |
| 420 | t.Fatal(err) |
| 421 | } |
| 422 | defer os.Remove(recursiveFile2) |
| 423 | |
| 424 | // import absolute path |
| 425 | result, err := testParseOne("import " + recursiveFile1) |
| 426 | if err != nil { |
| 427 | t.Fatal(err) |
| 428 | } |
| 429 | if !isExpected(result) { |
| 430 | t.Error("absolute+relative import failed") |
| 431 | } |
| 432 | |
| 433 | // import relative path |
| 434 | result, err = testParseOne("import testdata/recursive_import_test1") |
| 435 | if err != nil { |
| 436 | t.Fatal(err) |
| 437 | } |
| 438 | if !isExpected(result) { |
| 439 | t.Error("relative+relative import failed") |
| 440 | } |
| 441 | |
| 442 | // test absolute recursive import |
| 443 | err = os.WriteFile(recursiveFile1, []byte( |
| 444 | `localhost |
| 445 | dir1 |
| 446 | import `+recursiveFile2), 0o644) |
| 447 | if err != nil { |
| 448 | t.Fatal(err) |
| 449 | } |
| 450 | |
| 451 | // import absolute path |
| 452 | result, err = testParseOne("import " + recursiveFile1) |
| 453 | if err != nil { |
| 454 | t.Fatal(err) |
| 455 | } |
| 456 | if !isExpected(result) { |
| 457 | t.Error("absolute+absolute import failed") |
| 458 | } |
| 459 | |
| 460 | // import relative path |
| 461 | result, err = testParseOne("import testdata/recursive_import_test1") |
| 462 | if err != nil { |
| 463 | t.Fatal(err) |
| 464 | } |
| 465 | if !isExpected(result) { |
| 466 | t.Error("relative+absolute import failed") |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | func TestDirectiveImport(t *testing.T) { |
| 471 | testParseOne := func(input string) (ServerBlock, error) { |
| 472 | p := testParser(input) |
| 473 | p.Next() // parseOne doesn't call Next() to start, so we must |
| 474 | err := p.parseOne() |
| 475 | return p.block, err |
| 476 | } |
| 477 | |
| 478 | isExpected := func(got ServerBlock) bool { |
| 479 | textKeys := got.GetKeysText() |
| 480 | if len(textKeys) != 1 || textKeys[0] != "localhost" { |
| 481 | t.Errorf("got keys unexpected: expect localhost, got %v", textKeys) |
| 482 | return false |
| 483 | } |
| 484 | if len(got.Segments) != 2 { |
| 485 | t.Errorf("got wrong number of segments: expect 2, got %d", len(got.Segments)) |
| 486 | return false |
| 487 | } |
| 488 | if len(got.Segments[0]) != 1 || len(got.Segments[1]) != 8 { |
| 489 | t.Errorf("got unexpected tokens: %v", got.Segments) |
| 490 | return false |
| 491 | } |
| 492 | return true |
| 493 | } |
| 494 | |
| 495 | directiveFile, err := filepath.Abs("testdata/directive_import_test") |
| 496 | if err != nil { |
| 497 | t.Fatal(err) |
| 498 | } |
| 499 | |
| 500 | err = os.WriteFile(directiveFile, []byte(`prop1 1 |
| 501 | prop2 2`), 0o644) |
| 502 | if err != nil { |
| 503 | t.Fatal(err) |
| 504 | } |
| 505 | defer os.Remove(directiveFile) |
| 506 | |
| 507 | // import from existing file |
| 508 | result, err := testParseOne(`localhost |
| 509 | dir1 |
| 510 | proxy { |
| 511 | import testdata/directive_import_test |
| 512 | transparent |
| 513 | }`) |
| 514 | if err != nil { |
| 515 | t.Fatal(err) |
| 516 | } |
| 517 | if !isExpected(result) { |
| 518 | t.Error("directive import failed") |
| 519 | } |
| 520 | |
| 521 | // import from nonexistent file |
| 522 | _, err = testParseOne(`localhost |
| 523 | dir1 |
| 524 | proxy { |
| 525 | import testdata/nonexistent_file |
| 526 | transparent |
| 527 | }`) |
| 528 | if err == nil { |
| 529 | t.Fatal("expected error when importing a nonexistent file") |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | func TestParseAll(t *testing.T) { |
| 534 | for i, test := range []struct { |
| 535 | input string |
| 536 | shouldErr bool |
| 537 | keys [][]string // keys per server block, in order |
| 538 | }{ |
| 539 | {`localhost`, false, [][]string{ |
| 540 | {"localhost"}, |
| 541 | }}, |
| 542 | |
| 543 | {`localhost:1234`, false, [][]string{ |
| 544 | {"localhost:1234"}, |
| 545 | }}, |
| 546 | |
| 547 | {`localhost:1234 { |
| 548 | } |
| 549 | localhost:2015 { |
| 550 | }`, false, [][]string{ |
| 551 | {"localhost:1234"}, |
| 552 | {"localhost:2015"}, |
| 553 | }}, |
| 554 | |
| 555 | {`localhost:1234, http://host2`, false, [][]string{ |
| 556 | {"localhost:1234", "http://host2"}, |
| 557 | }}, |
| 558 | |
| 559 | {`foo.example.com , example.com`, false, [][]string{ |
| 560 | {"foo.example.com", "example.com"}, |
| 561 | }}, |
| 562 | |
| 563 | {`localhost:1234, http://host2,`, true, [][]string{}}, |
| 564 | |
| 565 | {`http://host1.com, http://host2.com { |
| 566 | } |
| 567 | https://host3.com, https://host4.com { |
| 568 | }`, false, [][]string{ |
| 569 | {"http://host1.com", "http://host2.com"}, |
| 570 | {"https://host3.com", "https://host4.com"}, |
| 571 | }}, |
| 572 | |
| 573 | {`import testdata/import_glob*.txt`, false, [][]string{ |
| 574 | {"glob0.host0"}, |
| 575 | {"glob0.host1"}, |
| 576 | {"glob1.host0"}, |
| 577 | {"glob2.host0"}, |
| 578 | }}, |
| 579 | |
| 580 | {`import notfound/*`, false, [][]string{}}, // glob needn't error with no matches |
| 581 | {`import notfound/file.conf`, true, [][]string{}}, // but a specific file should |
| 582 | |
| 583 | // recursive self-import |
| 584 | {`import testdata/import_recursive0.txt`, true, [][]string{}}, |
| 585 | {`import testdata/import_recursive3.txt |
| 586 | import testdata/import_recursive1.txt`, true, [][]string{}}, |
| 587 | |
| 588 | // cyclic imports |
| 589 | {`(A) { |
| 590 | import A |
| 591 | } |
| 592 | :80 |
| 593 | import A |
| 594 | `, true, [][]string{}}, |
| 595 | {`(A) { |
| 596 | import B |
| 597 | } |
| 598 | (B) { |
| 599 | import A |
| 600 | } |
| 601 | :80 |
| 602 | import A |
| 603 | `, true, [][]string{}}, |
| 604 | } { |
| 605 | p := testParser(test.input) |
| 606 | blocks, err := p.parseAll() |
| 607 | |
| 608 | if test.shouldErr && err == nil { |
| 609 | t.Errorf("Test %d: Expected an error, but didn't get one", i) |
| 610 | } |
| 611 | if !test.shouldErr && err != nil { |
| 612 | t.Errorf("Test %d: Expected no error, but got: %v", i, err) |
| 613 | } |
| 614 | |
| 615 | if len(blocks) != len(test.keys) { |
| 616 | t.Errorf("Test %d: Expected %d server blocks, got %d", |
| 617 | i, len(test.keys), len(blocks)) |
| 618 | continue |
| 619 | } |
| 620 | for j, block := range blocks { |
| 621 | if len(block.Keys) != len(test.keys[j]) { |
| 622 | t.Errorf("Test %d: Expected %d keys in block %d, got %d: %v", |
| 623 | i, len(test.keys[j]), j, len(block.Keys), block.Keys) |
| 624 | continue |
| 625 | } |
| 626 | for k, addr := range block.GetKeysText() { |
| 627 | if addr != test.keys[j][k] { |
| 628 | t.Errorf("Test %d, block %d, key %d: Expected '%s', but got '%s'", |
| 629 | i, j, k, test.keys[j][k], addr) |
| 630 | } |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | func TestEnvironmentReplacement(t *testing.T) { |
| 637 | os.Setenv("FOOBAR", "foobar") |
| 638 | os.Setenv("CHAINED", "$FOOBAR") |
| 639 | |
| 640 | for i, test := range []struct { |
| 641 | input string |
| 642 | expect string |
| 643 | }{ |
| 644 | { |
| 645 | input: "", |
| 646 | expect: "", |
| 647 | }, |
| 648 | { |
| 649 | input: "foo", |
| 650 | expect: "foo", |
| 651 | }, |
| 652 | { |
| 653 | input: "{$NOT_SET}", |
| 654 | expect: "", |
| 655 | }, |
| 656 | { |
| 657 | input: "foo{$NOT_SET}bar", |
| 658 | expect: "foobar", |
| 659 | }, |
| 660 | { |
| 661 | input: "{$FOOBAR}", |
| 662 | expect: "foobar", |
| 663 | }, |
| 664 | { |
| 665 | input: "foo {$FOOBAR} bar", |
| 666 | expect: "foo foobar bar", |
| 667 | }, |
| 668 | { |
| 669 | input: "foo{$FOOBAR}bar", |
| 670 | expect: "foofoobarbar", |
| 671 | }, |
| 672 | { |
| 673 | input: "foo\n{$FOOBAR}\nbar", |
| 674 | expect: "foo\nfoobar\nbar", |
| 675 | }, |
| 676 | { |
| 677 | input: "{$FOOBAR} {$FOOBAR}", |
| 678 | expect: "foobar foobar", |
| 679 | }, |
| 680 | { |
| 681 | input: "{$FOOBAR}{$FOOBAR}", |
| 682 | expect: "foobarfoobar", |
| 683 | }, |
| 684 | { |
| 685 | input: "{$CHAINED}", |
| 686 | expect: "$FOOBAR", // should not chain env expands |
| 687 | }, |
| 688 | { |
| 689 | input: "{$FOO:default}", |
| 690 | expect: "default", |
| 691 | }, |
| 692 | { |
| 693 | input: "foo{$BAR:bar}baz", |
| 694 | expect: "foobarbaz", |
| 695 | }, |
| 696 | { |
| 697 | input: "foo{$BAR:$FOOBAR}baz", |
| 698 | expect: "foo$FOOBARbaz", // should not chain env expands |
| 699 | }, |
| 700 | { |
| 701 | input: "{$FOOBAR", |
| 702 | expect: "{$FOOBAR", |
| 703 | }, |
| 704 | { |
| 705 | input: "{$LONGER_NAME $FOOBAR}", |
| 706 | expect: "", |
| 707 | }, |
| 708 | { |
| 709 | input: "{$}", |
| 710 | expect: "{$}", |
| 711 | }, |
| 712 | { |
| 713 | input: "{$$}", |
| 714 | expect: "", |
| 715 | }, |
| 716 | { |
| 717 | input: "{$", |
| 718 | expect: "{$", |
| 719 | }, |
| 720 | { |
| 721 | input: "}{$", |
| 722 | expect: "}{$", |
| 723 | }, |
| 724 | } { |
| 725 | actual := replaceEnvVars([]byte(test.input)) |
| 726 | if !bytes.Equal(actual, []byte(test.expect)) { |
| 727 | t.Errorf("Test %d: Expected: '%s' but got '%s'", i, test.expect, actual) |
| 728 | } |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | func TestImportReplacementInJSONWithBrace(t *testing.T) { |
| 733 | for i, test := range []struct { |
| 734 | args []string |
| 735 | input string |
| 736 | expect string |
| 737 | }{ |
| 738 | { |
| 739 | args: []string{"123"}, |
| 740 | input: "{args[0]}", |
| 741 | expect: "123", |
| 742 | }, |
| 743 | { |
| 744 | args: []string{"123"}, |
| 745 | input: `{"key":"{args[0]}"}`, |
| 746 | expect: `{"key":"123"}`, |
| 747 | }, |
| 748 | { |
| 749 | args: []string{"123", "123"}, |
| 750 | input: `{"key":[{args[0]},{args[1]}]}`, |
| 751 | expect: `{"key":[123,123]}`, |
| 752 | }, |
| 753 | } { |
| 754 | repl := makeArgsReplacer(test.args) |
| 755 | actual := repl.ReplaceKnown(test.input, "") |
| 756 | if actual != test.expect { |
| 757 | t.Errorf("Test %d: Expected: '%s' but got '%s'", i, test.expect, actual) |
| 758 | } |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | func TestSnippets(t *testing.T) { |
| 763 | p := testParser(` |
| 764 | (common) { |
| 765 | gzip foo |
| 766 | errors stderr |
| 767 | } |
| 768 | http://example.com { |
| 769 | import common |
| 770 | } |
| 771 | `) |
| 772 | blocks, err := p.parseAll() |
| 773 | if err != nil { |
| 774 | t.Fatal(err) |
| 775 | } |
| 776 | if len(blocks) != 1 { |
| 777 | t.Fatalf("Expect exactly one server block. Got %d.", len(blocks)) |
| 778 | } |
| 779 | if actual, expected := blocks[0].GetKeysText()[0], "http://example.com"; expected != actual { |
| 780 | t.Errorf("Expected server name to be '%s' but was '%s'", expected, actual) |
| 781 | } |
| 782 | if len(blocks[0].Segments) != 2 { |
| 783 | t.Fatalf("Server block should have tokens from import, got: %+v", blocks[0]) |
| 784 | } |
| 785 | if actual, expected := blocks[0].Segments[0][0].Text, "gzip"; expected != actual { |
| 786 | t.Errorf("Expected argument to be '%s' but was '%s'", expected, actual) |
| 787 | } |
| 788 | if actual, expected := blocks[0].Segments[1][1].Text, "stderr"; expected != actual { |
| 789 | t.Errorf("Expected argument to be '%s' but was '%s'", expected, actual) |
| 790 | } |
| 791 | } |
| 792 | |
| 793 | func writeStringToTempFileOrDie(t *testing.T, str string) (pathToFile string) { |
| 794 | file, err := os.CreateTemp("", t.Name()) |
| 795 | if err != nil { |
| 796 | panic(err) // get a stack trace so we know where this was called from. |
| 797 | } |
| 798 | if _, err := file.WriteString(str); err != nil { |
| 799 | panic(err) |
| 800 | } |
| 801 | if err := file.Close(); err != nil { |
| 802 | panic(err) |
| 803 | } |
| 804 | return file.Name() |
| 805 | } |
| 806 | |
| 807 | func TestImportedFilesIgnoreNonDirectiveImportTokens(t *testing.T) { |
| 808 | fileName := writeStringToTempFileOrDie(t, ` |
| 809 | http://example.com { |
| 810 | # This isn't an import directive, it's just an arg with value 'import' |
| 811 | basic_auth / import password |
| 812 | } |
| 813 | `) |
| 814 | // Parse the root file that imports the other one. |
| 815 | p := testParser(`import ` + fileName) |
| 816 | blocks, err := p.parseAll() |
| 817 | if err != nil { |
| 818 | t.Fatal(err) |
| 819 | } |
| 820 | auth := blocks[0].Segments[0] |
| 821 | line := auth[0].Text + " " + auth[1].Text + " " + auth[2].Text + " " + auth[3].Text |
| 822 | if line != "basic_auth / import password" { |
| 823 | // Previously, it would be changed to: |
| 824 | // basic_auth / import /path/to/test/dir/password |
| 825 | // referencing a file that (probably) doesn't exist and changing the |
| 826 | // password! |
| 827 | t.Errorf("Expected basic_auth tokens to be 'basic_auth / import password' but got %#q", line) |
| 828 | } |
| 829 | } |
| 830 | |
| 831 | func TestSnippetAcrossMultipleFiles(t *testing.T) { |
| 832 | // Make the derived Caddyfile that expects (common) to be defined. |
| 833 | fileName := writeStringToTempFileOrDie(t, ` |
| 834 | http://example.com { |
| 835 | import common |
| 836 | } |
| 837 | `) |
| 838 | |
| 839 | // Parse the root file that defines (common) and then imports the other one. |
| 840 | p := testParser(` |
| 841 | (common) { |
| 842 | gzip foo |
| 843 | } |
| 844 | import ` + fileName + ` |
| 845 | `) |
| 846 | |
| 847 | blocks, err := p.parseAll() |
| 848 | if err != nil { |
| 849 | t.Fatal(err) |
| 850 | } |
| 851 | if len(blocks) != 1 { |
| 852 | t.Fatalf("Expect exactly one server block. Got %d.", len(blocks)) |
| 853 | } |
| 854 | if actual, expected := blocks[0].GetKeysText()[0], "http://example.com"; expected != actual { |
| 855 | t.Errorf("Expected server name to be '%s' but was '%s'", expected, actual) |
| 856 | } |
| 857 | if len(blocks[0].Segments) != 1 { |
| 858 | t.Fatalf("Server block should have tokens from import") |
| 859 | } |
| 860 | if actual, expected := blocks[0].Segments[0][0].Text, "gzip"; expected != actual { |
| 861 | t.Errorf("Expected argument to be '%s' but was '%s'", expected, actual) |
| 862 | } |
| 863 | } |
| 864 | |
| 865 | func TestRejectsGlobalMatcher(t *testing.T) { |
| 866 | p := testParser(` |
| 867 | @rejected path /foo |
| 868 | |
| 869 | (common) { |
| 870 | gzip foo |
| 871 | errors stderr |
| 872 | } |
| 873 | |
| 874 | http://example.com { |
| 875 | import common |
| 876 | } |
| 877 | `) |
| 878 | _, err := p.parseAll() |
| 879 | if err == nil { |
| 880 | t.Fatal("Expected an error, but got nil") |
| 881 | } |
| 882 | expected := "request matchers may not be defined globally, they must be in a site block; found @rejected, at Testfile:2" |
| 883 | if err.Error() != expected { |
| 884 | t.Errorf("Expected error to be '%s' but got '%v'", expected, err) |
| 885 | } |
| 886 | } |
| 887 | |
| 888 | func TestRejectAnonymousImportBlock(t *testing.T) { |
| 889 | p := testParser(` |
| 890 | (site) { |
| 891 | http://{args[0]} https://{args[0]} { |
| 892 | {block} |
| 893 | } |
| 894 | } |
| 895 | |
| 896 | import site test.domain { |
| 897 | { |
| 898 | header_up Host {host} |
| 899 | header_up X-Real-IP {remote_host} |
| 900 | } |
| 901 | } |
| 902 | `) |
| 903 | _, err := p.parseAll() |
| 904 | if err == nil { |
| 905 | t.Fatal("Expected an error, but got nil") |
| 906 | } |
| 907 | expected := "anonymous blocks are not supported" |
| 908 | if !strings.HasPrefix(err.Error(), "anonymous blocks are not supported") { |
| 909 | t.Errorf("Expected error to start with '%s' but got '%v'", expected, err) |
| 910 | } |
| 911 | } |
| 912 | |
| 913 | func TestAcceptSiteImportWithBraces(t *testing.T) { |
| 914 | p := testParser(` |
| 915 | (site) { |
| 916 | http://{args[0]} https://{args[0]} { |
| 917 | {block} |
| 918 | } |
| 919 | } |
| 920 | |
| 921 | import site test.domain { |
| 922 | reverse_proxy http://192.168.1.1:8080 { |
| 923 | header_up Host {host} |
| 924 | } |
| 925 | } |
| 926 | `) |
| 927 | _, err := p.parseAll() |
| 928 | if err != nil { |
| 929 | t.Errorf("Expected error to be nil but got '%v'", err) |
| 930 | } |
| 931 | } |
| 932 | |
| 933 | func TestGlobalOptionsAfterImportedSnippetsGivesHelpfulError(t *testing.T) { |
| 934 | tempDir := t.TempDir() |
| 935 | importFile1 := filepath.Join(tempDir, "matcher_snippet_1.caddy") |
| 936 | importFile2 := filepath.Join(tempDir, "matcher_snippet_2.caddy") |
| 937 | |
| 938 | err := os.WriteFile(importFile1, []byte(`(matcher1)`), 0o644) |
| 939 | if err != nil { |
| 940 | t.Fatalf("writing first import file: %v", err) |
| 941 | } |
| 942 | |
| 943 | err = os.WriteFile(importFile2, []byte(`(matcher2)`), 0o644) |
| 944 | if err != nil { |
| 945 | t.Fatalf("writing second import file: %v", err) |
| 946 | } |
| 947 | |
| 948 | _, err = Parse("Testfile", []byte(`import `+importFile1+` |
| 949 | import `+importFile2+` |
| 950 | { |
| 951 | debug |
| 952 | }`)) |
| 953 | if err == nil { |
| 954 | t.Fatal("Expected an error, but got nil") |
| 955 | } |
| 956 | |
| 957 | expected := "global options block must appear before import directives; move the global options block to the top of the Caddyfile" |
| 958 | if !strings.HasPrefix(err.Error(), expected) { |
| 959 | t.Errorf("Expected error to start with '%s' but got '%v'", expected, err) |
| 960 | } |
| 961 | } |
| 962 | |
| 963 | func TestImportedSnippetDefinitionRetainsBlockPlaceholder(t *testing.T) { |
| 964 | tempDir := t.TempDir() |
| 965 | importFile := filepath.Join(tempDir, "snippets.caddy") |
| 966 | |
| 967 | err := os.WriteFile(importFile, []byte(` |
| 968 | (site) { |
| 969 | http://{args[0]} { |
| 970 | respond "before" |
| 971 | {block} |
| 972 | respond "after" |
| 973 | } |
| 974 | } |
| 975 | `), 0o644) |
| 976 | if err != nil { |
| 977 | t.Fatalf("writing imported snippet file: %v", err) |
| 978 | } |
| 979 | |
| 980 | for _, tc := range []struct { |
| 981 | name string |
| 982 | input string |
| 983 | expectedDirectives []string |
| 984 | }{ |
| 985 | { |
| 986 | name: "with nested block", |
| 987 | input: ` |
| 988 | import ` + importFile + ` |
| 989 | |
| 990 | import site example.com { |
| 991 | redir https://example.net |
| 992 | } |
| 993 | `, |
| 994 | expectedDirectives: []string{"respond", "redir", "respond"}, |
| 995 | }, |
| 996 | { |
| 997 | name: "without nested block", |
| 998 | input: ` |
| 999 | import ` + importFile + ` |
| 1000 | |
| 1001 | import site example.com |
| 1002 | `, |
| 1003 | expectedDirectives: []string{"respond", "respond"}, |
| 1004 | }, |
| 1005 | } { |
| 1006 | t.Run(tc.name, func(t *testing.T) { |
| 1007 | p := testParser(tc.input) |
| 1008 | blocks, err := p.parseAll() |
| 1009 | if err != nil { |
| 1010 | t.Fatalf("parseAll: %v", err) |
| 1011 | } |
| 1012 | |
| 1013 | if len(blocks) != 1 { |
| 1014 | t.Fatalf("expected exactly one server block, got %d", len(blocks)) |
| 1015 | } |
| 1016 | |
| 1017 | if actual := blocks[0].GetKeysText(); len(actual) != 1 || actual[0] != "http://example.com" { |
| 1018 | t.Fatalf("expected server block key http://example.com, got %v", actual) |
| 1019 | } |
| 1020 | |
| 1021 | if len(blocks[0].Segments) != len(tc.expectedDirectives) { |
| 1022 | t.Fatalf("expected %d segments, got %d", len(tc.expectedDirectives), len(blocks[0].Segments)) |
| 1023 | } |
| 1024 | |
| 1025 | for i, directive := range tc.expectedDirectives { |
| 1026 | if actual := blocks[0].Segments[i].Directive(); actual != directive { |
| 1027 | t.Fatalf("segment %d: expected directive %q, got %q", i, directive, actual) |
| 1028 | } |
| 1029 | } |
| 1030 | }) |
| 1031 | } |
| 1032 | } |
| 1033 | |
| 1034 | func testParser(input string) parser { |
| 1035 | return parser{Dispenser: NewTestDispenser(input)} |
| 1036 | } |