summaryrefslogtreecommitdiff
path: root/plugins/claude-security/scripts/lib
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-11-06 00:54:48 +0000
committerClaude <noreply@anthropic.com>2026-11-06 00:54:48 +0000
commit7aba3deae3ff17d032c37e07d2929d1426b34278 (patch)
tree9c482f9acda1599bd2f9bed95a6a46b75e634e80 /plugins/claude-security/scripts/lib
parent5472f5f56e0070feeeb464318b316714fe3e9105 (diff)
parentb8331dd69ab3e132bbf8cd6e89b5d8c1747e21b1 (diff)
Merge remote-tracking branch 'origin/main' into add-plugin/xcodeadd-plugin/xcode
Diffstat (limited to 'plugins/claude-security/scripts/lib')
-rw-r--r--plugins/claude-security/scripts/lib/finding.py258
-rw-r--r--plugins/claude-security/scripts/lib/git.py27
-rw-r--r--plugins/claude-security/scripts/lib/link.py23
-rw-r--r--plugins/claude-security/scripts/lib/plugin.py18
-rw-r--r--plugins/claude-security/scripts/lib/revision.py28
-rw-r--r--plugins/claude-security/scripts/lib/sarif.py51
-rw-r--r--plugins/claude-security/scripts/lib/secret.py22
-rw-r--r--plugins/claude-security/scripts/lib/strictjson.py20
8 files changed, 364 insertions, 83 deletions
diff --git a/plugins/claude-security/scripts/lib/finding.py b/plugins/claude-security/scripts/lib/finding.py
index b7cfa0dd..0a14e4d3 100644
--- a/plugins/claude-security/scripts/lib/finding.py
+++ b/plugins/claude-security/scripts/lib/finding.py
@@ -4,7 +4,11 @@ from __future__ import annotations
import ntpath
import os
+import posixpath
import re
+from enum import IntEnum
+from itertools import dropwhile
+from pathlib import Path
from typing import TypedDict
from . import absolute, cwe
@@ -38,6 +42,8 @@ class Finding(TypedDict):
snippet: str
symbol: str
declared_line: int
+ via_change: str | None
+ other_cwe_ids: list[str]
class Record(Finding):
@@ -46,9 +52,29 @@ class Record(Finding):
claudeSecurityPluginFindingId: str
-SEVERITIES = ("CRITICAL", "HIGH", "MEDIUM", "LOW")
-CONFIDENCES = ("low", "medium", "high")
-CONFIDENCE_RANK = {"low": 1, "medium": 2, "high": 3}
+class Severity(IntEnum):
+ """A finding's severity."""
+
+ CRITICAL = 4
+ HIGH = 3
+ MEDIUM = 2
+ LOW = 1
+
+ @classmethod
+ def of(cls, record: JsonMap) -> Severity | None:
+ """A record's severity from its word, stripped and in any letter case; None when the
+ word names none.
+ """
+ return cls.__members__.get(str(record.get("severity", "")).strip().upper())
+
+
+class Confidence(IntEnum):
+ """A finding's confidence."""
+
+ low = 1
+ medium = 2
+ high = 3
+
PANEL_VOTER_COUNT = 3
PANEL_KEEP_QUORUM = 2
@@ -71,7 +97,7 @@ class FindingPathError(FindingError):
finding_id: str
wrong: str
- cwe: int = 0
+ cwes: tuple[int, ...] = ()
snippet: str = ""
def __init__(self, finding_id: str, *, declared: str, wrong: str) -> None:
@@ -88,22 +114,60 @@ def cwe_number(item: JsonMap, finding_id: str) -> int:
under Uncategorized, and the renderer discloses the substitution.
"""
declared = text_field(item, "cwe_id", finding_id, required=True)
+ return cwe_parsed(declared, finding_id, "cwe_id")
+
+
+def cwe_parsed(declared: str, finding_id: str, field: str) -> int:
+ """The number in one CWE id as a record may spell it; anything else is refused."""
matched = re.fullmatch(
r"(?:CWE-)?0*([1-9][0-9]{0,4})", declared.strip().upper().replace("_", "-")
)
if not matched:
- msg = f"finding {finding_id} cwe_id {declared!r} is not a CWE id such as CWE-89"
+ msg = f"finding {finding_id} {field} {declared!r} is not a CWE id such as CWE-89"
raise FindingError(msg)
return int(matched[1])
-def confidence_value(raw: object) -> str:
- """A finding's stated confidence, normalized to low|medium|high; refuses others."""
+# The research schema opens every change link with "file:line "; sarif.placed reads that site.
+LINK_SITE = re.compile(r"(.+?):([1-9][0-9]{0,14})(?:-([1-9][0-9]{0,14}))?\b")
+
+
+def link_field(item: JsonMap, finding_id: str, scan_root: str, scan_prefix: str) -> str | None:
+ """A change scan's via_change with its leading file normalised like `file`; None when absent.
+
+ A link that does not open with a file:line the scan can place is kept as written.
+ """
+ link = text_field(item, "via_change", finding_id).strip() or None
+ matched = LINK_SITE.match(link or "")
+ if not (link and matched):
+ return link
+ try:
+ file = relative_path(matched[1], finding_id, scan_root, scan_prefix, must_exist=False)
+ except FindingPathError:
+ return link
+ return file + link[matched.end(1) :]
+
+
+def other_cwe_numbers(item: JsonMap, finding_id: str, primary: int) -> list[int]:
+ """The further CWE numbers a finding carries, the primary and repeats left out."""
+ raw = item.get("other_cwe_ids")
+ if raw is None:
+ return []
+ entries = [entry for entry in raw if is_str(entry)] if is_list(raw) else []
+ if not is_list(raw) or len(entries) != len(raw):
+ msg = f"finding {finding_id} other_cwe_ids is not a list of CWE ids"
+ raise FindingError(msg)
+ numbers = [cwe_parsed(entry, finding_id, "other_cwe_ids") for entry in entries]
+ return [n for n in dict.fromkeys(numbers) if n != primary]
+
+
+def confidence_value(raw: object) -> Confidence:
+ """A finding's stated confidence, in any letter case; refuses any other value."""
if is_str(raw):
word = raw.strip().lower()
- if word in CONFIDENCE_RANK:
- return word
- msg = f"confidence {raw!r} is not one of {'/'.join(CONFIDENCES)}"
+ if word in Confidence.__members__:
+ return Confidence[word]
+ msg = f"confidence {raw!r} is not one of {'/'.join(Confidence.__members__)}"
raise FindingError(msg)
@@ -127,12 +191,23 @@ def panel_complete(record: object) -> Panel | None:
}
-def vote_confidence_ceiling(record: object) -> str | None:
+def vote_rounds(votes: JsonMap) -> JsonMap:
+ """The vote record's rounds by id, or an empty map when it holds none."""
+ raw = votes.get("rounds")
+ return raw if is_map(raw) else {}
+
+
+def finding_panels(rounds: JsonMap, ids: list[str]) -> list[tuple[str, Panel | None]]:
+ """Each finding id with its complete panel in the rounds, or None, in the order given."""
+ return [(i, panel_complete(rounds.get(i))) for i in ids]
+
+
+def vote_confidence_ceiling(record: object) -> Confidence | None:
"""A finding's vote-backed confidence: `high` if unanimous, `medium` if complete, else None."""
panel = panel_complete(record)
if panel is None:
return None
- return "high" if panel["true"] >= PANEL_VOTER_COUNT else "medium"
+ return Confidence.high if panel["true"] >= PANEL_VOTER_COUNT else Confidence.medium
def line_number(raw: object) -> int | None:
@@ -151,6 +226,20 @@ def line_field(item: JsonMap, key: str, finding_id: str, default: int) -> int:
return line
+def repository_file(scan_prefix: str, *, file: str) -> str:
+ """A scan-root-relative `file` made repository-relative by a lexical fold."""
+ return posixpath.normpath(scan_prefix + file)
+
+
+def scan_prefix_fits(prefix: str, *, scan_root: str) -> bool:
+ """Whether `prefix` has no more components than the scan root's real path, as a prefix git
+ printed always does."""
+ try:
+ return prefix.count("/") <= len(Path(os.path.realpath(scan_root)).parents)
+ except (OSError, ValueError):
+ return False
+
+
def scan_prefix_shaped(prefix: str) -> bool:
"""Whether `prefix` is what `git rev-parse --show-prefix` prints: empty, or `a/b/`."""
if not prefix:
@@ -196,49 +285,102 @@ def file_field(
) -> str:
"""A finding's file relative to the scan root; a path that leaves the repository is refused.
- `scan_prefix` is the scan root's path below the repository top level (`a/b/`,
- or empty): a file may climb one directory per prefix component and no further.
- A file spelled relative to the top level, absent under the scan root but
- present under the top level, is respelled relative to the scan root.
- 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.
+ `scan_prefix` is the scan root's path below the repository top level (`a/b/`, or empty).
+ With `must_exist` (a codebase scan) a missing file is refused. relative_path has the rules.
"""
declared = text_field(item, "file", finding_id, required=True).strip()
+ return relative_path(declared, finding_id, scan_root, scan_prefix, must_exist)
+
+
+def located(spelled: str, *, root: Path, top: Path) -> Path | None:
+ """The path `spelled` resolves to from the scan root `root` or the repository top level `top`.
+
+ The result may lie outside the repository, through a link. None when no place holds the folder
+ the path names and the path has a `..` after its leading climb.
+ """
+ if Path(spelled).is_absolute():
+ return Path(os.path.realpath(spelled))
+ files: list[Path] = []
+ for base in dict.fromkeys((root, top)):
+ spelled_from = Path(base, spelled)
+ if top not in Path(os.path.normpath(spelled_from)).parents:
+ continue
+ folder = Path(os.path.realpath(spelled_from.parent))
+ if top not in {folder, *folder.parents}:
+ if not files:
+ return Path(os.path.realpath(spelled_from))
+ continue
+ if spelled_from.parent.is_dir():
+ file = Path(os.path.realpath(spelled_from))
+ if top not in file.parents:
+ if not files:
+ return file
+ continue
+ if file.exists():
+ return file
+ files.append(file)
+ if not files and ".." not in dropwhile(lambda part: part == "..", Path(spelled).parts):
+ files = [Path(os.path.realpath(Path(root, spelled)))]
+ return next(iter(files), None)
+
+
+def relative_path(
+ declared: str, finding_id: str, scan_root: str, scan_prefix: str, must_exist: bool
+) -> str:
+ """A file as a finding spells it, resolved and made relative to the scan root.
+
+ The path is refused when it resolves outside the repository, to the scan root or above, or
+ to a missing file that a codebase scan needs or whose stored path would name another file.
+ """
depth = scan_prefix.count("/")
escapes = f"escapes the {'repository' if depth else 'scan root'}"
- path = declared.replace("\\", "/")
+ unresolved = "cannot be resolved"
+ elsewhere = "could be mistaken for a path at the repository top level"
+ spelled = declared.replace("\\", "/")
prefix = scan_root.replace("\\", "/").rstrip("/") + "/"
- if scan_root and path.startswith(prefix):
- path = path[len(prefix) :].lstrip("/")
- if os.path.isabs(path):
- try:
- path = os.path.relpath(os.path.realpath(path), scan_root).replace("\\", "/")
- except (ValueError, OSError) as 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 scan_root and spelled.startswith(prefix):
+ spelled = spelled[len(prefix) :].lstrip("/")
+ root = Path(os.path.realpath(scan_root))
+ top = (root, *root.parents)[depth]
+ leaves = top not in Path(os.path.normpath(Path(root, spelled))).parents
+ if leaves and not Path(spelled).is_absolute():
+ raise FindingPathError(finding_id, declared=declared, wrong=escapes)
+ try:
+ file = located(spelled, root=root, top=top)
+ except (OSError, ValueError) as error:
+ wrong = escapes if leaves else unresolved
+ raise FindingPathError(finding_id, declared=declared, wrong=wrong) from error
+ if file is None:
+ unreadable = "cannot be read from the scan root or the repository top level"
+ raise FindingPathError(finding_id, declared=declared, wrong=unreadable)
+ if top not in file.parents:
+ raise FindingPathError(finding_id, declared=declared, wrong=escapes)
+ if root.is_relative_to(file):
+ raise FindingPathError(finding_id, declared=declared, wrong="names a folder, not a file")
+ relative = Path(os.path.relpath(file, root)).as_posix()
+ if leaked_spelling(relative, first=relative.split("/")[0], scan_root=scan_root):
+ raise FindingPathError(finding_id, declared=declared, wrong=escapes)
+ try:
+ exists = file.exists()
+ except OSError as error:
+ raise FindingPathError(finding_id, declared=declared, wrong=unresolved) from error
+ if exists:
+ return relative
+ if must_exist:
+ raise FindingPathError(
+ finding_id, declared=declared, wrong="does not exist in the scanned tree"
+ )
+ try:
+ again = located(relative, root=root, top=top)
+ except OSError as error:
+ raise FindingPathError(finding_id, declared=declared, wrong=unresolved) from error
if (
- not inside
- or ".." in inside
- or climb > depth
- or leaked_spelling(path, first=parts[0], scan_root=scan_root)
+ again is None
+ or top not in again.parents
+ or Path(os.path.relpath(again, root)).as_posix() != relative
):
- 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:
- at_top = os.path.join(os.path.normpath(os.path.join(scan_root, "../" * depth)), *parts)
- if os.path.lexists(at_top):
- return os.path.relpath(at_top, scan_root).replace("\\", "/")
- if must_exist:
- raise FindingPathError(
- finding_id, declared=declared, wrong="does not exist in the scanned tree"
- )
- return "/".join(parts)
+ raise FindingPathError(finding_id, declared=declared, wrong=elsewhere)
+ return relative
def build_finding(
@@ -259,18 +401,18 @@ def build_finding(
msg = f"finding id {finding_id!r} is not a valid id"
raise FindingError(msg)
- severity = str(raw.get("severity", "")).strip().upper()
- if severity not in SEVERITIES:
+ severity = Severity.of(raw)
+ if severity is None:
msg = (
f"finding {finding_id} severity {raw.get('severity')!r} is not one of "
- f"{'/'.join(SEVERITIES)}"
+ f"{'/'.join(Severity.__members__)}"
)
raise FindingError(msg)
confidence = confidence_value(raw.get("confidence"))
ceiling = vote_confidence_ceiling(rounds_by_id.get(finding_id))
- if ceiling is not None and CONFIDENCE_RANK[confidence] > CONFIDENCE_RANK[ceiling]:
- confidence = ceiling
+ if ceiling is not None:
+ confidence = min(confidence, ceiling)
line = line_field(raw, "line", finding_id, 0)
declared_line = line_field(raw, "declared_line", finding_id, line)
@@ -295,10 +437,12 @@ def build_finding(
recommendation = text_field(raw, "recommendation", finding_id)
snippet = text_field(raw, "snippet", finding_id)
symbol = text_field(raw, "symbol", finding_id)
+ via_change = link_field(raw, finding_id, scan_root, scan_prefix)
+ further = other_cwe_numbers(raw, finding_id, number)
try:
file = file_field(raw, finding_id, scan_root, scan_prefix, must_exist)
except FindingPathError as error:
- error.cwe, error.snippet = number, snippet
+ error.cwes, error.snippet = (number, *further), snippet
raise
return {
@@ -311,11 +455,13 @@ def build_finding(
"exploit_scenario": exploit_scenario,
"preconditions": preconditions,
"category": category.name if category is not None else cwe.UNCATEGORIZED,
- "severity": severity,
- "confidence": confidence,
+ "severity": severity.name,
+ "confidence": confidence.name,
"recommendation": recommendation,
"cwe_id": f"CWE-{number}",
"snippet": snippet,
"symbol": symbol,
"declared_line": declared_line,
+ "via_change": via_change,
+ "other_cwe_ids": [f"CWE-{n}" for n in further],
}
diff --git a/plugins/claude-security/scripts/lib/git.py b/plugins/claude-security/scripts/lib/git.py
new file mode 100644
index 00000000..ded163d3
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/git.py
@@ -0,0 +1,27 @@
+"""Read-only git calls for the scripts: one runner, prompts suppressed, output byte-faithful."""
+
+from __future__ import annotations
+
+import os
+import subprocess
+
+REDIRECTS = frozenset({"GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR"})
+ENV = {k: v for k, v in os.environ.items() if k not in REDIRECTS} | {"GIT_TERMINAL_PROMPT": "0"}
+
+
+def run(cwd: str, *args: str) -> str | None:
+ """The stdout of `git -C <cwd> <args>` without trailing newlines; None on any failure."""
+ try:
+ out = subprocess.run(
+ ["git", "-C", cwd, *args],
+ env=ENV,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ timeout=30,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if out.returncode != 0:
+ return None
+ return out.stdout.decode("utf-8", "surrogateescape").rstrip("\r\n")
diff --git a/plugins/claude-security/scripts/lib/link.py b/plugins/claude-security/scripts/lib/link.py
new file mode 100644
index 00000000..4c70b542
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/link.py
@@ -0,0 +1,23 @@
+"""Whether a path is a link that a removal must not be sent through."""
+
+from __future__ import annotations
+
+import os
+import stat
+
+
+def is_link(path: str | os.PathLike[str]) -> bool:
+ """Whether `path` is a symbolic link or, on Windows, a directory junction.
+
+ False for a path that is absent or cannot be examined.
+ """
+ try:
+ status = os.lstat(path)
+ except OSError:
+ return False
+ if stat.S_ISLNK(status.st_mode):
+ return True
+ if os.name == "nt":
+ reparse_point = status.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
+ return bool(reparse_point) and status.st_reparse_tag == stat.IO_REPARSE_TAG_MOUNT_POINT
+ return False
diff --git a/plugins/claude-security/scripts/lib/plugin.py b/plugins/claude-security/scripts/lib/plugin.py
index 2d8321cd..c7f902a0 100644
--- a/plugins/claude-security/scripts/lib/plugin.py
+++ b/plugins/claude-security/scripts/lib/plugin.py
@@ -16,8 +16,26 @@ TARGET_FILES_NAME = "target-files.json"
VOTES_PROVENANCE = "workflows/scan.js"
MODES = ("scan", "changes", "commit")
REPORT_DIR_PREFIX = "CLAUDE-SECURITY-"
+# \Z, not $: `$` also matches before a trailing newline, and this is a fence.
+REPORT_DIR_RE = re.compile(rf"^{re.escape(REPORT_DIR_PREFIX)}[0-9][0-9-]*\Z")
+JSONL_NAME = "CLAUDE-SECURITY-RESULTS.jsonl"
+REVISION_PREFIX = "CLAUDE-SECURITY-REVISION-"
# \Z, not $: `$` also matches before a trailing newline, and this id names product files.
SHA_RE = re.compile(r"^[0-9a-fA-F]{7,64}\Z")
+SHORT_ID_CHARS = 12
+_RETIRED_MAX_NOTE = (
+ "The `max` effort tier has been retired, so I'm running this scan at `high`. "
+ "A future version will stop accepting `max` and return an error."
+)
+RETIRED_MAX_RELAY = (
+ "relay: say this to the user exactly as printed, to open your kickoff message and "
+ f"again to close your results message: {_RETIRED_MAX_NOTE}"
+)
+
+
+def is_revision_stamp(path: Path) -> bool:
+ """Whether `path` has a revision stamp's name, `CLAUDE-SECURITY-REVISION-<tag>.json`."""
+ return path.name.startswith(REVISION_PREFIX) and path.suffix == ".json"
def version() -> str | None:
diff --git a/plugins/claude-security/scripts/lib/revision.py b/plugins/claude-security/scripts/lib/revision.py
new file mode 100644
index 00000000..afe334e2
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/revision.py
@@ -0,0 +1,28 @@
+"""The revision a scan records, and the `<base>..<commit>` range a change scan's revision names."""
+
+from __future__ import annotations
+
+from typing import Literal, TypedDict
+
+from .strictjson import JsonMap, is_str
+
+
+class Revision(TypedDict, total=False):
+ """What was scanned. `versioned` is always present; the rest when in git."""
+
+ versioned: bool
+ commit: str | None
+ parent: str | None
+ branch: str | None
+ dirty: bool | None
+ sparse: Literal[True]
+ not_checked_out_dirs: list[str]
+ base: str | None
+ merge_base: str | None
+
+
+def change_range(revision: JsonMap) -> str | None:
+ """The `<base>..<commit>` range a change scan's revision names; None when it names no change."""
+ base = revision.get("merge_base") or revision.get("parent")
+ commit = revision.get("commit")
+ return f"{base}..{commit}" if is_str(base) and is_str(commit) else None
diff --git a/plugins/claude-security/scripts/lib/sarif.py b/plugins/claude-security/scripts/lib/sarif.py
index de98e4f5..ace752ba 100644
--- a/plugins/claude-security/scripts/lib/sarif.py
+++ b/plugins/claude-security/scripts/lib/sarif.py
@@ -4,13 +4,13 @@ from __future__ import annotations
import hashlib
import json
-import posixpath
import re
from dataclasses import dataclass
from typing import TYPE_CHECKING, Final, NamedTuple
from urllib.parse import quote
from . import cwe, secret, source
+from .finding import LINK_SITE, repository_file
if TYPE_CHECKING:
import uuid
@@ -173,7 +173,7 @@ def placed(
`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.
"""
- texts = {repository_file(scan, file): text for file, text in sources.items()}
+ texts = {repository_file(scan.prefix, file=file): text for file, text in sources.items()}
secrets = {
(path, line)
for f in findings
@@ -188,23 +188,55 @@ def placed(
return [placed_one(f, scan, sources.get(f["file"]), secrets) for f in findings]
+class Span(NamedTuple):
+ """Lines `first` to `last` of the file at repository path `path`."""
+
+ path: str
+ first: int
+ last: int
+
+
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."""
+ """One finding placed in `text`, its file's content (None when unread), and given its id.
+
+ The link to the change is dropped for a finding inside a credential's window,
+ or whose link opens at a line or range that reaches one: it may describe the credential.
+ """
moved: Finding = finding
code = None
+ path = repository_path(scan, finding)
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)
+ code = None if near(Span(path, row + 1, row + 1), secrets) else code_at(lines, row)
+ anchor = Span(path, moved["line"], moved["line"])
+ link = link_site(scan, moved["via_change"])
+ if near(anchor, secrets) or (link is not None and near(link, secrets)):
+ moved = {**moved, "via_change": None}
return {**moved, FINDING_ID: fingerprint(moved, scan, code)}
+def near(span: Span, secrets: Collection[tuple[str, int]]) -> bool:
+ """True when `span` comes within CONTEXT_LINES of a credential line in its file."""
+ return any(
+ p == span.path and span.first - CONTEXT_LINES <= n <= span.last + CONTEXT_LINES
+ for p, n in secrets
+ )
+
+
+def link_site(scan: Scan, via_change: str | None) -> Span | None:
+ """The span a change link opens with; None when it opens with no file:line."""
+ matched = LINK_SITE.match(via_change or "")
+ if not matched:
+ return None
+ first, last = sorted((int(matched[2]), int(matched[3] or matched[2])))
+ return Span(repository_file(scan.prefix, file=matched[1]), first, last)
+
+
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.
@@ -306,12 +338,7 @@ 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 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)
+ return repository_file(scan.prefix, file=finding["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 67f4d0f4..df061c2e 100644
--- a/plugins/claude-security/scripts/lib/secret.py
+++ b/plugins/claude-security/scripts/lib/secret.py
@@ -1,12 +1,15 @@
-"""The snippet of a hard-coded credential finding, withheld from what the products carry.
+"""A hard-coded credential finding's snippet and link to the change, withheld from the products.
The line such a finding quotes is the credential itself, and the JSONL and
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 neither its id nor that of a
-finding placed near it hashes the credential's line.
+quoted. A change scan's link to the change (via_change) describes that same
+line in the researcher's words, so it goes with the snippet: here for the
+credential finding, in sarif.placed for a finding near the credential's line
+or whose link opens there. Only the emitted copy changes: the finding is still
+placed on the 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
@@ -28,10 +31,13 @@ def is_credential_cwe(number: int) -> bool:
def is_credential(finding: Finding) -> bool:
- """Whether the finding's CWE rolls up to Use of Hard-coded Credentials."""
- return is_credential_cwe(cwe.id_number(finding["cwe_id"]))
+ """Whether any CWE the finding carries rolls up to Use of Hard-coded Credentials."""
+ ids = (finding["cwe_id"], *finding["other_cwe_ids"])
+ return any(is_credential_cwe(cwe.id_number(cwe_id)) for cwe_id in ids)
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
+ """`finding` as the products carry it: a hard-coded credential's snippet and link withheld."""
+ if not is_credential(finding):
+ return finding
+ return {**finding, "snippet": "", "via_change": None}
diff --git a/plugins/claude-security/scripts/lib/strictjson.py b/plugins/claude-security/scripts/lib/strictjson.py
index 91d4ee30..b1b6f267 100644
--- a/plugins/claude-security/scripts/lib/strictjson.py
+++ b/plugins/claude-security/scripts/lib/strictjson.py
@@ -15,9 +15,11 @@ import re
from collections.abc import Mapping
from typing import TYPE_CHECKING, NoReturn, cast
+# pyright: reportMissingModuleSource=false
if TYPE_CHECKING:
from pathlib import Path
- from typing import TypeGuard
+
+ from typing_extensions import TypeGuard
JsonMap = Mapping[str, object]
@@ -65,14 +67,18 @@ def _finite(digits: str) -> float:
return value
+def loads(document: str) -> object:
+ """The JSON value in `document`; ValueError if not strict JSON."""
+ try:
+ return cast("object", json.loads(document, parse_constant=_refuse, parse_float=_finite))
+ except RecursionError as error:
+ msg = "nested too deeply"
+ raise ValueError(msg) from error
+
+
def load(path: Path) -> object:
"""The JSON value in `path`; OSError if unreadable, ValueError if not strict JSON."""
- 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:
- msg = "nested too deeply"
- raise ValueError(msg) from error
+ return loads(path.read_text(encoding="utf-8"))
def text(value: object, indent: int | None = None) -> str: