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
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ doc/
identity.key
**/identity.key

# Key/cert material — #68 asserts these stay covered, regardless of shape
*.pem
*.key
id_rsa
id_ed25519

# Claude Code worktrees
.claude/worktrees/

Expand Down
13 changes: 11 additions & 2 deletions .gitleaks.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,13 @@ description = "BUZZ_PRIVATE_KEY or a similarly-named 64-hex-character private ke
# leaks the moment useDefault is active; (?:a|b) is unaffected). No known
# gitleaks issue was found describing this, so treat every future rule here
# the same way: no capturing groups, ever, unless secretGroup is set to use one.
regex = '''(?i)[A-Z0-9_]*(?:PRIVATE_KEY|NSEC|SECKEY)[A-Z0-9_]*\s*=\s*['"]?[0-9a-fA-F]{64}['"]?'''
#
# The key/separator segment accepts an optional closing quote before `:` or
# `=` — found missing by #68's own agent-surface fixtures, which are JSON
# (`"BUZZ_PRIVATE_KEY": "..."`), not `.env`-shaped (`BUZZ_PRIVATE_KEY=...`).
# A `.env` file has no key-side quote to close, so the `['"]?` before the
# separator is optional, not required, and both forms still match.
regex = '''(?i)[A-Z0-9_]*(?:PRIVATE_KEY|NSEC|SECKEY)[A-Z0-9_]*['"]?\s*[:=]\s*['"]?[0-9a-fA-F]{64}['"]?'''
tags = ["key", "nostr"]

[[rules]]
Expand All @@ -50,7 +56,10 @@ description = "BUZZ_S3_ACCESS_KEY or BUZZ_S3_SECRET_KEY assignment"
# punctuation character as if it were a credential. Requiring a real value
# shape excludes it without an allowlist entry, and still matches every
# fixture and every real assignment this rule exists for.
regex = '''BUZZ_S3_(?:ACCESS|SECRET)_KEY\s*=\s*['"]?[A-Za-z0-9_\-]{6,}['"]?'''
# `['"]?` before the separator and `[:=]` instead of a bare `=`: same JSON-vs-
# .env gap #68's fixtures found on buzz-private-key, above — applied here too
# for the same reason, even though no fixture has yet forced this one.
regex = '''BUZZ_S3_(?:ACCESS|SECRET)_KEY['"]?\s*[:=]\s*['"]?[A-Za-z0-9_\-]{6,}['"]?'''
tags = ["key", "s3", "minio"]
# .env.example is, by repository-wide convention, entirely placeholder
# values meant to be copied and replaced — verified against .env.example
Expand Down
38 changes: 38 additions & 0 deletions launchpad/scripts/security_audit_agent_surface.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""The agent-configuration surface, in one place, for #68 and any future check
that needs the same list.

**Adding a new agent tool means adding one entry here** — a new directory (a
fifth `.<tool>/` convention) or a new config filename shape (a fifth kind of
persona/plugin/MCP file). Nothing else in #68's check needs to change.

Two kinds of surface, because they show up differently in the tree:

AGENT_SURFACE_DIRS top-level dotdirs a specific agent tool owns.
Scanned whole — anything under one of these is
in scope, regardless of filename.
AGENT_CONFIG_FILE_GLOBS filename shapes an agent pack uses wherever it
lives (e.g. `launchpad/agents/the-professor/`,
not under any `.{tool}/` directory at all) —
matched by glob across the whole repository.
"""

from __future__ import annotations

#: Top-level directories a specific agent tool owns. Verified present at repo
#: root as of #68 (each currently holds only a `skills/` subtree, but that is
#: not asserted here — the whole directory is in scope, not just what it
#: happens to contain today).
AGENT_SURFACE_DIRS = [
".claude",
".codex",
".goose",
".agents",
]

#: Filename shapes an agent/persona pack uses, wherever in the repository it
#: lives. Glob patterns, matched with `Path.rglob` from the repo root.
AGENT_CONFIG_FILE_GLOBS = [
"**/.mcp.json",
"**/*.persona.md",
"**/plugin.json",
]
155 changes: 155 additions & 0 deletions launchpad/scripts/security_audit_agent_surface_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
"""Agent-configuration-surface check for #68.

Scans the agent-surface directories and config-file shapes defined in
`security_audit_agent_surface.py` for credential-shaped strings — reusing
#67's gitleaks ruleset (`.gitleaks.toml`) rather than a second pattern set,
per this task's own definition of done. This is a present-tense content
check (what does the surface carry *today*), not a history scan — #67 already
owns history; this check exists because the agent-surface directories are a
distinct, growing part of the tree a contributor or an agent itself might
populate with a real credential (a live API key dropped into an MCP config
for local testing, for instance) that #67's PR-diff scan would only catch if
the addition happened inside a PR gitleaks actually ran on.

