diff --git a/src/secfoo/agents/base.py b/src/secfoo/agents/base.py index 054b718..811cb09 100644 --- a/src/secfoo/agents/base.py +++ b/src/secfoo/agents/base.py @@ -83,6 +83,13 @@ class AgentAdapter(ABC): name: ClassVar[str] binary: ClassVar[str] default_timeout_seconds: ClassVar[int] = 1800 + # Send the prompt on stdin instead of argv. npm-installed CLIs are + # `.cmd`/`.bat` shims on Windows, so argv goes through cmd.exe, which + # truncates it at the first newline and caps the whole command line at + # ~8K chars -- a multi-line skill prompt silently loses everything past + # line one. Only enable this for CLIs whose non-interactive mode + # documents reading the prompt from stdin. + prompt_via_stdin: ClassVar[bool] = False def is_available(self) -> bool: return shutil.which(self.binary) is not None @@ -99,6 +106,12 @@ def extract_usage(self, stdout: str) -> Usage: """Pull token counts / cost out of raw stdout. Default: unknown.""" return Usage() + def detect_failure(self, stdout: str, stderr: str) -> str | None: + """Return a reason when a zero-exit run still didn't do the job (e.g. + every tool call was refused, so the agent never saw the target and + its "no findings" report would read as a clean bill of health). + Default: trust the exit code.""" + return None def extract_usage_from_stderr(self, stderr: str) -> Usage: """Pull token counts / cost out of raw stderr. Default: unknown. @@ -129,6 +142,10 @@ def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> Agen ) cmd = self.build_command(prompt, workdir=workdir) + # Popen, unlike shutil.which, ignores PATHEXT on Windows, so a bare + # "copilot"/"codex" never finds the npm `.cmd` shim and raises + # FileNotFoundError. Launch exactly what is_available() found. + cmd[0] = shutil.which(cmd[0]) or cmd[0] effective_timeout = timeout or self.default_timeout_seconds started = time.monotonic() @@ -136,19 +153,42 @@ def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> Agen # can kill the whole process tree via _kill_process_tree() -- see # its docstring for why subprocess.run's own timeout handling isn't # enough on its own. - proc = subprocess.Popen( - cmd, - cwd=workdir, - stdin=subprocess.DEVNULL, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - start_new_session=True, - ) try: - stdout, stderr = proc.communicate(timeout=effective_timeout) + proc = subprocess.Popen( + cmd, + cwd=workdir, + # DEVNULL (or a pipe closed right after the prompt) means an + # interactive auth/trust prompt hits EOF instead of hanging. + stdin=subprocess.PIPE if self.prompt_via_stdin else subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + # Agent CLIs emit UTF-8; the Windows locale default (cp1252) + # would raise UnicodeDecodeError on e.g. Copilot's stats line. + encoding="utf-8", + errors="replace", + start_new_session=True, + ) + except OSError as exc: + return AgentResult( + agent=self.name, + exit_code=None, + stdout="", + stderr=f"failed to launch {cmd[0]!r}: {exc}", + duration_seconds=time.monotonic() - started, + timed_out=False, + status="failed", + raw_report="", + ) + stdin_input = prompt if self.prompt_via_stdin else None + try: + stdout, stderr = proc.communicate(input=stdin_input, timeout=effective_timeout) duration = time.monotonic() - started status: Status = "success" if proc.returncode == 0 else "failed" + if status == "success" and (reason := self.detect_failure(stdout, stderr)): + status = "failed" + stderr = f"secfoo: {reason}\n{stderr}" + usage = self.extract_usage(stdout) usage = self._collect_usage(stdout, stderr) return AgentResult( agent=self.name, diff --git a/src/secfoo/agents/codex.py b/src/secfoo/agents/codex.py index 28c6d4b..e456732 100644 --- a/src/secfoo/agents/codex.py +++ b/src/secfoo/agents/codex.py @@ -26,6 +26,7 @@ from __future__ import annotations +import os import re from pathlib import Path @@ -39,6 +40,23 @@ class CodexAdapter(AgentAdapter): name = "codex" binary = "codex" default_timeout_seconds = 1800 + # `codex exec -` reads the prompt from stdin; passing it as argv breaks + # on Windows, where `codex` is a `.cmd` shim and cmd.exe truncates the + # argument at its first newline. + prompt_via_stdin = True + + def detect_failure(self, stdout: str, stderr: str) -> str | None: + # On Windows without Codex's (admin-installed) sandbox, `--sandbox + # read-only` refuses *every* shell command, reads included, and + # `codex exec` still exits 0 with a "could not inspect" report + # (SECFOO-10 E2E, codex-cli 0.159.2). Never record that as success. + if "exec_command failed" not in stderr: + return None + hint = "" + if os.name == "nt": + hint = (" On Windows, Codex's read-only sandbox needs a one-time admin setup" + " (set windows.sandbox = \"elevated\" in ~/.codex/config.toml and approve the prompt).") + return "Codex's sandbox rejected its commands, so the target was never read." + hint def build_command(self, prompt: str, *, workdir: Path) -> list[str]: return [ @@ -58,10 +76,8 @@ def build_command(self, prompt: str, *, workdir: Path) -> list[str]: "never", "--cd", str(workdir), - # `--` so a prompt that happens to start with "-" is never - # parsed as a flag. - "--", - prompt, + # `-`: read the prompt from stdin (see prompt_via_stdin). + "-", ] def extract_usage_from_stderr(self, stderr: str) -> Usage: diff --git a/src/secfoo/agents/copilot.py b/src/secfoo/agents/copilot.py index abc2ea8..522d65c 100644 --- a/src/secfoo/agents/copilot.py +++ b/src/secfoo/agents/copilot.py @@ -23,9 +23,19 @@ adapters accept (none of claude.py/cursor.py/gemini.py/antigravity.py sandbox writes at the OS level either). -`-s`/`--silent` drops the token-usage stats banner so stdout is just the -agent's answer -- confirmed directly (no JSON envelope to unwrap, unlike -claude.py/gemini.py), so `extract_report()` is not overridden here. +`--output-format json` (JSONL events) replaces the earlier `-s` plain-text +mode. SECFOO-10 E2E (Sep 2026, CLI 1.0.89) showed the quirk below is +worse than cosmetic: the built-in scanner runs as a *subagent* +("security-review") and in text mode its output streams to stdout +concurrently with the main answer, interleaving mid-line (e.g. +"**Severity:# Secret LOW Scanning Report") and corrupting the report. +`--stream off` stops the interleaving but renders Markdown to plain text, +dropping the headings the report parsers need. In JSONL every subagent +event carries an `agentId`, so `extract_report()` takes the last +non-empty `assistant.message` without one -- the main agent's final +answer, clean and in raw Markdown. The history below is kept for context; +the `strip_preamble()` fallback it describes is still correct but no +longer needed for Copilot. CONFIRMED QUIRK (reproduced twice, Sep 2026 -- once on a casual prompt, once on a real `secfoo run --skill sast --agent copilot` end-to-end run): @@ -62,6 +72,7 @@ from __future__ import annotations +import json from pathlib import Path from secfoo.agents.base import AgentAdapter @@ -71,6 +82,27 @@ class CopilotAdapter(AgentAdapter): name = "copilot" binary = "copilot" default_timeout_seconds = 1800 + # Piped stdin instead of `-p `: on Windows `copilot` is a `.bat` + # shim, and cmd.exe cut a `-p` prompt off at its first newline + # (reproduced Sep 2026, CLI 1.0.89). With stdin piped and no `-p`, the + # CLI still runs one non-interactive turn and exits. + prompt_via_stdin = True def build_command(self, prompt: str, *, workdir: Path) -> list[str]: - return [self.binary, "-p", prompt, "-s", "--allow-all-tools"] + return [self.binary, "--output-format", "json", "--allow-all-tools"] + + def extract_report(self, stdout: str) -> str: + report = None + for line in stdout.splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(event, dict) or event.get("type") != "assistant.message" or "agentId" in event: + continue + content = (event.get("data") or {}).get("content") + if content: + report = content + # Not JSONL at all (e.g. an older CLI ignoring the flag): stdout is + # the answer itself, as in the old `-s` mode. + return report if report is not None else stdout diff --git a/tests/conftest.py b/tests/conftest.py index 99e1465..be43ac4 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -15,8 +15,11 @@ def __init__(self, *, returncode: int = 0, stdout: str = "", stderr: str = "", r self._raise_timeout = raise_timeout self._raised = False self.pid = 999999 + self.stdin_input = None - def communicate(self, timeout=None): + def communicate(self, input=None, timeout=None): + if input is not None: + self.stdin_input = input if self._raise_timeout and not self._raised: self._raised = True raise subprocess.TimeoutExpired(cmd=["fake"], timeout=timeout) diff --git a/tests/test_agents/test_base.py b/tests/test_agents/test_base.py index 91d2025..4169678 100644 --- a/tests/test_agents/test_base.py +++ b/tests/test_agents/test_base.py @@ -52,6 +52,28 @@ def test_stdin_is_devnull_so_interactive_prompts_fail_fast_not_hang(fake_popen, assert fake.call_kwargs["stdin"] == subprocess.DEVNULL +def test_launches_the_path_which_resolved(fake_popen, tmp_path, monkeypatch): + """Popen ignores PATHEXT on Windows, so the bare binary name would miss + an npm `.cmd` shim that shutil.which (and is_available) found.""" + _no_mcp_config(monkeypatch) + fake = fake_popen(returncode=0, stdout="ok", stderr="") + ClaudeAdapter().run("hi", workdir=tmp_path) + assert fake.call_args[0][0] == "/usr/bin/claude" + + +def test_launch_error_is_failed_status_not_a_crash(tmp_path, monkeypatch): + _no_mcp_config(monkeypatch) + monkeypatch.setattr("secfoo.agents.base.shutil.which", lambda name: f"/usr/bin/{name}") + + def _raise(*a, **kw): + raise FileNotFoundError(2, "The system cannot find the file specified") + + monkeypatch.setattr("secfoo.agents.base.subprocess.Popen", _raise) + result = ClaudeAdapter().run("hi", workdir=tmp_path) + assert result.status == "failed" + assert "failed to launch" in result.stderr + + def test_kill_process_tree_uses_killpg_on_posix(monkeypatch): # raising=False: os.getpgid/os.killpg/signal.SIGKILL don't exist as # attributes at all outside POSIX (that's the bug this whole file is diff --git a/tests/test_agents/test_codex.py b/tests/test_agents/test_codex.py index 1aadc39..d1f3586 100644 --- a/tests/test_agents/test_codex.py +++ b/tests/test_agents/test_codex.py @@ -1,5 +1,7 @@ from __future__ import annotations +import subprocess + from secfoo.agents import ADAPTERS, get_adapter from secfoo.agents.codex import CodexAdapter @@ -34,9 +36,36 @@ def test_build_command_sets_working_root(tmp_path): assert cmd[cmd.index("--cd") + 1] == str(tmp_path) -def test_prompt_is_last_arg_after_double_dash(tmp_path): - cmd = CodexAdapter().build_command("--looks-like-a-flag", workdir=tmp_path) - assert cmd[-2:] == ["--", "--looks-like-a-flag"] +def test_prompt_is_read_from_stdin_not_argv(fake_popen, tmp_path): + """On Windows `codex` is a .cmd shim; cmd.exe truncates an argv prompt + at its first newline, so `codex exec -` reads it from stdin instead.""" + fake = fake_popen(stdout="ok", returncode=0) + prompt = "--looks-like-a-flag\nline two" + CodexAdapter().run(prompt, workdir=tmp_path) + argv = fake.call_args[0] + assert argv[-1] == "-" + assert prompt not in argv + assert fake.call_kwargs["stdin"] == subprocess.PIPE + assert fake.stdin_input == prompt + + +def test_sandbox_rejected_commands_is_failed_not_success(fake_popen, tmp_path): + """Real stderr from a Windows E2E run (SECFOO-10): every read was + refused, yet `codex exec` exited 0 with a "could not inspect" report.""" + stderr = ( + '2026-09-30T02:21:59Z ERROR codex_core::tools::router: error=exec_command failed: CreateProcess ' + '{ message: "Rejected(\\"`powershell.exe -Command \'Get-ChildItem\'` rejected: blocked by policy\\")" }' + ) + fake_popen(returncode=0, stdout="# SAST Report\n\nI could not inspect the target.", stderr=stderr) + result = CodexAdapter().run("review", workdir=tmp_path) + assert result.status == "failed" + assert result.raw_report == "" + assert "never read" in result.stderr + + +def test_clean_run_stays_success(fake_popen, tmp_path): + fake_popen(returncode=0, stdout="# SAST Report\n\nfindings", stderr="exec\nrg --files\n") + assert CodexAdapter().run("review", workdir=tmp_path).status == "success" def test_extract_report_is_stdout_passthrough(): diff --git a/tests/test_agents/test_copilot.py b/tests/test_agents/test_copilot.py index 0656a81..1b0ebf0 100644 --- a/tests/test_agents/test_copilot.py +++ b/tests/test_agents/test_copilot.py @@ -1,12 +1,26 @@ from __future__ import annotations +import json +import subprocess + from secfoo.agents.copilot import CopilotAdapter def test_build_command(tmp_path): adapter = CopilotAdapter() cmd = adapter.build_command("hi", workdir=tmp_path) - assert cmd == ["copilot", "-p", "hi", "-s", "--allow-all-tools"] + assert cmd == ["copilot", "--output-format", "json", "--allow-all-tools"] + + +def test_prompt_goes_to_stdin_not_argv(fake_popen, tmp_path): + """On Windows `copilot` is a .bat shim; cmd.exe truncates a `-p` argv + prompt at its first newline, so the prompt must be piped instead.""" + fake = fake_popen(stdout="ok", returncode=0) + prompt = "line one\nline two" + CopilotAdapter().run(prompt, workdir=tmp_path) + assert fake.call_kwargs["stdin"] == subprocess.PIPE + assert fake.stdin_input == prompt + assert prompt not in fake.call_args[0] def test_build_command_never_grants_unrestricted_paths_or_urls(tmp_path): @@ -26,14 +40,30 @@ def test_binary_and_name(): assert CopilotAdapter.name == "copilot" -def test_extract_report_defaults_to_raw_stdout(): - """Unlike claude.py/gemini.py, `copilot -s` prints the answer directly - with no JSON envelope to unwrap -- confirmed against a real invocation. - """ +def test_extract_report_falls_back_to_raw_stdout_when_not_jsonl(): adapter = CopilotAdapter() assert adapter.extract_report("# SAST Report\n...") == "# SAST Report\n..." +def test_extract_report_takes_main_agent_answer_not_builtin_subagent(): + """Event shapes captured from a real CLI 1.0.89 run (SECFOO-10): the + built-in "security-review" subagent's messages carry an agentId and + must not leak into (or interleave with) the report.""" + events = [ + {"type": "session.tools_updated", "data": {}}, + {"type": "assistant.message", "data": {"content": ""}}, + {"type": "subagent.started", "data": {"agentName": "security-review"}, "agentId": "sub-1"}, + {"type": "assistant.message", "data": {"content": "## Security Findings\n### Alert 1", "phase": "final_answer"}, + "agentId": "sub-1"}, + {"type": "assistant.message_delta", "data": {"deltaContent": "# Secret"}}, + {"type": "assistant.message", "data": {"content": "# Secret Scanning Report\n\n## 1. Executive Summary", + "phase": "final_answer"}}, + {"type": "result", "exitCode": 0}, + ] + stdout = "\n".join(json.dumps(e) for e in events) + assert CopilotAdapter().extract_report(stdout) == "# Secret Scanning Report\n\n## 1. Executive Summary" + + def test_is_available_uses_binary_name(monkeypatch): monkeypatch.setattr("secfoo.agents.base.shutil.which", lambda name: "/usr/bin/copilot" if name == "copilot" else None) assert CopilotAdapter().is_available() is True