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()