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(ci): preserve Semgrep severities and reject incomplete scans (#6645)

LearningCircuiteb9069fb6ba9
diff --git a/.github/SECURITY_SCORECARD.md b/.github/SECURITY_SCORECARD.md
index 6e9d1d2cdb..fbd6f55027 100644
--- a/.github/SECURITY_SCORECARD.md
+++ b/.github/SECURITY_SCORECARD.md
@@ -76,7 +76,7 @@ The remaining pip commands use exact version pinning.
| mypy-type-check.yml | 39,47-48 | `pip install pdm==2.26.2 mypy==1.14.1...` | Version-pinned |
| publish.yml | 139,328 | `pip install pdm==2.26.2` `pip install wheel==0.46.2` | Version-pinned |
| puppeteer-e2e-tests.yml | 65 | `pip install -e .` | Local package |
-| semgrep.yml | 36 | `pip install semgrep==1.87.0` | Version-pinned |
+| semgrep.yml | 50 | `python -m pip install semgrep==1.177.0` | Version-pinned |
| update-precommit-hooks.yml | 35-38 | `pip install pip==25.0` `pip install pre-commit-update==0.6.1` | **Hash-pinned** |
| validate-image-pinning.yml | 67 | `pip install pyyaml==6.0.2` | Version-pinned |
| backwards-compatibility.yml | 66-68 | `pip install --upgrade pip` `pip install pytest` `pip install -e .` | Intentionally unpinned |
@@ -88,6 +88,60 @@ The remaining pip commands use exact version pinning.
> because it tests compatibility with prior PyPI releases of local-deep-research.
> Pinning these commands would defeat the purpose of the compatibility tests.
+> **Note:** `semgrep.yml` pins the Semgrep engine, but the `p/security-audit` and
+> `p/secrets` registry rulesets are fetched live and unpinned. The scan runs with
+> `--strict` and its reports are validated, so any scanner error or skipped rule
+> fails the job and therefore the release gate, with no repo change. That includes
+> an info-level `IncompatibleRule` error from an upstream rule that needs a newer
+> Semgrep, a rule timeout (runner-speed dependent, so possibly intermittent), and a
+> semgrep.dev registry outage while the rulesets are fetched. Remedy for
+> `IncompatibleRule`: bump the `semgrep==` pin in `semgrep.yml` (Dependabot does not
+> update pins in workflow `run:` lines) and update the line reference above;
+> otherwise re-run once the registry recovers.
+>
+> A parse error in a scanned file under `src/` also fails the job: with `--strict`,
+> Semgrep 1.177.0 exits non-zero on some valid syntax its parsers do not support
+> (reported for Python 3.12 mapping patterns with `**rest` in `match`/`case`, and
+> JavaScript class static blocks). `semgrep.yml`'s `pull_request` trigger includes
+> `src/**`, so this fails the pull request that adds such code instead of the next
+> release. Remedy: rewrite the construct in syntax Semgrep parses, or bump the
+> `semgrep==` pin to a release that parses it. Excluding the file with a
+> `.semgrepignore` or `--exclude` is not a remedy; the contract tests reject both,
+> because a skipped file would resolve its existing alerts.
+>
+> Semgrep copies a rule's `metadata.security-severity` into the SARIF rule's
+> `properties["security-severity"]`, which GitHub maps to `security_severity_level`,
+> the field the release gate's code-scanning alert check counts. No loaded rule sets
+> it today, so Semgrep alerts do not yet block a release. A custom rule or an
+> upstream ruleset update that adds the score as a quoted string (`"7.5"`) or an
+> integer (`8`) has it copied through, and a score of 4.0 or more then makes its
+> alerts block releases with no change to the gate. GitHub documents the property
+> as a string, so whether it maps an integer score is unverified. An unquoted float
+> (`7.5`) in a `.semgrep/rules/` file instead crashes Semgrep 1.177.0 ("Invalid YAML
+> tree structure ... ScalarFloat"), which fails the job. The report validation
+> checks the score of every loaded rule, including rules with no finding, and
+> accepts only a JSON number or a plain ASCII decimal string (`"8"`, `"7.5"`) from
+> 0 to 10. Anything else, such as a boolean, `"1e1"`, `"+8"`, `" 8 "`, `"8."`,
+> `"0_8"`, non-ASCII digits or an out-of-range value, fails the validation and so
+> the job.
+>
+> `tests/ci/test_semgrep_workflow.py` pins the known-good `semgrep.yml` job (step
+> sequence, exact scan text, action inputs, job keys, the workflow's top-level keys
+> and single job, no `.semgrepignore`) against accidental regressions such as
+> masking the exit status, filtering by severity or narrowing the scanned rules or
+> files. With no `.semgrepignore`, Semgrep applies its built-in default ignores and
+> silently skips any `tests/`, `test/`, `build/`, `dist/`, `vendor/` or
+> `node_modules/` directory and `*.min.js` files at any depth under `src/`. It also
+> silently skips a tracked symlink, and any file above its default
+> 1,000,000-byte `--max-target-bytes` cap; a submodule's gitlink entry is not a
+> blob Semgrep could scan either. None of this is tracked under `src/` today, and
+> the same test file fails if one is added. A deliberately
+> adversarial edit to the workflow is outside what static tests can guarantee; it
+> is covered by the required CODEOWNERS review of `.github/workflows/semgrep.yml`
+> (the maintainer-owned `*` rule) and `.semgrepignore`. The contract tests
+> themselves, and the standalone tests the scan job runs, live under `tests/ci/`,
+> which the wider `/tests/` CODEOWNERS group owns.
+
**Why we don't use hash pinning:**
1. **Platform-specific hashes**: pip package hashes vary by Python version, OS, and architecture.
diff --git a/.github/scripts/check_semgrep_report.py b/.github/scripts/check_semgrep_report.py
new file mode 100644
index 0000000000..03259eab3a
--- /dev/null
+++ b/.github/scripts/check_semgrep_report.py
@@ -0,0 +1,192 @@
+"""Reject incomplete Semgrep scans before publishing code-scanning results."""
+
+import argparse
+import json
+import re
+from collections import Counter
+from pathlib import Path
+
+SEVERITIES = frozenset(
+ {"INFO", "WARNING", "ERROR", "LOW", "MEDIUM", "HIGH", "CRITICAL"}
+)
+SARIF_LEVELS = frozenset({"error", "warning", "note"})
+# GitHub documents security-severity as a string holding a decimal score.
+# Accept only plain ASCII decimals ("7", "7.5"); Python's float() would also
+# take "1e1", "+8", " 8 ", "8.", "0_8" and non-ASCII digits, which GitHub may
+# not parse, leaving the alert without a level (and so never blocking).
+SECURITY_SEVERITY = re.compile(r"[0-9]+(?:\.[0-9]+)?")
+
+
+def _json_findings(report: object) -> tuple[Counter, Counter]:
+ """Validate the JSON report; return severity and per-rule counts."""
+ if not isinstance(report, dict):
+ raise ValueError("Semgrep JSON must be an object")
+ if report.get("errors") != []:
+ raise ValueError("Semgrep reported errors or omitted its error status")
+ if report.get("skipped_rules") != []:
+ raise ValueError(
+ "Semgrep skipped rules or omitted its skipped-rule status"
+ )
+ paths = report.get("paths")
+ scanned = paths.get("scanned") if isinstance(paths, dict) else None
+ if not isinstance(scanned, list) or not scanned:
+ raise ValueError("Semgrep did not report any scanned files")
+ if not all(isinstance(path, str) and path for path in scanned):
+ raise ValueError("Semgrep reported a malformed scanned path")
+ results = report.get("results")
+ if not isinstance(results, list):
+ raise ValueError("Semgrep findings are missing or malformed")
+ severities: Counter = Counter()
+ rules: Counter = Counter()
+ for result in results:
+ if not isinstance(result, dict):
+ raise ValueError("Semgrep finding is malformed")
+ extra = result.get("extra")
+ if not isinstance(extra, dict):
+ raise ValueError("Semgrep finding has no metadata")
+ severity = extra.get("severity")
+ if severity not in SEVERITIES:
+ raise ValueError("Semgrep finding has no recognized severity")
+ severities[severity] += 1
+ if extra.get("is_ignored") is not True:
+ rules[result.get("check_id")] += 1
+ return severities, rules
+
+
+def _check_notifications(invocation: dict) -> None:
+ for key in ("toolExecutionNotifications", "toolConfigurationNotifications"):
+ notifications = invocation.get(key, [])
+ if not isinstance(notifications, list):
+ raise ValueError(f"SARIF {key} are malformed")
+ for notification in notifications:
+ if not isinstance(notification, dict):
+ raise ValueError(f"SARIF {key} are malformed")
+ if notification.get("level", "warning") == "error":
+ raise ValueError(f"SARIF reports an error in {key}")
+
+
+def _security_severity(rule: object) -> float | None:
+ """A rule descriptor's validated security-severity, or None if unset.
+
+ The score is what GitHub maps to security_severity_level, the field the
+ release gate counts, so a score it may misread must fail the scan.
+ """
+ if not isinstance(rule, dict) or not isinstance(rule.get("id"), str):
+ raise ValueError("SARIF rule descriptor is malformed")
+ properties = rule.get("properties", {})
+ if not isinstance(properties, dict):
+ raise ValueError("SARIF rule properties are malformed")
+ if "security-severity" not in properties:
+ return None
+ score = properties["security-severity"]
+ if isinstance(score, str) and SECURITY_SEVERITY.fullmatch(score):
+ value = float(score)
+ # bool is an int subclass; true/false is not a score.
+ elif isinstance(score, (int, float)) and not isinstance(score, bool):
+ value = score
+ else:
+ raise ValueError("SARIF rule has a malformed security severity")
+ if not 0 <= value <= 10: # also rejects NaN
+ raise ValueError("SARIF rule has an out-of-range security severity")
+ return value
+
+
+def _sarif_findings(sarif: object) -> Counter:
+ """Validate the SARIF report; return unsuppressed per-rule counts."""
+ if not isinstance(sarif, dict) or sarif.get("version") != "2.1.0":
+ raise ValueError("Expected native SARIF 2.1.0")
+ runs = sarif.get("runs")
+ if not isinstance(runs, list) or not runs:
+ raise ValueError("SARIF contains no scan runs")
+ rules_seen: Counter = Counter()
+ for run in runs:
+ if not isinstance(run, dict) or not isinstance(
+ run.get("results"), list
+ ):
+ raise ValueError("SARIF findings are missing or malformed")
+ invocations = run.get("invocations")
+ if not isinstance(invocations, list) or not invocations:
+ raise ValueError("SARIF run has no scanner invocation")
+ for invocation in invocations:
+ if not isinstance(invocation, dict):
+ raise ValueError("SARIF invocation is malformed")
+ if invocation.get("executionSuccessful") is not True:
+ raise ValueError(
+ "SARIF does not report successful scanner execution"
+ )
+ _check_notifications(invocation)
+ # Semgrep lists every loaded rule here, not only rules with findings.
+ # No descriptors means no rules ran; an empty result set from such a
+ # scan would resolve every existing alert.
+ rules = run.get("tool", {}).get("driver", {}).get("rules")
+ if not isinstance(rules, list) or not rules:
+ raise ValueError("SARIF run lists no loaded rules")
+ # Every loaded rule's score is checked, not only the scores of rules
+ # with a finding in this scan.
+ by_id, scores = {}, {}
+ for rule in rules:
+ score = _security_severity(rule)
+ by_id[rule["id"]] = rule
+ scores[rule["id"]] = score
+ for result in run["results"]:
+ if not isinstance(result, dict):
+ raise ValueError("SARIF finding is malformed")
+ rule = by_id.get(result.get("ruleId"))
+ if rule is None:
+ raise ValueError("SARIF finding has no rule descriptor")
+ score = scores[result.get("ruleId")]
+ level = result.get(
+ "level", rule.get("defaultConfiguration", {}).get("level")
+ )
+ if score is None and level not in SARIF_LEVELS:
+ raise ValueError("SARIF finding lacks severity information")
+ if not result.get("suppressions"):
+ rules_seen[result.get("ruleId")] += 1
+ return rules_seen
+
+
+def validate(report: object, sarif: object) -> Counter:
+ """Validate both reports and return the JSON severity counts."""
+ severities, json_rules = _json_findings(report)
+ sarif_rules = _sarif_findings(sarif)
+ # Both reports come from one scan; a mismatch means one is truncated.
+ # Suppressed (nosemgrep) findings are excluded on both sides because the
+ # formats disagree on whether to emit them.
+ if json_rules != sarif_rules:
+ raise ValueError(
+ "Semgrep JSON and SARIF reports disagree: "
+ f"{sum(json_rules.values())} JSON vs "
+ f"{sum(sarif_rules.values())} SARIF unsuppressed findings"
+ )
+ return severities
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("json_report", type=Path)
+ parser.add_argument("sarif_report", type=Path)
+ 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")),
+ )
+ except (
+ OSError,
+ ValueError,
+ KeyError,
+ TypeError,
+ AttributeError,
+ OverflowError,
+ RecursionError,
+ ) as exc:
+ print(f"::error::Invalid Semgrep scan: {type(exc).__name__}: {exc}")
+ return 1
+ print(
+ f"Validated Semgrep scan: {sum(counts.values())} findings; {dict(counts)}"
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.github/workflows/semgrep.yml b/.github/workflows/semgrep.yml
index 7c8846b143..6fab92beb2 100644
--- a/.github/workflows/semgrep.yml
+++ b/.github/workflows/semgrep.yml
@@ -1,6 +1,20 @@
name: Semgrep Security Scan
on:
+ pull_request:
+ paths:
+ # The scanned tree: a file Semgrep cannot parse fails the scan
+ # (--strict), so it must fail here, at PR time, not first in the
+ # release gate.
+ - "src/**"
+ - ".github/workflows/semgrep.yml"
+ - ".github/scripts/check_semgrep_report.py"
+ - ".semgrep/**"
+ # Semgrep drops files matched by a .semgrepignore at the root or in
+ # any scanned directory; tests/ci/test_semgrep_workflow.py rejects one.
+ - ".semgrepignore"
+ - "**/.semgrepignore"
+ - "tests/ci/standalone/test_semgrep*.py"
workflow_call: # Called by release-gate.yml
workflow_dispatch:
@@ -33,219 +47,102 @@ jobs:
python-version: '3.12'
- name: Install Semgrep
- run: |
- # setuptools required: semgrep 1.87.0's opentelemetry dep imports pkg_resources,
- # which is not bundled with Python 3.12 by default on GitHub runners.
- # Pin setuptools<82 because 82.0 removed the pkg_resources module.
- pip install "setuptools<82" semgrep==1.87.0
-
+ run: python -m pip install semgrep==1.177.0
+
+ - name: Verify scanner and report contracts
+ run: python -m unittest discover -s tests/ci/standalone -p 'test_semgrep*.py' -v
+
+ # No --severity filter: it selects exact levels, not a minimum severity.
+ # Scanner/configuration errors must fail this step (--strict, no || true).
+ # Uploading a narrowed report (an extra option such as --exclude or
+ # --baseline-commit, a dropped --config) resolves existing alerts.
+ # tests/ci/test_semgrep_workflow.py pins this job's known-good text
+ # (steps, this exact run text, action inputs, job keys, the workflow's
+ # keys and single job, no .semgrepignore, no tracked src/ path that
+ # Semgrep's built-in default ignores would skip, e.g. tests/, build/,
+ # dist/, vendor/, node_modules/, *.min.js, and no tracked src/ symlink,
+ # submodule, or file above Semgrep's default 1,000,000-byte
+ # --max-target-bytes cap, all silently skipped the same way) against
+ # accidental regressions of that kind. It cannot guarantee
+ # anything against a deliberately adversarial edit; changes to this file
+ # and to .semgrepignore need CODEOWNERS review.
+ # Release blocking: Semgrep copies a rule's metadata.security-severity
+ # into the SARIF rule's properties["security-severity"], which GitHub maps
+ # to security_severity_level, the only field release-gate.yml's
+ # check-code-scanning-alerts counts (medium and above, i.e. a score of 4.0
+ # or more, blocks). No loaded rule sets it today, so Semgrep alerts do not
+ # yet block a release (until #6646 falls back to the SARIF level). A
+ # custom rule in .semgrep/rules/ or an upstream update to
+ # p/security-audit or p/secrets that adds the metadata as a quoted
+ # string ("7.5") or an integer (8) has it copied through, and a score of
+ # 4.0 or more then makes its alerts block releases with no change here
+ # (GitHub documents the property as a string; whether it maps an integer
+ # is unverified). An unquoted float (7.5) in a .semgrep/rules/ file
+ # instead crashes Semgrep 1.177.0 ("Invalid YAML tree structure ...
+ # ScalarFloat"), which fails this job and so the release gate.
+ # check_semgrep_report.py checks the score of every loaded rule, with or
+ # without a finding, and accepts only a JSON number or a plain ASCII
+ # decimal string ("8", "7.5") in 0-10. Anything else (a boolean, "1e1",
+ # "+8", " 8 ", "8.", "0_8", non-ASCII digits, out of range) fails this
+ # job: deliberately fail-closed, because that score is what the release
+ # gate reads.
+ # Availability: this job (and so the release gate) now fails on anything
+ # `|| true` used to hide: any scanner error or skipped rule, including a
+ # rule timeout (runner-speed dependent, so possibly intermittent), an
+ # info-level IncompatibleRule error from an upstream rule needing a newer
+ # Semgrep, and a semgrep.dev registry outage while the p/ packs are
+ # fetched. p/security-audit and p/secrets are fetched live and unpinned,
+ # so these can fail this job with no repo change. Remedy for
+ # IncompatibleRule: bump the semgrep pin in "Install Semgrep" (Dependabot
+ # does not update pins in `run:` lines); otherwise re-run once the
+ # registry recovers. A parse error in a scanned file also fails this job:
+ # with --strict, Semgrep 1.177.0 exits non-zero on some valid syntax its
+ # parsers do not support (reported for Python 3.12 mapping patterns with
+ # **rest in `match`/`case`, and JavaScript class static blocks). The
+ # pull_request trigger includes src/** so this fails the PR that adds such
+ # code rather than the next release. Remedy: rewrite the construct in
+ # syntax Semgrep parses, or bump the semgrep pin to a release that parses
+ # it. Excluding the file (.semgrepignore, --exclude) is not a remedy:
+ # tests/ci/test_semgrep_workflow.py rejects both, since a skipped file
+ # would resolve its alerts. The validator requires at least one loaded rule but
+ # cannot tell which config each rule came from, so completeness of the
+ # rulesets rests on the pinned --config list and on Semgrep failing hard
+ # when a config cannot be fetched.
- name: Run Semgrep security scan
+ id: scan
run: |
- semgrep \
+ semgrep scan \
--config=p/security-audit \
--config=p/secrets \
- --severity=INFO \
- --json \
- --output=semgrep-results.json \
- src/ || true
- # Crash detection: if semgrep crashed, no output file was produced
- if [ ! -f semgrep-results.json ]; then
- echo "::error::Semgrep security scan crashed — no output produced"
- exit 1
- fi
-
- - name: Run Semgrep custom rules for LDR
- run: |
- semgrep \
--config=.semgrep/rules/ \
- --severity=INFO \
- --json \
- --output=semgrep-custom-results.json \
- src/ || true
- # Crash detection: if semgrep crashed, no output file was produced
- if [ ! -f semgrep-custom-results.json ]; then
- echo "::error::Semgrep custom rules scan crashed — no output produced"
- exit 1
- fi
-
- - name: Merge Semgrep results
- run: |
- python3 -c "
- import json
- import glob
-
- results = []
- for file in glob.glob('semgrep-*.json'):
- try:
- with open(file) as f:
- data = json.load(f)
- if isinstance(data, dict) and 'results' in data:
- results.extend(data['results'])
- elif isinstance(data, list):
- results.extend(data)
- except Exception as e:
- print(f'Error reading {file}: {e}')
-
- output = {'results': results, 'version': '1.0.0'}
- with open('semgrep-combined-results.json', 'w') as f:
- json.dump(output, f, indent=2)
-
- print(f'Combined {len(results)} findings from Semgrep scans')
- "
-
- - name: Convert to SARIF format
- run: |
- python3 -c "
- import json
- import uuid
- from datetime import datetime
-
- # Load combined results
- with open('semgrep-combined-results.json') as f:
- semgrep_data = json.load(f)
-
- # Convert to SARIF
- sarif = {
- '\$schema': 'https://json.schemastore.org/sarif-2.1.0',
- 'version': '2.1.0',
- 'runs': [{
- 'tool': {
- 'driver': {
- 'name': 'Semgrep',
- 'version': '1.87.0',
- 'informationUri': 'https://semgrep.dev'
- }
- },
- 'results': []
- }]
- }
-
- for result in semgrep_data.get('results', []):
- sarif_result = {
- 'ruleId': result.get('check_id', 'unknown'),
- 'message': {
- 'text': result.get('message', 'Security issue detected')
- },
- 'level': 'warning' if result.get('metadata', {}).get('severity', 'INFO') in ['ERROR', 'WARNING'] else 'note',
- 'locations': [{
- 'physicalLocation': {
- 'artifactLocation': {
- 'uri': result.get('path', 'unknown')
- },
- 'region': {
- 'startLine': result.get('start', {}).get('line', 1),
- 'startColumn': result.get('start', {}).get('col', 1),
- 'endLine': result.get('end', {}).get('line', result.get('start', {}).get('line', 1)),
- 'endColumn': result.get('end', {}).get('col', result.get('start', {}).get('col', 1) + 1)
- }
- }
- }]
- }
-
- # Add rule information
- metadata = result.get('metadata', {})
- sarif_result['rule'] = {
- 'id': result.get('check_id', 'unknown'),
- 'name': metadata.get('name', 'Security Issue'),
- 'shortDescription': {
- 'text': metadata.get('name', 'Security Issue')
- },
- 'fullDescription': {
- 'text': metadata.get('description', 'Security vulnerability detected')
- },
- 'help': {
- 'text': metadata.get('remediation', 'Review and fix the security issue')
- },
- 'properties': {
- 'precision': 'medium',
- 'tags': ['security', 'semgrep']
- }
- }
-
- if 'security-severity' in metadata:
- sarif_result['rule']['properties']['security-severity'] = metadata['security-severity']
-
- sarif['runs'][0]['results'].append(sarif_result)
-
- # Write SARIF file
- with open('semgrep-results.sarif', 'w') as f:
- json.dump(sarif, f, indent=2)
-
- print(f'Converted {len(sarif[\"runs\"][0][\"results\"])} findings to SARIF format')
- "
-
- # Fail loudly if the SARIF conversion produced no file — never fabricate an
- # empty one. An empty-results SARIF uploaded under the semgrep-security
- # category would make GitHub mark every previously-open Semgrep alert as
- # fixed, silently clearing real findings. The "Convert to SARIF" step above
- # always writes the file (results:[] on a clean scan), so a missing file
- # means a real conversion failure. Mirror the Grype/Trivy jobs.
- - name: Ensure SARIF file exists
- id: check-sarif
- if: always()
- run: |
- if [ -f semgrep-results.sarif ]; then
- echo "exists=true" >> "$GITHUB_OUTPUT"
- else
- echo "::error::Semgrep SARIF conversion did not produce a file — scan needs to be rerun"
- exit 1
- fi
-
+ --strict \
+ --metrics=off \
+ --json-output=semgrep-results.json \
+ --sarif-output=semgrep-results.sarif \
+ src/
+
+ - name: Validate complete scanner reports
+ id: report
+ run: python .github/scripts/check_semgrep_report.py semgrep-results.json semgrep-results.sarif
+
+ # Upload only a successful, validated scan (implicit success(); never
+ # always()). An empty or partial report from a failed scan must never
+ # resolve existing code-scanning alerts. Fork PRs cannot upload because
+ # GitHub gives their token read-only permissions.
- name: Upload Semgrep results to GitHub Security tab
+ 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
- if: always() && steps.check-sarif.outputs.exists == 'true'
with:
- sarif_file: 'semgrep-results.sarif'
+ sarif_file: semgrep-results.sarif
category: semgrep-security
+ wait-for-processing: true
- - name: Upload Semgrep results as artifact
+ - name: Upload Semgrep diagnostics
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: always()
with:
name: semgrep-scan-results
path: |
semgrep-results.json
- semgrep-custom-results.json
- semgrep-combined-results.json
semgrep-results.sarif
- retention-days: 7 # Reduced for security
-
- - name: Display Semgrep summary
- if: always()
- run: |
- {
- echo "## Semgrep Security Scan Summary"
- echo ""
- } >> "$GITHUB_STEP_SUMMARY"
-
- if [ -f semgrep-combined-results.json ]; then
- # Count results by severity
- CRITICAL=$(python3 -c "import json; data=json.load(open('semgrep-combined-results.json')); print(len([r for r in data['results'] if r.get('metadata', {}).get('severity') == 'ERROR']))" 2>/dev/null || echo "0")
- HIGH=$(python3 -c "import json; data=json.load(open('semgrep-combined-results.json')); print(len([r for r in data['results'] if r.get('metadata', {}).get('severity') == 'WARNING']))" 2>/dev/null || echo "0")
- MEDIUM=$(python3 -c "import json; data=json.load(open('semgrep-combined-results.json')); print(len([r for r in data['results'] if r.get('metadata', {}).get('severity') == 'INFO']))" 2>/dev/null || echo "0")
- TOTAL=$(python3 -c "import json; data=json.load(open('semgrep-combined-results.json')); print(len(data['results']))" 2>/dev/null || echo "0")
-
- {
- echo "📊 **Scan Results:**"
- echo "- **Critical:** $CRITICAL"
- echo "- **High:** $HIGH"
- echo "- **Medium:** $MEDIUM"
- echo "- **Total:** $TOTAL"
- echo ""
- } >> "$GITHUB_STEP_SUMMARY"
-
- if [ "$CRITICAL" -gt 0 ] || [ "$HIGH" -gt 0 ]; then
- echo "⚠️ **Action Required:** Critical or High severity issues found" >> "$GITHUB_STEP_SUMMARY"
- else
- echo "✅ **No Critical or High severity issues found**" >> "$GITHUB_STEP_SUMMARY"
- fi
-
- {
- echo ""
- echo "📋 **Detailed Results:**"
- echo "- Security tab: Results uploaded to GitHub Security tab"
- echo "- Artifacts: Full JSON and SARIF reports available"
- } >> "$GITHUB_STEP_SUMMARY"
- else
- echo "❌ Semgrep scan failed or no results generated" >> "$GITHUB_STEP_SUMMARY"
- fi
+ retention-days: 7
diff --git a/docs/ci/workflow-status.md b/docs/ci/workflow-status.md
index 7de07cccc8..87daf26c61 100644
--- a/docs/ci/workflow-status.md
+++ b/docs/ci/workflow-status.md
@@ -73,7 +73,7 @@
| `retirejs.yml` | last 30 days | manual, workflow_call, schedule(0 4 * * 1) | [![status](https://github.com/LearningCircuit/local-deep-research/actions/workflows/retirejs.yml/badge.svg)](https://github.com/LearningCircuit/local-deep-research/actions/workflows/retirejs.yml) |
| `security-headers-validation.yml` | last 30 days | workflow_call, schedule(0 3 * * *), manual | [![status](https://github.com/LearningCircuit/local-deep-research/actions/workflows/security-headers-validation.yml/badge.svg)](https://github.com/LearningCircuit/local-deep-research/actions/workflows/security-headers-validation.yml) |
| `security-tests.yml` | last 30 days | workflow_call, manual | [![status](https://github.com/LearningCircuit/local-deep-research/actions/workflows/security-tests.yml/badge.svg)](https://github.com/LearningCircuit/local-deep-research/actions/workflows/security-tests.yml) |
-| `semgrep.yml` | last 30 days | workflow_call, manual | [![status](https://github.com/LearningCircuit/local-deep-research/actions/workflows/semgrep.yml/badge.svg)](https://github.com/LearningCircuit/local-deep-research/actions/workflows/semgrep.yml) |
+| `semgrep.yml` | last 30 days | PR, workflow_call, manual | [![status](https://github.com/LearningCircuit/local-deep-research/actions/workflows/semgrep.yml/badge.svg)](https://github.com/LearningCircuit/local-deep-research/actions/workflows/semgrep.yml) |
| `zizmor-security.yml` | last 30 days | PR, manual, workflow_call, schedule(0 9 * * 1) | [![status](https://github.com/LearningCircuit/local-deep-research/actions/workflows/zizmor-security.yml/badge.svg)](https://github.com/LearningCircuit/local-deep-research/actions/workflows/zizmor-security.yml) |
## Release gates — release-time only
diff --git a/tests/ci/standalone/test_semgrep_integration.py b/tests/ci/standalone/test_semgrep_integration.py
new file mode 100644
index 0000000000..abc2948fcc
--- /dev/null
+++ b/tests/ci/standalone/test_semgrep_integration.py
@@ -0,0 +1,91 @@
+"""Exercise the installed scanner against harmless synthetic fixtures in CI."""
+
+# allow: no-sut-import — invokes the scanner and its CI report policy.
+
+import json
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[3]
+
+
+ shutil.which("semgrep"), "Semgrep integration runs in scanner CI"
+)
+class ScannerTests(unittest.TestCase):
+ def test_native_reports_preserve_all_severities_and_clean_control(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"
+ " metadata:\n category: security\n"
+ for severity in ("ERROR", "WARNING", "INFO")
+ ),
+ encoding="utf-8",
+ )
+ target = root / "example.py"
+ for code, expected in (
+ (
+ "probe_error()\nprobe_warning()\nprobe_info()\n",
+ {"ERROR", "WARNING", "INFO"},
+ ),
+ ("value = 1\n", set()),
+ ):
+ target.write_text(code, encoding="utf-8")
+ result = subprocess.run(
+ [
+ "semgrep",
+ "scan",
+ "--config",
+ str(rules),
+ "--strict",
+ "--metrics=off",
+ "--disable-version-check",
+ "--json-output",
+ str(root / "report.json"),
+ "--sarif-output",
+ str(root / "report.sarif"),
+ str(target),
+ ],
+ cwd=root,
+ capture_output=True,
+ text=True,
+ timeout=90,
+ check=False,
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ report = json.loads(
+ (root / "report.json").read_text(encoding="utf-8")
+ )
+ self.assertEqual(
+ {r["extra"]["severity"] for r in report["results"]},
+ expected,
+ )
+ checked = subprocess.run(
+ [
+ sys.executable,
+ str(ROOT / ".github/scripts/check_semgrep_report.py"),
+ str(root / "report.json"),
+ str(root / "report.sarif"),
+ ],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ )
+ self.assertEqual(
+ checked.returncode, 0, checked.stdout + checked.stderr
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/ci/standalone/test_semgrep_report.py b/tests/ci/standalone/test_semgrep_report.py
new file mode 100644
index 0000000000..f1f1dcfde1
--- /dev/null
+++ b/tests/ci/standalone/test_semgrep_report.py
@@ -0,0 +1,507 @@
+"""Standalone report-policy tests; no application initialization required."""
+
+# allow: no-sut-import — imports the standalone CI script directly.
+
+import contextlib
+import copy
+import importlib.util
+import io
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parents[3]
+SPEC = importlib.util.spec_from_file_location(
+ "semgrep_report", ROOT / ".github/scripts/check_semgrep_report.py"
+)
+POLICY = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(POLICY)
+
+
+# Scores GitHub may not read as a decimal (so the alert would get no level
+# and never block a release), plus out-of-range values. float() accepts
+# every string here except "invalid" and "".
+BAD_SECURITY_SEVERITIES = (
+ None,
+ True,
+ False,
+ "NaN",
+ "Infinity",
+ float("nan"),
+ float("inf"),
+ "-1",
+ -1,
+ "11",
+ 11,
+ "10.5",
+ "invalid",
+ "",
+ "1e1",
+ "+8",
+ " 8 ",
+ "8\n",
+ "8.",
+ ".8",
+ "0_8",
+ "\u0668", # ARABIC-INDIC DIGIT EIGHT
+ "\uff18", # FULLWIDTH DIGIT EIGHT
+ [8],
+ {"score": 8},
+)
+
+
+class ReportTests(unittest.TestCase):
+ def setUp(self):
+ self.report = {
+ "errors": [],
+ "skipped_rules": [],
+ "paths": {"scanned": ["example.py"]},
+ "results": [],
+ }
+ self.sarif = {
+ "version": "2.1.0",
+ "runs": [
+ {
+ "invocations": [
+ {
+ "executionSuccessful": True,
+ "toolExecutionNotifications": [],
+ }
+ ],
+ "results": [],
+ "tool": {
+ "driver": {
+ "rules": [
+ {
+ "id": "example",
+ "defaultConfiguration": {
+ "level": "warning"
+ },
+ }
+ ]
+ }
+ },
+ }
+ ],
+ }
+
+ def _with_finding(self, level=None, rule_level="warning"):
+ """One consistent JSON/SARIF finding pair for rule ``example``."""
+ report = copy.deepcopy(self.report)
+ report["results"] = [
+ {"check_id": "example", "extra": {"severity": "WARNING"}}
+ ]
+ sarif = copy.deepcopy(self.sarif)
+ result = {"ruleId": "example"}
+ if level is not None:
+ result["level"] = level
+ sarif["runs"][0]["tool"] = {
+ "driver": {
+ "rules": [
+ {
+ "id": "example",
+ "defaultConfiguration": {"level": rule_level},
+ }
+ ]
+ }
+ }
+ sarif["runs"][0]["results"] = [result]
+ return report, sarif
+
+ def _rejects(self, message, report, sarif):
+ """Assert validation fails with ``message``, not some other check.
+
+ Matching the message keeps each negative case pinned to the check it
+ targets: a case another check also rejects would stay green if its
+ own check were deleted.
+ """
+ with self.assertRaisesRegex(ValueError, message):
+ POLICY.validate(report, sarif)
+
+ def test_clean_scan(self):
+ self.assertEqual(POLICY.validate(self.report, self.sarif), {})
+
+ def test_scanner_errors_and_missing_error_status_fail(self):
+ for errors in (None, [{"message": "scanner failure"}], "malformed"):
+ with self.subTest(errors=errors):
+ self._rejects(
+ "Semgrep reported errors",
+ {**self.report, "errors": errors},
+ self.sarif,
+ )
+
+ def test_empty_scan_scope_fails(self):
+ self._rejects(
+ "Semgrep did not report any scanned files",
+ {**self.report, "paths": {"scanned": []}},
+ self.sarif,
+ )
+
+ def test_scan_without_loaded_rules_fails(self):
+ """Semgrep lists every loaded rule; none means nothing was checked."""
+ for tool in (
+ None,
+ {},
+ {"driver": {}},
+ {"driver": {"rules": []}},
+ {"driver": {"rules": "example"}},
+ ):
+ sarif = copy.deepcopy(self.sarif)
+ if tool is None:
+ del sarif["runs"][0]["tool"]
+ else:
+ sarif["runs"][0]["tool"] = tool
+ with self.subTest(tool=tool):
+ self._rejects(
+ "SARIF run lists no loaded rules", self.report, sarif
+ )
+
+ def test_finding_severities_are_preserved(self):
+ self.report["results"] = [
+ {"extra": {"severity": s, "is_ignored": True}}
+ for s in ("ERROR", "WARNING", "INFO")
+ ]
+ self.assertEqual(
+ POLICY.validate(self.report, self.sarif),
+ {"ERROR": 1, "WARNING": 1, "INFO": 1},
+ )
+
+ def test_missing_sarif_run_or_failed_invocation_fails(self):
+ self._rejects(
+ "SARIF contains no scan runs",
+ self.report,
+ {**self.sarif, "runs": []},
+ )
+ # Each run otherwise passes (it has a loaded rule), so only the
+ # invocation check under test can reject it.
+ for invocation in (
+ {"executionSuccessful": False},
+ {},
+ {"executionSuccessful": "true"},
+ ):
+ sarif = copy.deepcopy(self.sarif)
+ sarif["runs"][0]["invocations"] = [invocation]
+ with self.subTest(invocation=invocation):
+ self._rejects(
+ "SARIF does not report successful scanner execution",
+ self.report,
+ sarif,
+ )
+ for invocations in ([], None):
+ sarif = copy.deepcopy(self.sarif)
+ if invocations is None:
+ del sarif["runs"][0]["invocations"]
+ else:
+ sarif["runs"][0]["invocations"] = invocations
+ with self.subTest(invocations=invocations):
+ self._rejects(
+ "SARIF run has no scanner invocation", self.report, sarif
+ )
+
+ def test_sarif_findings_need_severity_metadata(self):
+ self.sarif["runs"][0].update(
+ {
+ "tool": {
+ "driver": {
+ "rules": [
+ {
+ "id": "example",
+ "properties": {"security-severity": "8.0"},
+ }
+ ]
+ }
+ },
+ "results": [{"ruleId": "example"}],
+ }
+ )
+ self.report["results"] = [
+ {"check_id": "example", "extra": {"severity": "ERROR"}}
+ ]
+ self.assertEqual(POLICY.validate(self.report, self.sarif), {"ERROR": 1})
+ for score in ("0", "4", "7.5", "10.0", 0, 8, 7.5, 10):
+ good = copy.deepcopy(self.sarif)
+ good["runs"][0]["tool"]["driver"]["rules"][0]["properties"][
+ "security-severity"
+ ] = score
+ with self.subTest(score=score):
+ self.assertEqual(
+ POLICY.validate(self.report, good), {"ERROR": 1}
+ )
+ for score in BAD_SECURITY_SEVERITIES:
+ bad = copy.deepcopy(self.sarif)
+ bad["runs"][0]["tool"]["driver"]["rules"][0]["properties"][
+ "security-severity"
+ ] = score
+ with self.subTest(score=score):
+ self._rejects(
+ "SARIF rule has an? (malformed|out-of-range) security "
+ "severity",
+ self.report,
+ bad,
+ )
+
+ def test_every_loaded_rule_score_is_checked(self):
+ """A rule with no finding in this scan must still carry a valid score.
+
+ Its alerts are what the release gate counts once it fires.
+ """
+ report, sarif = self._with_finding()
+ rules = sarif["runs"][0]["tool"]["driver"]["rules"]
+ rules.append(
+ {"id": "quiet", "properties": {"security-severity": "7.5"}}
+ )
+ self.assertEqual(POLICY.validate(report, sarif), {"WARNING": 1})
+ for score in BAD_SECURITY_SEVERITIES:
+ rules[-1]["properties"]["security-severity"] = score
+ with self.subTest(score=score):
+ self._rejects(
+ "SARIF rule has an? (malformed|out-of-range) security "
+ "severity",
+ report,
+ sarif,
+ )
+ for rule, message in (
+ (None, "SARIF rule descriptor is malformed"),
+ ("quiet", "SARIF rule descriptor is malformed"),
+ ({}, "SARIF rule descriptor is malformed"),
+ ({"id": 1}, "SARIF rule descriptor is malformed"),
+ (
+ {"id": "quiet", "properties": []},
+ "SARIF rule properties are malformed",
+ ),
+ ):
+ rules[-1] = rule
+ with self.subTest(rule=rule):
+ self._rejects(message, report, sarif)
+
+ def test_malformed_json_results_fail(self):
+ for results, message in (
+ (None, "Semgrep findings are missing or malformed"),
+ ({}, "Semgrep findings are missing or malformed"),
+ ("results", "Semgrep findings are missing or malformed"),
+ ([None], "Semgrep finding is malformed"),
+ ([{"extra": None}], "Semgrep finding has no metadata"),
+ ):
+ with self.subTest(results=results):
+ self._rejects(
+ message, {**self.report, "results": results}, self.sarif
+ )
+
+ def test_unrecognized_severity_fails(self):
+ report, sarif = self._with_finding()
+ self.assertEqual(POLICY.validate(report, sarif), {"WARNING": 1})
+ for severity in (None, "", "info", "CRITICAL ", "UNKNOWN"):
+ report["results"][0]["extra"]["severity"] = severity
+ with self.subTest(severity=severity):
+ self._rejects(
+ "Semgrep finding has no recognized severity", report, sarif
+ )
+
+ def test_skipped_rules_fail(self):
+ for skipped in (None, [{"rule_id": "example"}], "malformed"):
+ report = {**self.report, "skipped_rules": skipped}
+ with self.subTest(skipped=skipped):
+ self._rejects("Semgrep skipped rules", report, self.sarif)
+ report = dict(self.report)
+ del report["skipped_rules"]
+ self._rejects("Semgrep skipped rules", report, self.sarif)
+
+ def test_malformed_scanned_paths_fail(self):
+ for scanned, message in (
+ ([""], "Semgrep reported a malformed scanned path"),
+ ([None], "Semgrep reported a malformed scanned path"),
+ (["example.py", ""], "Semgrep reported a malformed scanned path"),
+ ("example.py", "Semgrep did not report any scanned files"),
+ ):
+ report = {**self.report, "paths": {"scanned": scanned}}
+ with self.subTest(scanned=scanned):
+ self._rejects(message, report, self.sarif)
+
+ def test_non_native_sarif_version_fails(self):
+ for version in (None, "2.0.0", "2.1", 2.1):
+ with self.subTest(version=version):
+ self._rejects(
+ "Expected native SARIF 2.1.0",
+ self.report,
+ {**self.sarif, "version": version},
+ )
+
+ def test_malformed_sarif_run_results_fail(self):
+ for results in (None, {}, "results"):
+ sarif = copy.deepcopy(self.sarif)
+ sarif["runs"][0]["results"] = results
+ with self.subTest(results=results):
+ self._rejects(
+ "SARIF findings are missing or malformed",
+ self.report,
+ sarif,
+ )
+
+ def test_error_notifications_fail(self):
+ for key in (
+ "toolExecutionNotifications",
+ "toolConfigurationNotifications",
+ ):
+ sarif = copy.deepcopy(self.sarif)
+ sarif["runs"][0]["invocations"][0][key] = [
+ {"level": "error", "message": {"text": "rule failed"}}
+ ]
+ with self.subTest(key=key):
+ self._rejects(
+ f"SARIF reports an error in {key}", self.report, sarif
+ )
+ sarif = copy.deepcopy(self.sarif)
+ sarif["runs"][0]["invocations"][0]["toolExecutionNotifications"] = [
+ {"level": "note", "message": {"text": "informational"}}
+ ]
+ self.assertEqual(POLICY.validate(self.report, sarif), {})
+
+ def test_non_object_entries_fail(self):
+ """Each container check fails with its own message, not a crash."""
+ for report in (None, [], "report"):
+ with self.subTest(report=report):
+ self._rejects(
+ "Semgrep JSON must be an object", report, self.sarif
+ )
+ sarif = copy.deepcopy(self.sarif)
+ sarif["runs"][0]["invocations"] = [None]
+ self._rejects("SARIF invocation is malformed", self.report, sarif)
+ sarif = copy.deepcopy(self.sarif)
+ sarif["runs"][0]["results"] = [None]
+ self._rejects("SARIF finding is malformed", self.report, sarif)
+ for key in (
+ "toolExecutionNotifications",
+ "toolConfigurationNotifications",
+ ):
+ # {} is not a list but iterates as empty; [None] is a list whose
+ # entry is not an object.
+ for notifications in ({}, [None]):
+ sarif = copy.deepcopy(self.sarif)
+ sarif["runs"][0]["invocations"][0][key] = notifications
+ with self.subTest(key=key, notifications=notifications):
+ self._rejects(
+ f"SARIF {key} are malformed", self.report, sarif
+ )
+
+ def test_finding_without_rule_descriptor_fails(self):
+ # An explicit result level, so only the missing descriptor can fail.
+ report, sarif = self._with_finding("warning")
+ self.assertEqual(POLICY.validate(report, sarif), {"WARNING": 1})
+ sarif["runs"][0]["results"][0]["ruleId"] = "unknown"
+ report["results"][0]["check_id"] = "unknown"
+ self._rejects("SARIF finding has no rule descriptor", report, sarif)
+
+ def test_level_none_is_not_severity_information(self):
+ for level, rule_level in (("none", "warning"), (None, "none")):
+ report, sarif = self._with_finding(level, rule_level)
+ with self.subTest(level=level, rule_level=rule_level):
+ self._rejects(
+ "SARIF finding lacks severity information", report, sarif
+ )
+ report, sarif = self._with_finding("error", "none")
+ self.assertEqual(POLICY.validate(report, sarif), {"WARNING": 1})
+
+ def test_json_and_sarif_findings_must_agree(self):
+ report, sarif = self._with_finding()
+ truncated = copy.deepcopy(sarif)
+ truncated["runs"][0]["results"] = []
+ renamed = copy.deepcopy(report)
+ renamed["results"][0]["check_id"] = "other"
+ for bad_report, bad_sarif in (
+ (report, truncated),
+ (self.report, sarif),
+ (renamed, sarif),
+ ):
+ self._rejects(
+ "Semgrep JSON and SARIF reports disagree", bad_report, bad_sarif
+ )
+ # Suppressed findings are excluded on both sides.
+ suppressed = copy.deepcopy(sarif)
+ suppressed["runs"][0]["results"][0]["suppressions"] = [
+ {"kind": "inSource"}
+ ]
+ ignored = copy.deepcopy(report)
+ ignored["results"][0]["extra"]["is_ignored"] = True
+ self.assertEqual(POLICY.validate(ignored, suppressed), {"WARNING": 1})
+ self.assertEqual(POLICY.validate(ignored, truncated), {"WARNING": 1})
+
+ def test_hostile_input_reports_error_instead_of_traceback(self):
+ """Hostile reports fail with an ``::error::`` line, not a traceback.
+
+ The deeply nested input has two valid outcomes. Before Python 3.14
+ the C JSON decoder bounds nesting by a fixed recursion count, so it
+ raises ``RecursionError``. From 3.14 the bound is the C stack
+ size, so with a large or unlimited ``ulimit -s`` (as in the CI test
+ image, Python 3.14.7) the 100,000-deep list parses and is then
+ rejected as not being SARIF. No depth is deterministic there, since
+ an unlimited stack parses any depth that fits in memory. Either way
+ the validator must report an error and exit 1; that is what matters.
+ """
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ report = root / "report.json"
+ report.write_text(json.dumps(self.report), encoding="utf-8")
+ deep = root / "deep.sarif"
+ deep.write_text("[" * 100_000 + "]" * 100_000, encoding="utf-8")
+ huge = copy.deepcopy(self.sarif)
+ huge["runs"][0]["tool"] = {
+ "driver": {
+ "rules": [
+ {
+ "id": "example",
+ "properties": {"security-severity": 10**400},
+ }
+ ]
+ }
+ }
+ huge["runs"][0]["results"] = [{"ruleId": "example"}]
+ overflow = root / "overflow.sarif"
+ overflow.write_text(json.dumps(huge), encoding="utf-8")
+ for sarif_path, reason in (
+ (
+ deep,
+ r"RecursionError|ValueError: Expected native SARIF 2\.1\.0",
+ ),
+ (overflow, r"out-of-range security severity"),
+ ):
+ with self.subTest(sarif=sarif_path.name):
+ out = io.StringIO()
+ with (
+ mock.patch.object(
+ sys,
+ "argv",
+ ["check", str(report), str(sarif_path)],
+ ),
+ contextlib.redirect_stdout(out),
+ ):
+ self.assertEqual(POLICY.main(), 1)
+ self.assertRegex(
+ out.getvalue(),
+ rf"\A::error::Invalid Semgrep scan: [^\n]*(?:{reason})",
+ )
+ self.assertNotIn("Traceback", out.getvalue())
+
+ def test_cli_accepts_consistent_reports(self):
+ report, sarif = self._with_finding()
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ (root / "r.json").write_text(json.dumps(report), encoding="utf-8")
+ (root / "r.sarif").write_text(json.dumps(sarif), encoding="utf-8")
+ out = io.StringIO()
+ with (
+ mock.patch.object(
+ sys,
+ "argv",
+ ["check", str(root / "r.json"), str(root / "r.sarif")],
+ ),
+ contextlib.redirect_stdout(out),
+ ):
+ self.assertEqual(POLICY.main(), 0)
+ self.assertIn("1 findings", out.getvalue())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/ci/test_semgrep_workflow.py b/tests/ci/test_semgrep_workflow.py
new file mode 100644
index 0000000000..78cd20545e
--- /dev/null
+++ b/tests/ci/test_semgrep_workflow.py
@@ -0,0 +1,767 @@
+"""Contracts for the Semgrep scan's report integrity.
+
+A partial or filtered Semgrep report uploaded to code scanning silently
+resolves existing alerts. These tests pin the known-good workflow wiring
+that prevents that: the workflow has only the pinned top-level keys and the
+single ``semgrep-scan`` job, the job runs exactly the pinned steps in order
+with pinned action inputs and no job container or services, one
+``semgrep scan`` with a fixed command (every configured ruleset, every
+severity, ``src/``, no baseline or exclusions) writes the reports, no
+``.semgrepignore`` exists at the root or under ``src/``, no tracked file
+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
+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).
+
+Scope: these are regression tests. They guard against accidental edits of
+the kinds seen so far (masking the exit status with ``|| true``, filtering
+by severity, narrowing the scanned rules or files) by matching the pinned
+text exactly rather than looking for forbidden patterns. A deliberately
+adversarial edit to the workflow is outside what static tests can
+guarantee; that is covered by the required CODEOWNERS review of
+``.github/workflows/semgrep.yml`` and ``.semgrepignore``.
+"""
+
+import fnmatch
+import json
+import re
+import shlex
+import subprocess
+from pathlib import Path
+
+import yaml
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+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}"
+VERIFY_RUN = (
+ "python -m unittest discover -s tests/ci/standalone"
+ " -p 'test_semgrep*.py' -v"
+)
+INSTALL_RUN = re.compile(r"python -m pip install semgrep==\d+(\.\d+)+")
+# The complete scan argv. Any added option (``--exclude``,
+# ``--exclude-rule``, ``--include``, ``--baseline-commit``,
+# ``--max-target-bytes``, ...) or dropped ``--config`` narrows the report,
+# and the validator cannot tell a narrowed report from a complete one.
+SCAN_ARGV = [
+ "semgrep",
+ "scan",
+ "--config=p/security-audit",
+ "--config=p/secrets",
+ "--config=.semgrep/rules/",
+ "--strict",
+ "--metrics=off",
+ f"--json-output={JSON_REPORT}",
+ f"--sarif-output={SARIF_REPORT}",
+ "src/",
+]
+# The scan step's exact ``run`` text. It is compared verbatim, as the other
+# ``run`` steps are, because a tokenizer can disagree with bash (e.g. a
+# ``#\\`` line is one comment to bash but hides the next line from shlex).
+SCAN_RUN = (
+ f"{SCAN_ARGV[0]} {SCAN_ARGV[1]} \\\n"
+ + "".join(f" {arg} \\\n" for arg in SCAN_ARGV[2:-1])
+ + f" {SCAN_ARGV[-1]}\n"
+)
+# The job's steps, in order. Actions are matched by name (the pinned SHA
+# after ``@`` may change); ``run`` steps by their exact command.
+ACTION_STEPS = {
+ "harden-runner": "step-security/harden-runner",
+ "checkout": "actions/checkout",
+ "setup-python": "actions/setup-python",
+ "upload-sarif": "github/codeql-action/upload-sarif",
+ "upload-artifact": "actions/upload-artifact",
+}
+STEP_ORDER = [
+ "harden-runner",
+ "checkout",
+ "setup-python",
+ "install",
+ "verify",
+ "scan",
+ "validate",
+ "upload-sarif",
+ "upload-artifact",
+]
+UPLOAD_WITH = {
+ "sarif_file": SARIF_REPORT,
+ "category": "semgrep-security",
+ "wait-for-processing": True,
+}
+# Every action step's complete ``with``. For checkout, a ``sparse-checkout``,
+# ``ref``, ``repository`` or ``path`` would scan a narrower or different tree
+# and upload it as this commit's analysis.
+ACTION_WITH = {
+ "harden-runner": {"egress-policy": "audit"},
+ "checkout": {"persist-credentials": False},
+ "setup-python": {"python-version": "3.12"},
+ "upload-sarif": UPLOAD_WITH,
+ "upload-artifact": {
+ "name": "semgrep-scan-results",
+ "path": f"{JSON_REPORT}\n{SARIF_REPORT}\n",
+ "retention-days": 7,
+ },
+}
+# Job-level keys. ``container`` or ``services`` would run the steps in, or
+# next to, an image the contract does not see; ``defaults``, ``env``, ``if``
+# and ``continue-on-error`` change how or whether the steps run.
+JOB_KEYS = {"runs-on", "timeout-minutes", "permissions", "steps"}
+# Workflow-level keys. PyYAML (YAML 1.1) loads the ``on`` key as ``True``.
+# ``defaults``, ``env`` or ``concurrency`` would change how, or whether, the
+# job runs.
+WORKFLOW_KEYS = {"name", True, "permissions", "jobs"}
+# Semgrep 1.177.0's built-in ignore patterns, which apply when no
+# ``.semgrepignore`` exists (as test_no_semgrepignore_in_the_scanned_tree
+# requires). Files or directories with these names, at any depth:
+DEFAULT_IGNORED_NAMES = {".git", ".svn", ".hg", "_darcs", "CVS"}
+# directories with these names, at any depth:
+DEFAULT_IGNORED_DIRS = {
+ "build",
+ "vendor",
+ "dist",
+ ".env",
+ ".tox",
+ "node_modules",
+ ".npm",
+ ".yarn",
+ ".venv",
+ "_opam",
+ "_build",
+ "_cargo",
+ "test",
+ "tests",
+ "testsuite",
+}
+# and files matching these patterns.
+DEFAULT_IGNORED_FILES = ("*.min.js", "*_test.go")
+# Semgrep 1.177.0's default ``--max-target-bytes``: a tracked file above
+# this size is silently skipped, the same as a default-ignored path.
+MAX_TARGET_BYTES = 1_000_000
+# ``run`` steps may carry nothing that changes how their command runs:
+# no ``shell``, ``env`` (Semgrep reads e.g. SEMGREP_BASELINE_COMMIT and
+# SEMGREP_RULES), ``working-directory``, ``if`` or ``continue-on-error``.
+RUN_STEP_KEYS = {"name", "id", "run"}
+ACTION_STEP_KEYS = {"name", "id", "uses", "with", "if"}
+SEMGREP_EXECUTABLES = {"semgrep", "pysemgrep", "osemgrep", "semgrep-core"}
+STATUS_FUNCTIONS = ("success(", "always(", "failure(", "cancelled(")
+
+
+def _workflow() -> dict:
+ return yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))
+
+
+def _job() -> dict:
+ return _workflow()["jobs"]["semgrep-scan"]
+
+
+def _steps() -> list[dict]:
+ return _job()["steps"]
+
+
+def _run_tokens(step: dict) -> list[str]:
+ """Shell tokens of a ``run``; operators become their own tokens.
+
+ Only used to detect Semgrep invocations, never to accept a command.
+ ``#`` is kept as a word character so no text is hidden as a comment,
+ and backslash-newline is removed as bash removes it.
+ """
+ run = str(step.get("run", "")).replace("\\\n", "")
+ lexer = shlex.shlex(run, posix=True, punctuation_chars=True)
+ lexer.whitespace_split = True
+ lexer.commenters = ""
+ return list(lexer)
+
+
+def _invokes_semgrep(step: dict) -> bool:
+ """Whether the step runs the Semgrep scanner (not just installs it)."""
+ if "semgrep" in str(step.get("uses", "")).lower():
+ return True
+ tokens = _run_tokens(step)
+ for i, token in enumerate(tokens):
+ if token.rsplit("/", 1)[-1] in SEMGREP_EXECUTABLES:
+ return True
+ if token == "-m" and tokens[i + 1 : i + 2] == ["semgrep"]:
+ return True
+ return False
+
+
+def _scan_step(steps: list[dict]) -> dict:
+ scans = [step for step in steps if _invokes_semgrep(step)]
+ assert len(scans) == 1, [step.get("name") for step in scans]
+ return scans[0]
+
+
+def _scan_tokens(steps: list[dict]) -> list[str]:
+ return _run_tokens(_scan_step(steps))
+
+
+def _step_kind(step: dict) -> str:
+ uses = step.get("uses")
+ if uses is not None:
+ action = str(uses).split("@", 1)[0]
+ for kind, name in ACTION_STEPS.items():
+ if action == name:
+ return kind
+ return f"unknown action {uses!r}"
+ run = str(step.get("run", "")).strip()
+ if INSTALL_RUN.fullmatch(run):
+ return "install"
+ if run == VERIFY_RUN:
+ return "verify"
+ if run == VALIDATOR_RUN:
+ return "validate"
+ if step.get("run") == SCAN_RUN:
+ return "scan"
+ return f"unknown run {run!r}"
+
+
+def _index(steps: list[dict], kind: str) -> int:
+ kinds = [_step_kind(step) for step in steps]
+ assert kinds.count(kind) == 1, kinds
+ return kinds.index(kind)
+
+
+def _is_upload_sarif(step: dict) -> bool:
+ return _step_kind(step) == "upload-sarif"
+
+
+def _upload_condition(steps: list[dict]) -> str:
+ condition = " ".join(
+ str(steps[_index(steps, "upload-sarif")].get("if", "")).split()
+ )
+ if condition.startswith("${{") and condition.endswith("}}"):
+ condition = condition[3:-2].strip()
+ return condition
+
+
+# --- A minimal GitHub Actions expression evaluator ------------------------
+# Supports the subset the upload condition needs: context paths, string
+# literals, the ``true``/``false``/``null`` literals, ==, !=, !, &&, || and
+# parentheses, with GitHub's semantics for each. Anything else (notably
+# function calls and number literals) is rejected, and so is a path whose
+# first segment is not a context of the evaluated run (GitHub rejects an
+# unrecognized named-value too), so the condition cannot silently grow a
+# status function, a literal or other logic the truth-table test does not
+# model. Lookups are strict as well: a property the truth-table context does
+# not model raises instead of evaluating to null, because on GitHub such a
+# field (``github.actor``, ``github.run_id``, ``pull_request.number``) is
+# usually set and truthy, and a null stand-in would let an appended
+# ``|| github.actor`` pass the table while making fork PRs upload. Only
+# dereferencing a modelled null (a deleted fork's ``head.repo``) yields
+# null, as on GitHub. && and || short-circuit as on GitHub: an operand they
+# skip is parsed but its properties are not looked up, so a push run need
+# not model ``github.event.pull_request``.
+
+_EXPR_TOKEN = re.compile(
+ r"\s*(?:(?P<op>\|\||&&|==|!=|!|\(|\))"
+ r"|(?P<str>'(?:[^']|'')*')"
+ r"|(?P<bool>(?:true|false)(?![A-Za-z0-9_.-]))"
+ r"|(?P<null>null(?![A-Za-z0-9_.-]))"
+ r"|(?P<path>[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*))"
+)
+# The number formats GitHub accepts when it coerces a string to a number.
+_NUMBER = re.compile(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?")
+
+
+def _lex(expression: str) -> list[tuple[str, str]]:
+ tokens, pos = [], 0
+ expression = expression.strip()
+ while pos < len(expression):
+ match = _EXPR_TOKEN.match(expression, pos)
+ if not match or match.end() == pos:
+ raise ValueError(f"unsupported expression at {expression[pos:]!r}")
+ kind = match.lastgroup
+ tokens.append((kind, match.group(kind)))
+ pos = match.end()
+ return tokens
+
+
+def _lookup(context: dict, path: str):
+ root, *rest = path.split(".")
+ if root not in context:
+ raise ValueError(f"unrecognized named-value: {root!r}")
+ value = context[root]
+ for depth, part in enumerate(rest, start=1):
+ if value is None:
+ return None # GitHub: a property of null is null
+ if not isinstance(value, dict) or part not in value:
+ prefix = ".".join([root, *rest[:depth]])
+ raise ValueError(f"unmodelled context property: {prefix!r}")
+ value = value[part]
+ return value
+
+
+def _to_number(value) -> float:
+ # GitHub's coercion when == or != compares values of different types.
+ if value is None:
+ return 0.0
+ if isinstance(value, bool):
+ return 1.0 if value else 0.0
+ if isinstance(value, (int, float)):
+ return float(value)
+ if isinstance(value, str):
+ text = value.strip()
+ if not text:
+ return 0.0
+ return float(text) if _NUMBER.fullmatch(text) else float("nan")
+ return float("nan") # objects and arrays
+
+
+def _truthy(value) -> bool:
+ # GitHub's falsy values: false, 0, -0, '', null and NaN.
+ if value is None or value is False or value == "":
+ return False
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return value == value and value != 0
+ return True
+
+
+def _equal(left, right) -> bool:
+ # Same type: strings compare case-insensitively, objects by identity.
+ # Different types: both are coerced to numbers (NaN equals nothing), so
+ # e.g. null == false and null == '' are true, true == 'true' is false.
+ if isinstance(left, str) and isinstance(right, str):
+ return left.lower() == right.lower()
+ if isinstance(left, bool) and isinstance(right, bool):
+ return left is right
+ if left is None and right is None:
+ return True
+ if isinstance(left, (dict, list)) or isinstance(right, (dict, list)):
+ return left is right
+ return _to_number(left) == _to_number(right)
+
+
+def _evaluate(expression: str, context: dict):
+ tokens = _lex(expression)
+ pos = 0
+ # Depth of operands that && / || short-circuit past. GitHub does not
+ # evaluate them, so their paths are parsed but not looked up.
+ skipping = 0
+
+ def peek():
+ return tokens[pos] if pos < len(tokens) else (None, None)
+
+ def take(value=None):
+ nonlocal pos
+ token = peek()
+ if token[0] is None or (value is not None and token[1] != value):
+ raise ValueError(f"expected {value!r}, got {token[1]!r}")
+ pos += 1
+ return token
+
+ def primary():
+ kind, value = peek()
+ if value == "(":
+ take("(")
+ result = disjunction()
+ take(")")
+ return result
+ if value == "!":
+ take("!")
+ return not _truthy(primary())
+ take()
+ if kind == "str":
+ return value[1:-1].replace("''", "'")
+ if kind == "bool":
+ return value == "true"
+ if kind == "null":
+ return None
+ if kind == "path":
+ if peek()[1] == "(":
+ raise ValueError(f"function calls are unsupported: {value}")
+ if skipping: # GitHub still rejects an unknown named-value
+ _lookup(context, value.split(".")[0])
+ return None
+ return _lookup(context, value)
+ raise ValueError(f"unexpected token {value!r}")
+
+ def operand(parse, evaluated: bool):
+ nonlocal skipping
+ skipping += not evaluated
+ try:
+ return parse()
+ finally:
+ skipping -= not evaluated
+
+ def comparison():
+ left = primary()
+ while peek()[1] in ("==", "!="):
+ op = take()[1]
+ right = primary()
+ left = _equal(left, right) == (op == "==")
+ return left
+
+ def conjunction():
+ left = comparison()
+ while peek()[1] == "&&":
+ take("&&")
+ right = operand(comparison, _truthy(left))
+ left = right if _truthy(left) else left
+ return left
+
+ def disjunction():
+ left = conjunction()
+ while peek()[1] == "||":
+ take("||")
+ right = operand(conjunction, not _truthy(left))
+ left = left if _truthy(left) else right
+ return left
+
+ result = disjunction()
+ if pos != len(tokens):
+ raise ValueError(f"trailing tokens: {tokens[pos:]}")
+ return result
+
+
+REPOSITORY = "LearningCircuit/local-deep-research"
+FORK = "someone/local-deep-research"
+
+
+def _pr_context(head_repo) -> dict:
+ """A ``pull_request`` run; every field the pinned condition reads is set.
+
+ ``_lookup`` raises on any other property, so the table stays honest only
+ if each context models what the condition references, with the value
+ GitHub would supply for that case.
+ """
+ return {
+ "github": {
+ "event_name": "pull_request",
+ "repository": REPOSITORY,
+ "event": {"pull_request": {"head": {"repo": head_repo}}},
+ }
+ }
+
+
+def _head_repo(full_name: str) -> dict:
+ # ``fork`` is GitHub's flag for a head repository other than the base.
+ return {
+ "full_name": full_name,
+ "fork": full_name.lower() != REPOSITORY.lower(),
+ }
+
+
+# (description, context, upload expected)
+UPLOAD_CASES = [
+ ("same-repo PR", _pr_context(_head_repo(REPOSITORY)), True),
+ (
+ "same-repo PR, different case",
+ _pr_context(_head_repo(REPOSITORY.lower())),
+ True,
+ ),
+ ("fork PR", _pr_context(_head_repo(FORK)), False),
+ ("deleted-fork PR (head.repo null)", _pr_context(None), False),
+] + [
+ (
+ f"{event} run",
+ {
+ "github": {
+ "event_name": event,
+ "repository": REPOSITORY,
+ "event": {},
+ }
+ },
+ True,
+ )
+ # Under workflow_call, event_name is the caller's event.
+ for event in ("workflow_call", "schedule", "workflow_dispatch", "push")
+]
+
+
+def test_scan_has_no_severity_filter():
+ """``--severity`` selects exact levels; any use drops the other levels."""
+ assert not [t for t in _scan_tokens(_steps()) if "--severity" in t]
+
+
+def test_exactly_one_step_runs_semgrep():
+ """A second scan (e.g. INFO-only ``|| true``) could overwrite the reports."""
+ steps = _steps()
+ assert _scan_step(steps) is steps[_index(steps, "scan")]
+
+
+def test_scan_command_is_pinned():
+ """The scan ``run`` is exactly the pinned text, compared verbatim.
+
+ So an accidental ``|| true``, ``set +e``, extra option, dropped ruleset,
+ comment or second command in the scan step fails.
+ """
+ steps = _steps()
+ assert _scan_step(steps)["run"] == SCAN_RUN
+ assert _scan_tokens(steps) == SCAN_ARGV
+
+
+def test_action_inputs_are_pinned():
+ """Each action step's ``with`` is exactly the expected inputs."""
+ steps = _steps()
+ for kind, expected in ACTION_WITH.items():
+ assert steps[_index(steps, kind)].get("with") == expected, kind
+
+
+def test_workflow_has_only_the_semgrep_scan_job():
+ """A sibling job could run a narrowed or exit-masked scan.
+
+ Uploaded to the same ``semgrep-security`` category and ref, its report
+ would replace the full scan's analysis and resolve open alerts, and the
+ release gate calls this whole workflow.
+ """
+ workflow = _workflow()
+ assert set(workflow) == WORKFLOW_KEYS, set(workflow) ^ WORKFLOW_KEYS
+ assert set(workflow["jobs"]) == {"semgrep-scan"}, set(workflow["jobs"])
+
+
+def _default_ignored(path: str) -> bool:
+ *dirs, name = path.split("/")
+ return (
+ any(part in DEFAULT_IGNORED_NAMES for part in (*dirs, name))
+ or any(part in DEFAULT_IGNORED_DIRS for part in dirs)
+ or any(
+ fnmatch.fnmatchcase(part, pat)
+ for part in (*dirs, name)
+ for pat in DEFAULT_IGNORED_FILES
+ )
+ )
+
+
+def test_no_default_ignored_paths_under_src():
+ """No tracked file under ``src/`` matches Semgrep's built-in ignores.
+
+ With no ``.semgrepignore``, Semgrep 1.177.0 silently skips e.g. any
+ ``tests/``, ``build/``, ``dist/`` or ``vendor/`` directory,
+ ``node_modules/`` and ``*.min.js`` files at any depth, and the narrowed
+ report still validates. None is tracked under ``src/`` today; adding one
+ must move it or deliberately change this test and how the scan covers
+ it. Tracked files are what the scan job's fresh checkout contains; local
+ build output (e.g. the gitignored ``web/static/dist/``) is not.
+ """
+ listed = subprocess.run(
+ ["git", "ls-files", "-z", "--", "src"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ check=False,
+ )
+ assert listed.returncode == 0, listed.stderr
+ tracked = [path for path in listed.stdout.decode().split("\0") if path]
+ assert tracked, "git ls-files listed nothing under src/"
+ found = [path for path in tracked if _default_ignored(path)]
+ assert not found, found
+
+
+def test_no_oversized_or_special_entries_under_src():
+ """No tracked ``src/`` entry is a symlink, a submodule, or too big.
+
+ With no ``--max-target-bytes`` override, Semgrep 1.177.0 silently skips
+ any tracked file above its default 1,000,000-byte cap (exit 0, no
+ error, no skipped-rule entry) the same way it silently skips a
+ default-ignored path, and the narrowed report still validates. It also
+ silently skips a tracked symlink. A submodule's gitlink entry is not a
+ blob Semgrep could scan at all. ``git ls-files -s`` reports a symlink as
+ mode ``120000`` and a submodule as mode ``160000``; every other tracked
+ entry is a regular (mode ``100644``/``100755``) blob whose size is
+ checked with ``git cat-file -s``. None is tracked under ``src/`` today
+ (the largest tracked file is well under the cap); adding one that trips
+ this must shrink it, exclude it from ``src/``, or deliberately change
+ this test and how the scan covers it.
+ """
+ listed = subprocess.run(
+ ["git", "ls-files", "-s", "-z", "--", "src"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ check=False,
+ )
+ assert listed.returncode == 0, listed.stderr
+ entries = [entry for entry in listed.stdout.decode().split("\0") if entry]
+ assert entries, "git ls-files listed nothing under src/"
+
+ symlinks = []
+ submodules = []
+ oversized = []
+ for entry in entries:
+ meta, path = entry.split("\t", 1)
+ mode, sha, _stage = meta.split(" ")
+ if mode == "120000":
+ symlinks.append(path)
+ continue
+ if mode == "160000":
+ submodules.append(path)
+ continue
+ sized = subprocess.run(
+ ["git", "cat-file", "-s", sha],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ check=False,
+ )
+ assert sized.returncode == 0, sized.stderr
+ if int(sized.stdout) > MAX_TARGET_BYTES:
+ oversized.append(path)
+
+ assert not symlinks, symlinks
+ assert not submodules, submodules
+ assert not oversized, oversized
+
+
+def test_job_has_only_the_pinned_keys():
+ """No container, services, defaults, env, ``if`` or continue-on-error."""
+ job = _job()
+ assert set(job) == JOB_KEYS, set(job) ^ JOB_KEYS
+ assert job["runs-on"] == "ubuntu-latest"
+
+
+def test_no_semgrepignore_in_the_scanned_tree():
+ """No ``.semgrepignore`` at the repo root or anywhere under ``src/``.
+
+ Semgrep 1.177.0 honours a ``.semgrepignore`` at the root and in any
+ scanned subdirectory, and silently drops the matching files, so the
+ narrowed report still validates. None exists; false positives are
+ suppressed per line with ``nosemgrep``, which stays next to the code it
+ suppresses. Adding an ignore file must change this test too.
+ """
+ found = [
+ *REPO_ROOT.glob(".semgrepignore"),
+ *(REPO_ROOT / "src").rglob(".semgrepignore"),
+ ]
+ assert not found, found
+
+
+def test_job_runs_only_the_pinned_steps():
+ """Any other step could rewrite, filter or replace the reports."""
+ assert [_step_kind(step) for step in _steps()] == STEP_ORDER
+
+
+def test_only_the_scan_writes_the_reports():
+ """Other steps may only read the reports (validator and uploads)."""
+ 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)
+ )
+ ]
+ assert referencing == [
+ "scan",
+ "validate",
+ "upload-sarif",
+ "upload-artifact",
+ ]
+
+
+def test_no_step_or_default_can_mask_failure():
+ """No setting may mask a step's exit status or alter how it runs."""
+ workflow = _workflow()
+ job = _job()
+ # A default shell such as ``bash -c '{0} || true'`` masks every run step;
+ # a default working directory or env changes what the scan covers.
+ for scope in (workflow, job):
+ assert "defaults" not in scope
+ assert "env" not in scope
+ assert job.get("continue-on-error") in (None, False)
+ for step in _steps():
+ allowed = RUN_STEP_KEYS if "run" in step else ACTION_STEP_KEYS
+ assert set(step) <= allowed, (step.get("name"), set(step) - allowed)
+ assert step.get("continue-on-error") in (None, False)
+ for kind in ("harden-runner", "checkout", "setup-python", "scan"):
+ assert "if" not in _steps()[_index(_steps(), kind)]
+
+
+def test_reports_are_validated_immediately_before_upload():
+ steps = _steps()
+ scan = _index(steps, "scan")
+ validate = _index(steps, "validate")
+ upload = _index(steps, "upload-sarif")
+ assert scan < validate
+ # Nothing may touch the SARIF between validation and upload.
+ assert upload == validate + 1
+ # Exactly the validator command: nothing may suppress its exit status.
+ assert steps[validate]["run"].strip() == VALIDATOR_RUN
+
+
+def test_upload_is_the_validated_sarif():
+ steps = _steps()
+ upload_with = steps[_index(steps, "upload-sarif")]["with"]
+ # wait-for-processing surfaces processing errors; no ref/sha/path
+ # 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]
+ assert f"--sarif-output={SARIF_REPORT}" in _scan_tokens(steps)
+
+
+def test_upload_runs_only_after_success():
+ """No status function at all, so GitHub's implicit ``success()`` applies.
+
+ Any explicit status function (even ``success() || ...``) replaces the
+ implicit one and can upload the report of a failed scan or validation.
+ """
+ condition = "".join(_upload_condition(_steps()).split()).lower()
+ for status in STATUS_FUNCTIONS:
+ assert status not in condition
+
+
+def test_fork_pull_requests_do_not_upload():
+ """Fork PR tokens are read-only; every other run must upload."""
+ condition = _upload_condition(_steps())
+ for description, context, expected in UPLOAD_CASES:
+ assert _truthy(_evaluate(condition, context)) is expected, description
+
+
+def test_expression_evaluator_models_literals():
+ """Literals evaluate as GitHub evaluates them, not as context paths.
+
+ Otherwise an appended ``|| true`` would read an absent context, evaluate
+ to null and pass the truth table while making every run upload. For the
+ same reason a context property the table does not model raises.
+ """
+ context = _pr_context(None)
+ assert _evaluate("true", context) is True
+ assert _evaluate("false", context) is False
+ assert _evaluate("null", context) is None
+ assert _evaluate("false || true", context) is True
+ assert _evaluate("true && false", context) is False
+ assert _evaluate("!false", context) is True
+ assert _evaluate("null == false", context) is True
+ assert _evaluate("null == ''", context) is True
+ assert _evaluate("true == 'true'", context) is False
+ assert _evaluate("github.event.pull_request.head.repo == null", context)
+ assert (
+ _evaluate("github.event.pull_request.head.repo.fork", context) is None
+ )
+ assert _evaluate("true || github.actor", context) is True
+ assert _evaluate("false && github.actor", context) is False
+ for unsupported in (
+ "True",
+ "success()",
+ "1",
+ "true.x",
+ "nothing.here",
+ # Real but unmodelled fields must fail loud, not read as null.
+ "github.actor",
+ "github.event.pull_request.number",
+ "github.repository.owner",
+ "false && nothing.here",
+ ):
+ try:
+ _evaluate(unsupported, context)
+ except ValueError:
+ continue
+ raise AssertionError(f"accepted {unsupported!r}")
+
+
+def test_pull_requests_touching_the_scanned_tree_run_the_scan():
+ """``--strict`` fails the scan on a file Semgrep cannot parse.
+
+ Without ``src/**`` in the ``pull_request`` paths, a PR adding such a
+ file merges green and the failure first appears in the release gate.
+ """
+ triggers = _workflow()[True]
+ assert "src/**" in triggers["pull_request"]["paths"]
+ assert "paths-ignore" not in triggers["pull_request"]