diff --git a/docs/KIRO_CLINE_AUTOMATIONS.md b/docs/KIRO_CLINE_AUTOMATIONS.md new file mode 100644 index 00000000..881bfe53 --- /dev/null +++ b/docs/KIRO_CLINE_AUTOMATIONS.md @@ -0,0 +1,13 @@ +# Kiro and Cline Automations (#251) + +## Kiro (IDE & CLI) + +- **Config:** `.kiro/hooks/secfoo-.json` (workspace) or `~/.kiro/hooks/secfoo-.json` (user), using `"version": "v1"` and explicit `timeout` (default 60 s). +- **Triggers:** Supports `PreToolUse`, `PostToolUse`, `FileSave` / `PostFileSave`, `AgentStop`, `SessionStart`, and `SessionEnd`. +- **Debouncing:** `should_run_debounced(...)` prevents duplicate `FileSave` runs within the debounce window. + +## Cline + +- **Config:** `.clinerules/hooks/` (project) or `~/Documents/Cline/Hooks/` (user). +- **Activation:** Hook scripts are written executable (`0755`) and must be enabled in the **Cline Hooks tab**. +- **Events & Payloads:** Supports `PreToolUse`, `PostToolUse` (both `.postToolUse.toolName` and `.postToolUse.tool`), `TaskComplete`, `TaskCancel`, and `UserPromptSubmit`. 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/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..28dfb981 --- /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 claude, cline, kiro +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 == "kiro": + return kiro.parse(stdin_json, env) + if host == "cline": + return cline.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 in ("gemini", "antigravity"): + return _render_decision(result) + if host == "kiro": + return kiro.render(result) + if host == "cline": + return cline.render(result) + return claude.render(result) 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/cline.py b/src/secfoo/automations/hosts/cline.py new file mode 100644 index 00000000..99aaa0aa --- /dev/null +++ b/src/secfoo/automations/hosts/cline.py @@ -0,0 +1,76 @@ +"""Cline hook host adapter (#251).""" + +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", + "TaskComplete": "stop", + "TaskCancel": "session_end", + "UserPromptSubmit": "user_prompt_submit", +} + + +def parse(stdin_json: Mapping[str, Any], env: Mapping[str, str]) -> HookEvent: + """Parse Cline hook payload (supporting both toolName and tool sample variants).""" + raw_event = str(stdin_json.get("hookName") or stdin_json.get("hook_event_name") or "") + norm_event = _EVENT_MAP.get(raw_event, raw_event.lower() or "unknown") + + nested = stdin_json.get("preToolUse") or stdin_json.get("postToolUse") or {} + if not isinstance(nested, Mapping): + nested = {} + + tool_name = str(nested.get("toolName") or nested.get("tool") or stdin_json.get("toolName") or "") + params = nested.get("parameters") + if not isinstance(params, Mapping): + params = {} + + command = str(params.get("command") or stdin_json.get("command") or "") + edited: list[str] = [] + for key in ("path", "file_path", "target_file"): + val = params.get(key) or stdin_json.get(key) + if isinstance(val, str) and val.strip(): + edited.append(val.strip()) + + task_meta = stdin_json.get("taskMetadata") + session_id = "" + if isinstance(task_meta, Mapping): + session_id = str(task_meta.get("taskId") or "") + if not session_id: + session_id = str(stdin_json.get("taskId") or "") + + roots: list[str] = [] + if env.get("CLINE_PROJECT_DIR"): + roots.append(str(env["CLINE_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=session_id, + workspace_roots=tuple(dict.fromkeys(roots)), + loop_active=bool(stdin_json.get("stop_hook_active", False)), + host_version=str(env.get("CLINE_VERSION") or ""), + ) + + +def render(result: HookResult) -> tuple[str, int]: + """Render HookResult into Cline hook JSON (`cancel: true` or `contextModification`).""" + if result.decision == "deny": + reason = result.reason or result.message or "Blocked by secfoo" + if result.event in ("pre_shell", "post_edit"): + return json.dumps({"cancel": True, "errorMessage": reason}), 0 + return json.dumps({"contextModification": reason}), 0 + + if result.message or result.reason: + return json.dumps({"contextModification": result.message or result.reason}), 0 + return json.dumps({"cancel": False}), 0 diff --git a/src/secfoo/automations/hosts/kiro.py b/src/secfoo/automations/hosts/kiro.py new file mode 100644 index 00000000..6bdb9f93 --- /dev/null +++ b/src/secfoo/automations/hosts/kiro.py @@ -0,0 +1,71 @@ +"""Kiro IDE and CLI hook host adapter (#251).""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from secfoo.automations.hosts.base import HookEvent, HookResult + +_EVENT_MAP = { + "PreToolUse": "pre_shell", + "preToolUse": "pre_shell", + "PostToolUse": "post_edit", + "postToolUse": "post_edit", + "FileSave": "file_save", + "PostFileSave": "file_save", + "fileSave": "file_save", + "AgentStop": "stop", + "agentStop": "stop", + "SessionStart": "session_start", + "sessionStart": "session_start", + "SessionEnd": "session_end", + "sessionEnd": "session_end", +} + + +def parse(stdin_json: Mapping[str, Any], env: Mapping[str, str]) -> HookEvent: + """Parse Kiro hook payload.""" + raw_event = str(stdin_json.get("trigger") or 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 stdin_json.get("toolName") or "") + + tool_input = stdin_json.get("tool_input") + if not isinstance(tool_input, Mapping): + tool_input = {} + + command = str(tool_input.get("command") or stdin_json.get("command") or "") + edited: list[str] = [] + for key in ("file_path", "filePath", "path", "target_file"): + val = tool_input.get(key) or stdin_json.get(key) + if isinstance(val, str) and val.strip(): + edited.append(val.strip()) + if isinstance(stdin_json.get("files"), list): + edited.extend(str(p) for p in stdin_json["files"] if isinstance(p, str)) + + roots: list[str] = [] + if env.get("KIRO_PROJECT_DIR"): + roots.append(str(env["KIRO_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 stdin_json.get("sessionId") or ""), + workspace_roots=tuple(dict.fromkeys(roots)), + loop_active=bool(stdin_json.get("stop_hook_active", False)), + host_version=str(env.get("KIRO_VERSION") or ""), + ) + + +def render(result: HookResult) -> tuple[str, int]: + """Render HookResult for Kiro (exit 2 blocks PreToolUse; stdout feeds agent context).""" + if result.decision == "deny": + reason = result.reason or result.message or "Blocked by secfoo" + if result.event == "pre_shell": + return reason, 2 + return reason, 0 + return (result.message or result.reason or ""), 0 diff --git a/src/secfoo/automations/manager.py b/src/secfoo/automations/manager.py new file mode 100644 index 00000000..f2b5c43c --- /dev/null +++ b/src/secfoo/automations/manager.py @@ -0,0 +1,287 @@ +"""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/hooks.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"), + "cline": (".clinerules/hooks/PreToolUse", "PreToolUse"), +} + + +@dataclass(frozen=True) +class AutomationChange: + recipe_id: str + host: str + config_path: Path + changed: bool + dry_run: bool + action: str # "enabled" | "disabled" | "unchanged" + note: str = "" + + +def should_run_debounced( + key: str, + *, + window_seconds: float = 5.0, + state_dir: Path | None = None, + now: float | None = None, +) -> bool: + """Return True if *key* has not fired within *window_seconds* (File Save debounce).""" + import hashlib + import time + + ts = time.time() if now is None else now + base = state_dir if state_dir is not None else Path(".secfoo/debounce") + base.mkdir(parents=True, exist_ok=True) + stamp = base / f"{hashlib.sha256(key.encode('utf-8')).hexdigest()[:16]}.ts" + if stamp.is_file(): + try: + prev = float(stamp.read_text(encoding="utf-8").strip()) + if (ts - prev) < window_seconds: + return False + except ValueError: + # Corrupted debounce timestamp; overwrite it below. + stamp.unlink(missing_ok=True) + stamp.write_text(str(ts), encoding="utf-8") + return True + + +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" + 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: + 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] + cmd = _hook_command(recipe_id, host) + timeout_s = max(recipe.budget_seconds + 30, 60) + + if host == "kiro": + base = (home_dir if home_dir is not None else Path.home()) / ".kiro" / "hooks" if scope == "user" else project_dir / ".kiro" / "hooks" + cfg_path = base / f"secfoo-{recipe_id}.json" + if cfg_path.is_file(): + return AutomationChange(recipe_id, host, cfg_path, False, dry_run, "unchanged") + trigger = "FileSave" if "post_edit" in recipe.events else ("AgentStop" if "stop" in recipe.events else "PreToolUse") + payload = { + "version": "v1", + "hooks": [ + { + "name": f"secfoo-{recipe_id}", + "trigger": trigger, + "matcher": "*" if trigger == "FileSave" else "Bash", + "action": {"type": "command", "command": cmd}, + "timeout": timeout_s, + "enabled": True, + } + ], + } + if not dry_run: + _write_json_atomic(cfg_path, payload) + return AutomationChange(recipe_id, host, cfg_path, True, dry_run, "enabled") + + if host == "cline": + event_name = "PostToolUse" if "post_edit" in recipe.events else ("TaskComplete" if "stop" in recipe.events else "PreToolUse") + base = (home_dir if home_dir is not None else Path.home()) / "Documents" / "Cline" / "Hooks" if scope == "user" else project_dir / ".clinerules" / "hooks" + cfg_path = base / event_name + if cfg_path.is_file() and cmd in cfg_path.read_text(encoding="utf-8"): + return AutomationChange(recipe_id, host, cfg_path, False, dry_run, "unchanged") + script = f"#!/usr/bin/env sh\nexec {cmd}\n" + if not dry_run: + cfg_path.parent.mkdir(parents=True, exist_ok=True) + cfg_path.write_text(script, encoding="utf-8") + cfg_path.chmod(0o755) + return AutomationChange( + recipe_id, + host, + cfg_path, + True, + dry_run, + "enabled", + note="Enable hooks in the Cline Hooks tab so this script runs.", + ) + + 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 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 + if host == "cline": + if "secfoo hook " in cfg_path.read_text(encoding="utf-8"): + found.append({"host": host, "event": cfg_path.name, "path": str(cfg_path)}) + 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 + if host == "cline": + 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/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/cline/post_tool_use.json b/tests/fixtures/hooks/cline/post_tool_use.json new file mode 100644 index 00000000..e4db0c06 --- /dev/null +++ b/tests/fixtures/hooks/cline/post_tool_use.json @@ -0,0 +1,13 @@ +{ + "hookName": "PostToolUse", + "postToolUse": { + "tool": "write_to_file", + "parameters": { + "path": "src/main.ts" + } + }, + "taskMetadata": { + "taskId": "cline-task-2" + }, + "cwd": "/repo" +} diff --git a/tests/fixtures/hooks/cline/pre_tool_use.json b/tests/fixtures/hooks/cline/pre_tool_use.json new file mode 100644 index 00000000..50cc9610 --- /dev/null +++ b/tests/fixtures/hooks/cline/pre_tool_use.json @@ -0,0 +1,13 @@ +{ + "hookName": "PreToolUse", + "preToolUse": { + "toolName": "execute_command", + "parameters": { + "command": "git commit -m 'wip'" + } + }, + "taskMetadata": { + "taskId": "cline-task-1" + }, + "cwd": "/repo" +} diff --git a/tests/fixtures/hooks/cline/task_complete.json b/tests/fixtures/hooks/cline/task_complete.json new file mode 100644 index 00000000..49343d5b --- /dev/null +++ b/tests/fixtures/hooks/cline/task_complete.json @@ -0,0 +1,7 @@ +{ + "hookName": "TaskComplete", + "taskMetadata": { + "taskId": "cline-task-3" + }, + "cwd": "/repo" +} 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/kiro/agent_stop.json b/tests/fixtures/hooks/kiro/agent_stop.json new file mode 100644 index 00000000..6552c63d --- /dev/null +++ b/tests/fixtures/hooks/kiro/agent_stop.json @@ -0,0 +1,5 @@ +{ + "trigger": "AgentStop", + "cwd": "/repo", + "session_id": "kiro-sess-3" +} diff --git a/tests/fixtures/hooks/kiro/file_save.json b/tests/fixtures/hooks/kiro/file_save.json new file mode 100644 index 00000000..4beb8fa6 --- /dev/null +++ b/tests/fixtures/hooks/kiro/file_save.json @@ -0,0 +1,6 @@ +{ + "trigger": "FileSave", + "files": ["package-lock.json", "src/app.ts"], + "cwd": "/repo", + "session_id": "kiro-sess-2" +} diff --git a/tests/fixtures/hooks/kiro/pre_tool_use.json b/tests/fixtures/hooks/kiro/pre_tool_use.json new file mode 100644 index 00000000..5d34270b --- /dev/null +++ b/tests/fixtures/hooks/kiro/pre_tool_use.json @@ -0,0 +1,9 @@ +{ + "trigger": "PreToolUse", + "tool_name": "Bash", + "tool_input": { + "command": "git commit -m 'wip'" + }, + "cwd": "/repo", + "session_id": "kiro-sess-1" +} 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 diff --git a/tests/test_automations/test_kiro_cline_automations.py b/tests/test_automations/test_kiro_cline_automations.py new file mode 100644 index 00000000..9b1a1511 --- /dev/null +++ b/tests/test_automations/test_kiro_cline_automations.py @@ -0,0 +1,83 @@ +"""Tests for Kiro and Cline hook adapters, debounce, and config writers (#251).""" + +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, should_run_debounced + +KIRO_FIXTURES = Path(__file__).resolve().parent.parent / "fixtures" / "hooks" / "kiro" +CLINE_FIXTURES = Path(__file__).resolve().parent.parent / "fixtures" / "hooks" / "cline" + + +def _load(base: Path, name: str) -> dict: + return json.loads((base / name).read_text(encoding="utf-8")) + + +def test_kiro_parse_render_and_debounce(tmp_path: Path) -> None: + pre = parse_for_host("kiro", _load(KIRO_FIXTURES, "pre_tool_use.json"), {"KIRO_VERSION": "3.4.0"}) + assert pre.event == "pre_shell" + assert pre.command == "git commit -m 'wip'" + assert pre.host_version == "3.4.0" + + fsave = parse_for_host("kiro", _load(KIRO_FIXTURES, "file_save.json"), {"KIRO_PROJECT_DIR": "/ws"}) + assert fsave.event == "file_save" + assert fsave.edited_paths == ("package-lock.json", "src/app.ts") + assert fsave.workspace_roots == ("/ws", "/repo") + + stop = parse_for_host("kiro", _load(KIRO_FIXTURES, "agent_stop.json"), {}) + assert stop.event == "stop" + + out_deny, rc = render_for_host("kiro", HookResult(event="pre_shell", decision="deny", reason="blocked")) + assert rc == 2 + assert out_deny == "blocked" + + out_ctx, rc = render_for_host("kiro", HookResult(event="stop", decision="allow", message="2 findings")) + assert rc == 0 + assert out_ctx == "2 findings" + + # Debounce checks + assert should_run_debounced("kiro:file_save", window_seconds=5.0, state_dir=tmp_path, now=100.0) is True + assert should_run_debounced("kiro:file_save", window_seconds=5.0, state_dir=tmp_path, now=102.0) is False + assert should_run_debounced("kiro:file_save", window_seconds=5.0, state_dir=tmp_path, now=106.0) is True + + +def test_cline_parse_and_render() -> None: + pre = parse_for_host("cline", _load(CLINE_FIXTURES, "pre_tool_use.json"), {"CLINE_VERSION": "3.1.0"}) + assert pre.event == "pre_shell" + assert pre.tool_name == "execute_command" + assert pre.command == "git commit -m 'wip'" + assert pre.session_id == "cline-task-1" + assert pre.host_version == "3.1.0" + + post = parse_for_host("cline", _load(CLINE_FIXTURES, "post_tool_use.json"), {}) + assert post.event == "post_edit" + assert post.tool_name == "write_to_file" + assert post.edited_paths == ("src/main.ts",) + + done = parse_for_host("cline", _load(CLINE_FIXTURES, "task_complete.json"), {}) + assert done.event == "stop" + + out_cancel, rc = render_for_host("cline", HookResult(event="pre_shell", decision="deny", reason="dangerous cmd")) + assert rc == 0 + assert json.loads(out_cancel) == {"cancel": True, "errorMessage": "dangerous cmd"} + + out_ctx, rc = render_for_host("cline", HookResult(event="stop", decision="allow", message="1 high")) + assert rc == 0 + assert json.loads(out_ctx) == {"contextModification": "1 high"} + + +def test_enable_recipe_for_kiro_and_cline(tmp_path: Path) -> None: + kiro_change = enable_recipe("commit-guard", host="kiro", project_dir=tmp_path) + assert kiro_change.config_path == tmp_path / ".kiro" / "hooks" / "secfoo-commit-guard.json" + kiro_data = json.loads(kiro_change.config_path.read_text(encoding="utf-8")) + assert kiro_data["version"] == "v1" + assert kiro_data["hooks"][0]["trigger"] == "PreToolUse" + + cline_change = enable_recipe("commit-guard", host="cline", project_dir=tmp_path) + assert cline_change.config_path == tmp_path / ".clinerules" / "hooks" / "PreToolUse" + assert "Hooks tab" in cline_change.note + assert "secfoo hook commit-guard --host cline" in cline_change.config_path.read_text(encoding="utf-8")