diff --git a/.agents/skills/secfoo-fix-findings/SKILL.md b/.agents/skills/secfoo-fix-findings/SKILL.md new file mode 100644 index 00000000..c9422d49 --- /dev/null +++ b/.agents/skills/secfoo-fix-findings/SKILL.md @@ -0,0 +1,11 @@ +--- +name: secfoo-fix-findings +description: Triage and remediate open secfoo security findings in the repository. Shared by OpenAI Codex and Antigravity (`agy`). +--- + +# Fix secfoo Findings + +1. Run `secfoo run --json` (or inspect `.secfoo/findings.json` if inside a network-restricted sandbox). +2. Group findings by severity (`critical`, `high`, `medium`, `low`). +3. Fix each finding with minimal, well-tested edits. +4. Re-run `secfoo run --json` and the project test suite to verify the findings are resolved. diff --git a/docs/GEMINI_AGY_AUTOMATIONS.md b/docs/GEMINI_AGY_AUTOMATIONS.md new file mode 100644 index 00000000..edef76d0 --- /dev/null +++ b/docs/GEMINI_AGY_AUTOMATIONS.md @@ -0,0 +1,19 @@ +# Gemini CLI and Antigravity (`agy`) Automations (#247) + +secfoo supports both **Gemini CLI** and **Antigravity (`agy`)**. + +## Gemini CLI + +- **Config:** `.gemini/settings.json` (`hooks` object with `BeforeTool`, `AfterTool`, `AfterAgent`, `SessionStart`, `SessionEnd`). `timeout` is in **milliseconds** (default `60000`). +- **Extension:** Installable from GitHub via `gemini extensions install` using `extensions/gemini-secfoo/` (`gemini-extension.json`, `hooks/hooks.json`, `commands/secfoo/fix-findings.toml`, `skills/secfoo-fix-findings/SKILL.md`). +- **Headless (`gemini -p`):** secfoo's `SECFOO_HOOK_ACTIVE` recursion guard prevents nested hook loops when `gemini -p` is used as a delegate runner. +- **AfterTool:** Never denies (denying `AfterTool` hides tool output in Gemini CLI); instead surfaces `additionalContext`. +- **AfterAgent:** `decision: "deny"` forces a retry and is loop-guarded via `stop_hook_active` / `retry_active`. + +## Antigravity (`agy`) + +- **Config:** `.agents/hooks.json` (workspace) or `~/.gemini/config/hooks.json` (global). Hooks in `~/.gemini/antigravity-cli/settings.json` are **not** loaded. `timeout` is in **seconds** (default `30`). +- **Events:** `PreToolUse` (`run_command`), `PostToolUse`, `Stop` (`decision: "continue"`, guarded by `continuationActive`), and `SessionStart` (`injectSteps`). +- **Skills:** `.agents/skills//SKILL.md` is shared with OpenAI Codex without duplication. Workflows are deprecated in favor of skills. +- **Scheduling:** Session schedules in `agy` do not replace CI; use CI or a cloud scheduler for `scheduled-baseline`. +- **Migration note:** Users migrating from Gemini CLI to Antigravity should install hooks via `secfoo automations enable --host antigravity` rather than relying on `.gemini/settings.json` hook blocks carrying over automatically. diff --git a/docs/automations.md b/docs/automations.md new file mode 100644 index 00000000..4ddbda00 --- /dev/null +++ b/docs/automations.md @@ -0,0 +1,28 @@ +# Secfoo Automations & `secfoo hook` + +Secfoo provides a single tested hook entrypoint (`secfoo hook --host `) and a recipe manager (`secfoo automations`) for AI coding tools. + +## Recipes + +Built-in recipes live in `src/secfoo/automations/recipes/*.toml` (and user overrides in `~/.secfoo/automations/*.toml` — never loaded from untrusted target repositories): + +- `commit-guard`: Scans staged changes for secrets and high-risk issues before `git commit`, `git push`, or `gh pr create`. +- `secret-on-edit`: Scans edited files for credentials after file edits. +- `pr-security-review`: Runs quick SAST + reachability checks on changed files before PR creation. + +## Host Support & Detection + +Supported hosts: `claude` (reference adapter), `cursor`, `copilot`, `gemini`, `antigravity`, `kiro`, `droid`, `codex`, `opencode`. + +`secfoo hook` detects the actual host from environment variables and stdin payload shape, warns on `--host` mismatches, enforces `SECFOO_HOOK_ACTIVE=1` recursion protection and `stop_hook_active` / `continuationActive` / `loop_count` loop guards, deduplicates concurrent hooks, and fails open on errors or expired budgets. + +## CLI + +```sh +secfoo automations list +secfoo automations enable commit-guard --host claude --dry-run +secfoo automations enable commit-guard --host claude +secfoo automations status +secfoo automations doctor +secfoo automations disable commit-guard --host claude +``` diff --git a/extensions/gemini-secfoo/commands/secfoo/fix-findings.toml b/extensions/gemini-secfoo/commands/secfoo/fix-findings.toml new file mode 100644 index 00000000..02b1b0db --- /dev/null +++ b/extensions/gemini-secfoo/commands/secfoo/fix-findings.toml @@ -0,0 +1,4 @@ +description = "Run secfoo security review and remediate open findings" +prompt = """ +Run `secfoo run --json` to scan the workspace, group findings by severity, fix each finding cleanly, and re-run `secfoo run --json` to confirm zero open issues. +""" diff --git a/extensions/gemini-secfoo/gemini-extension.json b/extensions/gemini-secfoo/gemini-extension.json new file mode 100644 index 00000000..b7ccbb6a --- /dev/null +++ b/extensions/gemini-secfoo/gemini-extension.json @@ -0,0 +1,6 @@ +{ + "name": "secfoo", + "version": "0.1.0", + "description": "secfoo security hooks, commands, and skills for Gemini CLI", + "contextFileName": "GEMINI.md" +} diff --git a/extensions/gemini-secfoo/hooks/hooks.json b/extensions/gemini-secfoo/hooks/hooks.json new file mode 100644 index 00000000..e6b2bf13 --- /dev/null +++ b/extensions/gemini-secfoo/hooks/hooks.json @@ -0,0 +1,32 @@ +{ + "hooks": { + "BeforeTool": [ + { + "matcher": "run_shell_command", + "sequential": true, + "hooks": [ + { + "name": "secfoo-commit-guard", + "type": "command", + "command": "secfoo hook commit-guard --host gemini", + "timeout": 60000 + } + ] + } + ], + "AfterTool": [ + { + "matcher": "write_file|replace", + "sequential": false, + "hooks": [ + { + "name": "secfoo-secret-on-edit", + "type": "command", + "command": "secfoo hook secret-on-edit --host gemini", + "timeout": 60000 + } + ] + } + ] + } +} diff --git a/extensions/gemini-secfoo/skills/secfoo-fix-findings/SKILL.md b/extensions/gemini-secfoo/skills/secfoo-fix-findings/SKILL.md new file mode 100644 index 00000000..090da50c --- /dev/null +++ b/extensions/gemini-secfoo/skills/secfoo-fix-findings/SKILL.md @@ -0,0 +1,10 @@ +--- +name: secfoo-fix-findings +description: Triage and remediate open secfoo security findings in the repository. +--- + +# Fix secfoo Findings + +1. Run `secfoo run --json` to inspect open findings. +2. Remediate critical and high findings first, then medium and low. +3. Re-run `secfoo run --json` and project tests to confirm the fix. diff --git a/src/secfoo/automations/__init__.py b/src/secfoo/automations/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/src/secfoo/automations/__init__.py @@ -0,0 +1 @@ + diff --git a/src/secfoo/automations/engine.py b/src/secfoo/automations/engine.py new file mode 100644 index 00000000..8836da1f --- /dev/null +++ b/src/secfoo/automations/engine.py @@ -0,0 +1,472 @@ +"""Execution engine for `secfoo hook` (#242).""" + +from __future__ import annotations + +import hashlib +import json +import logging +import os +import subprocess # nosec B404 -- fixed git/secfoo argv, no shell +import sys +import tempfile +import threading +import time +import uuid +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from secfoo.automations.hosts.adapters import parse_for_host, render_for_host +from secfoo.automations.hosts.base import HookEvent, HookResult, detect_host +from secfoo.automations.recipes import Recipe, get_recipe + +DEDUP_TTL_SECONDS = 30.0 +DEFAULT_DEDUP_DIR = Path.home() / ".secfoo" / "hook-dedup" + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class DelegateOutcome: + """Result returned by a delegated security scan.""" + + passed: bool + findings_count: int = 0 + summary: str = "" + incomplete: bool = False + + +def _staged_files(cwd: str) -> list[str]: + try: + proc = subprocess.run( # nosec B603 B607 -- fixed git argv, no shell + ["git", "diff", "--cached", "--name-only"], + cwd=cwd or None, + capture_output=True, + text=True, + timeout=5, + check=False, + ) + if proc.returncode == 0: + return [ln.strip() for ln in proc.stdout.splitlines() if ln.strip()] + except (OSError, subprocess.TimeoutExpired) as exc: + # Fail-open: git may be missing or cwd not a git repo. + logger.debug("git diff --cached skipped: %s", exc) + return [] + + +def _claim_dedup_lock( + dedup_dir: Path, + *, + recipe_id: str, + session_ref: str, + diff_hash: str, + ttl_seconds: float = DEDUP_TTL_SECONDS, +) -> bool: + """Return True if this invocation owns the dedup slot, False if duplicate.""" + dedup_dir.mkdir(parents=True, exist_ok=True) + digest = hashlib.sha256(f"{recipe_id}\0{session_ref}\0{diff_hash}".encode()).hexdigest()[:24] + lock_file = dedup_dir / f"{digest}.lock" + now = time.time() + if lock_file.exists(): + try: + age = now - lock_file.stat().st_mtime + if age < ttl_seconds: + return False + except OSError as exc: + # Fail-open if another process removed the lock concurrently. + logger.debug("dedup stat ignored: %s", exc) + try: + lock_file.write_text(f"{now}\n", encoding="utf-8") + except OSError: + return True + return True + + +def _severity_trips_fail_on(outcome: Any, fail_on: str) -> tuple[bool, int]: + """Return `(tripped, matching_findings_count)` against `recipe.fail_on`.""" + crit = int(getattr(outcome, "critical_count", 0) or 0) + high = int(getattr(outcome, "high_count", 0) or 0) + med = int(getattr(outcome, "medium_count", 0) or 0) + low = int(getattr(outcome, "low_count", 0) or 0) + level = (fail_on or "high").lower() + if level == "critical": + count = crit + elif level == "medium": + count = crit + high + med + elif level == "low": + count = crit + high + med + low + else: + count = crit + high + return count > 0, count + + +def _resolve_hook_agent(recipe: Recipe, agent_override: str | None = None) -> str: + """Resolve agent id: CLI --agent -> recipe.agent -> ~/.secfoo/config.toml default.""" + if agent_override: + return agent_override + if recipe.agent: + return recipe.agent + from secfoo.settings import ConfigError, load_config + + try: + return load_config().defaults.agent + except ConfigError: + return "claude" + + +def _evaluate_outcomes(outcomes: list[Any], recipe: Recipe, changed_files: list[str]) -> DelegateOutcome: + """Evaluate runner/JSON outcomes, flagging non-success statuses as incomplete.""" + total_findings = 0 + tripped = False + incomplete_statuses: list[str] = [] + + for out in outcomes: + if isinstance(out, Mapping): + status = str(out.get("status") or "success") + sev = out.get("severity") or {} + norm = type( + "_Sev", + (), + { + "critical_count": sev.get("critical", out.get("critical_count", 0)), + "high_count": sev.get("high", out.get("high_count", 0)), + "medium_count": sev.get("medium", out.get("medium_count", 0)), + "low_count": sev.get("low", out.get("low_count", 0)), + }, + )() + hit, count = _severity_trips_fail_on(norm, recipe.fail_on) + else: + status = str(getattr(out, "status", None) or "success") + hit, count = _severity_trips_fail_on(out, recipe.fail_on) + + total_findings += count + if hit: + tripped = True + if status != "success": + incomplete_statuses.append(status) + + if tripped: + return DelegateOutcome( + passed=False, + findings_count=total_findings, + summary=f"Found {total_findings} {recipe.fail_on}+ issue(s) across {', '.join(recipe.skills)}.", + ) + if incomplete_statuses: + unique = ", ".join(dict.fromkeys(incomplete_statuses)) + return DelegateOutcome( + passed=False, + findings_count=0, + summary=f"secfoo scan did not complete: {unique}", + incomplete=True, + ) + return DelegateOutcome( + passed=True, + findings_count=0, + summary=f"Scanned {len(changed_files)} file(s) with {', '.join(recipe.skills)}: no {recipe.fail_on}+ issues.", + ) + + +def _default_delegate_runner( + recipe: Recipe, + event: HookEvent, + changed_files: list[str], + *, + agent_id: str | None = None, +) -> DelegateOutcome: + """Run the recipe's skills via `secfoo.runner.execute_runs` with `SECFOO_HOOK_ACTIVE=1`.""" + if not changed_files and recipe.scope in ("staged", "turn_changes"): + return DelegateOutcome(passed=True, findings_count=0, summary="No changed files to scan.") + + from secfoo import runner as secfoo_runner + + resolved_agent = _resolve_hook_agent(recipe, agent_id) + cwd = event.workspace_roots[0] if event.workspace_roots else "." + prev_hook_flag = os.environ.get("SECFOO_HOOK_ACTIVE") + os.environ["SECFOO_HOOK_ACTIVE"] = "1" + try: + outcomes = secfoo_runner.execute_runs( + skill_ids=list(recipe.skills), + target=cwd, + confluence_urls=[], + agent_id=resolved_agent, + depth="quick", + timeout=max(10, int(recipe.budget_seconds)), + changed_files=changed_files, + ) + finally: + if prev_hook_flag is None: + os.environ.pop("SECFOO_HOOK_ACTIVE", None) + else: + os.environ["SECFOO_HOOK_ACTIVE"] = prev_hook_flag + + return _evaluate_outcomes(outcomes, recipe, changed_files) + + +def _build_detached_run_argv(recipe: Recipe, cwd: str, changed_files: list[str], agent_id: str) -> list[str]: + argv = [ + sys.executable, + "-m", + "secfoo", + "run", + "--target", + cwd or ".", + "--depth", + "quick", + "--json", + "--rescan", + "--agent", + agent_id, + "--fail-on", + recipe.fail_on, + ] + for skill in recipe.skills: + argv.extend(["--skill", skill]) + if changed_files: + argv.extend(["--changed-files", ",".join(changed_files)]) + return argv + + +def _spawn_detached_process(argv: list[str], *, stdout_target: Any) -> subprocess.Popen[Any] | None: + env = dict(os.environ) + env["SECFOO_HOOK_ACTIVE"] = "1" + popen_kwargs: dict[str, Any] = { + "env": env, + "stdin": subprocess.DEVNULL, + "stdout": stdout_target, + "stderr": subprocess.DEVNULL, + "close_fds": True, + } + if sys.platform == "win32": + popen_kwargs["creationflags"] = ( + getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) + | getattr(subprocess, "DETACHED_PROCESS", 0) + ) + else: + popen_kwargs["start_new_session"] = True + try: + return subprocess.Popen(argv, **popen_kwargs) # nosec B603 -- fixed argv, no shell + except OSError as exc: + logger.debug("background scan spawn failed (fail-open): %s", exc) + return None + + +def _spawn_background_scan( + recipe: Recipe, + cwd: str, + changed_files: list[str], + agent_id: str | None = None, +) -> None: + """Launch a detached `secfoo run` subprocess so backgrounded scans outlive `secfoo hook`.""" + if not recipe.skills: + return + resolved = _resolve_hook_agent(recipe, agent_id) + _spawn_detached_process(_build_detached_run_argv(recipe, cwd, changed_files, resolved), stdout_target=subprocess.DEVNULL) + + +def _run_subprocess_with_budget( + recipe: Recipe, + cwd: str, + changed_files: list[str], + *, + agent_id: str, + budget_seconds: float, +) -> tuple[DelegateOutcome | None, bool]: + """Launch one detached `secfoo run` subprocess and wait up to `budget_seconds`. + + Returns `(outcome, timed_out)`. When timed out, the subprocess continues running + detached and `secfoo hook` exits immediately without waiting on any thread. + """ + if not changed_files and recipe.scope in ("staged", "turn_changes"): + return DelegateOutcome(passed=True, findings_count=0, summary="No changed files to scan."), False + if not recipe.skills: + return DelegateOutcome(passed=True, findings_count=0, summary="No skills configured."), False + + tmp_dir = Path(tempfile.mkdtemp(prefix="secfoo-hook-")) + out_path = tmp_dir / "result.json" + argv = _build_detached_run_argv(recipe, cwd, changed_files, agent_id) + with out_path.open("wb") as out_handle: + proc = _spawn_detached_process(argv, stdout_target=out_handle) + if proc is None: + return DelegateOutcome(passed=False, incomplete=True, summary="secfoo scan did not complete: spawn_failed"), False + + try: + proc.wait(timeout=max(0.05, float(budget_seconds))) + except subprocess.TimeoutExpired: + return None, True + + try: + payload = json.loads(out_path.read_text(encoding="utf-8")) + runs = payload.get("runs") if isinstance(payload, dict) else None + if not isinstance(runs, list): + return DelegateOutcome(passed=False, incomplete=True, summary="secfoo scan did not complete: invalid_output"), False + return _evaluate_outcomes(runs, recipe, changed_files), False + except (OSError, json.JSONDecodeError): + return DelegateOutcome(passed=False, incomplete=True, summary=f"secfoo scan did not complete: exit_{proc.returncode}"), False + finally: + try: + out_path.unlink(missing_ok=True) + tmp_dir.rmdir() + except OSError: + pass + + +def _run_callable_with_budget( + runner: Callable[[Recipe, HookEvent, list[str]], DelegateOutcome], + recipe: Recipe, + event: HookEvent, + changed_files: list[str], + *, + budget_seconds: float, +) -> tuple[DelegateOutcome | None, bool]: + """Run a test/injected callable on a daemon thread (never blocks interpreter exit).""" + done = threading.Event() + box: dict[str, Any] = {} + + def _target() -> None: + try: + box["outcome"] = runner(recipe, event, changed_files) + except Exception as exc: # noqa: BLE001 -- fail-open by contract + box["error"] = exc + finally: + done.set() + + thread = threading.Thread(target=_target, daemon=True) + thread.start() + if not done.wait(timeout=max(0.05, float(budget_seconds))): + return None, True + if "error" in box: + raise box["error"] + return box["outcome"], False + + +def execute_hook( + recipe_id: str, + *, + declared_host: str | None = None, + stdin_text: str = "", + env: Mapping[str, str] | None = None, + user_recipes_dir: Path | None = None, + dedup_dir: Path = DEFAULT_DEDUP_DIR, + mcp_configured: bool = False, + delegate_fn: Callable[[Recipe, HookEvent, list[str]], DelegateOutcome] | None = None, + agent_override: str | None = None, +) -> tuple[str, int, str | None]: + """Execute one hook invocation. Fail-open: never crashes the host on internal error. + + Returns `(stdout_text, exit_code, warning_message)`. + """ + active_env = dict(os.environ if env is None else env) + warning: str | None = None + + try: + payload: dict[str, Any] = {} + if stdin_text.strip(): + loaded = json.loads(stdin_text) + if isinstance(loaded, dict): + payload = loaded + + effective_host, mismatch_warn = detect_host(declared_host, payload, active_env) + warning = mismatch_warn + + # 1. Recursion guard: never trigger hooks from inside a delegated secfoo run + if active_env.get("SECFOO_HOOK_ACTIVE") == "1": + out, code = render_for_host(effective_host, HookResult(decision="allow")) + return out, code, warning + + recipe = get_recipe(recipe_id, user_dir=user_recipes_dir) + if recipe is None: + out, code = render_for_host(effective_host, HookResult(decision="allow")) + return out, code, f"unknown automation recipe {recipe_id!r}; failing open" + + event = parse_for_host(effective_host, payload, active_env) + + # 2. Loop guard (e.g. Stop / continuation hooks) + if event.loop_active: + out, code = render_for_host( + effective_host, + HookResult(decision="continue" if event.event == "stop" else "allow", event=event.event), + ) + return out, code, warning + + # 3. Event / shell filter + if recipe.events and event.event not in recipe.events: + out, code = render_for_host(effective_host, HookResult(decision="allow", event=event.event)) + return out, code, warning + if event.event == "pre_shell" and not recipe.matches_shell(event.command): + out, code = render_for_host(effective_host, HookResult(decision="allow", event=event.event)) + return out, code, warning + + # 4. Scope changed files & deduplicate across multiple host configs + cwd = event.workspace_roots[0] if event.workspace_roots else "." + changed = _staged_files(cwd) if recipe.scope == "staged" else list(event.edited_paths) + diff_hash = hashlib.sha256("\n".join(sorted(changed) + [event.command]).encode()).hexdigest()[:16] + if not _claim_dedup_lock( + dedup_dir, + recipe_id=recipe.id, + session_ref=event.session_id or "default", + diff_hash=diff_hash, + ): + out, code = render_for_host(effective_host, HookResult(decision="allow", event=event.event)) + return out, code, warning + + # 5. Mode selection: host (when MCP configured) vs delegate + if recipe.default_mode == "host" and mcp_configured: + run_id = uuid.uuid4().hex[:12] + skills_str = ", ".join(recipe.skills) + msg = ( + f"Run secfoo skills ({skills_str}) on {len(changed)} file(s) " + f"and call submit_report (run_id={run_id})." + ) + out, code = render_for_host( + effective_host, + HookResult(decision="warn", event=event.event, message=msg, run_id=run_id), + ) + return out, code, warning + + resolved_agent = _resolve_hook_agent(recipe, agent_override) + budget = float(recipe.budget_seconds) + if delegate_fn is not None: + outcome, timed_out = _run_callable_with_budget( + delegate_fn, recipe, event, changed, budget_seconds=budget + ) + if timed_out: + _spawn_background_scan(recipe, cwd, changed, agent_id=resolved_agent) + else: + outcome, timed_out = _run_subprocess_with_budget( + recipe, cwd, changed, agent_id=resolved_agent, budget_seconds=budget + ) + + if timed_out or outcome is None: + msg = ( + f"secfoo recipe '{recipe.id}' exceeded {recipe.budget_seconds}s budget; " + "continuing in background." + ) + out, code = render_for_host( + effective_host, + HookResult(decision="warn", event=event.event, message=msg, backgrounded=True), + ) + return out, code, warning + + if not outcome.passed: + decision = "warn" if outcome.incomplete else ("deny" if recipe.blocking else "warn") + out, code = render_for_host( + effective_host, + HookResult( + decision=decision, + event=event.event, + reason=outcome.summary or f"secfoo recipe {recipe.id!r} found {outcome.findings_count} issue(s)", + message=outcome.summary, + findings_count=outcome.findings_count, + ), + ) + return out, code, warning + + out, code = render_for_host( + effective_host, + HookResult(decision="allow", event=event.event, message=outcome.summary), + ) + return out, code, warning + except Exception as exc: # noqa: BLE001 -- fail-open by contract + print(f"[secfoo hook] fail-open error: {exc}", file=sys.stderr) + return "", 0, str(exc) diff --git a/src/secfoo/automations/hosts/__init__.py b/src/secfoo/automations/hosts/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/src/secfoo/automations/hosts/__init__.py @@ -0,0 +1 @@ + diff --git a/src/secfoo/automations/hosts/adapters.py b/src/secfoo/automations/hosts/adapters.py new file mode 100644 index 00000000..5c620d78 --- /dev/null +++ b/src/secfoo/automations/hosts/adapters.py @@ -0,0 +1,102 @@ +"""Host adapter registry for supported AI coding tools (#242).""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import Any + +from secfoo.automations.hosts import antigravity, claude, gemini_cli +from secfoo.automations.hosts.base import HookEvent, HookResult + + +def _parse_generic(stdin_json: Mapping[str, Any], env: Mapping[str, str]) -> HookEvent: + ev = claude.parse(stdin_json, env) + loop_active = ( + ev.loop_active + or bool(stdin_json.get("continuationActive", False)) + or int(stdin_json.get("loop_count", 0) or 0) > 0 + ) + cmd = ev.command or str(stdin_json.get("command") or "") + if not cmd and isinstance(stdin_json.get("toolArgs"), Mapping): + cmd = str(stdin_json["toolArgs"].get("command") or "") + return HookEvent( + event=ev.event, + tool_name=ev.tool_name or str(stdin_json.get("toolName") or ""), + command=cmd, + edited_paths=ev.edited_paths, + session_id=ev.session_id, + workspace_roots=ev.workspace_roots, + loop_active=loop_active, + host_version=str( + env.get("CURSOR_VERSION") + or env.get("GEMINI_CLI_VERSION") + or env.get("DROID_VERSION") + or ev.host_version + ), + ) + + +def _render_cursor(result: HookResult) -> tuple[str, int]: + if result.decision == "deny": + if result.event == "stop": + return json.dumps({"followup_message": result.reason or result.message}), 0 + return ( + json.dumps( + { + "permission": "deny", + "user_message": result.reason or result.message, + "agent_message": result.reason or result.message, + } + ), + 0, + ) + if result.message: + return json.dumps({"user_message": result.message, "agent_message": result.message}), 0 + return json.dumps({"permission": "allow"}), 0 + + +def _render_copilot(result: HookResult) -> tuple[str, int]: + if result.decision == "deny": + return json.dumps({"permissionDecision": "deny", "reason": result.reason or result.message}), 0 + return json.dumps({"permissionDecision": "allow"}), 0 + + +def _render_decision(result: HookResult, *, allow_word: str = "allow") -> tuple[str, int]: + if result.decision == "deny": + return json.dumps({"decision": "deny", "reason": result.reason or result.message}), 0 + if result.event == "stop": + return json.dumps({"decision": "continue", "message": result.message}), 0 + return json.dumps({"decision": allow_word, "message": result.message}), 0 + + +def _render_kiro(result: HookResult) -> tuple[str, int]: + if result.decision == "deny": + return (result.reason or result.message or "Blocked by secfoo"), 2 + return (result.message or ""), 0 + + +def parse_for_host(host: str, stdin_json: Mapping[str, Any], env: Mapping[str, str]) -> HookEvent: + if host == "claude": + return claude.parse(stdin_json, env) + if host == "gemini": + return gemini_cli.parse(stdin_json, env) + if host in ("antigravity", "agy"): + return antigravity.parse(stdin_json, env) + return _parse_generic(stdin_json, env) + + +def render_for_host(host: str, result: HookResult) -> tuple[str, int]: + if host == "claude": + return claude.render(result) + if host == "cursor": + return _render_cursor(result) + if host == "copilot": + return _render_copilot(result) + if host == "gemini": + return gemini_cli.render(result) + if host in ("antigravity", "agy"): + return antigravity.render(result) + if host == "kiro": + return _render_kiro(result) + return claude.render(result) diff --git a/src/secfoo/automations/hosts/antigravity.py b/src/secfoo/automations/hosts/antigravity.py new file mode 100644 index 00000000..31a0b351 --- /dev/null +++ b/src/secfoo/automations/hosts/antigravity.py @@ -0,0 +1,93 @@ +"""Antigravity (`agy`) hook host adapter (#247).""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import Any + +from secfoo.automations.hosts.base import HookEvent, HookResult + +_EVENT_MAP = { + "PreToolUse": "pre_shell", + "PostToolUse": "post_edit", + "PreInvocation": "pre_invocation", + "PostInvocation": "post_invocation", + "Stop": "stop", + "SessionStart": "session_start", +} + + +def parse(stdin_json: Mapping[str, Any], env: Mapping[str, str]) -> HookEvent: + """Parse Antigravity (`agy`) hook payload.""" + raw_event = str(stdin_json.get("hook_event_name") or "") + norm_event = _EVENT_MAP.get(raw_event, raw_event.lower() or "unknown") + tool_name = str(stdin_json.get("tool_name") or "") + tool_input = stdin_json.get("tool_input") + if not isinstance(tool_input, Mapping): + tool_input = {} + + command = str(tool_input.get("CommandLine") or tool_input.get("command") or "") + edited: list[str] = [] + for key in ("TargetFile", "file_path", "path", "target_file"): + val = tool_input.get(key) + if isinstance(val, str) and val.strip(): + edited.append(val.strip()) + if isinstance(tool_input.get("paths"), list): + edited.extend(str(p) for p in tool_input["paths"] if isinstance(p, str)) + + roots: list[str] = [] + if env.get("AGY_PROJECT_DIR"): + roots.append(str(env["AGY_PROJECT_DIR"])) + if isinstance(stdin_json.get("cwd"), str) and stdin_json["cwd"]: + roots.append(str(stdin_json["cwd"])) + + loop_active = bool(stdin_json.get("continuationActive", False)) or bool(stdin_json.get("stop_hook_active", False)) + + return HookEvent( + event=norm_event, + tool_name=tool_name, + command=command, + edited_paths=tuple(dict.fromkeys(edited)), + session_id=str(stdin_json.get("session_id") or ""), + workspace_roots=tuple(dict.fromkeys(roots)), + loop_active=loop_active, + host_version=str(env.get("AGY_VERSION") or env.get("ANTIGRAVITY_VERSION") or ""), + ) + + +def render(result: HookResult) -> tuple[str, int]: + """Render HookResult into Antigravity (`agy`) hook JSON.""" + if result.event == "session_start": + if result.message or result.reason: + return ( + json.dumps( + { + "injectSteps": [ + { + "title": "secfoo findings", + "status": "pending", + "note": result.message or result.reason, + } + ] + } + ), + 0, + ) + return "", 0 + + if result.event == "post_edit": + return json.dumps({"decision": "allow"}), 0 + + if result.event == "stop": + if result.decision == "deny": + return json.dumps({"decision": "continue", "reason": result.reason or result.message}), 0 + return "", 0 + + if result.decision == "deny": + return json.dumps({"decision": "deny", "reason": result.reason or result.message}), 0 + + if result.event == "pre_shell": + return json.dumps({"decision": "allow"}), 0 + + return "", 0 diff --git a/src/secfoo/automations/hosts/base.py b/src/secfoo/automations/hosts/base.py new file mode 100644 index 00000000..8ec2b9cc --- /dev/null +++ b/src/secfoo/automations/hosts/base.py @@ -0,0 +1,71 @@ +"""Normalized hook event/result types and host auto-detection (#242).""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import Any + + +@dataclass(frozen=True) +class HookEvent: + """Normalized representation of a host hook invocation.""" + + event: str # pre_shell | post_edit | stop | session_end | unknown + tool_name: str = "" + command: str = "" + edited_paths: tuple[str, ...] = () + session_id: str = "" + workspace_roots: tuple[str, ...] = () + loop_active: bool = False + host_version: str = "" + + +@dataclass(frozen=True) +class HookResult: + """Normalized outcome rendered into each host's native JSON/exit contract.""" + + decision: str = "allow" # allow | deny | warn | continue + event: str = "pre_shell" + reason: str = "" + message: str = "" + backgrounded: bool = False + run_id: str | None = None + findings_count: int = 0 + details: dict[str, Any] = field(default_factory=dict) + + +def detect_host( + declared_host: str | None, + payload: Mapping[str, Any], + env: Mapping[str, str], +) -> tuple[str, str | None]: + """Detect the real host from env and payload shape; warn on mismatch.""" + detected: str | None = None + if env.get("CURSOR_VERSION") or "loop_count" in payload or "hook_event_name" in payload and "cursor_version" in payload: + detected = "cursor" + elif env.get("DROID_VERSION") or "droid_version" in payload: + detected = "droid" + elif env.get("GEMINI_CLI") or env.get("GEMINI_PROJECT_DIR"): + detected = "gemini" + elif env.get("ANTIGRAVITY_AGENT") or env.get("AGY_SESSION_ID") or "continuationActive" in payload: + detected = "antigravity" + elif env.get("KIRO_VERSION") or env.get("KIRO_PROJECT_DIR"): + detected = "kiro" + elif env.get("GITHUB_COPILOT_CLI") or "hookEventName" in payload and "toolArgs" in payload: + detected = "copilot" + elif env.get("OPENCODE_VERSION") or env.get("OPENCODE_SESSION_ID"): + detected = "opencode" + elif env.get("CODEX_SANDBOX") or env.get("CODEX_CLI"): + detected = "codex" + elif env.get("CLAUDE_PROJECT_DIR") or "stop_hook_active" in payload or "hook_event_name" in payload: + detected = "claude" + + effective = detected or (declared_host or "claude") + warning = None + if declared_host and detected and declared_host != detected: + warning = ( + f"host mismatch: --host={declared_host} was passed, " + f"but runtime environment/payload indicates {detected}" + ) + return effective, warning diff --git a/src/secfoo/automations/hosts/claude.py b/src/secfoo/automations/hosts/claude.py new file mode 100644 index 00000000..137619ca --- /dev/null +++ b/src/secfoo/automations/hosts/claude.py @@ -0,0 +1,78 @@ +"""Reference Claude Code hook host adapter (#242 / #243).""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import Any + +from secfoo.automations.hosts.base import HookEvent, HookResult + +_EVENT_MAP = { + "PreToolUse": "pre_shell", + "PostToolUse": "post_edit", + "Stop": "stop", + "SubagentStop": "stop", + "SessionEnd": "session_end", +} + + +def parse(stdin_json: Mapping[str, Any], env: Mapping[str, str]) -> HookEvent: + raw_event = str(stdin_json.get("hook_event_name") or "") + norm_event = _EVENT_MAP.get(raw_event, raw_event.lower() or "unknown") + tool_name = str(stdin_json.get("tool_name") or "") + tool_input = stdin_json.get("tool_input") + if not isinstance(tool_input, Mapping): + tool_input = {} + + command = str(tool_input.get("command") or "") + edited: list[str] = [] + for key in ("file_path", "path", "target_file"): + val = tool_input.get(key) + if isinstance(val, str) and val.strip(): + edited.append(val.strip()) + if isinstance(tool_input.get("paths"), list): + edited.extend(str(p) for p in tool_input["paths"] if isinstance(p, str)) + + roots: list[str] = [] + if env.get("CLAUDE_PROJECT_DIR"): + roots.append(str(env["CLAUDE_PROJECT_DIR"])) + if isinstance(stdin_json.get("cwd"), str) and stdin_json["cwd"]: + roots.append(str(stdin_json["cwd"])) + + return HookEvent( + event=norm_event, + tool_name=tool_name, + command=command, + edited_paths=tuple(dict.fromkeys(edited)), + session_id=str(stdin_json.get("session_id") or ""), + workspace_roots=tuple(dict.fromkeys(roots)), + loop_active=bool(stdin_json.get("stop_hook_active", False)), + host_version=str(env.get("CLAUDE_CODE_VERSION") or ""), + ) + + +def render(result: HookResult) -> tuple[str, int]: + if result.decision == "deny": + if result.event == "pre_shell": + payload = { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": result.reason or result.message, + } + } + return json.dumps(payload), 0 + payload = { + "decision": "block", + "reason": result.reason or result.message, + } + return json.dumps(payload), 0 + + if result.decision in ("warn", "continue") and (result.message or result.reason): + payload = { + "systemMessage": result.message or result.reason, + } + return json.dumps(payload), 0 + + return "", 0 diff --git a/src/secfoo/automations/hosts/gemini_cli.py b/src/secfoo/automations/hosts/gemini_cli.py new file mode 100644 index 00000000..2497e572 --- /dev/null +++ b/src/secfoo/automations/hosts/gemini_cli.py @@ -0,0 +1,81 @@ +"""Gemini CLI hook host adapter (#247).""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import Any + +from secfoo.automations.hosts.base import HookEvent, HookResult + +_EVENT_MAP = { + "BeforeTool": "pre_shell", + "AfterTool": "post_edit", + "AfterAgent": "stop", + "SessionStart": "session_start", + "SessionEnd": "session_end", + "BeforeAgent": "before_agent", + "Notification": "notification", + "PreCompress": "pre_compact", +} + + +def parse(stdin_json: Mapping[str, Any], env: Mapping[str, str]) -> HookEvent: + """Parse Gemini CLI hook payload.""" + raw_event = str(stdin_json.get("hook_event_name") or "") + norm_event = _EVENT_MAP.get(raw_event, raw_event.lower() or "unknown") + tool_name = str(stdin_json.get("tool_name") or "") + tool_input = stdin_json.get("tool_input") + if not isinstance(tool_input, Mapping): + tool_input = {} + + command = str(tool_input.get("command") or "") + edited: list[str] = [] + for key in ("file_path", "path", "target_file"): + val = tool_input.get(key) + if isinstance(val, str) and val.strip(): + edited.append(val.strip()) + if isinstance(tool_input.get("paths"), list): + edited.extend(str(p) for p in tool_input["paths"] if isinstance(p, str)) + + roots: list[str] = [] + if env.get("GEMINI_PROJECT_DIR"): + roots.append(str(env["GEMINI_PROJECT_DIR"])) + if isinstance(stdin_json.get("cwd"), str) and stdin_json["cwd"]: + roots.append(str(stdin_json["cwd"])) + + loop_active = bool(stdin_json.get("stop_hook_active", False)) or bool(stdin_json.get("retry_active", False)) + + return HookEvent( + event=norm_event, + tool_name=tool_name, + command=command, + edited_paths=tuple(dict.fromkeys(edited)), + session_id=str(stdin_json.get("session_id") or ""), + workspace_roots=tuple(dict.fromkeys(roots)), + loop_active=loop_active, + host_version=str(env.get("GEMINI_CLI_VERSION") or ""), + ) + + +def render(result: HookResult) -> tuple[str, int]: + """Render HookResult into Gemini CLI hook JSON.""" + if result.event == "post_edit": + # AfterTool deny hides tool output in Gemini CLI; never block AfterTool. + payload: dict[str, Any] = {"decision": "allow"} + if result.message or result.reason: + payload["additionalContext"] = result.message or result.reason + return json.dumps(payload), 0 + + if result.event == "session_start": + if result.message or result.reason: + return json.dumps({"additionalContext": result.message or result.reason}), 0 + return "", 0 + + if result.decision == "deny": + return json.dumps({"decision": "deny", "reason": result.reason or result.message}), 0 + + if result.event == "pre_shell": + return json.dumps({"decision": "allow"}), 0 + + return "", 0 diff --git a/src/secfoo/automations/manager.py b/src/secfoo/automations/manager.py new file mode 100644 index 00000000..2692b722 --- /dev/null +++ b/src/secfoo/automations/manager.py @@ -0,0 +1,265 @@ +"""Configuration manager for `secfoo automations` (#242).""" + +from __future__ import annotations + +import json +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from secfoo.automations.recipes import Recipe, load_recipes + +HOST_CONFIG_PATHS: dict[str, tuple[str, str]] = { + "claude": (".claude/settings.json", "PreToolUse"), + "cursor": (".cursor/hooks.json", "preToolUse"), + "gemini": (".gemini/settings.json", "BeforeTool"), + "antigravity": (".agents/hooks.json", "PreToolUse"), + "copilot": (".github/hooks/secfoo.json", "preToolUse"), + "kiro": (".kiro/hooks/secfoo.json", "preToolUse"), + "droid": (".factory/settings.json", "PreToolUse"), + "codex": (".codex/hooks.json", "PreToolUse"), + "opencode": (".opencode/hooks.json", "preToolUse"), +} + + +@dataclass(frozen=True) +class AutomationChange: + recipe_id: str + host: str + config_path: Path + changed: bool + dry_run: bool + action: str # "enabled" | "disabled" | "unchanged" + + +def _normalize_host(host: str) -> str: + return "antigravity" if host == "agy" else host + + +def _antigravity_config_path(project_dir: Path, *, scope: str = "project", home_dir: Path | None = None) -> Path: + if scope == "user": + base = home_dir if home_dir is not None else Path.home() + return base / ".gemini" / "config" / "hooks.json" + return project_dir / ".agents" / "hooks.json" + + +def _event_key_for_host(host: str, recipe: Recipe) -> str: + if host == "claude": + if "post_edit" in recipe.events: + return "PostToolUse" + if "stop" in recipe.events: + return "Stop" + return "PreToolUse" + if host == "gemini": + if "post_edit" in recipe.events: + return "AfterTool" + if "stop" in recipe.events: + return "AfterAgent" + if "session_start" in recipe.events: + return "SessionStart" + if "session_end" in recipe.events: + return "SessionEnd" + return "BeforeTool" + if host == "antigravity": + if "post_edit" in recipe.events: + return "PostToolUse" + if "stop" in recipe.events: + return "Stop" + if "session_start" in recipe.events: + return "SessionStart" + return "PreToolUse" + return HOST_CONFIG_PATHS.get(host, (".claude/settings.json", "PreToolUse"))[1] + + +def _hook_command(recipe_id: str, host: str) -> str: + return f"secfoo hook {recipe_id} --host {host}" + + +def _read_json(path: Path) -> dict[str, Any]: + if not path.is_file(): + return {} + raw = path.read_text(encoding="utf-8") + if not raw.strip(): + return {} + data = json.loads(raw) + return data if isinstance(data, dict) else {} + + +def _write_json_atomic(path: Path, data: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(".tmp") + tmp.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + os.replace(tmp, path) + + +def enable_recipe( + recipe_id: str, + *, + host: str = "claude", + project_dir: Path = Path("."), + scope: str = "project", + home_dir: Path | None = None, + dry_run: bool = False, + user_recipes_dir: Path | None = None, +) -> AutomationChange: + host = _normalize_host(host) + recipes = load_recipes(user_dir=user_recipes_dir) + if recipe_id not in recipes: + raise ValueError(f"Unknown recipe {recipe_id!r}") + if host not in HOST_CONFIG_PATHS: + raise ValueError(f"Unsupported host {host!r}") + + recipe = recipes[recipe_id] + if host == "antigravity": + cfg_path = _antigravity_config_path(project_dir, scope=scope, home_dir=home_dir) + elif host == "gemini": + cfg_path = (home_dir / ".gemini" / "settings.json") if (scope == "user" and home_dir is not None) else (project_dir / ".gemini" / "settings.json") + else: + rel_path, _ = HOST_CONFIG_PATHS[host] + cfg_path = project_dir / rel_path + data = _read_json(cfg_path) + hooks = data.setdefault("hooks", {}) + if not isinstance(hooks, dict): + hooks = {} + data["hooks"] = hooks + + event_key = _event_key_for_host(host, recipe) + entries = hooks.setdefault(event_key, []) + if not isinstance(entries, list): + entries = [] + hooks[event_key] = entries + + cmd = _hook_command(recipe_id, host) + timeout_s = max(recipe.budget_seconds + 30, 150) + + already_present = any( + isinstance(e, dict) + and ( + e.get("command") == cmd + or any(isinstance(h, dict) and h.get("command") == cmd for h in e.get("hooks", [])) + ) + for e in entries + ) + if already_present: + return AutomationChange(recipe_id, host, cfg_path, False, dry_run, "unchanged") + + if host == "gemini": + entries.append( + { + "matcher": "run_shell_command" if "pre_shell" in recipe.events else "write_file|replace", + "sequential": True, + "hooks": [ + { + "name": f"secfoo-{recipe_id}", + "type": "command", + "command": cmd, + "timeout": max((recipe.budget_seconds + 30) * 1000, 60000), + } + ], + } + ) + elif host == "antigravity": + entry: dict[str, Any] = { + "enabled": True, + "command": cmd, + "timeout": max(recipe.budget_seconds + 30, 30), + "secfoo_recipe": recipe_id, + } + if event_key in ("PreToolUse", "PostToolUse"): + entry["matcher"] = "run_command" if "pre_shell" in recipe.events else "write_to_file|replace_file_content" + entries.append(entry) + elif host in ("claude", "droid"): + entries.append( + { + "matcher": "Bash" if "pre_shell" in recipe.events else "Write|Edit", + "hooks": [{"type": "command", "command": cmd, "timeout": timeout_s}], + } + ) + else: + entries.append({"command": cmd, "timeout": timeout_s, "secfoo_recipe": recipe_id}) + + if not dry_run: + _write_json_atomic(cfg_path, data) + return AutomationChange(recipe_id, host, cfg_path, True, dry_run, "enabled") + + +def disable_recipe( + recipe_id: str, + *, + host: str = "claude", + project_dir: Path = Path("."), + dry_run: bool = False, +) -> AutomationChange: + if host not in HOST_CONFIG_PATHS: + raise ValueError(f"Unsupported host {host!r}") + rel_path, _ = HOST_CONFIG_PATHS[host] + cfg_path = project_dir / rel_path + if not cfg_path.is_file(): + return AutomationChange(recipe_id, host, cfg_path, False, dry_run, "unchanged") + + data = _read_json(cfg_path) + hooks = data.get("hooks") + if not isinstance(hooks, dict): + return AutomationChange(recipe_id, host, cfg_path, False, dry_run, "unchanged") + + cmd = _hook_command(recipe_id, host) + removed = False + for event_key, entries in list(hooks.items()): + if not isinstance(entries, list): + continue + kept = [] + for entry in entries: + if not isinstance(entry, dict): + kept.append(entry) + continue + if entry.get("command") == cmd or entry.get("secfoo_recipe") == recipe_id: + removed = True + continue + sub = entry.get("hooks") + if isinstance(sub, list): + filtered_sub = [h for h in sub if not (isinstance(h, dict) and h.get("command") == cmd)] + if len(filtered_sub) != len(sub): + removed = True + if not filtered_sub: + continue + entry = {**entry, "hooks": filtered_sub} + kept.append(entry) + hooks[event_key] = kept + + if removed and not dry_run: + _write_json_atomic(cfg_path, data) + return AutomationChange(recipe_id, host, cfg_path, removed, dry_run, "disabled" if removed else "unchanged") + + +def status_automations(project_dir: Path = Path(".")) -> list[dict[str, str]]: + found: list[dict[str, str]] = [] + for host, (rel_path, _) in HOST_CONFIG_PATHS.items(): + cfg_path = project_dir / rel_path + if not cfg_path.is_file(): + continue + data = _read_json(cfg_path) + hooks = data.get("hooks") + if not isinstance(hooks, dict): + continue + for event_key, entries in hooks.items(): + if not isinstance(entries, list): + continue + for entry in entries: + raw_dump = json.dumps(entry) + if "secfoo hook " in raw_dump: + found.append({"host": host, "event": str(event_key), "path": str(cfg_path)}) + return found + + +def doctor_automations(project_dir: Path = Path(".")) -> list[str]: + issues: list[str] = [] + for host, (rel_path, _) in HOST_CONFIG_PATHS.items(): + cfg_path = project_dir / rel_path + if not cfg_path.is_file(): + continue + try: + _read_json(cfg_path) + except ValueError as exc: + issues.append(f"{host}: invalid JSON in {cfg_path}: {exc}") + return issues diff --git a/src/secfoo/automations/recipes.py b/src/secfoo/automations/recipes.py new file mode 100644 index 00000000..73079c8c --- /dev/null +++ b/src/secfoo/automations/recipes.py @@ -0,0 +1,79 @@ +"""Recipe loader for `secfoo hook` and `secfoo automations` (#242).""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path + +try: + import tomllib # type: ignore[import-not-found] +except ModuleNotFoundError: # pragma: no cover -- Python 3.10 + import tomli as tomllib # type: ignore[no-redef] + +BUILTIN_RECIPES_DIR = Path(__file__).resolve().parent / "recipes" +DEFAULT_USER_RECIPES_DIR = Path.home() / ".secfoo" / "automations" + + +@dataclass(frozen=True) +class Recipe: + """Versioned automation recipe loaded from built-in or user TOML.""" + + id: str + version: int + description: str + skills: tuple[str, ...] + events: tuple[str, ...] + shell_match: str | None = None + scope: str = "turn_changes" + blocking: bool = True + fail_on: str = "high" + budget_seconds: int = 120 + max_cost: float = 0.50 + default_mode: str = "delegate" + agent: str | None = None + source_path: Path | None = None + + def matches_shell(self, command: str) -> bool: + if not self.shell_match: + return True + if not command: + return False + return re.search(self.shell_match, command) is not None + + +def _parse_recipe(path: Path) -> Recipe: + data = tomllib.loads(path.read_text(encoding="utf-8")) + rid = str(data["id"]) + return Recipe( + id=rid, + version=int(data.get("version", 1)), + description=str(data.get("description", "")), + skills=tuple(str(s) for s in data.get("skills", [])), + events=tuple(str(e) for e in data.get("events", [])), + shell_match=str(data["shell_match"]) if data.get("shell_match") else None, + scope=str(data.get("scope", "turn_changes")), + blocking=bool(data.get("blocking", True)), + fail_on=str(data.get("fail_on", "high")), + budget_seconds=int(data.get("budget_seconds", 120)), + max_cost=float(data.get("max_cost", 0.50)), + default_mode=str(data.get("default_mode", "delegate")), + agent=str(data["agent"]) if data.get("agent") else None, + source_path=path, + ) + + +def load_recipes(*, user_dir: Path | None = DEFAULT_USER_RECIPES_DIR) -> dict[str, Recipe]: + """Load built-in recipes, plus user-configured recipes (never from target repos).""" + recipes: dict[str, Recipe] = {} + for directory in (BUILTIN_RECIPES_DIR, user_dir): + if directory is None or not directory.is_dir(): + continue + for toml_file in sorted(directory.glob("*.toml")): + recipe = _parse_recipe(toml_file) + recipes[recipe.id] = recipe + return recipes + + +def get_recipe(recipe_id: str, *, user_dir: Path | None = DEFAULT_USER_RECIPES_DIR) -> Recipe | None: + return load_recipes(user_dir=user_dir).get(recipe_id) diff --git a/src/secfoo/automations/recipes/commit-guard.toml b/src/secfoo/automations/recipes/commit-guard.toml new file mode 100644 index 00000000..11b8bd47 --- /dev/null +++ b/src/secfoo/automations/recipes/commit-guard.toml @@ -0,0 +1,12 @@ +id = "commit-guard" +version = 1 +description = "Scan staged changes for secrets and high-risk code before committing or pushing." +skills = ["secret-scanning", "sast"] +events = ["pre_shell"] +shell_match = '^\s*(git\s+(commit|push)|gh\s+pr\s+create)\b' +scope = "staged" +blocking = true +fail_on = "high" +budget_seconds = 120 +max_cost = 0.50 +default_mode = "delegate" diff --git a/src/secfoo/automations/recipes/pr-security-review.toml b/src/secfoo/automations/recipes/pr-security-review.toml new file mode 100644 index 00000000..035eb3c4 --- /dev/null +++ b/src/secfoo/automations/recipes/pr-security-review.toml @@ -0,0 +1,12 @@ +id = "pr-security-review" +version = 1 +description = "Run quick SAST and reachability checks on changed files before creating a PR." +skills = ["sast", "sca-reachability"] +events = ["pre_shell"] +shell_match = '^\s*(gh\s+pr\s+create|git\s+push)\b' +scope = "turn_changes" +blocking = true +fail_on = "high" +budget_seconds = 120 +max_cost = 0.50 +default_mode = "delegate" diff --git a/src/secfoo/automations/recipes/secret-on-edit.toml b/src/secfoo/automations/recipes/secret-on-edit.toml new file mode 100644 index 00000000..6d6112f8 --- /dev/null +++ b/src/secfoo/automations/recipes/secret-on-edit.toml @@ -0,0 +1,11 @@ +id = "secret-on-edit" +version = 1 +description = "Check edited files for hardcoded credentials or tokens after file edits." +skills = ["secret-scanning"] +events = ["post_edit"] +scope = "turn_changes" +blocking = false +fail_on = "medium" +budget_seconds = 45 +max_cost = 0.25 +default_mode = "delegate" diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 11aa9ed0..2b91bbf2 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -2882,6 +2882,99 @@ def sensor_conformance( raise typer.Exit(code=1) +@app.command(name="hook") +def hook_cmd( + recipe: Annotated[str, typer.Argument(help="Automation recipe id (e.g. commit-guard).")], + host: Annotated[str, typer.Option("--host", help="Host AI tool name (claude, cursor, copilot, gemini, ...).")] = "claude", + agent: Annotated[str | None, typer.Option("--agent", "-a", help="Override agent adapter (defaults to recipe or config default).")] = None, +) -> None: + """Single tested hook entrypoint for AI coding tools (#242).""" + import sys + + from secfoo.automations.engine import execute_hook + + stdin_text = sys.stdin.read() if not sys.stdin.isatty() else "" + stdout_text, exit_code, warning = execute_hook( + recipe, declared_host=host, stdin_text=stdin_text, agent_override=agent + ) + if warning: + err_console.print(f"[yellow]Warning:[/] {warning}") + if stdout_text: + sys.stdout.write(stdout_text + "\n") + raise typer.Exit(code=exit_code) + + +automations_app = typer.Typer(name="automations", help="Manage Secfoo hook recipes for AI coding tools (#242).") +app.add_typer(automations_app, name="automations") + + +@automations_app.command(name="list") +def automations_list() -> None: + """List built-in and user automation recipes.""" + from secfoo.automations.recipes import load_recipes + + for recipe in load_recipes().values(): + console.print(f"[bold]{recipe.id}[/] (v{recipe.version}) [{', '.join(recipe.events)}] - {recipe.description}") + + +@automations_app.command(name="enable") +def automations_enable( + recipe: Annotated[str, typer.Argument(help="Recipe id to enable.")], + host: Annotated[str, typer.Option("--host", help="Target AI tool host.")] = "claude", + project_dir: Annotated[Path, typer.Option("--project-dir", help="Project root containing host config.")] = Path("."), + dry_run: Annotated[bool, typer.Option("--dry-run", help="Preview without modifying files.")] = False, +) -> None: + """Enable an automation recipe for a host tool (idempotent).""" + from secfoo.automations.manager import enable_recipe + + res = enable_recipe(recipe, host=host, project_dir=project_dir, dry_run=dry_run) + console.print(f"{res.action}: {res.recipe_id} for {res.host} ({res.config_path})") + + +@automations_app.command(name="disable") +def automations_disable( + recipe: Annotated[str, typer.Argument(help="Recipe id to disable.")], + host: Annotated[str, typer.Option("--host", help="Target AI tool host.")] = "claude", + project_dir: Annotated[Path, typer.Option("--project-dir", help="Project root containing host config.")] = Path("."), + dry_run: Annotated[bool, typer.Option("--dry-run", help="Preview without modifying files.")] = False, +) -> None: + """Disable an automation recipe for a host tool (idempotent).""" + from secfoo.automations.manager import disable_recipe + + res = disable_recipe(recipe, host=host, project_dir=project_dir, dry_run=dry_run) + console.print(f"{res.action}: {res.recipe_id} for {res.host} ({res.config_path})") + + +@automations_app.command(name="status") +def automations_status( + project_dir: Annotated[Path, typer.Option("--project-dir", help="Project root to inspect.")] = Path("."), +) -> None: + """Show enabled secfoo hook automations in this project.""" + from secfoo.automations.manager import status_automations + + entries = status_automations(project_dir) + if not entries: + console.print("No secfoo automations enabled.") + return + for item in entries: + console.print(f"{item['host']} ({item['event']}): {item['path']}") + + +@automations_app.command(name="doctor") +def automations_doctor( + project_dir: Annotated[Path, typer.Option("--project-dir", help="Project root to validate.")] = Path("."), +) -> None: + """Validate host hook configuration files.""" + from secfoo.automations.manager import doctor_automations + + issues = doctor_automations(project_dir) + if issues: + for issue in issues: + err_console.print(f"[red]Error:[/] {issue}") + raise typer.Exit(code=1) + console.print("All automation configs look healthy.") + + _SITECUSTOMIZE = """\ # Written by `secfoo instrument` (#55): starts the secfoo runtime probe in # every Python process of the wrapped command. Inert unless SECFOO_SENSOR=1. diff --git a/tests/fixtures/hooks/antigravity/post_tool_use.json b/tests/fixtures/hooks/antigravity/post_tool_use.json new file mode 100644 index 00000000..363d7c43 --- /dev/null +++ b/tests/fixtures/hooks/antigravity/post_tool_use.json @@ -0,0 +1,9 @@ +{ + "hook_event_name": "PostToolUse", + "tool_name": "write_to_file", + "tool_input": { + "TargetFile": "src/config.py" + }, + "cwd": "/repo", + "session_id": "agy-sess-2" +} diff --git a/tests/fixtures/hooks/antigravity/pre_tool_use.json b/tests/fixtures/hooks/antigravity/pre_tool_use.json new file mode 100644 index 00000000..8b9820ee --- /dev/null +++ b/tests/fixtures/hooks/antigravity/pre_tool_use.json @@ -0,0 +1,9 @@ +{ + "hook_event_name": "PreToolUse", + "tool_name": "run_command", + "tool_input": { + "CommandLine": "git push --force" + }, + "cwd": "/repo", + "session_id": "agy-sess-1" +} diff --git a/tests/fixtures/hooks/antigravity/session_start.json b/tests/fixtures/hooks/antigravity/session_start.json new file mode 100644 index 00000000..b9fd1400 --- /dev/null +++ b/tests/fixtures/hooks/antigravity/session_start.json @@ -0,0 +1,5 @@ +{ + "hook_event_name": "SessionStart", + "cwd": "/repo", + "session_id": "agy-sess-4" +} diff --git a/tests/fixtures/hooks/antigravity/stop.json b/tests/fixtures/hooks/antigravity/stop.json new file mode 100644 index 00000000..a83613f5 --- /dev/null +++ b/tests/fixtures/hooks/antigravity/stop.json @@ -0,0 +1,7 @@ +{ + "hook_event_name": "Stop", + "continuationActive": true, + "fullyIdle": true, + "cwd": "/repo", + "session_id": "agy-sess-3" +} diff --git a/tests/fixtures/hooks/claude/v1/pre_shell.json b/tests/fixtures/hooks/claude/v1/pre_shell.json new file mode 100644 index 00000000..116520e4 --- /dev/null +++ b/tests/fixtures/hooks/claude/v1/pre_shell.json @@ -0,0 +1,9 @@ +{ + "session_id": "claude-sess-1", + "cwd": "/workspace/app", + "hook_event_name": "PreToolUse", + "tool_name": "Bash", + "tool_input": { + "command": "git commit -m 'feat: add api'" + } +} diff --git a/tests/fixtures/hooks/cursor/v1/pre_shell.json b/tests/fixtures/hooks/cursor/v1/pre_shell.json new file mode 100644 index 00000000..b1999715 --- /dev/null +++ b/tests/fixtures/hooks/cursor/v1/pre_shell.json @@ -0,0 +1,10 @@ +{ + "session_id": "cursor-sess-1", + "cwd": "/workspace/app", + "hook_event_name": "PreToolUse", + "tool_name": "Bash", + "tool_input": { + "command": "git commit -m 'feat: cursor'" + }, + "loop_count": 0 +} diff --git a/tests/fixtures/hooks/gemini/after_agent.json b/tests/fixtures/hooks/gemini/after_agent.json new file mode 100644 index 00000000..6c53bee9 --- /dev/null +++ b/tests/fixtures/hooks/gemini/after_agent.json @@ -0,0 +1,6 @@ +{ + "hook_event_name": "AfterAgent", + "retry_active": true, + "cwd": "/repo", + "session_id": "gemini-sess-3" +} diff --git a/tests/fixtures/hooks/gemini/after_tool.json b/tests/fixtures/hooks/gemini/after_tool.json new file mode 100644 index 00000000..c440df41 --- /dev/null +++ b/tests/fixtures/hooks/gemini/after_tool.json @@ -0,0 +1,9 @@ +{ + "hook_event_name": "AfterTool", + "tool_name": "write_file", + "tool_input": { + "file_path": "src/app.py" + }, + "cwd": "/repo", + "session_id": "gemini-sess-2" +} diff --git a/tests/fixtures/hooks/gemini/before_tool.json b/tests/fixtures/hooks/gemini/before_tool.json new file mode 100644 index 00000000..57136289 --- /dev/null +++ b/tests/fixtures/hooks/gemini/before_tool.json @@ -0,0 +1,9 @@ +{ + "hook_event_name": "BeforeTool", + "tool_name": "run_shell_command", + "tool_input": { + "command": "git commit -m 'wip'" + }, + "cwd": "/repo", + "session_id": "gemini-sess-1" +} diff --git a/tests/fixtures/hooks/gemini/session_start.json b/tests/fixtures/hooks/gemini/session_start.json new file mode 100644 index 00000000..c5791392 --- /dev/null +++ b/tests/fixtures/hooks/gemini/session_start.json @@ -0,0 +1,5 @@ +{ + "hook_event_name": "SessionStart", + "cwd": "/repo", + "session_id": "gemini-sess-4" +} diff --git a/tests/test_automations/test_gemini_agy_automations.py b/tests/test_automations/test_gemini_agy_automations.py new file mode 100644 index 00000000..d03aa7b6 --- /dev/null +++ b/tests/test_automations/test_gemini_agy_automations.py @@ -0,0 +1,87 @@ +"""Tests for Gemini CLI and Antigravity (agy) hook adapters and configs (#247).""" + +from __future__ import annotations + +import json +from pathlib import Path + +from secfoo.automations.hosts.adapters import parse_for_host, render_for_host +from secfoo.automations.hosts.base import HookResult +from secfoo.automations.manager import enable_recipe + +GEMINI_FIXTURES = Path(__file__).resolve().parent.parent / "fixtures" / "hooks" / "gemini" +AGY_FIXTURES = Path(__file__).resolve().parent.parent / "fixtures" / "hooks" / "antigravity" + + +def _load(base: Path, name: str) -> dict: + return json.loads((base / name).read_text(encoding="utf-8")) + + +def test_gemini_cli_parse_and_render() -> None: + before = parse_for_host("gemini", _load(GEMINI_FIXTURES, "before_tool.json"), {"GEMINI_CLI_VERSION": "0.5.0"}) + assert before.event == "pre_shell" + assert before.command == "git commit -m 'wip'" + assert before.host_version == "0.5.0" + + after_tool = parse_for_host("gemini", _load(GEMINI_FIXTURES, "after_tool.json"), {}) + assert after_tool.event == "post_edit" + assert after_tool.edited_paths == ("src/app.py",) + + after_agent = parse_for_host("gemini", _load(GEMINI_FIXTURES, "after_agent.json"), {}) + assert after_agent.event == "stop" + assert after_agent.loop_active is True + + # AfterTool never returns deny (would hide tool output) + out_after, rc = render_for_host("gemini", HookResult(event="post_edit", decision="deny", reason="secret found")) + assert rc == 0 + assert json.loads(out_after) == {"decision": "allow", "additionalContext": "secret found"} + + out_deny, rc = render_for_host("gemini", HookResult(event="pre_shell", decision="deny", reason="blocked")) + assert rc == 0 + assert json.loads(out_deny) == {"decision": "deny", "reason": "blocked"} + + out_ctx, rc = render_for_host("gemini", HookResult(event="session_start", decision="allow", message="2 findings")) + assert rc == 0 + assert json.loads(out_ctx) == {"additionalContext": "2 findings"} + + +def test_antigravity_parse_and_render() -> None: + pre = parse_for_host("agy", _load(AGY_FIXTURES, "pre_tool_use.json"), {"AGY_VERSION": "2.0.0"}) + assert pre.event == "pre_shell" + assert pre.command == "git push --force" + assert pre.host_version == "2.0.0" + + post = parse_for_host("antigravity", _load(AGY_FIXTURES, "post_tool_use.json"), {"AGY_PROJECT_DIR": "/ws"}) + assert post.event == "post_edit" + assert post.edited_paths == ("src/config.py",) + assert post.workspace_roots == ("/ws", "/repo") + + stop = parse_for_host("antigravity", _load(AGY_FIXTURES, "stop.json"), {}) + assert stop.event == "stop" + assert stop.loop_active is True + + out_stop, rc = render_for_host("antigravity", HookResult(event="stop", decision="deny", reason="fix findings")) + assert rc == 0 + assert json.loads(out_stop) == {"decision": "continue", "reason": "fix findings"} + + out_start, rc = render_for_host("agy", HookResult(event="session_start", decision="allow", message="1 high")) + assert rc == 0 + payload = json.loads(out_start) + assert payload["injectSteps"][0]["note"] == "1 high" + + +def test_enable_recipe_for_gemini_and_antigravity(tmp_path: Path) -> None: + gem_change = enable_recipe("commit-guard", host="gemini", project_dir=tmp_path) + assert gem_change.config_path == tmp_path / ".gemini" / "settings.json" + gem_data = json.loads(gem_change.config_path.read_text(encoding="utf-8")) + assert gem_data["hooks"]["BeforeTool"][0]["hooks"][0]["timeout"] >= 60000 + + agy_change = enable_recipe("commit-guard", host="agy", project_dir=tmp_path) + assert agy_change.config_path == tmp_path / ".agents" / "hooks.json" + agy_data = json.loads(agy_change.config_path.read_text(encoding="utf-8")) + assert agy_data["hooks"]["PreToolUse"][0]["enabled"] is True + + home = tmp_path / "home" + user_agy = enable_recipe("commit-guard", host="antigravity", project_dir=tmp_path, scope="user", home_dir=home) + assert user_agy.config_path == home / ".gemini" / "config" / "hooks.json" + assert user_agy.config_path.exists() diff --git a/tests/test_automations/test_hooks_and_automations.py b/tests/test_automations/test_hooks_and_automations.py new file mode 100644 index 00000000..2e4c2d9f --- /dev/null +++ b/tests/test_automations/test_hooks_and_automations.py @@ -0,0 +1,295 @@ +"""Tests for `secfoo hook` and `secfoo automations` (#242).""" + +from __future__ import annotations + +import json +import time +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +import pytest +from typer.testing import CliRunner + +from secfoo import runner as secfoo_runner +from secfoo.automations.engine import DelegateOutcome, execute_hook +from secfoo.automations.hosts.adapters import parse_for_host, render_for_host +from secfoo.automations.hosts.base import HookResult +from secfoo.automations.manager import ( + disable_recipe, + doctor_automations, + enable_recipe, + status_automations, +) +from secfoo.automations.recipes import Recipe, load_recipes +from secfoo.cli import app + +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "hooks" +runner = CliRunner() + + +def test_builtin_recipes_load_and_never_from_repo(tmp_path: Path): + recipes = load_recipes(user_dir=tmp_path / "empty-user") + assert "commit-guard" in recipes + assert "secret-on-edit" in recipes + assert "pr-security-review" in recipes + assert recipes["commit-guard"].matches_shell("git commit -m 'ok'") + assert not recipes["commit-guard"].matches_shell("ls -la") + + +@pytest.mark.parametrize( + ("host", "fixture_rel", "expected_key"), + [ + ("claude", "claude/v1/pre_shell.json", "hookSpecificOutput"), + ("cursor", "cursor/v1/pre_shell.json", "permission"), + ], +) +def test_recorded_stdin_fixtures_parse_and_render_roundtrip( + host: str, fixture_rel: str, expected_key: str +): + raw = (FIXTURES / fixture_rel).read_text(encoding="utf-8") + payload = json.loads(raw) + event = parse_for_host(host, payload, {}) + assert event.event == "pre_shell" + assert "git commit" in event.command + + out, code = render_for_host( + host, + HookResult(decision="deny", event="pre_shell", reason="secret detected"), + ) + assert code == 0 + rendered = json.loads(out) + assert expected_key in rendered + + +def test_host_mismatch_recursion_loop_dedup_nonblocking_budget_and_fail_open(tmp_path: Path): + claude_stdin = (FIXTURES / "claude" / "v1" / "pre_shell.json").read_text(encoding="utf-8") + calls: list[str] = [] + + def failing_scan(_recipe, _event, _files) -> DelegateOutcome: + calls.append("ran") + return DelegateOutcome(passed=False, findings_count=1, summary="AWS key found") + + # 1. Host mismatch warning when CURSOR_VERSION is present but --host claude is passed + out, code, warn = execute_hook( + "commit-guard", + declared_host="claude", + stdin_text=claude_stdin, + env={"CURSOR_VERSION": "1.2.3"}, + dedup_dir=tmp_path / "dedup1", + delegate_fn=failing_scan, + ) + assert code == 0 + assert warn is not None and "cursor" in warn + assert json.loads(out)["permission"] == "deny" + assert len(calls) == 1 + + # 2. Deduplication: second call with identical recipe/session/diff skips scan + execute_hook( + "commit-guard", + declared_host="claude", + stdin_text=claude_stdin, + env={"CURSOR_VERSION": "1.2.3"}, + dedup_dir=tmp_path / "dedup1", + delegate_fn=failing_scan, + ) + assert len(calls) == 1 + + # 3. Recursion guard: SECFOO_HOOK_ACTIVE=1 skips scan + out3, _, _ = execute_hook( + "commit-guard", + declared_host="claude", + stdin_text=claude_stdin, + env={"SECFOO_HOOK_ACTIVE": "1"}, + dedup_dir=tmp_path / "dedup2", + delegate_fn=failing_scan, + ) + assert out3 == "" + assert len(calls) == 1 + + # 4. Loop guard: stop_hook_active=true returns continue without scanning + stop_payload = json.dumps({"hook_event_name": "Stop", "stop_hook_active": True}) + execute_hook( + "commit-guard", + declared_host="claude", + stdin_text=stop_payload, + env={}, + dedup_dir=tmp_path / "dedup3", + delegate_fn=failing_scan, + ) + assert len(calls) == 1 + + # 5. Non-blocking budget expiry: returns immediately (<0.3s) and spawns detached background scan + user_recipes = tmp_path / "user-recipes" + user_recipes.mkdir() + (user_recipes / "fast-timeout.toml").write_text( + 'id = "fast-timeout"\nversion = 1\nevents = ["pre_shell"]\nbudget_seconds = 0\nskills = ["sast"]\n', + encoding="utf-8", + ) + + def slow_scan(_recipe: Recipe, _event, _files) -> DelegateOutcome: + time.sleep(0.8) + return DelegateOutcome(passed=True) + + with patch("secfoo.automations.engine._spawn_background_scan") as spawn_mock: + started = time.monotonic() + out5, _, _ = execute_hook( + "fast-timeout", + declared_host="claude", + stdin_text=claude_stdin, + env={"CLAUDE_PROJECT_DIR": str(tmp_path)}, + user_recipes_dir=user_recipes, + dedup_dir=tmp_path / "dedup4", + delegate_fn=slow_scan, + ) + elapsed = time.monotonic() - started + assert elapsed < 0.4 + assert spawn_mock.called + assert "background" in out5 + + # 6. Fail-open on malformed JSON stdin + out6, code6, warn6 = execute_hook( + "commit-guard", + declared_host="claude", + stdin_text="{not valid json", + dedup_dir=tmp_path / "dedup5", + ) + assert code6 == 0 + assert out6 == "" + assert warn6 is not None + + +def test_default_delegate_runner_executes_runner_and_blocks_on_findings(tmp_path: Path): + from secfoo.automations.engine import _default_delegate_runner + from secfoo.automations.recipes import get_recipe + + recipe = get_recipe("secret-on-edit", user_dir=tmp_path / "none") + assert recipe is not None + event = parse_for_host( + "claude", + { + "hook_event_name": "PostToolUse", + "tool_name": "Write", + "tool_input": {"file_path": str(tmp_path / "app.py")}, + "cwd": str(tmp_path), + "session_id": "sess-real-runner", + }, + {}, + ) + fake_outcome = SimpleNamespace( + status="success", + critical_count=0, + high_count=1, + medium_count=0, + low_count=0, + ) + with patch.object(secfoo_runner, "execute_runs", return_value=[fake_outcome]) as run_mock: + res = _default_delegate_runner(recipe, event, [str(tmp_path / "app.py")], agent_id="codex") + assert res.passed is False + assert res.findings_count == 1 + assert "1 medium+ issue(s)" in res.summary + assert run_mock.call_args.kwargs["agent_id"] == "codex" + + +@pytest.mark.parametrize("bad_status", ["failed", "timeout", "binary_not_found", "not_configured"]) +def test_incomplete_run_status_warns_instead_of_reporting_clean(tmp_path: Path, bad_status: str): + from secfoo.automations.engine import _evaluate_outcomes + from secfoo.automations.recipes import get_recipe + + recipe = get_recipe("commit-guard", user_dir=tmp_path / "none") + assert recipe is not None + outcome = _evaluate_outcomes( + [{"status": bad_status, "severity": {"critical": 0, "high": 0, "medium": 0, "low": 0}}], + recipe, + ["app.py"], + ) + assert outcome.passed is False + assert outcome.incomplete is True + assert f"secfoo scan did not complete: {bad_status}" in outcome.summary + + +def test_agent_resolution_uses_cli_recipe_and_config_default(tmp_path: Path, monkeypatch): + from secfoo.automations.engine import _resolve_hook_agent + + r_default = Recipe(id="r1", version=1, description="", skills=("sast",), events=("pre_shell",)) + r_custom = Recipe(id="r2", version=1, description="", skills=("sast",), events=("pre_shell",), agent="cursor") + monkeypatch.setattr("secfoo.settings.load_config", lambda: SimpleNamespace(defaults=SimpleNamespace(agent="gemini"))) + + assert _resolve_hook_agent(r_default, None) == "gemini" + assert _resolve_hook_agent(r_custom, None) == "cursor" + assert _resolve_hook_agent(r_custom, "claude") == "claude" + + +def test_subprocess_timeout_returns_immediately_without_blocking_interpreter(tmp_path: Path): + import subprocess + import sys + + from secfoo.automations.engine import _run_subprocess_with_budget + + recipe = Recipe( + id="slow", + version=1, + description="", + skills=("sast",), + events=("pre_shell",), + budget_seconds=0, + ) + started = time.monotonic() + with patch( + "secfoo.automations.engine._build_detached_run_argv", + return_value=[sys.executable, "-c", "import time; time.sleep(3)"], + ): + outcome, timed_out = _run_subprocess_with_budget( + recipe, str(tmp_path), ["a.py"], agent_id="claude", budget_seconds=0.15 + ) + elapsed = time.monotonic() - started + assert timed_out is True + assert outcome is None + assert elapsed < 1.0 + # Verify a child Python process running execute_hook exits immediately too (no atexit thread join) + script = ( + "import sys, time; from unittest.mock import patch; " + "from secfoo.automations.engine import _run_subprocess_with_budget; " + "from secfoo.automations.recipes import Recipe; " + "r = Recipe(id='s', version=1, description='', skills=('sast',), events=('pre_shell',), budget_seconds=0); " + "p = patch('secfoo.automations.engine._build_detached_run_argv', return_value=[sys.executable, '-c', 'import time; time.sleep(3)']); " + "p.start(); _run_subprocess_with_budget(r, '.', ['a.py'], agent_id='claude', budget_seconds=0.1); p.stop()" + ) + t0 = time.monotonic() + proc = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=10, check=False) + assert proc.returncode == 0, proc.stderr + assert (time.monotonic() - t0) < 1.5 + + +def test_automations_enable_disable_idempotent_dry_run_and_cli(tmp_path: Path): + claude_cfg = tmp_path / ".claude" / "settings.json" + claude_cfg.parent.mkdir(parents=True) + claude_cfg.write_text(json.dumps({"unrelatedKey": "keep-me"}), encoding="utf-8") + + # Dry-run writes nothing + dry = enable_recipe("commit-guard", host="claude", project_dir=tmp_path, dry_run=True) + assert dry.changed is True + assert "hooks" not in json.loads(claude_cfg.read_text(encoding="utf-8")) + + # Enable is idempotent and preserves unrelated keys + first = enable_recipe("commit-guard", host="claude", project_dir=tmp_path) + second = enable_recipe("commit-guard", host="claude", project_dir=tmp_path) + assert first.changed is True + assert second.changed is False + saved = json.loads(claude_cfg.read_text(encoding="utf-8")) + assert saved["unrelatedKey"] == "keep-me" + assert len(saved["hooks"]["PreToolUse"]) == 1 + + assert len(status_automations(tmp_path)) == 1 + assert doctor_automations(tmp_path) == [] + + # Disable removes only secfoo hook + dis = disable_recipe("commit-guard", host="claude", project_dir=tmp_path) + assert dis.changed is True + assert status_automations(tmp_path) == [] + assert json.loads(claude_cfg.read_text(encoding="utf-8"))["unrelatedKey"] == "keep-me" + + # CLI smoke test + res = runner.invoke(app, ["automations", "list"]) + assert res.exit_code == 0 + assert "commit-guard" in res.output