diff --git a/.config/advisory-exceptions.toml b/.config/advisory-exceptions.toml new file mode 100644 index 0000000000..fd7f6a9a99 --- /dev/null +++ b/.config/advisory-exceptions.toml @@ -0,0 +1,62 @@ +# Machine-enforced RustSec advisory exception registry. +# +# Validated by `scripts/security/check_advisories.py` in both `ci.yml` +# (`security-advisories`, required via `Test and Lint`) and daily `audit.yml`. +# +# Rules (rustfs/backlog#2668): +# - Every `[advisories].ignore` entry in `deny.toml` must match an entry here +# bidirectionally; comment-only or untracked ignores fail closed. +# - Timestamps use strict UTC RFC 3339 (`YYYY-MM-DDTHH:MM:SSZ`). +# - Maximum validity window is 90 days (`expires_at - approved_at <= 90d`). +# - Expired exceptions fail closed; renewals require explicit maintainer review +# and cannot be auto-extended or self-approved in a PR. + +schema_version = 1 + +[[exceptions]] +advisory_id = "RUSTSEC-2023-0071" +crate = "rsa" +affected_versions = "=0.9.10" +owner = "rustfs-maintainers" +tracking_issue = "https://github.com/rustfs/backlog/issues/2668" +reason = "Transitive rsa 0.9.10 pulled exclusively via openidconnect 4.1.0 <- rustfs-iam; direct workspace rsa consumers already upgraded to patched rsa 0.10.0 in PR #9492. Historical 2026-07 review window has expired and requires maintainer risk-acceptance sign-off or upstream openidconnect upgrade to rsa >=0.10.0 before promotion." +mitigation = "crates/iam/src/oidc uses openidconnect only for public-key JWS ID-token verification and rejects signed or encrypted UserInfo responses (crates/iam/src/oidc/runtime.rs), exposing no remote RSA private-key decryption oracle on rsa 0.9.10. Track upstream openidconnect migration off rsa 0.9.x." +approved_at = "2026-05-06T07:47:19Z" +expires_at = "2026-07-31T23:59:59Z" +approval_reference = "https://github.com/rustfs/rustfs/pull/2769" + +[[exceptions]] +advisory_id = "RUSTSEC-2026-0543" +crate = "chrono" +affected_versions = "=0.4.45" +owner = "rustfs-maintainers" +tracking_issue = "https://github.com/rustfs/backlog/issues/2668" +reason = "chrono is marked unmaintained with no patched release; retained temporarily at compatibility boundaries and transitive datafusion/arrow/openidconnect dependencies during the jiff 1.0 migration reviewed in PR #9492." +mitigation = "Informational unmaintained advisory with no CVE or memory-safety vulnerability; core server timestamp paths already migrated to jiff 1.0 in PR #9492 while remaining compatibility boundaries and upstream crates transition off chrono." +approved_at = "2026-11-18T12:17:44Z" +expires_at = "2026-11-30T23:59:59Z" +approval_reference = "https://github.com/rustfs/rustfs/pull/9492" + +[[exceptions]] +advisory_id = "RUSTSEC-2026-0555" +crate = "chrono-tz" +affected_versions = "=0.10.4" +owner = "rustfs-maintainers" +tracking_issue = "https://github.com/rustfs/backlog/issues/2668" +reason = "chrono-tz is marked unmaintained with no patched release; pulled transitively by arrow-array 59.3.3 and datafusion-functions 55.3.0 during the jiff migration reviewed in PR #9492." +mitigation = "Informational unmaintained advisory with no known security vulnerability; confined to transitive DataFusion/Arrow SQL timezone handling until upstream removes chrono-tz." +approved_at = "2026-11-18T12:17:44Z" +expires_at = "2026-11-30T23:59:59Z" +approval_reference = "https://github.com/rustfs/rustfs/pull/9492" + +[[exceptions]] +advisory_id = "RUSTSEC-2026-0542" +crate = "humantime" +affected_versions = "=2.4.0" +owner = "rustfs-maintainers" +tracking_issue = "https://github.com/rustfs/backlog/issues/2668" +reason = "humantime is marked unmaintained through chrono with no patched release; used by rustfs-madmin and transitively by object_store 0.13.2 / datafusion 55.3.0 as temporarily reviewed in PR #9492." +mitigation = "Informational unmaintained advisory with no known security vulnerability; limited to duration formatting and tracked for removal alongside the remaining chrono/jiff migration." +approved_at = "2026-11-18T12:17:44Z" +expires_at = "2026-11-30T23:59:59Z" +approval_reference = "https://github.com/rustfs/rustfs/pull/9492" diff --git a/.config/make/tests.mak b/.config/make/tests.mak index 800750a450..f043421bcf 100644 --- a/.config/make/tests.mak +++ b/.config/make/tests.mak @@ -93,6 +93,7 @@ script-tests: ## Run shell script tests $(RUSTFS_PYTHON_BIN) ./scripts/test_ci_merge_queue.py $(RUSTFS_PYTHON_BIN) -m unittest discover -s scripts/ci -p 'test_*.py' $(RUSTFS_PYTHON_BIN) ./scripts/check_security_coverage.py --self-test + $(RUSTFS_PYTHON_BIN) ./scripts/security/check_advisories.py --self-test $(RUSTFS_PYTHON_BIN) ./scripts/check_scheduled_validation_freshness.py --self-test $(RUSTFS_PYTHON_BIN) ./scripts/test_security_workflow.py $(RUSTFS_PYTHON_BIN) ./scripts/test_nightly_candidate.py diff --git a/.github/workflows/audit.yml b/.github/workflows/audit.yml index e7cf59138d..a60a06e64e 100644 --- a/.github/workflows/audit.yml +++ b/.github/workflows/audit.yml @@ -21,6 +21,9 @@ on: - '**/Cargo.toml' - '**/Cargo.lock' - 'deny.toml' + - '.config/advisory-exceptions.toml' + - 'scripts/security/check_advisories.py' + - 'scripts/security/test_check_advisories.py' - '.github/actions/**' - '.github/workflows/**' - 'scripts/release/**' @@ -46,6 +49,9 @@ on: - '**/Cargo.toml' - '**/Cargo.lock' - 'deny.toml' + - '.config/advisory-exceptions.toml' + - 'scripts/security/check_advisories.py' + - 'scripts/security/test_check_advisories.py' - '.github/actions/**' - '.github/workflows/**' - 'scripts/release/**' @@ -107,6 +113,7 @@ jobs: - name: Checkout repository uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7 with: + fetch-depth: 2 persist-credentials: false # cargo-deny compiles nothing, so the full setup composite (apt packages, @@ -134,12 +141,36 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' }} - name: Install cargo-deny + id: install-cargo-deny uses: taiki-e/install-action@7623a79cdfecb99d681017af368ca353d9f49bb5 # v2 with: - tool: cargo-deny + tool: cargo-deny@0.20.2 - name: Run cargo-deny - run: cargo deny check --hide-inclusion-graph advisories sources bans licenses + run: cargo deny --locked check --hide-inclusion-graph advisories sources bans licenses + + - name: Enforce time-bounded advisory exception registry + if: "!cancelled() && steps.install-cargo-deny.outcome == 'success'" + env: + GH_TOKEN: ${{ github.token }} + CI_BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + if [[ -n "$CI_BASE_SHA" ]]; then + git cat-file -e "${CI_BASE_SHA}^{commit}" 2>/dev/null || git fetch --no-tags --depth=1 origin "$CI_BASE_SHA" + fi + mkdir -p artifacts/advisories + python3 scripts/security/check_advisories.py \ + --output artifacts/advisories/advisories-gate.json \ + --raw-log artifacts/advisories/cargo-deny.log + + - name: Upload advisory audit evidence + if: "!cancelled() && steps.install-cargo-deny.outcome == 'success'" + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: audit-advisories-${{ github.run_number }}-${{ github.run_attempt }} + path: artifacts/advisories + if-no-files-found: error + retention-days: 7 workflow-pin-report: name: Workflow Pin Report diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b1e6a9fa0..c7e1e83ad2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -113,7 +113,7 @@ jobs: printf '%s\n' 'mode=full' >> "$GITHUB_OUTPUT" echo "Base CI policy unavailable; running the full matrix." fi - if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=9$' "$GITHUB_OUTPUT"; then + if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=10$' "$GITHUB_OUTPUT"; then printf '%s\n' 'mode=full' 'connect=true' 'full_validation=true' 'packages=' 'plan=' >> "$GITHUB_OUTPUT" echo "Base policy does not cover this workflow contract; retaining the full matrix." fi @@ -168,6 +168,60 @@ jobs: - name: Run shared quick checks uses: ./.github/actions/quick-checks + # Required dependency advisory and time-bounded exception gate (rustfs/backlog#2668). + # Runs on every non-closed event, including documentation-only PRs, because a + # RustSec advisory can be published or an exception can expire without lockfile edits. + security-advisories: + name: Security Advisories + if: github.event_name != 'pull_request' || github.event.action != 'closed' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Checkout repository + uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7 + with: + fetch-depth: 2 + persist-credentials: false + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable + + - name: Setup Rust cache + uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + with: + cache-all-crates: false + cache-on-failure: true + shared-key: rustfs-cargo-deny + save-if: 'false' + + - name: Install cargo-deny + id: install-cargo-deny + uses: taiki-e/install-action@7623a79cdfecb99d681017af368ca353d9f49bb5 # v2 + with: + tool: cargo-deny@0.20.2 + + - name: Run security advisories gate + env: + GH_TOKEN: ${{ github.token }} + CI_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }} + run: | + if [[ -n "$CI_BASE_SHA" ]]; then + git cat-file -e "${CI_BASE_SHA}^{commit}" 2>/dev/null || git fetch --no-tags --depth=1 origin "$CI_BASE_SHA" + fi + mkdir -p artifacts/advisories + python3 scripts/security/check_advisories.py \ + --output artifacts/advisories/advisories-gate.json \ + --raw-log artifacts/advisories/cargo-deny.log + + - name: Upload security advisories evidence + if: "!cancelled() && steps.install-cargo-deny.outcome == 'success'" + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: security-advisories-${{ github.run_number }}-${{ github.run_attempt }} + path: artifacts/advisories + if-no-files-found: error + retention-days: 7 + # Clippy runs beside the test-binary build instead of in front of it. The two # share no compiler output: Clippy writes check-mode metadata, the archive # needs codegen and linked test binaries, and both restore the third-party @@ -1270,6 +1324,7 @@ jobs: - classify-changes - typos - quick-checks + - security-advisories - workspace-clippy - workspace-lint-and-build - workspace-tests @@ -1304,6 +1359,7 @@ jobs: - required-checks - typos - quick-checks + - security-advisories - workspace-clippy - workspace-lint-and-build - workspace-tests diff --git a/deny.toml b/deny.toml index 69f47ea7e9..cd585322ee 100644 --- a/deny.toml +++ b/deny.toml @@ -8,8 +8,10 @@ # - which non-crates.io sources we trust, # - which duplicate crate versions we tolerate vs. flag. # -# When adding an exception, include an `# owner: review: ` +# When adding a non-advisory exception, include an `# owner: review: ` # comment so future audits know who signed off and when to revisit. +# Advisory ignores below are machine-enforced against `.config/advisory-exceptions.toml` +# by `scripts/security/check_advisories.py` (rustfs/backlog#2668); both files must match. [graph] all-features = true @@ -19,24 +21,23 @@ no-default-features = false version = 2 yanked = "deny" ignore = [ - # `rsa` Marvin timing sidechannel (RUSTSEC-2023-0071). Pulled in via - # `openidconnect` (transitive) and historically used directly. No upstream - # fix is available yet. Tracked separately for follow-up; remove this - # entry once a patched `rsa` lands in the dependency graph and any - # in-process RSA decryption oracles are removed. + # `rsa` Marvin timing sidechannel (RUSTSEC-2023-0071, patched in >= 0.10.0). + # Direct workspace consumers migrated to `rsa 0.10.0` in PR #9492; only + # transitive `rsa 0.9.10` remains via `openidconnect 4.1.0` (`rustfs-iam`). + # Machine-enforced expiry and approval metadata live in `.config/advisory-exceptions.toml`. # owner: rustfs-maintainers review: 2026-07 - { id = "RUSTSEC-2023-0071", reason = "rsa Marvin timing sidechannel; no fixed upstream version; tracked separately" }, + { id = "RUSTSEC-2023-0071", reason = "rsa 0.9.10 Marvin timing sidechannel via openidconnect 4.1.0; tracked in .config/advisory-exceptions.toml" }, # `chrono` is retained only at compatibility boundaries while the project # migrates its internal time model to jiff. The advisory reports no safe - # upgrade for any chrono release. + # upgrade for any chrono release. Tracked in `.config/advisory-exceptions.toml`. # owner: rustfs-maintainers review: 2026-11 { id = "RUSTSEC-2026-0543", reason = "chrono is unmaintained; temporary exception during jiff migration" }, # `chrono-tz` is retained by a narrow compatibility path during the same - # migration and has no safe upstream upgrade. + # migration and has no safe upstream upgrade. Tracked in `.config/advisory-exceptions.toml`. # owner: rustfs-maintainers review: 2026-11 { id = "RUSTSEC-2026-0555", reason = "chrono-tz is unmaintained; temporary exception during jiff migration" }, # humantime wraps chrono and is retained transitively while the chrono - # graph is being removed. + # graph is being removed. Tracked in `.config/advisory-exceptions.toml`. # owner: rustfs-maintainers review: 2026-11 { id = "RUSTSEC-2026-0542", reason = "humantime is unmaintained through chrono; temporary exception during jiff migration" }, ] diff --git a/scripts/ci_gate.py b/scripts/ci_gate.py index 910a92e271..e87d882a92 100644 --- a/scripts/ci_gate.py +++ b/scripts/ci_gate.py @@ -15,7 +15,7 @@ import tomllib import unittest ROOT = Path(__file__).resolve().parent.parent -ALWAYS_JOBS = ("classify-changes", "typos", "quick-checks") +ALWAYS_JOBS = ("classify-changes", "typos", "quick-checks", "security-advisories") CODE_JOBS = ( "workspace-clippy", "workspace-lint-and-build", "workspace-tests", "core-contract", "connect-feature-boundaries", "fips-provider", "test-and-lint-protocols", "build-rustfs-debug-binary", "uring-integration", @@ -34,7 +34,7 @@ NIGHTLY_JOBS = ("connect-feature-boundaries", "fips-provider", "uring-integratio # against this revision's expected job contract. The workflow refuses a plan # that does not carry the current marker and falls back to the full matrix, so # a base planner predating the contract cannot authorize a narrower selection. -PLAN_CONTRACT = "9" +PLAN_CONTRACT = "10" # These jobs still exercise the server and its black-box harness when only E2E # Rust sources change. Production code, manifests and shared test configuration # always select the full matrix. No production package depends on e2e_test. @@ -59,6 +59,8 @@ SETUP = "./.github/actions/setup" # The condition every cache-warm.yml build carries: Rust-cache does not save over an exact key match. HIT_SKIP = "steps.setup.outputs.cache-hit != 'true'" LINT_COMMANDS = ("cargo clippy --all-targets -- -D warnings", "python3 scripts/ci_test_artifact.py cargo lint --configuration workspace") +ADVISORIES_JOB = "security-advisories" +ADVISORIES_COMMAND = "python3 scripts/security/check_advisories.py" OPTIONAL_JOBS = ("e2e-full",) NON_VALIDATION_JOBS = {"required-checks", "cancel-closed-pr-runs", "alert-on-failure"} @@ -685,6 +687,22 @@ def check_plan_contract_marker(jobs: dict) -> list[str]: return [] +def check_advisories_lane(jobs: dict) -> list[str]: + """Keep security-advisories running the shared fail-closed checker without clock overrides.""" + errors = [] + block = jobs.get(ADVISORIES_JOB, {}) + if block.get("runs-on") != "ubuntu-latest": + errors.append(f"{ADVISORIES_JOB} must run on ubuntu-latest") + steps = [step for step in block.get("steps", []) if ADVISORIES_COMMAND in step.get("run", "")] + if len(steps) != 1 or "if" in steps[0]: + errors.append(f"{ADVISORIES_JOB} must unconditionally run {ADVISORIES_COMMAND}") + else: + body = steps[0].get("run", "") + if "|| true" in body or "--now" in body or "--allow-ci-clock-override-for-test" in body: + errors.append(f"{ADVISORIES_JOB} must not mask failures or override the CI clock") + return errors + + def check_workflow(root: Path) -> list[str]: try: document = workflow_document((root / ".github/workflows/ci.yml").read_text()) @@ -720,6 +738,7 @@ def check_workflow(root: Path) -> list[str]: or verifiers[0].get("shell") != "bash" or "if" in verifiers[0]): errors.append("required-checks must unconditionally verify actual needs and preserve its exit status") errors.extend(check_lint_lane(jobs)) + errors.extend(check_advisories_lane(jobs)) errors.extend(check_plan_contract_marker(jobs)) matrix = jobs.get("test-and-lint-protocols", {}).get("strategy", {}).get("matrix", {}) features = matrix.get("features", []) diff --git a/scripts/security/check_advisories.py b/scripts/security/check_advisories.py new file mode 100755 index 0000000000..b3df412d97 --- /dev/null +++ b/scripts/security/check_advisories.py @@ -0,0 +1,1597 @@ +#!/usr/bin/env python3 +# Copyright 2026 RustFS Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Fail-closed RustSec advisories and time-bounded exception gate (rustfs/backlog#2668).""" +from __future__ import annotations + +import argparse +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import tomllib +import unittest +from typing import Any + +ROOT = Path(__file__).resolve().parents[2] +DEFAULT_DENY_CONFIG = "deny.toml" +DEFAULT_EXCEPTIONS_CONFIG = ".config/advisory-exceptions.toml" +DEFAULT_CARGO_LOCK = "Cargo.lock" +DEFAULT_CARGO_MANIFEST = "Cargo.toml" +DEFAULT_ADVISORY_DB_URL = "https://github.com/RustSec/advisory-db" + +EXPECTED_CARGO_DENY_VERSION = "0.20.2" +SCHEMA_VERSION = 1 +MAX_VALIDITY_DAYS = 90 +MAX_CACHE_AGE_SECONDS = 24 * 60 * 60 +MAX_FUTURE_CLOCK_SKEW_SECONDS = 60 +MAX_CHAINS_PER_ADVISORY = 32 + +EXIT_OK = 0 +EXIT_ADVISORY_FOUND = 10 +EXIT_POLICY_ERROR = 11 +EXIT_EXCEPTION_EXPIRED = 12 +EXIT_INFRA_ERROR = 13 + +REQUIRED_EXCEPTION_FIELDS = frozenset({ + "advisory_id", + "crate", + "affected_versions", + "owner", + "tracking_issue", + "reason", + "mitigation", + "approved_at", + "expires_at", + "approval_reference", +}) + +ADVISORY_ID_RE = re.compile( + r"^(?:RUSTSEC-\d{4}-\d{4}|GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}|CVE-\d{4}-\d{4,})$" +) +CRATE_NAME_RE = re.compile(r"^[A-Za-z0-9_-]+$") +OWNER_RE = re.compile(r"^@?[A-Za-z0-9](?:[A-Za-z0-9_/-]{0,62}[A-Za-z0-9])?$") +PLACEHOLDER_VALUES = frozenset({"tbd", "todo", "none", "n/a", "na", "unknown", "pending"}) +TRACKING_ISSUE_RE = re.compile(r"^https://github\.com/rustfs/[A-Za-z0-9_.-]+/issues/[1-9][0-9]*$") +APPROVAL_REF_RE = re.compile( + r"^https://github\.com/rustfs/(?P[A-Za-z0-9_.-]+)/(?Ppull|issues)/(?P[1-9][0-9]*)" + r"(?:(?P#(?:pullrequestreview|issuecomment)-[1-9][0-9]*))?$" +) +UTC_TIMESTAMP_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$") +SHA40_RE = re.compile(r"^[0-9a-f]{40}$") +SEMVER_RE = re.compile( + r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)" + r"(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$" +) +CLAUSE_RE = re.compile(r"^(<=|>=|=|<|>)\s*(\S+)$") +FORBIDDEN_BLANKET_LEVELS = ("vulnerability", "unmaintained", "unsound", "notice") +TRUSTED_APPROVER_ASSOCIATIONS = frozenset({"OWNER", "MEMBER"}) + +SECRET_PATTERNS = ( + re.compile(r"(?i)(authorization:\s*(?:bearer|token|basic)\s+)\S+"), + re.compile(r"(?i)(x-access-token:)[^\s@]+"), + re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})\b"), + re.compile(r"\bAKIA[0-9A-Z]{16}\b"), +) + + +def sanitize_text(text: str) -> str: + cleaned = text + for pattern in SECRET_PATTERNS: + cleaned = pattern.sub(lambda m: (m.group(1) if m.lastindex else "") + "", cleaned) + return cleaned + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(65536), b""): + digest.update(chunk) + return digest.hexdigest() + + +def parse_utc(value: Any, field: str) -> datetime: + if not isinstance(value, str) or not UTC_TIMESTAMP_RE.fullmatch(value): + raise ValueError(f"{field} must be a strict UTC RFC 3339 timestamp (YYYY-MM-DDTHH:MM:SSZ)") + try: + return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) + except ValueError as exc: + raise ValueError(f"{field} is not a valid calendar UTC timestamp: {value!r}") from exc + + +def format_utc(value: datetime) -> str: + return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +@dataclass(frozen=True, order=True) +class SemVer: + major: int + minor: int + patch: int + prerelease: tuple[tuple[int, int | str], ...] = () + + @classmethod + def parse(cls, raw: str) -> "SemVer": + match = SEMVER_RE.fullmatch(raw.strip()) + if not match: + raise ValueError(f"invalid SemVer version: {raw!r}") + major, minor, patch = int(match.group(1)), int(match.group(2)), int(match.group(3)) + pre_raw = match.group(4) + if pre_raw is None: + # Release versions sort after any pre-release of the same core triple. + pre: tuple[tuple[int, int | str], ...] = ((2, ""),) + else: + parts = [] + for ident in pre_raw.split("."): + if not ident: + raise ValueError(f"invalid SemVer prerelease identifier in {raw!r}") + if ident.isdigit(): + if len(ident) > 1 and ident.startswith("0"): + raise ValueError(f"leading zero in numeric SemVer prerelease in {raw!r}") + parts.append((0, int(ident))) + else: + parts.append((1, ident)) + pre = tuple(parts) + return cls(major=major, minor=minor, patch=patch, prerelease=pre) + + +@dataclass(frozen=True) +class VersionInterval: + lower: SemVer | None + lower_inclusive: bool + upper: SemVer + upper_inclusive: bool + raw: str + + @classmethod + def parse(cls, raw: Any) -> "VersionInterval": + if not isinstance(raw, str) or not raw.strip(): + raise ValueError("affected_versions must be a non-empty version constraint string") + if "*" in raw: + raise ValueError("affected_versions must not contain wildcards ('*')") + clauses = [part.strip() for part in raw.split(",")] + if not clauses or any(not clause for clause in clauses): + raise ValueError(f"malformed affected_versions constraint: {raw!r}") + lower: SemVer | None = None + lower_inc = True + upper: SemVer | None = None + upper_inc = False + for clause in clauses: + match = CLAUSE_RE.fullmatch(clause) + if not match: + raise ValueError( + f"affected_versions clause {clause!r} must use explicit operator (=, <, <=, >, >=) and exact SemVer" + ) + op, ver_str = match.group(1), match.group(2) + ver = SemVer.parse(ver_str) + if op == "=": + if lower is None or ver > lower or (ver == lower and not lower_inc): + lower, lower_inc = ver, True + if upper is None or ver < upper or (ver == upper and not upper_inc): + upper, upper_inc = ver, True + elif op == ">=": + if lower is None or ver > lower: + lower, lower_inc = ver, True + elif op == ">": + if lower is None or ver > lower or (ver == lower and lower_inc): + lower, lower_inc = ver, False + elif op == "<=": + if upper is None or ver < upper: + upper, upper_inc = ver, True + elif op == "<": + if upper is None or ver < upper or (ver == upper and upper_inc): + upper, upper_inc = ver, False + if upper is None: + raise ValueError(f"affected_versions must specify a finite upper bound (=, <, or <=): {raw!r}") + if lower is not None: + if lower > upper or (lower == upper and not (lower_inc and upper_inc)): + raise ValueError(f"affected_versions defines an empty version range: {raw!r}") + return cls(lower=lower, lower_inclusive=lower_inc, upper=upper, upper_inclusive=upper_inc, raw=raw.strip()) + + def contains(self, version_str: str) -> bool: + ver = SemVer.parse(version_str) + if self.lower is not None: + if ver < self.lower or (ver == self.lower and not self.lower_inclusive): + return False + if ver > self.upper or (ver == self.upper and not self.upper_inclusive): + return False + return True + + def is_subset_of(self, other: "VersionInterval") -> bool: + if other.lower is not None: + if self.lower is None: + return False + if self.lower < other.lower: + return False + if self.lower == other.lower and self.lower_inclusive and not other.lower_inclusive: + return False + if self.upper > other.upper: + return False + if self.upper == other.upper and self.upper_inclusive and not other.upper_inclusive: + return False + return True + + +def parse_deny_config(text: str) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, dict[str, Any]]]: + try: + doc = tomllib.loads(text) + except tomllib.TOMLDecodeError as exc: + raise ValueError(f"invalid deny.toml TOML: {exc}") from exc + if not isinstance(doc, dict): + raise ValueError("deny.toml root must be a table") + errors: list[dict[str, Any]] = [] + graph = doc.get("graph") + if not isinstance(graph, dict): + errors.append({"code": "config_weakened", "message": "deny.toml must define [graph] table"}) + graph = {} + if graph.get("all-features") is not True: + errors.append({"code": "config_weakened", "message": "deny.toml [graph].all-features must remain true"}) + if graph.get("no-default-features") is not False: + errors.append({"code": "config_weakened", "message": "deny.toml [graph].no-default-features must remain false"}) + + advisories = doc.get("advisories") + if not isinstance(advisories, dict): + errors.append({"code": "config_weakened", "message": "deny.toml must define [advisories] table"}) + advisories = {} + if advisories.get("version") != 2: + errors.append({"code": "config_weakened", "message": "deny.toml [advisories].version must be 2"}) + if advisories.get("yanked") != "deny": + errors.append({"code": "config_weakened", "message": "deny.toml [advisories].yanked must remain 'deny'"}) + for key in FORBIDDEN_BLANKET_LEVELS: + if key in advisories and advisories[key] != "deny": + errors.append({ + "code": "config_weakened", + "message": f"deny.toml [advisories].{key} cannot be weakened to {advisories[key]!r}", + }) + + raw_ignores = advisories.get("ignore", []) + ignores: dict[str, dict[str, Any]] = {} + if not isinstance(raw_ignores, list): + errors.append({"code": "config_invalid", "message": "deny.toml [advisories].ignore must be a list"}) + raw_ignores = [] + for index, item in enumerate(raw_ignores): + if isinstance(item, str): + errors.append({ + "code": "bare_deny_ignore", + "message": f"deny.toml [advisories].ignore[{index}] uses bare string {item!r}; structured {{ id, reason }} entry required", + "advisory_id": item, + }) + if item in ignores: + errors.append({ + "code": "duplicate_deny_ignore", + "message": f"duplicate advisory ignore {item!r} in deny.toml", + "advisory_id": item, + }) + else: + ignores[item] = {"id": item, "reason": ""} + continue + if not isinstance(item, dict): + errors.append({ + "code": "config_invalid", + "message": f"deny.toml [advisories].ignore[{index}] must be a table", + }) + continue + adv_id = item.get("id") + reason = item.get("reason") + if not isinstance(adv_id, str) or not ADVISORY_ID_RE.fullmatch(adv_id): + errors.append({ + "code": "config_invalid", + "message": f"deny.toml [advisories].ignore[{index}] has invalid advisory id: {adv_id!r}", + }) + continue + if not isinstance(reason, str) or not reason.strip(): + errors.append({ + "code": "bare_deny_ignore", + "message": f"deny.toml [advisories].ignore entry for {adv_id} must include a non-empty reason", + "advisory_id": adv_id, + }) + if adv_id in ignores: + errors.append({ + "code": "duplicate_deny_ignore", + "message": f"duplicate advisory ignore {adv_id} in deny.toml", + "advisory_id": adv_id, + }) + continue + ignores[adv_id] = dict(item) + return doc, errors, ignores + + +def format_toml_key(key: str) -> str: + if re.fullmatch(r"[A-Za-z0-9_-]+", key): + return key + return json.dumps(key) + + +def format_toml_value(value: Any) -> str: + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, int): + return str(value) + if isinstance(value, float): + return repr(value) + if isinstance(value, str): + return json.dumps(value) + if isinstance(value, list): + return "[" + ", ".join(format_toml_value(item) for item in value) + "]" + if isinstance(value, dict): + items = ", ".join(f"{format_toml_key(k)} = {format_toml_value(v)}" for k, v in value.items()) + return "{ " + items + " }" + raise ValueError(f"unsupported TOML value type in deny.toml: {type(value).__name__}") + + +def strip_advisory_ignores_toml(text: str) -> str: + """Create a temporary deny.toml copy with [advisories].ignore emptied, preserving [graph] and [advisories].""" + doc = tomllib.loads(text) + lines: list[str] = [] + graph = doc.get("graph", {}) + lines.append("[graph]") + for key, val in graph.items(): + lines.append(f"{format_toml_key(key)} = {format_toml_value(val)}") + advisories = doc.get("advisories", {}) + lines.append("") + lines.append("[advisories]") + for key, val in advisories.items(): + if key == "ignore": + continue + lines.append(f"{format_toml_key(key)} = {format_toml_value(val)}") + lines.append("ignore = []") + return "\n".join(lines) + "\n" + + +def parse_exceptions_registry(text: str) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]: + try: + doc = tomllib.loads(text) + except tomllib.TOMLDecodeError as exc: + return {}, [{"code": "invalid_exception_schema", "message": f"invalid advisory-exceptions.toml TOML: {exc}"}] + if not isinstance(doc, dict): + return {}, [{"code": "invalid_exception_schema", "message": "advisory-exceptions.toml root must be a table"}] + errors: list[dict[str, Any]] = [] + unknown_top = sorted(set(doc.keys()) - {"schema_version", "exceptions"}) + if unknown_top: + errors.append({ + "code": "invalid_exception_schema", + "message": f"unknown top-level keys in advisory-exceptions.toml: {unknown_top}", + }) + if type(doc.get("schema_version")) is not int or doc.get("schema_version") != SCHEMA_VERSION: + errors.append({ + "code": "invalid_exception_schema", + "message": f"advisory-exceptions.toml schema_version must be integer {SCHEMA_VERSION}", + }) + raw_entries = doc.get("exceptions") + if raw_entries is None: + raw_entries = [] + if not isinstance(raw_entries, list): + errors.append({ + "code": "invalid_exception_schema", + "message": "advisory-exceptions.toml `exceptions` must be a list of tables", + }) + return {}, errors + + entries: dict[str, dict[str, Any]] = {} + for index, raw in enumerate(raw_entries): + if not isinstance(raw, dict): + errors.append({ + "code": "invalid_exception_schema", + "message": f"exceptions[{index}] must be a TOML table", + }) + continue + keys = set(raw.keys()) + missing = sorted(REQUIRED_EXCEPTION_FIELDS - keys) + unknown = sorted(keys - REQUIRED_EXCEPTION_FIELDS) + adv_id = raw.get("advisory_id") if isinstance(raw.get("advisory_id"), str) else f"index:{index}" + if missing: + errors.append({ + "code": "invalid_exception_schema", + "advisory_id": adv_id, + "message": f"exception {adv_id} missing required fields: {missing}", + }) + if unknown: + errors.append({ + "code": "invalid_exception_schema", + "advisory_id": adv_id, + "message": f"exception {adv_id} has unknown fields: {unknown}", + }) + + entry_errors: list[dict[str, Any]] = [] + if not isinstance(raw.get("advisory_id"), str) or not ADVISORY_ID_RE.fullmatch(raw["advisory_id"]): + entry_errors.append({ + "code": "invalid_exception_field", + "advisory_id": adv_id, + "message": f"invalid advisory_id: {raw.get('advisory_id')!r}", + }) + crate = raw.get("crate") + if not isinstance(crate, str) or not CRATE_NAME_RE.fullmatch(crate): + entry_errors.append({ + "code": "invalid_exception_field", + "advisory_id": adv_id, + "message": f"invalid crate name: {crate!r}", + }) + interval: VersionInterval | None = None + try: + interval = VersionInterval.parse(raw.get("affected_versions")) + except ValueError as exc: + entry_errors.append({ + "code": "invalid_version_range", + "advisory_id": adv_id, + "message": str(exc), + }) + owner = raw.get("owner") + if not isinstance(owner, str) or not OWNER_RE.fullmatch(owner.strip()) or owner.strip().lower() in PLACEHOLDER_VALUES: + entry_errors.append({ + "code": "invalid_exception_field", + "advisory_id": adv_id, + "message": f"invalid owner: {owner!r}", + }) + tracking_issue = raw.get("tracking_issue") + if not isinstance(tracking_issue, str) or not TRACKING_ISSUE_RE.fullmatch(tracking_issue.strip()): + entry_errors.append({ + "code": "invalid_exception_field", + "advisory_id": adv_id, + "message": f"tracking_issue must be a rustfs GitHub issue URL: {tracking_issue!r}", + }) + for text_field in ("reason", "mitigation"): + text_val = raw.get(text_field) + if ( + not isinstance(text_val, str) + or len(text_val.strip()) < 16 + or text_val.strip().lower() in PLACEHOLDER_VALUES + ): + entry_errors.append({ + "code": "invalid_exception_field", + "advisory_id": adv_id, + "message": f"{text_field} must be a non-placeholder explanation of at least 16 characters", + }) + approval_ref = raw.get("approval_reference") + if not isinstance(approval_ref, str) or not APPROVAL_REF_RE.fullmatch(approval_ref.strip()): + entry_errors.append({ + "code": "invalid_exception_field", + "advisory_id": adv_id, + "message": f"approval_reference must be a rustfs GitHub PR or review/comment URL: {approval_ref!r}", + }) + + approved_dt: datetime | None = None + expires_dt: datetime | None = None + try: + approved_dt = parse_utc(raw.get("approved_at"), "approved_at") + except ValueError as exc: + entry_errors.append({"code": "invalid_timestamp", "advisory_id": adv_id, "message": str(exc)}) + try: + expires_dt = parse_utc(raw.get("expires_at"), "expires_at") + except ValueError as exc: + entry_errors.append({"code": "invalid_timestamp", "advisory_id": adv_id, "message": str(exc)}) + if approved_dt is not None and expires_dt is not None: + if expires_dt <= approved_dt: + entry_errors.append({ + "code": "invalid_validity_window", + "advisory_id": adv_id, + "message": f"expires_at ({raw['expires_at']}) must be after approved_at ({raw['approved_at']})", + }) + elif expires_dt - approved_dt > timedelta(days=MAX_VALIDITY_DAYS): + entry_errors.append({ + "code": "validity_window_exceeded", + "advisory_id": adv_id, + "message": ( + f"exception {adv_id} validity window exceeds {MAX_VALIDITY_DAYS} days " + f"({raw['approved_at']} -> {raw['expires_at']})" + ), + }) + + errors.extend(entry_errors) + if isinstance(raw.get("advisory_id"), str) and ADVISORY_ID_RE.fullmatch(raw["advisory_id"]): + key = raw["advisory_id"] + if key in entries: + errors.append({ + "code": "duplicate_exception", + "advisory_id": key, + "message": f"duplicate exception entry for {key} in advisory-exceptions.toml", + }) + else: + entries[key] = { + **raw, + "_interval": interval, + "_approved_dt": approved_dt, + "_expires_dt": expires_dt, + "_errors": list(entry_errors), + } + return entries, errors + + +def run_git(repo_root: Path, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + ["git", *args], + cwd=repo_root, + capture_output=True, + text=True, + timeout=30, + check=False, + ) + + +def git_head_sha(repo_root: Path) -> str | None: + proc = run_git(repo_root, "rev-parse", "HEAD") + if proc.returncode == 0: + sha = proc.stdout.strip() + if SHA40_RE.fullmatch(sha): + return sha + return None + + +def git_show_optional(repo_root: Path, revision: str, rel_path: str) -> tuple[bool, str]: + proc = run_git(repo_root, "show", f"{revision}:{rel_path}") + if proc.returncode == 0: + return True, proc.stdout + return False, proc.stderr.strip() + + +def normalize_git_url(url: str) -> str: + cleaned = url.strip().rstrip("/") + if cleaned.endswith(".git"): + cleaned = cleaned[:-4] + return cleaned.lower() + + +def find_advisory_db_dir( + repo_root: Path, + deny_doc: dict[str, Any], + explicit_dir: Path | None, + expected_url: str, +) -> Path | None: + if explicit_dir is not None: + return explicit_dir + advisories = deny_doc.get("advisories", {}) if isinstance(deny_doc, dict) else {} + db_path = advisories.get("db-path") + if isinstance(db_path, str) and db_path.strip(): + candidate = Path(db_path).expanduser() + if not candidate.is_absolute(): + candidate = (repo_root / candidate).resolve() + return candidate + cargo_home = Path(os.environ.get("CARGO_HOME") or (Path.home() / ".cargo")) + dbs_root = cargo_home / "advisory-dbs" + if not dbs_root.is_dir(): + return None + expected_norm = normalize_git_url(expected_url) + matches: list[tuple[float, Path]] = [] + for child in sorted(dbs_root.iterdir()): + if not child.is_dir() or not (child / ".git").exists(): + continue + remote = run_git(child, "remote", "get-url", "origin") + if remote.returncode == 0 and normalize_git_url(remote.stdout) == expected_norm: + fetch_head = child / ".git" / "FETCH_HEAD" + mtime = fetch_head.stat().st_mtime if fetch_head.is_file() else child.stat().st_mtime + matches.append((mtime, child)) + if not matches: + return None + matches.sort(key=lambda item: item[0], reverse=True) + return matches[0][1] + + +def inspect_advisory_db( + db_dir: Path | None, + expected_url: str, + now: datetime, + *, + fresh_fetch: bool, + fetch_error: str | None = None, +) -> tuple[dict[str, Any], list[dict[str, Any]]]: + info: dict[str, Any] = { + "url": expected_url, + "path_label": db_dir.name if db_dir is not None else None, + "revision": None, + "commit_timestamp": None, + "fetched_at": None, + "freshness_source": "live_fetch" if fresh_fetch else "cached_fallback", + "used_cached_db": not fresh_fetch, + "cache_age_seconds": None, + "max_cache_age_seconds": MAX_CACHE_AGE_SECONDS, + } + if fetch_error: + info["fetch_error"] = sanitize_text(fetch_error) + errors: list[dict[str, Any]] = [] + if db_dir is None or not db_dir.is_dir() or not (db_dir / ".git").exists(): + errors.append({ + "code": "advisory_db_unavailable", + "message": "advisory database git checkout not found; cannot verify revision or freshness", + }) + return info, errors + remote = run_git(db_dir, "remote", "get-url", "origin") + if remote.returncode != 0 or normalize_git_url(remote.stdout) != normalize_git_url(expected_url): + errors.append({ + "code": "untrusted_advisory_db", + "message": ( + f"advisory database remote {remote.stdout.strip()!r} does not match expected {expected_url!r}" + ), + }) + return info, errors + head_proc = run_git(db_dir, "rev-parse", "HEAD") + rev = head_proc.stdout.strip() if head_proc.returncode == 0 else "" + if not SHA40_RE.fullmatch(rev): + errors.append({ + "code": "advisory_db_unavailable", + "message": "unable to resolve 40-character advisory database revision SHA", + }) + return info, errors + info["revision"] = rev + ts_proc = run_git(db_dir, "show", "-s", "--format=%cI", "HEAD") + if ts_proc.returncode == 0 and ts_proc.stdout.strip(): + info["commit_timestamp"] = ts_proc.stdout.strip() + + if fresh_fetch: + info["fetched_at"] = format_utc(now) + info["cache_age_seconds"] = 0 + return info, errors + + fetch_head = db_dir / ".git" / "FETCH_HEAD" + if not fetch_head.is_file() or fetch_head.stat().st_size == 0: + errors.append({ + "code": "stale_or_untrusted_advisory_db", + "message": "advisory database fetch failed and local cache has no verifiable FETCH_HEAD timestamp", + }) + return info, errors + fetched_dt = datetime.fromtimestamp(fetch_head.stat().st_mtime, tz=timezone.utc) + info["fetched_at"] = format_utc(fetched_dt) + age_seconds = int((now - fetched_dt).total_seconds()) + info["cache_age_seconds"] = age_seconds + if age_seconds < -MAX_FUTURE_CLOCK_SKEW_SECONDS: + errors.append({ + "code": "stale_or_untrusted_advisory_db", + "message": f"cached advisory database FETCH_HEAD timestamp {info['fetched_at']} is in the future", + }) + elif age_seconds > MAX_CACHE_AGE_SECONDS: + errors.append({ + "code": "stale_or_untrusted_advisory_db", + "message": ( + f"advisory database fetch failed and cached DB is stale ({age_seconds}s > {MAX_CACHE_AGE_SECONDS}s)" + ), + }) + return info, errors + + +def check_cargo_deny_version(cargo_deny_bin: str, expected_version: str) -> tuple[str | None, list[dict[str, Any]]]: + cmd = [cargo_deny_bin, "--version"] + try: + proc = subprocess.run(cmd, capture_output=True, text=True, timeout=30, check=False) + except OSError as exc: + return None, [{"code": "tool_unavailable", "message": f"failed to execute {cargo_deny_bin}: {exc}"}] + if proc.returncode != 0: + return None, [{ + "code": "tool_unavailable", + "message": f"{cargo_deny_bin} --version failed (exit {proc.returncode}): {sanitize_text(proc.stderr.strip())}", + }] + output = (proc.stdout or proc.stderr).strip() + match = re.search(r"cargo-deny\s+([0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?)", output) + if not match: + return output, [{"code": "tool_version_mismatch", "message": f"unparseable cargo-deny version: {output!r}"}] + actual = match.group(1) + if actual != expected_version: + return actual, [{ + "code": "tool_version_mismatch", + "message": f"cargo-deny version {actual} does not match pinned version {expected_version}", + }] + return actual, [] + + +def extract_chains(graphs: list[dict[str, Any]]) -> tuple[list[str], list[str]]: + versions: set[str] = set() + chains: list[str] = [] + + def walk(node: dict[str, Any], path: list[str]) -> None: + if len(chains) >= MAX_CHAINS_PER_ADVISORY: + return + krate = node.get("Krate") + if not isinstance(krate, dict): + return + name = str(krate.get("name", "")) + ver = str(krate.get("version", "")) + kind = krate.get("kind") + label = f"{name} {ver}" + (f" ({kind})" if kind else "") + next_path = [*path, label] + parents = node.get("parents") + if not parents: + chains.append(" <- ".join(next_path)) + return + for parent in parents: + if isinstance(parent, dict): + walk(parent, next_path) + if len(chains) >= MAX_CHAINS_PER_ADVISORY: + return + + for root in graphs: + if not isinstance(root, dict): + continue + krate = root.get("Krate") + if isinstance(krate, dict) and isinstance(krate.get("version"), str): + versions.add(krate["version"]) + walk(root, []) + return sorted(versions), chains + + +def parse_cargo_deny_jsonl(output: str) -> tuple[list[dict[str, Any]], dict[str, Any] | None, list[dict[str, Any]]]: + diagnostics: list[dict[str, Any]] = [] + summary: dict[str, Any] | None = None + parse_errors: list[dict[str, Any]] = [] + for raw_line in output.splitlines(): + line = raw_line.strip() + if not line: + continue + try: + obj = json.loads(line) + except json.JSONDecodeError: + parse_errors.append({ + "code": "scan_output_unparseable", + "message": f"non-JSON line in cargo-deny output: {sanitize_text(line[:180])}", + }) + continue + if not isinstance(obj, dict): + parse_errors.append({"code": "scan_output_unparseable", "message": "non-object JSON record in cargo-deny output"}) + continue + kind = obj.get("type") + fields = obj.get("fields", {}) + if kind == "summary" and isinstance(fields, dict): + summary = fields + elif kind == "diagnostic" and isinstance(fields, dict): + diagnostics.append(fields) + return diagnostics, summary, parse_errors + + +def hit_from_diagnostic(diag: dict[str, Any]) -> dict[str, Any]: + adv = diag.get("advisory") + code = str(diag.get("code", "unknown")) + graphs = diag.get("graphs") if isinstance(diag.get("graphs"), list) else [] + versions, chains = extract_chains(graphs) + crate_name = "" + if isinstance(adv, dict) and isinstance(adv.get("package"), str): + crate_name = adv["package"] + if not crate_name or not versions: + for label in diag.get("labels", []): + if isinstance(label, dict) and isinstance(label.get("span"), str): + parts = label["span"].split() + if len(parts) >= 2: + if not crate_name: + crate_name = parts[0] + if not versions: + versions = [parts[1]] + if isinstance(adv, dict) and isinstance(adv.get("id"), str): + return { + "advisory_id": adv["id"], + "code": code, + "severity": diag.get("severity", "error"), + "crate": crate_name, + "versions": versions, + "title": adv.get("title") or diag.get("message", ""), + "url": adv.get("url"), + "informational": adv.get("informational"), + "cvss": adv.get("cvss"), + "aliases": adv.get("aliases", []), + "chains": chains, + } + return { + "advisory_id": None, + "code": code, + "severity": diag.get("severity", "error"), + "crate": crate_name, + "versions": versions, + "title": diag.get("message", ""), + "url": None, + "informational": None, + "cvss": None, + "aliases": [], + "chains": chains, + } + + +def parse_github_json_object(stdout: str, endpoint: str) -> tuple[dict[str, Any] | None, str | None]: + try: + data = json.loads(stdout) + except (ValueError, TypeError): + return None, f"malformed JSON from GitHub API for {endpoint}" + if not isinstance(data, dict): + return None, f"unexpected non-object GitHub API payload for {endpoint}" + return data, None + + +def verify_github_approval( + exc: dict[str, Any], + pr_author: str | None, +) -> tuple[bool, str]: + token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") + if not token: + return False, "no GH_TOKEN available to verify approval_reference against GitHub" + match = APPROVAL_REF_RE.fullmatch(exc["approval_reference"].strip()) + if not match: + return False, "approval_reference is not a valid rustfs GitHub URL" + repo = match.group("repo") + kind = match.group("kind") + number = match.group("number") + fragment = match.group("fragment") or "" + env = { + "PATH": os.environ.get("PATH", ""), + "HOME": os.environ.get("HOME", ""), + "GH_TOKEN": token, + } + if fragment.startswith("#pullrequestreview-"): + if kind != "pull": + return False, "pullrequestreview fragment requires a pull request URL" + review_id = fragment.split("-", 1)[1] + endpoint = f"repos/rustfs/{repo}/pulls/{number}/reviews/{review_id}" + proc = subprocess.run(["gh", "api", endpoint], capture_output=True, text=True, env=env, timeout=30, check=False) + if proc.returncode != 0: + return False, f"GitHub review lookup failed for {endpoint}" + data, parse_err = parse_github_json_object(proc.stdout, endpoint) + if parse_err is not None or data is None: + return False, parse_err or f"invalid GitHub review payload for {endpoint}" + user = data.get("user") + author = user.get("login") if isinstance(user, dict) else None + assoc = data.get("author_association", "") + state = data.get("state", "") + body = data.get("body") or "" + if state != "APPROVED": + return False, f"review {review_id} state is {state!r}, not APPROVED" + if assoc not in TRUSTED_APPROVER_ASSOCIATIONS: + return False, f"reviewer {author!r} association {assoc!r} is not maintainer/owner" + if pr_author and author == pr_author: + return False, f"PR author {pr_author!r} cannot self-approve exception" + if ( + exc["advisory_id"] not in body + or exc["expires_at"][:10] not in body + or exc["affected_versions"] not in body + ): + return False, "review body must explicitly reference advisory_id, affected_versions, and expires_at date" + return True, f"verified APPROVED review {review_id} by {author} ({assoc})" + + if fragment.startswith("#issuecomment-"): + comment_id = fragment.split("-", 1)[1] + endpoint = f"repos/rustfs/{repo}/issues/comments/{comment_id}" + proc = subprocess.run(["gh", "api", endpoint], capture_output=True, text=True, env=env, timeout=30, check=False) + if proc.returncode != 0: + return False, f"GitHub comment lookup failed for {endpoint}" + data, parse_err = parse_github_json_object(proc.stdout, endpoint) + if parse_err is not None or data is None: + return False, parse_err or f"invalid GitHub comment payload for {endpoint}" + issue_url = data.get("issue_url") + expected_suffix = f"/repos/rustfs/{repo.lower()}/issues/{number}" + if not isinstance(issue_url, str) or not issue_url.rstrip("/").lower().endswith(expected_suffix): + return False, f"comment {comment_id} does not belong to rustfs/{repo}#{number}" + user = data.get("user") + author = user.get("login") if isinstance(user, dict) else None + assoc = data.get("author_association", "") + body = data.get("body") or "" + if assoc not in TRUSTED_APPROVER_ASSOCIATIONS: + return False, f"comment author {author!r} association {assoc!r} is not maintainer/owner" + if pr_author and author == pr_author: + return False, f"PR author {pr_author!r} cannot self-approve exception" + if ( + exc["advisory_id"] not in body + or exc["expires_at"][:10] not in body + or exc["affected_versions"] not in body + ): + return False, "approval comment must explicitly reference advisory_id, affected_versions, and expires_at date" + return True, f"verified maintainer comment {comment_id} by {author} ({assoc})" + + if kind == "pull": + endpoint = f"repos/rustfs/{repo}/pulls/{number}" + proc = subprocess.run(["gh", "api", endpoint], capture_output=True, text=True, env=env, timeout=30, check=False) + if proc.returncode != 0: + return False, f"GitHub PR lookup failed for {endpoint}" + data, parse_err = parse_github_json_object(proc.stdout, endpoint) + if parse_err is not None or data is None: + return False, parse_err or f"invalid GitHub PR payload for {endpoint}" + if not data.get("merged"): + return False, f"PR #{number} is not merged; open PR URLs require an explicit #pullrequestreview- approval" + merged_by_obj = data.get("merged_by") + merged_by = merged_by_obj.get("login") if isinstance(merged_by_obj, dict) else None + if not merged_by: + return False, f"merged PR #{number} lacks merged_by maintainer attribution" + pr_user = data.get("user") + pr_user_login = pr_user.get("login") if isinstance(pr_user, dict) else None + if pr_author and merged_by == pr_author and pr_user_login == pr_author: + return False, f"PR author {pr_author!r} cannot self-approve via self-merged PR" + body = data.get("body") or "" + if ( + exc["advisory_id"] not in body + or exc["expires_at"][:10] not in body + or exc["affected_versions"] not in body + ): + return ( + False, + f"merged PR #{number} body does not explicitly name advisory_id, affected_versions, and expires_at date; " + "cite a specific maintainer #pullrequestreview- or #issuecomment-", + ) + return True, f"verified merged PR #{number} merged by {merged_by}" + + return False, "bare issue URL is not an approval record; cite a maintainer #issuecomment- or #pullrequestreview-" + + +def verify_trusted_approval( + exc: dict[str, Any], + trusted_records: list[dict[str, Any]] | None, + pr_author: str | None, +) -> tuple[bool, str]: + if trusted_records is not None: + head_interval: VersionInterval | None = exc.get("_interval") + head_expires: datetime | None = exc.get("_expires_dt") + for record in trusted_records: + if not isinstance(record, dict): + continue + if ( + record.get("approval_reference") != exc.get("approval_reference") + or record.get("advisory_id") != exc.get("advisory_id") + or record.get("crate") != exc.get("crate") + ): + continue + if record.get("approver_association") not in TRUSTED_APPROVER_ASSOCIATIONS: + return False, f"approver association {record.get('approver_association')!r} is not trusted" + if pr_author and record.get("approver") == pr_author: + return False, f"PR author {pr_author!r} cannot self-approve exception" + if record.get("state") not in {"APPROVED", "MERGED"}: + return False, f"approval state {record.get('state')!r} is not APPROVED/MERGED" + try: + rec_interval = VersionInterval.parse(record.get("affected_versions")) + rec_expires = parse_utc(record.get("expires_at"), "trusted_approval.expires_at") + except ValueError as exc_err: + return False, f"invalid trusted approval record: {exc_err}" + if head_interval is None or not head_interval.is_subset_of(rec_interval): + return False, "exception affected_versions widens beyond trusted approval record" + if head_expires is None or head_expires > rec_expires: + return False, "exception expires_at exceeds trusted approval record" + return True, f"verified trusted approval by {record.get('approver')}" + return False, "no matching trusted approval record found" + return verify_github_approval(exc, pr_author) + + +def check_base_diff_approvals( + repo_root: Path, + base_ref: str, + head_exceptions: dict[str, dict[str, Any]], + deny_rel_path: str, + exceptions_rel_path: str, + trusted_records: list[dict[str, Any]] | None, + pr_author: str | None, +) -> tuple[dict[str, list[str]], list[dict[str, Any]]]: + """Compare head exceptions against base_ref and require trusted approval for new/widened/extended items.""" + per_id_reasons: dict[str, list[str]] = {} + errors: list[dict[str, Any]] = [] + + verify_ref = run_git(repo_root, "rev-parse", "--verify", f"{base_ref}^{{commit}}") + if verify_ref.returncode != 0: + errors.append({ + "code": "base_ref_unavailable", + "message": f"base commit {base_ref!r} is unavailable for PR exception diff verification", + }) + return per_id_reasons, errors + + has_base_exc, base_exc_text = git_show_optional(repo_root, base_ref, exceptions_rel_path) + has_base_deny, base_deny_text = git_show_optional(repo_root, base_ref, deny_rel_path) + + base_exceptions: dict[str, dict[str, Any]] = {} + base_deny_ignores: dict[str, dict[str, Any]] = {} + if has_base_exc: + base_exceptions, base_exc_errors = parse_exceptions_registry(base_exc_text) + if base_exc_errors: + # Corrupt base cannot authorize head changes; treat all head exceptions as requiring approval. + base_exceptions = {} + if has_base_deny: + try: + _, _, base_deny_ignores = parse_deny_config(base_deny_text) + except ValueError: + base_deny_ignores = {} + + for adv_id, exc in head_exceptions.items(): + changes: list[str] = [] + if has_base_exc: + base_exc = base_exceptions.get(adv_id) + if base_exc is None: + changes.append("added") + else: + if exc.get("crate") != base_exc.get("crate"): + changes.append("crate_changed") + head_iv, base_iv = exc.get("_interval"), base_exc.get("_interval") + if head_iv is not None and base_iv is not None and not head_iv.is_subset_of(base_iv): + changes.append("scope_widened") + head_exp, base_exp = exc.get("_expires_dt"), base_exc.get("_expires_dt") + if head_exp is not None and base_exp is not None and head_exp > base_exp: + changes.append("expiry_extended") + if exc.get("approved_at") != base_exc.get("approved_at") or exc.get("approval_reference") != base_exc.get("approval_reference"): + changes.append("approval_changed") + else: + # Initial migration PR: any advisory ignore not already in base deny.toml is a newly added exception. + if adv_id not in base_deny_ignores: + changes.append("added") + + if not changes: + continue + + ok, detail = verify_trusted_approval(exc, trusted_records, pr_author) + if not ok: + code = "widened_exception_scope" if "scope_widened" in changes else "unapproved_exception_change" + per_id_reasons.setdefault(adv_id, []).append(code) + errors.append({ + "code": code, + "advisory_id": adv_id, + "crate": exc.get("crate"), + "message": f"exception {adv_id} changed ({','.join(changes)}) without trusted approval: {detail}", + }) + return per_id_reasons, errors + + +def read_pr_author_from_event() -> str | None: + event_path = os.environ.get("GITHUB_EVENT_PATH") + if not event_path: + return None + try: + payload = json.loads(Path(event_path).read_text(encoding="utf-8")) + return (payload.get("pull_request") or {}).get("user", {}).get("login") + except (OSError, ValueError, AttributeError): + return None + + +def run_gate(args: argparse.Namespace) -> tuple[dict[str, Any], int]: + repo_root = Path(args.repo_root).resolve() + deny_path = (repo_root / args.deny_config).resolve() + exceptions_path = (repo_root / args.exceptions_config).resolve() + lock_path = (repo_root / args.cargo_lock).resolve() + manifest_path = (repo_root / args.manifest_path).resolve() + + in_github_actions = os.environ.get("GITHUB_ACTIONS", "").lower() == "true" + policy_errors: list[dict[str, Any]] = [] + infra_errors: list[dict[str, Any]] = [] + advisory_errors: list[dict[str, Any]] = [] + expiry_errors: list[dict[str, Any]] = [] + + if args.now is not None: + if in_github_actions and not args.allow_ci_clock_override_for_test: + policy_errors.append({ + "code": "untrusted_clock_override", + "message": "--now clock override is forbidden under GITHUB_ACTIONS", + }) + now = datetime.now(timezone.utc) + clock_source = "rejected_override" + else: + try: + now = parse_utc(args.now, "--now") + clock_source = "injected_test_clock" + except ValueError as exc: + policy_errors.append({"code": "invalid_timestamp", "message": str(exc)}) + now = datetime.now(timezone.utc) + clock_source = "system_utc_fallback" + else: + now = datetime.now(timezone.utc) + clock_source = "system_utc" + + digests: dict[str, str | None] = { + "cargo_lock_sha256": None, + "deny_toml_sha256": None, + "exceptions_toml_sha256": None, + } + for key, path in ( + ("cargo_lock_sha256", lock_path), + ("deny_toml_sha256", deny_path), + ("exceptions_toml_sha256", exceptions_path), + ): + if not path.is_file(): + infra_errors.append({"code": "missing_input_file", "message": f"required file missing: {path.name}"}) + else: + digests[key] = sha256_file(path) + + deny_doc: dict[str, Any] = {} + deny_ignores: dict[str, dict[str, Any]] = {} + deny_text = "" + if deny_path.is_file(): + deny_text = deny_path.read_text(encoding="utf-8") + try: + deny_doc, deny_cfg_errors, deny_ignores = parse_deny_config(deny_text) + policy_errors.extend(deny_cfg_errors) + except ValueError as exc: + policy_errors.append({"code": "config_invalid", "message": str(exc)}) + + exceptions: dict[str, dict[str, Any]] = {} + if exceptions_path.is_file(): + exc_text = exceptions_path.read_text(encoding="utf-8") + exceptions, exc_parse_errors = parse_exceptions_registry(exc_text) + policy_errors.extend(exc_parse_errors) + + # Bidirectional consistency between deny.toml [advisories].ignore and .config/advisory-exceptions.toml. + deny_ids = set(deny_ignores.keys()) + exc_ids = set(exceptions.keys()) + for adv_id in sorted(deny_ids - exc_ids): + policy_errors.append({ + "code": "untracked_deny_ignore", + "advisory_id": adv_id, + "message": f"advisory {adv_id} is ignored in deny.toml without a matching record in {args.exceptions_config}", + }) + for adv_id in sorted(exc_ids - deny_ids): + policy_errors.append({ + "code": "missing_deny_ignore", + "advisory_id": adv_id, + "message": f"exception {adv_id} is registered in {args.exceptions_config} but missing from deny.toml [advisories].ignore", + }) + + # Clock-based approval & expiry validation on every registered exception. + expired_ids: set[str] = set() + invalid_time_ids: set[str] = set() + for adv_id, exc in sorted(exceptions.items()): + approved_dt = exc.get("_approved_dt") + expires_dt = exc.get("_expires_dt") + if approved_dt is not None and now < approved_dt: + invalid_time_ids.add(adv_id) + policy_errors.append({ + "code": "invalid_approval_timestamp", + "advisory_id": adv_id, + "crate": exc.get("crate"), + "message": f"exception {adv_id} approved_at ({exc['approved_at']}) is after current UTC time ({format_utc(now)})", + }) + if expires_dt is not None and now >= expires_dt: + expired_ids.add(adv_id) + expiry_errors.append({ + "code": "exception_expired", + "advisory_id": adv_id, + "crate": exc.get("crate"), + "message": ( + f"exception {adv_id} for {exc.get('crate')} ({exc.get('affected_versions')}) " + f"expired at {exc['expires_at']} (evaluated at {format_utc(now)})" + ), + }) + + # Optional PR base-commit comparison for newly added / widened / extended exceptions. + base_ref = (args.base_ref or os.environ.get("CI_BASE_SHA") or "").strip() + trusted_records: list[dict[str, Any]] | None = None + if args.trusted_approvals_json: + try: + loaded = json.loads(Path(args.trusted_approvals_json).read_text(encoding="utf-8")) + if not isinstance(loaded, list): + raise ValueError("trusted-approvals-json must contain a JSON array") + trusted_records = loaded + except (OSError, ValueError) as exc_err: + policy_errors.append({"code": "invalid_trusted_approvals", "message": str(exc_err)}) + pr_author = args.pr_author or read_pr_author_from_event() + unapproved_by_id: dict[str, list[str]] = {} + if base_ref: + unapproved_by_id, base_diff_errors = check_base_diff_approvals( + repo_root, + base_ref, + exceptions, + args.deny_config, + args.exceptions_config, + trusted_records, + pr_author, + ) + policy_errors.extend(base_diff_errors) + + # Check pinned cargo-deny version. + actual_version, version_errors = check_cargo_deny_version(args.cargo_deny_bin, args.expected_cargo_deny_version) + infra_errors.extend(version_errors) + + expected_db_url = args.advisory_db_url + advisory_db_info: dict[str, Any] = { + "url": expected_db_url, + "path_label": None, + "revision": None, + "commit_timestamp": None, + "fetched_at": None, + "freshness_source": "not_run", + "used_cached_db": False, + "cache_age_seconds": None, + "max_cache_age_seconds": MAX_CACHE_AGE_SECONDS, + } + raw_log_chunks: list[str] = [] + authoritative_exit: int | None = None + probe_exit: int | None = None + advisory_hits: list[dict[str, Any]] = [] + unignored_hit_ids: set[str] = set() + + if not version_errors and deny_path.is_file() and lock_path.is_file() and manifest_path.is_file(): + # Step 1: Advisory database update (or verified <=24h cache fallback). + fresh_fetch = False + fetch_error: str | None = None + if args.offline_only: + fetch_error = "offline-only mode requested; skipped live fetch" + else: + fetch_cmd = [ + args.cargo_deny_bin, + "--locked", + "--config", + str(deny_path), + "--manifest-path", + str(manifest_path), + "fetch", + "db", + ] + try: + fetch_proc = subprocess.run(fetch_cmd, cwd=repo_root, capture_output=True, text=True, timeout=180, check=False) + raw_log_chunks.append( + f"=== fetch db (exit={fetch_proc.returncode}) ===\n{fetch_proc.stdout}{fetch_proc.stderr}\n" + ) + if fetch_proc.returncode == 0: + fresh_fetch = True + else: + fetch_error = (fetch_proc.stderr or fetch_proc.stdout).strip() or f"exit {fetch_proc.returncode}" + except (OSError, subprocess.TimeoutExpired) as exc_err: + fetch_error = str(exc_err) + raw_log_chunks.append(f"=== fetch db error ===\n{fetch_error}\n") + + db_dir = find_advisory_db_dir( + repo_root, + deny_doc, + Path(args.advisory_db_dir).resolve() if args.advisory_db_dir else None, + expected_db_url, + ) + advisory_db_info, db_errors = inspect_advisory_db( + db_dir, + expected_db_url, + now, + fresh_fetch=fresh_fetch, + fetch_error=fetch_error, + ) + infra_errors.extend(db_errors) + + # Step 2: Run cargo-deny check advisories (only if DB freshness verified). + if not db_errors: + with tempfile.TemporaryDirectory(prefix="rustfs-advisories-") as tmpdir: + tmp_root = Path(tmpdir) + metadata_arg: list[str] = [] + metadata_failed = False + if args.metadata_path: + meta_path = Path(args.metadata_path).resolve() + if not meta_path.is_file(): + infra_errors.append({"code": "metadata_failed", "message": f"metadata file not found: {meta_path}"}) + metadata_failed = True + else: + metadata_arg = ["--metadata-path", str(meta_path)] + elif not args.skip_cargo_metadata: + meta_cmd = [ + args.cargo_bin, + "metadata", + "--format-version", + "1", + "--locked", + "--manifest-path", + str(manifest_path), + "--all-features", + ] + if args.offline_only or not fresh_fetch: + meta_cmd.append("--offline") + try: + meta_proc = subprocess.run(meta_cmd, cwd=repo_root, capture_output=True, text=True, timeout=300, check=False) + if meta_proc.returncode != 0: + raw_log_chunks.append( + f"=== cargo metadata failed (exit={meta_proc.returncode}) ===\n{meta_proc.stderr}\n" + ) + infra_errors.append({ + "code": "metadata_failed", + "message": f"cargo metadata failed (exit {meta_proc.returncode}): {sanitize_text(meta_proc.stderr.strip()[:300])}", + }) + metadata_failed = True + else: + meta_file = tmp_root / "cargo-metadata.json" + meta_file.write_text(meta_proc.stdout, encoding="utf-8") + metadata_arg = ["--metadata-path", str(meta_file)] + except (OSError, subprocess.TimeoutExpired) as exc_err: + infra_errors.append({"code": "metadata_failed", "message": f"cargo metadata error: {exc_err}"}) + metadata_failed = True + + if not metadata_failed: + # 2a. Authoritative run against real deny.toml + auth_cmd = [ + args.cargo_deny_bin, + "--locked", + "--offline", + *metadata_arg, + "--config", + str(deny_path), + "--manifest-path", + str(manifest_path), + "--format", + "json", + "check", + "advisories", + ] + try: + auth_proc = subprocess.run(auth_cmd, cwd=repo_root, capture_output=True, text=True, timeout=180, check=False) + authoritative_exit = auth_proc.returncode + combined_auth = (auth_proc.stdout or "") + ("\n" + auth_proc.stderr if auth_proc.stderr else "") + raw_log_chunks.append(f"=== authoritative check (exit={authoritative_exit}) ===\n{combined_auth}\n") + auth_diags, auth_summary, auth_parse_errors = parse_cargo_deny_jsonl(combined_auth) + if auth_parse_errors: + infra_errors.extend(auth_parse_errors) + if auth_summary is None and authoritative_exit != 0 and not auth_diags: + infra_errors.append({ + "code": "cargo_deny_failed", + "message": f"cargo-deny failed without advisory diagnostics (exit {authoritative_exit})", + }) + for diag in auth_diags: + if diag.get("severity") == "error": + hit = hit_from_diagnostic(diag) + if hit["advisory_id"]: + unignored_hit_ids.add(hit["advisory_id"]) + advisory_errors.append({ + "code": "yanked_crate" if hit["code"] == "yanked" else "unexempted_advisory", + "advisory_id": hit["advisory_id"], + "crate": hit["crate"], + "message": ( + f"unexempted {hit['code']} on {hit['crate']} {','.join(hit['versions'])}: " + f"{hit['advisory_id'] or hit['title']}" + ), + }) + if authoritative_exit != 0 and not advisory_errors and not infra_errors: + infra_errors.append({ + "code": "cargo_deny_failed", + "message": f"cargo-deny returned non-zero exit code {authoritative_exit}", + }) + except (OSError, subprocess.TimeoutExpired) as exc_err: + infra_errors.append({"code": "cargo_deny_failed", "message": f"cargo-deny execution error: {exc_err}"}) + + # 2b. Unfiltered diagnostic probe with ignore=[] to capture full hit chains and verify exception scopes. + if not infra_errors and deny_text: + try: + probe_cfg = tmp_root / "deny-unfiltered.toml" + probe_cfg.write_text(strip_advisory_ignores_toml(deny_text), encoding="utf-8") + probe_cmd = [ + args.cargo_deny_bin, + "--locked", + "--offline", + *metadata_arg, + "--config", + str(probe_cfg), + "--manifest-path", + str(manifest_path), + "--format", + "json", + "check", + "advisories", + ] + probe_proc = subprocess.run(probe_cmd, cwd=repo_root, capture_output=True, text=True, timeout=180, check=False) + probe_exit = probe_proc.returncode + combined_probe = (probe_proc.stdout or "") + ("\n" + probe_proc.stderr if probe_proc.stderr else "") + raw_log_chunks.append(f"=== unfiltered probe (exit={probe_exit}) ===\n{combined_probe}\n") + probe_diags, probe_summary, probe_parse_errors = parse_cargo_deny_jsonl(combined_probe) + if probe_parse_errors: + infra_errors.extend(probe_parse_errors) + elif probe_summary is None and probe_exit != 0 and not probe_diags: + infra_errors.append({ + "code": "cargo_deny_probe_failed", + "message": f"unfiltered cargo-deny probe failed without diagnostics (exit {probe_exit})", + }) + else: + for diag in probe_diags: + if diag.get("severity") == "error": + advisory_hits.append(hit_from_diagnostic(diag)) + except (OSError, ValueError, subprocess.TimeoutExpired) as exc_err: + infra_errors.append({"code": "cargo_deny_probe_failed", "message": f"unfiltered probe error: {exc_err}"}) + + # Reconcile unfiltered hits with registered exceptions (crate name, exact affected_versions, stale exceptions). + hits_by_id: dict[str, list[dict[str, Any]]] = {} + for hit in advisory_hits: + adv_id = hit.get("advisory_id") + if adv_id: + hits_by_id.setdefault(adv_id, []).append(hit) + + exception_verdicts: list[dict[str, Any]] = [] + for adv_id, exc in sorted(exceptions.items()): + matched_hits = hits_by_id.get(adv_id, []) + matched_versions = sorted({v for h in matched_hits for v in h.get("versions", [])}) + matched_crates = sorted({h.get("crate", "") for h in matched_hits if h.get("crate")}) + entry_errs = list(exc.get("_errors", [])) + status = "valid" + + if adv_id in unapproved_by_id: + status = "unapproved_change" + for code in unapproved_by_id[adv_id]: + entry_errs.append({"code": code, "message": f"PR modification requires trusted approval ({code})"}) + + if adv_id not in deny_ids: + status = "invalid" + entry_errs.append({"code": "missing_deny_ignore", "message": "not present in deny.toml [advisories].ignore"}) + + if not infra_errors and probe_exit is not None: + if not matched_hits: + status = "stale_unused" + err = { + "code": "stale_unused_exception", + "advisory_id": adv_id, + "crate": exc.get("crate"), + "message": f"exception {adv_id} ({exc.get('crate')}) did not match any active advisory in Cargo.lock; remove stale ignore", + } + entry_errs.append(err) + policy_errors.append(err) + else: + if matched_crates != [exc.get("crate")]: + status = "scope_mismatch" + err = { + "code": "exception_scope_mismatch", + "advisory_id": adv_id, + "crate": exc.get("crate"), + "message": f"exception {adv_id} declares crate {exc.get('crate')!r}, but scan matched {matched_crates}", + } + entry_errs.append(err) + policy_errors.append(err) + interval: VersionInterval | None = exc.get("_interval") + if interval is not None: + out_of_scope = [v for v in matched_versions if not interval.contains(v)] + if out_of_scope: + status = "scope_mismatch" + err = { + "code": "exception_scope_mismatch", + "advisory_id": adv_id, + "crate": exc.get("crate"), + "message": ( + f"exception {adv_id} affected_versions {exc.get('affected_versions')!r} " + f"does not cover matched version(s): {out_of_scope}" + ), + } + entry_errs.append(err) + policy_errors.append(err) + + if adv_id in expired_ids: + status = "expired" + entry_errs.append({"code": "exception_expired", "message": f"expired at {exc.get('expires_at')}"}) + elif adv_id in invalid_time_ids or exc.get("_errors"): + status = "invalid" + + exception_verdicts.append({ + "advisory_id": adv_id, + "crate": exc.get("crate"), + "affected_versions": exc.get("affected_versions"), + "owner": exc.get("owner"), + "tracking_issue": exc.get("tracking_issue"), + "approved_at": exc.get("approved_at"), + "expires_at": exc.get("expires_at"), + "approval_reference": exc.get("approval_reference"), + "matched_versions": matched_versions, + "status": status, + "errors": [{"code": e["code"], "message": e["message"]} for e in entry_errs], + }) + + verdict_by_id = {v["advisory_id"]: v["status"] for v in exception_verdicts} + for hit in advisory_hits: + adv_id = hit.get("advisory_id") + if not adv_id or adv_id in unignored_hit_ids: + hit["disposition"] = "unexempted" + elif adv_id in verdict_by_id: + status_map = { + "valid": "exempted", + "expired": "expired_exception", + "unapproved_change": "unapproved_exception", + "scope_mismatch": "scope_mismatch", + "invalid": "invalid_exception", + "stale_unused": "stale_unused", + } + hit["disposition"] = status_map.get(verdict_by_id[adv_id], "invalid_exception") + else: + hit["disposition"] = "untracked_ignore" + + all_errors = [*infra_errors, *advisory_errors, *policy_errors, *expiry_errors] + reason_codes = sorted({e["code"] for e in all_errors}) + if infra_errors: + exit_code = EXIT_INFRA_ERROR + elif advisory_errors: + exit_code = EXIT_ADVISORY_FOUND + elif policy_errors: + exit_code = EXIT_POLICY_ERROR + elif expiry_errors: + exit_code = EXIT_EXCEPTION_EXPIRED + else: + exit_code = EXIT_OK + + raw_log_written: str | None = None + if args.raw_log: + raw_log_path = Path(args.raw_log) + raw_log_path.parent.mkdir(parents=True, exist_ok=True) + raw_log_path.write_text(sanitize_text("\n".join(raw_log_chunks)), encoding="utf-8") + raw_log_written = str(args.raw_log) + + graph_cfg = deny_doc.get("graph", {}) if isinstance(deny_doc, dict) else {} + adv_cfg = deny_doc.get("advisories", {}) if isinstance(deny_doc, dict) else {} + report = { + "schema_version": SCHEMA_VERSION, + "status": "pass" if exit_code == EXIT_OK else "fail", + "exit_code": exit_code, + "reason_codes": reason_codes, + "errors": all_errors, + "evaluated_at": format_utc(now), + "clock_source": clock_source, + "source_sha": git_head_sha(repo_root), + "base_sha": base_ref or None, + "run_identity": { + "repository": os.environ.get("GITHUB_REPOSITORY"), + "event_name": os.environ.get("GITHUB_EVENT_NAME"), + "ref": os.environ.get("GITHUB_REF"), + "run_id": os.environ.get("GITHUB_RUN_ID"), + "run_attempt": os.environ.get("GITHUB_RUN_ATTEMPT"), + "job": os.environ.get("GITHUB_JOB"), + }, + "digests": digests, + "tool": { + "name": "cargo-deny", + "expected_version": args.expected_cargo_deny_version, + "actual_version": actual_version, + "authoritative_exit_code": authoritative_exit, + "probe_exit_code": probe_exit, + }, + "graph_policy": { + "all_features": graph_cfg.get("all-features"), + "no_default_features": graph_cfg.get("no-default-features"), + "yanked": adv_cfg.get("yanked"), + "locked": True, + }, + "advisory_db": advisory_db_info, + "advisory_hits": advisory_hits, + "exceptions": exception_verdicts, + "raw_log_path": raw_log_written, + } + + if args.output: + out_path = Path(args.output) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text(json.dumps(report, indent=2, sort_keys=False) + "\n", encoding="utf-8") + + return report, exit_code + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--self-test", action="store_true", help="Run the unit test suite for this checker") + parser.add_argument("--repo-root", default=str(ROOT), help="Repository root directory") + parser.add_argument("--deny-config", default=DEFAULT_DENY_CONFIG, help="Path to deny.toml relative to repo root") + parser.add_argument( + "--exceptions-config", + default=DEFAULT_EXCEPTIONS_CONFIG, + help="Path to advisory-exceptions.toml relative to repo root", + ) + parser.add_argument("--cargo-lock", default=DEFAULT_CARGO_LOCK, help="Path to Cargo.lock relative to repo root") + parser.add_argument("--manifest-path", default=DEFAULT_CARGO_MANIFEST, help="Path to Cargo.toml relative to repo root") + parser.add_argument("--output", help="Write structured advisories-gate.json report to this path") + parser.add_argument("--raw-log", help="Write raw cargo-deny stdout/stderr log to this path") + parser.add_argument("--base-ref", default="", help="Base commit SHA for PR exception diff checks (defaults to CI_BASE_SHA)") + parser.add_argument("--trusted-approvals-json", help="Optional JSON array of verified maintainer approval records (for tests)") + parser.add_argument("--pr-author", help="Optional PR author login (defaults to GitHub Actions event payload)") + parser.add_argument("--now", help="Injected UTC RFC 3339 clock (forbidden under GITHUB_ACTIONS)") + parser.add_argument("--offline-only", action="store_true", help="Skip live DB fetch and evaluate cached DB freshness only") + parser.add_argument("--advisory-db-dir", help="Explicit advisory DB git checkout path (for tests)") + parser.add_argument("--advisory-db-url", default=DEFAULT_ADVISORY_DB_URL, help="Expected advisory DB remote URL") + parser.add_argument("--cargo-deny-bin", default="cargo-deny", help="cargo-deny executable path") + parser.add_argument("--cargo-bin", default="cargo", help="cargo executable path") + parser.add_argument("--expected-cargo-deny-version", default=EXPECTED_CARGO_DENY_VERSION, help="Pinned cargo-deny version") + parser.add_argument("--metadata-path", help="Precomputed cargo metadata JSON file") + parser.add_argument("--skip-cargo-metadata", action="store_true", help="Do not pre-run cargo metadata (for mocked tests)") + parser.add_argument("--allow-ci-clock-override-for-test", action="store_true", help=argparse.SUPPRESS) + return parser + + +def main(argv: list[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + if args.self_test: + suite = unittest.defaultTestLoader.discover(str(Path(__file__).resolve().parent), pattern="test_check_advisories.py") + result = unittest.TextTestRunner(verbosity=2).run(suite) + return 0 if result.wasSuccessful() else 1 + + report, exit_code = run_gate(args) + summary_line = ( + f"advisories-gate: status={report['status']} exit_code={exit_code} " + f"hits={len(report['advisory_hits'])} exceptions={len(report['exceptions'])} " + f"reasons={','.join(report['reason_codes']) or 'none'}" + ) + print(summary_line) + for err in report["errors"]: + print(f"ERROR [{err['code']}]: {err['message']}", file=sys.stderr) + return exit_code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/security/test_check_advisories.py b/scripts/security/test_check_advisories.py new file mode 100755 index 0000000000..23df372290 --- /dev/null +++ b/scripts/security/test_check_advisories.py @@ -0,0 +1,689 @@ +#!/usr/bin/env python3 +# Copyright 2026 RustFS Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contract and negative tests for scripts/security/check_advisories.py (rustfs/backlog#2668).""" +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +import json +import os +from pathlib import Path +import stat +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import check_advisories as gate # noqa: E402 + + +def make_diagnostic( + adv_id: str, + crate: str, + version: str, + *, + code: str = "vulnerability", + parent_crate: str = "rustfs-iam", +) -> dict: + return { + "type": "diagnostic", + "fields": { + "advisory": { + "id": adv_id, + "package": crate, + "title": f"Advisory {adv_id} on {crate}", + "url": f"https://rustsec.org/advisories/{adv_id}", + "informational": None if code == "vulnerability" else "unmaintained", + "cvss": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:N/A:N" if code == "vulnerability" else None, + "aliases": [], + }, + "code": code, + "severity": "error", + "message": f"Advisory {adv_id} detected", + "graphs": [ + { + "Krate": {"name": crate, "version": version}, + "parents": [ + { + "Krate": {"name": parent_crate, "version": "1.0.5"}, + "parents": [{"Krate": {"name": "rustfs", "version": "1.0.5"}}], + } + ], + } + ], + "labels": [{"span": f"{crate} {version} registry+https://github.com/rust-lang/crates.io-index"}], + }, + } + + +def make_summary(errors: int, notes: int = 0) -> dict: + return {"type": "summary", "fields": {"advisories": {"errors": errors, "helps": 0, "notes": notes, "warnings": 0}}} + + +class FixtureHarness: + """Isolated git repo + fake advisory DB + mock cargo-deny binary.""" + + def __init__(self, tmp_dir: str) -> None: + self.root = Path(tmp_dir) + self.repo = self.root / "repo" + self.repo.mkdir() + self.db_dir = self.root / "advisory-db" + self.db_dir.mkdir() + self.mock_bin = self.root / "mock-cargo-deny" + self.out_json = self.root / "advisories-gate.json" + self.raw_log = self.root / "cargo-deny.log" + self.mock_state = self.root / "mock-state.json" + + self._git(self.repo, "init", "-q") + self._git(self.repo, "config", "user.name", "Test") + self._git(self.repo, "config", "user.email", "test@example.invalid") + self.write("Cargo.toml", '[workspace]\nmembers = []\n') + self.write("Cargo.lock", 'version = 4\n\n[[package]]\nname = "rsa"\nversion = "0.9.10"\n') + + self._git(self.db_dir, "init", "-q") + self._git(self.db_dir, "config", "user.name", "DB") + self._git(self.db_dir, "config", "user.email", "db@example.invalid") + self._git(self.db_dir, "remote", "add", "origin", gate.DEFAULT_ADVISORY_DB_URL) + (self.db_dir / "README.md").write_text("rustsec fixture\n", encoding="utf-8") + self._git(self.db_dir, "add", "-A") + self._git(self.db_dir, "commit", "-qm", "db snapshot") + self.db_rev = self._git(self.db_dir, "rev-parse", "HEAD") + + self.set_mock() + self._install_mock_cargo_deny() + + def _git(self, cwd: Path, *args: str) -> str: + return subprocess.check_output( + ["git", "-c", "core.hooksPath=/dev/null", *args], + cwd=cwd, + text=True, + stderr=subprocess.PIPE, + ).strip() + + def write(self, rel: str, content: str) -> Path: + path = self.repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + return path + + def commit(self, msg: str = "fixture") -> str: + self._git(self.repo, "add", "-A") + self._git(self.repo, "commit", "-qm", msg) + return self._git(self.repo, "rev-parse", "HEAD") + + def set_fetch_head_age(self, now: datetime, age_seconds: int) -> None: + fetch_head = self.db_dir / ".git" / "FETCH_HEAD" + fetch_head.write_text(f"{self.db_rev}\t\tbranch 'main' of {gate.DEFAULT_ADVISORY_DB_URL}\n", encoding="utf-8") + ts = (now - timedelta(seconds=age_seconds)).timestamp() + os.utime(fetch_head, (ts, ts)) + + def set_mock( + self, + *, + version: str = gate.EXPECTED_CARGO_DENY_VERSION, + fetch_exit: int = 0, + fetch_stderr: str = "", + hits: list[dict] | None = None, + crash_check: bool = False, + malformed_output: bool = False, + ) -> None: + self.mock_state.write_text( + json.dumps({ + "version": version, + "fetch_exit": fetch_exit, + "fetch_stderr": fetch_stderr, + "hits": hits if hits is not None else [], + "crash_check": crash_check, + "malformed_output": malformed_output, + }), + encoding="utf-8", + ) + + def _install_mock_cargo_deny(self) -> None: + script = f"""#!{sys.executable} +import json, sys, tomllib +from pathlib import Path + +state = json.loads(Path({str(self.mock_state)!r}).read_text(encoding="utf-8")) +args = sys.argv[1:] +if args == ["--version"]: + print(f"cargo-deny {{state['version']}}") + raise SystemExit(0) +if "fetch" in args: + if state["fetch_stderr"]: + print(state["fetch_stderr"], file=sys.stderr) + raise SystemExit(state["fetch_exit"]) +if "check" in args: + if state["crash_check"]: + print("fatal metadata error", file=sys.stderr) + raise SystemExit(2) + if state["malformed_output"]: + print("NOT-JSON-OUTPUT") + raise SystemExit(1) + cfg_path = Path(args[args.index("--config") + 1]) + cfg = tomllib.loads(cfg_path.read_text(encoding="utf-8")) + ignored = set() + for item in cfg.get("advisories", {{}}).get("ignore", []): + if isinstance(item, str): + ignored.add(item) + elif isinstance(item, dict) and "id" in item: + ignored.add(item["id"]) + emitted = 0 + for hit in state["hits"]: + adv_id = (hit.get("fields", {{}}).get("advisory") or {{}}).get("id") + if adv_id and adv_id in ignored: + continue + print(json.dumps(hit)) + emitted += 1 + print(json.dumps({{"type": "summary", "fields": {{"advisories": {{"errors": emitted, "helps": 0, "notes": len(ignored), "warnings": 0}}}}}})) + raise SystemExit(1 if emitted else 0) +raise SystemExit(2) +""" + self.mock_bin.write_text(script, encoding="utf-8") + self.mock_bin.chmod(self.mock_bin.stat().st_mode | stat.S_IXUSR) + + def write_valid_pair( + self, + *, + adv_id: str = "RUSTSEC-2023-0071", + crate: str = "rsa", + affected_versions: str = "=0.9.10", + approved_at: str = "2026-10-01T00:00:00Z", + expires_at: str = "2026-12-15T00:00:00Z", + approval_ref: str = "https://github.com/rustfs/rustfs/pull/9492", + ) -> None: + self.write( + "deny.toml", + f"""[graph] +all-features = true +no-default-features = false + +[advisories] +version = 2 +yanked = "deny" +ignore = [ + {{ id = "{adv_id}", reason = "tracked temporary exception" }}, +] +""", + ) + self.write( + ".config/advisory-exceptions.toml", + f"""schema_version = 1 + +[[exceptions]] +advisory_id = "{adv_id}" +crate = "{crate}" +affected_versions = "{affected_versions}" +owner = "rustfs-maintainers" +tracking_issue = "https://github.com/rustfs/backlog/issues/2668" +reason = "Transitive dependency waiting on upstream release." +mitigation = "No vulnerable decryption oracle reachable from server handlers." +approved_at = "{approved_at}" +expires_at = "{expires_at}" +approval_reference = "{approval_ref}" +""", + ) + + def run( + self, + *, + now: str = "2026-11-26T00:00:00Z", + base_ref: str = "", + trusted_approvals: list[dict] | None = None, + pr_author: str | None = None, + offline_only: bool = False, + env_override: dict[str, str] | None = None, + ) -> tuple[dict, int]: + argv = [ + "--repo-root", + str(self.repo), + "--output", + str(self.out_json), + "--raw-log", + str(self.raw_log), + "--advisory-db-dir", + str(self.db_dir), + "--cargo-deny-bin", + str(self.mock_bin), + "--skip-cargo-metadata", + ] + if now is not None: + argv += ["--now", now] + if base_ref: + argv += ["--base-ref", base_ref] + if offline_only: + argv.append("--offline-only") + if pr_author: + argv += ["--pr-author", pr_author] + if trusted_approvals is not None: + trusted_path = self.root / "trusted-approvals.json" + trusted_path.write_text(json.dumps(trusted_approvals), encoding="utf-8") + argv += ["--trusted-approvals-json", str(trusted_path)] + args = gate.build_parser().parse_args(argv) + env = dict(os.environ) + env.pop("GITHUB_ACTIONS", None) + env.pop("CI_BASE_SHA", None) + if env_override: + env.update(env_override) + with patch.dict(os.environ, env, clear=True): + return gate.run_gate(args) + + +class AdvisoryGateTests(unittest.TestCase): + def setUp(self) -> None: + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.h = FixtureHarness(self.tmp.name) + + def test_valid_unexpired_exception_passes_and_emits_structured_report(self) -> None: + self.h.write_valid_pair() + self.h.commit("base") + self.h.set_mock(hits=[make_diagnostic("RUSTSEC-2023-0071", "rsa", "0.9.10")]) + + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_OK, report["errors"]) + self.assertEqual(report["status"], "pass") + self.assertEqual(report["schema_version"], 1) + self.assertEqual(report["advisory_db"]["revision"], self.h.db_rev) + self.assertEqual(report["advisory_db"]["freshness_source"], "live_fetch") + self.assertFalse(report["advisory_db"]["used_cached_db"]) + self.assertEqual(report["tool"]["actual_version"], gate.EXPECTED_CARGO_DENY_VERSION) + self.assertEqual(len(report["advisory_hits"]), 1) + self.assertEqual(report["advisory_hits"][0]["disposition"], "exempted") + self.assertIn("rsa 0.9.10 <- rustfs-iam 1.0.5 <- rustfs 1.0.5", report["advisory_hits"][0]["chains"]) + self.assertEqual(report["exceptions"][0]["status"], "valid") + self.assertEqual(report["exceptions"][0]["matched_versions"], ["0.9.10"]) + self.assertTrue(self.h.out_json.is_file()) + self.assertTrue(self.h.raw_log.is_file()) + + def test_clean_tree_with_zero_advisories_and_zero_exceptions_passes(self) -> None: + self.h.write( + "deny.toml", + '[graph]\nall-features = true\nno-default-features = false\n[advisories]\nversion = 2\nyanked = "deny"\nignore = []\n', + ) + self.h.write(".config/advisory-exceptions.toml", "schema_version = 1\nexceptions = []\n") + self.h.set_mock(hits=[]) + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_OK, report["errors"]) + self.assertEqual(report["advisory_hits"], []) + self.assertEqual(report["exceptions"], []) + + def test_unexempted_live_advisory_fails_with_advisory_exit_code(self) -> None: + self.h.write( + "deny.toml", + '[graph]\nall-features = true\nno-default-features = false\n[advisories]\nversion = 2\nyanked = "deny"\nignore = []\n', + ) + self.h.write(".config/advisory-exceptions.toml", "schema_version = 1\nexceptions = []\n") + self.h.set_mock(hits=[make_diagnostic("RUSTSEC-2026-9999", "foo", "1.2.3")]) + + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_ADVISORY_FOUND) + self.assertIn("unexempted_advisory", report["reason_codes"]) + self.assertEqual(report["advisory_hits"][0]["disposition"], "unexempted") + + def test_exact_boundary_and_past_expiry_fail_with_expiry_exit_code(self) -> None: + self.h.write_valid_pair(approved_at="2026-10-01T00:00:00Z", expires_at="2026-11-26T00:00:00Z") + self.h.set_mock(hits=[make_diagnostic("RUSTSEC-2023-0071", "rsa", "0.9.10")]) + + # Exact boundary: now == expires_at MUST fail. + report_exact, code_exact = self.h.run(now="2026-11-26T00:00:00Z") + self.assertEqual(code_exact, gate.EXIT_EXCEPTION_EXPIRED) + self.assertIn("exception_expired", report_exact["reason_codes"]) + self.assertEqual(report_exact["exceptions"][0]["status"], "expired") + + # One second before expiry passes. + report_before, code_before = self.h.run(now="2026-11-25T23:59:59Z") + self.assertEqual(code_before, gate.EXIT_OK, report_before["errors"]) + + def test_untracked_deny_ignore_and_bare_string_ignore_fail_closed(self) -> None: + self.h.write( + "deny.toml", + '[graph]\nall-features = true\nno-default-features = false\n[advisories]\nversion = 2\nyanked = "deny"\nignore = ["RUSTSEC-2023-0071"]\n', + ) + self.h.write(".config/advisory-exceptions.toml", "schema_version = 1\nexceptions = []\n") + self.h.set_mock(hits=[make_diagnostic("RUSTSEC-2023-0071", "rsa", "0.9.10")]) + + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("untracked_deny_ignore", report["reason_codes"]) + self.assertIn("bare_deny_ignore", report["reason_codes"]) + + def test_schema_validation_rejects_unknown_fields_duplicates_bad_dates_and_over_90d(self) -> None: + self.h.write_valid_pair() + self.h.set_mock(hits=[make_diagnostic("RUSTSEC-2023-0071", "rsa", "0.9.10")]) + + # Unknown schema version + self.h.write( + ".config/advisory-exceptions.toml", + (self.h.repo / ".config/advisory-exceptions.toml").read_text().replace("schema_version = 1", "schema_version = 2"), + ) + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("invalid_exception_schema", report["reason_codes"]) + + # Unknown field + self.h.write_valid_pair() + self.h.write( + ".config/advisory-exceptions.toml", + (self.h.repo / ".config/advisory-exceptions.toml").read_text() + 'extra_field = "nope"\n', + ) + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("invalid_exception_schema", report["reason_codes"]) + + # Duplicate advisory ID + self.h.write_valid_pair() + text = (self.h.repo / ".config/advisory-exceptions.toml").read_text() + entry_block = text.split("[[exceptions]]", 1)[1] + self.h.write(".config/advisory-exceptions.toml", text + "\n[[exceptions]]" + entry_block) + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("duplicate_exception", report["reason_codes"]) + + # Validity window > 90 days (91 days) + self.h.write_valid_pair(approved_at="2026-10-01T00:00:00Z", expires_at="2026-12-31T00:00:00Z") + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("validity_window_exceeded", report["reason_codes"]) + + # Non-UTC timestamp + self.h.write_valid_pair(approved_at="2026-10-01T00:00:00+08:00", expires_at="2026-12-01T00:00:00Z") + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("invalid_timestamp", report["reason_codes"]) + + # Missing owner / placeholder owner / wildcard version + self.h.write_valid_pair(affected_versions="*") + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("invalid_version_range", report["reason_codes"]) + + # Malformed TOML + self.h.write(".config/advisory-exceptions.toml", "schema_version = [unterminated\n") + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("invalid_exception_schema", report["reason_codes"]) + + def test_scope_mismatch_and_stale_unused_exception_fail_closed(self) -> None: + # Locked version 0.9.10 outside =0.9.9 + self.h.write_valid_pair(affected_versions="=0.9.9") + self.h.set_mock(hits=[make_diagnostic("RUSTSEC-2023-0071", "rsa", "0.9.10")]) + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("exception_scope_mismatch", report["reason_codes"]) + + # Stale unused exception when crate no longer hits advisory + self.h.write_valid_pair() + self.h.set_mock(hits=[]) + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("stale_unused_exception", report["reason_codes"]) + + def test_weakening_deny_graph_or_yanked_fails_closed(self) -> None: + self.h.write_valid_pair() + self.h.set_mock(hits=[make_diagnostic("RUSTSEC-2023-0071", "rsa", "0.9.10")]) + deny_text = (self.h.repo / "deny.toml").read_text() + for bad in ( + deny_text.replace("all-features = true", "all-features = false"), + deny_text.replace("no-default-features = false", "no-default-features = true"), + deny_text.replace('yanked = "deny"', 'yanked = "warn"'), + deny_text + 'vulnerability = "allow"\n', + ): + self.h.write("deny.toml", bad) + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("config_weakened", report["reason_codes"]) + + def test_pr_widening_or_self_written_approval_reference_is_rejected(self) -> None: + self.h.write_valid_pair( + affected_versions="=0.9.10", + approved_at="2026-10-01T00:00:00Z", + expires_at="2026-12-15T00:00:00Z", + ) + base = self.h.commit("base with narrow exception") + self.h.set_mock(hits=[make_diagnostic("RUSTSEC-2023-0071", "rsa", "0.9.10")]) + + # Unchanged exception against base passes without needing new approval. + report, code = self.h.run(base_ref=base, trusted_approvals=[]) + self.assertEqual(code, gate.EXIT_OK, report["errors"]) + + # Widening affected_versions without trusted approval fails. + self.h.write_valid_pair( + affected_versions=">=0.9.0, <0.10.0", + approved_at="2026-10-01T00:00:00Z", + expires_at="2026-12-15T00:00:00Z", + approval_ref="https://github.com/rustfs/rustfs/pull/99999", + ) + report, code = self.h.run(base_ref=base, trusted_approvals=[], pr_author="contributor") + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("widened_exception_scope", report["reason_codes"]) + + # Self-approval by PR author is rejected even if present in approval records. + self_approval = [{ + "approval_reference": "https://github.com/rustfs/rustfs/pull/99999", + "advisory_id": "RUSTSEC-2023-0071", + "crate": "rsa", + "affected_versions": ">=0.9.0, <0.10.0", + "expires_at": "2026-12-15T00:00:00Z", + "approver": "contributor", + "approver_association": "MEMBER", + "state": "APPROVED", + }] + report, code = self.h.run(base_ref=base, trusted_approvals=self_approval, pr_author="contributor") + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("widened_exception_scope", report["reason_codes"]) + + # Independent maintainer approval covering the widened scope passes. + maintainer_approval = [{ + **self_approval[0], + "approver": "overtrue", + }] + report, code = self.h.run(base_ref=base, trusted_approvals=maintainer_approval, pr_author="contributor") + self.assertEqual(code, gate.EXIT_OK, report["errors"]) + + def test_advisory_db_freshness_cache_fallback_and_stale_rejection(self) -> None: + self.h.write_valid_pair() + self.h.set_mock(fetch_exit=1, fetch_stderr="network unreachable", hits=[make_diagnostic("RUSTSEC-2023-0071", "rsa", "0.9.10")]) + now = datetime(2026, 11, 26, 0, 0, 0, tzinfo=timezone.utc) + + # No FETCH_HEAD -> arbitrary checkout rejected even when present. + report, code = self.h.run(now="2026-11-26T00:00:00Z") + self.assertEqual(code, gate.EXIT_INFRA_ERROR) + self.assertIn("stale_or_untrusted_advisory_db", report["reason_codes"]) + + # Fresh 2-hour cache passes and marks used_cached_db=True. + self.h.set_fetch_head_age(now, age_seconds=2 * 3600) + report, code = self.h.run(now="2026-11-26T00:00:00Z") + self.assertEqual(code, gate.EXIT_OK, report["errors"]) + self.assertTrue(report["advisory_db"]["used_cached_db"]) + self.assertEqual(report["advisory_db"]["freshness_source"], "cached_fallback") + self.assertEqual(report["advisory_db"]["cache_age_seconds"], 2 * 3600) + + # Stale 25-hour cache fails closed. + self.h.set_fetch_head_age(now, age_seconds=25 * 3600) + report, code = self.h.run(now="2026-11-26T00:00:00Z") + self.assertEqual(code, gate.EXIT_INFRA_ERROR) + self.assertIn("stale_or_untrusted_advisory_db", report["reason_codes"]) + + def test_tool_version_mismatch_crash_and_ci_clock_override_fail_closed(self) -> None: + self.h.write_valid_pair() + self.h.set_mock(version="0.18.0", hits=[make_diagnostic("RUSTSEC-2023-0071", "rsa", "0.9.10")]) + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_INFRA_ERROR) + self.assertIn("tool_version_mismatch", report["reason_codes"]) + + self.h.set_mock(crash_check=True) + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_INFRA_ERROR) + self.assertIn("cargo_deny_failed", report["reason_codes"]) + + self.h.set_mock(malformed_output=True) + report, code = self.h.run() + self.assertEqual(code, gate.EXIT_INFRA_ERROR) + self.assertIn("scan_output_unparseable", report["reason_codes"]) + + # Clock override via --now is rejected under GITHUB_ACTIONS=true. + self.h.set_mock(hits=[make_diagnostic("RUSTSEC-2023-0071", "rsa", "0.9.10")]) + report, code = self.h.run(now="2026-11-26T00:00:00Z", env_override={"GITHUB_ACTIONS": "true"}) + self.assertEqual(code, gate.EXIT_POLICY_ERROR) + self.assertIn("untrusted_clock_override", report["reason_codes"]) + + def test_github_approval_reference_verification_rejects_recycled_or_untrusted_records(self) -> None: + exc = { + "advisory_id": "RUSTSEC-2023-0071", + "crate": "rsa", + "affected_versions": "=0.9.10", + "expires_at": "2026-12-15T00:00:00Z", + "approval_reference": "https://github.com/rustfs/rustfs/pull/9999#pullrequestreview-12345", + } + good_body = "Approved RUSTSEC-2023-0071 for rsa =0.9.10 until 2026-12-15." + + def fake_gh(payload: dict, returncode: int = 0): + return subprocess.CompletedProcess(["gh"], returncode, stdout=json.dumps(payload), stderr="") + + with patch.dict(os.environ, {"GH_TOKEN": "tok"}, clear=False): + # Trusted maintainer APPROVED review passes. + with patch.object( + gate.subprocess, + "run", + return_value=fake_gh({"state": "APPROVED", "author_association": "MEMBER", "user": {"login": "overtrue"}, "body": good_body}), + ): + ok, _ = gate.verify_github_approval(exc, "contributor") + self.assertTrue(ok) + + # Self-approval by PR author is rejected. + with patch.object( + gate.subprocess, + "run", + return_value=fake_gh({"state": "APPROVED", "author_association": "MEMBER", "user": {"login": "contributor"}, "body": good_body}), + ): + ok, _ = gate.verify_github_approval(exc, "contributor") + self.assertFalse(ok) + + # Non-maintainer association is rejected. + with patch.object( + gate.subprocess, + "run", + return_value=fake_gh({"state": "APPROVED", "author_association": "CONTRIBUTOR", "user": {"login": "someone"}, "body": good_body}), + ): + ok, _ = gate.verify_github_approval(exc, "contributor") + self.assertFalse(ok) + + # Unrelated merged PR recycled without naming advisory/scope/expiry is rejected. + recycled_exc = {**exc, "approval_reference": "https://github.com/rustfs/rustfs/pull/1"} + with patch.object( + gate.subprocess, + "run", + return_value=fake_gh({"merged": True, "merged_by": {"login": "overtrue"}, "user": {"login": "other"}, "body": "unrelated PR"}), + ): + ok, _ = gate.verify_github_approval(recycled_exc, "contributor") + self.assertFalse(ok) + + # Bare issue URL without maintainer comment fragment is rejected. + issue_exc = {**exc, "approval_reference": "https://github.com/rustfs/rustfs/issues/2668"} + ok, _ = gate.verify_github_approval(issue_exc, "contributor") + self.assertFalse(ok) + + # Maintainer issue comment with matching issue_url naming advisory/scope/expiry passes. + comment_exc = {**exc, "approval_reference": "https://github.com/rustfs/rustfs/issues/2668#issuecomment-555"} + with patch.object( + gate.subprocess, + "run", + return_value=fake_gh({ + "issue_url": "https://api.github.com/repos/rustfs/rustfs/issues/2668", + "author_association": "OWNER", + "user": {"login": "overtrue"}, + "body": good_body, + }), + ): + ok, _ = gate.verify_github_approval(comment_exc, "contributor") + self.assertTrue(ok) + + # Comment belonging to a different issue/PR number is rejected. + with patch.object( + gate.subprocess, + "run", + return_value=fake_gh({ + "issue_url": "https://api.github.com/repos/rustfs/rustfs/issues/9999", + "author_association": "OWNER", + "user": {"login": "overtrue"}, + "body": good_body, + }), + ): + ok, _ = gate.verify_github_approval(comment_exc, "contributor") + self.assertFalse(ok) + + # Malformed or non-dict JSON from gh api fails closed without raising. + for raw_stdout in ("not-json", "[]", "null"): + with patch.object( + gate.subprocess, + "run", + return_value=subprocess.CompletedProcess(["gh"], 0, stdout=raw_stdout, stderr=""), + ): + ok, _ = gate.verify_github_approval(exc, "contributor") + self.assertFalse(ok) + ok, _ = gate.verify_github_approval(comment_exc, "contributor") + self.assertFalse(ok) + ok, _ = gate.verify_github_approval(recycled_exc, "contributor") + self.assertFalse(ok) + + def test_strip_advisory_ignores_toml_preserves_table_lists_such_as_graph_targets(self) -> None: + import tomllib + + sample = """[graph] +all-features = true +no-default-features = false +targets = [ + { triple = "x86_64-unknown-linux-gnu" }, + { triple = "aarch64-unknown-linux-musl", features = ["fips"] }, +] + +[advisories] +version = 2 +yanked = "deny" +ignore = [ + { id = "RUSTSEC-2023-0071", reason = "tracked" }, +] +""" + stripped = gate.strip_advisory_ignores_toml(sample) + parsed = tomllib.loads(stripped) + self.assertEqual(parsed["graph"]["targets"], [ + {"triple": "x86_64-unknown-linux-gnu"}, + {"triple": "aarch64-unknown-linux-musl", "features": ["fips"]}, + ]) + self.assertEqual(parsed["advisories"]["ignore"], []) + self.assertEqual(parsed["advisories"]["yanked"], "deny") + + def test_secret_redaction_strips_tokens_from_raw_log(self) -> None: + self.h.write_valid_pair() + self.h.set_mock( + fetch_exit=1, + fetch_stderr="Authorization: Bearer ghp_1234567890abcdefghij1234567890 failed AKIAIOSFODNN7EXAMPLE", + hits=[make_diagnostic("RUSTSEC-2023-0071", "rsa", "0.9.10")], + ) + now = datetime(2026, 11, 26, 0, 0, 0, tzinfo=timezone.utc) + self.h.set_fetch_head_age(now, age_seconds=60) + report, code = self.h.run(now="2026-11-26T00:00:00Z") + self.assertEqual(code, gate.EXIT_OK, report["errors"]) + log_text = self.h.raw_log.read_text(encoding="utf-8") + self.assertNotIn("ghp_1234567890abcdefghij1234567890", log_text) + self.assertNotIn("AKIAIOSFODNN7EXAMPLE", log_text) + self.assertIn("", log_text) + self.assertNotIn("ghp_1234567890abcdefghij1234567890", report["advisory_db"]["fetch_error"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test_ci_plan.py b/scripts/test_ci_plan.py index 927d34ef36..2daeea2ac1 100644 --- a/scripts/test_ci_plan.py +++ b/scripts/test_ci_plan.py @@ -558,6 +558,8 @@ class GateTests(unittest.TestCase): jobs[job] = {'name': job, 'if': expression, 'steps': []} jobs['classify-changes']['outputs'] = {'mode': '${{ steps.scope.outputs.mode }}'} jobs[gate.LINT_JOB]['steps'] = [{'run': 'cargo clippy --all-targets -- -D warnings'}] + jobs[gate.ADVISORIES_JOB]['runs-on'] = 'ubuntu-latest' + jobs[gate.ADVISORIES_JOB]['steps'] = [{'run': 'python3 scripts/security/check_advisories.py --output artifacts/advisories/advisories-gate.json'}] jobs['workspace-tests']['needs'] = [gate.ARCHIVE_PRODUCER] jobs['classify-changes']['steps'] = [{'id': 'scope', 'run': f"grep -q '^plan_contract={gate.PLAN_CONTRACT}$' \"$GITHUB_OUTPUT\""}] jobs['test-and-lint-protocols']['strategy'] = {'matrix': {'features': [ @@ -749,6 +751,35 @@ class GateTests(unittest.TestCase): # The checked-in workflow satisfies the same contract. self.assertEqual(gate.check_workflow(Path(gate.__file__).resolve().parent.parent), []) + def test_security_advisories_lane_gates_every_event_including_docs_and_proven(self): + advisories = gate.ADVISORIES_JOB + self.assertIn(advisories, gate.ALWAYS_JOBS) + for event, mode in (('pull_request', 'docs'), ('pull_request', 'e2e'), ('pull_request', 'full'), + ('push', 'full'), ('push', 'proven'), ('merge_group', 'full'), + ('schedule', 'full'), ('workflow_dispatch', 'full')): + plan = self.plan(event, mode) + self.assertEqual(plan['jobs'][advisories], 'success', (event, mode)) + self.assertEqual(gate.verify_results(self.needs(plan), event, plan['ref']), []) + for bad in ('failure', 'cancelled', 'skipped', None): + needs = self.needs(plan) + needs[advisories]['result'] = bad + errors = gate.verify_results(needs, event, plan['ref']) + self.assertTrue(any(error.startswith(f'{advisories}: expected success') for error in errors), (event, mode, bad, errors)) + workflow = self.workflow() + self.assertEqual(self.check(workflow), []) + for case, (mutate, message) in enumerate(( + (lambda w: w['jobs']['required-checks']['needs'].remove(advisories), 'required-checks must directly depend on every verification job exactly once'), + (lambda w: w['jobs'][advisories].update({'runs-on': 'sm-standard-4'}), f'{advisories} must run on ubuntu-latest'), + (lambda w: w['jobs'][advisories].update({'steps': []}), f'{advisories} must unconditionally run {gate.ADVISORIES_COMMAND}'), + (lambda w: w['jobs'][advisories]['steps'][0].update({'if': "github.event_name != 'pull_request'"}), f'{advisories} must unconditionally run {gate.ADVISORIES_COMMAND}'), + (lambda w: w['jobs'][advisories]['steps'][0].update({'run': f'{gate.ADVISORIES_COMMAND} || true'}), f'{advisories} must not mask failures or override the CI clock'), + (lambda w: w['jobs'][advisories]['steps'][0].update({'run': f'{gate.ADVISORIES_COMMAND} --now 2026-01-01T00:00:00Z'}), f'{advisories} must not mask failures or override the CI clock'), + (lambda w: w['jobs'][advisories].update({'continue-on-error': 'true'}), f'{advisories} cannot convert a validation failure into success'), + )): + changed = copy.deepcopy(workflow) + mutate(changed) + self.assertIn(message, self.check(changed), case) + def test_semantic_yaml_equivalence_and_wiring_boundaries(self): workflow = self.workflow() self.assertEqual(self.check(workflow), [])