Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 28 additions & 19 deletions apps/stackpanel-go/internal/setupagent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func Probe(ctx context.Context, agent Agent) (Capabilities, error) {
// unsupported; help omission is not evidence of incompatibility.
case "claude":
args = []string{"--help"}
required = []string{"--print", "--output-format", "stream-json", "--permission-mode", "plan", "acceptEdits", "--strict-mcp-config", "--mcp-config", "--settings"}
required = []string{"--print", "--output-format", "stream-json", "--permission-mode", "plan", "acceptEdits", "--strict-mcp-config", "--mcp-config", "--settings", "--disallowedTools"}
case "opencode":
return Capabilities{Reason: "OpenCode is installed, but this experiment cannot enforce read-only inspection with its configurable agents; select codex or claude"}, nil
default:
Expand Down Expand Up @@ -147,12 +147,21 @@ func commandFor(agent Agent, req RunRequest) ([]string, error) {
if req.ReadOnly {
mode, allowedTools = "plan", "Read,Glob,Grep"
}
return []string{
deniedTools, err := claudeProtectedTools(req)
if err != nil {
return nil, err
}
args := []string{
"--print", "--output-format", "stream-json", "--verbose",
"--permission-mode", mode,
"--tools", allowedTools, "--strict-mcp-config", "--mcp-config", `{"mcpServers":{}}`,
"--settings", `{"disableAllHooks":true}`,
}, nil
}
if len(deniedTools) != 0 {
args = append(args, "--disallowedTools")
args = append(args, deniedTools...)
}
return args, nil
default:
return nil, fmt.Errorf("unsupported setup agent %q", agent.ID)
}
Expand Down Expand Up @@ -389,25 +398,25 @@ func (w *eventWriter) claudePermissionDenials(denials []json.RawMessage) error {
if err := json.Unmarshal(raw, &denial); err != nil || denial.ToolName == "" {
return errors.New("Claude reported a permission denial for an unrecognized tool; inspect --agent-log diagnostics")
}
path := denial.ToolInput.FilePath
if path == "" {
path = denial.ToolInput.Path
}
if path == "" && denial.ToolName == "Glob" {
path = denial.ToolInput.Pattern
}
if len(path) > 300 {
path = path[:300] + "…"
}
detail := ""
if path != "" {
detail = fmt.Sprintf(" (%q)", path)
}
switch denial.ToolName {
case "Read", "Glob", "Grep":
path := denial.ToolInput.FilePath
if path == "" {
path = denial.ToolInput.Path
}
if path == "" && denial.ToolName == "Glob" {
path = denial.ToolInput.Pattern
}
if len(path) > 300 {
path = path[:300] + "…"
}
detail := denial.ToolName
if path != "" {
detail += fmt.Sprintf(" (%q)", path)
}
warnings = append(warnings, "Claude read permission denied: "+detail+". Continuing with available context; doctor still verifies the agreed outputs.")
warnings = append(warnings, "Claude read permission denied: "+denial.ToolName+detail+". Continuing with available context; doctor still verifies the agreed outputs.")
default:
return fmt.Errorf("agent requested permissions that were denied for tool %q; the request was not executed. Review this tool's CLI permission rules and retry (--agent-log records diagnostics)", denial.ToolName)
return fmt.Errorf("agent requested permissions that were denied for tool %q%s; the request was not executed. Review this tool's CLI permission rules and retry (--agent-log records diagnostics)", denial.ToolName, detail)
}
}
if w.onEvent != nil {
Expand Down
2 changes: 1 addition & 1 deletion apps/stackpanel-go/internal/setupagent/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
const (
validPlan = `{"summary":"Add web app","expectations":{"version":1,"config":[{"path":["apps","web"],"exists":true}],"requiredChecks":[]}}`
complete = `{"status":"complete","summary":"Configured web"}`
helpText = "--print --output-format stream-json --verbose --permission-mode plan acceptEdits --permission-prompts --tools --strict-mcp-config --mcp-config --settings --json --sandbox --config --color read-only workspace-write"
helpText = "--print --output-format stream-json --verbose --permission-mode plan acceptEdits --permission-prompts --tools --strict-mcp-config --mcp-config --settings --disallowedTools --json --sandbox --config --color read-only workspace-write"
)

// TestAgentProcess is an installed CLI stand-in. It never contacts a provider.
Expand Down
48 changes: 48 additions & 0 deletions apps/stackpanel-go/internal/setupagent/claude.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package setupagent

import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)

func claudeProtectedTools(req RunRequest) ([]string, error) {
if len(req.ProtectedPaths) == 0 {
return nil, nil
}
root, err := filepath.EvalSymlinks(req.Dir)
if err != nil {
return nil, err
}
var rules []string
seen := map[string]bool{}
// Claude's matcher does not protect a literal ? when written as \? or [?].
// Leave it unescaped in deny rules: overmatching is safer than permitting
// a protected edit. Other pattern characters retain their literal meaning.
escape := strings.NewReplacer(`\`, `\\`, `*`, `\*`, `[`, `\[`, `]`, `\]`)
add := func(path string) {
// Edit rules cover both Edit and Write. Absolute patterns cannot
// become negated rules or match a different working directory.
rule := "Edit(/" + escape.Replace(filepath.ToSlash(path)) + ")"
if !seen[rule] {
rules = append(rules, rule)
seen[rule] = true
}
}
for _, path := range req.ProtectedPaths {
if !filepath.IsLocal(path) {
return nil, fmt.Errorf("protected user path must be repository-relative: %q", path)
}
absolute := filepath.Join(root, path)
add(absolute)
resolved, err := filepath.EvalSymlinks(absolute)
if err == nil {
add(resolved)
} else if !errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("resolve protected user path %q: %w", path, err)
}
}
return rules, nil
}
188 changes: 188 additions & 0 deletions apps/stackpanel-go/internal/setupagent/claude_protection_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
package setupagent

import (
"bytes"
"context"
"encoding/json"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
)

func TestProbeClaudeRequiresProtectedFileRules(t *testing.T) {
agent := fakeAgent(t, "claude")
t.Setenv("STACKPANEL_TEST_AGENT_HELP", strings.ReplaceAll(helpText, "--disallowedTools", ""))
capabilities, err := Probe(context.Background(), agent)
if err != nil || capabilities.Write || !strings.Contains(capabilities.Reason, "--disallowedTools") {
t.Fatalf("Claude without protected-file enforcement must fail capability probe: %+v, %v", capabilities, err)
}
}

func TestRunAppliesClaudeProtectedFileRules(t *testing.T) {
root, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
name := `notes [*]? \ (copy), !.nix`
for _, path := range []string{name, "target.nix"} {
if err := os.WriteFile(filepath.Join(root, path), []byte("Preserve user contents\n"), 0o600); err != nil {
t.Fatal(err)
}
}
if err := os.Symlink("target.nix", filepath.Join(root, "linked.nix")); err != nil {
t.Fatal(err)
}
record := filepath.Join(root, "invocation.json")
t.Setenv("STACKPANEL_TEST_AGENT_RECORD", record)
t.Setenv("STACKPANEL_TEST_AGENT_EVENTS", claudeEvents(complete))
_, err = Run(context.Background(), fakeAgent(t, "claude"), RunRequest{
Dir: root, ProtectedPaths: []string{name, "linked.nix", "deleted.nix"},
})
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(record)
if err != nil {
t.Fatal(err)
}
var invocation struct{ Args []string }
if err := json.Unmarshal(data, &invocation); err != nil {
t.Fatal(err)
}
var settings struct {
DisableAllHooks bool `json:"disableAllHooks"`
}
var deniedTools []string
for i, arg := range invocation.Args {
if arg == "--settings" && i+1 < len(invocation.Args) {
if err := json.Unmarshal([]byte(invocation.Args[i+1]), &settings); err != nil {
t.Fatal(err)
}
}
if arg == "--disallowedTools" {
deniedTools = invocation.Args[i+1:]
}
}
prefix := "Edit(/" + filepath.ToSlash(root) + "/"
expected := []string{
prefix + `notes \[\*\]? \\ (copy), !.nix)`,
prefix + "linked.nix)", prefix + "target.nix)", prefix + "deleted.nix)",
}
if !settings.DisableAllHooks || !reflect.DeepEqual(deniedTools, expected) {
t.Fatalf("missing protected-file rules: %+v, hooks disabled: %t", deniedTools, settings.DisableAllHooks)
}
}

func TestClaudeDeniedMutationIdentifiesFileWithoutContents(t *testing.T) {
payload, err := json.Marshal(map[string]any{
"type": "result", "subtype": "success", "result": complete,
"permission_denials": []any{map[string]any{"tool_name": "Edit", "tool_input": map[string]string{
"file_path": "/repo/.envrc", "old_string": "private-old-contents", "new_string": "private-new-contents",
}}},
})
if err != nil {
t.Fatal(err)
}
t.Setenv("STACKPANEL_TEST_AGENT_EVENTS", string(payload)+"\n")
_, err = Run(context.Background(), fakeAgent(t, "claude"), RunRequest{Dir: t.TempDir()})
if err == nil || !strings.Contains(err.Error(), "/repo/.envrc") || strings.Contains(err.Error(), "private-") {
t.Fatalf("denial must identify the file without its contents: %v", err)
}
}

// This opt-in test makes one model request against harmless temporary files.
// The provider must enforce host-protected paths even when asked to write them.
func TestInstalledClaudeProtectsUserEdits(t *testing.T) {
if os.Getenv("STACKPANEL_TEST_INSTALLED_AGENTS") != "1" {
t.Skip("set STACKPANEL_TEST_INSTALLED_AGENTS=1 for real provider smoke test")
}
binary, err := exec.LookPath("claude")
if err != nil {
t.Fatal(err)
}
root, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
for _, path := range []string{".stack", "src"} {
if err := os.MkdirAll(filepath.Join(root, path), 0o700); err != nil {
t.Fatal(err)
}
}
files := map[string]string{
".stack/config.nix": "{ enable = false; }\n",
".stack/linked.nix": "{ preserve = true; }\n",
"src/user[1]?.txt": "Preserve literal brackets and question mark\n",
}
for path, contents := range files {
if err := os.WriteFile(filepath.Join(root, path), []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
}
for path, target := range map[string]string{"alias": ".stack", "shortcut.nix": ".stack/linked.nix"} {
if err := os.Symlink(target, filepath.Join(root, path)); err != nil {
t.Fatal(err)
}
}
prompt := `This is an isolated temporary permission test with harmless fixtures.
Use the native Write tool for each of these independent operations, in order:
1. Write exactly "Allowed fixture\n" to src/user1.txt.
2. Write exactly "Changed config\n" to alias/config.nix.
3. Write exactly "Changed brackets\n" to src/user[1]?.txt.
4. Write exactly "Changed linked target\n" to .stack/linked.nix.
Attempt each operation once. If denied, do not retry that operation or use another
path or tool for it. Continue with the next independent operation.
Do not call other tools, execute commands, or read other files.
Return exactly {"status":"complete","summary":"Attempted fixture writes"}.`
var stream bytes.Buffer
_, err = Run(context.Background(), Agent{ID: "claude", Path: binary}, RunRequest{
Dir: root, Prompt: prompt, ProtectedPaths: []string{".stack/config.nix", "src/user[1]?.txt", "shortcut.nix"},
Timeout: 3 * time.Minute, Stdout: &stream,
})
if err == nil || !strings.Contains(err.Error(), "denied") {
t.Errorf("protected writes must report denied permission: %v", err)
}
for path, expected := range files {
actual, err := os.ReadFile(filepath.Join(root, path))
if err != nil || string(actual) != expected {
t.Errorf("protected user file %s changed: %v", path, err)
}
}
denied := map[string]bool{}
for _, line := range bytes.Split(bytes.TrimSpace(stream.Bytes()), []byte("\n")) {
var event struct {
PermissionDenials []struct {
ToolInput struct {
FilePath string `json:"file_path"`
} `json:"tool_input"`
} `json:"permission_denials"`
}
if err := json.Unmarshal(line, &event); err != nil {
t.Fatal("provider emitted invalid JSON events")
}
for _, denial := range event.PermissionDenials {
path := denial.ToolInput.FilePath
if !filepath.IsAbs(path) {
path = filepath.Join(root, path)
}
relative, err := filepath.Rel(root, path)
if err != nil {
t.Fatal(err)
}
denied[filepath.ToSlash(relative)] = true
}
}
for _, path := range []string{"alias/config.nix", "src/user[1]?.txt", ".stack/linked.nix"} {
if !denied[path] {
t.Errorf("provider did not attempt and deny protected write %s", path)
}
}
actual, err := os.ReadFile(filepath.Join(root, "src/user1.txt"))
if err != nil || string(actual) != "Allowed fixture\n" {
t.Fatalf("ordinary source write was blocked: %v", err)
}
}
4 changes: 4 additions & 0 deletions apps/stackpanel-go/internal/setupagent/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,10 @@ If inspection cannot establish a valid plan, report the reason instead of invent
prompt.WriteString(`
Implement the frozen plan by editing repository files. Stackpanel has already
written missing scaffold files from the supplied template, preserving existing files.
The host owns .envrc, the shell-entry scaffold. Do not create, edit, or replace it;
preserve an existing .envrc. Host verification enters Nix directly without direnv.
If setup truly requires changing .envrc, report blocked with the required change
instead of attempting it or requesting broader tool permissions.
Do not invoke stack setup, nix, direnv, or enter a development shell. Your sandbox
cannot access the Nix daemon. Stackpanel will create/update flake.lock on the host
after your edits, then reconcile and verify. Do not create or edit flake.lock yourself.
Expand Down
Loading