From 1ef8edc8bcca9cfaf18a8d52ce55e85255cfe5cf Mon Sep 17 00:00:00 2001 From: lingjhf Date: Tue, 6 Oct 2026 12:56:31 +0800 Subject: [PATCH 01/10] refactor(windows): publish Velopack updates through Gitea Releases --- .gitea/workflows/ci.yml | 16 ++- docs/windows-updates.md | 69 ++++++++++++ pubspec.lock | 4 +- pubspec.yaml | 4 +- tool/README.md | 2 +- tool/check.py | 1 + tool/gitea/package-app.py | 62 ++++++---- tool/gitea/promote-release.py | 59 +++++----- tool/gitea/release_artifacts.py | 59 ++++++++++ tool/gitea/test_promote_release.py | 98 ++++++++++++++++ tool/gitea/test_release_artifacts.py | 106 ++++++++++++++++++ tool/tests/cli_test.py | 1 + .../windows/test_update_configuration_unit.py | 46 ++++++++ tool/windows/test_windows_updates.py | 12 +- tool/windows/update_versions.py | 18 +++ tool/windows/windows_updates.py | 39 ++----- windows/runner/update_configuration.cmake | 10 +- 17 files changed, 519 insertions(+), 87 deletions(-) create mode 100644 docs/windows-updates.md create mode 100644 tool/gitea/release_artifacts.py create mode 100644 tool/gitea/test_promote_release.py create mode 100644 tool/gitea/test_release_artifacts.py create mode 100644 tool/windows/test_update_configuration_unit.py create mode 100644 tool/windows/update_versions.py diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index d1cb3eb..e219a63 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -38,6 +38,12 @@ jobs: - run: flutter pub get --enforce-lockfile - run: dart analyze --fatal-infos - run: flutter test --reporter expanded test packages/cutdex_ui/test packages/cutdex_native/test + - name: Validate update and release tooling + run: | + python -m unittest discover -s tool/gitea -p 'test_*.py' + if ($LASTEXITCODE -ne 0) { throw 'Release tooling tests failed.' } + python -m unittest discover -s tool/windows -p '*_unit.py' + if ($LASTEXITCODE -ne 0) { throw 'Update tooling tests failed.' } - name: Bound Android build memory on the shared runner run: | $file = 'android/gradle.properties' @@ -55,9 +61,17 @@ jobs: if ($LASTEXITCODE -ne 0) { throw 'Packaging environment setup failed.' } & ./.build/package-tools/Scripts/python.exe -m pip install pefile==2024.8.26 if ($LASTEXITCODE -ne 0) { throw 'Packaging dependency installation failed.' } + - uses: https://github.com/actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 + with: + dotnet-version: '10.0.x' + - name: Install pinned Velopack release tool + run: | + dotnet tool install vpk --version 1.2.161 --tool-path .build/vpk + if ($LASTEXITCODE -ne 0) { throw 'Velopack tool installation failed.' } - name: Package application run: | - & ./.build/package-tools/Scripts/python.exe tool/gitea/package-app.py + & ./.build/package-tools/Scripts/python.exe tool/gitea/package-app.py --vpk .build/vpk/vpk.exe + if ($LASTEXITCODE -ne 0) { throw 'Application packaging failed.' } - name: Upload Android and Windows packages uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: diff --git a/docs/windows-updates.md b/docs/windows-updates.md new file mode 100644 index 0000000..841a7dd --- /dev/null +++ b/docs/windows-updates.md @@ -0,0 +1,69 @@ +# Windows 更新与 Gitea 发布 + +Cutdex 使用 deskup 0.2.0 的 Gitea 更新源,下载、校验、安装和重启由 +Velopack 1.2.161 完成。正式版构建固定使用公开仓库 +`https://git.orangraph.com/lingjhf/cutdex`,包身份为 `Cutdex`,更新频道为 +`win-x64`。正式版不读取开发更新源环境变量,也不包含 Gitea 访问令牌。 + +## 发布附件 + +每个正式 Gitea Release 同时包含: + +| 附件 | 用途 | +| --- | --- | +| `Cutdex-win-x64-Setup.exe` | 新用户安装 | +| `Cutdex-win-x64-Portable.zip` | Velopack 便携发行包,可自动更新 | +| `Cutdex-<更新版本>-win-x64-full.nupkg` | 完整更新包 | +| `releases.win-x64.json` | Windows x64 更新索引 | +| `cutdex-<显示版本>-android.apk` | Android ARM64/x86_64 应用 | +| `windows-dependency-audit.json` | Windows 原生依赖审计 | +| `SHA256SUMS` / `release-manifest.json` | 附件哈希与版本、频道、包身份声明 | + +CI 构建正常应用后,在临时目录组装 Windows 发行内容,排除构建符号、 +不用的 JNI DLL 和独立分发的 processing worker。审计及暂存文件校验后, +使用固定版本的 `vpk` 生成安装、便携和更新产物。每次使用新的打包输出目录, +索引只引用本次 Release 的一个完整包;不生成增量包。 + +`tool/gitea/package-app.py --vpk ` 要求 `dist` 为空。 +打包机需要 .NET(仅运行 vpk)与 `pefile`;用户电脑不需要 .NET 或 Python。 +CI 安装 .NET 10 和 vpk 1.2.161。 + +发布工作流只提升**同一提交**成功的 main CI 产物。上传前校验完整附件集合、 +版本、包身份、频道及索引指向的包哈希;上传至草稿 Release,重新读取所有 +附件逐字节核对,并拒绝多余或过期附件,之后才发布。发布失败保留草稿, +同内容可重试;已发布版本不可覆盖。 + +## 版本与迁移 + +例如 `pubspec.yaml` 的 `0.1.1+2` 对应显示版本/标签 `0.1.1`/`v0.1.1`, +Velopack 更新版本为 `0.1.1-build.2`。数字构建号参与更新版本排序, +避免 SemVer `+2` 不参与排序的问题。Windows 可执行文件版本必须与 pubspec +一致;每次正式发布提升应用版本与构建号,勿复用已发布标签。 + +旧的普通 `cutdex-<版本>-windows-x64.zip` 不含 Velopack 安装元数据,不能 +直接获得自动更新。旧用户需要先使用新的 Setup.exe 安装,或解压新的 +Velopack Portable ZIP;之后由应用内更新完成升级。 + +Gitea SDK 查询最近 10 个 Release,跳过标为预发布的 Release,并读取对应 +频道索引。需要保持最新正式 Windows Release 在这个查询窗口中。 +索引遗漏或损坏可能被 SDK 跳过并表现为没有更新,因此发布流程必须保证 +附件完整。仓库及附件必须可匿名下载,Gitea 服务的 API 应位于 `/api/v1`。 + +## 开发与验证 + +development 包身份为 `Cutdex.Dev`,默认不配置更新源,避免连接正式频道。 +设置 `CUTDEX_WINDOWS_UPDATE_URL` 可显式启用独立开发 Gitea 仓库。 +本地 HTTP 目录测试还需设置 `CUTDEX_WINDOWS_UPDATE_SOURCE=web` 和 +`CUTDEX_UPDATE_TEST_HTTP=1`,HTTP 仅允许带端口的 localhost/127.0.0.1。 +生产构建忽略这些开发配置。 + +```powershell +python -m unittest discover -s tool/gitea -p 'test_*.py' +python -m unittest discover -s tool/windows -p '*_unit.py' +python tool/windows/test_windows_updates.py --vpk --offline +``` + +本地更新测试会构建两版独立测试应用,验证损坏包拒绝、重新下载、安装和 +重启;不修改运行中的开发应用,也不上传真实 Release。正式发布前还应在 +独立 Windows 环境验证应用持久化与安装/便携两种分发方式。Android 签名与 +processing worker 独立分发策略沿用现有流水线。 diff --git a/pubspec.lock b/pubspec.lock index c0f4d1c..251c87f 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -303,10 +303,10 @@ packages: dependency: "direct main" description: name: deskup - sha256: "5a7fb021ba3207e5a85d440d378832156896d2eea616838ad21547aa0af68df1" + sha256: "722cd3c4aa51ebe886cd0fe0a842b7312a4235a4b2e097015aab51c10c010c4e" url: "https://pub.dev" source: hosted - version: "0.1.0" + version: "0.2.0" drift: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 89af0a2..b533dca 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -5,7 +5,7 @@ publish_to: none version: 0.1.0+1 environment: - sdk: ^3.13.2 + sdk: ^3.13.4 workspace: - packages/* @@ -13,7 +13,7 @@ workspace: dependencies: cutdex_ui: ^0.1.0 cutdex_native: ^0.1.0 - deskup: ^0.1.0 + deskup: ^0.2.0 flutter: sdk: flutter diff --git a/tool/README.md b/tool/README.md index 5293ea2..78560b7 100644 --- a/tool/README.md +++ b/tool/README.md @@ -64,7 +64,7 @@ python tool/windows/package_windows_release.py ` ## 应用更新产物 -Cutdex 的更新构建配置为 macOS 的 `CUTDEX_UPDATE_FEED_URL` / `CUTDEX_UPDATE_PUBLIC_KEY`,Windows 的 `CUTDEX_WINDOWS_UPDATE_URL`;在构建前设置正式 HTTPS 更新源。 +Cutdex 的 macOS 更新构建配置为 `CUTDEX_UPDATE_FEED_URL` / `CUTDEX_UPDATE_PUBLIC_KEY`;在构建前设置正式 HTTPS 更新源。Windows production 使用固定的公开 Gitea 仓库与 deskup 0.2.0;开发更新源、Release 附件与迁移说明见 [Windows 更新与发布](../docs/windows-updates.md)。 生成更新产物的应用入口: diff --git a/tool/check.py b/tool/check.py index 2278e10..5a1e5b3 100644 --- a/tool/check.py +++ b/tool/check.py @@ -38,6 +38,7 @@ def main(): ('tool/tests', '*_test.py'), ('tool/windows', 'test_check_windows_release.py'), ('tool/windows', '*_unit.py'), + ('tool/gitea', 'test_*.py'), ]: run([python, '-m', 'unittest', 'discover', '-s', directory, '-p', pattern]) flutter = os.environ.get('FLUTTER') or shutil.which('flutter') diff --git a/tool/gitea/package-app.py b/tool/gitea/package-app.py index 23cc6e9..5128f94 100644 --- a/tool/gitea/package-app.py +++ b/tool/gitea/package-app.py @@ -1,19 +1,27 @@ -"""Package the Windows Release directory and Android production APK.""" +"""Package Android and audited Velopack Windows installation/update artifacts.""" +import argparse import hashlib import json from pathlib import Path -import re import shutil import sys +import tempfile import zipfile +from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, app_versions, checksum_lines, validate_artifact + ROOT = Path(__file__).resolve().parents[2] def main(): - version = re.search(r'^version: (\S+)', (ROOT / 'pubspec.yaml').read_text(), re.M)[1].split('+')[0] + 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' - output.mkdir(exist_ok=True) + # 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(): @@ -25,23 +33,39 @@ 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') - shutil.copyfile(apk, output / f'cutdex-{version}-android.apk') sys.path.insert(0, str(ROOT / 'tool/windows')) from check_windows_release import audit - unused_jni = windows / 'dartjni.dll' - if unused_jni.exists(): - unused_jni.unlink() - report = audit(windows, require_processing=False) - (output / 'windows-dependency-audit.json').write_text(json.dumps(report, indent=2) + '\n') - package = output / f'cutdex-{version}-windows-x64.zip' - with zipfile.ZipFile(package, 'w', compression=zipfile.ZIP_DEFLATED) as archive: - for path in sorted(windows.rglob('*')): - if path.is_file() and path.suffix.lower() not in ('.pdb', '.lib', '.exp'): - archive.write(path, f'cutdex-{version}/' + path.relative_to(windows).as_posix()) - files = sorted(output.glob('*.apk')) + sorted(output.glob('*.zip')) - manifest = {path.name: hashlib.file_digest(path.open('rb'), 'sha256').hexdigest() for path in files} - (output / 'SHA256SUMS').write_text(''.join(f'{digest} {name}\n' for name, digest in manifest.items())) - (output / 'release-manifest.json').write_text(json.dumps({'version': version, 'files': manifest, 'androidSigning': 'debug', 'processingWorkersBundled': False}, indent=2) + '\n') + from windows_updates import package_app + with tempfile.TemporaryDirectory(prefix='cutdex-release-') as directory: + temporary = Path(directory) + staged, releases = temporary / 'app', temporary / 'releases' + shutil.copytree(windows, staged, + ignore=shutil.ignore_patterns('processing', '*.pdb', '*.lib', '*.exp', 'dartjni.dll')) + report = audit(staged, require_processing=False) + checksums = {} + for path in sorted(staged.rglob('*')): + if path.is_file(): + 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) + 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()} + 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)) diff --git a/tool/gitea/promote-release.py b/tool/gitea/promote-release.py index 9abb486..778f1bb 100644 --- a/tool/gitea/promote-release.py +++ b/tool/gitea/promote-release.py @@ -1,24 +1,20 @@ """Promote packages from a successful main CI for the exact release commit.""" -import hashlib import io import json import os from pathlib import Path -import re -import urllib.error import urllib.parse import urllib.request import uuid import zipfile +from release_artifacts import app_versions, validate_artifact + SERVER = 'https://git.orangraph.com' -REPO = os.environ['GITEA_REPOSITORY'] -TOKEN = os.environ['GITEA_TOKEN'] -BASE = f'{SERVER}/api/v1/repos/{REPO}' def request(url, data=None, method=None, content_type='application/json'): - headers = {'Authorization': f'token {TOKEN}'} + headers = {'Authorization': 'token ' + os.environ['GITEA_TOKEN']} if data is not None: headers['Content-Type'] = content_type if isinstance(data, dict): @@ -37,57 +33,56 @@ def download(asset): 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 = re.search(r'^version: (\S+)', Path('pubspec.yaml').read_text(), re.M)[1].split('+')[0] + 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'] + 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'] + 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") + data = request(f"{base}/actions/artifacts/{found[0]['id']}/zip") with zipfile.ZipFile(io.BytesIO(data)) as archive: - contents = {item.filename: archive.read(item) for item in archive.infolist() if not item.is_dir()} - manifest = json.loads(contents['release-manifest.json']) - if manifest['version'] != version: - raise ValueError('Artifact version does not match release') - expected = {f'cutdex-{version}-android.apk', f'cutdex-{version}-windows-x64.zip'} - if set(manifest['files']) != expected: - raise ValueError('Release requires both Android and Windows packages') - for name, digest in manifest['files'].items(): - if hashlib.sha256(contents[name]).hexdigest() != digest: - raise ValueError(f'Package checksum mismatch: {name}') - releases = request(f'{BASE}/releases?limit=100') + 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, 'body': f'Windows x64 portable ZIP and Android ARM64/x86_64 APK. 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") + 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: - downloaded = download(prior[0]) - if downloaded != body: - raise ValueError(f'Refusing to replace Release asset: {name}') 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()) - asset = request(f"{BASE}/releases/{release['id']}/assets?name={urllib.parse.quote(name)}", payload, 'POST', f'multipart/form-data; boundary={boundary}') - if download(asset) != body: - raise ValueError(f'Remote checksum verification failed: {name}') - request(f"{BASE}/releases/{release['id']}", {'draft': False}, 'PATCH') - print(f'{SERVER}/{REPO}/releases/tag/{tag}') + 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__': diff --git a/tool/gitea/release_artifacts.py b/tool/gitea/release_artifacts.py new file mode 100644 index 0000000..3b458c6 --- /dev/null +++ b/tool/gitea/release_artifacts.py @@ -0,0 +1,59 @@ +"""Validate the complete app artifact before creating or publishing a Release.""" +import hashlib +import json +from pathlib import Path +import re +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'windows')) +from update_versions import update_version + +FEED = 'releases.win-x64.json' +INSTALLER = 'Cutdex-win-x64-Setup.exe' +PORTABLE = 'Cutdex-win-x64-Portable.zip' +AUDIT = 'windows-dependency-audit.json' + + +def app_versions(pubspec): + match = re.search(r'^version:\s*(\d+\.\d+\.\d+)\+(\d+)\s*$', + Path(pubspec).read_text(encoding='utf-8'), re.M) + if not match: + raise ValueError('Application version must include a numeric build number') + return match[1], update_version(match[1], match[2]) + + +def checksum_lines(files): + return ''.join(f'{files[name]} {name}\n' for name in sorted(files)) + + +def validate_artifact(contents, version, windows_version): + manifest = json.loads(contents['release-manifest.json']) + if (manifest['version'] != version or manifest.get('windowsUpdateVersion') != windows_version + or manifest.get('windowsPackageId') != 'Cutdex' + or manifest.get('windowsChannel') != 'win-x64'): + raise ValueError('Artifact version, identity or channel does not match release') + feed = json.loads(contents[FEED]) + assets = feed.get('Assets', []) + if len(assets) != 1: + raise ValueError('Release index must contain exactly one complete full package') + asset = assets[0] + if (asset.get('PackageId') != 'Cutdex' or asset.get('Version') != windows_version + or asset.get('Type') != 'Full'): + raise ValueError('Update package identity, version or type does not match release') + package = asset.get('FileName', '') + 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'}: + 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}') + 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 diff --git a/tool/gitea/test_promote_release.py b/tool/gitea/test_promote_release.py new file mode 100644 index 0000000..36c55cd --- /dev/null +++ b/tool/gitea/test_promote_release.py @@ -0,0 +1,98 @@ +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() diff --git a/tool/gitea/test_release_artifacts.py b/tool/gitea/test_release_artifacts.py new file mode 100644 index 0000000..56e14c8 --- /dev/null +++ b/tool/gitea/test_release_artifacts.py @@ -0,0 +1,106 @@ +import copy +import hashlib +import json +from pathlib import Path +import tempfile +import unittest + +from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, app_versions, checksum_lines, validate_artifact + + +def fixture(): + package = 'Cutdex-0.1.0-build.2-win-x64-full.nupkg' + payload = b'full package' + feed = {'Assets': [{'PackageId': 'Cutdex', 'Version': '0.1.0-build.2', 'Type': 'Full', + 'FileName': package, 'Size': len(payload), + 'SHA1': hashlib.sha1(payload).hexdigest(), + 'SHA256': hashlib.sha256(payload).hexdigest()}]} + contents = {'cutdex-0.1.0-android.apk': b'apk', INSTALLER: b'exe', PORTABLE: b'zip', + FEED: json.dumps(feed).encode(), AUDIT: b'{}', package: payload} + manifest = {'version': '0.1.0', 'windowsUpdateVersion': '0.1.0-build.2', + 'windowsPackageId': 'Cutdex', 'windowsChannel': 'win-x64', 'files': {}} + return reseal(contents, manifest) + + +def reseal(contents, manifest=None): + if manifest is None: + manifest = json.loads(contents['release-manifest.json']) + manifest['files'] = {name: hashlib.sha256(body).hexdigest() for name, body in contents.items() + if name not in ['SHA256SUMS', 'release-manifest.json']} + contents['SHA256SUMS'] = checksum_lines(manifest['files']).encode() + contents['release-manifest.json'] = json.dumps(manifest).encode() + return contents + + +class ReleaseArtifactTests(unittest.TestCase): + def validate(self, contents): + return validate_artifact(contents, '0.1.0', '0.1.0-build.2') + + def test_complete_installer_portable_and_update_release(self): + self.assertEqual(self.validate(fixture())['windowsPackageId'], 'Cutdex') + + def test_missing_or_unexpected_attachments(self): + original = fixture() + for name in [INSTALLER, PORTABLE, 'Cutdex-0.1.0-build.2-win-x64-full.nupkg']: + contents = copy.deepcopy(original) + del contents[name] + with self.assertRaises(ValueError): + self.validate(contents) + contents = fixture() + contents['stale.zip'] = b'old' + with self.assertRaises(ValueError): + self.validate(reseal(contents)) + + def test_tampered_package_or_checksum_file(self): + for name in [INSTALLER, PORTABLE, 'SHA256SUMS']: + contents = fixture() + contents[name] += b'tampered' + with self.assertRaises(ValueError): + self.validate(contents) + + def test_wrong_identity_version_delta_or_escaping_filename(self): + for key, value in [('PackageId', 'Cutdex.Dev'), ('Version', '0.1.0-build.1'), + ('Type', 'Delta'), ('FileName', '../outside.nupkg')]: + contents = fixture() + feed = json.loads(contents[FEED]) + feed['Assets'][0][key] = value + contents[FEED] = json.dumps(feed).encode() + with self.assertRaises(ValueError): + self.validate(reseal(contents)) + + def test_resealed_manifest_cannot_hide_index_checksum_mismatch(self): + for field in ['SHA1', 'SHA256', 'Size']: + contents = fixture() + feed = json.loads(contents[FEED]) + feed['Assets'][0][field] = 0 if field == 'Size' else '0' * 64 + contents[FEED] = json.dumps(feed).encode() + with self.assertRaisesRegex(ValueError, 'index checksums'): + self.validate(reseal(contents)) + + def test_stale_or_mixed_index_and_metadata_are_rejected(self): + contents = fixture() + feed = json.loads(contents[FEED]) + feed['Assets'].append(dict(feed['Assets'][0])) + contents[FEED] = json.dumps(feed).encode() + with self.assertRaises(ValueError): + self.validate(reseal(contents)) + for key, value in [('version', '0.0.9'), ('windowsChannel', 'dev-win-x64'), + ('windowsUpdateVersion', '0.1.0-build.1')]: + contents = fixture() + manifest = json.loads(contents['release-manifest.json']) + manifest[key] = value + with self.assertRaises(ValueError): + self.validate(reseal(contents, manifest)) + + def test_build_number_is_part_of_update_version(self): + with tempfile.TemporaryDirectory() as directory: + spec = Path(directory) / 'pubspec.yaml' + spec.write_text('name: cutdex\nversion: 0.1.0+2\n') + self.assertEqual(app_versions(spec), ('0.1.0', '0.1.0-build.2')) + spec.write_text('version: 0.1.0\n') + with self.assertRaises(ValueError): + app_versions(spec) + + +if __name__ == '__main__': + unittest.main() diff --git a/tool/tests/cli_test.py b/tool/tests/cli_test.py index 2bc28e5..774b5ce 100644 --- a/tool/tests/cli_test.py +++ b/tool/tests/cli_test.py @@ -18,6 +18,7 @@ class CliTests(unittest.TestCase): 'macos/test_check_macos_release.py', 'windows/check_windows_release.py', 'windows/package_windows_release.py', 'windows/prepare_windows_sandbox.py', 'windows/windows_updates.py', 'windows/test_windows_updates.py', + 'gitea/package-app.py', 'diagnostics/frame_budget.py', ] for name in scripts: diff --git a/tool/windows/test_update_configuration_unit.py b/tool/windows/test_update_configuration_unit.py new file mode 100644 index 0000000..13e4a73 --- /dev/null +++ b/tool/windows/test_update_configuration_unit.py @@ -0,0 +1,46 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +@unittest.skipUnless(shutil.which('cmake'), 'CMake required') +class UpdateConfigurationTests(unittest.TestCase): + def configuration(self, flavor, **overrides): + environment = {name: value for name, value in os.environ.items() + if not name.startswith('CUTDEX_WINDOWS_UPDATE_') and name != 'CUTDEX_UPDATE_TEST_HTTP'} + environment.update(overrides) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + script = root / 'config.cmake' + script.write_text(f'set(FLUTTER_APP_FLAVOR "{flavor}")\n' + 'function(configure_updates)\n' + f'include("{ROOT.as_posix()}/windows/runner/update_configuration.cmake")\n' + 'endfunction()\nconfigure_updates()\n' + f'file(WRITE "{root.as_posix()}/result.txt" ' + '"${DESKUP_WINDOWS_UPDATE_SOURCE}|${DESKUP_WINDOWS_UPDATE_URL}|${DESKUP_UPDATE_PACKAGE_ID}|${DESKUP_ALLOW_LOCAL_HTTP}|${DESKUP_GITEA_INCLUDE_PRERELEASES}")\n') + result = subprocess.run(['cmake', '-P', str(script)], env=environment, + capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + return (root / 'result.txt').read_text().split('|') + + def test_production_always_uses_public_gitea_repository(self): + values = self.configuration('production', CUTDEX_WINDOWS_UPDATE_SOURCE='web', + CUTDEX_WINDOWS_UPDATE_URL='http://127.0.0.1:9999', CUTDEX_UPDATE_TEST_HTTP='1') + self.assertEqual(values, ['gitea', 'https://git.orangraph.com/lingjhf/cutdex', 'Cutdex', '0', 'OFF']) + + def test_development_has_no_implicit_production_feed(self): + self.assertEqual(self.configuration('development'), ['gitea', '', 'Cutdex.Dev', '0', 'OFF']) + + def test_development_supports_explicit_loopback_web_test_feed(self): + self.assertEqual(self.configuration('development', CUTDEX_WINDOWS_UPDATE_SOURCE='web', + CUTDEX_WINDOWS_UPDATE_URL='http://127.0.0.1:8765', CUTDEX_UPDATE_TEST_HTTP='1'), + ['web', 'http://127.0.0.1:8765', 'Cutdex.Dev', '1', 'OFF']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tool/windows/test_windows_updates.py b/tool/windows/test_windows_updates.py index c858cea..3a41615 100644 --- a/tool/windows/test_windows_updates.py +++ b/tool/windows/test_windows_updates.py @@ -54,6 +54,7 @@ def main(): definitions = work / 'defines.json' definitions.write_text(json.dumps({'CUTDEX_UPDATE_SMOKE_ROOT': work.as_posix()}), encoding='utf-8') environment = dict(os.environ, CUTDEX_WINDOWS_UPDATE_URL=f'http://127.0.0.1:{args.port}', + CUTDEX_WINDOWS_UPDATE_SOURCE='web', CUTDEX_UPDATE_TEST_HTTP='1') # Isolate Flutter caches, generated runner files and output from live builds. source = work / 'source' @@ -61,11 +62,14 @@ def main(): for name in ['windows']: shutil.copytree(ROOT / name, source / name, ignore=shutil.ignore_patterns('ephemeral', 'build', '__pycache__')) + configuration = source / 'windows/runner/update_configuration.cmake' + configuration.write_text(configuration.read_text().replace( + r'Software\\\\Cutdex\\\\', r'Software\\\\Cutdex\\\\UpdateSmoke\\\\')) # Exercise the real Runner/update bridge with a small Flutter test entry. # Media processing is covered separately and need not be rebuilt here. (source / 'pubspec.yaml').write_text( 'name: cutdex_update_smoke\nversion: 1.0.0+1\n' - 'environment:\n sdk: ^3.13.2\n' + 'environment:\n sdk: ^3.13.4\n' 'dependencies:\n flutter:\n sdk: flutter\n' f' deskup: {DESKUP_VERSION}\n' 'flutter:\n uses-material-design: true\n', encoding='utf-8') @@ -103,7 +107,11 @@ def verify_update(work, port): app = work / 'installed/Cutdex update test.exe' process = None try: - process = subprocess.Popen([str(app)], cwd=app.parent, creationflags=subprocess.CREATE_NO_WINDOW) + # The loopback fixture must not depend on a developer's HTTP proxy. + environment = {name: value for name, value in os.environ.items() + if name.lower() not in ('http_proxy', 'https_proxy', 'all_proxy')} + process = subprocess.Popen([str(app)], cwd=app.parent, env=environment, + creationflags=subprocess.CREATE_NO_WINDOW) deadline = time.monotonic() + 240 while time.monotonic() < deadline: if (work / 'failure.json').exists(): diff --git a/tool/windows/update_versions.py b/tool/windows/update_versions.py new file mode 100644 index 0000000..bf1e837 --- /dev/null +++ b/tool/windows/update_versions.py @@ -0,0 +1,18 @@ +"""Windows update version ordering, independent of Flutter package resolution.""" +import re + + +def update_version(display_version, build): + version = display_version + '-build.' + str(int(build)) + numeric_version(version) + return version + + +def numeric_version(version): + number = r'(0|[1-9]\d*)' + match = re.fullmatch(rf'{number}\.{number}\.{number}(?:-build\.{number})?', version) + if not match: + raise ValueError('Windows update versions must use major.minor.patch-build.number') + major, minor, patch, build = match.groups() + # SemVer +build metadata does not participate in precedence. + return (int(major), int(minor), int(patch), int(build is None), int(build or 0)) diff --git a/tool/windows/windows_updates.py b/tool/windows/windows_updates.py index 62d1ad8..451090d 100644 --- a/tool/windows/windows_updates.py +++ b/tool/windows/windows_updates.py @@ -12,6 +12,7 @@ from urllib.parse import urljoin, urlparse from urllib.request import url2pathname from check_windows_release import audit +from update_versions import numeric_version, update_version ROOT = Path(__file__).resolve().parents[2] def resolved_deskup(): @@ -58,12 +59,6 @@ def pack_release(command, *, app, output, package_id, version, title): '--delta', 'none'], check=True) -def update_version(display_version, build): - version = display_version + '-build.' + str(int(build)) - numeric_version(version) - return version - - def file_version(app): import pefile with pefile.PE(str(app / 'cutdex.exe')) as pe: @@ -78,17 +73,6 @@ def file_version(app): raise ValueError('Missing Flutter display version and build number in PE resources') -def numeric_version(version): - number = r'(0|[1-9]\d*)' - match = re.fullmatch(rf'{number}\.{number}\.{number}(?:-build\.{number})?', version) - if not match: - raise ValueError('Windows update versions must use major.minor.patch-build.number') - major, minor, patch, build = match.groups() - # SemVer build metadata (+number) does not participate in precedence. - # A numeric prerelease component does, and stable versions rank above it. - return (int(major), int(minor), int(patch), int(build is None), int(build or 0)) - - def validate_previous(output, package_id, version): candidate = numeric_version(version) for feed in output.glob('releases.*.json'): @@ -120,28 +104,28 @@ def verify_manifest(app): raise ValueError(f'Release checksum mismatch: {name}') -def package(args): - app, output = args.app.resolve(), args.output.resolve() +def package_app(app, output, vpk, *, development=False, require_processing=True): + app, output = Path(app).resolve(), Path(output).resolve() if output == app or output.is_relative_to(app) or app.is_relative_to(output): raise ValueError('Release output must be outside the staged app') - audit(app) + audit(app, require_processing=require_processing) verify_manifest(app) sdk_dll = app / 'velopack_libc.dll' if not sdk_dll.is_file(): raise ValueError('Rebuild the app with the Velopack integration before packaging') - command = vpk_command(args.vpk) + command = vpk_command(vpk) check_tool(command) version = file_version(app) - package_id = 'Cutdex.Dev' if args.development else 'Cutdex' - # The expected identity is compiled into the runner and must match the package. + package_id = 'Cutdex.Dev' if development else 'Cutdex' + # deskup compiles the identity into the plugin, rather than the runner. identity = package_id.encode('ascii') + b'\0' - if identity not in (app / 'cutdex.exe').read_bytes(): + if identity not in (app / 'deskup_plugin.dll').read_bytes(): raise ValueError('Package identity does not match the Flutter build flavor') validate_previous(output, package_id, version) output.mkdir(parents=True, exist_ok=True) pack_release(command, app=app, output=output, package_id=package_id, version=version, - title='Cutdex Dev' if args.development else 'Cutdex') - print(json.dumps({'version': version, 'packageId': package_id, 'output': str(output)})) + title='Cutdex Dev' if development else 'Cutdex') + return {'version': version, 'packageId': package_id, 'output': str(output)} def serve(directory, port): @@ -168,7 +152,8 @@ def main(): args = parser.parse_args() try: if args.command == 'pack': - package(args) + print(json.dumps(package_app(args.app, args.output, args.vpk, + development=args.development))) else: serve(args.directory, args.port) except KeyboardInterrupt: diff --git a/windows/runner/update_configuration.cmake b/windows/runner/update_configuration.cmake index 33671ee..072555c 100644 --- a/windows/runner/update_configuration.cmake +++ b/windows/runner/update_configuration.cmake @@ -1,9 +1,15 @@ # Configuration is baked into the binary; a user's environment cannot redirect it. -set(CUTDEX_WINDOWS_UPDATE_URL "$ENV{CUTDEX_WINDOWS_UPDATE_URL}") +set(CUTDEX_WINDOWS_UPDATE_SOURCE "gitea") +set(CUTDEX_WINDOWS_UPDATE_URL "https://git.orangraph.com/lingjhf/cutdex") set(CUTDEX_UPDATE_PACKAGE_ID "Cutdex") set(CUTDEX_UPDATE_TEST_HTTP 0) if(FLUTTER_APP_FLAVOR STREQUAL "development") set(CUTDEX_UPDATE_PACKAGE_ID "Cutdex.Dev") + # Development updates must opt into a separate repository/feed explicitly. + set(CUTDEX_WINDOWS_UPDATE_URL "$ENV{CUTDEX_WINDOWS_UPDATE_URL}") + if(DEFINED ENV{CUTDEX_WINDOWS_UPDATE_SOURCE}) + set(CUTDEX_WINDOWS_UPDATE_SOURCE "$ENV{CUTDEX_WINDOWS_UPDATE_SOURCE}") + endif() if("$ENV{CUTDEX_UPDATE_TEST_HTTP}" STREQUAL "1") set(CUTDEX_UPDATE_TEST_HTTP 1) endif() @@ -13,6 +19,8 @@ if(DEFINED ENV{CUTDEX_VELOPACK_ARCHIVE}) set(ENV{DESKUP_VELOPACK_ARCHIVE} "$ENV{CUTDEX_VELOPACK_ARCHIVE}") endif() set(DESKUP_WINDOWS_UPDATE_URL "${CUTDEX_WINDOWS_UPDATE_URL}" PARENT_SCOPE) +set(DESKUP_WINDOWS_UPDATE_SOURCE "${CUTDEX_WINDOWS_UPDATE_SOURCE}" PARENT_SCOPE) +set(DESKUP_GITEA_INCLUDE_PRERELEASES OFF PARENT_SCOPE) set(DESKUP_UPDATE_PACKAGE_ID "${CUTDEX_UPDATE_PACKAGE_ID}" PARENT_SCOPE) set(DESKUP_PREFERENCE_ROOT "Software\\\\Cutdex\\\\" PARENT_SCOPE) set(DESKUP_ALLOW_LOCAL_HTTP "${CUTDEX_UPDATE_TEST_HTTP}" PARENT_SCOPE) -- 2.54.0 From d83f94afd5f2589cac7ee25ed5740f5986c82764 Mon Sep 17 00:00:00 2001 From: lingjhf Date: Tue, 6 Oct 2026 13:38:11 +0800 Subject: [PATCH 02/10] refactor(updates): pass typed runtime policy to deskup --- docs/windows-updates.md | 24 +++++++--- lib/integrations/app_update_bridge.dart | 9 +++- .../app_update_configuration.dart | 48 +++++++++++++++++++ pubspec.lock | 11 +++-- pubspec.yaml | 5 +- test/app_update_configuration_test.dart | 30 ++++++++++++ tool/README.md | 2 + tool/testing/windows_update_smoke.dart | 34 +++++++++++-- .../windows/test_update_configuration_unit.py | 46 ------------------ tool/windows/test_windows_updates.py | 14 ++---- tool/windows/windows_updates.py | 10 ++-- windows/runner/CMakeLists.txt | 1 - windows/runner/update_configuration.cmake | 26 ---------- 13 files changed, 158 insertions(+), 102 deletions(-) create mode 100644 lib/integrations/app_update_configuration.dart create mode 100644 test/app_update_configuration_test.dart delete mode 100644 tool/windows/test_update_configuration_unit.py delete mode 100644 windows/runner/update_configuration.cmake diff --git a/docs/windows-updates.md b/docs/windows-updates.md index 841a7dd..81c79b8 100644 --- a/docs/windows-updates.md +++ b/docs/windows-updates.md @@ -1,6 +1,6 @@ # Windows 更新与 Gitea 发布 -Cutdex 使用 deskup 0.2.0 的 Gitea 更新源,下载、校验、安装和重启由 +Cutdex 使用 deskup 0.3.0 的 Gitea 更新源,下载、校验、安装和重启由 Velopack 1.2.161 完成。正式版构建固定使用公开仓库 `https://git.orangraph.com/lingjhf/cutdex`,包身份为 `Cutdex`,更新频道为 `win-x64`。正式版不读取开发更新源环境变量,也不包含 Gitea 访问令牌。 @@ -51,11 +51,23 @@ Gitea SDK 查询最近 10 个 Release,跳过标为预发布的 Release,并 ## 开发与验证 -development 包身份为 `Cutdex.Dev`,默认不配置更新源,避免连接正式频道。 -设置 `CUTDEX_WINDOWS_UPDATE_URL` 可显式启用独立开发 Gitea 仓库。 -本地 HTTP 目录测试还需设置 `CUTDEX_WINDOWS_UPDATE_SOURCE=web` 和 -`CUTDEX_UPDATE_TEST_HTTP=1`,HTTP 仅允许带端口的 localhost/127.0.0.1。 -生产构建忽略这些开发配置。 +development 包身份为 `Cutdex.Dev`,默认不配置更新源。 +更新策略通过 Dart 的 `WindowsUpdateConfiguration` 传入,不再使用 CMake +更新源变量。正式版固定选用正式 Gitea 仓库,保留 `Cutdex` 注册表偏好命名空间; +安装时显式传入静默和自动重启选项。 + +开发更新源通过编译期 Dart defines 配置,修改后需重新构建。例如本地测试: + +```powershell +flutter build windows --release --flavor development ` + --dart-define=CUTDEX_WINDOWS_UPDATE_SOURCE=web ` + --dart-define=CUTDEX_WINDOWS_UPDATE_URL=http://127.0.0.1:8765 ` + --dart-define=CUTDEX_UPDATE_TEST_HTTP=true +``` + +Gitea 开发仓库使用 `CUTDEX_WINDOWS_UPDATE_SOURCE=gitea` 和仓库 URL。 +仅设置进程环境变量不会配置 Dart 更新源。正式版忽略开发 defines。 +原生 SDK 离线缓存仍通过 `DESKUP_VELOPACK_ARCHIVE` 环境变量指定。 ```powershell python -m unittest discover -s tool/gitea -p 'test_*.py' diff --git a/lib/integrations/app_update_bridge.dart b/lib/integrations/app_update_bridge.dart index c0eeb04..24aa1bb 100644 --- a/lib/integrations/app_update_bridge.dart +++ b/lib/integrations/app_update_bridge.dart @@ -1,6 +1,7 @@ import 'dart:async'; import '../diagnostics/app_diagnostics.dart'; +import 'app_update_configuration.dart'; import 'package:deskup/deskup.dart'; import 'package:flutter/foundation.dart'; @@ -26,7 +27,11 @@ AppUpdateBridge appUpdateBridge(Ref ref) { // Application adapter: Riverpod ownership and the macOS workspace quit gate. class AppUpdateBridge { AppUpdateBridge([MethodChannel channel = appUpdatesChannel]) - : _updater = Deskup(channel: channel); + : _updater = Deskup( + channel: channel, + windows: windowsUpdateConfiguration(), + macos: macosUpdateConfiguration(), + ); final Deskup _updater; Stream get events => _updater.events; @@ -65,7 +70,7 @@ class AppUpdateBridge { Future check() => _updater.check(); Future download() => _updater.download(); Future validateInstall() => _updater.validateInstall(); - Future install() => _updater.install(); + Future install() => _updater.install(silent: true, restart: true); Future setAutomaticChecks(bool enabled) => _updater.setAutomaticChecks(enabled); diff --git a/lib/integrations/app_update_configuration.dart b/lib/integrations/app_update_configuration.dart new file mode 100644 index 0000000..e7301af --- /dev/null +++ b/lib/integrations/app_update_configuration.dart @@ -0,0 +1,48 @@ +import 'package:deskup/deskup.dart'; +import 'package:flutter/services.dart'; + +// Values are compiled from Dart defines; process environment does not redirect production. +MacOSUpdateConfiguration macosUpdateConfiguration() => + const MacOSUpdateConfiguration( + allowLocalHttp: + appFlavor == 'development' && + bool.fromEnvironment('CUTDEX_UPDATE_TEST_HTTP'), + ); + +WindowsUpdateConfiguration? windowsUpdateConfiguration({ + String? flavor, + String developmentUrl = const String.fromEnvironment( + 'CUTDEX_WINDOWS_UPDATE_URL', + ), + String developmentSource = const String.fromEnvironment( + 'CUTDEX_WINDOWS_UPDATE_SOURCE', + defaultValue: 'gitea', + ), + bool allowLocalHttp = const bool.fromEnvironment('CUTDEX_UPDATE_TEST_HTTP'), +}) { + final development = (flavor ?? appFlavor) == 'development'; + if (development && developmentUrl.isEmpty) return null; + final WindowsUpdateSource source; + if (!development) { + source = GiteaUpdateSource( + repositoryUrl: Uri.parse('https://git.orangraph.com/lingjhf/cutdex'), + ); + } else if (developmentSource == 'gitea') { + source = GiteaUpdateSource( + repositoryUrl: Uri.parse(developmentUrl), + allowLocalHttp: allowLocalHttp, + ); + } else if (developmentSource == 'web') { + source = WebUpdateSource( + url: Uri.parse(developmentUrl), + allowLocalHttp: allowLocalHttp, + ); + } else { + throw ArgumentError.value(developmentSource, 'developmentSource'); + } + return WindowsUpdateConfiguration( + source: source, + expectedPackageId: development ? 'Cutdex.Dev' : 'Cutdex', + preferenceNamespace: 'Cutdex', + ); +} diff --git a/pubspec.lock b/pubspec.lock index 251c87f..f37b818 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -302,11 +302,12 @@ packages: deskup: dependency: "direct main" description: - name: deskup - sha256: "722cd3c4aa51ebe886cd0fe0a842b7312a4235a4b2e097015aab51c10c010c4e" - url: "https://pub.dev" - source: hosted - version: "0.2.0" + path: "." + ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd + resolved-ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd + url: "https://github.com/lingjhf/deskup.git" + source: git + version: "0.3.0" drift: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index b533dca..41bba2e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -13,7 +13,10 @@ workspace: dependencies: cutdex_ui: ^0.1.0 cutdex_native: ^0.1.0 - deskup: ^0.2.0 + deskup: + git: + url: https://github.com/lingjhf/deskup.git + ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd flutter: sdk: flutter diff --git a/test/app_update_configuration_test.dart b/test/app_update_configuration_test.dart new file mode 100644 index 0000000..8dec600 --- /dev/null +++ b/test/app_update_configuration_test.dart @@ -0,0 +1,30 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:cutdex/integrations/app_update_configuration.dart'; + +void main() { + test('production ignores development source overrides', () { + final config = windowsUpdateConfiguration( + flavor: 'production', + developmentUrl: 'http://127.0.0.1:8765', + developmentSource: 'web', + allowLocalHttp: true, + )!; + final map = config.toMap(); + expect( + (map['source'] as Map)['url'], + 'https://git.orangraph.com/lingjhf/cutdex', + ); + expect(map['expectedPackageId'], 'Cutdex'); + }); + test('development requires opt-in and uses an isolated identity', () { + expect(windowsUpdateConfiguration(flavor: 'development'), isNull); + final map = windowsUpdateConfiguration( + flavor: 'development', + developmentUrl: 'http://127.0.0.1:8765', + developmentSource: 'web', + allowLocalHttp: true, + )!.toMap(); + expect(map['expectedPackageId'], 'Cutdex.Dev'); + expect((map['source'] as Map)['type'], 'web'); + }); +} diff --git a/tool/README.md b/tool/README.md index 78560b7..51603bc 100644 --- a/tool/README.md +++ b/tool/README.md @@ -75,6 +75,8 @@ python3 tool/windows/windows_updates.py pack --help 提升应用构建号,保留当前线上更新索引供版本检查;development 与 production 使用独立发布目录。脚本只生成产物,不上传。完整升级模拟使用各平台的 `test_*_updates.py`,参数见 `--help`,测试包不用于分发。 +deskup 0.3.0 的开发更新源由 Dart 参数配置。Windows 的编译期配置示例见 [Windows 更新文档](../docs/windows-updates.md)。macOS 本地 HTTP 更新测试的源应用需使用 `--flavor development --dart-define=CUTDEX_UPDATE_TEST_HTTP=true` 构建,再运行 `test_macos_updates.py`;签名公钥和 appcast 仍由打包工具写入应用 Info.plist。 + ## 诊断与共享测试入口 - `diagnostics/frame_budget.py`:读取 `CUTDEX_FRAME_TIMINGS` JSONL,可带阶段标记文件;报告帧耗时。 diff --git a/tool/testing/windows_update_smoke.dart b/tool/testing/windows_update_smoke.dart index 6af2681..2e94a74 100644 --- a/tool/testing/windows_update_smoke.dart +++ b/tool/testing/windows_update_smoke.dart @@ -5,11 +5,15 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:deskup/deskup.dart'; const channel = MethodChannel('deskup'); const smokeRoot = String.fromEnvironment('CUTDEX_UPDATE_SMOKE_ROOT'); -void main() { +List restartArguments = []; + +void main(List arguments) { + restartArguments = arguments; WidgetsFlutterBinding.ensureInitialized(); // The isolated smoke fixture depends only on Flutter, without Riverpod. // ignore: riverpod_lint/missing_provider_scope @@ -48,13 +52,33 @@ Future runSmoke() async { throw StateError('Set CUTDEX_UPDATE_SMOKE_ROOT for this test app'); } try { - await channel.invokeMethod('ready'); + final updater = Deskup( + windows: WindowsUpdateConfiguration( + source: WebUpdateSource( + url: Uri.parse( + const String.fromEnvironment('CUTDEX_WINDOWS_UPDATE_URL'), + ), + allowLocalHttp: true, + ), + expectedPackageId: 'Cutdex.Dev', + preferenceNamespace: 'Cutdex.UpdateSmoke', + automaticCheckInterval: const Duration(minutes: 5), + maximumDeltas: -1, + ), + ); + await updater.initialize(); final initial = await waitFor( (value) => value['configured'] == true && value['canCheck'] == true, ); await channel.invokeMethod('check'); var checked = await waitFor((value) => value['canCheck'] == true); if (initial['build'] == '900002') { + if (!restartArguments.contains('--deskup-smoke-restart') || + !restartArguments.contains('文档 with spaces')) { + throw StateError( + 'Restart arguments were not preserved: $restartArguments', + ); + } if (checked['phase'] != 'current') { throw StateError('Updated version was offered again: $checked'); } @@ -78,7 +102,11 @@ Future runSmoke() async { } await record('before', checked); await channel.invokeMethod('validateInstall'); - await channel.invokeMethod('install'); + await updater.install( + silent: true, + restart: true, + restartArguments: ['--deskup-smoke-restart', '文档 with spaces'], + ); } catch (error, stack) { await record('failure', {'error': '$error', 'stack': '$stack'}); exit(1); diff --git a/tool/windows/test_update_configuration_unit.py b/tool/windows/test_update_configuration_unit.py deleted file mode 100644 index 13e4a73..0000000 --- a/tool/windows/test_update_configuration_unit.py +++ /dev/null @@ -1,46 +0,0 @@ -import os -from pathlib import Path -import shutil -import subprocess -import tempfile -import unittest - -ROOT = Path(__file__).resolve().parents[2] - - -@unittest.skipUnless(shutil.which('cmake'), 'CMake required') -class UpdateConfigurationTests(unittest.TestCase): - def configuration(self, flavor, **overrides): - environment = {name: value for name, value in os.environ.items() - if not name.startswith('CUTDEX_WINDOWS_UPDATE_') and name != 'CUTDEX_UPDATE_TEST_HTTP'} - environment.update(overrides) - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - script = root / 'config.cmake' - script.write_text(f'set(FLUTTER_APP_FLAVOR "{flavor}")\n' - 'function(configure_updates)\n' - f'include("{ROOT.as_posix()}/windows/runner/update_configuration.cmake")\n' - 'endfunction()\nconfigure_updates()\n' - f'file(WRITE "{root.as_posix()}/result.txt" ' - '"${DESKUP_WINDOWS_UPDATE_SOURCE}|${DESKUP_WINDOWS_UPDATE_URL}|${DESKUP_UPDATE_PACKAGE_ID}|${DESKUP_ALLOW_LOCAL_HTTP}|${DESKUP_GITEA_INCLUDE_PRERELEASES}")\n') - result = subprocess.run(['cmake', '-P', str(script)], env=environment, - capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stderr) - return (root / 'result.txt').read_text().split('|') - - def test_production_always_uses_public_gitea_repository(self): - values = self.configuration('production', CUTDEX_WINDOWS_UPDATE_SOURCE='web', - CUTDEX_WINDOWS_UPDATE_URL='http://127.0.0.1:9999', CUTDEX_UPDATE_TEST_HTTP='1') - self.assertEqual(values, ['gitea', 'https://git.orangraph.com/lingjhf/cutdex', 'Cutdex', '0', 'OFF']) - - def test_development_has_no_implicit_production_feed(self): - self.assertEqual(self.configuration('development'), ['gitea', '', 'Cutdex.Dev', '0', 'OFF']) - - def test_development_supports_explicit_loopback_web_test_feed(self): - self.assertEqual(self.configuration('development', CUTDEX_WINDOWS_UPDATE_SOURCE='web', - CUTDEX_WINDOWS_UPDATE_URL='http://127.0.0.1:8765', CUTDEX_UPDATE_TEST_HTTP='1'), - ['web', 'http://127.0.0.1:8765', 'Cutdex.Dev', '1', 'OFF']) - - -if __name__ == '__main__': - unittest.main() diff --git a/tool/windows/test_windows_updates.py b/tool/windows/test_windows_updates.py index 3a41615..18052ea 100644 --- a/tool/windows/test_windows_updates.py +++ b/tool/windows/test_windows_updates.py @@ -15,7 +15,7 @@ import sys import threading import time -from windows_updates import DESKUP_VERSION, ROOT, check_tool, pack_release, update_version, vpk_command +from windows_updates import DESKUP_ROOT, ROOT, check_tool, pack_release, update_version, vpk_command class TestHandler(SimpleHTTPRequestHandler): @@ -52,26 +52,22 @@ def main(): command = vpk_command(args.vpk) check_tool(command) definitions = work / 'defines.json' - definitions.write_text(json.dumps({'CUTDEX_UPDATE_SMOKE_ROOT': work.as_posix()}), encoding='utf-8') - environment = dict(os.environ, CUTDEX_WINDOWS_UPDATE_URL=f'http://127.0.0.1:{args.port}', - CUTDEX_WINDOWS_UPDATE_SOURCE='web', - CUTDEX_UPDATE_TEST_HTTP='1') + definitions.write_text(json.dumps({'CUTDEX_UPDATE_SMOKE_ROOT': work.as_posix(), + 'CUTDEX_WINDOWS_UPDATE_URL': f'http://127.0.0.1:{args.port}'}), encoding='utf-8') + environment = dict(os.environ) # Isolate Flutter caches, generated runner files and output from live builds. source = work / 'source' source.mkdir() for name in ['windows']: shutil.copytree(ROOT / name, source / name, ignore=shutil.ignore_patterns('ephemeral', 'build', '__pycache__')) - configuration = source / 'windows/runner/update_configuration.cmake' - configuration.write_text(configuration.read_text().replace( - r'Software\\\\Cutdex\\\\', r'Software\\\\Cutdex\\\\UpdateSmoke\\\\')) # Exercise the real Runner/update bridge with a small Flutter test entry. # Media processing is covered separately and need not be rebuilt here. (source / 'pubspec.yaml').write_text( 'name: cutdex_update_smoke\nversion: 1.0.0+1\n' 'environment:\n sdk: ^3.13.4\n' 'dependencies:\n flutter:\n sdk: flutter\n' - f' deskup: {DESKUP_VERSION}\n' + f' deskup:\n path: {DESKUP_ROOT.as_posix()}\n' 'flutter:\n uses-material-design: true\n', encoding='utf-8') entry = source / 'tool/testing/windows_update_smoke.dart' entry.parent.mkdir(parents=True) diff --git a/tool/windows/windows_updates.py b/tool/windows/windows_updates.py index 451090d..b31c25b 100644 --- a/tool/windows/windows_updates.py +++ b/tool/windows/windows_updates.py @@ -117,9 +117,13 @@ def package_app(app, output, vpk, *, development=False, require_processing=True) check_tool(command) version = file_version(app) package_id = 'Cutdex.Dev' if development else 'Cutdex' - # deskup compiles the identity into the plugin, rather than the runner. - identity = package_id.encode('ascii') + b'\0' - if identity not in (app / 'deskup_plugin.dll').read_bytes(): + # The updater is generic; verify the host flavor through its PE branding. + import pefile + with pefile.PE(str(app / 'cutdex.exe')) as pe: + products = [table.entries.get(b'ProductName', b'').decode('utf-8') + for group in pe.FileInfo for block in group + if block.Key == b'StringFileInfo' for table in block.StringTable] + if ('Cutdex Dev' if development else 'Cutdex') not in products: raise ValueError('Package identity does not match the Flutter build flavor') validate_previous(output, package_id, version) output.mkdir(parents=True, exist_ok=True) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt index b2663e4..7001296 100644 --- a/windows/runner/CMakeLists.txt +++ b/windows/runner/CMakeLists.txt @@ -60,7 +60,6 @@ target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app dwmapi) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") -include("${CMAKE_CURRENT_SOURCE_DIR}/update_configuration.cmake") # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/update_configuration.cmake b/windows/runner/update_configuration.cmake deleted file mode 100644 index 072555c..0000000 --- a/windows/runner/update_configuration.cmake +++ /dev/null @@ -1,26 +0,0 @@ -# Configuration is baked into the binary; a user's environment cannot redirect it. -set(CUTDEX_WINDOWS_UPDATE_SOURCE "gitea") -set(CUTDEX_WINDOWS_UPDATE_URL "https://git.orangraph.com/lingjhf/cutdex") -set(CUTDEX_UPDATE_PACKAGE_ID "Cutdex") -set(CUTDEX_UPDATE_TEST_HTTP 0) -if(FLUTTER_APP_FLAVOR STREQUAL "development") - set(CUTDEX_UPDATE_PACKAGE_ID "Cutdex.Dev") - # Development updates must opt into a separate repository/feed explicitly. - set(CUTDEX_WINDOWS_UPDATE_URL "$ENV{CUTDEX_WINDOWS_UPDATE_URL}") - if(DEFINED ENV{CUTDEX_WINDOWS_UPDATE_SOURCE}) - set(CUTDEX_WINDOWS_UPDATE_SOURCE "$ENV{CUTDEX_WINDOWS_UPDATE_SOURCE}") - endif() - if("$ENV{CUTDEX_UPDATE_TEST_HTTP}" STREQUAL "1") - set(CUTDEX_UPDATE_TEST_HTTP 1) - endif() -endif() -# deskup validates feed URLs; the host limits local HTTP to development. -if(DEFINED ENV{CUTDEX_VELOPACK_ARCHIVE}) - set(ENV{DESKUP_VELOPACK_ARCHIVE} "$ENV{CUTDEX_VELOPACK_ARCHIVE}") -endif() -set(DESKUP_WINDOWS_UPDATE_URL "${CUTDEX_WINDOWS_UPDATE_URL}" PARENT_SCOPE) -set(DESKUP_WINDOWS_UPDATE_SOURCE "${CUTDEX_WINDOWS_UPDATE_SOURCE}" PARENT_SCOPE) -set(DESKUP_GITEA_INCLUDE_PRERELEASES OFF PARENT_SCOPE) -set(DESKUP_UPDATE_PACKAGE_ID "${CUTDEX_UPDATE_PACKAGE_ID}" PARENT_SCOPE) -set(DESKUP_PREFERENCE_ROOT "Software\\\\Cutdex\\\\" PARENT_SCOPE) -set(DESKUP_ALLOW_LOCAL_HTTP "${CUTDEX_UPDATE_TEST_HTTP}" PARENT_SCOPE) -- 2.54.0 From b225008476e7aa943a4bc651909e3737e64c2da1 Mon Sep 17 00:00:00 2001 From: lingjhf Date: Tue, 6 Oct 2026 14:04:09 +0800 Subject: [PATCH 03/10] ci(gitea): split builds and retry artifact publication --- .gitea/BUILD_AND_RELEASE.md | 69 ++++ .gitea/CI_PERFORMANCE.md | 76 ++++ .gitea/README.md | 26 -- .gitea/actions/upload-artifact/action.yml | 63 +++ .gitea/workflows/ci.yml | 181 +++++++-- .gitea/workflows/release.yml | 115 +++++- tool/gitea/package-app.py | 91 +++-- tool/gitea/prepare-build-cache.ps1 | 14 + tool/gitea/prepare-package-tools.ps1 | 40 ++ tool/gitea/promote-release.py | 89 ---- tool/gitea/release_artifacts.py | 29 +- tool/gitea/release_transport.py | 109 +++++ tool/gitea/stage-release.py | 287 +++++++++++++ tool/gitea/test_package_app.py | 112 ++++++ tool/gitea/test_promote_release.py | 98 ----- tool/gitea/test_release_artifacts.py | 26 +- tool/gitea/test_stage_release.py | 468 ++++++++++++++++++++++ tool/gitea/test_transfer_tools.py | 183 +++++++++ 18 files changed, 1790 insertions(+), 286 deletions(-) create mode 100644 .gitea/BUILD_AND_RELEASE.md create mode 100644 .gitea/CI_PERFORMANCE.md delete mode 100644 .gitea/README.md create mode 100644 .gitea/actions/upload-artifact/action.yml create mode 100644 tool/gitea/prepare-build-cache.ps1 create mode 100644 tool/gitea/prepare-package-tools.ps1 delete mode 100644 tool/gitea/promote-release.py create mode 100644 tool/gitea/release_transport.py create mode 100644 tool/gitea/stage-release.py create mode 100644 tool/gitea/test_package_app.py delete mode 100644 tool/gitea/test_promote_release.py create mode 100644 tool/gitea/test_stage_release.py create mode 100644 tool/gitea/test_transfer_tools.py diff --git a/.gitea/BUILD_AND_RELEASE.md b/.gitea/BUILD_AND_RELEASE.md new file mode 100644 index 0000000..7ecb158 --- /dev/null +++ b/.gitea/BUILD_AND_RELEASE.md @@ -0,0 +1,69 @@ +# Gitea Windows and Android builds + +The Windows x64 host runner needs Flutter 3.47.5, Python, Node, Visual Studio C++, +JDK 21 and Android SDK 36. The native cutdex_windows Release and cutdex_android +Maven packages must be published before building this app. The SDK Git dependency +is pinned to Gitea; the runner account needs SSH access to that private repository. + +Set CUTDEX_GITEA_TOKEN in repository Actions Secrets with repository read and +package read access. It authenticates private Gitea native package downloads. +The Android APK includes ARM64 and x86_64, uses the production flavor and currently +uses the project's debug signing configuration. Configure formal signing before +shipping a production signed Android release. The Windows ZIP includes the whole +Flutter Release directory and passes the PE dependency audit. Processing workers +and optional models are separate; these four repositories contain no worker bundle. + +PR/main CI analyzes and tests the app, builds both platforms, and uploads +cutdex-release-packages including SHA256SUMS and a release manifest. It also saves +cutdex-release-metadata containing only the manifest, checksums, Windows update +index and audit report. Platform, complete and metadata artifacts retain 30 days. Protect main +with `Gitea CI / Gitea CI passed (pull_request)`. + +Windows compilation and packaging are separate jobs. Compilation saves the +unpackaged Release directory as `cutdex-windows-app` for 30 days; packaging +downloads it and runs the existing PE audit and Velopack tools. Rerunning a failed +packaging job reuses this app without recompiling. Assembly and Release jobs +similarly reuse their upstream artifacts. Use the failed-job rerun option: a +whole-workflow rerun executes compilation again. A job always restarts from its +first step. Saving the Windows app adds one artifact transfer between the jobs. + +CI artifact uploads attempt at most three times, waiting 5 and 15 seconds between +attempts and replacing incomplete artifacts of the same job-owned name. Release +attachment uploads use the same bounded delays for temporary HTTP/network errors, +and check for already saved filenames before repeating a POST. Permanent errors +fail immediately and final attachment byte verification remains required. If the +Windows app cannot be saved after all attempts, its build job still needs to be +rerun. Draft creation and final publication are not automatically retried. + +After main CI succeeds, create v at that exact commit, or manually +dispatch the Release workflow with the existing tag. Release preparation selects +a successful main ci.yml run for the exact tagged commit and requires unexpired +cutdex-android-build, cutdex-windows-build and cutdex-release-metadata artifacts. It creates a draft bound to both that commit and +that CI run. Release jobs never rebuild the app or reinstall Flutter dependencies. + +Android and Windows independently download their platform artifacts from the +selected CI run and immediately upload them to the draft. These jobs run in +parallel. The final job accepts only the compact metadata artifact from that same +CI run. Complete binary archives cannot substitute for platform packages or +metadata. Missing, expired or duplicate required artifacts block preparation +before any draft is created. Platform uploads check attachment presence without +reading back their bytes. Before publication, every attachment is read back once +and verified against trusted SHA256 checksums; the full update package also +matches its index SHA1 and size. Upload and verification batches use at most two +requests per job. Verification reads in 1 MiB chunks. Tag, CI, draft and attachment +ID/name bindings are rechecked before the Release is made public. + +A failed upload leaves the draft unpublished with successful uploads retained. +Manual dispatch with the same tag resumes the original CI run, even if another CI +for that commit has since succeeded. Matching attachments are reused; changed or +unrelated attachments block publication rather than being replaced. If the +original platform or metadata artifacts have expired, release preparation fails and requires +operator attention. Published Releases are never overwritten. The built-in +GITEA_TOKEN handles release writes and Actions artifact reads; no separate +release-write PAT is required. Do not commit credentials or keystores. + +PR/main CI produces Actions artifacts without creating Releases. If a tag is pushed +before main CI succeeds, release preparation fails without creating a draft; retry +the Release workflow once CI has finished. This design overlaps platform uploads, +not main CI builds with Release uploads. There is no legacy whole-archive +promotion entry point or format fallback. diff --git a/.gitea/CI_PERFORMANCE.md b/.gitea/CI_PERFORMANCE.md new file mode 100644 index 0000000..7d35972 --- /dev/null +++ b/.gitea/CI_PERFORMANCE.md @@ -0,0 +1,76 @@ +# CI build performance + +The workflow runs checks first, then Android and Windows compilation concurrently. +Windows compilation saves `cutdex-windows-app`; an independent Windows job +downloads that app, audits it and creates Velopack packages. Packaging needs +neither Flutter dependencies nor another Windows compilation. The Android job +builds the APK. The final job downloads only platform packages and +validates the complete release manifest, update feed and checksums. The public +artifact remains `cutdex-release-packages`. + +Build jobs explicitly use persistent runner-user Pub and Gradle caches, respecting +existing `PUB_CACHE` and `GRADLE_USER_HOME` overrides. Gradle task output caching is +enabled for CI. Do not clear these caches between runs. Each job must have its own +checkout; do not share a Flutter `build/` or `.dart_tool/` directory between jobs. +With an ephemeral runner, these user directories must be persisted separately. + +The runner needs at least two execution slots. The local runner configuration at +`D:/workspace/gitea-stack/runner/config.yaml` currently has `capacity: 2`. The host +has 12 logical processors and approximately 16 GB RAM; the Android job retains its +3 GB heap and four-worker limit to leave room for concurrent Windows compilation. + +`prepare-package-tools.ps1` installs pinned `pefile` and `vpk` on first use under +the runner user's `%LOCALAPPDATA%/Cutdex/ci-tools/`. Later builds reuse them after +version checks. Python interpreter identity and tool versions isolate the cache, +and a mutex protects installation across concurrent workflows. .NET setup remains +in the Windows packaging job to provide SDK 10 and the runtime required by `vpk`. + +APK and Windows package uploads use `compression-level: 0` to avoid recompressing +already compressed artifacts. The saved Windows app uses compression level 1, +preserves nested and hidden runtime assets, and excludes the same debug files and +optional workers omitted by packaging. The saved app, platform packages, compact +metadata and validated release artifact all retain 30 days. + +Compare warm CI runs after the first cache fill. Measure checks, Android compile, +Windows compile, packaging and artifact transfer separately. Total duration follows +the slower platform branch, plus checks and final assembly; no fixed speedup is +assumed. Release audits and artifact validation remain mandatory. + +## Failure recovery + +Use Gitea's failed-job rerun rather than rerunning the entire workflow. A job +reruns from its first step, including downstream dependent jobs. Once the Windows +app artifact has been saved, a Windows packaging failure can be retried without +recompilation. Assembly failures reuse the saved Android and Windows packages; +Release failures reuse the successful main CI. Splitting Windows adds one app +upload/download on successful runs in exchange for this recovery point. + +Every CI artifact upload uses the local `upload-artifact` composite, with at most +three action attempts and 5/15-second delays. Attempts replace incomplete +artifacts with the same name; each name belongs to one producing job. Exhausted +retries fail the job. If the first Windows app checkpoint cannot be uploaded, +the build job must still be rerun; it has no saved app to restore. + +Release attachment uploads retry temporary network errors, HTTP 408/429 and +500/502/503/504 up to three POST attempts per file, also with 5/15-second delays. +Before retrying a POST, the uploader checks whether Gitea already saved the named +attachment, including after the final response is lost. This avoids duplicate +uploads after a timeout. Authorization, invalid-input and other permanent errors +fail immediately. No draft creation or publication PATCH is automatically retried. +Attachment-list reads have their own bounded retries. Final byte verification +remains mandatory even when an existing filename is reused. + +The tag/manual Release workflow reuses a successful main CI for the exact tagged +commit; it performs no Flutter builds, dependency resolution or Windows packaging. +A prepare job binds the draft and both platform upload jobs to one CI run. Android +and Windows independently fetch and upload their existing packages in parallel. +Publication requires the small cutdex-release-metadata artifact; it never +downloads the combined binary artifact. Missing or expired metadata/platform +artifacts fail preparation, with no old-format fallback. Every remote file is read and verified once, immediately +before publication, with two verification workers and 1 MiB chunks. Platform +upload steps check presence without repeating binary readbacks. Each upload +batch also uses at most two workers; while both platform jobs run, Android can +have one upload in flight alongside two Windows uploads. +Retries retain the original CI-run binding. Ordinary CI never creates +drafts. Wait for main CI success before tagging or retry Release after it finishes; +platform Release uploads overlap each other, not the original main builds. diff --git a/.gitea/README.md b/.gitea/README.md deleted file mode 100644 index bdd7ea1..0000000 --- a/.gitea/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# Gitea Windows and Android builds - -The Windows x64 host runner needs Flutter 3.47.5, Python, Node, Visual Studio C++, -JDK 21 and Android SDK 36. The native cutdex_windows Release and cutdex_android -Maven packages must be published before building this app. The SDK Git dependency -is pinned to Gitea; the runner account needs SSH access to that private repository. - -Set CUTDEX_GITEA_TOKEN in repository Actions Secrets with repository read and -package read access. It authenticates private Gitea native package downloads. -The Android APK includes ARM64 and x86_64, uses the production flavor and currently -uses the project's debug signing configuration. Configure formal signing before -shipping a production signed Android release. The Windows ZIP includes the whole -Flutter Release directory and passes the PE dependency audit. Processing workers -and optional models are separate; these four repositories contain no worker bundle. - -PR/main CI analyzes and tests the app, builds both platforms, and uploads -cutdex-release-packages including SHA256SUMS and a release manifest. Protect main -with `Gitea CI / Gitea CI passed (pull_request)`. - -After main CI succeeds, create v at that exact commit. The Release -workflow downloads the existing CI artifact, requires both APK and Windows ZIP, -checks their digests, uploads to a draft Release, verifies remote bytes, then -publishes it. It refuses to overwrite a published Release. A manual dispatch with -the existing tag can retry an interrupted draft publication. The built-in GITEA_TOKEN -handles release writes and Actions artifact reads; no separate release-write PAT -is required. Do not commit credentials or keystores. diff --git a/.gitea/actions/upload-artifact/action.yml b/.gitea/actions/upload-artifact/action.yml new file mode 100644 index 0000000..645bf42 --- /dev/null +++ b/.gitea/actions/upload-artifact/action.yml @@ -0,0 +1,63 @@ +name: Upload CI artifact with bounded retries +description: Save an artifact with at most three attempts, replacing incomplete uploads of the same name. +inputs: + name: + description: Artifact name, unique to this job in the workflow run + required: true + path: + description: Files and directories to upload + required: true + compression-level: + description: ZIP compression level + default: '0' + retention-days: + description: Artifact retention in days + default: '30' +runs: + using: composite + steps: + - name: Upload artifact (attempt 1 of 3) + id: first + continue-on-error: true + uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: ${{ inputs.name }} + path: ${{ inputs.path }} + compression-level: ${{ inputs.compression-level }} + retention-days: ${{ inputs.retention-days }} + if-no-files-found: error + include-hidden-files: true + overwrite: true + - name: Wait before second upload attempt + if: ${{ !cancelled() && steps.first.outcome == 'failure' }} + shell: pwsh + run: Start-Sleep -Seconds 5 + - name: Upload artifact (attempt 2 of 3) + id: second + if: ${{ !cancelled() && steps.first.outcome == 'failure' }} + continue-on-error: true + uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: ${{ inputs.name }} + path: ${{ inputs.path }} + compression-level: ${{ inputs.compression-level }} + retention-days: ${{ inputs.retention-days }} + if-no-files-found: error + include-hidden-files: true + overwrite: true + - name: Wait before final upload attempt + if: ${{ !cancelled() && steps.first.outcome == 'failure' && steps.second.outcome == 'failure' }} + shell: pwsh + run: Start-Sleep -Seconds 15 + - name: Upload artifact (attempt 3 of 3) + id: third + if: ${{ !cancelled() && steps.first.outcome == 'failure' && steps.second.outcome == 'failure' }} + uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: ${{ inputs.name }} + path: ${{ inputs.path }} + compression-level: ${{ inputs.compression-level }} + retention-days: ${{ inputs.retention-days }} + if-no-files-found: error + include-hidden-files: true + overwrite: true diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index e219a63..b6f7824 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -19,65 +19,185 @@ env: GIT_CONFIG_KEY_1: core.eol GIT_CONFIG_VALUE_1: lf jobs: - build: - name: Windows x64 and Android + quality: + name: Check code and tests runs-on: cutdex-windows-x64 env: GITEA_ACTOR: lingjhf CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }} steps: - - uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - name: Check out source + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: persist-credentials: false - - name: Verify toolchains + - name: Configure persistent build caches + run: ./tool/gitea/prepare-build-cache.ps1 + - name: Verify Flutter version and configure Java run: | $version = flutter --version --machine | ConvertFrom-Json if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' } flutter config --jdk-dir=$env:JAVA_HOME if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' } - - run: flutter pub get --enforce-lockfile - - run: dart analyze --fatal-infos - - run: flutter test --reporter expanded test packages/cutdex_ui/test packages/cutdex_native/test - - name: Validate update and release tooling + - name: Resolve locked Flutter dependencies + run: flutter pub get --enforce-lockfile + - name: Analyze Dart code + run: dart analyze --fatal-infos + - name: Run Flutter tests + run: flutter test --reporter expanded test packages/cutdex_ui/test packages/cutdex_native/test + - name: Test update and release tools run: | python -m unittest discover -s tool/gitea -p 'test_*.py' if ($LASTEXITCODE -ne 0) { throw 'Release tooling tests failed.' } python -m unittest discover -s tool/windows -p '*_unit.py' if ($LASTEXITCODE -ne 0) { throw 'Update tooling tests failed.' } - - name: Bound Android build memory on the shared runner + + android: + name: Build Android APK + needs: quality + runs-on: cutdex-windows-x64 + env: + GITEA_ACTOR: lingjhf + CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }} + steps: + - name: Check out source + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - name: Configure persistent build caches + run: ./tool/gitea/prepare-build-cache.ps1 + - name: Verify Flutter version and configure Java + run: | + $version = flutter --version --machine | ConvertFrom-Json + if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' } + flutter config --jdk-dir=$env:JAVA_HOME + if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' } + - name: Resolve locked Flutter dependencies + run: flutter pub get --enforce-lockfile + - name: Configure Gradle memory and build cache run: | $file = 'android/gradle.properties' $properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m') - [IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`n") - - run: flutter build apk --release --flavor production --target-platform android-arm64,android-x64 - - name: Build Windows from the pinned Gitea native release + [IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`norg.gradle.caching=true`n") + - name: Build production Android APK + run: flutter build apk --no-pub --release --flavor production --target-platform android-arm64,android-x64 + - name: Upload Android CI artifact + uses: ./.gitea/actions/upload-artifact + with: + name: cutdex-android-build + path: build/app/outputs/flutter-apk/app-production-release.apk + compression-level: 0 + retention-days: 30 + + windows-build: + name: Build Windows x64 app + needs: quality + runs-on: cutdex-windows-x64 + env: + GITEA_ACTOR: lingjhf + CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }} + steps: + - name: Check out source + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - name: Configure persistent build caches + run: ./tool/gitea/prepare-build-cache.ps1 + - name: Verify Flutter version + run: | + $version = flutter --version --machine | ConvertFrom-Json + if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' } + - name: Resolve locked Flutter dependencies + run: flutter pub get --enforce-lockfile + - name: Build production Windows app run: | Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue - flutter build windows --release --flavor production + flutter build windows --no-pub --release --flavor production if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' } - - name: Prepare isolated packaging tools - run: | - python -m venv .build/package-tools - if ($LASTEXITCODE -ne 0) { throw 'Packaging environment setup failed.' } - & ./.build/package-tools/Scripts/python.exe -m pip install pefile==2024.8.26 - if ($LASTEXITCODE -ne 0) { throw 'Packaging dependency installation failed.' } - - uses: https://github.com/actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 + - name: Save Windows app for independent packaging retries + uses: ./.gitea/actions/upload-artifact + with: + name: cutdex-windows-app + path: | + build/windows/x64/production/runner/Release/ + !build/windows/x64/production/runner/Release/**/processing/** + !build/windows/x64/production/runner/Release/**/*.pdb + !build/windows/x64/production/runner/Release/**/*.lib + !build/windows/x64/production/runner/Release/**/*.exp + !build/windows/x64/production/runner/Release/**/dartjni.dll + compression-level: 1 + retention-days: 30 + + windows: + name: Audit and package Windows x64 + needs: windows-build + runs-on: cutdex-windows-x64 + steps: + - name: Check out source + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - name: Download saved Windows app + uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + name: cutdex-windows-app + path: build/windows/x64/production/runner/Release/ + - name: Set up .NET SDK + uses: https://github.com/actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 with: dotnet-version: '10.0.x' - - name: Install pinned Velopack release tool + - name: Prepare pinned packaging tools + run: ./tool/gitea/prepare-package-tools.ps1 + - name: Audit and package Windows release run: | - dotnet tool install vpk --version 1.2.161 --tool-path .build/vpk - if ($LASTEXITCODE -ne 0) { throw 'Velopack tool installation failed.' } - - name: Package application + & $env:PACKAGE_PYTHON tool/gitea/package-app.py --platform windows --vpk $env:VPK_PATH + if ($LASTEXITCODE -ne 0) { throw 'Windows packaging failed.' } + - name: Upload Windows CI artifact + uses: ./.gitea/actions/upload-artifact + with: + name: cutdex-windows-build + path: dist/* + compression-level: 0 + retention-days: 30 + + build: + name: Assemble and validate CI artifacts + needs: [android, windows] + runs-on: cutdex-windows-x64 + env: + GITEA_ACTOR: lingjhf + CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }} + steps: + - name: Check out source + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - name: Download Android CI artifact + uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + name: cutdex-android-build + path: build/app/outputs/flutter-apk/ + - name: Download Windows CI artifact + uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + name: cutdex-windows-build + path: .build/windows-packages/ + - name: Validate packages and generate metadata run: | - & ./.build/package-tools/Scripts/python.exe tool/gitea/package-app.py --vpk .build/vpk/vpk.exe - if ($LASTEXITCODE -ne 0) { throw 'Application packaging failed.' } - - name: Upload Android and Windows packages - uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + python tool/gitea/package-app.py --platform assemble --windows-packages .build/windows-packages + if ($LASTEXITCODE -ne 0) { throw 'Application artifact validation failed.' } + - name: Upload combined CI artifact + uses: ./.gitea/actions/upload-artifact with: name: cutdex-release-packages path: dist/* - if-no-files-found: error + compression-level: 0 + retention-days: 30 + - name: Upload release verification metadata + uses: ./.gitea/actions/upload-artifact + with: + name: cutdex-release-metadata + path: .build/release-metadata/* + compression-level: 0 retention-days: 30 checks: name: Gitea CI passed @@ -85,7 +205,8 @@ jobs: needs: build runs-on: cutdex-windows-x64 steps: - - env: + - name: Verify CI result + env: RESULT: ${{ needs.build.result }} run: | if ($env:RESULT -ne 'success') { throw "App build: $env:RESULT" } diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index c8d9377..536b701 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -13,21 +13,116 @@ permissions: concurrency: group: cutdex-release cancel-in-progress: false +defaults: + run: + shell: pwsh +env: + PYTHONUTF8: '1' + GIT_CONFIG_COUNT: '2' + GIT_CONFIG_KEY_0: core.autocrlf + GIT_CONFIG_VALUE_0: 'false' + GIT_CONFIG_KEY_1: core.eol + GIT_CONFIG_VALUE_1: lf + RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }} + GITEA_REPOSITORY: ${{ gitea.repository }} jobs: - release: + prepare: + name: Prepare draft Release runs-on: cutdex-windows-x64 + outputs: + sha: ${{ steps.draft.outputs.sha }} + release-id: ${{ steps.draft.outputs.release-id }} + ci-run-id: ${{ steps.draft.outputs.ci-run-id }} + artifact-id: ${{ steps.draft.outputs.artifact-id }} + android-artifact-id: ${{ steps.draft.outputs.android-artifact-id }} + windows-artifact-id: ${{ steps.draft.outputs.windows-artifact-id }} + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} steps: - - uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - name: Check out release tag + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ gitea.event.inputs.tag || gitea.ref_name }} persist-credentials: false - - name: Publish validated Android and Windows packages - shell: pwsh - env: - GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} - GITEA_REPOSITORY: ${{ gitea.repository }} - RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }} + - name: Select successful CI and prepare draft + id: draft run: | $env:GITEA_SHA = git rev-parse HEAD - python tool/gitea/promote-release.py - if ($LASTEXITCODE -ne 0) { throw 'Release promotion failed.' } + if ($LASTEXITCODE -ne 0) { throw 'Release source resolution failed.' } + python tool/gitea/stage-release.py prepare-ci + if ($LASTEXITCODE -ne 0) { throw 'CI selection or draft preparation failed.' } + + android: + name: Upload Android to draft Release + needs: prepare + runs-on: cutdex-windows-x64 + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + GITEA_SHA: ${{ needs.prepare.outputs.sha }} + RELEASE_ID: ${{ needs.prepare.outputs.release-id }} + CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }} + CI_ARTIFACT_ID: ${{ needs.prepare.outputs.android-artifact-id }} + steps: + - name: Check out release commit + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ needs.prepare.outputs.sha }} + persist-credentials: false + - name: Download Android CI artifact + run: | + python tool/gitea/stage-release.py fetch-android --path .build/android + if ($LASTEXITCODE -ne 0) { throw 'android CI artifact download failed.' } + - name: Upload Android packages to draft + run: | + python tool/gitea/stage-release.py android --path .build/android + if ($LASTEXITCODE -ne 0) { throw 'android draft upload failed.' } + + windows: + name: Upload Windows to draft Release + needs: prepare + runs-on: cutdex-windows-x64 + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + GITEA_SHA: ${{ needs.prepare.outputs.sha }} + RELEASE_ID: ${{ needs.prepare.outputs.release-id }} + CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }} + CI_ARTIFACT_ID: ${{ needs.prepare.outputs.windows-artifact-id }} + steps: + - name: Check out release commit + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ needs.prepare.outputs.sha }} + persist-credentials: false + - name: Download Windows CI artifact + run: | + python tool/gitea/stage-release.py fetch-windows --path .build/windows + if ($LASTEXITCODE -ne 0) { throw 'windows CI artifact download failed.' } + - name: Upload Windows packages to draft + run: | + python tool/gitea/stage-release.py windows --path .build/windows + if ($LASTEXITCODE -ne 0) { throw 'windows draft upload failed.' } + + publish: + name: Verify and publish Release + needs: [prepare, android, windows] + runs-on: cutdex-windows-x64 + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + GITEA_SHA: ${{ needs.prepare.outputs.sha }} + RELEASE_ID: ${{ needs.prepare.outputs.release-id }} + CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }} + CI_ARTIFACT_ID: ${{ needs.prepare.outputs.artifact-id }} + steps: + - name: Check out release commit + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ needs.prepare.outputs.sha }} + persist-credentials: false + - name: Download release verification metadata + run: | + python tool/gitea/stage-release.py fetch-release --path dist + if ($LASTEXITCODE -ne 0) { throw 'CI verification metadata validation failed.' } + - name: Verify attachments and publish Release + run: | + python tool/gitea/stage-release.py publish --path dist + if ($LASTEXITCODE -ne 0) { throw 'Release publication failed.' } diff --git a/tool/gitea/package-app.py b/tool/gitea/package-app.py index 5128f94..f122ef7 100644 --- a/tool/gitea/package-app.py +++ b/tool/gitea/package-app.py @@ -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__': diff --git a/tool/gitea/prepare-build-cache.ps1 b/tool/gitea/prepare-build-cache.ps1 new file mode 100644 index 0000000..94ed9ec --- /dev/null +++ b/tool/gitea/prepare-build-cache.ps1 @@ -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" diff --git a/tool/gitea/prepare-package-tools.ps1 b/tool/gitea/prepare-package-tools.ps1 new file mode 100644 index 0000000..b1ce3e7 --- /dev/null +++ b/tool/gitea/prepare-package-tools.ps1 @@ -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 '(?' + + +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'' + + +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'^$', 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() diff --git a/tool/gitea/test_package_app.py b/tool/gitea/test_package_app.py new file mode 100644 index 0000000..5645576 --- /dev/null +++ b/tool/gitea/test_package_app.py @@ -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() diff --git a/tool/gitea/test_promote_release.py b/tool/gitea/test_promote_release.py deleted file mode 100644 index 36c55cd..0000000 --- a/tool/gitea/test_promote_release.py +++ /dev/null @@ -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() diff --git a/tool/gitea/test_release_artifacts.py b/tool/gitea/test_release_artifacts.py index 56e14c8..93c55b6 100644 --- a/tool/gitea/test_release_artifacts.py +++ b/tool/gitea/test_release_artifacts.py @@ -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() diff --git a/tool/gitea/test_stage_release.py b/tool/gitea/test_stage_release.py new file mode 100644 index 0000000..9ac3626 --- /dev/null +++ b/tool/gitea/test_stage_release.py @@ -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() diff --git a/tool/gitea/test_transfer_tools.py b/tool/gitea/test_transfer_tools.py new file mode 100644 index 0000000..a96719c --- /dev/null +++ b/tool/gitea/test_transfer_tools.py @@ -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() -- 2.54.0 From 8377e17ef15b99d4e70e41ef139e60f11a01ce81 Mon Sep 17 00:00:00 2001 From: lingjhf Date: Tue, 6 Oct 2026 14:07:09 +0800 Subject: [PATCH 04/10] fix(ci): package saved Windows builds without Flutter resolution --- .gitea/CI_PERFORMANCE.md | 3 +++ .gitea/workflows/ci.yml | 4 +++ tool/windows/test_windows_updates.py | 6 +++-- tool/windows/test_windows_updates_unit.py | 30 ++++++++++++++++++++++- tool/windows/windows_updates.py | 20 ++++++++++----- 5 files changed, 54 insertions(+), 9 deletions(-) diff --git a/.gitea/CI_PERFORMANCE.md b/.gitea/CI_PERFORMANCE.md index 7d35972..2a11e6c 100644 --- a/.gitea/CI_PERFORMANCE.md +++ b/.gitea/CI_PERFORMANCE.md @@ -24,6 +24,9 @@ the runner user's `%LOCALAPPDATA%/Cutdex/ci-tools/`. Later builds reuse them aft version checks. Python interpreter identity and tool versions isolate the cache, and a mutex protects installation across concurrent workflows. .NET setup remains in the Windows packaging job to provide SDK 10 and the runtime required by `vpk`. +The Windows build verifies that the resolved deskup native SDK matches the pinned +Velopack version before saving the app. Packaging imports no Flutter package +configuration and independently verifies the installed vpk version. APK and Windows package uploads use `compression-level: 0` to avoid recompressing already compressed artifacts. The saved Windows app uses compression level 1, diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index b6f7824..4ac9fad 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -113,6 +113,10 @@ jobs: Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue flutter build windows --no-pub --release --flavor production if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' } + - name: Verify native SDK matches pinned packaging tools + run: | + python tool/windows/windows_updates.py verify-sdk + if ($LASTEXITCODE -ne 0) { throw 'Windows native SDK version validation failed.' } - name: Save Windows app for independent packaging retries uses: ./.gitea/actions/upload-artifact with: diff --git a/tool/windows/test_windows_updates.py b/tool/windows/test_windows_updates.py index 18052ea..31f9d00 100644 --- a/tool/windows/test_windows_updates.py +++ b/tool/windows/test_windows_updates.py @@ -15,7 +15,7 @@ import sys import threading import time -from windows_updates import DESKUP_ROOT, ROOT, check_tool, pack_release, update_version, vpk_command +from windows_updates import ROOT, check_tool, pack_release, resolved_deskup, update_version, verify_sdk_version, vpk_command class TestHandler(SimpleHTTPRequestHandler): @@ -49,6 +49,8 @@ def main(): if work.exists(): parser.error('Use a new work directory so previous reports cannot pass this test') work.mkdir(parents=True) + deskup_root = resolved_deskup() + verify_sdk_version() command = vpk_command(args.vpk) check_tool(command) definitions = work / 'defines.json' @@ -67,7 +69,7 @@ def main(): 'name: cutdex_update_smoke\nversion: 1.0.0+1\n' 'environment:\n sdk: ^3.13.4\n' 'dependencies:\n flutter:\n sdk: flutter\n' - f' deskup:\n path: {DESKUP_ROOT.as_posix()}\n' + f' deskup:\n path: {deskup_root.as_posix()}\n' 'flutter:\n uses-material-design: true\n', encoding='utf-8') entry = source / 'tool/testing/windows_update_smoke.dart' entry.parent.mkdir(parents=True) diff --git a/tool/windows/test_windows_updates_unit.py b/tool/windows/test_windows_updates_unit.py index 5f94785..8a1a851 100644 --- a/tool/windows/test_windows_updates_unit.py +++ b/tool/windows/test_windows_updates_unit.py @@ -1,14 +1,42 @@ import hashlib +import importlib.util import json from pathlib import Path from unittest.mock import patch import tempfile import unittest -from windows_updates import resolved_deskup, numeric_version, pack_release, update_version, validate_previous, verify_manifest +from windows_updates import SDK_VERSION, check_tool, resolved_deskup, numeric_version, pack_release, update_version, validate_previous, verify_manifest, verify_sdk_version class UpdatePublicationTests(unittest.TestCase): + def test_packaging_module_imports_in_clean_checkout_without_flutter_config(self): + spec = importlib.util.spec_from_file_location('isolated_windows_updates', + Path(__file__).with_name('windows_updates.py')) + module = importlib.util.module_from_spec(spec) + with patch.object(Path, 'is_file', return_value=False): + spec.loader.exec_module(module) + self.assertEqual(module.SDK_VERSION, SDK_VERSION) + + def test_packaging_tool_check_does_not_resolve_flutter_dependencies(self): + from subprocess import CompletedProcess + with patch('windows_updates.resolved_deskup', side_effect=AssertionError('No Flutter config')), \ + patch('windows_updates.subprocess.run', return_value=CompletedProcess([], 0, f'vpk {SDK_VERSION}', '')): + check_tool(['vpk']) + + def test_build_sdk_check_rejects_mismatched_and_missing_versions(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + cmake = root / 'windows/velopack.cmake' + cmake.parent.mkdir() + with patch('windows_updates.resolved_deskup', return_value=root): + for contents in ('set(DESKUP_VELOPACK_VERSION "9.9.9")', ''): + cmake.write_text(contents) + with self.assertRaisesRegex(ValueError, 'Resolved deskup must use'): + verify_sdk_version() + cmake.write_text(f'set(DESKUP_VELOPACK_VERSION "{SDK_VERSION}")') + self.assertEqual(verify_sdk_version(), SDK_VERSION) + def test_deskup_is_located_from_resolved_package_config(self): with tempfile.TemporaryDirectory(prefix='deskup package ') as directory: root = Path(directory) diff --git a/tool/windows/windows_updates.py b/tool/windows/windows_updates.py index b31c25b..74569ef 100644 --- a/tool/windows/windows_updates.py +++ b/tool/windows/windows_updates.py @@ -15,6 +15,9 @@ from check_windows_release import audit from update_versions import numeric_version, update_version ROOT = Path(__file__).resolve().parents[2] +SDK_VERSION = '1.2.161' + + def resolved_deskup(): config = ROOT / '.dart_tool/package_config.json' if not config.is_file(): @@ -27,12 +30,13 @@ def resolved_deskup(): return Path(url2pathname(uri.path)) -DESKUP_ROOT = resolved_deskup() -DESKUP_VERSION = re.search(r'^version: ([^\s]+)', - (DESKUP_ROOT / 'pubspec.yaml').read_text(encoding='utf-8'), - re.MULTILINE).group(1) -SDK_VERSION = re.search(r'set\(DESKUP_VELOPACK_VERSION "([^"]+)"\)', - (DESKUP_ROOT / 'windows/velopack.cmake').read_text(encoding='utf-8')).group(1) +def verify_sdk_version(): + """Validate the resolved build SDK before saving the app for later packaging.""" + cmake = (resolved_deskup() / 'windows/velopack.cmake').read_text(encoding='utf-8') + match = re.search(r'set\(DESKUP_VELOPACK_VERSION "([^"]+)"\)', cmake) + if not match or match[1] != SDK_VERSION: + raise ValueError(f'Resolved deskup must use Velopack SDK {SDK_VERSION}') + return SDK_VERSION def vpk_command(path): @@ -145,6 +149,7 @@ def serve(directory, port): def main(): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest='command', required=True) + commands.add_parser('verify-sdk', help='Verify resolved native SDK before saving a build') pack = commands.add_parser('pack', help='Package a complete audited release; never uploads') pack.add_argument('--app', type=Path, required=True) pack.add_argument('--output', type=Path, required=True) @@ -156,8 +161,11 @@ def main(): args = parser.parse_args() try: if args.command == 'pack': + verify_sdk_version() print(json.dumps(package_app(args.app, args.output, args.vpk, development=args.development))) + elif args.command == 'verify-sdk': + print(f'Velopack SDK {verify_sdk_version()} verified') else: serve(args.directory, args.port) except KeyboardInterrupt: -- 2.54.0 From 2497865d0eed87b354a3af58c36c599395d6b181 Mon Sep 17 00:00:00 2001 From: lingjhf Date: Tue, 6 Oct 2026 14:14:15 +0800 Subject: [PATCH 05/10] test(windows): await workspace closure before deleting fixtures --- test/application_tools_test.dart | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/application_tools_test.dart b/test/application_tools_test.dart index b304354..395c6fe 100644 --- a/test/application_tools_test.dart +++ b/test/application_tools_test.dart @@ -126,9 +126,10 @@ void main() { .closeSource(); } await access.dispose(); - // UI/provider disposal owns the project; allow its async cleanup to finish. + // Provider disposal starts async cleanup without waiting for it. Close the + // workspace explicitly before deleting files, especially on Windows. + await container.read(projectsProvider.notifier).prepareToQuit(); container.dispose(); - await Future.delayed(const Duration(milliseconds: 50)); await root.delete(recursive: true); messenger.setMockMethodCallHandler(native, null); messenger.setMockMethodCallHandler(events, null); -- 2.54.0 From 933ace4e518b57bd242b3a492440f6ec398a303c Mon Sep 17 00:00:00 2001 From: lingjhf Date: Tue, 6 Oct 2026 14:16:32 +0800 Subject: [PATCH 06/10] fix(release): retry FRP tunnel reconnection responses --- .gitea/CI_PERFORMANCE.md | 2 ++ tool/gitea/release_transport.py | 5 +++++ tool/gitea/test_transfer_tools.py | 27 +++++++++++++++++++++++++++ 3 files changed, 34 insertions(+) diff --git a/.gitea/CI_PERFORMANCE.md b/.gitea/CI_PERFORMANCE.md index 2a11e6c..6ce0e28 100644 --- a/.gitea/CI_PERFORMANCE.md +++ b/.gitea/CI_PERFORMANCE.md @@ -56,6 +56,8 @@ the build job must still be rerun; it has no saved app to restore. Release attachment uploads retry temporary network errors, HTTP 408/429 and 500/502/503/504 up to three POST attempts per file, also with 5/15-second delays. +The specific FRP HTML "Not Found" page observed during tunnel reconnection is +also treated as temporary; ordinary Gitea API or HTML 404 responses still fail. Before retrying a POST, the uploader checks whether Gitea already saved the named attachment, including after the final response is lost. This avoids duplicate uploads after a timeout. Authorization, invalid-input and other permanent errors diff --git a/tool/gitea/release_transport.py b/tool/gitea/release_transport.py index fbe1d7c..5bc819a 100644 --- a/tool/gitea/release_transport.py +++ b/tool/gitea/release_transport.py @@ -17,6 +17,11 @@ RETRY_DELAYS = (5, 15) def transient(error): if isinstance(error, urllib.error.HTTPError): + if error.code == 404 and error.headers.get('Content-Type', '').split(';')[0].lower() == 'text/html': + body = error.read(64 * 1024).lower() + # FRP returns this page while the vhost tunnel is unavailable. + # A normal Gitea API 404 remains a permanent error. + return b'github.com/fatedier/frp' in body and b'not found' in body return error.code in {408, 429, 500, 502, 503, 504} return isinstance(error, (urllib.error.URLError, TimeoutError, ConnectionError, http.client.IncompleteRead)) diff --git a/tool/gitea/test_transfer_tools.py b/tool/gitea/test_transfer_tools.py index a96719c..39798bd 100644 --- a/tool/gitea/test_transfer_tools.py +++ b/tool/gitea/test_transfer_tools.py @@ -9,6 +9,33 @@ import release_transport as transfers class TransferToolsTests(unittest.TestCase): + def test_frp_tunnel_not_found_page_is_retried_as_a_temporary_failure(self): + calls = 0 + + def transport(url, data=None, method=None, content_type=None): + nonlocal calls + if method is None: + return [] + calls += 1 + if calls == 1: + body = b'

