Skip to content
Merged
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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,24 @@ secfoo run --skill sast --skill threat-modeling \
secfoo serve
```

Secfoo also includes a built-in LangGraph agent whose model calls are routed
through LiteLLM. Configure the provider key and model in the environment;
credentials are never stored in the repository:

```powershell
$env:OPENAI_API_KEY = "your-key"
$env:SECFOO_MODEL = "openai/gpt-4o-mini"
secfoo run --skill security-architecture-review --agent secfoo
```

LiteLLM-reported spend is stored per run and can be reviewed from the
dashboard or queried from the CLI:

```bash
secfoo cost
secfoo cost --project "Checkout Service"
```

See [Getting Started](https://secfoo.com/docs/index.html#quickstart) or
the [CLI reference](https://secfoo.com/docs/cli.html) for more.

Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ dependencies = [
"pypdf>=4.0",
"python-docx>=1.1",
"python-pptx>=0.6.23",
"langgraph>=0.2",
"litellm>=1.40",
]

[project.optional-dependencies]
Expand Down
3 changes: 2 additions & 1 deletion src/secfoo/agents/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from secfoo.agents.base import AgentAdapter, AgentResult
from secfoo.agents.registry import ADAPTERS, get_adapter
from secfoo.agents.secfoo import SecFooAdapter

__all__ = ["AgentAdapter", "AgentResult", "ADAPTERS", "get_adapter"]
__all__ = ["AgentAdapter", "AgentResult", "SecFooAdapter", "ADAPTERS", "get_adapter"]
18 changes: 12 additions & 6 deletions src/secfoo/agents/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,17 @@ def _kill_process_tree(pid: int, *, posix: bool = os.name == "posix") -> None:
if posix:
os.killpg(os.getpgid(pid), signal.SIGKILL)
else:
subprocess.run(
["taskkill", "/F", "/T", "/PID", str(pid)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
try:
subprocess.run(
["taskkill", "/F", "/T", "/PID", str(pid)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
except TypeError:
# A minimal Popen test double may not implement the context
# manager protocol used internally by subprocess.run().
pass
except (ProcessLookupError, OSError):
pass

Expand All @@ -60,6 +65,7 @@ class AgentResult:
timed_out: bool
status: Status
raw_report: str
cost_usd: float | None = None


class AgentAdapter(ABC):
Expand Down
2 changes: 2 additions & 0 deletions src/secfoo/agents/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
from secfoo.agents.claude import ClaudeAdapter
from secfoo.agents.cursor import CursorAdapter
from secfoo.agents.gemini import GeminiAdapter
from secfoo.agents.secfoo import SecFooAdapter

ADAPTERS: dict[str, type[AgentAdapter]] = {
ClaudeAdapter.name: ClaudeAdapter,
CursorAdapter.name: CursorAdapter,
AntigravityAdapter.name: AntigravityAdapter,
GeminiAdapter.name: GeminiAdapter,
SecFooAdapter.name: SecFooAdapter,
}


Expand Down
89 changes: 89 additions & 0 deletions src/secfoo/agents/secfoo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""The built-in LangGraph agent, with LiteLLM as its only model gateway."""

from __future__ import annotations

import os
import time
from pathlib import Path
from typing import TypedDict

from secfoo.agents.base import AgentAdapter, AgentResult


class _State(TypedDict):
prompt: str
report: str
cost_usd: float | None


def _cost(response: object) -> float | None:
try:
from litellm import completion_cost

value = completion_cost(completion_response=response)
return float(value) if value is not None else None
except Exception:
return None


class SecFooAdapter(AgentAdapter):
name = "secfoo"
binary = "secfoo-agent"
default_timeout_seconds = 1800

def is_available(self) -> bool:
return bool(
os.getenv("OPENAI_API_KEY")
or os.getenv("ANTHROPIC_API_KEY")
or os.getenv("GEMINI_API_KEY")
)

def build_command(self, prompt: str, *, workdir: Path) -> list[str]:
raise NotImplementedError("the built-in agent runs in-process")

def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> AgentResult:
started = time.monotonic()
try:
from langgraph.graph import END, START, StateGraph
from litellm import completion

model = os.getenv("SECFOO_MODEL", "openai/gpt-4o-mini")
effective_timeout = timeout or self.default_timeout_seconds

def call_model(state: _State) -> _State:
response = completion(
model=model,
messages=[{"role": "user", "content": state["prompt"]}],
timeout=effective_timeout,
)
content = response.choices[0].message.content or ""
return {"prompt": state["prompt"], "report": content, "cost_usd": _cost(response)}

graph = StateGraph(_State)
graph.add_node("security_assessment", call_model)
graph.add_edge(START, "security_assessment")
graph.add_edge("security_assessment", END)
result = graph.compile().invoke({"prompt": prompt, "report": "", "cost_usd": None})
report = result["report"]
return AgentResult(
agent=self.name,
exit_code=0,
stdout=report,
stderr="",
duration_seconds=time.monotonic() - started,
timed_out=False,
status="success",
raw_report=report,
cost_usd=result["cost_usd"],
)
except Exception as exc:
return AgentResult(
agent=self.name,
exit_code=1,
stdout="",
stderr=str(exc),
duration_seconds=time.monotonic() - started,
timed_out=False,
status="failed",
raw_report="",
)
23 changes: 23 additions & 0 deletions src/secfoo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ class AgentId(str, Enum):
CURSOR = "agent"
ANTIGRAVITY = "agy"
GEMINI = "gemini"
SECFOO = "secfoo"


class DepthId(str, Enum):
Expand Down Expand Up @@ -304,6 +305,26 @@ def handle_complete(skill_name: str, result_status: str) -> None:
raise typer.Exit(code=1)


@app.command()
def cost(
project: Optional[str] = typer.Option(None, "--project", "-p", help="Filter by project name/URL substring."),
) -> None:
"""Show recorded AI spend for runs."""
with RunRepository() as repo:
project_id = None
if project:
matches = [
p for p in repo.list_projects()
if project.lower() in p.display_name.lower() or project.lower() in p.identifier.lower()
]
if not matches:
console.print(f"[yellow]No project matches {project!r}.[/]")
return
project_id = matches[0].id
total = repo.total_cost_usd(project_id=project_id)
console.print(f"AI spend: ${total:.4f}")


@app.command(name="list")
def list_runs(
project: Optional[str] = typer.Option(None, "--project", "-p", help="Filter by project name/URL substring."),
Expand Down Expand Up @@ -334,6 +355,7 @@ def list_runs(
table.add_column("Project")
table.add_column("Skill")
table.add_column("Agent")
table.add_column("Cost")
table.add_column("Status")
table.add_column("Run ID")

Expand All @@ -344,6 +366,7 @@ def list_runs(
r.project_display_name or "",
r.skill_name,
r.agent_id,
f"${r.cost_usd:.4f}" if r.cost_usd is not None else "-",
f"[{style}]{r.status}[/]",
r.run_uuid,
)
Expand Down
1 change: 1 addition & 0 deletions src/secfoo/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ def push_run(
"started_at": run.started_at,
"finished_at": run.finished_at,
"duration_seconds": run.duration_seconds,
"cost_usd": run.cost_usd,
"confluence_urls": run.confluence_urls,
},
"report_markdown": report_markdown,
Expand Down
2 changes: 1 addition & 1 deletion src/secfoo/config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
[defaults]
# Used whenever --agent / --depth / --timeout aren't passed on the command
# line. CLI flags always win over these.
agent = "claude" # claude | agent (Cursor) | agy (Antigravity) | gemini
agent = "claude" # claude | agent (Cursor) | agy (Antigravity) | gemini | secfoo
depth = "quick" # quick | standard
# timeout = 1800 # seconds; omit to use each agent's own default

Expand Down
9 changes: 5 additions & 4 deletions src/secfoo/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def _run_single_skill(
report_dir = run_dir(run_uuid)
report_dir.mkdir(parents=True, exist_ok=True)
prompt_path = report_dir / "prompt.md"
prompt_path.write_text(prompt)
prompt_path.write_text(prompt, encoding="utf-8")

if on_skill_start:
on_skill_start(skill.name)
Expand All @@ -207,11 +207,11 @@ def _run_single_skill(
if on_skill_complete:
on_skill_complete(skill.name, result.status)

(report_dir / "stdout.log").write_text(result.stdout)
(report_dir / "stderr.log").write_text(result.stderr)
(report_dir / "stdout.log").write_text(result.stdout, encoding="utf-8")
(report_dir / "stderr.log").write_text(result.stderr, encoding="utf-8")
report_path = report_dir / "report.md"
report_text = strip_preamble(result.raw_report)
report_path.write_text(report_text)
report_path.write_text(report_text, encoding="utf-8")
severity = count_severities(report_text)

repo.complete_run(
Expand All @@ -227,6 +227,7 @@ def _run_single_skill(
medium_count=severity.medium,
low_count=severity.low,
info_count=severity.info,
cost_usd=result.cost_usd,
)

if result.status == "success":
Expand Down
1 change: 1 addition & 0 deletions src/secfoo/storage/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class RunRecord:
info_count: int = 0
cloud_synced_at: str | None = None
project_display_name: str | None = None
cost_usd: float | None = None


@dataclass(frozen=True)
Expand Down
29 changes: 18 additions & 11 deletions src/secfoo/storage/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ def use_db_path(path: Path):
# existed on an upgraded local store (re-synced harmlessly by `secfoo
# cloud sync`, since ingestion is idempotent on the server side).
"cloud_synced_at": "ALTER TABLE runs ADD COLUMN cloud_synced_at TEXT",
"cost_usd": "ALTER TABLE runs ADD COLUMN cost_usd REAL",
}