Never prints a matched value — same discipline as #67's check, and the same
`--redact` flag on every gitleaks invocation.
"""

from __future__ import annotations

import json
import subprocess
from pathlib import Path
from typing import List, Optional, Tuple

from security_audit_agent_surface import AGENT_CONFIG_FILE_GLOBS, AGENT_SURFACE_DIRS
from security_audit_core import CheckResult, Status

NAME = "agent-surface-secret-scan"
GITLEAKS_CONFIG = ".gitleaks.toml"
_TIMEOUT_SECONDS = 60


def _collect_surface_paths(repo_root: Path) -> List[Path]:
"""Every file under an AGENT_SURFACE_DIRS directory, plus every file
matching an AGENT_CONFIG_FILE_GLOBS shape anywhere in the repo. A set,
not a list, so a file matched both ways (a persona.md inside .claude/,
say) is scanned once.
"""
paths: set[Path] = set()
for dir_name in AGENT_SURFACE_DIRS:
directory = repo_root / dir_name
if directory.is_dir():
paths.update(p for p in directory.rglob("*") if p.is_file())
for glob_pattern in AGENT_CONFIG_FILE_GLOBS:
paths.update(p for p in repo_root.glob(glob_pattern) if p.is_file())
return sorted(paths)


def _summarize(findings: List[dict], repo_root: Path, limit: int = 8) -> str:
"""file:line (rule-id), repo-relative, never the matched value."""
locations = set()
for f in findings:
try:
rel = Path(f.get("File", "?")).relative_to(repo_root)
except ValueError:
rel = f.get("File", "?")
locations.add(f"{rel}:{f.get('StartLine', '?')} ({f.get('RuleID', '?')})")
shown = sorted(locations)
text = ", ".join(shown[:limit])
if len(shown) > limit:
text += f", and {len(shown) - limit} more"
return text


def _run_gitleaks_no_git(
repo_root: Path, source_paths: List[Path]
) -> Tuple[Optional[List[dict]], Optional[str]]:
config_path = repo_root / GITLEAKS_CONFIG
if not config_path.is_file():
return None, f"{GITLEAKS_CONFIG} not found at {config_path}"
if not source_paths:
return [], None

findings: List[dict] = []
for path in source_paths:
cmd = [
"gitleaks",
"detect",
"--no-git",
"--source",
str(path),
"--config",
str(config_path),
"--report-format",
"json",
"--report-path",
"-",
"--redact",
"--no-banner",
]
try:
result = subprocess.run(
cmd,
cwd=repo_root,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=_TIMEOUT_SECONDS,
)
except FileNotFoundError:
return None, "gitleaks is not installed or not on PATH"
except subprocess.TimeoutExpired:
return None, f"gitleaks did not finish within {_TIMEOUT_SECONDS}s scanning {path}"
except OSError as exc:
return None, f"could not run gitleaks on {path}: {exc}"

if result.returncode not in (0, 1):
stderr = (result.stderr or "").strip()[-500:]
return None, f"gitleaks exited {result.returncode} on {path}: {stderr}"

try:
file_findings = json.loads(result.stdout) if result.stdout.strip() else []
except json.JSONDecodeError as exc:
return None, f"could not parse gitleaks report for {path}: {exc}"
findings.extend(file_findings)

return findings, None


def run(repo_root: Path) -> CheckResult:
surface_paths = _collect_surface_paths(repo_root)
if not surface_paths:
# Nothing to scan is not a clean scan. Without this, a sparse checkout,
# a refactor that moves the agent-config directories, or any environment
# where AGENT_SURFACE_DIRS and AGENT_CONFIG_FILE_GLOBS resolve to nothing
# produces "no credential-shaped strings found across 0 agent-surface
# file(s)" — indistinguishable in the summary from a real clean scan of
# the full surface, and green because exit_code() only fails on FAIL. A
# security check that reports clean when it did not run is worse than no
# check. Same fail-closed shape as security_audit_ignore_coverage_check's
# unreadable-file case.
return CheckResult(
NAME,
Status.INDETERMINATE,
"no agent-surface files were found to scan, so this control asserts "
"nothing — this is not the same as scanning the surface and finding it "
f"clean. Looked for {list(AGENT_CONFIG_FILE_GLOBS)} under "
f"{list(AGENT_SURFACE_DIRS)} in {repo_root}",
)
findings, error = _run_gitleaks_no_git(repo_root, surface_paths)
if error is not None:
return CheckResult(NAME, Status.INDETERMINATE, error)
if findings:
return CheckResult(
NAME,
Status.FAIL,
f"{len(findings)} finding(s) on the agent-config surface: "
+ _summarize(findings, repo_root),
)
return CheckResult(
NAME,
Status.PASS,
f"no credential-shaped strings found across {len(surface_paths)} agent-surface file(s)",
)
98 changes: 98 additions & 0 deletions launchpad/scripts/security_audit_ignore_coverage_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""Ignore-coverage check for #68: the patterns that must never stop being
ignored, asserted directly against the files that carry them — not inferred
from `git check-ignore`, which would also report false if the file simply
doesn't exist.

Two files, because that is where the coverage actually lives today:

.gitignore repo-wide: env files, identity keys,
key/cert material.
launchpad/deploy/archived/.gitignore the deploy-secrets folder's own patterns
(env, keys, the generated `seed/` /
`seed.sample/` cloud-init output).

The second path moved once already — from `launchpad/deploy/.gitignore` to
`launchpad/deploy/archived/.gitignore` when the deploy method was archived,
after #68 was filed against the old path. Asserted against where the file
actually is today, not where the issue text says it was. If it moves again,
this check goes INDETERMINATE (missing file), not silently passes on nothing
— see `_read_lines`.

Coverage is checked as **literal line presence** — the exact pattern string
must appear as its own line in the file. This is deliberately stricter than
asking gitignore's own matcher whether a sample path would be ignored: a
functionally-equivalent but differently-spelled pattern (`*.env` vs `.env`)
would pass a matcher-based check while silently changing what's actually
covered, and this check exists to catch that kind of drift, not paper over it.
"""