Not Found

frp' + raise urllib.error.HTTPError(url, 404, 'Not Found', + {'Content-Type': 'text/html; charset=utf-8'}, io.BytesIO(body)) + return {} + + with patch.object(transfers.time, 'sleep') as sleep: + transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport) + self.assertEqual(calls, 2) + sleep.assert_called_once_with(5) + + def test_ordinary_html_not_found_and_json_api_errors_are_not_retried(self): + for content_type, body in [('text/html', b'

Not Found

'), + ('application/json', b'Not Found github.com/fatedier/frp')]: + with self.subTest(content_type=content_type): + error = urllib.error.HTTPError('url', 404, 'Not Found', + {'Content-Type': content_type}, io.BytesIO(body)) + self.assertFalse(transfers.transient(error)) + def test_transient_upload_failure_retries_without_restarting_other_files(self): calls = [] -- 2.54.0 From e06590dc82ce782a7916b3e2972af76578ebf375 Mon Sep 17 00:00:00 2001 From: lingjhf Date: Tue, 6 Oct 2026 14:27:00 +0800 Subject: [PATCH 07/10] fix(ci): regenerate release plugin registrants before building --- .gitea/CI_PERFORMANCE.md | 4 ++++ .gitea/workflows/ci.yml | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.gitea/CI_PERFORMANCE.md b/.gitea/CI_PERFORMANCE.md index 6ce0e28..01a1ccf 100644 --- a/.gitea/CI_PERFORMANCE.md +++ b/.gitea/CI_PERFORMANCE.md @@ -14,6 +14,10 @@ enabled for CI. Do not clear these caches between runs. Each job must have its o checkout; do not share a Flutter `build/` or `.dart_tool/` directory between jobs. With an ephemeral runner, these user directories must be persisted separately. +Build commands keep Flutter's default Pub preparation after the explicit locked +resolution. Do not use `--no-pub`: Flutter also regenerates release plugin +registrants in that preparation, removing dev-only plugins such as integration_test. + The runner needs at least two execution slots. The local runner configuration at `D:/workspace/gitea-stack/runner/config.yaml` currently has `capacity: 2`. The host has 12 logical processors and approximately 16 GB RAM; the Android job retains its diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 4ac9fad..0471aae 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -79,7 +79,7 @@ jobs: $properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m') [IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`norg.gradle.caching=true`n") - name: Build production Android APK - run: flutter build apk --no-pub --release --flavor production --target-platform android-arm64,android-x64 + run: flutter build apk --release --flavor production --target-platform android-arm64,android-x64 - name: Upload Android CI artifact uses: ./.gitea/actions/upload-artifact with: @@ -111,7 +111,7 @@ jobs: - name: Build production Windows app run: | Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue - flutter build windows --no-pub --release --flavor production + flutter build windows --release --flavor production if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' } - name: Verify native SDK matches pinned packaging tools run: | -- 2.54.0 From 8e523f0e892bdf0d4e77c4721c6c2e4575548008 Mon Sep 17 00:00:00 2001 From: lingjhf Date: Tue, 6 Oct 2026 14:49:31 +0800 Subject: [PATCH 08/10] perf(ci): transfer artifacts locally instead of through FRP --- .gitea/CI_PERFORMANCE.md | 9 +++++ .gitea/actions/upload-artifact/action.yml | 6 +++ .gitea/workflows/ci.yml | 7 ++++ .gitea/workflows/release.yml | 1 + tool/gitea/release_transport.py | 17 ++++++++- tool/gitea/test_transfer_tools.py | 45 +++++++++++++++++++++++ 6 files changed, 83 insertions(+), 2 deletions(-) diff --git a/.gitea/CI_PERFORMANCE.md b/.gitea/CI_PERFORMANCE.md index 01a1ccf..e77a192 100644 --- a/.gitea/CI_PERFORMANCE.md +++ b/.gitea/CI_PERFORMANCE.md @@ -38,6 +38,15 @@ preserves nested and hidden runtime assets, and excludes the same debug files an optional workers omitted by packaging. The saved app, platform packages, compact metadata and validated release artifact all retain 30 days. +This host runs both Gitea and the runner. The workflows set +`CUTDEX_GITEA_INTERNAL_URL=http://127.0.0.1:3000` and override `ACTIONS_RESULTS_URL` +on artifact upload/download steps, so those transfers stay on the host instead of +looping through the public FRP tunnel. Release API uploads and byte verification +also use this loopback endpoint; tooling rewrites only the validated public Gitea +origin. The server's public URL remains `https://git.orangraph.com`, and the runner +registration is unchanged. These workflow labels require this shared-host layout; +configure a reachable private endpoint before using runners on other hosts. + Compare warm CI runs after the first cache fill. Measure checks, Android compile, Windows compile, packaging and artifact transfer separately. Total duration follows the slower platform branch, plus checks and final assembly; no fixed speedup is diff --git a/.gitea/actions/upload-artifact/action.yml b/.gitea/actions/upload-artifact/action.yml index 645bf42..a52892c 100644 --- a/.gitea/actions/upload-artifact/action.yml +++ b/.gitea/actions/upload-artifact/action.yml @@ -20,6 +20,8 @@ runs: id: first continue-on-error: true uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + env: + ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} with: name: ${{ inputs.name }} path: ${{ inputs.path }} @@ -37,6 +39,8 @@ runs: if: ${{ !cancelled() && steps.first.outcome == 'failure' }} continue-on-error: true uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + env: + ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} with: name: ${{ inputs.name }} path: ${{ inputs.path }} @@ -53,6 +57,8 @@ runs: id: third if: ${{ !cancelled() && steps.first.outcome == 'failure' && steps.second.outcome == 'failure' }} uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + env: + ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} with: name: ${{ inputs.name }} path: ${{ inputs.path }} diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 0471aae..d958953 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -13,6 +13,7 @@ concurrency: cancel-in-progress: true env: PYTHONUTF8: '1' + CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000 GIT_CONFIG_COUNT: '2' GIT_CONFIG_KEY_0: core.autocrlf GIT_CONFIG_VALUE_0: 'false' @@ -142,6 +143,8 @@ jobs: persist-credentials: false - name: Download saved Windows app uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + env: + ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} with: name: cutdex-windows-app path: build/windows/x64/production/runner/Release/ @@ -177,11 +180,15 @@ jobs: persist-credentials: false - name: Download Android CI artifact uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + env: + ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} with: name: cutdex-android-build path: build/app/outputs/flutter-apk/ - name: Download Windows CI artifact uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + env: + ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} with: name: cutdex-windows-build path: .build/windows-packages/ diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 536b701..a735b25 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -18,6 +18,7 @@ defaults: shell: pwsh env: PYTHONUTF8: '1' + CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000 GIT_CONFIG_COUNT: '2' GIT_CONFIG_KEY_0: core.autocrlf GIT_CONFIG_VALUE_0: 'false' diff --git a/tool/gitea/release_transport.py b/tool/gitea/release_transport.py index 5bc819a..d9e0f2b 100644 --- a/tool/gitea/release_transport.py +++ b/tool/gitea/release_transport.py @@ -15,6 +15,19 @@ SERVER = 'https://git.orangraph.com' RETRY_DELAYS = (5, 15) +def transport_url(url): + """Route this host's Gitea traffic locally when the runner opts in.""" + internal = os.environ.get('CUTDEX_GITEA_INTERNAL_URL', '').rstrip('/') + if not internal: + return url + if internal != 'http://127.0.0.1:3000': + raise ValueError('Unexpected internal Gitea endpoint') + parsed = urllib.parse.urlparse(url) + if parsed.scheme != 'https' or parsed.netloc != 'git.orangraph.com': + raise ValueError('Unexpected Gitea transport origin') + return urllib.parse.urlunparse(parsed._replace(scheme='http', netloc='127.0.0.1:3000')) + + def transient(error): if isinstance(error, urllib.error.HTTPError): if error.code == 404 and error.headers.get('Content-Type', '').split(';')[0].lower() == 'text/html': @@ -45,7 +58,7 @@ def request(url, data=None, method=None, content_type='application/json'): 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) + req = urllib.request.Request(transport_url(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 @@ -61,7 +74,7 @@ def attachment_url(asset): 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), + req = urllib.request.Request(transport_url(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): diff --git a/tool/gitea/test_transfer_tools.py b/tool/gitea/test_transfer_tools.py index 39798bd..2545d13 100644 --- a/tool/gitea/test_transfer_tools.py +++ b/tool/gitea/test_transfer_tools.py @@ -9,6 +9,51 @@ import release_transport as transfers class TransferToolsTests(unittest.TestCase): + def setUp(self): + environment = patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': ''}) + environment.start() + self.addCleanup(environment.stop) + + def test_local_api_transport_preserves_authenticated_request_and_public_identity(self): + class Response(io.BytesIO): + headers = {'Content-Type': 'application/json'} + + with patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': 'http://127.0.0.1:3000/', + 'GITEA_TOKEN': 'test-token'}), \ + patch.object(transfers.urllib.request, 'urlopen', return_value=Response(b'{"id":3}')) as open_url: + result = transfers.request(transfers.SERVER + '/api/v1/releases?name=a%20b', + data=b'package', method='POST', content_type='application/octet-stream') + request = open_url.call_args.args[0] + self.assertEqual(result, {'id': 3}) + self.assertEqual(request.full_url, 'http://127.0.0.1:3000/api/v1/releases?name=a%20b') + self.assertEqual(request.get_method(), 'POST') + self.assertEqual(request.get_header('Authorization'), 'token test-token') + self.assertEqual(request.data, b'package') + self.assertEqual(transfers.SERVER, 'https://git.orangraph.com') + + def test_local_verification_routes_validated_attachment_without_changing_its_public_url(self): + asset = {'browser_download_url': 'https://git.orangraph.com/attachments/example'} + with patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': 'http://127.0.0.1:3000', + 'GITEA_TOKEN': 'test-token'}), \ + patch.object(transfers.urllib.request, 'urlopen', return_value=io.BytesIO(b'app')) as open_url: + result = transfers.fingerprint(asset) + self.assertEqual(open_url.call_args.args[0].full_url, 'http://127.0.0.1:3000/attachments/example') + self.assertEqual(result['sha256'], hashlib.sha256(b'app').hexdigest()) + self.assertEqual(asset['browser_download_url'], 'https://git.orangraph.com/attachments/example') + + def test_local_transport_rejects_unexpected_endpoint_or_origin_before_sending_credentials(self): + for internal, url, message in [ + ('http://example.com:3000', transfers.SERVER + '/api/v1/releases', 'internal Gitea endpoint'), + ('http://127.0.0.1:3000', 'https://example.com/file', 'transport origin'), + ('http://127.0.0.1:3000', 'http://git.orangraph.com/file', 'transport origin'), + ]: + with self.subTest(internal=internal, url=url), \ + patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': internal, 'GITEA_TOKEN': 'test-token'}), \ + patch.object(transfers.urllib.request, 'urlopen') as open_url: + with self.assertRaisesRegex(ValueError, message): + transfers.request(url) + open_url.assert_not_called() + def test_frp_tunnel_not_found_page_is_retried_as_a_temporary_failure(self): calls = 0 -- 2.54.0 From 44cb452350d6e581b75ecd582d7f6d3f8754f686 Mon Sep 17 00:00:00 2001 From: lingjhf Date: Tue, 6 Oct 2026 15:07:28 +0800 Subject: [PATCH 09/10] fix(ci): install dotnet without admin access and preserve public release links --- .gitea/CI_PERFORMANCE.md | 3 +++ .gitea/workflows/ci.yml | 6 ++++++ tool/gitea/release_transport.py | 14 +++++++++++--- tool/gitea/test_transfer_tools.py | 2 ++ 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.gitea/CI_PERFORMANCE.md b/.gitea/CI_PERFORMANCE.md index e77a192..7a98aed 100644 --- a/.gitea/CI_PERFORMANCE.md +++ b/.gitea/CI_PERFORMANCE.md @@ -28,6 +28,9 @@ the runner user's `%LOCALAPPDATA%/Cutdex/ci-tools/`. Later builds reuse them aft version checks. Python interpreter identity and tool versions isolate the cache, and a mutex protects installation across concurrent workflows. .NET setup remains in the Windows packaging job to provide SDK 10 and the runtime required by `vpk`. +The .NET installation uses the runner user's `Cutdex/ci-tools/dotnet` directory +through `DOTNET_INSTALL_DIR` and `DOTNET_ROOT`, so setup needs no administrator +access and later jobs reuse the installed SDK and runtime. The Windows build verifies that the resolved deskup native SDK matches the pinned Velopack version before saving the app. Packaging imports no Flutter package configuration and independently verifies the installed vpk version. diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index d958953..1839eb9 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -148,6 +148,12 @@ jobs: with: name: cutdex-windows-app path: build/windows/x64/production/runner/Release/ + - name: Configure user .NET installation + run: | + $directory = Join-Path $env:LOCALAPPDATA 'Cutdex/ci-tools/dotnet' + [IO.Directory]::CreateDirectory($directory) | Out-Null + "DOTNET_INSTALL_DIR=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append + "DOTNET_ROOT=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append - name: Set up .NET SDK uses: https://github.com/actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 with: diff --git a/tool/gitea/release_transport.py b/tool/gitea/release_transport.py index d9e0f2b..7384f0d 100644 --- a/tool/gitea/release_transport.py +++ b/tool/gitea/release_transport.py @@ -53,12 +53,16 @@ def retry_read(operation): def request(url, data=None, method=None, content_type='application/json'): + endpoint = transport_url(url) headers = {'Authorization': 'token ' + os.environ['GITEA_TOKEN']} + if endpoint != url: + # Gitea constructs response links from Host, even when reached locally. + headers['Host'] = 'git.orangraph.com' if data is not None: headers['Content-Type'] = content_type if isinstance(data, dict): data = json.dumps(data).encode() - req = urllib.request.Request(transport_url(url), data=data, headers=headers, method=method) + req = urllib.request.Request(endpoint, 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 @@ -74,8 +78,12 @@ def attachment_url(asset): 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(transport_url(attachment_url(asset)), - headers={'Authorization': 'token ' + os.environ['GITEA_TOKEN']}) + url = attachment_url(asset) + endpoint = transport_url(url) + headers = {'Authorization': 'token ' + os.environ['GITEA_TOKEN']} + if endpoint != url: + headers['Host'] = 'git.orangraph.com' + req = urllib.request.Request(endpoint, headers=headers) with urllib.request.urlopen(req, timeout=300) as response: while chunk := response.read(1024 * 1024): sha256.update(chunk) diff --git a/tool/gitea/test_transfer_tools.py b/tool/gitea/test_transfer_tools.py index 2545d13..69f3d66 100644 --- a/tool/gitea/test_transfer_tools.py +++ b/tool/gitea/test_transfer_tools.py @@ -28,6 +28,7 @@ class TransferToolsTests(unittest.TestCase): self.assertEqual(request.full_url, 'http://127.0.0.1:3000/api/v1/releases?name=a%20b') self.assertEqual(request.get_method(), 'POST') self.assertEqual(request.get_header('Authorization'), 'token test-token') + self.assertEqual(request.get_header('Host'), 'git.orangraph.com') self.assertEqual(request.data, b'package') self.assertEqual(transfers.SERVER, 'https://git.orangraph.com') @@ -38,6 +39,7 @@ class TransferToolsTests(unittest.TestCase): patch.object(transfers.urllib.request, 'urlopen', return_value=io.BytesIO(b'app')) as open_url: result = transfers.fingerprint(asset) self.assertEqual(open_url.call_args.args[0].full_url, 'http://127.0.0.1:3000/attachments/example') + self.assertEqual(open_url.call_args.args[0].get_header('Host'), 'git.orangraph.com') self.assertEqual(result['sha256'], hashlib.sha256(b'app').hexdigest()) self.assertEqual(asset['browser_download_url'], 'https://git.orangraph.com/attachments/example') -- 2.54.0 From f97d8bcb90ce400bc279c481a423a6fa3d80ea6b Mon Sep 17 00:00:00 2001 From: lingjhf Date: Tue, 6 Oct 2026 16:06:40 +0800 Subject: [PATCH 10/10] perf(ci): check out exact source through local Gitea --- .gitea/CI_PERFORMANCE.md | 3 +++ .gitea/workflows/ci.yml | 5 +++++ .gitea/workflows/release.yml | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/.gitea/CI_PERFORMANCE.md b/.gitea/CI_PERFORMANCE.md index 7a98aed..311a8f1 100644 --- a/.gitea/CI_PERFORMANCE.md +++ b/.gitea/CI_PERFORMANCE.md @@ -49,6 +49,9 @@ also use this loopback endpoint; tooling rewrites only the validated public Gite origin. The server's public URL remains `https://git.orangraph.com`, and the runner registration is unchanged. These workflow labels require this shared-host layout; configure a reachable private endpoint before using runners on other hosts. +Checkout uses the same endpoint through its `github-server-url` input, retaining +the requested commit/tag and disabling persisted credentials. Release requests +retain the public Host header so Gitea response links pass the public-origin checks. Compare warm CI runs after the first cache fill. Measure checks, Android compile, Windows compile, packaging and artifact transfer separately. Total duration follows diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 1839eb9..887ca84 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -31,6 +31,7 @@ jobs: uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Configure persistent build caches run: ./tool/gitea/prepare-build-cache.ps1 - name: Verify Flutter version and configure Java @@ -64,6 +65,7 @@ jobs: uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Configure persistent build caches run: ./tool/gitea/prepare-build-cache.ps1 - name: Verify Flutter version and configure Java @@ -101,6 +103,7 @@ jobs: uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Configure persistent build caches run: ./tool/gitea/prepare-build-cache.ps1 - name: Verify Flutter version @@ -141,6 +144,7 @@ jobs: uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Download saved Windows app uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 env: @@ -184,6 +188,7 @@ jobs: uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Download Android CI artifact uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 env: diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index a735b25..236c7e9 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -45,6 +45,7 @@ jobs: with: ref: ${{ gitea.event.inputs.tag || gitea.ref_name }} persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Select successful CI and prepare draft id: draft run: | @@ -69,6 +70,7 @@ jobs: with: ref: ${{ needs.prepare.outputs.sha }} persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Download Android CI artifact run: | python tool/gitea/stage-release.py fetch-android --path .build/android @@ -94,6 +96,7 @@ jobs: with: ref: ${{ needs.prepare.outputs.sha }} persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Download Windows CI artifact run: | python tool/gitea/stage-release.py fetch-windows --path .build/windows @@ -119,6 +122,7 @@ jobs: with: ref: ${{ needs.prepare.outputs.sha }} persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Download release verification metadata run: | python tool/gitea/stage-release.py fetch-release --path dist -- 2.54.0