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): inline suppression marker, custom patterns and a pre-commit mode (#2657)

Raghav Chamadiya117911de512b
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.md
index 56c7da3ee..53eae5d4c 100644
--- a/docs/agent/HOOKS.md
+++ b/docs/agent/HOOKS.md
@@ -20,6 +20,7 @@ crashes or blocks your agent.
| Hook | Family | Installed by | Fires on | What it does |
|------|--------|--------------|----------|--------------|
| **Post-commit auto-sync** | git | `repowise init` by default (`--no-hook` skips it), or `repowise hook install` | every `git commit` | Runs `repowise update` in the background so the wiki tracks your code |
+| **Pre-commit security check** | git | `repowise hook install --security` (opt-in) | every `git commit` | Runs `repowise security check --staged` and blocks a commit that adds a finding at or above `high` ([details](../layers/SECURITY.md#before-a-commit---staged)) |
| **SessionStart context** | Claude Code | `repowise init` | session `startup` / `resume` / `clear` | Live index-freshness line, core-tool trust rule, and the standing decisions relevant to this session |
| **PostToolUse enrichment** | Claude Code | `repowise init` | `Grep` / `Glob` / `Read` / `Edit` / `Write` / repowise MCP calls | Graph context on searches, read-intelligence notices, and edit-time "governed by" decision notices |
| **Wrong-path rescue** | Claude Code | `repowise init` | a `Read` / `Edit` / `Write` / `Grep` / `Glob` / `NotebookEdit` that failed on a path this tree does not have | Names the file when exactly one indexed file carries that basename; silent otherwise |
diff --git a/docs/layers/SECURITY.md b/docs/layers/SECURITY.md
index b8f68d544..0f13feba1 100644
--- a/docs/layers/SECURITY.md
+++ b/docs/layers/SECURITY.md
@@ -298,6 +298,32 @@ commit, so fetch the full history; the gate exits 2 rather than guess. The
GitHub Action, the GitLab template and the SARIF upload are in
[Repowise in CI](../start/CI.md).
+### Silencing one finding: `repowise-security-ignore`
+
+For a single false positive, put `repowise-security-ignore` on the finding's
+own line, in any comment syntax; `repowise-security-ignore: aws_access_key`
+silences only the kinds it lists. There is no next-line or whole-file form: use
+the baseline for that. A silenced finding never fails the gate and is still
+reported as suppressed in every format. The exact rules are in the
+[CLI reference](../reference/CLI_REFERENCE.md#repowise-security-check-revspec).
+
+### Custom patterns: `security.patterns`
+
+A secret shape of your own goes under `security.patterns` in
+`.repowise/config.yaml` as a name, a regex and a severity. Each becomes the
+secret kind `custom:<name>`, scanned and masked like the built-in ones, and an
+invalid pattern stops the check with exit 2. Keys and limits are in
+[the `security:` block](../reference/CONFIG.md#the-security-block).
+
+### Before a commit: `--staged`
+
+`repowise security check --staged` checks what the next commit would record:
+the staged lines, read from the index. `repowise hook install --security` runs
+it as a pre-commit hook that blocks a commit only on a finding at or above
+`high`, and lets the commit through when the check cannot run. Skip it once
+with `git commit --no-verify`. See
+[`repowise hook install`](../reference/CLI_REFERENCE.md#repowise-hook-install).
+
## Line verification
A finding's `line_number` is written at scan time, and the file moves on. A wrong
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 3c2531eae..3327cfd82 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -990,10 +990,21 @@ default branch.
| `--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) |
+| `--staged` | Check the staged lines, read from the index, for a pre-commit hook: no history scan, no REVSPEC; `security.patterns` still comes from the working tree |
| `--format` | `table` (default), `json`, `markdown`, `github`, `sarif`, `gitlab` (GitLab Code Quality report) |
+A `repowise-security-ignore` comment on a finding's line silences it:
+
+- The token is exact and case-sensitive and covers its own line only; there is no next-line or whole-file form.
+- Bare, it silences every kind on the line; `: kind, kind` silences only those (`custom:<name>` for a custom pattern). Free text after the colon names no kind and silences nothing.
+- A secret found in an earlier commit of the change stays silenced only if that commit carries the marker; squash or rotate.
+- Silenced findings never fail and never enter `--write-baseline`. JSON lists them in `gate.suppressed` (never the matched text) with `gate.suppressed_count`; SARIF marks them `inSource`; table, markdown and `github` count them; the GitLab report omits them and logs the count.
+
+Custom secret shapes go in [`security.patterns`](CONFIG.md#the-security-block).
+
```bash
repowise security check origin/main...HEAD
+repowise security check --staged
repowise security check --format github --baseline .security-baseline.json
repowise security check --format sarif > security.sarif
repowise security check --format gitlab > gl-code-quality-security.json
@@ -1002,8 +1013,9 @@ 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)
+a commit of the change, an unreadable baseline, an invalid `security.patterns`,
+an unexpected internal error, a REVSPEC given with `--staged`). 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.
---
@@ -1751,8 +1763,14 @@ Install a post-commit git hook that runs `repowise update` in the background aft
```bash
repowise hook install # current repo
repowise hook install --workspace # all workspace repos
+repowise hook install --security # also a pre-commit security check
```
+`--security` adds a marked block at the top of the pre-commit script that runs
+`repowise security check --staged`: exit 1 (a finding at or above `high`)
+blocks the commit; exit 2 or a missing `repowise` lets it through. `hook status`
+reports it. Skip it once with `git commit --no-verify`.
+
### `repowise hook status`
Check if hooks are installed.
@@ -1764,7 +1782,8 @@ repowise hook status --workspace
### `repowise hook uninstall`
-Remove the post-commit hook.
+Remove everything `hook install` added: the post-commit hook and, when
+installed, the `--security` pre-commit block.
```bash
repowise hook uninstall
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index ebfa2ffc5..433c63cbe 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -14,6 +14,7 @@ The `.repowise/` directory, provider setup, API keys, and what's customizable.
[The `hooks:` block](#the-hooks-block) ·
[The `mcp:` block](#the-mcp-block) ·
[The `decisions:` block](#the-decisions-block) ·
+[The `security:` block](#the-security-block) ·
[The `refactoring:` block](#the-refactoring-block) ·
[The `assertions:` block](#the-assertions-block)
@@ -89,8 +90,9 @@ flags like `--commit-limit`, `--follow-renames`, or `--wiki-style`.
> **Limited schema validation.** `config.yaml` is loaded as a plain YAML dict.
> Unknown or misspelled keys are silently ignored, they won't error and won't
-> take effect. `max_tokens` must be a positive integer when documentation is
-> generated. The `distill:` block is validated only when you run
+> take effect, except in the `security:` block, where they stop
+> `repowise security check`. `max_tokens` must be a positive integer when
+> documentation is generated. The `distill:` block is validated only when you run
> `repowise doctor`. If a setting doesn't seem to be taking effect, check
> spelling and indentation first.
@@ -554,6 +556,23 @@ Dismissals are sticky: `repowise decision dismiss` keeps the record as a
a confirmed (`active`) decision is never walked back to `proposed` by a
re-extraction.
+### The `security:` block
+
+Secret shapes of your own for `repowise security check`.
+
+```yaml
+security:
+ patterns:
+ - name: internal_token # 1 to 40 of a-z, 0-9, _ and -, unique
+ regex: 'itk_[A-Za-z0-9]{32}'
+ severity: high # low, med or high; high when omitted
+```
+
+- Each is the secret kind `custom:<name>` (SARIF rule `custom/<name>`): changed lines only, every commit of the change scanned, a match masked to its first four characters and `****` in every format. It keeps its severity under test, fixture and example paths.
+- A finding is keyed on file, kind and masked line, so two matches with the same visible prefix on one line share a baseline entry.
+- Exit 2 (`config_invalid`, every problem listed) on an unknown key, a missing name or regex, a duplicate or badly shaped name, a bad severity, or a regex that does not compile, can match zero characters, or nests repetition like `(a+)+` or `(a|aa)+` (best effort).
+- At most 50 patterns of 500 characters. Lines over 4096 characters are not matched and are counted (`long_lines_skipped` in JSON); a slow regex that passes the checks stays slow.
+
### The `refactoring:` block
Controls the refactoring-intelligence layer: the structured Extract Class /
diff --git a/docs/start/CI.md b/docs/start/CI.md
index bbb8d5a31..1ddd50abf 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -80,7 +80,8 @@ deletes or renames), which needs no baseline but does need `fetch-depth: 0`.
Security has a baseline too, for accepting a finding a change adds on purpose
(a documented test key, say): `repowise security check --write-baseline
.security-baseline.json` on that change records it, and `--baseline` accepts it
-from then on.
+from then on. A `repowise-security-ignore` comment silences one false positive
+([details](../layers/SECURITY.md#silencing-one-finding-repowise-security-ignore)).
## GitHub Actions
diff --git a/packages/cli/src/repowise/cli/ci.py b/packages/cli/src/repowise/cli/ci.py
index c47c9d79f..ef625c004 100644
--- a/packages/cli/src/repowise/cli/ci.py
+++ b/packages/cli/src/repowise/cli/ci.py
@@ -93,19 +93,24 @@ def ci_revspec(root: str, revspec: str | None) -> str:
raise CannotEvaluateError("base_not_found", str(exc)) from exc
-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."""
+def change_lines(
+ root: str, revspec: str | None, *, staged: bool = False
+) -> tuple[dict[str, set[int]], str]:
+ """``({file: new-side lines}, label)`` for *revspec*, else the CI's target branch.
+
+ With *staged*, the staged diff (what ``git commit`` would record) instead.
+ """
import subprocess
from repowise.core.analysis.changed_lines import changed_lines
- revspec = ci_revspec(root, revspec)
+ revspec = None if staged else ci_revspec(root, revspec)
try:
- return changed_lines(root, revspec)
+ return changed_lines(root, revspec, staged=staged)
except ValueError as exc:
+ hint = "" if staged else f" {SHALLOW_CLONE_HINT}"
raise CannotEvaluateError(
- "diff_failed",
- f"Could not diff {revspec}: {exc}. {SHALLOW_CLONE_HINT}"
+ "diff_failed", f"Could not diff {revspec or 'the staged changes'}: {exc}.{hint}"
) from exc
except (subprocess.SubprocessError, OSError) as exc:
raise CannotEvaluateError("git_failed", f"Could not run git: {exc}") from exc
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index ed7456f81..e70c8c5a6 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -67,12 +67,22 @@ def _hook_target(
default=False,
help="Force single-repo mode even when invoked from a workspace.",
)
-def hook_install(path: str | None, workspace: bool, no_workspace: bool) -> None:
+ "--security",
+ is_flag=True,
+ default=False,
+ help="Also install a pre-commit hook that runs `repowise security check --staged` "
+ "and blocks a commit that adds a finding at or above high (skip once with "
+ "git commit --no-verify).",
+)
+def hook_install(path: str | None, workspace: bool, no_workspace: bool, security: bool) -> None:
"""Install a post-commit hook that auto-syncs after every commit."""
- from repowise.cli.hooks import install
+ from repowise.cli.hooks import install, install_security
target = _hook_target(path, workspace, no_workspace)
_run_post_commit_action(target, install, action="installed")
+ if security:
+ _run_security_action(target, install_security, style="green")
@hook_group.command("uninstall")
@@ -91,10 +101,11 @@ def hook_install(path: str | None, workspace: bool, no_workspace: bool) -> None:
help="Force single-repo mode even when invoked from a workspace.",
)
def hook_uninstall(path: str | None, workspace: bool, no_workspace: bool) -> None:
- """Remove the repowise post-commit hook."""
- from repowise.cli.hooks import uninstall
+ """Remove everything repowise installed: the post-commit hook and the security block."""
+ from repowise.cli.hooks import uninstall, uninstall_security
target = _hook_target(path, workspace, no_workspace)
+ _run_security_action(target, uninstall_security)
_run_post_commit_action(target, uninstall, action="uninstalled")
@@ -120,6 +131,16 @@ def _run_post_commit_action(target, run: Callable[[Path], str], *, action: str)
raise click.ClickException(f"No post-commit hooks were {action}.")
+def _run_security_action(target, run: Callable[[Path], str], *, style: str = "") -> None:
+ """The opt-in pre-commit security block across the same targets as the post-commit hook."""
+ for alias, repo_path in _target_repo_entries(target):
+ result = run(repo_path)
+ if not style and not result.startswith("removed"):
+ continue # uninstall reports the block only where there was one
+ label = f" {alias} pre-commit (security)" if target.is_workspace else "Pre-commit (security)"
+ console.print(f"{label}: [{style}]{result}[/{style}]" if style else f"{label}: {result}")
+
+
@hook_group.group("rewrite")
def rewrite_group() -> None:
"""Manage the distill command-rewrite hook (Claude Code + Codex).
@@ -1008,20 +1029,24 @@ def hook_backfill(path: str | None, all_projects: bool, days: int | None, reset:
help="Force single-repo mode even when invoked from a workspace.",
)
def hook_status(path: str | None, workspace: bool, no_workspace: bool) -> None:
- """Check if the repowise post-commit hook is installed."""
- from repowise.cli.hooks import status
+ """Check if the repowise post-commit hook (and the security pre-commit block) is installed."""
+ from repowise.cli.hooks import security_status, status
target = _hook_target(path, workspace, no_workspace)
+ def _line(label: str, result: str) -> str:
+ icon = "[green]✓[/green]" if result.startswith("installed") else "[dim]✗[/dim]"
+ return f" {icon} {label}: {result}"
+
if target.is_workspace:
assert target.ws_root is not None and target.ws_config is not None
for entry in target.ws_config.repos:
abs_path = (target.ws_root / entry.path).resolve()
- result = status(abs_path)
- icon = "[green]✓[/green]" if result.startswith("installed") else "[dim]✗[/dim]"
- console.print(f" {icon} {entry.alias}: {result}")
+ console.print(_line(entry.alias, status(abs_path)))
+ if (result := security_status(abs_path)).startswith("installed"):
+ console.print(_line(f"{entry.alias} pre-commit (security)", result))
else:
assert target.repo_path is not None
- result = status(target.repo_path)
- icon = "[green]✓[/green]" if result.startswith("installed") else "[dim]✗[/dim]"
- console.print(f" {icon} post-commit: {result}")
+ console.print(_line("post-commit", status(target.repo_path)))
+ if (result := security_status(target.repo_path)).startswith("installed"):
+ console.print(_line("pre-commit (security)", result))
diff --git a/packages/cli/src/repowise/cli/commands/security_cmd.py b/packages/cli/src/repowise/cli/commands/security_cmd.py
index 0d4a7f63b..5d7dfad49 100644
--- a/packages/cli/src/repowise/cli/commands/security_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/security_cmd.py
@@ -6,7 +6,7 @@ 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 ...]
+ check [REVSPEC | --staged] [--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`).
@@ -14,6 +14,7 @@ Subcommands:
from __future__ import annotations
+from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
@@ -41,7 +42,7 @@ 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
+ from repowise.core.analysis.security_gate import ChangeScan, CustomPattern, GateResult
_CHECK_FORMATS = (*CI_FORMATS, "sarif", "gitlab")
@@ -242,6 +243,13 @@ def security_scan(
default=None,
help="A path inside the repository (defaults to cwd).",
)
+ "--staged",
+ is_flag=True,
+ default=False,
+ help="Check the staged changes (what the next commit records), read from the index; "
+ "for a pre-commit hook. Takes no REVSPEC.",
+)
@format_option(
choices=_CHECK_FORMATS,
help="Output format. ``github`` writes annotations to stdout and the "
@@ -254,6 +262,7 @@ def security_check(
baseline_path: Path | None,
write_baseline_path: Path | None,
repo: str | None,
+ staged: bool,
fmt: str,
) -> None:
"""Gate a change on the security findings it adds (no index needed, built for CI).
@@ -265,26 +274,73 @@ def security_check(
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.
+ pull-request variables, else the remote's default branch. ``--staged``
+ checks what the next commit would record instead.
+
+ A ``repowise-security-ignore`` comment on a finding's line silences it
+ (``repowise-security-ignore: kind, kind`` silences only those kinds); it is
+ still counted and listed. ``security.patterns`` in .repowise/config.yaml
+ adds secret shapes of your own.
Examples:
repowise security check origin/main...HEAD
+ repowise security check --staged
repowise security check --format github --baseline .security-baseline.json
repowise security check --format sarif > security.sarif
repowise security check --format gitlab > gl-code-quality-security.json
"""
- from repowise.core.analysis.security_gate import evaluate
-
+ if staged and revspec:
+ raise click.UsageError("--staged checks the staged changes; drop REVSPEC.")
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 [])
+ _check(
+ _CheckOptions(revspec, fail_on, baseline_path, write_baseline_path, repo, staged, fmt)
+ )
+ except (click.exceptions.Exit, click.ClickException, click.Abort):
+ raise
+ except Exception as exc:
+ # A crash must never read as a failed gate: a pre-commit hook blocks on 1 only.
+ cannot_evaluate(fmt, "internal_error", f"security check failed unexpectedly: {exc!r}")
+
+
+@dataclass(frozen=True)
+class _CheckOptions:
+ """The ``security check`` flags, as the command received them."""
+
+ revspec: str | None
+ fail_on: str
+ baseline_path: Path | None
+ write_baseline_path: Path | None
+ repo: str | None
+ staged: bool
+ fmt: str
+
+
+@dataclass(frozen=True)
+class _Verdict:
+ """A finished check, ready to render: *accepted* is the whole baseline."""
+
+ scan: ChangeScan
+ gate: GateResult
+ label: str
+ accepted: frozenset[str]
+ patterns: tuple[CustomPattern, ...]
+
+
+def _check(opts: _CheckOptions) -> None:
+ from repowise.core.analysis.security_gate import evaluate
+
+ fmt = opts.fmt
+ try:
+ root = repo_root(opts.repo)
+ patterns = _custom_patterns(root)
+ accepted = _baseline_entries(opts.baseline_path) if opts.baseline_path else None
+ changed, label = change_lines(str(root), opts.revspec, staged=opts.staged)
+ scan = _scan_change(root, changed, label, patterns=patterns, staged=opts.staged)
+ if opts.write_baseline_path is not None:
+ _record_baseline(opts.write_baseline_path, scan, fmt, also_keep=accepted or [])
return
except CannotEvaluateError as exc:
cannot_evaluate(fmt, exc.code, str(exc))
@@ -292,13 +348,37 @@ def security_check(
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())
+ gate = evaluate(
+ scan.findings, fail_on=opts.fail_on, baseline=baseline, suppressed=scan.suppressed
+ )
+ _EMITTERS.get(fmt, _print_check)(_Verdict(scan, gate, label, baseline or frozenset(), patterns))
if not gate.passed:
raise click.exceptions.Exit(EXIT_GATE_FAILED)
-def _scan_change(root: Path, changed: dict[str, set[int]], label: str) -> ChangeScan:
+def _custom_patterns(root: Path) -> tuple[CustomPattern, ...]:
+ """``security.patterns`` from the repo config; any invalid entry stops the check."""
+ from repowise.core.analysis.security_gate import custom_patterns
+ from repowise.core.repo_config import RepoConfigError, load_repo_config
+
+ try:
+ config = load_repo_config(root)
+ except (RepoConfigError, OSError) as exc:
+ raise CannotEvaluateError("config_invalid", str(exc)) from exc
+ patterns, errors = custom_patterns(config)
+ if errors:
+ raise CannotEvaluateError("config_invalid", " ".join(errors))
+ return patterns
+
+
+def _scan_change(
+ root: Path,
+ changed: dict[str, set[int]],
+ label: str,
+ *,
+ patterns: tuple[CustomPattern, ...],
+ staged: bool,
+) -> ChangeScan:
"""Scan the change, turning a git failure into a cannot-evaluate."""
import subprocess
@@ -309,7 +389,7 @@ def _scan_change(root: Path, changed: dict[str, set[int]], label: str) -> Change
)
try:
- return scan_change(str(root), changed, label)
+ return scan_change(str(root), changed, label, patterns=patterns, staged=staged)
except ShallowHistoryError as exc:
raise CannotEvaluateError("history_shallow", str(exc)) from exc
except MissingObjectError as exc:
@@ -355,87 +435,132 @@ def _record_baseline(path: Path, scan: ChangeScan, fmt: str, *, also_keep: list[
)
-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
+def _emit_json(v: _Verdict) -> None:
+ from repowise.core.analysis.security_gate import DETECTION_BASIS
- 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 == "gitlab":
- emit_json(
- security_gate.render_gitlab(scan.findings, fail_on=gate.fail_on, accepted=accepted)
+ emit_json(
+ {
+ "revspec": v.label,
+ "files_scanned": v.scan.files_scanned,
+ "commits_scanned": v.scan.commits_scanned,
+ "long_lines_skipped": v.scan.long_lines_skipped,
+ "findings_basis": DETECTION_BASIS,
+ "findings": v.scan.findings,
+ "gate": v.gate.to_dict(),
+ }
+ )
+
+
+def _emit_sarif(v: _Verdict) -> None:
+ from repowise.cli import __version__
+ from repowise.core.analysis.security_gate import SarifExtras, render_sarif
+
+ extras = SarifExtras(v.gate.suppressed, v.patterns, v.scan.long_lines_skipped)
+ emit_json(
+ render_sarif(
+ v.scan.findings,
+ tool_version=__version__,
+ fail_on=v.gate.fail_on,
+ accepted=v.accepted,
+ extras=extras,
)
- elif fmt in ("markdown", "github"):
- markdown = security_gate.render_markdown(
- gate,
- label=label,
- files_scanned=scan.files_scanned,
- commits_scanned=scan.commits_scanned,
+ )
+
+
+def _emit_gitlab(v: _Verdict) -> None:
+ from repowise.core.analysis.security_gate import render_gitlab
+
+ emit_json(render_gitlab(v.scan.findings, fail_on=v.gate.fail_on, accepted=v.accepted))
+ # Code Quality has no suppression field or run properties: counts go to the job log.
+ if v.gate.suppressed:
+ ci_notices("gitlab").print(
+ f"{len(v.gate.suppressed)} finding(s) suppressed inline "
+ "(repowise-security-ignore), left out of the report."
)
- 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)
+ if v.scan.long_lines_skipped:
+ ci_notices("gitlab").print(_long_lines_note(v.scan.long_lines_skipped))
+
+
+def _markdown(v: _Verdict) -> str:
+ from repowise.core.analysis.security_gate import render_markdown
+
+ return render_markdown(
+ v.gate,
+ label=v.label,
+ files_scanned=v.scan.files_scanned,
+ commits_scanned=v.scan.commits_scanned,
+ long_lines_skipped=v.scan.long_lines_skipped,
+ )
+
+
+def _emit_markdown(v: _Verdict) -> None:
+ click.echo(_markdown(v), nl=False)
+
+
+def _emit_github(v: _Verdict) -> None:
+ from repowise.core.analysis.security_gate import github_annotations
+
+ for line in github_annotations(v.scan.findings, v.gate):
+ click.echo(line)
+ append_step_summary(_markdown(v))
_SEVERITY_COLOUR = {"high": "red", "med": "yellow", "low": "dim"}
-def _print_check(scan: ChangeScan, gate: GateResult, label: str) -> None:
+def _print_check(v: _Verdict) -> None:
+ from repowise.core.analysis.security_gate import DETECTION_BASIS
+
+ console.print(
+ f"[bold]{escape(v.label)}[/bold]: {v.scan.files_scanned} changed file(s) and "
+ f"{v.scan.commits_scanned} commit(s) scanned"
+ )
+ _print_findings(v)
+ _print_suppressed(v.gate)
+ if v.scan.long_lines_skipped:
+ console.print(f"[yellow]{_long_lines_note(v.scan.long_lines_skipped)}[/yellow]")
+ _print_gate(v.gate)
+ console.print(f"[dim]{escape(DETECTION_BASIS)}[/dim]")
+
+
+def _print_findings(v: _Verdict) -> None:
+ """The findings the baseline did not accept, as a table."""
from rich.table import Table
- from repowise.core.analysis.security_gate import DETECTION_BASIS
+ from repowise.core.analysis.security_gate import location
+
+ accepted = {f["fingerprint"] for f in v.gate.baselined}
+ rows = [f for f in v.scan.findings if f["fingerprint"] not in accepted]
+ if not rows:
+ return
+ table = Table(show_edge=False, pad_edge=False)
+ for column in ("Severity", "Kind", "Where", "Matched (secrets masked)"):
+ table.add_column(column)
+ for f in rows:
+ colour = _SEVERITY_COLOUR[f["severity"]]
+ table.add_row(
+ f"[{colour}]{f['severity']}[/]",
+ escape(f["kind"]),
+ escape(location(f)),
+ escape(f["snippet"]),
+ )
+ console.print(table)
+
+def _print_suppressed(gate: GateResult) -> None:
+ from repowise.core.analysis.security_gate import location
+
+ if not gate.suppressed:
+ return
console.print(
- f"[bold]{escape(label)}[/bold]: {scan.files_scanned} changed file(s) and "
- f"{scan.commits_scanned} commit(s) scanned"
+ f"[dim]{len(gate.suppressed)} finding(s) suppressed inline "
+ "(repowise-security-ignore):[/dim]"
)
- 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)
+ for f in gate.suppressed:
+ console.print(f"[dim] {escape(location(f))} {escape(f['kind'])} ({f['severity']})[/dim]")
+
+
+def _print_gate(gate: GateResult) -> None:
if gate.passed:
console.print(f"[green]Gate passed[/green] [dim](fails on {gate.fail_on} or above)[/dim]")
else:
@@ -446,7 +571,25 @@ def _print_check(scan: ChangeScan, gate: GateResult, label: str) -> None:
)
if any(f["commit"] for f in gate.failing):
console.print(
- "[yellow]A row marked @ commit is a secret committed inside this change; "
+ "[yellow]A row naming a 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]")
+
+
+#: Writers per ``--format``; ``table`` (the default) is :func:`_print_check`.
+_EMITTERS = {
+ "json": _emit_json,
+ "sarif": _emit_sarif,
+ "gitlab": _emit_gitlab,
+ "markdown": _emit_markdown,
+ "github": _emit_github,
+}
+
+
+def _long_lines_note(n: int) -> str:
+ from repowise.core.analysis.security_gate import MAX_CUSTOM_LINE_LENGTH
+
+ return (
+ f"{n} line(s) over {MAX_CUSTOM_LINE_LENGTH} characters not matched "
+ "against custom patterns."
+ )
diff --git a/packages/cli/src/repowise/cli/hooks.py b/packages/cli/src/repowise/cli/hooks.py
index 8cc316968..d0981063e 100644
--- a/packages/cli/src/repowise/cli/hooks.py
+++ b/packages/cli/src/repowise/cli/hooks.py
@@ -1,9 +1,10 @@
-"""Git hook management for repowise auto-sync.
+"""Git hook management for repowise auto-sync and the opt-in security check.
Installs/uninstalls a post-commit hook that runs ``repowise update`` in the
-background after every commit, keeping the wiki in sync automatically.
+background after every commit, keeping the wiki in sync automatically, and on
+request a pre-commit block that runs ``repowise security check --staged``.
-The hook uses start/end markers so it can safely coexist with other hooks
+Each block uses start/end markers so it can safely coexist with other hooks
in the same file (a lint hook, another tool's index hook).
"""
@@ -98,6 +99,54 @@ _HOOK_SCRIPT = """\
# repowise-hook-end
"""
+_SECURITY_MARKER = "# repowise-security-hook-start"
+_SECURITY_MARKER_END = "# repowise-security-hook-end"
+
+# Pre-commit contract: only exit 1 (the gate failed) blocks the commit. Exit 2
+# (the check could not run) and a missing ``repowise`` let it through, because
+# a broken tool must not stop anyone committing. ``|| RW_STATUS=$?`` keeps a
+# ``sh -e`` hook alive to read the code, and there is no ``exit 0`` at the end,
+# so the user's own pre-commit lines after the block still run.
+_SECURITY_HOOK_SCRIPT = """\
+# repowise-security-hook-start
+# Blocks a commit whose staged lines add a security finding.
+# Installed by: repowise hook install --security (skip once: git commit --no-verify)
+RW_ROOT=$(git rev-parse --show-toplevel 2>/dev/null) || RW_ROOT=""
+RW_BIN=""
+if command -v repowise >/dev/null 2>&1; then
+ RW_BIN=repowise
+elif [ -x "$RW_ROOT/.venv/bin/repowise" ]; then
+ RW_BIN="$RW_ROOT/.venv/bin/repowise"
+elif [ -x "$RW_ROOT/.venv/Scripts/repowise.exe" ]; then
+ RW_BIN="$RW_ROOT/.venv/Scripts/repowise.exe"
+fi
+if [ -n "$RW_BIN" ]; then
+ RW_STATUS=0
+ "$RW_BIN" security check --staged || RW_STATUS=$?
+ if [ "$RW_STATUS" -eq 1 ]; then
+ echo "repowise: commit blocked by the security check (git commit --no-verify skips it)." >&2
+ exit 1
+ elif [ "$RW_STATUS" -ne 0 ]; then
+ echo "repowise: the security check could not run (exit $RW_STATUS); commit allowed." >&2
+ fi
+else
+ echo "repowise: repowise not found; security check skipped, commit allowed." >&2
+fi
+# repowise-security-hook-end
+"""
+
+
+def _write_hook(hook_path: Path, content: str) -> None:
+ """Write a hook script with LF endings and make it executable.
+
+ sh reads ``then\\r`` as a syntax error, and a pre-commit hook that errors
+ blocks every commit.
+ """
+ hook_path.write_text(content, encoding="utf-8", newline="\n")
+ # Make executable (no-op on Windows but harmless)
+ with contextlib.suppress(OSError):
+ hook_path.chmod(hook_path.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
+
def _git_root(path: Path) -> Path | None:
"""Walk up to find .git directory."""
@@ -260,7 +309,16 @@ def _strip_legacy_block(content: str) -> tuple[str, bool]:
return cleaned, True
-def _replace_marker_block(content: str, new_block: str) -> tuple[str, bool]:
+def _marker_block_re(start: str, end: str) -> re.Pattern[str]:
+ return re.compile(rf"{re.escape(start)}.*?{re.escape(end)}\n?", flags=re.DOTALL)
+
+
+def _replace_marker_block(
+ content: str,
+ new_block: str,
+ start: str = _HOOK_MARKER,
+ end: str = _HOOK_MARKER_END,
+) -> tuple[str, bool]:
"""Replace an existing repowise marker block in place. Returns (content, replaced).
Used when the hook is being upgraded: the marker is present but the
@@ -278,10 +336,7 @@ def _replace_marker_block(content: str, new_block: str) -> tuple[str, bool]:
breaking the shell quoting of the printf format string. A callable
bypasses escape processing entirely.
"""
- pattern = re.compile(
- rf"{re.escape(_HOOK_MARKER)}.*?{re.escape(_HOOK_MARKER_END)}\n?",
- flags=re.DOTALL,
- )
+ pattern = _marker_block_re(start, end)
if not pattern.search(content):
return content, False
replacement_text = new_block.rstrip() + "\n"
@@ -320,7 +375,7 @@ def install(repo_path: Path) -> str:
return "not installed: the existing post-commit hook is not a shell script"
content, migrated_legacy = _strip_legacy_block(content)
if migrated_legacy:
- hook_path.write_text(content, encoding="utf-8")
+ _write_hook(hook_path, content)
if _HOOK_MARKER in content:
# Marker block present. Decide whether to leave alone or upgrade.
@@ -330,16 +385,13 @@ def install(repo_path: Path) -> str:
return _annotate(_with_hook_execution_state(hook_path, state))
content, replaced = _replace_marker_block(content, _HOOK_SCRIPT)
if replaced:
- hook_path.write_text(content, encoding="utf-8")
+ _write_hook(hook_path, content)
return _annotate(_with_hook_execution_state(hook_path, "upgraded"))
return _annotate("already installed")
# Append to existing hook
- hook_path.write_text(
- content.rstrip() + "\n\n" + _HOOK_SCRIPT,
- encoding="utf-8",
- )
+ _write_hook(hook_path, content.rstrip() + "\n\n" + _HOOK_SCRIPT)
else:
- hook_path.write_text("#!/bin/sh\n" + _HOOK_SCRIPT, encoding="utf-8")
+ _write_hook(hook_path, "#!/bin/sh\n" + _HOOK_SCRIPT)
return _annotate(_with_hook_execution_state(hook_path, "installed"))
@@ -360,12 +412,60 @@ def _with_hook_execution_state(path: Path, state: str) -> str:
return state if _is_executable(path) else f"{state} but not executable"
+def install_security(repo_path: Path) -> str:
+ """Install the opt-in pre-commit block running ``repowise security check --staged``.
+
+ The block goes first, right after the shebang, so a user script that ends
+ in ``exit 0`` cannot make it unreachable. An older block is replaced in
+ place. Returns a human-readable status message.
+ """
+ if _git_root(repo_path) is None or (hooks_dir := _hooks_dir(repo_path)) is None:
+ return "not a git repository"
+ hooks_dir.mkdir(parents=True, exist_ok=True)
+ hook_path = hooks_dir / "pre-commit"
+ pending = husky_pending_reason(hooks_dir)
+ content = hook_path.read_text(encoding="utf-8") if hook_path.exists() else None
+ if content is not None and not _is_shell_hook(content):
+ return "not installed: the existing pre-commit hook is not a shell script"
+ content, state = _with_security_block(content)
+ if state != "already installed":
+ _write_hook(hook_path, content)
+ return f"{state} ({pending})" if pending else state
+
+
+def _with_security_block(content: str | None) -> tuple[str, str]:
+ """*content* (``None`` for no hook yet) holding the current block, and what changed."""
+ block = _SECURITY_HOOK_SCRIPT.rstrip() + "\n"
+ if content is None:
+ return "#!/bin/sh\n" + block, "installed"
+ if block in content:
+ return content, "already installed"
+ if _SECURITY_MARKER in content:
+ content, replaced = _replace_marker_block(
+ content, block, _SECURITY_MARKER, _SECURITY_MARKER_END
+ )
+ return content, "upgraded" if replaced else "already installed"
+ if content.startswith("#!"):
+ shebang, _, rest = content.partition("\n")
+ return f"{shebang}\n{block}{rest}", "installed"
+ return f"{block}{content}", "installed"
+
+
def uninstall(repo_path: Path) -> str:
"""Remove the repowise section from the post-commit hook.
Preserves other tools' hook content. Deletes the file entirely if
repowise was the only content.
"""
+ return _remove_block(repo_path, "post-commit", _HOOK_MARKER, _HOOK_MARKER_END)
+
+
+def uninstall_security(repo_path: Path) -> str:
+ """Remove the repowise security block from the pre-commit hook, as :func:`uninstall`."""
+ return _remove_block(repo_path, "pre-commit", _SECURITY_MARKER, _SECURITY_MARKER_END)
+
+
+def _remove_block(repo_path: Path, hook_name: str, start: str, end: str) -> str:
root = _git_root(repo_path)
if root is None:
return "not a git repository"
@@ -373,31 +473,35 @@ def uninstall(repo_path: Path) -> str:
hooks_dir = _hooks_dir(repo_path)
if hooks_dir is None:
return "not a git repository"
- hook_path = hooks_dir / "post-commit"
+ hook_path = hooks_dir / hook_name
if not hook_path.exists():
- return "no post-commit hook found"
+ return f"no {hook_name} hook found"
content = hook_path.read_text(encoding="utf-8")
- if _HOOK_MARKER not in content:
- return "repowise hook not found in post-commit"
+ if start not in content:
+ return f"repowise hook not found in {hook_name}"
- new_content = re.sub(
- rf"{re.escape(_HOOK_MARKER)}.*?{re.escape(_HOOK_MARKER_END)}\n?",
- "",
- content,
- flags=re.DOTALL,
- ).strip()
+ new_content = _marker_block_re(start, end).sub("", content).strip()
if not new_content or new_content in ("#!/bin/bash", "#!/bin/sh"):
hook_path.unlink()
return "removed"
else:
- hook_path.write_text(new_content + "\n", encoding="utf-8")
+ _write_hook(hook_path, new_content + "\n")
return "removed (other hook content preserved)"
def status(repo_path: Path) -> str:
"""Check if the repowise post-commit hook is installed."""
+ return _block_status(repo_path, "post-commit", _HOOK_MARKER)
+
+
+def security_status(repo_path: Path) -> str:
+ """Check if the repowise security pre-commit block is installed."""
+ return _block_status(repo_path, "pre-commit", _SECURITY_MARKER)
+
+
+def _block_status(repo_path: Path, hook_name: str, start: str) -> str:
root = _git_root(repo_path)
if root is None:
return "not a git repository"
@@ -405,12 +509,12 @@ def status(repo_path: Path) -> str:
hooks_dir = _hooks_dir(repo_path)
if hooks_dir is None:
return "not a git repository"
- hook_path = hooks_dir / "post-commit"
+ hook_path = hooks_dir / hook_name
if not hook_path.exists():
return "not installed"
content = hook_path.read_text(encoding="utf-8")
- if _HOOK_MARKER in content:
+ if start in content:
pending = husky_pending_reason(hook_path.parent)
state = "installed" if _is_executable(hook_path) else "installed but not executable"
return f"{state} ({pending})" if pending else state
diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.py
index 30ef31ba5..68378d661 100644
--- a/packages/core/src/repowise/core/analysis/changed_lines.py
+++ b/packages/core/src/repowise/core/analysis/changed_lines.py
@@ -32,10 +32,17 @@ from .git_cli 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
+#: Pinned diff output: ``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/")
+#: ``b/`` directory, and an external diff, a textconv or ``color.diff=always``
+#: would print something the parser reads as no change at all.
+DIFF_ARGS = (
+ "--src-prefix=a/",
+ "--dst-prefix=b/",
+ "--no-ext-diff",
+ "--no-color",
+ "--no-textconv",
+)
@dataclass
@@ -240,7 +247,7 @@ def changed_lines(
return _working_tree_lines(repo_path, base)
if staged or not revspec:
- diff = _git(["diff", "--cached", "--unified=0", *DIFF_PREFIXES], repo_path)
+ diff = _git(["diff", "--cached", "--unified=0", *DIFF_ARGS], repo_path)
return _parse_unified_diff(diff), "staged changes"
if (parts := split_revspec(revspec)) is not None:
@@ -250,7 +257,7 @@ def changed_lines(
_verify_ref(repo_path, base)
_verify_ref(repo_path, head)
label = f"{base}{sep}{head}"
- diff = _diff(repo_path, ["diff", "--unified=0", *DIFF_PREFIXES, label])
+ diff = _diff(repo_path, ["diff", "--unified=0", *DIFF_ARGS, label])
return _parse_unified_diff(diff), label
_verify_ref(repo_path, revspec)
@@ -261,7 +268,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", *DIFF_PREFIXES, "--format=", "-m", "--first-parent", revspec]
+ args = ["show", "--unified=0", *DIFF_ARGS, "--format=", "-m", "--first-parent", revspec]
return _parse_unified_diff(_diff(repo_path, args)), revspec
@@ -269,11 +276,11 @@ def _working_tree_lines(repo_path: str, base: str | None) -> tuple[dict[str, set
"""The working-tree half of :func:`changed_lines`: from *base*'s merge-base, else ``HEAD``."""
start = _merge_base_or_empty(repo_path, base) if base and base != "HEAD" else ""
if start:
- diff = _git(["diff", "--unified=0", *DIFF_PREFIXES, start], repo_path)
+ diff = _git(["diff", "--unified=0", *DIFF_ARGS, start], repo_path)
changed = _parse_unified_diff(diff)
changed.update(_untracked_lines(repo_path))
return changed, working_tree_label(base)
- diff = _git(["diff", "--unified=0", *DIFF_PREFIXES, "HEAD"], repo_path)
+ diff = _git(["diff", "--unified=0", *DIFF_ARGS, "HEAD"], repo_path)
changed = _parse_unified_diff(diff)
if base:
# Asked for what a push brings, with no merge-base to diff from: new
@@ -316,7 +323,7 @@ def diff_since(
the code being asked about (:func:`map_old_line` over ``FileDiff.hunks``).
"""
tail = [until] if until else []
- args = ["diff", "--unified=0", *DIFF_PREFIXES, since, *tail, "--", *paths]
+ args = ["diff", "--unified=0", *DIFF_ARGS, since, *tail, "--", *paths]
return parse_unified_diff(_diff(repo_path, args))
diff --git a/packages/core/src/repowise/core/analysis/security_gate.py b/packages/core/src/repowise/core/analysis/security_gate.py
index 7b4c47091..42b58042b 100644
--- a/packages/core/src/repowise/core/analysis/security_gate.py
+++ b/packages/core/src/repowise/core/analysis/security_gate.py
@@ -14,25 +14,34 @@ database. Two passes over the change:
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.
+
+Two repository-owned inputs shape a scan. ``security.patterns`` in
+``.repowise/config.yaml`` adds secret kinds (``custom:<name>``, see
+:func:`custom_patterns`), treated like the built-in ones. A
+``repowise-security-ignore`` marker on a finding's own line silences it (all
+kinds, or only the ``: kind, kind`` it lists); a silenced finding never fails
+the gate or enters a baseline, but every output still counts and lists it.
"""
from __future__ import annotations
import hashlib
+import re
+import string
import subprocess
-from collections.abc import Iterable, Mapping, Sequence
+from collections.abc import Iterable, Iterator, 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, gitlab, sarif
-from repowise.core.ci.markdown import ROW_LIMIT, cell, more_line, plural
+from repowise.core.ci.markdown import ROW_LIMIT, cell, details, 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
+from .changed_lines import DIFF_ARGS, parse_unified_diff
+from .security_scan import SECRET_KINDS, masked_snippet, scan_source, source_lines
#: Severities from least to most severe; ``--fail-on`` names the lowest that fails.
SEVERITIES = ("low", "med", "high")
@@ -96,6 +105,209 @@ _RULE_TEXT: dict[str, str] = {
}
+# ---------------------------------------------------------------------------
+# Custom patterns and the inline marker
+# ---------------------------------------------------------------------------
+
+MAX_CUSTOM_PATTERNS = 50
+MAX_CUSTOM_REGEX_LENGTH = 500
+#: Lines longer than this are not matched against custom patterns (counted as
+#: skipped). Ceiling: Python's ``re`` has no timeout, so only line length is
+#: bounded and a pathological regex that passes validation can still be slow.
+MAX_CUSTOM_LINE_LENGTH = 4096
+
+_CUSTOM_NAME = re.compile(r"[a-z0-9_-]{1,40}")
+_CUSTOM_KEYS = ("name", "regex", "severity")
+_CUSTOM_PREFIX = "custom:"
+#: Every printable ASCII character, so a zero-width pattern (``\b``, a
+#: lookaround such as ``(?=z)``) matches somewhere in it.
+_ZERO_WIDTH_PROBE = string.printable
+_QUANTIFIERS = ("*", "+", "{")
+
+_IGNORE_TOKEN = "repowise-security-ignore"
+_IGNORE_RE = re.compile(
+ rf"{_IGNORE_TOKEN}(?![\w-])"
+ r"(?:[ \t]*:[ \t]*([\w:-]+(?:[ \t]*,[ \t]*[\w:-]+)*))?"
+ # A colon no kind list follows is a malformed scope, which silences nothing.
+ r"(?P<stray>[ \t]*:)?"
+)
+
+
+@dataclass(frozen=True)
+class CustomPattern:
+ """One ``security.patterns`` entry: a secret shape the repository defines."""
+
+ name: str
+ regex: re.Pattern[str]
+ severity: str
+
+ @property
+ def kind(self) -> str:
+ return f"{_CUSTOM_PREFIX}{self.name}"
+
+
+def custom_patterns(
+ config: Mapping[str, Any],
+) -> tuple[tuple[CustomPattern, ...], tuple[str, ...]]:
+ """``security.patterns`` from a loaded repo config: the patterns, and every error found."""
+ raw, errors = _pattern_entries(config.get("security"))
+ patterns: list[CustomPattern] = []
+ for i, entry in enumerate(raw):
+ parsed = _custom_pattern(entry, {p.name for p in patterns})
+ if isinstance(parsed, CustomPattern):
+ patterns.append(parsed)
+ else:
+ errors.extend(f"{_entry_label(i, entry)}: {problem}" for problem in parsed)
+ return tuple(patterns), tuple(errors)
+
+
+def _pattern_entries(block: object) -> tuple[list, list[str]]:
+ """The ``security.patterns`` entries to parse, and the problems with the block around them."""
+ if block is None:
+ return [], []
+ if not isinstance(block, dict):
+ return [], ["security must be a mapping."]
+ unknown = sorted(str(k) for k in block if k != "patterns")
+ errors = [f"security: unknown key {', '.join(unknown)}; expected patterns."] if unknown else []
+ raw = block.get("patterns")
+ if raw is None:
+ return [], errors
+ if not isinstance(raw, list):
+ return [], [*errors, "security.patterns must be a list of {name, regex, severity}."]
+ if len(raw) > MAX_CUSTOM_PATTERNS:
+ errors.append(
+ f"security.patterns holds {len(raw)} entries; the limit is {MAX_CUSTOM_PATTERNS}."
+ )
+ return raw, errors
+
+
+def _entry_label(i: int, entry: object) -> str:
+ name = entry.get("name") if isinstance(entry, dict) else None
+ return f"security.patterns[{i}]" + (f" ({name!r})" if isinstance(name, str) else "")
+
+
+def _custom_pattern(entry: object, taken: set[str]) -> CustomPattern | list[str]:
+ """One entry, or every problem with it."""
+ if not isinstance(entry, dict):
+ return ["must be a mapping with name, regex and severity."]
+ name, severity = entry.get("name"), entry.get("severity", "high")
+ regex, regex_problems = _compiled_regex(entry.get("regex"))
+ problems = [
+ *_unknown_key_problems(entry),
+ *_name_problems(name, taken),
+ *_severity_problems(severity),
+ *regex_problems,
+ ]
+ if problems:
+ return problems
+ assert isinstance(name, str) and regex is not None
+ return CustomPattern(name, regex, str(severity))
+
+
+def _unknown_key_problems(entry: dict) -> list[str]:
+ unknown = sorted(str(k) for k in entry if k not in _CUSTOM_KEYS)
+ if not unknown:
+ return []
+ return [f"unknown key {', '.join(unknown)}; expected {', '.join(_CUSTOM_KEYS)}."]
+
+
+def _name_problems(name: object, taken: set[str]) -> list[str]:
+ if not isinstance(name, str) or not _CUSTOM_NAME.fullmatch(name):
+ return ["name must be 1 to 40 of a-z, 0-9, _ and -."]
+ return ["duplicate name; each pattern needs its own."] if name in taken else []
+
+
+def _severity_problems(severity: object) -> list[str]:
+ if severity in SEVERITIES:
+ return []
+ return [f"severity must be one of {', '.join(SEVERITIES)}, got {severity!r}."]
+
+
+def _compiled_regex(raw: object) -> tuple[re.Pattern[str] | None, list[str]]:
+ """*raw* compiled, or ``None`` and why it cannot be used."""
+ if not isinstance(raw, str) or not raw:
+ return None, ["regex must be a non-empty string."]
+ if len(raw) > MAX_CUSTOM_REGEX_LENGTH:
+ return None, [f"regex is longer than {MAX_CUSTOM_REGEX_LENGTH} characters."]
+ try:
+ regex = re.compile(raw)
+ except re.error as exc:
+ return None, [f"regex does not compile: {exc}."]
+ if _matches_zero_width(regex):
+ return None, ["regex can match zero characters, so it would match every line."]
+ if _nested_quantifier(raw):
+ return None, [
+ "regex repeats a group that itself repeats or alternates (like (a+)+ or "
+ "(a|aa)+), which can take exponential time; use a character class."
+ ]
+ return regex, []
+
+
+def _matches_zero_width(regex: re.Pattern[str]) -> bool:
+ if regex.search("") is not None:
+ return True
+ return any(m.start() == m.end() for m in regex.finditer(_ZERO_WIDTH_PROBE))
+
+
+def _nested_quantifier(regex: str) -> bool:
+ """Best effort: a group quantified by ``*``, ``+`` or ``{`` whose body repeats or alternates.
+
+ Reads the pattern's structure (:func:`_structure`) rather than a parse
+ tree, so it catches the classic backtracking shapes only.
+ """
+ stack = [False] # per open group: its body holds a quantifier or ``|``
+ for char, following in _structure(regex):
+ if char == "(":
+ stack.append(False)
+ elif char == ")" and len(stack) > 1:
+ risky = stack.pop()
+ quantified = following in _QUANTIFIERS
+ if risky and quantified:
+ return True
+ stack[-1] = stack[-1] or risky or quantified
+ elif char in _QUANTIFIERS or char == "|":
+ stack[-1] = True
+ return False
+
+
+def _structure(regex: str) -> Iterator[tuple[str, str]]:
+ """Each character of *regex* outside escapes and character classes, with the one after it."""
+ i = 0
+ while i < len(regex):
+ char = regex[i]
+ if char == "\\":
+ i += 2
+ elif char == "[":
+ i = _class_end(regex, i)
+ else:
+ yield char, regex[i + 1 : i + 2]
+ i += 1
+
+
+def _class_end(regex: str, start: int) -> int:
+ """The index just past the character class opening at *start*."""
+ i = start + 1
+ if regex[i : i + 1] == "^":
+ i += 1
+ if regex[i : i + 1] == "]":
+ i += 1
+ while i < len(regex) and regex[i] != "]":
+ i += 2 if regex[i] == "\\" else 1
+ return i + 1
+
+
+def _silenced(line: str, kind: str) -> bool:
+ """Whether a marker on *line* silences *kind*: the bare token all kinds, ``: a, b`` those."""
+ if _IGNORE_TOKEN not in line:
+ return False
+ match = _IGNORE_RE.search(line)
+ if match is None or match.group("stray"):
+ return False
+ if not match.group(1):
+ return True
+ return kind in {k.strip() for k in match.group(1).split(",")}
+
+
# ---------------------------------------------------------------------------
# Scan
# ---------------------------------------------------------------------------
@@ -110,9 +322,11 @@ def fingerprint_of(file_path: str, kind: str, snippet: str, material: str = "")
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.
+ Custom kinds do too: a repository's own pattern can be as weak as a password.
Consequence accepted: two identical matched lines in one file share a
- fingerprint, and so do two keyword secrets whose visible prefix and line agree.
+ fingerprint, and so do two keyword or custom 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]
@@ -125,6 +339,11 @@ class ChangeScan:
findings: list[dict]
files_scanned: int
commits_scanned: int
+ #: Silenced by a ``repowise-security-ignore`` marker on their line.
+ suppressed: list[dict] = field(default_factory=list)
+ #: Distinct changed lines over :data:`MAX_CUSTOM_LINE_LENGTH`, not matched
+ #: against custom patterns.
+ long_lines_skipped: int = 0
def _text(blob: bytes) -> str | None:
@@ -171,36 +390,144 @@ def _read_blobs(root: str, specs: Sequence[str]) -> list[str | 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.
+def _custom_spans(
+ line: str, patterns: Sequence[CustomPattern]
+) -> list[tuple[CustomPattern, list[tuple[int, int]]]]:
+ """Each pattern that matches *line*, with the span of every match."""
+ hits = []
+ for pattern in patterns:
+ spans = [m.span() for m in pattern.regex.finditer(line) if m.end() > m.start()]
+ if spans:
+ hits.append((pattern, spans))
+ return hits
+
+
+#: Set on a row a marker silenced; :func:`_split` removes it.
+_SUPPRESSED = "_suppressed"
+#: What JSON lists for a silenced finding: where and what, never the matched text.
+_SUPPRESSED_FIELDS = ("file_path", "line_number", "kind", "severity", "fingerprint", "commit")
+
+
+def _scoped(
+ path: str,
+ source: str,
+ lines: set[int],
+ *,
+ secrets_only: bool,
+ patterns: Sequence[CustomPattern] = (),
+) -> tuple[list[dict], set[tuple[str, str]]]:
+ """Findings in *source* that span a line in *lines*, as gate rows, and the long lines skipped.
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.
+ call, but a key pasted into a README is still a leak. Custom patterns are
+ secret kinds, matched on the lines in *lines* only; a custom match is also
+ masked in a built-in finding's snippet on its line, while that finding keeps
+ the fingerprint it has without patterns.
"""
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):
+ text = _Text(path, source_lines(source), patterns)
+ found = [
+ entry
+ for f in scan_source(path, source)
+ if (entry := _builtin_entry(text, f, lines, secrets_only)) is not None
+ ]
+ custom, long_lines = _custom_entries(text, lines)
+ return [_row(text, entry) for entry in [*found, *custom]], long_lines
+
+
+#: ``(line, kind, severity, snippet shown, fingerprint)``
+_Entry = tuple[int, str, str, str, str]
+
+
+@dataclass
+class _Text:
+ """One file's lines, with the custom-pattern matches on each looked up once."""
+
+ path: str
+ lines: list[str]
+ patterns: Sequence[CustomPattern]
+ _spans: dict[int, list[tuple[int, int]]] = field(default_factory=dict)
+ _hits: dict[int, list[CustomPattern]] = field(default_factory=dict)
+
+ def line(self, lineno: int) -> str:
+ return self.lines[lineno - 1] if lineno <= len(self.lines) else ""
+
+ def matched(self, lineno: int) -> list[CustomPattern]:
+ """The patterns matching *lineno*; none on a line too long to match."""
+ if lineno not in self._hits:
+ line = self.line(lineno)
+ hits = _custom_spans(line, self.patterns) if len(line) <= MAX_CUSTOM_LINE_LENGTH else []
+ self._hits[lineno] = [p for p, _ in hits]
+ self._spans[lineno] = [span for _, spans in hits for span in spans]
+ return self._hits[lineno]
+
+ def masked(self, lineno: int) -> str:
+ """*lineno* as a snippet with every custom match masked."""
+ self.matched(lineno)
+ return masked_snippet(self.line(lineno), self._spans[lineno])
+
+
+def _builtin_entry(
+ text: _Text, f: Mapping[str, Any], lines: set[int], secrets_only: bool
+) -> _Entry | None:
+ """A registry finding as an entry, or ``None`` when it is out of scope."""
+ if secrets_only and f["kind"] not in SECRET_KINDS:
+ return None
+ span = range(f["line"], f.get("end_line", f["line"]) + 1)
+ if lines.isdisjoint(span):
+ return None
+ material = ""
+ if f["kind"] in _KEY_SHAPE_KINDS:
+ material = "\n".join(text.lines[span.start - 1 : span.stop - 1])
+ snippet = f["snippet"]
+ fingerprint = fingerprint_of(text.path, f["kind"], snippet, material)
+ # Only a snippet cut from the line itself; a whole-line PEM mask stays.
+ if text.matched(f["line"]) and snippet == masked_snippet(text.line(f["line"])):
+ snippet = text.masked(f["line"])
+ return f["line"], f["kind"], f["severity"], snippet, fingerprint
+
+
+def _custom_entries(text: _Text, lines: set[int]) -> tuple[list[_Entry], set[tuple[str, str]]]:
+ """Custom-pattern entries on *lines*, and the lines too long to match."""
+ entries: list[_Entry] = []
+ long_lines: set[tuple[str, str]] = set()
+ if not text.patterns:
+ return entries, long_lines
+ for lineno in sorted(n for n in lines if n <= len(text.lines)):
+ if len(text.line(lineno)) > MAX_CUSTOM_LINE_LENGTH:
+ long_lines.add((text.path, text.line(lineno)))
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
+ snippet = text.masked(lineno)
+ for pattern in text.matched(lineno):
+ fingerprint = fingerprint_of(text.path, pattern.kind, snippet)
+ entries.append((lineno, pattern.kind, pattern.severity, snippet, fingerprint))
+ return entries, long_lines
+
+
+def _row(text: _Text, entry: _Entry) -> dict:
+ """*entry* as a gate row, flagged when a marker on its line silences it."""
+ lineno, kind, severity, snippet, fingerprint = entry
+ row = {
+ "file_path": text.path,
+ "line_number": lineno,
+ "kind": kind,
+ "severity": severity,
+ "snippet": snippet,
+ "fingerprint": fingerprint,
+ "commit": None,
+ }
+ if _silenced(text.line(lineno), kind):
+ row[_SUPPRESSED] = True
+ return row
+
+
+def _split(rows: Iterable[dict]) -> tuple[list[dict], list[dict]]:
+ """``(findings, suppressed)`` from :func:`_scoped` rows."""
+ findings: list[dict] = []
+ suppressed: list[dict] = []
+ for row in rows:
+ (suppressed if row.pop(_SUPPRESSED, False) else findings).append(row)
+ return findings, suppressed
def _log_range(root: str, revspec: str) -> list[str]:
@@ -219,19 +546,25 @@ def _log_range(root: str, revspec: str) -> list[str]:
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."""
+def _history_secrets(
+ root: str, revspec: str, patterns: Sequence[CustomPattern]
+) -> tuple[list[dict], int, set[tuple[str, str]]]:
+ """Secret rows on the lines each commit in the change added, oldest first.
+
+ Returns the :func:`_scoped` rows, the commits read and the long lines skipped.
+ """
# 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, "--"]
+ args = ["log", "--no-merges", "--reverse", "-p", "--unified=0"]
+ args += [*DIFF_ARGS, "--format=%x00%H", *log_range, "--"]
raw = _git(args, root)
chunks = raw.split("\0")[1:]
rows: list[dict] = []
+ skipped: set[tuple[str, str]] = set()
for chunk in chunks:
sha, _, diff = chunk.partition("\n")
sha = sha.strip()
@@ -248,10 +581,14 @@ def _history_secrets(root: str, revspec: str) -> tuple[list[dict], int]:
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):
+ scoped, long_lines = _scoped(
+ path, text, added[path], secrets_only=True, patterns=patterns
+ )
+ skipped |= long_lines
+ for row in scoped:
row["commit"] = sha
rows.append(row)
- return rows, len(chunks)
+ return rows, len(chunks), skipped
def _shallow_boundary(root: str, log_range: Sequence[str]) -> frozenset[str]:
@@ -277,31 +614,80 @@ def _shallow_boundary(root: str, log_range: Sequence[str]) -> frozenset[str]:
return frozenset(shallow.read_text(encoding="utf-8").split())
-def scan_change(root: str, changed: Mapping[str, set[int]], revspec: str) -> ChangeScan:
+def scan_change(
+ root: str,
+ changed: Mapping[str, set[int]],
+ revspec: str,
+ *,
+ patterns: Sequence[CustomPattern] = (),
+ staged: bool = False,
+) -> ChangeScan:
"""Every finding *revspec* adds; *changed* is its new-side lines per file.
+ With *staged*, *changed* is the staged diff: files are read from the index
+ and there is no history to scan, so *revspec* is only a label.
+
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] = []
+ # ``:0:<path>`` is the index's copy; ``:<path>`` misreads a path like ``1:notes.txt``.
+ rev = ":0" if staged else revspec_head(revspec)
+ rows: list[dict] = []
scanned = 0
- texts = _read_blobs(root, [f"{head}:{p}" for p in paths])
+ skipped: set[tuple[str, str]] = set()
+ texts = _read_blobs(root, [f"{rev}:{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)
+ scoped, long_lines = _scoped(
+ path, text, changed[path], secrets_only=False, patterns=patterns
+ )
+ rows += scoped
+ skipped |= long_lines
+ history: list[dict] = []
+ commits = 0
+ if not staged:
+ history, commits, long_lines = _history_secrets(root, revspec, patterns)
+ skipped |= long_lines
+ findings, suppressed = _merge(rows, history)
+ return ChangeScan(
+ findings,
+ files_scanned=scanned,
+ commits_scanned=commits,
+ suppressed=suppressed,
+ long_lines_skipped=len(skipped),
+ )
+
+
+def _merge(head: list[dict], history: list[dict]) -> tuple[list[dict], list[dict]]:
+ """``(findings, suppressed)``: the head's rows, then history rows no head row covers.
+
+ 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.
+ One fingerprint lands in one list, and an unsilenced row wins over a
+ silenced one.
+ """
+ findings, suppressed = _split(head)
+ failing = {f["fingerprint"] for f in findings}
+ suppressed = [r for r in suppressed if r["fingerprint"] not in failing]
+ silenced = {r["fingerprint"] for r in suppressed}
+ later_findings, later_suppressed = _split(history)
+ for row in later_findings:
+ fp = row["fingerprint"]
+ if fp in failing:
+ continue
+ if fp in silenced:
+ suppressed = [r for r in suppressed if r["fingerprint"] != fp]
+ silenced.discard(fp)
+ failing.add(fp)
+ findings.append(row)
+ for row in later_suppressed:
+ if row["fingerprint"] not in failing | silenced:
+ silenced.add(row["fingerprint"])
+ suppressed.append(row)
+ return findings, suppressed
# ---------------------------------------------------------------------------
@@ -320,6 +706,8 @@ class GateResult:
baselined: list[dict] = field(default_factory=list)
below_threshold: int = 0
fail_on: str = "high"
+ #: Silenced inline; never failing, at any severity.
+ suppressed: list[dict] = field(default_factory=list)
def to_dict(self) -> dict:
"""A stable JSON shape: the verdict, its counts, the failing findings."""
@@ -329,7 +717,9 @@ class GateResult:
"failing_count": len(self.failing),
"baselined_count": len(self.baselined),
"below_threshold_count": self.below_threshold,
+ "suppressed_count": len(self.suppressed),
"failing": [dict(f) for f in self.failing],
+ "suppressed": [{k: f[k] for k in _SUPPRESSED_FIELDS} for f in self.suppressed],
}
@@ -338,8 +728,9 @@ def evaluate(
*,
fail_on: str = "high",
baseline: frozenset[str] | None = None,
+ suppressed: Iterable[Mapping[str, Any]] = (),
) -> GateResult:
- """Split *findings* into failing, baselined and below-threshold."""
+ """Split *findings* into failing, baselined and below-threshold; *suppressed* rides along."""
accepted = baseline or frozenset()
floor = _RANK[fail_on]
failing: list[dict] = []
@@ -356,6 +747,7 @@ def evaluate(
baselined=baselined,
below_threshold=below,
fail_on=fail_on,
+ suppressed=[dict(f) for f in suppressed],
)
@@ -413,7 +805,8 @@ def _order(findings: Iterable[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
)
-def _where(finding: Mapping[str, Any]) -> str:
+def location(finding: Mapping[str, Any]) -> str:
+ """``path:line``, or ``path (commit abc1234)`` for a secret found in an earlier commit."""
if finding["commit"]:
return f"{finding['file_path']} (commit {finding['commit'][:7]})"
return f"{finding['file_path']}:{int(finding['line_number'])}"
@@ -435,6 +828,7 @@ def render_markdown(
label: str,
files_scanned: int,
commits_scanned: int,
+ long_lines_skipped: int = 0,
) -> str:
"""Step-summary / PR-comment markdown: verdict first, then a capped table."""
if gate.passed:
@@ -452,6 +846,13 @@ def render_markdown(
notes.append(f"{len(gate.baselined)} accepted by the baseline")
if gate.below_threshold:
notes.append(f"{gate.below_threshold} below the threshold")
+ if gate.suppressed:
+ notes.append(f"{plural(len(gate.suppressed), 'finding')} suppressed inline")
+ if long_lines_skipped:
+ notes.append(
+ f"{plural(long_lines_skipped, 'line')} over {MAX_CUSTOM_LINE_LENGTH} "
+ "characters not matched against custom patterns"
+ )
lines += ["", "; ".join(notes) + "."]
if gate.failing:
@@ -463,7 +864,7 @@ def render_markdown(
ordered = _order(gate.failing)
for f in ordered[:ROW_LIMIT]:
lines.append(
- f"| {cell(_where(f))} | {cell(f['kind'])} | {cell(f['severity'])} "
+ f"| {cell(location(f))} | {cell(f['kind'])} | {cell(f['severity'])} "
f"| {cell(f['snippet'])} |"
)
if len(ordered) > ROW_LIMIT:
@@ -475,6 +876,12 @@ def render_markdown(
"longer on a changed line at its head. Deleting it does not remove it "
"from the history: rotate it.",
]
+ if gate.suppressed:
+ items = [
+ f"{cell(location(f))} {cell(f['kind'])} ({cell(f['severity'])})"
+ for f in _order(gate.suppressed)
+ ]
+ lines += ["", *details("Suppressed inline (repowise-security-ignore)", items)]
lines += ["", f"_{DETECTION_BASIS}_"]
return "\n".join(lines) + "\n"
@@ -508,52 +915,92 @@ def github_annotations(findings: Sequence[Mapping[str, Any]], gate: GateResult)
return github.cap_annotations(errors + warnings, noun="security findings")
-def _sarif_rules() -> list[dict]:
+def _rule_id(kind: str) -> str:
+ """The SARIF rule id / Code Quality check name: ``custom:<name>`` reads ``custom/<name>``."""
+ return kind.replace(":", "/", 1)
+
+
+def _sarif_rules(patterns: Sequence[CustomPattern] = ()) -> list[dict]:
+ texts = {
+ **_RULE_TEXT,
+ **{
+ p.kind: f"A match for the custom pattern {p.name} (security.patterns)."
+ for p in patterns
+ },
+ }
return [
sarif.rule(
- kind,
- "".join(part.capitalize() for part in kind.split("_")),
+ _rule_id(kind),
+ "".join(part.capitalize() for part in re.split(r"[_:-]", kind)),
text,
f"{text} {DETECTION_BASIS}",
DETECTION_BASIS,
)
- for kind, text in _RULE_TEXT.items()
+ for kind, text in texts.items()
]
+@dataclass(frozen=True)
+class SarifExtras:
+ """What a SARIF log carries beyond the findings themselves."""
+
+ #: ``GateResult.suppressed``: listed with an ``inSource`` suppression.
+ suppressed: Sequence[Mapping[str, Any]] = ()
+ #: One rule each, ``custom/<name>``.
+ patterns: Sequence[CustomPattern] = ()
+ #: A run property, when not zero.
+ long_lines_skipped: int = 0
+
+
+_NO_EXTRAS = SarifExtras()
+
+
def render_sarif(
findings: Sequence[Mapping[str, Any]],
*,
tool_version: str,
fail_on: str = "high",
accepted: frozenset[str] = frozenset(),
+ extras: SarifExtras = _NO_EXTRAS,
) -> 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.
+ suppressed. Findings silenced inline follow them (:class:`SarifExtras`). 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)
+ results = [
+ _sarif_result(f, fail_on, suppression="external" if f["fingerprint"] in accepted else None)
+ for f in _order(findings)
+ ]
+ results += [
+ _sarif_result(f, fail_on, suppression="inSource") for f in _order(extras.suppressed)
+ ]
+ skipped = extras.long_lines_skipped
+ properties = {"longLinesSkipped": skipped} if skipped else None
+ return sarif.run(
+ SARIF_TOOL_NAME, tool_version, _sarif_rules(extras.patterns), results, properties=properties
+ )
+
+
+def _sarif_result(f: Mapping[str, Any], fail_on: str, *, suppression: str | None) -> dict:
+ properties: dict[str, Any] = {"severity": f["severity"], "snippet": f["snippet"]}
+ if f["commit"]:
+ properties["commit"] = f["commit"]
+ return sarif.result(
+ _rule_id(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=suppression is not None,
+ suppression_kind=suppression or "external",
+ )
def _gitlab_severity(severity: str, fail_on: str) -> str:
@@ -580,7 +1027,7 @@ def render_gitlab(
SARIF_TOOL_NAME,
(
gitlab.issue(
- str(f["kind"]),
+ _rule_id(str(f["kind"])),
_gitlab_severity(f["severity"], fail_on),
_message(f),
str(f["file_path"]),
diff --git a/packages/core/src/repowise/core/analysis/security_scan.py b/packages/core/src/repowise/core/analysis/security_scan.py
index a55c404c6..53d06f243 100644
--- a/packages/core/src/repowise/core/analysis/security_scan.py
+++ b/packages/core/src/repowise/core/analysis/security_scan.py
@@ -468,11 +468,14 @@ def _secret_spans(line: str) -> list[tuple[int, int]]:
return spans
-def _mask_line(line: str) -> str:
- if not _SECRET_PREFILTER.search(line):
+def _mask_line(line: str, extra: Iterable[tuple[int, int]] = ()) -> str:
+ spans = list(extra)
+ if _SECRET_PREFILTER.search(line):
+ spans += _secret_spans(line)
+ if not spans:
return line
merged: list[tuple[int, int]] = []
- for start, end in sorted(_secret_spans(line)):
+ for start, end in sorted(spans):
if merged and start < merged[-1][1]:
merged[-1] = (merged[-1][0], max(end, merged[-1][1]))
else:
@@ -487,12 +490,23 @@ def _mask_line(line: str) -> str:
return "".join(out)
-def _snippet(line: str) -> str:
+def masked_snippet(line: str, spans: Iterable[tuple[int, int]] = ()) -> str:
+ """:func:`_snippet` with the ``(start, end)`` *spans* of *line* masked as secrets too.
+
+ For secret shapes defined outside the registry. A line that reads as PEM
+ key body is masked whole, as the scan does for body lines.
+ """
+ if _PEM_BODY_LINE.search(line):
+ return _redaction(line.strip())
+ return _snippet(line, spans)
+
+
+def _snippet(line: str, extra: Iterable[tuple[int, int]] = ()) -> str:
"""*line* as stored: every secret on it masked, then stripped and trimmed.
Masking comes first because a value cut by the trim no longer matches.
"""
- text = _mask_line(line).strip()
+ text = _mask_line(line, extra).strip()
cut = _SNIPPET_MAX
if len(text) > cut:
# Never end inside a marker: a bare ``*`` run defeats line verification.
diff --git a/packages/core/src/repowise/core/ci/sarif.py b/packages/core/src/repowise/core/ci/sarif.py
index d33991b18..d55b35249 100644
--- a/packages/core/src/repowise/core/ci/sarif.py
+++ b/packages/core/src/repowise/core/ci/sarif.py
@@ -34,14 +34,16 @@ def result(
properties: Mapping[str, Any] | None = None,
*,
suppressed: bool = False,
+ suppression_kind: str = "external",
fixes: Sequence[Mapping[str, Any]] | None = None,
) -> dict:
"""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.
- *fixes* are :func:`fix` objects proposing an edit.
+ line belongs to another revision. *suppressed* marks one accepted, so code
+ scanning shows it closed rather than open: ``external`` for a baseline,
+ ``inSource`` for a marker in the code itself. *fixes* are :func:`fix`
+ objects proposing an edit.
"""
location: dict[str, Any] = {"artifactLocation": _artifact(path)}
if line is not None:
@@ -54,7 +56,7 @@ def result(
"partialFingerprints": {fingerprint_key: fingerprint},
}
if suppressed:
- out["suppressions"] = [{"kind": "external"}]
+ out["suppressions"] = [{"kind": suppression_kind}]
if fixes:
out["fixes"] = [dict(f) for f in fixes]
if properties:
@@ -102,8 +104,13 @@ def run(
version: str,
rules: Sequence[Mapping[str, Any]],
results: Sequence[Mapping[str, Any]],
+ *,
+ properties: Mapping[str, Any] | None = None,
) -> dict:
- """A complete log with one run; ``ruleIndex`` is filled for known rule ids."""
+ """A complete log with one run; ``ruleIndex`` is filled for known rule ids.
+
+ *properties* become the run's property bag (counts a result cannot carry).
+ """
index = {r["id"]: i for i, r in enumerate(rules)}
indexed = []
for res in results:
@@ -111,21 +118,18 @@ def run(
if res["ruleId"] in index:
res["ruleIndex"] = index[res["ruleId"]]
indexed.append(res)
- return {
- "$schema": SCHEMA,
- "version": "2.1.0",
- "runs": [
- {
- "tool": {
- "driver": {
- "name": tool_name,
- "version": version,
- "informationUri": INFORMATION_URI,
- "rules": [dict(r) for r in rules],
- }
- },
- "columnKind": "utf16CodeUnits",
- "results": indexed,
+ one_run: dict[str, Any] = {
+ "tool": {
+ "driver": {
+ "name": tool_name,
+ "version": version,
+ "informationUri": INFORMATION_URI,
+ "rules": [dict(r) for r in rules],
}
- ],
+ },
+ "columnKind": "utf16CodeUnits",
+ "results": indexed,
}
+ if properties:
+ one_run["properties"] = dict(properties)
+ return {"$schema": SCHEMA, "version": "2.1.0", "runs": [one_run]}
diff --git a/tests/unit/analysis/test_security_gate_extras.py b/tests/unit/analysis/test_security_gate_extras.py
new file mode 100644
index 000000000..28ca79270
--- /dev/null
+++ b/tests/unit/analysis/test_security_gate_extras.py
@@ -0,0 +1,405 @@
+"""``security_gate``: the inline ignore marker, custom patterns and the staged scan.
+
+Scans run against real temp git repositories, as in ``test_security_gate``,
+because scoping to changed lines and commits is part of what is under test.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+
+import pytest
+
+from repowise.core.analysis.changed_lines import changed_lines
+from repowise.core.analysis.security_gate import (
+ MAX_CUSTOM_LINE_LENGTH,
+ CustomPattern,
+ SarifExtras,
+ custom_patterns,
+ evaluate,
+ fingerprint_of,
+ render_gitlab,
+ render_markdown,
+ render_sarif,
+ scan_change,
+)
+
+KEY = "AKIA" + "QZXNRTVYWMPKLBHG"
+TOKEN = "itk_" + "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6"
+OTHER_TOKEN = "itk_" + "Z9y8X7w6V5u4T3s2R1q0P9o8N7m6L5k4"
+
+
+def _git(cwd, *args: str, stdin: str | None = None) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True, input=stdin
+ ).stdout
+
+
+def _write(repo, name: str, text: str) -> None:
+ (repo / name).write_text(text, encoding="utf-8", newline="\n")
+
+
+def _commit(repo, message: str) -> None:
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", message)
+
+
+def init_repo(path):
+ """A repository with one commit on ``main`` and a ``feature`` branch checked out."""
+ _git(path, "init", "-q", "-b", "main")
+ for key, value in (("user.email", "[email protected]"), ("user.name", "t"), ("core.autocrlf", "false")):
+ _git(path, "config", key, value)
+ _write(path, "app.py", "x = 1\n")
+ _commit(path, "base")
+ _git(path, "switch", "-qc", "feature")
+ return path
+
+
+def repo(tmp_path):
+ return init_repo(tmp_path)
+
+
+def _patterns(*entries: dict) -> tuple[CustomPattern, ...]:
+ patterns, errors = custom_patterns({"security": {"patterns": list(entries)}})
+ assert errors == ()
+ return patterns
+
+
+def _pattern(regex: str = r"itk_[A-Za-z0-9]{32}", severity: str = "high") -> CustomPattern:
+ (pattern,) = _patterns({"name": "internal_token", "regex": regex, "severity": severity})
+ return pattern
+
+
+def _scan(repo, revspec: str = "main...HEAD", patterns=()):
+ changed, label = changed_lines(str(repo), revspec)
+ return scan_change(str(repo), changed, label, patterns=patterns)
+
+
+def _staged_scan(repo, patterns=()):
+ changed, label = changed_lines(str(repo), staged=True)
+ return scan_change(str(repo), changed, label, patterns=patterns, staged=True)
+
+
+# ---------------------------------------------------------------------------
+# Inline marker
+# ---------------------------------------------------------------------------
+
+
+def test_a_bare_marker_silences_every_kind_on_its_line(repo):
+ _write(repo, "cfg.py", f"AWS = '{KEY}' # repowise-security-ignore\nimport os\nos.system(c)\n")
+ _commit(repo, "add")
+ scan = _scan(repo)
+ assert [f["kind"] for f in scan.findings] == ["os_system"]
+ (suppressed,) = scan.suppressed
+ assert (suppressed["kind"], suppressed["line_number"]) == ("aws_access_key", 1)
+
+
+def test_a_kind_scoped_marker_silences_only_the_kinds_it_names(repo):
+ _write(
+ repo,
+ "cfg.py",
+ f"AWS = '{KEY}'; eval(x) # repowise-security-ignore: aws_access_key, custom:other\n",
+ )
+ _commit(repo, "add")
+ scan = _scan(repo)
+ assert [f["kind"] for f in scan.findings] == ["eval_call"]
+ assert [f["kind"] for f in scan.suppressed] == ["aws_access_key"]
+
+
+ "text",
+ [
+ f"AWS = '{KEY}' # repowise-security-ignore-file\n",
+ f"AWS = '{KEY}' # repowise-security-ignore-next-line\n",
+ f"AWS = '{KEY}' # Repowise-Security-Ignore\n",
+ f"AWS = '{KEY}' # repowise-security-ignore: see ticket 12\n",
+ f"AWS = '{KEY}' # repowise-security-ignore:\n",
+ f"AWS = '{KEY}' # repowise-security-ignore: #12\n",
+ f"# repowise-security-ignore\nAWS = '{KEY}'\n", # the marker on another line
+ ],
+)
+def test_near_misses_free_text_kinds_and_other_lines_silence_nothing(repo, text):
+ _write(repo, "cfg.py", text)
+ _commit(repo, "add")
+ scan = _scan(repo)
+ assert [f["kind"] for f in scan.findings] == ["aws_access_key"]
+ assert scan.suppressed == []
+
+
+def test_the_marker_must_be_in_the_commit_that_added_the_line(repo):
+ _write(repo, "cfg.py", f"AWS = '{KEY}'\n")
+ _commit(repo, "leak")
+ _write(repo, "cfg.py", f"AWS = '{KEY}' # repowise-security-ignore\n")
+ _commit(repo, "silence")
+ scan = _scan(repo)
+ (finding,) = scan.findings
+ assert finding["commit"] and finding["kind"] == "aws_access_key"
+ assert [f["commit"] for f in scan.suppressed] == [None]
+
+ _git(repo, "reset", "-q", "--soft", "main")
+ _commit(repo, "squashed")
+ squashed = _scan(repo)
+ assert squashed.findings == [] and len(squashed.suppressed) == 1
+
+
+def test_a_fingerprint_is_never_both_failing_and_suppressed(repo):
+ # The marker sits past the 120-character snippet, so both commits share a fingerprint.
+ line = "password = 'hunter2hunter2' # " + "x" * 130
+ _write(repo, "cfg.py", line + "\n")
+ _commit(repo, "leak")
+ _write(repo, "cfg.py", line + " repowise-security-ignore\n")
+ _commit(repo, "silence")
+ scan = _scan(repo)
+ (finding,) = scan.findings
+ assert finding["commit"] and scan.suppressed == []
+
+
+def test_suppressed_findings_never_fail_and_are_counted_in_json(repo):
+ _write(repo, "cfg.py", f"AWS = '{KEY}' # repowise-security-ignore\n")
+ _commit(repo, "add")
+ scan = _scan(repo)
+ gate = evaluate(scan.findings, fail_on="low", suppressed=scan.suppressed)
+ assert gate.passed
+ doc = gate.to_dict()
+ assert doc["suppressed_count"] == 1
+ (row,) = doc["suppressed"]
+ assert set(row) == {"file_path", "line_number", "kind", "severity", "fingerprint", "commit"}
+ assert KEY not in json.dumps(doc)
+
+
+def test_sarif_carries_suppressed_findings_in_source(repo):
+ _write(repo, "cfg.py", f"AWS = '{KEY}' # repowise-security-ignore\n")
+ _commit(repo, "add")
+ scan = _scan(repo)
+ gate = evaluate(scan.findings, suppressed=scan.suppressed)
+ log = render_sarif(
+ scan.findings, tool_version="0", extras=SarifExtras(suppressed=gate.suppressed)
+ )
+ (result,) = log["runs"][0]["results"]
+ assert result["ruleId"] == "aws_access_key"
+ assert result["suppressions"] == [{"kind": "inSource"}]
+
+
+def test_markdown_lists_suppressed_findings_after_the_table(repo):
+ _write(repo, "cfg.py", f"AWS = '{KEY}' # repowise-security-ignore\neval(x)\n")
+ _commit(repo, "add")
+ scan = _scan(repo)
+ gate = evaluate(scan.findings, suppressed=scan.suppressed)
+ text = render_markdown(gate, label="main...HEAD", files_scanned=1, commits_scanned=1)
+ assert "1 finding suppressed inline" in text
+ assert text.index("| Where |") < text.index("<details>") < text.index("a floor, not")
+ assert "cfg.py:1" in text
+
+
+# ---------------------------------------------------------------------------
+# Custom patterns: config
+# ---------------------------------------------------------------------------
+
+
+def _errors(patterns) -> tuple[str, ...]:
+ return custom_patterns({"security": {"patterns": patterns}})[1]
+
+
+ ("entry", "needle"),
+ [
+ ({"name": "a", "regex": "x", "extra": 1}, "unknown key extra"),
+ ({"regex": "x"}, "name must be"),
+ ({"name": "Bad Name", "regex": "x"}, "name must be"),
+ ({"name": "a" * 41, "regex": "x"}, "name must be"),
+ ({"name": "a"}, "regex must be a non-empty string"),
+ ({"name": "a", "regex": "("}, "does not compile"),
+ ({"name": "a", "regex": "x*"}, "zero characters"),
+ ({"name": "a", "regex": r"\b"}, "zero characters"),
+ ({"name": "a", "regex": "(?=a)"}, "zero characters"),
+ ({"name": "a", "regex": "(?=z)"}, "zero characters"),
+ ({"name": "a", "regex": "(a+)+b"}, "exponential"),
+ ({"name": "a", "regex": r"k=(\w*)*;"}, "exponential"),
+ ({"name": "a", "regex": "(a|aa)+b"}, "exponential"),
+ ({"name": "a", "regex": "x" * 501}, "longer than 500"),
+ ({"name": "a", "regex": "x", "severity": "critical"}, "severity must be one of"),
+ ("not a mapping", "must be a mapping"),
+ ],
+)
+def test_every_invalid_entry_is_an_error(entry, needle):
+ (error,) = _errors([entry])
+ assert error.startswith("security.patterns[0]") and needle in error
+
+
+ "regex", [r"itk_[A-Za-z0-9]{32}", r"(itk|xtk)_[a-z]+", r"[(+*]+x", r"\(a+\)+", r"(?:ab)+c"]
+)
+def test_ordinary_patterns_pass_the_backtracking_check(regex):
+ assert _errors([{"name": "a", "regex": regex}]) == ()
+
+
+def test_every_problem_is_listed_not_just_the_first():
+ errors = _errors([{"name": "a", "regex": "("}, {"name": "b", "regex": "x", "severity": "x"}])
+ assert len(errors) == 2
+
+
+def test_a_duplicate_name_is_an_error():
+ (error,) = _errors([{"name": "a", "regex": "x"}, {"name": "a", "regex": "y"}])
+ assert error.startswith("security.patterns[1]") and "duplicate" in error
+
+
+def test_the_block_shape_and_the_pattern_cap_are_checked():
+ assert custom_patterns({}) == ((), ())
+ assert custom_patterns({"security": "x"})[1] == ("security must be a mapping.",)
+ assert "unknown key rules" in custom_patterns({"security": {"rules": []}})[1][0]
+ assert "must be a list" in _errors({"name": "a"})[0]
+ many = [{"name": f"p{i}", "regex": "x"} for i in range(51)]
+ assert any("the limit is 50" in e for e in _errors(many))
+
+
+def test_severity_defaults_to_high():
+ (pattern,) = _patterns({"name": "a", "regex": "x"})
+ assert pattern.severity == "high" and pattern.kind == "custom:a"
+
+
+# ---------------------------------------------------------------------------
+# Custom patterns: scanning
+# ---------------------------------------------------------------------------
+
+
+def test_a_custom_pattern_finds_and_masks_on_a_changed_line_only(repo):
+ _write(repo, "old.py", f"T = '{TOKEN}'\n")
+ _commit(repo, "before the change")
+ _git(repo, "branch", "-f", "main", "HEAD")
+ _write(repo, "old.py", f"T = '{TOKEN}'\nU = '{OTHER_TOKEN}'\n")
+ _commit(repo, "add one")
+ scan = _scan(repo, patterns=(_pattern(),))
+ (finding,) = scan.findings
+ assert (finding["kind"], finding["line_number"], finding["severity"]) == (
+ "custom:internal_token",
+ 2,
+ "high",
+ )
+ assert finding["snippet"] == "U = 'itk_****'"
+ assert OTHER_TOKEN not in json.dumps(scan.findings)
+
+
+def test_the_whole_match_is_masked_even_with_a_capture_group(repo):
+ _write(repo, "cfg.txt", f"id {TOKEN} end\n")
+ _commit(repo, "add")
+ scan = _scan(repo, patterns=(_pattern(r"(itk|xtk)_[A-Za-z0-9]{32}"),))
+ (finding,) = scan.findings
+ assert finding["snippet"] == "id itk_**** end"
+
+
+def test_overlapping_matches_are_masked_as_one_span(repo):
+ _write(repo, "cfg.txt", "k abcdefghijklmnop z\n")
+ _commit(repo, "add")
+ patterns = _patterns({"name": "a", "regex": "abcdefgh"}, {"name": "b", "regex": "efghijklmnop"})
+ scan = _scan(repo, patterns=patterns)
+ assert {f["snippet"] for f in scan.findings} == {"k abcd**** z"}
+
+
+def test_custom_severity_is_kept_under_a_test_path(repo):
+ (repo / "tests").mkdir()
+ _write(repo, "tests/cfg.py", f"T = '{TOKEN}'\n")
+ _commit(repo, "add")
+ (finding,) = _scan(repo, patterns=(_pattern(),)).findings
+ assert finding["severity"] == "high"
+
+
+def test_a_custom_secret_is_masked_in_a_builtin_snippet_and_its_fingerprint_is_kept(repo):
+ _write(repo, "run.py", f"import os\nos.system('{TOKEN}')\n")
+ _commit(repo, "add")
+ (plain,) = _scan(repo).findings
+ scan = _scan(repo, patterns=(_pattern(),))
+ builtin = next(f for f in scan.findings if f["kind"] == "os_system")
+ assert builtin["fingerprint"] == plain["fingerprint"]
+ assert TOKEN not in json.dumps(scan.findings)
+
+
+def test_adding_a_pattern_leaves_builtin_fingerprints_unchanged(repo):
+ long_line = f"os.system('{TOKEN}') # " + "y" * MAX_CUSTOM_LINE_LENGTH
+ _write(repo, "run.py", f"import os\n{long_line}\nAWS = '{KEY}'\n")
+ _commit(repo, "add")
+ before = {(f["kind"], f["fingerprint"], f["snippet"]) for f in _scan(repo).findings}
+ after = _scan(repo, patterns=(_pattern(),)).findings
+ assert {(f["kind"], f["fingerprint"], f["snippet"]) for f in after} == before
+
+
+def test_a_custom_fingerprint_is_the_masked_line_not_the_raw_token(repo):
+ _write(repo, "a.py", f"T = '{TOKEN}'\n")
+ _commit(repo, "a")
+ (finding,) = _scan(repo, patterns=(_pattern(),)).findings
+ expected = fingerprint_of("a.py", "custom:internal_token", "T = 'itk_****'")
+ assert finding["fingerprint"] == expected
+ assert _scan(repo, patterns=(_pattern(),)).findings[0]["fingerprint"] == finding["fingerprint"]
+
+
+def test_custom_patterns_are_scanned_in_intermediate_commits(repo):
+ _write(repo, "a.py", f"T = '{TOKEN}'\n")
+ _commit(repo, "leak")
+ _write(repo, "a.py", "T = None\n")
+ _commit(repo, "remove")
+ (finding,) = _scan(repo, patterns=(_pattern(),)).findings
+ assert finding["kind"] == "custom:internal_token" and finding["commit"]
+
+
+def test_a_custom_finding_can_be_silenced_by_its_kind(repo):
+ _write(repo, "a.py", f"T = '{TOKEN}' # repowise-security-ignore: custom:internal_token\n")
+ _commit(repo, "add")
+ scan = _scan(repo, patterns=(_pattern(),))
+ assert scan.findings == [] and [f["kind"] for f in scan.suppressed] == ["custom:internal_token"]
+
+
+def test_an_over_long_line_is_skipped_for_custom_patterns_and_counted_once(repo):
+ _write(repo, "a.py", f"T = '{TOKEN}'" + " " * MAX_CUSTOM_LINE_LENGTH + "\n")
+ _commit(repo, "add")
+ scan = _scan(repo, patterns=(_pattern(),))
+ assert scan.findings == []
+ assert scan.long_lines_skipped == 1 # at the head and in its commit: one line
+ log = render_sarif(scan.findings, tool_version="0", extras=SarifExtras(long_lines_skipped=1))
+ assert log["runs"][0]["properties"] == {"longLinesSkipped": 1}
+
+
+def test_sarif_and_gitlab_name_a_custom_rule_custom_slash_name(repo):
+ _write(repo, "a.py", f"T = '{TOKEN}'\n")
+ _commit(repo, "add")
+ pattern = _pattern()
+ scan = _scan(repo, patterns=(pattern,))
+ log = render_sarif(scan.findings, tool_version="0", extras=SarifExtras(patterns=(pattern,)))
+ run = log["runs"][0]
+ (result,) = run["results"]
+ assert result["ruleId"] == "custom/internal_token"
+ assert run["tool"]["driver"]["rules"][result["ruleIndex"]]["id"] == "custom/internal_token"
+ (issue,) = render_gitlab(scan.findings)
+ assert issue["check_name"] == "repowise-security/custom/internal_token"
+
+
+# ---------------------------------------------------------------------------
+# Staged
+# ---------------------------------------------------------------------------
+
+
+def test_a_staged_scan_reads_the_index_and_skips_unstaged_edits(repo):
+ _write(repo, "staged.py", f"AWS = '{KEY}'\n")
+ _git(repo, "add", "staged.py")
+ _write(repo, "loose.py", f"AWS = '{KEY}'\n") # untracked, never staged
+ _write(repo, "app.py", "import os\nos.system(c)\n") # tracked, edited, unstaged
+ scan = _staged_scan(repo)
+ assert [(f["file_path"], f["kind"]) for f in scan.findings] == [("staged.py", "aws_access_key")]
+ assert scan.commits_scanned == 0
+
+
[email protected](sys.platform == "win32", reason="git for Windows refuses a ':' in a path")
+def test_a_staged_path_that_looks_like_a_stage_number_is_read(repo):
+ sha = _git(repo, "hash-object", "-w", "--stdin", stdin=f"AWS = '{KEY}'\n").strip()
+ _git(repo, "update-index", "--add", "--cacheinfo", f"100644,{sha},1:notes.txt")
+ (finding,) = _staged_scan(repo).findings
+ assert finding["file_path"] == "1:notes.txt"
+
+
+def test_an_external_diff_or_forced_colour_cannot_hide_a_staged_secret(repo):
+ _git(repo, "config", "diff.external", "true")
+ _git(repo, "config", "color.diff", "always")
+ _write(repo, "staged.py", f"AWS = '{KEY}'\n")
+ _git(repo, "add", "staged.py")
+ assert [f["kind"] for f in _staged_scan(repo).findings] == ["aws_access_key"]
diff --git a/tests/unit/cli/test_hooks_security.py b/tests/unit/cli/test_hooks_security.py
new file mode 100644
index 000000000..4474b806c
--- /dev/null
+++ b/tests/unit/cli/test_hooks_security.py
@@ -0,0 +1,155 @@
+"""``repowise hook install --security``: the opt-in pre-commit security block.
+
+It shares the post-commit hook's marker-block contract: it coexists with a
+user's own pre-commit script, uninstall removes only its block, and status
+reports it. Plain ``hook install`` must not add it.
+"""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli import hooks
+from repowise.cli.commands.hook_cmd import hook_group
+
+
+def repo(tmp_path: Path) -> Path:
+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)
+ return tmp_path
+
+
+def _pre_commit(repo: Path) -> Path:
+ return repo / ".git" / "hooks" / "pre-commit"
+
+
+def test_install_writes_a_new_hook_and_status_reports_it(repo: Path) -> None:
+ assert hooks.security_status(repo) == "not installed"
+ assert hooks.install_security(repo) == "installed"
+ assert b"\r" not in _pre_commit(repo).read_bytes() # sh cannot run a CRLF script
+ text = _pre_commit(repo).read_text(encoding="utf-8")
+ assert text.startswith("#!/bin/sh\n# repowise-security-hook-start")
+ assert "security check --staged" in text
+ assert hooks.security_status(repo) == "installed"
+ assert hooks.install_security(repo) == "already installed"
+
+
+def test_install_keeps_a_user_script_and_goes_before_it(repo: Path) -> None:
+ user = "#!/bin/bash\nnpm run lint\nexit 0\n"
+ _pre_commit(repo).parent.mkdir(parents=True, exist_ok=True)
+ _pre_commit(repo).write_text(user, encoding="utf-8")
+ assert hooks.install_security(repo) == "installed"
+ text = _pre_commit(repo).read_text(encoding="utf-8")
+ assert text.startswith("#!/bin/bash\n# repowise-security-hook-start")
+ assert text.index("repowise-security-hook-end") < text.index("npm run lint")
+
+ assert hooks.uninstall_security(repo) == "removed (other hook content preserved)"
+ assert _pre_commit(repo).read_text(encoding="utf-8") == user
+ assert hooks.security_status(repo) == "not installed"
+
+
+def test_uninstall_deletes_a_hook_that_held_only_the_block(repo: Path) -> None:
+ hooks.install_security(repo)
+ assert hooks.uninstall_security(repo) == "removed"
+ assert not _pre_commit(repo).exists()
+ assert hooks.uninstall_security(repo) == "no pre-commit hook found"
+
+
+def test_an_older_block_is_upgraded_in_place(repo: Path) -> None:
+ hooks.install_security(repo)
+ hook = _pre_commit(repo)
+ stale = hook.read_text(encoding="utf-8").replace("Blocks a commit", "Old wording")
+ hook.write_text(stale + "echo after\n", encoding="utf-8")
+ assert hooks.install_security(repo) == "upgraded"
+ text = hook.read_text(encoding="utf-8")
+ assert "Old wording" not in text and text.count("repowise-security-hook-start") == 1
+ assert text.endswith("echo after\n")
+
+
+def test_a_non_shell_hook_is_left_alone(repo: Path) -> None:
+ _pre_commit(repo).parent.mkdir(parents=True, exist_ok=True)
+ _pre_commit(repo).write_text("#!/usr/bin/env node\nconsole.log(1)\n", encoding="utf-8")
+ assert hooks.install_security(repo).startswith("not installed")
+
+
+def test_the_cli_installs_it_only_when_asked_and_uninstall_removes_both(repo: Path) -> None:
+ runner = CliRunner()
+ (repo / ".repowise").mkdir() # hook subcommands act on indexed repositories only
+ assert runner.invoke(hook_group, ["install", str(repo), "--no-workspace"]).exit_code == 0
+ assert not _pre_commit(repo).exists()
+
+ result = runner.invoke(hook_group, ["install", str(repo), "--no-workspace", "--security"])
+ assert result.exit_code == 0 and "Pre-commit (security): installed" in result.output
+ assert hooks.security_status(repo) == "installed"
+ status = runner.invoke(hook_group, ["status", str(repo), "--no-workspace"])
+ assert "pre-commit (security): installed" in status.output
+
+ result = runner.invoke(hook_group, ["uninstall", str(repo), "--no-workspace"])
+ assert result.exit_code == 0 and "Pre-commit (security): removed" in result.output
+ assert hooks.status(repo) == "not installed" and hooks.security_status(repo) == "not installed"
+ status = runner.invoke(hook_group, ["status", str(repo), "--no-workspace"])
+ assert "pre-commit (security)" not in status.output
+
+
+def _sh() -> str | None:
+ found = shutil.which("sh")
+ return found if found and "system32" not in found.lower() else None
+
+
[email protected](_sh() is None, reason="needs a POSIX sh")
[email protected](("code", "blocked"), [(0, False), (1, True), (2, False)])
+def test_the_block_stops_the_commit_on_exit_one_only(
+ tmp_path: Path, code: int, blocked: bool
+) -> None:
+ fake = tmp_path / "bin"
+ fake.mkdir()
+ (fake / "repowise").write_text(f"#!/bin/sh\nexit {code}\n", encoding="utf-8", newline="\n")
+ (fake / "repowise").chmod(0o755)
+ script = tmp_path / "hook.sh"
+ script.write_text(
+ "#!/bin/sh -e\n" + hooks._SECURITY_HOOK_SCRIPT + "echo reached\n",
+ encoding="utf-8",
+ newline="\n",
+ )
+ env = {"PATH": f"{fake.as_posix()}:/usr/bin:/bin"}
+ proc = subprocess.run(
+ [_sh(), "-e", str(script)], cwd=tmp_path, env=env, capture_output=True, text=True
+ )
+ assert (proc.returncode != 0) is blocked
+ assert ("reached" in proc.stdout) is not blocked
+
+
[email protected](_sh() is None, reason="needs a POSIX sh")
+def test_the_block_lets_the_commit_through_without_a_repowise_binary(tmp_path: Path) -> None:
+ script = tmp_path / "hook.sh"
+ script.write_text(
+ "#!/bin/sh -e\n" + hooks._SECURITY_HOOK_SCRIPT + "echo reached\n",
+ encoding="utf-8",
+ newline="\n",
+ )
+ empty = tmp_path / "empty"
+ empty.mkdir()
+ proc = subprocess.run(
+ [_sh(), "-e", str(script)],
+ cwd=tmp_path,
+ env={"PATH": empty.as_posix()},
+ capture_output=True,
+ text=True,
+ )
+ assert proc.returncode == 0 and "reached" in proc.stdout
+ assert "repowise not found; security check skipped" in proc.stderr
+
+
+def test_a_block_that_cannot_be_replaced_is_not_reported_as_upgraded(repo: Path) -> None:
+ hook = _pre_commit(repo)
+ hook.parent.mkdir(parents=True, exist_ok=True)
+ # A start marker with no end marker: nothing can be replaced.
+ broken = "#!/bin/sh\n# repowise-security-hook-start\necho mine\n"
+ hook.write_text(broken, encoding="utf-8")
+ assert hooks.install_security(repo) == "already installed"
+ assert hook.read_text(encoding="utf-8") == broken
diff --git a/tests/unit/cli/test_security_check_cmd.py b/tests/unit/cli/test_security_check_cmd.py
index 76e56ee0c..85442205c 100644
--- a/tests/unit/cli/test_security_check_cmd.py
+++ b/tests/unit/cli/test_security_check_cmd.py
@@ -3,35 +3,24 @@
from __future__ import annotations
import json
-import subprocess
import pytest
from click.testing import CliRunner
from repowise.cli.commands.security_cmd import security_command
+from tests.unit.analysis.test_security_gate_extras import KEY, _git, _write, init_repo
+from tests.unit.analysis.test_security_gate_extras import _commit as _commit_all
from tests.unit.cli.test_format_json_rollout import _split_runner
-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)
+ _write(repo, name, text)
+ _commit_all(repo, name)
@pytest.fixture
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
+ return init_repo(tmp_path)
def _check(repo, *args: str, env=None):
@@ -175,3 +164,112 @@ def test_gitlab_prints_an_empty_list_when_it_cannot_evaluate(tmp_path):
)
assert result.exit_code == 2
assert json.loads(result.stdout) == []
+
+
+def _staged(repo, *args: str):
+ return _split_runner().invoke(
+ security_command, ["check", "--staged", "--path", str(repo), *args]
+ )
+
+
+def _stage(repo, name: str, text: str) -> None:
+ (repo / name).write_text(text, encoding="utf-8", newline="\n")
+ _git(repo, "add", name)
+
+
+def test_staged_fails_on_a_staged_secret_and_ignores_unstaged_ones(repo):
+ _stage(repo, "staged.py", f"AWS = '{KEY}'\n")
+ (repo / "loose.py").write_text(f"AWS = '{KEY}'\n", encoding="utf-8", newline="\n")
+ result = _staged(repo, "--format", "json")
+ assert result.exit_code == 1, result.output
+ doc = json.loads(result.stdout)
+ assert doc["revspec"] == "staged changes" and doc["commits_scanned"] == 0
+ assert [f["file_path"] for f in doc["findings"]] == ["staged.py"]
+
+
+def test_staged_passes_once_the_line_carries_the_marker(repo):
+ _stage(repo, "staged.py", f"AWS = '{KEY}' # repowise-security-ignore\n")
+ result = _staged(repo, "--format", "json")
+ assert result.exit_code == 0, result.output
+ assert json.loads(result.stdout)["gate"]["suppressed_count"] == 1
+
+
+def test_staged_with_a_revspec_is_a_usage_error(repo):
+ result = _split_runner().invoke(
+ security_command,
+ ["check", "main...HEAD", "--staged", "--path", str(repo), "--format", "json"],
+ )
+ assert result.exit_code == 2
+ assert "drop REVSPEC" in result.stderr
+
+
+def _config(repo, text: str) -> None:
+ (repo / ".repowise").mkdir(exist_ok=True)
+ (repo / ".repowise" / "config.yaml").write_text(text, encoding="utf-8")
+
+
+def test_an_invalid_pattern_config_exits_two_listing_every_error(repo):
+ _config(
+ repo,
+ "security:\n patterns:\n - name: a\n regex: '('\n"
+ " - name: b\n regex: 'x*'\n",
+ )
+ result = _check(repo, "--format", "json")
+ assert result.exit_code == 2
+ doc = json.loads(result.stdout)
+ assert doc["error"] == "config_invalid"
+ assert "patterns[0]" in doc["message"] and "patterns[1]" in doc["message"]
+
+
+def test_a_custom_pattern_from_config_gates_the_change(repo):
+ token = "itk_" + "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6"
+ _config(
+ repo,
+ "security:\n patterns:\n - name: internal_token\n regex: 'itk_[A-Za-z0-9]{32}'\n",
+ )
+ _commit(repo, "a.py", f"T = '{token}'\n")
+ result = _check(repo, "--format", "json")
+ assert result.exit_code == 1, result.output
+ (finding,) = json.loads(result.stdout)["findings"]
+ assert finding["kind"] == "custom:internal_token" and token not in result.output
+
+
+def test_gitlab_counts_suppressed_findings_on_stderr_only(repo):
+ _commit(repo, "cfg.py", f"AWS = '{KEY}' # repowise-security-ignore\n")
+ result = _split_runner().invoke(
+ security_command, ["check", "main...HEAD", "--path", str(repo), "--format", "gitlab"]
+ )
+ assert result.exit_code == 0
+ assert json.loads(result.stdout) == []
+ assert "1 finding(s) suppressed inline" in result.stderr
+
+
+def test_the_table_lists_suppressed_findings(repo):
+ _commit(repo, "cfg.py", f"AWS = '{KEY}' # repowise-security-ignore\n")
+ result = _check(repo)
+ assert result.exit_code == 0
+ assert "1 finding(s) suppressed inline" in result.output and "cfg.py:1" in result.output
+
+
+def test_an_unexpected_crash_cannot_evaluate_rather_than_fail(repo, monkeypatch):
+ from repowise.core.analysis import security_gate
+
+ def boom(*_args, **_kwargs):
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(security_gate, "scan_change", boom)
+ _stage(repo, "a.py", "x = 3\n")
+ for fmt in ("json", "table", "gitlab"):
+ result = _staged(repo, "--format", fmt)
+ assert result.exit_code == 2, (fmt, result.output)
+ assert json.loads(_staged(repo, "--format", "json").stdout)["error"] == "internal_error"
+
+
+def test_suppressed_findings_stay_out_of_a_written_baseline(repo, tmp_path):
+ _commit(repo, "cfg.py", f"AWS = '{KEY}' # repowise-security-ignore\nimport os\nos.system(c)\n")
+ baseline = tmp_path / "b.json"
+ result = _check(repo, "--write-baseline", str(baseline), "--format", "json")
+ assert result.exit_code == 0, result.output
+ assert json.loads(result.stdout)["recorded"] == 1
+ entries = json.loads(baseline.read_text(encoding="utf-8"))["entries"]
+ assert [e["kind"] for e in entries] == ["os_system"]