Add CMS deployment builders, policy sources and regression suite
This commit is contained in:
@@ -0,0 +1,259 @@
|
||||
"""Read-only, bounded Gitea source verification. No production execution authority.
|
||||
|
||||
The privileged installer must independently validate the returned TGZ with its
|
||||
canonical loader and reconcile its own journal. Nothing here accepts commands,
|
||||
paths, origins, or credentials from a workflow artifact.
|
||||
"""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import stat
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
from deployment_queue import REPOSITORY, REPOSITORY_ID, WORKFLOW, SHA, normalize_run, positive
|
||||
|
||||
|
||||
ORIGIN = "https://git.dcserve.ru"
|
||||
PREFIX = "/api/v1/repos/" + REPOSITORY
|
||||
PAGE_SIZE = 50
|
||||
MAX_PAGES = 200
|
||||
MAX_JSON = 8 * 1024 * 1024
|
||||
MAX_ARCHIVE = 64 * 1024 * 1024
|
||||
|
||||
|
||||
class SourceError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def require(condition, code):
|
||||
if not condition:
|
||||
raise SourceError(code)
|
||||
|
||||
|
||||
def strict_json(data):
|
||||
def unique(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
require(key not in result, "duplicate_json_key")
|
||||
result[key] = value
|
||||
return result
|
||||
try:
|
||||
return json.loads(data, object_pairs_hook=unique)
|
||||
except (UnicodeError, ValueError):
|
||||
raise SourceError("invalid_json") from None
|
||||
|
||||
|
||||
def signed_artifact_redirect(original, target):
|
||||
origin, dest = urllib.parse.urlsplit(original), urllib.parse.urlsplit(target)
|
||||
if (origin.scheme + "://" + origin.netloc != ORIGIN
|
||||
or dest.scheme + "://" + dest.netloc != ORIGIN or origin.query or dest.fragment
|
||||
or not re.fullmatch(re.escape(PREFIX) + r"/actions/artifacts/[1-9][0-9]*/zip", origin.path)
|
||||
or dest.path != origin.path + "/raw"):
|
||||
return False
|
||||
pairs = urllib.parse.parse_qsl(dest.query, keep_blank_values=True)
|
||||
params = dict(pairs)
|
||||
return (len(pairs) == 2 and set(params) == {"sig", "expires"}
|
||||
and re.fullmatch(r"[A-Za-z0-9_-]{32,128}", params["sig"]) is not None
|
||||
and re.fullmatch(r"[0-9]{10,13}", params["expires"]) is not None)
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
# Gitea 1.27 signs a same-origin /zip/raw URL. Only this exact route is
|
||||
# allowed and the persistent token is deliberately NOT forwarded.
|
||||
if (req is not None and req.get_method() == "GET" and code in (302, 303)
|
||||
and signed_artifact_redirect(req.full_url, newurl)):
|
||||
return urllib.request.Request(newurl, headers={"Accept": "application/octet-stream"})
|
||||
raise SourceError("api_redirect_refused")
|
||||
|
||||
|
||||
class GiteaSource:
|
||||
def __init__(self, token):
|
||||
require(isinstance(token, str) and re.fullmatch(r"[0-9a-f]{40}", token), "invalid_read_token")
|
||||
self._token = token
|
||||
self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
|
||||
|
||||
def request(self, suffix, *, archive=False):
|
||||
require(isinstance(suffix, str) and (suffix == "" or suffix.startswith("/")), "invalid_api_path")
|
||||
require(not any(value in suffix for value in ("..", "\\", "#", "@", "\r", "\n", "%")), "invalid_api_path")
|
||||
# Only methods below construct suffixes; this additional allowlist keeps
|
||||
# even accidental future callers from reading other API resources.
|
||||
require(re.fullmatch(
|
||||
r"(?:|/branches/master|/git/commits/[a-f0-9]{40}"
|
||||
r"|/actions/runs(?:/[1-9][0-9]*(?:/jobs|/artifacts)?)?"
|
||||
r"|/actions/artifacts/[1-9][0-9]*/zip)(?:\?page=[1-9][0-9]*&limit=50)?", suffix),
|
||||
"api_route_not_allowed")
|
||||
require(archive == suffix.endswith("/zip"), "api_response_type_mismatch")
|
||||
maximum = MAX_ARCHIVE if archive else MAX_JSON
|
||||
request = urllib.request.Request(ORIGIN + PREFIX + suffix,
|
||||
headers={"Authorization": "token " + self._token,
|
||||
"Accept": "application/octet-stream" if archive else "application/json"})
|
||||
try:
|
||||
with self._opener.open(request, timeout=25) as response:
|
||||
require(response.status == 200 and (response.geturl() == request.full_url or (archive and signed_artifact_redirect(request.full_url, response.geturl()))), "api_response_identity")
|
||||
data = response.read(maximum + 1)
|
||||
except urllib.error.HTTPError as error:
|
||||
raise SourceError("api_http_" + str(error.code)) from None
|
||||
except (OSError, urllib.error.URLError):
|
||||
raise SourceError("api_unavailable") from None
|
||||
require(len(data) <= maximum, "api_response_too_large")
|
||||
return data if archive else strict_json(data)
|
||||
|
||||
def repository(self):
|
||||
repo = self.request("")
|
||||
require(isinstance(repo, dict) and type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID
|
||||
and repo.get("full_name") == REPOSITORY and repo.get("default_branch") == "master"
|
||||
and repo.get("archived") is False and repo.get("mirror") is False,
|
||||
"repository_identity_mismatch")
|
||||
return repo
|
||||
|
||||
def pages(self, suffix, key):
|
||||
rows, identities, total = [], set(), None
|
||||
for page in range(1, MAX_PAGES + 1):
|
||||
data = self.request(suffix + "?page=" + str(page) + "&limit=50")
|
||||
require(isinstance(data, dict) and type(data.get("total_count")) is int
|
||||
and 0 <= data["total_count"] <= PAGE_SIZE * MAX_PAGES, "pagination_total_invalid")
|
||||
require(total is None or total == data["total_count"], "pagination_changed")
|
||||
total = data["total_count"]
|
||||
batch = data.get(key)
|
||||
require(isinstance(batch, list) and len(batch) <= PAGE_SIZE, "pagination_batch_invalid")
|
||||
for item in batch:
|
||||
require(isinstance(item, dict) and positive(item.get("id")) and item["id"] not in identities,
|
||||
"pagination_duplicate_or_invalid_id")
|
||||
identities.add(item["id"])
|
||||
rows.extend(batch)
|
||||
require(len(rows) <= total, "pagination_overflow")
|
||||
if len(rows) == total:
|
||||
return rows
|
||||
require(len(batch) == PAGE_SIZE, "pagination_incomplete")
|
||||
raise SourceError("pagination_limit")
|
||||
|
||||
def run(self, identity):
|
||||
require(positive(identity), "invalid_run_id")
|
||||
run = self.request("/actions/runs/" + str(identity))
|
||||
self.validate_run(run)
|
||||
require(run["id"] == identity, "run_identity_mismatch")
|
||||
return run
|
||||
|
||||
@staticmethod
|
||||
def validate_run(run):
|
||||
normalize_run(run)
|
||||
# Gitea 1.27.2 leaves top-level repository_id=0. The nested repository
|
||||
# and fixed repository endpoint carry the actual identity instead.
|
||||
repo = run.get("repository") or {}
|
||||
require(type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID
|
||||
and repo.get("full_name") == REPOSITORY, "run_repository_mismatch")
|
||||
|
||||
def discover(self):
|
||||
self.repository()
|
||||
runs = self.pages("/actions/runs", "workflow_runs")
|
||||
for run in runs:
|
||||
self.validate_run(run)
|
||||
require(len({run["run_number"] for run in runs}) == len(runs), "duplicate_run_number")
|
||||
# A push/deletion while pages were read must not silently hide an older
|
||||
# pending run. Recheck identity/count, without requiring phases to stop.
|
||||
check = self.pages("/actions/runs", "workflow_runs")
|
||||
identity = lambda values: sorted((r["id"], r["run_number"], r["head_sha"], r["event"], r["head_branch"], r["path"]) for r in values)
|
||||
for run in check:
|
||||
self.validate_run(run)
|
||||
require(identity(runs) == identity(check), "discovery_changed")
|
||||
return check
|
||||
|
||||
def successful_run(self, row):
|
||||
run = self.run(row["id"])
|
||||
require((run["run_number"], run["head_sha"], run["run_attempt"]) ==
|
||||
(row["number"], row["sha"], row["attempt"]), "qualified_run_changed")
|
||||
require(run["path"] == WORKFLOW and run["event"] == "push" and run["head_branch"] == "master"
|
||||
and run["status"] == "completed" and run["conclusion"] == "success", "run_not_qualified")
|
||||
jobs = self.pages("/actions/runs/" + str(run["id"]) + "/jobs", "jobs")
|
||||
require(len(jobs) == 1, "qualification_job_count")
|
||||
job = jobs[0]
|
||||
require(job.get("run_id") == run["id"] and job.get("head_sha") == run["head_sha"]
|
||||
and job.get("head_branch") == "master" and job.get("run_attempt") == run["run_attempt"]
|
||||
and job.get("name") == "qualify" and job.get("labels") == ["nodedc-node22-build"]
|
||||
and job.get("runner_id") == 1 and job.get("status") == "completed"
|
||||
and job.get("conclusion") == "success", "qualification_job_mismatch")
|
||||
steps = job.get("steps")
|
||||
require(isinstance(steps, list) and all(isinstance(s, dict) for s in steps) and [s.get("name") for s in steps] ==
|
||||
["Check the exact pushed commit", "Retain the qualified release in this Gitea run"]
|
||||
and all(s.get("status") == "completed" and s.get("conclusion") == "success" for s in steps),
|
||||
"qualification_steps_mismatch")
|
||||
return run
|
||||
|
||||
def main_commit(self):
|
||||
branch = self.request("/branches/master")
|
||||
require(isinstance(branch, dict) and branch.get("name") == "master", "main_branch_mismatch")
|
||||
sha = (branch.get("commit") or {}).get("id")
|
||||
require(isinstance(sha, str) and SHA.fullmatch(sha), "main_commit_invalid")
|
||||
return sha
|
||||
|
||||
def ancestor(self, ancestor, descendant, *, limit=1024):
|
||||
require(all(isinstance(s, str) and SHA.fullmatch(s) for s in (ancestor, descendant)), "ancestry_sha_invalid")
|
||||
pending, seen = [descendant], set()
|
||||
while pending:
|
||||
sha = pending.pop()
|
||||
if sha == ancestor:
|
||||
return True
|
||||
if sha in seen:
|
||||
continue
|
||||
require(len(seen) < limit, "ancestry_limit")
|
||||
seen.add(sha)
|
||||
commit = self.request("/git/commits/" + sha)
|
||||
require(isinstance(commit, dict) and commit.get("sha") == sha, "commit_identity_mismatch")
|
||||
parents = commit.get("parents")
|
||||
require(isinstance(parents, list) and len(parents) <= 32, "commit_parents_invalid")
|
||||
for parent in parents:
|
||||
value = parent.get("sha") if isinstance(parent, dict) else None
|
||||
require(isinstance(value, str) and SHA.fullmatch(value), "commit_parent_invalid")
|
||||
pending.append(value)
|
||||
return False
|
||||
|
||||
def prove_lineage(self, installed, candidate):
|
||||
main = self.main_commit()
|
||||
require(candidate != installed and self.ancestor(installed, candidate)
|
||||
and self.ancestor(candidate, main), "non_forward_main_release")
|
||||
require(self.main_commit() == main, "main_changed_during_proof")
|
||||
return main
|
||||
|
||||
def artifact(self, run):
|
||||
artifacts = self.pages("/actions/runs/" + str(run["id"]) + "/artifacts", "artifacts")
|
||||
candidates = [a for a in artifacts if a.get("name") == "dc-cms-release"]
|
||||
require(len(candidates) == 1, "qualified_artifact_count")
|
||||
artifact = candidates[0]
|
||||
owner = artifact.get("workflow_run") or {}
|
||||
require(owner.get("id") == run["id"] and owner.get("repository_id") == REPOSITORY_ID
|
||||
and owner.get("head_sha") == run["head_sha"] and artifact.get("expired") is False
|
||||
and type(artifact.get("size_in_bytes")) is int and 0 < artifact["size_in_bytes"] <= MAX_ARCHIVE,
|
||||
"artifact_owner_or_size_mismatch")
|
||||
blob = self.request("/actions/artifacts/" + str(artifact["id"]) + "/zip", archive=True)
|
||||
require(len(blob) == artifact["size_in_bytes"], "artifact_download_size_mismatch")
|
||||
return unpack_artifact(blob, run)
|
||||
|
||||
|
||||
def unpack_artifact(blob, run):
|
||||
identity = "nodedc-dc-cms-release-v1-r" + str(run["id"]) + "-" + run["head_sha"] + ".tgz"
|
||||
require(len(blob) <= MAX_ARCHIVE, "archive_too_large")
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(blob)) as archive:
|
||||
members = archive.infolist()
|
||||
require(len(members) == 2 and set(archive.namelist()) == {identity, "release.json"}, "zip_entry_mismatch")
|
||||
for member in members:
|
||||
require(not member.is_dir() and stat.S_IFMT(member.external_attr >> 16) in (0, stat.S_IFREG)
|
||||
and not member.flag_bits & 1 and 0 < member.file_size <= MAX_ARCHIVE,
|
||||
"zip_member_invalid")
|
||||
if member.filename == "release.json":
|
||||
require(member.file_size <= 4096, "zip_receipt_too_large")
|
||||
data = archive.read(identity)
|
||||
receipt = strict_json(archive.read("release.json"))
|
||||
except (zipfile.BadZipFile, RuntimeError, NotImplementedError, OSError):
|
||||
raise SourceError("archive_invalid") from None
|
||||
expected = {"artifact": identity, "sourceCommit": run["head_sha"], "runId": run["id"],
|
||||
"runNumber": run["run_number"], "deployed": False,
|
||||
"sha256": hashlib.sha256(data).hexdigest()}
|
||||
require(receipt == expected and type(receipt.get("runId")) is int
|
||||
and type(receipt.get("runNumber")) is int and receipt.get("deployed") is False, "release_receipt_mismatch")
|
||||
return receipt, data
|
||||
Reference in New Issue
Block a user