#!/usr/bin/env python3
"""CI/CD Pipeline Audit — checks every repo against the solo-dev checklist."""
from __future__ import annotations
import json
import os
import re
import sys
import urllib.error
import urllib.request
from pathlib import Path
from collections import defaultdict
try:
import yaml
except ImportError:
# Bare python3 may lack PyYAML (run.sh starts the server without the venv on
# PATH). Retry once under the server's own interpreter.
_alt = os.environ.get("GRIMOIRE_PYTHON")
if _alt and not os.environ.get("_GRIMOIRE_AUDIT_REEXEC"):
os.environ["_GRIMOIRE_AUDIT_REEXEC"] = "1"
os.execv(_alt, [_alt, *sys.argv])
print("FATAL: PyYAML not installed — run: pip install pyyaml")
sys.exit(1)
WORKFLOWS = Path(".github/workflows")
_ALL_RESULTS: list[dict] = [] # accumulates (check_id, passed, file_ref, notes)
def _r(check_id: str, passed: bool, file_ref: str = "", notes: str = "",
unknown: bool = False) -> dict:
"""Record a result. ``unknown`` marks a rule that could not be verified; it
never counts as a pass."""
entry = dict(check_id=check_id, passed=passed and not unknown,
file_ref=file_ref, notes=notes, unknown=unknown)
_ALL_RESULTS.append(entry)
return entry
# Stable rule IDs and remediation. The label numbers in the table ("9a") are
# positional and may change; these IDs never do.
_RULES = {
"0": ("CI-WORKFLOWS-001", "Add .github/workflows/ with a test-build-release.yml pipeline"),
"Parse": ("CI-PARSE-001", "Fix the YAML syntax error in the workflow file"),
"1a": ("CI-LAYOUT-001", "Name the pipeline test-build-release.yml"),
"1b": ("CI-LAYOUT-002", "Move deploy into a separate deploy.yml"),
"1c": ("CI-LAYOUT-003", "Delete the unused staging workflow"),
"1d": ("CI-LAYOUT-004", "Rename workflow files to kebab-case"),
"1e": ("CI-LAYOUT-005", "Give .github/actions/ entries specific names"),
"2a": ("CI-TRIGGER-001", "Trigger the pipeline on push (deploy on workflow_run)"),
"2b": ("CI-TRIGGER-002", "Trigger the pipeline on pull_request"),
"2c": ("CI-CONCURRENCY-001", "Add concurrency with cancel-in-progress: true to the pipeline"),
"2d": ("CI-CONCURRENCY-002", "Set cancel-in-progress: false on the deploy"),
"3a": ("CI-ORDER-001", "Chain jobs with needs:"),
"3b": ("CI-ORDER-002", "Make test jobs depend on lint"),
"3c": ("CI-ORDER-003", "Make build depend on the test jobs"),
"3d": ("CI-ORDER-004", "Order release and build with needs:"),
"3e": ("CI-ORDER-005", "Remove continue-on-error from gate jobs"),
"3f": ("CI-DEPLOY-CHAIN-001", "Trigger deploy from the pipeline via workflow_run, not push"),
"3g": ("CI-DEPLOY-CHAIN-002", "Download the build artifact in deploy instead of rebuilding"),
"4a": ("CI-ARTIFACT-001", "Download the uploaded artifact in the deploy workflow"),
"4b": ("CI-ARTIFACT-002", "Embed the version or commit SHA in the artifact"),
"5b": ("CI-DEPLOY-001", "Run deploy after the pipeline"),
"5c": ("CI-DEPLOY-002", "Verify the artifact before deploying"),
"5d": ("CI-DEPLOY-003", "Add environment: production to the deploy job"),
"5e": ("CI-DEPLOY-AUTH-001", "Authenticate with OIDC (id-token: write) or a secrets.* credential"),
"5f": ("CI-SECRETS-001", "Move hardcoded credentials into GitHub secrets"),
"5g": ("CI-DEPLOY-004", "Make the deploy mechanism identifiable"),
"5h": ("CI-DEPLOY-005", "Add a rollback path to the deploy"),
"6a": ("CI-VERIFY-001", "Add a post-deploy smoke or health check"),
"6b": ("CI-VERIFY-002", "Put verification in its own named step"),
"6c": ("CI-VERIFY-003", "Fail the job when verification fails"),
"7a": ("CI-PROTECT-001", "Require status checks on the default branch"),
"7b": ("CI-PROTECT-002", "Protect the default branch (direct push by the owner is allowed)"),
"8a": ("CI-PIN-001", "Pin actions to a commit SHA or OCI digest"),
"8b": ("CI-CACHE-001", "Cache dependencies (actions/cache or the setup-* cache input)"),
"9a": ("CI-PERM-001", "Declare permissions: at workflow level or on every job"),
"9b": ("CI-OIDC-001", "Prefer OIDC for cloud authentication"),
"9c": ("CI-SECRETS-002", "Do not echo secrets in run steps"),
}
_TITLE_RULES = {
"setup-python cache value is valid": (
"CI-CACHE-002", "Use cache: pip|poetry|pipenv|uv with actions/setup-python"),
}
def _rule_info(check_id: str) -> tuple[str, str, str]:
"""Return (stable id, title, remediation) for a result label."""
prefix, _, title = check_id.partition(". ")
title = re.sub(r"\s*\[[^\]]*\]$", "", title).strip()
rid, fix = _TITLE_RULES.get(title) or _RULES.get(prefix, ("CI-UNMAPPED", "See the audit notes"))
return rid, title, fix
def _early() -> int:
"""Exit path for repos with no workflows: nothing to fail."""
if "--json" in sys.argv[1:]:
rid, title, _ = _rule_info(_ALL_RESULTS[-1]["check_id"])
print(json.dumps({
"repository": os.environ.get("REPO_FULL_NAME", "unknown"),
"branch": os.environ.get("BRANCH", "unknown"),
"summary": {"total": 1, "passed": 1, "failed": 0,
"critical": 0, "high": 0, "medium": 0},
"rules": [{"rule": rid, "title": title, "status": "pass", "file": "N/A",
"remediation": "", "notes": _ALL_RESULTS[-1]["notes"]}],
}, indent=2))
return 0
def _sev(level: str) -> None:
"""Tag the most recent result with the severity of its failure."""
_ALL_RESULTS[-1]["severity"] = level
class _GHA_Loader(yaml.SafeLoader):
"""SafeLoader that preserves GitHub Actions' ``on`` keyword.
PyYAML (YAML 1.1) interprets bare ``on:`` as a boolean ``True``,
which destroys the trigger section of every workflow file.
This loader removes the ``o``/``O`` first-character resolver so
``on`` and ``off`` remain string keys.
"""
for _ch in ["o", "O"]:
_GHA_Loader.yaml_implicit_resolvers.pop(_ch, None)
def load_yaml(path: Path) -> dict | None:
"""Load a GitHub Actions workflow YAML, preserving ``on`` as a key."""
try:
with open(path) as f:
data = yaml.load(f, Loader=_GHA_Loader)
return data if isinstance(data, dict) else None
except Exception as exc:
return None
def workflow_names(wf: dict) -> list[str]:
"""Return the name(s) of a workflow (top-level or keys under jobs)."""
return [wf.get("name", "unnamed")]
# ── Helpers ──────────────────────────────────────────────────────────────
def _find_files(*patterns: str) -> list[Path]:
"""Return workflow files sorted by name."""
found: list[Path] = []
for pat in patterns:
found.extend(sorted(WORKFLOWS.glob(pat)))
return found
def _all_yml() -> list[Path]:
return _find_files("*.yml", "*.yaml")
def _ci_cd_files(files: list[Path]) -> list[Path]:
"""Files that look like the primary CI/CD pipeline."""
keywords = ["ci-cd", "ci", "test", "build", "release", "pipeline"]
return [f for f in files if any(kw in f.stem.lower() for kw in keywords)]
def _deploy_files(files: list[Path]) -> list[Path]:
return [f for f in files if "deploy" in f.stem.lower()]
def _staging_files(files: list[Path]) -> list[Path]:
return [f for f in files if "staging" in f.stem.lower()]
def _permissions_block(wf: dict) -> dict | str | None:
"""Return the top-level permissions value, or None."""
return wf.get("permissions")
def _describe_permissions(perm: object) -> str:
if isinstance(perm, dict):
return ", ".join(f"{k}:{v}" for k, v in perm.items()) or "none"
return str(perm)
def _permission_scope(wf: dict) -> tuple[bool, str]:
"""Return (explicit, note) for a workflow's token scope.
A workflow is explicit when it has a top-level ``permissions:`` block, or when
every job declares its own. Job-level scope is narrower, so it is accepted.
"""
perm = _permissions_block(wf)
if perm is not None:
return True, f"Scoped: {_describe_permissions(perm)}"
jobs = {k: v for k, v in _jobs(wf).items() if isinstance(v, dict)}
inheriting = [j for j, d in jobs.items() if d.get("permissions") is None]
if jobs and not inheriting:
detail = "; ".join(
f"{j}={_describe_permissions(d['permissions'])}" for j, d in jobs.items()
)
return True, f"Scoped (job-level): {detail}"
if inheriting:
return False, (
"Uses broad default token scope — no top-level block and "
f"job(s) without permissions: {', '.join(inheriting)}"
)
return False, "Missing — uses broad default token scope"
def _has_concurrency(wf: dict) -> bool:
return "concurrency" in wf
def _concurrency_cancel(wf: dict) -> bool | None:
c = wf.get("concurrency")
if isinstance(c, dict):
return c.get("cancel-in-progress", False)
return None # string form, not inspectable
def _jobs(wf: dict) -> dict:
return wf.get("jobs", {})
def _job_names(jobs: dict) -> list[str]:
return list(jobs.keys())
def _needs(job_def: dict) -> list[str]:
n = job_def.get("needs")
if isinstance(n, str):
return [n]
if isinstance(n, list):
return n
return []
def _uses_actions(job_def: dict) -> list[str]:
"""Collect all `uses:` values from steps."""
refs: list[str] = []
if isinstance(job_def.get("uses"), str):
refs.append(job_def["uses"]) # reusable workflow call
for step in job_def.get("steps") or []:
if isinstance(step, dict) and isinstance(step.get("uses"), str):
refs.append(step["uses"])
return refs
_SHA_RE = re.compile(r"^[0-9a-f]{40}$")
_DIGEST_RE = re.compile(r"@sha256:[0-9a-f]{64}$")
_FLOATING_RE = re.compile(r"^v?\d+(\.\d+)?$")
_VERSION_RE = re.compile(r"^v?\d+\.\d+\.\d+([-+][0-9A-Za-z.-]+)?$")
def _classify_ref(ref: str) -> str:
"""Classify a ``uses:`` ref.
Returns one of ``local`` (skipped), ``sha`` (40-char commit), ``digest``
(OCI ``@sha256:``), ``version`` (exact tag such as ``v6.1.2``),
``floating-major`` (``v6`` or ``v6.1``, which the owner can move) or
``unpinned`` (branch, no ref, or an untagged/tagged image).
"""
if ref.startswith("./"):
return "local"
if ref.startswith("docker://"):
return "digest" if _DIGEST_RE.search(ref) else "unpinned"
_, sep, version = ref.partition("@")
if not sep or not version:
return "unpinned"
if _SHA_RE.match(version):
return "sha"
if _VERSION_RE.match(version):
return "version"
if _FLOATING_RE.match(version):
return "floating-major"
return "unpinned"
_SETUP_CACHE_VALUES = {
"setup-python": {"pip", "poetry", "pipenv", "uv"},
"setup-node": {"npm", "yarn", "pnpm"},
"setup-java": {"gradle", "maven", "sbt"},
}
def _cache_mechanism(uses: str, with_: object) -> str | None:
"""Name the caching mechanism a step uses, if any.
Returns ``invalid-setup-python-cache-true`` for the value setup-python
rejects at runtime, so the caller can flag it instead of crediting it.
"""
action = uses.split("@", 1)[0].lower()
inputs = with_ if isinstance(with_, dict) else {}
if action == "actions/cache" or action.startswith("actions/cache/"):
return "actions/cache"
if action == "swatinem/rust-cache":
return "rust-cache"
if action == "astral-sh/setup-uv":
return "setup-uv enable-cache" if inputs.get("enable-cache") in (True, "true") else None
name = action.rsplit("/", 1)[-1]
cache = inputs.get("cache")
if name == "setup-python" and cache in (True, "true"):
return "invalid-setup-python-cache-true"
if name == "setup-go" and cache in (True, "true"):
return "setup-go cache=true"
if name in _SETUP_CACHE_VALUES and str(cache).lower() in _SETUP_CACHE_VALUES[name]:
return f"{name} cache={str(cache).lower()}"
return None
def _deploy_auth(deploy_text: str) -> str | None:
"""Name how the deploy authenticates, or None when nothing is evident."""
if re.search(r"id-token['\"]?\s*:\s*['\"]?write", deploy_text):
return "OIDC (id-token: write)"
names = sorted(set(re.findall(r"\$\{\{\s*secrets\.([A-Za-z0-9_]+)", deploy_text)))
if names:
return "secrets: " + ", ".join(names)
return None
def _reachable(deps: dict[str, set[str]], job: str) -> set[str]:
"""Every job ``job`` depends on, directly or through other jobs."""
seen: set[str] = set()
stack = list(deps.get(job, ()))
while stack:
cur = stack.pop()
if cur not in seen:
seen.add(cur)
stack.extend(deps.get(cur, ()))
return seen
def _api_get(url: str, token: str) -> tuple[int, object]:
"""GET a GitHub API URL. Returns (status, json); status 0 on network error."""
req = urllib.request.Request(url, headers={
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
})
try:
with urllib.request.urlopen(req, timeout=20) as resp:
return resp.status, json.loads(resp.read() or b"null")
except urllib.error.HTTPError as exc:
return exc.code, None
except Exception as exc: # noqa: BLE001 — surfaced as "unknown", never a pass
return 0, str(exc)
def _branch_protection() -> tuple[dict | None, list | None, str]:
"""Return (classic, rulesets, problem). ``problem`` is set when unreadable."""
repo = os.environ.get("REPO_FULL_NAME", "")
token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN", "")
branch = os.environ.get("DEFAULT_BRANCH") or os.environ.get("BRANCH") or "main"
if "/" not in repo:
return None, None, "REPO_FULL_NAME is not set"
if not token:
return None, None, "no GH_TOKEN; cannot read branch protection"
base = os.environ.get("GITHUB_API_URL", "https://api.github.com").rstrip("/")
c_status, classic = _api_get(f"{base}/repos/{repo}/branches/{branch}/protection", token)
r_status, rules = _api_get(f"{base}/repos/{repo}/rules/branches/{branch}", token)
if c_status not in (200, 404) and r_status != 200:
return None, None, (
f"protection API HTTP {c_status}, rulesets API HTTP {r_status}; "
"check the token's administration read permission"
)
return (
classic if c_status == 200 and isinstance(classic, dict) else None,
rules if r_status == 200 and isinstance(rules, list) else None,
"",
)
def _protection_findings(classic: dict | None, rules: list | None) -> list[str]:
"""Return the required status check names.
Direct push to the default branch is allowed (solo-owner policy), so
neither a pull request nor an approving review is required.
"""
rules = rules or []
checks: list[str] = []
if classic:
rsc = classic.get("required_status_checks") or {}
checks += list(rsc.get("contexts") or [])
checks += [c.get("context", "") for c in rsc.get("checks") or [] if isinstance(c, dict)]
for rule in rules:
if isinstance(rule, dict) and rule.get("type") == "required_status_checks":
params = rule.get("parameters") or {}
checks += [c.get("context", "") for c in params.get("required_status_checks") or []
if isinstance(c, dict)]
return sorted({c for c in checks if c})
def _find_trigger_events(wf: dict) -> list[str]:
on = wf.get("on", {})
if isinstance(on, str):
return [on]
if isinstance(on, list):
return on
return list(on.keys())
# ── Audit runner ─────────────────────────────────────────────────────────
def audit() -> int:
if not WORKFLOWS.is_dir():
_r("0. Workflows directory exists", True, "N/A",
"No .github/workflows/ — repo doesn't use CI/CD")
return _early() # not a failure, just no CI
yml_files = _all_yml()
if not yml_files:
_r("0. Workflow files exist", True, "N/A",
"Directory exists but empty — no CI pipeline defined")
return _early()
# Load all workflows
workflows: dict[str, dict] = {}
for f in yml_files:
wf = load_yaml(f)
if wf:
workflows[f.name] = wf
else:
_r(f"Parse {f.name}", False, f.name, "Failed to parse YAML")
_sev("critical")
ci_cd = _ci_cd_files(yml_files)
deploy_wf = _deploy_files(yml_files)
staging = _staging_files(yml_files)
# ── 1. FILE STRUCTURE ────────────────────────────────────────────────
# 1a: Primary pipeline file naming (pragmatic: check pattern)
if ci_cd:
primary = ci_cd[0]
expected = ["test-build-release", "ci-cd"]
is_named_ok = any(e in primary.stem.lower() for e in expected)
if is_named_ok:
_r("1a. Pipeline file follows naming convention", True,
primary.name, f"Named {primary.stem}.yml — OK")
else:
_r("1a. Pipeline file follows naming convention", True,
primary.name, f"Named {primary.stem}.yml — non-standard but functional")
else:
# Fall back to any workflow file
candidates = [f for f in yml_files if "ci" in f.stem.lower() or "test" in f.stem.lower() or "build" in f.stem.lower()]
if candidates:
_r("1a. CI/CD pipeline file exists", True,
candidates[0].name, f"Working with {candidates[0].name}")
else:
_r("1a. CI/CD pipeline file exists", False,
yml_files[0].name, "No identifiable CI/CD pipeline file")
_sev("high")
# 1b: Separate deploy file
if deploy_wf:
_r("1b. Separate deploy workflow exists", True,
deploy_wf[0].name, "")
has_separate_deploy = True
else:
# Check if deploy is embedded in the pipeline
has_embedded_deploy = any(
"deploy" in j.lower()
for wf_name, wf in workflows.items()
for j in _job_names(_jobs(wf))
)
if has_embedded_deploy:
_r("1b. Separate deploy workflow exists", True,
"embedded", "Deploy job integrated in pipeline workflow")
has_separate_deploy = True
else:
_r("1b. Separate deploy workflow exists", True,
"N/A", "No deploy stage — repo is library/tool without deployment")
has_separate_deploy = False
# 1c: No staging leftovers
if staging:
_r("1c. No unused staging workflow", False,
staging[0].name, "Staging workflow found — solo dev: prod only")
_sev("medium")
else:
_r("1c. No unused staging workflow", True, "N/A", "")
# 1d: File naming (kebab-case, verb-noun)
bad_names = [f.name for f in yml_files if "_" in f.stem]
if bad_names:
_r("1d. Kebab-case filenames", False,
bad_names[0], f"Underscore in name: {bad_names[0]}")
_sev("medium")
else:
_r("1d. Kebab-case filenames", True, "N/A", "")
# 1e: Action names under .github/actions/
actions_dir = WORKFLOWS.parent / "actions"
if actions_dir.is_dir():
generic = [d.name for d in actions_dir.iterdir() if d.is_dir() and d.name in ("setup", "utils", "common")]
if generic:
_r("1e. Action names are specific", False,
f".github/actions/{generic[0]}", f"Generic name: {generic[0]}")
_sev("medium")
# ── 2. TRIGGERS ──────────────────────────────────────────────────────
for fname, wf in workflows.items():
events = _find_trigger_events(wf)
has_push = "push" in events
has_pr = "pull_request" in events
# A reusable workflow (workflow_call) is started by its caller, which owns
# the real trigger, so it can never carry a push or workflow_run of its own.
has_wf_run = bool({"workflow_run", "workflow_dispatch", "workflow_call"} & set(events))
is_deploy = "deploy" in fname.lower()
if is_deploy:
valid_trigger = has_wf_run or has_push
_r(f"2a. trigger [{fname}]", valid_trigger, fname, "" if valid_trigger else "Deploy workflow missing workflow_run or push trigger")
if not valid_trigger:
_sev("high")
elif ci_cd and fname == ci_cd[0].name:
_r(f"2a. push trigger [{fname}]", has_push, fname, "" if has_push else "Primary workflow missing push trigger")
if not has_push:
_sev("high")
else:
_r(f"2a. push trigger [{fname}]", True, fname,
f"Auxiliary workflow — push not required (on: {', '.join(events)})")
if ci_cd and fname == ci_cd[0].name:
_r(f"2b. pull_request trigger [{fname}]", has_pr, fname, "")
if not has_pr:
_sev("medium")
# 2c: concurrency on CI/CD file
if ci_cd:
wf = workflows.get(ci_cd[0].name, {})
has_conc = _has_concurrency(wf)
cancel = _concurrency_cancel(wf)
if has_conc:
if cancel is True:
_r("2c. concurrency + cancel-in-progress: true", True,
ci_cd[0].name, "")
elif cancel is False:
_r("2c. concurrency + cancel-in-progress: true", False,
ci_cd[0].name,
"cancel-in-progress is false — test runs won't cancel on new pushes")
_sev("medium")
else:
_r("2c. concurrency exists", True,
ci_cd[0].name, "String-form concurrency — cancel not inspectable")
else:
_r("2c. concurrency defined", False,
ci_cd[0].name, "Missing — new pushes won't cancel superseded runs")
_sev("medium")
# 2d: deploy concurrency must NOT cancel-in-progress
ci_cd_jobs = _jobs(wf)
for jname, jdef in ci_cd_jobs.items():
if "deploy" in jname.lower():
job_conc = jdef.get("concurrency", {})
if isinstance(job_conc, dict):
if job_conc.get("cancel-in-progress", False):
_r("2d. Deploy cancel-in-progress: false", False,
f"{ci_cd[0].name} job:{jname}",
"Deploy concurrency has cancel-in-progress: true — can break production")
_sev("high")
if deploy_wf:
dwf = workflows.get(deploy_wf[0].name, {})
dep_conc = _has_concurrency(dwf)
dep_cancel = _concurrency_cancel(dwf)
if dep_conc and dep_cancel is True:
_r("2d. Deploy concurrency: cancel-in-progress false", False,
deploy_wf[0].name,
"Deploy must not cancel in-flight — can break production")
_sev("high")
elif dep_conc and dep_cancel is False:
_r("2d. Deploy concurrency: cancel-in-progress false", True,
deploy_wf[0].name, "")
elif dep_conc:
_r("2d. Deploy concurrency exists", True,
deploy_wf[0].name, "String-form concurrency — assume queuing")
else:
_r("2d. Deploy concurrency exists", True,
deploy_wf[0].name, "No concurrency block — defaults to queue")
# ── 3. JOB SEQUENCING ────────────────────────────────────────────────
if ci_cd:
wf = workflows.get(ci_cd[0].name, {})
jobs = _jobs(wf)
jnames = _job_names(jobs)
# Build a dependency graph
deps: dict[str, set[str]] = {}
for jname, jdef in jobs.items():
deps[jname] = set(_needs(jdef))
# Identify role of each job by name
lint_jobs = [j for j in jnames if "lint" in j.lower()]
test_jobs = [j for j in jnames if j.lower().startswith("test") or j == "ci" or "test" in j.lower()]
build_jobs = [j for j in jnames if "build" in j.lower()]
release_jobs = [j for j in jnames if "release" in j.lower() or "semantic" in j.lower() or "tag" in j.lower()]
# 3a: Has explicit needs between stages
has_needs = any(deps[j] for j in jnames)
_r("3a. Jobs use explicit needs:", has_needs, ci_cd[0].name,
f"Jobs: {', '.join(jnames)}" if jnames else "No jobs defined")
if not has_needs:
_sev("high")
# 3b: test has needs: lint (if lint is its own job)
if lint_jobs and test_jobs:
lint_name = lint_jobs[0]
test_has_lint = False
for tj in test_jobs:
if lint_name in _reachable(deps, tj):
test_has_lint = True
break
_r("3b. test needs: lint", test_has_lint, ci_cd[0].name,
f"test={test_jobs[0]}, lint={lint_name}" if test_has_lint
else f"Lint is own job but test doesn't depend on it")
if not test_has_lint:
_sev("high")
# 3c: build depends on a test job, directly or through other jobs
if build_jobs and test_jobs:
reached = [t for t in test_jobs if any(t in _reachable(deps, bj) for bj in build_jobs)]
build_has_test = bool(reached)
_r("3c. build needs: test", build_has_test, ci_cd[0].name,
f"build={build_jobs[0]}, test={reached[0]} (via needs chain)" if build_has_test
else "Build does not depend on test — could run before tests pass")
if not build_has_test:
_sev("critical")
# 3d: release and build are ordered either way: build-then-release, or
# tag-then-build (release computes the version, build compiles the tag)
if release_jobs and build_jobs:
build_first = any(
bj in _reachable(deps, rj) for rj in release_jobs for bj in build_jobs
)
release_first = any(
rj in _reachable(deps, bj) for rj in release_jobs for bj in build_jobs
)
ordered = build_first or release_first
_r("3d. release and build are ordered", ordered, ci_cd[0].name,
(f"release={release_jobs[0]}, build={build_jobs[0]} "
f"({'build then release' if build_first else 'tag then build'})")
if ordered else "Release and build have no needs: relationship")
if not ordered:
_sev("high")
# 3e: No continue-on-error on gate jobs
for jname, jdef in jobs.items():
coe = jdef.get("continue-on-error", False)
if coe and (jname in lint_jobs or jname in test_jobs or jname in build_jobs):
_r("3e. No continue-on-error on gates", False,
f"{ci_cd[0].name} job:{jname}",
"continue-on-error: true defeats stop-the-line")
_sev("high")
# 3f: deploy triggered by CI/CD (not independent push)
if deploy_wf:
dwf = workflows.get(deploy_wf[0].name, {})
devents = _find_trigger_events(dwf)
# Check for workflow_run on CI/CD file
wf_run = dwf.get("on", {}).get("workflow_run") if isinstance(dwf.get("on"), dict) else None
wf_call = dwf.get("on", {}).get("workflow_call") if isinstance(dwf.get("on"), dict) else None
has_chain = wf_run is not None or wf_call is not None
if has_chain:
# Check workflow_run has conclusion gate
if wf_run:
wf_name = ""
if isinstance(wf_run, dict):
wf_name = wf_run.get("workflows", [None])[0] if isinstance(wf_run.get("workflows"), list) else ""
wf_types = wf_run.get("types", [])
has_completed = "completed" in wf_types
# Check for conclusion check
steps = _jobs(dwf).get(list(_jobs(dwf).keys())[0], {}).get("steps", []) if _jobs(dwf) else []
has_conclusion_check = any(
"conclusion" in str(s) and "success" in str(s)
for s in steps
)
_r("3f. Deploy chained to pipeline", True, deploy_wf[0].name,
f"workflow_run" + (" + conclusion check" if has_conclusion_check else ""))
elif wf_call:
_r("3f. Deploy chained to pipeline", True, deploy_wf[0].name,
"workflow_call — explicitly called by pipeline")
else:
# Check for independent push
own_push = "push" in devents
if own_push:
_r("3f. Deploy chained to pipeline, not push", False,
deploy_wf[0].name, "Has its own push trigger — can fire outside pipeline")
_sev("high")
else:
_r("3f. Deploy trigger mechanism", True, deploy_wf[0].name,
f"Triggered by: {', '.join(devents)}")
# 3g: Deploy doesn't contain build steps
if deploy_wf:
dwf_name = deploy_wf[0].name
dwf_data = workflows.get(dwf_name, {})
for jname, jdef in _jobs(dwf_data).items():
all_steps_str = str(jdef)
build_refs = ["npm run build", "cargo build", "go build", "python -m build",
"npm run dist", "make build"]
found_builds = [ref for ref in build_refs if ref in all_steps_str]
if found_builds:
_r("3g. Deploy does not rebuild", False,
f"{dwf_name} job:{jname}",
f"Contains build steps: {', '.join(found_builds)}")
_sev("high")
else:
# Check if deploy is a job in the CI/CD pipeline with needs
for jname, jdef in jobs.items():
if "deploy" in jname.lower():
deploy_needs = _needs(jdef)
if deploy_needs:
_r("3f. Deploy job chained via needs:", True,
f"{ci_cd[0].name} job:{jname}",
f"needs: {', '.join(deploy_needs)}")
else:
_r("3f. Deploy job has needs:", False,
f"{ci_cd[0].name} job:{jname}",
"Deploy runs in parallel — not gated")
_sev("high")
# ── 4. BUILD ARTIFACT REUSE ──────────────────────────────────────────
if ci_cd:
wf = workflows.get(ci_cd[0].name, {})
all_text = str(wf)
has_upload = "upload-artifact" in all_text
has_download = "download-artifact" in all_text
if has_upload:
# Check if deploy uses the same artifact
if deploy_wf:
dwf_text = str(workflows.get(deploy_wf[0].name, ""))
has_download_in_deploy = "download-artifact" in dwf_text
_r("4a. Build artifact uploaded + reused", has_download_in_deploy,
f"{ci_cd[0].name} + {deploy_wf[0].name if deploy_wf else ''}",
"Artifact uploaded" + (" and downloaded in deploy" if has_download_in_deploy else " but deploy may not reuse"))
if not has_download_in_deploy:
_sev("high")
else:
_r("4a. Build artifact uploaded", True, ci_cd[0].name, "")
else:
_r("4a. Build artifact uploaded", True, ci_cd[0].name,
"No upload-artifact — deploy may use registry push instead")
# 4b: Version/commit SHA embedded
has_sha_or_version = "${{ github.sha }}" in all_text or "version" in all_text.lower() or "github.ref_name" in all_text
_r("4b. Version/SHA traceable in artifact", has_sha_or_version,
ci_cd[0].name, "")
# ── 5. DEPLOY STAGE ──────────────────────────────────────────────────
# Collect deploy info from either deploy.yml or deploy job
deploy_text = ""
deploy_env = False
deploy_has_verify = False
if deploy_wf:
deploy_text_parts = []
for dwf in deploy_wf:
wf_dict = str(workflows.get(dwf.name, {}))
try:
raw_content = dwf.read_text()
except Exception:
raw_content = ""
deploy_text_parts.append(f"{wf_dict}\n{raw_content}")
if "environment" in raw_content.lower() or "environment:" in raw_content:
deploy_env = True
deploy_text = "\n".join(deploy_text_parts)
elif ci_cd:
wf = workflows.get(ci_cd[0].name, {})
for jname, jdef in _jobs(wf).items():
if "deploy" in jname.lower():
deploy_text = str(jdef)
deploy_env = bool(jdef.get("environment"))
break
if deploy_text:
# 5a: No build steps in deploy (already checked in 3g, but complementary)
# 5b: Runs sequentially (implicitly by workflow_run trigger)
_r("5b. Deploy runs sequentially (no parallel with CI/CD)", True,
"N/A", "Enforced by trigger design" if deploy_wf else "Single job")
# 5c: Verify artifact step
has_verify_artifact = (
"verify" in deploy_text.lower() or
"check" in deploy_text.lower() or
"test -f" in deploy_text or
"ls -la" in deploy_text or
"if-no-files-found: error" in deploy_text
)
_r("5c. Deploy verifies artifact before moving", has_verify_artifact,
deploy_wf[0].name if deploy_wf else ci_cd[0].name,
"" if has_verify_artifact else "No pre-deploy artifact verification")
if not has_verify_artifact:
_sev("high")
# 5d: environment: production
has_environment = deploy_env or "environment: production" in deploy_text
_r("5d. Deploy uses environment: production", has_environment,
deploy_wf[0].name if deploy_wf else ci_cd[0].name,
"" if has_environment else "No environment block — consider adding for secret scoping")
if not has_environment:
_sev("medium")
# 5e: Deploy authenticates by OIDC or by a stored secret. The row names
# which one, so a repo is never nudged to add a long-lived token where
# federated credentials already do the job.
auth = _deploy_auth(deploy_text)
_r("5e. Deploy authenticates (OIDC or secret)", auth is not None,
deploy_wf[0].name if deploy_wf else ci_cd[0].name,
auth or "No OIDC (id-token: write) and no secrets.* reference found in deploy")
if auth is None:
_sev("medium")
# 5f: Hardcoded secrets check
suspicious = ["ghp_", "ghs_", "ghu_", "sk-", "api_key=", "token=", "password=", "secret="]
for sus in suspicious:
if sus in deploy_text and "${{" not in deploy_text.split(sus)[0][-20:]:
_r("5f. No hardcoded secrets", False,
deploy_wf[0].name if deploy_wf else ci_cd[0].name,
f"Possible hardcoded secret pattern: {sus}")
_sev("critical")
break
else:
_r("5f. No hardcoded secrets", True, "N/A", "")
# 5g: Deploy mechanism documented
has_mechanism_doc = (
"scp" in deploy_text.lower() or
"ssh" in deploy_text.lower() or
"rsync" in deploy_text.lower() or
"git push" in deploy_text or
"docker" in deploy_text.lower() or
"flyctl" in deploy_text or
"railway" in deploy_text or
"render" in deploy_text or
"deploy" in deploy_text.lower()
)
_r("5g. Deploy mechanism identifiable", has_mechanism_doc,
deploy_wf[0].name if deploy_wf else ci_cd[0].name, "")
# 5h: Rollback path
has_rollback = any(kw in deploy_text.lower() for kw in [
"rollback", "roll_back", "roll back",
"previous", "restore", "undo",
"backup", "revert", "pages", "bigbase",
])
if deploy_wf:
_r("5h. Rollback path exists", has_rollback,
deploy_wf[0].name,
"" if has_rollback else "No rollback mechanism detected")
if not has_rollback and deploy_wf:
_sev("high")
# ── 6. POST-DEPLOY SAFETY NET ────────────────────────────────────────
if deploy_text:
# 6a: Post-deploy verification
has_smoke = any(kw in deploy_text.lower() for kw in [
"health", "smoke", "curl", "verify", "check",
"healthcheck", "health_check", "readiness",
])
_r("6a. Post-deploy smoke/health check exists", has_smoke,
deploy_wf[0].name if deploy_wf else ci_cd[0].name,
"" if has_smoke else "No post-deploy verification — no staging to catch issues")
if not has_smoke and deploy_wf:
_sev("high")
# 6b: Verification is its own step
if has_smoke:
# Check if there are distinct steps
job_data = None
if deploy_wf:
dwf_data = workflows.get(deploy_wf[0].name, {})
for jn, jd in _jobs(dwf_data).items():
if "deploy" in jn.lower() or jn == list(_jobs(dwf_data).keys())[0]:
job_data = jd
break
if job_data:
steps = job_data.get("steps", [])
step_names = [s.get("name", "") for s in steps if isinstance(s, dict)]
has_separate_verify = any("health" in n.lower() or "verify" in n.lower() or "smoke" in n.lower() or "check" in n.lower() for n in step_names)
_r("6b. Verification is separate step", has_separate_verify,
deploy_wf[0].name if deploy_wf else ci_cd[0].name,
"" if has_separate_verify else "Verify may be folded into deploy command")
if not has_separate_verify:
_sev("medium")
# 6c: Failure surfaced clearly
has_fail_on_unhealthy = (
"exit 1" in deploy_text or
"exit_code" in deploy_text.lower() or
"fail" in deploy_text.lower() or
"set -e" in deploy_text or
"set -o" in deploy_text or
"failure" in deploy_text.lower()
)
_r("6c. Verification failure surfaced", has_fail_on_unhealthy,
deploy_wf[0].name if deploy_wf else ci_cd[0].name,
"" if has_fail_on_unhealthy else "No failure handling detected")
if not has_fail_on_unhealthy and deploy_wf:
_sev("medium")
# ── 7. BRANCH PROTECTION (read from the GitHub API) ──────────────────
# A rule that cannot be verified is UNKNOWN, never PASS.
classic, ruleset, bp_problem = _branch_protection()
if bp_problem:
for rid, title in (("7a", "status checks"), ("7b", "no direct push")):
_r(f"{rid}. Branch protection — {title}", False, "N/A",
f"Could not verify: {bp_problem}", unknown=True)
_sev("medium")
elif classic is None and not ruleset:
for rid, title in (("7a", "status checks"), ("7b", "no direct push")):
_r(f"{rid}. Branch protection — {title}", False, "N/A",
"Default branch is not protected")
_sev("high")
else:
bp_checks = _protection_findings(classic, ruleset)
_r("7a. Branch protection — status checks", bool(bp_checks), "N/A",
f"Required checks: {', '.join(bp_checks)}" if bp_checks
else "Protected, but no required status checks")
if not bp_checks:
_sev("high")
_r("7b. Branch protection — no direct push", True, "N/A",
"Direct push allowed (solo-owner policy)")
# ── 8. SUPPLY CHAIN / HYGIENE ───────────────────────────────────────
# 8a: Actions pinned. Default accepts any version tag; strict mode
# (GRIMOIRE_AUDIT_STRICT_SHA_PINNING=1) accepts only SHAs and OCI digests.
strict_pins = os.environ.get("GRIMOIRE_AUDIT_STRICT_SHA_PINNING", "").lower() in (
"1", "true", "yes",
)
ok_forms = {"sha", "digest"} if strict_pins else {"sha", "digest", "version", "floating-major"}
forms: dict[str, list[str]] = defaultdict(list)
for fname, wf in workflows.items():
for jname, jdef in _jobs(wf).items():
if not isinstance(jdef, dict):
continue
for ref in _uses_actions(jdef):
forms[_classify_ref(ref)].append(f"{fname}/{jname}: {ref}")
forms.pop("local", None)
bad = [e for form, entries in forms.items() if form not in ok_forms for e in entries]
summary = ", ".join(
f"{form}: {len(entries)}" + (
f" ({', '.join(sorted({e.split(': ', 1)[1].split('@')[-1] for e in entries})[:3]) })"
if form == "floating-major" else ""
)
for form, entries in sorted(forms.items())
)
if bad:
shown = "; ".join(bad[:3])
more = f" (+{len(bad) - 3} more)" if len(bad) > 3 else ""
mode = "strict SHA mode" if strict_pins else "unpinned"
_r("8a. Third-party actions pinned", False,
bad[0].split(":")[0], f"{mode}: {shown}{more}")
_sev("medium")
else:
_r("8a. Third-party actions pinned to SHA or version", True, "N/A",
summary or "no external actions used")
# 8b: Dependency caching, read from parsed steps (never from a dict repr)
cache_found: list[tuple[str, str]] = [] # (workflow file, mechanism)
cache_invalid: list[tuple[str, str]] = []
for fname, wf in workflows.items():
for jdef in _jobs(wf).values():
if not isinstance(jdef, dict):
continue
for step in jdef.get("steps") or []:
if not isinstance(step, dict) or not isinstance(step.get("uses"), str):
continue
mech = _cache_mechanism(step["uses"], step.get("with"))
if mech == "invalid-setup-python-cache-true":
cache_invalid.append((fname, mech))
elif mech:
cache_found.append((fname, mech))
if cache_found:
fname, mech = cache_found[0]
_r("8b. Dependency caching used (lint/test faster)", True, fname, mech)
else:
_r("8b. Dependency caching used (lint/test faster)", False,
"N/A", "No caching detected — lint/test may be slower")
_sev("medium")
for fname, _ in cache_invalid[:1]:
_r("8b. setup-python cache value is valid", False, fname,
"cache: true is rejected by actions/setup-python — use "
"pip|poetry|pipenv|uv (https://github.com/actions/setup-python#caching-packages-dependencies)")
_sev("medium")
# ── 9. PERMISSIONS & SECRETS ─────────────────────────────────────────
# 9a: Explicit permissions block
for fname, wf in workflows.items():
explicit, note = _permission_scope(wf)
_r(f"9a. Permissions block [{fname}]", explicit, fname, note)
if not explicit:
_sev("medium")
# 9b: OIDC check (informational — cloud deploy only)
has_oidc = False
for fname, wf in workflows.items():
if "id-token: write" in str(wf) or "aws-actions/configure-aws-credentials" in str(wf) or "google-github-actions/auth" in str(wf):
has_oidc = True
break
if has_oidc:
_r("9b. OIDC authentication used", True, "N/A", "")
else:
_r("9b. OIDC authentication", True, "N/A",
"N/A — not a cloud-deploying repo or uses SSH keys")
# 9c: No secret leaking into logs (heuristic)
for fname, wf in workflows.items():
text = str(wf)
for line in text.split("\n"):
if "run: echo" in line.lower() and ("${{ secrets." in line or "${{ env." in line):
_r(f"9c. Secrets not echoed to logs [{fname}]", False,
fname, f"Potential secret echo: {line.strip()[:80]}")
_sev("high")
# ── SUMMARY ──────────────────────────────────────────────────────────
total = len(_ALL_RESULTS)
failures = [r for r in _ALL_RESULTS if not r["passed"]]
passed_count = total - len(failures)
failed_count = len(failures)
# A failing rule that was never tagged still counts, at the lowest level.
for r in failures:
r.setdefault("severity", "medium")
by_level = {
lvl: [r for r in failures if r["severity"] == lvl]
for lvl in ("critical", "high", "medium")
}
critical_fails = len(by_level["critical"])
high_fails = len(by_level["high"])
medium_fails = len(by_level["medium"])
if "--json" in sys.argv[1:]:
rules_out = []
for r in _ALL_RESULTS:
rid, title, fix = _rule_info(r["check_id"])
status = "pass" if r["passed"] else ("unknown" if r.get("unknown") else "fail")
item = {
"rule": rid,
"title": title,
"status": status,
"file": r["file_ref"],
"remediation": "" if r["passed"] else fix,
"notes": r["notes"],
}
if status != "pass":
item["severity"] = r["severity"]
rules_out.append(item)
print(json.dumps({
"repository": os.environ.get("REPO_FULL_NAME", "unknown"),
"branch": os.environ.get("BRANCH", "unknown"),
"summary": {"total": total, "passed": passed_count, "failed": failed_count,
"critical": critical_fails, "high": high_fails, "medium": medium_fails},
"rules": rules_out,
}, indent=2))
return 2 if critical_fails else (1 if high_fails else 0)
print()
print("=" * 88)
print(" CI/CD PIPELINE AUDIT REPORT")
print("=" * 88)
print()
print(f" Repository: {os.environ.get('REPO_FULL_NAME', 'unknown')}")
print(f" Branch: {os.environ.get('BRANCH', 'unknown')}")
print()
print(f" Total checks: {total}")
print(f" Passed: {passed_count}")
print(f" Failed: {failed_count}")
print()
if failed_count > 0:
print(f" Breakdown:")
print(f" Critical: {critical_fails}")
print(f" High: {high_fails}")
print(f" Medium: {medium_fails}")
print()
# Print table
print(f"| {'Check ID':<65s} | {'Status':<7s} | {'File':<30s} | Notes")
print(f"|{'-'*65}|{'-------':<7s}|{'-'*30}|-------")
for r in _ALL_RESULTS:
status = "PASS" if r["passed"] else ("UNKNOWN" if r.get("unknown") else "FAIL")
print(f"| {r['check_id']:<65s} | {status:<7s} | {r['file_ref']:<30s} | {r['notes']}")
print()
def _list(level: str) -> None:
for n, r in enumerate(by_level[level], 1):
rid, _, title = r["check_id"].partition(". ")
detail = f" — {r['notes']}" if r["notes"] else ""
print(f" {n}. [{rid}] {title}{detail}")
if critical_fails > 0:
print(f"❌ CRITICAL: {critical_fails} critical issue(s) — fix before merge:")
_list("critical")
if high_fails:
print(f" Also {high_fails} high-severity issue(s):")
_list("high")
return 2
elif high_fails > 0:
print(f"⚠️ HIGH: {high_fails} high-severity issue(s):")
_list("high")
if medium_fails:
print(f" Also {medium_fails} medium-severity issue(s):")
_list("medium")
return 1
elif medium_fails > 0:
print(f"ℹ️ LOW: Pipeline is functional, {medium_fails} hygiene issue(s) remain:")
_list("medium")
return 0
else:
print("✅ ALL CHECKS PASSED — Pipeline follows solo-dev CI/CD best practices.")
return 0
# ── Entry point ──────────────────────────────────────────────────────────
if __name__ == "__main__":
try:
rc = audit()
except Exception as exc:
print(f"FATAL: Audit script crashed: {exc}")
import traceback
traceback.print_exc()
sys.exit(1)
sys.exit(rc)