fix(ci): publish verified previews through private Gitea API

This commit is contained in:
Pavlo Ratushnyi
2026-10-07 19:47:22 +02:00
parent 14bca78416
commit e028e5d414
5 changed files with 890 additions and 27 deletions
+99 -27
View File
@@ -100,13 +100,18 @@ jobs:
docker save --output "$package/runtime-image.tar" "$image"
cp "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" "$package/IMAGE-PROVENANCE.json"
(cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json > IMAGE-SHA256SUMS)
- uses: actions/upload-artifact@v4
with:
name: strata-next-static-cuda-preview
path: ${{ runner.temp }}/strata-package-${{ github.run_id }}/
if-no-files-found: error
retention-days: 7
- name: Publish exact six-file static CUDA preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile static-cuda \
--tag "static-cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \
--title "Static CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \
--notes 'Private build-only six-file preview. No hosted compiler/license receipt, GPU or model qualification.' \
--directory "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Remove uploaded package copy
if: always()
run: rm -rf -- "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Remove owned runtime image
if: always()
@@ -271,16 +276,40 @@ jobs:
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$RUNNER_TEMP/strata-hosted-image.json")"
docker save --output "$package/runtime-image.tar" "$image"
cp "$RUNNER_TEMP/strata-hosted-image.json" "$package/IMAGE-PROVENANCE.json"
python3 - <<'PYBIND'
import hashlib, json, os
from pathlib import Path
package=Path(os.environ['RUNNER_TEMP'])/'strata-hosted-cuda-package'
receipt=json.loads((package/'PROVENANCE.json').read_text())
image=json.loads((package/'IMAGE-PROVENANCE.json').read_text())
path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json'
toolchain=json.loads(path.read_text())
with (package/'runtime-image.tar').open('rb') as archive:
archive_sha=hashlib.file_digest(archive, 'sha256').hexdigest()
toolchain['docker_builder']={
'source_commit': os.environ['GITHUB_SHA'],
'image_id': toolchain['builder_image_id'],
'engine_sha256': receipt['engine']['sha256'],
'build_features_sha256': receipt['build_features_sha256'],
'runtime_image_id': image['image'],
'runtime_archive_sha256': archive_sha}
path.write_text(json.dumps(toolchain,indent=2)+'\n')
PYBIND
cp "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$package/CUDA-TOOLCHAIN.json"
tar -C "$CUDAToolkit_ROOT" -cf "$package/CUDA-LICENSES.tar" licenses
(cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json CUDA-TOOLCHAIN.json CUDA-LICENSES.tar > IMAGE-SHA256SUMS)
- uses: actions/upload-artifact@v4
with:
name: strata-next-hosted-cuda-preview
path: ${{ runner.temp }}/strata-hosted-cuda-package/
if-no-files-found: error
retention-days: 7
- name: Publish exact eight-file hosted CUDA preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile cuda \
--tag "cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \
--title "Hosted CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \
--notes 'Private build-only preview. GPU-hidden loader identity and help passed; no GPU/model inference or performance qualification.' \
--directory "$RUNNER_TEMP/strata-hosted-cuda-package"
- name: Remove uploaded package copy
if: always()
run: rm -rf -- "$RUNNER_TEMP/strata-hosted-cuda-package"
- name: Remove owned intermediate image and build files
if: always()
@@ -421,10 +450,15 @@ jobs:
docker image rm "$image"
rm "$receipt"
fi
- uses: actions/upload-artifact@v4
with:
name: strata-next-linux-x86_64-musl
path: dist/
- name: Publish exact four-file CLI preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile cli \
--tag "cli-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \
--title "CLI preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \
--notes 'CLI/control-plane preview. CUDA engine and model files are not included.' --directory dist
linux-cli-container:
needs: verify
@@ -447,17 +481,55 @@ jobs:
if: startsWith(github.ref, 'refs/tags/v')
needs: [linux-static-cli, linux-cli-container]
runs-on: ubuntu-latest
permissions:
contents: write
env:
CARGO_TARGET_DIR: ${{ github.workspace }}/control-plane/target
steps:
- uses: actions/download-artifact@v4
- uses: actions/checkout@v4
with:
name: strata-next-linux-x86_64-musl
path: dist/
- name: Publish CLI preview release
env:
GH_TOKEN: ${{ github.token }}
ref: ${{ github.ref }}
- name: Require the exact gated tag commit
run: test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
- name: Install musl toolchain
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y musl-tools cmake binutils python3
- name: Install pinned Rust and target
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl
- name: Rebuild static CLI at the exact gated tag
run: cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next
- name: Verify ELF and checksum
run: |
gh release create "${GITHUB_REF_NAME}" dist/strata-next-linux-x86_64-musl dist/SHA256SUMS dist/BUILD-PROVENANCE.txt dist/ELF-AUDIT.txt \
--repo "${GITHUB_REPOSITORY}" --title "Strata Next ${GITHUB_REF_NAME}" \
--notes 'CLI/control-plane preview. CUDA engine and model files are not included.' --prerelease
binary=control-plane/target/x86_64-unknown-linux-musl/release/strata-next
if readelf -l "$binary" | grep -q INTERP; then
echo 'ELF has a dynamic interpreter' >&2
exit 1
fi
if readelf -d "$binary" | grep -q NEEDED; then
echo 'ELF has a dynamic library dependency' >&2
exit 1
fi
"$binary" --version
mkdir -p dist
cp "$binary" dist/strata-next-linux-x86_64-musl
{
echo "Commit: $GITHUB_SHA"
echo "Workflow: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
rustc --version
cargo --version
musl-gcc --version
readelf --version
} > dist/BUILD-PROVENANCE.txt
{
readelf -h "$binary"
readelf -l "$binary"
readelf -d "$binary"
} > dist/ELF-AUDIT.txt
cd dist
sha256sum strata-next-linux-x86_64-musl BUILD-PROVENANCE.txt ELF-AUDIT.txt > SHA256SUMS
- name: Publish verified tagged CLI preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile cli --tag "$GITHUB_REF_NAME" --target "$GITHUB_SHA" \
--title "Strata Next ${GITHUB_REF_NAME}" \
--notes 'CLI/control-plane preview rebuilt at the exact tag after CLI and container gates passed. CUDA engine and model files are not included.' \
--directory dist
+17
View File
@@ -0,0 +1,17 @@
# Gitea preview publication
The Linux workflow publishes through `https://git.vezha.io/api/v1` with a repository-scoped `GITEA_TOKEN` secret. Python is used only for offline CI publication; serving is unchanged. The publisher and its API fixture tests derive from tracked commit `a8fa7e0`, adapted to the current assembly receipts. The imported Strata upstream record remains unchanged.
| Profile | Exact assets | Tag scope |
| --- | --- | --- |
| CLI | binary, BUILD-PROVENANCE.txt, ELF-AUDIT.txt, SHA256SUMS | cli-preview-RUN-ATTEMPT or explicit vVERSION |
| Hosted CUDA | binary, PROVENANCE.json, SHA256SUMS, runtime-image.tar, IMAGE-PROVENANCE.json, CUDA-TOOLCHAIN.json, CUDA-LICENSES.tar, IMAGE-SHA256SUMS | cuda-preview-RUN-ATTEMPT |
| Static CUDA | binary, PROVENANCE.json, SHA256SUMS, runtime-image.tar, IMAGE-PROVENANCE.json, IMAGE-SHA256SUMS | static-cuda-preview-RUN-ATTEMPT |
All profiles reject missing/extra files, symlinks, mismatched checksums and source revisions before creating a release. CLI publication requires one exact Commit line and a static x86_64 ELF audit. The existing static CLI lifecycle, Responses, restart and CPU rollback gates remain prerequisites. A version-tag job rebuilds the same gated tag commit with the existing pinned Rust/musl build command, then repeats the original ELF audit and generates checksums for the rebuilt assets; it does not claim bitwise reproducibility against the earlier preview binary.
CUDA publication validates current package `loader_probe` receipts from `--probe-in-runtime-image`, image/package receipt binding and canonical compile-feature digests. These producers do not emit the historical `engine_help_probe` strings; their existing loader/identity/help probes must pass for assembly to emit the current receipts. Hosted toolchain publication additionally binds the actual builder image identity, source, engine hash, compile-feature digest, runtime image identity and saved archive hash. The inactive static CUDA profile preserves its original six-file contract and has no hosted compiler or license receipt qualification. Its runner and build inputs are unchanged.
Publication creates a draft prerelease, streams the exact verified assets, checks response names/sizes, and rereads each same-origin Gitea attachment to compare size and SHA256. Only then does it remove draft status. Redirects and foreign asset URLs are rejected; tokens are not forwarded to them. HTTPS verifies certificates; plaintext is accepted only for loopback API fixtures. API error bodies are not printed. An upload or verification failure leaves a draft, and does not publish an incomplete release. A retry uses a fresh run attempt tag; existing release cleanup is an operator action. Gitea previews do not inherit the former GitHub artifact seven-day retention; retention is an operator policy.
Receipts record CI/operator-declared source identity, not binary-to-source attestation. GPU/model qualification stays false; these publications do not establish inference quality, throughput, model readiness or deployment readiness. Synthetic tests exercise API streaming, remote corruption, interrupted uploads, exact profiles, forged rehashed receipts and the current producer validators. Real private Gitea publication remains a workflow qualification gate.
+1
View File
@@ -14,6 +14,7 @@ python3 "${repo_root}/scripts/test-static-cuda-profile.py"
python3 "${repo_root}/scripts/test-static-cuda-elf.py"
python3 "${repo_root}/scripts/test-linux-package.py"
python3 "${repo_root}/scripts/test-runtime-image.py"
python3 "${repo_root}/scripts/test-gitea-release.py"
python3 "${repo_root}/scripts/test-keyless-routing.py"
cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check
+353
View File
@@ -0,0 +1,353 @@
#!/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, urlsplit
PACKAGE_BINARY = 'strata-next-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):
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)
return {'name': name, 'size': size}
finally:
if fd >= 0:
os.close(fd)
if conn is not None:
conn.close()
def verify_uploaded_asset(parts, token, metadata, expected):
# Never forward a scoped token to a redirect or to an asset's foreign URL.
url = metadata.get('browser_download_url')
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
not re.fullmatch(r'/attachments/[A-Za-z0-9-]+', asset_url.path)):
raise ValueError('Gitea asset download URL must be a same-origin attachment')
conn = connection(parts)
try:
conn.request('GET', asset_url.path, headers={'Authorization': f'token {token}'})
response = conn.getresponse()
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')
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]))
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()
+420
View File
@@ -0,0 +1,420 @@
#!/usr/bin/env python3
"""Contract tests for private CUDA preview release publishing."""
import hashlib
import importlib.util
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from pathlib import Path
import tempfile
import threading
from urllib.parse import parse_qs, urlsplit
import unittest
spec = importlib.util.spec_from_file_location('publisher', Path(__file__).with_name('publish-gitea-release.py'))
publisher = importlib.util.module_from_spec(spec)
spec.loader.exec_module(publisher)
TOKEN = 'fixture-action-token'
REVISION = 'a' * 40
class FakeGitea(BaseHTTPRequestHandler):
def log_message(self, *_args):
pass
def send_json(self, status, payload):
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
if self.headers.get('Authorization') != f'token {TOKEN}':
self.send_json(401, {'message': 'bad token'})
return
if self.path == '/api/v1/repos/owner/repo/releases':
body = self.rfile.read(int(self.headers['Content-Length']))
self.server.release_payload = json.loads(body)
if self.server.fail_create:
return self.send_json(403, {'message': TOKEN})
return self.send_json(201, dict(self.server.release_payload, id=73, html_url='http://gitea.invalid/owner/repo/releases/tag/x'))
parsed = urlsplit(self.path)
if parsed.path == '/api/v1/repos/owner/repo/releases/73/assets':
size = int(self.headers['Content-Length'])
digest = hashlib.sha256()
content = bytearray()
remaining = size
while remaining:
block = self.rfile.read(min(128 * 1024, remaining))
if not block:
raise AssertionError('truncated streamed request body')
digest.update(block)
content.extend(block)
remaining -= len(block)
name = parse_qs(parsed.query)['name'][0]
self.server.assets.append({'name': name, 'size': size, 'sha256': digest.hexdigest()})
if self.server.fail_asset:
return self.send_json(500, {'message': TOKEN})
attachment = hashlib.sha256(name.encode()).hexdigest()
self.server.downloads[attachment] = bytes(content)
download = f'http://127.0.0.1:{self.server.server_port}/attachments/{attachment}'
if self.server.foreign_download:
download = 'https://foreign.invalid/attachments/id'
return self.send_json(201, {'name': name, 'size': size, 'browser_download_url': download})
self.send_json(404, {'message': 'unexpected route'})
def do_GET(self):
if self.headers.get('Authorization') != f'token {TOKEN}':
return self.send_json(401, {'message': 'bad token'})
name = self.path.removeprefix('/attachments/')
content = self.server.downloads.get(name)
if content is None:
return self.send_json(404, {})
if self.server.corrupt_download:
content = b'x' + content[1:]
self.send_response(200)
self.send_header('Content-Length', str(len(content)))
self.end_headers()
self.wfile.write(content)
def do_PATCH(self):
if self.headers.get('Authorization') != f'token {TOKEN}':
return self.send_json(401, {'message': 'bad token'})
if self.path != '/api/v1/repos/owner/repo/releases/73':
return self.send_json(404, {'message': 'unexpected route'})
self.server.finalize_payload = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
self.send_json(200, {'id': 73, 'draft': self.server.finalize_payload['draft']})
class PublisherTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.directory = Path(self.tmp.name)
self.server = ThreadingHTTPServer(('127.0.0.1', 0), FakeGitea)
self.server.release_payload = None
self.server.finalize_payload = None
self.server.assets = []
self.server.fail_create = False
self.server.fail_asset = False
self.server.downloads = {}
self.server.foreign_download = False
self.server.corrupt_download = False
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
self.addCleanup(self.server.server_close)
self.addCleanup(self.thread.join)
self.addCleanup(self.server.shutdown)
self.api_url = f'http://127.0.0.1:{self.server.server_port}/api/v1'
self.write_artifacts()
def write_artifacts(self):
directory = self.directory
(directory / publisher.PACKAGE_BINARY).write_bytes(b'embedded-engine-fixture')
engine_sha = hashlib.sha256(b'cuda-engine-fixture').hexdigest()
features = {'schema_version': 1, 'source_revision': REVISION, 'cuda_architectures': '120',
'features': {'cuda': True, 'cuda_static_runtime': True, 'cxx_static_runtime': True,
'kar_ple': False, 'kar_experts': False, 'ple_trace': False}}
feature_sha = publisher.canonical_sha(features)
base = 'ubuntu@sha256:' + 'b' * 64
package_provenance = {
'schema_version': 1, 'kind': 'static-cuda-preview', 'source_revision': REVISION,
'target': 'x86_64-unknown-linux-musl', 'gpu_tested': False, 'model_tested': False,
'clean_node_tested': False,
'engine': {'sha256': engine_sha, 'embedded': True, 'target_os': 'linux',
'target_arch': 'x86_64', 'declared_source_revision': REVISION, 'bytes': 19},
'engine_elf_audit': {'toolkit_shared_libraries': False, 'host_glibc_required': True,
'minimum_glibc': '2.39'},
'loader_probe': {'environment': 'pinned-runtime-container', 'base': base, 'glibc': '2.43',
'image_id': 'sha256:' + 'b' * 64, 'user': '65532:65532', 'gpu_tested': False},
'build_features': features, 'build_features_sha256': feature_sha,
}
(directory / 'PROVENANCE.json').write_text(json.dumps(package_provenance))
package_files = [publisher.PACKAGE_BINARY, 'PROVENANCE.json']
(directory / 'SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(directory / name)} {name}\n' for name in package_files))
receipt = publisher.file_sha256(directory / 'SHA256SUMS')
(directory / 'runtime-image.tar').write_bytes(b'runtime-image-' * 180000)
image_provenance = {
'schema_version': 1, 'kind': 'static-cuda-preview', 'source_revision': REVISION,
'image': 'sha256:' + 'c' * 64, 'base': base, 'base_glibc': '2.43',
'gpu_tested': False, 'model_tested': False, 'package_receipt_sha256': receipt,
'build_features': features['features'], 'build_features_sha256': feature_sha,
'qualification': 'Non-root GPU-hidden embedded identity and loader help only.',
}
(directory / 'IMAGE-PROVENANCE.json').write_text(json.dumps(image_provenance))
(directory / 'CUDA-TOOLCHAIN.json').write_text(json.dumps({
'source': REVISION, 'driver_tested': False, 'model_tested': False,
'builder_image_id': 'sha256:' + 'd' * 64, 'cuda_architectures': '120',
'build_features': features['features'], 'build_features_sha256': feature_sha,
'docker_builder': {'source_commit': REVISION, 'engine_sha256': engine_sha,
'image_id': 'sha256:' + 'd' * 64, 'build_features_sha256': feature_sha,
'runtime_image_id': image_provenance['image'],
'runtime_archive_sha256': publisher.file_sha256(directory / 'runtime-image.tar')},
}))
(directory / 'CUDA-LICENSES.tar').write_bytes(b'license archive')
image_files = ['runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar']
(directory / 'IMAGE-SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(directory / name)} {name}\n' for name in image_files))
def test_uploads_exact_hashed_assets_via_api_v1_and_streams_large_asset(self):
result = publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'CUDA preview 42.1', 'Build-only preview.', self.directory)
self.assertEqual(result['release_id'], 73)
self.assertEqual(result['target'], REVISION)
self.assertEqual(len(result['assets']), len(publisher.ASSETS))
self.assertEqual(self.server.release_payload, {
'tag_name': 'cuda-preview-42-1', 'target_commitish': REVISION, 'name': 'CUDA preview 42.1',
'body': 'Build-only preview.', 'draft': True, 'prerelease': True,
})
self.assertEqual(self.server.finalize_payload, {'draft': False})
uploaded = {asset['name']: asset for asset in self.server.assets}
self.assertEqual(set(uploaded), publisher.ASSETS)
self.assertGreater(uploaded['runtime-image.tar']['size'], publisher.CHUNK_SIZE)
for name in publisher.ASSETS:
self.assertEqual(uploaded[name]['sha256'], publisher.file_sha256(self.directory / name))
def test_checksum_failure_precedes_api_call(self):
(self.directory / publisher.PACKAGE_BINARY).write_bytes(b'tampered')
with self.assertRaisesRegex(ValueError, 'SHA256SUMS checksum mismatch'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertIsNone(self.server.release_payload)
def test_wrong_source_provenance_is_rejected(self):
path = self.directory / 'IMAGE-PROVENANCE.json'
image = json.loads(path.read_text())
image['source_revision'] = 'c' * 40
path.write_text(json.dumps(image))
files = ['runtime-image.tar', 'IMAGE-PROVENANCE.json', 'CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar']
(self.directory / 'IMAGE-SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(self.directory / name)} {name}\n' for name in files))
with self.assertRaisesRegex(ValueError, 'runtime image provenance'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertIsNone(self.server.release_payload)
def test_api_failures_redact_token_and_do_not_finalize_incomplete_release(self):
self.server.fail_create = True
with self.assertRaisesRegex(RuntimeError, r'HTTP 403$') as failure:
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertNotIn(TOKEN, str(failure.exception))
self.assertIsNone(self.server.finalize_payload)
self.server.fail_create = False
self.server.fail_asset = True
with self.assertRaisesRegex(RuntimeError, r'HTTP 500$'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertIsNone(self.server.finalize_payload)
def test_unexpected_extra_file_and_invalid_route_are_rejected(self):
(self.directory / 'private-key').write_text('never upload')
with self.assertRaisesRegex(ValueError, 'exactly the CUDA preview files'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
(self.directory / 'private-key').unlink()
with self.assertRaisesRegex(ValueError, 'API URL'):
publisher.publish(self.api_url.replace('/api/v1', '/api/v3'), 'owner/repo', TOKEN,
'cuda-preview-42-1', REVISION, 'title', 'notes', self.directory)
self.assertIsNone(self.server.release_payload)
def test_invalid_scope_and_target_rejected(self):
with self.assertRaisesRegex(ValueError, 'owner/name'):
publisher.publish(self.api_url, '../repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
with self.assertRaisesRegex(ValueError, 'full lowercase Git SHA'):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', 'ABC',
'title', 'notes', self.directory)
self.assertIsNone(self.server.release_payload)
def rehash(self):
for manifest, names in [('SHA256SUMS', publisher.PACKAGE_ASSETS),
('IMAGE-SHA256SUMS', publisher.IMAGE_ASSETS)]:
(self.directory / manifest).write_text(''.join(
f'{publisher.file_sha256(self.directory / name)} {name}\n' for name in sorted(names)))
image_path = self.directory / 'IMAGE-PROVENANCE.json'
image = json.loads(image_path.read_text())
image['package_receipt_sha256'] = publisher.file_sha256(self.directory / 'SHA256SUMS')
image_path.write_text(json.dumps(image))
(self.directory / 'IMAGE-SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(self.directory / name)} {name}\n' for name in sorted(publisher.IMAGE_ASSETS)))
def test_current_producer_receipt_contract(self):
# Exercise the producer's own validators, not source-text pattern checks.
import shutil
for filename in ('build-linux-package.py', 'build-runtime-image.py'):
spec = importlib.util.spec_from_file_location('producer', Path(__file__).with_name(filename))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
package = json.loads((self.directory / 'PROVENANCE.json').read_text())
feature_file = root / 'BUILD-FEATURES.json'
feature_file.write_text(json.dumps(package['build_features'], sort_keys=True, indent=2) + '\n')
if filename == 'build-linux-package.py':
self.assertEqual(module.build_features(feature_file, REVISION),
(package['build_features'], package['build_features_sha256']))
else:
source = root / 'source'
stage = root / 'stage'
source.mkdir(); stage.mkdir()
for name in module.FILES:
shutil.copyfile(self.directory / name, source / name)
self.assertEqual(module.freeze(source, stage,
publisher.file_sha256(source / 'SHA256SUMS'), False), package)
self.assertEqual(set(publisher.verify_artifacts(self.directory, REVISION)), publisher.ASSETS)
def test_forged_receipt_bindings_fail_even_with_fresh_checksums(self):
faults = [('CUDA-TOOLCHAIN.json', ('docker_builder', 'engine_sha256'), 'e' * 64),
('CUDA-TOOLCHAIN.json', ('docker_builder', 'runtime_image_id'), 'sha256:' + 'e' * 64),
('CUDA-TOOLCHAIN.json', ('docker_builder', 'source_commit'), 'e' * 40),
('CUDA-TOOLCHAIN.json', ('docker_builder', 'runtime_archive_sha256'), 'e' * 64),
('CUDA-TOOLCHAIN.json', ('build_features_sha256',), 'e' * 64),
('IMAGE-PROVENANCE.json', ('base',), 'ubuntu@sha256:' + 'e' * 64),
('IMAGE-PROVENANCE.json', ('gpu_tested',), True),
('PROVENANCE.json', ('loader_probe', 'environment'), 'assembly-host'),
('PROVENANCE.json', ('build_features', 'source_revision'), 'e' * 40),
('PROVENANCE.json', ('build_features', 'features', 'kar_experts'), True),
('PROVENANCE.json', ('engine_elf_audit', 'toolkit_shared_libraries'), True),
('PROVENANCE.json', ('engine_elf_audit', 'minimum_glibc'), '99.0'),
('PROVENANCE.json', ('loader_probe', 'glibc'), None)]
for filename, keys, value in faults:
with self.subTest(filename=filename, keys=keys):
self.write_artifacts()
path = self.directory / filename
record = json.loads(path.read_text())
dest = record
for key in keys[:-1]:
dest = dest[key]
dest[keys[-1]] = value
path.write_text(json.dumps(record))
self.rehash()
with self.assertRaises(ValueError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertIsNone(self.server.release_payload)
def write_cli(self):
for path in self.directory.iterdir():
path.unlink()
(self.directory / publisher.PACKAGE_BINARY).write_bytes(b'synthetic-static-cli')
(self.directory / 'BUILD-PROVENANCE.txt').write_text(
f'Commit: {REVISION}\nWorkflow: https://gitea.invalid/owner/repo/actions/runs/42\nrustc fixture\n')
(self.directory / 'ELF-AUDIT.txt').write_text(
'ELF Header:\n Class: ELF64\n Machine: Advanced Micro Devices X86-64\nNo dynamic section.\n')
self.rehash_cli()
def rehash_cli(self):
(self.directory / 'SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(self.directory / name)} {name}\n'
for name in sorted(publisher.CLI_ASSETS - {'SHA256SUMS'})))
def test_cli_four_assets_and_version_tag_publish_after_all_uploads(self):
self.write_cli()
for tag in ('cli-preview-42-1', 'v0.1.0-preview'):
self.server.assets = []
result = publisher.publish(self.api_url, 'owner/repo', TOKEN, tag, REVISION,
'CLI preview', 'No engine or model.', self.directory, 'cli')
self.assertEqual({asset['name'] for asset in result['assets']}, publisher.CLI_ASSETS)
self.assertTrue(self.server.release_payload['draft'])
self.assertTrue(self.server.release_payload['prerelease'])
self.assertEqual(self.server.finalize_payload, {'draft': False})
def test_cli_mismatch_and_bad_static_audit_fail_before_create(self):
for fault in ('wrong-commit', 'duplicate-commit', 'dynamic-elf', 'tamper', 'extra-file'):
with self.subTest(fault=fault):
self.write_cli()
provenance = self.directory / 'BUILD-PROVENANCE.txt'
if fault == 'wrong-commit':
provenance.write_text(provenance.read_text().replace(REVISION, 'e' * 40))
elif fault == 'duplicate-commit':
provenance.write_text(provenance.read_text() + f'Commit: {REVISION}\n')
elif fault == 'dynamic-elf':
audit = self.directory / 'ELF-AUDIT.txt'
audit.write_text(audit.read_text() + 'INTERP\n')
elif fault == 'extra-file':
(self.directory / 'private-key').write_text('synthetic')
self.rehash_cli()
if fault == 'tamper':
(self.directory / publisher.PACKAGE_BINARY).write_bytes(b'tampered')
with self.assertRaises(ValueError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cli-preview-42-1', REVISION,
'title', 'notes', self.directory, 'cli')
self.assertIsNone(self.server.release_payload)
def test_missing_cuda_files_and_cli_upload_fault_leave_no_published_release(self):
(self.directory / 'CUDA-LICENSES.tar').unlink()
with self.assertRaises(ValueError):
publisher.verify_artifacts(self.directory, REVISION)
self.write_cli()
self.server.fail_asset = True
with self.assertRaises(RuntimeError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cli-preview-42-1', REVISION,
'title', 'notes', self.directory, 'cli')
self.assertTrue(self.server.release_payload['draft'])
self.assertIsNone(self.server.finalize_payload)
def test_remote_corruption_and_foreign_download_leave_release_draft(self):
for flag in ('corrupt_download', 'foreign_download'):
with self.subTest(flag=flag):
setattr(self.server, flag, True)
with self.assertRaises(ValueError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertTrue(self.server.release_payload['draft'])
self.assertIsNone(self.server.finalize_payload)
setattr(self.server, flag, False)
def test_static_cuda_exact_six_file_profile(self):
for name in ('CUDA-TOOLCHAIN.json', 'CUDA-LICENSES.tar'):
(self.directory / name).unlink()
(self.directory / 'IMAGE-SHA256SUMS').write_text(''.join(
f'{publisher.file_sha256(self.directory / name)} {name}\n'
for name in sorted(publisher.STATIC_IMAGE_ASSETS)))
result = publisher.publish(self.api_url, 'owner/repo', TOKEN, 'static-cuda-preview-42-1', REVISION,
'Static preview', 'No hosted toolchain qualification.', self.directory, 'static-cuda')
self.assertEqual({asset['name'] for asset in result['assets']}, publisher.STATIC_ASSETS)
with self.assertRaises(ValueError):
publisher.verify_artifacts(self.directory, REVISION, 'cuda')
def test_https_policy_and_profile_tag_isolation(self):
for url in ('http://gitea.invalid/api/v1', 'https://api.github.com/api/v1',
'https://user:password@gitea.invalid/api/v1'):
with self.assertRaises(ValueError):
publisher.parse_api_url(url)
for tag in ('cli-preview-42-1', 'static-cuda-preview-42-1', 'v0.1.0'):
with self.assertRaises(ValueError):
publisher.publish(self.api_url, 'owner/repo', TOKEN, tag, REVISION,
'title', 'notes', self.directory, 'cuda')
self.assertIsNone(self.server.release_payload)
def test_invalid_token_is_rejected_without_transport_or_secret_echo(self):
for token in ('synthetic-secret\r\ninjected', 'synthetic secret', 'x' * 513, 'synthetic-\u00e9'):
with self.subTest(token_kind=len(token)):
with self.assertRaisesRegex(ValueError, 'bounded printable ASCII') as failure:
publisher.publish(self.api_url, 'owner/repo', token, 'cuda-preview-42-1', REVISION,
'title', 'notes', self.directory)
self.assertNotIn(token, str(failure.exception))
self.assertNotIn('synthetic-secret', str(failure.exception))
self.assertIsNone(self.server.release_payload)
def test_nonregular_and_symlink_files_are_rejected_before_transport(self):
import os
path = self.directory / 'CUDA-LICENSES.tar'
path.unlink()
os.mkfifo(path)
with self.assertRaisesRegex(ValueError, 'regular artifact'):
publisher.verify_artifacts(self.directory, REVISION)
path.unlink()
path.symlink_to(self.directory / publisher.PACKAGE_BINARY)
with self.assertRaises(OSError):
publisher.verify_artifacts(self.directory, REVISION)
self.assertIsNone(self.server.release_payload)
if __name__ == '__main__':
unittest.main()