260 lines
10 KiB
Python
260 lines
10 KiB
Python
"""Read the public Planet release and immutable linux/amd64 images from Gitea."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
SERVER = "https://gitea.rclaw.top"
|
|
REPO = "linkong/planet"
|
|
REGISTRY = urllib.parse.urlsplit(SERVER).netloc
|
|
API = f"{SERVER}/api/v1/repos/{REPO}"
|
|
MANIFEST_NAME = "release-manifest.json"
|
|
MANIFEST_IMAGE = "release-manifest"
|
|
DEFAULT_USER_AGENT = "Planet-Release-Deploy/1.0"
|
|
SERVICES = {
|
|
"aiprovider": "AI_PROVIDER_IMAGE_NAME",
|
|
"backend": "BACKEND_IMAGE_NAME",
|
|
"admin": "ADMIN_IMAGE_NAME",
|
|
}
|
|
MANIFEST_TYPES = ", ".join(
|
|
(
|
|
"application/vnd.oci.image.index.v1+json",
|
|
"application/vnd.oci.image.manifest.v1+json",
|
|
"application/vnd.docker.distribution.manifest.list.v2+json",
|
|
"application/vnd.docker.distribution.manifest.v2+json",
|
|
)
|
|
)
|
|
|
|
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self, *args):
|
|
return None
|
|
|
|
|
|
def read_url(url, *, headers=None, limit=2 * 1024 * 1024):
|
|
"""Bound a release download and keep authorization on its original HTTPS endpoint."""
|
|
merged_headers = dict(headers or {})
|
|
if not any(key.lower() == "user-agent" for key in merged_headers):
|
|
merged_headers["User-Agent"] = DEFAULT_USER_AGENT
|
|
request = urllib.request.Request(url, headers=merged_headers)
|
|
for attempt in range(3):
|
|
try:
|
|
with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response:
|
|
data = response.read(limit + 1)
|
|
if len(data) > limit:
|
|
raise ValueError(f"Release response exceeds {limit} bytes")
|
|
return data
|
|
except urllib.error.HTTPError as exc:
|
|
if exc.code not in (502, 503, 504) or attempt == 2:
|
|
raise
|
|
except (urllib.error.URLError, TimeoutError, ConnectionError) as exc:
|
|
if attempt == 2:
|
|
raise RuntimeError(f"Could not read release metadata from {url}") from exc
|
|
time.sleep(1 + attempt)
|
|
|
|
|
|
def version(tag):
|
|
if not isinstance(tag, str) or not re.fullmatch(
|
|
r"v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)", tag
|
|
):
|
|
raise ValueError(f"Expected a stable version tag, got {tag!r}")
|
|
return tuple(int(part) for part in tag[1:].split("."))
|
|
|
|
|
|
def tag_commit(tag):
|
|
version(tag)
|
|
commit = json.loads(read_url(f"{API}/tags/{tag}"))["commit"]["sha"]
|
|
if not re.fullmatch("[0-9a-f]{40,64}", commit):
|
|
raise ValueError("Invalid Gitea commit ID")
|
|
return commit
|
|
|
|
|
|
def _verified_release_asset(release, tag, name, *, limit, label):
|
|
"""Download and verify a release asset against SHA256SUMS.txt."""
|
|
version(tag)
|
|
if release.get("tag_name") != tag or release.get("draft") or release.get("prerelease"):
|
|
raise ValueError("Expected the selected stable, published release")
|
|
assets = release.get("assets") or []
|
|
sizes = {entry["name"]: entry["size"] for entry in assets}
|
|
if len(assets) != len(sizes):
|
|
raise ValueError("Duplicate release attachment names")
|
|
base = f"{SERVER}/{REPO}/releases/download/{tag}"
|
|
if not 0 < sizes.get(name, 0) <= limit or "SHA256SUMS.txt" not in sizes:
|
|
raise ValueError(f"Release has no complete {label} and checksum list")
|
|
sums = read_url(f"{base}/SHA256SUMS.txt", limit=128 * 1024).decode().splitlines()
|
|
hashes = [line.split(" ", 1)[0] for line in sums if line.endswith(" " + name)]
|
|
data = read_url(f"{base}/{name}", limit=sizes[name])
|
|
sha = hashlib.sha256(data).hexdigest()
|
|
if hashes != [sha] or len(data) != sizes[name]:
|
|
raise ValueError(f"{label} failed release SHA-256 or size verification")
|
|
return name, data, sha
|
|
|
|
|
|
def release_bundle(release, tag):
|
|
"""Read the published hotfix and check it against the release checksum file."""
|
|
name = f"planet-earth-bundle-{tag[1:]}.tar.gz"
|
|
return _verified_release_asset(release, tag, name, limit=32 * 1024 * 1024, label="Earth bundle")
|
|
|
|
|
|
def _validate_release_manifest(manifest, tag):
|
|
"""Validate common schema and pin structure for a release manifest."""
|
|
if not isinstance(manifest, dict) or manifest.get("schema_version") != 1:
|
|
raise ValueError("Unsupported release manifest schema version")
|
|
if manifest.get("tag") != tag:
|
|
raise ValueError("Release manifest tag differs from the published release")
|
|
services = manifest.get("services")
|
|
if not isinstance(services, dict) or set(services.keys()) != set(SERVICES.keys()):
|
|
raise ValueError("Release manifest must pin all production service images")
|
|
client = manifest.get("client")
|
|
if not isinstance(client, dict) or client.get("mode") not in ("none", "hotfix", "full"):
|
|
raise ValueError("Release manifest has an invalid client mode")
|
|
return manifest
|
|
|
|
|
|
def release_manifest(release, tag):
|
|
"""Read and validate optional release-manifest.json; returns None for legacy releases."""
|
|
version(tag)
|
|
if release.get("tag_name") != tag or release.get("draft") or release.get("prerelease"):
|
|
raise ValueError("Expected the selected stable, published release")
|
|
assets = release.get("assets") or []
|
|
if not any(entry.get("name") == MANIFEST_NAME for entry in assets):
|
|
return None
|
|
_, data, _ = _verified_release_asset(
|
|
release, tag, MANIFEST_NAME, limit=512 * 1024, label="Release manifest"
|
|
)
|
|
return _validate_release_manifest(json.loads(data.decode("utf-8")), tag)
|
|
|
|
|
|
def latest_stable_tags(limit=30):
|
|
"""Return recent repository tags from Gitea."""
|
|
data = json.loads(read_url(f"{API}/tags?limit={int(limit)}"))
|
|
if not isinstance(data, list):
|
|
raise ValueError("Gitea returned invalid repository tag metadata")
|
|
return data
|
|
|
|
|
|
def release_by_tag(tag):
|
|
"""Return a published non-draft/non-prerelease Gitea Release dict, or None when absent."""
|
|
version(tag)
|
|
try:
|
|
release = json.loads(read_url(f"{API}/releases/tags/{tag}"))
|
|
except urllib.error.HTTPError as exc:
|
|
if exc.code == 404:
|
|
return None
|
|
raise
|
|
if not isinstance(release, dict) or release.get("draft") or release.get("prerelease"):
|
|
return None
|
|
return release
|
|
|
|
|
|
def resolve_service_ref(service, ref):
|
|
"""Verify an explicit ``image:tag@sha256:...`` pin against Gitea registry."""
|
|
prefix = image_name(service) + ":"
|
|
if not isinstance(ref, str) or not ref.startswith(prefix) or "@" not in ref:
|
|
raise ValueError(f"Invalid image reference for {service}: {ref!r}")
|
|
ref_tag, ref_digest = ref[len(prefix) :].split("@", 1)
|
|
version(ref_tag)
|
|
if not re.fullmatch(r"sha256:[a-f0-9]{64}", ref_digest):
|
|
raise ValueError(f"Invalid image digest for {service}: {ref!r}")
|
|
resolved = resolve_image(service, ref_tag, tag_commit(ref_tag))
|
|
if resolved != ref:
|
|
raise ValueError(f"{service} image reference differs from registry ({resolved!r} != {ref!r})")
|
|
return resolved
|
|
|
|
|
|
def image_name(service):
|
|
if service not in SERVICES:
|
|
raise ValueError(f"Unexpected production service: {service}")
|
|
return f"{REGISTRY}/{REPO}/{service}"
|
|
|
|
|
|
def manifest_image_name():
|
|
return f"{REGISTRY}/{REPO}/{MANIFEST_IMAGE}"
|
|
|
|
|
|
def digest(data):
|
|
return "sha256:" + hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def descriptor_digest(desc):
|
|
value = desc["digest"]
|
|
if not re.fullmatch(r"sha256:[a-f0-9]{64}", value):
|
|
raise ValueError("Registry returned an invalid digest")
|
|
return value
|
|
|
|
|
|
def _fetch_oci_config(repository, name, tag, commit):
|
|
"""Fetch and verify the linux/amd64 OCI manifest digest and revision label."""
|
|
query = urllib.parse.urlencode(
|
|
{"service": "container_registry", "scope": f"repository:{repository}:pull"}
|
|
)
|
|
token = json.loads(read_url(f"{SERVER}/v2/token?{query}"))["token"]
|
|
headers = {"Authorization": "Bearer " + token, "Accept": MANIFEST_TYPES}
|
|
base = f"{SERVER}/v2/{repository}"
|
|
try:
|
|
raw = read_url(f"{base}/manifests/{tag}", headers=headers)
|
|
except urllib.error.HTTPError as exc:
|
|
if exc.code == 404:
|
|
return None
|
|
raise
|
|
manifest = json.loads(raw)
|
|
if "manifests" in manifest:
|
|
candidates = [
|
|
entry
|
|
for entry in manifest["manifests"]
|
|
if entry.get("platform", {}).get("os") == "linux"
|
|
and entry["platform"].get("architecture") == "amd64"
|
|
]
|
|
if len(candidates) != 1:
|
|
raise ValueError(f"{name}:{tag} must contain one linux/amd64 image")
|
|
selected = descriptor_digest(candidates[0])
|
|
raw = read_url(f"{base}/manifests/{selected}", headers=headers)
|
|
if digest(raw) != selected:
|
|
raise ValueError("Registry platform manifest failed digest verification")
|
|
manifest = json.loads(raw)
|
|
config_digest = descriptor_digest(manifest["config"])
|
|
config_raw = read_url(f"{base}/blobs/{config_digest}", headers=headers)
|
|
if digest(config_raw) != config_digest:
|
|
raise ValueError("Registry image configuration failed digest verification")
|
|
config = json.loads(config_raw)
|
|
labels = config.get("config", {}).get("Labels") or {}
|
|
if (config.get("os"), config.get("architecture")) != ("linux", "amd64"):
|
|
raise ValueError(f"{name}:{tag} is not a linux/amd64 image")
|
|
if labels.get("org.opencontainers.image.revision") != commit:
|
|
raise ValueError(f"{name}:{tag} belongs to a different commit")
|
|
return digest(raw), labels
|
|
|
|
|
|
def resolve_image(service, tag, commit):
|
|
"""Return the immutable platform image; only an absent tag returns None."""
|
|
version(tag)
|
|
name = image_name(service)
|
|
fetched = _fetch_oci_config(f"{REPO}/{service}", name, tag, commit)
|
|
if fetched is None:
|
|
return None
|
|
manifest_digest, labels = fetched
|
|
if service == "admin" and labels.get("planet.frontend.target") != "admin":
|
|
raise ValueError("The production Admin image must be built with the admin-only target")
|
|
return f"{name}:{tag}@{manifest_digest}"
|
|
|
|
|
|
def resolve_release_manifest_oci(tag, commit):
|
|
"""Read and validate the OCI release-manifest:<tag> metadata artifact, or None on 404."""
|
|
version(tag)
|
|
name = manifest_image_name()
|
|
fetched = _fetch_oci_config(f"{REPO}/{MANIFEST_IMAGE}", name, tag, commit)
|
|
if fetched is None:
|
|
return None
|
|
_, labels = fetched
|
|
raw_manifest = labels.get("planet.release.manifest")
|
|
if not isinstance(raw_manifest, str) or not raw_manifest.strip():
|
|
raise ValueError(f"{name}:{tag} is missing planet.release.manifest label")
|
|
manifest = json.loads(raw_manifest)
|
|
return _validate_release_manifest(manifest, tag)
|