diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index ae72cc0..f879403 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -422,7 +422,7 @@ How MCP servers reach each agent varies by what its CLI actually supports: | Agent | Mechanism | |---|---| -| `claude` | Automatic on every `secfoo run` (`--mcp-config`, scoped to that invocation only — your global Claude config is never touched) | +| `claude` | Automatic on every `secfoo run` (`--mcp-config`, scoped to that invocation only — your global Claude config is never touched). These are the only MCP servers loaded during a scan (`--strict-mcp-config`): servers from your global Claude config or from the target's `.mcp.json` are not started | | `gemini`, `agent` (Cursor) | Run `secfoo mcp sync --agent ` once to register persistently in that tool's own config | | `codex` | Not wired up yet — Codex reads MCP servers from its own `~/.codex/config.toml` | | `agy` (Antigravity) | Not supported yet — its CLI has no MCP configuration mechanism as of this writing | diff --git a/src/secfoo/agents/base.py b/src/secfoo/agents/base.py index 811cb09..4dff466 100644 --- a/src/secfoo/agents/base.py +++ b/src/secfoo/agents/base.py @@ -122,6 +122,13 @@ def extract_usage_from_stderr(self, stderr: str) -> Usage: """ return Usage() + def describe_failure(self, stdout: str, stderr: str) -> str | None: + """Return the reason for a non-zero exit when the CLI reports it + somewhere other than stderr (e.g. Claude Code puts it in its stdout + JSON and leaves stderr empty), so the run isn't recorded as failed + with no explanation. Default: stderr already says why.""" + return None + def _collect_usage(self, stdout: str, stderr: str) -> Usage: usage = self.extract_usage(stdout) if usage == Usage(): @@ -188,6 +195,8 @@ def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> Agen if status == "success" and (reason := self.detect_failure(stdout, stderr)): status = "failed" stderr = f"secfoo: {reason}\n{stderr}" + elif status == "failed" and (reason := self.describe_failure(stdout, stderr)): + stderr = f"secfoo: {reason}\n{stderr}" usage = self.extract_usage(stdout) usage = self._collect_usage(stdout, stderr) return AgentResult( diff --git a/src/secfoo/agents/claude.py b/src/secfoo/agents/claude.py index 9a21668..c03207c 100644 --- a/src/secfoo/agents/claude.py +++ b/src/secfoo/agents/claude.py @@ -1,3 +1,29 @@ +"""Claude Code CLI adapter. + +Flags verified against a real `claude --help` and real runs (Claude Code +2.1.288, Oct 2026, Linux). Not checked on older versions, macOS or Windows; +an older CLI that lacks one of these flags fails fast with an "unknown +option" error on stderr rather than running with a weaker setup. + +`claude -p` runs one non-interactive turn; with no prompt argument it reads +the prompt from stdin. `--output-format json` prints a single result object +on stdout: `result` (the report), `usage`, `total_cost_usd`, `is_error`, +`subtype`, `permission_denials`. On an error result the CLI exits 1 with an +empty stderr, so the reason has to be read from that object. + +Read-only by tool grant, not by sandbox: only `ALLOWED_TOOLS` are +pre-approved, and in `-p` mode nothing can answer a permission prompt, so +any other tool call is denied (a `Write` attempt comes back in +`permission_denials` and no file is created). + +Deliberately NOT passed: +- `--dangerously-skip-permissions` / `--permission-mode bypassPermissions`: + a read-only review never needs them. +- `--bare`: it skips hooks too, but per `--help` it only authenticates with + `ANTHROPIC_API_KEY` or an `apiKeyHelper`, which would lock out + subscription logins. +""" + from __future__ import annotations import json @@ -12,10 +38,25 @@ ALLOWED_TOOLS = "Read,Grep,Glob,Bash(git log:*),Bash(git diff:*)" +def _result_payload(stdout: str) -> dict | None: + """The `--output-format json` result object, or None when stdout isn't + one (plain text from an older CLI, or JSON that isn't an object).""" + try: + payload = json.loads(stdout) + except json.JSONDecodeError: + return None + return payload if isinstance(payload, dict) else None + + class ClaudeAdapter(AgentAdapter): name = "claude" binary = "claude" default_timeout_seconds = 1800 + # SECFOO-42: with no prompt argument, `claude -p` reads the prompt from + # stdin. Passing it as argv breaks an npm install on Windows, where + # `claude` is a `.cmd` shim and cmd.exe cuts the argument at its first + # newline (the same failure PR #23 fixed for Codex and Copilot). + prompt_via_stdin = True def build_command(self, prompt: str, *, workdir: Path) -> list[str]: # MCP servers from ~/.secfoo/config.toml are injected here, scoped @@ -36,35 +77,73 @@ def build_command(self, prompt: str, *, workdir: Path) -> list[str]: cmd = [ self.binary, + # No prompt here: it arrives on stdin (see prompt_via_stdin). "-p", - prompt, "--output-format", "json", "--allowedTools", allowed_tools, + # SECFOO-43: `default` is no longer listed in `claude --help` + # (2.1.288 lists acceptEdits, auto, bypassPermissions, manual, + # dontAsk, plan) but is still accepted, and with it a tool + # outside the grant above is denied. Kept as is because it is + # the value every released version of this adapter has passed; + # the listed names were not tried on older CLIs. Kept explicit, + # rather than dropped, so the mode does not depend on a + # `defaultMode` in the user's own settings. "--permission-mode", "default", + # SECFOO-40: the target is untrusted, and `-p` skips Claude + # Code's workspace-trust prompt. Without these two flags the + # target's own `.claude/settings.json` is loaded: its hooks run + # as shell commands, and `enableAllProjectMcpServers` starts + # whatever its `.mcp.json` names -- both reproduced on Claude + # Code 2.1.288. `--setting-sources user` drops the project and + # local settings (the user's own still apply); + # `--strict-mcp-config` drops every MCP server except the ones + # secfoo passes via `--mcp-config` below, which also covers a + # user whose own settings auto-approve project servers. + "--setting-sources", + "user", + "--strict-mcp-config", + # SECFOO-43: don't leave a transcript in ~/.claude/projects for + # every assessment (the Codex adapter's `--ephemeral`). + "--no-session-persistence", ] if mcp_config_path: cmd += ["--mcp-config", str(mcp_config_path)] return cmd def extract_report(self, stdout: str) -> str: - try: - payload = json.loads(stdout) - except json.JSONDecodeError: - return stdout - return payload.get("result", stdout) + payload = _result_payload(stdout) + result = payload.get("result") if payload is not None else None + return result if isinstance(result, str) else stdout + + def describe_failure(self, stdout: str, stderr: str) -> str | None: + # SECFOO-41: on an error result Claude Code exits 1 with an empty + # stderr and puts the reason in the stdout JSON, e.g. + # {"is_error": true, "subtype": "error_max_budget_usd", + # "errors": ["Reached maximum budget ($0.0001)"]} + # (no "result" key; captured from Claude Code 2.1.288). Some error + # results carry their message in "result" instead, so fall back to + # that. + payload = _result_payload(stdout) + if payload is None or not payload.get("is_error"): + return None + errors = payload.get("errors") + details = [str(error) for error in errors] if isinstance(errors, list) else [] + result = payload.get("result") + if not details and isinstance(result, str) and result.strip(): + details = [result.strip()] + reason = f"Claude Code reported {payload.get('subtype') or 'an error'}" + return f"{reason}: {'; '.join(details)}" if details else reason def extract_usage(self, stdout: str) -> Usage: # `--output-format json` reports total_cost_usd plus a usage block. # On a subscription login the cost is claude's API-price estimate, # not an amount actually billed. - try: - payload = json.loads(stdout) - except json.JSONDecodeError: - return Usage() - if not isinstance(payload, dict): + payload = _result_payload(stdout) + if payload is None: return Usage() usage = payload.get("usage") or {} input_tokens = sum( diff --git a/tests/test_agents/test_base.py b/tests/test_agents/test_base.py index 4169678..979c5af 100644 --- a/tests/test_agents/test_base.py +++ b/tests/test_agents/test_base.py @@ -45,10 +45,12 @@ def test_stdin_is_devnull_so_interactive_prompts_fail_fast_not_hang(fake_popen, prompt) from stdin must hit immediate EOF rather than blocking on the caller's real terminal, which they can't see (stdout/stderr are captured into pipes) and therefore can't ever answer.""" - _no_mcp_config(monkeypatch) + # Cursor: an adapter that passes its prompt as argv. Adapters that pipe + # the prompt (claude, codex, copilot) get EOF once it has been written. + from secfoo.agents.cursor import CursorAdapter + fake = fake_popen(returncode=0, stdout="ok", stderr="") - adapter = ClaudeAdapter() - adapter.run("hi", workdir=tmp_path) + CursorAdapter().run("hi", workdir=tmp_path) assert fake.call_kwargs["stdin"] == subprocess.DEVNULL @@ -143,3 +145,36 @@ def test_run_prefers_stdout_usage_over_stderr(fake_popen, tmp_path, monkeypatch) fake_popen(returncode=0, stdout="# Report", stderr="tokens used\n15,201\n") result = CodexAdapter().run("hi", workdir=tmp_path) assert (result.input_tokens, result.output_tokens) == (7, 3) + + +def test_failed_run_is_not_given_a_reason_by_default(fake_popen, tmp_path): + from secfoo.agents.codex import CodexAdapter + + fake_popen(returncode=1, stdout="", stderr="boom") + result = CodexAdapter().run("hi", workdir=tmp_path) + assert result.status == "failed" + assert result.stderr == "boom" + + +def test_describe_failure_reason_is_prepended_to_stderr_of_a_failed_run(fake_popen, tmp_path, monkeypatch): + from secfoo.agents.codex import CodexAdapter + + monkeypatch.setattr( + CodexAdapter, "describe_failure", lambda self, stdout, stderr: f"reason from stdout: {stdout}" + ) + fake_popen(returncode=1, stdout="quota", stderr="") + result = CodexAdapter().run("hi", workdir=tmp_path) + assert result.status == "failed" + assert result.raw_report == "" + assert result.stderr == "secfoo: reason from stdout: quota\n" + + +def test_describe_failure_is_not_consulted_on_success(fake_popen, tmp_path, monkeypatch): + from secfoo.agents.codex import CodexAdapter + + def _must_not_be_called(self, stdout, stderr): + raise AssertionError("describe_failure is only for non-zero exits") + + monkeypatch.setattr(CodexAdapter, "describe_failure", _must_not_be_called) + fake_popen(returncode=0, stdout="report", stderr="") + assert CodexAdapter().run("hi", workdir=tmp_path).status == "success" diff --git a/tests/test_agents/test_claude.py b/tests/test_agents/test_claude.py index 92aaee0..5463169 100644 --- a/tests/test_agents/test_claude.py +++ b/tests/test_agents/test_claude.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import subprocess from secfoo.agents.claude import ClaudeAdapter from secfoo.settings import MCPServerConfig @@ -12,12 +13,26 @@ def test_build_command_argv(tmp_path, monkeypatch): cmd = adapter.build_command("hello", workdir=tmp_path) assert cmd[0] == "claude" assert "-p" in cmd - assert "hello" in cmd assert "--allowedTools" in cmd assert "--permission-mode" in cmd assert "default" in cmd +def test_prompt_goes_to_stdin_not_argv(fake_popen, tmp_path, monkeypatch): + """SECFOO-42: an npm-installed `claude` is a .cmd shim on Windows, and + cmd.exe truncates an argv prompt at its first newline, so the prompt is + piped to `claude -p` instead.""" + monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _empty_config()) + fake = fake_popen(returncode=0, stdout=json.dumps({"result": "ok"})) + prompt = "--looks-like-a-flag\nline two" + ClaudeAdapter().run(prompt, workdir=tmp_path) + argv = fake.call_args[0] + assert "-p" in argv + assert prompt not in argv + assert fake.call_kwargs["stdin"] == subprocess.PIPE + assert fake.stdin_input == prompt + + def test_build_command_no_mcp_config_flag_when_no_servers_configured(tmp_path, monkeypatch): monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _empty_config()) adapter = ClaudeAdapter() @@ -40,6 +55,51 @@ def test_build_command_adds_mcp_config_and_server_level_tool_grant(tmp_path, mon assert "mcp__Atlassian-Rovo-MCP" in cmd[allowed_tools_idx] +def test_build_command_ignores_the_targets_own_claude_settings(tmp_path, monkeypatch): + """SECFOO-40: the target is untrusted and `-p` skips the trust prompt, + so its `.claude/settings.json` (hooks, permissions.allow) must not be + loaded. Only the user's own settings may apply.""" + monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _empty_config()) + cmd = ClaudeAdapter().build_command("hello", workdir=tmp_path) + assert cmd[cmd.index("--setting-sources") + 1] == "user" + + +def test_build_command_only_loads_mcp_servers_secfoo_passes(tmp_path, monkeypatch): + """SECFOO-40: a `.mcp.json` in the target must never be started, with or + without secfoo-configured servers.""" + monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _empty_config()) + assert "--strict-mcp-config" in ClaudeAdapter().build_command("hello", workdir=tmp_path) + + server = MCPServerConfig(name="Atlassian-Rovo-MCP", command="npx", args=["-y", "mcp-remote@latest"]) + monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _config_with([server])) + monkeypatch.setattr("secfoo.agents.claude.write_claude_mcp_config", lambda servers: tmp_path / "mcp.json") + cmd = ClaudeAdapter().build_command("hello", workdir=tmp_path) + assert "--strict-mcp-config" in cmd + assert "--mcp-config" in cmd + + +def test_build_command_does_not_leave_a_session_file_per_scan(tmp_path, monkeypatch): + """SECFOO-43: without this every assessment writes a transcript under + ~/.claude/projects//.""" + monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _empty_config()) + assert "--no-session-persistence" in ClaudeAdapter().build_command("hello", workdir=tmp_path) + + +def test_build_command_pins_the_permission_mode(tmp_path, monkeypatch): + """SECFOO-43: passed explicitly so a `defaultMode` in the user's own + settings can't loosen a scan.""" + monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _empty_config()) + cmd = ClaudeAdapter().build_command("hello", workdir=tmp_path) + assert cmd[cmd.index("--permission-mode") + 1] == "default" + + +def test_build_command_never_bypasses_permissions(tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _empty_config()) + cmd = ClaudeAdapter().build_command("hello", workdir=tmp_path) + assert "--dangerously-skip-permissions" not in cmd + assert "bypassPermissions" not in cmd + + def _empty_config(): from secfoo.settings import Defaults, SecfooConfig @@ -103,3 +163,63 @@ def test_run_records_usage_from_json_output(tmp_path, monkeypatch, fake_popen): assert result.cost_usd == 1.5 assert result.input_tokens == 10 assert result.output_tokens == 5 + + +# Captured from a real `claude -p ... --max-budget-usd 0.0001` run (Claude +# Code 2.1.288): exit code 1, empty stderr, and no "result" key. +_ERROR_RESULT = json.dumps({ + "type": "result", + "subtype": "error_max_budget_usd", + "is_error": True, + "num_turns": 1, + "errors": ["Reached maximum budget ($0.0001)"], + "total_cost_usd": 0.000965, + "usage": {"input_tokens": 0, "output_tokens": 0}, +}) + + +def test_describe_failure_reads_subtype_and_errors_from_stdout_json(): + reason = ClaudeAdapter().describe_failure(_ERROR_RESULT, "") + assert reason == "Claude Code reported error_max_budget_usd: Reached maximum budget ($0.0001)" + + +def test_describe_failure_falls_back_to_result_text(): + stdout = json.dumps({"is_error": True, "subtype": "success", "result": "Invalid API key"}) + assert ClaudeAdapter().describe_failure(stdout, "") == "Claude Code reported success: Invalid API key" + + +def test_describe_failure_is_none_without_an_error_result(): + adapter = ClaudeAdapter() + assert adapter.describe_failure(json.dumps({"is_error": False, "result": "report"}), "") is None + assert adapter.describe_failure("not json", "") is None + assert adapter.describe_failure("[]", "") is None + + +def test_run_failed_records_the_reason_claude_put_in_stdout(fake_popen, tmp_path, monkeypatch): + """SECFOO-41: stderr is empty on a Claude error result, so without this + the run was saved as failed with no explanation.""" + monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _empty_config()) + fake_popen(returncode=1, stdout=_ERROR_RESULT, stderr="") + result = ClaudeAdapter().run("review this", workdir=tmp_path) + assert result.status == "failed" + assert result.raw_report == "" + assert result.stderr.startswith("secfoo: Claude Code reported error_max_budget_usd") + assert "Reached maximum budget" in result.stderr + # What the failed run did spend is still recorded. + assert result.cost_usd == 0.000965 + + +def test_run_failed_keeps_stderr_when_stdout_has_no_error_result(fake_popen, tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _empty_config()) + fake_popen(returncode=1, stdout="", stderr="error: unknown option '--nope'") + result = ClaudeAdapter().run("review this", workdir=tmp_path) + assert result.status == "failed" + assert result.stderr == "error: unknown option '--nope'" + + +def test_extract_report_falls_back_to_raw_stdout_when_result_is_not_text(): + adapter = ClaudeAdapter() + assert adapter.extract_report("[]") == "[]" + assert adapter.extract_report(_ERROR_RESULT) == _ERROR_RESULT + null_result = json.dumps({"result": None}) + assert adapter.extract_report(null_result) == null_result