droboticflow-new/scripts/verify_registry_manifest.py
2026-08-22 07:29:25 +08:00

112 lines
5.1 KiB
Python

#!/usr/bin/env python3
"""Fail closed when an immutable registry image manifest is unavailable.
Docker auth configuration is read from stdin so credentials never need to be
placed in command arguments, temporary files, or output.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from typing import Any, Callable
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
_IMAGE = re.compile(r"^(?P<host>[^/@\s]+)/(?P<repo>[^@\s]+)@(?P<digest>sha256:[a-f0-9]{64})$")
_ACCEPT = "application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json"
def parse_image(image: str) -> tuple[str, str, str]:
match = _IMAGE.fullmatch(image.strip())
if match is None:
raise RuntimeError("registry preflight image must be a digest-pinned host/repository@sha256 reference")
return match.group("host"), match.group("repo"), match.group("digest")
def auth_value(config: dict[str, Any], host: str) -> str:
auths = config.get("auths")
if not isinstance(auths, dict):
raise RuntimeError("registry preflight docker config has no auths object")
entry = auths.get(host) or auths.get("https://" + host)
if not isinstance(entry, dict):
entry = next((value for key, value in auths.items() if host in str(key) and isinstance(value, dict)), None)
value = str((entry or {}).get("auth") or "").strip()
if not value:
raise RuntimeError("registry preflight docker auth is unavailable")
return value
def bearer_challenge(value: str) -> dict[str, str]:
match = re.match(r"^Bearer\s+(.+)$", value.strip(), re.IGNORECASE)
if match is None:
return {}
fields = {key.lower(): field for key, field in re.findall(r'([A-Za-z]+)="([^"]*)"', match.group(1))}
return fields if fields.get("realm") else {}
def read_manifest(request: Request, basic_auth: str, opener: Callable[..., Any]) -> tuple[str, dict[str, Any]]:
try:
with opener(request, timeout=30) as response:
return str(response.headers.get("Docker-Content-Digest") or ""), json.loads(response.read().decode("utf-8"))
except HTTPError as exc:
challenge = bearer_challenge(str(exc.headers.get("WWW-Authenticate") or "")) if exc.code == 401 else {}
if not challenge:
raise RuntimeError(f"registry manifest is unavailable for {request.full_url.rsplit('/manifests/', 1)[0]}: HTTP {exc.code}") from exc
token_query = {key: value for key, value in challenge.items() if key in {"service", "scope"}}
token_request = Request(
challenge["realm"] + (("?" + urlencode(token_query)) if token_query else ""),
headers={"Authorization": "Basic " + basic_auth},
)
try:
with opener(token_request, timeout=30) as token_response:
token_payload = json.loads(token_response.read().decode("utf-8"))
except (HTTPError, URLError, json.JSONDecodeError) as token_error:
raise RuntimeError("registry bearer token lookup failed") from token_error
token = str(token_payload.get("token") or token_payload.get("access_token") or "").strip()
if not token:
raise RuntimeError("registry bearer token response is missing a token")
retry = Request(request.full_url, headers={"Authorization": "Bearer " + token, "Accept": _ACCEPT})
try:
with opener(retry, timeout=30) as response:
return str(response.headers.get("Docker-Content-Digest") or ""), json.loads(response.read().decode("utf-8"))
except HTTPError as retry_error:
raise RuntimeError(f"registry manifest is unavailable after bearer auth: HTTP {retry_error.code}") from retry_error
def verify(image: str, docker_config: dict[str, Any], opener: Callable[..., Any] = urlopen) -> dict[str, Any]:
host, repository, digest = parse_image(image)
request = Request(
f"https://{host}/v2/{repository}/manifests/{digest}",
headers={"Authorization": "Basic " + auth_value(docker_config, host), "Accept": _ACCEPT},
)
basic_auth = auth_value(docker_config, host)
try:
observed, payload = read_manifest(request, basic_auth, opener)
except URLError as exc:
raise RuntimeError(f"registry manifest lookup failed for {image}: {exc.reason}") from exc
if observed and observed != digest:
raise RuntimeError(f"registry manifest digest mismatch for {image}: observed {observed}")
return {"image": image, "manifestDigest": observed or digest, "configDigest": str((payload.get("config") or {}).get("digest") or ""), "layerCount": len(payload.get("layers") or [])}
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--image", required=True)
args = parser.parse_args()
try:
docker_config = json.load(sys.stdin)
result = verify(args.image, docker_config)
except (RuntimeError, json.JSONDecodeError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
print(json.dumps(result, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())