Skip to content

Commit 307fbb4

Browse files
fix(update): rescan security on a scanner bump in workspace updates (#6131)
`repowise update --workspace` (the index-only path) never compared security_scanner_version: it rescanned only the changed files and never wrote the stamp. After upgrading, every unchanged file kept the findings the old scanner wrote, and state.json kept the old version, so a scanner fix never reached most of a workspace index. The workspace pass now passes rescan_security when the stamp differs. The incremental update then rescans every file from the whole-repo parse it already builds, and _write_repo_state records the new version. The full-index fallback reports a rescan as well. stamps_moved counts a scanner change as stale, so a member with no new commit is still rescanned. A failed rescan leaves the old stamp, and the next update retries. security_scanner_changed moves into core, and the CLI's full-parse rescan uses the same core writer, rescan_repo_security.
1 parent 08b4c3b commit 307fbb4

9 files changed

Lines changed: 192 additions & 47 deletions

File tree

‎packages/cli/src/repowise/cli/commands/update_cmd/persistence.py‎

Lines changed: 3 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
save_state,
2929
)
3030
from repowise.core.analysis.health import health_analyzer_changed
31+
from repowise.core.analysis.security.patterns import security_scanner_changed
3132
from repowise.core.ingestion.git_indexer import GIT_HISTORY_VERSION, GIT_HISTORY_VERSION_KEY
3233
from repowise.core.pipeline import PhaseTimings, timed
3334
from repowise.core.pipeline.incremental.repair import record_repair_marker
@@ -1229,20 +1230,6 @@ async def _stored() -> bool:
12291230
return False
12301231

12311232

