Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

An invariant nothing enforced: zero CodeQL alerts, now actually gated (#815)

Beenu Aroraf16978438b29
diff --git a/.github/workflows/codeql-alert-gate.yml b/.github/workflows/codeql-alert-gate.yml
new file mode 100644
index 000000000..76785b0de
--- /dev/null
+++ b/.github/workflows/codeql-alert-gate.yml
@@ -0,0 +1,109 @@
+name: CodeQL alert gate
+
+# `apps/docs/docs/operations/security.md` has stated since the v8.0 wave-1 push
+# that the CodeQL alert count on `main` is zero and that this is enforced as a
+# CI gate. Nothing enforced it. `codeql.yml` uploads SARIF and
+# `github/codeql-action/analyze` does not fail a build on findings; `main` has
+# no branch protection, so "Code scanning results" was not a required check
+# either; and `security.yml`'s only hard job is the claim-to-gate matrix.
+# Alerts #893 and #896 — both `note` severity — sat open on `main` under a
+# documented invariant of zero, and no job anywhere could have gone red.
+#
+# This workflow is that gate. It is deliberately separate from `security.yml`
+# because it needs a `workflow_run` trigger that the observe-mode scanners
+# there should not inherit.
+
+on:
+ # What landed. A push-triggered run races the CodeQL analysis of its own
+ # commit, so the gate is pinned to `github.sha` and waits for that revision
+ # to be analyzed rather than reading the previous commit's alert list.
+ push:
+ branches: [main]
+ # What is proposed, before it lands.
+ pull_request:
+ branches: [main]
+ # Belt and braces for `main`: fires once CodeQL has actually finished, so a
+ # push whose analysis outran the wait window is still checked.
+ workflow_run:
+ workflows: [CodeQL]
+ types: [completed]
+ branches: [main]
+ # Daily, so a scan that quietly stops running is caught during a quiet week
+ # instead of at whatever push happens next. `main` can be stale-green.
+ schedule:
+ - cron: "0 6 * * *"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: codeql-alert-gate-${{ github.event_name }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ zero-open-alerts:
+ name: Zero open CodeQL alerts
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ security-events: read
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: "3.12"
+
+ - name: Install deps
+ # The gate itself is stdlib-only, deliberately: it must run on a bare
+ # interpreter. pytest is for the unit tests below; pydantic + httpx
+ # let the two `validate_playbooks` regression tests import the real
+ # model rather than skip — a skipped regression test is not a
+ # regression test. Same set the parity job in `ci.yml` installs, for
+ # the same reason.
+ run: pip install --quiet pytest pydantic httpx
+
+ # The self-test runs first and on the same tree. It injects an alert at
+ # every severity — including `note`, the severity of the two alerts that
+ # motivated this gate — plus each shape of vacuous pass (no analysis, a
+ # dropped language, a frozen analysis, mixed action pins, a PR-only
+ # trigger) and requires the gate to catch every one. A gate whose
+ # self-test is skipped is a gate that proves nothing.
+ - name: Self-test — prove the gate detects an injected alert
+ run: python3 scripts/check_codeql_alerts.py --self-test
+
+ - name: Unit tests
+ run: python3 -m pytest tests/test_codeql_alert_gate.py -q
+
+ # `main`, pinned to the revision that triggered this run.
+ - name: Gate — main
+ if: github.event_name != 'pull_request'
+ env:
+ GITHUB_TOKEN: ${{ github.token }}
+ run: |
+ python3 scripts/check_codeql_alerts.py \
+ --repo "${{ github.repository }}" \
+ --ref refs/heads/main \
+ ${{ github.event_name == 'push' && format('--commit {0} --wait-seconds 1500', github.sha) || '' }}
+
+ # The merge ref, so a contributor sees a new alert before it lands
+ # rather than after. `github.sha` on a `pull_request` event is the merge
+ # commit CodeQL analyses, so the same pin applies.
+ - name: Gate — pull request
+ if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork != true
+ env:
+ GITHUB_TOKEN: ${{ github.token }}
+ run: |
+ python3 scripts/check_codeql_alerts.py \
+ --repo "${{ github.repository }}" \
+ --ref "refs/pull/${{ github.event.pull_request.number }}/merge" \
+ --commit "${{ github.sha }}" \
+ --wait-seconds 1500
+
+ # A fork PR's GITHUB_TOKEN cannot read code scanning, so the alert query
+ # is impossible here. `--offline` checks the wiring and prints, in its
+ # own output, exactly which checks it did not perform — the push and
+ # workflow_run runs above are what hold the invariant for `main`.
+ - name: Gate — fork pull request (wiring only, alert query not possible)
+ if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true
+ run: python3 scripts/check_codeql_alerts.py --offline
diff --git a/AGENTS.md b/AGENTS.md
index 45b094253..959a6f4d8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -68,7 +68,7 @@
- Plugin manager OCI installs verify signed manifests against an allow-list and pin image digests at install time, re-verifying on every load.
- Dev-mode: one canonical `AISOC_DEV_MODE` env var replaces the per-service patchwork of `DEV_MODE` / `SKIP_AUTH` / `AISOC_DEMO_MODE` flags. `tests/test_security_defaults.py` is a CI gate that asserts no dev-mode shortcut is reachable when the flag is unset.
- LLM input contract: untrusted enrichment (threat-intel feeds, user-submitted content) runs through `services/api/app/services/llm_safety.py` (boundary markers, control-character stripping, length cap) before any prompt concatenation.
-- **Static analysis hygiene (CodeQL):** Python alert count on `main` is zero as of 2026-05-14, enforced as a CI gate. Two patterns drove the cleanup:
+- **Static analysis hygiene (CodeQL):** the invariant is **zero open CodeQL alerts on `main` at every severity, `note` included**, enforced by `.github/workflows/codeql-alert-gate.yml` running `scripts/check_codeql_alerts.py`. That gate did not exist until 2026-09-24 even though the docs had claimed one since 2026-05-15 — `analyze` does not fail a build on findings, `main` has no branch protection, and nothing queried the code-scanning API — so two `note` alerts sat open under a documented count of zero. Dismissed alerts are excluded (audited escape hatch, ~20 accepted-risk `py/request-without-cert-validation`) but counted in the gate's output; Scorecard SARIF is out of scope. The gate also fails on an unanalysed ref, a missing language, an analysis >10 days old, or one from a different commit than the run's. Two patterns drove the original cleanup:
- **`py/log-injection` — sanitise inline at the call site.** The taint tracker doesn't follow `_log_safe(value)` through function boundaries reliably, but it does recognise an inline `str(value).replace("\r", "").replace("\n", " ")[:N]` chain. Canonical example: `services/api/app/api/v1/endpoints/waitlist.py`. Even `uuid.UUID`-typed values are sanitised explicitly so the property is visible to both CodeQL and future readers.
- **`py/import-and-import-from` — pick one import style per module.** Tests that monkey-patch module-level constants should use `pytest.MonkeyPatch.setattr(module, "_NAME", value)` (with the standard from-import form), not `import app.foo as foo_module` _and_ a from-import for the same names.
- **`py/request-without-cert-validation` — accepted-risk for on-prem appliance clients.** The Splunk / FortiGate / PAN-OS / osctrl / FleetDM / MISP clients default to `verify=True` and only disable TLS verification on an explicit operator opt-in (required for self-signed / internal-CA appliances), so these ~20 alerts are dismissed `won't fix` with a comment recommending CA-bundle pinning as the future alternative. Related one-liners from the Jul-2026 pass: a count var named `secret*` trips the alert heuristic (rename to e.g. `vaulted`); `py/ineffectual-statement` on Protocol/abstract `...` bodies → use a docstring body; `py/empty-except` → add an explanatory comment. Zero open alerts re-confirmed on `main` (Jul 2026), now across Python + Go (`go vet` / `go build`).
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6f60d15fc..19e7ea4f9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -313,6 +313,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Security
+- **The zero-CodeQL-alert invariant was documented for four months with
+ nothing enforcing it.** `apps/docs/docs/operations/security.md` has said
+ since 2026-05-15 that "the Python alert count on `main` is zero, and we
+ treat that as a CI gate — a new alert breaks the security workflow". No such
+ gate existed anywhere in the repository. `codeql.yml` uploads SARIF and
+ `github/codeql-action/analyze` does not fail a build on findings; `main` has
+ no branch protection, so "Code scanning results" was not a required check
+ either; `security.yml`'s only hard job is the claim-to-gate matrix; and
+ nothing in the tree queried the code-scanning API. The scan itself was
+ healthy — `main` was analysed continuously, most recently minutes before
+ this was written — so the usual stale-green and mixed-`codeql-action`-pin
+ traps were both ruled out. The enforcement was simply imaginary, which is
+ why two `note`-severity alerts could sit open on `main` under a documented
+ count of zero.
+
+ `scripts/check_codeql_alerts.py` is that gate, wired into the new
+ `.github/workflows/codeql-alert-gate.yml` on push to `main`, on pull
+ requests, on a `workflow_run` after CodeQL finishes, and daily. It fails on
+ any open CodeQL alert at **any** severity — `note` included, since both
+ motivating alerts were `note` and carried no `security_severity_level`, so a
+ threshold anywhere would have reproduced the original silence exactly. It
+ also refuses the vacuous pass: an unanalysed ref, a declared language with
+ no analysis, an analysis older than ten days, or one belonging to a
+ different commit than the one that triggered the run are all failures rather
+ than a clean bill of health, and an input it cannot read exits 2 rather than
+ 0. Dismissed alerts stay excluded — that is GitHub's audited escape hatch
+ and the repository uses it for ~20 accepted-risk
+ `py/request-without-cert-validation` findings — but the count is printed on
+ every run so a silent mass-dismissal is visible. `--self-test` injects an
+ alert at each severity plus every shape of vacuous pass and requires the
+ gate to catch all ten; CI runs it immediately before the gate itself.
+
+- **`scripts/validate_playbooks.py` printed to stderr and called `sys.exit(2)`
+ while being imported** (CodeQL `py/print-during-import`, alert #896). Beyond
+ the note, this was a live defect:
+ `scripts/check_playbook_schema_parity.py` imports the module to read
+ `SUPPORTED_TRIGGERS` and wraps the import in `except Exception`, which
+ cannot catch `SystemExit` — a broken environment would have killed the
+ parity gate's interpreter instead of producing its diagnostic. The import
+ now raises `ImportError`, which that handler catches.
+
- **The maintainers' hosted origin shipped in the default CORS allow-list of
nine services.** `services/{api,agents,connectors,honeytokens,purple-team,ueba}`
(six byte-identical copies of the shared `cors.py`), `services/realtime`, and
diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.md
index 8508277da..f1821baf2 100644
--- a/apps/docs/docs/operations/security.md
+++ b/apps/docs/docs/operations/security.md
@@ -370,7 +370,23 @@ rather than the one that catches the library.
## Static analysis (CodeQL)
-GitHub CodeQL runs on every pull request and on a nightly schedule against `main`. As of the v8.0 wave-1 push the Python alert count on `main` is zero, and we treat that as a CI gate — a new alert breaks the security workflow and blocks the next release.
+GitHub CodeQL (`.github/workflows/codeql.yml`) analyses `javascript-typescript`, `python` and `go` on every push to `main`, on every pull request targeting `main`, and on a weekly schedule (Mondays, 03:00 UTC).
+
+**The invariant: zero *open* CodeQL alerts on `main`, at every severity — `note` included.** It is enforced by `.github/workflows/codeql-alert-gate.yml`, which runs `scripts/check_codeql_alerts.py`. Precisely what that means:
+
+- **Every severity counts.** `note`, `warning` and `error` all break the gate, and so do alerts that carry no `security_severity_level` at all (quality queries generally do not). There is no threshold to sit underneath.
+- **Dismissed alerts are excluded, and counted out loud.** Dismissal is GitHub's audited escape hatch: it records the actor, the reason and the timestamp, and it requires write access. We use it for roughly twenty accepted-risk `py/request-without-cert-validation` findings on the on-prem appliance clients (Splunk, FortiGate, PAN-OS, osctrl, FleetDM, MISP): those clients default to `verify=True` and only disable verification on an explicit operator opt-in, which self-signed and internal-CA appliances require. They are dismissed `won't fix` with CA-bundle pinning recorded as the future alternative. The gate prints how many dismissals it excluded on every run, so a silent mass-dismissal is visible in its own output rather than hidden behind a green tick.
+- **An unanalysed ref is a failure, not a pass.** The gate requires a CodeQL analysis for *each* declared language, pinned to the commit that triggered the run, and it fails if the newest analysis is more than ten days old. Zero alerts because nothing ran is the answer it exists to refuse.
+- **It runs on `push` to `main`, not only on pull requests,** plus a `workflow_run` trigger after CodeQL finishes and a daily schedule.
+- **Scorecard findings are out of scope.** Scorecard uploads SARIF to the same code-scanning page under its own tool name (`PinnedDependenciesID`, `TokenPermissionsID` and friends). They are a different policy with a different owner; the gate reports them and does not gate on them.
+
+`scripts/check_codeql_alerts.py --self-test` injects an alert at each severity plus every shape of vacuous pass — no analysis, a dropped language, a frozen analysis, mixed `codeql-action` pins, a PR-only trigger — and requires the gate to catch each one. CI runs that self-test immediately before the gate itself, on the same tree.
+
+:::warning This invariant was stated for four months before anything enforced it
+This section used to read "the Python alert count on `main` is zero, and we treat that as a CI gate — a new alert breaks the security workflow". No mechanism existed. `codeql.yml` uploads SARIF, and `github/codeql-action/analyze` does not fail a build on findings; `main` has no branch protection, so "Code scanning results" was not a required check either; and `security.yml`'s only hard job is the claim-to-gate matrix. Nothing in the repository queried the code-scanning API.
+
+It was found the way these things are always found: two alerts — [#893](https://github.com/beenuar/AiSOC/security/code-scanning/893) (`py/unused-global-variable`) and [#896](https://github.com/beenuar/AiSOC/security/code-scanning/896) (`py/print-during-import`), both `note` — sat open on `main` while this page said the count was zero. The scan itself was healthy and current; the enforcement was imaginary. The sentence above now describes a job that exists, and the gate's self-test is what keeps it that way.
+:::
Two patterns are worth documenting because they came up repeatedly during the sweep that drove the alert count to zero:
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 1e70d0bf2..14dbcc7a5 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -31,7 +31,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Every playbook route requires an authenticated, permitted caller | (implied by RBAC) | `ci.yml` api job (`test_tenant_scope_and_auth_holes.py` — each of the eight route functions takes an authenticated principal, the decorated-route count is asserted against the expected permission map so a new ungated route fails, execute stays distinct from write, and every permission named is one a role actually grants) | GATED | - |
| An MSSP parent holds only tenants that invited it | operations/security.md (MSSP parent/child links) | `ci.yml` api job (`test_mssp_cross_tenant_authz.py` — the four child-scoped write routes refuse a tenant that is not the caller's child and persist nothing; unknown and unowned are indistinguishable so the routes cannot enumerate tenant UUIDs; onboarding refuses without an invite, refuses an invite addressed to another parent, consumes the invite on success, and refuses self-adoption) | GATED | the guard is unit-level against the route functions; the nightly live-DB `cross-tenant-rbac.yml` sweep does not yet cover the MSSP routes |
| Cross-tenant isolation (Qdrant/Neo4j/Redis/ClickHouse/Kafka) | (implied by multi-tenant) | `isolation.yml` (offline: read paths construct a tenant scope) + `isolation-live.yml` (live A-vs-B replay: Neo4j property filter, Redis keyspace namespacing, ClickHouse via production `lake_sql.rewrite_for_tenant`, Kafka per-tenant envelope filter) | GATED | - |
-| SAST | README badge (CodeQL) | `codeql.yml` | GATED | - |
+| SAST | README badge (CodeQL) | `codeql.yml` (the scan) + `codeql-alert-gate.yml` (the invariant: `scripts/check_codeql_alerts.py` fails on any open CodeQL alert at any severity, `note` included, and refuses a ref whose declared languages were not analysed at the triggering commit — `analyze` never failed a build on findings, so this row named a scan and not a gate) | GATED | - |
| Dependency CVE scanning | (implied by security) | `security-audit.yml` | GATED | - |
| OpenSSF Scorecard | README badge L13 | `scorecard.yml` | GATED | - |
| Container image / IaC / secret scanning (Trivy/checkov/tfsec/gitleaks/Semgrep) | (implied by security) | `security.yml` (claim-matrix ratchet HARD; gitleaks/Semgrep/Trivy/checkov/tfsec observe) | PARTIAL (matrix ratchet enforced; secret + code/IaC/container scanners report-and-ratchet, allowlist at `.security/allowlist.yml` / `.gitleaksignore`; GitHub push-protection is the always-on hard secret gate) | Phase 2 |
diff --git a/scripts/check_codeql_alerts.py b/scripts/check_codeql_alerts.py
new file mode 100644
index 000000000..a66a6df49
--- /dev/null
+++ b/scripts/check_codeql_alerts.py
@@ -0,0 +1,721 @@
+#!/usr/bin/env python3
+"""
+Gate: zero open CodeQL alerts on the ref — from a scan that actually ran.
+
+`apps/docs/docs/operations/security.md` states that the CodeQL alert count on
+`main` is zero and that we treat it as a CI gate. Until this script existed
+that sentence described no mechanism: `codeql.yml` uploads SARIF and
+`github/codeql-action/analyze` does not fail a build on findings, `main` has no
+branch protection so "Code scanning results" was not a required check, and
+`security.yml`'s only hard job was the claim-to-gate matrix. Two `note`-severity
+alerts sat open on `main` under a documented invariant of zero.
+
+What this checks, and why each part exists:
+
+1. `open-alert` — any open CodeQL alert on the ref, **at every severity
+ including `note`**. The two alerts that motivated this gate were both
+ `note`; a gate that filtered them out would have reproduced the original
+ failure while printing OK.
+2. `no-analysis` / `language-not-analyzed` — the ref must actually have been
+ analyzed, per language declared in the workflow matrix. Zero alerts because
+ nothing ran is the vacuous pass this repository keeps rediscovering, so an
+ empty read is a failure, never a clean bill of health.
+3. `stale-analysis` — the newest analysis must be recent. `main` can be
+ stale-green: a workflow that stopped running still leaves its last passing
+ result in place, and the alert list simply freezes.
+4. `action-version-mismatch` — CodeQL refuses to run at all when one workflow
+ pins different versions across `init` / `autobuild` / `analyze`, which is
+ exactly what a dependabot bump splitting those three across separate PRs
+ produces. That failure mode removes the analysis, and without (2) and (3) it
+ would read as "no alerts".
+5. `no-push-to-main-trigger` / `no-pull-request-trigger` — a PR-only scan
+ inspects what contributors propose and never what lands.
+
+Dismissed alerts are out of scope by design: dismissal is GitHub's audited
+escape hatch (it records actor, reason and timestamp, and requires write
+access), and this repository uses it for ~22 accepted-risk
+`py/request-without-cert-validation` findings on on-prem appliance clients.
+They are counted and printed rather than hidden, so a silent mass-dismissal is
+visible in this gate's own output.
+
+Scorecard also uploads SARIF to the same code-scanning page. Its findings are a
+different policy with a different owner, so they are reported here and not
+gated.
+
+Usage:
+ python3 scripts/check_codeql_alerts.py # gate `main`
+ python3 scripts/check_codeql_alerts.py --ref refs/pull/1/merge
+ python3 scripts/check_codeql_alerts.py --json
+ python3 scripts/check_codeql_alerts.py --self-test # prove it bites
+ python3 scripts/check_codeql_alerts.py --offline # static checks only
+
+Exit codes: 0 clean · 1 the invariant is broken · 2 the gate could not read its
+inputs (never reported as clean).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from collections.abc import Callable
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any
+
+API_ROOT = "https://api.github.com"
+DEFAULT_REPO = "beenuar/AiSOC"
+DEFAULT_REF = "refs/heads/main"
+WORKFLOW_REL = Path(".github/workflows/codeql.yml")
+
+# The tool whose alerts this gate owns. Scorecard uploads to the same page
+# under its own name and is reported, not gated.
+GATED_TOOL = "CodeQL"
+
+# The weekly cron plus a push on every merge means a healthy `main` is analyzed
+# far more often than this. Ten days clears the widest legitimate gap (a quiet
+# week where only the Monday schedule fires) while still catching a workflow
+# that has stopped running.
+DEFAULT_MAX_ANALYSIS_AGE_DAYS = 10
+
+_ACTION_RE = re.compile(r"github/codeql-action/(init|autobuild|analyze)@(\S+)")
+_LANGUAGE_LIST_RE = re.compile(r"language:\s*\[([^\]]+)\]")
+_BRANCH_LIST_RE = re.compile(r"branches:\s*\[([^\]]+)\]")
+
+
+class GateError(RuntimeError):
+ """An input could not be read. Never downgraded to a passing result."""
+
+
+# --------------------------------------------------------------------------
+# Workflow parsing (offline)
+# --------------------------------------------------------------------------
+def _block(text: str, header: str) -> str | None:
+ """The indented block following the line whose content is `header`."""
+ lines = text.splitlines()
+ for i, line in enumerate(lines):
+ if line.strip() != header:
+ continue
+ base = len(line) - len(line.lstrip())
+ out: list[str] = []
+ for nxt in lines[i + 1 :]:
+ if not nxt.strip():
+ out.append(nxt)
+ continue
+ if len(nxt) - len(nxt.lstrip()) <= base:
+ break
+ out.append(nxt)
+ return "\n".join(out)
+ return None
+
+
+def parse_workflow(path: Path) -> dict[str, Any]:
+ """Read the declared languages, action pins and triggers out of codeql.yml.
+
+ Parsed with targeted regexes rather than PyYAML: this gate runs on a bare
+ `actions/setup-python` interpreter with nothing pip-installed, and a gate
+ that cannot run is worse than one with a narrower parser. Every field is
+ required — a parse that finds nothing raises instead of returning an empty
+ result that would read as "no problems found".
+ """
+ if not path.exists():
+ raise GateError(f"expected input does not exist: {path}")
+ text = path.read_text(encoding="utf-8")
+
+ versions: dict[str, str] = {}
+ for step, pin in _ACTION_RE.findall(text):
+ versions[step] = pin
+ for step in ("init", "autobuild", "analyze"):
+ if step not in versions:
+ raise GateError(f"{path}: no `github/codeql-action/{step}` step found")
+
+ lang_match = _LANGUAGE_LIST_RE.search(text)
+ if not lang_match:
+ raise GateError(f"{path}: could not parse the `language:` matrix")
+ languages = [item.strip().strip("'\"") for item in lang_match.group(1).split(",")]
+ languages = [item for item in languages if item]
+ if not languages:
+ raise GateError(f"{path}: parsed an empty `language:` matrix")
+
+ on_block = _block(text, "on:")
+ if on_block is None:
+ raise GateError(f"{path}: could not find the `on:` trigger block")
+ push_block = _block(on_block, "push:")
+ push_branches: list[str] = []
+ if push_block is not None:
+ branch_match = _BRANCH_LIST_RE.search(push_block)
+ if branch_match:
+ push_branches = [item.strip().strip("'\"") for item in branch_match.group(1).split(",")]
+
+ return {
+ "path": str(path),
+ "action_versions": versions,
+ "languages": languages,
+ "push_branches": push_branches,
+ "has_pull_request_trigger": _block(on_block, "pull_request:") is not None
+ or re.search(r"^\s*pull_request:\s*$", on_block, re.MULTILINE) is not None,
+ }
+
+
+# --------------------------------------------------------------------------
+# GitHub API (fails closed)
+# --------------------------------------------------------------------------
+def _token() -> str:
+ for name in ("GITHUB_TOKEN", "GH_TOKEN"):
+ value = os.environ.get(name)
+ if value:
+ return value
+ raise GateError(
+ "no GITHUB_TOKEN/GH_TOKEN in the environment; the gate needs "
+ "`security-events: read` to query code scanning. Re-run with --offline "
+ "to check only what can be checked without it."
+ )
+
+
+def _get(url: str, token: str) -> tuple[Any, str | None]:
+ request = urllib.request.Request( # noqa: S310 - fixed https API_ROOT below
+ url,
+ headers={
+ "Accept": "application/vnd.github+json",
+ "Authorization": f"Bearer {token}",
+ "X-GitHub-Api-Version": "2022-11-28",
+ "User-Agent": "aisoc-codeql-alert-gate",
+ },
+ )
+ if not url.startswith(API_ROOT + "/"):
+ raise GateError(f"refusing to call a non-GitHub URL: {url}")
+ try:
+ with urllib.request.urlopen(request, timeout=30) as response: # noqa: S310
+ payload = json.loads(response.read().decode("utf-8"))
+ link = response.headers.get("Link")
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode("utf-8", "replace")[:300]
+ raise GateError(f"GET {url} -> HTTP {exc.code}: {detail}") from exc
+ except (urllib.error.URLError, TimeoutError, ValueError) as exc:
+ raise GateError(f"GET {url} -> {type(exc).__name__}: {exc}") from exc
+
+ next_url = None
+ if link:
+ for part in link.split(","):
+ if 'rel="next"' in part:
+ next_url = part.split(";")[0].strip().strip("<>")
+ return payload, next_url
+
+
+def _paginate(url: str, token: str, limit_pages: int = 20) -> list[dict]:
+ items: list[dict] = []
+ pages = 0
+ while url and pages < limit_pages:
+ payload, url = _get(url, token)
+ if not isinstance(payload, list):
+ raise GateError(f"expected a JSON array from {url!r}, got {type(payload).__name__}")
+ items.extend(payload)
+ pages += 1
+ return items
+
+
+def fetch(repo: str, ref: str) -> dict[str, Any]:
+ """Open alerts, dismissed alerts and analyses for `ref`. Raises on failure."""
+ token = _token()
+ quoted = urllib.parse.quote(ref, safe="/")
+ base = f"{API_ROOT}/repos/{repo}/code-scanning"
+ open_alerts = _paginate(f"{base}/alerts?state=open&ref={quoted}&per_page=100", token)
+ dismissed = _paginate(f"{base}/alerts?state=dismissed&ref={quoted}&per_page=100", token)
+ analyses = _paginate(f"{base}/analyses?ref={quoted}&per_page=100", token, limit_pages=2)
+ return {"open_alerts": open_alerts, "dismissed_alerts": dismissed, "analyses": analyses}
+
+
+def fetch_when_analyzed(
+ repo: str,
+ ref: str,
+ *,
+ commit: str | None,
+ languages: list[str],
+ wait_seconds: int,
+ poll_seconds: int = 30,
+ sleep: Callable[[float], None] = time.sleep,
+) -> dict[str, Any]:
+ """`fetch`, but wait for the analyses of `commit` to land first.
+
+ The gate and the analysis it reads are triggered by the same push, so
+ without this the gate would routinely evaluate the previous commit and
+ call the new one clean. Timing out is a failure, not a pass: the caller
+ still evaluates, and the missing analyses surface as `no-analysis` or
+ `language-not-analyzed`.
+ """
+ deadline = time.monotonic() + max(wait_seconds, 0)
+ while True:
+ data = fetch(repo, ref)
+ if not commit or wait_seconds <= 0:
+ return data
+ covered = _analysis_languages(data["analyses"], commit)
+ if all(language in covered for language in languages):
+ return data
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return data
+ missing = [item for item in languages if item not in covered]
+ pending = ", ".join(missing)
+ print(
+ f"waiting for {GATED_TOOL} analysis of {commit[:8]} ({pending}); {int(remaining)}s left",
+ flush=True,
+ )
+ sleep(min(poll_seconds, max(remaining, 1)))
+
+
+# --------------------------------------------------------------------------
+# Evaluation (pure — the self-test drives this directly)
+# --------------------------------------------------------------------------
+def _analysis_languages(analyses: list[dict], commit: str | None = None) -> dict[str, datetime]:
+ """Newest analysis timestamp per language, read from the SARIF category.
+
+ `commit` pins the result to one revision. Without it a run triggered by a
+ push would happily read the *previous* commit's analysis — the alert list
+ for a ref does not change until the new analysis lands — and report the
+ incoming commit clean before anything had looked at it.
+ """
+ newest: dict[str, datetime] = {}
+ for analysis in analyses:
+ if analysis.get("tool", {}).get("name") != GATED_TOOL:
+ continue
+ if commit and analysis.get("commit_sha") != commit:
+ continue
+ category = analysis.get("category") or ""
+ language = category.split("/language:")[-1] if "/language:" in category else ""
+ if not language:
+ continue
+ created = analysis.get("created_at")
+ if not created:
+ continue
+ stamp = datetime.fromisoformat(created.replace("Z", "+00:00"))
+ if language not in newest or stamp > newest[language]:
+ newest[language] = stamp
+ return newest
+
+
+def evaluate(
+ *,
+ open_alerts: list[dict],
+ analyses: list[dict],
+ workflow: dict[str, Any],
+ now: datetime,
+ max_age_days: int,
+ alerts_checked: bool,
+ commit: str | None = None,
+) -> list[tuple[str, str]]:
+ """Return (code, detail) for every way the invariant is currently false."""
+ failures: list[tuple[str, str]] = []
+
+ pins = workflow["action_versions"]
+ if len(set(pins.values())) > 1:
+ rendered = ", ".join(f"{step}@{pin}" for step, pin in sorted(pins.items()))
+ failures.append(
+ (
+ "action-version-mismatch",
+ f"codeql-action steps pin different versions ({rendered}); CodeQL refuses "
+ "to run at all in this state, which would empty the alert list rather than "
+ "clear it",
+ )
+ )
+
+ if "main" not in workflow["push_branches"]:
+ failures.append(
+ (
+ "no-push-to-main-trigger",
+ f"{workflow['path']} does not run on push to main "
+ f"(push branches: {workflow['push_branches'] or 'none'}); a PR-only scan "
+ "never inspects what actually landed",
+ )
+ )
+ if not workflow["has_pull_request_trigger"]:
+ failures.append(
+ (
+ "no-pull-request-trigger",
+ f"{workflow['path']} does not run on pull requests, so a contributor only "
+ "learns about a new alert after it is already on main",
+ )
+ )
+
+ if alerts_checked:
+ by_language = _analysis_languages(analyses, commit)
+ scope = f" for commit {commit[:8]}" if commit else ""
+ if not by_language:
+ failures.append(
+ (
+ "no-analysis",
+ f"no {GATED_TOOL} analysis found for this ref{scope} — zero alerts here "
+ "means nothing was scanned, not that nothing was found",
+ )
+ )
+ else:
+ for language in workflow["languages"]:
+ if language not in by_language:
+ failures.append(
+ (
+ "language-not-analyzed",
+ f"the workflow declares `{language}` but no {GATED_TOOL} analysis "
+ f"for it exists on this ref{scope} (analyzed: {sorted(by_language)})",
+ )
+ )
+ cutoff = now - timedelta(days=max_age_days)
+ for language, stamp in sorted(by_language.items()):
+ if stamp < cutoff:
+ age = (now - stamp).days
+ failures.append(
+ (
+ "stale-analysis",
+ f"the newest `{language}` analysis is {age} days old "
+ f"({stamp.date()}), past the {max_age_days}-day limit; the alert "
+ "list is frozen, not clean",
+ )
+ )
+
+ for alert in open_alerts:
+ if alert.get("tool", {}).get("name") != GATED_TOOL:
+ continue
+ rule = alert.get("rule", {})
+ location = alert.get("most_recent_instance", {}).get("location", {})
+ failures.append(
+ (
+ "open-alert",
+ f"#{alert.get('number')} {rule.get('id')} [{rule.get('severity')}] "
+ f"{location.get('path')}:{location.get('start_line')}",
+ )
+ )
+
+ return failures
+
+
+# --------------------------------------------------------------------------
+# CLI
+# --------------------------------------------------------------------------
+def _summarise(items: list[dict], key) -> dict[str, int]:
+ counts: dict[str, int] = {}
+ for item in items:
+ name = key(item)
+ counts[name] = counts.get(name, 0) + 1
+ return counts
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY") or DEFAULT_REPO)
+ parser.add_argument("--ref", default=DEFAULT_REF)
+ parser.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parent.parent)
+ parser.add_argument("--max-analysis-age-days", type=int, default=DEFAULT_MAX_ANALYSIS_AGE_DAYS)
+ parser.add_argument(
+ "--commit",
+ default=None,
+ help="require the analyses to be of this revision, not merely of this ref",
+ )
+ parser.add_argument(
+ "--wait-seconds",
+ type=int,
+ default=0,
+ help="wait this long for --commit to be analyzed; timing out still fails",
+ )
+ parser.add_argument("--json", action="store_true")
+ parser.add_argument(
+ "--offline",
+ action="store_true",
+ help="check only the workflow wiring; states in its output that the alert "
+ "query was not performed (for fork PRs, whose token cannot read code scanning)",
+ )
+ parser.add_argument(
+ "--self-test",
+ action="store_true",
+ help="inject an alert and each vacuous-pass shape, and require the gate to catch each",
+ )
+ args = parser.parse_args(argv)
+
+ root = args.repo_root.resolve()
+ if args.self_test:
+ return self_test(root)
+
+ try:
+ workflow = parse_workflow(root / WORKFLOW_REL)
+ if args.offline:
+ data: dict[str, Any] = {"open_alerts": [], "dismissed_alerts": [], "analyses": []}
+ else:
+ data = fetch_when_analyzed(
+ args.repo,
+ args.ref,
+ commit=args.commit,
+ languages=workflow["languages"],
+ wait_seconds=args.wait_seconds,
+ )
+ except GateError as exc:
+ print(f"check_codeql_alerts: FAILED to read its inputs: {exc}", file=sys.stderr)
+ return 2
+
+ now = datetime.now(timezone.utc)
+ failures = evaluate(
+ open_alerts=data["open_alerts"],
+ analyses=data["analyses"],
+ workflow=workflow,
+ now=now,
+ max_age_days=args.max_analysis_age_days,
+ alerts_checked=not args.offline,
+ commit=args.commit,
+ )
+
+ by_language = _analysis_languages(data["analyses"], args.commit)
+ gated_open = [a for a in data["open_alerts"] if a.get("tool", {}).get("name") == GATED_TOOL]
+ other_open = [a for a in data["open_alerts"] if a.get("tool", {}).get("name") != GATED_TOOL]
+ gated_dismissed = [a for a in data["dismissed_alerts"] if a.get("tool", {}).get("name") == GATED_TOOL]
+
+ if args.json:
+ print(
+ json.dumps(
+ {
+ "repo": args.repo,
+ "ref": args.ref,
+ "commit": args.commit,
+ "offline": args.offline,
+ "workflow": workflow,
+ "analyses_by_language": {k: v.isoformat() for k, v in by_language.items()},
+ "open_codeql_alerts": [
+ {
+ "number": a.get("number"),
+ "rule": a.get("rule", {}).get("id"),
+ "severity": a.get("rule", {}).get("severity"),
+ "path": a.get("most_recent_instance", {}).get("location", {}).get("path"),
+ }
+ for a in gated_open
+ ],
+ "dismissed_codeql_alerts": len(gated_dismissed),
+ "open_other_tool_alerts": len(other_open),
+ "failures": [{"code": c, "detail": d} for c, d in failures],
+ },
+ indent=2,
+ sort_keys=True,
+ )
+ )
+ return 1 if failures else 0
+
+ # Name what was scanned before the verdict. A gate that prints only OK is
+ # indistinguishable from one that checked nothing.
+ print(f"repo {args.repo}")
+ print(f"ref {args.ref}{' @ ' + args.commit[:8] if args.commit else ''}")
+ print(f"workflow {workflow['path']} (languages: {', '.join(workflow['languages'])})")
+ pins = set(workflow["action_versions"].values())
+ print(f"codeql-action {'consistent @' + pins.pop() if len(pins) == 1 else 'MIXED PINS'}")
+ print(
+ f"triggers push:{workflow['push_branches'] or 'none'} "
+ f"pull_request:{'yes' if workflow['has_pull_request_trigger'] else 'no'}"
+ )
+ if args.offline:
+ print()
+ print("NOT VERIFIED open-alert count, analysis freshness and language coverage")
+ print(" (--offline: no code-scanning read available on this event)")
+ else:
+ if by_language:
+ for language, stamp in sorted(by_language.items()):
+ age = (now - stamp).days
+ print(f" analysed {language:24s} {stamp.isoformat()} ({age}d ago)")
+ else:
+ print(" analysed nothing")
+ print()
+ print(f"open {GATED_TOOL} alerts {len(gated_open)} (every severity, `note` included)")
+ print(f"dismissed {len(gated_dismissed)} — audited accepted risk, not gated here")
+ if other_open:
+ other = _summarise(other_open, lambda a: a.get("tool", {}).get("name") or "?")
+ print(f"other tools {other} open — reported, owned elsewhere")
+ print()
+
+ if failures:
+ print(f"FAIL — {len(failures)} finding(s):")
+ for code, detail in failures:
+ print(f" [{code}] {detail}")
+ return 1
+ if args.offline:
+ print("OK (offline) — workflow wiring is sound; the alert count was NOT checked.")
+ return 0
+ scanned = f"commit {args.commit[:8]}" if args.commit else f"the last {args.max_analysis_age_days} days"
+ print(f"OK — zero open {GATED_TOOL} alerts on {args.ref}, from a scan that ran on")
+ print(f" every declared language ({', '.join(workflow['languages'])}) for {scanned}.")
+ return 0
+
+
+# --------------------------------------------------------------------------
+# Self-test
+# --------------------------------------------------------------------------
+def _clean_fixture(root: Path, now: datetime) -> dict[str, Any]:
+ """A ref that genuinely satisfies the invariant, built from the real workflow."""
+ workflow = parse_workflow(root / WORKFLOW_REL)
+ analyses = [
+ {
+ "tool": {"name": GATED_TOOL},
+ "category": f"/language:{language}",
+ "created_at": (now - timedelta(hours=2)).isoformat().replace("+00:00", "Z"),
+ }
+ for language in workflow["languages"]
+ ]
+ return {"open_alerts": [], "analyses": analyses, "workflow": workflow}
+
+
+def _alert(number: int, rule: str, severity: str, path: str) -> dict[str, Any]:
+ return {
+ "number": number,
+ "tool": {"name": GATED_TOOL},
+ "rule": {"id": rule, "severity": severity},
+ "most_recent_instance": {"location": {"path": path, "start_line": 1}},
+ }
+
+
+def self_test(root: Path) -> int:
+ """Inject each shape of failure and require the gate to catch it.
+
+ The first two cases are the ones that matter most: they are the alerts that
+ were open on `main` while the documentation claimed zero. A severity filter
+ anywhere in this gate makes case 1 fail here rather than on the security
+ page months later.
+ """
+ now = datetime.now(timezone.utc)
+ try:
+ base = _clean_fixture(root, now)
+ except GateError as exc:
+ print(f"self-test: cannot read the tree: {exc}", file=sys.stderr)
+ return 2
+
+ def run(data: dict[str, Any], *, alerts_checked: bool = True, commit: str | None = None) -> set[str]:
+ return {
+ code
+ for code, _ in evaluate(
+ open_alerts=data["open_alerts"],
+ analyses=data["analyses"],
+ workflow=data["workflow"],
+ now=now,
+ max_age_days=DEFAULT_MAX_ANALYSIS_AGE_DAYS,
+ alerts_checked=alerts_checked,
+ commit=commit,
+ )
+ }
+
+ baseline = run(base)
+ if baseline:
+ print("self-test: the clean fixture already fails; fix that first", file=sys.stderr)
+ for code in sorted(baseline):
+ print(f" [{code}]", file=sys.stderr)
+ return 1
+
+ def mutate(**overrides: Any) -> dict[str, Any]:
+ data = {
+ "open_alerts": list(base["open_alerts"]),
+ "analyses": [dict(a) for a in base["analyses"]],
+ "workflow": dict(base["workflow"]),
+ }
+ data["workflow"]["action_versions"] = dict(base["workflow"]["action_versions"])
+ data["workflow"]["languages"] = list(base["workflow"]["languages"])
+ data["workflow"]["push_branches"] = list(base["workflow"]["push_branches"])
+ data.update(overrides)
+ return data
+
+ stale = mutate()
+ for analysis in stale["analyses"]:
+ analysis["created_at"] = (now - timedelta(days=DEFAULT_MAX_ANALYSIS_AGE_DAYS + 5)).isoformat().replace("+00:00", "Z")
+
+ mixed = mutate()
+ mixed["workflow"]["action_versions"]["analyze"] = "v3.28.0"
+
+ no_push = mutate()
+ no_push["workflow"]["push_branches"] = []
+
+ no_pr = mutate()
+ no_pr["workflow"]["has_pull_request_trigger"] = False
+
+ dropped_language = mutate()
+ dropped_language["analyses"] = dropped_language["analyses"][:-1]
+
+ cases: list[tuple[str, str, dict[str, Any]]] = [
+ (
+ "a `note`-severity alert — #893/#896's severity, which a filtered gate would pass",
+ "open-alert",
+ mutate(
+ open_alerts=[
+ _alert(893, "py/unused-global-variable", "note", "scripts/x.py"),
+ ]
+ ),
+ ),
+ (
+ "an `error`-severity alert",
+ "open-alert",
+ mutate(open_alerts=[_alert(1, "py/sql-injection", "error", "services/api/app/db.py")]),
+ ),
+ (
+ "the ref was never analyzed — zero alerts because nothing ran",
+ "no-analysis",
+ mutate(analyses=[]),
+ ),
+ (
+ "one declared language silently stopped being analyzed",
+ "language-not-analyzed",
+ dropped_language,
+ ),
+ (
+ "stale-green: the analysis is frozen, so the alert list cannot move",
+ "stale-analysis",
+ stale,
+ ),
+ (
+ "codeql-action pins split across init/autobuild/analyze, so CodeQL never runs",
+ "action-version-mismatch",
+ mixed,
+ ),
+ (
+ "the scan stopped running on push to main and only inspects proposals",
+ "no-push-to-main-trigger",
+ no_push,
+ ),
+ (
+ "the scan stopped running on pull requests",
+ "no-pull-request-trigger",
+ no_pr,
+ ),
+ ]
+
+ print(f"self-test against {root / WORKFLOW_REL}")
+ print("clean fixture: 0 failures (the baseline every case below perturbs)\n")
+ ok = True
+ for description, expected, data in cases:
+ codes = run(data)
+ caught = expected in codes
+ ok &= caught
+ print(f" {'PASS' if caught else 'FAIL'} {description}")
+ print(f" expected [{expected}] got {sorted(codes) or 'nothing'}")
+
+ # A push run must not read the previous commit's analysis and call the
+ # incoming one clean. With --commit pinned, an analysis of anything else
+ # is no analysis at all.
+ pinned = run(base, commit="0" * 40)
+ pinned_ok = "no-analysis" in pinned
+ ok &= pinned_ok
+ print(f" {'PASS' if pinned_ok else 'FAIL'} an analysis of a different commit is not this commit's")
+ print(f" expected [no-analysis] got {sorted(pinned) or 'nothing'}")
+
+ # --offline must not be a silent skip that still claims the alert count.
+ offline_codes = run(
+ mutate(open_alerts=[_alert(2, "py/print-during-import", "note", "scripts/y.py")]),
+ alerts_checked=False,
+ )
+ offline_quiet = "open-alert" not in offline_codes
+ ok &= offline_quiet
+ print(f" {'PASS' if offline_quiet else 'FAIL'} --offline reports no alert verdict at all")
+ print(f" expected no [open-alert] got {sorted(offline_codes) or 'nothing'}")
+
+ print()
+ if not ok:
+ print("self-test FAILED: the gate did not catch a defect it claims to catch")
+ return 1
+ print(f"self-test OK: {len(cases) + 2} injected defects, each caught by its own code")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/validate_playbooks.py b/scripts/validate_playbooks.py
index a431e3988..ada3937de 100755
--- a/scripts/validate_playbooks.py
+++ b/scripts/validate_playbooks.py
@@ -37,11 +37,18 @@ DEFAULT_PACK = ROOT / "playbooks" / "packs" / "v1"
# Make the services/agents Pydantic models importable.
sys.path.insert(0, str(ROOT / "services" / "agents"))
+# Raised rather than printed-and-exited: `scripts/check_playbook_schema_parity.py`
+# imports this module to read SUPPORTED_TRIGGERS, and `sys.exit()` raises
+# SystemExit, which derives from BaseException and so slips past that gate's
+# `except Exception`. A broken environment would have killed the parity gate's
+# interpreter instead of producing its diagnostic.
try:
from app.playbook.models import Playbook, StepType # type: ignore[import-not-found]
-except Exception as exc: # pragma: no cover - import errors visible to user
- print(f"FATAL: cannot import Playbook model: {exc}", file=sys.stderr)
- sys.exit(2)
+except Exception as exc: # noqa: BLE001 - environment, not input
+ raise ImportError(
+ f"cannot import the Playbook model from services/agents: {exc}. "
+ "Install that service's dependencies before running the playbook validator."
+ ) from exc
SUPPORTED_TRIGGERS = {"alert", "case", "manual", "schedule"}
diff --git a/tests/test_codeql_alert_gate.py b/tests/test_codeql_alert_gate.py
new file mode 100644
index 000000000..f5fe32b2f
--- /dev/null
+++ b/tests/test_codeql_alert_gate.py
@@ -0,0 +1,352 @@
+"""Tests for the CodeQL zero-alert gate.
+
+`apps/docs/docs/operations/security.md` has claimed since v8.0 wave-1 that the
+CodeQL alert count on `main` is zero and that this is enforced as a CI gate.
+There was no such gate. `codeql.yml` uploads SARIF and
+`github/codeql-action/analyze` does not fail a build on findings; `main` has no
+branch protection, so "Code scanning results" was not a required check either;
+and `security.yml`'s only hard job was the claim-to-gate matrix. Alerts #893
+and #896 sat open on `main` for hours under a documented invariant of zero, and
+nothing anywhere could have noticed.
+
+So these tests assert two different things, and the second matters as much as
+the first:
+
+1. The gate catches every shape of failure it claims to catch — in particular a
+ `note`-severity alert, because both alerts that motivated it were `note` and
+ a severity filter would have reproduced the original silence exactly.
+2. The gate is *reachable*. A gate wired into no workflow, or wired only into
+ `pull_request`, is the defect this repository keeps rediscovering: it
+ inspects what contributors propose and never what actually lands. The last
+ two tests read the workflow file and fail if that wiring disappears.
+"""
+
+from __future__ import annotations
+
+import ast
+import importlib.util
+import subprocess
+import sys
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+import pytest
+
+_REPO = Path(__file__).resolve().parents[1]
+_SCRIPT = _REPO / "scripts" / "check_codeql_alerts.py"
+_GATE_WORKFLOW = _REPO / ".github" / "workflows" / "codeql-alert-gate.yml"
+_VALIDATE_PLAYBOOKS = _REPO / "scripts" / "validate_playbooks.py"
+
+# Run in a subprocess, because the property under test is what happens at
+# import time and a module imported once in this process would not show it.
+_IMPORT_AND_REPORT_TRIGGERS = """
+import sys
+sys.path.insert(0, 'scripts')
+import validate_playbooks
+print(sorted(validate_playbooks.SUPPORTED_TRIGGERS))
+"""
+
+# Simulates the broken environment: `app.playbook.models` cannot be imported.
+_IMPORT_WITH_MODELS_BLOCKED = """
+import sys
+
+class Blocker:
+ def find_spec(self, name, path=None, target=None):
+ if name.startswith('app.playbook'):
+ raise ImportError('blocked for the test')
+ return None
+
+sys.meta_path.insert(0, Blocker())
+sys.path.insert(0, 'scripts')
+try:
+ import validate_playbooks
+except Exception as exc:
+ print('CAUGHT', type(exc).__name__)
+"""
+
+
+def _load_gate():
+ spec = importlib.util.spec_from_file_location("check_codeql_alerts", _SCRIPT)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+gate = _load_gate()
+
+
+def _clean(now: datetime) -> dict:
+ return gate._clean_fixture(_REPO, now)
+
+
+def _run(data: dict, now: datetime, *, alerts_checked: bool = True) -> set[str]:
+ return {
+ code
+ for code, _ in gate.evaluate(
+ open_alerts=data["open_alerts"],
+ analyses=data["analyses"],
+ workflow=data["workflow"],
+ now=now,
+ max_age_days=gate.DEFAULT_MAX_ANALYSIS_AGE_DAYS,
+ alerts_checked=alerts_checked,
+ )
+ }
+
+
+# --------------------------------------------------------------------------
+# The gate bites
+# --------------------------------------------------------------------------
+def test_clean_ref_passes() -> None:
+ now = datetime.now(timezone.utc)
+ assert _run(_clean(now), now) == set()
+
+
+def test_note_severity_alert_is_caught() -> None:
+ """The headline case: #893 and #896 were both `note`.
+
+ A gate that counted only `error`/`warning`, or only alerts carrying a
+ `security_severity_level` (both of these were `None`), would have printed
+ OK for the entire window in which the invariant was false.
+ """
+ now = datetime.now(timezone.utc)
+ data = _clean(now)
+ data["open_alerts"] = [gate._alert(896, "py/print-during-import", "note", "scripts/validate_playbooks.py")]
+ assert "open-alert" in _run(data, now)
+
+
[email protected]("severity", ["note", "warning", "error"])
+def test_every_severity_is_gated(severity: str) -> None:
+ now = datetime.now(timezone.utc)
+ data = _clean(now)
+ data["open_alerts"] = [gate._alert(1, "py/some-rule", severity, "scripts/x.py")]
+ assert "open-alert" in _run(data, now)
+
+
+def test_unanalyzed_ref_is_not_a_clean_ref() -> None:
+ """Zero alerts because nothing ran is the vacuous pass, not a pass."""
+ now = datetime.now(timezone.utc)
+ data = _clean(now)
+ data["analyses"] = []
+ assert "no-analysis" in _run(data, now)
+
+
+def test_stale_analysis_is_caught() -> None:
+ """`main` can be stale-green: a frozen scan leaves a frozen alert list."""
+ now = datetime.now(timezone.utc)
+ data = _clean(now)
+ for analysis in data["analyses"]:
+ analysis["created_at"] = (now - timedelta(days=gate.DEFAULT_MAX_ANALYSIS_AGE_DAYS + 1)).isoformat().replace("+00:00", "Z")
+ assert "stale-analysis" in _run(data, now)
+
+
+def test_language_dropped_from_analysis_is_caught() -> None:
+ now = datetime.now(timezone.utc)
+ data = _clean(now)
+ data["analyses"] = data["analyses"][:-1]
+ assert "language-not-analyzed" in _run(data, now)
+
+
+def test_mixed_codeql_action_pins_are_caught() -> None:
+ """CodeQL refuses to run when init/autobuild/analyze disagree.
+
+ Dependabot splitting those three across separate PRs produces exactly this
+ state, and it removes the analysis rather than the findings.
+ """
+ now = datetime.now(timezone.utc)
+ data = _clean(now)
+ data["workflow"] = dict(data["workflow"])
+ data["workflow"]["action_versions"] = dict(data["workflow"]["action_versions"])
+ data["workflow"]["action_versions"]["analyze"] = "v3.28.0"
+ assert "action-version-mismatch" in _run(data, now)
+
+
+def test_pr_only_scan_is_caught() -> None:
+ now = datetime.now(timezone.utc)
+ data = _clean(now)
+ data["workflow"] = dict(data["workflow"])
+ data["workflow"]["push_branches"] = []
+ assert "no-push-to-main-trigger" in _run(data, now)
+
+
+def test_offline_mode_claims_no_alert_verdict() -> None:
+ """`--offline` must abstain, not quietly report a clean alert count."""
+ now = datetime.now(timezone.utc)
+ data = _clean(now)
+ data["open_alerts"] = [gate._alert(1, "py/some-rule", "error", "scripts/x.py")]
+ assert "open-alert" not in _run(data, now, alerts_checked=False)
+
+
+def test_analysis_of_a_different_commit_is_not_this_commit() -> None:
+ """The push-race: the gate and the scan are triggered by the same push.
+
+ Unpinned, the gate reads the alert list left by the *previous* commit and
+ calls the incoming one clean before anything has looked at it.
+ """
+ now = datetime.now(timezone.utc)
+ data = _clean(now)
+ for analysis in data["analyses"]:
+ analysis["commit_sha"] = "a" * 40
+ codes = {
+ code
+ for code, _ in gate.evaluate(
+ open_alerts=[],
+ analyses=data["analyses"],
+ workflow=data["workflow"],
+ now=now,
+ max_age_days=gate.DEFAULT_MAX_ANALYSIS_AGE_DAYS,
+ alerts_checked=True,
+ commit="b" * 40,
+ )
+ }
+ assert "no-analysis" in codes
+
+
+def test_wait_times_out_into_a_failure_not_a_pass(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A bounded wait that gives up must hand back an unanalyzed verdict."""
+ now = datetime.now(timezone.utc)
+ languages = _clean(now)["workflow"]["languages"]
+ monkeypatch.setattr(
+ gate,
+ "fetch",
+ lambda repo, ref: {"open_alerts": [], "dismissed_alerts": [], "analyses": []},
+ )
+ slept: list[float] = []
+ data = gate.fetch_when_analyzed(
+ "example/repo",
+ "refs/heads/main",
+ commit="c" * 40,
+ languages=languages,
+ wait_seconds=2,
+ poll_seconds=1,
+ sleep=slept.append,
+ )
+ assert data["analyses"] == []
+ assert slept, "the gate returned without ever waiting"
+
+
+def test_bundled_self_test_passes() -> None:
+ """The same proof CI runs, run here too."""
+ assert gate.self_test(_REPO) == 0
+
+
+# --------------------------------------------------------------------------
+# The gate fails closed
+# --------------------------------------------------------------------------
+def test_missing_workflow_raises_rather_than_passing() -> None:
+ with pytest.raises(gate.GateError):
+ gate.parse_workflow(_REPO / ".github" / "workflows" / "does-not-exist.yml")
+
+
+def test_unreadable_inputs_exit_two_not_zero(tmp_path: Path) -> None:
+ """Exit 2 is "could not read", and must never be confused with "clean"."""
+ result = subprocess.run(
+ [sys.executable, str(_SCRIPT), "--repo-root", str(tmp_path), "--offline"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert result.returncode == 2, result.stdout + result.stderr
+
+
+def test_missing_token_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)
+ monkeypatch.delenv("GH_TOKEN", raising=False)
+ with pytest.raises(gate.GateError):
+ gate.fetch("beenuar/AiSOC", "refs/heads/main")
+
+
+def test_gate_refuses_non_github_urls() -> None:
+ with pytest.raises(gate.GateError):
+ gate._get("https://example.invalid/alerts", "token")
+
+
+# --------------------------------------------------------------------------
+# The gate is reachable
+# --------------------------------------------------------------------------
+def test_gate_is_wired_into_a_workflow() -> None:
+ """A gate no workflow invokes proves nothing, however good its self-test."""
+ text = _GATE_WORKFLOW.read_text(encoding="utf-8")
+ assert "scripts/check_codeql_alerts.py" in text
+ assert "--self-test" in text, "the self-test must run in CI, not only locally"
+ assert "tests/test_codeql_alert_gate.py" in text
+
+
+def test_gate_runs_on_push_to_main_not_only_on_pull_requests() -> None:
+ """A PR-only gate inspects what is proposed and never what landed."""
+ text = _GATE_WORKFLOW.read_text(encoding="utf-8")
+ on_block = gate._block(text, "on:")
+ assert on_block is not None
+ push_block = gate._block(on_block, "push:")
+ assert push_block is not None and "main" in push_block
+ assert gate._block(on_block, "pull_request:") is not None
+
+
+def test_gate_pins_the_pushed_commit_rather_than_the_ref() -> None:
+ """Otherwise the push run reads the analysis of the commit before it."""
+ text = _GATE_WORKFLOW.read_text(encoding="utf-8")
+ assert "--commit" in text and "--wait-seconds" in text
+
+
+def test_codeql_workflow_pins_one_action_version() -> None:
+ """CodeQL refuses to run when init/autobuild/analyze disagree.
+
+ Asserted against the real workflow, not a fixture: a dependabot bump that
+ lands for one of the three steps would otherwise silently remove the
+ analysis this gate depends on.
+ """
+ workflow = gate.parse_workflow(_REPO / ".github" / "workflows" / "codeql.yml")
+ pins = set(workflow["action_versions"].values())
+ assert len(pins) == 1, f"mixed codeql-action pins: {workflow['action_versions']}"
+
+
+# --------------------------------------------------------------------------
+# The alert this wave fixed stays fixed
+# --------------------------------------------------------------------------
+def test_importing_validate_playbooks_is_silent_and_does_not_exit() -> None:
+ """Regression for alert #896 (`py/print-during-import`).
+
+ The module printed to stderr and called `sys.exit(2)` while being
+ imported. Beyond the CodeQL note that is a live defect:
+ `scripts/check_playbook_schema_parity.py` imports this module to read
+ SUPPORTED_TRIGGERS, and `SystemExit` derives from `BaseException`, so its
+ `except Exception` could not catch it.
+ """
+ result = subprocess.run(
+ [sys.executable, "-c", _IMPORT_AND_REPORT_TRIGGERS],
+ cwd=_REPO,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert result.returncode == 0, result.stderr
+ assert result.stderr == ""
+ assert result.stdout.strip() == "['alert', 'case', 'manual', 'schedule']"
+
+
+def test_broken_model_import_is_catchable_by_the_parity_gate() -> None:
+ """It must raise ImportError, which `except Exception` catches."""
+ result = subprocess.run(
+ [sys.executable, "-c", _IMPORT_WITH_MODELS_BLOCKED],
+ cwd=_REPO,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert result.returncode == 0, result.stderr
+ assert "CAUGHT ImportError" in result.stdout, result.stdout + result.stderr
+
+
+def test_validate_playbooks_has_no_module_scope_print() -> None:
+ """The property CodeQL's `py/print-during-import` checks, asserted locally."""
+ tree = ast.parse(_VALIDATE_PLAYBOOKS.read_text(encoding="utf-8"))
+ offenders: list[int] = []
+ for node in tree.body:
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ continue
+ if isinstance(node, ast.If) and ast.unparse(node.test) == "__name__ == '__main__'":
+ continue # the entrypoint guard does not run on import
+ for sub in ast.walk(node):
+ if isinstance(sub, ast.Call) and getattr(sub.func, "id", None) == "print":
+ offenders.append(sub.lineno)
+ assert offenders == [], f"print() at module scope on line(s) {offenders}"