|
| 1 | +package handler |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "path/filepath" |
| 6 | + "strings" |
| 7 | + "testing" |
| 8 | +) |
| 9 | + |
| 10 | +func TestCopyFilesToTmpDir_PathTraversal_ShouldBeBlocked(t *testing.T) { |
| 11 | + testCases := []struct { |
| 12 | + name string |
| 13 | + filename string |
| 14 | + }{ |
| 15 | + {"dot-dot-slash", "../escape.txt"}, |
| 16 | + {"multiple-dot-dot", "../../escape.txt"}, |
| 17 | + {"deeply-nested-escape", "subdir/../../escape.txt"}, |
| 18 | + {"dot-dot-in-middle", "foo/../../../escape.txt"}, |
| 19 | + } |
| 20 | + |
| 21 | + for _, tc := range testCases { |
| 22 | + t.Run(tc.name, func(t *testing.T) { |
| 23 | + subTmpDir, err := os.MkdirTemp("", "test_sub_sandbox") |
| 24 | + if err != nil { |
| 25 | + t.Fatalf("failed to create temp dir: %v", err) |
| 26 | + } |
| 27 | + defer os.RemoveAll(subTmpDir) |
| 28 | + |
| 29 | + files := map[string]string{ |
| 30 | + tc.filename: "escaped content", |
| 31 | + } |
| 32 | + |
| 33 | + err = copyFilesToTmpDir(subTmpDir, files) |
| 34 | + |
| 35 | + if err == nil { |
| 36 | + t.Errorf("expected error for path traversal attempt %q, got nil", tc.filename) |
| 37 | + } else if !strings.Contains(err.Error(), "path traversal detected") { |
| 38 | + t.Errorf("expected 'path traversal detected' error, got: %v", err) |
| 39 | + } |
| 40 | + |
| 41 | + resultPath := filepath.Join(subTmpDir, tc.filename) |
| 42 | + cleanPath := filepath.Clean(resultPath) |
| 43 | + if _, statErr := os.Stat(cleanPath); statErr == nil { |
| 44 | + t.Errorf("file should NOT exist at escaped path: %s", cleanPath) |
| 45 | + } |
| 46 | + }) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +func TestCopyFilesToTmpDir_ValidPaths(t *testing.T) { |
| 51 | + tmpDir, err := os.MkdirTemp("", "test_sandbox") |
| 52 | + if err != nil { |
| 53 | + t.Fatalf("failed to create temp dir: %v", err) |
| 54 | + } |
| 55 | + defer os.RemoveAll(tmpDir) |
| 56 | + |
| 57 | + validFiles := map[string]string{ |
| 58 | + "main.go": "package main", |
| 59 | + "src/util.go": "package src", |
| 60 | + "src/lib/helper.go": "package lib", |
| 61 | + } |
| 62 | + |
| 63 | + err = copyFilesToTmpDir(tmpDir, validFiles) |
| 64 | + if err != nil { |
| 65 | + t.Fatalf("copyFilesToTmpDir failed for valid paths: %v", err) |
| 66 | + } |
| 67 | + |
| 68 | + for filename, expectedContent := range validFiles { |
| 69 | + filePath := filepath.Join(tmpDir, filename) |
| 70 | + content, err := os.ReadFile(filePath) |
| 71 | + if err != nil { |
| 72 | + t.Errorf("failed to read %s: %v", filename, err) |
| 73 | + continue |
| 74 | + } |
| 75 | + if string(content) != expectedContent { |
| 76 | + t.Errorf("content mismatch for %s: got %q, want %q", filename, string(content), expectedContent) |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments