返回 DeepSeek-Reasonix
permission_test.go
根目录 / internal / permission / permission_test.go
1 package permission
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "strings"
8 "testing"
9 )
10
11 func TestPwshUsesLegacyBashPermissionRules(t *testing.T) {
12 if !ruleToolMatches("Bash", "pwsh") || !ruleToolMatches("PowerShell", "bash") {
13 t.Fatal("shell aliases should share one permission capability")
14 }
15 p := New("ask", []string{"Bash(Get-ChildItem:*)"}, nil, nil)
16 if got := p.DecideSubject("pwsh", false, "Get-ChildItem -Force"); got != Allow {
17 t.Fatalf("legacy Bash allow rule for pwsh = %v", got)
18 }
19 }
20
21 func TestParseRule(t *testing.T) {
22 cases := []struct {
23 in string
24 wantTool string
25 wantSubj string
26 wantLit bool
27 wantOK bool
28 }{
29 {"bash", "bash", "", false, true},
30 {"Bash(npm run build)", "Bash", "npm run build", false, true},
31 {"Edit(docs/**)", "Edit", "docs/**", false, true},
32 {"bash(rm -rf*)", "bash", "rm -rf*", false, true},
33 {" read_file ", "read_file", "", false, true},
34 {"bash( go test ./... )", "bash", " go test ./... ", false, true}, // subject preserved verbatim
35 {"bash(echo (hi))", "bash", "echo (hi)", false, true}, // first '(' wins, trailing ')'
36 {"bash=rm *.log", "bash", "rm *.log", true, true}, // literal: '*' is not a wildcard
37 {"bash=make FOO=bar", "bash", "make FOO=bar", true, true}, // split on first '=' only
38 {"bash=echo (hi)", "bash", "echo (hi)", true, true}, // '=' before '(' → literal, parens kept
39 {"bash(make FOO=*)", "bash", "make FOO=*", false, true}, // '(' before '=' → still a glob
40 {"get-user", "get-user", "", false, true},
41 {"Set-Content", "Set-Content", "", false, true},
42 {"set-content", "set-content", "", false, true},
43 {"git", "git", "", false, true},
44 {"Get-CustomThing", "Get-CustomThing", "", false, true},
45 {"", "", "", false, false},
46 {"(noTool)", "", "", false, false},
47 }
48 for _, c := range cases {
49 r, ok := ParseRule(c.in)
50 if ok != c.wantOK {
51 t.Errorf("ParseRule(%q) ok = %v, want %v", c.in, ok, c.wantOK)
52 continue
53 }
54 if ok && (r.Tool != c.wantTool || r.Subject != c.wantSubj || r.Literal != c.wantLit) {
55 t.Errorf("ParseRule(%q) = {%q,%q,lit=%v}, want {%q,%q,lit=%v}", c.in, r.Tool, r.Subject, r.Literal, c.wantTool, c.wantSubj, c.wantLit)
56 }
57 }
58 }
59
60 func TestPowerShellLikeBareToolNamesKeepGenericRuleSemantics(t *testing.T) {
61 p := New("ask",
62 []string{"get-user"},
63 []string{"write-report"},
64 []string{"set-profile"},
65 )
66 if got := p.DecideSubject("get-user", false, ""); got != Allow {
67 t.Fatalf("bare allow tool rule = %v, want Allow", got)
68 }
69 if got := p.DecideSubject("write-report", true, ""); got != Ask {
70 t.Fatalf("bare ask tool rule = %v, want Ask", got)
71 }
72 if got := p.DecideSubject("set-profile", true, ""); got != Deny {
73 t.Fatalf("bare deny tool rule = %v, want Deny", got)
74 }
75 if got := p.DecideSubject("bash", false, "get-user --all"); got != Ask {
76 t.Fatalf("hyphenated command inherited a bare tool allow = %v, want Ask", got)
77 }
78 cmdletAllow := New("ask", []string{"Set-Content"}, nil, nil)
79 if got := cmdletAllow.DecideSubject("Set-Content", false, ""); got != Allow {
80 t.Fatalf("bare cmdlet allow tool rule = %v, want Allow", got)
81 }
82 if got := cmdletAllow.DecideSubject("bash", false, "Set-Content app.go"); got != Ask {
83 t.Fatalf("bare cmdlet allow leaked into Bash = %v, want Ask", got)
84 }
85 legacy := New("allow", nil, nil, []string{"Set-Content"})
86 if got := legacy.DecideSubject("Set-Content", true, ""); got != Deny {
87 t.Fatalf("legacy cmdlet exact tool deny = %v, want Deny", got)
88 }
89 if got := legacy.DecideSubject("bash", false, "set-content app.go"); got != Deny {
90 t.Fatalf("legacy cmdlet Bash deny = %v, want Deny", got)
91 }
92 }
93
94 func TestMatchGlob(t *testing.T) {
95 cases := []struct {
96 pattern, name string
97 want bool
98 }{
99 {"rm -rf*", "rm -rf /tmp/x", true}, // '*' crosses '/'
100 {"go test*", "go test ./...", true},
101 {"rm *", "rm *.log", true},
102 {"go test*", "go build", false},
103 {"*", "anything at all", true},
104 {"git ?ush", "git push", true},
105 {"git ?ush", "git rush", true},
106 {"git ?ush", "git pull", false},
107 {"exact", "exact", true},
108 {"exact", "exactly", false},
109 {"a*c", "abbbc", true},
110 {"a*c", "abbbd", false},
111 {"*.go", "main.go", true},
112 {"*.go", "main.rs", false},
113 }
114 for _, c := range cases {
115 if got := matchGlob(c.pattern, c.name); got != c.want {
116 t.Errorf("matchGlob(%q, %q) = %v, want %v", c.pattern, c.name, got, c.want)
117 }
118 }
119 }
120
121 func TestSubject(t *testing.T) {
122 cases := []struct {
123 args string
124 want string
125 }{
126 {`{"command":"go test ./..."}`, "go test ./..."},
127 {`{"file_path":"/a/b.go"}`, "/a/b.go"},
128 {`{"path":"/c/d"}`, "/c/d"},
129 {`{"pattern":"TODO","path":"/x"}`, "/x"}, // file_path/path beats pattern by key order
130 {`{"other":"x"}`, ""},
131 {`{}`, ""},
132 {``, ""},
133 {`not json`, ""},
134 }
135 for _, c := range cases {
136 if got := Subject(json.RawMessage(c.args)); got != c.want {
137 t.Errorf("Subject(%q) = %q, want %q", c.args, got, c.want)
138 }
139 }
140 }
141
142 func TestSubjectsForMoveFile(t *testing.T) {
143 got := Subjects(json.RawMessage(`{"source_path":"tmp/a.md","destination_path":"secrets/a.md"}`))
144 want := []string{"tmp/a.md", "secrets/a.md"}
145 if len(got) != len(want) {
146 t.Fatalf("Subjects length = %d (%v), want %d", len(got), got, len(want))
147 }
148 for i := range want {
149 if got[i] != want[i] {
150 t.Fatalf("Subjects[%d] = %q, want %q (all subjects: %v)", i, got[i], want[i], got)
151 }
152 }
153 if primary := Subject(json.RawMessage(`{"source_path":"tmp/a.md","destination_path":"secrets/a.md"}`)); primary != "tmp/a.md" {
154 t.Fatalf("Subject primary = %q, want source path", primary)
155 }
156 }
157
158 func TestPolicyDecide(t *testing.T) {
159 p := New("ask",
160 []string{"bash(go test*)", "ls"},
161 []string{"read_file"}, // force a prompt even though readers default allow
162 []string{"bash(rm -rf*)"},
163 )
164
165 cases := []struct {
166 name string
167 tool string
168 readOnly bool
169 args string
170 want Decision
171 }{
172 {"deny wins over fallback", "bash", false, `{"command":"rm -rf /"}`, Deny},
173 {"allow-listed command", "bash", false, `{"command":"go test ./..."}`, Allow},
174 {"writer fallback to mode(ask)", "bash", false, `{"command":"git commit"}`, Ask},
175 {"reader defaults allow", "grep", true, `{"pattern":"x"}`, Allow},
176 {"ask rule overrides reader-allow", "read_file", true, `{"path":"/a"}`, Ask},
177 {"bare allow rule", "ls", true, `{"path":"/a"}`, Allow},
178 {"subject rule needs subject", "bash", false, `{}`, Ask}, // no command → go test* can't match → fallback
179 }
180 for _, c := range cases {
181 got := p.Decide(c.tool, c.readOnly, json.RawMessage(c.args))
182 if got != c.want {
183 t.Errorf("%s: Decide(%q, ro=%v, %s) = %v, want %v", c.name, c.tool, c.readOnly, c.args, got, c.want)
184 }
185 }
186 }
187
188 func TestPolicyDecideMoveFileChecksBothEndpoints(t *testing.T) {
189 denyDest := New("allow", nil, nil, []string{"Edit(secrets/**)"})
190 if got := denyDest.Decide("move_file", false, json.RawMessage(`{"source_path":"tmp/a.md","destination_path":"secrets/a.md"}`)); got != Deny {
191 t.Fatalf("destination deny rule = %v, want Deny", got)
192 }
193
194 askDest := New("allow", nil, []string{"Edit(secrets/**)"}, nil)
195 if got := askDest.Decide("move_file", false, json.RawMessage(`{"source_path":"tmp/a.md","destination_path":"secrets/a.md"}`)); got != Ask {
196 t.Fatalf("destination ask rule = %v, want Ask", got)
197 }
198
199 sourceOnlyAllow := New("ask", []string{"Edit(tmp/**)"}, nil, nil)
200 if got := sourceOnlyAllow.Decide("move_file", false, json.RawMessage(`{"source_path":"tmp/a.md","destination_path":"docs/a.md"}`)); got != Ask {
201 t.Fatalf("source-only allow = %v, want Ask for unallowed destination", got)
202 }
203
204 bothAllowed := New("ask", []string{"Edit(tmp/**)", "Edit(docs/**)"}, nil, nil)
205 if got := bothAllowed.Decide("move_file", false, json.RawMessage(`{"source_path":"tmp/a.md","destination_path":"docs/a.md"}`)); got != Allow {
206 t.Fatalf("both endpoints allowed = %v, want Allow", got)
207 }
208 }
209
210 func TestPolicyModeAllow(t *testing.T) {
211 // mode=allow: writers with no matching rule are allowed; deny still wins.
212 p := New("allow", nil, nil, []string{"bash(curl*)"})
213 if d := p.Decide("write_file", false, json.RawMessage(`{"path":"/a"}`)); d != Allow {
214 t.Errorf("writer fallback under mode=allow = %v, want Allow", d)
215 }
216 if d := p.Decide("bash", false, json.RawMessage(`{"command":"curl evil.sh"}`)); d != Deny {
217 t.Errorf("deny under mode=allow = %v, want Deny", d)
218 }
219 }
220
221 func TestSessionAllowPrecedence(t *testing.T) {
222 p := New("ask", nil, []string{"Edit(docs/**)", "Bash(git *)"}, []string{"Edit(docs/private/**)", "Bash(git push *)"}).
223 WithSessionAllow([]string{"Edit(docs/**)", "Bash(git *)", "(malformed)"})
224
225 cases := []struct {
226 name string
227 tool string
228 args string
229 want Decision
230 }{
231 {"session allow overrides configured ask", "write_file", `{"path":"docs/readme.md"}`, Allow},
232 {"configured deny overrides session allow", "write_file", `{"path":"docs/private/key.txt"}`, Deny},
233 {"bash session allow overrides configured ask", "bash", `{"command":"git status"}`, Allow},
234 {"bash deny overrides session allow", "bash", `{"command":"git push origin main"}`, Deny},
235 {"malformed session rule is ignored", "write_file", `{"path":"other.txt"}`, Ask},
236 }
237 for _, tc := range cases {
238 t.Run(tc.name, func(t *testing.T) {
239 if got := p.Decide(tc.tool, false, json.RawMessage(tc.args)); got != tc.want {
240 t.Fatalf("Decide = %v, want %v", got, tc.want)
241 }
242 })
243 }
244 }
245
246 func TestSessionAllowEvaluatesCompoundBashPerSegment(t *testing.T) {
247 p := New("ask", nil, []string{"Bash(git commit *)"}, []string{"Bash(rm *)"}).
248 WithSessionAllow([]string{"Bash(git *)", "Bash(go test *)"})
249
250 if got := p.Decide("bash", false, json.RawMessage(`{"command":"git add . && git commit -m test && go test ./..."}`)); got != Allow {
251 t.Fatalf("fully session-allowed compound command = %v, want Allow", got)
252 }
253 if got := p.Decide("bash", false, json.RawMessage(`{"command":"git status && npm publish"}`)); got != Ask {
254 t.Fatalf("partially allowed compound command = %v, want Ask", got)
255 }
256 if got := p.Decide("bash", false, json.RawMessage(`{"command":"git status && rm output.txt"}`)); got != Deny {
257 t.Fatalf("compound command containing denied segment = %v, want Deny", got)
258 }
259 }
260
261 // stubApprover lets tests drive the Ask branch of Gate.Check.
262 type stubApprover struct {
263 allow bool
264 remember bool
265 err error
266 calls int
267 }
268
269 func (s *stubApprover) Approve(ctx context.Context, tool, subject string, args json.RawMessage) (bool, bool, error) {
270 s.calls++
271 return s.allow, s.remember, s.err
272 }
273
274 type policyReasonApprover struct {
275 reason string
276 }
277
278 func (a *policyReasonApprover) Approve(context.Context, string, string, json.RawMessage) (bool, bool, error) {
279 return true, false, nil
280 }
281
282 func (a *policyReasonApprover) ApproveWithPolicyReason(_ context.Context, _, _ string, _ json.RawMessage, reason string) (bool, bool, string, error) {
283 a.reason = reason
284 return true, false, "", nil
285 }
286
287 func TestGateReportsMatchedPermissionRule(t *testing.T) {
288 args := json.RawMessage(`{"command":"git status && git push origin main"}`)
289 approver := &policyReasonApprover{}
290 askGate := NewGate(New("allow", nil, []string{"Bash(git push:*)"}, nil), approver)
291 if allow, _, err := askGate.Check(context.Background(), "bash", args, false); err != nil || !allow {
292 t.Fatalf("ask-gated call = allow %v, err %v", allow, err)
293 }
294 if got, want := approver.reason, "Matched permission rule: ask Bash(git push:*)"; got != want {
295 t.Fatalf("approval reason = %q, want %q", got, want)
296 }
297
298 denyGate := NewGate(New("allow", nil, nil, []string{"Bash(git push:*)"}), nil)
299 allow, reason, err := denyGate.Check(context.Background(), "bash", args, false)
300 if err != nil || allow {
301 t.Fatalf("deny-gated call = allow %v, err %v", allow, err)
302 }
303 if !strings.Contains(reason, "Matched permission rule: deny Bash(git push:*)") {
304 t.Fatalf("deny reason = %q, want matched rule", reason)
305 }
306 }
307
308 func TestMatchedRuleDoesNotReportAskRuleOverriddenForOneEndpoint(t *testing.T) {
309 p := New("ask", nil, []string{"Edit(src/**)"}, nil).
310 WithSessionAllow([]string{"Edit(src/**)"})
311 args := json.RawMessage(`{"source_path":"src/old.go","destination_path":"generated/new.go"}`)
312 if got := p.Decide("move_file", false, args); got != Ask {
313 t.Fatalf("move decision = %v, want Ask from uncovered destination fallback", got)
314 }
315 if rule, ok := p.MatchedRule("move_file", Ask, args); ok {
316 t.Fatalf("MatchedRule = %q, want no rule provenance for fallback Ask", rule)
317 }
318 }
319
320 func TestGateHeadlessAllowsAsk(t *testing.T) {
321 // No approver → Ask resolves to allow (autonomy preserved), deny still blocks.
322 g := NewGate(New("ask", nil, nil, []string{"bash(rm*)"}), nil)
323
324 allow, _, err := g.Check(context.Background(), "bash", json.RawMessage(`{"command":"git commit"}`), false)
325 if err != nil || !allow {
326 t.Errorf("headless ask = (%v,%v), want allow", allow, err)
327 }
328 allow, reason, err := g.Check(context.Background(), "bash", json.RawMessage(`{"command":"rm file"}`), false)
329 if err != nil || allow || reason == "" {
330 t.Errorf("headless deny = (%v,%q,%v), want blocked with reason", allow, reason, err)
331 }
332 }
333
334 func TestGateInteractive(t *testing.T) {
335 var remembered string
336 ap := &stubApprover{allow: true, remember: true}
337 g := NewGate(New("ask", nil, nil, nil), ap)
338 g.OnRemember = func(rule string) { remembered = rule }
339
340 allow, _, err := g.Check(context.Background(), "bash", json.RawMessage(`{"command":"go build"}`), false)
341 if err != nil || !allow {
342 t.Fatalf("approved call = (%v,%v), want allow", allow, err)
343 }
344 if ap.calls != 1 {
345 t.Errorf("approver calls = %d, want 1", ap.calls)
346 }
347 // "Always allow" is tool-wide: the persisted rule is the bare tool name, not
348 // pinned to "go build", so any later command runs without re-prompting.
349 if remembered != "bash" {
350 t.Errorf("remembered rule = %q, want tool-wide %q", remembered, "bash")
351 }
352
353 // Decline path.
354 ap2 := &stubApprover{allow: false}
355 g2 := NewGate(New("ask", nil, nil, nil), ap2)
356 allow, reason, _ := g2.Check(context.Background(), "write_file", json.RawMessage(`{"path":"/a"}`), false)
357 if allow || reason == "" {
358 t.Errorf("declined call = (%v,%q), want blocked with reason", allow, reason)
359 }
360
361 // Error path aborts the turn.
362 ap3 := &stubApprover{err: errors.New("ctx cancelled")}
363 g3 := NewGate(New("ask", nil, nil, nil), ap3)
364 if _, _, err := g3.Check(context.Background(), "bash", json.RawMessage(`{"command":"x"}`), false); err == nil {
365 t.Error("approver error should propagate")
366 }
367
368 // Allowed-by-policy never reaches the approver.
369 ap4 := &stubApprover{allow: false}
370 g4 := NewGate(New("ask", []string{"bash(ok*)"}, nil, nil), ap4)
371 allow, _, _ = g4.Check(context.Background(), "bash", json.RawMessage(`{"command":"ok go"}`), false)
372 if !allow || ap4.calls != 0 {
373 t.Errorf("allow-listed call reached approver: allow=%v calls=%d", allow, ap4.calls)
374 }
375 }
376
377 func TestClaudeStyleRuleMatchesExactCommandWithoutWildcard(t *testing.T) {
378 p := New("ask", []string{"Bash(go build)"}, nil, nil)
379
380 if got := p.Decide("bash", false, json.RawMessage(`{"command":"go build"}`)); got != Allow {
381 t.Errorf("exact command = %v, want Allow", got)
382 }
383 if got := p.Decide("bash", false, json.RawMessage(`{"command":"go build ./cmd"}`)); got == Allow {
384 t.Errorf("exact command rule matched longer command")
385 }
386 }
387
388 // TestLegacyLiteralRuleMatchesExactly guards configs written before the
389 // Claude-style Bash(...) rules: a literal "bash=rm *.log" must allow only that
390 // exact command, never the wildcard expansion a glob "bash(rm *.log)" would
391 // have matched.
392 func TestLegacyLiteralRuleMatchesExactly(t *testing.T) {
393 p := New("ask", []string{"bash=rm *.log"}, nil, nil)
394
395 if got := p.Decide("bash", false, json.RawMessage(`{"command":"rm *.log"}`)); got != Allow {
396 t.Errorf("exact command = %v, want Allow", got)
397 }
398 if got := p.Decide("bash", false, json.RawMessage(`{"command":"rm secrets.log"}`)); got == Allow {
399 t.Errorf("literal rule wildcard-matched %q — '*' must stay literal", "rm secrets.log")
400 }
401 }
402
402 lines GO