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
76 changes: 76 additions & 0 deletions src/secfoo/agents/copilot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""GitHub Copilot CLI adapter.

Binary is `copilot` (npm package `@github/copilot`, GA since Feb 2026) --
not the older `gh copilot` GitHub CLI extension, which is now just a thin
wrapper that shells out to this same binary. Flags verified against a real
`copilot --help` (Sep 2026, CLI version 1.0.86); the CLI ships updates
often and flags have already drifted once (the pre-GA `gh copilot`
extension used different flags entirely), so re-verify before trusting an
older doc.

`--allow-all-tools` is not a convenience flag here -- `copilot --help`
states it directly: "required for non-interactive mode." Without it, `-p`
just hangs waiting for a permission prompt that can never be answered
non-interactively.

Deliberately does NOT pass `--allow-all-paths` or `--allow-all-urls` (both
folded into the broader `--allow-all`/`--yolo` flags) -- a read-only
security review only needs to read files already inside the target
workdir and never needs unrestricted filesystem or network access.
`--allow-all-tools` alone still lets the model use tools like `write`
without a prompt, but secfoo's prompts are read-only reviews by
instruction, not by sandboxing, matching the same trust level the other
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.

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):
this CLI unpromptedly auto-invokes its own built-in security-scanning
tool first, emitting a "## Security Findings" / "### Alert N" block (plus
its own Remediation Roadmap) *before* going on to separately produce the
skill's actual requested Markdown contract. The result is a report.md
roughly double the length it should be, with the required content
duplicated in two different shapes back-to-back.

This is cosmetic, not a data-integrity bug -- confirmed directly against
report/sast.py's real parser: `extract_findings_register_rows()` finds
the genuine "## 3. Findings Register" section by name regardless of what
precedes it, and `count_severities()`'s `### [SEVERITY]` pattern only
matches the compliant second half (Copilot's own native Alert format
uses plain "Severity: CRITICAL" text, no brackets), so the SAST Findings
Register and dashboard severity counts both come out correct. The actual
casualty was `report/markdown.py`'s `strip_preamble()`: it assumed every
agent emits a single top-level `# <Skill> Report` heading to anchor on,
but Copilot's output never uses a single `#` anywhere (every heading is
`##`/`###`), so the preamble-stripping regex found nothing to anchor on
and left the whole duplicated block in place. Fixed there (not here) by
adding a fallback anchor on "## 1. Executive Summary" -- every skill's
contract requires that as its first numbered section regardless of
which agent is running it, so it's a safe, skill-agnostic backstop for
any agent that skips the title outright. Verified against this exact
captured report: 713 lines / 29396 chars down to 281 / 14442, landing
exactly on the real content with no pollution left. No attempt was made
to suppress Copilot's native tool from firing in the first place (e.g.
via `--deny-tool`) -- the tool/skill name isn't known and guessing at it
without being able to verify the guess isn't worth the risk; cutting the
resulting preamble downstream is the safer fix.
"""

from __future__ import annotations

from pathlib import Path

from secfoo.agents.base import AgentAdapter


class CopilotAdapter(AgentAdapter):
name = "copilot"
binary = "copilot"
default_timeout_seconds = 1800

def build_command(self, prompt: str, *, workdir: Path) -> list[str]:
return [self.binary, "-p", prompt, "-s", "--allow-all-tools"]
2 changes: 2 additions & 0 deletions src/secfoo/agents/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from secfoo.agents.api import ApiAdapter
from secfoo.agents.base import AgentAdapter
from secfoo.agents.claude import ClaudeAdapter
from secfoo.agents.copilot import CopilotAdapter
from secfoo.agents.codex import CodexAdapter
from secfoo.agents.cursor import CursorAdapter
from secfoo.agents.gemini import GeminiAdapter
Expand All @@ -14,6 +15,7 @@
CursorAdapter.name: CursorAdapter,
AntigravityAdapter.name: AntigravityAdapter,
GeminiAdapter.name: GeminiAdapter,
CopilotAdapter.name: CopilotAdapter,
ApiAdapter.name: ApiAdapter,
SecFooAdapter.name: SecFooAdapter,
CodexAdapter.name: CodexAdapter,
Expand Down
1 change: 1 addition & 0 deletions src/secfoo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ class AgentId(str, Enum):
CURSOR = "agent"
ANTIGRAVITY = "agy"
GEMINI = "gemini"
COPILOT = "copilot"
API = "api"
SECFOO = "secfoo"
CODEX = "codex"
Expand Down
26 changes: 24 additions & 2 deletions src/secfoo/report/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,23 @@
)
_TOP_LEVEL_HEADING_RE = re.compile(r"^#\s+.+$", re.MULTILINE)

# Fallback anchor for an agent that skips the literal "# <Skill> Report"
# title outright (observed with the copilot adapter: it unpromptedly runs
# its own native security-scan tool first, emitting an unrelated "##"/"###"
# preamble, then goes straight into the skill's required numbered sections
# without ever writing a single top-level "#" heading anywhere). Every
# skill's contract requires "## 1. Executive Summary" verbatim as its
# first numbered section (see skills/renderer.py's shared "Required
# output format" block -- identical across every skill, not just SAST),
# so anchoring on that literal phrase, not just "## 1." with any text,
# matters: a preamble that itself numbers an unrelated "## 1. <something>"
# section (a plan, a to-do list) would otherwise be matched instead of the
# real report -- cutting to the wrong, earlier point instead of past the
# preamble entirely. Tried only when the primary title search above finds
# nothing, so a compliant agent's report (which always has both) is
# unaffected either way.
_NUMBERED_SECTION_ONE_RE = re.compile(r"^##\s+1\.\s+Executive Summary\s*$", re.MULTILINE | re.IGNORECASE)

# "commonmark" alone is the strict base spec and does NOT parse GFM pipe
# tables -- every `| a | b |` block silently fell through as a plain
# paragraph of literal text. `enable(["table"])` turns on just the table
Expand All @@ -71,10 +88,15 @@ def strip_preamble(text: str) -> str:
"""Drops any assistant chatter before the report's required top-level
heading (`# <Skill> Report`). The prompt explicitly forbids a preamble,
but that instruction isn't 100% reliable in practice -- this is the
defensive backstop. Leaves text unchanged if no top-level heading is
found at all, rather than risk hiding a malformed report.
defensive backstop. Falls back to anchoring on "## 1. Executive
Summary" (see _NUMBERED_SECTION_ONE_RE above) when no top-level heading
exists at all, for an agent that skips the title outright but still
gets to the required sections eventually. Leaves text unchanged if
neither anchor is found, rather than risk hiding a malformed report.
"""
match = _TOP_LEVEL_HEADING_RE.search(text)
if match is None:
match = _NUMBERED_SECTION_ONE_RE.search(text)
if match is None:
return text
return text[match.start():]
Expand Down
62 changes: 62 additions & 0 deletions tests/test_agents/test_copilot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from __future__ import annotations

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"]


def test_build_command_never_grants_unrestricted_paths_or_urls(tmp_path):
"""--allow-all-tools is required for non-interactive mode, but the
broader --allow-all/--yolo/--allow-all-paths/--allow-all-urls escape
hatches are a materially bigger grant (arbitrary filesystem/network
access) that a read-only security review never needs.
"""
adapter = CopilotAdapter()
cmd = adapter.build_command("hi", workdir=tmp_path)
for forbidden in ("--allow-all", "--yolo", "--allow-all-paths", "--allow-all-urls"):
assert forbidden not in cmd


def test_binary_and_name():
assert CopilotAdapter.binary == "copilot"
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.
"""
adapter = CopilotAdapter()
assert adapter.extract_report("# SAST Report\n...") == "# SAST Report\n..."


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


