diff options
| author | Claude <noreply@anthropic.com> | 2026-09-10 20:49:44 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-09-10 20:49:44 +0000 |
| commit | 8459dfc26ec93b3d7f53353a902fa2d530bcb154 (patch) | |
| tree | 9b87c6ca0f487f396d792c793a2f0ff56cf693bb /plugins/claude-security/scripts/lib | |
| parent | 4d2a599463bf3966c368dd8bfb30cfa1682cf126 (diff) | |
| parent | 3b600518a637492d37c9877aeb49c2a55d939c04 (diff) | |
Merge remote-tracking branch 'origin/main' into tobin/add-dynatrace
# Conflicts:
# .claude-plugin/marketplace.json
Diffstat (limited to 'plugins/claude-security/scripts/lib')
| -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 |
8 files changed, 396 insertions, 152 deletions
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: |