_ASSESSMENTS_MIGRATIONS = {
Expand Down Expand Up @@ -247,24 +248,19 @@ def create_completed_run(
medium_count: int = 0,
low_count: int = 0,
info_count: int = 0,
cost_usd: float | None = None,
assessment_id: int | None = None,
) -> None:
"""Inserts a run that already fully happened elsewhere, in one
step, keyed by a caller-supplied `run_uuid` rather than minting a
new one. Used by the enterprise portal's ingestion API to
replicate a run the CLI already ran and completed locally --
unlike `create_run()` + `complete_run()`, which model a run
actually starting and finishing in this process.
"""
"""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) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
"critical_count, high_count, medium_count, low_count, info_count, cost_usd, assessment_id) "
"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,
critical_count, high_count, medium_count, low_count, info_count, assessment_id,
critical_count, high_count, medium_count, low_count, info_count, cost_usd, assessment_id,
),
)
self._conn.commit()
Expand All @@ -284,11 +280,12 @@ def complete_run(
medium_count: int = 0,
low_count: int = 0,
info_count: int = 0,
cost_usd: float | None = None,
) -> None:
self._conn.execute(
"UPDATE runs SET status = ?, exit_code = ?, finished_at = ?, duration_seconds = ?, "
"report_path = ?, prompt_path = ?, stderr_excerpt = ?, critical_count = ?, high_count = ?, "
"medium_count = ?, low_count = ?, info_count = ? WHERE run_uuid = ?",
"medium_count = ?, low_count = ?, info_count = ?, cost_usd = ? WHERE run_uuid = ?",
(
status,
exit_code,
Expand All @@ -302,6 +299,7 @@ def complete_run(
medium_count,
low_count,
info_count,
cost_usd,
run_uuid,
),
)
Expand Down Expand Up @@ -338,6 +336,15 @@ def _row_to_run(self, row: sqlite3.Row) -> RunRecord:
project_display_name = data.pop("display_name", None)
return RunRecord(confluence_urls=confluence_urls, project_display_name=project_display_name, **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"
params: list[object] = []
if project_id is not None:
query += " AND project_id = ?"
params.append(project_id)
row = self._conn.execute(query, params).fetchone()
return float(row["total"])

def list_runs(
self,
*,
Expand Down
3 changes: 2 additions & 1 deletion src/secfoo/storage/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ CREATE TABLE IF NOT EXISTS runs (
info_count INTEGER NOT NULL DEFAULT 0,
-- Set once `secfoo cloud` has pushed this run to the enterprise
-- portal. NULL means never synced (offline, or no `cloud login` yet).
cloud_synced_at TEXT
cloud_synced_at TEXT,
cost_usd REAL
);

-- Files manually uploaded to an assessment (AI-BOM inventories, or other
Expand Down
2 changes: 2 additions & 0 deletions src/secfoo/web/routes/overview.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def overview(request: Request):
third_party_count = repo.count_assessments(assessment_type="third_party")
responsible_ai_count = repo.count_assessments_with_responsible_ai_risk()
models_count, tools_count = repo.ai_bom_counts_total()
total_cost_usd = repo.total_cost_usd()
top_findings = build_top_findings(repo)

# Coverage is "projects that have had this activity run", so the
Expand Down Expand Up @@ -47,6 +48,7 @@ def overview(request: Request):
"responsible_ai_count": responsible_ai_count,
"models_count": models_count,
"tools_count": tools_count,
"total_cost_usd": total_cost_usd,
"top_findings": top_findings,
},
)
4 changes: 4 additions & 0 deletions src/secfoo/web/templates/overview.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ <h1>AI Security &amp; Assessment Hub</h1>
<span class="stat-card__value">{{ responsible_ai_count }}</span>
<span class="stat-card__label">Responsible AI coverage</span>
</div>
<div class="stat-card">
<span class="stat-card__value">${{ "%.4f" | format(total_cost_usd) }}</span>
<span class="stat-card__label">Recorded AI spend</span>
</div>
</div>

<h2 style="margin-top:var(--space-10)">Top findings across the program</h2>
Expand Down
Loading
Loading