-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
545 lines (484 loc) · 16.7 KB
/
Copy pathmain_test.go
File metadata and controls
545 lines (484 loc) · 16.7 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
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// TestLandlockABIQuery verifies the ABI query returns a valid version number
// (including 0 on kernels without Landlock). This is purely a smoke test —
// whether Landlock is actually available depends on the host kernel.
func TestLandlockABIQuery(t *testing.T) {
abi := queryLandlockABI()
t.Logf("Landlock ABI support: %d (0 = unavailable)", abi)
if abi < 0 || abi > 10 {
t.Errorf("unexpected ABI version: %d", abi)
}
}
// TestLandlockWriteMaskForABI verifies the right-set negotiation table.
func TestLandlockWriteMaskForABI(t *testing.T) {
tests := []struct {
abi int
wantNonZero bool
}{
{0, true}, // baseline (v1 rights)
{1, true}, // v1
{2, true}, // v2 adds REFER
{3, true}, // v3 adds TRUNCATE
{4, true}, // v4 same as v3
{5, true}, // v5 adds IOCTL_DEV
{100, true}, // future-proof: uses the full set
}
for _, tt := range tests {
mask := landlockWriteMaskForABI(tt.abi)
if tt.wantNonZero && mask == 0 {
t.Errorf("ABI %d: expected non-zero mask, got 0", tt.abi)
}
// The write-file right (v1) should always be present.
if mask&landlockWriteBase == 0 {
t.Errorf("ABI %d: LANDLOCK_ACCESS_FS_WRITE_FILE missing from mask", tt.abi)
}
}
}
// TestLandlockWriteMaskMonotonic verifies that higher ABI versions never lose
// rights that earlier versions had.
func TestLandlockWriteMaskMonotonic(t *testing.T) {
var prev uint64
for abi := 0; abi <= 5; abi++ {
cur := landlockWriteMaskForABI(abi)
// cur must be a superset of prev.
if cur&prev != prev {
t.Errorf("ABI %d mask (0x%x) is not a superset of ABI %d mask (0x%x)", abi, cur, abi-1, prev)
}
prev = cur
}
}
// TestBinaryIntegration runs the compiled shofer-sandbox binary and verifies:
// - writes inside the worktree succeed
// - writes outside the worktree are denied (EACCES)
// - reads outside the worktree succeed (reads are unrestricted)
//
// This test requires either Landlock (kernel ≥ 5.13) or bwrap to be installed.
// On systems with neither, the test is skipped.
func TestBinaryIntegration(t *testing.T) {
sandboxBin := "./shofer-sandbox"
if _, err := os.Stat(sandboxBin); os.IsNotExist(err) {
t.Skip("shofer-sandbox binary not built — run 'go build -o shofer-sandbox .' first")
}
// Create the worktree directory. Because /tmp is itself write-allowed
// by the sandbox, the "outside" target must live somewhere NOT under
// /tmp or /dev. Use the test's own working directory (which is the
// sandbox source tree — not a write-allowed path).
worktree, err := os.MkdirTemp("", "shofer-sandbox-test-")
if err != nil {
t.Fatalf("MkdirTemp: %v", err)
}
defer os.RemoveAll(worktree)
// Create the "outside" directory in the current working directory
// (the sandbox source dir) — this is NOT in the Landlock ruleset.
cwd, _ := os.Getwd()
outsideDir := filepath.Join(cwd, "shofer-sandbox-outside-test")
if err := os.MkdirAll(outsideDir, 0o755); err != nil {
t.Fatalf("MkdirAll(outsideDir): %v", err)
}
defer os.RemoveAll(outsideDir)
outsideFile := filepath.Join(outsideDir, "should-not-exist.txt")
// 1. Write inside the worktree → must succeed.
insidePath := filepath.Join(worktree, "test.txt")
cmd := exec.Command(sandboxBin, worktree, "--",
"/bin/sh", "-c", "echo hello > "+insidePath)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("write inside worktree failed: %v\noutput: %s", err, out)
}
data, err := os.ReadFile(insidePath)
if err != nil {
t.Fatalf("ReadFile(%s): %v", insidePath, err)
}
if strings.TrimSpace(string(data)) != "hello" {
t.Errorf("expected 'hello', got '%s'", strings.TrimSpace(string(data)))
}
// 2. Write outside the worktree → must fail with EACCES (or at least non-zero).
cmd = exec.Command(sandboxBin, worktree, "--",
"/bin/sh", "-c", "echo overwrite > "+outsideFile)
out, err = cmd.CombinedOutput()
if err == nil {
t.Fatalf("write outside worktree should have been denied, but succeeded\noutput: %s", out)
}
// Verify the file was NOT overwritten.
data, _ = os.ReadFile(outsideFile)
if strings.TrimSpace(string(data)) == "overwrite" {
t.Errorf("outside file was overwritten despite sandbox")
}
// 3. Read outside the worktree → must succeed (reads unrestricted).
cmd = exec.Command(sandboxBin, worktree, "--",
"cat", "/etc/hostname")
out, err = cmd.CombinedOutput()
// cat may fail if /etc/hostname doesn't exist, but that's not a sandbox issue.
if _, statErr := os.Stat("/etc/hostname"); statErr == nil {
if err != nil && !strings.Contains(string(out), "No such file") {
t.Fatalf("read outside worktree failed with unexpected error: %v\noutput: %s", err, out)
}
}
}
// TestParseWorktreeGitDir verifies parsing the worktree .git file.
func TestParseWorktreeGitDir(t *testing.T) {
// Create a temp directory with a .git file simulating a git worktree.
dir := t.TempDir()
gitFile := filepath.Join(dir, ".git")
gitDir := filepath.Join(dir, "..", "main", ".git", "worktrees", "test-wt")
if err := os.MkdirAll(gitDir, 0o755); err != nil {
t.Fatalf("MkdirAll(gitDir): %v", err)
}
content := fmt.Sprintf("gitdir: %s\n", gitDir)
if err := os.WriteFile(gitFile, []byte(content), 0o644); err != nil {
t.Fatalf("WriteFile(.git): %v", err)
}
got, err := parseWorktreeGitDir(dir)
if err != nil {
t.Fatalf("parseWorktreeGitDir: %v", err)
}
if got != filepath.Clean(gitDir) {
t.Errorf("expected %s, got %s", filepath.Clean(gitDir), got)
}
}
// TestParseWorktreeGitDir_Relative verifies parsing a .git file with a
// relative gitdir path (rather than absolute).
func TestParseWorktreeGitDir_Relative(t *testing.T) {
dir := t.TempDir()
gitFile := filepath.Join(dir, ".git")
content := "gitdir: ../.git/worktrees/some-task\n"
if err := os.WriteFile(gitFile, []byte(content), 0o644); err != nil {
t.Fatalf("WriteFile(.git): %v", err)
}
got, err := parseWorktreeGitDir(dir)
if err != nil {
t.Fatalf("parseWorktreeGitDir: %v", err)
}
expected := filepath.Join(dir, "..", ".git", "worktrees", "some-task")
if got != filepath.Clean(expected) {
t.Errorf("expected %s, got %s", filepath.Clean(expected), got)
}
}
// TestParseWorktreeGitDir_NotAWorktree verifies that a directory without a
// .git file returns an error.
func TestParseWorktreeGitDir_NotAWorktree(t *testing.T) {
dir := t.TempDir()
_, err := parseWorktreeGitDir(dir)
if err == nil {
t.Error("expected error for non-worktree directory, got nil")
}
}
// TestResolveWorktreeGitPaths_Integration verifies end-to-end resolution
// of git metadata paths from a simulated worktree directory.
func TestResolveWorktreeGitPaths_Integration(t *testing.T) {
// Layout:
// repo/ ← repo root (contains .git/ dir)
// .git/ ← main .git directory
// objects/ ← shared objects dir
// refs/ ← shared refs dir
// logs/ ← shared reflog dir
// worktrees/
// test-wt/
// commondir ← contains "../.."
// sub/worktree/ ← the simulated checkout root
// .git ← "gitdir: .../repo/.git/worktrees/test-wt"
repo := t.TempDir()
mainGit := filepath.Join(repo, ".git")
wtGitDir := filepath.Join(mainGit, "worktrees", "test-wt")
worktree := filepath.Join(repo, "sub", "worktree")
// Create main .git directory (so resolveRepoRoot finds it).
// Create shared .git objects/, refs/, and logs/ — the three
// subdirectories git writes to during add/commit/checkout.
for _, d := range []string{
mainGit,
filepath.Join(mainGit, "objects"),
filepath.Join(mainGit, "refs"),
filepath.Join(mainGit, "logs"),
wtGitDir,
} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatalf("MkdirAll(%s): %v", d, err)
}
}
// Write commondir pointing back to the main .git
if err := os.WriteFile(
filepath.Join(wtGitDir, "commondir"),
[]byte("../..\n"),
0o644,
); err != nil {
t.Fatalf("WriteFile(commondir): %v", err)
}
// Write the worktree's .git file
if err := os.MkdirAll(worktree, 0o755); err != nil {
t.Fatalf("MkdirAll(worktree): %v", err)
}
if err := os.WriteFile(
filepath.Join(worktree, ".git"),
[]byte(fmt.Sprintf("gitdir: %s\n", wtGitDir)),
0o644,
); err != nil {
t.Fatalf("WriteFile(.git): %v", err)
}
paths := resolveWorktreeGitPaths(worktree)
// Expected: the worktree git dir + main .git/objects + main .git/refs
// + main .git/logs
expectedObjs := filepath.Join(mainGit, "objects")
expectedRefs := filepath.Join(mainGit, "refs")
expectedLogs := filepath.Join(mainGit, "logs")
foundGitDir := false
foundObjs := false
foundRefs := false
foundLogs := false
for _, p := range paths {
switch p {
case wtGitDir:
foundGitDir = true
case expectedObjs:
foundObjs = true
case expectedRefs:
foundRefs = true
case expectedLogs:
foundLogs = true
}
}
if !foundGitDir {
t.Errorf("expected git dir %s in paths, got %v", wtGitDir, paths)
}
if !foundObjs {
t.Errorf("expected objects dir %s in paths, got %v", expectedObjs, paths)
}
if !foundRefs {
t.Errorf("expected refs dir %s in paths, got %v", expectedRefs, paths)
}
if !foundLogs {
t.Errorf("expected logs dir %s in paths, got %v", expectedLogs, paths)
}
}
// TestParseCommondirPaths verifies that parseCommondirPaths returns the
// objects/, refs/, and logs/ subdirectories of the common dir, omitting
// any that don't exist on disk.
func TestParseCommondirPaths(t *testing.T) {
// Layout:
// <tmp>/
// gitDir/
// commondir ← contains "../common"
// common/
// objects/
// refs/
// logs/
tmp := t.TempDir()
gitDir := filepath.Join(tmp, "gitDir")
commonDir := filepath.Join(tmp, "common")
// Create gitDir with commondir pointing to ../common
if err := os.MkdirAll(gitDir, 0o755); err != nil {
t.Fatalf("MkdirAll(gitDir): %v", err)
}
if err := os.WriteFile(
filepath.Join(gitDir, "commondir"),
[]byte("../common\n"),
0o644,
); err != nil {
t.Fatalf("WriteFile(commondir): %v", err)
}
// Create all three subdirectories under common/
for _, sub := range []string{"objects", "refs", "logs"} {
if err := os.MkdirAll(filepath.Join(commonDir, sub), 0o755); err != nil {
t.Fatalf("MkdirAll(%s): %v", sub, err)
}
}
paths := parseCommondirPaths(gitDir)
// All three should be present.
wantPaths := map[string]bool{
filepath.Join(commonDir, "objects"): false,
filepath.Join(commonDir, "refs"): false,
filepath.Join(commonDir, "logs"): false,
}
for _, p := range paths {
if _, ok := wantPaths[p]; ok {
wantPaths[p] = true
}
}
for p, found := range wantPaths {
if !found {
t.Errorf("expected %s in parseCommondirPaths output, got %v", p, paths)
}
}
}
// TestParseCommondirPaths_PartialDirs verifies that parseCommondirPaths
// omits non-existent subdirectories (e.g. logs/ may not exist in repos
// with reflog disabled).
func TestParseCommondirPaths_PartialDirs(t *testing.T) {
tmp := t.TempDir()
gitDir := filepath.Join(tmp, "gitDir")
commonDir := filepath.Join(tmp, "common")
if err := os.MkdirAll(gitDir, 0o755); err != nil {
t.Fatalf("MkdirAll(gitDir): %v", err)
}
if err := os.WriteFile(
filepath.Join(gitDir, "commondir"),
[]byte("../common\n"),
0o644,
); err != nil {
t.Fatalf("WriteFile(commondir): %v", err)
}
// Only create objects/ — refs/ and logs/ are absent.
if err := os.MkdirAll(filepath.Join(commonDir, "objects"), 0o755); err != nil {
t.Fatalf("MkdirAll(objects): %v", err)
}
paths := parseCommondirPaths(gitDir)
// Only objects/ should be present.
if len(paths) != 1 {
t.Fatalf("expected 1 path (objects only), got %d: %v", len(paths), paths)
}
expected := filepath.Join(commonDir, "objects")
if paths[0] != expected {
t.Errorf("expected %s, got %s", expected, paths[0])
}
}
// TestParseCommondirPaths_NoCommondir verifies that parseCommondirPaths
// returns nil when the commondir file is missing.
func TestParseCommondirPaths_NoCommondir(t *testing.T) {
dir := t.TempDir()
paths := parseCommondirPaths(dir)
if paths != nil {
t.Errorf("expected nil for missing commondir, got %v", paths)
}
}
// TestResolveWorktreeGitPaths_TamperedGitFile verifies that a tampered .git
// file (e.g. gitdir: /etc) is rejected — no extra paths are whitelisted.
func TestResolveWorktreeGitPaths_TamperedGitFile(t *testing.T) {
// Layout: same as integration test but the .git file points to /etc.
repo := t.TempDir()
mainGit := filepath.Join(repo, ".git")
worktree := filepath.Join(repo, "sub", "worktree")
for _, d := range []string{mainGit, worktree} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatalf("MkdirAll(%s): %v", d, err)
}
}
// Tampered .git file — points to /etc instead of the real gitdir.
if err := os.WriteFile(
filepath.Join(worktree, ".git"),
[]byte("gitdir: /etc\n"),
0o644,
); err != nil {
t.Fatalf("WriteFile(.git): %v", err)
}
paths := resolveWorktreeGitPaths(worktree)
if paths != nil {
t.Errorf("expected nil for tampered .git file, got %v", paths)
}
}
// TestResolveWorktreeGitPaths_GitdirNotUnderRepo verifies that a gitdir
// pointing to a worktrees dir of a different repo is rejected.
func TestResolveWorktreeGitPaths_GitdirNotUnderRepo(t *testing.T) {
repo := t.TempDir()
mainGit := filepath.Join(repo, ".git")
worktree := filepath.Join(repo, "sub", "worktree")
// Create a fake .git/worktrees dir in a separate location.
otherRepo := t.TempDir()
otherGit := filepath.Join(otherRepo, ".git")
otherWtDir := filepath.Join(otherGit, "worktrees", "evil-wt")
for _, d := range []string{mainGit, worktree, otherGit, otherWtDir} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatalf("MkdirAll(%s): %v", d, err)
}
}
// .git file points to a different repo's worktree dir.
if err := os.WriteFile(
filepath.Join(worktree, ".git"),
[]byte(fmt.Sprintf("gitdir: %s\n", otherWtDir)),
0o644,
); err != nil {
t.Fatalf("WriteFile(.git): %v", err)
}
paths := resolveWorktreeGitPaths(worktree)
if paths != nil {
t.Errorf("expected nil for cross-repo gitdir, got %v", paths)
}
}
// TestIsValidGitDir verifies the validation logic directly.
func TestIsValidGitDir(t *testing.T) {
repo := "/repo"
tests := []struct {
name string
gitDir string
wantOk bool
}{
{"legitimate path", "/repo/.git/worktrees/my-task", true},
{"nested name", "/repo/.git/worktrees/sub/name", true},
{"not under worktrees", "/repo/.git/objects", false},
{"outside repo", "/etc/.git/worktrees/x", false},
{"exactly worktrees dir", "/repo/.git/worktrees", false},
{"path traversal in name", "/repo/.git/worktrees/../evil", false},
{"dot component", "/repo/.git/worktrees/./evil", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := isValidGitDir(repo, tt.gitDir)
if got != tt.wantOk {
t.Errorf("isValidGitDir(%q) = %v, want %v", tt.gitDir, got, tt.wantOk)
}
})
}
}
// TestResolveRepoRoot verifies walking up to find the main .git directory.
func TestResolveRepoRoot(t *testing.T) {
repo := t.TempDir()
mainGit := filepath.Join(repo, ".git")
if err := os.MkdirAll(mainGit, 0o755); err != nil {
t.Fatalf("MkdirAll(.git): %v", err)
}
// Worktree deep in the repo.
worktree := filepath.Join(repo, "a", "b", "c", "worktree")
if err := os.MkdirAll(worktree, 0o755); err != nil {
t.Fatalf("MkdirAll(worktree): %v", err)
}
got := resolveRepoRoot(worktree)
if got != repo {
t.Errorf("resolveRepoRoot(%s) = %s, want %s", worktree, got, repo)
}
}
// TestResolveRepoRoot_NotFound verifies walking up with no .git dir anywhere.
func TestResolveRepoRoot_NotFound(t *testing.T) {
dir := t.TempDir()
got := resolveRepoRoot(dir)
if got != "" {
t.Errorf("expected empty string, got %s", got)
}
}
// TestResolveWorktreeGitPaths_NonWorktree verifies that a directory without
// a .git file returns no extra paths.
func TestResolveWorktreeGitPaths_NonWorktree(t *testing.T) {
dir := t.TempDir()
paths := resolveWorktreeGitPaths(dir)
if paths != nil {
t.Errorf("expected nil for non-worktree dir, got %v", paths)
}
}
// TestBinaryWriteTmp verifies that /tmp is writable under the sandbox.
func TestBinaryWriteTmp(t *testing.T) {
sandboxBin := "./shofer-sandbox"
if _, err := os.Stat(sandboxBin); os.IsNotExist(err) {
t.Skip("shofer-sandbox binary not built — run 'go build -o shofer-sandbox .' first")
}
worktree, err := os.MkdirTemp("", "shofer-sandbox-test-")
if err != nil {
t.Fatalf("MkdirTemp: %v", err)
}
defer os.RemoveAll(worktree)
cmd := exec.Command(sandboxBin, worktree, "--",
"/bin/sh", "-c", "echo tmp-write-test > /tmp/shofer-sandbox-test.txt && cat /tmp/shofer-sandbox-test.txt")
out, err := cmd.CombinedOutput()
// Clean up regardless.
os.Remove("/tmp/shofer-sandbox-test.txt")
if err != nil {
t.Fatalf("write to /tmp failed: %v\noutput: %s", err, out)
}
if !strings.Contains(string(out), "tmp-write-test") {
t.Errorf("expected 'tmp-write-test' in output, got: %s", string(out))
}
}