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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(ci): stop the papers workflow pushing to protected main (#883)
Beenu Arorab37ae36852c1
diff --git a/.github/workflows/papers.yml b/.github/workflows/papers.ymlindex 5f3c68eff..0e25e4d94 100644--- a/.github/workflows/papers.yml+++ b/.github/workflows/papers.yml@@ -1,40 +1,46 @@name: Public papers (regenerate PDFs)-# Phase 4.3 — closes the "CI does not yet rebuild PDFs automatically"-# TODO that has been sitting in apps/web/public/papers/README.md since-# v8.0.+# Renders every white paper to PDF so a markdown change that breaks+# rendering is caught, and reports any committed PDF that is older than+# its source.#-# Triggers:-# * On every push to main that touches a paper's markdown source.-# * On every PR that touches a paper's source — we only build & upload-# in PR mode (no commit-back) so reviewers can preview the rendered-# PDF from the workflow artifacts.-# * Manually via workflow_dispatch.+# This workflow does not commit anything. It used to push refreshed PDFs+# straight to main, which stopped being possible when main became+# branch-protected: the push is rejected with GH006 and the run fails.+# Because the commit-back step was skipped on pull requests, it passed on+# every branch and failed only on main, so the breakage was invisible to+# anyone opening a PR. Redirecting it to open a pull request instead is+# not available either — this repository has Actions set to read-only+# permissions with PR creation disabled.#-# Output:-# * Always: `papers-pdf-${{ github.sha }}` artifact bundle.-# * On push to main only: a follow-up commit `chore: refresh public-# paper PDFs [skip ci]` if any rendered PDF differs from what's-# checked in. We never amend; we add a fresh commit.+# So staleness is reported rather than repaired, and refreshing a PDF is+# a local `make papers` followed by a commit. The check compares the+# digest of each markdown source against the digest recorded when its PDF+# was last rendered, held in apps/web/public/papers/render-manifest.json.+# It deliberately does not compare PDF bytes: WeasyPrint stamps a+# creation timestamp into its output and glyph metrics depend on the+# host's installed fonts, so two correct renders of one source differ.on:push:branches: [main]paths:- "apps/web/content/papers/**.md"+ - "apps/web/public/papers/render-manifest.json"- "scripts/render_white_paper.py"- "Makefile"- ".github/workflows/papers.yml"pull_request:paths:- "apps/web/content/papers/**.md"+ - "apps/web/public/papers/render-manifest.json"- "scripts/render_white_paper.py"- "Makefile"- ".github/workflows/papers.yml"workflow_dispatch:permissions:- contents: write+ contents: readconcurrency:group: papers-${{ github.ref }}@@ -46,20 +52,23 @@ jobs:runs-on: ubuntu-lateststeps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- with:- # We need full history so the auto-commit step's `git push`- # has a sane base to diff against.- fetch-depth: 0- # The auto-commit step pushes back to main, so the- # GITHUB_TOKEN persisted on the checkout must be the writeable- # one (default true).- persist-credentials: true- name: Set up Python 3.11uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0with:python-version: "3.11"+ # Ahead of the gate, so a staleness check that has stopped detecting+ # anything cannot report the tree clean.+ - name: The staleness check still detects what it claims to+ run: python3 scripts/render_white_paper.py --self-test++ # Runs before anything is rendered. `make papers` rewrites the+ # manifest, so checking afterwards would compare the tree against+ # itself and pass whatever the committed PDFs contain.+ - name: Every committed PDF is current with its source+ run: python3 scripts/render_white_paper.py --check+# WeasyPrint needs Pango / Cairo / GLib at the system level — the# same native deps that services/api/Dockerfile installs. Pinning# the exact apt package set means a Debian repo nudge doesn't@@ -72,55 +81,39 @@ jobs:libcairo2 libgdk-pixbuf-2.0-0 \libffi-dev shared-mime-info fonts-inter+ # Upper-bounded so a major release cannot change rendering without+ # someone choosing it. The exact version is not pinned because+ # nothing compares rendered bytes.- name: Install render_white_paper Python depsrun: |python -m pip install --quiet --upgrade pip- python -m pip install --quiet 'markdown>=3.5' 'weasyprint>=60'+ python -m pip install --quiet 'markdown>=3.5,<4' 'weasyprint>=60,<70'- name: Render every paper (make papers)run: make papers- - name: Diff rendered PDFs vs. tree- id: diff+ - name: Every source produced a PDFrun: |set -euo pipefail- if git diff --quiet -- 'apps/web/public/papers/*.pdf'; then- echo "changed=false" >> "$GITHUB_OUTPUT"- echo "::notice::No paper PDFs changed."- else- echo "changed=true" >> "$GITHUB_OUTPUT"- echo "::notice::The following PDFs changed and will be committed:"- git diff --name-only -- 'apps/web/public/papers/*.pdf'+ missing=0+ for src in apps/web/content/papers/*.md; do+ name="$(basename "${src%.md}")"+ case "$name" in _*) continue ;; esac+ if [ ! -s "apps/web/public/papers/$name.pdf" ]; then+ echo "::error::$src rendered no PDF at apps/web/public/papers/$name.pdf"+ missing=$((missing + 1))+ fi+ done+ if [ "$missing" -ne 0 ]; then+ echo "$missing paper(s) failed to render."+ exit 1fi+ echo "Every paper source rendered to a non-empty PDF."- - name: Upload rendered PDFs as artifact (always)+ - name: Upload rendered PDFs as artifactuses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7with:name: papers-pdf-${{ github.sha }}path: apps/web/public/papers/*.pdf- if-no-files-found: warn+ if-no-files-found: errorretention-days: 30-- # Only push back on main — never on PRs (we cannot trust PRs from- # forks with write tokens, and even for same-repo PRs the right- # surface is the artifact + a manual rebase).- - name: Commit refreshed PDFs back to main- if: |- github.event_name == 'push' &&- github.ref == 'refs/heads/main' &&- steps.diff.outputs.changed == 'true'- env:- GIT_AUTHOR_NAME: aisoc-papers-bot- GIT_AUTHOR_EMAIL: [email protected]- GIT_COMMITTER_NAME: aisoc-papers-bot- GIT_COMMITTER_EMAIL: [email protected]- run: |- set -euo pipefail- git add apps/web/public/papers/*.pdf- git commit -m "chore(papers): refresh rendered PDFs from $(git rev-parse --short HEAD) [skip ci]"- # If the underlying ref has moved while we were rendering,- # rebase onto the new HEAD. The PDF output is deterministic- # for a given markdown source, so re-rendering on the new- # base would produce the same bytes — a rebase is safe.- git pull --rebase origin main- git push origin HEAD:maindiff --git a/CHANGELOG.md b/CHANGELOG.mdindex e6b5cadbb..bba472cf1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -601,6 +601,50 @@ number is the one the requirement is sized against.### Fixed+- **The `Public papers (regenerate PDFs)` workflow could never succeed on+ `main`, and its design hid that from everyone opening a PR.** Its final step+ pushed refreshed PDFs directly to `main`, which stopped being possible when+ `main` became branch-protected — the push is rejected with+ `GH006: Protected branch update failed`. Because that step is skipped on pull+ requests, the workflow passed on every branch and failed only on `main`, so+ contributors saw green while `main` carried a permanently red workflow.+ Redirecting it to open a pull request instead is not available either: this+ repository has Actions set to read-only permissions with pull-request+ creation disabled.++ It now reports staleness rather than repairing it, and `make papers` plus a+ commit is the documented refresh path. The check compares each markdown+ source's SHA-256 against the digest recorded when its PDF was last rendered+ (`apps/web/public/papers/render-manifest.json`, written by `make papers`).+ It deliberately does **not** compare PDF bytes — the workflow's own comment+ asserted the render was deterministic, and it is not: WeasyPrint stamps a+ creation timestamp into its output and glyph metrics depend on the host's+ installed fonts, so two correct renders of one source differ and a byte+ comparison would fail for reasons unrelated to staleness. Each of the five+ conditions it claims to catch — edited source, missing PDF, unrecorded+ render, orphaned manifest entry, and no sources at all — is now asserted by+ a `--self-test` that runs as its own CI step ahead of the gate, so a check+ that has stopped detecting anything cannot report the tree clean. Each rule+ was then removed in turn to confirm the self-test fails without it. The run+ also fails if any source renders no PDF, which nothing previously checked.++ Adding a verdict mode made this script a gate, which `check_gate_contract.py`+ then judged by the same contract as the other 85: it reported that the script+ derived its repository root from `__file__` rather than asking git, and that+ it declared no self-test. Both are fixed. The control case in that self-test+ earned its place immediately — a nested helper assigned to the module paths+ without a `global` declaration, so all five cases silently graded the real+ tree, and only the case that *expects* a pass revealed it.++ Two things fell out of the change. `apps/web/public/papers/README.md` told+ readers "you no longer have to run the renderer locally before opening a PR"+ and described the commit-back step as current behaviour; both were false and+ are corrected. And the removed step set a commercial email domain as the+ commit author inside the open-source repository, so its `check_hosted_hostname.py`+ allow-list entry went with it — caught by that gate's own staleness check,+ which reported an exemption recording two occurrences in a file that now has+ none.+- **`check_mock_data_gated.py` reported "All sample-data fallbacks are gatedbehind demo mode." on a tree carrying nine of them.** Each gap was confirmedby running the gate's own patterns against the live lines rather than bydiff --git a/apps/web/public/papers/README.md b/apps/web/public/papers/README.mdindex 51c73cd4f..b3565e720 100644--- a/apps/web/public/papers/README.md+++ b/apps/web/public/papers/README.md@@ -54,22 +54,37 @@ When adding a new paper:2. Add a YAML frontmatter block with `title`, `subtitle`, `author`,`date`, and `version` keys (the render script reads these for thecover page).-3. Run the render script to produce the PDF.-4. Add an entry to the index table above.-5. Link the PDF from the relevant docs concept page or marketing surface.--Do not commit PDFs without their matching markdown source. CI now-rebuilds PDFs automatically via-[`.github/workflows/papers.yml`](../../../../.github/workflows/papers.yml)-on every push to `main` that touches a paper's markdown source —-**you no longer have to run the renderer locally before opening a-PR**. The workflow:--1. Builds every paper using the same WeasyPrint stack.-2. Uploads the rendered PDFs as a workflow artifact (visible on every- run — useful for PR preview).-3. On `main` only, commits any changed PDFs back as- `chore(papers): refresh rendered PDFs from <sha> [skip ci]`.+3. Run `make papers` to produce the PDF and record its source digest.+4. Commit the markdown, the PDF and `render-manifest.json` together.+5. Add an entry to the index table above.+6. Link the PDF from the relevant docs concept page or marketing surface.++Do not commit PDFs without their matching markdown source.++**Editing a paper's markdown means running `make papers` and committing+the result in the same change.** CI does not refresh PDFs for you. It+once did, pushing a `chore(papers)` commit straight to `main`, but that+stopped working when `main` became branch-protected — the push is+rejected with `GH006`. Opening a pull request instead is not available+either, because this repository has Actions set to read-only permissions+with pull-request creation disabled.++So [`.github/workflows/papers.yml`](../../../../.github/workflows/papers.yml)+reports rather than repairs:++1. Fails if any committed PDF is older than its markdown source, naming+ the papers to re-render.+2. Renders every paper, so a markdown change that breaks rendering fails+ the build rather than shipping a broken PDF.+3. Fails if any source produced no PDF.+4. Uploads the rendered PDFs as an artifact, useful for previewing a PR.++Staleness is judged by comparing each source's SHA-256 against the digest+recorded in `render-manifest.json` when its PDF was last rendered, which+`make papers` updates. PDF bytes are deliberately not compared: WeasyPrint+stamps a creation timestamp into its output and glyph metrics depend on+the host's installed fonts, so two correct renders of the same source are+not byte-identical. Commit `render-manifest.json` alongside the PDF.The hosted PDF is the public artefact; the markdown is the canonicalone.diff --git a/apps/web/public/papers/render-manifest.json b/apps/web/public/papers/render-manifest.jsonnew file mode 100644index 000000000..f6eaac477--- /dev/null+++ b/apps/web/public/papers/render-manifest.json@@ -0,0 +1,5 @@+{+ "sources": {+ "l0-l4-automation-maturity.md": "4da4b02d8e7b6d2839a593f09303191cd71c6b9ef28b34555a1a2086cf4c8781"+ }+}\ No newline at end of filediff --git a/scripts/check_hosted_hostname.py b/scripts/check_hosted_hostname.pyindex 921e94188..52592b4cb 100644--- a/scripts/check_hosted_hostname.py+++ b/scripts/check_hosted_hostname.py@@ -124,7 +124,6 @@ ALLOWED: dict[str, tuple[int, str]] = {"apps/web/fly.toml": (4, _MANAGED_DEPLOY),"scripts/demo-public.sh": (3, _MANAGED_DEPLOY),"scripts/adoption_snapshot.py": (1, _MANAGED_DEPLOY),- ".github/workflows/papers.yml": (2, _MANAGED_DEPLOY),".github/FUNDING.yml": (1, _MANAGED_DEPLOY),".github/ISSUE_TEMPLATE/benchmark_submission.yml": (2, _MANAGED_DEPLOY),"apps/web/e2e/demo/screencast.spec.ts": (1, _MANAGED_DEPLOY),diff --git a/scripts/render_white_paper.py b/scripts/render_white_paper.pyindex d86eb7e19..4bdd0c2e0 100755--- a/scripts/render_white_paper.py+++ b/scripts/render_white_paper.py@@ -28,14 +28,33 @@ is already part of the AiSOC build profile for the API service.from __future__ import annotationsimport argparse+import hashlib+import jsonimport reimport sys+import tempfilefrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent+# `scripts/` is on sys.path when this file is run as a program, but not when a+# sibling imports it.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_main # noqa: E402++REPO_ROOT = repo_root()DEFAULT_SRC_DIR = REPO_ROOT / "apps" / "web" / "content" / "papers"DEFAULT_OUT_DIR = REPO_ROOT / "apps" / "web" / "public" / "papers"+# Records the digest of each markdown source at the moment its PDF was+# rendered, so `--check` can tell a stale PDF from a current one.+#+# The digest is taken over the *source markdown*, never the rendered PDF.+# WeasyPrint stamps a creation timestamp into its output and glyph metrics+# depend on which fonts the host happens to have installed, so two correct+# renders of one source do not produce equal bytes. A PDF byte comparison+# would therefore fail for reasons that have nothing to do with staleness.+MANIFEST_PATH = DEFAULT_OUT_DIR / "render-manifest.json"+PRINT_CSS = """@page {size: A4;@@ -249,6 +268,40 @@ def _discover() -> list[tuple[Path, Path]]:return pairs+def _source_digest(path: Path) -> str:+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def _display(path: Path) -> str:+ """Repository-relative where possible, absolute where not.++ The gate-contract harness and ``--self-test`` both point this script at a+ tree outside ``REPO_ROOT``, where ``relative_to`` raises.+ """+ try:+ return str(path.relative_to(REPO_ROOT))+ except ValueError:+ return str(path)+++def _read_manifest() -> dict[str, str]:+ if not MANIFEST_PATH.exists():+ return {}+ try:+ loaded = json.loads(MANIFEST_PATH.read_text())+ except json.JSONDecodeError:+ return {}+ sources = loaded.get("sources")+ return sources if isinstance(sources, dict) else {}+++def _record_rendered(sources: dict[str, str]) -> None:+ """Merge digests for the papers just rendered into the manifest."""+ merged = {**_read_manifest(), **sources}+ MANIFEST_PATH.parent.mkdir(parents=True, exist_ok=True)+ MANIFEST_PATH.write_text(json.dumps({"sources": dict(sorted(merged.items()))}, indent=2) + "\n")++def _render_all() -> None:pairs = _discover()if not pairs:@@ -259,6 +312,104 @@ def _render_all() -> None:returnfor src, dst in pairs:_render_one(src, dst)+ _record_rendered({src.name: _source_digest(src) for src, _ in pairs})+++def _check() -> int:+ """Report papers whose PDF is missing or older than its source.++ Needs no rendering stack, so it runs anywhere python does.+ """+ pairs = _discover()+ if not pairs:+ print(+ f"[render_white_paper] refusing to pass: no markdown sources under {DEFAULT_SRC_DIR}",+ file=sys.stderr,+ )+ return 1++ manifest = _read_manifest()+ problems: list[str] = []++ for src, pdf in pairs:+ if not pdf.exists():+ problems.append(f"{_display(pdf)} does not exist")+ continue+ recorded = manifest.get(src.name)+ if recorded is None:+ problems.append(f"{src.name} has a PDF but no recorded render")+ elif recorded != _source_digest(src):+ problems.append(f"{src.name} changed since its PDF was rendered")++ known = {src.name for src, _ in pairs}+ for orphan in sorted(set(manifest) - known):+ problems.append(f"{orphan} is recorded but its source is gone")++ if problems:+ print("[render_white_paper] rendered PDFs are out of date:", file=sys.stderr)+ for problem in problems:+ print(f" - {problem}", file=sys.stderr)+ print(+ "\nRun `make papers` and commit the result. CI cannot refresh them for\n"+ "you: main is branch-protected, so a workflow cannot push to it.",+ file=sys.stderr,+ )+ return 1++ print(f"[render_white_paper] {len(pairs)} paper(s) up to date with their sources")+ return 0+++def _injected_defect_cases() -> list[tuple[str, bool]]:+ """Plant each defect ``--check`` claims to catch and require a refusal.++ The control case matters as much as the rest: a gate that refused+ everything would "detect" all four defects and be useless, so a+ well-formed paper is required to pass.+ """+ global DEFAULT_SRC_DIR, DEFAULT_OUT_DIR, MANIFEST_PATH++ def plant(root: Path, *, pdf: bool, recorded: str | None, orphan: bool) -> None:+ # Without this, the assignments below bind locals to `plant` and every+ # case silently grades the real tree instead of the planted one.+ global DEFAULT_SRC_DIR, DEFAULT_OUT_DIR, MANIFEST_PATH++ src_dir, out_dir = root / "content", root / "public"+ src_dir.mkdir(parents=True)+ out_dir.mkdir(parents=True)+ source = src_dir / "paper.md"+ source.write_text("# a paper\n")+ if pdf:+ (out_dir / "paper.pdf").write_bytes(b"%PDF-1.7 not a real render\n")+ entries: dict[str, str] = {}+ if recorded == "match":+ entries["paper.md"] = _source_digest(source)+ elif recorded == "stale":+ entries["paper.md"] = "0" * 64+ if orphan:+ entries["deleted.md"] = "0" * 64+ DEFAULT_SRC_DIR, DEFAULT_OUT_DIR = src_dir, out_dir+ MANIFEST_PATH = out_dir / "render-manifest.json"+ MANIFEST_PATH.write_text(json.dumps({"sources": entries}) + "\n")++ cases: list[tuple[str, dict[str, object], bool]] = [+ ("a paper whose PDF matches its recorded source passes", {"pdf": True, "recorded": "match", "orphan": False}, True),+ ("a source edited since its PDF was rendered is refused", {"pdf": True, "recorded": "stale", "orphan": False}, False),+ ("a source with no PDF at all is refused", {"pdf": False, "recorded": "match", "orphan": False}, False),+ ("a PDF with no recorded render is refused", {"pdf": True, "recorded": None, "orphan": False}, False),+ ("a recorded paper whose source is gone is refused", {"pdf": True, "recorded": "match", "orphan": True}, False),+ ]++ saved = (DEFAULT_SRC_DIR, DEFAULT_OUT_DIR, MANIFEST_PATH)+ results: list[tuple[str, bool]] = []+ try:+ for description, shape, should_pass in cases:+ with tempfile.TemporaryDirectory() as tmp:+ plant(Path(tmp), **shape) # type: ignore[arg-type]+ results.append((description, (_check() == 0) is should_pass))+ finally:+ DEFAULT_SRC_DIR, DEFAULT_OUT_DIR, MANIFEST_PATH = saved+ return resultsdef main(argv: list[str] | None = None) -> int:@@ -276,15 +427,38 @@ def main(argv: list[str] | None = None) -> int:action="store_true",help=("Render every paper under apps/web/content/papers/. Default when neither --input nor --output is supplied."),)+ parser.add_argument(+ "--check",+ action="store_true",+ help=("Report papers whose PDF is missing or older than its source. Renders nothing."),+ )+ parser.add_argument(+ "--self-test",+ action="store_true",+ help=("Prove --check still detects each defect it claims to, then exit. Renders nothing."),+ )args = parser.parse_args(argv)+ if args.self_test:+ return self_test_main(Path(__file__).name, ["--check"], extra=_injected_defect_cases())++ if args.check and (args.input or args.output or args.all):+ parser.error("--check renders nothing, so it takes no other arguments")if args.input and not args.output:parser.error("--output is required when --input is supplied")if args.output and not args.input:parser.error("--input is required when --output is supplied")+ if args.check:+ return _check()+if args.input and args.output:- _render_one(Path(args.input), Path(args.output))+ source = Path(args.input)+ _render_one(source, Path(args.output))+ # Keep the manifest honest when a single paper is rendered in place,+ # so the next --check does not report a paper that was just refreshed.+ if source.resolve().parent == DEFAULT_SRC_DIR:+ _record_rendered({source.name: _source_digest(source)})else:_render_all()return 0