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)