130 lines
5.6 KiB
Python
130 lines
5.6 KiB
Python
"""Fail-closed validation for CI-to-release and release-to-deploy workflow events."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
SHA_RE = re.compile(r"[0-9a-f]{40}\Z")
|
|
RUN_ID_RE = re.compile(r"[0-9]+\Z")
|
|
DESCRIPTOR_RE = re.compile(r"release-descriptor-([0-9]+)-([0-9a-f]{64})\Z")
|
|
|
|
|
|
def latest_main_sha(checkout: Path | None = None) -> str:
|
|
result = subprocess.run(
|
|
["git", "-C", str(checkout or Path.cwd()), "ls-remote", "--exit-code", "origin", "refs/heads/main"],
|
|
check=True,
|
|
text=True,
|
|
capture_output=True,
|
|
timeout=10,
|
|
)
|
|
if len(result.stdout) > 256:
|
|
raise ValueError("current main lookup exceeded its output limit")
|
|
fields = result.stdout.split()
|
|
if len(fields) != 2 or fields[1] != "refs/heads/main" or not SHA_RE.fullmatch(fields[0]):
|
|
raise ValueError("could not determine the current main commit")
|
|
return fields[0]
|
|
|
|
|
|
def validate_source(
|
|
*, workflow: str, event: str, conclusion: str, branch: str, run_id: str, head_sha: str,
|
|
workflow_path: str, repository: str, stage: str, current_main: str,
|
|
) -> None:
|
|
expected = {
|
|
"release": ("CI", "ci.yaml@refs/heads/main", "push"),
|
|
"handoff": ("Release production images", "release-images.yaml@refs/heads/main", "workflow_run"),
|
|
}
|
|
if stage not in expected:
|
|
raise ValueError("unknown release handoff stage")
|
|
expected_workflow, expected_path, expected_event = expected[stage]
|
|
if workflow != expected_workflow or workflow_path != expected_path or event != expected_event:
|
|
raise ValueError("source workflow or event is not approved for this stage")
|
|
if repository != "admin/akyldash":
|
|
raise ValueError("source repository is not admin/akyldash")
|
|
if conclusion != "success" or branch != "main":
|
|
raise ValueError("only successful source runs on main may continue")
|
|
if not RUN_ID_RE.fullmatch(run_id) or not SHA_RE.fullmatch(head_sha):
|
|
raise ValueError("source run ID or commit SHA is invalid")
|
|
if current_main != head_sha:
|
|
raise ValueError("source run is stale because main has advanced")
|
|
|
|
|
|
def descriptor_request(artifact_response: object, *, run_id: str, head_sha: str) -> dict[str, str]:
|
|
if not isinstance(artifact_response, dict):
|
|
raise ValueError("artifact metadata must be a JSON object")
|
|
artifacts = artifact_response.get("artifacts")
|
|
if not isinstance(artifacts, list) or len(artifacts) != 1:
|
|
raise ValueError("expected exactly one release descriptor artifact")
|
|
artifact = artifacts[0]
|
|
if not isinstance(artifact, dict):
|
|
raise ValueError("release artifact metadata is invalid")
|
|
name = artifact.get("name")
|
|
match = DESCRIPTOR_RE.fullmatch(name) if isinstance(name, str) else None
|
|
if not match or match.group(1) != run_id:
|
|
raise ValueError("release artifact name does not bind the source run and descriptor digest")
|
|
if artifact.get("expired") is True:
|
|
raise ValueError("release descriptor artifact has expired")
|
|
source = artifact.get("workflow_run")
|
|
if not isinstance(source, dict) or (
|
|
str(source.get("id")) != run_id
|
|
or source.get("head_sha") != head_sha
|
|
or source.get("head_branch") != "main"
|
|
or source.get("event") != "workflow_run"
|
|
or source.get("conclusion") != "success"
|
|
):
|
|
raise ValueError("artifact metadata does not match the successful source release run")
|
|
return {"run_id": run_id, "commit": head_sha, "descriptor_sha256": match.group(2)}
|
|
|
|
|
|
def _source_from_environment() -> dict[str, str]:
|
|
return {
|
|
"workflow": os.environ.get("SOURCE_WORKFLOW", ""),
|
|
"workflow_path": os.environ.get("SOURCE_WORKFLOW_PATH", ""),
|
|
"event": os.environ.get("SOURCE_EVENT", ""),
|
|
"conclusion": os.environ.get("SOURCE_CONCLUSION", ""),
|
|
"branch": os.environ.get("SOURCE_BRANCH", ""),
|
|
"run_id": os.environ.get("SOURCE_RUN_ID", ""),
|
|
"head_sha": os.environ.get("SOURCE_SHA", ""),
|
|
"repository": os.environ.get("SOURCE_REPOSITORY", ""),
|
|
}
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("stage", choices=("validate-ci-source", "validate-handoff-source", "dry-run"))
|
|
parser.add_argument("--artifact-metadata", type=Path)
|
|
args = parser.parse_args()
|
|
try:
|
|
source = _source_from_environment()
|
|
stage = "release" if args.stage == "validate-ci-source" else "handoff"
|
|
validate_source(**source, stage=stage, current_main=latest_main_sha())
|
|
if args.stage == "validate-ci-source":
|
|
print(f"PASS successful CI source {source['head_sha']} is current main")
|
|
return 0
|
|
if args.artifact_metadata is None:
|
|
print(
|
|
"DRY-RUN only: source release is current, but artifact metadata was not read; "
|
|
"host handoff is unavailable"
|
|
)
|
|
return 0
|
|
response = json.loads(args.artifact_metadata.read_text(encoding="utf-8"))
|
|
request = descriptor_request(response, run_id=source["run_id"], head_sha=source["head_sha"])
|
|
except (OSError, UnicodeError, json.JSONDecodeError, subprocess.CalledProcessError, ValueError) as error:
|
|
print(f"ERROR: {error}", file=sys.stderr)
|
|
return 1
|
|
print(
|
|
"DRY-RUN only: validated handoff tuple "
|
|
f"run_id={request['run_id']} commit={request['commit']} "
|
|
f"descriptor_sha256={request['descriptor_sha256']}; ZIP bytes were not fetched and no host connection was opened"
|
|
)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|