1232-
def security_scanner_changed(state: dict) -> bool:
1233-
"""Whether the stored security findings were written by a different scanner.
1234-
1235-
Unlike :func:`health_analyzer_changed`, a state file with no stamp **is** a
1236-
change: the stamp arrived after 0.55.0 (#3086), so an unstamped store was
1237-
written by an older scanner. Reading absence as current would also keep it
1238-
unstamped forever, since only the rescan this gates writes the stamp.
1239-
``init`` stamps every fresh index, so a new install never reads as stale.
1240-
"""
1241-
from repowise.core.analysis.security_scan import SECURITY_SCANNER_VERSION
1242-
1243-
return state.get("security_scanner_version") != SECURITY_SCANNER_VERSION
1244-
1245-
12461233
def renderer_changed(
12471234
stored_fp: str | None, current_fp: str, docs_mode: str, *, index_only: bool
12481235
) -> bool:
@@ -1358,30 +1345,9 @@ async def _security_rescan_from_full_parse(repo_path: Any, exclude_patterns: lis
13581345
scan. ``replace_findings`` only ever deletes/replaces working-tree rows
13591346
(``commit_sha`` empty); history rows from ``scan --history`` are untouched.
13601347
"""
1361-
from repowise.cli.helpers import get_db_url_for_repo
1362-
from repowise.core.analysis.security_scan import SecurityScanner, scan_source_map
1363-
from repowise.core.persistence import (
1364-
create_engine,
1365-
create_session_factory,
1366-
get_session,
1367-
init_db,
1368-
upsert_repository,
1369-
)
1348+
from repowise.core.pipeline.persist import rescan_repo_security
13701349

13711350
parsed_files, source_map, _graph_builder, _repo_structure, _file_count = _build_repo_graph(
13721351
repo_path, exclude_patterns, collect_sources=True
13731352
)
1374-
1375-
url = get_db_url_for_repo(repo_path)
1376-
engine = create_engine(url)
1377-
try:
1378-
await init_db(engine)
1379-
sf = create_session_factory(engine)
1380-
async with get_session(sf) as session:
1381-
repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))
1382-
findings_by_file, scanned_paths = scan_source_map(parsed_files, source_map)
1383-
await SecurityScanner(session, repo.id).replace_findings(
1384-
findings_by_file, scanned_paths
1385-
)
1386-
finally:
1387-
await engine.dispose()
1353+
await rescan_repo_security(repo_path, parsed_files, source_map)

‎packages/core/src/repowise/core/analysis/security/patterns.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,19 @@
1414
SECURITY_SCANNER_VERSION = 7
1515

1616

17+
def security_scanner_changed(state: dict) -> bool:
18+
"""Whether the stored security findings were written by a different scanner.
19+
20+
*state* is the repo's ``state.json``. Unlike ``health_analyzer_changed``, a
21+
state file with no stamp **is** a change: the stamp arrived after 0.55.0
22+
(#3086), so an unstamped store was written by an older scanner. Reading
23+
absence as current would also keep it unstamped forever, since only the
24+
rescan this gates writes the stamp. ``init`` stamps every fresh index, so
25+
a new install never reads as stale.
26+
"""
27+
return state.get("security_scanner_version") != SECURITY_SCANNER_VERSION
28+
29+
1730
# ---------------------------------------------------------------------------
1831
# Pattern registry: (compiled_pattern, kind_label, severity)
1932
# ---------------------------------------------------------------------------

‎packages/core/src/repowise/core/analysis/security_scan.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@
116116
SECRET_KINDS,
117117
SECURITY_SCANNER_VERSION,
118118
SYMBOL_NAME_KINDS,
119+
security_scanner_changed,
119120
)
120121
from repowise.core.analysis.security.refinements import (
121122
_NOT_FOR_SECURITY,

‎packages/core/src/repowise/core/pipeline/persist/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@
8484
_replace_security_findings,
8585
persist_incremental_security_findings,
8686
persist_security_findings,
87+
rescan_repo_security,
8788
)
8889
from .sweeps import (
8990
_SWEPT_GENERATED_PAGE_TYPES,

‎packages/core/src/repowise/core/pipeline/persist/security.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,36 @@ async def _replace_security_findings(
5656
scan_source_map, parsed_files, source_map
5757
)
5858
await SecurityScanner(session, repo_id).replace_findings(findings_by_file, scanned_paths)
59+
60+
61+
async def rescan_repo_security(
62+
repo_path: Any, parsed_files: Any, source_map: dict[str, Any]
63+
) -> None:
64+
"""Replace every working-tree security finding from a whole-repo parse.
65+
66+
The rescan a scanner version bump owes (#3072): the incremental persist only
67+
rescans the changed files, so every other file keeps rows the old scanner
68+
wrote. *parsed_files* and *source_map* must cover the whole repo.
69+
``replace_findings`` only replaces working-tree rows; history rows from
70+
``scan --history`` are untouched.
71+
"""
72+
from repowise.core.persistence import (
73+
create_engine,
74+
create_session_factory,
75+
get_session,
76+
init_db,
77+
upsert_repository,
78+
)
79+
from repowise.core.persistence.database import resolve_db_url
80+
81+
if parsed_files and not source_map:
82+
# Scanning no text would wipe every real finding; fail so the stamp stays.
83+
raise ValueError("a full security rescan needs the parsed source text")
84+
engine = create_engine(resolve_db_url(repo_path))
85+
try:
86+
await init_db(engine)
87+
async with get_session(create_session_factory(engine)) as session:
88+
repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))
89+
await _replace_security_findings(session, repo.id, parsed_files, source_map)
90+
finally:
91+
await engine.dispose()

‎packages/core/src/repowise/core/workspace/update/repo.py‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,9 @@ class RepoUpdateResult:
144144
# reached the store, so the caller can stamp ``last_full_rescore_at`` /
145145
# ``health_analyzer_version``.
146146
health_rescored: bool = False
147+
# True when every tracked file's security findings were rescanned with this
148+
# build's scanner, so the caller can stamp ``security_scanner_version``.
149+
security_rescanned: bool = False
147150
# The graph rebuild's patch-or-rebuild decision, stamped as state.json
148151
# "graph_update"; None leaves the stored record alone.
149152
graph_update: dict[str, Any] | None = None
@@ -185,6 +188,7 @@ async def _incremental_repo_update(
185188
force_full_git: bool = False,
186189
products_sink: list[UpdateProducts] | None = None,
187190
rescore_health: bool = False,
191+
rescan_security: bool = False,
188192
) -> RepoUpdateResult | None:
189193
"""Refresh an already-indexed repo through the incremental update path.
190194
@@ -199,6 +203,8 @@ async def _incremental_repo_update(
199203
rebuilt; a run with no relevant changes rebuilds nothing and appends
200204
nothing. *rescore_health* re-scores every file's health after persisting,
201205
in place of the changed-files health pass that re-score would replace.
206+
*rescan_security* rescans every file's security findings after persisting,
207+
for a scanner version bump the changed-files scan cannot reach.
202208
203209
The result's ``phase_timings`` carries the seconds each phase took.
204210
@@ -220,10 +226,10 @@ async def _incremental_repo_update(
220226
file_diffs, working_tree_paths = await asyncio.to_thread(
221227
_changed_file_diffs, repo_path, state, base_ref, include_working_tree, merged_excludes
222228
)
223-
if not file_diffs and not force_full_git and not rescore_health:
229+
if not file_diffs and not force_full_git and not rescore_health and not rescan_security:
224230
# Nothing the index cares about changed: report success so the caller
225231
# bumps ``last_sync_commit`` instead of re-diffing forever. A re-score
226-
# still runs: it is owed for every file, changed or not.
232+
# or rescan still runs: it is owed for every file, changed or not.
227233
return RepoUpdateResult(alias=alias, updated=True, working_tree_paths=working_tree_paths)
228234

229235
# A moved or copied checkout's store still names the old path; adopt its
@@ -324,6 +330,10 @@ async def _incremental_repo_update(
324330
rescored_report = await _rescore_repo_health(
325331
repo_path, graph_builder, parsed_files, merged_excludes, timings
326332
)
333+
security_rescanned = False
334+
if rescan_security:
335+
with timed(timings, "security_rescan"):
336+
security_rescanned = await _rescan_repo_security(repo_path, parsed_files, source_map)
327337
if products_sink is not None:
328338
health_report = (
329339
rescored_report
@@ -360,6 +370,7 @@ async def _incremental_repo_update(
360370
# The re-score reads git rows from the store: scored over rows that did
361371
# not land, it is not stamped, so the next run re-scores with the walk.
362372
health_rescored=rescored_report is not None and "Git persist" not in failed_steps,
373+
security_rescanned=security_rescanned,
363374
graph_update=getattr(graph_builder, "incremental_graph_decision", None),
364375
pending_repair=marker.get("pending_repair"),
365376
)
@@ -395,6 +406,22 @@ async def _rescore_repo_health(
395406
return None
396407

397408

409+
async def _rescan_repo_security(repo_path: Path, parsed_files: Any, source_map: Any) -> bool:
410+
"""Every file's security findings rescanned, or ``False`` when the rescan failed.
411+
412+
Best-effort, as the CLI update's rescan is: a failure leaves the old stamp,
413+
so the next update retries.
414+
"""
415+
from ...pipeline.persist import rescan_repo_security
416+
417+
try:
418+
await rescan_repo_security(repo_path, parsed_files, source_map)
419+
except Exception:
420+
_log.warning("Full security rescan failed for %s", repo_path, exc_info=True)
421+
return False
422+
return True
423+
424+
398425
async def _stored_health_report(repo_path: Path) -> Any:
399426
"""The whole-repo health report read back from the store, or ``None``.
400427
@@ -586,6 +613,7 @@ async def update_single_repo_index(
586613
products_sink: list[UpdateProducts] | None = None,
587614
full_index_fallback: bool = True,
588615
rescore_health: bool = False,
616+
rescan_security: bool = False,
589617
) -> RepoUpdateResult:
590618
"""Refresh the index for a single repo.
591619
@@ -607,6 +635,8 @@ async def update_single_repo_index(
607635
changed ones, after the incremental write. The products' health report
608636
covers the whole repo either way, so a caller needs it only to refresh
609637
every file's scores, not to get a whole-repo report.
638+
- ``rescan_security=True`` rescans every file's security findings, not
639+
only the changed ones: the rescan a ``SECURITY_SCANNER_VERSION`` bump owes.
610640
"""
611641
from ...repo_config import load_repo_config
612642

@@ -651,6 +681,7 @@ async def update_single_repo_index(
651681
include_working_tree,
652682
products_sink=products_sink,
653683
rescore_health=rescore_health,
684+
rescan_security=rescan_security,
654685
)
655686
if incremental_result is not None:
656687
if unrepaired is not None and incremental_result.pending_repair is None:
@@ -759,6 +790,7 @@ async def _try_incremental_update(
759790
*,
760791
products_sink: list[UpdateProducts] | None = None,
761792
rescore_health: bool = False,
793+
rescan_security: bool = False,
762794
) -> tuple[RepoUpdateResult | None, str | None]:
763795
"""The incremental update's result, or ``None`` and the error to fall back on."""
764796
from ...ingestion.document_extractors import DocumentExtractionError
@@ -773,6 +805,7 @@ async def _try_incremental_update(
773805
force_full_git=git_history_stale(state),
774806
products_sink=products_sink,
775807
rescore_health=rescore_health,
808+
rescan_security=rescan_security,
776809
)
777810
except DocumentExtractionError:
778811
raise
@@ -830,6 +863,8 @@ async def _full_index_update(
830863
git_history_refreshed=getattr(result, "git_summary", None) is not None,
831864
# The full pipeline scores every file with this build's analyzer.
832865
health_rescored=getattr(result, "health_report", None) is not None,
866+
# The full pipeline scans every file with this build's scanner.
867+
security_rescanned=True,
833868
)
834869
except Exception as exc:
835870
return RepoUpdateResult(

‎packages/core/src/repowise/core/workspace/update/state.py‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -305,24 +305,30 @@ def check_repo_staleness(
305305

306306

307307
def stamps_moved(repo_path: Path) -> bool:
308-
"""Whether an indexed repo's health or git history stamp is behind this build.
308+
"""Whether an indexed repo's health, security or git history stamp is behind this build.
309309
310-
Work no commit explains: rows scored by an older health analyzer, or git
311-
rows written under older history rules. A repo with no recorded sync, or
310+
Work no commit explains: rows scored by an older health analyzer, findings
311+
an older security scanner wrote, or git rows written under older history
312+
rules. A repo with no recorded sync, or
312313
no local store and no configured database, has no rows for either stamp
313314
to describe. Under a configured database the repository row is not looked
314315
up: this check stays offline, and a member with a moved stamp but no rows
315316
there is reported stale on purpose, since the full index that update falls
316317
back to writes the rows it is missing.
317318
"""
318319
from ...analysis.health import health_analyzer_changed
320+
from ...analysis.security.patterns import security_scanner_changed
319321
from ...ingestion.git_indexer import git_history_stale
320322
from ...persistence.database import has_db_store
321323

322324
state = read_repo_state(repo_path)
323325
if not state.get("last_sync_commit") or not has_db_store(repo_path):
324326
return False
325-
return health_analyzer_changed(state) or git_history_stale(state)
327+
return (
328+
health_analyzer_changed(state)
329+
or security_scanner_changed(state)
330+
or git_history_stale(state)
331+
)
326332

327333

328334
def restamp_changed_sync_commit(repo_path: Path, previous: str | None, current: str | None) -> None:

‎packages/core/src/repowise/core/workspace/update/workspace_pass.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
)
3232

3333
from ...analysis.health import health_analyzer_changed
34+
from ...analysis.security.patterns import security_scanner_changed
3435
from ...docs_mode import docs_mode_state_fields
3536
from ...ingestion.change_detector import has_working_tree_changes
3637
from ...ingestion.git_indexer import (
@@ -320,14 +321,16 @@ async def _update_stale_repo(update_pass: _RepoUpdatePass, repo: _StaleRepo) ->
320321

321322
try:
322323
update_started = time.monotonic()
324+
repo_state = read_repo_state(path)
323325
result = await update_single_repo_index(
324326
path,
325327
commit_depth=update_pass.commit_depth,
326328
exclude_patterns=update_pass.exclude_patterns,
327329
include_working_tree=update_pass.include_working_tree,
328-
# Rows an older analyzer scored are re-scored whole, as
329-
# the single-repo update does, even with no file changed.
330-
rescore_health=health_analyzer_changed(read_repo_state(path)),
330+
# Rows an older analyzer or scanner wrote are redone whole,
331+
# as the single-repo update does, even with no file changed.
332+
rescore_health=health_analyzer_changed(repo_state),
333+
rescan_security=security_scanner_changed(repo_state),
331334
)
332335
if result.updated and result.phase_timings is None:
333336
result.phase_timings = {"run": time.monotonic() - update_started}
@@ -431,6 +434,10 @@ def _write_repo_state(
431434
from ...analysis.health import HEALTH_ANALYZER_VERSION
432435

433436
state["health_analyzer_version"] = HEALTH_ANALYZER_VERSION
437+
if result.security_rescanned:
438+
from ...analysis.security.patterns import SECURITY_SCANNER_VERSION
439+
440+
state["security_scanner_version"] = SECURITY_SCANNER_VERSION
434441
if result.graph_update is not None:
435442
from ...pipeline.incremental.feature import stamp_graph_update
436443

0 commit comments

Comments
 (0)