| 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "path/filepath" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | func TestPersistProjectWriteAccessWritesBothSections(t *testing.T) { |
| 11 | dir := t.TempDir() |
| 12 | path := filepath.Join(dir, "reasonix.toml") |
| 13 | if err := os.WriteFile(path, []byte("# keep\n[permissions]\nallow = [\"Bash(go test:*)\"]\n\n[sandbox]\nbash = \"enforce\"\n"), 0o644); err != nil { |
| 14 | t.Fatal(err) |
| 15 | } |
| 16 | extra := filepath.Join(dir, ".local") |
| 17 | if err := PersistProjectWriteAccess(path, []string{extra}, "Edit"); err != nil { |
| 18 | t.Fatal(err) |
| 19 | } |
| 20 | raw, err := os.ReadFile(path) |
| 21 | if err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | body := string(raw) |
| 25 | if !strings.Contains(body, "# keep") { |
| 26 | t.Fatal("comments must be preserved") |
| 27 | } |
| 28 | if !strings.Contains(body, "Bash(go test:*)") || !strings.Contains(body, "Edit") { |
| 29 | t.Fatalf("permission rules missing: %s", body) |
| 30 | } |
| 31 | if !strings.Contains(body, "allow_write") || !strings.Contains(body, extra) && !strings.Contains(body, ".local") { |
| 32 | t.Fatalf("allow_write missing: %s", body) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | func TestPersistProjectWriteAccessDoesNotDuplicateAncestor(t *testing.T) { |
| 37 | dir := t.TempDir() |
| 38 | path := filepath.Join(dir, "reasonix.toml") |
| 39 | parent := filepath.Join(dir, "home") |
| 40 | if err := os.MkdirAll(parent, 0o755); err != nil { |
| 41 | t.Fatal(err) |
| 42 | } |
| 43 | fixture := "[sandbox]\nallow_write = " + renderStringArray([]string{parent}) + "\n" |
| 44 | if err := os.WriteFile(path, []byte(fixture), 0o644); err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | if err := PersistProjectWriteAccess(path, []string{filepath.Join(parent, "bin")}, ""); err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | raw, err := os.ReadFile(path) |
| 51 | if err != nil { |
| 52 | t.Fatal(err) |
| 53 | } |
| 54 | if strings.Count(string(raw), "allow_write") != 1 { |
| 55 | t.Fatalf("unexpected allow_write rewrite: %s", raw) |
| 56 | } |
| 57 | if strings.Contains(string(raw), filepath.Join(parent, "bin")) { |
| 58 | t.Fatalf("child should not be persisted when ancestor exists: %s", raw) |
| 59 | } |
| 60 | } |
| 61 |