384 lines
21 KiB
Python
384 lines
21 KiB
Python
#!/usr/bin/env python3
|
|
"""Publish verified CLI or privately built CUDA previews through Gitea's API v1."""
|
|
import argparse
|
|
import hashlib
|
|
import http.client
|
|
import ipaddress
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import ssl
|
|
import stat
|
|
import sys
|
|
from urllib.parse import urlencode, urljoin, urlsplit
|
|
|
|
PACKAGE_BINARY = 'leleka-api-linux-x86_64-musl'
|
|
PACKAGE_ASSETS = {PACKAGE_BINARY, 'PROVENANCE.json'}
|
|
IMAGE_ASSETS = {'runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar'}
|
|
ASSETS = PACKAGE_ASSETS | IMAGE_ASSETS | {'SHA256SUMS', 'IMAGE-SHA256SUMS'}
|
|
STATIC_IMAGE_ASSETS = {'runtime-image.tar', 'IMAGE-PROVENANCE.json'}
|
|
STATIC_ASSETS = PACKAGE_ASSETS | STATIC_IMAGE_ASSETS | {'SHA256SUMS', 'IMAGE-SHA256SUMS'}
|
|
CLI_ASSETS = {PACKAGE_BINARY, 'BUILD-PROVENANCE.txt', 'ELF-AUDIT.txt', 'SHA256SUMS'}
|
|
CHUNK_SIZE = 1024 * 1024
|
|
|
|
|
|
def file_sha256(path):
|
|
fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
|
|
with os.fdopen(fd, 'rb') as source:
|
|
if not stat.S_ISREG(os.fstat(source.fileno()).st_mode):
|
|
raise ValueError(f'not a regular artifact file: {path.name}')
|
|
return hashlib.file_digest(source, 'sha256').hexdigest()
|
|
|
|
|
|
def verify_manifest(directory, manifest, expected):
|
|
path = directory / manifest
|
|
lines = path.read_text(encoding='ascii').splitlines()
|
|
entries = {}
|
|
for line in lines:
|
|
match = re.fullmatch(r'([0-9a-f]{64}) ([A-Za-z0-9_.-]+)', line)
|
|
if not match or match[2] in entries:
|
|
raise ValueError(f'invalid {manifest} entry')
|
|
entries[match[2]] = match[1]
|
|
if set(entries) != expected:
|
|
raise ValueError(f'{manifest} does not cover the required artifact set')
|
|
for name, expected_sha in entries.items():
|
|
if file_sha256(directory / name) != expected_sha:
|
|
raise ValueError(f'{manifest} checksum mismatch: {name}')
|
|
|
|
|
|
def read_json(path):
|
|
try:
|
|
value = json.loads(path.read_text(encoding='utf-8'))
|
|
except (OSError, json.JSONDecodeError) as error:
|
|
raise ValueError(f'invalid artifact JSON: {path.name}') from error
|
|
if not isinstance(value, dict):
|
|
raise ValueError(f'artifact JSON must be an object: {path.name}')
|
|
return value
|
|
|
|
|
|
def canonical_sha(record):
|
|
return hashlib.sha256((json.dumps(record, sort_keys=True, indent=2) + '\n').encode()).hexdigest()
|
|
|
|
|
|
def valid_digest(value, prefix=''):
|
|
return isinstance(value, str) and re.fullmatch(re.escape(prefix) + r'[0-9a-f]{64}', value) is not None
|
|
|
|
|
|
def verify_artifacts(directory, target, profile='cuda'):
|
|
if profile not in {'cli', 'cuda', 'static-cuda'}:
|
|
raise ValueError('unsupported artifact profile')
|
|
expected = {'cli': CLI_ASSETS, 'cuda': ASSETS, 'static-cuda': STATIC_ASSETS}[profile]
|
|
if not directory.is_dir():
|
|
raise ValueError('artifact directory does not exist')
|
|
paths = list(directory.iterdir())
|
|
if {path.name for path in paths} != expected:
|
|
raise ValueError(f'artifact directory must contain exactly the {profile.upper()} preview files')
|
|
for path in paths:
|
|
file_sha256(path)
|
|
verify_manifest(directory, 'SHA256SUMS', expected - {'SHA256SUMS'} if profile == 'cli' else PACKAGE_ASSETS)
|
|
if profile == 'cli':
|
|
provenance = (directory / 'BUILD-PROVENANCE.txt').read_text(encoding='utf-8')
|
|
commits = re.findall(r'^Commit: (.*)$', provenance, re.MULTILINE)
|
|
if commits != [target] or not re.search(r'^Workflow: https?://\S+$', provenance, re.MULTILINE):
|
|
raise ValueError('CLI build provenance is not bound to this exact commit and workflow')
|
|
audit = (directory / 'ELF-AUDIT.txt').read_text(encoding='utf-8')
|
|
if ('ELF Header:' not in audit or not re.search(r'Class:\s+ELF64', audit) or
|
|
not re.search(r'Machine:\s+Advanced Micro Devices X86-64', audit) or
|
|
'INTERP' in audit or 'NEEDED' in audit):
|
|
raise ValueError('CLI ELF audit does not describe a static x86_64 executable')
|
|
else:
|
|
verify_manifest(directory, 'IMAGE-SHA256SUMS', STATIC_IMAGE_ASSETS if profile == 'static-cuda' else IMAGE_ASSETS)
|
|
package = read_json(directory / 'PROVENANCE.json')
|
|
engine = package.get('engine', {})
|
|
features = package.get('build_features', {})
|
|
feature_sha = package.get('build_features_sha256')
|
|
loader = package.get('loader_probe', {})
|
|
audit = package.get('engine_elf_audit', {})
|
|
if (type(package.get('schema_version')) is not int or package.get('schema_version') != 1 or
|
|
package.get('kind') != 'static-cuda-preview' or
|
|
package.get('target') != 'x86_64-unknown-linux-musl' or package.get('source_revision') != target or
|
|
package.get('gpu_tested') is not False or package.get('model_tested') is not False or
|
|
package.get('clean_node_tested') is not False or not isinstance(engine, dict) or
|
|
engine.get('embedded') is not True or engine.get('declared_source_revision') != target or
|
|
engine.get('target_os') != 'linux' or engine.get('target_arch') != 'x86_64' or
|
|
type(engine.get('bytes')) is not int or not 0 < engine['bytes'] <= 1024**3 or
|
|
not valid_digest(engine.get('sha256')) or not isinstance(loader, dict) or
|
|
loader.get('environment') != 'pinned-runtime-container' or loader.get('gpu_tested') is not False or
|
|
loader.get('user') != '65532:65532' or not valid_digest(loader.get('image_id'), 'sha256:')):
|
|
raise ValueError('combined package provenance is not a CUDA-only preview for this commit')
|
|
if (not isinstance(audit, dict) or audit.get('toolkit_shared_libraries') is not False or
|
|
audit.get('host_glibc_required') is not True or
|
|
not isinstance(audit.get('minimum_glibc'), str) or
|
|
not re.fullmatch(r'[0-9]+\.[0-9]+(?:\.[0-9]+)?', audit['minimum_glibc']) or
|
|
not isinstance(loader.get('glibc'), str) or
|
|
not re.fullmatch(r'[0-9]+\.[0-9]+(?:\.[0-9]+)?', loader['glibc'])):
|
|
raise ValueError('CUDA ELF audit and loader glibc receipts are required')
|
|
minimum = tuple(map(int, audit['minimum_glibc'].split('.')))
|
|
actual = tuple(map(int, loader['glibc'].split('.')))
|
|
if actual + (0,) * (3 - len(actual)) < minimum + (0,) * (3 - len(minimum)):
|
|
raise ValueError('loader glibc is below the engine ELF audit requirement')
|
|
if (not isinstance(features, dict) or set(features) != {
|
|
'schema_version', 'source_revision', 'cuda_architectures', 'features'} or
|
|
type(features.get('schema_version')) is not int or features.get('schema_version') != 1 or
|
|
features.get('source_revision') != target or
|
|
not isinstance(features.get('cuda_architectures'), str) or
|
|
not re.fullmatch(r'[0-9]+(?:-(?:real|virtual))?(?:;[0-9]+(?:-(?:real|virtual))?)*', features['cuda_architectures']) or
|
|
not valid_digest(feature_sha) or canonical_sha(features) != feature_sha):
|
|
raise ValueError('CUDA build feature receipt is not bound to this source and digest')
|
|
values = features['features']
|
|
if (not isinstance(values, dict) or set(values) != {
|
|
'cuda', 'cuda_static_runtime', 'cxx_static_runtime', 'kar_ple', 'kar_experts', 'ple_trace'} or
|
|
any(type(value) is not bool for value in values.values()) or
|
|
any(values[key] is not True for key in ('cuda', 'cuda_static_runtime', 'cxx_static_runtime')) or
|
|
values['kar_experts'] is not False or values['ple_trace'] is not False):
|
|
raise ValueError('unsupported CUDA compile feature selection')
|
|
image = read_json(directory / 'IMAGE-PROVENANCE.json')
|
|
if (type(image.get('schema_version')) is not int or image.get('schema_version') != 1 or
|
|
image.get('kind') != 'static-cuda-preview' or
|
|
image.get('source_revision') != target or not valid_digest(image.get('image'), 'sha256:') or
|
|
not isinstance(image.get('base'), str) or
|
|
not re.fullmatch(r'[a-z0-9][a-z0-9./:_-]*@sha256:[0-9a-f]{64}', image['base']) or
|
|
image.get('base') != loader.get('base') or image.get('base_glibc') != loader.get('glibc') or
|
|
image.get('gpu_tested') is not False or image.get('model_tested') is not False or
|
|
image.get('build_features') != values or image.get('build_features_sha256') != feature_sha or
|
|
image.get('package_receipt_sha256') != file_sha256(directory / 'SHA256SUMS')):
|
|
raise ValueError('runtime image provenance is not qualified for this package and commit')
|
|
if profile == 'cuda':
|
|
toolchain = read_json(directory / 'CUDA-TOOLCHAIN.json')
|
|
builder = toolchain.get('docker_builder')
|
|
if (toolchain.get('source') != target or toolchain.get('driver_tested') is not False or
|
|
toolchain.get('model_tested') is not False or toolchain.get('build_features') != values or
|
|
toolchain.get('build_features_sha256') != feature_sha or
|
|
toolchain.get('cuda_architectures') != features['cuda_architectures'] or
|
|
not valid_digest(toolchain.get('builder_image_id'), 'sha256:') or
|
|
not isinstance(builder, dict) or builder.get('source_commit') != target or
|
|
builder.get('image_id') != toolchain.get('builder_image_id') or
|
|
builder.get('engine_sha256') != engine['sha256'] or
|
|
builder.get('build_features_sha256') != feature_sha or
|
|
builder.get('runtime_image_id') != image['image'] or
|
|
builder.get('runtime_archive_sha256') != file_sha256(directory / 'runtime-image.tar')):
|
|
raise ValueError('CUDA toolchain provenance is not bound to this commit, engine and runtime image')
|
|
return {path.name: {'size': path.stat().st_size, 'sha256': file_sha256(path)} for path in paths}
|
|
|
|
|
|
def parse_api_url(api_url):
|
|
parts = urlsplit(api_url)
|
|
if (parts.scheme not in {'http', 'https'} or not parts.hostname or parts.username or parts.password or
|
|
parts.query or parts.fragment or not parts.path.rstrip('/').endswith('/api/v1')):
|
|
raise ValueError('API URL must be a Gitea /api/v1 base URL')
|
|
if parts.scheme == 'http':
|
|
try:
|
|
local = ipaddress.ip_address(parts.hostname).is_loopback
|
|
except ValueError:
|
|
local = parts.hostname == 'localhost'
|
|
if not local:
|
|
raise ValueError('non-loopback Gitea API must use verified HTTPS')
|
|
if parts.hostname in {'github.com', 'api.github.com'}:
|
|
raise ValueError('API URL must identify Gitea, not GitHub')
|
|
prefix = parts.path.rstrip('/')
|
|
return parts, prefix
|
|
|
|
|
|
def connection(parts):
|
|
cls = http.client.HTTPSConnection if parts.scheme == 'https' else http.client.HTTPConnection
|
|
return cls(parts.hostname, parts.port, timeout=300, **({'context': ssl.create_default_context()} if parts.scheme == 'https' else {}))
|
|
|
|
|
|
def request_json(parts, prefix, path, token, payload, method='POST', expected_status=201):
|
|
body = json.dumps(payload, separators=(',', ':')).encode('utf-8')
|
|
conn = connection(parts)
|
|
try:
|
|
conn.request(method, prefix + path, body=body,
|
|
headers={'Authorization': f'token {token}', 'Content-Type': 'application/json',
|
|
'Accept': 'application/json'})
|
|
response = conn.getresponse()
|
|
data = response.read(1024 * 1024 + 1)
|
|
if len(data) > 1024 * 1024:
|
|
raise ValueError('Gitea response exceeds size limit')
|
|
if response.status != expected_status:
|
|
raise RuntimeError(f'Gitea API returned HTTP {response.status}')
|
|
result = json.loads(data)
|
|
if not isinstance(result, dict):
|
|
raise ValueError('Gitea response must be a JSON object')
|
|
return result
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def upload_asset(parts, prefix, path, token, asset, expected, repository, tag):
|
|
name = asset.name
|
|
route = prefix + path + '/assets?' + urlencode({'name': name})
|
|
fd = os.open(asset, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
|
|
conn = None
|
|
try:
|
|
source_stat = os.fstat(fd)
|
|
if not stat.S_ISREG(source_stat.st_mode):
|
|
raise ValueError(f'not a regular artifact file: {name}')
|
|
size = source_stat.st_size
|
|
if size != expected['size']:
|
|
raise ValueError(f'artifact size changed after verification: {name}')
|
|
conn = connection(parts)
|
|
conn.putrequest('POST', route)
|
|
conn.putheader('Authorization', f'token {token}')
|
|
conn.putheader('Content-Type', 'application/octet-stream')
|
|
conn.putheader('Content-Length', str(size))
|
|
conn.putheader('Accept', 'application/json')
|
|
conn.endheaders()
|
|
digest = hashlib.sha256()
|
|
sent = 0
|
|
with os.fdopen(fd, 'rb') as source:
|
|
fd = -1
|
|
while sent < size:
|
|
block = source.read(min(CHUNK_SIZE, size - sent))
|
|
if not block:
|
|
raise ValueError(f'artifact was truncated during upload: {name}')
|
|
sent += len(block)
|
|
digest.update(block)
|
|
conn.send(block)
|
|
if digest.hexdigest() != expected['sha256']:
|
|
raise ValueError(f'artifact content changed after verification: {name}')
|
|
response = conn.getresponse()
|
|
data = response.read(1024 * 1024 + 1)
|
|
if len(data) > 1024 * 1024:
|
|
raise ValueError('Gitea response exceeds size limit')
|
|
if response.status != 201:
|
|
raise RuntimeError(f'Gitea asset upload returned HTTP {response.status}')
|
|
metadata = json.loads(data)
|
|
if not isinstance(metadata, dict):
|
|
raise ValueError('Gitea asset response must be a JSON object')
|
|
if metadata.get('name') != name or metadata.get('size') != size:
|
|
raise ValueError(f'Gitea returned mismatched asset metadata: {name}')
|
|
verify_uploaded_asset(parts, token, metadata, expected, repository, tag)
|
|
return {'name': name, 'size': size}
|
|
finally:
|
|
if fd >= 0:
|
|
os.close(fd)
|
|
if conn is not None:
|
|
conn.close()
|
|
|
|
|
|
def validate_download_url(parts, url, allowed_paths):
|
|
if not isinstance(url, str):
|
|
raise ValueError('Gitea asset lacks its download URL')
|
|
asset_url = urlsplit(url)
|
|
if (asset_url.scheme != parts.scheme or asset_url.hostname != parts.hostname or
|
|
(asset_url.port or (443 if asset_url.scheme == 'https' else 80)) !=
|
|
(parts.port or (443 if parts.scheme == 'https' else 80)) or
|
|
asset_url.username or asset_url.password or asset_url.query or asset_url.fragment or
|
|
asset_url.path not in allowed_paths):
|
|
raise ValueError('Gitea asset URL must match its same-origin release or attachment route')
|
|
return asset_url
|
|
|
|
|
|
def verify_uploaded_asset(parts, token, metadata, expected, repository, tag):
|
|
# Gitea POST may return the UUID attachment route; later reads may return
|
|
# the exact release route. Both are bound to the same uploaded asset.
|
|
# Validate every hop before sending a scoped token; never follow foreign URLs.
|
|
base_path = parts.path.rstrip('/').removesuffix('/api/v1')
|
|
repo_path = base_path + '/' + repository
|
|
release_path = f"{repo_path}/releases/download/{tag}/{metadata['name']}"
|
|
url = metadata.get('browser_download_url')
|
|
attachment = metadata.get('uuid')
|
|
if not isinstance(attachment, str) or not re.fullmatch(
|
|
r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', attachment):
|
|
raise ValueError('Gitea asset lacks a valid attachment UUID')
|
|
attachment_paths = {f'{base_path}/attachments/{attachment}',
|
|
f'{repo_path}/attachments/{attachment}',
|
|
f'{repo_path}/releases/attachments/{attachment}'}
|
|
initial_paths = {release_path} | attachment_paths
|
|
for hop in range(3):
|
|
asset_url = validate_download_url(parts, url, initial_paths if hop == 0 else attachment_paths)
|
|
conn = connection(parts)
|
|
try:
|
|
conn.request('GET', asset_url.path, headers={'Authorization': f'token {token}'})
|
|
response = conn.getresponse()
|
|
if response.status in {301, 302, 303, 307, 308}:
|
|
if hop == 2:
|
|
raise ValueError('Gitea asset verification exceeds two redirects')
|
|
location = response.getheader('Location')
|
|
if not location:
|
|
raise ValueError('Gitea asset redirect lacks its location')
|
|
candidate = urljoin(url, location)
|
|
validate_download_url(parts, candidate, attachment_paths)
|
|
url = candidate
|
|
continue
|
|
if response.status != 200:
|
|
raise RuntimeError(f'Gitea asset verification returned HTTP {response.status}')
|
|
digest = hashlib.sha256()
|
|
total = 0
|
|
while block := response.read(min(CHUNK_SIZE, expected['size'] - total + 1)):
|
|
total += len(block)
|
|
if total > expected['size']:
|
|
raise ValueError('Gitea uploaded asset exceeds its verified size')
|
|
digest.update(block)
|
|
if total != expected['size'] or digest.hexdigest() != expected['sha256']:
|
|
raise ValueError('Gitea uploaded asset checksum mismatch')
|
|
return
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def publish(api_url, repository, token, tag, target, title, notes, directory, profile='cuda'):
|
|
if not token:
|
|
raise ValueError('GITEA_TOKEN is required')
|
|
if not isinstance(token, str) or len(token) > 512 or any(not 33 <= ord(char) <= 126 for char in token):
|
|
raise ValueError('GITEA_TOKEN must be bounded printable ASCII without whitespace')
|
|
repo_parts = repository.split('/')
|
|
if len(repo_parts) != 2 or any(part in {'.', '..'} or not re.fullmatch(r'[A-Za-z0-9_.-]+', part)
|
|
for part in repo_parts):
|
|
raise ValueError('repository must be owner/name')
|
|
tag_pattern = {'cuda': r'cuda-preview-[0-9]+-[0-9]+',
|
|
'static-cuda': r'static-cuda-preview-[0-9]+-[0-9]+',
|
|
'cli': r'(?:cli-preview-[0-9]+-[0-9]+|v[0-9][A-Za-z0-9_.-]*)'}.get(profile, '')
|
|
if not re.fullmatch(tag_pattern, tag):
|
|
raise ValueError('tag does not match the explicit preview profile')
|
|
if not re.fullmatch(r'[0-9a-f]{40}', target):
|
|
raise ValueError('target must be a full lowercase Git SHA')
|
|
parts, prefix = parse_api_url(api_url)
|
|
hashes = verify_artifacts(directory, target, profile)
|
|
owner, repo = repo_parts
|
|
release = request_json(parts, prefix, f'/repos/{owner}/{repo}/releases', token,
|
|
{'tag_name': tag, 'target_commitish': target, 'name': title,
|
|
'body': notes, 'draft': True, 'prerelease': True})
|
|
release_id = release.get('id')
|
|
if (type(release_id) is not int or release_id <= 0 or release.get('draft') is not True or
|
|
release.get('prerelease') is not True or release.get('tag_name') != tag or
|
|
release.get('target_commitish') != target):
|
|
raise ValueError('Gitea did not confirm the exact draft prerelease identity')
|
|
asset_route = f'/repos/{owner}/{repo}/releases/{release_id}'
|
|
uploaded = []
|
|
for name in sorted(hashes):
|
|
uploaded.append(upload_asset(parts, prefix, asset_route, token, directory / name, hashes[name], repository, tag))
|
|
finalized = request_json(parts, prefix, asset_route, token, {'draft': False},
|
|
method='PATCH', expected_status=200)
|
|
if finalized.get('id') != release_id or finalized.get('draft') is not False:
|
|
raise ValueError('Gitea did not confirm publication of the complete preview release')
|
|
return {'release_id': release_id, 'release_url': release.get('html_url'),
|
|
'tag': tag, 'target': target, 'assets': [dict(uploaded_asset, sha256=hashes[uploaded_asset['name']]['sha256'])
|
|
for uploaded_asset in uploaded]}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--api-url', default=os.environ.get('GITHUB_API_URL'), required=os.environ.get('GITHUB_API_URL') is None)
|
|
parser.add_argument('--repository', default=os.environ.get('GITHUB_REPOSITORY'), required=os.environ.get('GITHUB_REPOSITORY') is None)
|
|
parser.add_argument('--profile', choices=['cli', 'cuda', 'static-cuda'], required=True)
|
|
parser.add_argument('--tag', required=True)
|
|
parser.add_argument('--target', required=True)
|
|
parser.add_argument('--title', required=True)
|
|
parser.add_argument('--notes', required=True)
|
|
parser.add_argument('--directory', type=Path, required=True)
|
|
args = parser.parse_args()
|
|
try:
|
|
result = publish(args.api_url, args.repository, os.environ.get('GITEA_TOKEN', ''),
|
|
args.tag, args.target, args.title, args.notes, args.directory, args.profile)
|
|
print(json.dumps(result, sort_keys=True))
|
|
except (ValueError, OSError, RuntimeError, http.client.HTTPException, json.JSONDecodeError) as error:
|
|
print(f'Gitea release publication failed: {error}', file=sys.stderr)
|
|
raise SystemExit(1)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|