Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(security): honor reviewed Semgrep source suppressions (#7103)

LearningCircuit9835bcb510b3
diff --git a/.github/scripts/check_semgrep_report.py b/.github/scripts/check_semgrep_report.py
index 03259eab3a..bb030fe4f7 100644
--- a/.github/scripts/check_semgrep_report.py
+++ b/.github/scripts/check_semgrep_report.py
@@ -1,7 +1,9 @@
"""Reject incomplete Semgrep scans before publishing code-scanning results."""
import argparse
+import copy
import json
+import os
import re
from collections import Counter
from pathlib import Path
@@ -16,6 +18,32 @@ SARIF_LEVELS = frozenset({"error", "warning", "note"})
# not parse, leaving the alert without a level (and so never blocking).
SECURITY_SEVERITY = re.compile(r"[0-9]+(?:\.[0-9]+)?")
+# Semgrep 1.177.0 (src/reporting/Nosemgrep.ml) honours a case-insensitive
+# "nosem"/"nosemgrep" after a space anywhere on a finding's first line,
+# string literals and prose included, or at the start of the previous line
+# after only non-alphanumeric ASCII characters. Without rule ids, or with
+# ids it cannot parse, a match suppresses every rule on that line. Python's
+# re.IGNORECASE also folds non-ASCII look-alikes (U+017F for "s"), so this
+# finds every marker Semgrep would honour, and possibly more.
+NOSEM_MARKER = re.compile(r"nosem(?:grep)?", re.IGNORECASE)
+NOSEM_PREVIOUS_LINE_PREFIX = re.compile(r"[^a-zA-Z0-9]*")
+# The only accepted form: one or more rule ids, then a "reason:" item:
+# nosemgrep: <rule-id>[, <rule-id>]..., reason: <text without commas>
+# Semgrep splits the text after "nosemgrep: " at commas and takes the first
+# space-separated word of each item as a rule id, so it reads the rule ids
+# plus "reason:", which is not a valid rule id (no colon is allowed) and so
+# suppresses nothing. That extra item is load-bearing: when a comment holds
+# a single id, Semgrep reports a SemgrepWarning ("found 'nosem' comment with
+# id ..., but no corresponding rule trying ...") for every OTHER rule that
+# matches the line, and with --strict that fails the whole scan. With two or
+# more items it reports none (Nosemgrep.ml, NOTE(multiple)), so a new rule
+# matching an annotated line is uploaded as an alert instead.
+REVIEWED_RULE_ID = r"[A-Za-z0-9_.-]+"
+REVIEWED_ANNOTATION = re.compile(
+ rf"nosemgrep: (?P<rules>{REVIEWED_RULE_ID}(?:, {REVIEWED_RULE_ID})*)"
+ r", reason: (?P<reason>[^,]*[A-Za-z][^,]*)"
+)
+
def _json_findings(report: object) -> tuple[Counter, Counter]:
"""Validate the JSON report; return severity and per-rule counts."""
@@ -140,11 +168,120 @@ def _sarif_findings(sarif: object) -> Counter:
)
if score is None and level not in SARIF_LEVELS:
raise ValueError("SARIF finding lacks severity information")
- if not result.get("suppressions"):
+ if not _source_suppressed(result):
rules_seen[result.get("ruleId")] += 1
return rules_seen
+def _source_suppressed(result: dict) -> bool:
+ """Recognize source suppressions; reject unknown suppression semantics."""
+ suppressions = result.get("suppressions", [])
+ if not isinstance(suppressions, list):
+ raise ValueError("SARIF finding has malformed suppressions")
+ for suppression in suppressions:
+ if (
+ not isinstance(suppression, dict)
+ or suppression.get("kind") != "inSource"
+ or suppression.get("status", "accepted") != "accepted"
+ ):
+ raise ValueError(
+ "SARIF finding has unsupported suppression metadata"
+ )
+ return bool(suppressions)
+
+
+def nosem_markers(line: str, *, previous_line: bool) -> list[int]:
+ """Offsets of every marker Semgrep would honour on ``line``.
+
+ On a finding's own line Semgrep honours a marker after a space; on the
+ line above it, only a marker preceded by nothing but non-alphanumeric
+ ASCII characters.
+ """
+ offsets = []
+ for match in NOSEM_MARKER.finditer(line):
+ start = match.start()
+ if previous_line:
+ honoured = bool(NOSEM_PREVIOUS_LINE_PREFIX.fullmatch(line[:start]))
+ else:
+ honoured = start > 0 and line[start - 1] == " "
+ if honoured:
+ offsets.append(start)
+ return offsets
+
+
+def reviewed_annotation_rules(
+ line: str, *, previous_line: bool
+) -> tuple[str, ...]:
+ """The rules named by ``line``'s reviewed annotation, or ().
+
+ A reviewed annotation is the line's only Semgrep marker, written exactly
+ as ``nosemgrep: <rule-id>[, <rule-id>]..., reason: <reason>``. Bare,
+ rule-less, reasonless and case-variant markers name no rule.
+ """
+ offsets = nosem_markers(line, previous_line=previous_line)
+ if len(offsets) != 1:
+ return ()
+ match = REVIEWED_ANNOTATION.fullmatch(line[offsets[0] :].rstrip("\r"))
+ return tuple(match.group("rules").split(", ")) if match else ()
+
+
+def _source_lines(source_root: Path, result: dict) -> tuple[str | None, str]:
+ """The previous and first line of a SARIF result's primary location."""
+ try:
+ location = result["locations"][0]["physicalLocation"]
+ uri = location["artifactLocation"]["uri"]
+ line_number = location["region"]["startLine"]
+ except (KeyError, IndexError, TypeError) as exc:
+ raise ValueError("Suppressed SARIF finding has no source line") from exc
+ if (
+ not isinstance(uri, str)
+ or not uri
+ or ":" in uri
+ or "%" in uri
+ or not isinstance(line_number, int)
+ or isinstance(line_number, bool)
+ or line_number < 1
+ ):
+ raise ValueError("Suppressed SARIF finding has a malformed location")
+ try:
+ data = (source_root / uri).read_bytes()
+ except OSError as exc:
+ raise ValueError(
+ f"Cannot read the source of a suppressed finding: {uri}"
+ ) from exc
+ # Semgrep splits lines at "\n" only; str.splitlines() would also split
+ # at characters such as U+2028 and shift the line numbers.
+ lines = data.decode("utf-8", errors="surrogateescape").split("\n")
+ if line_number > len(lines):
+ raise ValueError(f"Suppressed SARIF finding is beyond the end of {uri}")
+ previous = lines[line_number - 2] if line_number > 1 else None
+ return previous, lines[line_number - 1]
+
+
+def _check_reviewed_annotation(source_root: Path, result: dict) -> None:
+ """Require a reviewed annotation naming this suppressed result's rule.
+
+ The SARIF suppression does not record which rule a comment named, and a
+ bare ``nosemgrep`` hides every rule on its line, so the comment itself is
+ read back from the scanned file. The result's exact rule id must be one
+ of the ids the annotation lists; a suffix Semgrep would also honour is
+ not enough.
+ """
+ rule = result.get("ruleId")
+ previous, line = _source_lines(source_root, result)
+ if rule in reviewed_annotation_rules(line, previous_line=False):
+ return
+ if previous is not None and rule in reviewed_annotation_rules(
+ previous, previous_line=True
+ ):
+ return
+ uri = result["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]
+ raise ValueError(
+ f"Source-suppressed {rule} finding in {uri} has no reviewed "
+ f"'nosemgrep: {rule}, reason: <reason>' annotation"
+ )
+
+
def validate(report: object, sarif: object) -> Counter:
"""Validate both reports and return the JSON severity counts."""
severities, json_rules = _json_findings(report)
@@ -161,16 +298,90 @@ def validate(report: object, sarif: object) -> Counter:
return severities
+def prepare_github_sarif(
+ report: object, sarif: object, *, source_root: Path
+) -> dict:
+ """Validate the full scan, then omit source-suppressed results for GitHub.
+
+ Semgrep's native SARIF retains nosemgrep findings as inSource suppressions,
+ but GitHub's SARIF import does not honor them. Each suppressed result must
+ come from a reviewed annotation naming its rule, read from the scanned
+ file under ``source_root``. Preserve the native reports for diagnostics
+ and change only the upload copy's results arrays.
+ """
+ validate(report, sarif)
+ for run in sarif["runs"]:
+ for result in run["results"]:
+ if _source_suppressed(result):
+ _check_reviewed_annotation(source_root, result)
+ upload = copy.deepcopy(sarif)
+ for run in upload["runs"]:
+ run["results"] = [
+ result
+ for result in run["results"]
+ if not _source_suppressed(result)
+ ]
+ validate(report, upload)
+ return upload
+
+
+def _same_file(first: Path, second: Path) -> bool:
+ """Whether two paths name one file: same device and inode, or same path.
+
+ Comparing resolved paths alone misses a hard link to a raw report.
+ """
+ if first.resolve() == second.resolve():
+ return True
+ try:
+ a, b = os.stat(first), os.stat(second)
+ except FileNotFoundError:
+ return False
+ return (a.st_dev, a.st_ino) == (b.st_dev, b.st_ino)
+
+
+def _check_upload_path(output: Path, *raw_reports: Path) -> None:
+ if any(_same_file(output, path) for path in raw_reports):
+ raise ValueError("GitHub SARIF output must not overwrite a raw report")
+
+
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("json_report", type=Path)
parser.add_argument("sarif_report", type=Path)
+ parser.add_argument(
+ "--github-sarif-output",
+ type=Path,
+ help="Write a validated GitHub upload copy, retaining both raw reports",
+ )
+ parser.add_argument(
+ "--source-root",
+ type=Path,
+ default=Path(),
+ help="Directory the SARIF result paths are relative to "
+ "(default: the current directory, where Semgrep ran)",
+ )
args = parser.parse_args()
try:
- counts = validate(
- json.loads(args.json_report.read_text(encoding="utf-8")),
- json.loads(args.sarif_report.read_text(encoding="utf-8")),
- )
+ report = json.loads(args.json_report.read_text(encoding="utf-8"))
+ sarif = json.loads(args.sarif_report.read_text(encoding="utf-8"))
+ counts = validate(report, sarif)
+ if args.github_sarif_output is not None:
+ _check_upload_path(
+ args.github_sarif_output, args.json_report, args.sarif_report
+ )
+ upload = prepare_github_sarif(
+ report, sarif, source_root=args.source_root
+ )
+ args.github_sarif_output.write_text(
+ json.dumps(upload, indent=2) + "\n", encoding="utf-8"
+ )
+ omitted = sum(len(run["results"]) for run in sarif["runs"]) - sum(
+ len(run["results"]) for run in upload["runs"]
+ )
+ print(
+ f"Prepared GitHub SARIF: {omitted} source-suppressed findings "
+ "with reviewed annotations omitted"
+ )
except (
OSError,
ValueError,
diff --git a/.github/workflows/semgrep.yml b/.github/workflows/semgrep.yml
index 6fab92beb2..3a44e3a163 100644
--- a/.github/workflows/semgrep.yml
+++ b/.github/workflows/semgrep.yml
@@ -123,7 +123,18 @@ jobs:
- name: Validate complete scanner reports
id: report
- run: python .github/scripts/check_semgrep_report.py semgrep-results.json semgrep-results.sarif
+ # Semgrep retains nosemgrep findings in native SARIF; GitHub does not
+ # honor SARIF suppressions. Validate both raw reports before deriving
+ # an upload copy that omits only recognized source-suppressed results.
+ # Each one must sit on (or below) a rule-specific reviewed annotation,
+ # "nosemgrep: <rule-id>[, <rule-id>]..., reason: <reason>", read back
+ # from the checked-out file; a bare or unreviewed marker fails this
+ # step instead. The "reason:" item keeps Semgrep from failing the
+ # --strict scan when another rule matches an annotated line (see
+ # .semgrep/rules/README.md); that rule's finding is uploaded.
+ run: >-
+ python .github/scripts/check_semgrep_report.py semgrep-results.json semgrep-results.sarif
+ --github-sarif-output semgrep-results.github.sarif
# Upload only a successful, validated scan (implicit success(); never
# always()). An empty or partial report from a failed scan must never
@@ -133,7 +144,7 @@ jobs:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
uses: github/codeql-action/upload-sarif@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
with:
- sarif_file: semgrep-results.sarif
+ sarif_file: semgrep-results.github.sarif
category: semgrep-security
wait-for-processing: true
@@ -145,4 +156,5 @@ jobs:
path: |
semgrep-results.json
semgrep-results.sarif
+ semgrep-results.github.sarif
retention-days: 7
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 2fa5b8afb9..4b7bef2439 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -335,6 +335,15 @@ repos:
description: "Bearer ignores a bearer:disable directive unless it is the bare
rule id on its own line above the statement; reject same-line or
trailing-prose directives that would silently suppress nothing"
+ - id: check-nosemgrep-annotations
+ name: Check nosemgrep annotations are reviewed and rule-specific
+ entry: .pre-commit-hooks/check-nosemgrep-annotations.py
+ language: script
+ files: ^src/
+ types: [text]
+ description: "Semgrep honours any case-insensitive nosem marker, even in
+ strings, and a rule-less one hides every rule on its line from code
+ scanning; require `nosemgrep: <rule.id> -- <reason>` in a comment"
- id: check-loguru-formatting
name: Check loguru formatting style
entry: .pre-commit-hooks/check-loguru-formatting.py
diff --git a/.pre-commit-hooks/check-nosemgrep-annotations.py b/.pre-commit-hooks/check-nosemgrep-annotations.py
new file mode 100755
index 0000000000..1be7a0743d
--- /dev/null
+++ b/.pre-commit-hooks/check-nosemgrep-annotations.py
@@ -0,0 +1,183 @@
+#!/usr/bin/env python3
+"""Pre-commit guard: Semgrep ``nosemgrep`` annotations must be reviewed and
+rule-specific.
+
+Semgrep 1.177.0 honours a case-insensitive ``nosem``/``nosemgrep`` marker
+after a space anywhere on a finding's line (string literals, prose and words
+such as "NoSemantics" included) or at the start of the line above it. Without
+a rule id, a marker hides EVERY rule on that line. The GitHub upload omits
+source-suppressed findings, so such a marker silently removes alerts from
+code scanning and from the release gate.
+
+This hook fails the commit unless every marker Semgrep would honour in a
+scanned file (``src/``) is the only marker on its line and is written exactly
+as::
+
+ # nosemgrep: <rule.id>[, <rule.id>]..., reason: <reason>
+
+(``//``, ``{#``, ``<!--`` or ``/*`` instead of ``#`` outside Python). Each
+rule id must be namespaced (contain a dot), because Semgrep also accepts any
+suffix of a rule id. The reason must not contain a comma: Semgrep reads each
+comma-separated item after the colon as another rule id. The ``reason:``
+item is not a valid rule id, so it suppresses nothing, but it keeps the
+comment at two or more items; Semgrep 1.177.0 fails a ``--strict`` scan when
+a single-id comment sits on a line that another rule also matches.
+
+Python files are tokenized, so a marker inside a string literal or docstring
+is rejected even when it is well-formed. Other files only need the comment
+opener directly before the marker; a well-formed annotation embedded in a
+string there is not detected, but it still names its rules and a reason.
+
+The grammar is shared with ``.github/scripts/check_semgrep_report.py``,
+which also rejects, at upload time, any source-suppressed finding whose
+line lacks a reviewed annotation naming its rule.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import io
+import sys
+import tokenize
+from pathlib import Path
+
+_REPORT_SCRIPT = (
+ Path(__file__).resolve().parents[1]
+ / ".github"
+ / "scripts"
+ / "check_semgrep_report.py"
+)
+_SPEC = importlib.util.spec_from_file_location(
+ "check_semgrep_report", _REPORT_SCRIPT
+)
+_REPORT = importlib.util.module_from_spec(_SPEC)
+_SPEC.loader.exec_module(_REPORT)
+
+# A marker must start a comment: the opener, one space, then the marker.
+_COMMENT_OPENERS = ("# ", "// ", "{# ", "{#- ", "<!-- ", "/* ")
+
+_FORM = "write it as `nosemgrep: <rule.id>[, <rule.id>]..., reason: <reason>`"
+_MULTIPLE_MSG = (
+ "more than one nosem marker on one line; Semgrep reads each one, so keep "
+ "a single reviewed annotation per line"
+)
+_CASE_MSG = (
+ "Semgrep matches `nosem`/`nosemgrep` in any case, so this text acts as a "
+ f"suppression; {_FORM} (lowercase) or reword it"
+)
+_FORM_MSG = (
+ "a bare, rule-less or reasonless nosemgrep, or one without the "
+ "`reason:` item, hides rules without review or fails a strict scan; "
+ f"{_FORM}, with no comma in the reason"
+)
+_NAMESPACE_MSG = (
+ "use fully qualified rule ids: Semgrep also accepts any suffix of a "
+ "rule id, so a short id can hide other rules"
+)
+_COMMENT_MSG = (
+ "the marker must start a comment (`# `, `// `, `{# `, `<!-- ` or `/* ` "
+ "directly before it); Semgrep also honours text in strings and code"
+)
+_STRING_MSG = (
+ "nosem text inside a Python string or docstring still suppresses "
+ "Semgrep findings; move the annotation into a `#` comment or reword it"
+)
+
+
+def _python_comment_spans(content: str) -> list[tuple[int, int, int]] | None:
+ """(row, start_col, end_col) of each comment, or None if untokenizable."""
+ try:
+ tokens = tokenize.generate_tokens(io.StringIO(content).readline)
+ return [
+ (tok.start[0], tok.start[1], tok.end[1])
+ for tok in tokens
+ if tok.type == tokenize.COMMENT
+ ]
+ except (tokenize.TokenError, IndentationError, SyntaxError):
+ return None
+
+
+def check_line(line: str) -> str | None:
+ """The violation on one line, or None if it has no marker or is valid."""
+ offsets = sorted(
+ set(_REPORT.nosem_markers(line, previous_line=False))
+ | set(_REPORT.nosem_markers(line, previous_line=True))
+ )
+ if not offsets:
+ return None
+ if len(offsets) > 1:
+ return _MULTIPLE_MSG
+ offset = offsets[0]
+ rest = line[offset:].rstrip("\r")
+ if not rest.startswith("nosemgrep"):
+ return _CASE_MSG
+ match = _REPORT.REVIEWED_ANNOTATION.fullmatch(rest)
+ if match is None:
+ return _FORM_MSG
+ if any("." not in rule for rule in match.group("rules").split(", ")):
+ return _NAMESPACE_MSG
+ if not line[:offset].endswith(_COMMENT_OPENERS):
+ return _COMMENT_MSG
+ return None
+
+
+def check_content(content: str, *, python: bool) -> list[tuple[int, str]]:
+ errors: list[tuple[int, str]] = []
+ # Semgrep splits lines at "\n" only.
+ lines = content.split("\n")
+ comments = _python_comment_spans(content) if python else None
+ for row, line in enumerate(lines, start=1):
+ msg = check_line(line)
+ if msg is None and python and comments is not None:
+ offsets = _REPORT.nosem_markers(
+ line, previous_line=False
+ ) + _REPORT.nosem_markers(line, previous_line=True)
+ if offsets and not any(
+ r == row and start <= offsets[0] < end
+ for r, start, end in comments
+ ):
+ msg = _STRING_MSG
+ if msg is not None:
+ errors.append((row, msg))
+ return errors
+
+
+def check_file(filename: str) -> list[tuple[int, str]]:
+ try:
+ content = (
+ Path(filename)
+ .read_bytes()
+ .decode("utf-8", errors="surrogateescape")
+ )
+ except OSError:
+ return []
+ # A UTF-8 BOM is part of Semgrep's first line but not of a comment token.
+ python = filename.endswith(".py")
+ if python and content.startswith(""):
+ content = content[1:]
+ return check_content(content, python=python)
+
+
+def main(argv: list[str]) -> int:
+ failed = False
+ for filename in argv:
+ errors = check_file(filename)
+ if errors:
+ failed = True
+ print(f"\n{filename}:")
+ for line_num, msg in sorted(errors):
+ print(f" Line {line_num}: {msg}")
+ if failed:
+ print(
+ "\nUnreviewed Semgrep suppression(s). Each nosemgrep annotation must "
+ "name fully\nqualified rules and give a reason, e.g.:\n"
+ " # nosemgrep: semgrep.rules.weak-random-generation, "
+ "reason: jitter only\n"
+ "See .semgrep/rules/README.md."
+ )
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/.semgrep/rules/README.md b/.semgrep/rules/README.md
index c4dd769e4c..f8a06a7de4 100644
--- a/.semgrep/rules/README.md
+++ b/.semgrep/rules/README.md
@@ -91,6 +91,37 @@ semgrep --config=.semgrep/rules/ src/
semgrep --config=p/security-audit --config=.semgrep/rules/ src/
```
+## GitHub upload and source suppressions
+
+Semgrep 1.177.0 omits `nosemgrep` findings from its JSON report but retains
+them in native SARIF with `inSource` suppression metadata. GitHub's SARIF
+import does not honor that metadata, so uploading the native report would
+publish the ignored findings as open alerts.
+
+The workflow validates the complete native JSON and SARIF reports, then
+creates `semgrep-results.github.sarif`. Only results with recognized
+`inSource` suppressions (no status, or `accepted`) are omitted from that
+copy, and only when the scanned file holds a reviewed annotation naming the
+result's rule (see below) on the result's first line or on the line above
+it. The SARIF suppression does not record which rule a comment named, so
+the validator reads the line back; a suppressed result without such an
+annotation fails validation. Unknown suppression kinds or statuses fail
+validation too. All other
+findings and scan metadata are preserved, and the upload copy is validated
+again. Scanner errors, skipped rules, empty scope and mismatched reports
+still prevent upload.
+
+The diagnostic artifact retains both native reports and the GitHub upload
+copy for 7 days. Tests using native scanner reports and synthetic fixtures check that
+suppressing one result preserves every unsuppressed result, including the
+same rule at other locations and other rules at the same location; the
+real-scanner test runs three rules on one line, annotates one or two of
+them, and checks that the strict scan stays error-free and the rest are
+uploaded.
+
+References: [Semgrep source suppressions](https://docs.semgrep.dev/ignoring-files-folders-code)
+and [GitHub's supported SARIF properties](https://docs.github.com/en/code-security/reference/code-scanning/sarif-files/sarif-support).
+
## Adding New Rules
To add new custom rules:
@@ -100,6 +131,59 @@ To add new custom rules:
3. Test the rule: `semgrep --config=.semgrep/rules/your-rule.yaml src/`
4. Document the rule in this README
+## Reviewed source annotations
+
+Use a rule-specific reviewed annotation beside a reviewed false positive,
+at the end of the finding's first line or alone on the line above it:
+
+```python
+# nosemgrep: semgrep.rules.weak-random-generation, reason: Non-security jitter
+delay_seconds = random.randint(1, 30)
+```
+
+Write it exactly as `nosemgrep: <rule-id>[, <rule-id>]..., reason: <reason>`,
+starting a comment (`#`, `//`, `{#`, `<!--` or `/*`), with fully qualified
+rule ids (list several when one line has several reviewed false positives)
+and no comma in the reason. Semgrep 1.177.0 honours a case-insensitive
+`nosem` marker after a space anywhere on a line, including string literals
+and words such as "NoSemantics", and a marker without a rule id hides every
+rule on that line. Semgrep also accepts any suffix of a rule id and reads
+the first word of each comma-separated item after the colon as a rule id.
+The `check-nosemgrep-annotations` pre-commit hook rejects every other marker
+under `src/`, including one inside a Python string or docstring, and the
+upload validator rejects a suppressed result without an annotation naming
+its exact rule id.
+
+The `reason:` item is required, not decoration. Semgrep reads it as one
+more id; `reason:` is not a valid rule id, so it suppresses nothing. But a
+comment with a single id makes Semgrep 1.177.0 report a warning for every
+other rule that matches the same line ("found 'nosem' comment with id ...,
+but no corresponding rule trying ..."), and under `--strict` that fails the
+whole scan, and so the release gate. Semgrep skips that warning when a
+comment holds two or more ids, so with the `reason:` item a new or updated
+rule matching an annotated line produces an ordinary uploaded alert
+instead. If that alert is another reviewed false positive, add its rule id
+to the annotation.
+
+Keep the rule enabled elsewhere; do not exclude a file or weaken the release
+threshold to clear an alert. Re-review the annotation when the expression or
+its input boundary changes.
+
+The October 2026 review identified these cases:
+
+| Finding | Why the annotated use is safe | Existing verification |
+| --- | --- | --- |
+| Seven script interpolations | Jinja's `tojson` escapes HTML delimiters before embedding JSON in a script. | Template injection and JSON rendering tests in `tests/security/test_injection_and_template_safety.py`. |
+| Eleven unquoted attribute expressions | Both branches emit fixed `selected`/`checked` tokens or the empty string; no input is inserted into an attribute name. | Inspect the literal branches in `embedding_settings.html`; the rest of each attribute remains quoted. |
+| `help_tip`'s `safe` filter | Every current caller passes a source literal, intentionally containing help markup. | Review all call sites. The existing security test catches simple variable arguments, but does not fully parse composed Jinja expressions. |
+| Four `random` calls | They control subscription jitter or rate-limit exploration, not credentials, identifiers or authorization. | Scheduler and rate-limit tests; cryptographic operations still use `secrets`. |
+| Two apparent secrets | One is an empty API-key default; the other is the existing placeholder only used for unencrypted databases. | Configuration and authentication tests retain the surrounding behavior. |
+| Two pickle calls | They raise `UnpicklingError` on rejected globals/extensions rather than loading data. | `tests/vector_stores/test_faiss_safe_load_security.py` exercises hostile payloads, extension caches, persistent IDs and legitimate docstores. |
+| XML import | It imports `xml.sax.saxutils.escape` to encode text, not an XML parser. | Note-AI prompt rendering tests. |
+
+The separate DevSkim annotation in `services/ui.js` covers its fragment-based
+anchor renderer, which already adds both `noopener` and `noreferrer`.
+
## Rule Template
```yaml
diff --git a/changelog.d/+semgrep-source-suppressions.bugfix.md b/changelog.d/+semgrep-source-suppressions.bugfix.md
new file mode 100644
index 0000000000..1be2114fd9
--- /dev/null
+++ b/changelog.d/+semgrep-source-suppressions.bugfix.md
@@ -0,0 +1 @@
+Honor Semgrep source suppressions from rule-specific reviewed annotations (`nosemgrep: <rule-id>[, <rule-id>]..., reason: <reason>`) in GitHub code-scanning uploads while preserving all other findings, including findings of other rules on an annotated line (the `reason:` item keeps Semgrep's `--strict` scan from failing on them). A source-suppressed finding whose line lacks such an annotation for its rule fails the scan instead of being omitted, a new pre-commit hook rejects bare, rule-less, case-variant and string-literal `nosem` markers under `src/`, and the complete native scan reports remain in the workflow's 7-day diagnostic artifact.
diff --git a/src/local_deep_research/research_library/notes/services/note_ai_service.py b/src/local_deep_research/research_library/notes/services/note_ai_service.py
index 723dc0737a..fda6ba3dda 100644
--- a/src/local_deep_research/research_library/notes/services/note_ai_service.py
+++ b/src/local_deep_research/research_library/notes/services/note_ai_service.py
@@ -10,6 +10,8 @@ import math
import re
import threading
from typing import Any, Callable, Dict, List, Optional, TypeVar
+
+# nosemgrep: python.lang.security.use-defused-xml.use-defused-xml, reason: Text escaping only; this import does not expose an XML parser
from xml.sax.saxutils import escape as xml_escape
from loguru import logger
diff --git a/src/local_deep_research/research_library/services/faiss_safe_load.py b/src/local_deep_research/research_library/services/faiss_safe_load.py
index 0012ea7e45..8c8f991f7b 100644
--- a/src/local_deep_research/research_library/services/faiss_safe_load.py
+++ b/src/local_deep_research/research_library/services/faiss_safe_load.py
@@ -73,12 +73,14 @@ class _RestrictedFaissUnpickler(pickle._Unpickler):
def find_class(self, module: str, name: str) -> Any:
if (module, name) in _ALLOWED_GLOBALS:
return super().find_class(module, name)
+ # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle, reason: Raises a rejection exception; this call does not deserialize data
raise pickle.UnpicklingError(
f"Refusing to unpickle disallowed object '{module}.{name}' from "
f"FAISS docstore (possible tampering)."
)
def get_extension(self, code: int) -> Any:
+ # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle, reason: Raises a rejection exception; this call does not deserialize data
raise pickle.UnpicklingError(
f"Refusing to resolve copyreg extension code {code} from FAISS "
f"docstore (possible tampering)."
diff --git a/src/local_deep_research/research_library/zotero/sync_service.py b/src/local_deep_research/research_library/zotero/sync_service.py
index 09411762c7..73f4404faa 100644
--- a/src/local_deep_research/research_library/zotero/sync_service.py
+++ b/src/local_deep_research/research_library/zotero/sync_service.py
@@ -149,6 +149,7 @@ class ZoteroConfig:
# On by default — inert until an API key is configured; the toggle is an
# opt-out kill-switch, not a required opt-in step.
enabled: bool = True
+ # nosemgrep: semgrep.rules.hardcoded-secret-detection, reason: Empty API-key default; not a credential
api_key: str = ""
library_type: str = "user"
library_id: str = ""
diff --git a/src/local_deep_research/scheduler/background.py b/src/local_deep_research/scheduler/background.py
index 08e92a2ad3..c14089b2b7 100644
--- a/src/local_deep_research/scheduler/background.py
+++ b/src/local_deep_research/scheduler/background.py
@@ -651,6 +651,7 @@ class BackgroundJobScheduler:
# Calculate jitter
# Security: random jitter to distribute subscription timing, not security-sensitive
max_jitter = int(self.config.get("max_jitter_seconds", 300))
+ # nosemgrep: semgrep.rules.weak-random-generation, reason: Non-security scheduling or rate-limit jitter
jitter = random.randint(0, max_jitter)
# Determine trigger based on frequency
@@ -1989,6 +1990,7 @@ class BackgroundJobScheduler:
for sub in overdue_subs:
# Run immediately with small random delay
# Security: random delay to stagger overdue jobs, not security-sensitive
+ # nosemgrep: semgrep.rules.weak-random-generation, reason: Non-security scheduling or rate-limit jitter
delay_seconds = random.randint(1, 30)
job_id = (
f"overdue_{username}_{sub.id}_{int(now.timestamp())}"
@@ -2106,6 +2108,7 @@ class BackgroundJobScheduler:
# Security: random jitter to distribute subscription timing, not security-sensitive
next_run = datetime.now(UTC) + timedelta(
minutes=sub.refresh_interval_minutes,
+ # nosemgrep: semgrep.rules.weak-random-generation, reason: Non-security scheduling or rate-limit jitter
seconds=random.randint(
0, int(self.config.get("max_jitter_seconds", 300))
),
diff --git a/src/local_deep_research/web/dependencies/auth.py b/src/local_deep_research/web/dependencies/auth.py
index d6b500b7d7..8bbbbf559e 100644
--- a/src/local_deep_research/web/dependencies/auth.py
+++ b/src/local_deep_research/web/dependencies/auth.py
@@ -386,6 +386,7 @@ def ensure_user_database(request: Request) -> None:
# Source 3: Dummy password for unencrypted databases
if not password and not db_manager.has_encryption:
+ # nosemgrep: semgrep.rules.hardcoded-secret-detection, reason: The placeholder is used only when SQLCipher encryption is unavailable
password = "dummy" # noqa: S105 — not a real password; placeholder for unencrypted DBs
if password:
diff --git a/src/local_deep_research/web/static/js/services/ui.js b/src/local_deep_research/web/static/js/services/ui.js
index e53a11d844..7b5e2708fd 100644
--- a/src/local_deep_research/web/static/js/services/ui.js
+++ b/src/local_deep_research/web/static/js/services/ui.js
@@ -297,7 +297,7 @@ function renderMarkdown(markdown) {
const renderer = new marked.Renderer();
const _origLink = renderer.link.bind(renderer);
renderer.link = function(token) {
- return _origLink(token).replace(/^<a /, '<a target="_blank" rel="noopener noreferrer" ');
+ return _origLink(token).replace(/^<a /, '<a target="_blank" rel="noopener noreferrer" '); // DevSkim: ignore DS610000
};
marked.setOptions({
breaks: true,
diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.html
index f1a5e5aad0..454a4b47b6 100644
--- a/src/local_deep_research/web/templates/base.html
+++ b/src/local_deep_research/web/templates/base.html
@@ -230,10 +230,10 @@
<!-- Consumed by: src/local_deep_research/web/static/js/config/constants.js (ResearchStates helpers) -->
<!-- Must remain a bare <script> (no defer) so window.* is set before defer-ed scripts run. -->
<script>
- window.RESEARCH_STATUS = Object.freeze({{ research_status_enum | tojson }});
- window.RESEARCH_TERMINAL_STATES = Object.freeze(new Set({{ research_terminal_states | tojson }}));
- window.LDR_LOG_LIMITS = Object.freeze({{ log_limits | tojson }});
- window.LDR_LOCAL_SEARCH_DEFAULTS = Object.freeze({{ local_search_defaults | tojson }});
+ window.RESEARCH_STATUS = Object.freeze({{ research_status_enum | tojson }}); // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiters
+ window.RESEARCH_TERMINAL_STATES = Object.freeze(new Set({{ research_terminal_states | tojson }})); // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiters
+ window.LDR_LOG_LIMITS = Object.freeze({{ log_limits | tojson }}); // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiters
+ window.LDR_LOCAL_SEARCH_DEFAULTS = Object.freeze({{ local_search_defaults | tojson }}); // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiters
</script>
<!-- Constants and URL Configuration -->
diff --git a/src/local_deep_research/web/templates/components/help_macros.html b/src/local_deep_research/web/templates/components/help_macros.html
index aee5d2b088..5b56ed45a0 100644
--- a/src/local_deep_research/web/templates/components/help_macros.html
+++ b/src/local_deep_research/web/templates/components/help_macros.html
@@ -113,7 +113,7 @@
{% macro help_tip(text, variant='info') %}
<div class="ldr-help-tip{% if variant == 'warning' %} ldr-help-tip--warning{% endif %}">
<i aria-hidden="true" class="fas fa-{% if variant == 'warning' %}exclamation-triangle{% else %}lightbulb{% endif %}" ></i>
- <span>{{ text|safe }}</span>
+ <span>{{ text|safe }}</span> {# nosemgrep: python.flask.security.xss.audit.template-unescaped-with-safe.template-unescaped-with-safe, reason: Current callers pass literal HTML; reviewed in test_injection_and_template_safety.py #}
</div>
{%- endmacro %}
diff --git a/src/local_deep_research/web/templates/pages/embedding_settings.html b/src/local_deep_research/web/templates/pages/embedding_settings.html
index 85442c4576..96876a04d7 100644
--- a/src/local_deep_research/web/templates/pages/embedding_settings.html
+++ b/src/local_deep_research/web/templates/pages/embedding_settings.html
@@ -154,10 +154,10 @@
<div class="ldr-form-group ldr-col-md-6">
<label for="splitter-type">{{ tooltip("Text Splitter Type", "Method used to split documents into chunks.") }}</label>
<select id="splitter-type" class="ldr-form-control">
- <option value="recursive" {{ 'selected' if local_search_defaults.splitter_type == 'recursive' else '' }}>Recursive (Default - uses separators)</option>
- <option value="token" {{ 'selected' if local_search_defaults.splitter_type == 'token' else '' }}>Token-based (Good for LLM context)</option>
- <option value="sentence" {{ 'selected' if local_search_defaults.splitter_type == 'sentence' else '' }}>Sentence-based (Clean boundaries)</option>
- <option value="semantic" {{ 'selected' if local_search_defaults.splitter_type == 'semantic' else '' }}>Semantic (Smart grouping - slower)</option>
+ <option value="recursive" {{ 'selected' if local_search_defaults.splitter_type == 'recursive' else '' }}>Recursive (Default - uses separators)</option> {# nosemgrep: generic.html-templates.security.unquoted-attribute-var.unquoted-attribute-var, reason: Only fixed selected/checked attribute names can be emitted #}
+ <option value="token" {{ 'selected' if local_search_defaults.splitter_type == 'token' else '' }}>Token-based (Good for LLM context)</option> {# nosemgrep: generic.html-templates.security.unquoted-attribute-var.unquoted-attribute-var, reason: Only fixed selected/checked attribute names can be emitted #}
+ <option value="sentence" {{ 'selected' if local_search_defaults.splitter_type == 'sentence' else '' }}>Sentence-based (Clean boundaries)</option> {# nosemgrep: generic.html-templates.security.unquoted-attribute-var.unquoted-attribute-var, reason: Only fixed selected/checked attribute names can be emitted #}
+ <option value="semantic" {{ 'selected' if local_search_defaults.splitter_type == 'semantic' else '' }}>Semantic (Smart grouping - slower)</option> {# nosemgrep: generic.html-templates.security.unquoted-attribute-var.unquoted-attribute-var, reason: Only fixed selected/checked attribute names can be emitted #}
</select>
<small class="ldr-form-text ldr-text-muted">
Recursive and semantic respect text separators; token and sentence ignore them.
@@ -166,9 +166,9 @@
<div class="ldr-form-group ldr-col-md-6">
<label for="distance-metric">Distance Metric</label>
<select id="distance-metric" class="ldr-form-control">
- <option value="cosine" {{ 'selected' if local_search_defaults.distance_metric == 'cosine' else '' }}>Cosine Similarity (Recommended)</option>
- <option value="l2" {{ 'selected' if local_search_defaults.distance_metric == 'l2' else '' }}>Euclidean Distance (L2)</option>
- <option value="dot_product" {{ 'selected' if local_search_defaults.distance_metric == 'dot_product' else '' }}>Dot Product</option>
+ <option value="cosine" {{ 'selected' if local_search_defaults.distance_metric == 'cosine' else '' }}>Cosine Similarity (Recommended)</option> {# nosemgrep: generic.html-templates.security.unquoted-attribute-var.unquoted-attribute-var, reason: Only fixed selected/checked attribute names can be emitted #}
+ <option value="l2" {{ 'selected' if local_search_defaults.distance_metric == 'l2' else '' }}>Euclidean Distance (L2)</option> {# nosemgrep: generic.html-templates.security.unquoted-attribute-var.unquoted-attribute-var, reason: Only fixed selected/checked attribute names can be emitted #}
+ <option value="dot_product" {{ 'selected' if local_search_defaults.distance_metric == 'dot_product' else '' }}>Dot Product</option> {# nosemgrep: generic.html-templates.security.unquoted-attribute-var.unquoted-attribute-var, reason: Only fixed selected/checked attribute names can be emitted #}
</select>
<small class="ldr-form-text ldr-text-muted">
Cosine similarity recommended for text embeddings
@@ -177,9 +177,9 @@
<div class="ldr-form-group ldr-col-md-6">
<label for="index-type">{{ tooltip("Index Type", "Flat: exact but slow for large collections. HNSW: approximate but 50x faster for >10K docs. IVF: good balance for frequently updated collections.") }}</label>
<select id="index-type" class="ldr-form-control">
- <option value="flat" {{ 'selected' if local_search_defaults.index_type == 'flat' else '' }}>Flat (Exact search, &lt;10K docs)</option>
- <option value="hnsw" {{ 'selected' if local_search_defaults.index_type == 'hnsw' else '' }}>HNSW (Fast, large collections)</option>
- <option value="ivf" {{ 'selected' if local_search_defaults.index_type == 'ivf' else '' }}>IVF (Balanced, updates)</option>
+ <option value="flat" {{ 'selected' if local_search_defaults.index_type == 'flat' else '' }}>Flat (Exact search, &lt;10K docs)</option> {# nosemgrep: generic.html-templates.security.unquoted-attribute-var.unquoted-attribute-var, reason: Only fixed selected/checked attribute names can be emitted #}
+ <option value="hnsw" {{ 'selected' if local_search_defaults.index_type == 'hnsw' else '' }}>HNSW (Fast, large collections)</option> {# nosemgrep: generic.html-templates.security.unquoted-attribute-var.unquoted-attribute-var, reason: Only fixed selected/checked attribute names can be emitted #}
+ <option value="ivf" {{ 'selected' if local_search_defaults.index_type == 'ivf' else '' }}>IVF (Balanced, updates)</option> {# nosemgrep: generic.html-templates.security.unquoted-attribute-var.unquoted-attribute-var, reason: Only fixed selected/checked attribute names can be emitted #}
</select>
<small class="ldr-form-text ldr-text-muted">
HNSW recommended for &gt;10K documents (50-60× faster)
@@ -189,7 +189,7 @@
<div class="ldr-form-group">
<label>
- <input type="checkbox" id="normalize-vectors" {{ 'checked' if local_search_defaults.normalize_vectors else '' }}>
+ <input type="checkbox" id="normalize-vectors" {{ 'checked' if local_search_defaults.normalize_vectors else '' }}> {# nosemgrep: generic.html-templates.security.unquoted-attribute-var.unquoted-attribute-var, reason: Only fixed selected/checked attribute names can be emitted #}
Normalize vectors (L2)
</label>
<small class="ldr-form-text ldr-text-muted" style="display: block; margin-left: 25px;">
diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.html
index 98e61c5f30..26798b4805 100644
--- a/src/local_deep_research/web/templates/pages/library.html
+++ b/src/local_deep_research/web/templates/pages/library.html
@@ -1271,8 +1271,8 @@ document.querySelectorAll('.ldr-view-toggle button').forEach(btn => {
<!-- Semantic Search -->
<script>
- var DEFAULT_LIBRARY_COLLECTION_ID = {{ (default_collection_id or '')|tojson }};
- var COLLECTIONS_DATA = {{ collections|tojson }};
+ var DEFAULT_LIBRARY_COLLECTION_ID = {{ (default_collection_id or '')|tojson }}; // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiters
+ var COLLECTIONS_DATA = {{ collections|tojson }}; // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiters
</script>
<script defer src="/static/js/components/semantic_search.js"></script>
<script defer src="/static/js/components/library_search.js"></script>
diff --git a/src/local_deep_research/web/templates/pages/note_detail.html b/src/local_deep_research/web/templates/pages/note_detail.html
index 6a44d7b5fe..cf3b112366 100644
--- a/src/local_deep_research/web/templates/pages/note_detail.html
+++ b/src/local_deep_research/web/templates/pages/note_detail.html
@@ -1972,7 +1972,7 @@
<!-- Note: url-validator.js, ui.js, urls.js, formatting.js, api.js are already loaded in base.html -->
<script>
// Pass note ID to JavaScript
- window.noteId = {{ note_id | tojson }};
+ window.noteId = {{ note_id | tojson }}; // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiters
</script>
<!-- Shared SemanticSearch helpers — provides window.SemanticSearch.isSafeExternalUrl,
used to gate external source links rendered by the fact-check verdicts. -->
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
index 711b22057d..7f514b3706 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
@@ -470,6 +470,7 @@ class AdaptiveRateLimitTracker:
# Security: random used for non-security rate-limit jitter, not tokens or secrets
# Exploration vs exploitation
+ # nosemgrep: semgrep.rules.weak-random-generation, reason: Non-security scheduling or rate-limit jitter
if random.random() < self.exploration_rate:
# Explore: try a faster rate to see if API limits have relaxed
wait_time = base_wait * random.uniform(0.5, 0.9)
diff --git a/tests/ci/standalone/test_semgrep_integration.py b/tests/ci/standalone/test_semgrep_integration.py
index abc2948fcc..9a9ed43cf6 100644
--- a/tests/ci/standalone/test_semgrep_integration.py
+++ b/tests/ci/standalone/test_semgrep_integration.py
@@ -17,6 +17,305 @@ ROOT = Path(__file__).resolve().parents[3]
shutil.which("semgrep"), "Semgrep integration runs in scanner CI"
)
class ScannerTests(unittest.TestCase):
+ def test_github_upload_honors_only_the_selected_source_suppression(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ rules = root / "rules.yml"
+ rules.write_text(
+ "rules:\n"
+ + "".join(
+ f" - id: probe-{severity.lower()}\n"
+ f" languages: [python]\n pattern: probe_{severity.lower()}()\n"
+ f" message: Synthetic {severity} finding\n severity: {severity}\n"
+ for severity in ("ERROR", "WARNING", "INFO")
+ ),
+ encoding="utf-8",
+ )
+ target = root / "example.py"
+ target.write_text(
+ "probe_error() # nosemgrep: probe-error, reason: reviewed probe\n"
+ "probe_error()\n"
+ "probe_warning()\nprobe_warning()\nprobe_info()\nprobe_info()\n",
+ encoding="utf-8",
+ )
+ report_path, sarif_path = (
+ root / "report.json",
+ root / "report.sarif",
+ )
+ upload_path = root / "github.sarif"
+ scanned = subprocess.run(
+ [
+ "semgrep",
+ "scan",
+ "--config",
+ str(rules),
+ "--strict",
+ "--metrics=off",
+ "--disable-version-check",
+ "--json-output",
+ str(report_path),
+ "--sarif-output",
+ str(sarif_path),
+ str(target),
+ ],
+ cwd=root,
+ capture_output=True,
+ text=True,
+ timeout=90,
+ check=False,
+ )
+ self.assertEqual(scanned.returncode, 0, scanned.stderr)
+ originals = report_path.read_bytes(), sarif_path.read_bytes()
+ native = json.loads(originals[1])
+ self.assertEqual(len(native["runs"][0]["results"]), 6)
+ checked = subprocess.run(
+ [
+ sys.executable,
+ str(ROOT / ".github/scripts/check_semgrep_report.py"),
+ str(report_path),
+ str(sarif_path),
+ "--github-sarif-output",
+ str(upload_path),
+ "--source-root",
+ str(root),
+ ],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ )
+ self.assertEqual(
+ checked.returncode, 0, checked.stdout + checked.stderr
+ )
+ uploaded = json.loads(upload_path.read_text(encoding="utf-8"))
+ positions = {
+ (
+ result["ruleId"],
+ result["locations"][0]["physicalLocation"]["region"][
+ "startLine"
+ ],
+ )
+ for result in uploaded["runs"][0]["results"]
+ }
+ self.assertEqual(
+ positions,
+ {
+ ("probe-error", 2),
+ ("probe-warning", 3),
+ ("probe-warning", 4),
+ ("probe-info", 5),
+ ("probe-info", 6),
+ },
+ )
+ self.assertEqual(len(uploaded["runs"][0]["results"]), 5)
+ self.assertEqual(
+ uploaded["runs"][0]["tool"], native["runs"][0]["tool"]
+ )
+ self.assertEqual(
+ uploaded["runs"][0]["invocations"],
+ native["runs"][0]["invocations"],
+ )
+ self.assertEqual(
+ (report_path.read_bytes(), sarif_path.read_bytes()), originals
+ )
+
+ def test_other_rules_on_an_annotated_line_are_uploaded(self):
+ """A reviewed annotation must not break the scan for other rules.
+
+ Three rules match each probe_x() call. An annotation naming one or
+ two of them must leave the strict scan error-free and the other
+ rules' results in the upload: Semgrep 1.177.0 fails a --strict scan
+ when a single-id nosemgrep comment sits on a line that another rule
+ matches, which the trailing "reason:" item avoids.
+ """
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ rules = root / "rules.yml"
+ rules.write_text(
+ "rules:\n"
+ + "".join(
+ f" - id: probe-{name}\n"
+ " languages: [python]\n pattern: probe_x()\n"
+ f" message: Synthetic {name} finding\n"
+ " severity: WARNING\n"
+ for name in ("a", "b", "c")
+ ),
+ encoding="utf-8",
+ )
+ target = root / "example.py"
+ report_path, sarif_path = (
+ root / "report.json",
+ root / "report.sarif",
+ )
+ upload_path = root / "github.sarif"
+
+ def scan(code):
+ target.write_text(code, encoding="utf-8")
+ return subprocess.run(
+ [
+ "semgrep",
+ "scan",
+ "--config",
+ str(rules),
+ "--strict",
+ "--metrics=off",
+ "--disable-version-check",
+ "--json-output",
+ str(report_path),
+ "--sarif-output",
+ str(sarif_path),
+ str(target),
+ ],
+ cwd=root,
+ capture_output=True,
+ text=True,
+ timeout=90,
+ check=False,
+ )
+
+ # The premise: a comment with a single id fails the strict scan
+ # as soon as another rule matches its line.
+ scanned = scan("probe_x() # nosemgrep: probe-a\n")
+ self.assertNotEqual(scanned.returncode, 0, scanned.stderr)
+ self.assertIn(
+ "no corresponding rule trying",
+ json.dumps(
+ json.loads(report_path.read_text(encoding="utf-8"))[
+ "errors"
+ ]
+ ),
+ )
+
+ scanned = scan(
+ "probe_x() # nosemgrep: probe-a, reason: reviewed probe\n"
+ "# nosemgrep: probe-a, probe-b, reason: reviewed probe\n"
+ "probe_x()\n"
+ )
+ self.assertEqual(scanned.returncode, 0, scanned.stderr)
+ report = json.loads(report_path.read_text(encoding="utf-8"))
+ self.assertEqual(report["errors"], [])
+
+ def positions(sarif, suppressed):
+ return {
+ (
+ result["ruleId"],
+ result["locations"][0]["physicalLocation"]["region"][
+ "startLine"
+ ],
+ )
+ for result in sarif["runs"][0]["results"]
+ if bool(result.get("suppressions")) is suppressed
+ }
+
+ native = json.loads(sarif_path.read_text(encoding="utf-8"))
+ self.assertEqual(
+ positions(native, True),
+ {("probe-a", 1), ("probe-a", 3), ("probe-b", 3)},
+ )
+ checked = subprocess.run(
+ [
+ sys.executable,
+ str(ROOT / ".github/scripts/check_semgrep_report.py"),
+ str(report_path),
+ str(sarif_path),
+ "--github-sarif-output",
+ str(upload_path),
+ "--source-root",
+ str(root),
+ ],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ )
+ self.assertEqual(
+ checked.returncode, 0, checked.stdout + checked.stderr
+ )
+ uploaded = json.loads(upload_path.read_text(encoding="utf-8"))
+ self.assertEqual(
+ positions(uploaded, False),
+ {("probe-b", 1), ("probe-c", 1), ("probe-c", 3)},
+ )
+ self.assertEqual(len(uploaded["runs"][0]["results"]), 3)
+
+ def test_github_upload_rejects_unreviewed_source_suppressions(self):
+ """Semgrep honours each of these; none may drop a GitHub alert."""
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ rules = root / "rules.yml"
+ rules.write_text(
+ "rules:\n - id: probe-error\n languages: [python]\n"
+ " pattern: probe_error()\n message: Synthetic finding\n"
+ " severity: ERROR\n",
+ encoding="utf-8",
+ )
+ target = root / "example.py"
+ for line in (
+ "probe_error() # nosemgrep",
+ "probe_error() # NOSEMGREP: probe-error, reason: reviewed probe",
+ "probe_error() # nosemgrep: probe-error",
+ "probe_error() # nosemgrep: probe-error -- reviewed probe",
+ 'probe_error() or "see nosemgrep docs"',
+ "probe_error() # NoSemantics",
+ ):
+ with self.subTest(line=line):
+ target.write_text(line + "\n", encoding="utf-8")
+ report_path = root / "report.json"
+ sarif_path = root / "report.sarif"
+ upload_path = root / "github.sarif"
+ scanned = subprocess.run(
+ [
+ "semgrep",
+ "scan",
+ "--config",
+ str(rules),
+ "--strict",
+ "--metrics=off",
+ "--disable-version-check",
+ "--json-output",
+ str(report_path),
+ "--sarif-output",
+ str(sarif_path),
+ str(target),
+ ],
+ cwd=root,
+ capture_output=True,
+ text=True,
+ timeout=90,
+ check=False,
+ )
+ self.assertEqual(scanned.returncode, 0, scanned.stderr)
+ native = json.loads(sarif_path.read_text(encoding="utf-8"))
+ # The premise: Semgrep itself suppressed the finding.
+ self.assertEqual(
+ [
+ r.get("suppressions")
+ for r in native["runs"][0]["results"]
+ ],
+ [[{"kind": "inSource"}]],
+ )
+ checked = subprocess.run(
+ [
+ sys.executable,
+ str(
+ ROOT / ".github/scripts/check_semgrep_report.py"
+ ),
+ str(report_path),
+ str(sarif_path),
+ "--github-sarif-output",
+ str(upload_path),
+ "--source-root",
+ str(root),
+ ],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ )
+ self.assertEqual(checked.returncode, 1, checked.stdout)
+ self.assertIn("no reviewed", checked.stdout)
+ self.assertFalse(upload_path.exists())
+
def test_native_reports_preserve_all_severities_and_clean_control(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
diff --git a/tests/ci/standalone/test_semgrep_report.py b/tests/ci/standalone/test_semgrep_report.py
index f1f1dcfde1..f3e1ed4af5 100644
--- a/tests/ci/standalone/test_semgrep_report.py
+++ b/tests/ci/standalone/test_semgrep_report.py
@@ -7,6 +7,7 @@ import copy
import importlib.util
import io
import json
+import os
import sys
import tempfile
import unittest
@@ -55,6 +56,13 @@ BAD_SECURITY_SEVERITIES = (
class ReportTests(unittest.TestCase):
def setUp(self):
+ # Suppressed results are checked against the scanned source file.
+ source_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(source_dir.cleanup)
+ self.source_root = Path(source_dir.name)
+ self._write_source(
+ {4: "probe() # nosemgrep: example, reason: reviewed probe"}
+ )
self.report = {
"errors": [],
"skipped_rules": [],
@@ -111,6 +119,39 @@ class ReportTests(unittest.TestCase):
sarif["runs"][0]["results"] = [result]
return report, sarif
+ def _write_source(self, lines, name="example.py"):
+ """Write ``name`` with ``lines`` ({number: text}), others as code."""
+ last = max(8, *lines)
+ text = "\n".join(
+ lines.get(number, "probe()") for number in range(1, last + 1)
+ )
+ (self.source_root / name).write_text(text, encoding="utf-8")
+
+ @staticmethod
+ def _location(line, uri="example.py"):
+ return [
+ {
+ "physicalLocation": {
+ "artifactLocation": {"uri": uri},
+ "region": {"startLine": line},
+ }
+ }
+ ]
+
+ def _suppressed_finding(self, line=4, uri="example.py"):
+ """A JSON/SARIF pair whose only finding is source-suppressed."""
+ report, sarif = self._with_finding()
+ report["results"][0]["extra"]["is_ignored"] = True
+ result = sarif["runs"][0]["results"][0]
+ result["suppressions"] = [{"kind": "inSource"}]
+ result["locations"] = self._location(line, uri)
+ return report, sarif
+
+ def _prepare(self, report, sarif):
+ return POLICY.prepare_github_sarif(
+ report, sarif, source_root=self.source_root
+ )
+
def _rejects(self, message, report, sarif):
"""Assert validation fails with ``message``, not some other check.
@@ -428,6 +469,347 @@ class ReportTests(unittest.TestCase):
self.assertEqual(POLICY.validate(ignored, suppressed), {"WARNING": 1})
self.assertEqual(POLICY.validate(ignored, truncated), {"WARNING": 1})
+ def test_github_upload_preserves_unsuppressed_results_and_metadata(self):
+ for suppression in (
+ {"kind": "inSource"},
+ {
+ "kind": "inSource",
+ "status": "accepted",
+ "justification": "Reviewed",
+ },
+ ):
+ with self.subTest(suppression=suppression):
+ report, sarif = self._with_finding()
+ run = sarif["runs"][0]
+ run["automationDetails"] = {"id": "semgrep-security/"}
+ kept = run["results"][0]
+ kept.update(
+ {
+ "suppressions": [],
+ "message": {"text": "Must remain visible"},
+ "partialFingerprints": {
+ "primaryLocationLineHash": "abc"
+ },
+ "locations": self._location(8),
+ "codeFlows": [{"threadFlows": []}],
+ }
+ )
+ # Same rule as the retained result: rule-wide removal is wrong.
+ removed = copy.deepcopy(kept)
+ removed["suppressions"] = [suppression]
+ removed["locations"][0]["physicalLocation"]["region"][
+ "startLine"
+ ] = 4
+ run["results"].insert(0, removed)
+ # A different rule at the suppressed location must survive.
+ other = copy.deepcopy(kept)
+ other["ruleId"] = "another-rule"
+ other["locations"][0]["physicalLocation"]["region"][
+ "startLine"
+ ] = 4
+ run["results"].append(other)
+ descriptor = copy.deepcopy(run["tool"]["driver"]["rules"][0])
+ descriptor["id"] = "another-rule"
+ run["tool"]["driver"]["rules"].append(descriptor)
+ other_json = copy.deepcopy(report["results"][0])
+ other_json["check_id"] = "another-rule"
+ report["results"].append(other_json)
+ # Preserve other runs and repeated findings, not just a set of IDs.
+ sarif["runs"].append(copy.deepcopy(run))
+ report["results"] *= 2
+ original_sarif = copy.deepcopy(sarif)
+ original_report = copy.deepcopy(report)
+ expected = copy.deepcopy(sarif)
+ for output_run in expected["runs"]:
+ output_run["results"] = copy.deepcopy([kept, other])
+
+ self.assertEqual(self._prepare(report, sarif), expected)
+ self.assertEqual(sarif, original_sarif)
+ self.assertEqual(report, original_report)
+
+ def test_github_upload_without_suppressions_is_unchanged(self):
+ report, sarif = self._with_finding()
+ self.assertEqual(self._prepare(report, sarif), sarif)
+
+ def test_all_suppressed_upload_keeps_rules_and_scan_metadata(self):
+ _, sarif = self._suppressed_finding()
+ upload = self._prepare(self.report, sarif)
+ self.assertEqual(upload, self.sarif)
+
+ def test_unknown_suppression_semantics_fail_closed(self):
+ for suppressions in (
+ None,
+ True,
+ {},
+ "inSource",
+ [None],
+ [{}],
+ [{"kind": "external"}],
+ [{"kind": "inSource", "status": "rejected"}],
+ [{"kind": "inSource", "status": "underReview"}],
+ [{"kind": "inSource", "status": None}],
+ [{"kind": "inSource"}, {"kind": "external"}],
+ ):
+ with self.subTest(suppressions=suppressions):
+ _, sarif = self._with_finding()
+ sarif["runs"][0]["results"][0]["suppressions"] = suppressions
+ with self.assertRaisesRegex(ValueError, "suppression"):
+ self._prepare(self.report, sarif)
+
+ def test_suppressed_results_are_validated_before_removal(self):
+ _, sarif = self._with_finding(level="none", rule_level="none")
+ sarif["runs"][0]["results"][0]["suppressions"] = [{"kind": "inSource"}]
+ with self.assertRaisesRegex(ValueError, "lacks severity information"):
+ self._prepare(self.report, sarif)
+
+ def test_github_upload_rejects_incomplete_scans(self):
+ report, sarif = self._with_finding()
+ for bad_report, bad_sarif, reason in (
+ (
+ {**report, "errors": [{"message": "failure"}]},
+ sarif,
+ "reported errors",
+ ),
+ ({**report, "skipped_rules": ["example"]}, sarif, "skipped rules"),
+ ({**report, "paths": {"scanned": []}}, sarif, "any scanned files"),
+ (self.report, sarif, "reports disagree"),
+ ):
+ with self.subTest(reason=reason):
+ with self.assertRaisesRegex(ValueError, reason):
+ self._prepare(bad_report, bad_sarif)
+
+ def test_suppressions_need_a_reviewed_annotation_for_their_rule(self):
+ """A bare or unreviewed marker must not drop a finding from GitHub.
+
+ Semgrep 1.177.0 honours each of these (a rule-less match hides every
+ rule on the line), but none names this rule with a reason.
+ """
+ for line in (
+ "probe() # nosemgrep",
+ "probe() # nosem",
+ "probe() # NOSEMGREP: example, reason: reviewed probe",
+ "probe() # nosem: example, reason: reviewed probe",
+ "probe() # nosemgrep: example",
+ "probe() # nosemgrep: example, reason:",
+ "probe() # nosemgrep: example, reason: 42",
+ "probe() # nosemgrep:example, reason: reviewed probe",
+ "probe() # nosemgrep: other, reason: reviewed probe",
+ "probe() # nosemgrep: other, x.example, reason: reviewed probe",
+ "probe() # nosemgrep: example, reason: reviewed, other",
+ "probe() # nosemgrep: example,reason: reviewed probe",
+ "probe() # nosemgrep: example reason: reviewed probe",
+ "probe() # nosemgrep: example, reason: reviewed # nosemgrep",
+ # The single-id form fails a strict scan when another rule
+ # matches the line, so it is not a reviewed annotation.
+ "probe() # nosemgrep: example -- reviewed probe",
+ "probe() # nosemgrep: example, other -- reviewed probe",
+ 'probe("see nosemgrep docs")',
+ "probe() # NoSemantics",
+ "probe() # no\u017fem",
+ ):
+ with self.subTest(line=line):
+ self._write_source({4: line})
+ report, sarif = self._suppressed_finding()
+ with self.assertRaisesRegex(
+ ValueError,
+ "no reviewed 'nosemgrep: example, reason: <reason>'",
+ ):
+ self._prepare(report, sarif)
+
+ def test_reviewed_annotations_on_the_line_or_the_line_above(self):
+ expected = copy.deepcopy(self.sarif)
+ for lines in (
+ {4: "probe() # nosemgrep: example, reason: reviewed probe"},
+ {4: "probe() // nosemgrep: example, reason: reviewed probe"},
+ {3: " # nosemgrep: example, reason: reviewed probe"},
+ {3: "{# nosemgrep: example, reason: reviewed probe #}"},
+ {3: "# nosemgrep: example, reason: reviewed probe\r"},
+ # Several reviewed rules in one annotation; the result's exact
+ # id must be one of them.
+ {4: "probe() # nosemgrep: other, example, reason: reviewed"},
+ {3: "# nosemgrep: example, x.other, reason: reviewed probe"},
+ ):
+ with self.subTest(lines=lines):
+ self._write_source(lines)
+ report, sarif = self._suppressed_finding()
+ self.assertEqual(self._prepare(report, sarif), expected)
+
+ def test_previous_line_annotation_needs_semgreps_own_line_form(self):
+ # Semgrep ignores a marker after code on the line above a finding,
+ # so the finding here was suppressed by something else.
+ for lines in (
+ {3: "x = 1 # nosemgrep: example, reason: reviewed probe"},
+ {2: "# nosemgrep: example, reason: reviewed probe"},
+ ):
+ with self.subTest(lines=lines):
+ self._write_source(lines)
+ report, sarif = self._suppressed_finding()
+ with self.assertRaisesRegex(ValueError, "no reviewed"):
+ self._prepare(report, sarif)
+
+ def test_source_lines_split_like_semgrep(self):
+ # str.splitlines() would also split at U+2028 and shift line 4.
+ (self.source_root / "example.py").write_text(
+ "a\u2028b\nprobe()\nprobe()\n"
+ "probe() # nosemgrep: example, reason: reviewed probe\n",
+ encoding="utf-8",
+ )
+ report, sarif = self._suppressed_finding()
+ self.assertEqual(self._prepare(report, sarif), self.sarif)
+
+ def test_unreadable_suppressed_locations_fail_closed(self):
+ for uri, line, message in (
+ ("missing.py", 4, "Cannot read the source"),
+ ("example.py", 99, "beyond the end"),
+ ("example.py", 0, "malformed location"),
+ ("example.py", True, "malformed location"),
+ ("example.py", "4", "malformed location"),
+ ("file:///etc/passwd", 4, "malformed location"),
+ ("example%2Epy", 4, "malformed location"),
+ ("", 4, "malformed location"),
+ ):
+ with self.subTest(uri=uri, line=line):
+ report, sarif = self._suppressed_finding(line, uri)
+ with self.assertRaisesRegex(ValueError, message):
+ self._prepare(report, sarif)
+ report, sarif = self._suppressed_finding()
+ del sarif["runs"][0]["results"][0]["locations"]
+ with self.assertRaisesRegex(ValueError, "has no source line"):
+ self._prepare(report, sarif)
+
+ def test_cli_rejects_unreviewed_suppressions_without_writing(self):
+ self._write_source({4: "probe() # nosemgrep"})
+ report, sarif = self._suppressed_finding()
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ report_path, sarif_path = root / "raw.json", root / "raw.sarif"
+ upload_path = root / "github.sarif"
+ report_path.write_text(json.dumps(report), encoding="utf-8")
+ sarif_path.write_text(json.dumps(sarif), encoding="utf-8")
+ out = io.StringIO()
+ with (
+ mock.patch.object(
+ sys,
+ "argv",
+ [
+ "check",
+ str(report_path),
+ str(sarif_path),
+ "--github-sarif-output",
+ str(upload_path),
+ "--source-root",
+ str(self.source_root),
+ ],
+ ),
+ contextlib.redirect_stdout(out),
+ ):
+ self.assertEqual(POLICY.main(), 1)
+ self.assertIn("no reviewed", out.getvalue())
+ self.assertFalse(upload_path.exists())
+
+ def test_cli_creates_upload_and_preserves_raw_reports(self):
+ report, sarif = self._with_finding()
+ suppressed = {
+ "ruleId": "example",
+ "suppressions": [{"kind": "inSource"}],
+ "locations": self._location(4),
+ }
+ sarif["runs"][0]["results"].append(suppressed)
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ report_path, sarif_path = root / "raw.json", root / "raw.sarif"
+ upload_path = root / "github.sarif"
+ report_path.write_text(json.dumps(report), encoding="utf-8")
+ sarif_path.write_text(json.dumps(sarif), encoding="utf-8")
+ originals = report_path.read_bytes(), sarif_path.read_bytes()
+ with (
+ mock.patch.object(
+ sys,
+ "argv",
+ [
+ "check",
+ str(report_path),
+ str(sarif_path),
+ "--github-sarif-output",
+ str(upload_path),
+ "--source-root",
+ str(self.source_root),
+ ],
+ ),
+ contextlib.redirect_stdout(io.StringIO()),
+ ):
+ self.assertEqual(POLICY.main(), 0)
+ expected = copy.deepcopy(sarif)
+ expected["runs"][0]["results"].pop()
+ self.assertEqual(json.loads(upload_path.read_text()), expected)
+ self.assertEqual(
+ (report_path.read_bytes(), sarif_path.read_bytes()), originals
+ )
+
+ def test_cli_rejects_raw_report_overwrites(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ report_path, sarif_path = root / "raw.json", root / "raw.sarif"
+ report_path.write_text(json.dumps(self.report), encoding="utf-8")
+ sarif_path.write_text(json.dumps(self.sarif), encoding="utf-8")
+ alias = root / "alias.sarif"
+ alias.symlink_to(sarif_path)
+ # A hard link resolves to its own path; only the inode matches.
+ hard_link = root / "hard-link.sarif"
+ os.link(sarif_path, hard_link)
+ originals = report_path.read_bytes(), sarif_path.read_bytes()
+ for destination in (report_path, sarif_path, alias, hard_link):
+ with self.subTest(destination=destination):
+ out = io.StringIO()
+ with (
+ mock.patch.object(
+ sys,
+ "argv",
+ [
+ "check",
+ str(report_path),
+ str(sarif_path),
+ "--github-sarif-output",
+ str(destination),
+ ],
+ ),
+ contextlib.redirect_stdout(out),
+ ):
+ self.assertEqual(POLICY.main(), 1)
+ self.assertIn(
+ "must not overwrite a raw report", out.getvalue()
+ )
+ self.assertEqual(
+ (report_path.read_bytes(), sarif_path.read_bytes()),
+ originals,
+ )
+
+ def test_cli_does_not_write_upload_after_validation_failure(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ report_path, sarif_path = root / "raw.json", root / "raw.sarif"
+ upload_path = root / "github.sarif"
+ report_path.write_text(
+ json.dumps({**self.report, "errors": ["failure"]})
+ )
+ sarif_path.write_text(json.dumps(self.sarif))
+ with (
+ mock.patch.object(
+ sys,
+ "argv",
+ [
+ "check",
+ str(report_path),
+ str(sarif_path),
+ "--github-sarif-output",
+ str(upload_path),
+ ],
+ ),
+ contextlib.redirect_stdout(io.StringIO()),
+ ):
+ self.assertEqual(POLICY.main(), 1)
+ self.assertFalse(upload_path.exists())
+
def test_hostile_input_reports_error_instead_of_traceback(self):
"""Hostile reports fail with an ``::error::`` line, not a traceback.
diff --git a/tests/ci/test_semgrep_workflow.py b/tests/ci/test_semgrep_workflow.py
index 78cd20545e..d0032e9c3e 100644
--- a/tests/ci/test_semgrep_workflow.py
+++ b/tests/ci/test_semgrep_workflow.py
@@ -12,8 +12,9 @@ under ``src/`` matches Semgrep's built-in default ignores, no tracked entry
under ``src/`` is a symlink or a submodule, and none is above
Semgrep's default 1,000,000-byte ``--max-target-bytes`` cap (Semgrep
silently skips a symlink or an oversized file the same way it skips a
-default-ignored path), scanner errors fail the job, the reports are
-validated immediately before upload, a failed step is never followed
+default-ignored path), scanner errors fail the job, the raw reports are
+validated before deriving a GitHub upload copy that honors source suppressions,
+a failed step is never followed
by an upload, and a pull request touching ``src/`` runs the scan (so a file
Semgrep cannot parse fails that PR rather than the next release).
@@ -41,7 +42,11 @@ WORKFLOW = REPO_ROOT / ".github" / "workflows" / "semgrep.yml"
VALIDATOR = ".github/scripts/check_semgrep_report.py"
JSON_REPORT = "semgrep-results.json"
SARIF_REPORT = "semgrep-results.sarif"
-VALIDATOR_RUN = f"python {VALIDATOR} {JSON_REPORT} {SARIF_REPORT}"
+GITHUB_SARIF_REPORT = "semgrep-results.github.sarif"
+VALIDATOR_RUN = (
+ f"python {VALIDATOR} {JSON_REPORT} {SARIF_REPORT}"
+ f" --github-sarif-output {GITHUB_SARIF_REPORT}"
+)
VERIFY_RUN = (
"python -m unittest discover -s tests/ci/standalone"
" -p 'test_semgrep*.py' -v"
@@ -92,7 +97,7 @@ STEP_ORDER = [
"upload-artifact",
]
UPLOAD_WITH = {
- "sarif_file": SARIF_REPORT,
+ "sarif_file": GITHUB_SARIF_REPORT,
"category": "semgrep-security",
"wait-for-processing": True,
}
@@ -106,7 +111,7 @@ ACTION_WITH = {
"upload-sarif": UPLOAD_WITH,
"upload-artifact": {
"name": "semgrep-scan-results",
- "path": f"{JSON_REPORT}\n{SARIF_REPORT}\n",
+ "path": f"{JSON_REPORT}\n{SARIF_REPORT}\n{GITHUB_SARIF_REPORT}\n",
"retention-days": 7,
},
}
@@ -636,14 +641,19 @@ def test_job_runs_only_the_pinned_steps():
def test_only_the_scan_writes_the_reports():
- """Other steps may only read the reports (validator and uploads)."""
+ """The validator preserves raw reports and creates a separate upload copy."""
steps = _steps()
referencing = [
_step_kind(step)
for step in steps
if any(
name in str(step.get("run", "")) + json.dumps(step.get("with"))
- for name in ("semgrep-results", JSON_REPORT, SARIF_REPORT)
+ for name in (
+ "semgrep-results",
+ JSON_REPORT,
+ SARIF_REPORT,
+ GITHUB_SARIF_REPORT,
+ )
)
]
assert referencing == [
@@ -691,8 +701,11 @@ def test_upload_is_the_validated_sarif():
# overrides may redirect the upload.
assert upload_with == UPLOAD_WITH
validated = shlex.split(steps[_index(steps, "validate")]["run"])
- # The validator's second (SARIF) argument, and the scan's SARIF output.
- assert upload_with["sarif_file"] == validated[-1]
+ # Upload only the validator's dedicated output; retain the native input.
+ assert validated[2:4] == [JSON_REPORT, SARIF_REPORT]
+ assert validated[-2:] == ["--github-sarif-output", GITHUB_SARIF_REPORT]
+ assert upload_with["sarif_file"] == GITHUB_SARIF_REPORT
+ assert GITHUB_SARIF_REPORT not in (JSON_REPORT, SARIF_REPORT)
assert f"--sarif-output={SARIF_REPORT}" in _scan_tokens(steps)
diff --git a/tests/security/test_nosemgrep_annotation_guard.py b/tests/security/test_nosemgrep_annotation_guard.py
new file mode 100644
index 0000000000..a5d50ef2c1
--- /dev/null
+++ b/tests/security/test_nosemgrep_annotation_guard.py
@@ -0,0 +1,246 @@
+"""Tests for the check-nosemgrep-annotations pre-commit guard.
+
+Semgrep honours a case-insensitive ``nosem`` marker anywhere after a space
+(strings and prose included); a rule-less one hides every rule on its line,
+and the GitHub upload drops source-suppressed findings. The guard accepts
+only ``nosemgrep: <rule.id>[, <rule.id>]..., reason: <reason>`` at the start
+of a comment.
+"""
+
+# allow: no-sut-import — the SUT is a pre-commit hook script under
+# .pre-commit-hooks/, not a local_deep_research module; it is loaded via
+# importlib below.
+
+import importlib.util
+import re
+import subprocess
+from pathlib import Path
+
+import pytest
+import yaml
+
+_ROOT = Path(__file__).resolve().parents[2]
+_HOOK = _ROOT / ".pre-commit-hooks" / "check-nosemgrep-annotations.py"
+
+
+def _load():
+ spec = importlib.util.spec_from_file_location(
+ "check_nosemgrep_annotations", _HOOK
+ )
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+guard = _load()
+
+RULE = "semgrep.rules.weak-random-generation"
+OTHER = "python.lang.security.audit.other-rule"
+
+VALID_LINES = [
+ f"jitter = random.randint(0, 5) # nosemgrep: {RULE}, reason: jitter only",
+ f" # nosemgrep: {RULE}, reason: jitter only",
+ f"x = {{{{ v|tojson }}}}; // nosemgrep: {RULE}, reason: tojson escapes",
+ f"<b {{{{ a }}}}> {{# nosemgrep: {RULE}, reason: fixed tokens only #}}",
+ f"<b> <!-- nosemgrep: {RULE}, reason: fixed tokens only -->",
+ f"x(); /* nosemgrep: {RULE}, reason: reviewed */",
+ f"run(q) # nosemgrep: {RULE}, {OTHER}, reason: both reviewed",
+ f" # nosemgrep: {OTHER}, {RULE}, reason: both reviewed",
+ # Mentions Semgrep cannot read as a marker (no space or code before it).
+ "see the xnosemgrep option",
+ "value = 1",
+]
+
+INVALID_LINES = [
+ "run(q) # nosemgrep",
+ "run(q) # nosem",
+ f"run(q) # nosemgrep: {RULE}",
+ f"run(q) # nosemgrep: {RULE}, reason:",
+ f"run(q) # nosemgrep: {RULE}, reason: 42",
+ f"run(q) # NOSEMGREP: {RULE}, reason: reviewed",
+ f"run(q) # NoSemgrep: {RULE}, reason: reviewed",
+ f"run(q) # nosem: {RULE}, reason: reviewed",
+ f"run(q) # nosemgrep={RULE}, reason: reviewed",
+ f"run(q) # nosemgrep:{RULE}, reason: reviewed",
+ f"run(q) # nosemgrep: {RULE},reason: reviewed",
+ f"run(q) # nosemgrep: {RULE}, reason: reviewed",
+ f"run(q) # nosemgrep: {RULE} reason: reviewed",
+ f"run(q) # nosemgrep: {RULE}, reason: reviewed, other",
+ f"run(q) # nosemgrep: {RULE}, reason: reviewed # nosemgrep",
+ # The single-id form fails a strict scan when another rule matches.
+ f"run(q) # nosemgrep: {RULE} -- reviewed",
+ f"run(q) # nosemgrep: {RULE}, {OTHER} -- reviewed",
+ "run(q) # nosemgrep: weak-random-generation, reason: suffix ids",
+ f"run(q) # nosemgrep: {RULE}, short-id, reason: suffix ids",
+ f"run(q) # reason; nosemgrep: {RULE}, reason: reviewed",
+ f"<b> nosemgrep: {RULE}, reason: reviewed",
+ "# TODO: NOSEM later",
+ " nosemgrep at the start of a docstring line",
+ "run(q) # NoSemantics here",
+ 'raise ValueError("see nosemgrep docs")',
+]
+
+
[email protected]("line", VALID_LINES)
+def test_valid_lines_pass(line):
+ assert guard.check_line(line) is None
+
+
[email protected]("line", INVALID_LINES)
+def test_invalid_lines_flagged(line):
+ assert guard.check_line(line) is not None
+
+
[email protected]("line", VALID_LINES)
+def test_accepted_annotations_name_the_rule_for_the_report_check(line):
+ """The upload check reads the same annotation the hook accepted."""
+ if "nosemgrep:" not in line:
+ return
+ report = guard._REPORT
+ rules = report.reviewed_annotation_rules(
+ line, previous_line=False
+ ) + report.reviewed_annotation_rules(line, previous_line=True)
+ assert RULE in rules
+
+
+# Semgrep 1.177.0's parsing (src/reporting/Nosemgrep.ml): the ids after the
+# marker are split at commas, each item is stripped of spaces and quotes and
+# its first space-separated word is the id. Rule_ID.validate allows only
+# [a-zA-Z0-9._-]; an invalid id suppresses nothing.
+_SEMGREP_IDS = r"(?:[:=][\s]?(?P<ids>([^,\s](?:[,\s]+)?)+))?"
+_SEMGREP_INLINE = re.compile(r" nosem(?:grep)?" + _SEMGREP_IDS, re.IGNORECASE)
+_SEMGREP_PREVIOUS = re.compile(
+ r"^[^a-zA-Z0-9]* *nosem(?:grep)?" + _SEMGREP_IDS, re.IGNORECASE
+)
+_SEMGREP_VALID_ID = re.compile(r"[a-zA-Z0-9._-]*")
+
+
+def _semgrep_ids(line, *, previous_line):
+ rex = _SEMGREP_PREVIOUS if previous_line else _SEMGREP_INLINE
+ ids = []
+ for match in rex.finditer(line):
+ if match.group("ids") is None:
+ continue # a bare marker
+ for item in match.group("ids").split(","):
+ ids.append(item.strip(" ").split(" ")[0].strip('"'))
+ return ids
+
+
+def _annotated_lines():
+ files = subprocess.run(
+ ["git", "ls-files", "-z", "src"],
+ cwd=_ROOT,
+ capture_output=True,
+ check=True,
+ ).stdout.split(b"\0")
+ for name in filter(None, files):
+ path = _ROOT / name.decode()
+ if path.is_symlink() or not path.is_file():
+ continue
+ data = path.read_bytes()
+ if b"nosemgrep:" in data:
+ yield from (
+ line
+ for line in data.decode("utf-8").split("\n")
+ if "nosemgrep:" in line
+ )
+
+
[email protected]("previous_line", [False, True])
+def test_semgrep_reads_the_reviewed_rules_plus_an_inert_item(previous_line):
+ """Semgrep sees exactly the reviewed rules and one invalid extra id.
+
+ With a single id, Semgrep 1.177.0 fails a --strict scan whenever another
+ rule matches the annotated line ("found 'nosem' comment with id ...,
+ but no corresponding rule trying ..."); it skips that check when a
+ comment holds two or more ids. The trailing "reason:" item is the extra
+ id, and it cannot match any rule because it is not a valid rule id.
+ """
+ report = guard._REPORT
+ lines = [line for line in VALID_LINES if "nosemgrep:" in line]
+ lines += list(_annotated_lines())
+ checked = 0
+ for line in lines:
+ rules = report.reviewed_annotation_rules(
+ line, previous_line=previous_line
+ )
+ if not rules:
+ continue
+ checked += 1
+ ids = _semgrep_ids(line, previous_line=previous_line)
+ assert ids == [*rules, "reason:"], line
+ assert len(ids) >= 2
+ assert all(_SEMGREP_VALID_ID.fullmatch(rule) for rule in rules)
+ assert not _SEMGREP_VALID_ID.fullmatch(ids[-1])
+ assert checked > 0
+
+
+def test_python_string_literal_annotation_flagged():
+ src = f'x = "# nosemgrep: {RULE}, reason: reviewed"\n'
+ errors = guard.check_content(src, python=True)
+ assert len(errors) == 1
+ assert "string" in errors[0][1]
+
+
+def test_python_docstring_annotation_flagged():
+ src = f'def f():\n """Doc.\n\n # nosemgrep: {RULE}, reason: reviewed\n """\n'
+ errors = guard.check_content(src, python=True)
+ assert [row for row, _ in errors] == [4]
+
+
+def test_python_comment_annotation_passes():
+ src = (
+ f"# nosemgrep: {RULE}, reason: jitter only\n"
+ "delay = random.randint(1, 30)\n"
+ f"x = random.random() # nosemgrep: {RULE}, reason: jitter only\n"
+ )
+ assert guard.check_content(src, python=True) == []
+
+
+def test_lines_split_like_semgrep():
+ # U+2028 is not a line break for Semgrep; the marker is on line 1.
+ src = "x = 1
y # nosemgrep\n"
+ assert [row for row, _ in guard.check_content(src, python=False)] == [1]
+
+
+def test_main_reports_failures(tmp_path, capsys):
+ bad = tmp_path / "bad.html"
+ bad.write_text("<b {{ a }}> {# nosemgrep #}\n", encoding="utf-8")
+ good = tmp_path / "good.py"
+ good.write_text(f"# nosemgrep: {RULE}, reason: jitter only\nx = 1\n")
+ assert guard.main([str(good)]) == 0
+ assert guard.main([str(good), str(bad)]) == 1
+ assert "bad.html" in capsys.readouterr().out
+
+
+def test_repository_annotations_pass():
+ files = subprocess.run(
+ ["git", "ls-files", "-z", "src"],
+ cwd=_ROOT,
+ capture_output=True,
+ check=True,
+ ).stdout.split(b"\0")
+ annotated = 0
+ for name in filter(None, files):
+ path = _ROOT / name.decode()
+ if path.is_symlink() or not path.is_file():
+ continue
+ assert guard.check_file(str(path)) == [], path
+ if b"nosemgrep:" in path.read_bytes():
+ annotated += 1
+ # The sweep is not vacuous: the reviewed annotations were checked.
+ assert annotated > 0
+
+
+def test_hook_is_registered_for_the_scanned_tree():
+ config = yaml.safe_load(
+ (_ROOT / ".pre-commit-config.yaml").read_text(encoding="utf-8")
+ )
+ hooks = {
+ hook["id"]: hook for repo in config["repos"] for hook in repo["hooks"]
+ }
+ hook = hooks["check-nosemgrep-annotations"]
+ assert hook["entry"] == ".pre-commit-hooks/check-nosemgrep-annotations.py"
+ # Semgrep scans every file under src/, templates and static included.
+ assert hook["files"] == "^src/"
+ assert "types" not in hook or hook["types"] == ["text"]