Merge updated findings history into instruction digest recording

This commit is contained in:
Michael D'Angelo
2026-11-20 01:08:16 -08:00
17 changed files with 653 additions and 1695 deletions
@@ -204,11 +204,8 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
detail.add_argument("--metadata-only", action="store_true")
get_scan.add_argument("--check-target", action="store_true")
get_finding = subparsers.add_parser("get-finding")
get_finding.add_argument("--occurrence-id", required=True)
rename_scan = subparsers.add_parser("rename-scan")
rename_scan.add_argument("--scan-id", required=True)
rename_scan.add_argument("--name", required=True)
add_command("get-finding", "--occurrence-id")
add_command("rename-scan", "--scan-id", "--name")
read_scan_usage = add_command("read-scan-usage", "--scan-id", "--thread-id")
read_scan_usage.add_argument("--validation-thread-id")
+21 -49
View File
@@ -78,6 +78,7 @@ from workbench_instruction_digest import (
selected_instruction_digest,
verify_sealed_instruction_digests,
)
from workbench_native_indexes import indexed_scan_findings
from workbench_scan_start import (
archive_scan,
insert_running_scan,
@@ -1857,12 +1858,11 @@ def set_finding_triage(connection: sqlite3.Connection, args: argparse.Namespace)
occurrence = require_occurrence(connection, args.occurrence_id)
scan = require_scan(connection, occurrence["scan_id"])
scan_history.require_finding_checkout_owner(connection, scan)
indexed_finding = _indexed_scan_findings(connection, scan).get(occurrence["id"])
indexed_finding = indexed_scan_findings(connection, scan).get(occurrence["id"])
triaged_occurrences = finding_results.triage_occurrences(
connection, occurrence, indexed_finding
)
verification_ids = {occurrence["id"]}
verification_loaded = False
verification_ids = None
if args.status == "closed":
for checked_occurrence in triaged_occurrences:
remediation = remediation_state.latest_attempt(connection, checked_occurrence["id"])
@@ -1882,23 +1882,17 @@ def set_finding_triage(connection: sqlite3.Connection, args: argparse.Namespace)
and remediation is not None
and remediation["state"] == "verified"
):
if checked_occurrence["id"] not in verification_ids and not verification_loaded:
active_finding = _indexed_scan_findings(
connection,
scan,
include_resolved=False,
verification_occurrence_id=occurrence["id"],
).get(occurrence["id"])
if active_finding is not None:
verification_ids.update(active_finding["active_occurrence_ids"])
verification_loaded = True
if checked_occurrence["id"] in verification_ids:
checked_scan = require_scan(connection, checked_occurrence["scan_id"])
require_remediation_checkout_unchanged(
checked_scan,
remediation,
require_applied_content=True,
)
if checked_occurrence["id"] != occurrence["id"]:
if verification_ids is None:
verification_ids = native_indexes.verification_occurrence_ids(
connection, indexed_finding, coverage_for_comparison
)
if checked_occurrence["id"] not in verification_ids:
continue
checked_scan = require_scan(connection, checked_occurrence["scan_id"])
require_remediation_checkout_unchanged(
checked_scan, remediation, require_applied_content=True
)
admission_sequence = connection.execute(
"SELECT COALESCE(MAX(sequence), 0) FROM scan_admissions"
).fetchone()[0]
@@ -1976,7 +1970,7 @@ def require_finding_open(connection: sqlite3.Connection, occurrence_id: str) ->
occurrence = require_occurrence(connection, occurrence_id)
scan = require_scan(connection, occurrence["scan_id"])
scan_history.require_finding_checkout_owner(connection, scan)
triage = _indexed_scan_findings(connection, scan).get(occurrence_id)
triage = indexed_scan_findings(connection, scan).get(occurrence_id)
if triage is None:
triage = connection.execute(
"SELECT status FROM finding_triage WHERE occurrence_id = ?",
@@ -2710,29 +2704,11 @@ def scan_context(
return context
def _indexed_scan_findings(
connection: sqlite3.Connection,
scan: sqlite3.Row,
*,
through_scan: sqlite3.Row | None = None,
include_resolved: bool = True,
verification_occurrence_id: str | None = None,
) -> dict[str, dict[str, Any]]:
return native_indexes.indexed_scan_findings(
connection,
scan,
read_coverage=coverage_for_comparison,
through_scan=through_scan,
include_resolved=include_resolved,
verification_occurrence_id=verification_occurrence_id,
)
def scan_finding_triage(
connection: sqlite3.Connection, scan: sqlite3.Row, *, through_scan: sqlite3.Row | None = None
) -> dict[str, dict[str, Any]]:
return finding_results.scan_finding_triage(
connection, scan, _indexed_scan_findings(connection, scan, through_scan=through_scan)
connection, scan, indexed_scan_findings(connection, scan, through_scan=through_scan)
)
@@ -2843,7 +2819,7 @@ def list_findings(connection: sqlite3.Connection, args: argparse.Namespace) -> d
scan = require_scan(connection, args.scan_id)
scan_history.require_finding_checkout_owner(connection, scan)
backfill_legacy_finding_details(connection, scan)
indexed = _indexed_scan_findings(connection, scan)
indexed = indexed_scan_findings(connection, scan)
connection.create_function(
"codex_security_aggregate_status",
2,
@@ -2943,7 +2919,7 @@ def scan_result(
if all(row["id"] != occurrence["id"] for row in occurrence_rows):
occurrence_rows.append(occurrence)
indexed_findings = (
_indexed_scan_findings(connection, scan)
indexed_scan_findings(connection, scan)
if occurrence_rows
and (
scan["status"] == "complete"
@@ -3130,7 +3106,7 @@ def finding_result(
related: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
if full_details:
indexed_finding = _indexed_scan_findings(connection, scan).get(occurrence["id"])
indexed_finding = indexed_scan_findings(connection, scan).get(occurrence["id"])
return finding_results.finding_result(
connection,
scan,
@@ -3330,12 +3306,8 @@ def main(*, before_archive: Callable[[], None] | None = None) -> None:
"set-scan-cost-limit": set_scan_cost_limit,
"read-scan-usage": read_scan_usage,
"finalize-scan-usage": finalize_scan_usage,
"list-global-findings": partial(
native_indexes.list_global_findings, read_coverage=coverage_for_comparison
),
"list-repositories": partial(
native_indexes.list_repositories, read_coverage=coverage_for_comparison
),
"list-global-findings": native_indexes.list_global_findings,
"list-repositories": native_indexes.list_repositories,
"list-findings": list_findings,
"complete-budget-exhausted-scan": complete_budget_exhausted_scan,
"set-finding-triage": set_finding_triage,
@@ -31,8 +31,6 @@ from workbench_validation import bounded_output_text, timestamp_key
def list_global_findings(
connection: sqlite3.Connection,
args: argparse.Namespace,
*,
read_coverage: Callable | None = None,
) -> dict[str, Any]:
"""Return a page of indexed findings after applying the requested filters, with nextOffset for continuation."""
limit = args.limit
@@ -275,18 +273,8 @@ def _indexed_findings(
and match["after_generation"] is not None
):
continue
before = group(
(
before_repository,
match["before_finding_id"],
)
)
after = group(
(
after_repository,
match["after_finding_id"],
)
)
before = group((before_repository, match["before_finding_id"]))
after = group((after_repository, match["after_finding_id"]))
if before != after:
parents[after] = before
@@ -339,20 +327,9 @@ def _indexed_findings(
triage.status AS decision_status,
triage.close_reason,
triage.updated_at AS decision_updated_at,
COALESCE(
(SELECT MAX(decisions.decision_sequence)
FROM finding_decisions AS decisions
WHERE decisions.occurrence_id = occurrences.id),
triage.rowid
) AS decision_sequence,
(SELECT decisions.scan_sequence
FROM finding_decisions AS decisions
WHERE decisions.occurrence_id = occurrences.id
ORDER BY decisions.decision_sequence DESC LIMIT 1) AS decision_scan_sequence,
(SELECT decisions.admission_sequence
FROM finding_decisions AS decisions
WHERE decisions.occurrence_id = occurrences.id
ORDER BY decisions.decision_sequence DESC LIMIT 1) AS decision_admission_sequence,
COALESCE(decision.decision_sequence, triage.rowid) AS decision_sequence,
decision.scan_sequence AS decision_scan_sequence,
decision.admission_sequence AS decision_admission_sequence,
scans.rowid AS scan_sequence,
admissions.sequence AS admission_sequence,
COALESCE(scans.target_id, scans.target_path) AS indexed_target_id,
@@ -364,19 +341,16 @@ def _indexed_findings(
LEFT JOIN security_targets AS targets ON targets.id = scans.target_id
LEFT JOIN scan_admissions AS admissions ON admissions.scan_id = scans.id
LEFT JOIN finding_triage AS triage ON triage.occurrence_id = occurrences.id
LEFT JOIN finding_decisions AS decision ON decision.rowid = (
SELECT rowid FROM finding_decisions WHERE occurrence_id = occurrences.id
ORDER BY decision_sequence DESC LIMIT 1
)
WHERE {target_filter}
""",
((query,) if query else ()) + target_values,
):
grouped.setdefault(
group(
(
repository_group(row),
row["finding_id"],
)
),
[],
).append(row)
key = group((repository_group(row), row["finding_id"]))
grouped.setdefault(key, []).append(row)
# When a match group spans current targets, keep decisions within each verified
# generation or legacy target in that group. Scoped queries already select their history.
@@ -511,10 +485,7 @@ def indexed_scan_findings(
connection: sqlite3.Connection,
scan: sqlite3.Row,
*,
read_coverage: Callable[[sqlite3.Row], dict[str, Any]],
through_scan: sqlite3.Row | None = None,
include_resolved: bool = True,
verification_occurrence_id: str | None = None,
) -> dict[str, dict[str, Any]]:
if not connection.execute(
"SELECT 1 FROM finding_occurrences WHERE scan_id = ? LIMIT 1", (scan["id"],)
@@ -554,11 +525,66 @@ def indexed_scan_findings(
through_admission_sequence=through,
require_current_owners=True,
)
coverage_by_scan_id: dict[str, tuple[sqlite3.Row, dict[str, Any] | None]] = {}
uncertain_occurrence_ids: set[str] | None = None
return {occurrence: row for row in indexed for occurrence in row["occurrence_ids"]}
def superseded_for_verification(finding, later_scan, finding_group):
nonlocal uncertain_occurrence_ids
def verification_occurrence_ids(
connection: sqlite3.Connection,
finding_group: dict[str, Any],
read_coverage: Callable[[sqlite3.Row], dict[str, Any]],
) -> set[str]:
admitted = json.dumps(finding_group["known_scan_ids"])
verification_scans = connection.execute(
"SELECT scans.*, rowid AS scan_sequence, "
"(SELECT sequence FROM scan_admissions WHERE scan_id = scans.id) AS admission_sequence, "
"COALESCE(target_id, target_path) AS indexed_target_id "
"FROM scans WHERE id IN (SELECT value FROM json_each(?)) ORDER BY rowid DESC",
(admitted,),
).fetchall()
@cache
def has_uncertain_match():
return any(
match[f"{side}OccurrenceId"] in finding_group["occurrence_ids"]
for comparison in connection.execute(
"SELECT result_json FROM scan_comparisons "
"WHERE before_scan_id IN (SELECT value FROM json_each(?)) "
"OR after_scan_id IN (SELECT value FROM json_each(?))",
(admitted, admitted),
)
for match in json.loads(comparison["result_json"]).get("uncertain", [])
for side in ("before", "after")
)
@cache
def verification_coverage(scan):
if (
scan["status"] != "complete"
or scan["mode"] == "diff"
or scan["seal_manifest_digest"] is None
):
return None
try:
return read_coverage(scan)
except SystemExit as error:
cause: BaseException | None = error
while cause is not None:
if isinstance(cause, FileNotFoundError):
return None
cause = cause.__cause__
message = str(error)
if message == "Scan directory must be an existing canonical non-symlink directory.":
try:
Path(scan["scan_dir"]).lstat()
except FileNotFoundError:
return None
if message.startswith("missing required contract artifact: ") or message.endswith(
": expected a regular file inside the scan directory."
):
return None
raise
def superseded(finding, later_scan):
if (
finding["scan_sequence"] >= later_scan["scan_sequence"]
or finding["indexed_target_id"] != later_scan["indexed_target_id"]
@@ -575,55 +601,9 @@ def indexed_scan_findings(
)
):
return False
if uncertain_occurrence_ids is None:
admitted = json.dumps(sorted(finding_group["known_scan_ids"]))
uncertain_occurrence_ids = {
match[f"{side}OccurrenceId"]
for comparison in connection.execute(
"SELECT result_json FROM scan_comparisons "
"WHERE before_scan_id IN (SELECT value FROM json_each(?)) "
"OR after_scan_id IN (SELECT value FROM json_each(?))",
(admitted, admitted),
)
for match in json.loads(comparison["result_json"]).get("uncertain", [])
for side in ("before", "after")
}
if finding_group["occurrence_ids"] & uncertain_occurrence_ids:
if has_uncertain_match():
return False
scan_id = later_scan["id"]
if scan_id not in coverage_by_scan_id:
scan = later_scan
coverage = None
if (
scan["status"] == "complete"
and scan["mode"] != "diff"
and scan["seal_manifest_digest"] is not None
):
try:
coverage = read_coverage(scan)
except SystemExit as error:
cause: BaseException | None = error
while cause is not None and not isinstance(cause, FileNotFoundError):
cause = cause.__cause__
message = str(error)
if isinstance(cause, FileNotFoundError):
pass
elif message == (
"Scan directory must be an existing canonical non-symlink directory."
):
try:
Path(scan["scan_dir"]).lstat()
except FileNotFoundError:
pass
else:
raise
elif not (
message.startswith("missing required contract artifact: ")
or message.endswith(": expected a regular file inside the scan directory.")
):
raise
coverage_by_scan_id[scan_id] = scan, coverage
scan, coverage = coverage_by_scan_id[scan_id]
coverage = verification_coverage(later_scan)
return (
coverage is not None
and coverage.get("completeness", "complete") == "complete"
@@ -633,40 +613,23 @@ def indexed_scan_findings(
for surface in coverage.get("surfaces", [])
)
and scan_history.scan_covers_path(
{**dict(scan), "target_id": later_scan["indexed_target_id"]},
{**dict(later_scan), "target_id": later_scan["indexed_target_id"]},
target_id=finding["indexed_target_id"],
path=finding["location_path"],
coverage=coverage,
)
)
result = {}
for row in indexed:
row["active_occurrence_ids"] = row["occurrence_ids"]
if verification_occurrence_id in row["occurrence_ids"]:
verification_scans = connection.execute(
"SELECT scans.*, rowid AS scan_sequence, "
"(SELECT sequence FROM scan_admissions WHERE scan_id = scans.id) AS admission_sequence, "
"COALESCE(target_id, target_path) AS indexed_target_id "
"FROM scans WHERE id IN (SELECT value FROM json_each(?)) ORDER BY rowid DESC",
(json.dumps(row["known_scan_ids"]),),
).fetchall()
row["active_occurrence_ids"] = {
item["occurrence_id"]
for item in row["occurrences"]
if not any(
superseded_for_verification(item, later, row) for later in verification_scans
)
}
result.update(dict.fromkeys(row["occurrence_ids"], row))
return result
return {
item["occurrence_id"]
for item in finding_group["occurrences"]
if not any(superseded(item, later) for later in verification_scans)
}
def list_repositories(
connection: sqlite3.Connection,
args: argparse.Namespace | None = None,
*,
read_coverage: Callable | None = None,
) -> dict[str, Any]:
"""Return tracked targets with scan summaries, finding counts, and current checkout availability."""
identities = RepositoryIdentityCache(connection)
@@ -50,7 +50,7 @@ def test_scan_context_reports_only_other_running_deep_scans(
"UPDATE scans SET handoff_status = 'delivered' WHERE id IN (?, ?)",
(scans["other"]["scanId"], scans["failed"]["scanId"]),
)
current = Namespace(scan_id=scans["current"]["scanId"], occurrence_id=None, check_target=False)
current = Namespace(scan_id=scans["current"]["scanId"], occurrence_id=None)
other = scans["other"]
assert workbench_api["get_scan"](workbench_db, current)["otherRunningDeepScans"] == [
{
@@ -3,8 +3,6 @@ from __future__ import annotations
import json
import runpy
import sqlite3
import subprocess
import sys
from contextlib import closing
from pathlib import Path
@@ -22,36 +20,17 @@ from test_workbench_setup_and_migrations import (
)
from workbench_test_support import (
SCRIPT,
close_finding,
complete_pending,
create_cli_scan,
finding_detail,
get_scan,
load_script,
run_workbench,
write_completed_contract,
scan_finding,
)
def complete_pending(state: Path, repository: Path, scan: dict, *, failed: bool = False):
scan_dir = Path(scan["scanDir"])
write_completed_contract(scan_dir, scan["scanId"], repository)
subprocess.run(
[
sys.executable,
str(SCRIPT.with_name("finalize_scan_contract.py")),
"--scan-dir",
str(scan_dir),
],
check=True,
capture_output=True,
text=True,
)
return run_workbench(
state,
"fail-scan" if failed else "complete-scan",
"--scan-id",
scan["scanId"],
*(["--message", "Synthetic interruption"] if failed else []),
)
@pytest.mark.parametrize(
("ordering", "reason"),
[
@@ -74,9 +53,7 @@ def test_triage_observes_first_result_admission(tmp_path: Path, ordering: str, r
state, scans, repository = tmp_path / "state", tmp_path / "scans", tmp_path / "repository"
repository.mkdir()
first = create_cli_scan(state, scans, repository)
occurrence = run_workbench(state, "get-scan", "--scan-id", first["scanId"])["scan"]["findings"][
0
]["occurrenceId"]
occurrence = scan_finding(state, first)["occurrenceId"]
pending = (
None
if ordering == "registered-after"
@@ -88,18 +65,7 @@ def test_triage_observes_first_result_admission(tmp_path: Path, ordering: str, r
target = tmp_path / "other-repository"
target.mkdir()
create_cli_scan(state, scans, target)
run_workbench(
state,
"set-finding-triage",
"--occurrence-id",
occurrence,
"--status",
"closed",
"--close-reason",
reason,
"--note",
"Synthetic reviewed decision.",
)
close_finding(state, occurrence, reason, "Synthetic reviewed decision.")
if pending is None:
pending = create_cli_scan(state, scans, repository)
elif ordering != "complete":
@@ -117,7 +83,7 @@ def test_triage_observes_first_result_admission(tmp_path: Path, ordering: str, r
)["findings"]
assert len(findings) == 1
assert findings[0]["status"] == expected
detail = run_workbench(state, "get-scan", "--scan-id", pending["scanId"])["scan"]["findings"]
detail = get_scan(state, pending["scanId"])["scan"]["findings"]
assert detail[0]["status"] == expected
assert len(
run_workbench(
@@ -135,21 +101,8 @@ def test_comparison_reopens_finding_admitted_after_dismissal(tmp_path: Path):
repository.mkdir()
pending = create_cli_scan(state, scans, repository, complete=False)
completed = create_cli_scan(state, scans, repository)
occurrence = run_workbench(state, "get-scan", "--scan-id", completed["scanId"])["scan"][
"findings"
][0]["occurrenceId"]
run_workbench(
state,
"set-finding-triage",
"--occurrence-id",
occurrence,
"--status",
"closed",
"--close-reason",
"false_positive",
"--note",
"Synthetic dismissal.",
)
occurrence = scan_finding(state, completed)["occurrenceId"]
close_finding(state, occurrence, "false_positive", "Synthetic dismissal.")
complete_pending(state, repository, pending)
assert compare_scan_pair(state, completed, pending)["summary"]["reopened"] == 1
@@ -160,21 +113,8 @@ def test_replayed_completion_does_not_advance_admission(tmp_path: Path, failed:
repository.mkdir()
scan = create_cli_scan(state, scans, repository, complete=False)
complete_pending(state, repository, scan, failed=failed)
occurrence = run_workbench(state, "get-scan", "--scan-id", scan["scanId"])["scan"]["findings"][
0
]["occurrenceId"]
run_workbench(
state,
"set-finding-triage",
"--occurrence-id",
occurrence,
"--status",
"closed",
"--close-reason",
"false_positive",
"--note",
"Synthetic retained decision.",
)
occurrence = scan_finding(state, scan)["occurrenceId"]
close_finding(state, occurrence, "false_positive", "Synthetic retained decision.")
with sqlite3.connect(state / "workbench.sqlite3") as connection:
before = connection.execute("SELECT sequence, scan_id FROM scan_admissions").fetchall()
run_workbench(
@@ -184,9 +124,7 @@ def test_replayed_completion_does_not_advance_admission(tmp_path: Path, failed:
assert (
connection.execute("SELECT sequence, scan_id FROM scan_admissions").fetchall() == before
)
detail = run_workbench(state, "get-finding", "--occurrence-id", occurrence)["scan"]["findings"][
0
]
detail = finding_detail(state, occurrence)
assert detail["status"] == "closed"
@@ -41,7 +41,7 @@ def test_get_scan_returns_consistent_progress_when_canceled_during_read(tmp_path
monkeypatch.setattr(workbench, "backfill_legacy_finding_details", cancel_after_backfill)
with closing(workbench.connect(deferred=True)) as connection:
result = workbench.get_scan(
connection, argparse.Namespace(scan_id=scan_id, occurrence_id=None, check_target=False)
connection, argparse.Namespace(scan_id=scan_id, occurrence_id=None)
)
scan = result["scan"]
assert scan["progress"]["status"] == scan["lifecycle"]["status"] == "canceled"
@@ -837,7 +837,7 @@ def test_csv_export_escapes_newline_and_full_width_formula_prefixes(tmp_path: Pa
assert row["remediation"] == "' \t+1+1"
def test_completed_findings_support_requested_page_sizes(tmp_path: Path) -> None:
def test_completed_findings_are_returned_in_bounded_pages(tmp_path: Path) -> None:
state_dir, target, scan_id, scan_dir = empty_target_scan(tmp_path)
write_completed_contract(scan_dir, scan_id, target)
findings_path = scan_dir / "findings.json"
@@ -863,7 +863,6 @@ def test_completed_findings_support_requested_page_sizes(tmp_path: Path) -> None
assert second_page["offset"] == 20
assert second_page["nextOffset"] == 70
assert second_page["total"] == 75
assert second_page["limit"] == 50
assert len(second_page["findings"]) == 50
assert embedded_occurrence_ids.isdisjoint(
finding["occurrenceId"] for finding in second_page["findings"]
File diff suppressed because it is too large Load Diff
@@ -14,21 +14,23 @@ from test_workbench_scan_history import (
create_cli_scan,
save_scan_matches,
)
from workbench_test_support import initialize_git_repository, run_workbench, set_triage
from workbench_test_support import (
close_finding,
finding_detail,
initialize_git_repository,
run_workbench,
scan_finding,
)
SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "workbench_db.py"
def finding(state, scan):
return run_workbench(state, "get-scan", "--scan-id", scan["scanId"])["scan"]["findings"][0]
@pytest.mark.parametrize("command", ["triage", "remediation"])
def test_previous_owner_cannot_mutate_or_replay_finding_actions(tmp_path, command):
state, root, repository = tmp_path / "state", tmp_path / "scans", tmp_path / "repository"
revision = initialize_git_repository(repository)
previous = create_cli_scan(state, root, repository, target_revision=revision)
occurrence = finding(state, previous)["occurrenceId"]
occurrence = scan_finding(state, previous)["occurrenceId"]
request, token = str(uuid.uuid4()), str(uuid.uuid4())
arguments = (
["set-finding-triage", "--occurrence-id", occurrence, "--status", "open"]
@@ -64,21 +66,13 @@ def test_feedback_cites_the_selected_occurrence_of_an_existing_match(tmp_path):
)
for name in ("first", "second")
]
findings = [finding(state, scan) for scan in scans]
findings = [scan_finding(state, scan) for scan in scans]
save_scan_matches(state, *scans, confirmed_match(*(row["occurrenceId"] for row in findings)))
current = create_cli_scan(state, root, repository, complete=False)
note = "Reviewed this synthetic occurrence."
for index, expected_decisions in ((0, 2), (1, 3), (1, 3)):
reviewed = findings[index]
set_triage(
state,
reviewed["occurrenceId"],
"closed",
"--close-reason",
"false_positive",
"--note",
note,
)
close_finding(state, reviewed["occurrenceId"], "false_positive", note)
(feedback,) = run_workbench(state, "get-scan-feedback", "--scan-id", current["scanId"])[
"falsePositives"
]
@@ -102,16 +96,10 @@ def test_replacement_checkout_does_not_receive_previous_owner_feedback(tmp_path)
state, root, repository = tmp_path / "state", tmp_path / "scans", tmp_path / "repository"
repository.mkdir()
previous = create_cli_scan(state, root, repository)
run_workbench(
close_finding(
state,
"set-finding-triage",
"--occurrence-id",
finding(state, previous)["occurrenceId"],
"--status",
"closed",
"--close-reason",
scan_finding(state, previous)["occurrenceId"],
"false_positive",
"--note",
"Synthetic previous-owner rationale.",
)
current = create_cli_scan(state, root, repository, complete=False)
@@ -128,9 +116,9 @@ def test_related_findings_respect_the_current_owner_of_both_scans(
state, root, repository = tmp_path / "state", tmp_path / "scans", tmp_path / "repository"
repository.mkdir()
before = create_cli_scan(state, root, repository, identity_anchor="before")
old_finding = finding(state, before)
old_finding = scan_finding(state, before)
after = create_cli_scan(state, root, repository, identity_anchor="after")
current_finding = finding(state, after)
current_finding = scan_finding(state, after)
# A persisted comparison may survive a later checkout replacement.
run_workbench(
state,
@@ -165,9 +153,7 @@ def test_related_findings_respect_the_current_owner_of_both_scans(
"UPDATE scans SET target_device = ?, target_inode = ? WHERE id = ?",
(*identity, after["scanId"]),
)
detail = run_workbench(
state, "get-finding", "--occurrence-id", current_finding["occurrenceId"]
)["scan"]["findings"][0]
detail = finding_detail(state, current_finding["occurrenceId"])
assert len(detail.get("related", [])) == (0 if replaced else 1)
@@ -762,7 +762,7 @@ def test_confirmed_history_follows_recurring_ids_and_reverts_after_unlink(
# Both the group and its matches follow scan start time.
for scan in group:
row = db.execute("SELECT * FROM scans WHERE id = ?", (scan,)).fetchone()
indexed = workbench_api["_indexed_scan_findings"](db, row)[occurrences[scan]]
indexed = workbench_api["indexed_scan_findings"](db, row)[occurrences[scan]]
matches, first, bounds = history.finding_matches(
db, occurrences[scan], indexed["occurrence_ids"]
)
@@ -1,126 +0,0 @@
from __future__ import annotations
import json
import sqlite3
import subprocess
import sys
from pathlib import Path
import pytest
from test_workbench_history_regressions import verified_patch
from test_workbench_scan_history import FINALIZER, create_cli_scan, run_workbench
from workbench_test_support import initialize_git_repository, write_completed_contract
@pytest.mark.parametrize("review", ["complete", "deferred", "reopened"])
def test_stable_recurrence_keeps_older_patch_verification(tmp_path: Path, review: str) -> None:
state, root, repository = tmp_path / "state", tmp_path / "scans", tmp_path / "repository"
initialize_git_repository(repository)
(repository / "src").mkdir()
source = repository / "src/extract.py"
source.write_text("vulnerable\n")
subprocess.run(["git", "-C", str(repository), "add", "."], check=True)
subprocess.run(
["git", "-C", str(repository), "commit", "-qm", "Synthetic stable finding"], check=True
)
revision = subprocess.check_output(
["git", "-C", str(repository), "rev-parse", "HEAD"], text=True
).strip()
earlier = create_cli_scan(state, root, repository, target_revision=revision)
first = run_workbench(state, "get-scan", "--scan-id", earlier["scanId"])["scan"]["findings"][0]
verified_patch(state, earlier, first["occurrenceId"], repository, revision)
source.write_text("vulnerable\n")
later = create_cli_scan(state, root, repository, complete=False)
with sqlite3.connect(state / "workbench.sqlite3") as connection:
snapshot_digest = connection.execute(
"SELECT target_snapshot_digest FROM scans WHERE id = ?", (later["scanId"],)
).fetchone()[0]
directory = Path(later["scanDir"])
write_completed_contract(
directory,
later["scanId"],
repository,
target_kind="git_revision",
target_revision=revision,
snapshot_digest=snapshot_digest,
)
if review == "deferred":
coverage_path = directory / "coverage.json"
coverage = json.loads(coverage_path.read_text())
coverage["deferred"].append(
{
"id": "synthetic-follow-up",
"reason": "Synthetic unfinished review.",
"paths": ["src/extract.py"],
}
)
coverage_path.write_text(json.dumps(coverage))
subprocess.run([sys.executable, str(FINALIZER), "--scan-dir", str(directory)], check=True)
run_workbench(state, "complete-scan", "--scan-id", later["scanId"])
second = run_workbench(state, "get-scan", "--scan-id", later["scanId"])["scan"]["findings"][0]
assert first["findingId"] == second["findingId"]
if review == "reopened":
run_workbench(
state,
"set-finding-triage",
"--occurrence-id",
second["occurrenceId"],
"--status",
"open",
)
result = run_workbench(
state,
"set-finding-triage",
"--occurrence-id",
second["occurrenceId"],
"--status",
"closed",
"--close-reason",
"already_fixed",
check=False,
)
if review == "complete":
assert result["returncode"] == 0, result["stderr"]
else:
assert result["returncode"] != 0
assert "Working-tree contents changed" in result["stderr"]
finding = run_workbench(state, "get-scan", "--scan-id", earlier["scanId"])["scan"]["findings"][
0
]
assert finding["status"] == ("closed" if review == "complete" else "open")
def test_newer_stopped_recurrence_retains_completed_triage(tmp_path: Path) -> None:
state, root, repository = tmp_path / "state", tmp_path / "scans", tmp_path / "repository"
repository.mkdir()
earlier = create_cli_scan(state, root, repository)
finding = run_workbench(state, "get-scan", "--scan-id", earlier["scanId"])["scan"]["findings"][
0
]
run_workbench(
state,
"set-finding-triage",
"--occurrence-id",
finding["occurrenceId"],
"--status",
"closed",
"--close-reason",
"wont_fix",
"--note",
"Synthetic accepted risk.",
)
stopped = create_cli_scan(state, root, repository, complete=False)
directory = Path(stopped["scanDir"])
write_completed_contract(directory, stopped["scanId"], repository)
subprocess.run([sys.executable, str(FINALIZER), "--scan-dir", str(directory)], check=True)
run_workbench(
state, "fail-scan", "--scan-id", stopped["scanId"], "--message", "Synthetic interruption"
)
findings = run_workbench(state, "list-global-findings", "--include-resolved")["findings"]
assert len(findings) == 1
assert findings[0]["status"] == "closed"
assert findings[0]["scanId"] == stopped["scanId"]
assert findings[0]["occurrenceCount"] == 2
assert findings[0]["knownScanIds"] == [earlier["scanId"], stopped["scanId"]]
@@ -1069,6 +1069,33 @@ def usage_counts(
}
def scan_finding(state: Path, scan: dict) -> dict:
return get_scan(state, scan["scanId"])["scan"]["findings"][0]
def finding_detail(state: Path, occurrence: str) -> dict:
return run_workbench(state, "get-finding", "--occurrence-id", occurrence)["scan"]["findings"][0]
def close_finding(state: Path, occurrence: str, reason: str, note: str | None = None, **options):
extra = ["--note", note] if note is not None else []
return set_triage(state, occurrence, "closed", "--close-reason", reason, *extra, **options)
def complete_pending(state: Path, repository: Path, scan: dict, *, failed: bool = False):
scan_dir = Path(scan["scanDir"])
write_completed_contract(scan_dir, scan["scanId"], repository)
finalize_cli_scan(scan_dir)
if failed:
return fail_scan(state, scan["scanId"], "Synthetic interruption")
return scan_command(state, "complete-scan", scan["scanId"])
def finalize_cli_scan(scan_dir: Path) -> None:
finalizer = SCRIPT.with_name("finalize_scan_contract.py")
subprocess.run([sys.executable, str(finalizer), "--scan-dir", str(scan_dir)], check=True)
def create_cli_scan(
state_dir: Path,
root: Path,
@@ -1170,15 +1197,7 @@ def create_cli_scan(
{"id": "unreviewed-path", "reason": "Review incomplete", "paths": ["src/extract.py"]}
]
coverage_path.write_text(json.dumps(coverage))
subprocess.run(
[
sys.executable,
str(SCRIPT.with_name("finalize_scan_contract.py")),
"--scan-dir",
str(scan_dir),
],
check=True,
)
finalize_cli_scan(scan_dir)
completion = ["complete-scan", "--scan-id", launched["scanId"]]
if cost is not None:
completion.extend(("--cost-json", json.dumps(cost)))
+23 -38
View File
@@ -2932,6 +2932,14 @@ export async function main(
}
});
};
const findingOccurrenceArgs = z.object({
occurrenceId: z
.string()
.trim()
.min(1)
.max(256)
.describe("Finding occurrence ID from findings list."),
});
const findingFeedback = Cli.create("findings", {
description: "Browse and manage saved findings (defaults to list).",
})
@@ -3026,28 +3034,19 @@ export async function main(
!argv.some((argument) =>
/^--(?:offset|limit)(?:=|$)/u.test(argument),
);
const arguments_ = [
...(options.scan === undefined
? ["list-global-findings"]
: ["list-findings", "--scan-id", options.scan]),
...(options.scan === undefined && status === "closed"
? ["--include-resolved"]
: []),
...(repository === undefined ? [] : ["--repository", repository]),
...(options.query === undefined ? [] : [`--query=${options.query}`]),
...(options.severity === undefined
? []
: ["--severity", options.severity]),
...(status === undefined ? [] : ["--status", status]),
...(allPages
? []
: [
"--offset",
String(options.offset),
"--limit",
String(options.limit),
]),
];
const arguments_ = workbenchArgs(
options.scan === undefined ? "list-global-findings" : "list-findings",
{
scanId: options.scan,
includeResolved: options.scan === undefined && status === "closed",
repository,
query: options.query,
severity: options.severity,
status,
offset: allPages ? undefined : options.offset,
limit: allPages ? undefined : options.limit,
},
);
return presentHistory(
await history(arguments_, async (response): Promise<JsonObject> => {
const page = savedFindingPage(response);
@@ -3085,14 +3084,7 @@ export async function main(
.command("show", {
description:
"Show finding details, its occurrence ID, and its scan history.",
args: z.object({
occurrenceId: z
.string()
.trim()
.min(1)
.max(256)
.describe("Finding occurrence ID from findings list."),
}),
args: findingOccurrenceArgs,
output: z.record(z.string(), z.unknown()).optional(),
async run({ args, format }) {
return presentHistory(
@@ -3148,14 +3140,7 @@ export async function main(
],
hint: "Future scans of the repository can reuse the reason while it applies. Read the occurrence’s triage.note in codex-security scans show SCAN_ID --json.",
destructive: true,
args: z.object({
occurrenceId: z
.string()
.trim()
.min(1)
.max(256)
.describe("Finding occurrence ID from findings list."),
}),
args: findingOccurrenceArgs,
options: z.object({
reason: z
.string()
+23 -63
View File
@@ -321,13 +321,7 @@ export function renderScanHistory(
if (Array.isArray(locations) && locations.length > 1) {
lines.push("", ` ${strong("AFFECTED LOCATIONS")}`);
for (const location of locations) {
if (
typeof location !== "object" ||
location === null ||
Array.isArray(location)
) {
continue;
}
if (!isRecord(location)) continue;
const path = location["path"];
if (typeof path !== "string") continue;
const startLine = location["startLine"];
@@ -380,9 +374,7 @@ export function renderScanHistory(
["CONFIDENCE", "confidence"],
] as const) {
const value = result[key];
if (typeof value !== "object" || value === null || Array.isArray(value)) {
continue;
}
if (!isRecord(value)) continue;
const level = value["level"];
const rationale = description(value);
if (
@@ -408,11 +400,7 @@ export function renderScanHistory(
: result[key];
const detail = description(value);
const sections = detail === undefined ? [] : [detail];
if (
typeof value === "object" &&
value !== null &&
!Array.isArray(value)
) {
if (isRecord(value)) {
if (key === "validation") {
for (const [fieldLabel, fieldKey] of [
["Method", "method"],
@@ -447,57 +435,32 @@ export function renderScanHistory(
if (nested !== undefined) {
sections.push(`${nestedLabel}: ${nested}`);
}
if (
typeof nestedValue !== "object" ||
nestedValue === null ||
Array.isArray(nestedValue)
) {
continue;
if (!isRecord(nestedValue)) continue;
const isDataflow = nestedLabel === "Dataflow";
if (!isDataflow && nestedKey !== "reachability") continue;
const attributes: [string, string][] = [
["Source", "source"],
["Sink", "sink"],
["Outcome", "outcome"],
];
if (!isDataflow) {
attributes.unshift(
["Attacker", "attacker"],
["Entry point", "entrypoint"],
);
}
const attributes: ReadonlyArray<readonly [string, string]> =
nestedKey === "dataflow" ||
nestedKey === "dataFlow" ||
nestedKey === "data_flow"
? [
["Source", "source"],
["Sink", "sink"],
["Outcome", "outcome"],
]
: nestedKey === "reachability"
? [
["Attacker", "attacker"],
["Entry point", "entrypoint"],
["Source", "source"],
["Sink", "sink"],
["Outcome", "outcome"],
]
: [];
for (const [attributeLabel, attributeKey] of attributes) {
const detail = description(nestedValue[attributeKey]);
if (detail !== undefined) {
sections.push(`${attributeLabel}: ${detail}`);
}
}
if (
nestedKey === "dataflow" ||
nestedKey === "dataFlow" ||
nestedKey === "data_flow"
) {
appendDescriptions(
sections,
nestedValue,
"transformations",
"Transformation",
);
}
if (nestedKey === "reachability") {
appendDescriptions(
sections,
nestedValue,
"preconditions",
"Precondition",
);
}
appendDescriptions(
sections,
nestedValue,
isDataflow ? "transformations" : "preconditions",
isDataflow ? "Transformation" : "Precondition",
);
}
}
const caveats: ReadonlyArray<readonly [string, string]> =
@@ -614,10 +577,7 @@ export function renderScanHistory(
}
if (typeof result["occurrenceId"] === "string") {
const triage = result["triage"];
const details =
typeof triage === "object" && triage !== null && !Array.isArray(triage)
? triage
: undefined;
const details = isRecord(triage) ? triage : undefined;
const action =
details?.["status"] === "closed"
? ""
@@ -1,4 +1,3 @@
import { runTestInSubprocess } from "./support/test-subprocess.js";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { hash } from "node:crypto";
import { execFile } from "node:child_process";
@@ -15,6 +14,7 @@ import {
scanRuntimeDependencies,
} from "./support/api-events.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
import { runTestInSubprocess } from "./support/test-subprocess.js";
import { writeSession } from "./support/usage-rollout.js";
const { temporaryDirectory, cleanup } = createApiTestFixtures();
+157 -299
View File
@@ -3,24 +3,52 @@ import { resolve } from "node:path";
import { describe, expect, test } from "bun:test";
import type { JsonObject } from "../src/index.js";
import { main } from "../src/cli.js";
import { capture, dependencies } from "./cli-fixtures.js";
import {
capture,
dependencies,
mustNotInitializeCodex,
} from "./cli-fixtures.js";
async function runHistory(
args: string[],
response: JsonObject | ((args: readonly string[]) => JsonObject),
options: { interactive?: boolean; directory?: string } = {},
) {
const calls: (readonly string[])[] = [];
const deps = dependencies({
onWorkbench: (command) => {
calls.push(command);
return typeof response === "function" ? response(command) : response;
},
});
const { directory, interactive } = options;
if (directory !== undefined) deps.currentDirectory = () => directory;
deps.createSecurity = mustNotInitializeCodex;
const stdout = capture(interactive);
const stderr = capture();
const code = await main(args, stdout.stream, stderr.stream, deps);
expect(code, stderr.text()).toBe(0);
return { calls, stdout };
}
const repositoryQuery = (repository: string) => [
"list-global-findings",
"--repository",
repository,
"--status",
"open",
"--offset",
"0",
"--limit",
"20",
];
describe("CLI findings history", () => {
test("expands a home-relative repository before querying saved findings", async () => {
const calls: Array<readonly string[]> = [];
expect(
await main(
["findings", "list", "~/repository", "--json"],
capture().stream,
capture().stream,
dependencies({
onWorkbench: (args) => {
calls.push(args);
return { findings: [] };
},
}),
),
).toBe(0);
const { calls } = await runHistory(
["findings", "list", "~/repository", "--json"],
{ findings: [] },
);
expect(calls[0]).toContain(resolve(homedir(), "repository"));
});
@@ -29,20 +57,10 @@ describe("CLI findings history", () => {
{ scope: ["--all-repositories"] },
{ scope: ["--scan", "saved-scan"] },
])("accepts larger finding pages for scope %j", async ({ scope }) => {
const calls: Array<readonly string[]> = [];
expect(
await main(
["findings", "list", ...scope, "--limit", "100", "--json"],
capture().stream,
capture().stream,
dependencies({
onWorkbench: (args) => {
calls.push(args);
return { findings: [], findingsPage: { findings: [] } };
},
}),
),
).toBe(0);
const { calls } = await runHistory(
["findings", "list", ...scope, "--limit", "100", "--json"],
{ findings: [], findingsPage: { findings: [] } },
);
expect(calls[0]?.slice(-2)).toEqual(["--limit", "100"]);
});
@@ -53,46 +71,13 @@ describe("CLI findings history", () => {
["findings", "list"],
["findings", "list", repository],
]) {
const calls: Array<readonly string[]> = [];
const stdout = capture();
const deps = dependencies({
onWorkbench: (args): JsonObject => {
calls.push(args);
return {
findings: [
{ occurrenceId: "occ-1", title: "Missing authorization" },
],
limit: 20,
nextOffset: null,
offset: 0,
};
},
const { calls, stdout } = await runHistory([...command, "--json"], {
findings: [{ occurrenceId: "occ-1", title: "Missing authorization" }],
limit: 20,
nextOffset: null,
offset: 0,
});
deps.createSecurity = () => {
throw new Error("saved findings must not initialize Codex");
};
expect(
await main(
[...command, "--json"],
stdout.stream,
capture().stream,
deps,
),
).toBe(0);
expect(calls).toEqual([
[
"list-global-findings",
"--repository",
repository,
"--status",
"open",
"--offset",
"0",
"--limit",
"20",
],
]);
expect(calls).toEqual([repositoryQuery(repository)]);
expect(JSON.parse(stdout.text())).toMatchObject({
findings: [{ occurrenceId: "occ-1" }],
});
@@ -101,37 +86,12 @@ describe("CLI findings history", () => {
test("lets the workbench scope findings from a checkout subdirectory", async () => {
const repository = resolve("/current/repository/src");
const calls: Array<readonly string[]> = [];
const stdout = capture();
const deps = dependencies({
onWorkbench: (args): JsonObject => {
calls.push(args);
return { findings: [{ occurrenceId: "nested-finding" }] };
},
});
deps.currentDirectory = () => repository;
expect(
await main(
["findings", "list", "--json"],
stdout.stream,
capture().stream,
deps,
),
).toBe(0);
expect(calls).toEqual([
[
"list-global-findings",
"--repository",
repository,
"--status",
"open",
"--offset",
"0",
"--limit",
"20",
],
]);
const { calls, stdout } = await runHistory(
["findings", "list", "--json"],
{ findings: [{ occurrenceId: "nested-finding" }] },
{ directory: repository },
);
expect(calls).toEqual([repositoryQuery(repository)]);
expect(JSON.parse(stdout.text())).toMatchObject({
findings: [{ occurrenceId: "nested-finding" }],
});
@@ -139,43 +99,20 @@ describe("CLI findings history", () => {
test("preserves pagination for machine-readable current-repository findings", async () => {
const repository = resolve("/current/repository");
const calls: Array<readonly string[]> = [];
const stdout = capture();
const page = {
findings: [{ occurrenceId: "first-finding" }],
limit: 20,
nextOffset: 20,
offset: 0,
};
expect(
await main(
["findings", "list", "--json"],
stdout.stream,
capture().stream,
dependencies({
onWorkbench: (args) => {
calls.push(args);
return calls.length === 1
? page
: { ...page, findings: [], nextOffset: null, offset: 20 };
},
}),
),
).toBe(0);
expect(calls).toEqual([
[
"list-global-findings",
"--repository",
repository,
"--status",
"open",
"--offset",
"0",
"--limit",
"20",
],
]);
const { calls, stdout } = await runHistory(
["findings", "list", "--json"],
(args) =>
args[args.indexOf("--offset") + 1] === "20"
? { ...page, findings: [], nextOffset: null, offset: 20 }
: page,
);
expect(calls).toEqual([repositoryQuery(repository)]);
expect(JSON.parse(stdout.text())).toEqual({ ...page, repository });
});
@@ -183,30 +120,20 @@ describe("CLI findings history", () => {
{ scope: [], status: "open" },
{ scope: ["--scan", "saved-scan"], status: "all" },
])("shows the effective filters for scope %j", async ({ scope, status }) => {
const stdout = capture(true);
const calls: Array<readonly string[]> = [];
const page = { findings: [], limit: 20, nextOffset: null, offset: 0 };
expect(
await main(
[
"findings",
"list",
...scope,
"--query",
"authorization",
"--severity",
"high",
],
stdout.stream,
capture().stream,
dependencies({
onWorkbench: (args) => {
calls.push(args);
return scope.length === 0 ? page : { findingsPage: page };
},
}),
),
).toBe(0);
const { calls, stdout } = await runHistory(
[
"findings",
"list",
...scope,
"--query",
"authorization",
"--severity",
"high",
],
scope.length === 0 ? page : { findingsPage: page },
{ interactive: true },
);
expect(calls).toHaveLength(1);
expect(stdout.text()).toContain(`Status: ${status}`);
expect(stdout.text()).toContain("Severity: high");
@@ -218,20 +145,10 @@ describe("CLI findings history", () => {
[[], "open"],
[["--status", "closed"], "closed"],
] as const) {
const calls: Array<readonly string[]> = [];
expect(
await main(
["findings", "list", "--all-repositories", ...arguments_],
capture().stream,
capture().stream,
dependencies({
onWorkbench: (args) => {
calls.push(args);
return { findings: [], limit: 20, nextOffset: null, offset: 0 };
},
}),
),
).toBe(0);
const { calls } = await runHistory(
["findings", "list", "--all-repositories", ...arguments_],
{ findings: [], limit: 20, nextOffset: null, offset: 0 },
);
expect(calls[0]).toContain("--status");
expect(calls[0]).toContain(expectedStatus);
}
@@ -244,27 +161,16 @@ describe("CLI findings history", () => {
])(
"includes resolved findings in closed history for scope %j",
async ({ scope, includeResolved }) => {
const calls: Array<readonly string[]> = [];
const stdout = capture();
const finding = { occurrenceId: "resolved-finding", status: "closed" };
expect(
await main(
["findings", "list", ...scope, "--status", "closed", "--json"],
stdout.stream,
capture().stream,
dependencies({
onWorkbench: (args) => {
calls.push(args);
const findings =
args[0] === "list-findings" ||
args.includes("--include-resolved")
? [finding]
: [];
return { findings };
},
}),
),
).toBe(0);
const { calls, stdout } = await runHistory(
["findings", "list", ...scope, "--status", "closed", "--json"],
(args) => ({
findings:
args[0] === "list-findings" || args.includes("--include-resolved")
? [finding]
: [],
}),
);
expect(JSON.parse(stdout.text())).toEqual({
...(scope.length === 0
? { repository: resolve("/current/repository") }
@@ -277,26 +183,17 @@ describe("CLI findings history", () => {
);
test("preserves the current checkout when opening a relocated finding", async () => {
const stdout = capture();
const deps = dependencies({
onWorkbench: (): JsonObject => ({
const { stdout } = await runHistory(
["findings", "show", "historical-occurrence", "--json"],
{
scan: {
scanId: "historical-scan",
targetPath: "/previous/checkout",
currentTargetPath: "/current/repository",
findings: [{ occurrenceId: "historical-occurrence" }],
},
}),
});
expect(
await main(
["findings", "show", "historical-occurrence", "--json"],
stdout.stream,
capture().stream,
deps,
),
).toBe(0);
},
);
expect(JSON.parse(stdout.text())).toMatchObject({
targetPath: "/previous/checkout",
currentTargetPath: "/current/repository",
@@ -304,30 +201,20 @@ describe("CLI findings history", () => {
});
test("lists findings across repositories without a target filter", async () => {
const calls: Array<readonly string[]> = [];
expect(
await main(
[
"findings",
"list",
"--all-repositories",
"--severity",
"critical",
"--status",
"open",
"--limit",
"5",
],
capture().stream,
capture().stream,
dependencies({
onWorkbench: (args) => {
calls.push(args);
return { findings: [], limit: 5, nextOffset: null, offset: 0 };
},
}),
),
).toBe(0);
const { calls } = await runHistory(
[
"findings",
"list",
"--all-repositories",
"--severity",
"critical",
"--status",
"open",
"--limit",
"5",
],
{ findings: [], limit: 5, nextOffset: null, offset: 0 },
);
expect(calls).toEqual([
[
"list-global-findings",
@@ -344,52 +231,41 @@ describe("CLI findings history", () => {
});
test("paginates and filters findings from a selected historical scan", async () => {
const calls: Array<readonly string[]> = [];
const stdout = capture();
expect(
await main(
[
"findings",
"list",
"--scan",
"31107fbe",
"--query",
"login injection",
"--severity",
"high",
"--status",
"open",
"--offset",
"20",
"--limit",
"5",
"--json",
],
stdout.stream,
capture().stream,
dependencies({
onWorkbench: (args) => {
calls.push(args);
return {
findingsPage: {
findings: [{ occurrenceId: "occ-25", title: "Historic SQLi" }],
limit: 5,
nextOffset: null,
offset: 20,
scanId: "31107fbe-full",
total: 21,
},
};
},
}),
),
).toBe(0);
const page = {
findings: [{ occurrenceId: "occ-25", title: "Historic SQLi" }],
limit: 5,
nextOffset: null,
offset: 20,
scanId: "31107fbe-full",
total: 21,
};
const { calls, stdout } = await runHistory(
[
"findings",
"list",
"--scan",
"31107fbe",
"--query",
"login injection",
"--severity",
"high",
"--status",
"open",
"--offset",
"20",
"--limit",
"5",
"--json",
],
{ findingsPage: page },
);
expect(calls).toEqual([
[
"list-findings",
"--scan-id",
"31107fbe",
"--query=login injection",
"--query",
"login injection",
"--severity",
"high",
"--status",
@@ -400,14 +276,7 @@ describe("CLI findings history", () => {
"5",
],
]);
expect(JSON.parse(stdout.text())).toEqual({
findings: [{ occurrenceId: "occ-25", title: "Historic SQLi" }],
limit: 5,
nextOffset: null,
offset: 20,
scanId: "31107fbe-full",
total: 21,
});
expect(JSON.parse(stdout.text())).toEqual(page);
});
test("rejects repository arguments with conflicting findings scopes", async () => {
@@ -461,8 +330,6 @@ describe("CLI findings history", () => {
});
test("shows a historical occurrence without exposing unrelated findings", async () => {
const calls: Array<readonly string[]> = [];
const stdout = capture();
const selected: JsonObject = {
occurrenceId: "occ-25",
severity: { level: "high" },
@@ -471,29 +338,20 @@ describe("CLI findings history", () => {
remediationTests: ["Reject interpolated account identifiers."],
preventiveControls: ["Require parameterized query helpers."],
};
expect(
await main(
["findings", "show", "occ-25", "--json"],
stdout.stream,
capture().stream,
dependencies({
onWorkbench: (args) => {
calls.push(args);
return {
scan: {
scanId: "31107fbe-full",
scanDir: "/private/results/31107fbe-full",
targetPath: "/current/repository",
findings: [
{ occurrenceId: "occ-other", title: "Unrelated finding" },
selected,
],
},
};
},
}),
),
).toBe(0);
const { calls, stdout } = await runHistory(
["findings", "show", "occ-25", "--json"],
{
scan: {
scanId: "31107fbe-full",
scanDir: "/private/results/31107fbe-full",
targetPath: "/current/repository",
findings: [
{ occurrenceId: "occ-other", title: "Unrelated finding" },
selected,
],
},
},
);
expect(calls).toEqual([["get-finding", "--occurrence-id", "occ-25"]]);
expect(JSON.parse(stdout.text())).toEqual({
...selected,
@@ -145,9 +145,9 @@ const findingsIndexProbe = [
"connection.execute(\"ALTER TABLE scans ADD COLUMN completion_warnings_json TEXT DEFAULT '[]'\")",
"if settings.get('repositories'):",
" connection.execute('CREATE TABLE scan_progress AS SELECT id scan_id, updated_at, 0 reportable_findings_count, 0 scope_file_count, 0 review_items_completed, 0 review_items_total FROM scans')",
" result = indexes.list_repositories(connection, read_coverage=coverage)",
" result = indexes.list_repositories(connection)",
"else:",
" result = indexes.list_global_findings(connection, args, read_coverage=coverage)",
" result = indexes.list_global_findings(connection, args)",
"finding_detail, overview_finding, scan_pages, rejected_previous_owner, rejected_previous_owner_list, rejected_legacy_owner, rejected_legacy_owner_list, rejected_legacy_descendant, rejected_legacy_descendant_list = None, None, None, None, None, None, None, None, None",
"pending_remediation_error, pending_triage_rows, remediation_guard_error = None, None, None",
"if settings.get('matchedTriage') or settings.get('targetlessHistory'):",
@@ -190,7 +190,7 @@ const findingsIndexProbe = [
" connection.commit()",
" workbench.scan_context = lambda *arguments: {}",
" workbench.set_finding_triage(connection, argparse.Namespace(occurrence_id='current-old-occurrence', status='closed', close_reason=settings['matchedTriage'], note='Verified test dismissal' if settings['matchedTriage'] == 'false_positive' else None))",
" result = indexes.list_global_findings(connection, args, read_coverage=coverage)",
" result = indexes.list_global_findings(connection, args)",
" selected_scan = 'orphan-new' if settings.get('targetlessHistory') else 'current-new'",
" selected_occurrence = selected_scan + '-occurrence'",
" scan = connection.execute('SELECT * FROM scans WHERE id = ?', (selected_scan,)).fetchone()",
@@ -204,7 +204,7 @@ const findingsIndexProbe = [
" workbench.finding_results.finding_management_updated_at = lambda *_arguments: None",
" overview_finding = workbench.scan_result(connection, scan)['findings'][0]",
" else:",
" overview_finding = workbench.finding_result(connection, scan, occurrence, indexed_finding=workbench._indexed_scan_findings(connection, scan).get(occurrence['id']))",
" overview_finding = workbench.finding_result(connection, scan, occurrence, indexed_finding=workbench.indexed_scan_findings(connection, scan).get(occurrence['id']))",
" scan_pages = {status: workbench.list_findings(connection, argparse.Namespace(scan_id=selected_scan, query=None, severity=None, status=status, offset=0, limit=20))['findingsPage'] for status in ('open', 'closed')}",
" try:",
" workbench.require_finding_open(connection, selected_occurrence)",