From cd4bdf62f6c7f234af7b5ba2dc4d169758205feb Mon Sep 17 00:00:00 2001 From: SriRamKunamsetty Date: Sun, 6 Dec 2026 18:53:00 +0530 Subject: [PATCH] feat(cloud): add trigger provenance, outcome reporting, outbox, and env-var key (#241) --- docs/REFERENCE.md | 29 ++ src/secfoo/cli.py | 73 ++++- src/secfoo/cloud.py | 277 ++++++++++++++--- src/secfoo/runner.py | 50 ++- src/secfoo/storage/models.py | 6 + src/secfoo/storage/repository.py | 121 ++++++-- src/secfoo/storage/schema.sql | 9 +- src/secfoo/web/routes/projects.py | 23 +- src/secfoo/web/templates/project.html | 27 +- src/secfoo/web/templates/run_detail.html | 12 + tests/test_automation_reporting.py | 370 +++++++++++++++++++++++ 11 files changed, 920 insertions(+), 77 deletions(-) create mode 100644 tests/test_automation_reporting.py diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index cfff1ddf..ec7a838a 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -784,6 +784,35 @@ required on every route, the `Host` check and rate limits still apply, and the key still crosses the network in clear text, so anyone on that network can read it. +## Cloud reporting, trigger provenance, and outbox + +Every run is saved locally first, and pushed to the enterprise portal when an +ingest key (`sfc_ingest_...`) is configured: + +- **Credentials:** Environment variables take precedence over + `~/.secfoo/cloud.toml` (`secfoo cloud login`): `SECFOO_API_KEY`, then + `SECFOO_API_KEY_FILE`, then `SECFOO_CLOUD_API_KEY` (legacy alias), paired + with `SECFOO_SERVER` (or `SECFOO_CLOUD_PORTAL_URL` alias). View keys + (`sfc_view_...`) are strictly refused from uploading and raw keys are + redacted from logs, `--json`, and stored errors. +- **Trigger provenance:** Each run carries a `trigger` object + (`source`, `host`, `host_version`, `recipe`, `recipe_version`, `event`, + `mode`, `decision`, and a per-install salted SHA-256 `session_ref`). Raw + hook payloads (`user_email`, `transcript_path`, prompts, tool arguments, or + file contents) are never sent. +- **Outcome statuses:** In addition to `success`, `failed`, `timeout`, + `binary_not_found`, and `not_configured`, runs may end as `skipped` (nothing in + scope) or `not_submitted` (host-mode run never completed). Non-success runs + never mutate local or portal findings state and are pushed when + `GET /api/v1/whoami` advertises `"capabilities": ["run_outcomes_v1"]` + (otherwise only `success` runs upload). +- **Outbox & visibility:** Failed uploads record `sync_attempts`, + `last_sync_error`, and exponential-backoff `next_sync_at`, and are retried + opportunistically at CLI startup (within a 2 s budget, only when queued runs + are ready) or via `secfoo cloud sync`. `secfoo run --json` includes + `"cloud": {"state", "error"}` and `secfoo cloud status` groups queued runs by + error reason. + ## Install Pick whichever fits how you work — they're all the same tool underneath. diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 11aa9ed0..50ab77e8 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -99,14 +99,34 @@ def _show_version(value: bool) -> None: raise typer.Exit() +def _opportunistic_outbox_flush() -> None: + """Flush queued portal runs quickly at CLI startup without touching network when empty (#241).""" + from secfoo.storage import repository as repo_mod + + try: + if not Path(repo_mod.DB_PATH).is_file(): + return + with RunRepository() as repo: + if not hasattr(repo, "list_unsynced_runs"): + return + if not repo.list_unsynced_runs(limit=1, include_all_outcomes=True, respect_backoff=True): + return + cloud_module.flush_outbox(repo, time_budget_seconds=2.0, max_runs=10) + except Exception: # noqa: BLE001 -- opportunistic startup flush must never affect CLI exit code or output + return + + @app.callback() def _root( + ctx: typer.Context, version: Annotated[ bool, typer.Option("--version", "-V", is_eager=True, callback=_show_version, help="Show the installed version and exit."), ] = False, ) -> None: """AI security review CLI: SAST, secret scanning, SCA, threat modeling and architecture review.""" + if ctx.invoked_subcommand not in {None, "cloud", "hook", "version"}: + _opportunistic_outbox_flush() @app.command() @@ -801,6 +821,10 @@ def handle_complete(skill_name: str, result_status: str) -> None: {"source": c.source, "type": c.type, "reached": c.reached, "notes": c.notes} for c in o.context_sources ], + "cloud": { + "state": o.cloud_state, + "error": o.cloud_error, + }, } for o in outcomes ], @@ -1947,35 +1971,65 @@ def cloud_logout() -> None: @cloud_app.command(name="status") def cloud_status() -> None: """Show portal connection status and how many local runs are unsynced.""" - config = cloud_module.load_cloud_config() + try: + config = cloud_module.load_cloud_config() + except CloudError as exc: + err_console.print(f"[yellow]Cloud configuration refused:[/] {cloud_module.redact_secret(str(exc))}") + return if config is None: console.print("Not connected. Run [bold]secfoo cloud login --api-key [/] to connect.") return with RunRepository() as repo: - unsynced = repo.list_unsynced_runs() + unsynced = repo.list_unsynced_runs(include_all_outcomes=True) + + grouped_errors: dict[str, int] = {} + for item in unsynced: + if item.last_sync_error: + grouped_errors[item.last_sync_error] = grouped_errors.get(item.last_sync_error, 0) + 1 try: info = cloud_module.whoami(config) except CloudError as exc: - err_console.print(f"[yellow]Connected to {config.portal_url}, but couldn't reach it just now:[/] {exc}") + err_console.print( + f"[yellow]Connected to {config.portal_url}, but couldn't reach it just now:[/] " + f"{cloud_module.redact_secret(str(exc), config.api_key)}" + ) console.print(f"Unsynced local runs: {len(unsynced)}") + for err, count in grouped_errors.items(): + console.print(f" Queued ({count}): {err}") return console.print(f"Connected to [bold]{info.get('tenant_display_name', info.get('tenant_slug'))}[/] at {config.portal_url}.") console.print(f"Unsynced local runs: {len(unsynced)}") + for err, count in grouped_errors.items(): + console.print(f" Queued ({count}): {err}") @cloud_app.command(name="sync") def cloud_sync() -> None: """Push any local runs not yet synced to the portal.""" - config = cloud_module.load_cloud_config() + try: + config = cloud_module.load_cloud_config() + except CloudError as exc: + err_console.print(f"[red]Cloud sync refused:[/] {cloud_module.redact_secret(str(exc))}") + raise typer.Exit(code=1) from exc if config is None: err_console.print("[yellow]Not connected.[/] Run [bold]secfoo cloud login --api-key [/] first.") raise typer.Exit(code=1) + try: + info = cloud_module.whoami(config) + except CloudError as exc: + err_console.print( + f"[yellow]Failed to verify portal connection:[/] " + f"{cloud_module.redact_secret(str(exc), config.api_key)}" + ) + raise typer.Exit(code=1) from exc + + supports_all = cloud_module.portal_supports_all_outcomes(info) with RunRepository() as repo: - unsynced = repo.list_unsynced_runs() + unsynced = repo.list_unsynced_runs(include_all_outcomes=supports_all) if not unsynced: console.print("Nothing to sync -- every local run is already synced.") return @@ -1983,10 +2037,15 @@ def cloud_sync() -> None: synced_count = 0 for run in unsynced: try: - cloud_module.sync_run(repo, run.run_uuid, config) + cloud_module.sync_run(repo, run.run_uuid, config, identity=info) synced_count += 1 + except cloud_module.CapabilityUnsupportedError: + continue except CloudError as exc: - err_console.print(f"[yellow]Failed to sync {run.run_uuid}:[/] {exc}") + err_console.print( + f"[yellow]Failed to sync {run.run_uuid}:[/] " + f"{cloud_module.redact_secret(str(exc), config.api_key)}" + ) console.print(f"Synced {synced_count}/{len(unsynced)} run(s).") diff --git a/src/secfoo/cloud.py b/src/secfoo/cloud.py index c5c855e1..a9de0833 100644 --- a/src/secfoo/cloud.py +++ b/src/secfoo/cloud.py @@ -14,14 +14,19 @@ from __future__ import annotations +import hashlib import json import os import re +import secrets import sys +import time import urllib.error import urllib.request from dataclasses import dataclass +from datetime import datetime, timedelta, timezone from pathlib import Path +from typing import Any from urllib.parse import urlsplit if sys.version_info >= (3, 11): @@ -29,31 +34,89 @@ else: import tomli as tomllib -from secfoo.config import CLOUD_CONFIG_PATH, write_private_text +from secfoo.config import CLOUD_CONFIG_PATH, STORE_DIR, write_private_text from secfoo.egress import PORTAL_HOST, EgressError, require_origin from secfoo.storage.models import AssessmentRecord, RunRecord from secfoo.storage.repository import RunRepository DEFAULT_PORTAL_URL = "https://app.secfoo.com" REQUEST_TIMEOUT_SECONDS = 15 +CAPABILITY_RUN_OUTCOMES = "run_outcomes_v1" # Portal keys are `sfc_ingest_` or `sfc_view_` plus url-safe token material. # Sync may use only the ingest form. # A view key logs into the browser and must never upload a report. _INGEST_KEY_RE = re.compile(r"^sfc_ingest_[A-Za-z0-9_-]+$") _VIEW_KEY_RE = re.compile(r"^sfc_view_[A-Za-z0-9_-]+$") +_ANY_KEY_RE = re.compile(r"sfc_(?:ingest|view)_[A-Za-z0-9_-]+") class CloudError(RuntimeError): pass +class CapabilityUnsupportedError(CloudError): + """Raised when attempting to push a non-success run to a portal without `run_outcomes_v1`.""" + + @dataclass(frozen=True) class CloudConfig: api_key: str portal_url: str = DEFAULT_PORTAL_URL +@dataclass(frozen=True) +class OutboxFlushSummary: + attempted: int + synced: int + failed: int + state: str # synced | queued | local_only | refused + error: str | None = None + + +def redact_secret(text: str, secret: str | None = None) -> str: + """Scrub portal API keys from user-facing messages and stored sync errors (#241).""" + out = str(text or "") + if secret: + out = out.replace(secret, "[REDACTED_KEY]") + return _ANY_KEY_RE.sub("[REDACTED_KEY]", out) + + +def sanitize_trigger(trigger: dict[str, Any] | None) -> dict[str, Any]: + """Build strictly scoped `trigger` provenance dict, dropping any hook payload secrets.""" + raw = trigger if isinstance(trigger, dict) else {} + return { + "source": raw.get("source") or "cli", + "host": raw.get("host"), + "host_version": raw.get("host_version"), + "recipe": raw.get("recipe"), + "recipe_version": raw.get("recipe_version"), + "event": raw.get("event") or ("manual" if (raw.get("source") or "cli") == "cli" else None), + "mode": raw.get("mode"), + "decision": raw.get("decision") or "none", + "session_ref": raw.get("session_ref"), + } + + +def hash_session_ref(session_id: str | None, *, salt_path: Path | None = None) -> str | None: + """Return salted SHA-256 of host session ID so raw session IDs never leave the machine (#241).""" + clean = (session_id or "").strip() + if not clean: + return None + target = salt_path or (STORE_DIR / "install_salt") + try: + if target.is_file(): + salt = target.read_text(encoding="utf-8").strip() + else: + salt = "" + if not salt: + salt = secrets.token_hex(32) + write_private_text(target, salt + "\n") + except OSError: + salt = "ephemeral" + return hashlib.sha256(f"{salt}:{clean}".encode()).hexdigest() + + def key_kind(api_key: str) -> str | None: """`ingest`, `view`, or None when the string is not a portal key.""" key = (api_key or "").strip() @@ -81,8 +144,26 @@ def _toml_escape(value: str) -> str: def _env_credentials() -> tuple[str | None, str]: - key = (os.environ.get("SECFOO_CLOUD_API_KEY") or "").strip() or None - portal = (os.environ.get("SECFOO_CLOUD_PORTAL_URL") or "").strip() or DEFAULT_PORTAL_URL + """Read cloud credentials from env with one unified precedence order (#241). + + Key order: `SECFOO_API_KEY` -> `SECFOO_API_KEY_FILE` -> `SECFOO_CLOUD_API_KEY` (alias). + Portal order: `SECFOO_SERVER` -> `SECFOO_CLOUD_PORTAL_URL` (alias) -> `DEFAULT_PORTAL_URL`. + """ + key = (os.environ.get("SECFOO_API_KEY") or "").strip() or None + if key is None: + key_file = (os.environ.get("SECFOO_API_KEY_FILE") or "").strip() + if key_file: + try: + key = Path(key_file).expanduser().read_text(encoding="utf-8").strip() or None + except OSError as exc: + raise CloudError(f"Could not read SECFOO_API_KEY_FILE: {exc}") from exc + if key is None: + key = (os.environ.get("SECFOO_CLOUD_API_KEY") or "").strip() or None + portal = ( + (os.environ.get("SECFOO_SERVER") or "").strip() + or (os.environ.get("SECFOO_CLOUD_PORTAL_URL") or "").strip() + or DEFAULT_PORTAL_URL + ) return key, portal @@ -91,9 +172,10 @@ def load_cloud_config(path: Path | None = None) -> CloudConfig | None: optional/additive) -- callers treat that as "not logged in", not an error. - When `path` is omitted, `SECFOO_CLOUD_API_KEY` (plus optional - `SECFOO_CLOUD_PORTAL_URL`) takes precedence over `~/.secfoo/cloud.toml` - so CLI runs, `runner.py`, and `secfoo mcp serve` share one config source. + When `path` is omitted, env vars (`SECFOO_API_KEY`, `SECFOO_API_KEY_FILE`, or + `SECFOO_CLOUD_API_KEY` alias, plus optional `SECFOO_SERVER` / + `SECFOO_CLOUD_PORTAL_URL`) take precedence over `~/.secfoo/cloud.toml` so + CLI runs, `runner.py`, and `secfoo mcp serve` share one config source. """ if path is None: env_key, env_portal = _env_credentials() @@ -124,7 +206,10 @@ def resolve_cloud_status(path: Path | None = None) -> tuple[CloudConfig | None, Returns `(ingest_config_or_none, status_dict)` where `uploads_enabled` is True strictly for valid `sfc_ingest_*` keys. """ - raw_key, raw_url = _env_credentials() + try: + raw_key, raw_url = _env_credentials() + except CloudError: + raw_key, raw_url = None, DEFAULT_PORTAL_URL if raw_key is None: target = path or CLOUD_CONFIG_PATH if target.exists(): @@ -191,7 +276,7 @@ def _portal_origin(url: str) -> str: raise CloudError(str(exc)) from exc -def _request(url: str, *, api_key: str, payload: dict | None = None) -> dict: +def _request(url: str, *, api_key: str, payload: dict | None = None, timeout: float | None = None) -> dict: parts = urlsplit(url) url = _portal_origin(f"{parts.scheme}://{parts.netloc}") + (parts.path or "") headers = {"Authorization": f"Bearer {api_key}"} @@ -201,21 +286,35 @@ def _request(url: str, *, api_key: str, payload: dict | None = None) -> dict: headers["Content-Type"] = "application/json" request = urllib.request.Request(url, data=data, headers=headers) # nosec B310 -- user-configured portal URL try: - with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: # nosec B310 -- user-configured portal URL, same trust as MCP settings + effective_timeout = REQUEST_TIMEOUT_SECONDS if timeout is None else max(0.1, float(timeout)) + with urllib.request.urlopen(request, timeout=effective_timeout) as response: # nosec B310 -- user-configured portal URL, same trust as MCP settings return json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as exc: - detail = exc.read().decode("utf-8", errors="replace") + detail = redact_secret(exc.read().decode("utf-8", errors="replace"), api_key) raise CloudError(f"Portal returned {exc.code}: {detail or exc.reason}") from exc except urllib.error.URLError as exc: - raise CloudError(f"Could not reach the portal: {exc.reason}") from exc + raise CloudError(f"Could not reach the portal: {redact_secret(str(exc.reason), api_key)}") from exc + except TimeoutError as exc: + raise CloudError("Could not reach the portal: timed out") from exc + except OSError as exc: + raise CloudError(f"Could not reach the portal: {redact_secret(str(exc), api_key)}") from exc -def whoami(config: CloudConfig) -> dict: +def whoami(config: CloudConfig, *, timeout: float | None = None) -> dict: """Validates a key against the portal -- used interactively by `secfoo cloud login`/`status`, where a failure should be reported to the user, unlike push_run's silent-failure contract. """ - return _request(f"{config.portal_url.rstrip('/')}/api/v1/whoami", api_key=config.api_key) + return _request( + f"{config.portal_url.rstrip('/')}/api/v1/whoami", + api_key=config.api_key, + timeout=timeout, + ) + + +def portal_supports_all_outcomes(identity: dict[str, Any] | None) -> bool: + caps = (identity or {}).get("capabilities") + return isinstance(caps, list) and CAPABILITY_RUN_OUTCOMES in caps def push_run( @@ -226,32 +325,29 @@ def push_run( project_kind: str, report_markdown: str, assessment: AssessmentRecord | None = None, + identity: dict[str, Any] | None = None, + timeout: float | None = None, ) -> None: """Pushes one completed run to the portal. Raises CloudError on any failure -- callers that must never fail the local run over this (runner.py's auto-push hook) catch it; `secfoo cloud sync`, run interactively, lets it surface per-run instead. - The report is sent only after the portal's whoami endpoint confirms - this exact key is scope `ingest`. A view key, a revoked key, or any - other string never gets as far as the upload. - - `assessment`, when given, is the case file this run is attached to - locally -- included so the portal's Assessments register actually - gets populated instead of only ever seeing bare runs (the gap that - made every synced run show up under its Activity page but never as - an assessment). Keyed by `assessment.assessment_uuid`, not the local - autoincrement id, since that id only means something within this - one machine's SQLite file -- see schema.sql's comment on that column. + Non-success outcomes are pushed only when `/api/v1/whoami` advertises the + `run_outcomes_v1` capability (#241); otherwise only `success` runs push. """ api_key = _require_ingest_key(config.api_key) confirmed = CloudConfig(api_key=api_key, portal_url=config.portal_url) - identity = whoami(confirmed) - if identity.get("scope") != "ingest": + resolved_identity = identity if identity is not None else whoami(confirmed, timeout=timeout) + if resolved_identity.get("scope") != "ingest": raise CloudError( "Sync refused: the portal did not accept this key as an ingest key. " "The report was not uploaded." ) + if run.status != "success" and not portal_supports_all_outcomes(resolved_identity): + raise CapabilityUnsupportedError( + f"Portal does not advertise {CAPABILITY_RUN_OUTCOMES}; non-success run {run.run_uuid} kept local." + ) payload = { "client_run_uuid": run.run_uuid, @@ -277,6 +373,7 @@ def push_run( # findings lifecycle closes only what this run actually scanned. "scan_scope": run.scan_scope, }, + "trigger": sanitize_trigger(run.trigger), "report_markdown": report_markdown, "cli_version": _cli_version(), } @@ -291,7 +388,12 @@ def push_run( "review_date": assessment.review_date, "notes": assessment.notes, } - _request(f"{confirmed.portal_url.rstrip('/')}/api/v1/runs", api_key=api_key, payload=payload) + _request( + f"{confirmed.portal_url.rstrip('/')}/api/v1/runs", + api_key=api_key, + payload=payload, + timeout=timeout, + ) def _cli_version() -> str: @@ -300,12 +402,23 @@ def _cli_version() -> str: return __version__ -def sync_run(repo: RunRepository, run_uuid: str, config: CloudConfig) -> None: +def compute_next_retry_at(attempts: int) -> str: + """Exponential backoff (30s, 60s, ..., capped at 1h) for outbox retries.""" + delay = min(3600, 30 * (2 ** min(max(attempts, 0), 8))) + return (datetime.now(timezone.utc) + timedelta(seconds=delay)).isoformat() + + +def sync_run( + repo: RunRepository, + run_uuid: str, + config: CloudConfig, + *, + identity: dict[str, Any] | None = None, + timeout: float | None = None, +) -> None: """Pushes one already-completed local run to the portal and marks it synced on success. Raises CloudError (from push_run) or ValueError (if - the run/project can't be found locally) -- never swallows anything - itself; callers decide what "best-effort" means for them (runner.py's - hook catches broadly, `secfoo cloud sync` reports failures per-run). + the run/project can't be found locally). """ run = repo.get_run(run_uuid) if run is None: @@ -320,12 +433,98 @@ def sync_run(repo: RunRepository, run_uuid: str, config: CloudConfig) -> None: assessment = repo.get_assessment(run.assessment_id) if run.assessment_id else None - push_run( - config, - run=run, - project_identifier=project.identifier, - project_kind=project.kind, - report_markdown=report_markdown, - assessment=assessment, - ) + try: + push_run( + config, + run=run, + project_identifier=project.identifier, + project_kind=project.kind, + report_markdown=report_markdown, + assessment=assessment, + identity=identity, + timeout=timeout, + ) + except CapabilityUnsupportedError: + raise + except CloudError as exc: + repo.record_sync_failure( + run_uuid, + error=redact_secret(str(exc), config.api_key), + next_sync_at=compute_next_retry_at(run.sync_attempts), + ) + raise repo.mark_run_synced(run_uuid) + + +def flush_outbox( + repo: RunRepository, + *, + time_budget_seconds: float = 2.0, + max_runs: int = 10, +) -> OutboxFlushSummary: + """Opportunistically push ready queued runs within `time_budget_seconds`. + + Skips without touching the network when nothing is queued, and never raises (#241). + """ + try: + config = load_cloud_config() + except CloudError as exc: + return OutboxFlushSummary( + attempted=0, synced=0, failed=0, state="refused", error=redact_secret(str(exc)) + ) + if config is None: + return OutboxFlushSummary(attempted=0, synced=0, failed=0, state="local_only") + + candidate_runs = repo.list_unsynced_runs( + limit=max_runs, + include_all_outcomes=True, + respect_backoff=True, + ) + if not candidate_runs: + return OutboxFlushSummary(attempted=0, synced=0, failed=0, state="synced") + + deadline = time.monotonic() + max(0.2, float(time_budget_seconds)) + try: + identity = whoami(config, timeout=max(0.2, deadline - time.monotonic())) + except CloudError as exc: + return OutboxFlushSummary( + attempted=0, + synced=0, + failed=0, + state="queued", + error=redact_secret(str(exc), config.api_key), + ) + if identity.get("scope") != "ingest": + return OutboxFlushSummary( + attempted=0, + synced=0, + failed=0, + state="refused", + error="Sync refused: key scope is not ingest.", + ) + + supports_all = portal_supports_all_outcomes(identity) + runs = ( + candidate_runs + if supports_all + else repo.list_unsynced_runs(limit=max_runs, include_all_outcomes=False, respect_backoff=True) + ) + attempted = 0 + synced = 0 + failed = 0 + last_err: str | None = None + for run in runs: + remaining = deadline - time.monotonic() + if remaining <= 0: + break + attempted += 1 + try: + sync_run(repo, run.run_uuid, config, identity=identity, timeout=remaining) + synced += 1 + except CapabilityUnsupportedError: + continue + except (CloudError, ValueError) as exc: + failed += 1 + last_err = redact_secret(str(exc), config.api_key) + state = "queued" if failed > 0 else "synced" + return OutboxFlushSummary(attempted=attempted, synced=synced, failed=failed, state=state, error=last_err) diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 76e7344c..14fb0376 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -19,7 +19,7 @@ from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import Literal +from typing import Any, Literal from secfoo import cloud, cvss, memory, osv from secfoo.agents.registry import get_adapter @@ -154,6 +154,8 @@ class RunOutcome: project_id: int | None = None findings: tuple[dict[str, str], ...] = () changed_files: tuple[str, ...] | None = None + cloud_state: str = "local_only" + cloud_error: str | None = None def _project_display_name(resolved: ResolvedTarget) -> str: @@ -165,19 +167,38 @@ def _project_display_name(resolved: ResolvedTarget) -> str: return Path(resolved.display_name).name or resolved.display_name -def _try_cloud_sync(repo: RunRepository, run_uuid: str) -> None: - """Best-effort push to the enterprise portal, if `secfoo cloud login` - has configured one. A portal outage, missing config, or any other - failure here must never fail the local run -- `secfoo cloud status` - and `secfoo cloud sync` are how a user checks/retries, not this hook. +def _try_cloud_sync(repo: RunRepository, run_uuid: str) -> tuple[str, str | None]: + """Best-effort push to the enterprise portal, returning `(state, error)`. + + A portal outage, missing config, or any other failure must never fail the + local run -- failed pushes stay queued in the local outbox (#241). """ + api_key: str | None = None try: config = cloud.load_cloud_config() - if config is None: - return + except cloud.CloudError as exc: + logger.debug("cloud config refused sync for run %s: %s", run_uuid, exc) + return "refused", cloud.redact_secret(str(exc)) + except Exception: # broad on purpose: any sync failure must not fail the local run + logger.debug("cloud sync skipped for run %s", run_uuid, exc_info=True) + return "queued", "cloud sync failed" + if config is None: + return "local_only", None + api_key = config.api_key + try: cloud.sync_run(repo, run_uuid, config) + return "synced", None + except cloud.CapabilityUnsupportedError: + return "local_only", None + except cloud.CloudError as exc: + reason = cloud.redact_secret(str(exc), api_key) + logger.debug("cloud sync failed for run %s: %s", run_uuid, reason) + if "ingest" in reason.lower() or "refused" in reason.lower(): + return "refused", reason + return "queued", reason except Exception: # broad on purpose: any sync failure must not fail the local run logger.debug("cloud sync skipped for run %s", run_uuid, exc_info=True) + return "queued", "cloud sync failed" def _try_osv_enrich(repo: RunRepository, report_text: str) -> None: @@ -396,6 +417,7 @@ def _mark_run_crashed(repo: RunRepository, run_uuid: str, *, duration_seconds: f prompt_path=None, stderr_excerpt=f"secfoo crashed during this run:\n{traceback.format_exc()}"[-STDERR_EXCERPT_LIMIT:], ) + _try_cloud_sync(repo, run_uuid) except Exception: logger.exception("Failed to mark crashed run %s as failed", run_uuid) @@ -603,6 +625,7 @@ def _run_single_skill( stack: Stack | None = None, model: str | None = None, max_input_tokens: int | None = None, + trigger: dict[str, Any] | None = None, ) -> RunOutcome: skill = load_skill(skill_id) memory_enabled = memory.is_active_for_agent(agent_id) @@ -631,6 +654,7 @@ def _run_single_skill( skill_version=skill.version, skill_source=skill.source_label, skill_sha256=skill.sha256 or None, + trigger=cloud.sanitize_trigger(trigger) if trigger is not None else None, ) started = time.monotonic() @@ -757,9 +781,13 @@ def _run_single_skill( except Exception: logger.exception("Failed to record documentation coverage for run %s", run_uuid) + sync_res = _try_cloud_sync(repo, run_uuid) + if isinstance(sync_res, tuple) and len(sync_res) == 2: + cloud_state, cloud_error = sync_res + else: + cloud_state, cloud_error = "local_only", None run_findings: list[dict[str, str]] = [] if result.status == "success": - _try_cloud_sync(repo, run_uuid) output_type = skill.output_type # #79: a custom skill may reuse a built-in's lifecycle if output_type == SCA_SKILL_ID: _try_osv_enrich(repo, report_text) @@ -828,6 +856,8 @@ def _run_single_skill( project_id=project_id, findings=tuple(run_findings), changed_files=tuple(changed_files) if changed_files is not None else None, + cloud_state=cloud_state, + cloud_error=cloud_error, ) finally: repo.close() @@ -856,6 +886,7 @@ def execute_runs( project_id: int | None = None, project_display_name: str | None = None, assessment_application_id: str | None = None, + trigger: dict[str, Any] | None = None, ) -> list[RunOutcome]: """Run each skill in `skill_ids` concurrently against `agent_id`. @@ -977,6 +1008,7 @@ def execute_runs( exclude_paths=exclude_paths, changed_files=scoped_files, stack=stack, + trigger=trigger, ) for skill_id in skill_ids ] diff --git a/src/secfoo/storage/models.py b/src/secfoo/storage/models.py index 46c49355..88c7a8b9 100644 --- a/src/secfoo/storage/models.py +++ b/src/secfoo/storage/models.py @@ -2,6 +2,7 @@ import json from dataclasses import dataclass +from typing import Any @dataclass(frozen=True) @@ -53,6 +54,11 @@ class RunRecord: skill_sha256: str | None = None # #131: the report's own overall rating, stored at run completion. overall_rating: str | None = None + # #241: trigger provenance & portal outbox tracking. + trigger: dict[str, Any] | None = None + sync_attempts: int = 0 + last_sync_error: str | None = None + next_sync_at: str | None = None @dataclass(frozen=True) diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index 6422f1ec..e9468f88 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -10,7 +10,7 @@ from contextvars import ContextVar from datetime import date, datetime, timedelta, timezone from pathlib import Path -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from secfoo.config import DB_PATH, ensure_store_dirs from secfoo.report.markdown import read_stored_report @@ -100,6 +100,11 @@ def use_db_path(path: Path): "skill_sha256": "ALTER TABLE runs ADD COLUMN skill_sha256 TEXT", # #131: stored so the Responsible AI badge doesn't re-read report files. "overall_rating": "ALTER TABLE runs ADD COLUMN overall_rating TEXT", + # #241: trigger provenance & outbox backoff tracking. + "trigger_json": "ALTER TABLE runs ADD COLUMN trigger_json TEXT", + "sync_attempts": "ALTER TABLE runs ADD COLUMN sync_attempts INTEGER NOT NULL DEFAULT 0", + "last_sync_error": "ALTER TABLE runs ADD COLUMN last_sync_error TEXT", + "next_sync_at": "ALTER TABLE runs ADD COLUMN next_sync_at TEXT", } _ASSESSMENTS_MIGRATIONS = { @@ -398,7 +403,11 @@ def _migrate_runs_status_check(self) -> None: def needs_rebuild() -> str | None: row = self._conn.execute("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'runs'").fetchone() sql = row["sql"] if row else "" - return sql if "'binary_not_found'" in sql and "'not_configured'" not in sql else None + if "'binary_not_found'" not in sql: + return None + if "'not_configured'" not in sql or "'skipped'" not in sql or "'not_submitted'" not in sql: + return sql + return None if needs_rebuild() is None: return @@ -410,7 +419,10 @@ def needs_rebuild() -> str | None: if old_sql is None: self._conn.rollback() return - new_sql = old_sql.replace("'binary_not_found'", "'binary_not_found','not_configured'", 1) + new_sql = old_sql + for candidate in ("'not_configured'", "'skipped'", "'not_submitted'"): + if candidate not in new_sql: + new_sql = new_sql.replace("'binary_not_found'", f"'binary_not_found',{candidate}", 1) new_sql = re.sub(r'^\s*CREATE TABLE\s+(IF NOT EXISTS\s+)?["`\[]?runs["`\]]?', "CREATE TABLE runs_new", new_sql, count=1, flags=re.IGNORECASE) columns = ", ".join(f'"{row["name"]}"' for row in self._conn.execute("PRAGMA table_info(runs)")) @@ -526,14 +538,16 @@ def create_run( skill_version: int | None = None, skill_source: str | None = None, skill_sha256: str | None = None, + trigger: dict[str, Any] | None = None, + status: str = "running", ) -> str: run_uuid = str(uuid.uuid4()) self._conn.execute( "INSERT INTO runs (run_uuid, project_id, assessment_id, skill_id, skill_name, agent_id, " - "confluence_urls, status, started_at, model, skill_version, skill_source, skill_sha256) " - "VALUES (?, ?, ?, ?, ?, ?, ?, 'running', ?, ?, ?, ?, ?)", - (run_uuid, project_id, assessment_id, skill_id, skill_name, agent_id, json.dumps(confluence_urls), _now(), - model, skill_version, skill_source, skill_sha256), + "confluence_urls, status, started_at, model, skill_version, skill_source, skill_sha256, trigger_json) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + (run_uuid, project_id, assessment_id, skill_id, skill_name, agent_id, json.dumps(confluence_urls), status, _now(), + model, skill_version, skill_source, skill_sha256, None if trigger is None else json.dumps(trigger)), ) self._conn.commit() return run_uuid @@ -564,14 +578,15 @@ def create_completed_run( cost_usd: float | None = None, scan_scope: list[str] | None = None, overall_rating: str | None = None, + trigger: dict[str, Any] | None = None, ) -> None: """Insert a run that already completed in another process.""" self._conn.execute( "INSERT INTO runs (run_uuid, project_id, skill_id, skill_name, agent_id, confluence_urls, " "status, exit_code, started_at, finished_at, duration_seconds, report_path, " "critical_count, high_count, medium_count, low_count, info_count, assessment_id, " - "input_tokens, output_tokens, cost_usd, scan_scope, overall_rating) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "input_tokens, output_tokens, cost_usd, scan_scope, overall_rating, trigger_json) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ( run_uuid, project_id, skill_id, skill_name, agent_id, json.dumps(confluence_urls), status, exit_code, started_at, finished_at, duration_seconds, report_path, @@ -579,6 +594,7 @@ def create_completed_run( input_tokens, output_tokens, cost_usd, None if scan_scope is None else json.dumps(scan_scope), (overall_rating or "").strip().lower() or None, + None if trigger is None else json.dumps(trigger), ), ) self._conn.commit() @@ -755,21 +771,77 @@ def mark_run_synced(self, run_uuid: str) -> None: the timestamp. """ self._conn.execute( - "UPDATE runs SET cloud_synced_at = ? WHERE run_uuid = ?", (_now(), run_uuid) + "UPDATE runs SET cloud_synced_at = ?, last_sync_error = NULL, next_sync_at = NULL WHERE run_uuid = ?", + (_now(), run_uuid), ) self._conn.commit() - def list_unsynced_runs(self, limit: int = 500) -> list[RunRecord]: - """Successful runs never pushed to the portal -- what `secfoo cloud - sync` catches up after a run happened while offline or before - `cloud login` was ever run. + def record_sync_failure(self, run_uuid: str, *, error: str, next_sync_at: str | None = None) -> None: + """Increment retry counter and record sanitized error + backoff timestamp.""" + self._conn.execute( + "UPDATE runs SET sync_attempts = sync_attempts + 1, last_sync_error = ?, next_sync_at = ? " + "WHERE run_uuid = ?", + (error[:500], next_sync_at, run_uuid), + ) + self._conn.commit() + + def update_run_trigger(self, run_uuid: str, trigger: dict[str, Any]) -> None: + """Update trigger provenance JSON (e.g. setting decision on hook completion).""" + self._conn.execute( + "UPDATE runs SET trigger_json = ? WHERE run_uuid = ?", + (json.dumps(trigger), run_uuid), + ) + self._conn.commit() + + def mark_stale_host_runs_not_submitted(self, session_ref: str) -> list[str]: + """Mark pending host-mode runs for `session_ref` as `not_submitted`.""" + rows = self._conn.execute( + "SELECT run_uuid, trigger_json FROM runs " + "WHERE status IN ('pending', 'running') AND json_extract(trigger_json, '$.mode') = 'host' " + "AND json_extract(trigger_json, '$.session_ref') = ?", + (session_ref,), + ).fetchall() + marked: list[str] = [] + now = _now() + for row in rows: + trig = json.loads(row["trigger_json"] or "{}") + trig.setdefault("decision", "none") + self._conn.execute( + "UPDATE runs SET status = 'not_submitted', finished_at = ?, duration_seconds = 0.0, trigger_json = ? " + "WHERE run_uuid = ?", + (now, json.dumps(trig), row["run_uuid"]), + ) + marked.append(row["run_uuid"]) + if marked: + self._conn.commit() + return marked + + def list_unsynced_runs( + self, + limit: int = 500, + *, + include_all_outcomes: bool = False, + respect_backoff: bool = False, + ) -> list[RunRecord]: + """Runs never pushed to the portal -- caught up by `secfoo cloud sync` + and opportunistic outbox flushes (#241). """ + clauses = ["runs.cloud_synced_at IS NULL"] + params: list[object] = [] + if include_all_outcomes: + clauses.append("runs.status NOT IN ('pending', 'running')") + else: + clauses.append("runs.status = 'success'") + if respect_backoff: + clauses.append("(runs.next_sync_at IS NULL OR runs.next_sync_at <= ?)") + params.append(_now()) + params.append(limit) rows = self._conn.execute( "SELECT runs.*, projects.display_name FROM runs " "JOIN projects ON projects.id = runs.project_id " - "WHERE runs.status = 'success' AND runs.cloud_synced_at IS NULL " + f"WHERE {' AND '.join(clauses)} " # nosec B608 -- fixed internal SQL clauses, values bound via ? "ORDER BY runs.started_at ASC LIMIT ?", - (limit,), + params, ).fetchall() return [self._row_to_run(row) for row in rows] @@ -777,9 +849,16 @@ def _row_to_run(self, row: sqlite3.Row) -> RunRecord: data = dict(row) confluence_urls = json.loads(data.pop("confluence_urls") or "[]") project_display_name = data.pop("display_name", None) + trigger_raw = data.pop("trigger_json", None) + trigger = json.loads(trigger_raw) if trigger_raw else None if data.get("scan_scope") is not None: data["scan_scope"] = json.loads(data["scan_scope"]) - return RunRecord(confluence_urls=confluence_urls, project_display_name=project_display_name, **data) + return RunRecord( + confluence_urls=confluence_urls, + project_display_name=project_display_name, + trigger=trigger, + **data, + ) def total_cost_usd(self, *, project_id: int | None = None) -> float: query = "SELECT COALESCE(SUM(cost_usd), 0) AS total FROM runs WHERE 1=1" @@ -798,6 +877,8 @@ def list_runs( skill_id: str | None = None, limit: int = 200, status: str | None = None, + host: str | None = None, + recipe: str | None = None, ) -> list[RunRecord]: query = ( "SELECT runs.*, projects.display_name FROM runs " @@ -816,6 +897,12 @@ def list_runs( if status is not None: query += " AND runs.status = ?" params.append(status) + if host: + query += " AND json_extract(runs.trigger_json, '$.host') = ?" + params.append(host) + if recipe: + query += " AND json_extract(runs.trigger_json, '$.recipe') = ?" + params.append(recipe) query += " ORDER BY runs.started_at DESC LIMIT ?" params.append(limit) rows = self._conn.execute(query, params).fetchall() diff --git a/src/secfoo/storage/schema.sql b/src/secfoo/storage/schema.sql index 008fd655..3102ffb1 100644 --- a/src/secfoo/storage/schema.sql +++ b/src/secfoo/storage/schema.sql @@ -46,7 +46,7 @@ CREATE TABLE IF NOT EXISTS runs ( model TEXT, -- requested model; NULL = CLI default/unknown confluence_urls TEXT NOT NULL DEFAULT '[]', status TEXT NOT NULL CHECK (status IN - ('pending','running','success','failed','timeout','binary_not_found','not_configured')), + ('pending','running','success','failed','timeout','binary_not_found','not_configured','skipped','not_submitted')), exit_code INTEGER, started_at TEXT NOT NULL, finished_at TEXT, @@ -92,7 +92,12 @@ CREATE TABLE IF NOT EXISTS runs ( -- completion. The Responsible AI badge reads this column instead of -- re-opening every assessment's report file on every page load. -- NULL for runs from before this column existed, or with no rating. - overall_rating TEXT + overall_rating TEXT, + -- #241: trigger provenance JSON and portal sync outbox state. + trigger_json TEXT, + sync_attempts INTEGER NOT NULL DEFAULT 0, + last_sync_error TEXT, + next_sync_at TEXT ); -- Documentation sources a run was given and whether the agent reached each diff --git a/src/secfoo/web/routes/projects.py b/src/secfoo/web/routes/projects.py index 449413bb..7f243486 100644 --- a/src/secfoo/web/routes/projects.py +++ b/src/secfoo/web/routes/projects.py @@ -20,12 +20,27 @@ @router.get("/projects/{project_id}") -def project_detail(request: Request, project_id: int, tm_rerun: str | None = None): +def project_detail( + request: Request, + project_id: int, + tm_rerun: str | None = None, + host: str | None = None, + recipe: str | None = None, +): + host_filter = (host or "").strip() or None + recipe_filter = (recipe or "").strip() or None with RunRepository() as repo: project = repo.get_project(project_id) if project is None: raise HTTPException(status_code=404, detail="Project not found") - runs = repo.list_runs(project_id=project_id, limit=200) + all_runs = repo.list_runs(project_id=project_id, limit=200) + runs = ( + repo.list_runs(project_id=project_id, limit=200, host=host_filter, recipe=recipe_filter) + if (host_filter or recipe_filter) + else all_runs + ) + available_hosts = sorted({r.trigger["host"] for r in all_runs if r.trigger and r.trigger.get("host")}) + available_recipes = sorted({r.trigger["recipe"] for r in all_runs if r.trigger and r.trigger.get("recipe")}) coverage = repo.project_activity_coverage(project_id) tm_correlation = correlate_project_traffic(repo, project_id) runtime_dash = runtime_dashboard.build(repo, project_id) @@ -47,6 +62,10 @@ def project_detail(request: Request, project_id: int, tm_rerun: str | None = Non "tm_correlation": tm_correlation, "tm_rerun": tm_rerun, "runtime_dash": runtime_dash, + "available_hosts": available_hosts, + "available_recipes": available_recipes, + "filter_host": host_filter or "", + "filter_recipe": recipe_filter or "", }, ) diff --git a/src/secfoo/web/templates/project.html b/src/secfoo/web/templates/project.html index 14b0078e..9da59891 100644 --- a/src/secfoo/web/templates/project.html +++ b/src/secfoo/web/templates/project.html @@ -83,15 +83,40 @@

Activity coverage

Runs

+{% if available_hosts or available_recipes or filter_host or filter_recipe %} +
+ + + + {% if filter_host or filter_recipe %} + Clear + {% endif %} +
+{% endif %}
- + {% for run in runs %} + diff --git a/src/secfoo/web/templates/run_detail.html b/src/secfoo/web/templates/run_detail.html index 16bcdd2c..2edc77a2 100644 --- a/src/secfoo/web/templates/run_detail.html +++ b/src/secfoo/web/templates/run_detail.html @@ -39,6 +39,18 @@

Run receipt

agent{{ run.agent_id }}
model{{ run.model or 'CLI default' }}
skill{{ run.skill_id }}
+ {% if run.trigger %} +
+ trigger + + {{ run.trigger.get('source') or 'cli' }} + {% if run.trigger.get('host') %} · {{ run.trigger.get('host') }}{% if run.trigger.get('host_version') %} ({{ run.trigger.get('host_version') }}){% endif %}{% endif %} + {% if run.trigger.get('recipe') %} · {{ run.trigger.get('recipe') }}{% endif %} + {% if run.trigger.get('event') %} · {{ run.trigger.get('event') }}{% endif %} + {% if run.trigger.get('decision') and run.trigger.get('decision') != 'none' %} · {{ run.trigger.get('decision') }}{% endif %} + +
+ {% endif %} {% if run.skill_source %}
skill definition diff --git a/tests/test_automation_reporting.py b/tests/test_automation_reporting.py new file mode 100644 index 00000000..a4c6f92e --- /dev/null +++ b/tests/test_automation_reporting.py @@ -0,0 +1,370 @@ +"""Tests for automation run reporting, trigger provenance, outbox, and env-var key (#241).""" + +from __future__ import annotations + +import hashlib +import json +import sqlite3 +import time +import urllib.error +from datetime import datetime, timezone + +import pytest +from fastapi.testclient import TestClient +from typer.testing import CliRunner + +from secfoo import cloud +from secfoo.agents.base import AgentResult +from secfoo.cli import app +from secfoo.runner import execute_runs +from secfoo.storage.models import RunRecord +from secfoo.storage.repository import RunRepository +from secfoo.web.app import create_app + + +class _FakeHTTPResponse: + def __init__(self, body: dict): + self._raw = json.dumps(body).encode("utf-8") + + def read(self) -> bytes: + return self._raw + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + +def _setup_target_and_fake_agent(monkeypatch, tmp_path, *, status: str = "success"): + target = tmp_path / "repo" + target.mkdir(exist_ok=True) + (target / "app.py").write_text("x = 1\n", encoding="utf-8") + + reports_root = tmp_path / "reports" + reports_root.mkdir(exist_ok=True) + monkeypatch.setattr("secfoo.runner.run_dir", lambda ru: reports_root / ru) + monkeypatch.setattr("secfoo.runner.ensure_store_dirs", lambda: None) + monkeypatch.setattr("secfoo.cloud.CLOUD_CONFIG_PATH", tmp_path / "missing-cloud.toml") + monkeypatch.setattr("secfoo.cli.CLOUD_CONFIG_PATH", tmp_path / "missing-cloud.toml") + + class _Adapter: + def configure_model(self, m): + pass + + def configure_max_input_tokens(self, n): + pass + + def run(self, prompt, *, workdir, timeout=None, prev_commit=None): + report = ( + "# Security Review\n\n## 1. Executive Summary\nClean.\n" + if status == "success" + else "" + ) + return AgentResult( + agent="claude", + exit_code=0 if status == "success" else 1, + stdout=report, + stderr="" if status == "success" else "boom", + duration_seconds=0.1, + timed_out=(status == "timeout"), + status=status, # type: ignore[arg-type] + raw_report=report, + ) + + monkeypatch.setattr("secfoo.runner.get_adapter", lambda _a: _Adapter()) + return target + + +def test_non_success_statuses_respect_whoami_capability_and_never_close_findings(monkeypatch, tmp_path): + target = _setup_target_and_fake_agent(monkeypatch, tmp_path, status="timeout") + monkeypatch.setenv("SECFOO_API_KEY", "sfc_ingest_secret_123") + + pushed: list[dict] = [] + caps: list[str] = [] + + def _fake_urlopen(req, timeout=None): + if req.full_url.endswith("/whoami"): + return _FakeHTTPResponse({"scope": "ingest", "capabilities": list(caps)}) + pushed.append(json.loads(req.data.decode("utf-8"))) + return _FakeHTTPResponse({"server_run_id": "srv-1", "status": "recorded"}) + + monkeypatch.setattr("secfoo.cloud.urllib.request.urlopen", _fake_urlopen) + + db_path = tmp_path / "secfoo.db" + with RunRepository(db_path=db_path) as repo: + pid = repo.upsert_project(str(target), "repo", "local") + seed_uuid = repo.create_run(project_id=pid, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[]) + repo.complete_run(seed_uuid, status="success", exit_code=0, duration_seconds=0.1, report_path=None, prompt_path=None, stderr_excerpt=None) + seed_run = repo.get_run(seed_uuid) + repo.upsert_sast_finding( + project_id=pid, run_id=seed_run.id, fingerprint="fp-keep-open", current_ref="F1", + title="SQLi", severity="high", cwe="CWE-89", owasp="A03", verdict="confirmed", + location_file="app.py", location_line="1", cvss_vector=None, cvss_score=None, + ) + + # Without capability: non-success run stays local, not pushed + [out1] = execute_runs( + skill_ids=["sast"], target=str(target), confluence_urls=[], agent_id="claude", repo=repo, + trigger={"source": "hook", "host": "claude-code", "recipe": "turn-review", "event": "turn_end"}, + ) + assert out1.cloud_state == "local_only" + assert pushed == [] + assert repo.get_run(out1.run_uuid).cloud_synced_at is None + + # With run_outcomes_v1 capability: timeout + skipped + not_submitted all push once & findings remain open + caps[:] = ["run_outcomes_v1"] + [out2] = execute_runs( + skill_ids=["sast"], target=str(target), confluence_urls=[], agent_id="claude", repo=repo, + trigger={"source": "hook", "host": "claude-code", "recipe": "turn-review", "event": "turn_end"}, + ) + assert out2.cloud_state == "synced" + assert repo.get_run(out2.run_uuid).cloud_synced_at is not None + + for st in ("skipped", "not_submitted"): + ru = repo.create_run( + project_id=pid, skill_id="sast", skill_name="SAST", agent_id="claude", + confluence_urls=[], trigger={"source": "hook", "host": "copilot", "recipe": "commit-guard", "event": "pre_shell"}, + ) + repo.complete_run(ru, status=st, exit_code=0, duration_seconds=0.0, report_path=None, prompt_path=None, stderr_excerpt=None) + cloud.sync_run(repo, ru, cloud.CloudConfig(api_key="sfc_ingest_secret_123")) + + assert [p["run"]["status"] for p in pushed] == ["timeout", "skipped", "not_submitted"] + # Findings from seed run stayed untouched (still open) + assert len(repo.list_sast_findings(project_id=pid, status="open")) == 1 + + +def test_trigger_provenance_strips_forbidden_hook_fields_and_hashes_session(monkeypatch, tmp_path): + monkeypatch.setattr("secfoo.cloud.STORE_DIR", tmp_path) + sent_bodies: list[dict] = [] + + def _fake_urlopen(req, timeout=None): + if req.full_url.endswith("/whoami"): + return _FakeHTTPResponse({"scope": "ingest", "capabilities": ["run_outcomes_v1"]}) + sent_bodies.append(json.loads(req.data.decode("utf-8"))) + return _FakeHTTPResponse({"status": "ok"}) + + monkeypatch.setattr("secfoo.cloud.urllib.request.urlopen", _fake_urlopen) + + session_ref = cloud.hash_session_ref("raw-secret-conv-id", salt_path=tmp_path / "install_salt") + assert session_ref and session_ref != "raw-secret-conv-id" and len(session_ref) == 64 + assert session_ref != hashlib.sha256(b"raw-secret-conv-id").hexdigest() + + poisoned_trigger = { + "source": "hook", + "host": "grok-build", + "host_version": "2.1.0", + "recipe": "commit-guard", + "recipe_version": 1, + "event": "pre_shell", + "mode": "delegate", + "decision": "blocked", + "session_ref": session_ref, + "user_email": "alice@secret.corp", + "transcript_path": "/Users/alice/.cursor/transcript.jsonl", + "prompt": "do not leak me", + "tool_input": {"command": "git push origin main --token=xyz"}, + "file_contents": "SECRET_KEY=topsecret", + } + sanitized = cloud.sanitize_trigger(poisoned_trigger) + serialized = json.dumps(sanitized) + for forbidden in ("alice@secret.corp", "transcript.jsonl", "do not leak me", "SECRET_KEY=topsecret", "user_email", "transcript_path"): + assert forbidden not in serialized + + run = RunRecord( + id=1, run_uuid="u-trig-1", project_id=1, skill_id="sast", skill_name="SAST", agent_id="claude", + confluence_urls=[], status="success", exit_code=0, started_at="2026-12-04T00:00:00Z", + finished_at="2026-12-04T00:00:01Z", duration_seconds=1.0, report_path=None, + prompt_path=None, stderr_excerpt=None, trigger=sanitized, + ) + cloud.push_run(cloud.CloudConfig(api_key="sfc_ingest_ok"), run=run, project_identifier="/tmp/p", project_kind="local", report_markdown="") + assert sent_bodies[0]["trigger"] == sanitized + assert sent_bodies[0]["trigger"]["host"] == "grok-build" + assert sent_bodies[0]["trigger"]["session_ref"] == session_ref + + +def test_outbox_queue_backoff_and_budget_flush(monkeypatch, tmp_path): + monkeypatch.setattr("secfoo.cloud.CLOUD_CONFIG_PATH", tmp_path / "missing.toml") + monkeypatch.setenv("SECFOO_API_KEY", "sfc_ingest_tok_redacted_test") + db_path = tmp_path / "secfoo.db" + + with RunRepository(db_path=db_path) as repo: + pid = repo.upsert_project("/p", "p", "local") + ru = repo.create_run(project_id=pid, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[]) + repo.complete_run(ru, status="success", exit_code=0, duration_seconds=0.5, report_path=None, prompt_path=None, stderr_excerpt=None) + + def _down(req, timeout=None): + raise urllib.error.URLError("firewall blocked sfc_ingest_tok_redacted_test") + + monkeypatch.setattr("secfoo.cloud.urllib.request.urlopen", _down) + # Try sync -> queues with backoff and key redacted + with pytest.raises(cloud.CloudError): + cloud.sync_run(repo, ru, cloud.load_cloud_config()) + rec = repo.get_run(ru) + assert rec.cloud_synced_at is None + assert rec.sync_attempts == 1 + assert rec.last_sync_error is not None + assert "sfc_ingest_tok_redacted_test" not in rec.last_sync_error + assert rec.next_sync_at is not None + + # Backoff not yet expired -> flush_outbox does not attempt yet + called = [] + + def _up(req, timeout=None): + called.append(req.full_url) + if req.full_url.endswith("/whoami"): + return _FakeHTTPResponse({"scope": "ingest", "capabilities": ["run_outcomes_v1"]}) + return _FakeHTTPResponse({"status": "recorded"}) + + monkeypatch.setattr("secfoo.cloud.urllib.request.urlopen", _up) + summary1 = cloud.flush_outbox(repo, time_budget_seconds=1.5) + assert summary1.attempted == 0 + + # Once backoff passes -> flush_outbox pushes and marks synced (and idempotent second push works) + past = datetime(2020, 1, 1, tzinfo=timezone.utc).isoformat() + repo.connection.execute("UPDATE runs SET next_sync_at = ? WHERE run_uuid = ?", (past, ru)) + repo.connection.commit() + started = time.monotonic() + summary2 = cloud.flush_outbox(repo, time_budget_seconds=1.5) + assert time.monotonic() - started < 1.5 + assert summary2.synced == 1 + assert repo.get_run(ru).cloud_synced_at is not None + # Idempotent second push + cloud.sync_run(repo, ru, cloud.load_cloud_config()) + assert repo.get_run(ru).cloud_synced_at is not None + + +def test_env_view_key_refused_without_leak_and_dashboard_filters(monkeypatch, tmp_path): + monkeypatch.setattr("secfoo.cloud.CLOUD_CONFIG_PATH", tmp_path / "missing.toml") + monkeypatch.setattr("secfoo.cli.CLOUD_CONFIG_PATH", tmp_path / "missing.toml") + secret_view = "sfc_view_super_secret_999" + monkeypatch.setenv("SECFOO_API_KEY", secret_view) + + def _never(*args, **kwargs): + raise AssertionError("network must never be called for view key") + + monkeypatch.setattr("secfoo.cloud.urllib.request.urlopen", _never) + res = CliRunner().invoke(app, ["cloud", "status"]) + combined = res.stdout + res.stderr + assert secret_view not in combined + assert "refused" in combined.lower() + + # Dashboard run page & project filters show trigger host + recipe + db_path = tmp_path / "dash.db" + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", db_path) + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + with RunRepository(db_path=db_path) as repo: + pid = repo.upsert_project("/proj", "proj", "local") + r1 = repo.create_run( + project_id=pid, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[], + trigger={"source": "hook", "host": "claude-code", "recipe": "commit-guard", "event": "pre_shell", "decision": "blocked"}, + ) + repo.complete_run(r1, status="success", exit_code=0, duration_seconds=0.2, report_path=None, prompt_path=None, stderr_excerpt=None) + r2 = repo.create_run( + project_id=pid, skill_id="secret-scanning", skill_name="Secrets", agent_id="copilot", confluence_urls=[], + trigger={"source": "hook", "host": "copilot", "recipe": "turn-review", "event": "turn_end", "decision": "allowed"}, + ) + repo.complete_run(r2, status="skipped", exit_code=0, duration_seconds=0.0, report_path=None, prompt_path=None, stderr_excerpt=None) + + client = TestClient(create_app()) + detail = client.get(f"/runs/{r1}") + assert detail.status_code == 200 + assert "claude-code" in detail.text and "commit-guard" in detail.text + + filtered = client.get(f"/projects/{pid}?host=copilot") + assert filtered.status_code == 200 + assert "turn-review" in filtered.text + assert "commit-guard" not in filtered.text.split("
", 1)[1].split("", 1)[0] + + +def test_secfoo_api_key_file_and_legacy_db_migration(monkeypatch, tmp_path): + monkeypatch.setattr("secfoo.cloud.CLOUD_CONFIG_PATH", tmp_path / "missing.toml") + key_file = tmp_path / "key.txt" + key_file.write_text("sfc_ingest_from_file_123\n", encoding="utf-8") + monkeypatch.delenv("SECFOO_API_KEY", raising=False) + monkeypatch.setenv("SECFOO_API_KEY_FILE", str(key_file)) + cfg = cloud.load_cloud_config() + assert cfg is not None and cfg.api_key == "sfc_ingest_from_file_123" + + # Legacy DB with pre-#241 runs status CHECK migrates cleanly to accept skipped & not_submitted + legacy_db = tmp_path / "legacy.db" + conn = sqlite3.connect(legacy_db) + conn.executescript( + """ + CREATE TABLE projects (id INTEGER PRIMARY KEY AUTOINCREMENT, identifier TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL, kind TEXT NOT NULL, first_seen_at TEXT NOT NULL, last_run_at TEXT NOT NULL); + CREATE TABLE runs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, run_uuid TEXT NOT NULL UNIQUE, project_id INTEGER NOT NULL REFERENCES projects(id), + skill_id TEXT NOT NULL, skill_name TEXT NOT NULL, agent_id TEXT NOT NULL, confluence_urls TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL CHECK (status IN ('pending','running','success','failed','timeout','binary_not_found','not_configured')), + exit_code INTEGER, started_at TEXT NOT NULL, finished_at TEXT, duration_seconds REAL, report_path TEXT, prompt_path TEXT, stderr_excerpt TEXT + ); + """ + ) + conn.commit() + conn.close() + + with RunRepository(db_path=legacy_db) as repo: + pid = repo.upsert_project("/p", "p", "local") + ru = repo.create_run(project_id=pid, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[]) + repo.complete_run(ru, status="not_submitted", exit_code=None, duration_seconds=0.0, report_path=None, prompt_path=None, stderr_excerpt=None) + assert repo.get_run(ru).status == "not_submitted" + + +def test_env_precedence_flush_no_network_when_empty_and_none_stub_tolerance(monkeypatch, tmp_path): + """Unified env precedence, zero-network empty flush, fake-repo resilience, and None-stub safety.""" + # 1. Unified env precedence: SECFOO_API_KEY > SECFOO_API_KEY_FILE > SECFOO_CLOUD_API_KEY > cloud.toml + toml_path = tmp_path / "cloud.toml" + cloud.save_cloud_config(cloud.CloudConfig(api_key="sfc_ingest_toml", portal_url="https://app.secfoo.com"), toml_path) + monkeypatch.setattr("secfoo.cloud.CLOUD_CONFIG_PATH", toml_path) + + key_file = tmp_path / "key.txt" + key_file.write_text("sfc_ingest_file\n", encoding="utf-8") + + monkeypatch.setenv("SECFOO_CLOUD_API_KEY", "sfc_ingest_alias") + assert cloud.load_cloud_config().api_key == "sfc_ingest_alias" + + monkeypatch.setenv("SECFOO_API_KEY_FILE", str(key_file)) + assert cloud.load_cloud_config().api_key == "sfc_ingest_file" + + monkeypatch.setenv("SECFOO_API_KEY", "sfc_ingest_primary") + assert cloud.load_cloud_config().api_key == "sfc_ingest_primary" + + monkeypatch.delenv("SECFOO_API_KEY", raising=False) + monkeypatch.delenv("SECFOO_API_KEY_FILE", raising=False) + monkeypatch.delenv("SECFOO_CLOUD_API_KEY", raising=False) + assert cloud.load_cloud_config().api_key == "sfc_ingest_toml" + + # 2. Empty outbox flush makes zero network calls + def _no_net(*args, **kwargs): + raise AssertionError("network must not be called when outbox is empty") + + monkeypatch.setattr("secfoo.cloud.urllib.request.urlopen", _no_net) + db_path = tmp_path / "empty.db" + with RunRepository(db_path=db_path) as repo: + summary = cloud.flush_outbox(repo, time_budget_seconds=1.0) + assert summary.attempted == 0 and summary.state == "synced" + + # 3. Startup opportunistic flush survives fake repo lacking list_unsynced_runs + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", db_path) + + class _FakeRepo: + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def list_runs(self, **kwargs): + return [] + + monkeypatch.setattr("secfoo.cli.RunRepository", _FakeRepo) + res = CliRunner().invoke(app, ["list"], env={"NO_COLOR": "1", "TERM": "dumb"}) + assert res.exit_code == 0 + + # 4. _try_cloud_sync returning None (legacy test stubs) does not raise TypeError + target = _setup_target_and_fake_agent(monkeypatch, tmp_path, status="success") + monkeypatch.setattr("secfoo.runner._try_cloud_sync", lambda repo, run_uuid: None) + with RunRepository(db_path=db_path) as repo: + [out] = execute_runs(skill_ids=["sast"], target=str(target), confluence_urls=[], agent_id="claude", repo=repo) + assert out.status == "success" + assert out.cloud_state == "local_only"
StartedSkillAgentModelStatusDurationCost
StartedSkillAgentTriggerModelStatusDurationCost
{{ run.started_at | fmt_time }} {{ run.skill_name }} {{ run.agent_id }}{% if run.trigger and (run.trigger.get('host') or run.trigger.get('recipe')) %}{{ run.trigger.get('host') or run.trigger.get('source') or '-' }}{% if run.trigger.get('recipe') %} {{ run.trigger.get('recipe') }}{% endif %}{% else %}-{% endif %} {{ run.model or '-' }} {{ run.status }} {{ run.duration_seconds | fmt_duration }}