def test_is_available_false_when_binary_missing(monkeypatch):
monkeypatch.setattr("secfoo.agents.base.shutil.which", lambda name: None)
assert CopilotAdapter().is_available() is False


def test_run_success(fake_popen, tmp_path):
fake_popen(stdout="# SAST Report\n\nfindings...", stderr="", returncode=0)
adapter = CopilotAdapter()
result = adapter.run("hi", workdir=tmp_path)
assert result.status == "success"
assert result.raw_report == "# SAST Report\n\nfindings..."


def test_run_timeout_does_not_raise(fake_popen, tmp_path):
fake_popen(raise_timeout=True, stdout="partial", stderr="")
adapter = CopilotAdapter()
result = adapter.run("hi", workdir=tmp_path, timeout=1)
assert result.status == "timeout"
assert result.timed_out is True
assert result.exit_code is None
assert result.raw_report == ""
45 changes: 45 additions & 0 deletions tests/test_report/test_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,51 @@ def test_strip_preamble_leaves_text_unchanged_when_no_heading_found():
assert strip_preamble(text) == text


def test_strip_preamble_falls_back_to_numbered_section_one():
"""Regression test for the copilot adapter: it unpromptedly runs its
own native security-scan tool first (an unrelated "##"/"###" preamble
with no single top-level "#" heading anywhere) before going straight
into the required numbered sections without ever writing the "#
<Skill> Report" title. The primary anchor never fires here, so this
must fall back to "## 1. Executive Summary" instead of giving up.
"""
required_report = "## 1. Executive Summary\nRisk is high.\n\n## 2. Scope\n..."
text = (
"## Security Findings\n\n"
"### Alert 1\n**Severity: CRITICAL**\nSome native alert content.\n\n"
"## Remediation Roadmap\n- fix it\n\n"
+ required_report
)
assert strip_preamble(text) == required_report


def test_strip_preamble_fallback_ignores_unrelated_numbered_sections():
"""The fallback must match the literal "## 1. Executive Summary"
text, not just any "## 1. <anything>" heading -- otherwise a
preamble that numbers its own unrelated section "1." (a plan, a
to-do list) gets matched instead of the real report, cutting to the
wrong, earlier point rather than past the preamble entirely.
"""
required_report = "## 1. Executive Summary\nThe real content that should be kept."
text = (
"## My plan\n1. Read the target files\n2. Check for issues\n\n"
"## 1. Setup notes before I start\n"
"This has nothing to do with the real report at all.\n\n"
+ required_report
)
assert strip_preamble(text) == required_report


def test_strip_preamble_prefers_top_level_heading_over_numbered_fallback():
"""When both anchors are present, the title must win so the report
keeps its own heading -- proved by placing "## 1. Executive Summary"
chatter *before* the real title, which the fallback alone would
match and cut into instead of skipping past entirely.
"""
text = "## 1. Executive Summary\nThis mentions the section name but isn't the report.\n\n" + SAMPLE_REPORT
assert strip_preamble(text) == SAMPLE_REPORT


FINDINGS_REGISTER_REPORT = """\
# Threat Assessment Report

Expand Down
Loading