| 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 fileserver |
| 16 | |
| 17 | import ( |
| 18 | "context" |
| 19 | "net/http" |
| 20 | "net/http/httptest" |
| 21 | "net/url" |
| 22 | "os" |
| 23 | "path/filepath" |
| 24 | "runtime" |
| 25 | "strings" |
| 26 | "testing" |
| 27 | |
| 28 | "github.com/caddyserver/caddy/v2" |
| 29 | "github.com/caddyserver/caddy/v2/internal/filesystems" |
| 30 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" |
| 31 | "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" |
| 32 | ) |
| 33 | |
| 34 | type testCase struct { |
| 35 | path string |
| 36 | expectedPath string |
| 37 | expectedType string |
| 38 | matched bool |
| 39 | } |
| 40 | |
| 41 | func TestFileMatcher(t *testing.T) { |
| 42 | // Windows doesn't like colons in files names |
| 43 | isWindows := runtime.GOOS == "windows" |
| 44 | if !isWindows { |
| 45 | filename := "with:in-name.txt" |
| 46 | f, err := os.Create("./testdata/" + filename) |
| 47 | if err != nil { |
| 48 | t.Fail() |
| 49 | return |
| 50 | } |
| 51 | t.Cleanup(func() { |
| 52 | os.Remove("./testdata/" + filename) |
| 53 | }) |
| 54 | f.WriteString(filename) |
| 55 | f.Close() |
| 56 | } |
| 57 | |
| 58 | for i, tc := range []testCase{ |
| 59 | { |
| 60 | path: "/foo.txt", |
| 61 | expectedPath: "/foo.txt", |
| 62 | expectedType: "file", |
| 63 | matched: true, |
| 64 | }, |
| 65 | { |
| 66 | path: "/foo.txt/", |
| 67 | expectedPath: "/foo.txt", |
| 68 | expectedType: "file", |
| 69 | matched: true, |
| 70 | }, |
| 71 | { |
| 72 | path: "/foo.txt?a=b", |
| 73 | expectedPath: "/foo.txt", |
| 74 | expectedType: "file", |
| 75 | matched: true, |
| 76 | }, |
| 77 | { |
| 78 | path: "/foodir", |
| 79 | expectedPath: "/foodir/", |
| 80 | expectedType: "directory", |
| 81 | matched: true, |
| 82 | }, |
| 83 | { |
| 84 | path: "/foodir/", |
| 85 | expectedPath: "/foodir/", |
| 86 | expectedType: "directory", |
| 87 | matched: true, |
| 88 | }, |
| 89 | { |
| 90 | path: "/foodir/foo.txt", |
| 91 | expectedPath: "/foodir/foo.txt", |
| 92 | expectedType: "file", |
| 93 | matched: true, |
| 94 | }, |
| 95 | { |
| 96 | path: "/missingfile.php", |
| 97 | matched: false, |
| 98 | }, |
| 99 | { |
| 100 | path: "ملف.txt", // the path file name is not escaped |
| 101 | expectedPath: "/ملف.txt", |
| 102 | expectedType: "file", |
| 103 | matched: true, |
| 104 | }, |
| 105 | { |
| 106 | path: url.PathEscape("ملف.txt"), // singly-escaped path |
| 107 | expectedPath: "/ملف.txt", |
| 108 | expectedType: "file", |
| 109 | matched: true, |
| 110 | }, |
| 111 | { |
| 112 | path: url.PathEscape(url.PathEscape("ملف.txt")), // doubly-escaped path |
| 113 | expectedPath: "/%D9%85%D9%84%D9%81.txt", |
| 114 | expectedType: "file", |
| 115 | matched: true, |
| 116 | }, |
| 117 | { |
| 118 | path: "./with:in-name.txt", // browsers send the request with the path as such |
| 119 | expectedPath: "/with:in-name.txt", |
| 120 | expectedType: "file", |
| 121 | matched: !isWindows, |
| 122 | }, |
| 123 | } { |
| 124 | fileMatcherTest(t, i, tc) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | func TestFileMatcherNonWindows(t *testing.T) { |
| 129 | if runtime.GOOS == "windows" { |
| 130 | return |
| 131 | } |
| 132 | |
| 133 | // this is impossible to test on Windows, but tests a security patch for other platforms |
| 134 | tc := testCase{ |
| 135 | path: "/foodir/secr%5Cet.txt", |
| 136 | expectedPath: "/foodir/secr\\et.txt", |
| 137 | expectedType: "file", |
| 138 | matched: true, |
| 139 | } |
| 140 | |
| 141 | f, err := os.Create(filepath.Join("testdata", strings.TrimPrefix(tc.expectedPath, "/"))) |
| 142 | if err != nil { |
| 143 | t.Fatalf("could not create test file: %v", err) |
| 144 | } |
| 145 | defer f.Close() |
| 146 | defer os.Remove(f.Name()) |
| 147 | |
| 148 | fileMatcherTest(t, 0, tc) |
| 149 | } |
| 150 | |
| 151 | func fileMatcherTest(t *testing.T, i int, tc testCase) { |
| 152 | m := &MatchFile{ |
| 153 | fsmap: &filesystems.FileSystemMap{}, |
| 154 | Root: "./testdata", |
| 155 | TryFiles: []string{"{http.request.uri.path}", "{http.request.uri.path}/"}, |
| 156 | } |
| 157 | |
| 158 | u, err := url.Parse(tc.path) |
| 159 | if err != nil { |
| 160 | t.Errorf("Test %d: parsing path: %v", i, err) |
| 161 | } |
| 162 | |
| 163 | req := &http.Request{URL: u} |
| 164 | repl := caddyhttp.NewTestReplacer(req) |
| 165 | |
| 166 | result, err := m.MatchWithError(req) |
| 167 | if err != nil { |
| 168 | t.Errorf("Test %d: unexpected error: %v", i, err) |
| 169 | } |
| 170 | if result != tc.matched { |
| 171 | t.Errorf("Test %d: expected match=%t, got %t", i, tc.matched, result) |
| 172 | } |
| 173 | |
| 174 | rel, ok := repl.Get("http.matchers.file.relative") |
| 175 | if !ok && result { |
| 176 | t.Errorf("Test %d: expected replacer value", i) |
| 177 | } |
| 178 | if !result { |
| 179 | return |
| 180 | } |
| 181 | |
| 182 | if rel != tc.expectedPath { |
| 183 | t.Errorf("Test %d: actual path: %v, expected: %v", i, rel, tc.expectedPath) |
| 184 | } |
| 185 | |
| 186 | fileType, _ := repl.Get("http.matchers.file.type") |
| 187 | if fileType != tc.expectedType { |
| 188 | t.Errorf("Test %d: actual file type: %v, expected: %v", i, fileType, tc.expectedType) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | func TestTryFilesRewriteEscapesMatchedPath(t *testing.T) { |
| 193 | root := t.TempDir() |
| 194 | |
| 195 | tests := []struct { |
| 196 | name string |
| 197 | requestTarget string |
| 198 | filename string |
| 199 | extraFiles []string |
| 200 | wantPath string |
| 201 | wantRequestURI string |
| 202 | skipWindows bool |
| 203 | }{ |
| 204 | { |
| 205 | name: "question mark in path", |
| 206 | requestTarget: "/%3F.html", |
| 207 | filename: "?.html", |
| 208 | wantPath: "/?.html", |
| 209 | wantRequestURI: "/%3F.html", |
| 210 | skipWindows: true, |
| 211 | }, |
| 212 | { |
| 213 | name: "percent in path", |
| 214 | requestTarget: "/%25.html", |
| 215 | filename: "%.html", |
| 216 | wantPath: "/%.html", |
| 217 | wantRequestURI: "/%25.html", |
| 218 | }, |
| 219 | { |
| 220 | name: "encoded question mark remains percent-encoded", |
| 221 | requestTarget: "/%253F.html", |
| 222 | filename: "%3F.html", |
| 223 | wantPath: "/%3F.html", |
| 224 | wantRequestURI: "/%253F.html", |
| 225 | }, |
| 226 | { |
| 227 | name: "question mark in nested path", |
| 228 | requestTarget: "/nested/%3F.html", |
| 229 | filename: filepath.Join("nested", "?.html"), |
| 230 | wantPath: "/nested/?.html", |
| 231 | wantRequestURI: "/nested/%3F.html", |
| 232 | skipWindows: true, |
| 233 | }, |
| 234 | { |
| 235 | name: "encoded slash in filename does not conflict with nesting", |
| 236 | requestTarget: "/nested%252Ffile.html", |
| 237 | filename: "nested%2Ffile.html", |
| 238 | extraFiles: []string{filepath.Join("nested", "file.html")}, |
| 239 | wantPath: "/nested%2Ffile.html", |
| 240 | wantRequestURI: "/nested%252Ffile.html", |
| 241 | }, |
| 242 | } |
| 243 | |
| 244 | for _, tc := range tests { |
| 245 | t.Run(tc.name, func(t *testing.T) { |
| 246 | if tc.skipWindows && runtime.GOOS == "windows" { |
| 247 | t.Skip("Windows file names cannot contain question marks") |
| 248 | } |
| 249 | |
| 250 | for _, name := range append([]string{tc.filename}, tc.extraFiles...) { |
| 251 | filename := filepath.Join(root, name) |
| 252 | if err := os.MkdirAll(filepath.Dir(filename), 0o700); err != nil { |
| 253 | t.Fatalf("creating test file parent directory: %v", err) |
| 254 | } |
| 255 | if err := os.WriteFile(filename, []byte(name), 0o600); err != nil { |
| 256 | t.Fatalf("writing test file: %v", err) |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | m := &MatchFile{ |
| 261 | fsmap: &filesystems.FileSystemMap{}, |
| 262 | Root: root, |
| 263 | TryFiles: []string{"{http.request.uri.path}"}, |
| 264 | } |
| 265 | req := httptest.NewRequest(http.MethodGet, "http://example.com"+tc.requestTarget, nil) |
| 266 | repl := caddyhttp.NewTestReplacer(req) |
| 267 | |
| 268 | matched, err := m.MatchWithError(req) |
| 269 | if err != nil { |
| 270 | t.Fatalf("matching file: %v", err) |
| 271 | } |
| 272 | if !matched { |
| 273 | t.Fatalf("expected request %s to match %s", tc.requestTarget, tc.filename) |
| 274 | } |
| 275 | |
| 276 | rewrite.Rewrite{URI: "{http.matchers.file.relative}"}.Rewrite(req, repl) |
| 277 | |
| 278 | if req.URL.Path != tc.wantPath { |
| 279 | t.Errorf("rewritten path = %q, want %q", req.URL.Path, tc.wantPath) |
| 280 | } |
| 281 | if req.RequestURI != tc.wantRequestURI { |
| 282 | t.Errorf("rewritten request URI = %q, want %q", req.RequestURI, tc.wantRequestURI) |
| 283 | } |
| 284 | if req.URL.RawQuery != "" { |
| 285 | t.Errorf("rewritten raw query = %q, want empty", req.URL.RawQuery) |
| 286 | } |
| 287 | }) |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | func TestPHPFileMatcher(t *testing.T) { |
| 292 | for i, tc := range []struct { |
| 293 | path string |
| 294 | expectedPath string |
| 295 | expectedType string |
| 296 | matched bool |
| 297 | }{ |
| 298 | { |
| 299 | path: "/index.php", |
| 300 | expectedPath: "/index.php", |
| 301 | expectedType: "file", |
| 302 | matched: true, |
| 303 | }, |
| 304 | { |
| 305 | path: "/index.php/somewhere", |
| 306 | expectedPath: "/index.php", |
| 307 | expectedType: "file", |
| 308 | matched: true, |
| 309 | }, |
| 310 | { |
| 311 | path: "/remote.php", |
| 312 | expectedPath: "/remote.php", |
| 313 | expectedType: "file", |
| 314 | matched: true, |
| 315 | }, |
| 316 | { |
| 317 | path: "/remote.php/somewhere", |
| 318 | expectedPath: "/remote.php", |
| 319 | expectedType: "file", |
| 320 | matched: true, |
| 321 | }, |
| 322 | { |
| 323 | path: "/missingfile.php", |
| 324 | matched: false, |
| 325 | }, |
| 326 | { |
| 327 | path: "/notphp.php.txt", |
| 328 | expectedPath: "/notphp.php.txt", |
| 329 | expectedType: "file", |
| 330 | matched: true, |
| 331 | }, |
| 332 | { |
| 333 | path: "/notphp.php.txt/", |
| 334 | expectedPath: "/notphp.php.txt", |
| 335 | expectedType: "file", |
| 336 | matched: true, |
| 337 | }, |
| 338 | { |
| 339 | path: "/notphp.php.txt.suffixed", |
| 340 | matched: false, |
| 341 | }, |
| 342 | { |
| 343 | path: "/foo.php.php/index.php", |
| 344 | expectedPath: "/foo.php.php/index.php", |
| 345 | expectedType: "file", |
| 346 | matched: true, |
| 347 | }, |
| 348 | { |
| 349 | // See https://github.com/caddyserver/caddy/issues/3623 |
| 350 | path: "/%E2%C3", |
| 351 | expectedPath: "/%E2%C3", |
| 352 | expectedType: "file", |
| 353 | matched: false, |
| 354 | }, |
| 355 | { |
| 356 | path: "/index.php?path={path}&{query}", |
| 357 | expectedPath: "/index.php", |
| 358 | expectedType: "file", |
| 359 | matched: true, |
| 360 | }, |
| 361 | } { |
| 362 | m := &MatchFile{ |
| 363 | fsmap: &filesystems.FileSystemMap{}, |
| 364 | Root: "./testdata", |
| 365 | TryFiles: []string{"{http.request.uri.path}", "{http.request.uri.path}/index.php"}, |
| 366 | SplitPath: []string{".php"}, |
| 367 | } |
| 368 | |
| 369 | u, err := url.Parse(tc.path) |
| 370 | if err != nil { |
| 371 | t.Errorf("Test %d: parsing path: %v", i, err) |
| 372 | } |
| 373 | |
| 374 | req := &http.Request{URL: u} |
| 375 | repl := caddyhttp.NewTestReplacer(req) |
| 376 | |
| 377 | result, err := m.MatchWithError(req) |
| 378 | if err != nil { |
| 379 | t.Errorf("Test %d: unexpected error: %v", i, err) |
| 380 | } |
| 381 | if result != tc.matched { |
| 382 | t.Errorf("Test %d: expected match=%t, got %t", i, tc.matched, result) |
| 383 | } |
| 384 | |
| 385 | rel, ok := repl.Get("http.matchers.file.relative") |
| 386 | if !ok && result { |
| 387 | t.Errorf("Test %d: expected replacer value", i) |
| 388 | } |
| 389 | if !result { |
| 390 | continue |
| 391 | } |
| 392 | |
| 393 | if rel != tc.expectedPath { |
| 394 | t.Errorf("Test %d: actual path: %v, expected: %v", i, rel, tc.expectedPath) |
| 395 | } |
| 396 | |
| 397 | fileType, _ := repl.Get("http.matchers.file.type") |
| 398 | if fileType != tc.expectedType { |
| 399 | t.Errorf("Test %d: actual file type: %v, expected: %v", i, fileType, tc.expectedType) |
| 400 | } |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | func TestFirstSplit(t *testing.T) { |
| 405 | m := MatchFile{ |
| 406 | SplitPath: []string{".php"}, |
| 407 | fsmap: &filesystems.FileSystemMap{}, |
| 408 | } |
| 409 | actual, remainder := m.firstSplit("index.PHP/somewhere") |
| 410 | expected := "index.PHP" |
| 411 | expectedRemainder := "/somewhere" |
| 412 | if actual != expected { |
| 413 | t.Errorf("Expected split %s but got %s", expected, actual) |
| 414 | } |
| 415 | if remainder != expectedRemainder { |
| 416 | t.Errorf("Expected remainder %s but got %s", expectedRemainder, remainder) |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | var expressionTests = []struct { |
| 421 | name string |
| 422 | expression *caddyhttp.MatchExpression |
| 423 | urlTarget string |
| 424 | httpMethod string |
| 425 | httpHeader *http.Header |
| 426 | wantErr bool |
| 427 | wantResult bool |
| 428 | clientCertificate []byte |
| 429 | expectedPath string |
| 430 | }{ |
| 431 | { |
| 432 | name: "file error no args (MatchFile)", |
| 433 | expression: &caddyhttp.MatchExpression{ |
| 434 | Expr: `file()`, |
| 435 | }, |
| 436 | urlTarget: "https://example.com/foo.txt", |
| 437 | wantResult: true, |
| 438 | }, |
| 439 | { |
| 440 | name: "file error bad try files (MatchFile)", |
| 441 | expression: &caddyhttp.MatchExpression{ |
| 442 | Expr: `file({"try_file": ["bad_arg"]})`, |
| 443 | }, |
| 444 | urlTarget: "https://example.com/foo", |
| 445 | wantErr: true, |
| 446 | }, |
| 447 | { |
| 448 | name: "file match short pattern index.php (MatchFile)", |
| 449 | expression: &caddyhttp.MatchExpression{ |
| 450 | Expr: `file("index.php")`, |
| 451 | }, |
| 452 | urlTarget: "https://example.com/foo", |
| 453 | wantResult: true, |
| 454 | }, |
| 455 | { |
| 456 | name: "file match short pattern foo.txt (MatchFile)", |
| 457 | expression: &caddyhttp.MatchExpression{ |
| 458 | Expr: `file({http.request.uri.path})`, |
| 459 | }, |
| 460 | urlTarget: "https://example.com/foo.txt", |
| 461 | wantResult: true, |
| 462 | }, |
| 463 | { |
| 464 | name: "file match index.php (MatchFile)", |
| 465 | expression: &caddyhttp.MatchExpression{ |
| 466 | Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}, "/index.php"]})`, |
| 467 | }, |
| 468 | urlTarget: "https://example.com/foo", |
| 469 | wantResult: true, |
| 470 | }, |
| 471 | { |
| 472 | name: "file match long pattern foo.txt (MatchFile)", |
| 473 | expression: &caddyhttp.MatchExpression{ |
| 474 | Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}]})`, |
| 475 | }, |
| 476 | urlTarget: "https://example.com/foo.txt", |
| 477 | wantResult: true, |
| 478 | }, |
| 479 | { |
| 480 | name: "file match long pattern foo.txt with concatenation (MatchFile)", |
| 481 | expression: &caddyhttp.MatchExpression{ |
| 482 | Expr: `file({"root": ".", "try_files": ["./testdata" + {http.request.uri.path}]})`, |
| 483 | }, |
| 484 | urlTarget: "https://example.com/foo.txt", |
| 485 | wantResult: true, |
| 486 | }, |
| 487 | { |
| 488 | name: "file not match long pattern (MatchFile)", |
| 489 | expression: &caddyhttp.MatchExpression{ |
| 490 | Expr: `file({"root": "./testdata", "try_files": [{http.request.uri.path}]})`, |
| 491 | }, |
| 492 | urlTarget: "https://example.com/nopenope.txt", |
| 493 | wantResult: false, |
| 494 | }, |
| 495 | { |
| 496 | name: "file match long pattern foo.txt with try_policy (MatchFile)", |
| 497 | expression: &caddyhttp.MatchExpression{ |
| 498 | Expr: `file({"root": "./testdata", "try_policy": "largest_size", "try_files": ["foo.txt", "large.txt"]})`, |
| 499 | }, |
| 500 | urlTarget: "https://example.com/", |
| 501 | wantResult: true, |
| 502 | expectedPath: "/large.txt", |
| 503 | }, |
| 504 | } |
| 505 | |
| 506 | func TestMatchExpressionMatch(t *testing.T) { |
| 507 | for _, tst := range expressionTests { |
| 508 | tc := tst |
| 509 | t.Run(tc.name, func(t *testing.T) { |
| 510 | caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) |
| 511 | defer cancel() |
| 512 | err := tc.expression.Provision(caddyCtx) |
| 513 | if err != nil { |
| 514 | if !tc.wantErr { |
| 515 | t.Errorf("MatchExpression.Provision() error = %v, wantErr %v", err, tc.wantErr) |
| 516 | } |
| 517 | return |
| 518 | } |
| 519 | |
| 520 | req := httptest.NewRequest(tc.httpMethod, tc.urlTarget, nil) |
| 521 | if tc.httpHeader != nil { |
| 522 | req.Header = *tc.httpHeader |
| 523 | } |
| 524 | repl := caddyhttp.NewTestReplacer(req) |
| 525 | repl.Set("http.vars.root", "./testdata") |
| 526 | ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) |
| 527 | req = req.WithContext(ctx) |
| 528 | |
| 529 | matches, err := tc.expression.MatchWithError(req) |
| 530 | if err != nil { |
| 531 | t.Errorf("MatchExpression.Match() error = %v", err) |
| 532 | return |
| 533 | } |
| 534 | if matches != tc.wantResult { |
| 535 | t.Errorf("MatchExpression.Match() expected to return '%t', for expression : '%s'", tc.wantResult, tc.expression.Expr) |
| 536 | } |
| 537 | |
| 538 | if tc.expectedPath != "" { |
| 539 | path, ok := repl.Get("http.matchers.file.relative") |
| 540 | if !ok { |
| 541 | t.Errorf("MatchExpression.Match() expected to return path '%s', but got none", tc.expectedPath) |
| 542 | } |
| 543 | if path != tc.expectedPath { |
| 544 | t.Errorf("MatchExpression.Match() expected to return path '%s', but got '%s'", tc.expectedPath, path) |
| 545 | } |
| 546 | } |
| 547 | }) |
| 548 | } |
| 549 | } |