diff --git a/README.md b/README.md index 06876d1..6768cb9 100644 --- a/README.md +++ b/README.md @@ -69,11 +69,17 @@ secfoo run --skill sast --agent api --target https://github.com/org/repo It suits small and medium repositories: the whole target has to fit in one request, and larger ones are rejected with a message suggesting `--exclude`. +(`--agent secfoo` is a minimal variant of the same LiteLLM path that sends +only the rendered prompt, without the target's source files, and reads +`SECFOO_MODEL` instead. Prefer `api` unless you have a reason not to.) + ### Tracking AI spend Every run records tokens and cost where the agent reports them (`api`, -`claude`; `gemini` reports tokens only). See it per run in `secfoo run`, -`secfoo list` and the dashboard, or summarised: +`secfoo`, `claude`; `gemini` reports tokens only; `agent` and `agy` report +neither and show as unpriced rather than $0). See it per run in +`secfoo run`, `secfoo list`, the dashboard and the enterprise portal, or +summarised: ```bash secfoo cost # by agent @@ -81,24 +87,31 @@ secfoo cost --by skill --since 2026-09-01 secfoo cost --project checkout ``` -Secfoo also includes a built-in LangGraph agent whose model calls are routed -through LiteLLM. Configure the provider key and model in the environment; -credentials are never stored in the repository: - -```powershell -$env:OPENAI_API_KEY = "your-key" -$env:SECFOO_MODEL = "openai/gpt-4o-mini" -secfoo run --skill security-architecture-review --agent secfoo -``` +### Using it as a CI gate -LiteLLM-reported spend is stored per run and can be reviewed from the -dashboard or queried from the CLI: +`secfoo run` is non-interactive when stdin isn't a terminal. Two flags turn +an assessment into a policy check, and `--json` gives the pipeline +something it can parse instead of a table: ```bash -secfoo cost -secfoo cost --project "Checkout Service" +secfoo run --skill sast --agent api --target . \ + --fail-on high --max-cost 2.00 --json > secfoo-result.json ``` +| Exit code | Meaning | +|---|---| +| `0` | Every run succeeded and no gate tripped | +| `1` | A run failed or timed out (gate verdicts from a partial scan aren't trusted) | +| `2` | Every run succeeded but `--fail-on` found a finding at/above the threshold, or `--max-cost` was exceeded | + +The JSON document carries per-skill status, severity counts +(critical/high/medium/low/info parsed from the report contract, not the +prose), tokens, USD, and each gate's verdict. `--max-cost` is checked after +the runs finish — an agent only reports spend on completion — and runs +whose agent reports no cost are counted as `unpriced_runs` so the pipeline +can decide whether that's acceptable. Both flags have config-file +defaults (`[defaults].fail_on`, `[defaults].max_cost_usd`). + See [Getting Started](https://secfoo.com/docs/index.html#quickstart) or the [CLI reference](https://secfoo.com/docs/cli.html) for more. @@ -116,8 +129,8 @@ the [CLI reference](https://secfoo.com/docs/cli.html) for more. over-permissioning risk - **Track third-party/vendor risk** with AI-BOM inventories and a dedicated third-party review workflow -- **Run it in CI**, non-interactively, with the same commands you'd use - locally +- **Run it in CI** as a real gate: `--fail-on high`, `--max-cost 2.00`, + `--json`, and distinct exit codes for "scan broke" vs "policy failed" - **Browse every assessment across every project** in a local dashboard, or sync to your org's enterprise portal diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index a35226f..ae72cc0 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -325,8 +325,37 @@ secfoo show # Launch the local dashboard secfoo serve + +# AI spend across past runs +secfoo cost --by skill --since 2026-09-01 ``` +### CI gates and machine-readable output + +```bash +secfoo run --skill sast --skill secret-scanning --agent api --target . \ + --fail-on high --max-cost 2.00 --json > secfoo-result.json +``` + +| Flag | Effect | +|---|---| +| `--fail-on critical\|high\|medium\|low` | Exit `2` if any run reports a finding at that severity or worse. Counts come from the report contract's `### [SEVERITY] Fn:` headings, not from prose. | +| `--max-cost ` | Exit `2` if the summed agent-reported spend for this invocation exceeds the cap. Evaluated after the runs complete. | +| `--json` | Write one JSON document to stdout (per-skill status, severity counts, tokens, USD, gate verdicts, resolved exit code); progress and notes go to stderr. Also suppresses the interactive project-name prompt. | + +Exit codes: `0` clean, `1` a run failed or timed out (gate verdicts are +still reported in the JSON but a partial scan never passes), `2` all runs +succeeded but a gate tripped. Config-file defaults: `[defaults].fail_on` +and `[defaults].max_cost_usd`. + +Cost provenance: `api`/`secfoo` take LiteLLM's `completion_cost`, `claude` +takes `total_cost_usd` from `--output-format json`, `gemini` reports tokens +only, `agent`/`agy` report nothing. Runs with no reported cost count as +`unpriced_runs` in the JSON and in `secfoo cost`; they never pass a cap as +"$0". The enterprise portal stores the client-reported tokens/USD on +ingest — spend can't be recomputed server-side from report text the way +severity counts are. + ## Assessments An **assessment** is a case-file container -- an Application ID / Security @@ -375,6 +404,9 @@ depth = "quick" # Vendored copies / unrelated repos checked out inside a project. Added to # the built-in exclusions (node_modules/, .git/, ...), never replacing them. exclude = ["vendor/", "some-cloned-repo/"] +# CI gates (see "CI gates" above); --fail-on / --max-cost override per run. +fail_on = "high" +max_cost_usd = 2.00 [[mcp_servers]] name = "Atlassian-Rovo-MCP" diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 8be8280..b3c0226 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -106,6 +106,31 @@ class DepthId(str, Enum): STANDARD = "standard" +class FailOn(str, Enum): + CRITICAL = "critical" + HIGH = "high" + MEDIUM = "medium" + LOW = "low" + + +# Exit codes for `secfoo run`, so CI can tell "the scan broke" from "the +# scan worked and the policy gate failed" without parsing output. +EXIT_RUN_FAILED = 1 +EXIT_GATE_FAILED = 2 + +_SEVERITY_ORDER = ("critical", "high", "medium", "low") + + +def _findings_at_or_above(outcome, threshold: str) -> int: + """Count of findings in `outcome` at `threshold` severity or worse.""" + total = 0 + for level in _SEVERITY_ORDER: + total += getattr(outcome, f"{level}_count", 0) + if level == threshold: + break + return total + + class AssessmentTypeId(str, Enum): INTERNAL = "internal" THIRD_PARTY = "third-party" @@ -212,20 +237,46 @@ def run( "checked-out repo). Repeatable, and added on top of [defaults].exclude " "in ~/.secfoo/config.toml and the built-in exclusions.", ), + fail_on: Optional[FailOn] = typer.Option( + None, + "--fail-on", + help="Exit 2 if any run reports a finding at this severity or worse " + "(critical|high|medium|low). Falls back to [defaults].fail_on in " + "~/.secfoo/config.toml; unset means findings never fail the command.", + ), + max_cost: Optional[float] = typer.Option( + None, + "--max-cost", + min=0.0, + help="Exit 2 if the summed reported AI spend (USD) for this invocation " + "exceeds this amount. Checked after the runs finish (an agent CLI " + "only reports cost on completion). Falls back to [defaults].max_cost_usd.", + ), + json_output: bool = typer.Option( + False, + "--json", + help="Print one JSON document (per-skill outcomes, severity counts, " + "spend, gate results) to stdout instead of the table -- for CI.", + ), ) -> None: """Run one or more security skills against a target using the chosen agent. Multiple --skill flags run concurrently, not one after another. + + Exit codes: 0 success, 1 a run failed/timed out, 2 all runs succeeded + but a --fail-on / --max-cost gate tripped. """ for url in confluence: if not url.strip().lower().startswith(("http://", "https://")): - console.print(f"[yellow]Warning:[/] {url!r} doesn't look like a URL — passing it through anyway.") + (err_console if json_output else console).print( + f"[yellow]Warning:[/] {url!r} doesn't look like a URL — passing it through anyway." + ) # No --assessment means execute_runs() will auto-create one for this run. # On a real terminal, ask for the two fields that make that case file # actually trackable later instead of silently falling back to a # URL/path-derived name and no application ID. - if assessment is None and _is_interactive(): + if assessment is None and _is_interactive() and not json_output: if project_name is None: try: default_name = _project_display_name(resolve_target(target)) @@ -247,12 +298,23 @@ def run( depth = DepthId(file_defaults.depth) if file_defaults.depth else DepthId.QUICK if timeout is None: timeout = file_defaults.timeout + if fail_on is None and file_defaults.fail_on: + fail_on = FailOn(file_defaults.fail_on) + if max_cost is None: + max_cost = file_defaults.max_cost_usd # Exclusions are additive rather than override: --exclude adds to the # config's list, so naming one path can't silently drop the others. exclude_paths = _merge_excludes(file_defaults.exclude, exclude) task_ids: dict[str, int] = {} - progress = Progress(SpinnerColumn(finished_text=" "), TextColumn("{task.description}"), console=console) + # In --json mode nothing but the final document may reach stdout, so + # the spinner is disabled and human-facing notes go to stderr. + progress = Progress( + SpinnerColumn(finished_text=" "), + TextColumn("{task.description}"), + console=console, + disable=json_output, + ) def handle_start(skill_name: str) -> None: task_ids[skill_name] = progress.add_task(f"Running [bold]{skill_name}[/] via {agent.value}...", total=None) @@ -289,34 +351,112 @@ def handle_complete(skill_name: str, result_status: str) -> None: err_console.print(f"[red]Error:[/] {exc}") raise typer.Exit(code=1) from None - table = Table(title="Assessment results") - table.add_column("Skill") - table.add_column("Status") - table.add_column("Duration") - table.add_column("Cost", justify="right") - table.add_column("Run ID") + any_failed = any(o.status != "success" for o in outcomes) + priced = [o.cost_usd for o in outcomes if o.cost_usd is not None] + total_cost = sum(priced) if priced else None + unpriced_runs = len(outcomes) - len(priced) + + # Policy gates. Both are evaluated even when a run failed, so the JSON + # document is complete, but a failed run always wins on exit code (1): + # a gate verdict computed from a partial scan isn't trustworthy. + gate_findings = None + if fail_on is not None: + gate_findings = { + "threshold": fail_on.value, + "count": sum(_findings_at_or_above(o, fail_on.value) for o in outcomes), + } + gate_findings["passed"] = gate_findings["count"] == 0 + gate_cost = None + if max_cost is not None: + gate_cost = { + "max_cost_usd": max_cost, + "total_cost_usd": total_cost, + "unpriced_runs": unpriced_runs, + # No reported spend at all can't be judged against a cap -- treat + # as passed but surface unpriced_runs so CI can decide otherwise. + "passed": total_cost is None or total_cost <= max_cost, + } + gate_failed = (gate_findings is not None and not gate_findings["passed"]) or ( + gate_cost is not None and not gate_cost["passed"] + ) - any_failed = False - for outcome in outcomes: - style = _STATUS_STYLE.get(outcome.status, "white") - duration = f"{outcome.duration_seconds:.1f}s" if outcome.duration_seconds else "-" - table.add_row( - outcome.skill_name, - f"[{style}]{outcome.status}[/]", - duration, - format_cost(outcome.cost_usd), - outcome.run_uuid, - ) - if outcome.status != "success": - any_failed = True + if json_output: + document = { + "agent": agent.value, + "depth": depth.value, + "runs": [ + { + "run_uuid": o.run_uuid, + "skill_id": o.skill_id, + "skill_name": o.skill_name, + "status": o.status, + "exit_code": o.exit_code, + "duration_seconds": o.duration_seconds, + "report_path": o.report_path, + "input_tokens": o.input_tokens, + "output_tokens": o.output_tokens, + "cost_usd": o.cost_usd, + "severity": { + "critical": o.critical_count, + "high": o.high_count, + "medium": o.medium_count, + "low": o.low_count, + "info": o.info_count, + }, + } + for o in outcomes + ], + "total_cost_usd": total_cost, + "unpriced_runs": unpriced_runs, + "gates": {"findings": gate_findings, "cost": gate_cost}, + "any_run_failed": any_failed, + "exit_code": EXIT_RUN_FAILED if any_failed else (EXIT_GATE_FAILED if gate_failed else 0), + } + # Plain print, not rich: the document must be byte-exact JSON. + print(json.dumps(document, indent=2)) + else: + table = Table(title="Assessment results") + table.add_column("Skill") + table.add_column("Status") + table.add_column("Duration") + table.add_column("Findings (C/H/M/L)") + table.add_column("Cost", justify="right") + table.add_column("Run ID") + + for outcome in outcomes: + style = _STATUS_STYLE.get(outcome.status, "white") + duration = f"{outcome.duration_seconds:.1f}s" if outcome.duration_seconds else "-" + table.add_row( + outcome.skill_name, + f"[{style}]{outcome.status}[/]", + duration, + f"{outcome.critical_count}/{outcome.high_count}/{outcome.medium_count}/{outcome.low_count}", + format_cost(outcome.cost_usd), + outcome.run_uuid, + ) + + console.print(table) + if total_cost is not None: + console.print(f"AI spend for this run: [bold]{format_cost(total_cost)}[/]") + if gate_findings is not None: + verdict = "[green]passed[/]" if gate_findings["passed"] else "[red]FAILED[/]" + console.print( + f"Findings gate (--fail-on {gate_findings['threshold']}): {verdict} " + f"-- {gate_findings['count']} finding(s) at or above threshold" + ) + if gate_cost is not None: + verdict = "[green]passed[/]" if gate_cost["passed"] else "[red]FAILED[/]" + console.print( + f"Cost gate (--max-cost {format_cost(max_cost)}): {verdict} " + f"-- reported spend {format_cost(total_cost)}" + + (f", {unpriced_runs} run(s) unpriced" if unpriced_runs else "") + ) + console.print("Run [bold]secfoo serve[/] to view full reports in your browser.") - console.print(table) - priced = [o.cost_usd for o in outcomes if o.cost_usd is not None] - if priced: - console.print(f"AI spend for this run: [bold]{format_cost(sum(priced))}[/]") - console.print("Run [bold]secfoo serve[/] to view full reports in your browser.") if any_failed: - raise typer.Exit(code=1) + raise typer.Exit(code=EXIT_RUN_FAILED) + if gate_failed: + raise typer.Exit(code=EXIT_GATE_FAILED) @app.command(name="list") diff --git a/src/secfoo/config.example.toml b/src/secfoo/config.example.toml index 2092c97..05315cd 100644 --- a/src/secfoo/config.example.toml +++ b/src/secfoo/config.example.toml @@ -5,12 +5,18 @@ [defaults] # Used whenever --agent / --depth / --timeout aren't passed on the command # line. CLI flags always win over these. -agent = "claude" # claude | agent (Cursor) | agy (Antigravity) | gemini | api (API key, no CLI) -agent = "claude" # claude | agent (Cursor) | agy (Antigravity) | gemini | secfoo -agent = "claude" # claude | agent (Cursor) | agy (Antigravity) | gemini | secfoo | codex +# Agent CLIs: claude | agent (Cursor) | agy (Antigravity) | gemini | codex | copilot +# API-key agents (no CLI): api | secfoo +agent = "claude" depth = "quick" # quick | standard # timeout = 1800 # seconds; omit to use each agent's own default +# CI gates -- both make `secfoo run` exit 2 (runs themselves succeeded, but +# policy failed) so a pipeline can block a merge. CLI flags --fail-on and +# --max-cost override these for a single run. +# fail_on = "high" # fail when any finding is high or critical +# max_cost_usd = 2.00 # fail when the summed reported AI spend exceeds this + # Paths that are never part of a system under review -- vendored copies, # unrelated repos checked out inside a project, large test fixtures. These # are ADDED to secfoo's built-in exclusions (node_modules/, .git/, dist/, diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 5d05063..7eafeb8 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -66,6 +66,13 @@ class RunOutcome: cost_usd: float | None = None input_tokens: int | None = None output_tokens: int | None = None + # Severity counts parsed from the report's `### [SEVERITY] Fn:` headings, + # so CI gates (`secfoo run --fail-on`) don't have to re-read the report. + critical_count: int = 0 + high_count: int = 0 + medium_count: int = 0 + low_count: int = 0 + info_count: int = 0 def _project_display_name(resolved: ResolvedTarget) -> str: @@ -296,6 +303,11 @@ def _run_single_skill( cost_usd=result.cost_usd, input_tokens=result.input_tokens, output_tokens=result.output_tokens, + critical_count=severity.critical, + high_count=severity.high, + medium_count=severity.medium, + low_count=severity.low, + info_count=severity.info, ) finally: repo.close() diff --git a/src/secfoo/settings.py b/src/secfoo/settings.py index bf1b997..52d4711 100644 --- a/src/secfoo/settings.py +++ b/src/secfoo/settings.py @@ -51,6 +51,14 @@ class Defaults: # Additive on top of the renderer's built-in exclusions, never a # replacement -- see renderer._exclude_section. exclude: list[str] = field(default_factory=list) + # CI gates, overridable per run by `secfoo run --fail-on / --max-cost`. + # fail_on: lowest severity that fails the run (critical|high|medium|low). + # max_cost_usd: fail the run when the summed reported spend exceeds this. + fail_on: str | None = None + max_cost_usd: float | None = None + + +VALID_FAIL_ON = ("critical", "high", "medium", "low") @dataclass(frozen=True) @@ -90,11 +98,21 @@ def load_config(path: Path | None = None) -> SecfooConfig: exclude_raw = defaults_raw.get("exclude", []) if not isinstance(exclude_raw, list) or not all(isinstance(p, str) for p in exclude_raw): raise ConfigError("defaults.exclude must be an array of strings") + fail_on = defaults_raw.get("fail_on") + if fail_on is not None and fail_on not in VALID_FAIL_ON: + raise ConfigError(f"defaults.fail_on must be one of {', '.join(VALID_FAIL_ON)}, got {fail_on!r}") + max_cost_usd = defaults_raw.get("max_cost_usd") + if max_cost_usd is not None: + if isinstance(max_cost_usd, bool) or not isinstance(max_cost_usd, (int, float)) or max_cost_usd <= 0: + raise ConfigError("defaults.max_cost_usd must be a positive number") + max_cost_usd = float(max_cost_usd) defaults = Defaults( agent=defaults_raw.get("agent"), depth=defaults_raw.get("depth"), timeout=defaults_raw.get("timeout"), exclude=list(exclude_raw), + fail_on=fail_on, + max_cost_usd=max_cost_usd, ) servers = [] diff --git a/tests/test_cli.py b/tests/test_cli.py index d8d5e7c..fc92acb 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,5 +1,7 @@ from __future__ import annotations +import json + import pytest from typer.testing import CliRunner @@ -396,6 +398,160 @@ def test_config_init_writes_file(tmp_path, monkeypatch): assert "mcp_servers" in config_path.read_text() +def test_config_init_output_is_loadable(tmp_path, monkeypatch): + """The starter file must itself parse -- a duplicate key (which TOML + forbids) shipped once and made every fresh `secfoo run` fail on the + config it had just been told to create.""" + from secfoo.settings import load_config + + config_path = tmp_path / "config.toml" + monkeypatch.setattr("secfoo.cli.CONFIG_PATH", config_path) + assert runner.invoke(app, ["config", "init"]).exit_code == 0 + cfg = load_config(config_path) + assert cfg.defaults.agent == "claude" + + +# --------------------------------------------------------------------------- +# CI gates: --fail-on, --max-cost, --json, exit codes +# --------------------------------------------------------------------------- + + +def _priced_outcome(status="success", *, cost=None, high=0, medium=0, critical=0, low=0, skill="sast"): + return RunOutcome( + run_uuid="u-" + skill, + skill_id=skill, + skill_name=skill.upper(), + agent_id="api", + status=status, + exit_code=0 if status == "success" else 1, + duration_seconds=2.0, + report_path="/tmp/r.md", + cost_usd=cost, + input_tokens=100 if cost is not None else None, + output_tokens=50 if cost is not None else None, + critical_count=critical, + high_count=high, + medium_count=medium, + low_count=low, + ) + + +def _no_config(monkeypatch): + monkeypatch.setattr("secfoo.cli.load_config", lambda: SecfooConfig(defaults=Defaults(), mcp_servers=[])) + + +def test_fail_on_trips_at_or_above_threshold(monkeypatch): + _no_config(monkeypatch) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: [_priced_outcome(high=1)]) + result = runner.invoke(app, ["run", "--skill", "sast", "--fail-on", "high"]) + assert result.exit_code == 2 + assert "FAILED" in result.stdout + + +def test_fail_on_passes_when_only_lower_severities_present(monkeypatch): + _no_config(monkeypatch) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: [_priced_outcome(medium=3, low=5)]) + result = runner.invoke(app, ["run", "--skill", "sast", "--fail-on", "high"]) + assert result.exit_code == 0 + + +def test_fail_on_counts_critical_as_above_high(monkeypatch): + _no_config(monkeypatch) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: [_priced_outcome(critical=1)]) + assert runner.invoke(app, ["run", "--skill", "sast", "--fail-on", "high"]).exit_code == 2 + + +def test_no_fail_on_means_findings_never_fail_the_command(monkeypatch): + _no_config(monkeypatch) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: [_priced_outcome(critical=9)]) + assert runner.invoke(app, ["run", "--skill", "sast"]).exit_code == 0 + + +def test_max_cost_trips_when_summed_spend_exceeds_cap(monkeypatch): + _no_config(monkeypatch) + monkeypatch.setattr( + "secfoo.cli.execute_runs", + lambda **kw: [_priced_outcome(cost=0.80, skill="sast"), _priced_outcome(cost=0.70, skill="sca")], + ) + result = runner.invoke(app, ["run", "--skill", "sast", "--max-cost", "1.00"]) + assert result.exit_code == 2 + + +def test_max_cost_passes_under_cap(monkeypatch): + _no_config(monkeypatch) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: [_priced_outcome(cost=0.30)]) + assert runner.invoke(app, ["run", "--skill", "sast", "--max-cost", "1.00"]).exit_code == 0 + + +def test_max_cost_with_no_reported_spend_passes_but_flags_unpriced(monkeypatch): + """An agent that reports no cost (cursor, agy) can't be judged against a + cap; that must not be a silent pass that looks like $0 -- the JSON + surfaces unpriced_runs so the pipeline can choose to fail on it.""" + _no_config(monkeypatch) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: [_priced_outcome(cost=None)]) + result = runner.invoke(app, ["run", "--skill", "sast", "--max-cost", "1.00", "--json"]) + assert result.exit_code == 0 + doc = json.loads(result.stdout) + assert doc["gates"]["cost"]["passed"] is True + assert doc["gates"]["cost"]["unpriced_runs"] == 1 + assert doc["total_cost_usd"] is None + + +def test_run_failure_takes_precedence_over_gate_exit_code(monkeypatch): + _no_config(monkeypatch) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: [_priced_outcome("failed", high=5)]) + assert runner.invoke(app, ["run", "--skill", "sast", "--fail-on", "high"]).exit_code == 1 + + +def test_gate_defaults_come_from_config_file(monkeypatch): + monkeypatch.setattr( + "secfoo.cli.load_config", + lambda: SecfooConfig(defaults=Defaults(fail_on="medium", max_cost_usd=0.10), mcp_servers=[]), + ) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: [_priced_outcome(cost=0.05, medium=1)]) + assert runner.invoke(app, ["run", "--skill", "sast"]).exit_code == 2 + + +def test_cli_flag_overrides_config_gate(monkeypatch): + monkeypatch.setattr( + "secfoo.cli.load_config", + lambda: SecfooConfig(defaults=Defaults(fail_on="medium"), mcp_servers=[]), + ) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: [_priced_outcome(medium=1)]) + assert runner.invoke(app, ["run", "--skill", "sast", "--fail-on", "critical"]).exit_code == 0 + + +def test_json_output_is_a_single_parseable_document(monkeypatch): + _no_config(monkeypatch) + monkeypatch.setattr( + "secfoo.cli.execute_runs", lambda **kw: [_priced_outcome(cost=0.42, high=2, medium=1)] + ) + result = runner.invoke( + app, ["run", "--skill", "sast", "--json", "--fail-on", "high", "--max-cost", "5"] + ) + assert result.exit_code == 2 + doc = json.loads(result.stdout) # would raise if the table/spinner leaked into stdout + assert doc["exit_code"] == 2 + assert doc["runs"][0]["severity"] == {"critical": 0, "high": 2, "medium": 1, "low": 0, "info": 0} + assert doc["runs"][0]["cost_usd"] == 0.42 + assert doc["total_cost_usd"] == 0.42 + assert doc["gates"]["findings"] == {"threshold": "high", "count": 2, "passed": False} + assert doc["gates"]["cost"]["passed"] is True + assert doc["any_run_failed"] is False + + +def test_json_output_suppresses_interactive_prompts(monkeypatch): + _no_config(monkeypatch) + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: [_priced_outcome()]) + monkeypatch.setattr("secfoo.cli._is_interactive", lambda: True) + monkeypatch.setattr( + "secfoo.cli.Prompt.ask", lambda *a, **k: (_ for _ in ()).throw(AssertionError("prompted")) + ) + result = runner.invoke(app, ["run", "--skill", "sast", "--json"]) + assert result.exit_code == 0 + json.loads(result.stdout) + + def test_config_init_refuses_to_overwrite_without_force(tmp_path, monkeypatch): config_path = tmp_path / "config.toml" config_path.write_text("# existing\n") diff --git a/tests/test_settings.py b/tests/test_settings.py index b7e91a7..a78c98c 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -20,6 +20,33 @@ def test_load_config_parses_defaults(tmp_path): assert cfg.defaults.timeout == 900 +def test_load_config_parses_ci_gate_defaults(tmp_path): + path = tmp_path / "config.toml" + path.write_text('[defaults]\nfail_on = "high"\nmax_cost_usd = 2\n') + cfg = load_config(path) + assert cfg.defaults.fail_on == "high" + assert cfg.defaults.max_cost_usd == 2.0 + + +def test_load_config_gate_defaults_are_none_when_absent(tmp_path): + path = tmp_path / "config.toml" + path.write_text('[defaults]\nagent = "claude"\n') + cfg = load_config(path) + assert cfg.defaults.fail_on is None + assert cfg.defaults.max_cost_usd is None + + +@pytest.mark.parametrize( + "body", + ['[defaults]\nfail_on = "severe"\n', "[defaults]\nmax_cost_usd = 0\n", "[defaults]\nmax_cost_usd = true\n"], +) +def test_load_config_rejects_invalid_gate_defaults(tmp_path, body): + path = tmp_path / "config.toml" + path.write_text(body) + with pytest.raises(ConfigError): + load_config(path) + + def test_load_config_parses_stdio_mcp_server(tmp_path): path = tmp_path / "config.toml" path.write_text(