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.

ci: verify release decisions and expiring exceptions (#6887)

LearningCircuit3d626c2a4abd
diff --git a/.file-whitelist.txt b/.file-whitelist.txt
index ae62aeaa36..e382151cf4 100644
--- a/.file-whitelist.txt
+++ b/.file-whitelist.txt
@@ -29,6 +29,7 @@
^package-lock\.json$
^lighthouserc\.json$
^\.github/ai-review-label-policy\.json$
+^\.github/release-security-exceptions\.json$
^\.github/release-scan-policy\.json$
^tests/(.*/)?package\.json$
^tests/(.*/)?package-lock\.json$
diff --git a/.github/SECURITY_ALERTS.md b/.github/SECURITY_ALERTS.md
index 9944b66409..21b7fea4b0 100644
--- a/.github/SECURITY_ALERTS.md
+++ b/.github/SECURITY_ALERTS.md
@@ -1,7 +1,155 @@
# Security Alert Assessment
This document explains the security scanning alerts that have been assessed
-and determined to be false positives or intentionally suppressed.
+and determined to be false positives, intentionally suppressed, or temporarily
+accepted for release.
+
+## Temporary release exceptions
+
+The release gate's alert checks block on every open critical, high, or medium
+code scanning alert, whichever tool raised it. For a finding that only these
+alert checks block, **the preferred temporary approach while waiting for an
+upstream fix is a narrowly scoped, expiring release exception**, provided
+reviewers accept the documented risk for that specific alert. Record it in
+[release-security-exceptions.json](release-security-exceptions.json), then review
+and merge the policy change through a PR before using it for a release. This
+accepts the risk temporarily; it does not fix the vulnerability or automatically
+authorize exceptions for other alerts.
+
+Exactly two steps read the policy, both in the `Check Code Scanning Alerts` job
+of `release-gate.yml`: `Validate fresh analyses and open alerts`
+(`check_release_scan_evidence.py`) and `Check open alerts and reviewed
+exceptions` (`check_code_scanning_alerts.py`). `Release Gate Summary` still
+requires every other gate job to succeed, and the Trivy scans during Docker
+publication do not read the policy. An exception therefore cannot unblock a
+scanner job that fails on its own findings; see
+[Scanners that fail on findings](#scanners-that-fail-on-findings).
+
+Keep scanners running and the finding visible while the exception is active.
+For a finding that only the alert checks block, use this reviewed policy for
+the waiting period instead of dismissing a valid alert, suppressing the finding
+in the scanner's configuration, bypassing the release gate, or carrying a local
+dependency backport solely to unblock a release. If reviewers cannot accept the
+risk, the alert continues to block. Once a verified upstream fix is available,
+deploy it, rebuild and scan, and remove the exception. Any extension requires a
+fresh review of the risk and expiry.
+
+Each entry must identify an exact alert number, rule ID, tool, scan category,
+file path, and severity, together with a rationale, tracking link, and expiry.
+The repository must also match. There are no wildcard matches: a new alert or
+severity increase still blocks. The checker rejects missing or malformed policy
+files and API responses, and queries all pages before deciding whether to pass.
+An empty `exceptions` list restores the normal policy without exceptions.
+The final check, which reads the default branch's open alerts, does not block
+low or unscored alerts. The fresh-evidence check additionally blocks unscored
+error/warning findings on the release ref. An invalid supplied severity fails
+the gate.
+
+`expires_on` is an exclusive UTC date: an entry with `2026-10-13` stops applying
+at **00:00 UTC on October 13, 2026**. An expired entry with an open matching alert
+blocks release again. An entry for an alert that is no longer open grants
+nothing and should be removed. Extensions require another reviewed policy change.
+
+The gate retains the earliest **applied** expiry from both the fresh-evidence
+check on the release ref and the later default-branch alert check, even if an
+alert is absent from the later response. It carries that expiry through Docker
+publication and GitHub Release creation. The successful release build records it in an
+immutable `release-security-decision-<attempt>` artifact, bound to the repository,
+release commit, workflow run, and build attempt. PyPI dispatches carry the
+artifact ID. The verifier checks GitHub's artifact/run metadata, main ancestry,
+the successful build and upload time, and the archive digest before reading its
+deadline. A caller-supplied `release_deadline` is never used. Missing, expired,
+tampered, or unrelated artifacts fail closed. A partial rerun keeps the artifact
+ID from the original successful build, even when the parent run's attempt changes.
+
+Each publication checks the original deadline after environment approval,
+including publish-job reruns. The explicit value `none` is recorded only when
+no exception applied. Expired decisions require a fix or a reviewed policy
+update and a new release run; editing `main` does not renew an old decision.
+The decision artifact is retained for 30 days, without extending its deadline.
+Native Docker builds load their images locally; a separate push step checks
+expiry again after the build. Signed SLSA provenance and per-platform SBOM
+attestations are still added by `create-manifest`; BuildKit's additional inline
+provenance is disabled for compatibility with the local Docker image store.
+An upload already started or an artifact already published is not rolled back.
+
+The policy and gate come from the triggering release commit. The build must
+prove that commit is an ancestor of `main`; PyPI verifies its dispatched SHA
+against `main` too. PyPI loads its decision verifier from the default-branch
+commit that supplies the publishing workflow. The `release` environment restricts
+deployments to `main`
+and `v*` tags and requires reviewer approval (verified September 27, 2026).
+Keep those environment restrictions in place: a branch-only gate run is for
+validation and does not authorize publication.
+
+The exception applies only to those two alert checks. Scanners still run,
+failing scanner jobs still block, SARIF uploads are unchanged, and the alert
+stays open in GitHub Security. The job summary lists open, excepted, and
+blocking counts, plus each applied exception's reason and expiry. The overall
+release summary explicitly reports when it passes with exceptions. Publishing
+still uses the existing release approvals; the checker has no permission to
+dismiss alerts. API failures report a bounded, workflow-command-escaped error
+body for diagnosis.
+
+Before reading alerts, the gate polls every 15 seconds until every required
+analysis category has a fresh successful analysis, for at most 300 seconds in
+total. Evidence must match the release commit, ref, workflow and job, and be no
+older than the workflow run. Missing, failed or unverifiable analyses block
+release. The exception policy cannot replace this fresh evidence. Hosted
+release qualification is tracked in
+[issue #4823](https://github.com/LearningCircuit/local-deep-research/issues/4823).
+
+### Scanners that fail on findings
+
+The jobs below fail on their own findings, not only through code scanning
+alerts, so a release exception cannot unblock them. Each keeps its own
+suppression. Change one only through a reviewed PR that records the reason and
+a tracking link beside the entry, and remove the entry once the fix ships.
+
+- **OSV-Scanner** (`osv-scan`): any vulnerability in a completed scan fails the
+ job. Add an `[[IgnoredVulns]]` entry with `id`, `ignoreUntil`, and `reason`
+ to the `osv-scanner.toml` in the affected lockfile's directory. `ignoreUntil`
+ is a native expiry: afterwards the finding fails the scan again. The two v2
+ release entries in [osv-scanner.toml](../osv-scanner.toml)
+ (`GHSA-8mgp-746c-j5xp` and `GHSA-4mvj-m6j5-pmf7`, `ignoreUntil = 2026-10-31`)
+ are the model.
+- **Trivy during Docker publication**: the `Security Scan` job in
+ `prerelease-docker.yml` and the digest rescan in `docker-publish.yml` fail on
+ fixable critical or high image findings, after release approval. Both read
+ [.trivyignore](../.trivyignore), not the exception policy, so an exception
+ for such a `container-security` alert passes the gate but not publication.
+ Add the ID with Trivy's native `exp:YYYY-MM-DD` expiry and a comment like the
+ existing entries. The gate's `container-security` scan reads the same file,
+ so it stops reporting the finding too. Medium findings only raise
+ `container-security` alerts, which an exception can cover.
+- **npm audit** (`npm-audit`): a moderate or higher advisory fails the job
+ unless its GHSA ID is in `AUDIT_ALLOWLIST`, the environment variable that
+ `.github/scripts/npm_audit_allowlist.py` reads. The allowlist is only for
+ advisories with no available fix in dev or test-only tooling. It has no
+ expiry: remove the ID in a follow-up PR.
+- **Retire.js** (`retirejs-scan`): a medium or higher finding fails release
+ runs. No Retire.js ignore file is checked in; update or replace the library.
+- **Gitleaks** (`gitleaks-scan`): any detected secret fails the job. Rotate a
+ real secret. Record a reviewed false positive as a rule-scoped allowlist in
+ `.gitleaks.toml` or a fingerprint in `.gitleaksignore`; neither expires.
+
+Any other gate job that fails blocks the release the same way. Hadolint,
+Checkov, and the ZAP baseline, for example, fail on findings in this
+repository's own Dockerfile, compose files, workflows, or running app. One
+finding can also block through several scanners: a Python dependency
+vulnerability can fail OSV-Scanner and raise Grype or Trivy alerts as well.
+Cover every path that blocks.
+
+### Current exception policy
+
+The checked-in policy has an empty `exceptions` list. It grants no release
+exception for CVE-2026-87910 / alert #8273 or any other finding. Runtime image
+remediation is tracked in
+[issue #6678](https://github.com/LearningCircuit/local-deep-research/issues/6678).
+Unresolved findings continue to block according to the normal gate policy;
+adding an exception would require a separately reviewed policy change.
+
+---
## DS162092 - Hardcoded URLs
diff --git a/.github/release-security-exceptions.json b/.github/release-security-exceptions.json
new file mode 100644
index 0000000000..8a00ff91ec
--- /dev/null
+++ b/.github/release-security-exceptions.json
@@ -0,0 +1,5 @@
+{
+ "version": 1,
+ "repository": "LearningCircuit/local-deep-research",
+ "exceptions": []
+}
diff --git a/.github/scripts/check_code_scanning_alerts.py b/.github/scripts/check_code_scanning_alerts.py
new file mode 100644
index 0000000000..671fb877eb
--- /dev/null
+++ b/.github/scripts/check_code_scanning_alerts.py
@@ -0,0 +1,372 @@
+#!/usr/bin/env python3
+"""Enforce the release alert gate without closing temporarily excepted alerts.
+
+Only GET requests are made. A reviewed, expiring policy can exempt an exact
+alert from this check and the fresh-evidence check; scanner results and GitHub
+alert state stay intact. It cannot unblock a scanner job that fails on its own
+findings. Deploy the verified fix and remove the exception once available; see
+.github/SECURITY_ALERTS.md for the policy.
+"""
+
+from __future__ import annotations
+
+import argparse
+from collections import Counter
+from datetime import date, datetime, timezone
+import html
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+
+
+SEVERITIES = ("critical", "high", "medium")
+POLICY_PATH = (
+ Path(__file__).resolve().parents[1] / "release-security-exceptions.json"
+)
+EXCEPTION_FIELDS = {
+ "alert_number",
+ "rule_id",
+ "tool",
+ "category",
+ "path",
+ "severity",
+ "expires_on",
+ "reason",
+ "tracking_url",
+}
+
+
+def load_exceptions(path: Path, repository: str) -> dict[int, dict]:
+ policy = json.loads(path.read_text(encoding="utf-8"))
+ if (
+ not isinstance(policy, dict)
+ or set(policy) != {"version", "repository", "exceptions"}
+ or type(policy["version"]) is not int
+ or policy["version"] != 1
+ or policy["repository"] != repository
+ or not isinstance(policy["exceptions"], list)
+ ):
+ raise ValueError("Invalid exception policy or repository mismatch")
+
+ exceptions = {}
+ for entry in policy["exceptions"]:
+ if not isinstance(entry, dict) or set(entry) != EXCEPTION_FIELDS:
+ raise ValueError("Exception has missing or unknown fields")
+ number = entry["alert_number"]
+ if type(number) is not int or number <= 0 or number in exceptions:
+ raise ValueError(
+ "Exception alert numbers must be unique positive integers"
+ )
+ for field in EXCEPTION_FIELDS - {"alert_number"}:
+ if not isinstance(entry[field], str) or not entry[field].strip():
+ raise ValueError(f"Exception #{number} has invalid {field}")
+ if entry["severity"] not in SEVERITIES:
+ raise ValueError(f"Exception #{number} has invalid severity")
+ expires = date.fromisoformat(entry["expires_on"])
+ if expires.isoformat() != entry["expires_on"]:
+ raise ValueError(
+ f"Exception #{number} needs an ISO YYYY-MM-DD expiry"
+ )
+ if not re.fullmatch(
+ r"https://github\.com/[\w./#-]+", entry["tracking_url"]
+ ):
+ raise ValueError(f"Exception #{number} needs a GitHub tracking URL")
+ exceptions[number] = entry
+ return exceptions
+
+
+def validate_alerts(alerts: object) -> None:
+ if not isinstance(alerts, list):
+ raise ValueError("Code scanning API response must be a JSON array")
+ for alert in alerts:
+ if (
+ not isinstance(alert, dict)
+ or type(alert.get("number")) is not int
+ or alert["number"] <= 0
+ or alert.get("state") != "open"
+ or not isinstance(alert.get("rule"), dict)
+ or not isinstance(alert["rule"].get("id"), str)
+ or alert["rule"].get("security_severity_level")
+ not in (*SEVERITIES, "low", None)
+ ):
+ raise ValueError("Malformed open code scanning alert")
+
+
+def fetch_alerts(repository: str) -> list[dict]:
+ alerts = []
+ page = 1
+ while True:
+ # Explicit GET and argv (no shell): this gate cannot dismiss alerts.
+ result = subprocess.run(
+ [
+ "gh",
+ "api",
+ "--method",
+ "GET",
+ "-H",
+ "Accept: application/vnd.github+json",
+ "-H",
+ "X-GitHub-Api-Version: 2022-11-28",
+ f"/repos/{repository}/code-scanning/alerts"
+ f"?state=open&per_page=100&page={page}",
+ ],
+ check=True,
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+ batch = json.loads(result.stdout)
+ validate_alerts(batch)
+ if not batch:
+ return alerts
+ alerts.extend(batch)
+ page += 1
+
+
+def matches_exception(alert: dict, entry: dict) -> bool:
+ instance = alert.get("most_recent_instance") or {}
+ tool = alert.get("tool") or {}
+ if not isinstance(instance, dict) or not isinstance(tool, dict):
+ return False
+ location = instance.get("location") or {}
+ if not isinstance(location, dict):
+ return False
+ return (
+ alert["number"] == entry["alert_number"]
+ and alert["rule"]["id"] == entry["rule_id"]
+ and alert["rule"].get("security_severity_level") == entry["severity"]
+ and tool.get("name") == entry["tool"]
+ and instance.get("category") == entry["category"]
+ and location.get("path") == entry["path"]
+ )
+
+
+def classify_alerts(
+ alerts: list[dict],
+ exceptions: dict[int, dict],
+ today: date,
+) -> tuple[list[dict], list[dict], list[int]]:
+ blocking, excepted, expired = [], [], []
+ for alert in alerts:
+ if alert["rule"].get("security_severity_level") not in SEVERITIES:
+ continue
+ entry = exceptions.get(alert["number"])
+ if entry is not None and matches_exception(alert, entry):
+ # The exception stops applying at 00:00 UTC on expires_on.
+ if today < date.fromisoformat(entry["expires_on"]):
+ excepted.append(alert)
+ continue
+ expired.append(alert["number"])
+ blocking.append(alert)
+ return blocking, excepted, expired
+
+
+def publication_deadline(
+ excepted: list[dict], exceptions: dict[int, dict]
+) -> str:
+ """Carry only applied exceptions' earliest expiry into publication jobs."""
+ return min(
+ (exceptions[alert["number"]]["expires_on"] for alert in excepted),
+ default="none",
+ )
+
+
+def earliest_deadline(previous: str, current: str, today: date) -> str:
+ """Retain every applied expiry, including alerts absent from a later query."""
+ deadlines = []
+ for value in (previous, current):
+ if value == "none":
+ continue
+ expiry = date.fromisoformat(value)
+ if expiry.isoformat() != value:
+ raise ValueError("Release deadline must be YYYY-MM-DD or none")
+ if today >= expiry:
+ raise ValueError(
+ f"Release exception expired at 00:00 UTC on {value}"
+ )
+ deadlines.append(value)
+ return min(deadlines, default="none")
+
+
+def summary_text(value: str) -> str:
+ return (
+ html.escape(value)
+ .replace("\n", " ")
+ .replace("\r", " ")
+ .replace("|", "&#124;")
+ .replace("`", "&#96;")
+ )
+
+
+def render_summary(
+ repository: str,
+ alerts: list[dict],
+ blocking: list[dict],
+ excepted: list[dict],
+ expired: list[int],
+ exceptions: dict[int, dict],
+ deadline: str,
+) -> str:
+ open_counts, excepted_counts, blocking_counts = (
+ Counter(alert["rule"].get("security_severity_level") for alert in group)
+ for group in (alerts, excepted, blocking)
+ )
+ lines = [
+ "## Code Scanning Alert Summary",
+ "",
+ f"Fetched {len(alerts)} open alert(s).",
+ "",
+ "| Severity | Open | Temporarily excepted | Blocking |",
+ "|----------|------|----------------------|----------|",
+ ]
+ for severity in SEVERITIES:
+ lines.append(
+ f"| {severity.title()} | {open_counts[severity]} | "
+ f"{excepted_counts[severity]} | {blocking_counts[severity]} |"
+ )
+ if excepted:
+ lines += [
+ "",
+ "### Temporary release exceptions",
+ "",
+ "These alerts remain open in GitHub Security. "
+ "Scanner findings are unchanged.",
+ "",
+ ]
+ for alert in excepted:
+ entry = exceptions[alert["number"]]
+ lines.append(
+ f"- [#{alert['number']}](https://github.com/{repository}"
+ f"/security/code-scanning/{alert['number']}) "
+ f"`{summary_text(entry['rule_id'])}`: expires at "
+ f"00:00 UTC on **{entry['expires_on']}**. "
+ f"{summary_text(entry['reason'])} "
+ f"[Tracking]({entry['tracking_url']})"
+ )
+ if expired:
+ lines += [
+ "",
+ "Expired exceptions (blocking again): "
+ + ", ".join(f"#{number}" for number in expired),
+ ]
+ if blocking:
+ lines += ["", f"**Release blocked: {len(blocking)} alert(s).**", ""]
+ for alert in blocking:
+ description = alert["rule"].get("description")
+ detail = (
+ f": {summary_text(description)}"
+ if isinstance(description, str) and description
+ else ""
+ )
+ lines.append(
+ f"- [{alert['rule']['security_severity_level'].upper()}] "
+ f"`{summary_text(alert['rule']['id'])}` "
+ f"[#{alert['number']}](https://github.com/{repository}"
+ f"/security/code-scanning/{alert['number']}){detail}"
+ )
+ elif excepted:
+ lines += [
+ "",
+ f"**Passed with {len(excepted)} temporary release exception(s).**",
+ ]
+ elif deadline != "none":
+ lines += [
+ "",
+ "**Passed with temporary release exceptions from the fresh "
+ "scan evidence check. Their original expiry still applies.**",
+ ]
+ else:
+ lines += ["", "**No open critical, high, or medium severity alerts.**"]
+ if not blocking:
+ lines += [
+ "",
+ "Publication deadline (UTC, exclusive; `none` means no applied "
+ "exceptions): "
+ f"`{deadline}`.",
+ ]
+ return "\n".join(lines) + "\n"
+
+
+def annotate(level: str, message: str) -> None:
+ # Escape untrusted text before emitting a GitHub workflow command.
+ escaped = (
+ message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
+ )
+ print(f"::{level}::{escaped}")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repository", required=True)
+ parser.add_argument("--exceptions", type=Path, default=POLICY_PATH)
+ parser.add_argument("--evidence-deadline", required=True)
+ args = parser.parse_args()
+ if not re.fullmatch(r"[\w.-]+/[\w.-]+", args.repository):
+ parser.error("Repository must be OWNER/REPO")
+ try:
+ earliest_deadline(
+ args.evidence_deadline, "none", datetime.now(timezone.utc).date()
+ )
+ exceptions = load_exceptions(args.exceptions, args.repository)
+ alerts = fetch_alerts(args.repository)
+ today = datetime.now(timezone.utc).date()
+ blocking, excepted, expired = classify_alerts(
+ alerts,
+ exceptions,
+ today,
+ )
+ deadline = earliest_deadline(
+ args.evidence_deadline,
+ publication_deadline(excepted, exceptions),
+ today,
+ )
+ report = render_summary(
+ args.repository,
+ alerts,
+ blocking,
+ excepted,
+ expired,
+ exceptions,
+ deadline,
+ )
+ print(report)
+ if path := os.environ.get("GITHUB_STEP_SUMMARY"):
+ with Path(path).open("a", encoding="utf-8") as summary:
+ summary.write(report)
+ for alert in excepted:
+ entry = exceptions[alert["number"]]
+ annotate(
+ "warning",
+ f"Release exception for open alert #{alert['number']} "
+ f"expires at 00:00 UTC on {entry['expires_on']}",
+ )
+ if blocking:
+ annotate(
+ "error",
+ f"Security gate failed: {len(blocking)} blocking alert(s)",
+ )
+ return 1
+ if path := os.environ.get("GITHUB_OUTPUT"):
+ with Path(path).open("a", encoding="utf-8") as output:
+ output.write(f"excepted_count={len(excepted)}\n")
+ output.write(f"release_deadline={deadline}\n")
+ return 0
+ except subprocess.CalledProcessError as exc:
+ # gh puts useful HTTP/rate-limit diagnostics on stderr. Bound and
+ # escape them so API errors stay actionable without log injection.
+ detail = exc.stderr or exc.stdout or "No API error body returned"
+ annotate(
+ "error",
+ f"Security alert API request failed (exit {exc.returncode}): "
+ f"{detail[:2000]}",
+ )
+ return 1
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
+ annotate("error", f"Security alert gate could not complete: {exc}")
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.github/scripts/check_release_deadline.py b/.github/scripts/check_release_deadline.py
new file mode 100644
index 0000000000..8fb9f8ce32
--- /dev/null
+++ b/.github/scripts/check_release_deadline.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python3
+"""Recheck the security gate's deadline after approvals, before publishing.
+
+The original gate emits YYYY-MM-DD (exclusive, UTC) or the explicit sentinel
+`none` when no exception was applied. Missing or malformed values fail closed;
+reruns must not silently turn a lost output into an unlimited exception.
+"""
+
+from __future__ import annotations
+
+import argparse
+from datetime import date, datetime, timezone
+
+
+def check_deadline(value: str, now: datetime) -> None:
+ if value == "none":
+ return
+ try:
+ expiry = date.fromisoformat(value)
+ except ValueError:
+ raise ValueError(
+ "Missing or invalid release deadline; use the original security "
+ "gate output (YYYY-MM-DD or none)."
+ ) from None
+ if expiry.isoformat() != value:
+ raise ValueError("Release deadline must be YYYY-MM-DD or none.")
+ if now.astimezone(timezone.utc).date() >= expiry:
+ raise ValueError(
+ f"Release exception expired at 00:00 UTC on {value}; "
+ "publication is blocked. Fix the alert or merge a reviewed "
+ "policy update and start a new release run."
+ )
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--deadline", required=True)
+ args = parser.parse_args()
+ try:
+ check_deadline(args.deadline, datetime.now(timezone.utc))
+ except ValueError as exc:
+ # Messages contain only constants and a validated ISO date.
+ print(f"::error::{exc}")
+ return 1
+ print(f"Release exception deadline verified: {args.deadline}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.github/scripts/check_release_scan_evidence.py b/.github/scripts/check_release_scan_evidence.py
index 63684a6dc4..1ece843529 100644
--- a/.github/scripts/check_release_scan_evidence.py
+++ b/.github/scripts/check_release_scan_evidence.py
@@ -1,11 +1,14 @@
"""Require fresh release scan analyses before evaluating open alerts."""
+import argparse
+import importlib.util
import json
import os
import re
import subprocess
+import sys
import time
-from datetime import datetime
+from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlencode
@@ -144,8 +147,27 @@ def blocking_alert(alert):
return level in {"error", "warning"}
-def evaluate(fetch=api, sleep=time.sleep, monotonic=time.monotonic):
+def _exception_checker():
+ path = Path(__file__).with_name("check_code_scanning_alerts.py")
+ spec = importlib.util.spec_from_file_location("release_alert_policy", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def evaluate(
+ fetch=api,
+ sleep=time.sleep,
+ monotonic=time.monotonic,
+ *,
+ exception_policy=None,
+):
repo = os.environ["GITHUB_REPOSITORY"]
+ checker = None
+ exceptions = {}
+ if exception_policy is not None:
+ checker = _exception_checker()
+ exceptions = checker.load_exceptions(Path(exception_policy), repo)
sha, ref = os.environ["GITHUB_SHA"], os.environ["GITHUB_REF"]
root = f"repos/{repo}"
run = fetch(f"{root}/actions/runs/{os.environ['GITHUB_RUN_ID']}")
@@ -184,6 +206,16 @@ def evaluate(fetch=api, sleep=time.sleep, monotonic=time.monotonic):
for row in page
]
blocking = [row for row in alerts if blocking_alert(row)]
+ excepted = []
+ if checker is not None:
+ checker.validate_alerts(alerts)
+ _, excepted, _ = checker.classify_alerts(
+ alerts, exceptions, datetime.now(timezone.utc).date()
+ )
+ excepted_numbers = {row["number"] for row in excepted}
+ blocking = [
+ row for row in blocking if row["number"] not in excepted_numbers
+ ]
with open(
os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8"
) as summary:
@@ -194,6 +226,12 @@ def evaluate(fetch=api, sleep=time.sleep, monotonic=time.monotonic):
summary.write(
f"Open blocking alerts: **{len(blocking)}** (critical/high/medium or unscored error/warning).\n"
)
+ if excepted:
+ summary.write(
+ f"Reviewed, unexpired exceptions: **{len(excepted)}**. "
+ "These alerts remain open; publication still requires "
+ "the separate bound security decision and deadline.\n"
+ )
# Do not copy findings or source excerpts into publicly visible logs.
for alert in blocking:
number = int(alert["number"])
@@ -209,14 +247,26 @@ def evaluate(fetch=api, sleep=time.sleep, monotonic=time.monotonic):
f"{len(blocking)} blocking code-scanning alerts remain open: "
+ named
)
+ if checker is not None and (path := os.environ.get("GITHUB_OUTPUT")):
+ with Path(path).open("a", encoding="utf-8") as output:
+ output.write(
+ "release_deadline="
+ f"{checker.publication_deadline(excepted, exceptions)}\n"
+ )
print(
f"Release scan policy passed for {sha}: {len(expected)} fresh categories"
)
-def main():
+def main(argv=()):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--exceptions", type=Path)
+ args = parser.parse_args(argv)
try:
- evaluate()
+ if args.exceptions is None:
+ evaluate()
+ else:
+ evaluate(exception_policy=args.exceptions)
except (
OSError,
ValueError,
@@ -238,10 +288,15 @@ def main():
snippet = _TOKEN_PATTERN.sub("[REDACTED]", stderr.strip())[:500]
if snippet:
detail = f"{detail} | gh stderr: {snippet}"
+ # Tool names and gh stderr are untrusted: escape them so they cannot
+ # end this line and start another workflow command.
+ detail = (
+ detail.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
+ )
print(f"::error::Release scan evidence failed: {detail}")
return 1
return 0
if __name__ == "__main__":
- raise SystemExit(main())
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/.github/scripts/release_security_decision.py b/.github/scripts/release_security_decision.py
new file mode 100644
index 0000000000..b09606a5a6
--- /dev/null
+++ b/.github/scripts/release_security_decision.py
@@ -0,0 +1,271 @@
+#!/usr/bin/env python3
+"""Record a release gate decision and verify its immutable GitHub artifact.
+
+Dispatch payloads select an artifact, never a deadline. Only a successful build
+in this repository's release workflow, on a commit reachable from main, can
+authorize publication. The recorded attempt remains valid on partial reruns.
+"""
+
+from __future__ import annotations
+
+import argparse
+from datetime import datetime, timedelta, timezone
+import hashlib
+import io
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import zipfile
+
+from check_release_deadline import check_deadline
+
+
+RECORD_NAME = "release-security-decision.json"
+ARTIFACT_PREFIX = "release-security-decision-"
+MAX_ARCHIVE_BYTES = 65536
+
+
+def require(condition: bool, message: str) -> None:
+ if not condition:
+ raise ValueError(message)
+
+
+def positive_integer(value: str) -> int:
+ require(
+ bool(re.fullmatch(r"[1-9][0-9]*", value)), "Invalid artifact/run ID"
+ )
+ return int(value)
+
+
+def validate_identity(repository: str, sha: str) -> None:
+ require(
+ bool(re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository)),
+ "Invalid repository",
+ )
+ require(bool(re.fullmatch(r"[0-9a-f]{40}", sha)), "Invalid release commit")
+
+
+def record_decision(args: argparse.Namespace) -> None:
+ validate_identity(args.repository, args.sha)
+ run_id = positive_integer(args.run_id)
+ attempt = positive_integer(args.run_attempt)
+ check_deadline(args.deadline, datetime.now(timezone.utc))
+ record = {
+ "version": 1,
+ "repository": args.repository,
+ "sha": args.sha,
+ "run_id": run_id,
+ "run_attempt": attempt,
+ "release_deadline": args.deadline,
+ }
+ args.output.write_text(json.dumps(record) + "\n", encoding="utf-8")
+
+
+def api_bytes(endpoint: str) -> bytes:
+ return subprocess.run(
+ [
+ "gh",
+ "api",
+ "--method",
+ "GET",
+ "-H",
+ "Accept: application/vnd.github+json",
+ "-H",
+ "X-GitHub-Api-Version: 2022-11-28",
+ endpoint,
+ ],
+ check=True,
+ capture_output=True,
+ timeout=60,
+ ).stdout
+
+
+def api_object(endpoint: str) -> dict:
+ value = json.loads(api_bytes(endpoint))
+ require(isinstance(value, dict), "Malformed GitHub API response")
+ return value
+
+
+def parse_timestamp(value: str) -> datetime:
+ require(isinstance(value, str), "Missing artifact/build timestamp")
+ stamp = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ require(stamp.tzinfo is not None, "Timestamp must include a timezone")
+ return stamp
+
+
+def successful_build(endpoint: str, run_id: int, attempt: int) -> dict:
+ builds = []
+ page = 1
+ while True:
+ response = api_object(f"{endpoint}/jobs?per_page=100&page={page}")
+ jobs = response.get("jobs")
+ require(isinstance(jobs, list), "Missing release jobs")
+ for job in jobs:
+ require(isinstance(job, dict), "Malformed release job")
+ if job.get("name") == "build":
+ builds.append(job)
+ if len(jobs) < 100:
+ break
+ page += 1
+ require(
+ len(builds) == 1, "Expected one release build in the recorded attempt"
+ )
+ build = builds[0]
+ require(
+ type(build.get("run_id")) is int
+ and type(build.get("run_attempt")) is int
+ and build.get("run_id") == run_id
+ and build.get("run_attempt") == attempt
+ and build.get("status") == "completed"
+ and build.get("conclusion") == "success",
+ "The recorded release build did not succeed",
+ )
+ return build
+
+
+def verify_decision(repository: str, sha: str, artifact_id: str) -> str:
+ validate_identity(repository, sha)
+ number = positive_integer(artifact_id)
+ root = f"/repos/{repository}"
+ artifact_endpoint = f"{root}/actions/artifacts/{number}"
+ artifact = api_object(artifact_endpoint)
+ require(
+ type(artifact.get("id")) is int
+ and artifact["id"] == number
+ and artifact.get("expired") is False
+ and type(artifact.get("size_in_bytes")) is int
+ and 0 < artifact["size_in_bytes"] <= MAX_ARCHIVE_BYTES,
+ "Missing, expired, or oversized release decision artifact",
+ )
+ name = artifact.get("name")
+ require(isinstance(name, str), "Missing release decision artifact name")
+ require(name.startswith(ARTIFACT_PREFIX), "Unexpected release artifact")
+ attempt = positive_integer(name.removeprefix(ARTIFACT_PREFIX))
+ source = artifact.get("workflow_run")
+ require(isinstance(source, dict), "Artifact has no workflow provenance")
+ run_id = source.get("id")
+ require(type(run_id) is int and run_id > 0, "Artifact has no source run")
+ require(
+ source.get("head_sha") == sha, "Artifact commit does not match release"
+ )
+
+ # The parent release is normally still running while PyPI publishes. Its
+ # successful build proves the required gates passed; do not require the
+ # entire parent run to finish, which would deadlock with monitor-pypi.
+ attempt_endpoint = f"{root}/actions/runs/{run_id}/attempts/{attempt}"
+ run = api_object(attempt_endpoint)
+ require(
+ type(run.get("id")) is int
+ and type(run.get("run_attempt")) is int
+ and run.get("id") == run_id
+ and run.get("run_attempt") == attempt
+ and run.get("head_sha") == sha
+ and run.get("path") == ".github/workflows/release.yml"
+ and run.get("event") in ("push", "workflow_dispatch")
+ and isinstance(run.get("repository"), dict)
+ and run["repository"].get("full_name") == repository
+ and isinstance(run.get("head_repository"), dict)
+ and run["head_repository"].get("full_name") == repository,
+ "Artifact was not produced by the expected release workflow and attempt",
+ )
+ comparison = api_object(f"{root}/compare/{sha}...heads/main")
+ require(
+ comparison.get("status") in ("ahead", "identical"),
+ "Release decision commit is not on main",
+ )
+ build = successful_build(attempt_endpoint, run_id, attempt)
+ created = parse_timestamp(artifact.get("created_at"))
+ # GitHub timestamps may be rounded to seconds. Reject an artifact from
+ # another job/attempt uploaded after the trusted build has completed.
+ require(
+ parse_timestamp(build.get("started_at"))
+ <= created
+ < parse_timestamp(build.get("completed_at")) + timedelta(seconds=1),
+ "Decision artifact was not created during the release build",
+ )
+
+ archive = api_bytes(f"{artifact_endpoint}/zip")
+ require(len(archive) <= MAX_ARCHIVE_BYTES, "Decision archive is too large")
+ require(
+ artifact.get("digest")
+ == "sha256:" + hashlib.sha256(archive).hexdigest(),
+ "Decision artifact digest mismatch",
+ )
+ with zipfile.ZipFile(io.BytesIO(archive)) as zipped:
+ require(
+ zipped.namelist() == [RECORD_NAME],
+ "Unexpected decision archive contents",
+ )
+ require(
+ zipped.getinfo(RECORD_NAME).file_size <= 16384,
+ "Decision record is too large",
+ )
+ record = json.loads(zipped.read(RECORD_NAME))
+ require(isinstance(record, dict), "Malformed release decision")
+ deadline = record.get("release_deadline")
+ require(isinstance(deadline, str), "Missing recorded deadline")
+ require(
+ type(record.get("version")) is int
+ and type(record.get("run_id")) is int
+ and type(record.get("run_attempt")) is int
+ and record
+ == {
+ "version": 1,
+ "repository": repository,
+ "sha": sha,
+ "run_id": run_id,
+ "run_attempt": attempt,
+ "release_deadline": deadline,
+ },
+ "Release decision does not match its artifact provenance",
+ )
+ check_deadline(deadline, datetime.now(timezone.utc))
+ return deadline
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ modes = parser.add_subparsers(dest="mode", required=True)
+ write = modes.add_parser("record")
+ verify = modes.add_parser("verify")
+ for command in (write, verify):
+ command.add_argument("--repository", required=True)
+ command.add_argument("--sha", required=True)
+ write.add_argument("--run-id", required=True)
+ write.add_argument("--run-attempt", required=True)
+ write.add_argument("--deadline", required=True)
+ write.add_argument("--output", type=Path, required=True)
+ verify.add_argument("--artifact-id", required=True)
+ args = parser.parse_args()
+ try:
+ if args.mode == "record":
+ record_decision(args)
+ else:
+ deadline = verify_decision(
+ args.repository, args.sha, args.artifact_id
+ )
+ if path := os.environ.get("GITHUB_OUTPUT"):
+ with Path(path).open("a", encoding="utf-8") as output:
+ output.write(f"release_deadline={deadline}\n")
+ print(f"Verified original release decision; deadline: {deadline}")
+ return 0
+ except (
+ OSError,
+ ValueError,
+ subprocess.SubprocessError,
+ zipfile.BadZipFile,
+ ) as exc:
+ detail = str(exc)
+ if isinstance(exc, subprocess.CalledProcessError) and exc.stderr:
+ detail = exc.stderr.decode("utf-8", errors="replace")[:2000]
+ detail = (
+ detail.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
+ )
+ print(f"::error::Release decision verification failed: {detail}")
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.github/workflows/ci-policy-tests.yml b/.github/workflows/ci-policy-tests.yml
index 47d8097df5..bbbb83a0f6 100644
--- a/.github/workflows/ci-policy-tests.yml
+++ b/.github/workflows/ci-policy-tests.yml
@@ -5,6 +5,9 @@ on:
paths:
- ".github/workflows/**"
- ".github/scripts/check_release_scan_evidence.py"
+ # The release-scan suite loads both release-exception checkers.
+ - ".github/scripts/check_code_scanning_alerts.py"
+ - ".github/scripts/check_release_deadline.py"
- ".github/scripts/retire_json_to_sarif.py"
- ".github/scripts/run_osv_scan.py"
- ".github/release-scan-policy.json"
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml
index 936953dad7..d23ad3cbbe 100644
--- a/.github/workflows/docker-publish.yml
+++ b/.github/workflows/docker-publish.yml
@@ -36,6 +36,10 @@ on:
description: "sha256:... digest of the prerelease manifest, captured by prerelease-docker.yml. Used to verify retag preserves the digest end-to-end."
type: string
required: true
+ release_deadline:
+ description: "Original security gate deadline (YYYY-MM-DD or none)"
+ type: string
+ required: true
secrets:
DOCKER_USERNAME:
required: true
@@ -153,6 +157,7 @@ jobs:
- name: Promote (retag) prerelease manifest to release tags
env:
+ RELEASE_DEADLINE: ${{ inputs.release_deadline }}
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
SOURCE_TAG: ${{ steps.version.outputs.source_tag }}
VERSION: ${{ steps.version.outputs.version }}
@@ -162,6 +167,7 @@ jobs:
SOURCE="${DOCKER_USERNAME}/local-deep-research:${SOURCE_TAG}"
# Single imagetools create with multiple -t — registry-side
# metadata-only operation, takes seconds, preserves digest.
+ python3 .github/scripts/check_release_deadline.py --deadline "$RELEASE_DEADLINE"
docker buildx imagetools create \
-t "${DOCKER_USERNAME}/local-deep-research:${VERSION}" \
-t "${DOCKER_USERNAME}/local-deep-research:${MAJOR_MINOR}" \
diff --git a/.github/workflows/prerelease-docker.yml b/.github/workflows/prerelease-docker.yml
index 71d1991e79..eb5898dc78 100644
--- a/.github/workflows/prerelease-docker.yml
+++ b/.github/workflows/prerelease-docker.yml
@@ -12,7 +12,7 @@ name: Prerelease Docker Image
# enforced by the caller. The build runs automatically; the only human
# approval in the release flow is the `release` env on this workflow's
# jobs + publish-docker + trigger-pypi + create-release in release.yml
-# (gates the actual publish, not the canonical build).
+# (gates both the build and publication).
on:
workflow_call:
@@ -25,6 +25,10 @@ on:
description: "First 7 chars of commit SHA (used in the prerelease tag)"
type: string
required: true
+ release_deadline:
+ description: "Original security gate deadline (YYYY-MM-DD or none)"
+ type: string
+ required: true
secrets:
# Explicit secrets contract instead of `secrets: inherit` on the
# caller side — narrower blast radius if a future caller misuses
@@ -42,14 +46,11 @@ on:
permissions: {} # Minimal top-level for OSSF Scorecard Token-Permissions
-# No approval gate at the build step — the build runs automatically once
-# security gates and CI gates in release.yml pass. The only meaningful
-# human decision in the release flow is "should this signed, attested,
-# tested image become the official release?" — gated by the `release`
-# environment on this workflow's jobs + `publish-docker` + `trigger-pypi`
-# + `create-release` in release.yml. The maintainer can pull
-# `:prerelease-v<ver>-<sha>` and smoke-test between build completion
-# and approving the release env.
+# Environment approval precedes the native builds. Images are loaded locally
+# first, then the original security deadline is checked immediately before push.
+# Signed SLSA provenance and per-platform SBOM attestations are attached by
+# create-manifest below; the classic local image store cannot retain BuildKit's
+# additional inline attestations.
jobs:
build-amd64:
@@ -80,17 +81,33 @@ jobs:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- - name: Build and push AMD64 image
+ - name: Check release exception deadline before building
+ env:
+ RELEASE_DEADLINE: ${{ inputs.release_deadline }}
+ run: python3 .github/scripts/check_release_deadline.py --deadline "$RELEASE_DEADLINE"
+
+ - name: Build AMD64 image locally
id: build
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
with:
context: .
platforms: linux/amd64
- push: true
+ push: false
+ load: true
+ provenance: false
tags: ${{ secrets.DOCKER_USERNAME }}/local-deep-research:prerelease-v${{ inputs.version }}-${{ inputs.short_sha }}-amd64
cache-from: type=gha,scope=linux-amd64
cache-to: type=gha,mode=max,scope=linux-amd64
+ - name: Push AMD64 image before the deadline
+ env:
+ RELEASE_DEADLINE: ${{ inputs.release_deadline }}
+ IMAGE: ${{ secrets.DOCKER_USERNAME }}/local-deep-research:prerelease-v${{ inputs.version }}-${{ inputs.short_sha }}-amd64
+ run: |
+ set -euo pipefail
+ python3 .github/scripts/check_release_deadline.py --deadline "$RELEASE_DEADLINE"
+ docker push "$IMAGE"
+
build-arm64:
name: Build ARM64 Prerelease Image
runs-on: ubuntu-24.04-arm
@@ -119,17 +136,33 @@ jobs:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- - name: Build and push ARM64 image
+ - name: Check release exception deadline before building
+ env:
+ RELEASE_DEADLINE: ${{ inputs.release_deadline }}
+ run: python3 .github/scripts/check_release_deadline.py --deadline "$RELEASE_DEADLINE"
+
+ - name: Build ARM64 image locally
id: build
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
with:
context: .
platforms: linux/arm64
- push: true
+ push: false
+ load: true
+ provenance: false
tags: ${{ secrets.DOCKER_USERNAME }}/local-deep-research:prerelease-v${{ inputs.version }}-${{ inputs.short_sha }}-arm64
cache-from: type=gha,scope=linux-arm64
cache-to: type=gha,mode=max,scope=linux-arm64
+ - name: Push ARM64 image before the deadline
+ env:
+ RELEASE_DEADLINE: ${{ inputs.release_deadline }}
+ IMAGE: ${{ secrets.DOCKER_USERNAME }}/local-deep-research:prerelease-v${{ inputs.version }}-${{ inputs.short_sha }}-arm64
+ run: |
+ set -euo pipefail
+ python3 .github/scripts/check_release_deadline.py --deadline "$RELEASE_DEADLINE"
+ docker push "$IMAGE"
+
security-scan:
name: Security Scan
runs-on: ubuntu-latest
@@ -250,6 +283,7 @@ jobs:
- name: Create and push multi-platform manifest
env:
+ RELEASE_DEADLINE: ${{ inputs.release_deadline }}
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
VERSION: ${{ inputs.version }}
SHORT_SHA: ${{ inputs.short_sha }}
@@ -257,6 +291,7 @@ jobs:
set -euo pipefail
TAG="prerelease-v${VERSION}-${SHORT_SHA}"
echo "Creating manifest for: ${DOCKER_USERNAME}/local-deep-research:${TAG}"
+ python3 .github/scripts/check_release_deadline.py --deadline "$RELEASE_DEADLINE"
docker buildx imagetools create -t "${DOCKER_USERNAME}/local-deep-research:${TAG}" \
"${DOCKER_USERNAME}/local-deep-research:${TAG}-amd64" \
"${DOCKER_USERNAME}/local-deep-research:${TAG}-arm64"
@@ -268,6 +303,7 @@ jobs:
# versioned tag above remains for reproducibility (and is what
# docker-publish.yml retags by digest into :1.6.9 / :1.6 / :latest).
echo "Updating floating tag: ${DOCKER_USERNAME}/local-deep-research:prerelease"
+ python3 .github/scripts/check_release_deadline.py --deadline "$RELEASE_DEADLINE"
docker buildx imagetools create -t "${DOCKER_USERNAME}/local-deep-research:prerelease" \
"${DOCKER_USERNAME}/local-deep-research:${TAG}"
echo "Floating :prerelease tag updated"
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index bdba2eebbd..6157bc471e 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -22,6 +22,7 @@ jobs:
file_hashes: ${{ steps.verify.outputs.file_hashes }}
artifact_attempt: ${{ steps.source.outputs.artifact_attempt }}
artifact_id: ${{ steps.publisher-upload.outputs.artifact-id }}
+ release_deadline: ${{ steps.security-decision.outputs.release_deadline }}
steps:
- name: Harden runner
uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1
@@ -37,6 +38,16 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
run: python3 .github/scripts/release_package.py source
+ - name: Verify original release security decision
+ id: security-decision
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RELEASE_SHA: ${{ github.event.client_payload.sha }}
+ RELEASE_DECISION_ARTIFACT_ID: ${{ github.event.client_payload.release_decision_artifact_id }}
+ run: |
+ python3 .github/scripts/release_security_decision.py verify \
+ --repository "$GITHUB_REPOSITORY" --sha "$RELEASE_SHA" \
+ --artifact-id "$RELEASE_DECISION_ARTIFACT_ID"
- name: Download tested release artifact by ID
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
@@ -125,6 +136,23 @@ jobs:
assert actual == expected[path.name], f"distribution digest changed: {path.name}"
print("Publishing the exact distributions tested by the release gate")
PYCODE
+ # Environment approval and partial reruns cannot renew this deadline.
+ - name: Check release exception deadline before publishing
+ env:
+ RELEASE_DEADLINE: ${{ needs.build-package.outputs.release_deadline }}
+ run: |
+ python3 - <<'PYCODE'
+ from datetime import date, datetime, timezone
+ import os
+ value = os.environ["RELEASE_DEADLINE"]
+ if value != "none":
+ expiry = date.fromisoformat(value)
+ if expiry.isoformat() != value:
+ raise SystemExit("Invalid release deadline")
+ if datetime.now(timezone.utc).date() >= expiry:
+ raise SystemExit("Release exception expired; publication is blocked")
+ print("Original release deadline remains valid")
+ PYCODE
- name: Publish to Test PyPI
if: github.event.client_payload.prerelease == true
uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2
diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml
index a998aa58ec..cbbc662a91 100644
--- a/.github/workflows/release-gate.yml
+++ b/.github/workflows/release-gate.yml
@@ -4,6 +4,12 @@ name: Release Gate
#
# Security model:
# - All security scans must pass before any release artifacts are published
+# - Open security alerts block release unless an exact, unexpired exception
+# is reviewed in .github/release-security-exceptions.json. Alerts stay open.
+# Only the two alert checks in check-code-scanning-alerts read that policy:
+# scanner jobs that fail on their own findings (OSV-Scanner, npm audit,
+# Retire.js, Gitleaks) still block and keep their own suppressions.
+# See .github/SECURITY_ALERTS.md#temporary-release-exceptions.
# - Docker and PyPI publish workflows are triggered ONLY via repository_dispatch
# from release.yml, which depends on this gate passing
# - Direct release creation via GitHub UI will NOT trigger publishing
@@ -22,6 +28,9 @@ name: Release Gate
on:
workflow_call: # Called by release.yml
outputs:
+ release_deadline:
+ description: "Earliest applied exception expiry (exclusive UTC date), or none"
+ value: ${{ jobs.check-code-scanning-alerts.outputs.release_deadline }}
package_artifact_id:
description: Immutable artifact containing the tested wheel and sdist
value: ${{ jobs.pip-install-check.outputs.artifact_id }}
@@ -762,13 +771,16 @@ jobs:
# ============================================
# Check for open code scanning alerts
# This runs after all SARIF uploads complete and fails if
- # critical/high/medium severity alerts exist from ANY tool, or if a
- # native SARIF alert has no numerical security score but reports an
- # unscored error/warning level
+ # critical/high/medium or unscored warning/error alerts block release.
+ # Fresh scan evidence is required, and reviewed exceptions must satisfy
+ # the checked-in policy and its original release deadline.
# ============================================
check-code-scanning-alerts:
name: Check Code Scanning Alerts
runs-on: ubuntu-latest
+ outputs:
+ excepted_count: ${{ steps.alert-check.outputs.excepted_count }}
+ release_deadline: ${{ steps.alert-check.outputs.release_deadline }}
needs:
# Wait for all SARIF-uploading scans to complete
- codeql-scan
@@ -802,15 +814,28 @@ jobs:
with:
egress-policy: audit
- - name: Checkout release policy
+ - name: Checkout release policies and checkers
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Validate fresh analyses and open alerts
+ id: scan-evidence
env:
GH_TOKEN: ${{ github.token }}
- run: python3 .github/scripts/check_release_scan_evidence.py
+ run: >-
+ python3 .github/scripts/check_release_scan_evidence.py
+ --exceptions .github/release-security-exceptions.json
+
+ - name: Check open alerts and reviewed exceptions
+ id: alert-check
+ env:
+ GH_TOKEN: ${{ github.token }}
+ EVIDENCE_DEADLINE: ${{ steps.scan-evidence.outputs.release_deadline }}
+ run: |
+ python3 .github/scripts/check_code_scanning_alerts.py \
+ --repository "$GITHUB_REPOSITORY" \
+ --evidence-deadline "$EVIDENCE_DEADLINE"
# ============================================
# Summary job that reports overall status
@@ -862,7 +887,7 @@ jobs:
# CPU baseline smoke — catches dependency wheels that raise the
# x86 instruction-set baseline and SIGILL on older CPUs (#4480)
- cpu-baseline-smoke
- # Alert check (fails if any critical/high/medium alerts exist)
+ # Alert check (fails on critical/high/medium alerts without an active exception)
- check-code-scanning-alerts
if: always()
permissions:
@@ -897,6 +922,8 @@ jobs:
if: always()
env:
GATE_RESULTS: ${{ toJSON(needs) }}
+ EXCEPTED_ALERT_COUNT: ${{ needs.check-code-scanning-alerts.outputs.excepted_count || '0' }}
+ RELEASE_DEADLINE: ${{ needs.check-code-scanning-alerts.outputs.release_deadline }}
run: |
# Redirect all output to GITHUB_STEP_SUMMARY (fixes SC2129)
exec >> "$GITHUB_STEP_SUMMARY"
@@ -962,8 +989,8 @@ jobs:
if [ -z "$FAILED" ]; then
echo "# :white_check_mark: RELEASE GATE: PASSED"
echo ""
- echo "> **All $TOTAL security scans passed successfully.**"
- echo "> This release is approved from a security perspective."
+ echo "> **All $TOTAL required security checks passed.**"
+ echo "> Review any temporary alert exceptions listed below before publishing."
else
echo "# :x: RELEASE GATE: FAILED"
echo ""
@@ -1237,9 +1264,15 @@ jobs:
echo "### Code Scanning Alerts"
if [ "${{ needs.check-code-scanning-alerts.result }}" = "success" ]; then
- echo "✅ **Alert Check**: No critical/high/medium alerts"
+ if [ "$RELEASE_DEADLINE" != "none" ]; then
+ echo "⚠️ **Alert Check**: Passed with temporary release exception(s). Applied exceptions retain their original deadline."
+ echo " > Publication deadline: $RELEASE_DEADLINE (exclusive UTC); $EXCEPTED_ALERT_COUNT exception(s) matched the final alert query."
+ echo " > See the Check Code Scanning Alerts job summary for alert links, rationale, and expiry dates."
+ else
+ echo "✅ **Alert Check**: No critical/high/medium alerts"
+ fi
else
- echo "❌ **Alert Check**: ${{ needs.check-code-scanning-alerts.result }} - Open alerts found!"
+ echo "❌ **Alert Check**: ${{ needs.check-code-scanning-alerts.result }} - Blocking alerts or an alert-check error."
FAILED="true"
fi
@@ -1269,5 +1302,5 @@ jobs:
echo "| **Gate** | :white_check_mark: **APPROVED** |"
echo "| **Passed** | $PASS_COUNT / $TOTAL |"
echo ""
- echo "_All security scans passed. E2E tests run as separate gate in release pipeline._"
+ echo "_All required security checks passed, subject to any temporary alert exceptions listed above. E2E tests run as a separate gate._"
fi
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 9ad9b25f5d..2267156975 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -269,6 +269,8 @@ jobs:
short_sha: ${{ steps.version.outputs.short_sha }}
release_exists: ${{ steps.check_release.outputs.exists }}
hashes: ${{ steps.hash.outputs.hashes }}
+ release_deadline: ${{ needs.release-gate.outputs.release_deadline }}
+ release_decision_artifact_id: ${{ steps.security-decision.outputs.artifact-id }}
permissions:
contents: read
pull-requests: read
@@ -592,6 +594,29 @@ jobs:
# a retention input, align both values.
retention-days: 7
+ - name: Record release security decision
+ if: steps.check_release.outputs.exists == 'false'
+ env:
+ RELEASE_DEADLINE: ${{ needs.release-gate.outputs.release_deadline }}
+ run: |
+ python3 .github/scripts/release_security_decision.py record \
+ --repository "$GITHUB_REPOSITORY" --sha "$GITHUB_SHA" \
+ --run-id "$GITHUB_RUN_ID" --run-attempt "$GITHUB_RUN_ATTEMPT" \
+ --deadline "$RELEASE_DEADLINE" \
+ --output "$RUNNER_TEMP/release-security-decision.json"
+
+ - name: Upload immutable release security decision
+ if: steps.check_release.outputs.exists == 'false'
+ id: security-decision
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: release-security-decision-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/release-security-decision.json
+ archive: true
+ if-no-files-found: error
+ overwrite: false
+ retention-days: 30
+
# Generate SLSA provenance for release artifacts
provenance:
needs: [build]
@@ -632,6 +657,7 @@ jobs:
with:
version: ${{ needs.build.outputs.version }}
short_sha: ${{ needs.build.outputs.short_sha }}
+ release_deadline: ${{ needs.build.outputs.release_deadline }}
secrets:
# Explicit list (not `secrets: inherit`) — defense-in-depth so a
# future edit to prerelease-docker.yml that references an unrelated
@@ -667,6 +693,7 @@ jobs:
tag: ${{ needs.build.outputs.tag }}
source_tag: prerelease-v${{ needs.build.outputs.version }}-${{ needs.build.outputs.short_sha }}
expected_digest: ${{ needs.prerelease-docker.outputs.manifest_digest }}
+ release_deadline: ${{ needs.build.outputs.release_deadline }}
secrets:
# Explicit secret pass — env-scoped (`release`) DOCKER_USERNAME and
# DOCKER_PASSWORD become available to the callee's `promote` job
@@ -715,6 +742,7 @@ jobs:
docs/release_notes/
changelog.d/
pyproject.toml
+ .github/scripts/check_release_deadline.py
.github/scripts/shorten_release_notes.py
sparse-checkout-cone-mode: false
fetch-depth: 1
@@ -1347,6 +1375,9 @@ jobs:
# v1.9.0 that would have tagged a commit 4 PRs past the one the
# gates ran against). Ignored when the tag already exists (e.g.
# tag-push-triggered runs), so it is safe in every trigger mode.
+ # Approval, artifact preparation, and release-note generation can
+ # outlive an exception. Recheck immediately before publishing.
+ python3 .github/scripts/check_release_deadline.py --deadline "$RELEASE_DEADLINE"
gh release create "$RELEASE_TAG" \
--target "$GITHUB_SHA" \
--repo "$GITHUB_REPOSITORY" \
@@ -1371,6 +1402,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.PAT_TOKEN }}
RELEASE_TAG: ${{ needs.build.outputs.tag }}
RELEASE_VERSION: ${{ needs.build.outputs.version }}
+ RELEASE_DEADLINE: ${{ needs.build.outputs.release_deadline }}
# Optional AI summarization. If OPENROUTER_API_KEY is not configured
# in the release environment, the step skips the AI section silently.
OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}
@@ -1599,6 +1631,7 @@ jobs:
env:
RELEASE_TAG: ${{ needs.build.outputs.tag }}
RELEASE_SHA: ${{ github.sha }}
+ RELEASE_DECISION_ARTIFACT_ID: ${{ needs.build.outputs.release_decision_artifact_id }}
PACKAGE_ARTIFACT_ID: ${{ needs.release-gate.outputs.package_artifact_id }}
PACKAGE_MANIFEST_SHA256: ${{ needs.release-gate.outputs.package_manifest_sha256 }}
with:
@@ -1633,6 +1666,7 @@ jobs:
client_payload: {
tag: process.env.RELEASE_TAG,
sha: process.env.RELEASE_SHA,
+ release_decision_artifact_id: process.env.RELEASE_DECISION_ARTIFACT_ID,
run_id: String(context.runId),
artifact_id: process.env.PACKAGE_ARTIFACT_ID,
dispatch_id: dispatchId,
@@ -1781,6 +1815,7 @@ jobs:
env:
RELEASE_TAG: ${{ needs.build.outputs.tag }}
PYPI_RESULT: ${{ steps.wait.outputs.pypi_result }}
+ RELEASE_DECISION_ARTIFACT_ID: ${{ needs.build.outputs.release_decision_artifact_id }}
with:
script: |
const { owner, repo } = context.repo;
@@ -1791,7 +1826,8 @@ jobs:
const action = '**Suggested action:** Inspect the matching publish.yml run in the [Actions tab](https://github.com/' + owner + '/' + repo + '/actions).'
+ ' Re-run failed publisher jobs to preserve the original tested artifact and dispatch payload.'
+ ' If no publisher run exists, re-run the failed release jobs to dispatch it.'
- + ' Expired artifacts require a fresh release gate run; do not rebuild in the publisher.'
+ + ' Expired artifacts or security decisions require a fresh release gate run; do not rebuild in the publisher.'
+ + ' After PyPI succeeds, re-run monitor-pypi and its dependent jobs in the original release run so create-release sees a successful monitor.'
+ ' A dispatch is rejected once a later release attempt rebuilt the package; publish the dispatch from that newer attempt instead.'
+ ' See docs/RELEASE_GUIDE.md "Recovery from PyPI failure".';
diff --git a/.gitignore b/.gitignore
index c896cb9c47..ac11875a55 100644
--- a/.gitignore
+++ b/.gitignore
@@ -107,6 +107,7 @@ src/local_deep_research/web/static/css/themes.css
!.github/**/*.yml
!.github/**/*.yaml
!.github/ai-review-label-policy.json
+!.github/release-security-exceptions.json
!.github/**/*.md
!.github/**/*.sh
!.github/**/*.py
diff --git a/changelog.d/6837.security.md b/changelog.d/6837.security.md
index e0e4a863ee..0ab3d64eda 100644
--- a/changelog.d/6837.security.md
+++ b/changelog.d/6837.security.md
@@ -1 +1 @@
-RIS export no longer writes the credentials or port of a source URL into the publisher (`PB`) field: `https://user:[email protected]/…` now exports `PB - arXiv` rather than `PB - user:[email protected]`, and `example.com:8080` exports `PB - example.com`.
+RIS export no longer writes the credentials or port of a source URL into the publisher (`PB`) field: `https://user:[email protected]/…` now exports `PB - arXiv` rather than `PB - user:[email protected]`, and `example.com:8080` exports `PB - example.com`. <!-- email-domains: allow — illustrative source URL userinfo, not a contact address -->
diff --git a/docs/RELEASE_GUIDE.md b/docs/RELEASE_GUIDE.md
index 06c6ffee53..e458536177 100644
--- a/docs/RELEASE_GUIDE.md
+++ b/docs/RELEASE_GUIDE.md
@@ -169,6 +169,42 @@ Start new release attempts from a revision containing this change. If an old
attempt partially published, use the recovery guidance below before starting
another publisher for that version.
+### When an upstream security finding blocks a release
+
+First find which job blocks. The release exception policy is read only by the
+two alert checks in the release gate's `Check Code Scanning Alerts` job. For a
+finding that only those checks block, **the preferred temporary approach while
+awaiting an upstream fix is a narrowly scoped, expiring release exception
+approved through a PR.** Reviewers must accept the documented risk for the
+exact finding; without that decision, release stays blocked. This is temporary
+risk acceptance, and the upstream fix remains required.
+
+1. Add the exact alert, scanner, category, path, severity, rationale, tracking
+ link, and expiry to
+ [the release exception policy](../.github/release-security-exceptions.json).
+2. Review and merge the policy PR before starting a release with that exception.
+ Keep scanners, alert visibility, and release approvals in place. The gate
+ records the decision, and publication rechecks its original expiry.
+3. Track the upstream fix, confirm it resolves the finding, deploy it, rebuild
+ and scan, then remove the exception. If waiting becomes unacceptable, assess
+ another remediation; any extension needs another reviewed policy change.
+
+For such a finding, use this policy for the waiting period instead of
+dismissing the valid alert, suppressing the finding in the scanner's
+configuration, bypassing the gate, or carrying a local dependency backport
+solely to unblock publication.
+
+An exception cannot unblock a scanner job that fails on its own findings. In
+the gate, `Release Gate Summary` requires every job to succeed, which covers
+OSV-Scanner, npm audit, Retire.js, and Gitleaks. During Docker publication, the
+Trivy scans fail on fixable critical or high image findings and do not read the
+policy. Each of these keeps its own reviewed suppression, such as an
+`[[IgnoredVulns]]` entry with `ignoreUntil` in `osv-scanner.toml` or an `exp:`
+date in `.trivyignore`. See
+[Temporary release exceptions](../.github/SECURITY_ALERTS.md#temporary-release-exceptions)
+for each scanner's suppression and expiry, the matching rules, and the current
+assessment.
+
### Recovery from PyPI failure (atomicity hole)
The one orphan state the pipeline cannot fully clean up: `publish-docker`
@@ -197,11 +233,21 @@ succeeded, PyPI failed. At this point Docker `:1.6.9` / `:1.6` /
one. Reruns that leave `pip Install Verification` as a carried-over
success, such as "Re-run failed jobs" after a later job failed, keep
the original build, so its original artifact can still be published.
-3. Once PyPI publishes successfully, manually create the GitHub Release
- from the existing tag (the SBOM/sig/provenance artifacts are still
- uploaded as workflow artifacts on the failed `release.yml` run; you
- can download them and attach manually, or re-run `create-release`
- manually if the run is still re-runnable in the Actions UI).
+ The original security decision and its recorded deadline are verified too.
+ Rerunning publisher jobs preserves that decision; an expired or unavailable
+ decision requires a new release run after remediation or a separately reviewed
+ exception update. Recovery cannot override the original deadline.
+3. Once PyPI publishes successfully, re-run **`monitor-pypi` and its dependent
+ jobs** in the original release run while the original deadline is valid.
+ The monitor must succeed before `create-release` can run; retrying only
+ `create-release` leaves its failed prerequisite unchanged. In the Actions UI,
+ select the failed monitor job and use "Re-run jobs". With the CLI, use
+ `gh run rerun <release-run-id> --job <monitor-job-database-id>` (obtain that
+ database ID with `gh run view <release-run-id> --json jobs`). This reruns the
+ monitor and its dependents, including `create-release`, which checks expiry
+ again immediately before publication. Do not bypass an expired exception
+ with manual publication. Already published Docker or PyPI artifacts are not
+ automatically rolled back when an exception expires.
> Earlier iterations of this refactor described a single approval gate
> with a pre-approval testing window. That design required
@@ -396,6 +442,10 @@ Useful while iterating on a fragment locally.
- [ ] Version updated in `__version__.py` (or auto-bump PR merged)
- [ ] Code owner approval received
- [ ] CI tests passing
+- [ ] Blocking security findings fixed, or covered while awaiting upstream fixes
+ by a reviewed, expiring release exception (alert-only findings) or by the
+ failing scanner's own reviewed suppression (see
+ [the policy](../.github/SECURITY_ALERTS.md#temporary-release-exceptions))
- [ ] Merge to main completed
- [ ] Release automatically created
- [ ] PyPI/Docker publishing approved
diff --git a/tests/ci/standalone/test_release_scan_evidence.py b/tests/ci/standalone/test_release_scan_evidence.py
index 4bb2f05b5c..98310c5074 100644
--- a/tests/ci/standalone/test_release_scan_evidence.py
+++ b/tests/ci/standalone/test_release_scan_evidence.py
@@ -9,11 +9,14 @@ import os
import re
import shutil
import subprocess
+import sys
import tempfile
import unittest
from contextlib import redirect_stdout
+from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import patch
+from urllib.parse import urlencode
ROOT = Path(__file__).resolve().parents[3]
SPEC = importlib.util.spec_from_file_location(
@@ -536,6 +539,37 @@ class EvidenceTests(unittest.TestCase):
self.assertIn("[REDACTED]", output)
self.assertNotIn("z" * 600, output)
+ def test_main_escapes_untrusted_text_in_the_failure_annotation(self):
+ """A tool name or gh stderr must stay inside the one ::error:: line.
+
+ Unescaped, a newline in either starts a forged workflow command.
+ """
+ tool = {"name": "Grype\n::add-mask::deadbeef 100%"}
+ with self.assertRaises(ValueError) as caught:
+ POLICY.blocking_alert(alert(state="fixed", tool=tool))
+ api_error = subprocess.CalledProcessError(
+ 1, ["gh", "api", "x"], output="", stderr="403\r\n::warning::x"
+ )
+ for exc, escaped in (
+ (caught.exception, "(Grype%0A::add-mask::deadbeef 100%25)"),
+ (api_error, "gh stderr: 403%0D%0A::warning::x"),
+ ):
+ with self.subTest(exc=type(exc).__name__):
+ buffer = io.StringIO()
+ with (
+ patch.object(POLICY, "evaluate", side_effect=exc),
+ redirect_stdout(buffer),
+ ):
+ self.assertEqual(POLICY.main(), 1)
+ lines = buffer.getvalue().splitlines()
+ self.assertEqual(len(lines), 1, lines)
+ self.assertTrue(
+ lines[0].startswith(
+ "::error::Release scan evidence failed:"
+ )
+ )
+ self.assertIn(escaped, lines[0])
+
def test_evaluate_rejects_a_run_for_a_different_commit(self):
"""R1: head_sha != GITHUB_SHA must be rejected."""
@@ -706,6 +740,274 @@ class EvidenceTests(unittest.TestCase):
],
)
+ @staticmethod
+ def _reviewed_alert_and_entry():
+ finding = alert(
+ rule={
+ "id": "fixture-rule",
+ "security_severity_level": "medium",
+ "severity": "warning",
+ },
+ most_recent_instance={
+ "category": "fixture-category",
+ "location": {"path": "fixture.py"},
+ },
+ )
+ entry = {
+ "alert_number": 1,
+ "rule_id": "fixture-rule",
+ "tool": "CodeQL",
+ "category": "fixture-category",
+ "path": "fixture.py",
+ "severity": "medium",
+ "expires_on": (
+ datetime.now(timezone.utc).date() + timedelta(days=7)
+ ).isoformat(),
+ "reason": "Synthetic reviewed fixture",
+ "tracking_url": "https://github.com/owner/repo/issues/1",
+ }
+ return finding, entry
+
+ def _evaluate_reviewed(
+ self, alerts, entries, *, fresh=True, repository="owner/repo", ref=REF
+ ):
+ expected = json.loads(
+ (ROOT / ".github/release-scan-policy.json").read_text()
+ )
+ complete = [
+ analysis(
+ category=category, analysis_key=f"{WORKFLOW}:{job}", ref=ref
+ )
+ for category, job in expected.items()
+ ]
+ self.reviewed_api_calls = []
+
+ def fetch(endpoint):
+ self.reviewed_api_calls.append(endpoint)
+ if "/actions/runs/" in endpoint:
+ return {"head_sha": SHA, "created_at": START, "path": WORKFLOW}
+ if "/analyses?" in endpoint:
+ return complete if fresh else []
+ self.assertIn(urlencode({"ref": ref}), endpoint)
+ return alerts
+
+ with (
+ tempfile.TemporaryDirectory() as directory,
+ patch.dict(
+ os.environ,
+ {
+ **self._run_env(directory),
+ "GITHUB_REF": ref,
+ "GITHUB_OUTPUT": str(Path(directory) / "output"),
+ },
+ ),
+ ):
+ path = Path(directory) / "exceptions.json"
+ path.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "repository": repository,
+ "exceptions": entries,
+ }
+ )
+ )
+ ticks = iter([0, 301])
+ POLICY.evaluate(
+ fetch,
+ lambda _: self.fail("unexpected polling"),
+ lambda: next(ticks),
+ exception_policy=path,
+ )
+ self.reviewed_output = Path(os.environ["GITHUB_OUTPUT"]).read_text()
+ return Path(os.environ["GITHUB_STEP_SUMMARY"]).read_text()
+
+ def test_reviewed_exception_remains_open_after_fresh_evidence(self):
+ finding, entry = self._reviewed_alert_and_entry()
+ before = json.loads(json.dumps(finding))
+ summary = self._evaluate_reviewed([finding], [entry])
+ self.assertIn("Open blocking alerts: **0**", summary)
+ self.assertIn("Reviewed, unexpired exceptions: **1**", summary)
+ self.assertEqual(finding, before)
+ self.assertEqual(finding["state"], "open")
+ self.assertEqual(
+ self.reviewed_output, f"release_deadline={entry['expires_on']}\n"
+ )
+
+ def test_later_alert_query_cannot_discard_an_applied_deadline(self):
+ finding, entry = self._reviewed_alert_and_entry()
+ checker = POLICY._exception_checker()
+ deadline_spec = importlib.util.spec_from_file_location(
+ "deadline", ROOT / ".github/scripts/check_release_deadline.py"
+ )
+ deadline = importlib.util.module_from_spec(deadline_spec)
+ deadline_spec.loader.exec_module(deadline)
+ for case, ref, later_alerts in (
+ ("same alert", REF, [finding]),
+ ("different ref", REF, []),
+ ("resolved between checks", "refs/heads/main", []),
+ ):
+ with self.subTest(case=case):
+ self._evaluate_reviewed([finding], [entry], ref=ref)
+ carried = self.reviewed_output.strip().split("=", 1)[1]
+ responses = iter([later_alerts, []] if later_alerts else [[]])
+
+ def run(args, **kwargs):
+ self.assertEqual(args[:4], ["gh", "api", "--method", "GET"])
+ self.assertNotIn("ref=", args[-1])
+ return subprocess.CompletedProcess(
+ args, 0, stdout=json.dumps(next(responses))
+ )
+
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "exceptions.json"
+ path.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "repository": "owner/repo",
+ "exceptions": [entry],
+ }
+ )
+ )
+ output = Path(directory) / "output"
+ with (
+ patch.dict(
+ os.environ,
+ {
+ **self._run_env(directory),
+ "GITHUB_OUTPUT": str(output),
+ },
+ ),
+ patch.object(
+ checker.subprocess, "run", side_effect=run
+ ),
+ patch.object(
+ sys,
+ "argv",
+ [
+ "checker",
+ "--repository",
+ "owner/repo",
+ "--exceptions",
+ str(path),
+ "--evidence-deadline",
+ carried,
+ ],
+ ),
+ ):
+ self.assertEqual(checker.main(), 0)
+ outputs = dict(
+ line.split("=", 1)
+ for line in output.read_text().splitlines()
+ )
+ self.assertEqual(
+ outputs["release_deadline"], entry["expires_on"]
+ )
+ self.assertEqual(
+ outputs["excepted_count"], str(len(later_alerts))
+ )
+ with self.assertRaisesRegex(ValueError, "expired"):
+ deadline.check_deadline(
+ outputs["release_deadline"],
+ datetime.fromisoformat(entry["expires_on"]).replace(
+ tzinfo=timezone.utc
+ ),
+ )
+
+ def test_fresh_evidence_without_applied_exceptions_emits_explicit_none(
+ self,
+ ):
+ self._evaluate_reviewed([], [])
+ self.assertEqual(self.reviewed_output, "release_deadline=none\n")
+
+ def test_empty_policy_keeps_scored_and_unscored_alerts_blocking(self):
+ finding, _ = self._reviewed_alert_and_entry()
+ native = {
+ **finding,
+ "number": 2,
+ "rule": {
+ "id": "native-rule",
+ "security_severity_level": None,
+ "severity": "warning",
+ },
+ }
+ for current in (finding, native):
+ with (
+ self.subTest(rule=current["rule"]),
+ self.assertRaisesRegex(
+ ValueError, "blocking code-scanning alerts"
+ ),
+ ):
+ self._evaluate_reviewed([current], [])
+
+ def test_expired_reviewed_exception_blocks_again(self):
+ finding, entry = self._reviewed_alert_and_entry()
+ entry["expires_on"] = "2000-01-01"
+ with self.assertRaisesRegex(
+ ValueError, "blocking code-scanning alerts"
+ ):
+ self._evaluate_reviewed([finding], [entry])
+
+ def test_reviewed_exception_requires_every_identity_field(self):
+ finding, entry = self._reviewed_alert_and_entry()
+ for field, replacement in (
+ ("alert_number", 2),
+ ("rule_id", "other-rule"),
+ ("tool", "OtherTool"),
+ ("category", "other-category"),
+ ("path", "other.py"),
+ ("severity", "high"),
+ ):
+ with (
+ self.subTest(field=field),
+ self.assertRaisesRegex(
+ ValueError, "blocking code-scanning alerts"
+ ),
+ ):
+ self._evaluate_reviewed(
+ [finding], [{**entry, field: replacement}]
+ )
+
+ def test_reviewed_exception_does_not_cover_unrelated_or_native_alerts(self):
+ finding, entry = self._reviewed_alert_and_entry()
+ for other in (
+ {**finding, "number": 2},
+ {
+ **finding,
+ "number": 2,
+ "rule": {
+ "id": "native-rule",
+ "security_severity_level": None,
+ "severity": "error",
+ },
+ },
+ ):
+ with (
+ self.subTest(rule=other["rule"]),
+ self.assertRaisesRegex(
+ ValueError, "1 blocking code-scanning alert"
+ ),
+ ):
+ self._evaluate_reviewed([finding, other], [entry])
+
+ def test_reviewed_exception_cannot_replace_fresh_analyses(self):
+ finding, entry = self._reviewed_alert_and_entry()
+ with self.assertRaisesRegex(ValueError, "No fresh successful analysis"):
+ self._evaluate_reviewed([finding], [entry], fresh=False)
+ self.assertFalse(
+ any("/alerts?" in endpoint for endpoint in self.reviewed_api_calls)
+ )
+
+ def test_reviewed_policy_repository_and_schema_fail_before_api_calls(self):
+ finding, entry = self._reviewed_alert_and_entry()
+ with self.assertRaisesRegex(ValueError, "repository mismatch"):
+ self._evaluate_reviewed([finding], [entry], repository="other/repo")
+ self.assertEqual(self.reviewed_api_calls, [])
+ with self.assertRaisesRegex(ValueError, "missing or unknown fields"):
+ self._evaluate_reviewed([finding], [{**entry, "unexpected": True}])
+ self.assertEqual(self.reviewed_api_calls, [])
+
def _step_run_script(workflow_text, step_id):
"""The `run: |` block of the step with `id: <step_id>`, dedented.
diff --git a/tests/ci/test_release_deadline.py b/tests/ci/test_release_deadline.py
new file mode 100644
index 0000000000..618826f8b8
--- /dev/null
+++ b/tests/ci/test_release_deadline.py
@@ -0,0 +1,394 @@
+"""An approval delay or publish-job rerun cannot renew a release exception."""
+
+# allow: no-sut-import — the SUT is the standalone publication deadline guard.
+
+from datetime import datetime, timedelta, timezone
+import importlib.util
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+import yaml
+
+
+ROOT = Path(__file__).resolve().parents[2]
+SCRIPT = ROOT / ".github/scripts/check_release_deadline.py"
+spec = importlib.util.spec_from_file_location("release_deadline", SCRIPT)
+deadline = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(deadline)
+GUARD = 'python3 .github/scripts/check_release_deadline.py --deadline "$RELEASE_DEADLINE"'
+BUILD_DEADLINE = "${{ needs.build.outputs.release_deadline }}"
+INPUT_DEADLINE = "${{ inputs.release_deadline }}"
+DECISION_ARTIFACT = "${{ needs.build.outputs.release_decision_artifact_id }}"
+VERIFIED_DEADLINE = "${{ steps.security-decision.outputs.release_deadline }}"
+
+
+def workflow(name):
+ return yaml.safe_load((ROOT / f".github/workflows/{name}.yml").read_text())
+
+
+def step_named(job, name):
+ return next(step for step in job["steps"] if step.get("name") == name)
+
+
+ "instant,allowed",
+ [
+ ("2026-10-12T23:59:59+00:00", True),
+ ("2026-10-13T00:00:00+00:00", False),
+ ("2026-10-14T12:00:00+00:00", False),
+ ("2026-10-12T20:00:00-04:00", False),
+ ("2026-10-13T01:59:59+02:00", True),
+ ],
+)
+def test_approval_and_rerun_time_is_checked_in_utc(instant, allowed):
+ now = datetime.fromisoformat(instant)
+ if allowed:
+ deadline.check_deadline("2026-10-13", now)
+ else:
+ with pytest.raises(ValueError, match="expired"):
+ deadline.check_deadline("2026-10-13", now)
+
+
+ "value",
+ [
+ "",
+ "null",
+ "None",
+ "0",
+ "20261013",
+ "2026-10-13T00:00:00Z",
+ "*",
+ "none\n",
+ ],
+)
+def test_missing_or_malformed_transport_never_means_unlimited(value):
+ with pytest.raises(ValueError):
+ deadline.check_deadline(
+ value, datetime(2026, 9, 27, tzinfo=timezone.utc)
+ )
+
+
+def test_explicit_no_exception_result_does_not_expire():
+ deadline.check_deadline("none", datetime(2099, 1, 1, tzinfo=timezone.utc))
+
+
+def test_cli_uses_current_utc_time_after_approval(monkeypatch, capsys):
+ class FrozenDateTime(datetime):
+ @classmethod
+ def now(cls, tz=None):
+ assert tz == timezone.utc
+ return datetime(2026, 10, 13, tzinfo=tz)
+
+ monkeypatch.setattr(deadline, "datetime", FrozenDateTime)
+ monkeypatch.setattr(sys, "argv", [str(SCRIPT), "--deadline", "2026-10-13"])
+ assert deadline.main() == 1
+ assert "::error::Release exception expired" in capsys.readouterr().out
+
+
+def test_original_deadline_reaches_every_publication_path():
+ gate = workflow("release-gate")
+ # PyYAML reads the unquoted GitHub Actions 'on' key as YAML 1.1 True.
+ exported = gate[True]["workflow_call"]["outputs"]["release_deadline"]
+ assert exported["value"] == (
+ "${{ jobs.check-code-scanning-alerts.outputs.release_deadline }}"
+ )
+ assert (
+ gate["jobs"]["check-code-scanning-alerts"]["outputs"][
+ "release_deadline"
+ ]
+ == "${{ steps.alert-check.outputs.release_deadline }}"
+ )
+
+ jobs = workflow("release")["jobs"]
+ assert jobs["build"]["outputs"]["release_deadline"] == (
+ "${{ needs.release-gate.outputs.release_deadline }}"
+ )
+ for caller in ("prerelease-docker", "publish-docker"):
+ assert jobs[caller]["with"]["release_deadline"] == BUILD_DEADLINE
+ called_name = jobs[caller]["uses"].split("/")[-1].removesuffix(".yml")
+ contract = workflow(called_name)[True]["workflow_call"]["inputs"][
+ "release_deadline"
+ ]
+ assert contract["required"] is True
+ assert "default" not in contract
+
+ dispatch = step_named(jobs["trigger-pypi"], "Trigger PyPI publish workflow")
+ assert dispatch["env"]["RELEASE_DECISION_ARTIFACT_ID"] == DECISION_ARTIFACT
+ assert (
+ "release_decision_artifact_id: process.env.RELEASE_DECISION_ARTIFACT_ID"
+ in dispatch["with"]["script"]
+ )
+ recovery = step_named(
+ jobs["monitor-pypi"], "Create issue on PyPI publish failure"
+ )
+ assert recovery["env"]["RELEASE_DECISION_ARTIFACT_ID"] == DECISION_ARTIFACT
+ recovery_script = recovery["with"]["script"]
+ assert "Re-run failed publisher jobs" in recovery_script
+ assert "preserve the original tested artifact and dispatch payload" in (
+ recovery_script
+ )
+ assert "Expired artifacts or security decisions" in recovery_script
+ assert "re-run monitor-pypi and its dependent jobs" in recovery_script
+ assert "client_payload[" not in recovery_script
+
+ build = jobs["build"]
+ assert build.get("name", "build") == "build"
+ assert "needs.release-gate.result == 'success'" in build["if"]
+ record = step_named(build, "Record release security decision")
+ assert (
+ record["env"]["RELEASE_DEADLINE"]
+ == "${{ needs.release-gate.outputs.release_deadline }}"
+ )
+ upload = step_named(build, "Upload immutable release security decision")
+ assert upload["with"]["overwrite"] is False
+ assert upload["with"]["if-no-files-found"] == "error"
+ assert (
+ upload["with"]["name"]
+ == "release-security-decision-${{ github.run_attempt }}"
+ )
+ assert (
+ build["outputs"]["release_decision_artifact_id"]
+ == "${{ steps.security-decision.outputs.artifact-id }}"
+ )
+
+
[email protected]("job_id", ["build-amd64", "build-arm64"])
+def test_prerelease_push_checks_deadline_after_approval(job_id):
+ job = workflow("prerelease-docker")["jobs"][job_id]
+ assert job["environment"] == "release"
+ steps = job["steps"]
+ build_index = next(
+ i for i, step in enumerate(steps) if step.get("id") == "build"
+ )
+ build = steps[build_index]
+ assert build["with"]["push"] is False
+ assert build["with"]["load"] is True
+ guard = next(s for s in steps if 'docker push "$IMAGE"' in s.get("run", ""))
+ assert steps.index(guard) > build_index
+ assert guard["run"].index(GUARD) < guard["run"].index(
+ 'docker push "$IMAGE"'
+ )
+ assert guard["env"]["RELEASE_DEADLINE"] == INPUT_DEADLINE
+ assert "if" not in guard and not guard.get("continue-on-error")
+
+
+def test_pypi_checks_after_its_own_approval_and_before_both_upload_targets():
+ jobs = workflow("publish")["jobs"]
+ verifier = jobs["build-package"]
+ verify = step_named(verifier, "Verify original release security decision")
+ assert "release_security_decision.py verify" in verify["run"]
+ assert (
+ verify["env"]["RELEASE_DECISION_ARTIFACT_ID"]
+ == "${{ github.event.client_payload.release_decision_artifact_id }}"
+ )
+ assert "if" not in verify and not verify.get("continue-on-error")
+ assert verifier["outputs"]["release_deadline"] == VERIFIED_DEADLINE
+
+ job = jobs["publish"]
+ assert job["environment"] == "release"
+ assert job["needs"] == "build-package"
+ assert job["permissions"] == {
+ "contents": "read",
+ "actions": "read",
+ "id-token": "write",
+ }
+ assert "github.event.client_payload.release_deadline" not in str(job)
+ steps = job["steps"]
+ # Main revalidates the package source after approval. Its narrowly scoped
+ # policy checkout must coexist with the original security-decision deadline.
+ checkouts = [
+ step
+ for step in steps
+ if step.get("uses", "").startswith("actions/checkout@")
+ ]
+ assert len(checkouts) == 1
+ checkout = checkouts[0]
+ assert checkout["with"]["persist-credentials"] is False
+ assert (
+ checkout["with"]["sparse-checkout"]
+ == ".github/scripts/release_package.py"
+ )
+ revalidate = step_named(job, "Revalidate source release run after approval")
+ assert steps.index(checkout) < steps.index(revalidate)
+ guard = step_named(
+ job, "Check release exception deadline before publishing"
+ )
+ assert (
+ guard["env"]["RELEASE_DEADLINE"]
+ == "${{ needs.build-package.outputs.release_deadline }}"
+ )
+ assert "if" not in guard and not guard.get("continue-on-error")
+ guard_index = steps.index(guard)
+ assert steps.index(revalidate) < guard_index
+ assert steps[guard_index + 1]["name"] == "Publish to Test PyPI"
+ assert steps[guard_index + 2]["name"] == "Publish to PyPI"
+
+
+ "value,allowed",
+ [
+ ("none", True),
+ ("tomorrow", True),
+ ("today", False),
+ ("yesterday", False),
+ ("", False),
+ ("null", False),
+ ("20261013", False),
+ ("none\n", False),
+ ],
+)
+def test_pypi_executes_its_guard_without_checkout(tmp_path, value, allowed):
+ today = datetime.now(timezone.utc).date()
+ relative = {
+ "tomorrow": today + timedelta(days=1),
+ "today": today,
+ "yesterday": today - timedelta(days=1),
+ }
+ if value in relative:
+ value = relative[value].isoformat()
+ guard = step_named(
+ workflow("publish")["jobs"]["publish"],
+ "Check release exception deadline before publishing",
+ )
+ result = subprocess.run(
+ ["bash", "-e", "-o", "pipefail", "-c", guard["run"]],
+ cwd=tmp_path,
+ env={**os.environ, "RELEASE_DEADLINE": value},
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ assert (result.returncode == 0) is allowed, result.stdout + result.stderr
+
+
+ "workflow_name,job_id,step_name,publish_command",
+ [
+ (
+ "docker-publish",
+ "promote",
+ "Promote (retag) prerelease manifest to release tags",
+ "docker buildx imagetools create",
+ ),
+ (
+ "prerelease-docker",
+ "create-manifest",
+ "Create and push multi-platform manifest",
+ "docker buildx imagetools create",
+ ),
+ (
+ "release",
+ "create-release",
+ "Create GitHub Release",
+ "gh release create",
+ ),
+ ],
+)
+def test_tag_publication_is_guarded_after_approval(
+ workflow_name, job_id, step_name, publish_command
+):
+ job = workflow(workflow_name)["jobs"][job_id]
+ assert job["environment"] == "release"
+ publish = step_named(job, step_name)
+ assert not publish.get("continue-on-error")
+ expected = BUILD_DEADLINE if workflow_name == "release" else INPUT_DEADLINE
+ assert publish["env"]["RELEASE_DEADLINE"] == expected
+ run = publish["run"]
+ assert run.index(GUARD) < run.index(publish_command)
+ assert run.count(GUARD) == run.count(publish_command)
+ checkout = next(
+ (
+ s
+ for s in job["steps"]
+ if s.get("uses", "").startswith("actions/checkout@")
+ ),
+ None,
+ )
+ assert checkout is not None, (
+ f"{workflow_name}/{job_id} must check out the deadline checker"
+ )
+ assert job["steps"].index(checkout) < job["steps"].index(publish)
+ assert checkout.get("with", {}).get("ref") in (None, "${{ github.sha }}"), (
+ f"{workflow_name}/{job_id} must check out the caller's commit"
+ )
+ if "sparse-checkout" in checkout.get("with", {}):
+ assert (
+ str(SCRIPT.relative_to(ROOT)) in checkout["with"]["sparse-checkout"]
+ )
+
+
[email protected]("expired", [False, True])
+def test_expired_approval_stops_actual_promotion_shell(tmp_path, expired):
+ """Execute the real promotion step; replace only Docker's remote effect."""
+ job = workflow("docker-publish")["jobs"]["promote"]
+ publish = step_named(
+ job, "Promote (retag) prerelease manifest to release tags"
+ )
+ docker = tmp_path / "docker"
+ docker.write_text('#!/bin/sh\ntouch "$PUBLISHED_MARKER"\n')
+ docker.chmod(0o755)
+ marker = tmp_path / "published"
+ day = datetime.now(timezone.utc).date() + timedelta(
+ days=-1 if expired else 1
+ )
+ result = subprocess.run(
+ ["bash", "-e", "-o", "pipefail", "-c", publish["run"]],
+ cwd=ROOT,
+ env={
+ **os.environ,
+ "PATH": f"{tmp_path}:{os.environ['PATH']}",
+ "PUBLISHED_MARKER": str(marker),
+ "RELEASE_DEADLINE": day.isoformat(),
+ "DOCKER_USERNAME": "test",
+ "SOURCE_TAG": "prerelease-v1.0.0-abcdef0",
+ "VERSION": "1.0.0",
+ "MAJOR_MINOR": "1.0",
+ },
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ assert (result.returncode == 0) is not expired, (
+ result.stdout + result.stderr
+ )
+ assert marker.exists() is not expired
+
+
[email protected]("arch", ["amd64", "arm64"])
[email protected]("expired", [False, True])
+def test_native_build_crossing_deadline_cannot_push(tmp_path, arch, expired):
+ today = datetime.now(timezone.utc).date()
+ expiry = today + timedelta(days=-1 if expired else 1)
+ # The pre-build check passed, then a long build/runner pause crossed expiry.
+ started = datetime.combine(
+ expiry - timedelta(days=1), datetime.min.time(), timezone.utc
+ )
+ deadline.check_deadline(expiry.isoformat(), started)
+ job = workflow("prerelease-docker")["jobs"][f"build-{arch}"]
+ push = step_named(job, f"Push {arch.upper()} image before the deadline")
+ docker = tmp_path / "docker"
+ docker.write_text('#!/bin/sh\ntouch "$PUBLISHED_MARKER"\n')
+ docker.chmod(0o755)
+ marker = tmp_path / "published"
+ result = subprocess.run(
+ ["bash", "-e", "-o", "pipefail", "-c", push["run"]],
+ cwd=ROOT,
+ env={
+ **os.environ,
+ "PATH": f"{tmp_path}:{os.environ['PATH']}",
+ "PUBLISHED_MARKER": str(marker),
+ "RELEASE_DEADLINE": expiry.isoformat(),
+ "IMAGE": f"test/local-deep-research:prerelease-v1.0.0-abcdef0-{arch}",
+ },
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ assert (result.returncode == 0) is not expired, (
+ result.stdout + result.stderr
+ )
+ assert marker.exists() is not expired
diff --git a/tests/ci/test_release_security_decision.py b/tests/ci/test_release_security_decision.py
new file mode 100644
index 0000000000..4cf241df8c
--- /dev/null
+++ b/tests/ci/test_release_security_decision.py
@@ -0,0 +1,420 @@
+"""Only an authentic release build may supply PyPI's security deadline."""
+
+# allow: no-sut-import — the SUT is the standalone release decision verifier.
+
+from argparse import Namespace
+from copy import deepcopy
+from datetime import datetime, timezone
+import hashlib
+import importlib.util
+import io
+import json
+from pathlib import Path
+import subprocess
+import sys
+from unittest.mock import patch
+import zipfile
+
+import pytest
+
+
+SCRIPTS = Path(__file__).resolve().parents[2] / ".github/scripts"
+spec = importlib.util.spec_from_file_location(
+ "security_decision", SCRIPTS / "release_security_decision.py"
+)
+decision = importlib.util.module_from_spec(spec)
+with patch.object(sys, "path", [str(SCRIPTS), *sys.path]):
+ spec.loader.exec_module(decision)
+
+REPOSITORY = "LearningCircuit/local-deep-research"
+SHA = "a" * 40
+ROOT = f"/repos/{REPOSITORY}"
+ARTIFACT = f"{ROOT}/actions/artifacts/500"
+ATTEMPT = f"{ROOT}/actions/runs/42/attempts/1"
+JOBS = f"{ATTEMPT}/jobs?per_page=100&page=1"
+
+
[email protected](autouse=True)
+def clock(monkeypatch):
+ class FrozenDateTime(datetime):
+ @classmethod
+ def now(cls, tz=None):
+ assert tz == timezone.utc
+ return cls(2026, 10, 12, 12, tzinfo=tz)
+
+ monkeypatch.setattr(decision, "datetime", FrozenDateTime)
+
+
+def record():
+ return {
+ "version": 1,
+ "repository": REPOSITORY,
+ "sha": SHA,
+ "run_id": 42,
+ "run_attempt": 1,
+ "release_deadline": "2026-10-13",
+ }
+
+
+def archive_bytes(record, filename=decision.RECORD_NAME):
+ stream = io.BytesIO()
+ with zipfile.ZipFile(stream, "w", zipfile.ZIP_DEFLATED) as zipped:
+ zipped.writestr(filename, json.dumps(record))
+ return stream.getvalue()
+
+
+def responses(record, monkeypatch):
+ blob = archive_bytes(record)
+ responses = {
+ ARTIFACT: {
+ "id": 500,
+ "name": "release-security-decision-1",
+ "expired": False,
+ "size_in_bytes": len(blob),
+ "digest": "sha256:" + hashlib.sha256(blob).hexdigest(),
+ "created_at": "2026-10-12T10:04:55Z",
+ "workflow_run": {"id": 42, "head_sha": SHA},
+ },
+ ATTEMPT: {
+ "id": 42,
+ "run_attempt": 1,
+ "path": ".github/workflows/release.yml",
+ "head_sha": SHA,
+ "event": "push",
+ "status": "in_progress",
+ "repository": {"full_name": REPOSITORY},
+ "head_repository": {"full_name": REPOSITORY},
+ },
+ f"{ROOT}/compare/{SHA}...heads/main": {"status": "identical"},
+ JOBS: {
+ "jobs": [
+ {
+ "name": "build",
+ "run_id": 42,
+ "run_attempt": 1,
+ "status": "completed",
+ "conclusion": "success",
+ "started_at": "2026-10-12T10:00:00Z",
+ "completed_at": "2026-10-12T10:05:00Z",
+ }
+ ]
+ },
+ f"{ARTIFACT}/zip": blob,
+ }
+
+ def read(endpoint):
+ response = responses[endpoint]
+ return (
+ response
+ if isinstance(response, bytes)
+ else json.dumps(response).encode()
+ )
+
+ monkeypatch.setattr(decision, "api_bytes", read)
+ return responses
+
+
+def replace_archive(responses, record, filename=decision.RECORD_NAME):
+ blob = archive_bytes(record, filename)
+ responses[f"{ARTIFACT}/zip"] = blob
+ responses[ARTIFACT]["digest"] = "sha256:" + hashlib.sha256(blob).hexdigest()
+ responses[ARTIFACT]["size_in_bytes"] = len(blob)
+
+
+def verify():
+ return decision.verify_decision(REPOSITORY, SHA, "500")
+
+
+def cli(monkeypatch, tmp_path):
+ output = tmp_path / "output"
+ monkeypatch.setenv("GITHUB_OUTPUT", str(output))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "verifier",
+ "verify",
+ "--repository",
+ REPOSITORY,
+ "--sha",
+ SHA,
+ "--artifact-id",
+ "500",
+ ],
+ )
+ return output
+
+
+def test_successful_build_authorizes_while_parent_waits_for_pypi(responses):
+ assert responses[ATTEMPT]["status"] == "in_progress"
+ assert verify() == "2026-10-13"
+
+
+def test_partial_rerun_keeps_original_artifact_attempt(responses):
+ # Attempt 1 built successfully, but a later job failed. The current
+ # attempt reruns only the monitor, so it has no new build to authorize.
+ responses[ATTEMPT].update(status="completed", conclusion="failure")
+ later_attempt = f"{ROOT}/actions/runs/42/attempts/2"
+ responses[later_attempt] = {
+ **responses[ATTEMPT],
+ "run_attempt": 2,
+ "status": "in_progress",
+ "conclusion": None,
+ }
+ responses[f"{ROOT}/actions/runs/42"] = responses[later_attempt]
+ responses[f"{later_attempt}/jobs?per_page=100&page=1"] = {
+ "jobs": [
+ {
+ "name": "monitor-pypi",
+ "run_id": 42,
+ "run_attempt": 2,
+ "status": "in_progress",
+ "conclusion": None,
+ }
+ ]
+ }
+ with patch.object(decision, "api_bytes", wraps=decision.api_bytes) as api:
+ assert verify() == "2026-10-13"
+ api.assert_any_call(ATTEMPT)
+ api.assert_any_call(JOBS)
+
+
+def test_no_exception_sentinel_requires_an_authentic_decision(
+ responses, record
+):
+ record["release_deadline"] = "none"
+ replace_archive(responses, record)
+ assert verify() == "none"
+
+
+ "field,value",
+ [
+ ("id", 501),
+ ("expired", True),
+ ("expired", None),
+ ("size_in_bytes", 1000000),
+ ("name", "other-artifact"),
+ ("name", "release-security-decision-none"),
+ ("workflow_run", None),
+ ],
+)
+def test_wrong_or_missing_artifact_is_rejected(responses, field, value):
+ responses[ARTIFACT][field] = value
+ with pytest.raises(ValueError):
+ verify()
+
+
+def test_artifact_for_another_commit_is_rejected(responses):
+ responses[ARTIFACT]["workflow_run"]["head_sha"] = "b" * 40
+ with pytest.raises(ValueError, match="commit"):
+ verify()
+
+
+ "field,value",
+ [
+ ("path", ".github/workflows/attacker.yml"),
+ ("event", "pull_request"),
+ ("head_sha", "b" * 40),
+ ("run_attempt", 2),
+ ("run_attempt", True),
+ ("id", 43),
+ ("repository", {"full_name": "other/repository"}),
+ ("head_repository", {"full_name": "attacker/fork"}),
+ ],
+)
+def test_wrong_workflow_run_or_fork_is_rejected(responses, field, value):
+ responses[ATTEMPT][field] = value
+ with pytest.raises(ValueError, match="expected release workflow"):
+ verify()
+
+
[email protected]("status", ["diverged", "behind", None])
+def test_unreviewed_commit_cannot_authorize_publication(responses, status):
+ responses[f"{ROOT}/compare/{SHA}...heads/main"]["status"] = status
+ with pytest.raises(ValueError, match="not on main"):
+ verify()
+
+
+ "field,value",
+ [
+ ("conclusion", "failure"),
+ ("conclusion", "skipped"),
+ ("status", "in_progress"),
+ ("run_attempt", 2),
+ ("run_id", 43),
+ ],
+)
+def test_failed_or_unfinished_build_cannot_authorize(responses, field, value):
+ responses[JOBS]["jobs"][0][field] = value
+ with pytest.raises(ValueError, match="did not succeed"):
+ verify()
+
+
[email protected]("count", [0, 2])
+def test_missing_or_ambiguous_build_fails_closed(responses, count):
+ responses[JOBS]["jobs"] *= count
+ with pytest.raises(ValueError, match="Expected one"):
+ verify()
+
+
+def test_all_job_pages_are_checked(responses):
+ build = deepcopy(responses[JOBS]["jobs"])
+ responses[JOBS]["jobs"] = [{"name": f"scan-{n}"} for n in range(100)]
+ responses[f"{ATTEMPT}/jobs?per_page=100&page=2"] = {"jobs": build}
+ assert verify() == "2026-10-13"
+
+
+ "created", ["2026-10-12T09:59:59Z", "2026-10-12T10:05:01Z"]
+)
+def test_artifact_from_outside_build_window_fails(responses, created):
+ responses[ARTIFACT]["created_at"] = created
+ with pytest.raises(ValueError, match="during the release build"):
+ verify()
+
+
+def test_tampered_download_fails_digest_verification(responses):
+ responses[f"{ARTIFACT}/zip"] += b"tampered"
+ with pytest.raises(ValueError, match="digest mismatch"):
+ verify()
+
+
+def test_missing_digest_fails_closed(responses):
+ del responses[ARTIFACT]["digest"]
+ with pytest.raises(ValueError, match="digest mismatch"):
+ verify()
+
+
+ "field,value",
+ [
+ ("version", True),
+ ("sha", "b" * 40),
+ ("repository", "attacker/fork"),
+ ("run_id", 43),
+ ("run_attempt", 2),
+ ("run_attempt", True),
+ ("release_deadline", None),
+ ("release_deadline", ""),
+ ],
+)
+def test_record_must_match_its_provenance(responses, record, field, value):
+ record[field] = value
+ replace_archive(responses, record)
+ with pytest.raises(ValueError):
+ verify()
+
+
+ "filename", ["../release-security-decision.json", "other.json"]
+)
+def test_unexpected_archive_member_is_rejected(responses, record, filename):
+ replace_archive(responses, record, filename)
+ with pytest.raises(ValueError, match="archive contents"):
+ verify()
+
+
[email protected]("artifact_id", ["", "none", "0", "../500", "500\n"])
+def test_missing_or_malformed_artifact_id_fails_before_api(
+ monkeypatch, artifact_id
+):
+ def forbidden(*args):
+ pytest.fail("API must not run for invalid artifact IDs")
+
+ monkeypatch.setattr(decision, "api_bytes", forbidden)
+ with pytest.raises(ValueError):
+ decision.verify_decision(REPOSITORY, SHA, artifact_id)
+
+
+def test_record_writer_binds_context_and_deadline(tmp_path, record):
+ path = tmp_path / decision.RECORD_NAME
+ decision.record_decision(
+ Namespace(
+ repository=REPOSITORY,
+ sha=SHA,
+ run_id="42",
+ run_attempt="1",
+ deadline="2026-10-13",
+ output=path,
+ )
+ )
+ assert json.loads(path.read_text()) == record
+
+
+def test_writer_does_not_record_expired_permission(tmp_path):
+ path = tmp_path / decision.RECORD_NAME
+ with pytest.raises(ValueError, match="expired"):
+ decision.record_decision(
+ Namespace(
+ repository=REPOSITORY,
+ sha=SHA,
+ run_id="42",
+ run_attempt="1",
+ deadline="2026-10-12",
+ output=path,
+ )
+ )
+ assert not path.exists()
+
+
+def test_cli_publishes_only_verified_output(responses, cli):
+ assert decision.main() == 0
+ assert cli.read_text() == "release_deadline=2026-10-13\n"
+
+
[email protected]("override", ["none", "2099-01-01"])
+ "recorded_deadline,allowed",
+ [("2026-10-12", False), ("2026-10-13", True)],
+)
+def test_cli_uses_recorded_deadline_despite_deadline_environment(
+ responses, record, cli, monkeypatch, override, recorded_deadline, allowed
+):
+ record["release_deadline"] = recorded_deadline
+ replace_archive(responses, record)
+ # The environment is an attempted override, not a supported input.
+ monkeypatch.setenv("RELEASE_DEADLINE", override)
+ assert decision.main() == (0 if allowed else 1)
+ if allowed:
+ assert cli.read_text() == f"release_deadline={recorded_deadline}\n"
+ else:
+ assert not cli.exists()
+
+
[email protected]("override", ["none", "2099-01-01"])
+def test_verify_cli_rejects_a_deadline_argument(cli, monkeypatch, override):
+ monkeypatch.setattr(sys, "argv", [*sys.argv, "--deadline", override])
+ with patch.object(decision, "api_bytes") as api:
+ with pytest.raises(SystemExit) as exc:
+ decision.main()
+ assert exc.value.code == 2
+ api.assert_not_called()
+ assert not cli.exists()
+
+
+def test_cli_api_error_never_emits_permission(monkeypatch, cli, capsys):
+ def fail(endpoint):
+ raise subprocess.CalledProcessError(
+ 1, ["gh", "api"], stderr=b"HTTP 403\n::warning::injected"
+ )
+
+ monkeypatch.setattr(decision, "api_bytes", fail)
+ assert decision.main() == 1
+ assert not cli.exists()
+ assert "HTTP 403%0A::warning::injected" in capsys.readouterr().out
+
+
+def test_api_transport_uses_only_get(monkeypatch):
+ def run(args, **kwargs):
+ assert args[:4] == ["gh", "api", "--method", "GET"]
+ assert kwargs["check"] and kwargs["timeout"] == 60
+ return subprocess.CompletedProcess(args, 0, stdout=b"{}")
+
+ monkeypatch.setattr(decision.subprocess, "run", run)
+ assert decision.api_object(ARTIFACT) == {}
diff --git a/tests/ci/test_release_security_exceptions.py b/tests/ci/test_release_security_exceptions.py
new file mode 100644
index 0000000000..9727a89042
--- /dev/null
+++ b/tests/ci/test_release_security_exceptions.py
@@ -0,0 +1,549 @@
+"""Exercise release decisions while preserving open security alerts."""
+
+# allow: no-sut-import — the SUT is the standalone release gate script.
+
+from copy import deepcopy
+from datetime import date, datetime, timezone
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+import yaml
+
+
+ROOT = Path(__file__).resolve().parents[2]
+REPOSITORY = "LearningCircuit/local-deep-research"
+SCRIPT = ROOT / ".github/scripts/check_code_scanning_alerts.py"
+spec = importlib.util.spec_from_file_location("release_alert_gate", SCRIPT)
+gate = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(gate)
+TODAY = date(2026, 9, 27)
+
+
+def alert():
+ return {
+ "number": 8273,
+ "state": "open",
+ "rule": {
+ "id": "CVE-2026-87910-python",
+ "security_severity_level": "medium",
+ },
+ "tool": {"name": "Grype"},
+ "most_recent_instance": {
+ "category": "grype-container",
+ "location": {
+ "path": "local-deep-research//usr/local/bin/python3.14",
+ },
+ },
+ }
+
+
+def policy():
+ return {
+ "version": 1,
+ "repository": REPOSITORY,
+ "exceptions": [
+ {
+ "alert_number": 8273,
+ "rule_id": "CVE-2026-87910-python",
+ "tool": "Grype",
+ "category": "grype-container",
+ "path": "local-deep-research//usr/local/bin/python3.14",
+ "severity": "medium",
+ "expires_on": "2026-10-13",
+ "reason": "Wait for a confirmed fixed upstream image.",
+ "tracking_url": "https://github.com/LearningCircuit/local-deep-research/pull/6628",
+ }
+ ],
+ }
+
+
+def exceptions(tmp_path, policy):
+ path = tmp_path / "exceptions.json"
+ path.write_text(json.dumps(policy))
+ return gate.load_exceptions(path, REPOSITORY)
+
+
+def test_checked_in_policy_is_valid():
+ # Keep testing the mechanism after the temporary entry is removed.
+ gate.load_exceptions(gate.POLICY_PATH, REPOSITORY)
+
+
+def test_matching_exception_does_not_mutate_alert(alert, exceptions):
+ original = deepcopy(alert)
+ blocking, excepted, expired = gate.classify_alerts(
+ [alert], exceptions, TODAY
+ )
+
+ assert blocking == []
+ assert excepted == [alert]
+ assert expired == []
+ assert alert == original
+ assert alert["state"] == "open"
+
+
+ "today,expected_blocking",
+ [
+ (date(2026, 10, 12), False),
+ (date(2026, 10, 13), True),
+ (date(2026, 10, 14), True),
+ ],
+)
+def test_expiry_boundary(alert, exceptions, today, expected_blocking):
+ blocking, excepted, expired = gate.classify_alerts(
+ [alert], exceptions, today
+ )
+ assert bool(blocking) is expected_blocking
+ assert bool(excepted) is not expected_blocking
+ assert expired == ([8273] if expected_blocking else [])
+
+
+ "keys,value",
+ [
+ (("number",), 8274),
+ (("rule", "id"), "CVE-2026-87910-other-package"),
+ (("rule", "security_severity_level"), "high"),
+ (("rule", "security_severity_level"), "critical"),
+ (("tool", "name"), "CodeQL"),
+ (("most_recent_instance", "category"), "grype-filesystem"),
+ (("most_recent_instance", "location", "path"), "/usr/bin/python3.14"),
+ (("most_recent_instance", "location", "path"), None),
+ (("most_recent_instance", "location"), None),
+ (("most_recent_instance", "location"), "invalid"),
+ (("most_recent_instance",), None),
+ (("most_recent_instance",), "invalid"),
+ (("tool",), None),
+ (("tool",), "invalid"),
+ ],
+)
+def test_scope_drift_and_severity_increase_block(
+ alert, exceptions, keys, value
+):
+ target = alert
+ for key in keys[:-1]:
+ target = target[key]
+ target[keys[-1]] = value
+ blocking, excepted, _ = gate.classify_alerts([alert], exceptions, TODAY)
+ assert blocking == [alert]
+ assert excepted == []
+
+
[email protected]("severity", ["critical", "high", "medium"])
+def test_unrelated_alerts_still_block(alert, exceptions, severity):
+ other = deepcopy(alert)
+ other["number"] = 8185
+ other["rule"] = {
+ "id": "py/stack-trace-exposure",
+ "security_severity_level": severity,
+ }
+ other["tool"] = {"name": "CodeQL"}
+ blocking, excepted, _ = gate.classify_alerts(
+ [alert, other], exceptions, TODAY
+ )
+ assert blocking == [other]
+ assert excepted == [alert]
+
+
[email protected]("severity", ["low", None])
+def test_existing_nonblocking_severities_are_preserved(alert, severity):
+ alert["rule"]["security_severity_level"] = severity
+ gate.validate_alerts([alert])
+ assert gate.classify_alerts([alert], {}, TODAY) == ([], [], [])
+
+
+def test_quality_alert_without_security_severity_is_nonblocking(
+ monkeypatch, cli
+):
+ # Shape of real Hadolint alert #8101: ordinary rule severity is not a
+ # security severity. The optional security_severity_level is absent.
+ alert = {
+ "number": 8101,
+ "state": "open",
+ "rule": {"id": "DL3025", "severity": "warning"},
+ "tool": {"name": "Hadolint"},
+ }
+ original = deepcopy(alert)
+ _mock_pages(monkeypatch, [[alert], []])
+ assert gate.main() == 0
+ assert "Fetched 1 open alert(s)" in cli[0].read_text()
+ assert "No open critical" in cli[0].read_text()
+ assert cli[1].read_text() == "excepted_count=0\nrelease_deadline=none\n"
+ assert alert == original
+
+
+def test_empty_policy_restores_blocking(alert):
+ assert gate.classify_alerts([alert], {}, TODAY) == ([alert], [], [])
+
+
+def test_expired_entry_for_closed_alert_does_not_block(exceptions):
+ # Only open alerts are fetched; stale entries do not grant anything.
+ assert gate.classify_alerts([], exceptions, date(2027, 1, 1)) == (
+ [],
+ [],
+ [],
+ )
+
+
+ "field,value",
+ [
+ ("expires_on", None),
+ ("expires_on", ""),
+ ("expires_on", "2026-13-01"),
+ ("expires_on", "20261013"),
+ ("severity", "*"),
+ ("reason", " "),
+ ("alert_number", True),
+ ("alert_number", 0),
+ ("tracking_url", "javascript:alert(1)"),
+ ],
+)
+def test_invalid_exception_is_rejected(tmp_path, policy, field, value):
+ policy["exceptions"][0][field] = value
+ path = tmp_path / "exceptions.json"
+ path.write_text(json.dumps(policy))
+ with pytest.raises(ValueError):
+ gate.load_exceptions(path, REPOSITORY)
+
+
+ "change", ["missing", "unknown", "duplicate", "repository", "version"]
+)
+def test_policy_mistakes_fail_closed(tmp_path, policy, change):
+ if change == "missing":
+ del policy["exceptions"][0]["expires_on"]
+ elif change == "unknown":
+ policy["exceptions"][0]["expiry"] = "2026-10-13"
+ elif change == "duplicate":
+ policy["exceptions"].append(deepcopy(policy["exceptions"][0]))
+ elif change == "repository":
+ policy["repository"] = "another/repository"
+ else:
+ policy["version"] = True
+ path = tmp_path / "exceptions.json"
+ path.write_text(json.dumps(policy))
+ with pytest.raises(ValueError):
+ gate.load_exceptions(path, REPOSITORY)
+
+
+def _mock_pages(monkeypatch, pages):
+ responses = iter(pages)
+ calls = []
+
+ def run(args, **kwargs):
+ calls.append(args)
+ assert args[:4] == ["gh", "api", "--method", "GET"]
+ assert f"page={len(calls)}" in args[-1]
+ assert kwargs["check"] is True
+ assert kwargs["timeout"] == 60
+ response = next(responses)
+ if isinstance(response, Exception):
+ raise response
+ return subprocess.CompletedProcess(args, 0, stdout=json.dumps(response))
+
+ monkeypatch.setattr(gate.subprocess, "run", run)
+ return calls
+
+
+def test_all_pages_are_fetched_before_deciding(monkeypatch, alert, exceptions):
+ other = deepcopy(alert)
+ other["number"] = 9008
+ calls = _mock_pages(monkeypatch, [[alert], [other], []])
+ alerts = gate.fetch_alerts(REPOSITORY)
+ blocking, excepted, _ = gate.classify_alerts(alerts, exceptions, TODAY)
+ assert len(calls) == 3
+ assert blocking == [other]
+ assert excepted == [alert]
+
+
+def cli(monkeypatch, tmp_path, policy):
+ class FrozenDateTime(datetime):
+ @classmethod
+ def now(cls, tz=None):
+ assert tz == timezone.utc
+ return datetime(2026, 9, 27, tzinfo=tz)
+
+ monkeypatch.setattr(gate, "datetime", FrozenDateTime)
+ path = tmp_path / "exceptions.json"
+ path.write_text(json.dumps(policy))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(SCRIPT),
+ "--repository",
+ REPOSITORY,
+ "--exceptions",
+ str(path),
+ "--evidence-deadline",
+ "none",
+ ],
+ )
+ summary = tmp_path / "summary.md"
+ output = tmp_path / "output.txt"
+ monkeypatch.setenv("GITHUB_STEP_SUMMARY", str(summary))
+ monkeypatch.setenv("GITHUB_OUTPUT", str(output))
+ return summary, output
+
+
+def test_cli_reports_exception_without_claiming_no_alerts(
+ monkeypatch, cli, alert, capsys
+):
+ summary, output = cli
+ _mock_pages(monkeypatch, [[alert], []])
+ assert gate.main() == 0
+ report = summary.read_text()
+ assert "| Medium | 1 | 1 | 0 |" in report
+ assert "These alerts remain open" in report
+ assert "2026-10-13" in report
+ assert "No open critical" not in report
+ assert output.read_text() == (
+ "excepted_count=1\nrelease_deadline=2026-10-13\n"
+ )
+ assert (
+ "::warning::Release exception for open alert #8273"
+ in capsys.readouterr().out
+ )
+
+
+ "batch", [{"message": "error"}, [None], [{"number": 3}]]
+)
+def test_bad_api_data_never_passes(monkeypatch, cli, batch):
+ _mock_pages(monkeypatch, [batch])
+ assert gate.main() == 1
+ assert not cli[1].exists()
+
+
[email protected]("severity", ["unknown", "", 5, True, [], {}])
+def test_malformed_alert_severity_fails(monkeypatch, cli, alert, severity):
+ alert["rule"]["security_severity_level"] = severity
+ _mock_pages(monkeypatch, [[alert]])
+ assert gate.main() == 1
+
+
+def test_api_failure_after_first_page_never_grants_exception(
+ monkeypatch, cli, alert
+):
+ failure = subprocess.CalledProcessError(1, ["gh", "api"])
+ _mock_pages(monkeypatch, [[alert], failure])
+ assert gate.main() == 1
+ assert not cli[1].exists()
+
+
[email protected]("channel", ["stderr", "output"])
+def test_api_failure_preserves_bounded_escaped_diagnostics(
+ monkeypatch, cli, capsys, channel
+):
+ failure = subprocess.CalledProcessError(
+ 1,
+ ["gh", "api"],
+ **{channel: "HTTP 403 rate limit\n::warning::injected%\r" + "x" * 3000},
+ )
+ _mock_pages(monkeypatch, [failure])
+ assert gate.main() == 1
+ report = capsys.readouterr().out
+ assert "HTTP 403 rate limit%0A::warning::injected%25%0D" in report
+ assert "x" * 2001 not in report
+ assert len(report.splitlines()) == 1
+ assert not cli[1].exists()
+
+
+def test_missing_policy_fails_before_api(monkeypatch, cli, tmp_path):
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(SCRIPT),
+ "--repository",
+ REPOSITORY,
+ "--exceptions",
+ str(tmp_path / "missing.json"),
+ "--evidence-deadline",
+ "none",
+ ],
+ )
+ calls = _mock_pages(monkeypatch, [])
+ assert gate.main() == 1
+ assert calls == []
+
+
+def test_cli_unrelated_blocker_returns_failure(monkeypatch, cli, alert):
+ other = deepcopy(alert)
+ other["number"] = 9008
+ _mock_pages(monkeypatch, [[alert, other], []])
+ assert gate.main() == 1
+ assert "| Medium | 2 | 1 | 1 |" in cli[0].read_text()
+ assert not cli[1].exists(), "A blocked gate must not grant a deadline"
+
+
+def test_publication_deadline_uses_earliest_applied_exception(
+ alert, exceptions
+):
+ second = deepcopy(alert)
+ second["number"] = 42
+ exceptions[42] = {**exceptions[8273], "expires_on": "2026-10-05"}
+ # An unused/closed alert's entry must not constrain this release.
+ exceptions[99] = {"expires_on": "2020-01-01"}
+ assert (
+ gate.publication_deadline([alert, second], exceptions) == "2026-10-05"
+ )
+ assert gate.publication_deadline([alert], exceptions) == "2026-10-13"
+ assert gate.publication_deadline([], exceptions) == "none"
+
+
+ "previous,current,expected",
+ [
+ ("none", "none", "none"),
+ ("2026-10-05", "none", "2026-10-05"),
+ ("none", "2026-10-13", "2026-10-13"),
+ ("2026-10-05", "2026-10-13", "2026-10-05"),
+ ("2026-10-13", "2026-10-05", "2026-10-05"),
+ ],
+)
+def test_earliest_deadline_retains_both_gate_decisions(
+ previous, current, expected
+):
+ assert gate.earliest_deadline(previous, current, TODAY) == expected
+
+
+ "previous,expected",
+ [
+ ("none", "2026-10-13"),
+ ("2026-10-05", "2026-10-05"),
+ ("2026-10-20", "2026-10-13"),
+ ],
+)
+def test_cli_carries_earliest_deadline_from_either_query(
+ monkeypatch, cli, alert, previous, expected
+):
+ monkeypatch.setattr(sys, "argv", [*sys.argv[:-1], previous])
+ _mock_pages(monkeypatch, [[alert], []])
+ assert gate.main() == 0
+ assert cli[1].read_text() == (
+ f"excepted_count=1\nrelease_deadline={expected}\n"
+ )
+ assert f"`{expected}`" in cli[0].read_text()
+
+
+ "previous", ["", "20261013", "invalid", "2026-09-27", "2026-09-26"]
+)
+def test_invalid_or_expired_evidence_deadline_fails_before_api(
+ monkeypatch, cli, previous
+):
+ monkeypatch.setattr(sys, "argv", [*sys.argv[:-1], previous])
+ calls = _mock_pages(monkeypatch, [])
+ assert gate.main() == 1
+ assert calls == []
+ assert not cli[1].exists()
+
+
+def test_missing_evidence_deadline_is_not_unlimited(monkeypatch, cli):
+ monkeypatch.setattr(sys, "argv", sys.argv[:-2])
+ calls = _mock_pages(monkeypatch, [])
+ with pytest.raises(SystemExit) as error:
+ gate.main()
+ assert error.value.code == 2
+ assert calls == []
+ assert not cli[1].exists()
+
+
+def test_evidence_expiring_during_alert_fetch_does_not_grant_output(
+ monkeypatch, cli
+):
+ class AdvancingDateTime(datetime):
+ times = iter(
+ [
+ datetime(2026, 10, 12, 23, 59, tzinfo=timezone.utc),
+ datetime(2026, 10, 13, tzinfo=timezone.utc),
+ ]
+ )
+
+ @classmethod
+ def now(cls, tz=None):
+ assert tz == timezone.utc
+ return next(cls.times)
+
+ monkeypatch.setattr(gate, "datetime", AdvancingDateTime)
+ monkeypatch.setattr(sys, "argv", [*sys.argv[:-1], "2026-10-13"])
+ _mock_pages(monkeypatch, [[]])
+ assert gate.main() == 1
+ assert not cli[1].exists()
+
+
+def test_workflow_keeps_scans_and_alert_gate_required():
+ workflow = yaml.safe_load(
+ (ROOT / ".github/workflows/release-gate.yml").read_text()
+ )
+ job = workflow["jobs"]["check-code-scanning-alerts"]
+ assert job["permissions"] == {
+ "contents": "read",
+ "actions": "read",
+ "security-events": "read",
+ }
+ assert "grype-scan" in job["needs"]
+ assert not job.get("continue-on-error")
+ steps = job["steps"]
+ evidence = next(
+ step
+ for step in steps
+ if "check_release_scan_evidence.py" in step.get("run", "")
+ )
+ assert not evidence.get("continue-on-error")
+ assert evidence["id"] == "scan-evidence"
+ assert (
+ "--exceptions .github/release-security-exceptions.json"
+ in evidence["run"]
+ )
+ check = next(step for step in steps if step.get("id") == "alert-check")
+ assert steps.index(evidence) < steps.index(check)
+ assert not check.get("continue-on-error")
+ assert ".github/scripts/check_code_scanning_alerts.py" in check["run"]
+ assert '--repository "$GITHUB_REPOSITORY"' in check["run"]
+ assert '--evidence-deadline "$EVIDENCE_DEADLINE"' in check["run"]
+ assert check["env"]["EVIDENCE_DEADLINE"] == (
+ "${{ steps.scan-evidence.outputs.release_deadline }}"
+ )
+ assert any(
+ step.get("uses", "").startswith("actions/checkout@") for step in steps
+ )
+ summary = workflow["jobs"]["release-gate-summary"]
+ assert "check-code-scanning-alerts" in summary["needs"]
+ assert "grype-scan" in summary["needs"]
+ required_results = next(
+ step
+ for step in summary["steps"]
+ if "GATE_RESULTS" in step.get("env", {})
+ and "EXCEPTED_ALERT_COUNT" not in step.get("env", {})
+ )
+ assert summary["if"] == "always()"
+ assert "if" not in required_results
+ assert not required_results.get("continue-on-error")
+ reporting = next(
+ step
+ for step in summary["steps"]
+ if "EXCEPTED_ALERT_COUNT" in step.get("env", {})
+ )
+ assert summary["steps"].index(required_results) < summary["steps"].index(
+ reporting
+ )
+ assert "excepted_count" in reporting["env"]["EXCEPTED_ALERT_COUNT"]
+ assert reporting["env"]["RELEASE_DEADLINE"] == (
+ "${{ needs.check-code-scanning-alerts.outputs.release_deadline }}"
+ )
+ assert 'if [ "$RELEASE_DEADLINE" != "none" ]' in reporting["run"]
+ assert (
+ "Applied exceptions retain their original deadline" in reporting["run"]
+ )
diff --git a/tests/database/test_retry_on_db_lock.py b/tests/database/test_retry_on_db_lock.py
index 857a983fa0..d361d9509d 100644
--- a/tests/database/test_retry_on_db_lock.py
+++ b/tests/database/test_retry_on_db_lock.py
@@ -243,8 +243,8 @@ class TestRetryOnLockIntegration:
conn.close()
holder_started = threading.Event()
- first_lock_error = threading.Event()
- holder_committed = threading.Event()
+ holder_release = threading.Event()
+ holder_done = threading.Event()
call_count = []
def holder():
@@ -256,14 +256,12 @@ class TestRetryOnLockIntegration:
c.execute("BEGIN IMMEDIATE")
c.execute("INSERT INTO counters (id, n) VALUES (2, 100)")
holder_started.set()
- # Hold the lock until the writer has actually seen a lock
- # error. A wall-clock release can race ahead of a writer
- # delayed by a loaded CI runner.
- assert first_lock_error.wait(timeout=30.0)
+ # Hold the writer lock until the test releases us.
+ holder_release.wait()
c.commit()
- holder_committed.set()
finally:
c.close()
+ holder_done.set()
def writer_callable():
"""Open a fresh session, do an ``UPDATE`` inside an
@@ -271,9 +269,9 @@ class TestRetryOnLockIntegration:
``IMMEDIATE`` is what makes ``busy_timeout`` apply: it
acquires the writer lock at BEGIN, so a contended writer
- hits the spinner that ``busy_timeout`` bounds. With
- ``DEFERRED`` (the default), the write transaction would
- acquire the lock at the first UPDATE instead.
+ hits the spinner that ``busy_timeout`` bounds. Release
+ the holder only after observing that real lock error,
+ regardless of how long opening this connection takes.
"""
call_count.append(1)
c = self._open_with_tight_timeout(
@@ -282,10 +280,11 @@ class TestRetryOnLockIntegration:
try:
try:
c.execute("BEGIN IMMEDIATE")
- except sqlcipher_module.OperationalError:
- first_lock_error.set()
- assert holder_committed.wait(timeout=10.0), (
- "lock holder did not commit after the first timeout"
+ except sqlcipher_module.OperationalError as exc:
+ assert "locked" in str(exc).lower()
+ holder_release.set()
+ assert holder_done.wait(timeout=5.0), (
+ "Holder did not release its transaction"
)
raise
c.execute("UPDATE counters SET n = n + 1 WHERE id = 1")
@@ -296,22 +295,21 @@ class TestRetryOnLockIntegration:
t_holder = threading.Thread(target=holder)
t_holder.start()
- # Make sure the holder is in its BEGIN IMMEDIATE before the
- # writer's first attempt.
- assert holder_started.wait(timeout=10.0)
-
- # The first attempt times out while the holder still owns the
- # lock. The holder commits only after that error, so the retry
- # exercises the successful path without relying on scheduler timing.
- result = retry_on_db_lock(
- writer_callable, attempts=3, base_delay_seconds=0.1
- )
- assert result == "committed"
-
- t_holder.join()
+ try:
+ # The first attempt must observe contention before the
+ # holder releases its transaction and permits the retry.
+ assert holder_started.wait(timeout=5.0)
+ result = retry_on_db_lock(
+ writer_callable, attempts=3, base_delay_seconds=0.1
+ )
+ assert result == "committed"
+ finally:
+ # Also release the holder if setup or the retry helper fails.
+ holder_release.set()
+ t_holder.join(timeout=5.0)
+ assert not t_holder.is_alive(), "Holder thread did not finish"
- # The helper must have retried at least once (the first
- # attempt inside the 200 ms busy_timeout window).
+ # The helper must have retried after the real lock error.
assert len(call_count) >= 2, (
f"Expected at least 2 attempts (first lock + retry), got "
f"{len(call_count)}"