107 lines
4.5 KiB
Python
107 lines
4.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Validate the shape and repository allowlist of a prepared release manifest."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
SERVICES = {"backend", "opensearch"}
|
|
COMMIT_RE = re.compile(r"[0-9a-f]{40}\Z")
|
|
REPOSITORY_RE = re.compile(
|
|
r"[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[0-9]+)?"
|
|
r"(?:/[a-z0-9]+(?:[._-][a-z0-9]+)*)*\Z"
|
|
)
|
|
IMAGE_RE = re.compile(r"(.+)@sha256:([0-9a-f]{64})\Z")
|
|
|
|
|
|
def unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
|
result: dict[str, object] = {}
|
|
for key, value in pairs:
|
|
if key in result:
|
|
raise ValueError(f"duplicate JSON key: {key}")
|
|
result[key] = value
|
|
return result
|
|
|
|
|
|
def read_json(path: Path) -> object:
|
|
try:
|
|
return json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique_object)
|
|
except (OSError, UnicodeError, json.JSONDecodeError) as error:
|
|
raise ValueError(f"cannot read valid JSON from {path}: {error}") from error
|
|
|
|
|
|
def validate_policy(policy: object) -> dict[str, list[str]]:
|
|
if not isinstance(policy, dict) or set(policy) != {"schema_version", "repositories"}:
|
|
raise ValueError("policy must contain exactly schema_version and repositories")
|
|
if type(policy["schema_version"]) is not int or policy["schema_version"] != 1:
|
|
raise ValueError("unsupported policy schema_version")
|
|
repositories = policy["repositories"]
|
|
if not isinstance(repositories, dict) or set(repositories) != SERVICES:
|
|
raise ValueError("policy repositories must contain exactly backend and opensearch")
|
|
result: dict[str, list[str]] = {}
|
|
for service in sorted(SERVICES):
|
|
allowed = repositories[service]
|
|
if not isinstance(allowed, list) or not allowed:
|
|
raise ValueError(f"policy repository allowlist for {service} must be a non-empty list")
|
|
if any(not isinstance(repository, str) or not REPOSITORY_RE.fullmatch(repository) for repository in allowed):
|
|
raise ValueError(f"policy contains an invalid repository for {service}")
|
|
if len(set(allowed)) != len(allowed):
|
|
raise ValueError(f"policy repository allowlist for {service} contains duplicates")
|
|
result[service] = allowed
|
|
return result
|
|
|
|
|
|
def validate_manifest(manifest: object, policy: object) -> dict[str, object]:
|
|
allowed_repositories = validate_policy(policy)
|
|
if not isinstance(manifest, dict) or set(manifest) != {
|
|
"schema_version", "source_ref", "commit", "images"
|
|
}:
|
|
raise ValueError("manifest must contain exactly schema_version, source_ref, commit, and images")
|
|
if type(manifest["schema_version"]) is not int or manifest["schema_version"] != 1:
|
|
raise ValueError("unsupported manifest schema_version")
|
|
if manifest["source_ref"] != "refs/heads/main":
|
|
raise ValueError("manifest source_ref must be refs/heads/main")
|
|
commit = manifest["commit"]
|
|
if not isinstance(commit, str) or not COMMIT_RE.fullmatch(commit):
|
|
raise ValueError("manifest commit must be a 40-character lowercase Git SHA-1")
|
|
images = manifest["images"]
|
|
if not isinstance(images, dict) or set(images) != SERVICES:
|
|
raise ValueError("manifest images must contain exactly backend and opensearch")
|
|
for service in sorted(SERVICES):
|
|
image = images[service]
|
|
match = IMAGE_RE.fullmatch(image) if isinstance(image, str) else None
|
|
if not match:
|
|
raise ValueError(f"{service} image must use repository@sha256:<64 lowercase hex>")
|
|
repository = match.group(1)
|
|
if not REPOSITORY_RE.fullmatch(repository):
|
|
raise ValueError(f"{service} image has an invalid OCI repository")
|
|
if repository not in allowed_repositories[service]:
|
|
raise ValueError(f"{service} image repository is not allowed by policy")
|
|
return manifest
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("manifest", type=Path)
|
|
parser.add_argument("--policy", required=True, type=Path)
|
|
args = parser.parse_args()
|
|
try:
|
|
manifest = validate_manifest(read_json(args.manifest), read_json(args.policy))
|
|
except ValueError as error:
|
|
print(f"ERROR: {error}", file=sys.stderr)
|
|
return 1
|
|
images = manifest["images"]
|
|
print(
|
|
"PASS release manifest "
|
|
f"commit={manifest['commit']} backend={images['backend']} opensearch={images['opensearch']}"
|
|
)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|