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
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,22 +43,22 @@ A code repository is one input. Real reviews also need the design doc, the
threat model from last year, the runbook and the ticket that explains why the
odd thing is there. secfoo passes that context to the agent through
[MCP](https://modelcontextprotocol.io) and asks the skills to use it:
the architecture review compares what is *documented* (Confluence, README,
ADRs) with what is *implemented* and reports the gaps; secret scanning
covers linked Confluence pages as well as code; every report ends with a
coverage section that says which documentation sources were reached and
which were not.
the architecture review compares what is *documented* (the provided
documentation sources, README, ADRs) with what is *implemented* and reports
the gaps; secret scanning covers linked documentation sources as well as code;
every report ends with a coverage section that says which documentation sources
were reached and which were not.

```bash
secfoo run --skill security-architecture-review --skill threat-modeling \
--target https://github.com/org/payments-api \
--confluence https://yourcompany.atlassian.net/wiki/spaces/PAY/pages/123/Architecture \
--confluence https://yourcompany.atlassian.net/wiki/spaces/SEC/pages/456/Threat+Model
--context https://yourcompany.atlassian.net/wiki/spaces/PAY/pages/123/Architecture \
--context ../design-docs/threat-model.pdf
```

Connect the documentation sources once in `~/.secfoo/config.toml`; any MCP
Connect remote documentation sources once in `~/.secfoo/config.toml`; any MCP
server works, so the same applies to SharePoint and Microsoft 365, Jira,
Notion, Google Drive or an internal wiki:
Notion, Google Docs or an internal wiki:

```toml
[[mcp_servers]]
Expand All @@ -75,7 +75,7 @@ headers = { Authorization = "Bearer ..." }

| Context | How it gets in | Used by |
|---|---|---|
| Confluence pages | `--confluence <url>` (repeatable) plus an Atlassian MCP server | Architecture review, threat modeling, secret scanning, compliance skills |
| Documentation sources (Confluence, Jira, SharePoint, Notion, Google Docs, local PDF/DOCX/Markdown) | `--context <url\|path>` (repeatable; `--confluence` / `-c` alias) with an MCP server or local file extraction | Architecture review, threat modeling, secret scanning, compliance skills |
| Jira, SharePoint, Notion, Google Drive, internal wikis | `[[mcp_servers]]` in config; the agent calls them as tools during the review | Every skill |
| Vendor documents (PDF, DOCX, PPTX) and AI-BOM files | `secfoo assessment upload <id> <file>` | Third-party risk assessment, Responsible AI compliance |
| Curated vulnerability patterns | `secfoo memory signup` (optional hosted service, exposed as an MCP server) | SAST, SCA, secret scanning |
Expand Down
21 changes: 21 additions & 0 deletions docs/CI.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,27 @@ Cap spend with `--max-cost`; Claude and the `api` agent report real USD,
Gemini reports tokens only, Cursor and Antigravity report nothing (those
runs count as `unpriced_runs` in the JSON and never pass a cap as "$0").

## Passing documentation context in CI

Pass architecture docs, threat models, or wiki specifications to the agent with `--context`:

```bash
secfoo run --agent claude --target . --depth quick --json \
--skill security-architecture-review --skill threat-modeling \
--context https://yourcompany.atlassian.net/wiki/spaces/SEC/pages/123 \
--context ../external-specs/architecture.pdf > secfoo-result.json
```

- **HTTPS URLs:** Require an MCP server configured on the runner for that host (e.g. in `~/.secfoo/config.toml`), otherwise the agent cannot query the service and the source will be recorded as not reached in the coverage table. `--agent api` cannot read URL sources and records them as not reached, while local files work with every agent because secfoo inlines them.
- **Local files:** Must live **outside** the target checkout being scanned (e.g. checked out to a sibling directory or staged from an external workflow artifact). Passing a file or folder inside the scanned target is rejected with exit code `2`.
- **Failing CI on unreached documentation:** If your pipeline requires all declared context sources to be verified and reached by the agent, check the `--json` output with `jq`:

```bash
jq -e '[.runs[].context_sources[] | select(.reached | not)] | length == 0' secfoo-result.json
```

A URL source is only reachable when the agent has an MCP server for it, so CI that gates on `reached` will also fail for that reason.

## GitHub Actions

### The Action
Expand Down
82 changes: 80 additions & 2 deletions docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -744,11 +744,12 @@ SARIF upload) is covered in [CI.md](CI.md).
# Run a skill against the current directory with Claude Code
secfoo run --skill security-architecture-review --agent claude

# Run multiple skills against a GitHub repo, with Confluence context
# Run multiple skills against a GitHub repo, with documentation context
secfoo run \
--skill security-architecture-review --skill threat-modeling \
--target https://github.com/org/repo \
--confluence https://yourcompany.atlassian.net/wiki/spaces/SEC/pages/123 \
--context https://yourcompany.atlassian.net/wiki/spaces/SEC/pages/123 \
--context ../design-docs/architecture.pdf \
--agent agent

# See what's on PATH
Expand Down Expand Up @@ -796,6 +797,78 @@ only, `agent`/`agy` report nothing. Runs with no reported cost count as
ingest — spend can't be recomputed server-side from report text the way
severity counts are.

### Providing documentation context (`--context`)

Security assessments are more accurate when the agent has design context (architecture specifications, threat models, API definitions, or runbooks) alongside source code. Pass external documentation with `--context`:

```bash
secfoo run --skill security-architecture-review \
--target . \
--context https://yourcompany.atlassian.net/wiki/spaces/SEC/pages/123 \
--context ../shared-docs/architecture.pdf \
--context ../docs/threat-model.docx \
--context ../specs/
```

- **Repeatable & types supported:**
- **HTTPS URLs:** Any `https://` documentation link (Confluence, Jira, SharePoint, Notion, Google Docs, etc.).
- **Local files:** Markdown (`.md`, `.markdown`), plain text (`.txt`), and document files (`.pdf`, `.docx`, `.pptx`).
- **Local folders:** Directories containing supported file types.
- `--confluence` / `-c` is retained as a backwards-compatible alias for `--context`.
- **Path resolution & deduplication:**
Relative paths are resolved against the directory secfoo is run from, `~` is expanded, and the same value written two ways counts once.
- **Merge order:**
Context sources are merged in this order:
1. Config file `[defaults].context` (in `~/.secfoo/config.toml`)
2. `--confluence` CLI flags
3. `--context` CLI flags
- **Validation and rejection rules (exit code 2):**
Inputs are validated strictly before runs start. Any invalid source causes `secfoo run` to exit immediately with code `2`:
- Plain `http://` is forbidden (must use `https://`).
- URLs with embedded credentials (e.g. `https://user:pass@host`) are rejected.
- URLs missing a hostname or containing whitespace are rejected.
- Local paths that do not exist trigger an error (scheme-less URLs like `wiki.example.com` receive a hint that URLs require the `https://` prefix).
- Unsupported local file extensions are rejected (supported: `.docx`, `.markdown`, `.md`, `.pdf`, `.pptx`, `.txt`).
- **Target boundary enforcement:** Local context files and folders must live *outside* the target being scanned, and cannot contain the target (a target folder cannot be inside a context folder). secfoo checks real filesystem identity (resolving symlinks, casing, and path traversals, failing closed on permission error) to ensure context files are strictly external reference material, not code under review.
- **How sources are presented to the agent:**
- **HTTPS URLs:** Grouped and classified in the prompt brief by host kind (`confluence`, `jira`, `sharepoint`, `notion`, `google_docs`, `other`). secfoo checks the host against configured `[[mcp_servers]]` (including server `hosts` patterns) and names the likely MCP server for the agent to invoke (matching server names, commands, or URLs from `[[mcp_servers]]`; credentials and environment values are never printed). If no matching MCP server is configured, secfoo states a coverage gap in the brief. Only URLs provided via `--confluence` or classified as Confluence populate `confluence_urls` for skill prompts with dedicated Confluence instructions; other URL kinds are presented purely as reference context with their likely reader tools.
- **Local files and folders:** Extracted directly by secfoo and inlined into the prompt brief as untrusted reference material (the prompt explicitly instructs the agent to treat context as reference data and never follow instructions found within it). Local extraction is bounded by plain limits:
- 20,000 characters per source (text files read up to 80,000 bytes; documents up to 25 MB).
- 60,000 characters in total across all local sources.
- 50 files per folder examined. Symlinks are never followed. A folder that exceeds the file cap is marked truncated in its note and still counts as reached. When post-truncation file inspection reaches the safety limit (10,000 files), the note reports `truncated: at least <k> more files not read (<reason>)`.
- Two local files with the same name are labelled with enough parent folder names to tell them apart (e.g. `a/README.md` and `b/README.md`).
- **Web dashboard integration:**
The web dashboard's Run Assessment form (`/assessments/{id}/runs`) includes a "Documentation context (optional)" field, accepting one HTTPS URL or local file/folder path per line. It merges with `[defaults].context`, enforces the same target boundary and URL validation rules, and passes resolved context sources into the run.
- **Configuring default context sources:**
In `~/.secfoo/config.toml`:
```toml
[defaults]
context = [
"https://yourcompany.atlassian.net/wiki/spaces/SEC/pages/123",
"/shared/docs/security-baseline.md",
]
```
- **Documentation coverage table & reporting:**
When one or more context sources are given, the prompt asks the agent to add a `### Documentation coverage` table at the end of its Coverage Notes section (Secret Scanning uses its section 5 for it). The table may sit under any heading level (such as `##`, `###`, `####`, or numbered headings like `## 5. Documentation coverage`), with the columns shown:
```markdown
| Source | Type | Reached | Notes |
|---|---|---|---|
| https://yourcompany.atlassian.net/wiki/spaces/SEC/pages/123 | Confluence page | Yes | Reviewed architecture and trust boundaries |
| architecture.pdf | local file | Yes | Inlined by secfoo |
```
On run completion, secfoo parses this table and reconciles each declared context source (marking whether it was reached and preserving the agent's notes). Matching rule: a row matches a source only when its Source cell is that source's label (a URL or a file/folder name; markdown links and one trailing "(note)" are tolerated); there is no fuzzy or positional matching; a source with no matching row is recorded as not reported ("not reported by the agent"). If the run itself does not complete, URL sources are recorded as not reached ("run did not complete") while local files secfoo already inlined stay reached. The coverage is saved in the local database (`context_sources` table per run) and displayed in the web dashboard run detail view (with a `documentation sources: X of Y reached` receipt line and a Documentation coverage table card with status badges).
- **Machine-readable JSON output:**
When passing `--json`, each run object in `runs` includes a `context_sources` array:
```json
{
"source": "https://yourcompany.atlassian.net/wiki/spaces/SEC/pages/123",
"type": "Confluence page",
"reached": true,
"notes": "Reviewed architecture and trust boundaries"
}
```
Values for `type` produced by secfoo are `Confluence page`, `Jira`, `SharePoint`, `Notion`, `Google Docs`, `other URL`, `local file`, and `local folder`. Rows the agent adds beyond the declared sources use the agent's own type text.

## Assessments

An **assessment** is a case-file container -- an Application ID / Security
Expand Down Expand Up @@ -841,6 +914,8 @@ secfoo config init # writes a starter ~/.secfoo/config.toml
[defaults]
agent = "claude"
depth = "quick"
# Default documentation sources (HTTPS URLs, local files or folders)
context = ["https://yourcompany.atlassian.net/wiki/spaces/SEC/pages/123"]
# Vendored copies / unrelated repos checked out inside a project. Added to
# the built-in exclusions (node_modules/, .git/, ...), never replacing them.
exclude = ["vendor/", "some-cloned-repo/"]
Expand All @@ -859,8 +934,11 @@ max_input_tokens = 150000
name = "Atlassian-Rovo-MCP"
command = "npx"
args = ["-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"]
hosts = ["wiki.internal.example", "*.atlassian.net"]
```

The optional `hosts` array specifies hostnames or domain patterns served by this MCP server (e.g. `["wiki.internal.example", "*.atlassian.net"]`). A `*.` pattern matches subdomains only; list the bare domain too if needed. secfoo uses `hosts` to route URL context sources to their likely MCP readers and classify internal enterprise Confluence / Jira URLs.

CLI flags always override `[defaults]`. See
[`src/secfoo/config.example.toml`](../src/secfoo/config.example.toml) for the
full reference, including remote HTTP/SSE servers.
Expand Down
14 changes: 14 additions & 0 deletions fuzz/fuzz_parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@
import atheris

with atheris.instrument_imports():
from secfoo.report.context_coverage import (
MAX_NOTES_CHARS,
MAX_ROWS,
MAX_SOURCE_CHARS,
MAX_TYPE_CHARS,
parse_documentation_coverage,
)
from secfoo.report.severity import count_severities, extract_overall_risk_rating
from secfoo.skills.loader import SkillLoadError, _parse_frontmatter
from secfoo.web.finding_filters import normalize_severity
Expand All @@ -36,6 +43,13 @@ def test_one_input(data: bytes) -> None:
assert counts.total == counts.critical + counts.high + counts.medium + counts.low + counts.info
rating = extract_overall_risk_rating(text)
assert rating is None or rating == rating.lower()
coverage_rows = parse_documentation_coverage(text)
assert len(coverage_rows) <= MAX_ROWS
for row in coverage_rows:
assert len(row.source) <= MAX_SOURCE_CHARS
assert len(row.type) <= MAX_TYPE_CHARS
assert len(row.notes) <= MAX_NOTES_CHARS
assert isinstance(row.reached, bool)

# Frontmatter parsing may reject input, but only with SkillLoadError.
try:
Expand Down
41 changes: 33 additions & 8 deletions src/secfoo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import typer
from rich.console import Console
from rich.markup import escape
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.prompt import Confirm, Prompt
from rich.table import Table
Expand All @@ -25,6 +26,8 @@
from secfoo.attachments import infer_attachment_kind
from secfoo.cloud import CloudConfig, CloudError
from secfoo.config import CLOUD_CONFIG_PATH, STORE_DIR, attachment_dir
from secfoo.context_run import resolve_run_context
from secfoo.context_sources import ContextSourceError
from secfoo.cost import format_cost, format_tokens, sum_optional
from secfoo.report.sarif import findings_to_sarif
from secfoo.runner import _project_display_name, already_scanned_skills, execute_runs
Expand Down Expand Up @@ -294,8 +297,14 @@ def run(
None, "--target", "-t", help="GitHub URL or local directory. Defaults to the current directory."
),
confluence: list[str] = typer.Option(
[], "--confluence", "-c", help="Confluence page URL for extra context. Repeatable."
[], "--confluence", "-c", help="Alias of --context, kept for existing scripts. Repeatable."
),
context: Annotated[list[str] | None, typer.Option(
"--context",
help="Documentation source for the agent to read: an https:// URL (Confluence, Jira, "
"SharePoint, Notion, Google Docs) or a local Markdown, text, PDF, DOCX or PPTX file or "
"folder. Repeatable, and added on top of [defaults].context in ~/.secfoo/config.toml.",
)] = None,
agent: Optional[AgentId] = typer.Option(
None,
"--agent",
Expand Down Expand Up @@ -398,12 +407,6 @@ def run(
but the --fail-on gate tripped, 3 all runs succeeded but the --max-cost
gate tripped.
"""
for url in confluence:
if not url.strip().lower().startswith(("http://", "https://")):
(err_console if json_output else console).print(
f"[yellow]Warning:[/] {url!r} doesn't look like a URL — passing it through anyway."
)

skill_file_entries = skill_file or []
skill_sha256_entries = skill_sha256 or []
if len(skill_sha256_entries) > len(skill_file_entries):
Expand Down Expand Up @@ -480,6 +483,22 @@ def run(
# config's list, so naming one path can't silently drop the others.
exclude_paths = _merge_excludes(file_defaults.exclude, exclude)

try:
scanned_dir = resolve_target(target).path
except TargetResolutionError:
scanned_dir = None # execute_runs reports the bad target below
try:
run_context = resolve_run_context(
defaults_context=file_defaults.context,
confluence_values=confluence,
context_values=context or [],
target_dir=scanned_dir,
mcp_servers=file_config.mcp_servers,
)
except ContextSourceError as exc:
err_console.print(f"[red]Error:[/] {escape(str(exc))}")
raise typer.Exit(code=2) from None

# Memory Bank: on a terminal, ask before repeating a scan of a commit that
# was already scanned. Only here, never in execute_runs(), which the
# dashboard and CI also call with no terminal to answer.
Expand Down Expand Up @@ -539,7 +558,9 @@ def handle_complete(skill_name: str, result_status: str) -> None:
outcomes = execute_runs(
skill_ids=skill_ids,
target=target,
confluence_urls=confluence,
confluence_urls=run_context.confluence_urls,
context_sources=run_context.sources,
mcp_servers=file_config.mcp_servers,
agent_id=agent.value,
model=model,
max_input_tokens=max_input_tokens,
Expand Down Expand Up @@ -613,6 +634,10 @@ def handle_complete(skill_name: str, result_status: str) -> None:
"low": o.low_count,
"info": o.info_count,
},
"context_sources": [
{"source": c.source, "type": c.type, "reached": c.reached, "notes": c.notes}
for c in o.context_sources
],
}
for o in outcomes
],
Expand Down
Loading