ci(gitea): split builds and retry artifact publication

This commit is contained in:
lingjhf committed 2026-10-06 14:04:09 +08:00
1 parent d83f94afd5
commit b225008476
18 files changed
+1790 -286

No files matched your search

+63 -28
View File
@@ -8,24 +8,12 @@ import sys
import tempfile
import zipfile
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, app_versions, checksum_lines, validate_artifact
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, METADATA, app_versions, checksum_lines, validate_artifact
ROOT = Path(__file__).resolve().parents[2]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--vpk', type=Path, required=True, help='Pinned vpk executable or DLL')
args = parser.parse_args()
version, windows_version = app_versions(ROOT / 'pubspec.yaml')
output = ROOT / 'dist'
# Repeated builds must not accidentally upload a previous version's files.
if output.exists() and any(output.iterdir()):
raise ValueError('dist must be empty; use a clean release workspace')
apk = ROOT / 'build/app/outputs/flutter-apk/app-production-release.apk'
windows = ROOT / 'build/windows/x64/production/runner/Release'
if not apk.is_file() or not (windows / 'cutdex.exe').is_file():
raise ValueError('Both production builds are required')
def validate_apk(apk):
with zipfile.ZipFile(apk) as archive:
names = archive.namelist()
for abi in ('arm64-v8a', 'x86_64'):
@@ -33,6 +21,9 @@ def main():
raise ValueError(f'APK missing Flutter ABI: {abi}')
if any(name.startswith('lib/armeabi-v7a/') for name in names):
raise ValueError('APK must use supported 64-bit ABIs only')
def package_windows(windows, vpk, windows_version):
sys.path.insert(0, str(ROOT / 'tool/windows'))
from check_windows_release import audit
from windows_updates import package_app
@@ -48,25 +39,69 @@ def main():
with path.open('rb') as stream:
checksums[path.relative_to(staged).as_posix()] = hashlib.file_digest(stream, 'sha256').hexdigest()
(staged / 'checksums.json').write_text(json.dumps(checksums), encoding='utf-8')
result = package_app(staged, releases, args.vpk, require_processing=False)
result = package_app(staged, releases, vpk, require_processing=False)
if result['version'] != windows_version:
raise ValueError('Built Windows version differs from pubspec')
contents = {f'cutdex-{version}-android.apk': apk.read_bytes(),
AUDIT: (json.dumps(report, indent=2) + '\n').encode()}
contents = {AUDIT: (json.dumps(report, indent=2) + '\n').encode()}
for path in releases.iterdir():
if path.name in {FEED, INSTALLER, PORTABLE} or path.suffix == '.nupkg':
contents[path.name] = path.read_bytes()
files = {name: hashlib.sha256(body).hexdigest() for name, body in contents.items()}
manifest = {'version': version, 'files': files, 'windowsUpdateVersion': windows_version,
'windowsPackageId': 'Cutdex', 'windowsChannel': 'win-x64',
'androidSigning': 'debug', 'processingWorkersBundled': False}
contents['SHA256SUMS'] = checksum_lines(files).encode()
contents['release-manifest.json'] = (json.dumps(manifest, indent=2) + '\n').encode()
validate_artifact(contents, version, windows_version)
output.mkdir(exist_ok=True)
for name, body in contents.items():
(output / name).write_bytes(body)
print(json.dumps(manifest, indent=2))
return contents
def assemble(contents, version, windows_version):
files = {name: hashlib.sha256(body).hexdigest() for name, body in contents.items()}
manifest = {'version': version, 'files': files, 'windowsUpdateVersion': windows_version,
'windowsPackageId': 'Cutdex', 'windowsChannel': 'win-x64',
'androidSigning': 'debug', 'processingWorkersBundled': False}
contents['SHA256SUMS'] = checksum_lines(files).encode()
contents['release-manifest.json'] = (json.dumps(manifest, indent=2) + '\n').encode()
validate_artifact(contents, version, windows_version)
return contents
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--platform', choices=['all', 'windows', 'assemble'], default='all')
parser.add_argument('--vpk', type=Path, help='Pinned vpk executable or DLL')
parser.add_argument('--windows-packages', type=Path, help='Previously packaged Windows artifact directory')
args = parser.parse_args()
if args.platform != 'assemble' and args.vpk is None:
parser.error('--vpk is required when packaging Windows')
if args.platform == 'assemble' and args.windows_packages is None:
parser.error('--windows-packages is required when assembling artifacts')
version, windows_version = app_versions(ROOT / 'pubspec.yaml')
output = ROOT / 'dist'
if output.exists() and any(output.iterdir()):
raise ValueError('dist must be empty; use a clean release workspace')
metadata = ROOT / '.build/release-metadata'
if args.platform != 'windows' and metadata.exists() and any(metadata.iterdir()):
raise ValueError('Release metadata output must be empty')
apk = ROOT / 'build/app/outputs/flutter-apk/app-production-release.apk'
windows = ROOT / 'build/windows/x64/production/runner/Release'
if args.platform != 'windows':
validate_apk(apk)
if args.platform == 'assemble':
contents = {path.name: path.read_bytes() for path in args.windows_packages.iterdir() if path.is_file()}
if any(path.is_dir() for path in args.windows_packages.iterdir()):
raise ValueError('Windows packages must be a flat artifact directory')
if f'cutdex-{version}-android.apk' in contents:
raise ValueError('Unexpected Android package in Windows artifact')
else:
if not (windows / 'cutdex.exe').is_file():
raise ValueError('Production Windows build is required')
contents = package_windows(windows, args.vpk, windows_version)
if args.platform != 'windows':
contents[f'cutdex-{version}-android.apk'] = apk.read_bytes()
assemble(contents, version, windows_version)
output.mkdir(exist_ok=True)
for name, body in contents.items():
(output / name).write_bytes(body)
if args.platform != 'windows':
metadata.mkdir(parents=True, exist_ok=True)
for name in METADATA:
(metadata / name).write_bytes(contents[name])
print(json.dumps({'platform': args.platform, 'version': version, 'files': sorted(contents)}, indent=2))
if __name__ == '__main__':
+14
View File
@@ -0,0 +1,14 @@
$ErrorActionPreference = 'Stop'
# Use runner-user caches rather than checkout-local directories. Preserve any
# administrator overrides, and do not archive caches while another job uses them.
$pubCache = if ($env:PUB_CACHE) { $env:PUB_CACHE } else { Join-Path $env:LOCALAPPDATA 'Pub/Cache' }
$gradleCache = if ($env:GRADLE_USER_HOME) { $env:GRADLE_USER_HOME } else { Join-Path $env:USERPROFILE '.gradle' }
foreach ($directory in @($pubCache, $gradleCache)) {
[IO.Directory]::CreateDirectory($directory) | Out-Null
}
if ($env:GITHUB_ENV) {
"PUB_CACHE=$pubCache" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
"GRADLE_USER_HOME=$gradleCache" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
}
Write-Output "Persistent Pub cache: $pubCache"
Write-Output "Persistent Gradle cache: $gradleCache"
+40
View File
@@ -0,0 +1,40 @@
$ErrorActionPreference = 'Stop'
# Persist fixed-version tools outside checkout, which Actions cleans between jobs.
$identity = python -c "import hashlib, sys; print(hashlib.sha256((sys.executable + sys.version).encode()).hexdigest()[:16])"
if ($LASTEXITCODE -ne 0) { throw 'Cannot identify packaging Python.' }
$root = Join-Path $env:LOCALAPPDATA "Cutdex/ci-tools/python-$identity-pefile-2024.8.26-vpk-1.2.161"
$python = Join-Path $root 'python/Scripts/python.exe'
$vpk = Join-Path $root 'vpk/vpk.exe'
$mutex = [Threading.Mutex]::new($false, "Local\CutdexPackageTools-$identity")
$locked = $false
try {
try { $locked = $mutex.WaitOne([TimeSpan]::FromMinutes(10)) }
catch [Threading.AbandonedMutexException] { $locked = $true }
if (-not $locked) { throw 'Timed out waiting for packaging tools setup.' }
if (-not (Test-Path -LiteralPath $python)) {
python -m venv (Join-Path $root 'python')
if ($LASTEXITCODE -ne 0) { throw 'Packaging environment setup failed.' }
}
$pefileVersion = & $python -c "import importlib.metadata; print(next((d.version for d in importlib.metadata.distributions() if d.metadata['Name'].lower() == 'pefile'), 'missing'))"
if ($LASTEXITCODE -ne 0) { throw 'Cached packaging Python failed.' }
if ($pefileVersion -ne '2024.8.26') {
& $python -m pip install pefile==2024.8.26
if ($LASTEXITCODE -ne 0) { throw 'Packaging dependency installation failed.' }
}
if (-not (Test-Path -LiteralPath $vpk)) {
dotnet tool install vpk --version 1.2.161 --tool-path (Join-Path $root 'vpk')
if ($LASTEXITCODE -ne 0) { throw 'Velopack tool installation failed.' }
}
$help = & $vpk --legacyConsole --skip-updates --help 2>&1
if ($LASTEXITCODE -ne 0 -or ($help -join "`n") -notmatch '(?<![\d.])1\.2\.161(?![\d.])') {
throw 'Cached Velopack version validation failed.'
}
if ($env:GITHUB_ENV) {
"PACKAGE_PYTHON=$python" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
"VPK_PATH=$vpk" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
}
Write-Output "Packaging tools ready: $root"
} finally {
if ($locked) { $mutex.ReleaseMutex() }
$mutex.Dispose()
}
-89
View File
@@ -1,89 +0,0 @@
"""Promote packages from a successful main CI for the exact release commit."""
import io
import json
import os
from pathlib import Path
import urllib.parse
import urllib.request
import uuid
import zipfile
from release_artifacts import app_versions, validate_artifact
SERVER = 'https://git.orangraph.com'
def request(url, data=None, method=None, content_type='application/json'):
headers = {'Authorization': 'token ' + os.environ['GITEA_TOKEN']}
if data is not None:
headers['Content-Type'] = content_type
if isinstance(data, dict):
data = json.dumps(data).encode()
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=300) as response:
body = response.read()
return json.loads(body) if 'application/json' in response.headers.get('Content-Type', '') else body
def download(asset):
url = urllib.parse.urlparse(asset['browser_download_url'])
if url.hostname != 'git.orangraph.com':
raise ValueError('Unexpected attachment host')
return request(urllib.parse.urlunparse(url._replace(scheme='https', netloc='git.orangraph.com')))
def main():
repo = os.environ['GITEA_REPOSITORY']
base = f'{SERVER}/api/v1/repos/{repo}'
sha = os.environ['GITEA_SHA']
tag = os.environ['RELEASE_TAG']
version, windows_version = app_versions('pubspec.yaml')
if tag != f'v{version}':
raise ValueError('Release tag must match pubspec version')
runs = request(f'{base}/actions/runs?limit=100')['workflow_runs']
matches = [run for run in runs if run['head_sha'] == sha and run['path'].endswith('@refs/heads/main') and run['conclusion'] == 'success' and Path(run['path'].split('@')[0]).name == 'ci.yml']
if not matches:
raise ValueError('No successful main CI for this exact commit; run CI before releasing')
run = max(matches, key=lambda item: item['id'])
artifacts = request(f"{base}/actions/runs/{run['id']}/artifacts")['artifacts']
found = [item for item in artifacts if item['name'] == 'cutdex-release-packages' and not item.get('expired', False)]
if len(found) != 1:
raise ValueError('Expected one validated application artifact')
data = request(f"{base}/actions/artifacts/{found[0]['id']}/zip")
with zipfile.ZipFile(io.BytesIO(data)) as archive:
entries = [item for item in archive.infolist() if not item.is_dir()]
if len({item.filename for item in entries}) != len(entries):
raise ValueError('Duplicate artifact filenames')
contents = {item.filename: archive.read(item) for item in entries}
validate_artifact(contents, version, windows_version)
releases = request(f'{base}/releases?limit=100')
existing = [release for release in releases if release['tag_name'] == tag]
if existing:
release = existing[0]
if not release['draft']:
raise ValueError('Release already published; choose a new version')
else:
release = request(f'{base}/releases', {'tag_name': tag, 'target_commitish': sha, 'name': f'Cutdex {version}', 'draft': True, 'prerelease': False, 'body': f'Windows x64 Velopack installer EXE, Portable ZIP, full update package and channel index; Android ARM64/x86_64 APK. Windows update version: {windows_version}. Android currently uses the project debug signing key. Processing workers and models are distributed separately. Verified CI run: {run["id"]}.'}, 'POST')
assets = request(f"{base}/releases/{release['id']}/assets")
for name, body in contents.items():
if '/' in name or '\\' in name:
raise ValueError('Unexpected artifact path')
prior = [asset for asset in assets if asset['name'] == name]
if prior:
continue
boundary = uuid.uuid4().hex
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + body + f'\r\n--{boundary}--\r\n'.encode())
request(f"{base}/releases/{release['id']}/assets?name={urllib.parse.quote(name)}", payload, 'POST', f'multipart/form-data; boundary={boundary}')
# Refuse publishing a resumed draft containing unrelated/stale attachments.
final_assets = request(f"{base}/releases/{release['id']}/assets")
if len(final_assets) != len(contents) or {asset['name'] for asset in final_assets} != set(contents):
raise ValueError('Draft Release attachments differ from the validated artifact')
for asset in final_assets:
if download(asset) != contents[asset['name']]:
raise ValueError('Final Release attachment verification failed: ' + asset['name'])
request(f"{base}/releases/{release['id']}", {'draft': False, 'prerelease': False}, 'PATCH')
print(f'{SERVER}/{repo}/releases/tag/{tag}')
if __name__ == '__main__':
main()
+25 -4
View File
@@ -12,6 +12,7 @@ FEED = 'releases.win-x64.json'
INSTALLER = 'Cutdex-win-x64-Setup.exe'
PORTABLE = 'Cutdex-win-x64-Portable.zip'
AUDIT = 'windows-dependency-audit.json'
METADATA = frozenset({'release-manifest.json', 'SHA256SUMS', FEED, AUDIT})
def app_versions(pubspec):
@@ -26,7 +27,9 @@ def checksum_lines(files):
return ''.join(f'{files[name]} {name}\n' for name in sorted(files))
def validate_artifact(contents, version, windows_version):
def validate_metadata(contents, version, windows_version):
if set(contents) != METADATA:
raise ValueError('Release metadata requires manifest, checksums, index and audit')
manifest = json.loads(contents['release-manifest.json'])
if (manifest['version'] != version or manifest.get('windowsUpdateVersion') != windows_version
or manifest.get('windowsPackageId') != 'Cutdex'
@@ -44,16 +47,34 @@ def validate_artifact(contents, version, windows_version):
if not re.fullmatch(r'[A-Za-z0-9_.-]+\.nupkg', package):
raise ValueError('Invalid update package filename')
expected = {f'cutdex-{version}-android.apk', INSTALLER, PORTABLE, FEED, AUDIT, package}
if set(manifest['files']) != expected or set(contents) != expected | {'SHA256SUMS', 'release-manifest.json'}:
if set(manifest['files']) != expected:
raise ValueError('Release requires APK, installer, Portable ZIP, index, full package and audit')
for name, digest in manifest['files'].items():
if not isinstance(digest, str) or not re.fullmatch(r'[0-9a-f]{64}', digest):
raise ValueError('Invalid package checksum: ' + name)
if name in contents and hashlib.sha256(contents[name]).hexdigest() != digest:
raise ValueError(f'Package checksum mismatch: {name}')
if (not isinstance(asset.get('Size'), int) or asset['Size'] < 0
or str(asset.get('SHA256', '')).lower() != manifest['files'][package]
or not re.fullmatch(r'[0-9a-fA-F]{40}', str(asset.get('SHA1', '')))):
raise ValueError('Update index checksums do not match the full package')
if contents['SHA256SUMS'].decode('utf-8') != checksum_lines(manifest['files']):
raise ValueError('SHA256SUMS differs from the release manifest')
return manifest
def validate_artifact(contents, version, windows_version):
manifest = validate_metadata({name: contents[name] for name in METADATA}, version, windows_version)
if set(contents) != set(manifest['files']) | {'SHA256SUMS', 'release-manifest.json'}:
raise ValueError('Release requires APK, installer, Portable ZIP, index, full package and audit')
for name, digest in manifest['files'].items():
if hashlib.sha256(contents[name]).hexdigest() != digest:
raise ValueError(f'Package checksum mismatch: {name}')
asset = json.loads(contents[FEED])['Assets'][0]
package = asset['FileName']
payload = contents[package]
if (asset.get('Size') != len(payload)
or str(asset.get('SHA256', '')).lower() != hashlib.sha256(payload).hexdigest()
or str(asset.get('SHA1', '')).lower() != hashlib.sha1(payload).hexdigest()):
raise ValueError('Update index checksums do not match the full package')
if contents['SHA256SUMS'].decode('utf-8') != checksum_lines(manifest['files']):
raise ValueError('SHA256SUMS differs from the release manifest')
return manifest
+109
View File
@@ -0,0 +1,109 @@
"""Gitea HTTP and bounded transfer helpers for staged release publication."""
import hashlib
from concurrent.futures import ThreadPoolExecutor
import http.client
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
SERVER = 'https://git.orangraph.com'
RETRY_DELAYS = (5, 15)
def transient(error):
if isinstance(error, urllib.error.HTTPError):
return error.code in {408, 429, 500, 502, 503, 504}
return isinstance(error, (urllib.error.URLError, TimeoutError, ConnectionError,
http.client.IncompleteRead))
def retry_read(operation):
"""Retry safe attachment-list reads, without retrying permanent HTTP errors."""
for attempt in range(len(RETRY_DELAYS) + 1):
try:
return operation()
except Exception as error:
if not transient(error) or attempt == len(RETRY_DELAYS):
raise
print(f'Attachment list temporarily unavailable; retrying in {RETRY_DELAYS[attempt]}s.', file=sys.stderr)
time.sleep(RETRY_DELAYS[attempt])
def request(url, data=None, method=None, content_type='application/json'):
headers = {'Authorization': 'token ' + os.environ['GITEA_TOKEN']}
if data is not None:
headers['Content-Type'] = content_type
if isinstance(data, dict):
data = json.dumps(data).encode()
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=300) as response:
body = response.read()
return json.loads(body) if body and 'application/json' in response.headers.get('Content-Type', '') else body
def attachment_url(asset):
url = urllib.parse.urlparse(asset['browser_download_url'])
if url.hostname != 'git.orangraph.com':
raise ValueError('Unexpected attachment host')
return urllib.parse.urlunparse(url._replace(scheme='https', netloc='git.orangraph.com'))
def fingerprint(asset):
"""Hash one remote attachment in chunks, keeping memory usage bounded."""
sha256, sha1, size = hashlib.sha256(), hashlib.sha1(), 0
req = urllib.request.Request(attachment_url(asset),
headers={'Authorization': 'token ' + os.environ['GITEA_TOKEN']})
with urllib.request.urlopen(req, timeout=300) as response:
while chunk := response.read(1024 * 1024):
sha256.update(chunk)
sha1.update(chunk)
size += len(chunk)
return {'sha256': sha256.hexdigest(), 'sha1': sha1.hexdigest(), 'size': size}
def upload_contents(base, release_id, contents, *, transport=None):
send = transport or request
def attachment_names():
assets = retry_read(lambda: send(f"{base}/releases/{release_id}/assets"))
names = [asset['name'] for asset in assets]
if len(set(names)) != len(names):
raise ValueError('Duplicate Release attachments')
return set(names)
names = attachment_names()
for name in contents:
if '/' in name or '\\' in name:
raise ValueError('Unexpected artifact path')
def upload(item):
name, body = item
boundary = uuid.uuid4().hex
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + body + f'\r\n--{boundary}--\r\n'.encode())
for attempt in range(len(RETRY_DELAYS) + 1):
# A timeout can occur after Gitea has committed the upload. Reconcile
# before another POST; publication will still verify the file bytes.
if attempt and name in attachment_names():
return
try:
send(f"{base}/releases/{release_id}/assets?name={urllib.parse.quote(name)}", payload, 'POST', f'multipart/form-data; boundary={boundary}')
return
except Exception as error:
if not transient(error):
raise
if attempt == len(RETRY_DELAYS):
if name in attachment_names():
return
raise
print(f'Upload temporarily failed for {name}; retrying in {RETRY_DELAYS[attempt]}s.', file=sys.stderr)
time.sleep(RETRY_DELAYS[attempt])
pending = [(name, body) for name, body in contents.items() if name not in names]
with ThreadPoolExecutor(max_workers=2) as executor:
# Consume every result so failures prevent the publication step.
list(executor.map(upload, pending))
+287
View File
@@ -0,0 +1,287 @@
"""Upload platform builds to a commit-bound draft, then verify and publish it."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import importlib.util
import io
import json
import os
from pathlib import Path
import urllib.error
import urllib.parse
import zipfile
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, app_versions, validate_metadata
import release_transport as transport
request = transport.request
fingerprint = transport.fingerprint
def context():
base = f"{transport.SERVER}/api/v1/repos/{os.environ['GITEA_REPOSITORY']}"
sha, tag = os.environ['GITEA_SHA'], os.environ['RELEASE_TAG']
version, windows_version = app_versions('pubspec.yaml')
if tag != f'v{version}':
raise ValueError('Release tag must match pubspec version')
remote_tag = request(f'{base}/tags/{urllib.parse.quote(tag, safe="")}')
if remote_tag['commit']['sha'] != sha:
raise ValueError('Release tag no longer matches the checked-out commit')
if os.environ.get('CI_RUN_ID'):
successful_ci(base, sha, int(os.environ['CI_RUN_ID']))
return base, sha, tag, version, windows_version
def marker(sha):
return f'<!-- cutdex-source-commit:{sha} -->'
def check_draft(release, sha, tag):
if not release.get('draft'):
raise ValueError('Release already published; choose a new version')
if release.get('tag_name') != tag or marker(sha) not in (release.get('body') or '').splitlines():
raise ValueError('Draft Release belongs to a different commit or release flow')
def ci_marker(run_id):
return f'<!-- cutdex-ci-run:{run_id} -->'
def successful_ci(base, sha, run_id=None):
runs = request(f'{base}/actions/runs?limit=100')['workflow_runs']
matches = [run for run in runs if run['head_sha'] == sha
and run['path'].endswith('@refs/heads/main')
and Path(run['path'].split('@')[0]).name == 'ci.yml'
and run['conclusion'] == 'success'
and (run_id is None or run['id'] == run_id)]
if not matches:
raise ValueError('No successful main CI for this exact commit; run CI before releasing')
return max(matches, key=lambda run: run['id'])
def ci_artifacts(base, run_id):
return [item for item in request(f'{base}/actions/runs/{run_id}/artifacts')['artifacts']
if not item.get('expired', False)]
def artifact_named(artifacts, name):
matches = [item for item in artifacts if item['name'] == name]
if len(matches) != 1:
raise ValueError('Expected one unexpired CI artifact: ' + name)
return matches[0]
def prepare_ci(base, sha, tag, version, windows_version):
# Keep retries bound to the original run, even if another same-commit CI
# succeeds later with different build bytes.
try:
existing = request(f'{base}/releases/tags/{urllib.parse.quote(tag, safe="")}')
except urllib.error.HTTPError as error:
if error.code != 404:
raise
existing = None
run_id = None
if existing is not None:
check_draft(existing, sha, tag)
import re
matches = re.findall(r'^<!-- cutdex-ci-run:(\d+) -->$', existing.get('body') or '', re.M)
if len(matches) != 1:
raise ValueError('Existing draft is not bound to a main CI run')
run_id = int(matches[0])
run = successful_ci(base, sha, run_id)
artifacts = ci_artifacts(base, run['id'])
verification = artifact_named(artifacts, 'cutdex-release-metadata')
selected = {platform: artifact_named(artifacts, f'cutdex-{platform}-build')
for platform in ('android', 'windows')}
release = prepare(base, sha, tag, version, windows_version, ci_run=run['id'])
if os.environ.get('GITHUB_OUTPUT'):
with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as stream:
stream.write(f"sha={sha}\nci-run-id={run['id']}\nartifact-id={verification['id']}\n")
for platform, artifact in selected.items():
stream.write(f"{platform}-artifact-id={artifact['id']}\n")
return release
def prepare(base, sha, tag, version, windows_version, *, ci_run=None):
try:
release = request(f'{base}/releases/tags/{urllib.parse.quote(tag, safe="")}')
except urllib.error.HTTPError as error:
if error.code != 404:
raise
release = request(f'{base}/releases', {
'tag_name': tag, 'target_commitish': sha, 'name': f'Cutdex {version}',
'draft': True, 'prerelease': False,
'body': f'{marker(sha)}\n' + (f'{ci_marker(ci_run)}\n' if ci_run is not None else '')
+ 'Windows x64 installer, Portable ZIP and full update package; '
f'Android ARM64/x86_64 APK. Windows update version: {windows_version}. '
'Packages are reused from successful main CI and uploaded independently. '
'Publication waits for all checks. '
'Android currently uses the project debug signing key. '
'Processing workers and models are distributed separately.'}, 'POST')
check_draft(release, sha, tag)
if ci_run is not None and ci_marker(ci_run) not in (release.get('body') or '').splitlines():
raise ValueError('Draft Release belongs to a different CI run')
if os.environ.get('GITHUB_OUTPUT'):
with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as stream:
stream.write(f"release-id={release['id']}\n")
return release
def upload_platform(base, release, contents):
"""Confirm upload presence; defer all byte verification to publication."""
transport.upload_contents(base, release['id'], contents, transport=request)
assets = request(f"{base}/releases/{release['id']}/assets")
names = [asset['name'] for asset in assets]
if len(set(names)) != len(names):
raise ValueError('Duplicate Release attachments')
if not set(contents) <= set(names):
raise ValueError('Missing uploaded platform attachments')
def asset_snapshot(assets):
return sorted((asset['id'], asset['name']) for asset in assets)
def verify_remote(base, release, metadata, manifest):
expected = dict(manifest['files'])
for name in ('SHA256SUMS', 'release-manifest.json'):
expected[name] = hashlib.sha256(metadata[name]).hexdigest()
assets = request(f"{base}/releases/{release['id']}/assets")
names = [asset['name'] for asset in assets]
if len(set(names)) != len(names) or set(names) != set(expected):
raise ValueError('Draft Release attachments differ from the validated artifact')
full = json.loads(metadata[FEED])['Assets'][0]
def verify(asset):
name = asset['name']
actual = fingerprint(asset)
if actual['sha256'] != expected[name]:
raise ValueError('Release attachment verification failed: ' + name)
if name == full['FileName'] and (actual['sha1'] != full['SHA1'].lower() or actual['size'] != full['Size']):
raise ValueError('Update index checksums do not match the full package')
with ThreadPoolExecutor(max_workers=2) as executor:
list(executor.map(verify, assets))
return asset_snapshot(assets)
def platform_contents(platform, path, version, windows_version):
if platform == 'android':
if path.is_dir():
expected = f'cutdex-{version}-android.apk'
if set(read_directory(path)) != {expected}:
raise ValueError('Expected exactly one Android APK')
path = path / expected
# Import lazily: assembling/uploading Windows must not require an APK.
spec = importlib.util.spec_from_file_location('package_app', Path(__file__).with_name('package-app.py'))
packaging = importlib.util.module_from_spec(spec)
spec.loader.exec_module(packaging)
packaging.validate_apk(path)
return {f'cutdex-{version}-android.apk': path.read_bytes()}
contents = read_directory(path)
# Validate the Windows feed/version/full-package hashes using the same
# complete-artifact validator before any bytes are uploaded.
required = {AUDIT, FEED, INSTALLER, PORTABLE}
if not required <= set(contents):
raise ValueError('Incomplete Windows packages')
dummy_apk = f'cutdex-{version}-android.apk'
if dummy_apk in contents or 'release-manifest.json' in contents or 'SHA256SUMS' in contents:
raise ValueError('Windows artifact contains unexpected release metadata')
validation = dict(contents)
validation[dummy_apk] = b''
spec = importlib.util.spec_from_file_location('package_app', Path(__file__).with_name('package-app.py'))
packaging = importlib.util.module_from_spec(spec)
spec.loader.exec_module(packaging)
packaging.assemble(validation, version, windows_version)
return contents
def read_directory(path):
paths = list(path.iterdir())
if any(not item.is_file() or item.is_symlink() for item in paths):
raise ValueError('Expected a flat package directory with regular files')
return {item.name: item.read_bytes() for item in paths}
def fetch_ci_artifact(base, command, path, version, windows_version):
run_id = int(os.environ['CI_RUN_ID'])
artifact_id = int(os.environ['CI_ARTIFACT_ID'])
artifacts = ci_artifacts(base, run_id)
matches = [item for item in artifacts if item['id'] == artifact_id]
if len(matches) != 1:
raise ValueError('Artifact does not belong to the selected CI run or has expired')
artifact = matches[0]
platform = command.removeprefix('fetch-')
expected = 'cutdex-release-metadata' if platform == 'release' else f'cutdex-{platform}-build'
if artifact['name'] != expected:
raise ValueError('Unexpected CI artifact type')
data = request(f'{base}/actions/artifacts/{artifact_id}/zip')
with zipfile.ZipFile(io.BytesIO(data)) as archive:
entries = [item for item in archive.infolist() if not item.is_dir()]
names = [item.filename for item in entries]
if len(set(names)) != len(names) or any('/' in name or '\\' in name for name in names):
raise ValueError('CI artifact requires unique flat filenames')
contents = {item.filename: archive.read(item) for item in entries}
apk_name = f'cutdex-{version}-android.apk'
if artifact['name'] == 'cutdex-release-metadata':
validate_metadata(contents, version, windows_version)
elif platform == 'android':
if set(contents) != {'app-production-release.apk'}:
raise ValueError('Unexpected Android build artifact')
contents = {apk_name: contents['app-production-release.apk']}
if path.exists() and any(path.iterdir()):
raise ValueError('CI artifact output directory must be empty')
path.mkdir(parents=True, exist_ok=True)
for name, body in contents.items():
(path / name).write_bytes(body)
if platform in {'android', 'windows'}:
platform_contents(platform, path, version, windows_version)
return artifact_id
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('command', choices=['prepare', 'prepare-ci', 'fetch-android', 'fetch-windows',
'fetch-release', 'android', 'windows', 'publish'])
parser.add_argument('--path', type=Path)
args = parser.parse_args()
if args.command not in {'prepare', 'prepare-ci'} and args.path is None:
parser.error('--path is required for uploading or publishing')
base, sha, tag, version, windows_version = context()
if args.command.startswith('fetch-'):
fetch_ci_artifact(base, args.command, args.path, version, windows_version)
return
if args.command == 'prepare-ci':
release = prepare_ci(base, sha, tag, version, windows_version)
elif args.command == 'prepare':
release = prepare(base, sha, tag, version, windows_version)
else:
release = request(f"{base}/releases/{int(os.environ['RELEASE_ID'])}")
check_draft(release, sha, tag)
if os.environ.get('CI_RUN_ID') and ci_marker(int(os.environ['CI_RUN_ID'])) not in (release.get('body') or '').splitlines():
raise ValueError('Draft Release belongs to a different CI run')
if args.command == 'publish':
contents = read_directory(args.path)
manifest = validate_metadata(contents, version, windows_version)
# Platform binaries must already have been independently uploaded.
metadata = {'SHA256SUMS', 'release-manifest.json'}
assets = request(f"{base}/releases/{release['id']}/assets")
if {asset['name'] for asset in assets} - metadata != set(manifest['files']):
raise ValueError('Not all platform packages have been uploaded')
transport.upload_contents(base, release['id'], {name: contents[name] for name in metadata}, transport=request)
snapshot = verify_remote(base, release, contents, manifest)
# Recheck tag binding and draft status immediately before publishing.
context()
check_draft(request(f"{base}/releases/{release['id']}"), sha, tag)
if snapshot != asset_snapshot(request(f"{base}/releases/{release['id']}/assets")):
raise ValueError('Release attachments changed during verification')
request(f"{base}/releases/{release['id']}", {'draft': False, 'prerelease': False}, 'PATCH')
else:
contents = platform_contents(args.command, args.path, version, windows_version)
upload_platform(base, release, contents)
print(json.dumps({'releaseId': release['id'], 'tag': tag, 'command': args.command}))
if __name__ == '__main__':
main()
+112
View File
@@ -0,0 +1,112 @@
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import zipfile
from test_release_artifacts import fixture
from release_artifacts import METADATA, validate_artifact, validate_metadata
spec = importlib.util.spec_from_file_location('package_app', Path(__file__).with_name('package-app.py'))
packaging = importlib.util.module_from_spec(spec)
spec.loader.exec_module(packaging)
def apk_bytes(abis=('arm64-v8a', 'x86_64')):
stream = io.BytesIO()
with zipfile.ZipFile(stream, 'w') as archive:
for abi in abis:
archive.writestr(f'lib/{abi}/libflutter.so', b'flutter')
return stream.getvalue()
class SplitPackagingTests(unittest.TestCase):
def run_cli(self, root, *args):
with patch.object(packaging, 'ROOT', root), patch('sys.argv', ['package-app.py', *args]), patch('sys.stdout', io.StringIO()):
packaging.main()
def prepare(self, root):
(root / 'pubspec.yaml').write_text('version: 0.1.0+2\n')
apk = root / 'build/app/outputs/flutter-apk/app-production-release.apk'
apk.parent.mkdir(parents=True)
apk.write_bytes(apk_bytes())
packages = root / 'windows-packages'
packages.mkdir()
for name, body in fixture().items():
if name not in {'cutdex-0.1.0-android.apk', 'SHA256SUMS', 'release-manifest.json'}:
(packages / name).write_bytes(body)
return packages
def test_assemble_requires_no_windows_build_or_resolved_dependencies(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
packages = self.prepare(root)
self.run_cli(root, '--platform', 'assemble', '--windows-packages', str(packages))
contents = {p.name: p.read_bytes() for p in (root / 'dist').iterdir()}
validate_artifact(contents, '0.1.0', '0.1.0-build.2')
metadata = {p.name: p.read_bytes() for p in (root / '.build/release-metadata').iterdir()}
self.assertEqual(set(metadata), METADATA)
validate_metadata(metadata, '0.1.0', '0.1.0-build.2')
self.assertTrue(all(metadata[name] == contents[name] for name in metadata))
self.assertEqual(contents['cutdex-0.1.0-android.apk'],
(root / 'build/app/outputs/flutter-apk/app-production-release.apk').read_bytes())
def test_assemble_rejects_tampered_update_package_before_writing(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
packages = self.prepare(root)
next(packages.glob('*.nupkg')).write_bytes(b'tampered')
with self.assertRaisesRegex(ValueError, 'index checksums'):
self.run_cli(root, '--platform', 'assemble', '--windows-packages', str(packages))
self.assertFalse((root / 'dist').exists())
def test_assemble_rejects_missing_stale_or_nested_windows_packages(self):
for change in ('missing', 'stale', 'nested'):
with self.subTest(change=change), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
packages = self.prepare(root)
if change == 'missing':
(packages / packaging.INSTALLER).unlink()
elif change == 'stale':
(packages / 'old.zip').write_bytes(b'old')
else:
(packages / 'nested').mkdir()
with self.assertRaises(ValueError):
self.run_cli(root, '--platform', 'assemble', '--windows-packages', str(packages))
self.assertFalse((root / 'dist').exists())
def test_windows_packaging_does_not_require_android(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / 'pubspec.yaml').write_text('version: 0.1.0+2\n')
windows = root / 'build/windows/x64/production/runner/Release'
windows.mkdir(parents=True)
(windows / 'cutdex.exe').write_bytes(b'exe')
with patch.object(packaging, 'package_windows', return_value={'windows.zip': b'zip'}) as pack:
self.run_cli(root, '--platform', 'windows', '--vpk', 'vpk.exe')
pack.assert_called_once_with(windows, Path('vpk.exe'), '0.1.0-build.2')
self.assertEqual({p.name for p in (root / 'dist').iterdir()}, {'windows.zip'})
def test_apk_rejects_missing_abi_and_32_bit_libraries(self):
for abis in [('arm64-v8a',), ('arm64-v8a', 'x86_64', 'armeabi-v7a')]:
with tempfile.TemporaryDirectory() as directory:
apk = Path(directory) / 'app.apk'
apk.write_bytes(apk_bytes(abis))
with self.assertRaises(ValueError):
packaging.validate_apk(apk)
def test_assemble_refuses_existing_output(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
packages = self.prepare(root)
(root / 'dist').mkdir()
(root / 'dist/stale.zip').write_bytes(b'stale')
with self.assertRaisesRegex(ValueError, 'dist must be empty'):
self.run_cli(root, '--platform', 'assemble', '--windows-packages', str(packages))
if __name__ == '__main__':
unittest.main()
-98
View File
@@ -1,98 +0,0 @@
import importlib.util
import io
from pathlib import Path
from unittest.mock import patch
import unittest
import urllib.parse
import zipfile
from test_release_artifacts import fixture
spec = importlib.util.spec_from_file_location('promote_release', Path(__file__).with_name('promote-release.py'))
promote = importlib.util.module_from_spec(spec)
spec.loader.exec_module(promote)
class PromotionTests(unittest.TestCase):
def scenario(self, *, extra=False, corrupt_remote=False, corrupt_artifact=False, resume=False, wrong_commit=False):
contents = fixture()
if corrupt_artifact:
contents['Cutdex-win-x64-Setup.exe'] += b'corrupt'
archive = io.BytesIO()
with zipfile.ZipFile(archive, 'w') as bundle:
for name, body in contents.items():
bundle.writestr(name, body)
stored = dict(contents) if resume else {}
if extra:
stored['stale.zip'] = b'stale'
calls = []
def assets():
return [{'name': name} for name in stored]
def request(url, data=None, method=None, content_type=None):
calls.append((method, url))
if url.endswith('/actions/runs?limit=100'):
return {'workflow_runs': [{'head_sha': 'other' if wrong_commit else 'commit',
'path': '.gitea/workflows/ci.yml@refs/heads/main', 'conclusion': 'success', 'id': 1}]}
if url.endswith('/actions/runs/1/artifacts'):
return {'artifacts': [{'name': 'cutdex-release-packages', 'id': 2}]}
if url.endswith('/actions/artifacts/2/zip'):
return archive.getvalue()
if url.endswith('/releases?limit=100'):
return [{'id': 3, 'tag_name': 'v0.1.0', 'draft': True}] if resume else []
if url.endswith('/releases') and method == 'POST':
self.assertTrue(data['draft'])
return {'id': 3}
if url.endswith('/releases/3/assets'):
return assets()
if '/assets?name=' in url and method == 'POST':
name = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)['name'][0]
boundary = content_type.split('boundary=')[1].encode()
stored[name] = data.split(b'\r\n\r\n', 1)[1].rsplit(b'\r\n--' + boundary, 1)[0]
return {'name': name}
if url.endswith('/releases/3') and method == 'PATCH':
self.assertEqual(data, {'draft': False, 'prerelease': False})
return {}
raise AssertionError('Unexpected request: ' + url)
def download(asset):
body = stored[asset['name']]
return body + b'corrupt' if corrupt_remote else body
environment = {'GITEA_REPOSITORY': 'owner/cutdex', 'GITEA_SHA': 'commit', 'RELEASE_TAG': 'v0.1.0'}
with patch.dict('os.environ', environment), patch.object(promote, 'request', side_effect=request), \
patch.object(promote, 'download', side_effect=download), \
patch.object(promote, 'app_versions', return_value=('0.1.0', '0.1.0-build.2')):
if extra or corrupt_remote or corrupt_artifact or wrong_commit:
with self.assertRaises(ValueError):
promote.main()
self.assertFalse(any(method == 'PATCH' for method, _ in calls))
if corrupt_artifact or wrong_commit:
self.assertFalse(any(method == 'POST' for method, _ in calls))
else:
promote.main()
self.assertEqual(calls[-1][0], 'PATCH')
self.assertEqual(set(stored), set(contents))
if resume:
self.assertFalse(any(method == 'POST' for method, _ in calls))
def test_complete_draft_is_verified_before_publication(self):
self.scenario()
def test_matching_draft_can_be_resumed_without_replacing_assets(self):
self.scenario(resume=True)
def test_stale_or_corrupt_remote_attachment_keeps_release_draft(self):
self.scenario(extra=True)
self.scenario(corrupt_remote=True)
def test_tampered_artifact_never_creates_release(self):
self.scenario(corrupt_artifact=True)
def test_successful_ci_for_other_commit_cannot_publish(self):
self.scenario(wrong_commit=True)
if __name__ == '__main__':
unittest.main()
+25 -1
View File
@@ -5,7 +5,7 @@ from pathlib import Path
import tempfile
import unittest
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, app_versions, checksum_lines, validate_artifact
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, METADATA, app_versions, checksum_lines, validate_artifact, validate_metadata
def fixture():
@@ -101,6 +101,30 @@ class ReleaseArtifactTests(unittest.TestCase):
with self.assertRaises(ValueError):
app_versions(spec)
def test_compact_metadata_validates_without_binary_packages(self):
contents = fixture()
metadata = {name: contents[name] for name in METADATA}
manifest = validate_metadata(metadata, '0.1.0', '0.1.0-build.2')
self.assertIn(INSTALLER, manifest['files'])
self.assertNotIn(INSTALLER, metadata)
def test_compact_metadata_rejects_missing_extra_or_tampered_files(self):
original = {name: body for name, body in fixture().items() if name in METADATA}
for name in METADATA:
with self.subTest(name=name):
metadata = dict(original)
del metadata[name]
with self.assertRaises(ValueError):
validate_metadata(metadata, '0.1.0', '0.1.0-build.2')
for name in ['SHA256SUMS', AUDIT, FEED]:
metadata = dict(original)
metadata[name] += b'corrupt'
with self.assertRaises(ValueError):
validate_metadata(metadata, '0.1.0', '0.1.0-build.2')
metadata = dict(original, unexpected=b'file')
with self.assertRaises(ValueError):
validate_metadata(metadata, '0.1.0', '0.1.0-build.2')
if __name__ == '__main__':
unittest.main()
+468
View File
@@ -0,0 +1,468 @@
import importlib.util
import hashlib
import io
from pathlib import Path
import tempfile
import threading
import unittest
from unittest.mock import patch
import urllib.error
import urllib.parse
import zipfile
from test_package_app import apk_bytes
from test_release_artifacts import fixture, reseal
from release_artifacts import METADATA
spec = importlib.util.spec_from_file_location('stage_release', Path(__file__).with_name('stage-release.py'))
stage = importlib.util.module_from_spec(spec)
spec.loader.exec_module(stage)
class StagedReleaseTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name)
self.sha = 'a' * 40
self.remote_sha = self.sha
self.release = None
self.stored = {}
self.ids = {}
self.calls = []
self.corrupt_remote = False
self.fingerprint_calls = []
self.contents = fixture()
self.contents['cutdex-0.1.0-android.apk'] = apk_bytes()
reseal(self.contents)
self.ci_runs = [{'id': 1, 'head_sha': self.sha, 'conclusion': 'success',
'path': '.gitea/workflows/ci.yml@refs/heads/main'}]
self.run_artifacts = {1: [{'id': 10, 'name': 'cutdex-release-packages'},
{'id': 11, 'name': 'cutdex-android-build'},
{'id': 12, 'name': 'cutdex-windows-build'},
{'id': 13, 'name': 'cutdex-release-metadata'}]}
self.artifact_contents = {10: self.contents,
11: {'app-production-release.apk': self.contents['cutdex-0.1.0-android.apk']},
12: {name: body for name, body in self.contents.items()
if name not in {'cutdex-0.1.0-android.apk', 'SHA256SUMS', 'release-manifest.json'}}}
self.artifact_contents[13] = {name: self.contents[name] for name in METADATA}
self.apk = self.root / 'app.apk'
self.apk.write_bytes(self.contents['cutdex-0.1.0-android.apk'])
self.windows = self.root / 'windows'
self.windows.mkdir()
self.dist = self.root / 'dist'
self.dist.mkdir()
for name, body in self.contents.items():
if name in METADATA:
(self.dist / name).write_bytes(body)
if name not in {'cutdex-0.1.0-android.apk', 'SHA256SUMS', 'release-manifest.json'}:
(self.windows / name).write_bytes(body)
self.environment = {'GITEA_REPOSITORY': 'owner/cutdex', 'GITEA_SHA': self.sha,
'RELEASE_TAG': 'v0.1.0', 'RELEASE_ID': '3',
'GITHUB_OUTPUT': str(self.root / 'outputs')}
for patcher in [patch.dict('os.environ', self.environment),
patch.object(stage, 'request', side_effect=self.request),
patch.object(stage, 'fingerprint', side_effect=self.fingerprint),
patch.object(stage, 'app_versions', return_value=('0.1.0', '0.1.0-build.2'))]:
patcher.start()
self.addCleanup(patcher.stop)
def assets(self):
return [{'name': name, 'id': self.ids[name]} for name in self.stored]
def request(self, url, data=None, method=None, content_type=None):
self.calls.append((method, url))
if url.endswith('/actions/runs?limit=100'):
return {'workflow_runs': self.ci_runs}
if '/actions/runs/' in url and url.endswith('/artifacts'):
return {'artifacts': self.run_artifacts[int(url.split('/actions/runs/')[1].split('/')[0])]}
if '/actions/artifacts/' in url and url.endswith('/zip'):
contents = self.artifact_contents[int(url.split('/actions/artifacts/')[1].split('/')[0])]
stream = io.BytesIO()
with zipfile.ZipFile(stream, 'w') as archive:
for name, body in contents.items():
archive.writestr(name, body)
return stream.getvalue()
if url.endswith('/tags/v0.1.0') and '/releases/' not in url:
return {'commit': {'sha': self.remote_sha}}
if url.endswith('/releases/tags/v0.1.0'):
if self.release is None:
raise urllib.error.HTTPError(url, 404, 'missing', {}, None)
return dict(self.release)
if url.endswith('/releases') and method == 'POST':
self.release = dict(data, id=3)
return dict(self.release)
if url.endswith('/releases/3'):
if method == 'PATCH':
self.assertEqual(data, {'draft': False, 'prerelease': False})
self.release.update(data)
return dict(self.release)
if url.endswith('/releases/3/assets'):
return self.assets()
if '/assets?name=' in url and method == 'POST':
name = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)['name'][0]
boundary = content_type.split('boundary=')[1].encode()
self.stored[name] = data.split(b'\r\n\r\n', 1)[1].rsplit(b'\r\n--' + boundary, 1)[0]
self.ids[name] = max(self.ids.values(), default=0) + 1
return {'name': name, 'id': self.ids[name]}
if '/assets/' in url and method == 'DELETE':
asset_id = int(url.rsplit('/', 1)[1])
name = next(name for name in self.stored if self.ids[name] == asset_id)
del self.stored[name]
return b''
raise AssertionError('Unexpected request: ' + url)
def download(self, asset):
return self.stored[asset['name']] + (b'corrupt' if self.corrupt_remote else b'')
def fingerprint(self, asset):
self.fingerprint_calls.append(asset['name'])
body = self.download(asset)
return {'sha256': hashlib.sha256(body).hexdigest(), 'sha1': hashlib.sha1(body).hexdigest(), 'size': len(body)}
def run_cli(self, command, path=None):
args = ['stage-release.py', command]
if path is not None:
args += ['--path', str(path)]
with patch('sys.argv', args), patch('sys.stdout', io.StringIO()):
stage.main()
def upload_platforms(self):
self.run_cli('prepare')
self.run_cli('android', self.apk)
self.run_cli('windows', self.windows)
def assert_draft(self):
self.assertTrue(self.release['draft'])
self.assertFalse(any(method == 'PATCH' for method, _ in self.calls))
def test_android_upload_does_not_wait_for_windows_or_publish(self):
self.run_cli('prepare')
self.run_cli('android', self.apk)
self.assertEqual(set(self.stored), {'cutdex-0.1.0-android.apk'})
self.assert_draft()
self.assertEqual((self.root / 'outputs').read_text(), 'release-id=3\n')
def test_windows_can_finish_first_and_only_complete_release_is_published(self):
self.run_cli('prepare')
self.run_cli('windows', self.windows)
self.assertNotIn('cutdex-0.1.0-android.apk', self.stored)
self.assert_draft()
self.run_cli('android', self.apk)
before = len(self.calls)
self.run_cli('publish', self.dist)
uploads = [url for method, url in self.calls[before:] if method == 'POST']
self.assertEqual(len(uploads), 2) # Only final checksums and manifest.
self.assertEqual(self.stored, self.contents)
self.assertFalse(self.release['draft'])
def test_missing_platform_cannot_publish(self):
self.run_cli('prepare')
self.run_cli('android', self.apk)
with self.assertRaisesRegex(ValueError, 'Not all platform'):
self.run_cli('publish', self.dist)
self.assert_draft()
def test_remote_corruption_or_extra_asset_keeps_release_draft(self):
self.upload_platforms()
self.corrupt_remote = True
with self.assertRaisesRegex(ValueError, 'verification failed'):
self.run_cli('publish', self.dist)
self.assert_draft()
self.corrupt_remote = False
self.stored['stale.zip'] = b'stale'
self.ids['stale.zip'] = 999
with self.assertRaises(ValueError):
self.run_cli('publish', self.dist)
self.assert_draft()
def test_invalid_local_windows_package_never_uploads(self):
self.run_cli('prepare')
next(self.windows.glob('*.nupkg')).write_bytes(b'corrupt')
with self.assertRaisesRegex(ValueError, 'index checksums'):
self.run_cli('windows', self.windows)
self.assertEqual(self.stored, {})
self.assert_draft()
def test_tag_movement_and_different_commit_draft_are_rejected(self):
self.run_cli('prepare')
self.remote_sha = 'b' * 40
with self.assertRaisesRegex(ValueError, 'no longer matches'):
self.run_cli('android', self.apk)
self.remote_sha = self.sha
self.release['body'] = stage.marker('b' * 40)
with self.assertRaisesRegex(ValueError, 'different commit'):
self.run_cli('prepare')
self.assertEqual(self.stored, {})
def test_published_release_cannot_be_modified(self):
self.upload_platforms()
self.run_cli('publish', self.dist)
before = len(self.calls)
for command, path in [('prepare', None), ('android', self.apk), ('publish', self.dist)]:
with self.assertRaisesRegex(ValueError, 'already published'):
self.run_cli(command, path)
self.assertFalse(any(method in {'POST', 'PATCH', 'DELETE'} for method, _ in self.calls[before:]))
def test_retry_reuses_files_without_replacing_existing_attachments(self):
self.upload_platforms()
before = len(self.calls)
self.run_cli('prepare')
self.run_cli('android', self.apk)
self.assertFalse(any(method in {'POST', 'DELETE'} for method, _ in self.calls[before:]))
self.apk.write_bytes(self.apk.read_bytes() + b'new-build')
self.run_cli('android', self.apk)
self.assertEqual(self.stored['cutdex-0.1.0-android.apk'], self.contents['cutdex-0.1.0-android.apk'])
for name, body in self.contents.items():
if name not in {'cutdex-0.1.0-android.apk', 'SHA256SUMS', 'release-manifest.json'}:
self.assertEqual(self.stored[name], body)
self.assert_draft()
def test_authentication_failure_does_not_create_a_draft(self):
with patch.object(stage, 'request', side_effect=urllib.error.HTTPError('url', 403, 'forbidden', {}, None)):
with self.assertRaises(urllib.error.HTTPError):
stage.prepare('base', self.sha, 'v0.1.0', '0.1.0', '0.1.0-build.2')
self.assertIsNone(self.release)
def test_tag_moved_during_final_verification_is_not_published(self):
self.upload_platforms()
tag_checks = 0
def move_tag(url, *args, **kwargs):
nonlocal tag_checks
if url.endswith('/tags/v0.1.0') and '/releases/' not in url:
tag_checks += 1
if tag_checks == 2:
self.remote_sha = 'b' * 40
return self.request(url, *args, **kwargs)
with patch.object(stage, 'request', side_effect=move_tag):
with self.assertRaisesRegex(ValueError, 'no longer matches'):
self.run_cli('publish', self.dist)
self.assert_draft()
def test_invalid_final_manifest_never_uploads_metadata_or_publishes(self):
self.upload_platforms()
(self.dist / 'SHA256SUMS').write_bytes(b'corrupt')
before = len(self.calls)
with self.assertRaisesRegex(ValueError, 'SHA256SUMS'):
self.run_cli('publish', self.dist)
self.assertFalse(any(method in {'POST', 'DELETE', 'PATCH'} for method, _ in self.calls[before:]))
self.assert_draft()
def test_prepare_ci_selects_exact_successful_main_and_platform_artifacts(self):
self.ci_runs += [{'id': 2, 'head_sha': 'b' * 40, 'conclusion': 'success',
'path': '.gitea/workflows/ci.yml@refs/heads/main'},
{'id': 3, 'head_sha': self.sha, 'conclusion': 'success',
'path': '.gitea/workflows/ci.yml@refs/pull/4/head'}]
self.run_cli('prepare-ci')
output = (self.root / 'outputs').read_text()
for value in ['ci-run-id=1', 'artifact-id=13', 'android-artifact-id=11', 'windows-artifact-id=12']:
self.assertIn(value, output)
self.assertIn(stage.ci_marker(1), self.release['body'])
self.assert_draft()
def test_ci_failure_or_expired_metadata_never_creates_draft(self):
self.ci_runs[0]['conclusion'] = 'failure'
with self.assertRaisesRegex(ValueError, 'No successful main CI'):
self.run_cli('prepare-ci')
self.assertIsNone(self.release)
self.ci_runs[0]['conclusion'] = 'success'
self.run_artifacts[1][3]['expired'] = True
with self.assertRaisesRegex(ValueError, 'unexpired CI artifact'):
self.run_cli('prepare-ci')
self.assertIsNone(self.release)
def test_ci_retry_stays_on_original_run_after_new_same_commit_ci(self):
self.run_cli('prepare-ci')
self.ci_runs.append(dict(self.ci_runs[0], id=2))
self.run_artifacts[2] = [{'id': 20, 'name': 'cutdex-release-packages'}]
self.run_cli('prepare-ci')
self.assertNotIn('ci-run-id=2', (self.root / 'outputs').read_text())
with patch.dict('os.environ', {'CI_RUN_ID': '2'}):
with self.assertRaisesRegex(ValueError, 'different CI run'):
self.run_cli('android', self.apk)
self.assertEqual(self.stored, {})
def test_missing_or_expired_platform_artifacts_fail_before_creating_draft(self):
for platform in ('android', 'windows'):
artifact = next(item for item in self.run_artifacts[1] if item['name'] == f'cutdex-{platform}-build')
artifact['expired'] = True
with self.assertRaisesRegex(ValueError, f'cutdex-{platform}-build'):
self.run_cli('prepare-ci')
self.assertIsNone(self.release)
artifact['expired'] = False
self.run_artifacts[1].remove(artifact)
with self.assertRaisesRegex(ValueError, f'cutdex-{platform}-build'):
self.run_cli('prepare-ci')
self.assertIsNone(self.release)
self.run_artifacts[1].append(artifact)
def test_complete_archive_cannot_replace_new_artifact_types(self):
self.run_cli('prepare-ci')
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '10'}):
for command in ('fetch-android', 'fetch-windows', 'fetch-release'):
with self.assertRaisesRegex(ValueError, 'Unexpected CI artifact type'):
self.run_cli(command, self.root / 'legacy-archive')
self.assertFalse(any('/actions/artifacts/10/zip' in url for _, url in self.calls))
self.assertFalse((self.root / 'legacy-archive').exists())
def test_publish_rejects_complete_archive_input(self):
self.upload_platforms()
complete = self.root / 'complete'
complete.mkdir()
for name, body in self.contents.items():
(complete / name).write_bytes(body)
before = len(self.calls)
with self.assertRaisesRegex(ValueError, 'Release metadata requires'):
self.run_cli('publish', complete)
self.assertFalse(any(method in {'POST', 'DELETE', 'PATCH'} for method, _ in self.calls[before:]))
self.assert_draft()
def test_missing_metadata_cannot_fall_back_to_complete_archive(self):
self.run_artifacts[1] = [item for item in self.run_artifacts[1]
if item['name'] != 'cutdex-release-metadata']
with self.assertRaisesRegex(ValueError, 'cutdex-release-metadata'):
self.run_cli('prepare-ci')
self.assertIsNone(self.release)
def test_preferred_platform_artifacts_are_downloaded_and_validated(self):
self.run_cli('prepare-ci')
for platform, artifact_id in [('android', '11'), ('windows', '12')]:
destination = self.root / f'fetched-{platform}'
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': artifact_id}):
self.run_cli(f'fetch-{platform}', destination)
self.run_cli(platform, destination)
self.assert_draft()
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '13'}):
self.run_cli('publish', self.dist)
self.assertFalse(self.release['draft'])
def test_artifact_from_wrong_run_expired_or_tampered_is_rejected(self):
self.run_cli('prepare-ci')
destination = self.root / 'rejected'
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '99'}):
with self.assertRaisesRegex(ValueError, 'does not belong'):
self.run_cli('fetch-release', destination)
self.run_artifacts[1][3]['expired'] = True
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '13'}):
with self.assertRaisesRegex(ValueError, 'has expired'):
self.run_cli('fetch-release', destination)
self.run_artifacts[1][3]['expired'] = False
self.artifact_contents[13][stage.AUDIT] = b'tampered'
with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
self.run_cli('fetch-release', destination)
self.assertFalse(destination.exists())
self.assert_draft()
def test_unsafe_archive_paths_are_rejected_before_extraction(self):
self.run_cli('prepare-ci')
self.artifact_contents[11]['../outside.apk'] = b'bad'
destination = self.root / 'rejected'
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '11'}):
with self.assertRaisesRegex(ValueError, 'unique flat filenames'):
self.run_cli('fetch-android', destination)
self.assertFalse(destination.exists())
def test_platform_bytes_must_match_complete_ci_artifact_before_publication(self):
self.run_cli('prepare-ci')
self.artifact_contents[11]['app-production-release.apk'] += b'different-build'
with patch.dict('os.environ', {'CI_RUN_ID': '1'}):
for platform, artifact_id in [('android', '11'), ('windows', '12')]:
destination = self.root / f'fetched-{platform}'
with patch.dict('os.environ', {'CI_ARTIFACT_ID': artifact_id}):
self.run_cli(f'fetch-{platform}', destination)
self.run_cli(platform, destination)
with self.assertRaisesRegex(ValueError, 'verification failed'):
self.run_cli('publish', self.dist)
self.assert_draft()
def add_compact_metadata(self):
self.artifact_contents[13] = {name: self.contents[name] for name in METADATA}
def test_compact_metadata_avoids_complete_download_and_verifies_each_file_once(self):
self.add_compact_metadata()
self.run_cli('prepare-ci')
self.assertIn('artifact-id=13', (self.root / 'outputs').read_text())
with patch.dict('os.environ', {'CI_RUN_ID': '1'}):
for platform, artifact_id in [('windows', '12'), ('android', '11')]:
path = self.root / f'compact-{platform}'
with patch.dict('os.environ', {'CI_ARTIFACT_ID': artifact_id}):
self.run_cli(f'fetch-{platform}', path)
self.run_cli(platform, path)
self.assertEqual(self.fingerprint_calls, [])
path = self.root / 'compact-metadata'
with patch.dict('os.environ', {'CI_ARTIFACT_ID': '13'}):
self.run_cli('fetch-release', path)
self.assertEqual({p.name for p in path.iterdir()}, METADATA)
self.run_cli('publish', path)
self.assertFalse(self.release['draft'])
self.assertEqual(sorted(self.fingerprint_calls), sorted(self.contents))
self.assertFalse(any('/actions/artifacts/10/zip' in url for _, url in self.calls))
def test_invalid_compact_metadata_is_rejected_without_binary_download(self):
self.add_compact_metadata()
self.artifact_contents[13]['SHA256SUMS'] = b'bad'
self.run_cli('prepare-ci')
path = self.root / 'invalid-metadata'
with patch.dict('os.environ', {'CI_RUN_ID': '1', 'CI_ARTIFACT_ID': '13'}):
with self.assertRaisesRegex(ValueError, 'SHA256SUMS'):
self.run_cli('fetch-release', path)
self.assertFalse(path.exists())
self.assert_draft()
def test_remote_corruption_is_detected_with_metadata_only(self):
self.upload_platforms()
path = self.root / 'compact-metadata'
path.mkdir()
for name in METADATA:
(path / name).write_bytes(self.contents[name])
self.corrupt_remote = True
with self.assertRaisesRegex(ValueError, 'verification failed'):
self.run_cli('publish', path)
self.assert_draft()
def test_attachment_replacement_during_verification_blocks_publication(self):
self.upload_platforms()
count = 0
def changed_fingerprint(asset):
nonlocal count
result = self.fingerprint(asset)
count += 1
if count == len(self.contents):
self.ids[asset['name']] += 100
return result
with patch.object(stage, 'fingerprint', side_effect=changed_fingerprint):
with self.assertRaisesRegex(ValueError, 'changed during verification'):
self.run_cli('publish', self.dist)
self.assert_draft()
def test_remote_verification_runs_with_two_workers(self):
self.upload_platforms()
barrier = threading.Barrier(2)
lock = threading.Lock()
active, maximum = 0, 0
def parallel_fingerprint(asset):
nonlocal active, maximum
with lock:
active += 1
maximum = max(maximum, active)
try:
barrier.wait(timeout=5)
return self.fingerprint(asset)
finally:
with lock:
active -= 1
# There are eight attachments, so each pair reaches the barrier.
with patch.object(stage, 'fingerprint', side_effect=parallel_fingerprint):
self.run_cli('publish', self.dist)
self.assertEqual(maximum, 2)
self.assertFalse(self.release['draft'])
if __name__ == '__main__':
unittest.main()
+183
View File
@@ -0,0 +1,183 @@
import hashlib
import io
import threading
import unittest
import urllib.error
from unittest.mock import patch
import release_transport as transfers
class TransferToolsTests(unittest.TestCase):
def test_transient_upload_failure_retries_without_restarting_other_files(self):
calls = []
def transport(url, data=None, method=None, content_type=None):
if method is None:
return []
calls.append(url)
if url.endswith('name=retry.zip') and calls.count(url) == 1:
raise urllib.error.URLError('connection reset')
return {}
with patch.object(transfers.time, 'sleep') as sleep:
transfers.upload_contents('base', 3, {'retry.zip': b'a', 'ok.zip': b'b'}, transport=transport)
self.assertEqual(sum(url.endswith('name=retry.zip') for url in calls), 2)
self.assertEqual(sum(url.endswith('name=ok.zip') for url in calls), 1)
sleep.assert_called_once_with(5)
def test_response_lost_after_upload_does_not_duplicate_attachment(self):
for committed_on in (1, 3):
with self.subTest(committed_on=committed_on):
calls = 0
assets = []
def transport(url, data=None, method=None, content_type=None):
nonlocal calls
if method is None:
return assets
calls += 1
if calls == committed_on:
assets.append({'name': 'app.zip'})
raise TimeoutError('response lost')
with patch.object(transfers.time, 'sleep'):
transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport)
self.assertEqual(calls, committed_on)
self.assertEqual(len(assets), 1)
def test_upload_retries_are_bounded_and_last_error_is_propagated(self):
calls = 0
def transport(url, data=None, method=None, content_type=None):
nonlocal calls
if method is None:
return []
calls += 1
raise urllib.error.HTTPError(url, 503, 'Unavailable', {}, None)
with patch.object(transfers.time, 'sleep') as sleep:
with self.assertRaises(urllib.error.HTTPError):
transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport)
self.assertEqual(calls, 3)
self.assertEqual([call.args[0] for call in sleep.call_args_list], [5, 15])
def test_permanent_upload_errors_fail_without_retries(self):
for status in (400, 401, 403, 404, 409, 422):
with self.subTest(status=status):
calls = 0
def transport(url, data=None, method=None, content_type=None):
nonlocal calls
if method is None:
return []
calls += 1
raise urllib.error.HTTPError(url, status, 'Permanent failure', {}, None)
with patch.object(transfers.time, 'sleep') as sleep:
with self.assertRaises(urllib.error.HTTPError):
transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport)
self.assertEqual(calls, 1)
sleep.assert_not_called()
def test_retry_reconciliation_rejects_duplicate_attachments(self):
reads, uploads = 0, 0
def transport(url, data=None, method=None, content_type=None):
nonlocal reads, uploads
if method is None:
reads += 1
return [] if reads == 1 else [{'name': 'app.zip'}, {'name': 'app.zip'}]
uploads += 1
raise TimeoutError('response lost')
with patch.object(transfers.time, 'sleep'):
with self.assertRaisesRegex(ValueError, 'Duplicate Release attachments'):
transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport)
self.assertEqual(uploads, 1)
def test_attachment_list_retries_rate_limiting_before_upload(self):
reads, uploads = 0, 0
def transport(url, data=None, method=None, content_type=None):
nonlocal reads, uploads
if method is None:
reads += 1
if reads == 1:
raise urllib.error.HTTPError(url, 429, 'Rate limited', {}, None)
return []
uploads += 1
return {}
with patch.object(transfers.time, 'sleep') as sleep:
transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport)
self.assertEqual((reads, uploads), (2, 1))
sleep.assert_called_once_with(5)
def test_uploads_run_with_at_most_two_workers(self):
barrier = threading.Barrier(2)
lock = threading.Lock()
active, maximum = 0, 0
uploads = []
def transport(url, data=None, method=None, content_type=None):
nonlocal active, maximum
if method is None:
return []
self.assertEqual(method, 'POST')
with lock:
active += 1
maximum = max(maximum, active)
try:
barrier.wait(timeout=5)
with lock:
uploads.append(url)
return {}
finally:
with lock:
active -= 1
transfers.upload_contents('base', 3, {f'file-{i}.zip': b'file' for i in range(4)}, transport=transport)
self.assertEqual(maximum, 2)
self.assertEqual(len(uploads), 4)
def test_worker_failure_is_propagated(self):
def transport(url, data=None, method=None, content_type=None):
if method is None:
return []
raise OSError('upload failed')
with self.assertRaisesRegex(OSError, 'upload failed'):
transfers.upload_contents('base', 3, {'first.zip': b'a', 'second.zip': b'b'}, transport=transport)
def test_invalid_filename_is_rejected_before_any_upload(self):
with patch.object(transfers, 'request', return_value=[]) as request:
with self.assertRaisesRegex(ValueError, 'Unexpected artifact path'):
transfers.upload_contents('base', 3, {'valid.zip': b'a', '../invalid.zip': b'b'})
self.assertEqual(request.call_count, 1)
def test_streaming_fingerprint_never_reads_entire_response_at_once(self):
body = b'a' * (1024 * 1024 + 123)
class Response(io.BytesIO):
def read(self, size=-1):
if size != 1024 * 1024:
raise AssertionError('Expected bounded chunk reads')
return super().read(size)
with patch.dict('os.environ', {'GITEA_TOKEN': 'test-token'}), \
patch.object(transfers.urllib.request, 'urlopen', return_value=Response(body)) as open_url:
result = transfers.fingerprint({'browser_download_url': 'http://git.orangraph.com/attachments/example'})
self.assertEqual(result, {'sha256': hashlib.sha256(body).hexdigest(),
'sha1': hashlib.sha1(body).hexdigest(), 'size': len(body)})
self.assertEqual(open_url.call_args.args[0].full_url, 'https://git.orangraph.com/attachments/example')
def test_streaming_verification_rejects_unexpected_host(self):
with patch.object(transfers.urllib.request, 'urlopen') as open_url:
with self.assertRaisesRegex(ValueError, 'Unexpected attachment host'):
transfers.fingerprint({'browser_download_url': 'https://example.com/file'})
open_url.assert_not_called()
if __name__ == '__main__':
unittest.main()