|
| 1 | +package ospath |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "path/filepath" |
| 6 | + "strings" |
| 7 | + "testing" |
| 8 | +) |
| 9 | + |
| 10 | +func TestSanitize(t *testing.T) { |
| 11 | + // Create a temp folder and file to simulate "already exists" |
| 12 | + existingDir := t.TempDir() |
| 13 | + existingFile := filepath.Join(existingDir, "exists.txt") |
| 14 | + if err := os.WriteFile(existingFile, []byte("data"), 0644); err != nil { |
| 15 | + t.Fatal(err) |
| 16 | + } |
| 17 | + |
| 18 | + tests := []struct { |
| 19 | + name string |
| 20 | + path string |
| 21 | + disallowedPrefixes []string |
| 22 | + expectedPath string |
| 23 | + expectedErrPrefix string |
| 24 | + }{ |
| 25 | + { |
| 26 | + name: "valid path", |
| 27 | + path: filepath.Join(existingDir, "test"), |
| 28 | + expectedPath: filepath.Join(existingDir, "test"), |
| 29 | + }, |
| 30 | + { |
| 31 | + name: "empty path", |
| 32 | + path: "", |
| 33 | + expectedErrPrefix: errUnsafePath.Error(), |
| 34 | + }, |
| 35 | + { |
| 36 | + name: "path traversal", |
| 37 | + path: `C:\foo\..\Windows`, |
| 38 | + disallowedPrefixes: []string{`C:\Windows`}, |
| 39 | + expectedErrPrefix: errUnsafePath.Error(), |
| 40 | + }, |
| 41 | + { |
| 42 | + name: "UNC path", |
| 43 | + path: `\\server\share`, |
| 44 | + expectedErrPrefix: errUnsafePath.Error(), |
| 45 | + }, |
| 46 | + { |
| 47 | + name: "disallowed prefix", |
| 48 | + path: `C:\Windows\System32`, |
| 49 | + disallowedPrefixes: []string{`C:\Windows`}, |
| 50 | + expectedErrPrefix: errUnsafePath.Error(), |
| 51 | + }, |
| 52 | + { |
| 53 | + name: "existing folder", |
| 54 | + path: existingDir, |
| 55 | + expectedErrPrefix: "already exists", |
| 56 | + }, |
| 57 | + { |
| 58 | + name: "existing file", |
| 59 | + path: existingFile, |
| 60 | + expectedErrPrefix: "already exists", |
| 61 | + }, |
| 62 | + } |
| 63 | + |
| 64 | + for _, tt := range tests { |
| 65 | + t.Run(tt.name, func(t *testing.T) { |
| 66 | + got, err := Sanitize(tt.path, tt.disallowedPrefixes) |
| 67 | + |
| 68 | + if tt.expectedErrPrefix != "" { |
| 69 | + if err == nil { |
| 70 | + t.Fatalf("expected error containing %q, got nil", tt.expectedErrPrefix) |
| 71 | + } |
| 72 | + if !strings.Contains(err.Error(), tt.expectedErrPrefix) { |
| 73 | + t.Fatalf("expected error to contain %q, got %v", tt.expectedErrPrefix, err) |
| 74 | + } |
| 75 | + } else if err != nil { |
| 76 | + t.Fatalf("expected no error, got %v", err) |
| 77 | + } |
| 78 | + |
| 79 | + if !strings.EqualFold(got, tt.expectedPath) { |
| 80 | + t.Errorf("expected path %q, got %q", tt.expectedPath, got) |
| 81 | + } |
| 82 | + }) |
| 83 | + } |
| 84 | +} |
0 commit comments