返回 DeepSeek-Reasonix
session_guard_test.go
根目录 / internal / tool / builtin / session_guard_test.go
1 package builtin
2
3 import (
4 "context"
5 "encoding/json"
6 "os"
7 "path/filepath"
8 "strings"
9 "testing"
10
11 "reasonix/internal/sandbox"
12 )
13
14 // stateRootFor builds a fake Reasonix state root with the two guarded session
15 // trees populated, returning the root and one file path in each tree.
16 func stateRootFor(t *testing.T) (root, cliSession, projectSession string) {
17 t.Helper()
18 root = t.TempDir()
19 cliSession = filepath.Join(root, "sessions", "20260707-abc.jsonl")
20 projectSession = filepath.Join(root, "projects", "-Users-me-proj", "sessions", "20260707-def.jsonl")
21 for _, p := range []string{cliSession, projectSession} {
22 if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
23 t.Fatal(err)
24 }
25 if err := os.WriteFile(p, []byte("{}\n"), 0o644); err != nil {
26 t.Fatal(err)
27 }
28 }
29 return root, cliSession, projectSession
30 }
31
32 func TestSessionDataGuardDeniesSessionStores(t *testing.T) {
33 root, cliSession, projectSession := stateRootFor(t)
34 g := NewSessionDataGuard(root, nil)
35
36 for _, target := range []string{
37 cliSession,
38 projectSession,
39 filepath.Join(root, "sessions", "sub", "new.jsonl"), // not-yet-existing file under the store
40 filepath.Join(root, "projects", "any-slug", "sessions", "x.jsonl.meta"), // CAS ledger sidecar
41 } {
42 if err := g.Check(target); err == nil {
43 t.Errorf("Check(%q) = nil, want session-data denial", target)
44 } else if !strings.Contains(err.Error(), "Reasonix's own session/state data") {
45 t.Errorf("Check(%q) error %q does not name session/state data", target, err)
46 }
47 }
48 }
49
50 func TestSessionDataGuardDeniesRuntimeLedgers(t *testing.T) {
51 root, _, _ := stateRootFor(t)
52 g := NewSessionDataGuard(root, nil)
53
54 for _, target := range []string{
55 filepath.Join(root, "desktop-tabs.json"),
56 filepath.Join(root, "desktop-tabs.json.tmp"), // the fixed atomic-save sibling
57 filepath.Join(root, "desktop-projects.json"),
58 filepath.Join(root, "desktop-window.json"),
59 filepath.Join(root, "desktop-workspace"),
60 filepath.Join(root, "metrics-pending.json"),
61 filepath.Join(root, "crash-pending.json"),
62 } {
63 if err := g.Check(target); err == nil {
64 t.Errorf("Check(%q) = nil, want runtime-ledger denial", target)
65 }
66 }
67 // Same names below a NESTED directory are ordinary files (only
68 // state-root-direct ledgers are the app's).
69 if err := g.Check(filepath.Join(root, "backups", "desktop-tabs.json")); err != nil {
70 t.Errorf("nested copy of a ledger name should be writable: %v", err)
71 }
72 // heartbeat-tasks.json is a documented human/AI-editable contract
73 // (desktop/heartbeat.go; the heartbeat panel tip tells users agents can
74 // edit it) — the guard must never break that flow.
75 if err := g.Check(filepath.Join(root, "heartbeat-tasks.json")); err != nil {
76 t.Errorf("heartbeat-tasks.json is AI-editable by product contract, got %v", err)
77 }
78 }
79
80 func TestSessionDataGuardCaseVariantOnFoldingSystems(t *testing.T) {
81 if !foldPaths {
82 t.Skip("case-sensitive default filesystem: a case variant is a genuinely different path")
83 }
84 root, cliSession, _ := stateRootFor(t)
85 g := NewSessionDataGuard(root, nil)
86
87 upper := filepath.Join(root, "SESSIONS", filepath.Base(cliSession))
88 if err := g.Check(upper); err == nil {
89 t.Fatalf("Check(%q) = nil; case variant reaches the same store on this filesystem and must be denied", upper)
90 }
91 mixedLedger := filepath.Join(root, "Desktop-Tabs.JSON")
92 if err := g.Check(mixedLedger); err == nil {
93 t.Fatalf("Check(%q) = nil, want case-folded ledger denial", mixedLedger)
94 }
95 }
96
97 func TestConfineReadCaseVariantOnFoldingSystems(t *testing.T) {
98 if !foldPaths {
99 t.Skip("case-sensitive default filesystem: a case variant is a genuinely different path")
100 }
101 forbidDir := t.TempDir()
102 secret := filepath.Join(forbidDir, "secret.txt")
103 if err := os.WriteFile(secret, []byte("classified"), 0o644); err != nil {
104 t.Fatal(err)
105 }
106 forbidRoots := realRoots([]string{forbidDir})
107 upper := filepath.Join(filepath.Dir(forbidDir), strings.ToUpper(filepath.Base(forbidDir)), "secret.txt")
108 if !confineRead(forbidRoots, upper) {
109 t.Fatalf("confineRead missed case variant %q of a forbidden root", upper)
110 }
111 }
112
113 func TestSessionDataGuardAllowsOrdinaryStatePaths(t *testing.T) {
114 root, _, _ := stateRootFor(t)
115 g := NewSessionDataGuard(root, nil)
116
117 for _, target := range []string{
118 filepath.Join(root, "config.toml"), // config is confine()'s job, not this guard's
119 filepath.Join(root, "projects", "slug", "memory", "a.md"), // memory files are not session data
120 filepath.Join(root, "skills", "demo", "SKILL.md"),
121 filepath.Join(t.TempDir(), "unrelated.txt"),
122 } {
123 if err := g.Check(target); err != nil {
124 t.Errorf("Check(%q) = %v, want nil", target, err)
125 }
126 }
127 }
128
129 func TestSessionDataGuardZeroValueUnconfined(t *testing.T) {
130 var g SessionDataGuard
131 if err := g.Check("/anywhere/sessions/x.jsonl"); err != nil {
132 t.Errorf("zero-value guard should be unconfined, got %v", err)
133 }
134 if hint := g.CommandHint("", "rm -rf ~/.reasonix/sessions"); hint != "" {
135 t.Errorf("zero-value guard hint = %q, want empty", hint)
136 }
137 }
138
139 func TestSessionDataGuardDeniesSecurityBoundaryFiles(t *testing.T) {
140 root, _, _ := stateRootFor(t)
141 g := NewSessionDataGuard(root, nil)
142
143 // settings.json holds the global hooks (arbitrary shell commands run on
144 // every future session), so it remains a security boundary.
145 target := filepath.Join(root, "settings.json")
146 if err := g.Check(target); err == nil {
147 t.Errorf("Check(%q) = nil, want security-boundary denial", target)
148 } else if !strings.Contains(err.Error(), "security boundary") {
149 t.Errorf("Check(%q) error %q should name the security boundary", target, err)
150 }
151 if err := g.Check(filepath.Join(root, "trust.json")); err != nil {
152 t.Errorf("obsolete trust.json should not remain a security boundary: %v", err)
153 }
154 // The same names nested below the state root are ordinary files (a project
155 // checkout under a home workspace may legitimately contain them).
156 if err := g.Check(filepath.Join(root, "backups", "settings.json")); err != nil {
157 t.Errorf("nested settings.json should be writable: %v", err)
158 }
159 // An explicit allow_write entry stays the sanctioned escape hatch.
160 allowed := NewSessionDataGuard(root, []string{root})
161 if err := allowed.Check(filepath.Join(root, "settings.json")); err != nil {
162 t.Errorf("allow_write-covered settings.json should pass, got %v", err)
163 }
164 }
165
166 func TestSessionDataGuardSecurityFilesCaseVariantOnFoldingSystems(t *testing.T) {
167 if !foldPaths {
168 t.Skip("case-sensitive default filesystem: a case variant is a genuinely different path")
169 }
170 root, _, _ := stateRootFor(t)
171 g := NewSessionDataGuard(root, nil)
172 if err := g.Check(filepath.Join(root, "Settings.JSON")); err == nil {
173 t.Fatal("case variant of settings.json reaches the same bytes on this filesystem and must be denied")
174 }
175 }
176
177 func TestSessionDataGuardAllowWriteEscapeHatch(t *testing.T) {
178 root, cliSession, projectSession := stateRootFor(t)
179 g := NewSessionDataGuard(root, []string{filepath.Join(root, "sessions")})
180
181 if err := g.Check(cliSession); err != nil {
182 t.Errorf("allow_write-listed store should pass, got %v", err)
183 }
184 // The other store stays guarded.
185 if err := g.Check(projectSession); err == nil {
186 t.Error("project store should stay denied when only the CLI store is allowed")
187 }
188 }
189
190 func TestWriteToolsRejectSessionData(t *testing.T) {
191 root, cliSession, projectSession := stateRootFor(t)
192 // Workspace root covers the state root — the accidental self-write shape
193 // (e.g. a home-directory workspace).
194 guard := NewSessionDataGuard(root, nil)
195 tools := ConfineWriters([]string{root}, guard, ManagedConfigPaths{})
196
197 argsFor := func(name, target string) json.RawMessage {
198 var m map[string]any
199 switch name {
200 case "write_file":
201 m = map[string]any{"path": target, "content": "tampered"}
202 case "edit_file":
203 m = map[string]any{"path": target, "old_string": "{}", "new_string": "[]"}
204 case "multi_edit":
205 m = map[string]any{"path": target, "edits": []map[string]any{{"old_string": "{}", "new_string": "[]"}}}
206 case "move_file":
207 m = map[string]any{"source_path": target, "destination_path": target + ".bak"}
208 case "notebook_edit":
209 m = map[string]any{"path": target, "cell_index": 0, "mode": "delete"}
210 case "delete_range":
211 m = map[string]any{"path": target, "start_anchor": "{}", "end_anchor": "{}"}
212 case "delete_symbol":
213 m = map[string]any{"path": target, "name": "x"}
214 default:
215 t.Fatalf("unhandled tool %s", name)
216 }
217 b, err := json.Marshal(m)
218 if err != nil {
219 t.Fatal(err)
220 }
221 return b
222 }
223
224 for _, tl := range tools {
225 for _, target := range []string{cliSession, projectSession} {
226 _, err := tl.Execute(context.Background(), argsFor(tl.Name(), target))
227 if err == nil || !strings.Contains(err.Error(), "session/state data") {
228 t.Errorf("%s on %q: err = %v, want session-data denial", tl.Name(), target, err)
229 }
230 }
231 // The same tool still writes ordinary workspace files (guard is not a
232 // blanket block on the state root).
233 if tl.Name() == "write_file" {
234 ok := filepath.Join(root, "notes.txt")
235 if _, err := tl.Execute(context.Background(), argsFor("write_file", ok)); err != nil {
236 t.Errorf("write_file on ordinary path: %v", err)
237 }
238 }
239 }
240 }
241
242 func TestSessionDataGuardCommandHint(t *testing.T) {
243 root, cliSession, _ := stateRootFor(t)
244 g := NewSessionDataGuard(root, nil)
245
246 hinted := []string{
247 "python3 fix.py " + cliSession,
248 "rm -rf " + filepath.ToSlash(filepath.Join(root, "projects", "slug", "sessions")),
249 "Get-Content " + strings.ToUpper(filepath.ToSlash(filepath.Join(root, "sessions"))) + "/x.jsonl", // case-insensitive
250 }
251 for _, cmd := range hinted {
252 if hint := g.CommandHint("", cmd); hint == "" {
253 t.Errorf("CommandHint(%q) = empty, want warning", cmd)
254 } else if !strings.Contains(hint, "conflict cop") {
255 t.Errorf("CommandHint(%q) = %q, want conflict-copy explanation", cmd, hint)
256 }
257 }
258 for _, cmd := range []string{
259 "go test ./...",
260 "ls " + filepath.Join(t.TempDir(), "sessions"), // "sessions" under an unrelated root
261 "",
262 } {
263 if hint := g.CommandHint("", cmd); hint != "" {
264 t.Errorf("CommandHint(%q) = %q, want empty", cmd, hint)
265 }
266 }
267 }
268
269 func TestSessionDataGuardCommandHintEnvVarForm(t *testing.T) {
270 home := t.TempDir()
271 t.Setenv("HOME", home)
272 t.Setenv("USERPROFILE", home)
273 state := filepath.Join(home, ".reasonix")
274 if err := os.MkdirAll(filepath.Join(state, "sessions"), 0o755); err != nil {
275 t.Fatal(err)
276 }
277 g := NewSessionDataGuard(state, nil)
278
279 for _, cmd := range []string{
280 `python3 -c "open('$HOME/.reasonix/sessions/x.jsonl','w')"`,
281 "rm ${HOME}/.reasonix/projects/slug/sessions/y.jsonl",
282 } {
283 if hint := g.CommandHint("", cmd); hint == "" {
284 t.Errorf("CommandHint(%q) = empty, want warning for env-var path form", cmd)
285 }
286 }
287 }
288
289 func TestSessionDataGuardCommandHintRelativeFromStateRoot(t *testing.T) {
290 root, _, _ := stateRootFor(t)
291 g := NewSessionDataGuard(root, nil)
292 // The desktop Global workspace lives at <state root>/global-workspace, so a
293 // relative ../sessions reaches the store without an absolute path in the
294 // command text.
295 workDir := filepath.Join(root, "global-workspace")
296 if err := os.MkdirAll(workDir, 0o755); err != nil {
297 t.Fatal(err)
298 }
299
300 if hint := g.CommandHint(workDir, "python3 fix.py ../sessions/x.jsonl"); hint == "" {
301 t.Error("relative reference from a state-root workDir should warn")
302 }
303 if hint := g.CommandHint(workDir, "go build ./..."); hint != "" {
304 t.Errorf("ordinary command in the Global workspace should stay clean, got %q", hint)
305 }
306 // A workDir already inside a guarded store warns on every command: any
307 // relative operation there touches the store.
308 inStore := filepath.Join(root, "projects", "slug", "sessions")
309 if hint := g.CommandHint(inStore, "python3 fix.py x.jsonl"); hint == "" {
310 t.Error("workDir inside a session store should warn unconditionally")
311 }
312 // An unrelated workDir does not fabricate warnings.
313 if hint := g.CommandHint(t.TempDir(), "cat ../sessions/x.jsonl"); hint != "" {
314 t.Errorf("relative form outside the state root should stay clean, got %q", hint)
315 }
316 }
317
318 func TestBashAppendsSessionDataHint(t *testing.T) {
319 root, cliSession, _ := stateRootFor(t)
320 guard := NewSessionDataGuard(root, nil)
321 b := ConfineBash(sandbox.Spec{Mode: "off"}, guard)
322
323 args, _ := json.Marshal(map[string]string{"command": "echo " + cliSession})
324 out, err := b.Execute(context.Background(), args)
325 if err != nil {
326 t.Fatalf("bash: %v", err)
327 }
328 if !strings.Contains(out, "WARNING: this command referenced Reasonix's own session/state data") {
329 t.Fatalf("bash output missing session-data warning:\n%s", out)
330 }
331 // An ordinary command stays clean.
332 args, _ = json.Marshal(map[string]string{"command": "echo hello"})
333 out, err = b.Execute(context.Background(), args)
334 if err != nil {
335 t.Fatalf("bash: %v", err)
336 }
337 if strings.Contains(out, "WARNING") {
338 t.Fatalf("bash output has spurious warning:\n%s", out)
339 }
340 }
341
341 lines GO