Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(security): deduplicate history findings across file versions (#3631)
arnavsx3fe5aa3ad3121
diff --git a/packages/core/src/repowise/core/analysis/history_scan.py b/packages/core/src/repowise/core/analysis/history_scan.pyindex aae3d9ef8..c39dbf09c 100644--- a/packages/core/src/repowise/core/analysis/history_scan.py+++ b/packages/core/src/repowise/core/analysis/history_scan.py@@ -42,9 +42,11 @@ from typing import Anyfrom repowise.core.analysis.git_cat_file import cat_file_batchfrom repowise.core.analysis.secret_allowlist import secret_path_allowlist+from repowise.core.analysis.security_gate import _KEY_SHAPE_KINDS, fingerprint_offrom repowise.core.analysis.security_scan import (SECRET_KINDS,SecurityScanner,+ source_lines,)from repowise.core.ingestion.models import EXTENSION_TO_LANGUAGE@@ -331,9 +333,19 @@ class HistorySecurityScanner:for blob_sha, path in blobs.items()if not path or self._is_source(path)]+ commit_positions = {sha: index for index, (sha, _) in enumerate(commits)}++ def introduction_order(item: tuple[str, str]) -> int:+ commit_sha = blob_introduced_at.get(item[0], "")+ return commit_positions.get(commit_sha, len(commits))++ # Keep the earliest introduction in Git history order: author dates+ # can be backdated. Blobs with unknown provenance are processed last.+ source_items.sort(key=introduction_order)contents_map = self._read_blobs_batch(repo_path, [blob_sha for blob_sha, _ in source_items])+ seen: set[str] = set()for idx, (blob_sha, path) in enumerate(source_items, start=1):summary.files_scanned += 1@@ -362,17 +374,32 @@ class HistorySecurityScanner:if commit_sha:commit_at = _parse_author_date(commit_dates.get(commit_sha, ""))- inserted = await self._scanner.persist(- path or "<unknown>",- kept,- commit_sha=commit_sha,- commit_at=commit_at,- )- summary.findings_inserted += inserted+ lines = source_lines(content)for f in kept:+ material = ""+ if f["kind"] in _KEY_SHAPE_KINDS:+ material = "\n".join(lines[f["line"] - 1 : f.get("end_line", f["line"])])+ fingerprint = fingerprint_of(+ path or "<unknown>", f["kind"], f.get("snippet", ""), material+ )+ if fingerprint in seen:+ continue+ seen.add(fingerprint)++ # Count actual writes per finding, including on idempotent+ # re-runs where an existing provenance row inserts nothing.+ inserted = await self._scanner.persist(+ path or "<unknown>",+ [f],+ commit_sha=commit_sha,+ commit_at=commit_at,+ )+ if not inserted:+ continue+ summary.findings_inserted += insertedsev = f.get("severity", "unknown")kind = f.get("kind", "unknown")- summary.by_severity[sev] = summary.by_severity.get(sev, 0) + 1- summary.by_kind[kind] = summary.by_kind.get(kind, 0) + 1+ summary.by_severity[sev] = summary.by_severity.get(sev, 0) + inserted+ summary.by_kind[kind] = summary.by_kind.get(kind, 0) + insertedreturn summarydiff --git a/tests/unit/analysis/test_security_scan_history.py b/tests/unit/analysis/test_security_scan_history.pyindex 6930b8f9e..7deaf4d2d 100644--- a/tests/unit/analysis/test_security_scan_history.py+++ b/tests/unit/analysis/test_security_scan_history.py@@ -333,10 +333,13 @@ def test_secret_kinds_are_the_genuine_credential_patterns() -> None:# ----------------------------------------------------------------------------def _git(repo: Path, *args: str) -> None:+def _git(repo: Path, *args: str) -> str:import subprocess- subprocess.run(["git", *args], cwd=str(repo), check=True, capture_output=True)+ result = subprocess.run(+ ["git", *args], cwd=str(repo), check=True, capture_output=True, text=True+ )+ return result.stdout.strip()@pytest.fixture@@ -409,6 +412,188 @@ async def test_history_reports_a_blob_at_its_path_outside_the_allowlist(assert {r._mapping["file_path"] for r in rows} == {"src/creds.py"}+async def test_history_deduplicates_non_secrets_in_an_allowlisted_path(+ session: AsyncSession, secret_repo: Path+) -> None:+ """The path allowlist suppresses secrets while non-secret findings deduplicate."""+ (secret_repo / ".gitleaks.toml").write_text("[allowlist]\npaths = ['''^leak\\.py$''']\n")+ source = secret_repo / "leak.py"+ with source.open("a") as stream:+ stream.write('import os\nos.system("echo hello")\n')+ _git(secret_repo, "add", "leak.py")+ _git(secret_repo, "commit", "-m", "add a non-secret finding")+ first_commit = _git(secret_repo, "rev-parse", "HEAD")+ with source.open("a") as stream:+ stream.write("value = 1\n")+ _git(secret_repo, "add", "leak.py")+ _git(secret_repo, "commit", "-m", "unrelated edit")++ scanner = HistorySecurityScanner(session, "repo-1")+ summary = await scanner.scan_history(secret_repo, secrets_only=False)+ rows = (await session.execute(text("SELECT kind, commit_sha FROM security_findings"))).all()+ assert [(row.kind, row.commit_sha) for row in rows] == [("os_system", first_commit)]+ assert summary.findings_inserted == 1+ assert summary.by_kind == {"os_system": 1}++ rerun = await scanner.scan_history(secret_repo, secrets_only=False)+ assert rerun.findings_inserted == 0+ assert rerun.by_kind == {}+ assert rerun.by_severity == {}+++ ("versions", "introduction_indexes"),+ [+ (+ [+ 'password = "hunter2-not-a-real-secret"\n',+ 'password = "hunter2-not-a-real-secret"\nvalue = 1\n',+ 'password = "hunter2-not-a-real-secret"\nvalue = 2\n',+ ],+ [0],+ ),+ (+ [+ 'password = "hunter2-not-a-real-secret"\n',+ 'password = "different-not-a-real-secret"\n',+ 'password = "different-not-a-real-secret"\nvalue = 1\n',+ ],+ [0, 1],+ ),+ (+ [+ 'password = "hunter2-not-a-real-secret"\n',+ "value = 1\n",+ 'password = "hunter2-not-a-real-secret"\nvalue = 2\n',+ ],+ [0],+ ),+ ],+ ids=["unrelated-edits", "changed-password", "removed-and-readded"],+)+async def test_history_deduplicates_findings_across_file_versions(+ session: AsyncSession,+ secret_repo: Path,+ versions: list[str],+ introduction_indexes: list[int],+) -> None:+ """An unchanged finding belongs to its earliest commit, not every later blob."""+ _git(secret_repo, "commit", "--amend", "--no-edit", "--date=2026-01-01T00:00:00+00:00")+ commits = [_git(secret_repo, "rev-parse", "HEAD")]+ for index, content in enumerate(versions[1:], start=2):+ (secret_repo / "leak.py").write_text(content)+ _git(secret_repo, "add", "leak.py")+ _git(+ secret_repo,+ "commit",+ "-m",+ f"version {index}",+ f"--date=2026-01-{index:02d}T00:00:00+00:00",+ )+ commits.append(_git(secret_repo, "rev-parse", "HEAD"))++ scanner = HistorySecurityScanner(session, "repo-1")+ summary = await scanner.scan_history(secret_repo)+ rows = (await session.execute(text("SELECT commit_sha FROM security_findings"))).all()+ assert {row.commit_sha for row in rows} == {commits[i] for i in introduction_indexes}+ assert len(rows) == summary.findings_inserted == len(introduction_indexes)+ assert summary.by_kind == {"hardcoded_password": len(introduction_indexes)}+ assert summary.by_severity == {"high": len(introduction_indexes)}+ assert summary.commits_scanned == 3+ assert summary.files_scanned == summary.blobs_scanned == 4++ rerun = await scanner.scan_history(secret_repo)+ assert rerun.findings_inserted == 0+ assert rerun.by_kind == {}+ assert rerun.by_severity == {}+ rows_after_rerun = (await session.execute(text("SELECT id FROM security_findings"))).all()+ assert len(rows_after_rerun) == len(rows)+++ "later_author_date",+ ["2026-01-01T00:00:00+00:00", "2025-12-31T00:00:00+00:00"],+ ids=["equal-author-dates", "backdated-later-commit"],+)+async def test_history_uses_commit_order_regardless_of_author_dates(+ session: AsyncSession, secret_repo: Path, later_author_date: str+) -> None:+ """Equal or backdated author dates must not let a later edit win attribution."""+ date = "2026-01-01T00:00:00+00:00"+ _git(secret_repo, "commit", "--amend", "--no-edit", f"--date={date}")+ first_commit = _git(secret_repo, "rev-parse", "HEAD")+ with (secret_repo / "leak.py").open("a") as source:+ source.write("value = 1\n")+ _git(secret_repo, "add", "leak.py")+ _git(secret_repo, "commit", "-m", "unrelated edit", f"--date={later_author_date}")++ summary = await HistorySecurityScanner(session, "repo-1").scan_history(secret_repo)+ rows = (await session.execute(text("SELECT commit_sha FROM security_findings"))).all()+ assert [row.commit_sha for row in rows] == [first_commit]+ assert summary.findings_inserted == 1+++async def test_history_keeps_distinct_vendor_keys_with_the_same_masked_snippet(+ session: AsyncSession, secret_repo: Path+) -> None:+ """Vendor-key identity includes the raw material's hash, not just its mask."""+ commits = []+ for index, suffix in enumerate(["QZXNRTVYWMPKLBHG", "ZXCVBNMLKJHGFDSA"], start=1):+ (secret_repo / "client.py").write_text(f'client_id = "AKIA{suffix}"\n')+ _git(secret_repo, "add", "client.py")+ _git(+ secret_repo,+ "commit",+ "-m",+ f"key {index}",+ f"--date=2026-01-{index:02d}T00:00:00+00:00",+ )+ commits.append(_git(secret_repo, "rev-parse", "HEAD"))++ summary = await HistorySecurityScanner(session, "repo-1").scan_history(secret_repo)+ rows = (+ await session.execute(+ text("SELECT snippet, commit_sha FROM security_findings WHERE kind = 'aws_access_key'")+ )+ ).all()+ assert len(rows) == 2+ assert len({row.snippet for row in rows}) == 1+ assert {row.commit_sha for row in rows} == set(commits)+ assert summary.by_kind["aws_access_key"] == 2+++async def test_history_prefers_known_introduction_over_missing_provenance(+ session: AsyncSession, monkeypatch: pytest.MonkeyPatch+) -> None:+ scanner = HistorySecurityScanner(session, "repo-1")+ content = 'password = "hunter2-not-a-real-secret"\n'+ monkeypatch.setattr(scanner, "_list_commits", lambda *a: [("c1", "2026-01-01T00:00:00Z")])+ monkeypatch.setattr(scanner, "_unique_blobs", lambda *a: {"unknown": "a.py", "known": "a.py"})+ monkeypatch.setattr(+ scanner,+ "_blob_introductions",+ lambda *a: (+ {"known": "c1"},+ {"c1": "2026-01-01T00:00:00Z"},+ {},+ ),+ )+ monkeypatch.setattr(+ scanner,+ "_read_blobs_batch",+ lambda *a: {+ "unknown": content + "value = 1\n",+ "known": content,+ },+ )++ summary = await scanner.scan_history(Path("/unused"))+ rows = (await session.execute(text("SELECT commit_sha FROM security_findings"))).all()+ assert [row.commit_sha for row in rows] == ["c1"]+ assert summary.files_scanned == 2+ assert summary.findings_inserted == 1++async def test_history_default_skips_test_fixtures_and_placeholders(session: AsyncSession, secret_repo: Path) -> None: