| 1 | //go:build windows |
| 2 | |
| 3 | package agent |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "testing" |
| 10 | ) |
| 11 | |
| 12 | // TestRemoveAndUnlockDeletesViaDispositionNotFallback pins the Windows delete |
| 13 | // path: the lock handle must carry DELETE access so the disposition call |
| 14 | // succeeds and the TOCTOU-free branch is the one actually taken. A fallback |
| 15 | // means the handle was opened without DELETE and the cleanup-vs-saver window |
| 16 | // is silently back. |
| 17 | func TestRemoveAndUnlockDeletesViaDispositionNotFallback(t *testing.T) { |
| 18 | dir := t.TempDir() |
| 19 | lockPath := filepath.Join(dir, "session.jsonl.lock") |
| 20 | before := sessionLockDispositionFallbacks.Load() |
| 21 | lock, err := tryTakeSessionLockFile(lockPath) |
| 22 | if err != nil { |
| 23 | t.Fatalf("tryTakeSessionLockFile: %v", err) |
| 24 | } |
| 25 | if err := lock.RemoveAndUnlock(); err != nil { |
| 26 | t.Fatalf("RemoveAndUnlock: %v", err) |
| 27 | } |
| 28 | if got := sessionLockDispositionFallbacks.Load(); got != before { |
| 29 | t.Fatalf("delete disposition fell back to path removal (%d -> %d); lock handle lacks DELETE access", before, got) |
| 30 | } |
| 31 | if _, err := os.Stat(lockPath); !os.IsNotExist(err) { |
| 32 | t.Fatalf("lock file still present after RemoveAndUnlock (err=%v)", err) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | // TestTryTakeSessionLockFileTreatsOpenHandleAsHeld pins the sharing-violation |
| 37 | // mapping: a plain Go open (no DELETE sharing) must read as "held", not as an |
| 38 | // error, because reconcile treats held lock files as live and skips them. |
| 39 | func TestTryTakeSessionLockFileTreatsOpenHandleAsHeld(t *testing.T) { |
| 40 | dir := t.TempDir() |
| 41 | lockPath := filepath.Join(dir, "session.jsonl.lock") |
| 42 | f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600) |
| 43 | if err != nil { |
| 44 | t.Fatal(err) |
| 45 | } |
| 46 | defer f.Close() |
| 47 | if _, err := tryTakeSessionLockFile(lockPath); !errors.Is(err, ErrSessionFileLockHeld) { |
| 48 | t.Fatalf("tryTakeSessionLockFile with plain open handle = %v, want ErrSessionFileLockHeld", err) |
| 49 | } |
| 50 | } |
| 51 |