diff --git a/docs/operating.md b/docs/operating.md index d384a67..8cb44ea 100644 --- a/docs/operating.md +++ b/docs/operating.md @@ -351,6 +351,13 @@ run looks like, and where it currently stops: duplicate results, aborted runs, incomplete recovery and final backend failures remain rejected; failed-attempt text is never returned as the report. + With `--backend claude`, the fixed headless invocation disables built-in tools + before launch with `--tools ""` (a separate empty argument), keeps the one-turn + bound, strictly replaces MCP servers with an empty set, and disables hooks in + explicit neutral settings. Verified skill text and the task travel only in the + bounded stdin frame, never in argv. Stream parsing also rejects tool calls as + defense in depth; it is not the pre-launch tool control. + **Evidence record schema:** `cortex qa run --evidence ` requires a top-level JSON array containing up to 8 diff --git a/internal/cli/qa_test.go b/internal/cli/qa_test.go index 486d692..da651f9 100644 --- a/internal/cli/qa_test.go +++ b/internal/cli/qa_test.go @@ -9,6 +9,8 @@ import ( "io" "os" "path/filepath" + "runtime" + "slices" "sort" "strings" "testing" @@ -17,6 +19,7 @@ import ( "github.com/refactor-ia/cortex/internal/catalog" "github.com/refactor-ia/cortex/internal/installstate" "github.com/refactor-ia/cortex/internal/qaactor" + "github.com/refactor-ia/cortex/internal/qaadmission" "github.com/refactor-ia/cortex/internal/qapi" "github.com/refactor-ia/cortex/internal/qarole" "github.com/refactor-ia/cortex/internal/runtimematrix" @@ -26,15 +29,102 @@ import ( ) func TestMain(m *testing.M) { - if len(os.Args) > 1 && (os.Args[1] == "--version" || os.Args[1] == "--model" || os.Args[1] == "--list-models" || os.Args[1] == "auth") { + if len(os.Args) > 1 && (os.Args[1] == "--version" || os.Args[1] == "--model" || os.Args[1] == "--list-models" || os.Args[1] == "auth" || os.Args[1] == "-p") { os.Exit(fakePi()) } os.Exit(m.Run()) } +// fakeClaudeQA records the actual process boundary without any runtime or +// provider access. The existing frame recorder captures stdin separately. +func fakeClaudeQA() int { + if len(os.Args) == 2 && os.Args[1] == "--version" { + fmt.Println("2.1.316 (Claude Code)") + return 0 + } + if slices.Equal(os.Args[1:], []string{"auth", "status", "--json"}) { + fmt.Println(`{"loggedIn":true,"authMethod":"fixture"}`) + return 0 + } + qaRecordRoleEvidence() + observation, err := json.Marshal(struct{ Argv, Env []string }{os.Args[1:], os.Environ()}) + if err != nil || os.WriteFile("qa-child-observation", observation, 0600) != nil { + return 2 + } + fmt.Println(`{"type":"system","subtype":"init"}`) + fmt.Println(`{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"fixture"}]}}`) + result, _ := json.Marshal(map[string]any{"type": "result", "num_turns": 1, "is_error": false, "result": fixtureReport}) + fmt.Println(string(result)) + return 0 +} + +func TestQARunClaudeDisablesToolsBeforeLaunch(t *testing.T) { + catalogRoot := must(filepath.Abs("../../catalog")) + home := canonicalHome(t) + cwd := must(filepath.EvalSymlinks(t.TempDir())) + t.Setenv("HOME", home) + t.Setenv("PI_CODING_AGENT_DIR", "") + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("USER", "fixture-operator") + t.Setenv("PATH", "/synthetic/path") + t.Setenv("CORTEX_HOSTILE_FIXTURE", "must-not-reach-child") + t.Setenv("NODE_OPTIONS", "--hostile-fixture") + t.Chdir(cwd) + var installOut, installErr bytes.Buffer + if code := runWithInstallDependencies(context.Background(), []string{"install"}, &installOut, &installErr, readyRunner(), compatibleInstallDependencies(t, home)); code != exitOK || installErr.Len() != 0 { + t.Fatalf("fixture install = %d stdout=%q stderr=%q", code, installOut.String(), installErr.String()) + } + mustOK(os.WriteFile("qa-report-scenario", []byte("claude-report"), 0600)) + original := qaPiResolver + qaPiResolver = fixturePi{must(os.Executable())} + t.Cleanup(func() { qaPiResolver = original }) + const task = "HOSTILE-TASK --tools Bash --max-turns 99\n$(echo injected); --settings hooks" + mustOK(os.WriteFile("request.txt", []byte(task), 0600)) + args := []string{"qa", "run", "--role", "requirements-analyst", "--request", "request.txt", "--catalog", catalogRoot, "--backend", "claude"} + stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} + code := Run(context.Background(), args, stdout, stderr, nil) + if code != exitOK || stdout.String() != fixtureReport+"\n" || stderr.Len() != 0 { + t.Fatalf("Claude run = %d stdout=%q stderr=%q", code, stdout.String(), stderr.String()) + } + var child struct{ Argv, Env []string } + mustOK(json.Unmarshal(must(os.ReadFile("qa-child-observation")), &child)) + want := []string{"-p", "--output-format", "stream-json", "--verbose", "--max-turns", "1", "--tools", "", "--strict-mcp-config", "--mcp-config", `{"mcpServers":{}}`, "--settings", `{"hooks":{},"disableAllHooks":true}`} + if !slices.Equal(child.Argv, want) { + t.Errorf("child argv = %q, want %q", child.Argv, want) + } + allowed := []string{"LC_ALL", "LANG", "NO_COLOR", "TERM", "PATH", "HOME", "USER", "TMPDIR", "TMP", "TEMP"} + if runtime.GOOS == "windows" { + allowed = append(allowed, "SystemRoot", "ComSpec", "PATHEXT") + } + for _, entry := range child.Env { + name, _, _ := strings.Cut(entry, "=") + if !slices.Contains(allowed, name) || strings.Contains(entry, task) { + t.Errorf("unexpected child environment name %q", name) + } + } + for _, required := range []string{"LC_ALL=C", "LANG=C", "NO_COLOR=1", "TERM=dumb", "HOME=" + home, "USER=fixture-operator", "PATH=/synthetic/path"} { + if !slices.Contains(child.Env, required) { + t.Errorf("child environment omitted %q", required) + } + } + frame := must(os.ReadFile("qa-report-frame")) + skill := must(os.ReadFile(filepath.Join(home, ".claude", "skills", "cortex-requirements-analyst", "SKILL.md"))) + if !bytes.Contains(frame, []byte(task)) || !bytes.Contains(frame, skill) || len(frame) > qaadmission.MaxRequestBytes || !bytes.Contains(frame, []byte("skill_delivery inline\n")) { + t.Fatal("child stdin lost bounded inline skill/task framing") + } + for _, argument := range child.Argv { + if strings.Contains(argument, "HOSTILE-TASK") || strings.Contains(argument, "cortex-") { + t.Error("prompt input leaked into child argv") + } + } +} + // fakePi is a deterministic fake Pi subprocess used only as test evidence; it // never performs provider, authentication, or network work. func fakePi() int { + if scenario, _ := os.ReadFile("qa-report-scenario"); string(scenario) == "claude-report" { + return fakeClaudeQA() + } if os.Args[1] == "--version" { fmt.Println(qapi.PiSDKVersion) return 0 diff --git a/internal/qapi/claude.go b/internal/qapi/claude.go index 99d8227..b1faa31 100644 --- a/internal/qapi/claude.go +++ b/internal/qapi/claude.go @@ -116,13 +116,16 @@ func (claudeBackend) BuildInvocation(route qaroute.ResolvedRoute, binding BoundI // system/init -> assistant -> rate_limit_event -> result stream. // // --max-turns 1 is the single-turn bound, and --verbose is required for -// stream-json to emit anything but the terminal event under -p. +// stream-json to emit anything but the terminal event under -p. --tools with +// a separate empty token disables built-in tools before launch; MCP and hooks +// are neutralized separately. Stream tool-call rejection remains defense in depth. func claudeArgv() []string { return []string{ "-p", "--output-format", "stream-json", "--verbose", "--max-turns", "1", + "--tools", "", "--strict-mcp-config", "--mcp-config", claudeEmptyMCPConfig, "--settings", claudeNeutralSettings, diff --git a/internal/qapi/claude_test.go b/internal/qapi/claude_test.go index b378d81..e97dc26 100644 --- a/internal/qapi/claude_test.go +++ b/internal/qapi/claude_test.go @@ -42,6 +42,7 @@ func TestClaudeArgvContract(t *testing.T) { "--output-format", "stream-json", "--verbose", "--max-turns", "1", + "--tools", "", "--strict-mcp-config", "--mcp-config", `{"mcpServers":{}}`, "--settings", `{"hooks":{},"disableAllHooks":true}`, @@ -56,9 +57,31 @@ func TestClaudeArgvContract(t *testing.T) { // stays clear of argv size limits, and keeps role content out of the process // table. func TestClaudeInvocationCarriesNoRoleInput(t *testing.T) { - for _, argument := range claudeArgv() { - if bytes.Contains([]byte(argument), []byte("cortex-")) { - t.Fatalf("argv carries role input: %q", argument) + backend := NewClaudeBackend(nil) + const hostile = "HOSTILE-FIXTURE --tools Bash --settings '{\"hooks\":{}}'\n--max-turns 99; $(echo injected)" + for _, role := range qarole.Catalog() { + route, failure := qaroute.Resolve(qaroute.Request{Role: role.ID, Backend: "claude"}, qaroute.Snapshot{}) + if failure.Code != "" { + t.Fatal(failure.Code) + } + paths, err := BindInvocationPaths(role.ID, "/runtime/claude", "", "/assets/skill.md", "/workspace") + if err != nil { + t.Fatal(err) + } + invocation, err := backend.BuildInvocation(route, paths) + if err != nil || !slices.Equal(invocation.Argv(), claudeArgv()) { + t.Fatalf("%s invocation = %q, %v", role.ID, invocation.Argv(), err) + } + frame, err := backend.EncodeInput(route, strings.Repeat("a", 64), strings.Repeat("b", 64), []byte(hostile), []byte(hostile)) + if err != nil || bytes.Count(frame, []byte(hostile)) != 2 { + t.Fatalf("%s hostile input was not confined to the frame: %v", role.ID, err) + } + if !slices.Equal(invocation.Argv(), claudeArgv()) { + t.Fatal("framing changed argv") + } + route.Role = qarole.RoleID(hostile) + if _, err := backend.BuildInvocation(route, paths); err == nil { + t.Fatal("hostile role accepted") } } } diff --git a/internal/qapi/run_test.go b/internal/qapi/run_test.go index f15b774..24b1127 100644 --- a/internal/qapi/run_test.go +++ b/internal/qapi/run_test.go @@ -10,6 +10,7 @@ import ( "os/exec" "path/filepath" "runtime" + "slices" "strings" "testing" "time" @@ -225,6 +226,10 @@ func TestRunRejectsInvalidInputBeforeStart(t *testing.T) { {"oversized frame", testInvocation(t, "success"), bytes.Repeat([]byte("x"), qaadmission.MaxRequestBytes+1), 30 * time.Second}, {"too short timeout", testInvocation(t, "success"), []byte("frame"), 29 * time.Second}, {"too long timeout", testInvocation(t, "success"), []byte("frame"), 3601 * time.Second}, + {"Claude empty frame", Invocation{binary: "/runtime/claude", cwd: "/workspace", argv: claudeArgv()}, nil, 30 * time.Second}, + {"Claude oversized frame", Invocation{binary: "/runtime/claude", cwd: "/workspace", argv: claudeArgv()}, bytes.Repeat([]byte("x"), qaadmission.MaxRequestBytes+1), 30 * time.Second}, + {"Claude too short timeout", Invocation{binary: "/runtime/claude", cwd: "/workspace", argv: claudeArgv()}, []byte("frame"), 29 * time.Second}, + {"Claude too long timeout", Invocation{binary: "/runtime/claude", cwd: "/workspace", argv: claudeArgv()}, []byte("frame"), 3601 * time.Second}, } { t.Run(tc.name, func(t *testing.T) { facts := runOnce(context.Background(), tc.invocation, tc.frame, tc.timeout) @@ -235,6 +240,84 @@ func TestRunRejectsInvalidInputBeforeStart(t *testing.T) { } } +func TestRunPreservesNULStdin(t *testing.T) { + t.Setenv("PATH", "/synthetic/path") + invocation := testInvocation(t, "success") + canonicalCWD, err := filepath.EvalSymlinks(invocation.cwd) + if err != nil { + t.Fatal(err) + } + invocation.cwd = canonicalCWD + frame := []byte("bounded\x00stdin") + before := bytes.Clone(frame) + facts := runOnce(context.Background(), invocation, frame, 30*time.Second) + want := fmt.Sprintf("stdin=%s cwd=%s fixed=true path=true\n", sha256Text(frame), sha256Text([]byte(invocation.cwd))) + if facts.invalid || facts.launchFailed || facts.timedOut || facts.exitNonZero || facts.waitFailed || facts.stdoutTruncated || facts.stderrTruncated || string(facts.stdout) != want || len(facts.stderr) != 0 || !bytes.Equal(frame, before) { + t.Fatalf("stdin was not preserved: stdout=%q stderr=%q facts=%#v", facts.stdout, facts.stderr, facts) + } +} + +// Only the complete fixed Claude vector may carry an empty argument. Every +// near-match and every generic/Pi/OpenCode empty or NUL stays pre-launch invalid. +func TestRunRejectsEmptyAndNULArgvBeforeStart(t *testing.T) { + invocation := testInvocation(t, "success") + marker := filepath.Join(invocation.cwd, "launch-marker") + if err := os.WriteFile(marker, []byte("unchanged\n"), 0600); err != nil { + t.Fatal(err) + } + cases := [][]string{ + nil, {""}, {"--tools", ""}, {"--model", ""}, + {"run", "--format", "json", "-m", ""}, + append(claudeArgv(), "extra"), append(claudeArgv(), ""), claudeArgv()[1:], + } + for index, argument := range claudeArgv() { + if argument != "" { + argv := slices.Clone(claudeArgv()) + argv[index] = "changed" + cases = append(cases, argv) + } + for _, invalid := range []string{"", "nul\x00byte"} { + argv := slices.Clone(claudeArgv()) + if argv[index] == invalid { + continue + } + argv[index] = invalid + cases = append(cases, argv) + } + } + for _, invalid := range []string{"", "nul\x00byte"} { + argv := invocation.Argv() + cases = append(cases, append(argv, invalid)) + } + for index, argv := range cases { + t.Run(fmt.Sprint(index), func(t *testing.T) { + candidate := invocation + candidate.argv = argv + facts := runOnce(context.Background(), candidate, []byte("frame"), 30*time.Second) + if !facts.invalid || facts.launchFailed || facts.timedOut || facts.exitNonZero || facts.waitFailed || facts.stdoutTruncated || facts.stderrTruncated || len(facts.stdout) != 0 || len(facts.stderr) != 0 { + t.Fatalf("rejected argv facts = %#v", facts) + } + if got, err := os.ReadFile(marker); err != nil || string(got) != "unchanged\n" { + t.Fatalf("rejected argv changed launch counter: %q, %v", got, err) + } + }) + } + for _, path := range []string{"relative", "", "/nul\x00path"} { + for _, field := range []string{"binary", "cwd"} { + candidate := invocation + candidate.argv = claudeArgv() + if field == "binary" { + candidate.binary = path + } else { + candidate.cwd = path + } + if facts := runOnce(context.Background(), candidate, []byte("frame"), 30*time.Second); !facts.invalid || len(facts.stdout) != 0 || len(facts.stderr) != 0 { + t.Fatalf("invalid %s accepted: %#v", field, facts) + } + } + } +} + func TestRunWaitDelayReportsUndrainedDescendantPipe(t *testing.T) { started := time.Now() facts := runOnce(context.Background(), testInvocation(t, "descendant"), []byte("frame"), 30*time.Second) @@ -286,6 +369,9 @@ func TestRunHelper(t *testing.T) { } switch os.Args[index+1] { case "success": + if err := os.WriteFile("launch-marker", []byte("launched\n"), 0600); err != nil { + os.Exit(2) + } input, err := io.ReadAll(os.Stdin) if err != nil { os.Exit(2) diff --git a/internal/qapi/runner.go b/internal/qapi/runner.go index 9bcfb50..53c2afd 100644 --- a/internal/qapi/runner.go +++ b/internal/qapi/runner.go @@ -7,6 +7,7 @@ import ( "os" "os/exec" "runtime" + "slices" "strings" "time" @@ -24,7 +25,7 @@ type runFacts struct { stderrTruncated bool } -// runOnce starts exactly one already-bound Pi command. Its raw inputs and captures remain in memory. +// runOnce starts exactly one already-bound backend command. Its raw inputs and captures remain in memory. func runOnce(ctx context.Context, invocation Invocation, framedInput []byte, timeout time.Duration) runFacts { if !validInvocation(invocation) || len(framedInput) == 0 || len(framedInput) > qaadmission.MaxRequestBytes || timeout < time.Duration(qaadmission.MinimumTimeoutSeconds)*time.Second || timeout > time.Duration(qaadmission.MaximumTimeoutSeconds)*time.Second { return runFacts{invalid: true} @@ -66,8 +67,11 @@ func validInvocation(invocation Invocation) bool { if !absolutePaths(invocation.binary, invocation.cwd) || len(invocation.argv) == 0 { return false } + // Only the complete fixed Claude vector may carry its intentional empty + // --tools value. A preceding flag alone never authorizes an empty token. + fixedClaude := slices.Equal(invocation.argv, claudeArgv()) for _, argument := range invocation.argv { - if argument == "" || strings.IndexByte(argument, 0) >= 0 { + if (argument == "" && !fixedClaude) || strings.IndexByte(argument, 0) >= 0 { return false } }