diff options
| author | mmoore <mmoore@anthropic.com> | 2026-09-01 11:18:30 -0700 |
|---|---|---|
| committer | mmoore <mmoore@anthropic.com> | 2026-09-01 11:18:30 -0700 |
| commit | f85f7cfcbbe9c949ba63304add8be7daf5c13e78 (patch) | |
| tree | 7ed935773a561a74448b1fa42d6bcb135be7fb11 /plugins/claude-security/scripts | |
| parent | 4b909c3492b350cdc42160ffe4b135e6f5c1db12 (diff) | |
Claude Security Plugin - v0.11.0claude-security-v0.11.0
Diffstat (limited to 'plugins/claude-security/scripts')
| -rwxr-xr-x | plugins/claude-security/scripts/keep-waiting.sh | 4 | ||||
| -rw-r--r-- | plugins/claude-security/scripts/lib/absolute.py | 13 | ||||
| -rw-r--r-- | plugins/claude-security/scripts/lib/chain.py | 67 | ||||
| -rw-r--r-- | plugins/claude-security/scripts/lib/finding.py | 126 | ||||
| -rw-r--r-- | plugins/claude-security/scripts/lib/plugin.py | 3 | ||||
| -rw-r--r-- | plugins/claude-security/scripts/lib/sarif.py | 224 | ||||
| -rw-r--r-- | plugins/claude-security/scripts/lib/secret.py | 15 | ||||
| -rw-r--r-- | plugins/claude-security/scripts/lib/source.py | 94 | ||||
| -rw-r--r-- | plugins/claude-security/scripts/lib/strictjson.py | 6 | ||||
| -rwxr-xr-x | plugins/claude-security/scripts/patch_artifacts.py | 160 | ||||
| -rwxr-xr-x | plugins/claude-security/scripts/render_report.py | 368 | ||||
| -rwxr-xr-x | plugins/claude-security/scripts/save_result.py | 489 | ||||
| -rwxr-xr-x | plugins/claude-security/scripts/write_scan_meta.py | 98 |
13 files changed, 1301 insertions, 366 deletions
diff --git a/plugins/claude-security/scripts/keep-waiting.sh b/plugins/claude-security/scripts/keep-waiting.sh index 8920d36d..8cb993a5 100755 --- a/plugins/claude-security/scripts/keep-waiting.sh +++ b/plugins/claude-security/scripts/keep-waiting.sh @@ -1,10 +1,10 @@ #!/usr/bin/env bash # Hold the Security Lead's turn while the scan workflow runs: wait, then tell the # caller to run this again unless the workflow's result has arrived. -# Usage: keep-waiting.sh [SECONDS] (1 to 110, default 90; exits 2 on a bad value) +# Usage: keep-waiting.sh [SECONDS] (1 to 110, default 30; exits 2 on a bad value) # The wait stays under the Bash tool's two-minute default timeout, past which a # command is moved to the background and no longer holds the turn. -seconds=${1:-90} +seconds=${1:-30} case $seconds in '' | *[!0-9]*) seconds=0 ;; esac if [ "$seconds" -lt 1 ] || [ "$seconds" -gt 110 ]; then echo "usage: keep-waiting.sh [SECONDS between 1 and 110]" >&2 diff --git a/plugins/claude-security/scripts/lib/absolute.py b/plugins/claude-security/scripts/lib/absolute.py index 45f28ed3..fa72a510 100644 --- a/plugins/claude-security/scripts/lib/absolute.py +++ b/plugins/claude-security/scripts/lib/absolute.py @@ -1,9 +1,10 @@ -"""Whether a path is spelled absolutely on any platform, not just the one this runs on.""" +"""Whether a path is absolute on any platform, and where an absolute path sits under a root.""" from __future__ import annotations import ntpath import os +from pathlib import PurePath def spelled(path: str) -> bool: @@ -13,3 +14,13 @@ def spelled(path: str) -> bool: or path.replace("\\", "/").startswith("/") or bool(ntpath.splitdrive(path)[0]) ) + + +def relative(path: str, root: str) -> str | None: + """Where a normalised absolute `path` sits below `root`, as "a/b" ("." for root); else None.""" + try: + inside = PurePath(path).relative_to(root) + except ValueError: + return None + # A ".." could name somewhere above root; a normalised path never carries one. + return None if ".." in inside.parts else inside.as_posix() diff --git a/plugins/claude-security/scripts/lib/chain.py b/plugins/claude-security/scripts/lib/chain.py new file mode 100644 index 00000000..70e4b511 --- /dev/null +++ b/plugins/claude-security/scripts/lib/chain.py @@ -0,0 +1,67 @@ +"""The chain a vote record carries: which verification run wrote it, and what it left pending.""" + +from __future__ import annotations + +from typing import TypedDict + +from .strictjson import JsonMap, is_int, is_list, is_map + + +class Chain(TypedDict): + """A scan's position after a run: the run, the next free report id, the ranks pending.""" + + shard: int + next_id: int + pending: list[list[int]] + retry: list[int] + + +def _positive(raw: JsonMap, key: str) -> int: + """A field holding an integer from 1.""" + value = raw.get(key) + if not is_int(value) or value < 1: + msg = f"field {key!r} is not a positive integer" + raise ValueError(msg) + return value + + +def _ranks(raw: object, key: str) -> list[int]: + """A field holding a list of ranks (integers from 1).""" + if is_list(raw): + ranks = [n for n in raw if is_int(n) and n >= 1] + if len(ranks) == len(raw): + return ranks + msg = f"field {key!r} is not a list of ranks" + raise ValueError(msg) + + +def _span(raw: object) -> list[int]: + """One `[from, to]` entry of `pending`.""" + span = _ranks(raw, "pending") + if len(span) != 2 or span[0] > span[1]: + msg = "field 'pending' is not a list of [from, to] rank ranges" + raise ValueError(msg) + return span + + +def chain_of(raw: object) -> Chain: + """The chain `raw` spells; ValueError naming the field when it is not one.""" + if not is_map(raw): + msg = "is not an object" + raise ValueError(msg) + pending = raw.get("pending") + if not is_list(pending): + msg = "field 'pending' is not a list of [from, to] rank ranges" + raise ValueError(msg) + return { + "shard": _positive(raw, "shard"), + "next_id": _positive(raw, "next_id"), + "pending": [_span(entry) for entry in pending], + "retry": _ranks(raw.get("retry"), "retry"), + } + + +def pending_ranks(chain: Chain) -> list[int]: + """Every rank the chain leaves to the next run, ascending.""" + spanned = {n for start, end in chain["pending"] for n in range(start, end + 1)} + return sorted(spanned | set(chain["retry"])) diff --git a/plugins/claude-security/scripts/lib/finding.py b/plugins/claude-security/scripts/lib/finding.py index e21a1c74..b7cfa0dd 100644 --- a/plugins/claude-security/scripts/lib/finding.py +++ b/plugins/claude-security/scripts/lib/finding.py @@ -1,7 +1,8 @@ -"""The Finding record every product carries, and build_finding, which validates a raw one.""" +"""The Finding every product is built from, and build_finding, which validates a raw one.""" from __future__ import annotations +import ntpath import os import re from typing import TypedDict @@ -19,7 +20,7 @@ class Panel(TypedDict): class Finding(TypedDict): - """One validated finding: the JSONL record, whose field order is this class's order.""" + """One validated finding, in the JSONL record's field order; the record adds the id (Record).""" id: str title: str @@ -36,6 +37,13 @@ class Finding(TypedDict): cwe_id: str snippet: str symbol: str + declared_line: int + + +class Record(Finding): + """A finding as every product carries it: placed on its line (sarif.placed), its id last.""" + + claudeSecurityPluginFindingId: str SEVERITIES = ("CRITICAL", "HIGH", "MEDIUM", "LOW") @@ -53,6 +61,25 @@ class FindingError(Exception): """A refusal; the message names what a findings.json record got wrong.""" +class FindingPathError(FindingError): + """A refusal of one finding's model-written path; the rest of a report can still carry. + + The message names the finding and quotes the declared path; `finding_id` + and `wrong` (what is wrong with the path, without the path) are what a + caller surviving the refusal may record in a product. + """ + + finding_id: str + wrong: str + cwe: int = 0 + snippet: str = "" + + def __init__(self, finding_id: str, *, declared: str, wrong: str) -> None: + super().__init__(f"finding {finding_id} file {declared!r} {wrong}") + self.finding_id = finding_id + self.wrong = wrong + + def cwe_number(item: JsonMap, finding_id: str) -> int: """A finding's CWE number; a cwe_id missing, unreadable or malformed is refused. @@ -108,6 +135,34 @@ def vote_confidence_ceiling(record: object) -> str | None: return "high" if panel["true"] >= PANEL_VOTER_COUNT else "medium" +def line_number(raw: object) -> int | None: + """A findings.json line value as an integer: an int, or digits in a string; None otherwise.""" + if is_str(raw) and re.fullmatch(r"\s*-?[0-9]{1,15}\s*", raw): + return int(raw) + return raw if is_int(raw) else None + + +def line_field(item: JsonMap, key: str, finding_id: str, default: int) -> int: + """One of a finding's line fields as an integer (line_number); absent reads as `default`.""" + line = line_number(item.get(key, default)) + if line is None: + msg = f"finding {finding_id} {key} {item.get(key)!r} is not an integer" + raise FindingError(msg) + return line + + +def scan_prefix_shaped(prefix: str) -> bool: + """Whether `prefix` is what `git rev-parse --show-prefix` prints: empty, or `a/b/`.""" + if not prefix: + return True + return ( + prefix.endswith("/") + and "\\" not in prefix + and not ntpath.splitdrive(prefix)[0] + and all(segment not in {"", ".", ".."} for segment in prefix.split("/")[:-1]) + ) + + def text_field(item: JsonMap, key: str, finding_id: str, required: bool = False) -> str: """One of a finding's text fields; absent or null reads as empty unless it is required.""" value = item.get(key) @@ -127,6 +182,15 @@ def text_field(item: JsonMap, key: str, finding_id: str, required: bool = False) return text +def leaked_spelling(path: str, *, first: str, scan_root: str) -> bool: + """Whether a path's cross-platform absolute spelling names the machine, not the repository.""" + if not absolute.spelled(path): + return False + if os.name == "nt": + return True + return not os.path.lexists(os.path.join(scan_root, first)) + + def file_field( item: JsonMap, finding_id: str, scan_root: str, scan_prefix: str, must_exist: bool ) -> str: @@ -139,11 +203,12 @@ def file_field( With `must_exist` (a codebase scan, whose whole tree is still present when the report renders), a path that exists neither under the scan root nor at the repository top level is refused. + A name that merely spells like another platform's absolute path is treated + as repository content when the scan root holds its first segment. """ declared = text_field(item, "file", finding_id, required=True).strip() depth = scan_prefix.count("/") - beyond = "repository" if depth else "scan root" - refusal = f"finding {finding_id} file {declared!r} escapes the {beyond}" + escapes = f"escapes the {'repository' if depth else 'scan root'}" path = declared.replace("\\", "/") prefix = scan_root.replace("\\", "/").rstrip("/") + "/" if scan_root and path.startswith(prefix): @@ -152,12 +217,17 @@ def file_field( try: path = os.path.relpath(os.path.realpath(path), scan_root).replace("\\", "/") except (ValueError, OSError) as error: - raise FindingError(refusal) from error + raise FindingPathError(finding_id, declared=declared, wrong=escapes) from error parts = [part for part in path.split("/") if part and part != "."] climb = next((i for i, part in enumerate(parts) if part != ".."), len(parts)) inside = parts[climb:] - if not inside or absolute.spelled(path) or ".." in inside or climb > depth: - raise FindingError(refusal) + if ( + not inside + or ".." in inside + or climb > depth + or leaked_spelling(path, first=parts[0], scan_root=scan_root) + ): + raise FindingPathError(finding_id, declared=declared, wrong=escapes) if not os.path.lexists(os.path.join(scan_root, *parts)): # A file only the repository top level holds was spelled relative to it, not the scan root. if depth and not climb: @@ -165,8 +235,9 @@ def file_field( if os.path.lexists(at_top): return os.path.relpath(at_top, scan_root).replace("\\", "/") if must_exist: - msg = f"finding {finding_id} file {declared!r} does not exist in the scanned tree" - raise FindingError(msg) + raise FindingPathError( + finding_id, declared=declared, wrong="does not exist in the scanned tree" + ) return "/".join(parts) @@ -201,12 +272,8 @@ def build_finding( if ceiling is not None and CONFIDENCE_RANK[confidence] > CONFIDENCE_RANK[ceiling]: confidence = ceiling - line = raw.get("line", 0) - if is_str(line) and re.fullmatch(r"\s*-?[0-9]{1,15}\s*", line): - line = int(line) - if not is_int(line): - msg = f"finding {finding_id} line {raw.get('line')!r} is not an integer" - raise FindingError(msg) + line = line_field(raw, "line", finding_id, 0) + declared_line = line_field(raw, "declared_line", finding_id, line) preconditions: list[str] = [] declared = raw.get("preconditions") @@ -221,21 +288,34 @@ def build_finding( number = cwe_number(raw, finding_id) category = cwe.catalog.category(number) + title = text_field(raw, "title", finding_id, required=True) + impact = text_field(raw, "impact", finding_id) + description = text_field(raw, "description", finding_id, required=True) + exploit_scenario = text_field(raw, "exploit_scenario", finding_id, required=True) + recommendation = text_field(raw, "recommendation", finding_id) + snippet = text_field(raw, "snippet", finding_id) + symbol = text_field(raw, "symbol", finding_id) + try: + file = file_field(raw, finding_id, scan_root, scan_prefix, must_exist) + except FindingPathError as error: + error.cwe, error.snippet = number, snippet + raise return { "id": finding_id, - "title": text_field(raw, "title", finding_id, required=True), - "impact": text_field(raw, "impact", finding_id), - "file": file_field(raw, finding_id, scan_root, scan_prefix, must_exist), + "title": title, + "impact": impact, + "file": file, "line": line, - "description": text_field(raw, "description", finding_id, required=True), - "exploit_scenario": text_field(raw, "exploit_scenario", finding_id, required=True), + "description": description, + "exploit_scenario": exploit_scenario, "preconditions": preconditions, "category": category.name if category is not None else cwe.UNCATEGORIZED, "severity": severity, "confidence": confidence, - "recommendation": text_field(raw, "recommendation", finding_id), + "recommendation": recommendation, "cwe_id": f"CWE-{number}", - "snippet": text_field(raw, "snippet", finding_id), - "symbol": text_field(raw, "symbol", finding_id), + "snippet": snippet, + "symbol": symbol, + "declared_line": declared_line, } diff --git a/plugins/claude-security/scripts/lib/plugin.py b/plugins/claude-security/scripts/lib/plugin.py index c5daa153..2d8321cd 100644 --- a/plugins/claude-security/scripts/lib/plugin.py +++ b/plugins/claude-security/scripts/lib/plugin.py @@ -11,6 +11,9 @@ from .strictjson import is_map, is_str NAME = "claude-security" ROOT = Path(__file__).resolve().parents[2] RUN_DIR_NAME = ".claude-security-run" +TARGET_FILES_NAME = "target-files.json" +# Set only by workflows/scan.js (its PROVENANCE) on each vote record it computes. +VOTES_PROVENANCE = "workflows/scan.js" MODES = ("scan", "changes", "commit") REPORT_DIR_PREFIX = "CLAUDE-SECURITY-" # \Z, not $: `$` also matches before a trailing newline, and this id names product files. diff --git a/plugins/claude-security/scripts/lib/sarif.py b/plugins/claude-security/scripts/lib/sarif.py index 1b851101..de98e4f5 100644 --- a/plugins/claude-security/scripts/lib/sarif.py +++ b/plugins/claude-security/scripts/lib/sarif.py @@ -6,19 +6,17 @@ import hashlib import json import posixpath import re -from bisect import bisect_right from dataclasses import dataclass -from itertools import accumulate -from typing import TYPE_CHECKING, NamedTuple +from typing import TYPE_CHECKING, Final, NamedTuple from urllib.parse import quote -from . import cwe, secret +from . import cwe, secret, source if TYPE_CHECKING: import uuid - from collections.abc import Mapping, Sequence + from collections.abc import Collection, Mapping, Sequence - from .finding import Finding, Panel + from .finding import Finding, Panel, Record SCHEMA_ID = ( "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json" @@ -28,7 +26,8 @@ TOOL_NAME = "Claude Security Plugin for Claude Code" TOOL_URI = "https://claude.com/product/claude-security" PROPERTY_BAG = "claudeSecurityPlugin" ID_PREFIX = "claude-security-plugin" -FINGERPRINT_KEY = ID_PREFIX + "/v2" +FINDING_ID: Final = "claudeSecurityPluginFindingId" +ID_VERSION = "v3" CONTEXT_LINES = 3 SRCROOT = "%SRCROOT%" # error is SARIF's highest level, so CRITICAL and HIGH both map to it. @@ -52,19 +51,17 @@ class Scan: def log( - findings: Sequence[Finding], + findings: Sequence[Record], scan: Scan, tool_version: str | None, run_properties: Mapping[str, object], panels: Mapping[str, Panel], - sources: Mapping[str, str], notifications: Sequence[Mapping[str, object]], ) -> dict[str, object]: """The SARIF 2.1.0 log for one scan: one run, one rule per category, one result per finding. - `sources` is the text of each scanned file a finding names, keyed by the - finding's `file`; a finding whose file is absent from it is fingerprinted - on its own quote of the code instead. + `findings` are the records render_report built with placed(): each on the + line its file places it on, carrying its id. """ filed = [(item, category_of(item)) for item in findings] categories = list(dict.fromkeys(category for _, category in filed)) @@ -89,14 +86,7 @@ def log( "invocations": [invocation], "originalUriBaseIds": {SRCROOT: {"description": {"text": base_description}}}, "results": [ - result( - item, - category, - index[category], - scan, - panels.get(item["id"]), - sources.get(item["file"]), - ) + result(item, category, index[category], scan, panels.get(item["id"])) for item, category in filed ], "properties": { @@ -171,125 +161,111 @@ def rule(category: cwe.Category | None) -> dict[str, object]: } -def fingerprint( - finding: Finding, category: cwe.Category | None, scan: Scan, source: str | None -) -> str: - """The finding's partial fingerprint: a sha256 over its rule, its path and the code it names. +def placed( + findings: Sequence[Finding], + scan: Scan, + sources: Mapping[str, str], + *, + refused_secrets: Collection[str], +) -> list[Record]: + """Each finding as the products carry it: `line` moved to where its file places it, id added. - `source` is the text of the finding's file. The code is the file's own - lines around the one that places the finding (see code_at); when the file - was not read, or no line of it places the finding, the finding's symbol - and snippet stand in for them, and the line when it has neither. A - hard-coded credential finding is the exception: its symbol and the number - of the line that places it stand in for the code always, so no text of a - file that holds a credential enters the hash. + `sources` is the text of each scanned file by the finding's `file`; a + finding whose file is absent from it keeps its line and hashes the number. """ - parts = [scan.remote or "", rule_id(category), repository_path(scan, finding)] - symbol = finding["symbol"].strip() - snippet = quoted_line(finding) - if secret.is_credential(finding): - lines = None if source is None else normalized_lines(source) - placed = None if lines is None else placing_row(lines, finding["line"], snippet) - parts += [symbol, str(finding["line"] if placed is None else placed + 1)] - return hashlib.sha256(json.dumps(parts).encode()).hexdigest() - code = None if source is None else code_at(source, finding["line"], snippet) - if code is not None: - parts.append(code) - else: - parts += [symbol, snippet] - if not symbol and not snippet: - parts.append(str(finding["line"])) - return hashlib.sha256(json.dumps(parts).encode()).hexdigest() - - -class Site(NamedTuple): - """What one result stands for: a rule at a line of a file; the log holds one result per site.""" - - rule: str - path: str - line: int + texts = {repository_file(scan, file): text for file, text in sources.items()} + secrets = { + (path, line) + for f in findings + if secret.is_credential(f) + for path, line in secret_lines(repository_path(scan, f), f, texts) + } | { + (path, line) + for quote in refused_secrets + for path, text in texts.items() + for line in source.quoted_lines(text, quote, whole=False) + } + return [placed_one(f, scan, sources.get(f["file"]), secrets) for f in findings] + + +def placed_one( + finding: Finding, scan: Scan, text: str | None, secrets: Collection[tuple[str, int]] +) -> Record: + """One finding placed in `text`, its file's content (None when unread), and given its id.""" + moved: Finding = finding + code = None + if text is not None: + lines = source.normalized_lines(text) + row = source.placing_row(lines, finding["line"], finding["snippet"]) + if row is not None: + moved = {**finding, "line": row + 1} + path = repository_path(scan, finding) + near_secret = any(p == path and abs(row + 1 - n) <= CONTEXT_LINES for p, n in secrets) + code = None if near_secret else code_at(lines, row) + return {**moved, FINDING_ID: fingerprint(moved, scan, code)} + + +def secret_lines(home: str, credential: Finding, texts: Mapping[str, str]) -> set[tuple[str, int]]: + """Every (repository path, line) of `texts` on which the `credential` finding's quote occurs. + + `home` is the credential's own repository path and `texts` the scanned + files by repository path. The quote is marked wherever it occurs in any + file, with one restraint: a quote its own file shows only as part of a + longer line is marked in the other files just where it is a whole line of + theirs. The credential's own line is always marked, for one whose quote + matched nothing or whose file was not read. + """ + snippet = credential["snippet"] + own = texts.get(home, "") + found = bool(source.quoted_lines(own, snippet, whole=False)) + fragment = found and not source.quoted_lines(own, snippet, whole=True) + return { + (path, line) + for path, text in texts.items() + for line in source.quoted_lines(text, snippet, whole=fragment and path != home) + } | {(home, credential["line"])} -def site(finding: Finding, scan: Scan, source: str | None) -> Site | None: - """The finding's site: its rule id, its repository path, and the line that places it. +def fingerprint(finding: Finding, scan: Scan, code: str | None) -> str: + """ID_VERSION, a colon, and a sha256 hex over the rule id, the repository path and `code`. - The line is the one of `source`, the finding's file, that places the - finding (placing_row), so two findings that quote one line of code are one - site whatever lines they declare; it is the declared line when the file - was not read or no line of it places the finding. A finding left with no - line (it declared none, line < 1, and none places it) has no site: None. + `code` is the file's normalized lines around the placed one (code_at); + None hashes the finding's line number in its place. """ - line = finding["line"] - if source is not None: - row = placing_row(normalized_lines(source), line, quoted_line(finding)) - if row is not None: - line = row + 1 - if line < 1: - return None - return Site(rule_id(category_of(finding)), repository_path(scan, finding), line) - + where: str | int = finding["line"] if code is None else code + basis = [rule_id(category_of(finding)), repository_path(scan, finding), where] + canonical = json.dumps(basis, separators=(",", ":"), ensure_ascii=True) + return f"{ID_VERSION}:{hashlib.sha256(canonical.encode()).hexdigest()}" -def quoted_line(finding: Finding) -> str: - """The finding's snippet with its whitespace normalized, the form placing_row looks for.""" - return " ".join(finding["snippet"].split()) +def code_at(lines: Sequence[str], row: int) -> str: + """The normalized `lines` CONTEXT_LINES either side of `row`, joined; fewer at a file's ends.""" + return "\n".join(lines[max(row - CONTEXT_LINES, 0) : row + CONTEXT_LINES + 1]) -def normalized_lines(source: str) -> list[str]: - """A file's lines, split on the newline alone, each with its whitespace normalized.""" - return [" ".join(each.split()) for each in source.split("\n")] +class Site(NamedTuple): + """What one result stands for: a rule at a line of a file; the log holds one result per site.""" -def placing_row(lines: Sequence[str], line: int, quoted: str) -> int | None: - """The index into the normalized `lines` of the one placing a finding; None when none does. - - The finding is placed on the line nearest its declared `line` where - `quoted`, its normalized snippet, appears, whitespace aside, and on the - declared line itself when it appears nowhere. - """ - declared = line - 1 - at = min( - (min(max(declared, first), last) for first, last in occurrences(lines, quoted)), - key=lambda row: abs(row - declared), - default=declared, - ) - return at if 0 <= at < len(lines) else None + rule: str + path: str + line: int -def code_at(source: str, line: int, quoted: str) -> str | None: - """The normalized lines of `source` around the one placing a finding; None when none does.""" - lines = normalized_lines(source) - at = placing_row(lines, line, quoted) - if at is None: +def site(finding: Record, scan: Scan) -> Site | None: + """The finding's site: its rule id, repository path and placed line; None for a line below 1.""" + if finding["line"] < 1: return None - return "\n".join(lines[max(at - CONTEXT_LINES, 0) : at + CONTEXT_LINES + 1]) - - -def occurrences(lines: Sequence[str], quoted: str) -> list[tuple[int, int]]: - """The (first, last) index into the normalized `lines` of each occurrence of `quoted`.""" - if not quoted: - return [] - filled = [row for row, line in enumerate(lines) if line] - starts = list(accumulate((len(lines[row]) + 1 for row in filled), initial=0)) - flat = " ".join(lines[row] for row in filled) - - def row_at(offset: int) -> int: - return filled[bisect_right(starts, offset) - 1] - - return [ - (row_at(found.start()), row_at(found.end() - 1)) - for found in re.finditer(re.escape(quoted), flat) - ] + return Site(rule_id(category_of(finding)), repository_path(scan, finding), finding["line"]) def result( - finding: Finding, + finding: Record, category: cwe.Category | None, rule_index: int, scan: Scan, panel: Panel | None, - source: str | None, ) -> dict[str, object]: - """One result: the finding under its rule, its partial fingerprint, and its JSONL record.""" + """One result: the finding under its rule, its location, and its JSONL record, id included.""" shown = secret.withheld(finding) record: dict[str, object] = {**shown} if panel is not None: @@ -300,13 +276,16 @@ def result( "level": LEVEL[finding["severity"]], "message": {"text": message(finding)}, "locations": [location(shown, scan)], - "partialFingerprints": {FINGERPRINT_KEY: fingerprint(finding, category, scan, source)}, "properties": {PROPERTY_BAG: record}, } def location(finding: Finding, scan: Scan) -> dict[str, object]: - """A result's one location: the file relative to SRCROOT, the line, the snippet, the symbol.""" + """A result's one location: the file relative to SRCROOT, the line, the snippet, the symbol. + + The line is the finding's placed line (placed()): where its quoted code + sits in the file, or the line it declared when nothing places it. + """ line = finding["line"] region: dict[str, object] = {"startLine": max(line, 1)} if line >= 1 and finding["snippet"].strip(): @@ -327,7 +306,12 @@ def location(finding: Finding, scan: Scan) -> dict[str, object]: def repository_path(scan: Scan, finding: Finding) -> str: """The finding's file relative to the repository top level, with any leading climb folded.""" - return posixpath.normpath(scan.prefix + finding["file"]) + return repository_file(scan, finding["file"]) + + +def repository_file(scan: Scan, file: str) -> str: + """A scan-root-relative `file`, as file_field carries it, made repository-relative.""" + return posixpath.normpath(scan.prefix + file) def uri_bytes(text: str) -> bytes: diff --git a/plugins/claude-security/scripts/lib/secret.py b/plugins/claude-security/scripts/lib/secret.py index 9bf90a3a..67f4d0f4 100644 --- a/plugins/claude-security/scripts/lib/secret.py +++ b/plugins/claude-security/scripts/lib/secret.py @@ -5,8 +5,8 @@ SARIF files exist to leave the machine (a code scanning upload, a CI artifact), so neither file quotes it: the finding's file, line and symbol still locate the code, and the SARIF result's message says why no line is quoted. Only the emitted copy changes: the finding is still placed on the -snippet as the researcher quoted it, and its fingerprint hashes no text of -the file (see sarif.fingerprint). +snippet as the researcher quoted it, and neither its id nor that of a +finding placed near it hashes the credential's line. """ from __future__ import annotations @@ -16,17 +16,22 @@ from typing import TYPE_CHECKING from . import cwe if TYPE_CHECKING: - from .finding import Finding + from .finding import Finding, Record # CWE's Simplified Mapping entry Use of Hard-coded Credentials; CWE-259, 321 and 671 roll up to it. CREDENTIALS = 798 +def is_credential_cwe(number: int) -> bool: + """Whether CWE `number` rolls up to Use of Hard-coded Credentials.""" + return cwe.catalog.category_of.get(number) == CREDENTIALS + + def is_credential(finding: Finding) -> bool: """Whether the finding's CWE rolls up to Use of Hard-coded Credentials.""" - return cwe.catalog.category_of.get(cwe.id_number(finding["cwe_id"])) == CREDENTIALS + return is_credential_cwe(cwe.id_number(finding["cwe_id"])) -def withheld(finding: Finding) -> Finding: +def withheld(finding: Record) -> Record: """`finding` as the products carry it: a hard-coded credential's snippet is empty.""" return {**finding, "snippet": ""} if is_credential(finding) else finding diff --git a/plugins/claude-security/scripts/lib/source.py b/plugins/claude-security/scripts/lib/source.py new file mode 100644 index 00000000..fe7fa2a3 --- /dev/null +++ b/plugins/claude-security/scripts/lib/source.py @@ -0,0 +1,94 @@ +"""A scanned file a finding names: reading it, and finding the line that places the finding.""" + +from __future__ import annotations + +import re +from bisect import bisect_right +from itertools import accumulate +from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Sequence + + +def read(scan_root: str, file: str) -> str | None: + """The text of `file`, relative to `scan_root`; None when it cannot be read.""" + try: + return Path(scan_root, file).read_bytes().decode("utf-8", "surrogateescape") + except (OSError, ValueError): + return None + + +def placed_line(text: str | None, line: int, snippet: str) -> int: + """The 1-based line of `text` that places a finding declaring `line` and quoting `snippet`. + + `text` is the text of the finding's file, None when it was not read; the + declared `line` comes back unchanged then, and when no line of the file + places the finding (placing_row). + """ + if text is None: + return line + row = placing_row(normalized_lines(text), line, snippet) + return line if row is None else row + 1 + + +def normalized_lines(source: str) -> list[str]: + """A file's lines, split on the newline alone, each with its whitespace normalized.""" + return [" ".join(each.split()) for each in source.split("\n")] + + +def quoted_lines(text: str, snippet: str, *, whole: bool) -> set[int]: + """Every 1-based line of `text` on which the quoted `snippet` occurs, whitespace aside. + + With `whole`, only occurrences that are entire lines of `text` count, so a + quote of part of a line matches nothing. + """ + lines = normalized_lines(text) + quoted = " ".join(snippet.split()) + spans = [ + (first, last) + for first, last in occurrences(lines, quoted) + if not whole or " ".join(filter(None, lines[first : last + 1])) == quoted + ] + return {row + 1 for first, last in spans for row in range(first, last + 1)} + + +def placing_span(lines: Sequence[str], line: int, snippet: str) -> tuple[int, int] | None: + """The (first, last) rows of the occurrence of `snippet` nearest the declared line, or None.""" + declared = line - 1 + return min( + occurrences(lines, " ".join(snippet.split())), + key=lambda span: abs(min(max(declared, span[0]), span[1]) - declared), + default=None, + ) + + +def placing_row(lines: Sequence[str], line: int, snippet: str) -> int | None: + """The index into the normalized `lines` of the one placing a finding; None when none does. + + The finding is placed on the line nearest its declared `line` where + `snippet`, the code it quotes, appears, whitespace aside, and on the + declared line itself when it appears nowhere. + """ + declared = line - 1 + span = placing_span(lines, line, snippet) + at = declared if span is None else min(max(declared, span[0]), span[1]) + return at if 0 <= at < len(lines) else None + + +def occurrences(lines: Sequence[str], quoted: str) -> list[tuple[int, int]]: + """The (first, last) index into the normalized `lines` of each occurrence of `quoted`.""" + if not quoted: + return [] + filled = [row for row, line in enumerate(lines) if line] + starts = list(accumulate((len(lines[row]) + 1 for row in filled), initial=0)) + flat = " ".join(lines[row] for row in filled) + + def row_at(offset: int) -> int: + return filled[bisect_right(starts, offset) - 1] + + return [ + (row_at(found.start()), row_at(found.end() - 1)) + for found in re.finditer(re.escape(quoted), flat) + ] diff --git a/plugins/claude-security/scripts/lib/strictjson.py b/plugins/claude-security/scripts/lib/strictjson.py index 2c5a9900..91d4ee30 100644 --- a/plugins/claude-security/scripts/lib/strictjson.py +++ b/plugins/claude-security/scripts/lib/strictjson.py @@ -16,7 +16,7 @@ from collections.abc import Mapping from typing import TYPE_CHECKING, NoReturn, cast if TYPE_CHECKING: - import os + from pathlib import Path from typing import TypeGuard JsonMap = Mapping[str, object] @@ -65,9 +65,9 @@ def _finite(digits: str) -> float: return value -def load(path: str | os.PathLike[str]) -> object: +def load(path: Path) -> object: """The JSON value in `path`; OSError if unreadable, ValueError if not strict JSON.""" - with open(path, encoding="utf-8") as handle: + with path.open(encoding="utf-8") as handle: try: return cast("object", json.load(handle, parse_constant=_refuse, parse_float=_finite)) except RecursionError as error: diff --git a/plugins/claude-security/scripts/patch_artifacts.py b/plugins/claude-security/scripts/patch_artifacts.py index 73ef5149..ad5248f1 100755 --- a/plugins/claude-security/scripts/patch_artifacts.py +++ b/plugins/claude-security/scripts/patch_artifacts.py @@ -27,19 +27,19 @@ from __future__ import annotations import argparse import os -import pathlib import re import shlex import shutil import stat import subprocess import sys +from pathlib import Path from typing import TYPE_CHECKING, TypedDict # The lib/ package lives next to this script. Python normally adds a script's own # directory to the import path, but not under -P or PYTHONSAFEPATH, so we add it here. -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from lib import console, plugin, strictjson +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from lib import absolute, console, plugin, strictjson from lib.strictjson import JsonMap, is_list, is_map, is_str if TYPE_CHECKING: @@ -233,11 +233,10 @@ def build_unit(item: object, index: int) -> Unit: ) -def load_units(patch_dir: str) -> list[Unit]: +def load_units(patch_dir: Path) -> list[Unit]: """Read and validate patches.json (an object with a `units` array).""" - path = os.path.join(patch_dir, "patches.json") try: - raw = strictjson.load(path) + raw = strictjson.load(patch_dir / "patches.json") except OSError as error: msg = "patches.json is missing from the patch directory. Write it before running this." raise PatchError(msg) from error @@ -258,13 +257,13 @@ def load_units(patch_dir: str) -> list[Unit]: return units -def read_diff(patch_dir: str, unit_id: str, required: bool) -> bytes | None: +def read_diff(patch_dir: Path, unit_id: str, required: bool) -> bytes | None: """The raw diff git wrote for this unit; None only if absent and optional. A required one (a written patch) must exist and hold at least one `diff --git` section, since the patch and its diffstat are built from it. """ - path = os.path.join(patch_dir, f"{unit_id}.diff") + path = patch_dir / f"{unit_id}.diff" if not os.path.isfile(path): if required: msg = ( @@ -274,7 +273,7 @@ def read_diff(patch_dir: str, unit_id: str, required: bool) -> bytes | None: ) raise PatchError(msg) return None - data = pathlib.Path(path).read_bytes() + data = path.read_bytes() if required and DIFF_HEADER.encode("ascii") not in data: msg = f"{unit_id}.diff contains no '{DIFF_HEADER.strip()}' header; it is not a git diff" raise PatchError(msg) @@ -369,7 +368,7 @@ def git_toplevel(scan_root: str) -> str | None: return top or None -def apply_check(top: str | None, patch_path: str) -> str: +def apply_check(top: str | None, patch_path: Path) -> str: """`git apply --check` against the user's tree: 'clean', 'conflicts: ...', or 'not_run'.""" if top is None: return "not_run" @@ -589,55 +588,42 @@ def jsonl( return "\n".join(rows) + ("\n" if rows else "") -def clear_stale_products(patches_dir: str, produced: set[str]) -> list[str]: +def clear_stale_products(patches_dir: Path, produced: set[str]) -> list[str]: """Remove F<n>.patch / F<n>.md files an earlier run left that this run did not write. Only the script's own product names (F<n>.patch, F<n>.md) are removed; every other file in the folder is left alone. """ removed: list[str] = [] - for name in sorted(os.listdir(patches_dir)): - stem, dot, ext = name.rpartition(".") - if not dot or ext not in {"patch", "md"} or not FINDING_ID_RE.match(stem): + for path in sorted(patches_dir.iterdir()): + if path.suffix not in {".patch", ".md"} or not FINDING_ID_RE.match(path.stem): continue - if name in produced: + if path.name in produced or os.path.isdir(path): continue - path = os.path.join(patches_dir, name) - if os.path.isdir(path): - continue - os.unlink(path) - removed.append(name) + path.unlink() + removed.append(path.name) return removed -def ensure_gitignore(report_dir: str) -> str: +def ensure_gitignore(report_dir: Path) -> str: """Fence the report directory with a `*` .gitignore if it has none. Returns "written" when the fence was just added, "present" when an existing .gitignore already ignores everything, and "open" when one exists but has no bare `*` line; an existing file is never rewritten. """ - path = os.path.join(report_dir, ".gitignore") + path = report_dir / ".gitignore" if os.path.lexists(path): try: - existing = pathlib.Path(path).read_text(encoding="utf-8", errors="replace") + existing = path.read_text(encoding="utf-8", errors="replace") except OSError: return "open" return "present" if "*" in (line.strip() for line in existing.splitlines()) else "open" - with open(path, "w", encoding="utf-8", newline="\n") as out: - out.write("*\n") + path.write_bytes(b"*\n") return "written" -def contained_relpath(target: str, root: str) -> str | None: - """`target` as a path from `root`, or None when it does not sit inside root.""" - rel = os.path.relpath(os.path.realpath(target), os.path.realpath(root)) - if rel == ".." or rel.startswith(".." + os.sep) or os.path.isabs(rel): - return None - return rel.replace(os.sep, "/") - - -def report_path_from_root(report_dir: str, top: str | None, fallback: str) -> str: +def report_path_from_root(report_dir: Path, top: str | None, fallback: str) -> str: """The report directory as a path from the repository root, for the apply command. Falls back to the bare folder name when git cannot name a root or the @@ -645,35 +631,35 @@ def report_path_from_root(report_dir: str, top: str | None, fallback: str) -> st """ if top is None: return fallback - return contained_relpath(report_dir, top) or fallback + return absolute.relative(os.path.realpath(report_dir), os.path.realpath(top)) or fallback -def resolve_report_dir(patches_dir: str) -> tuple[str, str]: +def resolve_report_dir(patches_dir: Path) -> Path: """The report directory holding `patches_dir`, validated by name.""" - patches_abs = os.path.abspath(patches_dir) - report_dir = os.path.dirname(patches_abs) - report_dir_name = os.path.basename(report_dir) - if os.path.basename(patches_abs) != PATCHES_DIR_NAME: + # abspath folds ".." without following symlinks, so the checks below see this path's own names. + patches_abs = Path(os.path.abspath(patches_dir)) + report_dir = patches_abs.parent + if patches_abs.name != PATCHES_DIR_NAME: msg = ( f"patches dir must be a directory named {PATCHES_DIR_NAME!r} inside the " f"report directory; got {patches_abs}" ) raise PatchError(msg) - if not REPORT_DIR_RE.match(report_dir_name): + if not REPORT_DIR_RE.match(report_dir.name): msg = ( "patches dir must live inside a CLAUDE-SECURITY-<timestamp> report " - f"directory; its parent is {report_dir_name!r}. Refusing rather than " + f"directory; its parent is {report_dir.name!r}. Refusing rather than " "fence the wrong directory with a .gitignore." ) raise PatchError(msg) - return report_dir, report_dir_name + return report_dir -def run(patch_dir: str, patches_dir: str, scan_root: str, base: str) -> int: +def run(patch_dir: Path, patches_dir: Path, scan_root: str, base: str) -> int: units = load_units(patch_dir) - report_dir, report_dir_name = resolve_report_dir(patches_dir) + report_dir = resolve_report_dir(patches_dir) top = git_toplevel(scan_root) - report_ref = shlex.quote(report_path_from_root(report_dir, top, report_dir_name)) + report_ref = shlex.quote(report_path_from_root(report_dir, top, report_dir.name)) stats_by_id: dict[str, list[DiffStat] | None] = {} checks: dict[str, str] = {} produced: set[str] = set() @@ -683,9 +669,9 @@ def run(patch_dir: str, patches_dir: str, scan_root: str, base: str) -> int: stats = numstat(diff) if diff is not None else None stats_by_id[unit["id"]] = stats if written and diff is not None: - patch_path = os.path.join(patches_dir, f"{unit['id']}.patch") + patch_path = patches_dir / f"{unit['id']}.patch" header = header_comment(unit, base, report_ref) - pathlib.Path(patch_path).write_bytes(header.encode("utf-8") + diff) + patch_path.write_bytes(header.encode() + diff) check = apply_check(top, patch_path) checks[unit["id"]] = check note = note_written(unit, stats, check, report_ref) @@ -694,16 +680,11 @@ def run(patch_dir: str, patches_dir: str, scan_root: str, base: str) -> int: else: note = note_declined(unit, stats) print(f"{unit['id']}: no patch ({unit['status']}) -> {unit['id']}.md") - note_path = os.path.join(patches_dir, f"{unit['id']}.md") - with open(note_path, "w", encoding="utf-8", newline="\n") as out: - out.write(note) + (patches_dir / f"{unit['id']}.md").write_bytes(note.encode()) produced.add(f"{unit['id']}.md") - index_path = os.path.join(patches_dir, "PATCHES.md") - with open(index_path, "w", encoding="utf-8", newline="\n") as out: - out.write(index_markdown(units, base, report_dir_name, report_ref)) - jsonl_path = os.path.join(patches_dir, "patches.jsonl") - with open(jsonl_path, "w", encoding="utf-8", newline="\n") as out: - out.write(jsonl(units, base, stats_by_id, checks)) + index = index_markdown(units, base, report_dir.name, report_ref) + (patches_dir / "PATCHES.md").write_bytes(index.encode()) + (patches_dir / "patches.jsonl").write_bytes(jsonl(units, base, stats_by_id, checks).encode()) for name in clear_stale_products(patches_dir, produced): print(f"removed stale {name} (not produced by this run)") swept, warnings = remove_workspaces_in(patch_dir) @@ -731,24 +712,22 @@ def run(patch_dir: str, patches_dir: str, scan_root: str, base: str) -> int: return 0 -def refuse_reason(path: str) -> str | None: +def refuse_reason(path: Path) -> str | None: """Why `path` may NOT be deleted as a scratch workspace, or None when it may. Only `<report>/.claude-security-run/patch-<ts>/scratch-F<n>` holding its own `.git` may be deleted; every other shape is refused. """ - leaf = os.path.normpath(os.path.abspath(path)) + leaf = Path(os.path.abspath(path)) if not os.path.isdir(leaf): return "it is not a directory" - if not SCRATCH_NAME_RE.match(os.path.basename(leaf)): + if not SCRATCH_NAME_RE.match(leaf.name): return "its name is not scratch-F<n>" - run = os.path.dirname(leaf) - top = os.path.dirname(run) - if not PATCH_DIR_RE.match(os.path.basename(run)): + if not PATCH_DIR_RE.match(leaf.parent.name): return "it is not inside a patch-<timestamp> run directory" - if os.path.basename(top) != plugin.RUN_DIR_NAME: + if leaf.parents[1].name != plugin.RUN_DIR_NAME: return f"its run directory is not inside {plugin.RUN_DIR_NAME}/" - if not os.path.isdir(os.path.join(leaf, ".git")): + if not os.path.isdir(leaf / ".git"): return "it holds no .git directory of its own" return None @@ -762,26 +741,25 @@ def clear_readonly( # Git writes read-only objects, which Windows will not delete. if func not in {os.unlink, os.rmdir}: raise exc_info[1] - os.chmod(path, stat.S_IWRITE) + Path(path).chmod(stat.S_IWRITE) func(path) -def remove_workspace(path: str) -> None: +def remove_workspace(path: Path) -> None: """Delete one scratch workspace, refusing anything off the fenced layout.""" reason = refuse_reason(path) if reason is not None: - msg = f"refusing to remove {path!r}: {reason}" + msg = f"refusing to remove '{path}': {reason}" raise PatchError(msg) - target = os.path.normpath(os.path.abspath(path)) try: - shutil.rmtree(target, onerror=clear_readonly) + shutil.rmtree(os.path.abspath(path), onerror=clear_readonly) except OSError as error: detail = console.removal_failure_detail(error) - msg = f"could not remove {path!r}: {detail}" + msg = f"could not remove '{path}': {detail}" raise PatchError(msg) from error -def remove_workspaces_in(patch_dir: str) -> tuple[list[str], list[str]]: +def remove_workspaces_in(patch_dir: Path) -> tuple[list[str], list[str]]: """Remove every scratch workspace in a patch run directory. Returns (removed names, warnings). Never raises: a workspace that cannot @@ -790,43 +768,42 @@ def remove_workspaces_in(patch_dir: str) -> tuple[list[str], list[str]]: removed: list[str] = [] warnings: list[str] = [] try: - names = sorted(os.listdir(patch_dir)) + paths = sorted(patch_dir.iterdir()) except OSError as error: - return removed, [f"could not list {patch_dir!r}: {error}"] - for name in names: - if not name.startswith("scratch-"): + return removed, [f"could not list '{patch_dir}': {error}"] + for path in paths: + if not path.name.startswith("scratch-"): continue - path = os.path.join(patch_dir, name) try: remove_workspace(path) except PatchError as error: warnings.append(str(error)) else: - removed.append(name) + removed.append(path.name) return removed, warnings -def remove_patch_run(patch_dir: str) -> tuple[list[str], list[str]]: +def remove_patch_run(patch_dir: Path) -> tuple[list[Path], list[str]]: """Remove a finished patch run directory, and its run directory if now empty. Returns (removed paths, warnings). Never raises; only the recipe's own `<report>/.claude-security-run/patch-<ts>` layout is deleted. """ - removed: list[str] = [] - target = os.path.normpath(os.path.abspath(patch_dir)) - run_dir = os.path.dirname(target) - if not PATCH_DIR_RE.match(os.path.basename(target)): - return removed, [f"left {patch_dir!r} in place: its name is not patch-<timestamp>"] - if os.path.basename(run_dir) != plugin.RUN_DIR_NAME: - return removed, [f"left {patch_dir!r} in place: it is not inside {plugin.RUN_DIR_NAME}/"] + removed: list[Path] = [] + target = Path(os.path.abspath(patch_dir)) + run_dir = target.parent + if not PATCH_DIR_RE.match(target.name): + return removed, [f"left '{patch_dir}' in place: its name is not patch-<timestamp>"] + if run_dir.name != plugin.RUN_DIR_NAME: + return removed, [f"left '{patch_dir}' in place: it is not inside {plugin.RUN_DIR_NAME}/"] try: - shutil.rmtree(target, onerror=clear_readonly) + shutil.rmtree(str(target), onerror=clear_readonly) except OSError as error: detail = console.removal_failure_detail(error) - return removed, [f"could not remove {patch_dir!r}: {detail}"] + return removed, [f"could not remove '{patch_dir}': {detail}"] removed.append(target) try: - os.rmdir(run_dir) + run_dir.rmdir() except OSError: return removed, [] removed.append(run_dir) @@ -838,7 +815,7 @@ def main(argv: list[str]) -> int: if len(argv) != 2: die_usage("--remove-scratch takes exactly one workspace path") try: - remove_workspace(argv[1]) + remove_workspace(Path(argv[1])) except PatchError as error: die(str(error)) print(f"removed workspace {argv[1]!r}") @@ -847,6 +824,7 @@ def main(argv: list[str]) -> int: prog="patch_artifacts.py", description="Render suggested-fix patch files and notes from a patch run directory.", epilog="Also: --remove-scratch <workspace> deletes one fenced scratch workspace.", + allow_abbrev=False, ) parser.add_argument("patch_dir", help="the patch run dir holding patches.json and F<n>.diff") parser.add_argument("patches_dir", help="the report's patches/ directory to write into") @@ -859,7 +837,7 @@ def main(argv: list[str]) -> int: if not plugin.SHA_RE.match(args.base): die_usage(f"--base {args.base!r} is not a hex revision id") try: - return run(args.patch_dir, args.patches_dir, args.scan_root, args.base) + return run(Path(args.patch_dir), Path(args.patches_dir), args.scan_root, args.base) except PatchError as error: die(str(error)) except OSError as error: diff --git a/plugins/claude-security/scripts/render_report.py b/plugins/claude-security/scripts/render_report.py index c81c7415..c00a8218 100755 --- a/plugins/claude-security/scripts/render_report.py +++ b/plugins/claude-security/scripts/render_report.py @@ -5,21 +5,25 @@ Writes CLAUDE-SECURITY-RESULTS.jsonl (one finding per line, fields in a fixed order), CLAUDE-SECURITY-RESULTS.sarif (the same findings as a SARIF 2.1.0 log) and the CLAUDE-SECURITY-REVISION-<tag>.json stamp, places the report markdown beside them, then removes the scan's run directory now that its records are -rendered. Findings that name one rule at one line of a file are one record in -every product (see one_per_site). Filenames, JSONL field order, and -verification.status semantics are stable across releases. +rendered. Each finding sits at the line of its file its quoted code is on and +carries an id computed from the file there, and findings that name one rule +at one line of a file are one record in every product (see one_per_site). +Filenames, JSONL field order, and verification.status semantics are stable +across releases. Usage: render_report.py <run_dir> [--products-dir <dir>] Exits 0 on success, 1 on a refusal naming what is wrong, 2 on a usage error. +A finding whose path cannot be carried is refused by name instead: the render +still exits 0, delivers the products without it, and marks the stamp +unverified (see verification.refused_findings). Python 3.9-compatible, stdlib only. """ from __future__ import annotations import argparse -import ntpath import os import re import shutil @@ -33,7 +37,8 @@ from typing import TYPE_CHECKING, NamedTuple, TypedDict # The lib/ package lives next to this script. Python normally adds a script's own # directory to the import path, but not under -P or PYTHONSAFEPATH, so we add it here. sys.path.insert(0, str(Path(__file__).resolve().parent)) -from lib import absolute, console, cwe, plugin, sarif, secret, strictjson +from lib import absolute, console, cwe, plugin, sarif, secret, source, strictjson +from lib.chain import chain_of, pending_ranks from lib.finding import ( CONFIDENCES, PANEL_KEEP_QUORUM, @@ -41,8 +46,11 @@ from lib.finding import ( SEVERITIES, Finding, FindingError, + FindingPathError, + Record, build_finding, panel_complete, + scan_prefix_shaped, ) from lib.strictjson import JsonMap, is_int, is_list, is_map, is_str @@ -57,7 +65,18 @@ class _ResearcherCounts(TypedDict, total=False): researchers_returned: int -class VerificationSummary(_ResearcherCounts): +class _RefusalRecord(TypedDict): + id: str + reason: str + + +class _RefusedFindings(TypedDict, total=False): + """The refusals a render may add; absent entirely when every finding carried.""" + + refused_findings: list[_RefusalRecord] + + +class VerificationSummary(_ResearcherCounts, _RefusedFindings): """The stamp's `verification` object; every path names why if not verified.""" status: str @@ -70,6 +89,7 @@ class VerificationSummary(_ResearcherCounts): incomplete_panel_candidates: int attested_findings: int reason: str | None + reason_kind: str | None class Meta(NamedTuple): @@ -86,19 +106,18 @@ class Meta(NamedTuple): class Rendered(NamedTuple): """A completed render: the findings, their verification, and the stamp's tag.""" - findings: list[Finding] + findings: list[Record] verification: VerificationSummary tag: str REVISION_PREFIX = "CLAUDE-SECURITY-REVISION-" +STAMP_ONLY = frozenset({"duration_s", "verification_runs", "reason_kind"}) JSONL_NAME = "CLAUDE-SECURITY-RESULTS.jsonl" SARIF_NAME = "CLAUDE-SECURITY-RESULTS.sarif" SANITIZED_REMOTE_RE = re.compile( r"https://[a-z0-9.-]+(?::[0-9]+)?/(?:[A-Za-z0-9._~/-]|%[0-9A-F]{2})+\Z" ) -# Set only by workflows/scan.js (its PROVENANCE) on each vote record it computes. -VOTES_PROVENANCE = "workflows/scan.js" class Args(argparse.Namespace): @@ -112,10 +131,10 @@ class RenderError(Exception): """A refusal; the message names what the caller must fix.""" -def read_json(run_dir: str, name: str) -> object: +def read_json(run_dir: Path, name: str) -> object: """The JSON value in a run file the render requires; a missing or malformed one is a refusal.""" try: - return strictjson.load(os.path.join(run_dir, name)) + return strictjson.load(run_dir / name) except FileNotFoundError as error: msg = f"{name} is missing from the run directory. Write it before running this script." raise RenderError(msg) from error @@ -124,10 +143,10 @@ def read_json(run_dir: str, name: str) -> object: raise RenderError(msg) from error -def read_votes(run_dir: str) -> JsonMap | None: +def read_votes(run_dir: Path) -> JsonMap | None: """The workflow's vote record, or None when votes.json is absent or not marked as its own.""" try: - raw = strictjson.load(os.path.join(run_dir, "votes.json")) + raw = strictjson.load(run_dir / "votes.json") except FileNotFoundError: return None except ValueError as error: @@ -135,20 +154,12 @@ def read_votes(run_dir: str) -> JsonMap | None: raise RenderError(msg) from error if not is_map(raw): raise RenderError("votes.json must be a JSON object mapping the vote record") - if raw.get("provenance") != VOTES_PROVENANCE: + if raw.get("provenance") != plugin.VOTES_PROVENANCE: return None return raw -def read_source(scan_root: str, file: str) -> str | None: - """The text of a scanned file a finding names; None when it cannot be read.""" - try: - return Path(scan_root, file).read_bytes().decode("utf-8", "surrogateescape") - except (OSError, ValueError): - return None - - -def read_coverage(run_dir: str) -> tuple[JsonMap | None, str]: +def read_coverage(run_dir: Path) -> tuple[JsonMap | None, str]: """The optional coverage.json for the informational run_shape field. Returns (map_or_None, source): source is "coverage.json" when the file @@ -157,7 +168,7 @@ def read_coverage(run_dir: str) -> tuple[JsonMap | None, str]: """ name = "coverage.json" try: - raw = strictjson.load(os.path.join(run_dir, name)) + raw = strictjson.load(run_dir / name) except FileNotFoundError: return None, "unavailable" except (OSError, ValueError): @@ -184,14 +195,15 @@ def coverage_texts(raw: object, cap: int) -> list[str]: def tree_relative(path: str, scan_root: str) -> str | None: - """A skipped path relative to the scan root; None for an absolute one that is not inside it.""" + """A skipped path relative to the scan root; None for an absolute spelling of anything else.""" if not absolute.spelled(path): return path + if not os.path.isabs(path): + return None try: - relative = os.path.relpath(os.path.realpath(path), scan_root).replace("\\", "/") + return absolute.relative(os.path.realpath(path), scan_root) except (ValueError, OSError): return None - return None if relative == ".." or relative.startswith("../") else relative def skipped_component(item: JsonMap, scan_root: str) -> dict[str, object]: @@ -220,8 +232,49 @@ def coverage_count(value: object) -> int | None: return value if is_int(value) else None +class ResearchCoverage(TypedDict): + """The stamp's research_coverage: the coverage account's counts, and whether a list was cut.""" + + files: int + read: int + not_reached: int + unaccounted: int + outside_components: int + capped: bool + + +def research_coverage(raw: object) -> ResearchCoverage | None: + """coverage.research as the stamp carries it, or None when the account was not checked.""" + tree = raw.get("tree") if is_map(raw) else None + if not is_map(raw) or not is_map(tree): + return None + files, read, not_reached, unaccounted, outside = ( + tree.get(key) for key in ("files", "read", "notReached", "unaccounted", "outsideComponents") + ) + if not ( + is_int(files) + and is_int(read) + and is_int(not_reached) + and is_int(unaccounted) + and is_int(outside) + ): + return None + return { + "files": files, + "read": read, + "not_reached": not_reached, + "unaccounted": unaccounted, + "outside_components": outside, + "capped": raw.get("capped") is True, + } + + def run_shape( - coverage: JsonMap | None, source: str, effort: object, scan_root: str + coverage: JsonMap | None, + source: str, + effort: object, + scan_root: str, + research: ResearchCoverage | None, ) -> dict[str, object]: """What shape actually ran, distinct from the effort tier that was asked.""" shape: dict[str, object] = {"requested_effort": effort, "collapsed": None, "source": source} @@ -236,6 +289,7 @@ def run_shape( "empty_diff": bool(coverage.get("emptyDiff")), "empty_scope": bool(coverage.get("emptyScope")), "researchers_dispatched": coverage_count(coverage.get("researchersDispatched")), + "verification_runs": coverage_count(coverage.get("verificationRun")), "skipped_components": skipped_components(coverage.get("skippedComponents"), scan_root), "completeness_check_outcome": coverage_enum( coverage.get("completenessCheckOutcome"), @@ -247,21 +301,43 @@ def run_shape( ("inventory-failed", "empty-partition", "incomplete-partition"), ), "top_level_dir_count": coverage_count(coverage.get("topLevelCount")), + "target_files": coverage_count(coverage.get("targetFiles")), + "component_cap": coverage_count(coverage.get("componentCap")), + "research_coverage": research, } +def handed_on(votes: JsonMap) -> int: + """How many candidates the vote record's chain leaves to a run that did not complete.""" + raw = votes.get("chain") + if raw is None: + return 0 + try: + parsed = chain_of(raw) + except ValueError as error: + msg = f"votes.json chain {error}; the vote record is malformed" + raise RenderError(msg) from error + return len(pending_ranks(parsed)) + + def verification_summary( - findings: list[Finding], + findings: Sequence[Finding], votes: JsonMap, votes_present: bool = True, + continuing: int = 0, + refused: Sequence[_RefusalRecord] = (), ) -> VerificationSummary: - """Compute the stamp's verification object from the vote record. + """Compute the stamp's verification object from the vote record and the render's refusals. status is 'verified' only when the vote record proves a complete panel round for every finding the report contains and for every other candidate - it holds a round for; otherwise 'unverified' with a `reason`. + it holds a round for, and the render refused nothing; otherwise + 'unverified' with a `reason` in prose and a fixed `reason_kind` word. `incomplete_panel_candidates` counts the unreported candidates whose round - is not complete. votes_present is False when read_votes returned None. + is not complete. votes_present is False when read_votes returned None; + `continuing` is handed_on(votes), the candidates left to a verification run + that did not complete. `refused` lists the findings the render refused, + which the summary repeats under `refused_findings`. """ raw_rounds = votes.get("rounds") rounds: JsonMap = raw_rounds if is_map(raw_rounds) else {} @@ -291,45 +367,66 @@ def verification_summary( dispatched = as_count("researchers_dispatched") if "researchers_dispatched" in votes else None returned = as_count("researchers_returned") if "researchers_returned" in votes else None + kind: str | None = None reason: str | None = None if not votes_present: + kind = "no-vote-record" reason = ( "votes.json is absent from the run directory or is not the scan workflow's record: " "the verification pipeline left no vote record, so nothing about this report can " "be attested" ) elif "candidates" not in votes: + kind = "no-candidate-count" reason = ( "votes.json has no 'candidates' field: the vote record does not prove the pipeline " "ran, so nothing about this report can be attested" ) elif dispatched and returned == 0: + kind = "nothing-examined" reason = ( f"{dispatched} research agent(s) were dispatched but none returned; the scan " "examined nothing" ) elif incomplete: + kind = "finding-panel-incomplete" reason = ( f"these findings have no complete {PANEL_VOTER_COUNT}-voter panel round: " f"{', '.join(incomplete)}" ) elif findings and quorum != len(findings): + kind = "finding-below-quorum" reason = ( f"{len(findings) - quorum} of {len(findings)} reported findings did not reach the " "keep quorum, so the report contains findings the panel rejected" ) elif not findings and not rounds and candidates: + kind = "candidates-not-paneled" reason = f"{candidates} candidates were recorded but none was paneled" elif not findings and rounds and not any(map(panel_complete, rounds.values())): + kind = "no-panel-completed" reason = ( f"{len(rounds)} panel round(s) were dispatched but none completed a full " f"{PANEL_VOTER_COUNT}-voter review; no candidate was actually verified" ) elif dropped_incomplete: + kind = "candidate-panel-incomplete" reason = ( f"{len(dropped_incomplete)} candidate(s) were dropped without a complete " f"{PANEL_VOTER_COUNT}-voter panel round: {', '.join(dropped_incomplete)}" ) + elif continuing: + kind = "continuation-incomplete" + reason = continuation_text(continuing) + refusals = list(refused) + if refusals: + names = ", ".join(record["id"] for record in refusals) + refusal_reason = ( + f"{len(refusals)} finding(s) were refused at render and are absent " + f"from this report: {names}" + ) + reason = f"{reason}; {refusal_reason}" if reason else refusal_reason + kind = kind or "findings-refused" summary: VerificationSummary = { "status": "verified" if reason is None else "unverified", "candidates": candidates, @@ -341,11 +438,14 @@ def verification_summary( "incomplete_panel_candidates": len(dropped_incomplete), "attested_findings": 0, "reason": reason, + "reason_kind": kind, } if dispatched is not None: summary["researchers_dispatched"] = dispatched if returned is not None: summary["researchers_returned"] = returned + if refusals: + summary["refused_findings"] = refusals return summary @@ -363,18 +463,6 @@ def revision_tag(revision: object) -> str: return sha[:12] + ("" if revision.get("dirty") is False else "-dirty") -def show_prefix_shaped(prefix: str) -> bool: - """Whether `prefix` is what `git rev-parse --show-prefix` prints: empty, or `a/b/`.""" - if not prefix: - return True - return ( - prefix.endswith("/") - and "\\" not in prefix - and not ntpath.splitdrive(prefix)[0] - and all(segment not in {"", ".", ".."} for segment in prefix.split("/")[:-1]) - ) - - def scan_of(meta: JsonMap) -> Meta: """The scan meta the run records, every field shape-checked; a wrong one is a refusal.""" scan_id = meta.get("scan_id") @@ -399,7 +487,7 @@ def scan_of(meta: JsonMap) -> Meta: prefix = meta.get("scan_prefix") if prefix is None: prefix = "" - if not is_str(prefix) or not show_prefix_shaped(prefix): + if not is_str(prefix) or not scan_prefix_shaped(prefix): msg = ( f"scan-meta.json scan_prefix {prefix!r} is not a path prefix; rerun write_scan_meta.py" ) @@ -444,7 +532,21 @@ def scan_of(meta: JsonMap) -> Meta: return Meta(scan, scan_root, revision, revision_source, meta.get("model"), meta.get("effort")) -def jsonl_text(findings: Sequence[Finding]) -> str: +def elapsed_seconds(started_at: object, now: datetime) -> int | None: + """Whole seconds from scan-meta.json's started_at to now, floored at 0. + + None when started_at is absent, unparseable or timezone-naive. + """ + if not is_str(started_at): + return None + try: + started = datetime.fromisoformat(started_at) + except ValueError: + return None + return max(int((now - started).total_seconds()), 0) if started.tzinfo else None + + +def jsonl_text(findings: Sequence[Record]) -> str: """The findings as JSONL: one record per line as the products carry it, findings.json order.""" return "".join(strictjson.text(secret.withheld(item)) + "\n" for item in findings) @@ -454,9 +556,7 @@ def strength(finding: Finding) -> tuple[int, int]: return -SEVERITIES.index(finding["severity"]), CONFIDENCES.index(finding["confidence"]) -def one_per_site( - findings: Sequence[Finding], scan: sarif.Scan, sources: Mapping[str, str] -) -> tuple[list[Finding], list[str]]: +def one_per_site(findings: Sequence[Record], scan: sarif.Scan) -> tuple[list[Record], list[str]]: """The findings reduced to one per site, and one disclosure sentence per finding merged away. A site is a rule at a line of a file (sarif.site), which is what a result @@ -466,8 +566,8 @@ def one_per_site( named in a sentence with the finding it was merged into. A finding with no site, one whose line was never determined, is kept as it is. """ - sites = [sarif.site(item, scan, sources.get(item["file"])) for item in findings] - by_site: dict[sarif.Site, list[Finding]] = {} + sites = [sarif.site(item, scan) for item in findings] + by_site: dict[sarif.Site, list[Record]] = {} for item, where in zip(findings, sites): if where is not None: by_site.setdefault(where, []).append(item) @@ -497,19 +597,30 @@ def unrecognized_cwes(findings: Sequence[Finding]) -> list[str]: ] +def continuation_text(continuing: int) -> str: + """The sentence the stamp's reason and the log's notification share for an unfinished chain.""" + return f"{continuing} candidate(s) were handed to a verification run that did not complete" + + def notifications_of( shape: Mapping[str, object], + research: ResearchCoverage | None, verification: VerificationSummary, merged: Sequence[str], unrecognized: Sequence[str], symlinks: Sequence[str], revision: object, + continuing: int, + refused: Sequence[_RefusalRecord], ) -> list[dict[str, object]]: - """The invocation notifications: what was skipped, capped, merged, mislabeled or unverified. + """The invocation notifications: skipped, capped, merged, mislabeled, refused or unverified. - The sentences of `merged` (one_per_site) are disclosed at level note, those + `research` is research_coverage's. The sentences of `merged` (one_per_site) + are disclosed at level note, those of `unrecognized` (unrecognized_cwes) at level warning. `symlinks` names - the root-level symbolic links the scan's extent left out unfollowed. + the root-level symbolic links the scan's extent left out unfollowed; + `continuing` is handed_on(votes); `refused` is the render's per-finding + path refusals, each disclosed at level warning. """ note = sarif.notification skipped = shape.get("skipped_components") @@ -534,6 +645,16 @@ def notifications_of( names = ", ".join(symlinks) text = f"Root-level symbolic links not followed, left out of the scan's extent: {names}" notes.append(note("coverage/unfollowed-symlinks", "note", text)) + if research and (research["not_reached"] or research["unaccounted"]): + floor, ceiling = ("at least ", "at most ") if research["capped"] else ("", "") + text = ( + f"Research coverage: of {research['files']} files in the components researched, " + f"{floor}{research['read']} read to a conclusion, " + f"{research['not_reached']} declared not reached, " + f"{ceiling}{research['unaccounted']} in no researcher's account; " + f"{research['outside_components']} more outside every component" + ) + notes.append(note("coverage/files-not-reached", "note", text)) if unreviewed := verification["unreviewed_candidate_sites"]: text = f"{unreviewed} candidate site(s) were recorded but never reviewed by the panel" notes.append(note("coverage/unverified-by-cap", "warning", text)) @@ -543,14 +664,41 @@ def notifications_of( f"{PANEL_VOTER_COUNT}-voter panel round" ) notes.append(note("verification/incomplete-panel", "warning", text)) + if continuing: + text = continuation_text(continuing) + notes.append(note("verification/continuation-incomplete", "warning", text)) notes += [note("finding/merged", "note", text) for text in merged] notes += [note("cwe/unrecognized", "warning", text) for text in unrecognized] + notes += [ + note( + "verification/refused-finding", + "warning", + f"Finding {record['id']} was refused at render and is absent from " + f"this report: {record['reason']}", + ) + for record in refused + ] if verification["status"] == "unverified": notes.append(note("verification/unverified", "error", verification["reason"] or "")) return notes -def render(run_dir: str, products_dir: str) -> Rendered: +def built_or_refused( + raw: object, + index: int, + rounds_by_id: JsonMap, + scan_root: str, + scan_prefix: str, + must_exist: bool, +) -> Finding | FindingPathError: + """One finding carried, or the named path refusal that kept it out of the report.""" + try: + return build_finding(raw, index, rounds_by_id, scan_root, scan_prefix, must_exist) + except FindingPathError as error: + return error + + +def render(run_dir: Path, products_dir: Path) -> Rendered: """Read the run's records, validate them, build every product, then write them, stamp last.""" meta = read_json(run_dir, "scan-meta.json") if not is_map(meta): @@ -571,11 +719,17 @@ def render(run_dir: str, products_dir: str) -> Rendered: rounds_by_id = rounds_raw scan, scan_root, revision, revision_source, model, effort = scan_of(meta) tag = revision_tag(revision) - built = [ - build_finding(raw, i, rounds_by_id, scan_root, scan.prefix, scan.mode == "scan") + + outcomes = [ + built_or_refused(raw, i, rounds_by_id, scan_root, scan.prefix, scan.mode == "scan") for i, raw in enumerate(findings_in) ] - counted = Counter(f["id"] for f in built) + built = [item for item in outcomes if not isinstance(item, FindingPathError)] + path_errors = [item for item in outcomes if isinstance(item, FindingPathError)] + refused: list[_RefusalRecord] = [ + {"id": item.finding_id, "reason": f"its file {item.wrong}"} for item in path_errors + ] + counted = Counter([f["id"] for f in built] + [record["id"] for record in refused]) repeated = sorted(finding_id for finding_id, count in counted.items() if count > 1) if repeated: msg = f"findings.json uses these finding ids more than once: {', '.join(repeated)}" @@ -583,28 +737,40 @@ def render(run_dir: str, products_dir: str) -> Rendered: sources = { path: text for path in {f["file"] for f in built} - if (text := read_source(scan_root, path)) is not None + if (text := source.read(scan_root, path)) is not None } - findings, merged = one_per_site(built, scan, sources) + refused_secrets = [e.snippet for e in path_errors if secret.is_credential_cwe(e.cwe)] + records = sarif.placed(built, scan, sources, refused_secrets=refused_secrets) + findings, merged = one_per_site(records, scan) - markdown_path = os.path.join(run_dir, "CLAUDE-SECURITY-RESULTS.md") + markdown_path = run_dir / "CLAUDE-SECURITY-RESULTS.md" if not os.path.isfile(markdown_path): raise RenderError( "CLAUDE-SECURITY-RESULTS.md is missing. Write the human-readable " "report before running this script." ) - with open(markdown_path, encoding="utf-8", newline="") as handle: - try: - markdown = handle.read() - except UnicodeDecodeError as error: - msg = f"CLAUDE-SECURITY-RESULTS.md is not valid UTF-8: {error}" - raise RenderError(msg) from error + markdown = markdown_path.read_bytes() + try: + markdown.decode("utf-8") + except UnicodeDecodeError as error: + msg = f"CLAUDE-SECURITY-RESULTS.md is not valid UTF-8: {error}" + raise RenderError(msg) from error counts = Counter(f["severity"] for f in findings) - verification = verification_summary(findings, votes, votes_present=votes_raw is not None) - shape = run_shape(coverage, coverage_source, effort, scan_root) + continuing = handed_on(votes) + verification = verification_summary( + findings, + votes, + votes_present=votes_raw is not None, + continuing=continuing, + refused=refused, + ) + research = research_coverage(coverage.get("research") if coverage else None) + shape = run_shape(coverage, coverage_source, effort, scan_root, research) + generated = datetime.now(timezone.utc).replace(microsecond=0) stamp: dict[str, object] = { - "generated_at": datetime.now(timezone.utc).replace(microsecond=0).isoformat(), + "generated_at": generated.isoformat(), + "duration_s": elapsed_seconds(meta.get("started_at"), generated), "scan_id": str(scan.id), "mode": scan.mode, "scan_prefix": scan.prefix, @@ -625,49 +791,53 @@ def render(run_dir: str, products_dir: str) -> Rendered: } jsonl = jsonl_text(findings) - run_properties = {k: v for k, v in stamp.items() if k != "model" or v is not None} + run_properties = { + key: {k: v for k, v in value.items() if k not in STAMP_ONLY} if is_map(value) else value + for key, value in stamp.items() + if key not in STAMP_ONLY and (key != "model" or value is not None) + } panels = { f["id"]: panel for f in findings if (panel := panel_complete(rounds_by_id.get(f["id"]))) } unrecognized = unrecognized_cwes(findings) - for text in merged + unrecognized: + unfinished = [continuation_text(continuing)] if continuing else [] + refusal_lines = [f"refused {error.finding_id}: {error}" for error in path_errors] + for text in merged + unrecognized + unfinished + refusal_lines: sys.stderr.write(f"render_report.py: {text}\n") symlinks = coverage_texts(meta.get("unfollowed_symlinks"), 200) - notifications = notifications_of(shape, verification, merged, unrecognized, symlinks, revision) - sarif_log = sarif.log( - findings, scan, plugin.version(), run_properties, panels, sources, notifications + notifications = notifications_of( + shape, research, verification, merged, unrecognized, symlinks, revision, continuing, refused ) + sarif_log = sarif.log(findings, scan, plugin.version(), run_properties, panels, notifications) sarif_doc = strictjson.text(sarif_log, indent=2) + "\n" - for stale in os.listdir(products_dir): - if stale.startswith(REVISION_PREFIX) and stale.endswith(".json"): - os.unlink(os.path.join(products_dir, stale)) - with open(os.path.join(products_dir, JSONL_NAME), "w", encoding="utf-8", newline="\n") as out: - out.write(jsonl) - with open(os.path.join(products_dir, SARIF_NAME), "w", encoding="utf-8", newline="\n") as out: - out.write(sarif_doc) - markdown_out = os.path.join(products_dir, "CLAUDE-SECURITY-RESULTS.md") + for stale in products_dir.iterdir(): + if stale.name.startswith(REVISION_PREFIX) and stale.suffix == ".json": + stale.unlink() + (products_dir / JSONL_NAME).write_bytes(jsonl.encode()) + (products_dir / SARIF_NAME).write_bytes(sarif_doc.encode()) + markdown_out = products_dir / "CLAUDE-SECURITY-RESULTS.md" + # realpath, not Path.resolve(): on 3.9 for Windows resolve() raises on volumes realpath accepts. relocated = os.path.realpath(markdown_path) != os.path.realpath(markdown_out) if relocated: - with open(markdown_out, "w", encoding="utf-8", newline="\n") as out: - out.write(markdown) - stamp_path = os.path.join(products_dir, f"{REVISION_PREFIX}{tag}.json") - with open(stamp_path, "w", encoding="utf-8", newline="\n") as out: - out.write(strictjson.text(stamp, indent=2) + "\n") + markdown_out.write_bytes(markdown) + stamp_path = products_dir / f"{REVISION_PREFIX}{tag}.json" + stamp_path.write_bytes((strictjson.text(stamp, indent=2) + "\n").encode()) if relocated: - os.unlink(markdown_path) + markdown_path.unlink() return Rendered(findings, verification, tag) -def remove_run_dir(run_dir: str, products_dir: str) -> str: +def remove_run_dir(run_dir: Path, products_dir: Path) -> str: """Remove the scan's run directory once rendered; returns a one-line status.""" - target = os.path.normpath(os.path.abspath(run_dir)) - if os.path.basename(target) != plugin.RUN_DIR_NAME: + # abspath folds ".." without following symlinks, so the check below sees this path's own name. + target = Path(os.path.abspath(run_dir)) + if target.name != plugin.RUN_DIR_NAME: return f"kept {run_dir} (not a {plugin.RUN_DIR_NAME} run directory)" if os.path.realpath(target) == os.path.realpath(products_dir): return f"kept {run_dir} (it holds the products)" try: - shutil.rmtree(target) + shutil.rmtree(str(target)) except OSError as error: detail = console.removal_failure_detail(error) return f"WARNING: could not remove run directory {run_dir}: {detail}" @@ -679,6 +849,7 @@ def argument_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="render_report.py", description="Render a scan's machine-readable artifacts from its run directory.", + allow_abbrev=False, ) parser.add_argument("run_dir", help="the run directory holding the scan's records") parser.add_argument( @@ -692,18 +863,19 @@ def main(argv: list[str]) -> int: args = parser.parse_args(argv, namespace=Args()) if not os.path.isdir(args.run_dir): parser.error(f"not a directory: {args.run_dir}") - products_dir = args.products_dir or args.run_dir - if not os.path.isdir(products_dir): - parser.error(f"products directory is not a directory: {products_dir}") + products = args.products_dir or args.run_dir + if not os.path.isdir(products): + parser.error(f"products directory is not a directory: {products}") + run_dir, products_dir = Path(args.run_dir), Path(products) try: - rendered = render(args.run_dir, products_dir) + rendered = render(run_dir, products_dir) except (RenderError, FindingError) as error: sys.stderr.write(f"render_report.py: {error}\n") return 1 except OSError as error: sys.stderr.write(f"render_report.py: could not read or write the report's files: {error}\n") return 1 - removal = remove_run_dir(args.run_dir, products_dir) + removal = remove_run_dir(run_dir, products_dir) count = len(rendered.findings) stamp_name = f"{REVISION_PREFIX}{rendered.tag}.json" print( diff --git a/plugins/claude-security/scripts/save_result.py b/plugins/claude-security/scripts/save_result.py new file mode 100755 index 00000000..1056c848 --- /dev/null +++ b/plugins/claude-security/scripts/save_result.py @@ -0,0 +1,489 @@ +#!/usr/bin/env python3 +"""Record a scan workflow's result in its run directory and say what to do next. + +Reads the JSON file the Claude Code runtime writes when a workflow task +completes, folds the result's findings, votes and coverage into +findings.json, votes.json and coverage.json in the run directory (appending +to an earlier run's when this result continues one), writes the candidate +files a further verification run loads, and prints one `next:` line: the +Workflow call that continues the verification, or the instruction to write +the report. Each finding is recorded at the line of its file that its quoted +code is on, with the line the researcher declared kept beside it. + +Usage: + save_result.py <output_file> <run_dir> + +Exits 0 when the result is recorded or already was, 1 when it could not be +(the `next:` line still says what to do), 2 on a usage error. +Python 3.9-compatible, stdlib only. +""" + +from __future__ import annotations + +import argparse +import os +import re +import sys +from pathlib import Path +from typing import NamedTuple + +# The lib/ package lives next to this script. Python normally adds a script's own +# directory to the import path, but not under -P or PYTHONSAFEPATH, so we add it here. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from lib import console, plugin, source, strictjson +from lib.chain import Chain, chain_of, pending_ranks +from lib.finding import ( + CONFIDENCE_RANK, + SEVERITIES, + FindingError, + file_field, + line_number, + scan_prefix_shaped, +) +from lib.strictjson import JsonMap, is_int, is_list, is_map, is_str + +# Rows per candidate file; workflows/scan.js derives each file's ranks from the same number. +CHUNK = 25 +UNACCOUNTED_ECHO_CAP = 40 +CID_RE = re.compile(r"^C([1-9][0-9]*)\Z") +WRITE_REPORT = ( + "next: write CLAUDE-SECURITY-RESULTS.md from findings.json and coverage.json per the " + "report spec, then run render_report.py" +) + + +class Records(NamedTuple): + """A scan's three records and the chain its vote record carries.""" + + findings: list[JsonMap] + votes: JsonMap + coverage: JsonMap + chain: Chain + + +class Args(argparse.Namespace): + """The parsed command line.""" + + output_file: str = "" + run_dir: str = "" + + +class NotAResultError(Exception): + """The output file holds no scan result this script can fold; the message names why.""" + + fallback: str = ( + "Write the result's findings, votes and coverage from the completion notice to " + "findings.json, votes.json and coverage.json in the run directory yourself, then " + + WRITE_REPORT[len("next: ") :] + ) + + +class CannotContinueError(Exception): + """The run directory cannot take this result; the message names why.""" + + fallback: str = "stop; nothing was recorded, so say so and name the report directory" + + +def count(record: JsonMap, key: str) -> int: + """A count the workflow wrote; anything but a non-negative integer cannot be folded.""" + value = record.get(key) + if not is_int(value) or value < 0: + msg = f"{key!r} is {value!r}, not a count" + raise CannotContinueError(msg) + return value + + +def texts(record: JsonMap, key: str) -> list[object]: + """A list the workflow wrote, empty when absent.""" + value = record.get(key) + return list(value) if is_list(value) else [] + + +def rank_of(row: JsonMap) -> int: + """A candidate row's rank, from its `cid`.""" + cid = row.get("cid") + matched = CID_RE.match(cid) if is_str(cid) else None + if not matched: + msg = f"a pending row's cid is {cid!r}, not C<rank>" + raise NotAResultError(msg) + return int(matched[1]) + + +def scan_settings(run_dir: Path) -> JsonMap: + """scan-meta.json from the run directory: the settings every run of this scan shares.""" + if run_dir.name != plugin.RUN_DIR_NAME: + msg = f"{run_dir} is not a {plugin.RUN_DIR_NAME} run directory" + raise CannotContinueError(msg) + try: + meta = strictjson.load(run_dir / "scan-meta.json") + except (OSError, ValueError) as error: + msg = f"scan-meta.json cannot be read from {run_dir}: {error}" + raise CannotContinueError(msg) from error + if not is_map(meta) or not is_str(meta.get("scan_root")): + msg = "scan-meta.json names no scan_root" + raise CannotContinueError(msg) + return meta + + +def recorded(run_dir: Path) -> Records | None: + """The scan's records as an earlier save left them; None before the first.""" + if not os.path.isfile(run_dir / "votes.json"): + return None + findings, votes, coverage = ( + strictjson.load(run_dir / name) for name in ("findings.json", "votes.json", "coverage.json") + ) + if not is_list(findings) or not is_map(votes) or not is_map(coverage): + msg = "the run directory's records are not the shapes this script wrote" + raise CannotContinueError(msg) + kept = [f for f in findings if is_map(f) and is_str(f.get("id"))] + if len(kept) != len(findings): + msg = "findings.json holds a finding without an id" + raise CannotContinueError(msg) + try: + chain = chain_of(votes.get("chain")) + except ValueError as error: + msg = f"votes.json chain {error}" + raise CannotContinueError(msg) from error + return Records(kept, votes, coverage, chain) + + +def result_in(output_file: Path) -> JsonMap: + """The `result` object the runtime wrote to the workflow's output file.""" + try: + output = strictjson.load(output_file) + except (OSError, ValueError) as error: + msg = f"the output file cannot be read: {error}" + raise NotAResultError(msg) from error + result = output.get("result") if is_map(output) else None + if not is_map(result): + msg = "the output file holds no result object" + raise NotAResultError(msg) + return result + + +def records_in(result: JsonMap) -> tuple[Records, dict[int, JsonMap]]: + """A run's records and its pending rows by rank, narrowed from its result.""" + raw, votes, coverage, pending = ( + result.get(key) for key in ("findings", "votes", "coverage", "pending") + ) + findings = [f for f in raw if is_map(f) and is_str(f.get("id"))] if is_list(raw) else [] + if not is_list(raw) or len(findings) != len(raw): + msg = "'findings' is not a list of findings with ids" + raise NotAResultError(msg) + if not is_map(votes) or votes.get("provenance") != plugin.VOTES_PROVENANCE: + msg = "'votes' is not the scan workflow's vote record" + raise NotAResultError(msg) + if not is_map(coverage) or not is_str(coverage.get("effort")): + msg = "'coverage' does not name the effort" + raise NotAResultError(msg) + if not is_list(pending): + msg = "'pending' is not a list of candidate rows" + raise NotAResultError(msg) + try: + chain = chain_of(votes.get("chain")) + except ValueError as error: + msg = f"'votes' chain {error}" + raise NotAResultError(msg) from error + + rows = {rank_of(row): row for row in pending if is_map(row)} + if len(rows) != len(pending) or sorted(rows) != pending_ranks(chain): + msg = "'pending' rows are not the ranks the chain hands on" + raise NotAResultError(msg) + return Records(findings, votes, coverage, chain), rows + + +def ancestry(path: str) -> list[str]: + """`path` and each directory above it, nearest last: a/b/c gives a, a/b, a/b/c.""" + parts = path.split("/") + return ["/".join(parts[:depth]) for depth in range(1, len(parts) + 1)] + + +def checked(coverage: JsonMap, meta: JsonMap, run_dir: Path) -> JsonMap: + """`coverage` carrying, under `research.tree`, its coverage accounts counted against the + scan target's tracked files; `coverage` as given when the accounts are not checkable.""" + research = coverage.get("research") + if not is_map(research) or research.get("checkable") is not True: + return coverage + listing = run_dir / plugin.TARGET_FILES_NAME + try: + listed = strictjson.load(listing) + except (OSError, ValueError) as error: + sys.stderr.write(f"save_result.py: coverage account not checked: {error}\n") + return coverage + if not is_list(listed): + sys.stderr.write(f"save_result.py: coverage account not checked: {listing} is not a list\n") + return coverage + files = [path for path in listed if is_str(path)] + names = {name for path in files for name in ancestry(path)} + scan_prefix = str(meta.get("scan_prefix") or "") + scan_root = str(meta.get("scan_root") or "").replace("\\", "/").strip("/") + "/" + names.add("") + + def named(path: str) -> str: + slashed = path.replace("\\", "/") + folded = ( + (slashed + "/").removeprefix(root).strip("/") for root in (scan_prefix, scan_root) + ) + return next((s for s in (path, slashed, *folded) if s in names), path) + + accounts = [account for account in texts(research, "components") if is_map(account)] + inside = {named(p) for account in accounts for p in texts(account, "paths") if is_str(p)} + read = {named(p) for account in accounts for p in texts(account, "filesRead") if is_str(p)} + declared = (e.get("path") for a in accounts for e in texts(a, "notReached") if is_map(e)) + missed = {named(p) for p in declared if is_str(p)} + assigned = [f for f in files if not inside.isdisjoint(["", *ancestry(f)])] + unread = [f for f in assigned if f not in read] + unaccounted = [f for f in unread if missed.isdisjoint(["", *ancestry(f)])] + tree = { + "files": len(assigned), + "read": len(assigned) - len(unread), + "notReached": len(unread) - len(unaccounted), + "unaccounted": len(unaccounted), + "unaccountedPaths": unaccounted[:UNACCOUNTED_ECHO_CAP], + "outsideComponents": len(files) - len(assigned), + } + return {**coverage, "research": {**research, "tree": tree}} + + +def placed(finding: JsonMap, meta: JsonMap) -> JsonMap: + """`finding` at the line of its file that its quoted snippet is on, its declared line kept. + + `line` becomes the line of the finding's file under the scan root that + places it (source.placed_line) and the line as it arrived moves to + `declared_line`; both hold the arriving line when the file cannot be + read or nothing in it places the finding. A finding whose line or snippet + is not a shape the render accepts is returned as it is. + """ + finding_id, line, snippet = ( + finding["id"], + line_number(finding.get("line")), + finding.get("snippet"), + ) + scan_root, prefix = meta.get("scan_root"), meta.get("scan_prefix") or "" + if ( + line is None + or not (snippet is None or is_str(snippet)) + or not is_str(finding_id) + or not is_str(scan_root) + or not is_str(prefix) + or not scan_prefix_shaped(prefix) + ): + return finding + try: + file = file_field(finding, finding_id, scan_root, prefix, meta.get("mode") == "scan") + text = source.read(scan_root, file) + except FindingError: + text = None + return {**finding, "line": source.placed_line(text, line, snippet or ""), "declared_line": line} + + +def report_order(finding: JsonMap) -> tuple[int, int]: + """Sort key: severity, then confidence, strongest first; unknown values last.""" + severity = str(finding.get("severity", "")).upper() + confidence = str(finding.get("confidence", "")).lower() + return ( + SEVERITIES.index(severity) if severity in SEVERITIES else len(SEVERITIES), + -CONFIDENCE_RANK.get(confidence, 0), + ) + + +def merged(scan: Records, run: Records) -> Records: + """The scan's records with one further verification run folded in.""" + handed = pending_ranks(scan.chain) + if run.chain["shard"] != scan.chain["shard"] + 1: + msg = ( + f"this is run {run.chain['shard']} but run {scan.chain['shard']} was the last recorded" + ) + raise CannotContinueError(msg) + if run.coverage.get("received") != len(handed): + received = run.coverage.get("received") + msg = f"the run was handed {received!r} candidates, not the {len(handed)} pending" + raise CannotContinueError(msg) + if run.coverage.get("effort") != scan.coverage.get("effort"): + msg = "the run's effort is not the scan's" + raise CannotContinueError(msg) + + findings = scan.findings + [f for f in run.findings if f not in scan.findings] + ids = [f["id"] for f in findings] + if len(ids) != len(set(ids)): + msg = "the run reuses a finding id the scan already has" + raise CannotContinueError(msg) + + scan_rounds, run_rounds = scan.votes.get("rounds"), run.votes.get("rounds") + if not is_map(scan_rounds) or not is_map(run_rounds): + msg = "'rounds' is not an object" + raise CannotContinueError(msg) + repanelled = {r.get("candidate") for r in run_rounds.values() if is_map(r)} + rounds = { + rid: r + for rid, r in scan_rounds.items() + if not (is_map(r) and r.get("continued") is True and r.get("candidate") in repanelled) + } + if rounds.keys() & run_rounds.keys(): + msg = "the run reuses a round id the scan already has" + raise CannotContinueError(msg) + + votes = { + **scan.votes, + "panel_votes": count(scan.votes, "panel_votes") + count(run.votes, "panel_votes"), + "unreviewed_candidate_sites": count(scan.votes, "unreviewed_candidate_sites") + - len(handed) + + count(run.votes, "unreviewed_candidate_sites"), + "rounds": {**rounds, **run_rounds}, + "chain": run.chain, + } + coverage = ( + scan.coverage + if scan.coverage.get("verificationRun") == run.chain["shard"] + else { + **scan.coverage, + "adversarialCasualties": texts(scan.coverage, "adversarialCasualties") + + texts(run.coverage, "adversarialCasualties"), + "lostCandidates": texts(scan.coverage, "lostCandidates") + + texts(run.coverage, "lostCandidates"), + "severityLowered": texts(scan.coverage, "severityLowered") + + texts(run.coverage, "severityLowered"), + "dispatchRefusals": count(scan.coverage, "dispatchRefusals") + + count(run.coverage, "dispatchRefusals"), + "continued": run.coverage.get("continued"), + "verificationRun": run.chain["shard"], + } + ) + return Records(sorted(findings, key=report_order), votes, coverage, run.chain) + + +def write_json(run_dir: Path, name: str, value: object, indent: int = 2) -> None: + """Write one record through a temporary name, so it is never seen half-written.""" + partial = run_dir / f"{name}.partial" + partial.write_bytes((strictjson.text(value, indent=indent) + "\n").encode()) + partial.replace(run_dir / name) + + +def write_records(run_dir: Path, records: Records, rows: dict[int, JsonMap]) -> None: + """The three records and the next run's candidate files; votes.json last.""" + write_json(run_dir, "findings.json", records.findings) + write_json(run_dir, "coverage.json", records.coverage) + shard = records.chain["shard"] + 1 + ranks = sorted(rows) + for number, start in enumerate(range(0, len(ranks), CHUNK), start=1): + chunk = { + "runDir": str(run_dir), + "shard": shard, + "chunk": number, + "candidates": [rows[rank] for rank in ranks[start : start + CHUNK]], + } + write_json(run_dir, f"candidates.{shard}.{number}.json", chunk, indent=1) + write_json(run_dir, "votes.json", records.votes) + + +def summary(records: Records) -> str: + """One line on where the scan stands.""" + rounds = records.votes.get("rounds") + return ( + f"recorded verification run {records.chain['shard']}: {len(records.findings)} findings, " + f"{len(rounds) if is_map(rounds) else 0} rounds, " + f"{len(pending_ranks(records.chain))} pending, " + f"{len(texts(records.coverage, 'lostCandidates'))} lost" + ) + + +def next_step(run_dir: Path, meta: JsonMap, chain: Chain) -> str: + """The `next:` line: the Workflow call that panels what is pending, or the report.""" + if not pending_ranks(chain): + return WRITE_REPORT + args = { + "scanRoot": meta.get("scan_root"), + "runDir": str(run_dir), + "mode": meta.get("mode"), + "effort": meta.get("effort"), + "verify": { + "shard": chain["shard"] + 1, + "idBase": chain["next_id"], + "pending": chain["pending"], + "retry": chain["retry"], + }, + } + return ( + "next: make this Workflow call exactly as printed, wait for it with keep-waiting.sh " + "as before, then run save_result.py on its output file\n" + f'Workflow({{ name: "claude-security:scan", args: {strictjson.text(args)} }})' + ) + + +def otherwise(run_dir: Path, fallback: str) -> str: + """The `next:` line when this result could not be recorded.""" + if os.path.isfile(run_dir / "votes.json"): + return WRITE_REPORT + "; its stamp will name what was not verified" + return f"next: {fallback}" + + +def standing(run_dir: Path, meta: JsonMap, scan: Records | None, result: JsonMap) -> Records: + """The scan's records once `result` is taken into account, written if that changed them. + + `meta` is the scan's settings (scan_settings), which placing a finding reads. + """ + if result.get("started") is False: + if scan is None: + msg = "the workflow did not accept its settings, so no scan ran" + raise CannotContinueError(msg) + return scan + run, rows = records_in(result) + made_for = result.get("runDir") + if not is_str(made_for) or os.path.abspath(made_for) != str(run_dir): + msg = f"the result names {made_for!r} as its run directory, not this one" + raise CannotContinueError(msg) + if scan is None and run.chain["shard"] != 1: + msg = f"this is run {run.chain['shard']} but nothing is recorded yet" + raise CannotContinueError(msg) + if scan is not None and run.chain["shard"] <= scan.chain["shard"]: + return scan + run = run._replace( + findings=[placed(item, meta) for item in run.findings], + coverage=checked(run.coverage, meta, run_dir), + ) + records = run if scan is None else merged(scan, run) + write_records(run_dir, records, rows) + return records + + +def save(output_file: Path, run_dir: Path) -> None: + """Fold the result into the run directory and print where the scan stands.""" + meta = scan_settings(run_dir) + records = standing(run_dir, meta, recorded(run_dir), result_in(output_file)) + print(summary(records)) + print(next_step(run_dir, meta, records.chain)) + + +def argument_parser() -> argparse.ArgumentParser: + """The command line: the workflow's output file and the scan's run directory.""" + parser = argparse.ArgumentParser( + prog="save_result.py", + description="Record a scan workflow's result in its run directory and say what to do next.", + allow_abbrev=False, + ) + parser.add_argument("output_file", help="the file the workflow's completion notice names") + parser.add_argument("run_dir", help="the scan's run directory") + return parser + + +def main(argv: list[str]) -> int: + args = argument_parser().parse_args(argv, namespace=Args()) + output_file = Path(os.path.abspath(args.output_file)) + # abspath folds ".." without following symlinks, so later checks see this path's own name. + run_dir = Path(os.path.abspath(args.run_dir)) + try: + save(output_file, run_dir) + except (NotAResultError, CannotContinueError) as error: + sys.stderr.write(f"save_result.py: {error}\n") + print(otherwise(run_dir, error.fallback)) + return 1 + except (OSError, ValueError) as error: + sys.stderr.write(f"save_result.py: could not read or write the run's files: {error}\n") + print(otherwise(run_dir, CannotContinueError.fallback)) + return 1 + return 0 + + +if __name__ == "__main__": + console.tolerate_undecodable_names() + sys.exit(main(sys.argv[1:])) diff --git a/plugins/claude-security/scripts/write_scan_meta.py b/plugins/claude-security/scripts/write_scan_meta.py index f75b9e31..0ff642bf 100755 --- a/plugins/claude-security/scripts/write_scan_meta.py +++ b/plugins/claude-security/scripts/write_scan_meta.py @@ -1,19 +1,24 @@ #!/usr/bin/env python3 """Write scan-meta.json for a run: the record of what was scanned. -Mints the scan's id and captures, from git itself: the revision, the scan -root's path within the repository, the credential-free https form of its -remote and, for a whole-repository scan, the tree's top-level directories, -printed as a JSON array on a `top_level_dirs:` line and recorded in the meta -file with any root-level symbolic links left out of them. +Mints the scan's id, records when the scan started, and captures, from git +itself: the revision, the scan root's path within the repository, the +credential-free https form of its remote and, for a whole-repository scan, +the tree's top-level directories, printed as a JSON array on a +`top_level_dirs:` line and recorded in the meta file with any root-level +symbolic links left out of them. For a codebase scan it also lists the scan +target's tracked files into target-files.json beside the meta file and prints +their count on a `file_count:` line and, for a whole-repository scan, the +count under each top-level directory on a `dir_file_counts:` line. Usage: write_scan_meta.py <run_dir> <scan_root> --mode scan|changes|commit --effort low|medium|high|max [--scope a,b] [--base <ref>] [--merge-base <sha>] [--commit <sha>] -Exits 0 on success, 1 on a refusal naming what is wrong, 2 on a usage error; -the file is written only on success. +Exits 0 on success, 1 on a refusal naming what is wrong (a run directory that +already holds a scan-meta.json is one), 2 on a usage error; the file is +written only on success. Python 3.9-compatible, stdlib only. """ @@ -26,6 +31,8 @@ import stat import subprocess import sys import uuid +from collections import Counter +from datetime import datetime, timezone from pathlib import Path from typing import Literal, NamedTuple, TypedDict from urllib.parse import quote, unquote, urlsplit @@ -88,12 +95,14 @@ def git(cwd: str, *args: str) -> str | None: class Extent(NamedTuple): - """The scan target's top-level directories, its root-level symbolic links, and - the tracked top-level directories its working tree does not hold.""" + """The scan target's top-level directories, its root-level symbolic links, the + tracked top-level directories its working tree does not hold, and whether + git tracks anything here at all.""" dirs: list[str] symlinks: list[str] absent: list[str] + tracked: bool def tree_extent(scan_root: str) -> Extent | None: @@ -137,7 +146,7 @@ def tree_extent(scan_root: str) -> Extent | None: kept = sorted(n for n in names if not n.startswith(plugin.REPORT_DIR_PREFIX)) on_disk = {n for n in kept if os.path.lexists(os.path.join(scan_root, n))} dirs = [n for n in kept if n in on_disk] - return Extent(dirs, sorted(symlinks), [n for n in kept if n not in on_disk]) + return Extent(dirs, sorted(symlinks), [n for n in kept if n not in on_disk], bool(listing)) def sparse_checkout(scan_root: str, extent: Extent | None) -> list[str] | None: @@ -147,6 +156,28 @@ def sparse_checkout(scan_root: str, extent: Extent | None) -> list[str] | None: return extent.absent if extent else [] +def target_files(scan_root: str, scope: list[str]) -> list[str] | None: + """The scan target's tracked regular files in the working tree, sorted; None if unlisted.""" + listing = git(scan_root, "ls-files", "-z", "--", *scope) + if listing is None: + return None + return sorted({ + path + for path in listing.split("\0") + if path + and not path.startswith(plugin.REPORT_DIR_PREFIX) + and regular_file(os.path.join(scan_root, path)) + }) + + +def regular_file(path: str) -> bool: + """Whether `path` is a regular file, judged without following a symbolic link.""" + try: + return stat.S_ISREG(os.lstat(path).st_mode) + except OSError: + return False + + REMOTE_SCHEMES = frozenset({"http", "https", "ssh", "git", "git+ssh"}) @@ -237,9 +268,12 @@ def capture_revision(scan_root: str, opts: Args) -> Revision: def scoped(entry: str, scan_root: str) -> str: - """A scope entry relative to the scan root; an absolute one that is not inside it is refused.""" + """A scope entry relative to the scan root; an absolute spelling of anything else is refused.""" if not absolute.spelled(entry): return entry + msg = f"--scope entry {entry!r} is not inside the scan root {scan_root!r}" + if not os.path.isabs(entry): + raise MetaError(f"{msg}; write ./{entry} to name a directory in the tree") literal = os.path.abspath(entry) parent, name = os.path.split(literal) try: @@ -251,19 +285,14 @@ def scoped(entry: str, scan_root: str) -> str: except OSError: resolutions = [literal] for resolved in resolutions: - try: - relative = os.path.relpath(resolved, scan_root).replace("\\", "/") - except ValueError: - continue - if relative != ".." and not relative.startswith("../"): + if (relative := absolute.relative(resolved, scan_root)) is not None: return relative - msg = f"--scope entry {entry!r} is not inside the scan root {scan_root!r}" raise MetaError(msg) def parse_options(argv: list[str]) -> Args: """The parsed command line; anything wrong with it is argparse's exit 2.""" - ap = argparse.ArgumentParser(prog="write_scan_meta") + ap = argparse.ArgumentParser(prog="write_scan_meta", allow_abbrev=False) ap.add_argument("run_dir") ap.add_argument("scan_root") ap.add_argument("--mode", required=True, choices=plugin.MODES) @@ -282,7 +311,8 @@ def parse_options(argv: list[str]) -> Args: def main(argv: list[str]) -> int: opts = parse_options(argv) - run_dir = os.path.realpath(os.path.abspath(opts.run_dir)) + # abspath first: "x/.." is x's parent as typed, where realpath alone would follow a symlink x. + run_dir = Path(os.path.realpath(os.path.abspath(opts.run_dir))) scan_root = os.path.realpath(os.path.abspath(opts.scan_root)) revision = capture_revision(scan_root, opts) extent = tree_extent(scan_root) @@ -302,9 +332,17 @@ def main(argv: list[str]) -> int: if scope and all(s in {".", "./"} for s in scope): scope = [] whole_repo = opts.mode == "scan" and not scope + tracked = opts.mode == "scan" and extent is not None and extent.tracked + files = target_files(scan_root, scope) if tracked else None + if tracked and files is None: + sys.stderr.write(f"write_scan_meta: could not list {scan_root}; file_count unknown\n") if whole_repo and extent is None: sys.stderr.write(f"write_scan_meta: could not list {scan_root}; top_level_dirs unknown\n") top_level, symlinks = (extent.dirs, extent.symlinks) if whole_repo and extent else (None, None) + dir_file_counts = None + if top_level is not None and files is not None: + per_dir = Counter(path.partition("/")[0] for path in files if "/" in path) + dir_file_counts = {name: per_dir[name] for name in top_level} if symlinks: sys.stderr.write( "write_scan_meta: root-level symbolic links not followed, " @@ -312,10 +350,11 @@ def main(argv: list[str]) -> int: ) meta: dict[str, object] = { "scan_id": str(uuid.uuid4()), + "started_at": datetime.now(timezone.utc).replace(microsecond=0).isoformat(), "scan_root": scan_root, "scan_prefix": scan_prefix, "remote": remote, - "run_dir": run_dir, + "run_dir": str(run_dir), "flow": "scan" if opts.mode == "scan" else "changes", "agent": f"{plugin.NAME}:{plugin.NAME}", "mode": opts.mode, @@ -327,15 +366,28 @@ def main(argv: list[str]) -> int: "top_level_dirs": top_level, "unfollowed_symlinks": symlinks, } - path = os.path.join(run_dir, "scan-meta.json") - with open(path, "w", encoding="utf-8", newline="\n") as out: - out.write(strictjson.text(meta, indent=2) + "\n") + path = run_dir / "scan-meta.json" + # Created exclusively: a run directory that already holds one belongs to another scan. + try: + with path.open("x", encoding="utf-8", newline="\n") as out: + out.write(strictjson.text(meta, indent=2) + "\n") + except FileExistsError as error: + msg = ( + f"{run_dir} already holds a scan's scan-meta.json, so another scan is using this " + "report directory; make a new report directory named for the current time and " + "run this again there" + ) + raise MetaError(msg) from error + if files is not None: + (run_dir / plugin.TARGET_FILES_NAME).write_bytes((strictjson.text(files) + "\n").encode()) sys.stdout.write(f"scan-meta.json written: {path}\n") sys.stdout.write(f"revision: {revision.get('commit') or 'UNVERSIONED'}\n") if absent is not None: listed = strictjson.text(absent) sys.stdout.write(f"sparse checkout: top-level directories not checked out: {listed}\n") sys.stdout.write(f"top_level_dirs: {strictjson.text(top_level)}\n") + sys.stdout.write(f"file_count: {strictjson.text(None if files is None else len(files))}\n") + sys.stdout.write(f"dir_file_counts: {strictjson.text(dir_file_counts)}\n") return 0 |
