Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
73 changes: 66 additions & 7 deletions src/secfoo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
],
Expand Down Expand Up @@ -1947,46 +1971,81 @@ 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 <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 <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

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).")

Expand Down
Loading
Loading