-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
630 lines (536 loc) · 16.1 KB
/
main_test.go
File metadata and controls
630 lines (536 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
package main
import (
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
)
// setupTestRepo creates a temporary git repository with some commits for testing
func setupTestRepo(t *testing.T) (repoDir string, cleanup func()) {
t.Helper()
// Create temp directory
tmpDir, err := os.MkdirTemp("", "differing-test-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
cleanup = func() {
os.RemoveAll(tmpDir)
}
// Initialize git repo
runGitCmd := func(args ...string) {
cmd := exec.Command("git", args...)
cmd.Dir = tmpDir
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Git command failed: %s\nOutput: %s", err, output)
}
}
runGitCmd("init")
runGitCmd("config", "user.name", "Test User")
// Create first commit with a test file
testFile1 := filepath.Join(tmpDir, "test1.go")
if err := os.WriteFile(testFile1, []byte("package main\n\nfunc hello() {}\n"), 0644); err != nil {
t.Fatalf("Failed to write test file: %v", err)
}
runGitCmd("add", "test1.go")
runGitCmd("commit", "-m", "Initial commit")
// Create second commit modifying the file
if err := os.WriteFile(testFile1, []byte("package main\n\nfunc hello() string {\n\treturn \"hello\"\n}\n"), 0644); err != nil {
t.Fatalf("Failed to write test file: %v", err)
}
runGitCmd("add", "test1.go")
runGitCmd("commit", "-m", "Update hello function")
// Create third commit adding a new file
testFile2 := filepath.Join(tmpDir, "test2.ts")
if err := os.WriteFile(testFile2, []byte("export function world() {}\n"), 0644); err != nil {
t.Fatalf("Failed to write test file: %v", err)
}
runGitCmd("add", "test2.ts")
runGitCmd("commit", "-m", "Add TypeScript file")
// Modify test2.ts in working tree (not committed)
if err := os.WriteFile(testFile2, []byte("export function world() {\n return 'world';\n}\n"), 0644); err != nil {
t.Fatalf("Failed to write test file: %v", err)
}
return tmpDir, cleanup
}
func TestGetDiffsNullByteSeparator(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
defer cleanup()
// Change to test repo directory
oldDir, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current dir: %v", err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to change to test repo: %v", err)
}
// Test that git log with null byte separator works
cmd := exec.Command("git", "log", "--oneline", "-20", "--pretty=format:%H%x00%s%x00%an%x00%at")
output, err := cmd.Output()
if err != nil {
t.Fatalf("Failed to get git log: %v", err)
}
// Parse output - should have 3 commits
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
if len(lines) != 3 {
t.Errorf("Expected 3 commits, got %d", len(lines))
}
// Verify each line has 4 null-separated parts
for i, line := range lines {
parts := strings.Split(line, "\x00")
if len(parts) != 4 {
t.Errorf("Line %d: expected 4 parts, got %d: %v", i, len(parts), parts)
}
// Verify parts are not empty (except possibly message)
if parts[0] == "" { // commit hash
t.Errorf("Line %d: commit hash is empty", i)
}
if parts[2] == "" { // author
t.Errorf("Line %d: author is empty", i)
}
if parts[3] == "" { // timestamp
t.Errorf("Line %d: timestamp is empty", i)
}
}
}
func TestGetDiffFilesWithWorkingTree(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
defer cleanup()
oldDir, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current dir: %v", err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to change to test repo: %v", err)
}
// Get the most recent commit hash
cmd := exec.Command("git", "rev-parse", "HEAD")
output, err := cmd.Output()
if err != nil {
t.Fatalf("Failed to get HEAD: %v", err)
}
commitHash := string(output[:len(output)-1]) // trim newline
// Get files changed from parent to working tree
cmd = exec.Command("git", "diff", "--name-status", commitHash+"^")
output, err = cmd.Output()
if err != nil {
t.Fatalf("Failed to get diff files: %v", err)
}
// Should show both test1.go (from earlier commit) and test2.ts (modified in working tree)
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
if len(lines) == 0 {
t.Error("Expected at least one changed file")
}
// Verify we can see working tree changes
foundTest2 := false
for _, line := range lines {
if strings.Contains(line, "test2.ts") {
foundTest2 = true
}
}
if foundTest2 {
// Verify the status shows modification
cmd = exec.Command("git", "status", "--porcelain", "test2.ts")
output, err = cmd.Output()
if err != nil {
t.Fatalf("Failed to get git status: %v", err)
}
if len(output) == 0 {
t.Error("test2.ts should show as modified in working tree")
}
}
}
func TestGetFileDiffUsesWorkingTree(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
defer cleanup()
oldDir, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current dir: %v", err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to change to test repo: %v", err)
}
// Get the most recent commit hash
cmd := exec.Command("git", "rev-parse", "HEAD")
output, err := cmd.Output()
if err != nil {
t.Fatalf("Failed to get HEAD: %v", err)
}
commitHash := string(output[:len(output)-1])
// Get old version from HEAD (committed version of test2.ts)
cmd = exec.Command("git", "show", commitHash+":test2.ts")
oldOutput, err := cmd.Output()
if err != nil {
t.Fatalf("Failed to get committed version: %v", err)
}
// Get new version from working tree
newContent, err := os.ReadFile("test2.ts")
if err != nil {
t.Fatalf("Failed to read working tree file: %v", err)
}
oldStr := string(oldOutput)
newStr := string(newContent)
// They should be different (we modified the file in working tree)
if oldStr == newStr {
t.Error("Expected old and new content to be different")
}
// New content should contain the working tree changes
if !strings.Contains(newStr, "return 'world'") {
t.Error("New content should contain working tree changes")
}
// Old content should be the original from HEAD commit
if !strings.Contains(oldStr, "export function world() {}") {
t.Error("Old content should be from commit")
}
}
func TestCommitTimestampParsing(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
defer cleanup()
oldDir, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current dir: %v", err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to change to test repo: %v", err)
}
cmd := exec.Command("git", "log", "--oneline", "-1", "--pretty=format:%H%x00%s%x00%an%x00%at")
output, err := cmd.Output()
if err != nil {
t.Fatalf("Failed to get git log: %v", err)
}
parts := strings.Split(string(output), "\x00")
if len(parts) < 4 {
t.Fatalf("Expected 4 parts, got %d", len(parts))
}
// Parse timestamp
timestamp, err := strconv.ParseInt(strings.TrimSpace(parts[3]), 10, 64)
if err != nil {
t.Errorf("Failed to parse timestamp: %v", err)
}
// Verify it's a reasonable Unix timestamp (after year 2020)
ts := time.Unix(timestamp, 0)
if ts.Year() < 2020 {
t.Errorf("Timestamp seems invalid: %v", ts)
}
}
func init() {
// Set gin to test mode
gin.SetMode(gin.TestMode)
}
func TestValidateRepoPath(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
defer cleanup()
oldDir, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current dir: %v", err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to change to test repo: %v", err)
}
// Initialize global gitRoot for testing
gitRoot, err = getGitRoot()
if err != nil {
t.Fatalf("Failed to get git root: %v", err)
}
tests := []struct {
name string
filePath string
wantError bool
errorMsg string
}{
{
name: "valid tracked file",
filePath: "test1.go",
wantError: false,
},
{
name: "another valid tracked file",
filePath: "test2.ts",
wantError: false,
},
{
name: "untracked file",
filePath: "untracked.txt",
wantError: true,
errorMsg: "not tracked by git",
},
{
name: "directory traversal attack - parent directory",
filePath: "../../../etc/passwd",
wantError: true,
errorMsg: "not tracked by git",
},
{
name: "directory traversal attack - mixed",
filePath: "test1.go/../../etc/passwd",
wantError: true,
errorMsg: "not tracked by git",
},
{
name: "absolute path",
filePath: "/etc/passwd",
wantError: true,
errorMsg: "invalid file path",
},
{
name: "empty path",
filePath: "",
wantError: true,
errorMsg: "invalid file path",
},
{
name: "file that doesn't exist but is tracked",
filePath: "nonexistent.go",
wantError: true,
errorMsg: "not tracked by git",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateRepoPath(tt.filePath)
if tt.wantError {
if err == nil {
t.Errorf("validateRepoPath(%q) expected error, got nil", tt.filePath)
} else if !strings.Contains(err.Error(), tt.errorMsg) {
t.Errorf("validateRepoPath(%q) error = %v, want error containing %q", tt.filePath, err, tt.errorMsg)
}
} else {
if err != nil {
t.Errorf("validateRepoPath(%q) unexpected error: %v", tt.filePath, err)
}
}
})
}
}
func TestGetGitRoot(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
defer cleanup()
oldDir, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current dir: %v", err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to change to test repo: %v", err)
}
// Test from repo root
root, err := getGitRoot()
if err != nil {
t.Fatalf("getGitRoot() failed: %v", err)
}
absRepoDir, _ := filepath.Abs(repoDir)
if root != absRepoDir {
t.Errorf("getGitRoot() = %q, want %q", root, absRepoDir)
}
// Test from non-git directory
if err := os.Chdir("/tmp"); err != nil {
t.Fatalf("Failed to change to /tmp: %v", err)
}
_, err = getGitRoot()
if err == nil {
t.Error("getGitRoot() from non-git directory should fail")
}
}
func TestGetGitRootWithWorktree(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
defer cleanup()
oldDir, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current dir: %v", err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to change to test repo: %v", err)
}
// Create a worktree
worktreePath := filepath.Join(filepath.Dir(repoDir), "test-worktree")
defer os.RemoveAll(worktreePath)
cmd := exec.Command("git", "worktree", "add", worktreePath, "HEAD")
cmd.Dir = repoDir
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to create worktree: %v - %s", err, output)
}
// Change to worktree directory
if err := os.Chdir(worktreePath); err != nil {
t.Fatalf("Failed to change to worktree: %v", err)
}
// Get git root from worktree - should return the worktree path, not the main repo
worktreeRoot, err := getGitRoot()
if err != nil {
t.Fatalf("getGitRoot() from worktree failed: %v", err)
}
absWorktreePath, _ := filepath.Abs(worktreePath)
if worktreeRoot != absWorktreePath {
t.Errorf("getGitRoot() from worktree = %q, want %q", worktreeRoot, absWorktreePath)
}
// Verify that files in the worktree are accessible
// The worktree should have the same tracked files as the main repo
gitRoot = worktreeRoot
err = validateRepoPath("test1.go")
if err != nil {
t.Errorf("validateRepoPath() in worktree failed: %v", err)
}
}
func TestSaveFileWithOsRoot(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
defer cleanup()
oldDir, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current dir: %v", err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to change to test repo: %v", err)
}
// Initialize globals for testing
gitRoot, err = getGitRoot()
if err != nil {
t.Fatalf("Failed to get git root: %v", err)
}
secureRoot, err = os.OpenRoot(gitRoot)
if err != nil {
t.Fatalf("Failed to create secure root: %v", err)
}
tests := []struct {
name string
filePath string
newContent string
wantSuccess bool
}{
{
name: "valid file write",
filePath: "test1.go",
newContent: "package main\n\nfunc updated() {}\n",
wantSuccess: true,
},
{
name: "directory traversal attempt",
filePath: "../../../tmp/evil.txt",
newContent: "malicious content",
wantSuccess: false,
},
{
name: "untracked file",
filePath: "newfile.txt",
newContent: "should not write",
wantSuccess: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// First validate the path
err := validateRepoPath(tt.filePath)
if tt.wantSuccess && err != nil {
t.Errorf("validateRepoPath(%q) unexpected error: %v", tt.filePath, err)
return
}
if !tt.wantSuccess && err == nil {
// Expected to fail validation
return
}
if tt.wantSuccess {
// Try to write using os.Root
file, err := secureRoot.OpenFile(tt.filePath, os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
t.Errorf("OpenFile(%q) failed: %v", tt.filePath, err)
return
}
defer file.Close()
_, err = file.Write([]byte(tt.newContent))
if err != nil {
t.Errorf("Write(%q) failed: %v", tt.filePath, err)
return
}
// Verify the content was written correctly
writtenContent, err := os.ReadFile(filepath.Join(gitRoot, tt.filePath))
if err != nil {
t.Errorf("Failed to read back file: %v", err)
return
}
if string(writtenContent) != tt.newContent {
t.Errorf("File content = %q, want %q", string(writtenContent), tt.newContent)
}
}
})
}
// Explicitly test that os.Root prevents directory traversal
_, err = secureRoot.OpenFile("../../../etc/passwd", os.O_RDONLY, 0)
if err == nil {
t.Error("os.Root should prevent access to files outside the root")
}
}
func TestSaveFileInWorktree(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
defer cleanup()
oldDir, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current dir: %v", err)
}
defer os.Chdir(oldDir)
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to change to test repo: %v", err)
}
// Create a worktree
worktreePath := filepath.Join(filepath.Dir(repoDir), "test-worktree-save")
defer os.RemoveAll(worktreePath)
cmd := exec.Command("git", "worktree", "add", worktreePath, "HEAD")
cmd.Dir = repoDir
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to create worktree: %v - %s", err, output)
}
// Change to worktree
if err := os.Chdir(worktreePath); err != nil {
t.Fatalf("Failed to change to worktree: %v", err)
}
// Initialize globals for worktree
gitRoot, err = getGitRoot()
if err != nil {
t.Fatalf("Failed to get git root from worktree: %v", err)
}
secureRoot, err = os.OpenRoot(gitRoot)
if err != nil {
t.Fatalf("Failed to create secure root for worktree: %v", err)
}
// Test writing a file in the worktree
testContent := "package main\n\nfunc worktreeTest() {}\n"
err = validateRepoPath("test1.go")
if err != nil {
t.Fatalf("validateRepoPath() failed in worktree: %v", err)
}
file, err := secureRoot.OpenFile("test1.go", os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
t.Fatalf("OpenFile() failed in worktree: %v", err)
}
defer file.Close()
_, err = file.Write([]byte(testContent))
if err != nil {
t.Fatalf("Write() failed in worktree: %v", err)
}
file.Close()
// Verify the content was written
writtenContent, err := os.ReadFile(filepath.Join(gitRoot, "test1.go"))
if err != nil {
t.Fatalf("Failed to read back file from worktree: %v", err)
}
if string(writtenContent) != testContent {
t.Errorf("Worktree file content = %q, want %q", string(writtenContent), testContent)
}
// Ensure directory traversal is still blocked in worktree
err = validateRepoPath("../../etc/passwd")
if err == nil {
t.Error("validateRepoPath() should reject directory traversal in worktree")
}
_, err = secureRoot.OpenFile("../../etc/passwd", os.O_RDONLY, 0)
if err == nil {
t.Error("os.Root should prevent directory traversal in worktree")
}
}