Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(security): gate a change on the findings it adds in CI (#2635)

Raghav Chamadiya77f6f1a28970
diff --git a/docs/business/COMMERCIAL.md b/docs/business/COMMERCIAL.md
index 64770c5a2..d98cd36c9 100644
--- a/docs/business/COMMERCIAL.md
+++ b/docs/business/COMMERCIAL.md
@@ -169,6 +169,7 @@ the items that matter most to you can be prioritized.
| Auto-generated CLAUDE.md | ✅ | ✅ |
| Test intelligence (coverage ingestion **and** the graph-inferred test map) | ✅ | ✅ |
| Local full-history secret scan (`repowise security scan --history`) | ✅ | ✅ |
+| Local CI security gate on a change (`repowise security check`, SARIF output, committed baseline) | ✅ | ✅ |
| Graph-aware enhanced security scanning | — | ✅ *(GA on hosted)* |
| Language-specific security rulesets | — | ✅ *(dev)* |
| CVE-aware dependency analysis (KEV / EPSS / priority-scored) | — | ✅ *(GA on hosted)* |
diff --git a/docs/layers/SECURITY.md b/docs/layers/SECURITY.md
index 45499cdd2..d6fa8c5cc 100644
--- a/docs/layers/SECURITY.md
+++ b/docs/layers/SECURITY.md
@@ -21,18 +21,23 @@ repowise init # working-tree signals populate during index
repowise security scan --history # walk every tracked revision for leaked secrets
repowise security scan --history --since v1.0.0 --to HEAD
repowise security scan --history --all-patterns --format json
+repowise security check origin/main...HEAD # CI gate on what a change adds (see below)
```
+`scan --history` stores what it finds and prints counts, not a list:
+
```
repowise security scan --history
-
- 8 findings across 412 commits
-
- high hardcoded_secret config/settings.py:14 a3f19c2 2025-11-04
- high hardcoded_password deploy/bootstrap.sh:31 91b7ee0 2025-08-22
- high hardcoded_secret tests/fixtures/auth.py:7 4c02da8 2025-06-13
+ Commits scanned: 412
+ Blobs scanned: 2318
+ Files scanned: 1604
+ Findings stored: 8
+ By severity: high=6, low=2
+ By kind: aws_access_key=1, hardcoded_password=2, hardcoded_secret=5
```
+The findings themselves are read where the stored rows surface, below.
+
From an agent, through the risk surface:
```python
@@ -45,8 +50,12 @@ Findings also appear on the Security tab of the code-health page, and at
## What the registry catches
Twenty-two patterns plus a symbol-name scan, giving twenty-three kinds across
-three severities. Severity is a fixed property of the pattern; nothing is
-scored, ranked, or aggregated.
+three severities. Severity is a fixed property of the pattern, with one
+exception: a secret kind found in test material, or under a directory named
+`test`, `tests`, `__tests__`, `__test__`, `fixtures`, `__fixtures__`, `spec`,
+`specs`, `mock`, `mocks`, `__mocks__`, `example` or `examples`, is recorded at
+`low`, since those are mostly fake keys but a real one is still
+worth seeing. Nothing is scored, ranked, or aggregated.
| Kind | Severity | Matches |
|------|----------|---------|
@@ -211,14 +220,110 @@ Both paths land in the same `security_findings` table, with a unique constraint
on `(repository_id, file_path, kind, line_number, commit_sha)`. Re-running either
scan is idempotent.
+## In CI: `repowise security check`
+
+A third surface, for pull requests. It needs git and nothing else: no index,
+no database, no API key, and it stores nothing.
+
+```bash
+repowise security check origin/main...HEAD
+repowise security check --fail-on med --format github
+repowise security check --format sarif > security.sarif
+```
+
+It judges what the change adds, not the repository:
+
+- **At the change's head**, every file the change touched is scanned as the
+ head commit has it, and a finding counts only when a line it spans is one
+ the change added or edited. The two multi-line kinds count when any line of
+ their span changed, so editing only the `shell=True` line of a call, or only
+ the body of a PEM key, still counts. In a documentation file (`.md`, `.mdx`,
+ `.rst`, `.txt`, `.adoc`) only the secret kinds count: prose naming
+ `pickle.loads` is not a call, but a key pasted into a README is a leak.
+- **Inside the change**, every commit in the range is scanned the same way
+ for the secret kinds only. A key committed in one commit and deleted in the
+ next is absent from the head and present in every clone; the gate reports it
+ with the commit that added it and says to rotate it. Merge commits are
+ skipped, so merging the target branch in does not blame its lines on the
+ change. A code smell added and removed inside the change does not count.
+
+`--fail-on` names the lowest severity that fails (`high` by default, then
+`med`, `low`). A secret under a test, fixture, spec, mock or example path is
+`low` (see above), so under the default it shows as a warning and does not
+fail; pass `--fail-on low` to fail on those too. Exit codes are the ones every
+repowise CI gate uses: `0` passed,
+`1` failed, `2` could not evaluate (not a git repository, unknown revision, no
+merge-base in a shallow clone, a commit of the change cut off by a shallow
+clone, an unreadable baseline). A git error is never read as a clean change.
+
+Every format carries the masked snippet only, because CI logs are often
+public: `table`, `json`, `markdown`, `github` (annotations plus the job
+summary) and `sarif` (for code-scanning upload). The gate is the registry
+above and has its limits: a pass means no pattern matched a changed line.
+
+**Baseline.** `--write-baseline FILE` records the change's findings in a
+committed JSON file and exits 0; `--baseline FILE` accepts what it lists, so
+only new findings fail. A finding is keyed on its file, kind and masked
+matched line, so it stays accepted when an edit above it shifts its line
+number. The vendor key shapes mask to their fixed prefix (`AKIA****`), so their
+key also takes a one-way hash of the matched text: a different key on an
+identical line is a new finding. The file never holds a raw value. The keyword
+kinds (`hardcoded_password`, `hardcoded_secret`) stay keyed on the masked line
+alone, because a short password could be guessed back from a hash of it; a
+different value sharing the first four characters on an identical line stays
+accepted. Because the gate sees one change at a time, writing to an existing
+baseline adds to its entries (and to those of `--baseline`, when given)
+instead of replacing them; remove an entry by deleting it from the file.
+`--format sarif` marks accepted findings as suppressed.
+
+GitHub Actions, with the SARIF uploaded from your own workflow:
+
+```yaml
+on: pull_request
+permissions:
+ contents: read
+ actions: read # upload-sarif needs it in a private repository
+ security-events: write
+jobs:
+ security:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0 # the gate reads every commit of the change
+ - run: pip install repowise
+ - run: repowise security check --format github --baseline .security-baseline.json
+ - if: always()
+ run: |
+ repowise security check --format sarif --baseline .security-baseline.json > security.sarif || true
+ [ -s security.sarif ] || rm security.sarif
+ - if: always() && hashFiles('security.sarif') != ''
+ uses: github/codeql-action/upload-sarif@v3
+ with:
+ sarif_file: security.sarif
+```
+
+A pull request from a fork runs with a read-only token, so the upload step
+fails there; the gate step itself still runs and still fails the check. When
+the gate cannot evaluate (exit 2) the SARIF file is empty, so it is removed
+and the upload is skipped.
+
+Without a REVSPEC the base comes from the CI's pull-request variables
+(`GITHUB_BASE_REF`, GitLab's `CI_MERGE_REQUEST_TARGET_BRANCH_NAME`, Jenkins'
+`CHANGE_TARGET`, Bitbucket's `BITBUCKET_PR_DESTINATION_BRANCH`), else the
+remote's default branch. A shallow checkout cannot be read commit by commit,
+so fetch the full history; the gate exits 2 rather than guess.
+
## Line verification
A finding's `line_number` is written at scan time, and the file moves on. A wrong
line on a security finding is worse than none: it sends the reader to innocent
code while looking authoritative. So the line is re-checked against the live file
-every time a finding is served, using the stored snippet — the first 120
-characters of the matched line, which is always a substring of the line it came
-from.
+every time a finding is served, using the stored snippet: the matched line,
+stripped and trimmed to 120 characters, with every credential value on it
+masked to its first four characters and `****`. An unmasked snippet is a
+substring of the line it came from; a masked one is matched on the text before
+the first `****`.
Three outcomes, on every finding the API returns:
@@ -246,8 +351,8 @@ One table, `security_findings`, written by both scan paths:
|---|---|
| `file_path` | Repo-relative |
| `kind` | One of the kinds in the table above |
-| `severity` | `high`, `med`, `low` — fixed per pattern |
-| `snippet` | Matched line, trimmed to 120 characters; a symbol name for `security_sensitive_symbol` |
+| `severity` | `high`, `med`, `low`: fixed per pattern, except a secret kind in test material is `low` |
+| `snippet` | Matched line, trimmed to 120 characters, credential values masked (`AKIA****`); a symbol name for `security_sensitive_symbol`. The raw value is never stored |
| `line_number` | As of scan time; verified at serve time |
| `commit_sha` | Empty for working-tree rows, the introducing commit for history rows |
| `commit_at` | Author date, history rows only |
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 408f3958a..bdd06d82c 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -902,12 +902,14 @@ counts. See [Branch overlap](../layers/CHANGE_RISK.md#branch-overlap).
Security signal scanning. Working-tree scanning already runs during
`repowise init` / `repowise update`. The CLI group exists so you can also walk
**full git history** for leaked secrets and risky patterns that were later
-removed (something the working-tree scan cannot see).
+removed (something the working-tree scan cannot see), and to gate a change in
+CI.
**Subcommands:**
```bash
repowise security scan --history [OPTIONS]
+repowise security check [REVSPEC] [OPTIONS] # CI gate on what a change adds
```
Without `--history`, `security scan` prints a short hint and exits — it does
@@ -921,7 +923,7 @@ not re-run the working-tree scan.
| `--since <rev>` | Lower git revision bound (exclusive). Defaults to all history |
| `--to <rev>` | Upper git revision bound (inclusive). Defaults to HEAD / all history |
| `--path <dir>` | Repo path (defaults to cwd / workspace primary) |
-| `--all-patterns` | History mode: also report code-smell patterns (`eval`, `os.system`, weak hashes, …). Default history mode reports only leaked-secret patterns (`hardcoded_password` / `hardcoded_secret`) to avoid noise |
+| `--all-patterns` | History mode: also report code-smell patterns (`eval`, `os.system`, weak hashes, …). Default history mode reports only leaked-secret patterns (the credential assignments and vendor key shapes) to avoid noise |
| `--format` | `table` (default) or `json`. `--output` is a deprecated alias, still accepted; when both are given `--output` wins |
```bash
@@ -931,7 +933,43 @@ repowise security scan --history --all-patterns --format json
```
Findings are written to the `security_findings` table (idempotent on re-run)
-and surface in the local server security API / UI.
+and surface in the local server security API / UI. The command prints counts;
+read the findings there.
+
+#### `repowise security check [REVSPEC]`
+
+Gate a change on the security findings it adds. Built for CI: it needs git and
+nothing else (no index, no database, no API key) and stores nothing. It scans
+the files the change touched, as its head has them, and keeps the findings on
+changed lines; secret kinds are also checked in every commit of the change, so
+a key committed and then deleted inside it still fails. Snippets are masked in
+every format.
+
+REVSPEC is the change: `origin/main...HEAD` (the pull-request view),
+`base..head`, or one commit. Without it, the base comes from the CI's
+pull-request variables (GitHub, GitLab, Jenkins, Bitbucket), else the remote's
+default branch.
+
+| Flag | Description |
+|------|-------------|
+| `--fail-on` | Exit 1 on a finding of this severity or above: `high` (default), `med`, `low`. A secret under a test, fixture, spec, mock or example path is `low` |
+| `--baseline` | Accept the findings recorded in this file; only new ones fail |
+| `--write-baseline` | Add this change's findings to this file, keeping its entries and those of `--baseline`, and exit 0 |
+| `--path` | A path inside the repository (defaults to cwd) |
+| `--format` | `table` (default), `json`, `markdown`, `github`, `sarif` |
+
+```bash
+repowise security check origin/main...HEAD
+repowise security check --format github --baseline .security-baseline.json
+repowise security check --format sarif > security.sarif
+repowise security check --write-baseline .security-baseline.json
+```
+
+Exit codes: `0` gate passed, `1` gate failed, `2` could not evaluate (not a git
+repository, unknown revision, a shallow clone missing the merge-base or cutting
+a commit of the change, an unreadable baseline). Check out with full history
+(`fetch-depth: 0`). See [In CI](../layers/SECURITY.md#in-ci-repowise-security-check)
+for the scoping rules and a GitHub Actions recipe with SARIF upload.
---
diff --git a/packages/cli/src/repowise/cli/ci.py b/packages/cli/src/repowise/cli/ci.py
index ca787e5c7..273fbe1c3 100644
--- a/packages/cli/src/repowise/cli/ci.py
+++ b/packages/cli/src/repowise/cli/ci.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import os
from collections.abc import Mapping
+from pathlib import Path
from typing import Any, NoReturn
import click
@@ -52,6 +53,50 @@ def cannot_evaluate(fmt: str, code: str, message: str) -> NoReturn:
raise click.exceptions.Exit(EXIT_CANNOT_EVALUATE)
+class CannotEvaluateError(Exception):
+ """The check could not run; *code* names why, the message what to do instead."""
+
+ def __init__(self, code: str, message: str) -> None:
+ super().__init__(message)
+ self.code = code
+
+
+def repo_root(path: str | None) -> Path:
+ """The git toplevel holding *path* (default: cwd)."""
+ from repowise.core import git_refs
+
+ root = git_refs.toplevel(str(Path(path or ".").resolve()))
+ if not root:
+ raise CannotEvaluateError(
+ "not_a_git_repository", "Not a git repository (or git is not installed)."
+ )
+ return Path(root)
+
+
+def change_lines(root: str, revspec: str | None) -> tuple[dict[str, set[int]], str]:
+ """``({file: new-side lines}, label)`` for *revspec*, else the CI's target branch."""
+ import subprocess
+
+ from repowise.core.analysis.changed_lines import changed_lines
+ from repowise.core.ci.base import BaseNotFoundError, default_revspec
+
+ try:
+ revspec = revspec or default_revspec(root)
+ except BaseNotFoundError as exc:
+ raise CannotEvaluateError("base_not_found", str(exc)) from exc
+ try:
+ return changed_lines(root, revspec)
+ except ValueError as exc:
+ raise CannotEvaluateError(
+ "diff_failed",
+ f"Could not diff {revspec}: {exc}. A shallow CI clone needs the base "
+ "branch and enough history for a merge-base (fetch-depth: 0, or "
+ "git fetch --deepen)."
+ ) from exc
+ except (subprocess.SubprocessError, OSError) as exc:
+ raise CannotEvaluateError("git_failed", f"Could not run git: {exc}") from exc
+
+
def append_step_summary(markdown: str, *, env: Mapping[str, str] | None = None) -> bool:
"""Add *markdown* to the GitHub Actions job summary; ``False`` when not in Actions."""
target = (os.environ if env is None else env).get("GITHUB_STEP_SUMMARY")
diff --git a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
index a0c31b851..09df663b8 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
@@ -23,9 +23,12 @@ from rich.markup import escape
from repowise.cli.ci import (
CI_FORMATS,
EXIT_GATE_FAILED,
+ CannotEvaluateError,
append_step_summary,
cannot_evaluate,
+ change_lines,
ci_notices,
+ repo_root,
)
from repowise.cli.helpers import console, repo_index_session, run_async
from repowise.cli.output import emit_json, format_option
@@ -33,14 +36,6 @@ from repowise.core.analysis.health.coverage import PARSERS as COVERAGE_PARSERS
from repowise.core.persistence.database import has_db_store
-class _CannotEvaluateError(Exception):
- """The check could not run; *code* names why, the message what to do instead."""
-
- def __init__(self, code: str, message: str) -> None:
- super().__init__(message)
- self.code = code
-
-
@click.command("check")
@click.argument("revspec", required=False, default=None)
@click.option(
@@ -100,7 +95,7 @@ def coverage_check(
notices = ci_notices(fmt)
try:
pc = _evaluate(revspec, reports, report_format, fail_under, repo, notices)
- except _CannotEvaluateError as exc:
+ except CannotEvaluateError as exc:
cannot_evaluate(fmt, exc.code, str(exc))
_emit(pc, fmt)
if pc.gate == "fail":
@@ -110,13 +105,13 @@ def coverage_check(
def _evaluate(revspec, reports, report_format, fail_under, repo, notices):
from repowise.core.analysis.patch_coverage import patch_coverage_from_resolved
- root = _repo_root(repo)
+ root = repo_root(repo)
cfg = _coverage_config(root, validate_threshold=fail_under is None)
threshold = fail_under if fail_under is not None else cfg.fail_under
report_paths = [Path(p) for p in reports] or cfg.report_paths(root)
if not report_paths and not has_db_store(root):
- raise _CannotEvaluateError("no_report", _NO_REPORT)
- changed, label = _changed_lines(str(root), revspec or _default_revspec(str(root)))
+ raise CannotEvaluateError("no_report", _NO_REPORT)
+ changed, label = change_lines(str(root), revspec)
if not report_paths:
# No report on disk: the index's stored coverage answers, when it can.
if notices is console:
@@ -150,17 +145,17 @@ def _gateable(pc):
comment: either would pass a gate that measured nothing.
"""
if pc is None:
- raise _CannotEvaluateError("no_report", _NO_REPORT)
+ raise CannotEvaluateError("no_report", _NO_REPORT)
if pc.scope.freshness != "current":
at = f" at {pc.scope.measured_commit[:7]}" if pc.scope.measured_commit else ""
- raise _CannotEvaluateError(
+ raise CannotEvaluateError(
"coverage_stale",
f"The stored coverage was measured{at}, not at this change's head. "
"Pass a fresh report with --report, or re-run `repowise coverage add`.",
)
measurable = pc.with_status("measured") + pc.with_status("no_coverable_changes")
if pc.with_status("no_line_data") and not measurable:
- raise _CannotEvaluateError(
+ raise CannotEvaluateError(
"no_line_data",
"The stored coverage predates executable-line data. Re-run "
"`repowise coverage add` with the report, or pass it with --report.",
@@ -190,7 +185,7 @@ async def _stored(root: Path, changed, label: str, threshold: float | None):
threshold=threshold,
)
except SQLAlchemyError as exc:
- raise _CannotEvaluateError(
+ raise CannotEvaluateError(
"index_unreadable", f"Could not read the index's coverage: {exc}"
) from exc
@@ -211,11 +206,11 @@ def _resolve_reports(root, cfg, report_paths, report_format, notices):
for path, err in errors:
notices.print(f"[yellow]{escape(path.name)}: {escape(err)}[/yellow]")
if len(errors) == len(report_paths):
- raise _CannotEvaluateError(
+ raise CannotEvaluateError(
"report_unreadable", "No coverage report could be read; see the messages above."
)
if not resolved.files:
- raise _CannotEvaluateError(
+ raise CannotEvaluateError(
"report_unmatched",
"No report path matched a file in this repository. If the report paths "
"carry a build prefix, set coverage.strip_prefix in .repowise/config.yaml."
@@ -228,17 +223,6 @@ def _resolve_reports(root, cfg, report_paths, report_format, notices):
return resolved
-def _repo_root(repo: str | None) -> Path:
- from repowise.core import git_refs
-
- root = git_refs.toplevel(str(Path(repo or ".").resolve()))
- if not root:
- raise _CannotEvaluateError(
- "not_a_git_repository", "Not a git repository (or git is not installed)."
- )
- return Path(root)
-
-
def _coverage_config(root: Path, *, validate_threshold: bool):
from repowise.core.analysis.health.coverage import CoverageConfig
from repowise.core.repo_config import RepoConfigError, load_repo_config
@@ -246,46 +230,19 @@ def _coverage_config(root: Path, *, validate_threshold: bool):
try:
raw = load_repo_config(root)
except RepoConfigError as exc:
- raise _CannotEvaluateError("config_invalid", str(exc)) from exc
+ raise CannotEvaluateError("config_invalid", str(exc)) from exc
cfg = CoverageConfig.from_repo_config(raw)
block = raw.get("coverage")
bad = isinstance(block, dict) and block.get("fail_under") is not None and cfg.fail_under is None
if validate_threshold and bad:
# A gate that silently stops gating is worse than no gate.
- raise _CannotEvaluateError(
+ raise CannotEvaluateError(
"config_invalid",
f"coverage.fail_under must be a number from 0 to 100, got {block['fail_under']!r}."
)
return cfg
-def _default_revspec(root: str) -> str:
- from repowise.core.ci.base import BaseNotFoundError, default_revspec
-
- try:
- return default_revspec(root)
- except BaseNotFoundError as exc:
- raise _CannotEvaluateError("base_not_found", str(exc)) from exc
-
-
-def _changed_lines(root: str, revspec: str) -> tuple[dict[str, set[int]], str]:
- import subprocess
-
- from repowise.core.analysis.changed_lines import changed_lines
-
- try:
- return changed_lines(root, revspec)
- except ValueError as exc:
- raise _CannotEvaluateError(
- "diff_failed",
- f"Could not diff {revspec}: {exc}. A shallow CI clone needs the base "
- "branch and enough history for a merge-base (fetch-depth: 0, or "
- "git fetch --deepen)."
- ) from exc
- except (subprocess.SubprocessError, OSError) as exc:
- raise _CannotEvaluateError("git_failed", f"Could not run git: {exc}") from exc
-
-
def _emit(pc, fmt: str) -> None:
from repowise.core.analysis.patch_coverage import github_annotations, render_markdown
diff --git a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
index 277814d86..95493bd78 100644
--- a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
@@ -170,6 +170,7 @@ def _emit(
*,
gate: GateResult | None = None,
report: DocDriftReport | None = None,
+ accepted: frozenset[str] = frozenset(),
) -> None:
"""Write *payload* in *fmt*; *gate* and *report* exist only under ``--check``."""
from repowise.core.analysis.doc_drift import render
@@ -181,7 +182,11 @@ def _emit(
from repowise.cli import __version__
fail_on = gate.fail_on if gate is not None else HIGH_CONFIDENCE_THRESHOLD
- emit_json(render.render_sarif(findings, tool_version=__version__, fail_on=fail_on))
+ emit_json(
+ render.render_sarif(
+ findings, tool_version=__version__, fail_on=fail_on, accepted=accepted
+ )
+ )
elif fmt in ("markdown", "github"):
markdown = render.render_markdown(
findings,
@@ -285,7 +290,7 @@ def _run_check(
suppressed=report.suppressed,
gate=gate.to_dict(),
)
- _emit(fmt, payload, gate=gate, report=report)
+ _emit(fmt, payload, gate=gate, report=report, accepted=baseline or frozenset())
if not gate.passed:
raise click.exceptions.Exit(EXIT_GATE_FAILED)
diff --git a/packages/cli/src/repowise/cli/commands/security_cmd.py b/packages/cli/src/repowise/cli/commands/security_cmd.py
index 14897f8d2..56f333059 100644
--- a/packages/cli/src/repowise/cli/commands/security_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/security_cmd.py
@@ -1,4 +1,4 @@
-"""``repowise security scan`` — security signal scanning.
+"""``repowise security``: security signal scanning and its CI gate.
Subcommands:
scan --history [--since <rev>] [--to <rev>] [--format json]
@@ -6,12 +6,30 @@ Subcommands:
the same pattern registry the indexer uses, and persist any secrets or
risky patterns into the shared ``security_findings`` table — tagged with
the commit that introduced them. Re-runs are idempotent.
+ check [REVSPEC] [--fail-on high|med|low] [--baseline FILE] [--format ...]
+ Gate a change on the findings it adds: its changed lines at the head,
+ plus secrets committed and removed inside it. Git only, no index and no
+ database; exit codes are the shared CI ones (:mod:`repowise.cli.ci`).
"""
from __future__ import annotations
+from pathlib import Path
+from typing import TYPE_CHECKING
+
import click
+from rich.markup import escape
+from repowise.cli.ci import (
+ CI_FORMATS,
+ EXIT_GATE_FAILED,
+ CannotEvaluateError,
+ append_step_summary,
+ cannot_evaluate,
+ change_lines,
+ ci_notices,
+ repo_root,
+)
from repowise.cli.helpers import (
console,
ensure_repowise_dir,
@@ -22,10 +40,15 @@ from repowise.cli.helpers import (
)
from repowise.cli.output import emit_json, format_option, notice_console
+if TYPE_CHECKING:
+ from repowise.core.analysis.security_gate import ChangeScan, GateResult
+
+_CHECK_FORMATS = (*CI_FORMATS, "sarif")
+
@click.group("security")
def security_command() -> None:
- """Security signal scanning (working tree + full git history)."""
+ """Security signal scanning (working tree + full git history) and its CI gate."""
@security_command.command("scan")
@@ -187,3 +210,238 @@ def security_scan(
"\nFindings are written to the security_findings table and show up in "
"`repowise server`'s security API and UI. Re-running is idempotent."
)
+
+
+@security_command.command("check")
[email protected]("revspec", required=False, default=None)
+ "--fail-on",
+ type=click.Choice(["high", "med", "low"]),
+ default="high",
+ show_default=True,
+ help="Exit 1 on a finding of this severity or above.",
+)
+ "--baseline",
+ "baseline_path",
+ type=click.Path(dir_okay=False, path_type=Path),
+ default=None,
+ help="Accept the findings recorded in this file; only new ones fail.",
+)
+ "--write-baseline",
+ "write_baseline_path",
+ type=click.Path(dir_okay=False, path_type=Path),
+ default=None,
+ help="Add this change's findings to this file, keeping its entries and those of "
+ "--baseline, and exit 0.",
+)
+ "--path",
+ "repo",
+ default=None,
+ help="A path inside the repository (defaults to cwd).",
+)
+@format_option(
+ choices=_CHECK_FORMATS,
+ help="Output format. ``github`` writes annotations to stdout and the "
+ "markdown summary to $GITHUB_STEP_SUMMARY when set; ``sarif`` is for "
+ "code-scanning upload.",
+)
+def security_check(
+ revspec: str | None,
+ fail_on: str,
+ baseline_path: Path | None,
+ write_baseline_path: Path | None,
+ repo: str | None,
+ fmt: str,
+) -> None:
+ """Gate a change on the security findings it adds (no index needed, built for CI).
+
+ Scans the files the change touched, as its head has them, and keeps the
+ findings on changed lines. Secret kinds are also checked in every commit
+ of the change, so a key committed and then deleted inside it still fails:
+ it stays in the history. Snippets are masked in every format.
+
+ REVSPEC is the change: ``origin/main...HEAD`` (the pull-request view),
+ ``base..head``, or one commit. Without it, the base comes from the CI's
+ pull-request variables, else the remote's default branch.
+
+ Examples:
+
+ repowise security check origin/main...HEAD
+ repowise security check --format github --baseline .security-baseline.json
+ repowise security check --format sarif > security.sarif
+ """
+ from repowise.core.analysis.security_gate import evaluate
+
+ if fmt != "table":
+ silence_logs_for_machine_output()
+ try:
+ root = repo_root(repo)
+ accepted = _baseline_entries(baseline_path) if baseline_path is not None else None
+ changed, label = change_lines(str(root), revspec)
+ scan = _scan_change(root, changed, label)
+ if write_baseline_path is not None:
+ _record_baseline(write_baseline_path, scan, fmt, also_keep=accepted or [])
+ return
+ except CannotEvaluateError as exc:
+ cannot_evaluate(fmt, exc.code, str(exc))
+
+ baseline = None
+ if accepted is not None:
+ baseline = frozenset(e["fingerprint"] for e in accepted)
+ gate = evaluate(scan.findings, fail_on=fail_on, baseline=baseline)
+ _emit_check(fmt, scan, gate, label, accepted=baseline or frozenset())
+ if not gate.passed:
+ raise click.exceptions.Exit(EXIT_GATE_FAILED)
+
+
+def _scan_change(root: Path, changed: dict[str, set[int]], label: str) -> ChangeScan:
+ """Scan the change, turning a git failure into a cannot-evaluate."""
+ import subprocess
+
+ from repowise.core.analysis.security_gate import (
+ MissingObjectError,
+ ShallowHistoryError,
+ scan_change,
+ )
+
+ try:
+ return scan_change(str(root), changed, label)
+ except ShallowHistoryError as exc:
+ raise CannotEvaluateError("history_shallow", str(exc)) from exc
+ except MissingObjectError as exc:
+ raise CannotEvaluateError("object_missing", str(exc)) from exc
+ except subprocess.CalledProcessError as exc:
+ stderr = exc.stderr or ""
+ if isinstance(stderr, bytes):
+ stderr = stderr.decode("utf-8", errors="replace")
+ detail = stderr.strip().splitlines()
+ raise CannotEvaluateError(
+ "git_failed", f"git failed: {detail[-1] if detail else f'exit {exc.returncode}'}"
+ ) from exc
+ except (subprocess.SubprocessError, OSError) as exc:
+ raise CannotEvaluateError("git_failed", f"Could not run git: {exc}") from exc
+
+
+def _baseline_entries(path: Path) -> list[dict]:
+ from repowise.core.ci.baseline import BaselineError, read_entries
+
+ try:
+ return read_entries(path)
+ except BaselineError as exc:
+ raise CannotEvaluateError("baseline_unreadable", str(exc)) from exc
+
+
+def _record_baseline(path: Path, scan: ChangeScan, fmt: str, *, also_keep: list[dict]) -> None:
+ """Add the change's findings to *path*, keeping its entries and *also_keep* (``--baseline``)."""
+ from repowise.core.analysis.security_gate import write_baseline
+
+ keep = [*(_baseline_entries(path) if path.exists() else []), *also_keep]
+ try:
+ written = write_baseline(path, scan.findings, keep=keep)
+ except OSError as exc:
+ raise CannotEvaluateError(
+ "baseline_unwritable", f"cannot write baseline {path}: {exc}"
+ ) from exc
+ if fmt == "json":
+ emit_json({"baseline": str(path), "recorded": len(scan.findings), "entries": written})
+ return
+ ci_notices(fmt).print(
+ f"Recorded {len(scan.findings)} finding(s); {escape(str(path))} now holds "
+ f"{written} entr{'y' if written == 1 else 'ies'}."
+ )
+
+
+def _emit_check(
+ fmt: str, scan: ChangeScan, gate: GateResult, label: str, *, accepted: frozenset[str]
+) -> None:
+ """Write the verdict in *fmt*; *accepted* is the whole baseline, below the threshold too."""
+ from repowise.core.analysis import security_gate
+
+ if fmt == "json":
+ emit_json(
+ {
+ "revspec": label,
+ "files_scanned": scan.files_scanned,
+ "commits_scanned": scan.commits_scanned,
+ "findings_basis": security_gate.DETECTION_BASIS,
+ "findings": scan.findings,
+ "gate": gate.to_dict(),
+ }
+ )
+ elif fmt == "sarif":
+ from repowise.cli import __version__
+
+ emit_json(
+ security_gate.render_sarif(
+ scan.findings,
+ tool_version=__version__,
+ fail_on=gate.fail_on,
+ accepted=accepted,
+ )
+ )
+ elif fmt in ("markdown", "github"):
+ markdown = security_gate.render_markdown(
+ gate,
+ label=label,
+ files_scanned=scan.files_scanned,
+ commits_scanned=scan.commits_scanned,
+ )
+ if fmt == "markdown":
+ click.echo(markdown, nl=False)
+ else:
+ for line in security_gate.github_annotations(scan.findings, gate):
+ click.echo(line)
+ append_step_summary(markdown)
+ else:
+ _print_check(scan, gate, label)
+
+
+_SEVERITY_COLOUR = {"high": "red", "med": "yellow", "low": "dim"}
+
+
+def _print_check(scan: ChangeScan, gate: GateResult, label: str) -> None:
+ from rich.table import Table
+
+ from repowise.core.analysis.security_gate import DETECTION_BASIS
+
+ console.print(
+ f"[bold]{escape(label)}[/bold]: {scan.files_scanned} changed file(s) and "
+ f"{scan.commits_scanned} commit(s) scanned"
+ )
+ accepted = {f["fingerprint"] for f in gate.baselined}
+ rows = [f for f in scan.findings if f["fingerprint"] not in accepted]
+ if rows:
+ table = Table(show_edge=False, pad_edge=False)
+ table.add_column("Severity")
+ table.add_column("Kind")
+ table.add_column("Where")
+ table.add_column("Matched (secrets masked)")
+ for f in rows:
+ where = f"{f['file_path']}:{f['line_number']}"
+ if f["commit"]:
+ where += f" @ {f['commit'][:7]}"
+ colour = _SEVERITY_COLOUR[f["severity"]]
+ table.add_row(
+ f"[{colour}]{f['severity']}[/]",
+ escape(f["kind"]),
+ escape(where),
+ escape(f["snippet"]),
+ )
+ console.print(table)
+ if gate.passed:
+ console.print(f"[green]Gate passed[/green] [dim](fails on {gate.fail_on} or above)[/dim]")
+ else:
+ note = f", {len(gate.baselined)} accepted by baseline" if gate.baselined else ""
+ console.print(
+ f"[red]Gate failed:[/red] {len(gate.failing)} finding(s) at {gate.fail_on} "
+ f"or above{note}"
+ )
+ if any(f["commit"] for f in gate.failing):
+ console.print(
+ "[yellow]A row marked @ commit is a secret committed inside this change; "
+ "deleting it does not remove it from the history. Rotate it.[/yellow]"
+ )
+ console.print(f"[dim]{escape(DETECTION_BASIS)}[/dim]")
diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.py
index 8d65a3651..006c479ca 100644
--- a/packages/core/src/repowise/core/analysis/changed_lines.py
+++ b/packages/core/src/repowise/core/analysis/changed_lines.py
@@ -31,6 +31,11 @@ from .change_risk.features import _git, split_revspec
# count of 0 means "nothing on that side" (pure insertion / pure deletion).
_HUNK_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
+#: Pinned header prefixes: ``diff.noprefix`` or a custom prefix in the user's
+#: config would otherwise make :func:`_header_path` strip a real ``a/`` or
+#: ``b/`` directory, or keep a prefix that names no file.
+DIFF_PREFIXES = ("--src-prefix=a/", "--dst-prefix=b/")
+
@dataclass
class FileDiff:
@@ -53,14 +58,36 @@ class FileDiff:
added: list[str] = field(default_factory=list)
+_C_ESCAPES = {"a": 7, "b": 8, "t": 9, "n": 10, "v": 11, "f": 12, "r": 13}
+
+
+def _c_unquote(text: str) -> str:
+ """Undo git's C-style path quoting: ``caf\\303\\251.py`` -> ``café.py``."""
+ out = bytearray()
+ i = 0
+ while i < len(text):
+ if text[i] == "\\" and i + 1 < len(text):
+ nxt = text[i + 1]
+ if nxt in "01234567":
+ out.append(int(text[i + 1 : i + 4], 8) & 0xFF)
+ i += 4
+ continue
+ out += bytes([_C_ESCAPES[nxt]]) if nxt in _C_ESCAPES else nxt.encode("utf-8")
+ i += 2
+ continue
+ out += text[i].encode("utf-8")
+ i += 1
+ return out.decode("utf-8", errors="replace")
+
+
def _header_path(raw: str) -> str | None:
"""Normalize a ``--- a/x`` / ``+++ b/x`` header path. ``None`` for /dev/null."""
path = raw.strip()
- # git quotes paths with special chars ("b/pa\tth"); strip the quotes so the
- # common (unquoted) key still resolves. Rare enough to accept the imperfect
- # unescaping.
+ # git quotes a path holding a non-ASCII byte, a tab, a quote or a backslash
+ # ("b/caf\303\251.py"); left escaped it names no file, and a reader that
+ # looks the file up would skip it.
if len(path) >= 2 and path[0] == '"' and path[-1] == '"':
- path = path[1:-1]
+ path = _c_unquote(path[1:-1])
if path == "/dev/null":
return None
return path[2:] if path[:2] in ("a/", "b/") else path
@@ -168,11 +195,11 @@ def changed_lines(
if working_tree:
# Untracked files are absent by design: they are new, so neither caller
# (prior fixes, per-test coverage) has a row to find for them anyway.
- diff = _git(["diff", "--unified=0", "HEAD"], repo_path)
+ diff = _git(["diff", "--unified=0", *DIFF_PREFIXES, "HEAD"], repo_path)
return _parse_unified_diff(diff), "working tree"
if staged or not revspec:
- diff = _git(["diff", "--cached", "--unified=0"], repo_path)
+ diff = _git(["diff", "--cached", "--unified=0", *DIFF_PREFIXES], repo_path)
return _parse_unified_diff(diff), "staged changes"
if (parts := split_revspec(revspec)) is not None:
@@ -182,7 +209,8 @@ def changed_lines(
_verify_ref(repo_path, base)
_verify_ref(repo_path, head)
label = f"{base}{sep}{head}"
- return _parse_unified_diff(_diff(repo_path, ["diff", "--unified=0", label])), label
+ diff = _diff(repo_path, ["diff", "--unified=0", *DIFF_PREFIXES, label])
+ return _parse_unified_diff(diff), label
_verify_ref(repo_path, revspec)
if _is_shallow_root(repo_path, revspec):
@@ -192,7 +220,7 @@ def changed_lines(
# --format= drops the commit message so only the diff body is parsed.
# -m --first-parent matches what change risk counts on a merge; without it
# git's combined diff emits nothing at all and a merged PR reads as empty.
- args = ["show", "--unified=0", "--format=", "-m", "--first-parent", revspec]
+ args = ["show", "--unified=0", *DIFF_PREFIXES, "--format=", "-m", "--first-parent", revspec]
return _parse_unified_diff(_diff(repo_path, args)), revspec
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/baseline.py b/packages/core/src/repowise/core/analysis/doc_drift/baseline.py
index 0e4d06710..abc1b5c28 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/baseline.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/baseline.py
@@ -1,24 +1,35 @@
"""A committed file of accepted documentation drift.
-The baseline lets a repository adopt the gate without first fixing every
-existing finding: what it lists does not fail, anything new does. It is a file
-path the caller names, never ``.repowise/config.yaml``, because that config is
-local state and a CI policy has to live in the repository.
-
-Entries are keyed on the line-independent fingerprint and sorted, and the bytes
-are deterministic, so rewriting an unchanged baseline is a no-op diff.
+The envelope (version, sorted entries, deterministic bytes, refusals) is the
+shared one in :mod:`repowise.core.ci.baseline`; this module supplies the
+entries. They are keyed on the line-independent fingerprint, so an accepted
+finding stays accepted when an edit above it shifts its line.
"""
from __future__ import annotations
-import json
from collections.abc import Iterable, Mapping
from pathlib import Path
from typing import Any
+from repowise.core.ci.baseline import (
+ BASELINE_VERSION,
+ BaselineError,
+ build_document,
+ read_baseline,
+ write_document,
+)
+
from .serialize import fingerprint_of
-BASELINE_VERSION = 1
+__all__ = [
+ "BASELINE_BASIS",
+ "BASELINE_VERSION",
+ "BaselineError",
+ "build_baseline",
+ "read_baseline",
+ "write_baseline",
+]
BASELINE_BASIS = (
"Documentation drift accepted as known. A listed finding does not fail the "
@@ -26,63 +37,24 @@ BASELINE_BASIS = (
)
-class BaselineError(ValueError):
- """A baseline file that cannot be used; the message says why."""
-
-
def build_baseline(findings: Iterable[Mapping[str, Any]]) -> dict:
"""The baseline document for *findings*, one entry per fingerprint."""
- entries: dict[str, dict] = {}
- for finding in findings:
- fp = fingerprint_of(finding)
- entries.setdefault(
- fp,
- {
- "fingerprint": fp,
- "file_path": finding["file_path"],
- "kind": str(finding["kind"]),
- "target": finding["target"],
- },
- )
- ordered = sorted(
- entries.values(), key=lambda e: (e["file_path"], e["kind"], e["target"])
+ entries = (
+ {
+ "fingerprint": fingerprint_of(finding),
+ "file_path": finding["file_path"],
+ "kind": str(finding["kind"]),
+ "target": finding["target"],
+ }
+ for finding in findings
+ )
+ return build_document(
+ entries,
+ basis=BASELINE_BASIS,
+ sort_key=lambda e: (e["file_path"], e["kind"], e["target"]),
)
- return {"version": BASELINE_VERSION, "basis": BASELINE_BASIS, "entries": ordered}
def write_baseline(path: Path | str, findings: Iterable[Mapping[str, Any]]) -> int:
"""Write the baseline for *findings* to *path*; returns entries written."""
- doc = build_baseline(findings)
- text = json.dumps(doc, indent=2, ensure_ascii=False) + "\n"
- Path(path).write_text(text, encoding="utf-8")
- return len(doc["entries"])
-
-
-def read_baseline(path: Path | str) -> frozenset[str]:
- """The fingerprints *path* accepts; raises :class:`BaselineError` if unusable."""
- try:
- text = Path(path).read_text(encoding="utf-8")
- except (OSError, UnicodeDecodeError) as exc:
- raise BaselineError(f"cannot read baseline {path}: {exc}") from exc
- try:
- doc = json.loads(text)
- except json.JSONDecodeError as exc:
- raise BaselineError(f"baseline {path} is not valid JSON: {exc}") from exc
- if not isinstance(doc, dict):
- raise BaselineError(f"baseline {path} must be a JSON object")
- version = doc.get("version")
- if version != BASELINE_VERSION:
- raise BaselineError(
- f"baseline {path} has version {version!r}; this build reads "
- f"version {BASELINE_VERSION}"
- )
- entries = doc.get("entries")
- if not isinstance(entries, list):
- raise BaselineError(f"baseline {path} has no 'entries' list")
- out: set[str] = set()
- for i, entry in enumerate(entries):
- fp = entry.get("fingerprint") if isinstance(entry, dict) else None
- if not isinstance(fp, str) or not fp:
- raise BaselineError(f"baseline {path} entry {i} has no fingerprint")
- out.add(fp)
- return frozenset(out)
+ return write_document(path, build_baseline(findings))
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/render.py b/packages/core/src/repowise/core/analysis/doc_drift/render.py
index 197d67c14..76da73a50 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/render.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/render.py
@@ -211,10 +211,13 @@ def render_sarif(
*,
tool_version: str,
fail_on: float = HIGH_CONFIDENCE_THRESHOLD,
+ accepted: frozenset[str] = frozenset(),
) -> dict:
"""One SARIF 2.1.0 run; ``partialFingerprints`` survive line shifts.
- A finding at or above *fail_on* is an ``error``, so the level matches the gate.
+ A finding at or above *fail_on* is an ``error``, so the level matches the
+ gate, and one whose fingerprint is in *accepted* (the baseline) is marked
+ suppressed.
"""
results = []
for f in _order(findings):
@@ -238,6 +241,7 @@ def render_sarif(
SARIF_FINGERPRINT_KEY,
fingerprint_of(f),
properties,
+ suppressed=fingerprint_of(f) in accepted,
)
)
return sarif.run(SARIF_TOOL_NAME, tool_version, _sarif_rules(), results)
diff --git a/packages/core/src/repowise/core/analysis/security_gate.py b/packages/core/src/repowise/core/analysis/security_gate.py
new file mode 100644
index 000000000..d2a56fbdf
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/security_gate.py
@@ -0,0 +1,556 @@
+"""The CI gate over security signals: what a change adds, judged against a threshold.
+
+Reads git (every call raises on failure, so a git error can never read as a
+clean change) and runs :func:`~.security_scan.scan_source`; no index, no
+database. Two passes over the change:
+
+* **At its head.** Every changed file is scanned as the head commit has it, and
+ a finding counts when a line it spans is on the new side of the diff.
+* **Secrets inside it.** Each commit in the range is scanned the same way,
+ secret kinds only, so a key added in one commit and deleted in the next is
+ still caught: it stays in the history, and in every clone, after HEAD
+ drops it. File contents are held in memory for the scan and never written.
+
+Only the masked snippet (:func:`~.security_scan._snippet`) leaves this module,
+and the fingerprint is taken over it too, so neither a CI log nor the committed
+baseline holds a raw value.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import subprocess
+from collections.abc import Iterable, Mapping, Sequence
+from dataclasses import dataclass, field
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+from repowise.core.ci import baseline as ci_baseline
+from repowise.core.ci import github, sarif
+from repowise.core.ci.markdown import ROW_LIMIT, cell, more_line, plural
+from repowise.core.support_paths import DOC_EXTENSIONS
+
+from .change_risk.features import GIT_TIMEOUT_SECONDS, _git, revspec_head, split_revspec
+from .changed_lines import DIFF_PREFIXES, parse_unified_diff
+from .security_scan import SECRET_KINDS, scan_source, source_lines
+
+#: Severities from least to most severe; ``--fail-on`` names the lowest that fails.
+SEVERITIES = ("low", "med", "high")
+_RANK = {s: i for i, s in enumerate(SEVERITIES)}
+
+#: Secret kinds matched by the value's own vendor format rather than a variable
+#: name; see :func:`fingerprint_of`.
+_KEY_SHAPE_KINDS = SECRET_KINDS - {"hardcoded_password", "hardcoded_secret"}
+
+
+class ShallowHistoryError(ValueError):
+ """The change reaches past a shallow clone's cut; its history cannot be read."""
+
+
+class MissingObjectError(ValueError):
+ """git has no object for a path a diff listed."""
+
+DETECTION_BASIS = (
+ "Pattern matches from a fixed regex registry: a floor, not a scanner. A clean "
+ "result means no pattern matched a changed line, not that the change is safe."
+)
+
+BASELINE_BASIS = (
+ "Security findings accepted as known. A listed finding does not fail the gate; "
+ "it is keyed on file, kind and the masked matched line, not line number."
+)
+
+SARIF_TOOL_NAME = "repowise-security"
+SARIF_FINGERPRINT_KEY = "repowiseSecurity/v1"
+
+_FINGERPRINT_NAMESPACE = "repowise.security.fingerprint.v1"
+_FIELD_SEP = "\x1f"
+#: Bytes read to decide a blob is binary, as git itself does.
+_BINARY_SNIFF = 8000
+
+#: SARIF rule text per kind the gate can report. ``security_sensitive_symbol``
+#: is absent on purpose: it needs parsed symbols and never gates.
+_RULE_TEXT: dict[str, str] = {
+ "eval_call": "A call to eval.",
+ "exec_call": "A call to exec (outside Python, in a file that names child_process).",
+ "pickle_loads": "pickle.loads, which runs code from the data it loads.",
+ "subprocess_shell_true": "A subprocess call with shell=True.",
+ "os_system": "os.system, which runs its argument through a shell.",
+ "hardcoded_password": "A quoted literal assigned to a password-named variable.",
+ "hardcoded_secret": "A quoted literal assigned to a key-, secret- or token-named variable.",
+ "aws_access_key": "An AWS access key ID.",
+ "github_token": "A GitHub token.",
+ "slack_token": "A Slack token.",
+ "google_api_key": "A Google API key.",
+ "stripe_key": "A Stripe secret or restricted key.",
+ "private_key_pem": "A PEM private key with its body.",
+ "fstring_sql": "An f-string holding SQL and an interpolation.",
+ "concat_sql": "SQL built by string concatenation.",
+ "tls_verify_false": "TLS certificate verification turned off (verify=False).",
+ "weak_hash": "The words md5 or sha1.",
+ "unsafe_inner_html": "__html set from a non-literal value.",
+ "template_literal_sql": "A template literal holding SQL and an interpolation.",
+ "public_env_secret": "A secret-shaped name behind a NEXT_PUBLIC_ or VITE_ prefix.",
+ "new_function_call": "new Function(...), which compiles a string as code.",
+ "reject_unauthorized_false": "TLS verification turned off (rejectUnauthorized: false).",
+}
+
+
+# ---------------------------------------------------------------------------
+# Scan
+# ---------------------------------------------------------------------------
+
+
+def fingerprint_of(file_path: str, kind: str, snippet: str, material: str = "") -> str:
+ """The line-independent key a baseline holds, over the *masked* snippet.
+
+ *material* is the matched text itself, passed only for the vendor key
+ shapes (:data:`_KEY_SHAPE_KINDS`): those mask to the vendor's fixed prefix
+ (``AKIA****``), so without it a different key on an identical line would
+ inherit an accepted key's fingerprint. They are high-entropy by format, so a
+ one-way hash of them cannot be walked back. The keyword kinds keep the
+ masked-only key, because a short password could be guessed from its hash.
+
+ Consequence accepted: two identical matched lines in one file share a
+ fingerprint, and so do two keyword secrets whose visible prefix and line agree.
+ """
+ parts = (_FINGERPRINT_NAMESPACE, file_path, kind, snippet, material)
+ return hashlib.sha256(_FIELD_SEP.join(parts).encode("utf-8")).hexdigest()[:32]
+
+
+@dataclass(frozen=True)
+class ChangeScan:
+ """The findings a change adds and how much of it was read."""
+
+ findings: list[dict]
+ files_scanned: int
+ commits_scanned: int
+
+
+def _text(blob: bytes) -> str | None:
+ """*blob* as text, or ``None`` when it is binary."""
+ if b"\0" in blob[:_BINARY_SNIFF]:
+ return None
+ return blob.decode("utf-8", errors="replace")
+
+
+def _read_blobs(root: str, specs: Sequence[str]) -> list[str | None]:
+ """The text of each ``rev:path`` in *specs*, in order, over one ``cat-file``.
+
+ ``None`` for an object that is not a blob (a submodule) or is binary.
+ Raises when git fails, and :class:`MissingObjectError` for an object git
+ does not have: every spec names a file a diff just listed, so a miss means
+ the path was misread, and skipping it would pass a file nobody scanned.
+ """
+ if not specs:
+ return []
+ proc = subprocess.run(
+ ["git", "cat-file", "--batch"],
+ cwd=root,
+ input=("\n".join(specs) + "\n").encode("utf-8"),
+ capture_output=True,
+ timeout=GIT_TIMEOUT_SECONDS,
+ check=True,
+ )
+ out, pos, texts = proc.stdout, 0, []
+ for spec in specs:
+ nl = out.index(b"\n", pos)
+ header = out[pos:nl].split()
+ pos = nl + 1
+ # "<sha> <type> <size>", "<sha> submodule" for a gitlink, else
+ # "<spec> missing" (the spec may hold spaces).
+ if len(header) == 2 and header[1] == b"submodule":
+ texts.append(None)
+ continue
+ if len(header) != 3 or not header[2].isdigit():
+ raise MissingObjectError(f"git has no object for {spec!r}")
+ size = int(header[2])
+ body = out[pos : pos + size]
+ pos += size + 1
+ texts.append(_text(body) if header[1] == b"blob" else None)
+ return texts
+
+
+def _scoped(path: str, source: str, lines: set[int], *, secrets_only: bool) -> list[dict]:
+ """Findings in *source* that span a line in *lines*, as gate rows.
+
+ A document keeps only secret kinds: prose naming ``pickle.loads`` is not a
+ call, but a key pasted into a README is still a leak.
+ """
+ secrets_only = secrets_only or PurePosixPath(path).suffix.lower() in DOC_EXTENSIONS
+ text_lines = source_lines(source)
+ rows = []
+ for f in scan_source(path, source):
+ if secrets_only and f["kind"] not in SECRET_KINDS:
+ continue
+ span = range(f["line"], f.get("end_line", f["line"]) + 1)
+ if lines.isdisjoint(span):
+ continue
+ material = ""
+ if f["kind"] in _KEY_SHAPE_KINDS:
+ material = "\n".join(text_lines[span.start - 1 : span.stop - 1])
+ rows.append(
+ {
+ "file_path": path,
+ "line_number": f["line"],
+ "kind": f["kind"],
+ "severity": f["severity"],
+ "snippet": f["snippet"],
+ "fingerprint": fingerprint_of(path, f["kind"], f["snippet"], material),
+ "commit": None,
+ }
+ )
+ return rows
+
+
+def _log_range(root: str, revspec: str) -> list[str]:
+ """The commits *revspec* covers, as ``git log`` arguments.
+
+ A range lists what its head has and its base does not, which for
+ ``base...head`` is the branch's own commits. One revision covers itself,
+ and for a merge the branch it brought in, matching the first-parent diff
+ :func:`~.changed_lines.changed_lines` takes of it.
+ """
+ if (parts := split_revspec(revspec)) is not None:
+ base, _, head = parts
+ return [f"{base}..{head}"]
+ if _git(["rev-parse", "--verify", "--quiet", f"{revspec}^"], root, check=False).strip():
+ return [f"{revspec}^..{revspec}"]
+ return ["--max-count=1", revspec] # a root commit
+
+
+def _history_secrets(root: str, revspec: str) -> tuple[list[dict], int]:
+ """Secret findings on the lines each commit in the change added, oldest first."""
+ # Merges are skipped: a merge from the target branch brings its lines, not
+ # the change's. Ceiling: a secret written in a conflict resolution is caught
+ # only if the head keeps it; ``--diff-merges=remerge`` (git 2.36+) could show
+ # what a resolution itself introduced.
+ log_range = _log_range(root, revspec)
+ cut = _shallow_boundary(root, log_range)
+ args = ["log", "--no-merges", "--reverse", "-p", "--unified=0", "--no-color"]
+ args += ["--no-ext-diff", *DIFF_PREFIXES, "--format=%x00%H", *log_range, "--"]
+ raw = _git(args, root)
+ chunks = raw.split("\0")[1:]
+ rows: list[dict] = []
+ for chunk in chunks:
+ sha, _, diff = chunk.partition("\n")
+ sha = sha.strip()
+ if sha in cut:
+ raise ShallowHistoryError(
+ f"Commit {sha[:7]} in this change has its parents cut off by a shallow "
+ "clone, so every line it holds would read as added. Fetch the full "
+ "history (fetch-depth: 0)."
+ )
+ added = {p: d.new_lines for p, d in parse_unified_diff(diff).items() if d.new_lines}
+ # One read per commit bounds memory to the files a single commit touched.
+ paths = sorted(added)
+ texts = _read_blobs(root, [f"{sha}:{p}" for p in paths])
+ for path, text in zip(paths, texts, strict=True):
+ if text is None:
+ continue
+ for row in _scoped(path, text, added[path], secrets_only=True):
+ row["commit"] = sha
+ rows.append(row)
+ return rows, len(chunks)
+
+
+def _shallow_boundary(root: str, log_range: Sequence[str]) -> frozenset[str]:
+ """Commits whose parents a shallow clone left out (empty in a full clone).
+
+ Raises :class:`ShallowHistoryError` when the range's own ends have no
+ merge-base: a cut on the base side hides that the head's older history is
+ the base's too, and ``base..head`` would walk it back to the root.
+ """
+ if _git(["rev-parse", "--is-shallow-repository"], root).strip() != "true":
+ return frozenset()
+ if len(log_range) == 1 and ".." in log_range[0]:
+ base, _, head = log_range[0].partition("..")
+ if not _git(["merge-base", base, head], root, check=False).strip():
+ raise ShallowHistoryError(
+ f"{base} and {head} share no commit in this shallow clone, so the "
+ "change's own commits cannot be told apart. Fetch the full history "
+ "(fetch-depth: 0)."
+ )
+ shallow = Path(root, _git(["rev-parse", "--git-path", "shallow"], root).strip())
+ if not shallow.exists():
+ return frozenset()
+ return frozenset(shallow.read_text(encoding="utf-8").split())
+
+
+def scan_change(root: str, changed: Mapping[str, set[int]], revspec: str) -> ChangeScan:
+ """Every finding *revspec* adds; *changed* is its new-side lines per file.
+
+ Raises :class:`subprocess.CalledProcessError` when git fails and
+ :class:`ShallowHistoryError` when a commit of the change lost its parents.
+ """
+ paths = sorted(changed)
+ head = revspec_head(revspec)
+ findings: list[dict] = []
+ scanned = 0
+ texts = _read_blobs(root, [f"{head}:{p}" for p in paths])
+ for path, text in zip(paths, texts, strict=True):
+ if text is None:
+ continue
+ scanned += 1
+ findings += _scoped(path, text, changed[path], secrets_only=False)
+ history, commits = _history_secrets(root, revspec)
+ # A secret still on a changed line at the head is reported there, once; a
+ # secret committed twice inside the change is reported at its first commit.
+ seen = {f["fingerprint"] for f in findings}
+ for row in history:
+ if row["fingerprint"] not in seen:
+ seen.add(row["fingerprint"])
+ findings.append(row)
+ return ChangeScan(findings, files_scanned=scanned, commits_scanned=commits)
+
+
+# ---------------------------------------------------------------------------
+# Verdict and baseline
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class GateResult:
+ """What the gate decided, and which findings it decided on."""
+
+ passed: bool
+ #: At or above ``fail_on`` and not baselined.
+ failing: list[dict] = field(default_factory=list)
+ #: At or above ``fail_on`` but accepted by the baseline.
+ baselined: list[dict] = field(default_factory=list)
+ below_threshold: int = 0
+ fail_on: str = "high"
+
+ def to_dict(self) -> dict:
+ """A stable JSON shape: the verdict, its counts, the failing findings."""
+ return {
+ "passed": self.passed,
+ "fail_on": self.fail_on,
+ "failing_count": len(self.failing),
+ "baselined_count": len(self.baselined),
+ "below_threshold_count": self.below_threshold,
+ "failing": [dict(f) for f in self.failing],
+ }
+
+
+def evaluate(
+ findings: Iterable[Mapping[str, Any]],
+ *,
+ fail_on: str = "high",
+ baseline: frozenset[str] | None = None,
+) -> GateResult:
+ """Split *findings* into failing, baselined and below-threshold."""
+ accepted = baseline or frozenset()
+ floor = _RANK[fail_on]
+ failing: list[dict] = []
+ baselined: list[dict] = []
+ below = 0
+ for finding in findings:
+ if _RANK[finding["severity"]] < floor:
+ below += 1
+ continue
+ (baselined if finding["fingerprint"] in accepted else failing).append(dict(finding))
+ return GateResult(
+ passed=not failing,
+ failing=failing,
+ baselined=baselined,
+ below_threshold=below,
+ fail_on=fail_on,
+ )
+
+
+def write_baseline(
+ path: Path | str,
+ findings: Iterable[Mapping[str, Any]],
+ *,
+ keep: Iterable[Mapping[str, Any]] = (),
+) -> int:
+ """Write *findings* (plus the entries in *keep*) as the baseline at *path*.
+
+ *keep* is the file's current entries: the gate sees one change at a time,
+ so accepting this change's findings must not drop earlier ones.
+ """
+ entries = [
+ *keep,
+ *(
+ {
+ "fingerprint": f["fingerprint"],
+ "file_path": f["file_path"],
+ "kind": f["kind"],
+ "snippet": f["snippet"],
+ }
+ for f in findings
+ ),
+ ]
+ doc = ci_baseline.build_document(
+ entries,
+ basis=BASELINE_BASIS,
+ sort_key=lambda e: (
+ str(e.get("file_path", "")),
+ str(e.get("kind", "")),
+ str(e.get("snippet", "")),
+ e["fingerprint"],
+ ),
+ )
+ return ci_baseline.write_document(path, doc)
+
+
+# ---------------------------------------------------------------------------
+# Renderings
+# ---------------------------------------------------------------------------
+
+
+def _order(findings: Iterable[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
+ return sorted(
+ findings,
+ key=lambda f: (
+ -_RANK[f["severity"]],
+ f["commit"] is not None,
+ f["file_path"],
+ int(f["line_number"]),
+ f["kind"],
+ ),
+ )
+
+
+def _where(finding: Mapping[str, Any]) -> str:
+ if finding["commit"]:
+ return f"{finding['file_path']} (commit {finding['commit'][:7]})"
+ return f"{finding['file_path']}:{int(finding['line_number'])}"
+
+
+def _message(finding: Mapping[str, Any]) -> str:
+ text = f"{finding['kind']} ({finding['severity']}): {finding['snippet']}"
+ if finding["commit"]:
+ text += (
+ f" Committed in {finding['commit'][:7]} inside this change and not on a "
+ "changed line at its head; it stays in the git history. Rotate it."
+ )
+ return text
+
+
+def render_markdown(
+ gate: GateResult,
+ *,
+ label: str,
+ files_scanned: int,
+ commits_scanned: int,
+) -> str:
+ """Step-summary / PR-comment markdown: verdict first, then a capped table."""
+ if gate.passed:
+ lines = [f"**No security findings at or above {gate.fail_on} in {cell(label)}.**"]
+ else:
+ n = len(gate.failing)
+ lines = [
+ f"**Security: {plural(n, 'finding')} {'fails' if n == 1 else 'fail'} the gate** "
+ f"(severity {gate.fail_on} or above, in {cell(label)})."
+ ]
+ notes = [
+ f"{plural(files_scanned, 'changed file')} and {plural(commits_scanned, 'commit')} scanned"
+ ]
+ if gate.baselined:
+ notes.append(f"{len(gate.baselined)} accepted by the baseline")
+ if gate.below_threshold:
+ notes.append(f"{gate.below_threshold} below the threshold")
+ lines += ["", "; ".join(notes) + "."]
+
+ if gate.failing:
+ lines += [
+ "",
+ "| Where | Kind | Severity | Matched (secrets masked) |",
+ "| --- | --- | --- | --- |",
+ ]
+ ordered = _order(gate.failing)
+ for f in ordered[:ROW_LIMIT]:
+ lines.append(
+ f"| {cell(_where(f))} | {cell(f['kind'])} | {cell(f['severity'])} "
+ f"| {cell(f['snippet'])} |"
+ )
+ if len(ordered) > ROW_LIMIT:
+ lines += ["", more_line(len(ordered) - ROW_LIMIT, "findings")]
+ if any(f["commit"] for f in gate.failing):
+ lines += [
+ "",
+ "A row naming a commit is a secret committed inside this change and no "
+ "longer on a changed line at its head. Deleting it does not remove it "
+ "from the history: rotate it.",
+ ]
+
+ lines += ["", f"_{DETECTION_BASIS}_"]
+ return "\n".join(lines) + "\n"
+
+
+def github_annotations(findings: Sequence[Mapping[str, Any]], gate: GateResult) -> list[str]:
+ """``::error`` for failing findings, ``::warning`` below the threshold, errors first.
+
+ Baselined findings are accepted, so they are not annotated. A secret found
+ only in an earlier commit is annotated on its file with no line, because
+ the head's line numbers do not describe it.
+ """
+ # The fingerprint covers path and kind, so it fixes the severity: one
+ # fingerprint is never both failing and below the threshold.
+ failing = {f["fingerprint"] for f in gate.failing}
+ accepted = {f["fingerprint"] for f in gate.baselined}
+ errors: list[str] = []
+ warnings: list[str] = []
+ for f in _order(findings):
+ if f["fingerprint"] in accepted:
+ continue
+ level = "error" if f["fingerprint"] in failing else "warning"
+ line = github.annotation(
+ level,
+ _message(f),
+ file=str(f["file_path"]),
+ line=None if f["commit"] else int(f["line_number"]),
+ title=f"Security: {f['kind']} ({f['severity']})",
+ )
+ (errors if level == "error" else warnings).append(line)
+ return github.cap_annotations(errors + warnings, noun="security findings")
+
+
+def _sarif_rules() -> list[dict]:
+ return [
+ sarif.rule(
+ kind,
+ "".join(part.capitalize() for part in kind.split("_")),
+ text,
+ f"{text} {DETECTION_BASIS}",
+ DETECTION_BASIS,
+ )
+ for kind, text in _RULE_TEXT.items()
+ ]
+
+
+def render_sarif(
+ findings: Sequence[Mapping[str, Any]],
+ *,
+ tool_version: str,
+ fail_on: str = "high",
+ accepted: frozenset[str] = frozenset(),
+) -> dict:
+ """One SARIF 2.1.0 run; ``partialFingerprints`` survive line shifts.
+
+ A finding at or above *fail_on* is an ``error``, so the level matches the
+ gate, and one whose fingerprint is in *accepted* (the baseline) is marked
+ suppressed. A secret found only in an earlier commit is located on its file
+ with no line: its line number belongs to that commit, not the head.
+ """
+ results = []
+ for f in _order(findings):
+ properties: dict[str, Any] = {"severity": f["severity"], "snippet": f["snippet"]}
+ if f["commit"]:
+ properties["commit"] = f["commit"]
+ results.append(
+ sarif.result(
+ str(f["kind"]),
+ "error" if _RANK[f["severity"]] >= _RANK[fail_on] else "warning",
+ _message(f),
+ str(f["file_path"]),
+ None if f["commit"] else int(f["line_number"]),
+ SARIF_FINGERPRINT_KEY,
+ f["fingerprint"],
+ properties,
+ suppressed=f["fingerprint"] in accepted,
+ )
+ )
+ return sarif.run(SARIF_TOOL_NAME, tool_version, _sarif_rules(), results)
diff --git a/packages/core/src/repowise/core/analysis/security_scan.py b/packages/core/src/repowise/core/analysis/security_scan.py
index 96cb1cfe9..74e39b2e5 100644
--- a/packages/core/src/repowise/core/analysis/security_scan.py
+++ b/packages/core/src/repowise/core/analysis/security_scan.py
@@ -308,14 +308,23 @@ def _redaction(val: str) -> str:
# ``public_env_secret`` has no capture group, so its value is found here. In
# ``SECRET_KINDS`` the empty capture would fail validation and drop the finding.
-_ASSIGNED_VALUE = re.compile(r"""\A['"]?\s*[:=]+\s*['"`]?([^'"`\s,;]+)""")
+# After the name: the name's own closing quote or bracket, then an operator
+# (``=``, ``:``, ``=>``, ``??``, ``||``) or plain whitespace (a Dockerfile
+# ``ENV NAME value``), then the value, quoted or not.
+_PUBLIC_VALUE = re.compile(r"""\A['"\]]*(?:\s*[:=>?|]+\s*|\s+)(['"`]?)(?=[^\s;,)])""")
_SECRET_PATTERNS = [(p, kind) for p, kind, _ in _PATTERNS if kind in SECRET_KINDS]
_PUBLIC_ENV_PATTERN = next(p for p, kind, _ in _PATTERNS if kind == "public_env_secret")
-# A PEM body written on its header's line (escaped ``\n`` breaks), up to ``-----END``.
+# A PEM body written on its header's line (escaped ``\n`` breaks, or spaces when
+# an environment variable flattened it), up to ``-----END``.
_PEM_INLINE_BODY = re.compile(
- r"(?i:-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY-----)(?:\\[rn])*((?:[A-Za-z0-9+/=]|\\[rn])+)"
+ r"(?i:-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY-----)(?:\\[rn])*"
+ r"((?:[A-Za-z0-9+/=]|\\[rn]|[ \t])+)"
)
+# A header that ends its line: the body follows on the next lines.
+_PEM_HEADER_LINE = re.compile(r"(?i:-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY-----)['\"]?\s*\Z")
+# A line of key body: one base64 run, however indented.
+_PEM_BODY_LINE = re.compile(r"\A\s*[A-Za-z0-9+/=]{16,}\s*\Z")
_SECRET_PREFILTER = re.compile(
"|".join(
f"(?:{p.pattern})"
@@ -327,20 +336,56 @@ _SNIPPET_MAX = 120
_MARKER = "****"
+def _string_end(line: str, start: int) -> int:
+ """Where the string literal holding *start* closes, else the end of *line*.
+
+ The keyword captures stop at the first quote of either kind, so a value
+ holding the other quote would otherwise be masked only up to it.
+ """
+ quote = line[start - 1] if start > 0 else ""
+ i = start
+ while i < len(line):
+ if line[i] == "\\":
+ i += 2
+ elif line[i] == quote:
+ return i
+ else:
+ i += 1
+ return len(line)
+
+
+def _value_span(kind: str, match: re.Match, line: str) -> tuple[int, int]:
+ """The captured credential's span; a keyword value runs to its closing quote."""
+ start, end = match.span(1)
+ return (start, _string_end(line, start)) if kind in _KEYWORD_KINDS else (start, end)
+
+
+def _public_env_value(line: str, name_end: int) -> tuple[int, int] | None:
+ """The value assigned to a public env name ending at *name_end*, if any."""
+ value = _PUBLIC_VALUE.search(line[name_end:])
+ if value is None:
+ return None
+ start = name_end + value.end()
+ if value.group(1):
+ return start, _string_end(line, start)
+ stop = next((i for i in range(start, len(line)) if line[i].isspace()), len(line))
+ return start, stop
+
+
def _secret_spans(line: str) -> list[tuple[int, int]]:
"""Every credential value on *line*, including repeats of one elsewhere on it."""
spans: list[tuple[int, int]] = []
for pattern, kind in _SECRET_PATTERNS:
for match in pattern.finditer(line):
- if _is_secret_value(kind, match.group(1)):
- spans.append(match.span(1))
+ start, end = _value_span(kind, match, line)
+ if _is_secret_value(kind, line[start:end]):
+ spans.append((start, end))
for match in _PEM_INLINE_BODY.finditer(line):
if _is_valid_credential_value(match.group(1)):
spans.append(match.span(1))
for match in _PUBLIC_ENV_PATTERN.finditer(line):
- value = _ASSIGNED_VALUE.search(line[match.end() :])
- if value is not None:
- spans.append((match.end() + value.start(1), match.end() + value.end(1)))
+ if (span := _public_env_value(line, match.end())) is not None:
+ spans.append(span)
for val in {line[start:end] for start, end in spans}:
if len(val) < 4:
continue
@@ -488,6 +533,15 @@ def _mask_comments_and_strings(source: str) -> str:
return "".join(chars)
+def source_lines(source: str) -> list[str]:
+ """*source* split where git splits it, so line numbers agree with a diff.
+
+ ``str.splitlines`` also breaks on form feeds and Unicode separators, which
+ numbered every later finding past git's line for it.
+ """
+ return [line.removesuffix("\r") for line in source.split("\n")]
+
+
def _call_findings(file_path: str, source: str) -> list[dict]:
"""Find executable eval/exec calls with AST or bounded lexical fallback."""
if file_path.lower().endswith((".py", ".pyi")):
@@ -496,6 +550,7 @@ def _call_findings(file_path: str, source: str) -> list[dict]:
except SyntaxError:
pass
else:
+ lines = source_lines(source)
findings = []
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
@@ -512,14 +567,18 @@ def _call_findings(file_path: str, source: str) -> list[dict]:
{
"kind": f"{call_name}_call",
"severity": "high",
- "snippet": _snippet(source.splitlines()[node.lineno - 1]),
+ # ast also breaks lines on a lone ``\r``, which git does
+ # not; such a line number can outrun the split.
+ "snippet": _snippet(lines[node.lineno - 1])
+ if node.lineno <= len(lines)
+ else "",
"line": node.lineno,
}
)
return findings
masked = _mask_comments_and_strings(source)
- lines = source.splitlines()
+ lines = source_lines(source)
findings = []
def add(kind: str, severity: str, offset: int) -> None:
@@ -557,7 +616,7 @@ def _is_missing_table_error(exc: Exception) -> bool:
def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> list[dict]:
"""Scan *source* text and symbol names; return finding dicts. No I/O."""
findings: list[dict] = []
- lines = source.splitlines()
+ lines = source_lines(source)
findings.extend(_call_findings(file_path, source))
@@ -574,8 +633,9 @@ def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> lis
continue
match = pattern.search(line)
if match:
+ value = line[slice(*_value_span(kind, match, line))] if match.groups() else ""
if kind in SECRET_KINDS:
- if not _is_secret_value(kind, match.group(1)):
+ if not _is_secret_value(kind, value):
continue
if is_low_sev_file:
severity = "low"
@@ -589,9 +649,9 @@ def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> lis
}
findings.append(finding)
if kind in _KEYWORD_KINDS:
- keyword_hits.append((finding, match.group(1)))
+ keyword_hits.append((finding, value))
elif kind in SECRET_KINDS:
- vendor_values.append(match.group(1))
+ vendor_values.append(value)
# One secret, one finding: the vendor shape already names what the keyword saw.
for finding, value in keyword_hits:
if any(vendor in value for vendor in vendor_values):
@@ -609,6 +669,7 @@ def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> lis
if is_low_sev_file:
severity = "low"
start_line = source.count("\n", 0, match.start()) + 1
+ end_line = source.count("\n", 0, match.end()) + 1
if kind == "private_key_pem":
end = source.find("-----END", match.end())
end_line = source.count("\n", 0, end if end != -1 else match.end()) + 1
@@ -625,9 +686,24 @@ def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> lis
"severity": severity,
"snippet": _snippet(source[line_start:line_end]),
"line": start_line,
+ # The last line the match spans, so a diff-scoped reader
+ # counts an edit anywhere inside the call or key.
+ "end_line": end_line,
}
)
+ # The base64 lines after a header that ends its line are body whether or not
+ # the key validated: an indented YAML block or a key with no END line never
+ # matches the pattern above, and its body lines would otherwise reach another
+ # kind's snippet. The run stops at the first line that is not base64, so a
+ # header constant in code that assembles PEM text marks nothing after it.
+ in_body = False
+ for lineno, line in enumerate(lines, start=1):
+ if in_body and _PEM_BODY_LINE.search(line):
+ pem_body_lines.add(lineno)
+ else:
+ in_body = bool(_PEM_HEADER_LINE.search(line))
+
# A key body line matches nothing of its own, so a hit there is stray and its
# snippet would carry key material: mask the whole line.
for finding in findings:
diff --git a/packages/core/src/repowise/core/ci/baseline.py b/packages/core/src/repowise/core/ci/baseline.py
new file mode 100644
index 000000000..74bf78d2a
--- /dev/null
+++ b/packages/core/src/repowise/core/ci/baseline.py
@@ -0,0 +1,79 @@
+"""A committed file of accepted findings, shared by every gate that takes one.
+
+The baseline lets a repository adopt a gate without first fixing every existing
+finding: what it lists does not fail, anything new does. It is a file path the
+caller names, never ``.repowise/config.yaml``, because that config is local
+state and a CI policy has to live in the repository.
+
+Each feature supplies its entries (a ``fingerprint`` plus whatever a reader
+needs to recognise the finding) and their order; this module owns the envelope.
+One entry per fingerprint, sorted, deterministic bytes, so rewriting an
+unchanged baseline is a no-op diff.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Callable, Iterable, Mapping
+from pathlib import Path
+from typing import Any
+
+BASELINE_VERSION = 1
+
+
+class BaselineError(ValueError):
+ """A baseline file that cannot be used; the message says why."""
+
+
+def build_document(
+ entries: Iterable[Mapping[str, Any]],
+ *,
+ basis: str,
+ sort_key: Callable[[dict], Any],
+) -> dict:
+ """The baseline document: the first entry per fingerprint, ordered by *sort_key*."""
+ unique: dict[str, dict] = {}
+ for entry in entries:
+ unique.setdefault(entry["fingerprint"], dict(entry))
+ ordered = sorted(unique.values(), key=sort_key)
+ return {"version": BASELINE_VERSION, "basis": basis, "entries": ordered}
+
+
+def write_document(path: Path | str, doc: Mapping[str, Any]) -> int:
+ """Write *doc* to *path*; returns the entries written."""
+ text = json.dumps(doc, indent=2, ensure_ascii=False) + "\n"
+ Path(path).write_text(text, encoding="utf-8")
+ return len(doc["entries"])
+
+
+def read_entries(path: Path | str) -> list[dict]:
+ """The entries *path* holds; raises :class:`BaselineError` if unusable."""
+ try:
+ text = Path(path).read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError) as exc:
+ raise BaselineError(f"cannot read baseline {path}: {exc}") from exc
+ try:
+ doc = json.loads(text)
+ except json.JSONDecodeError as exc:
+ raise BaselineError(f"baseline {path} is not valid JSON: {exc}") from exc
+ if not isinstance(doc, dict):
+ raise BaselineError(f"baseline {path} must be a JSON object")
+ version = doc.get("version")
+ if version != BASELINE_VERSION:
+ raise BaselineError(
+ f"baseline {path} has version {version!r}; this build reads "
+ f"version {BASELINE_VERSION}"
+ )
+ entries = doc.get("entries")
+ if not isinstance(entries, list):
+ raise BaselineError(f"baseline {path} has no 'entries' list")
+ for i, entry in enumerate(entries):
+ fp = entry.get("fingerprint") if isinstance(entry, dict) else None
+ if not isinstance(fp, str) or not fp:
+ raise BaselineError(f"baseline {path} entry {i} has no fingerprint")
+ return entries
+
+
+def read_baseline(path: Path | str) -> frozenset[str]:
+ """The fingerprints *path* accepts; raises :class:`BaselineError` if unusable."""
+ return frozenset(entry["fingerprint"] for entry in read_entries(path))
diff --git a/packages/core/src/repowise/core/ci/sarif.py b/packages/core/src/repowise/core/ci/sarif.py
index 64d07928f..852b2e64c 100644
--- a/packages/core/src/repowise/core/ci/sarif.py
+++ b/packages/core/src/repowise/core/ci/sarif.py
@@ -28,29 +28,36 @@ def result(
level: str,
message: str,
path: str,
- line: int,
+ line: int | None,
fingerprint_key: str,
fingerprint: str,
properties: Mapping[str, Any] | None = None,
+ *,
+ suppressed: bool = False,
) -> dict:
- """One result, located relative to ``%SRCROOT%`` with a percent-encoded URI."""
+ """One result, located relative to ``%SRCROOT%`` with a percent-encoded URI.
+
+ *line* ``None`` locates the result on the file alone, for a finding whose
+ line belongs to another revision. *suppressed* marks one accepted outside
+ the log (a baseline), so code scanning shows it closed rather than open.
+ """
+ location: dict[str, Any] = {
+ "artifactLocation": {
+ "uri": quote(path.replace("\\", "/").lstrip("/"), safe="/"),
+ "uriBaseId": "%SRCROOT%",
+ }
+ }
+ if line is not None:
+ location["region"] = {"startLine": max(1, int(line))}
out: dict[str, Any] = {
"ruleId": rule_id,
"level": level,
"message": {"text": message},
- "locations": [
- {
- "physicalLocation": {
- "artifactLocation": {
- "uri": quote(path.replace("\\", "/").lstrip("/"), safe="/"),
- "uriBaseId": "%SRCROOT%",
- },
- "region": {"startLine": max(1, int(line))},
- }
- }
- ],
+ "locations": [{"physicalLocation": location}],
"partialFingerprints": {fingerprint_key: fingerprint},
}
+ if suppressed:
+ out["suppressions"] = [{"kind": "external"}]
if properties:
out["properties"] = dict(properties)
return out
diff --git a/packages/server/src/repowise/server/routers/security.py b/packages/server/src/repowise/server/routers/security.py
index a6e2eda69..8c467e674 100644
--- a/packages/server/src/repowise/server/routers/security.py
+++ b/packages/server/src/repowise/server/routers/security.py
@@ -8,6 +8,7 @@ from fastapi import APIRouter, Depends, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.security_scan import source_lines
from repowise.core.persistence.models import Repository, SecurityFinding
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas import SecurityFindingResponse
@@ -126,6 +127,8 @@ def _read_guarded(repo_root: Path, file_path: str) -> list[str] | None:
target = (repo_root / file_path).resolve()
if not target.is_relative_to(repo_root):
return None
- return target.read_text(encoding="utf-8", errors="replace").splitlines()
+ # Split as the scanner numbered the lines (where git splits), so a form
+ # feed or a lone carriage return does not move a verified line.
+ return source_lines(target.read_bytes().decode("utf-8", errors="replace"))
except (OSError, ValueError):
return None
diff --git a/tests/unit/analysis/test_security_gate.py b/tests/unit/analysis/test_security_gate.py
new file mode 100644
index 000000000..d766605c7
--- /dev/null
+++ b/tests/unit/analysis/test_security_gate.py
@@ -0,0 +1,477 @@
+"""``security_gate``: what a change adds, scoped to its lines and its commits.
+
+Scans run against real temp git repositories, because the scoping (changed
+lines at the head, added lines per commit) is the thing under test.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+
+import pytest
+
+from repowise.core.analysis import security_gate
+from repowise.core.analysis.changed_lines import changed_lines
+from repowise.core.analysis.doc_drift.render import render_sarif as doc_drift_sarif
+from repowise.core.analysis.security_gate import (
+ evaluate,
+ fingerprint_of,
+ github_annotations,
+ render_markdown,
+ render_sarif,
+ scan_change,
+ write_baseline,
+)
+from repowise.core.analysis.security_scan import _PATTERNS, _SPANNING_PATTERNS
+from repowise.core.ci.baseline import read_baseline, read_entries
+
+KEY = "AKIA" + "QZXNRTVYWMPKLBHG"
+PEM_BODY = "MIIEpAIBAAKCAQEAu1SU1LfVLPHCozMxH2Mo4lgOEePzNm0tRgeLezV6ffAt0gunVTLw"
+
+
+def _git(cwd, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True
+ ).stdout
+
+
+def _write(repo, name: str, text: str) -> None:
+ path = repo / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8", newline="\n")
+
+
+def _commit(repo, message: str) -> None:
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", message)
+
+
+def repo(tmp_path):
+ _git(tmp_path, "init", "-q", "-b", "main")
+ _git(tmp_path, "config", "user.email", "[email protected]")
+ _git(tmp_path, "config", "user.name", "t")
+ _git(tmp_path, "config", "core.autocrlf", "false")
+ _write(tmp_path, "app.py", "import os\n\nos.system('old')\n\ndef run():\n return 1\n")
+ _commit(tmp_path, "base")
+ _git(tmp_path, "switch", "-qc", "feature")
+ return tmp_path
+
+
+def _scan(repo, revspec: str = "main...HEAD"):
+ changed, label = changed_lines(str(repo), revspec)
+ return scan_change(str(repo), changed, label)
+
+
+def _kinds(scan) -> list[tuple[str, int, bool]]:
+ return sorted((f["kind"], f["line_number"], f["commit"] is not None) for f in scan.findings)
+
+
+# ---------------------------------------------------------------------------
+# Line scoping
+# ---------------------------------------------------------------------------
+
+
+def test_only_findings_on_changed_lines_count(repo):
+ _write(
+ repo,
+ "app.py",
+ "import os\n\nos.system('old')\n\ndef run():\n return eval('1')\n",
+ )
+ _commit(repo, "eval")
+ scan = _scan(repo)
+ # The pre-existing os.system on line 3 is untouched and stays out.
+ assert _kinds(scan) == [("eval_call", 6, False)]
+ assert scan.files_scanned == 1 and scan.commits_scanned == 1
+
+
+def test_a_multi_line_call_counts_when_only_its_last_line_changed(repo):
+ _write(repo, "run.py", "import subprocess\nsubprocess.run(\n cmd,\n shell=False,\n)\n")
+ _commit(repo, "safe call")
+ base = _git(repo, "rev-parse", "HEAD").strip()
+ _write(repo, "run.py", "import subprocess\nsubprocess.run(\n cmd,\n shell=True,\n)\n")
+ _commit(repo, "shell")
+ scan = _scan(repo, f"{base}..HEAD")
+ assert _kinds(scan) == [("subprocess_shell_true", 2, False)]
+
+
+def test_a_pem_key_counts_when_only_its_body_changed(repo):
+ pem = "-----BEGIN RSA PRIVATE KEY-----\n{}\n-----END RSA PRIVATE KEY-----\n"
+ _write(repo, "key.pem", pem.format("x"))
+ _commit(repo, "placeholder")
+ base = _git(repo, "rev-parse", "HEAD").strip()
+ _write(repo, "key.pem", pem.format(PEM_BODY))
+ _commit(repo, "real key")
+ scan = _scan(repo, f"{base}..HEAD")
+ assert [(f["kind"], f["line_number"]) for f in scan.findings] == [("private_key_pem", 1)]
+
+
+def test_a_document_reports_secrets_but_not_code_smells(repo):
+ _write(repo, "README.md", f"Call `pickle.loads` and `os.system`.\n\nkey: {KEY}\n")
+ _commit(repo, "docs")
+ assert [f["kind"] for f in _scan(repo).findings] == ["aws_access_key"]
+
+
+# ---------------------------------------------------------------------------
+# Secrets inside the change
+# ---------------------------------------------------------------------------
+
+
+def test_a_secret_added_then_deleted_inside_the_change_is_caught(repo):
+ _write(repo, "cfg.py", f"AWS = '{KEY}'\n")
+ _commit(repo, "add key")
+ introduced = _git(repo, "rev-parse", "HEAD").strip()
+ _write(repo, "cfg.py", "AWS = None\n")
+ _commit(repo, "remove key")
+ scan = _scan(repo)
+ (finding,) = scan.findings
+ assert finding["kind"] == "aws_access_key"
+ assert finding["commit"] == introduced
+ assert scan.commits_scanned == 2
+
+
+def test_a_secret_still_at_the_head_is_reported_once_at_the_head(repo):
+ _write(repo, "cfg.py", f"AWS = '{KEY}'\n")
+ _commit(repo, "add key")
+ _write(repo, "other.py", "x = 1\n")
+ _commit(repo, "unrelated")
+ assert _kinds(_scan(repo)) == [("aws_access_key", 1, False)]
+
+
+def test_a_secret_that_predates_the_change_is_not_blamed_on_it(repo):
+ _git(repo, "switch", "-q", "main")
+ _write(repo, "cfg.py", f"AWS = '{KEY}'\nX = 1\n")
+ _commit(repo, "old key on main")
+ _git(repo, "switch", "-qc", "later")
+ _write(repo, "cfg.py", f"AWS = '{KEY}'\nX = 2\n")
+ _commit(repo, "touch another line")
+ assert _scan(repo).findings == []
+
+
+def test_code_smells_in_intermediate_commits_do_not_count(repo):
+ _write(repo, "tmp.py", "eval('1')\n")
+ _commit(repo, "smell")
+ _write(repo, "tmp.py", "x = 1\n")
+ _commit(repo, "gone")
+ assert _scan(repo).findings == []
+
+
+def test_a_merge_commit_covers_the_branch_it_brought_in(repo):
+ _write(repo, "cfg.py", f"AWS = '{KEY}'\n")
+ _commit(repo, "add key")
+ _write(repo, "cfg.py", "AWS = None\n")
+ _commit(repo, "remove key")
+ _git(repo, "switch", "-q", "main")
+ _git(repo, "merge", "-q", "--no-ff", "-m", "merge", "feature")
+ (finding,) = _scan(repo, "HEAD").findings
+ assert finding["kind"] == "aws_access_key" and finding["commit"]
+
+
+def test_a_shallow_cut_inside_the_change_refuses_rather_than_blaming_old_lines(repo, tmp_path):
+ _git(repo, "switch", "-q", "main")
+ _write(repo, "cfg.py", f"AWS = '{KEY}'\n")
+ _commit(repo, "old key on main")
+ _git(repo, "switch", "-q", "feature")
+ _git(repo, "merge", "-q", "main")
+ _write(repo, "a.py", "x = 1\n")
+ _commit(repo, "one")
+ _write(repo, "a.py", "x = 2\n")
+ _commit(repo, "two")
+ clone = tmp_path / "clone"
+ _git(tmp_path, "clone", "-q", "--depth", "2", "--branch", "feature", repo.as_uri(), str(clone))
+ _git(clone, "fetch", "-q", "--depth", "1", "origin", "main:refs/remotes/origin/main")
+ changed, label = changed_lines(str(clone), "origin/main..HEAD")
+ with pytest.raises(security_gate.ShallowHistoryError, match="fetch-depth: 0"):
+ scan_change(str(clone), changed, label)
+
+
+def test_a_git_failure_raises_instead_of_reading_as_clean(repo):
+ with pytest.raises(subprocess.CalledProcessError):
+ scan_change(str(repo), {}, "no-such-ref..HEAD")
+
+
+# ---------------------------------------------------------------------------
+# Verdict and baseline
+# ---------------------------------------------------------------------------
+
+
+def _row(kind="eval_call", severity="high", path="a.py", line=1, snippet="eval(x)", commit=None):
+ return {
+ "file_path": path,
+ "line_number": line,
+ "kind": kind,
+ "severity": severity,
+ "snippet": snippet,
+ "fingerprint": fingerprint_of(path, kind, snippet),
+ "commit": commit,
+ }
+
+
+ ("fail_on", "failing", "below"),
+ [("high", 1, 2), ("med", 2, 1), ("low", 3, 0)],
+)
+def test_fail_on_names_the_lowest_failing_severity(fail_on, failing, below):
+ rows = [
+ _row(),
+ _row("tls_verify_false", "med", snippet="verify=False"),
+ _row("weak_hash", "low", snippet="md5"),
+ ]
+ gate = evaluate(rows, fail_on=fail_on)
+ assert len(gate.failing) == failing and gate.below_threshold == below
+ assert gate.passed is False
+
+
+def test_baseline_survives_a_line_shift(repo, tmp_path):
+ _write(repo, "cfg.py", f"AWS = '{KEY}'\n")
+ _commit(repo, "add key")
+ baseline = tmp_path / "baseline.json"
+ write_baseline(baseline, _scan(repo).findings)
+
+ _write(repo, "cfg.py", f"import os\n\n\nAWS = '{KEY}'\n")
+ _commit(repo, "shift")
+ shifted = _scan(repo)
+ assert shifted.findings[0]["line_number"] == 4
+ gate = evaluate(shifted.findings, baseline=read_baseline(baseline))
+ assert gate.passed and len(gate.baselined) == 1
+
+
+def test_write_baseline_keeps_earlier_entries_and_is_deterministic(tmp_path):
+ a, b = tmp_path / "a.json", tmp_path / "b.json"
+ write_baseline(a, [_row(path="z.py")])
+ assert write_baseline(a, [_row(path="a.py")], keep=read_entries(a)) == 2
+ write_baseline(b, [_row(path="a.py"), _row(path="z.py"), _row(path="a.py")])
+ assert a.read_bytes() == b.read_bytes()
+ entries = json.loads(a.read_text(encoding="utf-8"))["entries"]
+ assert [e["file_path"] for e in entries] == ["a.py", "z.py"]
+
+
+# ---------------------------------------------------------------------------
+# Renderings
+# ---------------------------------------------------------------------------
+
+
+def test_no_raw_secret_in_any_format(repo, tmp_path):
+ _write(repo, "cfg.py", f"AWS = '{KEY}'\npassword = 'hunter2hunter2'\n")
+ _write(repo, "key.pem", f"-----BEGIN RSA PRIVATE KEY-----\n{PEM_BODY}\n-----END RSA PRIVATE KEY-----\n")
+ _commit(repo, "secrets")
+ _write(repo, "old.py", f"TOKEN = '{KEY}'\n")
+ _commit(repo, "more")
+ _write(repo, "old.py", "TOKEN = None\n")
+ _commit(repo, "remove")
+ scan = _scan(repo)
+ assert {f["kind"] for f in scan.findings} >= {"aws_access_key", "hardcoded_password"}
+ assert any(f["commit"] for f in scan.findings)
+ gate = evaluate(scan.findings)
+ baseline = tmp_path / "b.json"
+ write_baseline(baseline, scan.findings)
+ outputs = [
+ json.dumps(scan.findings),
+ json.dumps(gate.to_dict()),
+ render_markdown(gate, label="main...HEAD", files_scanned=2, commits_scanned=3),
+ "\n".join(github_annotations(scan.findings, gate)),
+ json.dumps(render_sarif(scan.findings, tool_version="0")),
+ baseline.read_text(encoding="utf-8"),
+ ]
+ for raw in (KEY, "hunter2hunter2", PEM_BODY[:20]):
+ for text in outputs:
+ assert raw not in text
+
+
+def test_annotations_are_capped_escaped_and_skip_the_baseline():
+ rows = [_row(path=f"src/a,b:{i}.py", snippet=f"eval({i})") for i in range(12)]
+ rows.append(_row("weak_hash", "low", snippet="md5"))
+ rows.append(_row(snippet="eval(accepted)"))
+ gate = evaluate(rows, baseline=frozenset({rows[-1]["fingerprint"]}))
+ lines = github_annotations(rows, gate)
+ assert len(lines) == 11 and lines[-1].startswith("::notice::3 more security findings")
+ assert all(line.startswith("::error ") for line in lines[:10])
+ assert "file=src/a%2Cb%3A0.py,line=1," in lines[0]
+ assert not any("accepted" in line for line in lines)
+
+
+def test_an_earlier_commit_secret_is_annotated_without_a_line():
+ row = _row("aws_access_key", snippet="AWS = 'AKIA****'", commit="a" * 40)
+ (line,) = github_annotations([row], evaluate([row]))
+ assert "line=" not in line and "aaaaaaa" in line
+
+
+def test_markdown_passes_short_and_always_states_its_basis():
+ text = render_markdown(evaluate([]), label="main...HEAD", files_scanned=0, commits_scanned=0)
+ assert text.startswith("**No security findings at or above high")
+ assert "a floor, not a scanner" in text
+
+
+def test_sarif_shares_doc_drifts_envelope():
+ rows = [_row(), _row("weak_hash", "low", snippet="md5")]
+ log = render_sarif(rows, tool_version="1.2.3")
+ drift = doc_drift_sarif([], tool_version="1.2.3")
+ assert log.keys() == drift.keys()
+ assert log["runs"][0].keys() == drift["runs"][0].keys()
+ driver = log["runs"][0]["tool"]["driver"]
+ assert driver["name"] == "repowise-security" and driver["version"] == "1.2.3"
+ first, second = log["runs"][0]["results"]
+ assert (first["level"], second["level"]) == ("error", "warning")
+ assert first["partialFingerprints"] == {"repowiseSecurity/v1": rows[0]["fingerprint"]}
+ assert driver["rules"][first["ruleIndex"]]["id"] == "eval_call"
+
+
+def test_every_gating_kind_has_a_sarif_rule():
+ kinds = {kind for _, kind, _ in [*_PATTERNS, *_SPANNING_PATTERNS]}
+ assert kinds == set(security_gate._RULE_TEXT)
+
+
+# ---------------------------------------------------------------------------
+# Review regressions
+# ---------------------------------------------------------------------------
+
+
+ ("line", "raw"),
+ [
+ ("PASSWORD = 'Tr0ub4dor\"TAILSECRET9876' # md5\n", "TAILSECRET9876"),
+ ('secret = "token = \'RAWVALUE12345678\'" # md5\n', "RAWVALUE12345678"),
+ ('ENV["NEXT_PUBLIC_API_KEY"] = "RAWVALUE12345678" # md5\n', "RAWVALUE12345678"),
+ ("ENV NEXT_PUBLIC_API_KEY RAWVALUE12345678 md5\n", "RAWVALUE12345678"),
+ ('k = process.env.NEXT_PUBLIC_API_KEY ?? "RAWVALUE12345678" // md5\n', "RAWVALUE12345678"),
+ ],
+)
+def test_no_raw_value_escapes_the_mask(line, raw):
+ from repowise.core.analysis.security_scan import scan_source
+
+ findings = scan_source("cfg.py", line)
+ assert findings and all(raw not in f["snippet"] for f in findings)
+
+
+ "source",
+ [
+ f"key: |\n -----BEGIN RSA PRIVATE KEY-----\n {PEM_BODY}md5\n -----END RSA PRIVATE KEY-----\n",
+ f"-----BEGIN RSA PRIVATE KEY-----\n{PEM_BODY}\n{PEM_BODY[::-1]}md5\n",
+ f"KEY=-----BEGIN RSA PRIVATE KEY----- {PEM_BODY} md5 -----END RSA PRIVATE KEY-----\n",
+ ],
+)
+def test_pem_body_lines_never_reach_a_snippet(source):
+ from repowise.core.analysis.security_scan import scan_source
+
+ for f in scan_source("cfg.yaml", source):
+ assert PEM_BODY[:12] not in f["snippet"] and PEM_BODY[::-1][:12] not in f["snippet"]
+
+
+def test_line_numbers_follow_git_past_a_form_feed(repo):
+ _write(repo, "ff.py", "a = 1\n\x0c\nb = 2\n")
+ _commit(repo, "ff")
+ base = _git(repo, "rev-parse", "HEAD").strip()
+ _write(repo, "ff.py", "a = 1\n\x0c\nb = 2\npassword = 'Zq8vLm2pXr7w'\n")
+ _commit(repo, "pw")
+ assert _kinds(_scan(repo, f"{base}..HEAD")) == [("hardcoded_password", 4, False)]
+
+
+def test_a_non_ascii_path_is_scanned(repo):
+ _write(repo, "café.py", "password = 'Zq8vLm2pXr7w'\n")
+ _commit(repo, "accent")
+ scan = _scan(repo)
+ assert [f["file_path"] for f in scan.findings] == ["café.py"]
+
+
+def test_two_vendor_keys_on_identical_lines_stay_distinct(repo, tmp_path):
+ _write(repo, "cfg.py", f"AWS = '{KEY}'\n")
+ _commit(repo, "key a")
+ baseline = tmp_path / "b.json"
+ write_baseline(baseline, _scan(repo).findings)
+ other = "AKIA" + "ZXCVBNMLKJHGFDSA"
+ _write(repo, "cfg.py", f"AWS = '{other}'\n")
+ _commit(repo, "key b")
+ scan = _scan(repo)
+ # Both keys are reported: B at the head, A from the commit that added it.
+ assert sorted(f["commit"] is None for f in scan.findings) == [False, True]
+ gate = evaluate(scan.findings, baseline=read_baseline(baseline))
+ assert [f["commit"] for f in gate.failing] == [None]
+
+
+def test_a_shallow_cut_on_the_base_side_refuses(repo, tmp_path):
+ _git(repo, "switch", "-q", "main")
+ _write(repo, "old.py", "password = 'Zq8vLm2pXr7w'\n")
+ _commit(repo, "old")
+ _git(repo, "switch", "-qc", "feat")
+ _write(repo, "a.py", "x = 1\n")
+ _commit(repo, "f1")
+ _git(repo, "switch", "-q", "main")
+ _write(repo, "m.py", "y = 1\n")
+ _commit(repo, "m4")
+ clone = tmp_path / "clone"
+ _git(tmp_path, "clone", "-q", "--depth", "1", "--branch", "main", repo.as_uri(), str(clone))
+ _git(clone, "fetch", "-q", "--depth", "10", "origin", "feat:refs/remotes/origin/feat")
+ changed, label = changed_lines(str(clone), "origin/main..origin/feat")
+ with pytest.raises(security_gate.ShallowHistoryError, match="share no commit"):
+ scan_change(str(clone), changed, label)
+
+
+def test_a_path_git_does_not_have_raises():
+ with pytest.raises(security_gate.MissingObjectError):
+ security_gate._read_blobs(".", ["HEAD:no/such/file-anywhere.py"])
+
+
+def test_sarif_suppresses_the_baseline_and_drops_history_lines():
+ head = _row()
+ old = _row("aws_access_key", snippet="AWS = 'AKIA****'", commit="a" * 40)
+ log = render_sarif([head, old], tool_version="0", accepted=frozenset({head["fingerprint"]}))
+ by_rule = {r["ruleId"]: r for r in log["runs"][0]["results"]}
+ assert by_rule["eval_call"]["suppressions"] == [{"kind": "external"}]
+ assert "suppressions" not in by_rule["aws_access_key"]
+ assert "region" not in by_rule["aws_access_key"]["locations"][0]["physicalLocation"]
+
+
+ ("line", "raw"),
+ [
+ ("ENV NEXT_PUBLIC_API_KEY p@ssw0rd!Xy#Zq9 md5\n", "p@ssw0rd!Xy#Zq9"),
+ ('ENV["NEXT_PUBLIC_TOKEN"] = "Ab$9!kLm@2#Qr%zz" # md5\n', "Ab$9!kLm@2#Qr%zz"),
+ ('x = NEXT_PUBLIC_SECRET ?? "p@ss:w0rd!2024x" // md5\n', "p@ss:w0rd!2024x"),
+ ("password = \"ab'SuperSecretPassword123\"; eval(x)\n", "SuperSecretPassword123"),
+ ],
+)
+def test_values_with_symbols_or_an_early_quote_are_masked(line, raw):
+ from repowise.core.analysis.security_scan import scan_source
+
+ findings = scan_source("cfg.js", line)
+ assert findings and all(raw[4:] not in f["snippet"] for f in findings)
+
+
+def test_ordinary_text_after_a_public_env_name_is_left_readable():
+ from repowise.core.analysis.security_scan import scan_source
+
+ (hit,) = scan_source("a.ts", "const k = process.env.NEXT_PUBLIC_API_KEY;\n")
+ assert hit["snippet"] == "const k = process.env.NEXT_PUBLIC_API_KEY;"
+
+
+def test_a_pem_header_constant_does_not_mask_the_code_after_it():
+ from repowise.core.analysis.security_scan import scan_source
+
+ source = 'PEM = "-----BEGIN RSA PRIVATE KEY-----"\n\ndef f(s):\n return eval(s)\n'
+ (hit,) = [f for f in scan_source("a.py", source) if f["kind"] == "eval_call"]
+ assert hit["snippet"] == "return eval(s)"
+
+
+def test_a_lone_carriage_return_does_not_crash_the_scan():
+ from repowise.core.analysis.security_scan import scan_source
+
+ assert [f["kind"] for f in scan_source("a.py", "import os\rx = 1\reval(y)\r")] == ["eval_call"]
+
+
+def test_a_submodule_in_the_change_is_skipped_not_fatal(repo, tmp_path):
+ sub = tmp_path / "sub"
+ sub.mkdir()
+ _git(sub, "init", "-q")
+ _git(sub, "-c", "[email protected]", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "s")
+ _git(repo, "-c", "protocol.file.allow=always", "submodule", "add", "-q", sub.as_uri(), "sub")
+ _commit(repo, "submodule")
+ assert _scan(repo).findings == []
+
+
+def test_diff_noprefix_config_does_not_misread_paths(repo):
+ _git(repo, "config", "diff.noprefix", "true")
+ _write(repo, "b/cfg.py", "password = 'Zq8vLm2pXr7w'\n")
+ _commit(repo, "nested")
+ assert [f["file_path"] for f in _scan(repo).findings] == ["b/cfg.py"]
diff --git a/tests/unit/cli/test_coverage_check_cmd.py b/tests/unit/cli/test_coverage_check_cmd.py
index f2cd9a431..160446645 100644
--- a/tests/unit/cli/test_coverage_check_cmd.py
+++ b/tests/unit/cli/test_coverage_check_cmd.py
@@ -192,7 +192,8 @@ def test_flag_overrides_a_bad_config_threshold(repo) -> None:
def test_stored_coverage_is_not_gated_when_stale_or_without_line_data() -> None:
- from repowise.cli.commands.coverage_check_cmd import _CannotEvaluateError, _gateable
+ from repowise.cli.ci import CannotEvaluateError
+ from repowise.cli.commands.coverage_check_cmd import _gateable
from repowise.core.analysis.health.coverage import file_coverage
from repowise.core.analysis.patch_coverage import PatchScope, compute_patch_coverage
@@ -203,12 +204,12 @@ def test_stored_coverage_is_not_gated_when_stale_or_without_line_data() -> None:
fresh = _pc(file_coverage("a.py", [1], [1]), "current")
assert _gateable(fresh) is fresh
- with pytest.raises(_CannotEvaluateError) as stale:
+ with pytest.raises(CannotEvaluateError) as stale:
_gateable(_pc(file_coverage("a.py", [1], [1]), "stale"))
assert stale.value.code == "coverage_stale"
- with pytest.raises(_CannotEvaluateError) as legacy:
+ with pytest.raises(CannotEvaluateError) as legacy:
_gateable(_pc(file_coverage("a.py", [1], []), "current"))
assert legacy.value.code == "no_line_data"
- with pytest.raises(_CannotEvaluateError) as missing:
+ with pytest.raises(CannotEvaluateError) as missing:
_gateable(None)
assert missing.value.code == "no_report"
diff --git a/tests/unit/cli/test_security_check_cmd.py b/tests/unit/cli/test_security_check_cmd.py
new file mode 100644
index 000000000..86e37a8f8
--- /dev/null
+++ b/tests/unit/cli/test_security_check_cmd.py
@@ -0,0 +1,139 @@
+"""``repowise security check``: the index-free CI gate and its exit codes."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands.security_cmd import security_command
+
+KEY = "AKIA" + "QZXNRTVYWMPKLBHG"
+
+
+def _git(cwd, *args: str) -> None:
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)
+
+
+def _commit(repo, name: str, text: str) -> None:
+ (repo / name).write_text(text, encoding="utf-8", newline="\n")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", name)
+
+
+def repo(tmp_path):
+ _git(tmp_path, "init", "-q", "-b", "main")
+ _git(tmp_path, "config", "user.email", "[email protected]")
+ _git(tmp_path, "config", "user.name", "t")
+ _commit(tmp_path, "app.py", "x = 1\n")
+ _git(tmp_path, "switch", "-qc", "feature")
+ return tmp_path
+
+
+def _check(repo, *args: str, env=None):
+ return CliRunner().invoke(
+ security_command,
+ ["check", "main...HEAD", "--path", str(repo), *args],
+ env=env or {},
+ )
+
+
+def test_a_clean_change_exits_zero(repo):
+ _commit(repo, "app.py", "x = 2\n")
+ result = _check(repo)
+ assert result.exit_code == 0, result.output
+ assert "Gate passed" in result.output
+
+
+def test_a_secret_deleted_inside_the_change_exits_one(repo):
+ _commit(repo, "cfg.py", f"AWS = '{KEY}'\n")
+ _commit(repo, "cfg.py", "AWS = None\n")
+ result = _check(repo, "--format", "json")
+ assert result.exit_code == 1
+ doc = json.loads(result.stdout)
+ (finding,) = doc["findings"]
+ assert finding["kind"] == "aws_access_key" and finding["commit"]
+ assert doc["gate"]["passed"] is False and doc["commits_scanned"] == 2
+ assert KEY not in result.output
+
+
+def test_fail_on_decides_what_fails(repo):
+ _commit(repo, "h.py", "import hashlib\nhashlib.md5(b'')\n")
+ assert _check(repo).exit_code == 0
+ assert _check(repo, "--fail-on", "low").exit_code == 1
+
+
+def test_unknown_revision_exits_two_with_a_json_document(repo):
+ result = CliRunner().invoke(
+ security_command, ["check", "nope...HEAD", "--path", str(repo), "--format", "json"]
+ )
+ assert result.exit_code == 2
+ assert json.loads(result.stdout)["error"] == "diff_failed"
+
+
+def test_not_a_git_repository_exits_two(tmp_path):
+ result = CliRunner().invoke(
+ security_command, ["check", "--path", str(tmp_path), "--format", "json"]
+ )
+ assert result.exit_code == 2
+ assert json.loads(result.stdout)["error"] == "not_a_git_repository"
+
+
+def test_unreadable_baseline_exits_two(repo, tmp_path):
+ bad = tmp_path / "baseline.json"
+ bad.write_text("not json", encoding="utf-8")
+ result = _check(repo, "--baseline", str(bad), "--format", "json")
+ assert result.exit_code == 2
+ assert json.loads(result.stdout)["error"] == "baseline_unreadable"
+
+
+def test_written_baseline_accepts_the_findings(repo, tmp_path):
+ _commit(repo, "cfg.py", f"AWS = '{KEY}'\n")
+ baseline = tmp_path / "baseline.json"
+ assert _check(repo, "--write-baseline", str(baseline)).exit_code == 0
+ assert KEY not in baseline.read_text(encoding="utf-8")
+ result = _check(repo, "--baseline", str(baseline))
+ assert result.exit_code == 0, result.output
+
+
+def test_github_format_annotates_and_fills_the_step_summary(repo, tmp_path):
+ _commit(repo, "run.py", "import os\nos.system(cmd)\n")
+ summary = tmp_path / "summary.md"
+ result = _check(repo, "--format", "github", env={"GITHUB_STEP_SUMMARY": str(summary)})
+ assert result.exit_code == 1
+ assert result.stdout.startswith("::error file=run.py,line=2,")
+ assert "a floor, not a scanner" in summary.read_text(encoding="utf-8")
+
+
+def test_sarif_format_is_one_log(repo):
+ _commit(repo, "run.py", "import os\nos.system(cmd)\n")
+ result = _check(repo, "--format", "sarif")
+ assert result.exit_code == 1
+ log = json.loads(result.stdout)
+ assert log["runs"][0]["results"][0]["ruleId"] == "os_system"
+
+
+def test_write_baseline_merges_the_given_baseline_and_speaks_json(repo, tmp_path):
+ _commit(repo, "cfg.py", f"AWS = '{KEY}'\n")
+ old = tmp_path / "old.json"
+ old.write_text(
+ '{"version": 1, "entries": [{"fingerprint": "f" }]}', encoding="utf-8"
+ )
+ new = tmp_path / "new.json"
+ result = _check(
+ repo, "--baseline", str(old), "--write-baseline", str(new), "--format", "json"
+ )
+ assert result.exit_code == 0, result.output
+ assert json.loads(result.stdout) == {"baseline": str(new), "recorded": 1, "entries": 2}
+
+
+def test_sarif_suppresses_baselined_findings_below_the_threshold(repo, tmp_path):
+ _commit(repo, "h.py", "import hashlib\nhashlib.md5(b'')\n")
+ baseline = tmp_path / "b.json"
+ assert _check(repo, "--write-baseline", str(baseline)).exit_code == 0
+ result = _check(repo, "--baseline", str(baseline), "--format", "sarif")
+ (res,) = json.loads(result.stdout)["runs"][0]["results"]
+ assert res["ruleId"] == "weak_hash" and res["suppressions"] == [{"kind": "external"}]
diff --git a/tests/unit/test_ci_sarif.py b/tests/unit/test_ci_sarif.py
index aeeb03136..aa8ef1536 100644
--- a/tests/unit/test_ci_sarif.py
+++ b/tests/unit/test_ci_sarif.py
@@ -25,3 +25,9 @@ def test_run_indexes_known_rules_and_encodes_uris():
assert second["locations"][0]["physicalLocation"]["artifactLocation"]["uri"] == "docs/a.md"
assert second["properties"] == {"x": 1}
assert "properties" not in first
+
+
+def test_result_without_a_line_or_accepted_by_a_baseline():
+ res = sarif.result("r", "error", "m", "a.py", None, "k/v1", "abc", suppressed=True)
+ assert "region" not in res["locations"][0]["physicalLocation"]
+ assert res["suppressions"] == [{"kind": "external"}]