from __future__ import annotations

from pathlib import Path
from typing import Dict, List

from security_audit_core import CheckResult, Status

NAME = "ignore-coverage"

#: repo-relative gitignore path -> patterns that MUST be present, one per line.
REQUIRED_COVERAGE: Dict[str, List[str]] = {
".gitignore": [
".env",
".env.local",
".env.*.local",
"identity.key",
"**/identity.key",
"*.pem",
"*.key",
"id_rsa",
"id_ed25519",
],
"launchpad/deploy/archived/.gitignore": [
"seed/",
"seed.sample/",
],
}


def _read_lines(path: Path) -> List[str] | None:
try:
return path.read_text(encoding="utf-8").splitlines()
except OSError:
return None


def run(repo_root: Path) -> CheckResult:
missing: List[str] = []
unreadable: List[str] = []

for rel_path, patterns in REQUIRED_COVERAGE.items():
lines = _read_lines(repo_root / rel_path)
if lines is None:
unreadable.append(rel_path)
continue
line_set = set(lines)
for pattern in patterns:
if pattern not in line_set:
missing.append(f"{rel_path}: {pattern!r}")

if unreadable:
return CheckResult(
NAME,
Status.INDETERMINATE,
"could not read " + ", ".join(unreadable) + " — coverage cannot be asserted "
"against a file this check cannot find; this is not the same as the patterns "
"being absent from an existing file",
)
if missing:
return CheckResult(
NAME,
Status.FAIL,
f"{len(missing)} required ignore pattern(s) missing: " + "; ".join(missing),
)
return CheckResult(
NAME,
Status.PASS,
f"all {sum(len(p) for p in REQUIRED_COVERAGE.values())} required patterns present "
f"across {len(REQUIRED_COVERAGE)} file(s)",
)
14 changes: 10 additions & 4 deletions launchpad/scripts/security_audit_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,21 @@
CHECKS. Nothing else changes — not this file's structure, not the workflow YAML,
not security_audit.py.

Empty except for the self-test today; #62's detection checks (secret material,
ignore coverage, Actions hygiene, settings attestation) land here as separate
tasks.
#62's detection checks (secret material, ignore coverage, Actions hygiene,
settings attestation) land here as separate tasks; Actions hygiene and
settings attestation remain.
"""

from security_audit_selftest_check import run as harness_self_test
from security_audit_agent_surface_check import run as agent_surface_secret_scan
from security_audit_ignore_coverage_check import run as ignore_coverage
from security_audit_secrets_check import run as secret_material_scan
from security_audit_selftest_check import run as harness_self_test
from security_audit_tracked_files_check import run as tracked_sensitive_files

CHECKS = [
harness_self_test,
secret_material_scan,
ignore_coverage,
tracked_sensitive_files,
agent_surface_secret_scan,
]
Loading
Loading