From 7e2d4ddba1a78ca522e76c90b69aec067825d21d Mon Sep 17 00:00:00 2001 From: selikhov Date: Sun, 4 Oct 2026 18:07:21 +0300 Subject: [PATCH] ci fixes Signed-off-by: selikhov --- .gitea/actions/checks/action.yml | 62 +++++ .gitea/workflows/ci.yml | 36 +++ .gitea/workflows/release.yml | 110 +++++++++ .github/actions/system-deps/action.yml | 11 +- .github/workflows/ci.yml | 39 +++- .github/workflows/release.yml | 21 +- Cargo.toml | 9 +- android/app/build.gradle.kts | 2 +- crates/voelin-gateway/Dockerfile | 1 + docker/android.Dockerfile | 7 +- docker/linux.Dockerfile | 2 + docker/windows.Dockerfile | 2 + docs/building.md | 11 + docs/ci.md | 146 ++++++++++++ docs/release.md | 46 ++++ .../flatpak/io.github.faumaray.Voelin.yml | 3 + scripts/flatpak-build.sh | 36 +++ scripts/gitea-release.sh | 162 +++++++++++++ scripts/test-gitea-release.py | 221 ++++++++++++++++++ 19 files changed, 901 insertions(+), 26 deletions(-) create mode 100644 .gitea/actions/checks/action.yml create mode 100644 .gitea/workflows/ci.yml create mode 100644 .gitea/workflows/release.yml create mode 100644 docs/ci.md create mode 100755 scripts/flatpak-build.sh create mode 100755 scripts/gitea-release.sh create mode 100644 scripts/test-gitea-release.py diff --git a/.gitea/actions/checks/action.yml b/.gitea/actions/checks/action.yml new file mode 100644 index 0000000..f22b828 --- /dev/null +++ b/.gitea/actions/checks/action.yml @@ -0,0 +1,62 @@ +name: Linux checks +description: Shared Linux validation for Gitea CI and release packaging. +runs: + using: composite + steps: + - uses: ./.github/actions/system-deps + - name: Install pinned Rust toolchain + run: | + set -euo pipefail + export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}" + export PATH="$CARGO_HOME/bin:$PATH" + if ! command -v rustup >/dev/null 2>&1; then + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \ + sh -s -- -y --profile minimal --default-toolchain none + fi + if [[ -f "$CARGO_HOME/env" ]]; then + # shellcheck source=/dev/null + source "$CARGO_HOME/env" + fi + echo "$CARGO_HOME/bin" >> "$GITHUB_PATH" + rustup toolchain install + shell: bash + - name: rustfmt (own crates) + run: | + set -euo pipefail + packages=$(scripts/own-crates.sh) + read -r -a packages <<< "$packages" + cargo fmt "${packages[@]}" --check + shell: bash + - name: clippy (own crates, deny warnings) + run: | + set -euo pipefail + packages=$(scripts/own-crates.sh) + read -r -a packages <<< "$packages" + cargo clippy "${packages[@]}" --all-targets --no-deps --locked -- -D warnings + shell: bash + - name: clippy (workspace, report warnings) + run: cargo clippy --workspace --all-targets --locked + shell: bash + - name: Build + run: cargo build --workspace --all-targets --locked + shell: bash + - name: Test (X11 enabled) + run: | + # DISPLAY is assigned by xvfb-run, then expanded by the inner shell. + # shellcheck disable=SC2016 + xvfb-run -a bash -c 'VOELIN_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked' + shell: bash + - name: Install cargo-deny and cargo-about + run: | + cargo install cargo-deny --locked --version 0.20.2 + cargo install cargo-about --locked --version 0.9.2 --features cli + shell: bash + - name: Dependency policy + run: cargo deny --locked --workspace check + shell: bash + - name: Third-party notices + run: scripts/notices.sh --check + shell: bash + - name: Release tooling regressions + run: python3 scripts/test-gitea-release.py + shell: bash diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..1aea1ea --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,36 @@ +name: CI + +# Linux checks for Gitea act_runner; runner setup and scope: docs/ci.md. +on: + push: + branches: [main, master] + paths: + - "**" + - "!docs/**" + - "!**/*.md" + - "THIRD_PARTY_NOTICES.md" + pull_request: + paths: + - "**" + - "!docs/**" + - "!**/*.md" + - "THIRD_PARTY_NOTICES.md" + workflow_dispatch: + +env: + CARGO_TERM_COLOR: always + CARGO_BUILD_JOBS: "1" + CARGO_INCREMENTAL: "0" + RUST_BACKTRACE: "0" + +jobs: + linux: + name: Linux checks + runs-on: ubuntu-24.04 + timeout-minutes: 180 + defaults: + run: + shell: bash + steps: + - uses: https://github.com/actions/checkout@v4 + - uses: ./.gitea/actions/checks diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..30b9b45 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,110 @@ +name: Release + +# Complete package set, built on a dedicated trusted host; see docs/ci.md. +# Manual runs upload artifacts only. v* tags also create a draft release. +on: + push: + tags: ["v*"] + workflow_dispatch: + +env: + CARGO_TERM_COLOR: always + CARGO_BUILD_JOBS: "1" + CARGO_INCREMENTAL: "0" + RUST_BACKTRACE: "0" + +jobs: + package: + name: packages + draft release + # Native host, not the untrusted-PR CI container: Docker and Flatpak need + # host privileges. Register only for this repository; capacity must be 1. + runs-on: voelin-release + timeout-minutes: 480 + defaults: + run: + shell: bash + steps: + - uses: https://github.com/actions/checkout@v4 + with: + persist-credentials: false + - uses: ./.gitea/actions/checks + - name: Check release tools + run: | + set -euo pipefail + command -v docker python3 + docker info >/dev/null + # Remove only output owned by this workflow in its checkout. + rm -rf dist + - name: Linux packages + run: scripts/docker-build.sh linux --progress=plain + - name: Windows packages (MinGW) + run: scripts/docker-build.sh windows --progress=plain + - name: Android debug APK + run: scripts/docker-build.sh android --progress=plain + - name: Android release APK (signed, optional) + env: + KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + VOELIN_SIGNING_STORE_PASSWORD: ${{ secrets.VOELIN_SIGNING_STORE_PASSWORD }} + VOELIN_SIGNING_KEY_ALIAS: ${{ secrets.VOELIN_SIGNING_KEY_ALIAS }} + VOELIN_SIGNING_KEY_PASSWORD: ${{ secrets.VOELIN_SIGNING_KEY_PASSWORD }} + run: | + set -euo pipefail + if [[ -z "$KEYSTORE_BASE64" ]]; then + echo "No ANDROID_KEYSTORE_BASE64: debug APK only" + exit 0 + fi + : "${VOELIN_SIGNING_STORE_PASSWORD:?Missing Android store password}" + : "${VOELIN_SIGNING_KEY_ALIAS:?Missing Android key alias}" + : "${VOELIN_SIGNING_KEY_PASSWORD:?Missing Android key password}" + umask 077 + signing=$(mktemp -d "$RUNNER_TEMP/voelin-signing.XXXXXX") + trap 'rm -rf "$signing"' EXIT + signing=$(cd "$signing" && pwd -P) + [[ "$signing" != "$(pwd -P)/"* ]] || { echo "RUNNER_TEMP must be outside the checkout" >&2; exit 1; } + export SIGNING_ENV="$signing/signing.env" + printf '%s' "$KEYSTORE_BASE64" | base64 -d > "$signing/release.jks" + # The Dockerfile sources this with /bin/sh; quote arbitrary secret + # values as POSIX shell data, never interpolate them into code. + python3 - <<'PY' + import os, shlex + from pathlib import Path + names = ("VOELIN_SIGNING_STORE_PASSWORD", "VOELIN_SIGNING_KEY_ALIAS", "VOELIN_SIGNING_KEY_PASSWORD") + Path(os.environ["SIGNING_ENV"]).write_text("".join(f"{name}={shlex.quote(os.environ[name])}\n" for name in names)) + PY + scripts/docker-build.sh android --progress=plain --build-arg APK=release \ + --build-arg "SIGNING_CACHE_BUST=$(basename "$signing")" \ + --secret "id=keystore,src=$signing/release.jks" \ + --secret "id=signing,src=$SIGNING_ENV" + - name: Flatpak bundle + run: scripts/flatpak-build.sh dist/flatpak + - name: Gateway container image + run: | + set -euo pipefail + version=$(sed -n 's/^version = "\(.*\)"$/\1/p' crates/voelin-gateway/Cargo.toml | head -n 1) + test -n "$version" + docker build -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest . + mkdir -p dist/gateway + docker save "tsgw:$version" tsgw:latest | gzip > dist/gateway/tsgw-image.tar.gz + - name: Collect packages and checksums + run: | + set -euo pipefail + mkdir -p dist/release + for file in dist/{linux,windows,android,flatpak,gateway}/*; do + [[ -f "$file" && ! -L "$file" ]] || { echo "Missing package: $file" >&2; exit 1; } + name=$(basename "$file") + [[ "$name" != SHA256SUMS* ]] || continue + [[ ! -e "dist/release/$name" ]] || { echo "Duplicate package: $name" >&2; exit 1; } + cp -- "$file" "dist/release/$name" + done + (cd dist/release && sha256sum -- * > SHA256SUMS) + # Gitea-compatible artifact API (Node 20), not stock GitHub artifact v4. + - uses: https://gitea.com/actions/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 + with: + name: voelin-packages + path: dist/release/ + if-no-files-found: error + - name: Draft Gitea release + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') + env: + GITEA_RELEASE_TOKEN: ${{ secrets.GITEA_RELEASE_TOKEN }} + run: scripts/gitea-release.sh dist/release diff --git a/.github/actions/system-deps/action.yml b/.github/actions/system-deps/action.yml index 0d3b031..bb10f50 100644 --- a/.github/actions/system-deps/action.yml +++ b/.github/actions/system-deps/action.yml @@ -19,11 +19,16 @@ runs: # (video codecs), PipeWire + SPA (screen and audio capture), libclang # (bindgen), Xvfb (X11 tests). run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends \ + # Gitea container runners may run as root and need the base build + # tools that GitHub's hosted images already provide. + sudo=() + if [ "$(id -u)" -ne 0 ]; then sudo=(sudo); fi + "${sudo[@]}" apt-get update + "${sudo[@]}" apt-get install -y --no-install-recommends \ + build-essential ca-certificates cmake curl git jq pkg-config python3 \ libasound2-dev libfontconfig1-dev libxkbcommon-dev \ libvpx-dev libdav1d-dev libpipewire-0.3-dev libspa-0.2-dev libclang-dev \ - xvfb + xvfb xauth # aws-lc-sys (WebRTC DTLS through str0m) assembles with NASM on Windows. - name: NASM diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1cc4b5..6b4ef11 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,6 +32,9 @@ concurrency: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: "0" + # In particular, do not compile the generated UI lib and lib-test together. + CARGO_BUILD_JOBS: "1" + CARGO_INCREMENTAL: "0" jobs: lint: @@ -47,11 +50,17 @@ jobs: # and have known clippy findings (cleanup is milestone M1), so the strict # checks cover our own crates only. - name: rustfmt (own crates) - run: cargo fmt $(scripts/own-crates.sh) --check + run: | + packages=$(scripts/own-crates.sh) + read -r -a packages <<< "$packages" + cargo fmt "${packages[@]}" --check - name: clippy (own crates, deny warnings) - run: cargo clippy $(scripts/own-crates.sh) --all-targets --no-deps -- -D warnings + run: | + packages=$(scripts/own-crates.sh) + read -r -a packages <<< "$packages" + cargo clippy "${packages[@]}" --all-targets --no-deps --locked -- -D warnings - name: clippy (workspace, report only) - run: cargo clippy --workspace --all-targets + run: cargo clippy --workspace --all-targets --locked # Under Xvfb, so X11 tests (screen capture, global hotkeys through XTEST # input) run instead of skipping. Windows tests run in release.yml. @@ -67,7 +76,10 @@ jobs: - name: Build run: cargo build --workspace --all-targets --locked - name: Test - run: xvfb-run -a bash -c 'VOELIN_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked' + run: | + # DISPLAY is assigned by xvfb-run, then expanded by the inner shell. + # shellcheck disable=SC2016 + xvfb-run -a bash -c 'VOELIN_X11_TEST_DISPLAY="$DISPLAY" cargo test --workspace --locked' # Windows-only code compiles and is lint-clean (MSVC, libvpx from vcpkg). clippy-windows: @@ -81,7 +93,10 @@ jobs: - uses: Swatinem/rust-cache@v2 - name: clippy (own crates, deny warnings) shell: bash - run: cargo clippy $(scripts/own-crates.sh) --all-targets --no-deps --locked -- -D warnings + run: | + packages=$(scripts/own-crates.sh) + read -r -a packages <<< "$packages" + cargo clippy "${packages[@]}" --all-targets --no-deps --locked -- -D warnings # The Android-only code (docs/android.md), for the Android target. The APKs # are built by release.yml. @@ -106,13 +121,17 @@ jobs: java-version: 17 - name: Android SDK packages run: | - yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null + # sdkmanager closes stdin after the last license; ignore only yes's + # SIGPIPE, not a failure from sdkmanager (also works with pipefail). + yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null || test "${PIPESTATUS[1]}" -eq 0 "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \ "ndk;$NDK_VERSION" "platforms;android-36" > /dev/null - echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV" - # CMake (libopus) and Slint's Java helper. - echo "ANDROID_NDK_ROOT=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV" - echo "ANDROID_JAR=$ANDROID_HOME/platforms/android-36/android.jar" >> "$GITHUB_ENV" + { + echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/$NDK_VERSION" + # CMake (libopus) and Slint's Java helper. + echo "ANDROID_NDK_ROOT=$ANDROID_HOME/ndk/$NDK_VERSION" + echo "ANDROID_JAR=$ANDROID_HOME/platforms/android-36/android.jar" + } >> "$GITHUB_ENV" - name: Install cargo-ndk run: cargo install cargo-ndk --locked --version 4.1.2 - name: clippy (Android target, deny warnings) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9ef67cc..6559f9a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,6 +21,8 @@ permissions: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: "0" + CARGO_BUILD_JOBS: "1" + CARGO_INCREMENTAL: "0" jobs: # The same checks as every push (lint, Linux tests, Windows and Android @@ -177,13 +179,17 @@ jobs: java-version: 17 - name: Android SDK packages run: | - yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null + # Ignore yes's SIGPIPE when sdkmanager closes stdin, but preserve + # sdkmanager failures under bash -o pipefail. + yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null || test "${PIPESTATUS[1]}" -eq 0 "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \ "ndk;$NDK_VERSION" "platforms;android-36" "build-tools;36.0.0" > /dev/null - echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV" - # CMake (libopus) and Slint's Java helper. - echo "ANDROID_NDK_ROOT=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV" - echo "ANDROID_JAR=$ANDROID_HOME/platforms/android-36/android.jar" >> "$GITHUB_ENV" + { + echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/$NDK_VERSION" + # CMake (libopus) and Slint's Java helper. + echo "ANDROID_NDK_ROOT=$ANDROID_HOME/ndk/$NDK_VERSION" + echo "ANDROID_JAR=$ANDROID_HOME/platforms/android-36/android.jar" + } >> "$GITHUB_ENV" - name: Install cargo-ndk run: cargo install cargo-ndk --locked --version 4.1.2 - name: Debug APK @@ -203,9 +209,10 @@ jobs: exit 0 fi export VOELIN_SIGNING_STORE_FILE="$RUNNER_TEMP/release.jks" + trap 'rm -f "$VOELIN_SIGNING_STORE_FILE"' EXIT + umask 077 echo "$KEYSTORE_BASE64" | base64 -d > "$VOELIN_SIGNING_STORE_FILE" ./gradlew --no-daemon assembleRelease -Pvoelin.abis=arm64-v8a,x86_64 - rm -f "$VOELIN_SIGNING_STORE_FILE" - name: Package run: scripts/package.sh android dist - uses: actions/upload-artifact@v4 @@ -236,7 +243,7 @@ jobs: - name: Checksums run: | cd dist - rm -f SHA256SUMS-* + rm -f SHA256SUMS SHA256SUMS-* sha256sum -- * > SHA256SUMS - uses: softprops/action-gh-release@v2 with: diff --git a/Cargo.toml b/Cargo.toml index e85f785..db62918 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -140,10 +140,11 @@ debug = false dimpl = { path = "third_party/dimpl" } [profile.release] -# One optimisation unit across all crates: inlining across crate boundaries -# matters for the per-pixel and per-packet code of streams. Panics still +# Thin LTO keeps cross-crate optimisation without materialising the entire +# app in one LLVM module. Split codegen keeps the generated Slint UI within +# the memory budget of CI and release builders. Panics still # unwind (no `panic = "abort"`): a panic in one tokio task or media thread # must not end the app (tasks and threads report it, mutexes recover from # poisoning), and the crash reporter's hook runs either way. -lto = "fat" -codegen-units = 1 +lto = "thin" +codegen-units = 16 diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 4612f00..824e483 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -109,7 +109,7 @@ for ((buildType, release) in listOf("debug" to false, "release" to true)) { workingDir = workspace val command = mutableListOf("cargo", "ndk", "--platform", "29", "-o", out.get().asFile.path) abis.forEach { command += listOf("-t", it) } - command += listOf("build", "-p", "voelin-android") + command += listOf("build", "--locked", "-p", "voelin-android") if (release) command += "--release" commandLine(command) val ndk = android.ndkDirectory.path diff --git a/crates/voelin-gateway/Dockerfile b/crates/voelin-gateway/Dockerfile index 1a997f4..ac5e3c4 100644 --- a/crates/voelin-gateway/Dockerfile +++ b/crates/voelin-gateway/Dockerfile @@ -1,6 +1,7 @@ # Build: docker build -f crates/voelin-gateway/Dockerfile -t tsgw . # Run: docker run -v ./tsgw.toml:/etc/tsgw/tsgw.toml -p 7788:7788 tsgw FROM rust:1.94-bookworm AS build +ENV CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0 WORKDIR /src RUN apt-get update && apt-get install -y --no-install-recommends cmake libasound2-dev && rm -rf /var/lib/apt/lists/* COPY . . diff --git a/docker/android.Dockerfile b/docker/android.Dockerfile index 2ac9985..ca9770d 100644 --- a/docker/android.Dockerfile +++ b/docker/android.Dockerfile @@ -18,6 +18,8 @@ # unsigned. FROM ubuntu:24.04 AS toolchain +# Serial builds keep the generated Slint UI within the CI memory budget. +ENV CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0 ARG DEBIAN_FRONTEND=noninteractive # JDK 17 (Gradle, the Android Gradle plugin), CMake + Ninja (the bundled libopus). RUN apt-get update && apt-get install -y --no-install-recommends \ @@ -79,6 +81,9 @@ FROM toolchain AS build ARG ABIS=arm64-v8a,x86_64 # debug (installable as is) or release (signed with the build secrets). ARG APK=debug +# BuildKit secrets do not invalidate cached RUN steps. A signed CI build +# supplies a fresh non-secret nonce so a rotated key cannot reuse an old APK. +ARG SIGNING_CACHE_BUST=unsigned WORKDIR /src COPY . . RUN --mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry \ @@ -86,7 +91,7 @@ RUN --mount=type=cache,id=voelin-cargo-registry,target=/usr/local/cargo/registry --mount=type=cache,id=voelin-gradle,target=/root/.gradle \ --mount=type=secret,id=keystore,required=false \ --mount=type=secret,id=signing,required=false \ - set -e; \ + set -e; : "$SIGNING_CACHE_BUST"; \ if [ "$APK" = release ] && [ -f /run/secrets/keystore ]; then \ export VOELIN_SIGNING_STORE_FILE=/run/secrets/keystore; \ set -a; . /run/secrets/signing; set +a; \ diff --git a/docker/linux.Dockerfile b/docker/linux.Dockerfile index efb3e92..1ce37cf 100644 --- a/docker/linux.Dockerfile +++ b/docker/linux.Dockerfile @@ -11,6 +11,8 @@ # live in cache mounts, so rebuilds are incremental. FROM ubuntu:24.04 AS toolchain +# Serial builds keep the generated Slint UI within the CI memory budget. +ENV CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0 ARG DEBIAN_FRONTEND=noninteractive # The same libraries as CI (.github/actions/system-deps), plus dpkg-dev for # the .deb's dependencies. diff --git a/docker/windows.Dockerfile b/docker/windows.Dockerfile index 3233179..4a2ae86 100644 --- a/docker/windows.Dockerfile +++ b/docker/windows.Dockerfile @@ -11,6 +11,8 @@ # on Windows 10 and 11. Unsigned, like CI's (signing: docs/release.md). FROM ubuntu:24.04 AS toolchain +# Serial builds keep the generated Slint UI within the CI memory budget. +ENV CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0 ARG DEBIAN_FRONTEND=noninteractive # mingw-w64 (C compiler and linker), NASM (aws-lc and libvpx assembly), CMake # (the bundled libopus, aws-lc), NSIS (the installer), zip. diff --git a/docs/building.md b/docs/building.md index 82a4c7b..f227b9b 100644 --- a/docs/building.md +++ b/docs/building.md @@ -30,6 +30,13 @@ signed with a debug key (fine for testing, not for the Play Store). The gateway's image can also be built directly: `docker build -f crates/voelin-gateway/Dockerfile -t tsgw .`. +Gitea at [git.faumaray.ru](https://git.faumaray.ru) builds the same package +types through `.gitea/workflows/release.yml`: manual runs produce one +`voelin-packages` artifact; `v*` tag pushes also attach the packages to a +draft release. Windows packages there use MinGW rather than MSVC. See +[Gitea releases](release.md#gitea-releases) for signing and publishing, +and [runner setup](ci.md#gitea-release-runner) for host requirements. + ## From releases `.github/workflows/release.yml` builds every package: @@ -109,3 +116,7 @@ the proxy is on localhost. If the proxy inspects TLS, set - **Android:** [android.md](android.md) (SDK, NDK, cargo-ndk), then `cd android && ./gradlew assembleDebug` and `scripts/package.sh android`. - **Flatpak:** [packaging/README.md](../packaging/README.md#flatpak). + On a trusted machine with rootful Docker, + `scripts/flatpak-build.sh` writes `dist/flatpak/voelin.flatpak` using the + release builder image. It requires a privileged container for Flatpak's + nested sandbox; do not use it on an untrusted build host. diff --git a/docs/ci.md b/docs/ci.md new file mode 100644 index 0000000..11effd7 --- /dev/null +++ b/docs/ci.md @@ -0,0 +1,146 @@ +# CI + +GitHub Actions runs `.github/workflows/ci.yml`, including Linux checks, +Windows and Android Clippy, and TeamSpeak integration smoke tests. Both +GitHub and Gitea provide release packaging; see [release.md](release.md) and +[building.md](building.md). + +Cargo builds use one job in CI so the generated UI library and its test +target do not compile concurrently. The release profile uses ThinLTO and +16 codegen units instead of fat LTO and one unit, reducing peak compiler +memory while retaining optimised builds and panic unwinding. Flatpak sets +the Cargo job limit inside its build sandbox as well. This trades some +whole-program optimisation for lower build-memory requirements; release +runtime performance has not been benchmarked for this change. + +## Gitea Actions + +`.gitea/workflows/ci.yml` runs a single Linux job on pushes to `main` and +`master`, pull requests, and manual dispatch. Documentation-only changes +are excluded; `THIRD_PARTY_NOTICES.md` is not excluded because the app embeds +it and CI verifies it. + +The job runs: + +- formatting and warnings-as-errors Clippy for our crates; +- workspace Clippy (vendored warnings are reported, compilation errors fail); +- a locked workspace all-targets build and workspace tests under Xvfb; +- cargo-deny 0.20.2 workspace policy checks and the cargo-about 0.9.2 notices check; +- offline regression tests of the Gitea draft-release uploader. + +The workspace tests are not disabled. Xvfb supplies the display for X11 +capture and hotkey tests. This is Linux CI, not parity with every GitHub job: +it does not run Windows/Android checks, Docker-based TeamSpeak smoke tests, +opt-in browser interop, or package builds. Gitea release packaging runs in +the separate `release.yml` workflow below. + +### Runner setup + +1. Enable Actions on the Gitea instance and in the repository settings. +2. Register an **x86_64 Linux** `act_runner` with a Docker-capable host and + this label (the left side must match the workflow's `runs-on`): + + ```text + ubuntu-24.04:docker://ghcr.io/catthehacker/ubuntu:act-24.04 + ``` + + Configure this in the runner's labels when registering/configuring it; + an `ubuntu-latest` label alone does not match. The job image must provide + Bash, Git, Node.js for checkout v4, and root or passwordless sudo for apt. +3. Allow network access from the runner and job container to the Gitea + instance, GitHub (checkout action, dependencies and RustSec advisories), + GHCR (runner image), Ubuntu apt mirrors, rustup distribution servers, + crates.io and dependency/license sources used by cargo-about. +4. Provision enough RAM, swap and free disk for a full Slint workspace build + plus cargo-deny/cargo-about compilation. These are large builds; monitor + the first run and size the runner accordingly. The workflow limits Cargo + to one build job, disables incremental compilation, and reuses build + outputs between steps in one job. It does not create swap or modify the + Gitea host. +5. The workflow requests a three-hour job timeout. Legacy `act_runner` + versions ignore `timeout-minutes`; configure their runner-level limit + in the runner configuration instead: + + ```yaml + runner: + timeout: 3h + ``` + + Newer `gitea-runner` (2.0+) supports the workflow-level timeout. Check + the installed runner's configuration rather than assuming the YAML + timeout is enforced. + +The workflow shares the repository's local system-dependencies action with +GitHub CI and bootstraps rustup if absent, then installs the toolchain and +components pinned in `rust-toolchain.toml`. Checkout uses a fully qualified +GitHub action URL rather than depending on the instance's action-source +configuration. + +No GitHub cache/artifact service or reusable-workflow support is required. +The job does not need a Docker socket mounted inside its container; the +runner itself still needs Docker access to start that container. Keep this +runner isolated from production services and credentials, particularly when +accepting untrusted pull requests. No release signing or publishing secrets +are needed. + +After registering the runner, dispatch **CI** in Gitea Actions and inspect +all step results. Local YAML/shell checks do not prove that a particular +Gitea instance, runner registration, network policy or resource allocation +can complete this job. + +### Gitea release runner + +The instance at `https://git.faumaray.ru` reported Gitea **1.25.4** on +2026-10-04. Release publishing uses its REST API; artifact upload uses the +pinned Gitea artifact-action fork, not stock GitHub upload-artifact v4. + +Register a separate **repository-scoped**, **x86_64 Ubuntu 24.04 native +host** runner with the label: + +```text +voelin-release:host +``` + +Provision Bash, Git, Node.js 20+, Python 3.11+, curl, tar, gzip and rootful +Docker 23+ with BuildKit. Use **act_runner 0.2.7 or newer** (prefer the latest +maintained release), or gitea-runner 2+. Older act_runner does not provide +`ACTIONS_RESULTS_URL`, which the pinned artifact action needs. Register the +runner against `https://git.faumaray.ru`, reachable from both the host and +build containers. Gitea 1.25.4 provides the required artifact-v4 API. +The shared checks install native build dependencies +through root or passwordless sudo and bootstrap Rust. Docker builds install +Windows cross-toolchains, Android SDK/NDK and Java themselves; no Windows +runner or preinstalled Android SDK is needed. The Flatpak builder runs a +privileged container using the same Freedesktop 25.08 image as GitHub. +Allow network access to the existing CI sources, Flathub, Google's Android +downloads/Maven, Chromium's libvpx git server, Docker Hub, GHCR and the +gateway image's distroless base at GCR. Configure Gitea release attachment +types/size limits and reverse-proxy upload limits for the APKs, Flatpak and +gateway image; artifact and release storage must fit the full package set. + +This host is not the container runner used for pull requests. Restrict it +to this repository's trusted release workflow, protect `v*` tags, and only +dispatch trusted branches. Do not advertise this label on an instance-wide +runner that untrusted repositories or PR workflows can select. Docker and +Flatpak privileges effectively grant host access. Use an isolated machine +with no production services or credentials. + +Configure **one release runner**, with capacity 1, so runs do not race: + +```yaml +runner: + capacity: 1 + timeout: 8h +``` + +The workflow requests eight hours; older act_runner ignores job-level +timeouts, so the runner limit is required. Keep sufficient RAM/swap and +free disk for all package builds and their Docker caches. Builds run +sequentially and limit Cargo to one job. The workflow never prunes shared +Docker state or creates host swap. The token and optional Android signing +secrets are documented in [Gitea releases](release.md#gitea-releases). + +Gitea packages pass the shared Linux checks but do not gain native Windows, +Android Clippy or TS3/TS6 smoke-test acceptance from a successful release +job. Full hosted builds and a draft upload must be verified on the registered +runner; local shell/API fixtures do not establish deployment acceptance. diff --git a/docs/release.md b/docs/release.md index 1f97a04..6886e48 100644 --- a/docs/release.md +++ b/docs/release.md @@ -4,6 +4,52 @@ How a release is versioned, built, signed and checked. The app id `io.github.faumaray.Voelin` ([packaging/README.md](../packaging/README.md)) cannot change after the first release on Flathub or Google Play. +CI resource settings and the Linux Gitea runner setup are documented in +[ci.md](ci.md). Release packaging and draft publication run on GitHub and +Gitea ([git.faumaray.ru](https://git.faumaray.ru)); runner and credential +requirements differ. + +## Gitea releases + +`.gitea/workflows/release.yml` builds Linux tarballs and `.deb` files, Windows +zip and NSIS installer (MinGW cross-build), Android debug APK (arm64-v8a and +x86_64), a Flatpak bundle, and the gateway container image. It shares Linux +checks with Gitea CI, and reuses the Dockerfiles and `scripts/package.sh`. +Unlike GitHub's release pipeline, it does not run native Windows tests, +Android Clippy, TeamSpeak smoke tests or browser interop; complete those +checks in GitHub or separately before accepting a release. + +- **Manual dispatch:** after checks and all builds pass, download the + `voelin-packages` artifact from the run. Manual runs never publish a draft, + even when dispatched against a tag. +- **Push a `v*` tag:** the same artifact is uploaded, then packages and a + combined `SHA256SUMS` are attached to a **draft** Gitea release. Review, + sign checksums and publish manually, just as on GitHub. + +Set the repository secret `GITEA_RELEASE_TOKEN` to a Gitea personal access +token with `write:repository`, limited to this repository where supported. +The token's account must be able to write releases. The publishing script +uses the runner's `GITHUB_SERVER_URL` and `GITHUB_REPOSITORY`; it requires +HTTPS and never uses GitHub's release API. On this instance the server URL +is `https://git.faumaray.ru`. No registry credentials are needed: the gateway +image is attached as `tsgw-image.tar.gz`, not pushed to an OCI registry. + +Retries update only a matching **draft**, replacing same-named assets. +Published releases are not changed; a failed upload leaves a partial draft +for retry. Do not publish or modify a draft while the workflow runs. Gitea +1.25 ignores workflow concurrency and environment approvals; use the +dedicated, serial trusted runner described in [ci.md](ci.md#gitea-release-runner). + +For an optional signed Android release APK, set the same four signing secrets +listed below. They are written outside the Docker build context with private +permissions, passed as BuildKit secrets, and removed on success or failure. +Signed builds invalidate the signing stage's cache on every run; changing a +key or password cannot return a cached APK signed with the previous key. +Without the keystore secret, only the installable debug APK is produced; a +partially configured keystore fails the job rather than producing an +unsigned release. Windows and Flatpak packages are not code-signed by this +workflow. + ## Versioning - One version for the apps: `version` of `crates/voelin-ui` (desktop; the diff --git a/packaging/flatpak/io.github.faumaray.Voelin.yml b/packaging/flatpak/io.github.faumaray.Voelin.yml index f2e7b31..6a7a5c8 100644 --- a/packaging/flatpak/io.github.faumaray.Voelin.yml +++ b/packaging/flatpak/io.github.faumaray.Voelin.yml @@ -37,6 +37,9 @@ build-options: env: CARGO_HOME: /run/build/voelin/cargo CARGO_NET_OFFLINE: "true" + # flatpak-builder does not inherit Cargo settings from the outer job. + CARGO_BUILD_JOBS: "1" + CARGO_INCREMENTAL: "0" LIBCLANG_PATH: /usr/lib/sdk/llvm20/lib modules: diff --git a/scripts/flatpak-build.sh b/scripts/flatpak-build.sh new file mode 100755 index 0000000..f3d6196 --- /dev/null +++ b/scripts/flatpak-build.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Build the release Flatpak in the same privileged image as GitHub Actions. +# Requires rootful Docker on a trusted machine. No CI cache/artifact API used. +# Usage: scripts/flatpak-build.sh [out-dir, default dist/flatpak] +set -euo pipefail +cd "$(dirname "$0")/.." +mkdir -p "${1:-dist/flatpak}" +out=$(cd "${1:-dist/flatpak}" && pwd) +tmp=$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/voelin-flatpak.XXXXXX") +trap 'rm -rf "$tmp"' EXIT +mkdir "$tmp/source" +# Copy tracked working-tree files only: target/, secrets, and runner state +# must not become a Flatpak source or enter the privileged build container. +git ls-files -z | tar --null -T - -cf - | tar -C "$tmp/source" -xf - + +docker run --rm --privileged \ + --mount "type=bind,src=$tmp/source,dst=/src" \ + --mount "type=bind,src=$out,dst=/out" \ + --workdir /src \ + ghcr.io/flathub-infra/flatpak-github-actions:freedesktop-25.08 \ + bash -euo pipefail -c ' + curl -sSfL -o /tmp/flatpak-cargo-generator.py \ + https://raw.githubusercontent.com/flatpak/flatpak-builder-tools/41c20aa10819cdb2a4f3ca171758a96d1955c018/cargo/flatpak-cargo-generator.py + python3 -m venv /tmp/venv + /tmp/venv/bin/pip install --quiet "aiohttp>=3.9.5,<4" "tomlkit>=0.13.3,<1" "PyYAML>=6.0.2,<7" + /tmp/venv/bin/python /tmp/flatpak-cargo-generator.py Cargo.lock -o packaging/flatpak/cargo-sources.json + flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo + xvfb-run -a flatpak-builder --repo=/tmp/repo --state-dir=/tmp/state \ + --disable-rofiles-fuse --install-deps-from=flathub --force-clean \ + --default-branch=master --arch=x86_64 \ + /tmp/build packaging/flatpak/io.github.faumaray.Voelin.yml + flatpak build-bundle --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo \ + --arch=x86_64 /tmp/repo /out/voelin.flatpak io.github.faumaray.Voelin master + ' +test -s "$out/voelin.flatpak" +printf '%s\n' "$out/voelin.flatpak" diff --git a/scripts/gitea-release.sh b/scripts/gitea-release.sh new file mode 100755 index 0000000..7b8b50a --- /dev/null +++ b/scripts/gitea-release.sh @@ -0,0 +1,162 @@ +#!/usr/bin/env bash +# Upload verified packages to a draft only; publication is always manual. +set +x +set -euo pipefail +if (( $# > 1 )); then + echo "usage: $0 [asset-directory]" >&2 + exit 1 +fi +release_tmp=$(mktemp -d /tmp/gitea-release.XXXXXXXX) +trap 'rm -rf -- "$release_tmp"' EXIT +trap 'exit 130' INT +trap 'exit 143' HUP TERM +python3 - "${1:-dist/release}" "$release_tmp" <<'PY' +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +from urllib.parse import quote, urlsplit + + +def fail(message): + raise ValueError(message) + + +def positive_id(value): + if type(value) is not int or value <= 0: + fail("API returned an invalid id") + return value + + +def main(): + token = os.environ.get("GITEA_RELEASE_TOKEN", "") + if not token or any(ord(c) < 33 or ord(c) > 126 for c in token): + fail("GITEA_RELEASE_TOKEN is missing or invalid") + server = os.environ.get("GITHUB_SERVER_URL", "") + parsed = urlsplit(server) + if (parsed.scheme != "https" or not parsed.hostname or parsed.username + or parsed.password or parsed.query or parsed.fragment + or any(c.isspace() for c in server)): + fail("GITHUB_SERVER_URL must be an HTTPS server URL without credentials or query") + repo = os.environ.get("GITHUB_REPOSITORY", "").split("/") + if len(repo) != 2 or any(not part or part in (".", "..") for part in repo): + fail("GITHUB_REPOSITORY must be owner/repo") + ref = os.environ.get("GITHUB_REF", "") + if not ref.startswith("refs/tags/v") or len(ref) <= len("refs/tags/v"): + fail("GITHUB_REF must be a v* tag") + tag = ref[len("refs/tags/"):] + sha = os.environ.get("GITHUB_SHA", "") + if not re.fullmatch(r"[0-9a-fA-F]{40}|[0-9a-fA-F]{64}", sha): + fail("GITHUB_SHA must be a full commit id") + directory = Path(sys.argv[1]) + if directory.is_symlink() or not directory.is_dir(): + fail("asset directory must be a non-symlink directory") + files = sorted(directory.iterdir()) + if any(p.is_symlink() or not p.is_file() for p in files): + fail("asset directory must contain only regular non-symlink files") + names = {p.name for p in files} + if "SHA256SUMS" not in names or len(names) < 2: + fail("SHA256SUMS and at least one package are required") + # Exclude control characters and sha256sum's escaped filename syntax. + if any(any(ord(c) < 32 or c == "\\" for c in name) for name in names): + fail("unsupported control character or backslash in asset name") + expected = {} + for line in (directory / "SHA256SUMS").read_text().splitlines(): + match = re.fullmatch(r"([0-9a-fA-F]{64}) [ *](.+)", line) + if not match or match[2] in expected: + fail("invalid or duplicate SHA256SUMS entry") + expected[match[2]] = match[1].lower() + if set(expected) != names - {"SHA256SUMS"}: + fail("SHA256SUMS must describe exactly all package files") + for name, digest in expected.items(): + with (directory / name).open("rb") as package: + actual = hashlib.file_digest(package, "sha256").hexdigest() + if actual != digest: + fail("package checksum mismatch") + + base = server.rstrip("/") + "/api/v1/repos/" + "/".join(quote(p, safe="") for p in repo) + "/releases" + # /tmp is outside the checkout/build context; mkdtemp and the header are private. + with tempfile.TemporaryDirectory(prefix="gitea-release-", dir=sys.argv[2]) as temp: + header = Path(temp) / "headers" + fd = os.open(header, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w") as output: + output.write("Authorization: token " + token + "\n") + environment = os.environ.copy() + environment.pop("GITEA_RELEASE_TOKEN", None) + + not_found = object() + + def diagnostic(text): + # Redact before truncation and again after stripping control characters. + text = text.replace(token, "[REDACTED]") + text = "".join(c for c in text if c.isprintable()) + return text.replace(token, "[REDACTED]")[:512] + + def request(method, url, *, payload=None, package=None, missing=False): + response = Path(temp) / "response" + args = ["curl", "--disable", "--silent", "--show-error", "--proto", "=https", + "--connect-timeout", "30", "--max-time", "1800", + "--request", method, "--header", "@" + str(header), + "--output", str(response), "--write-out", "%{http_code}", url] + if payload is not None: + body = Path(temp) / "request.json" + body.write_text(json.dumps(payload)) + args += ["--header", "Content-Type: application/json", "--data-binary", "@" + str(body)] + if package is not None: + # Quoted curl form path protects commas/semicolons/quotes in paths. + path = str(package.resolve()).replace("\\", "\\\\").replace('"', '\\"') + args += ["--form", 'attachment=@"' + path + '"'] + result = subprocess.run(args, capture_output=True, text=True, env=environment) + if result.returncode: + fail(f"Gitea API {method} transport failed (curl {result.returncode}): " + + diagnostic(result.stderr)) + if missing and result.stdout == "404": + return not_found + if not re.fullmatch(r"2[0-9]{2}", result.stdout): + message = "" + try: + with response.open() as output: + error = json.loads(output.read(8192)) + if isinstance(error, dict) and isinstance(error.get("message"), str): + message = ": " + diagnostic(error["message"]) + except (OSError, ValueError): + pass + fail(f"Gitea API {method} failed (HTTP {diagnostic(result.stdout)})" + message) + return json.loads(response.read_text()) if response.stat().st_size else None + + release = request("GET", base + "/tags/" + quote(tag, safe=""), missing=True) + if release is not_found: + release = request("POST", base, payload={"tag_name": tag, "target_commitish": sha, + "name": tag, "draft": True, "prerelease": False, + "body": "Packages and SHA256 checksums. Review before publishing."}) + if not isinstance(release, dict) or release.get("tag_name") != tag or release.get("draft") is not True: + fail("refusing to modify a published or mismatched release") + assets_url = base + "/" + str(positive_id(release.get("id"))) + "/assets" + assets = request("GET", assets_url) + if not isinstance(assets, list): + fail("API returned an invalid asset list") + for asset in assets: + if not isinstance(asset, dict) or not isinstance(asset.get("name"), str): + fail("API returned an invalid asset") + positive_id(asset.get("id")) + for package in files: + for asset in assets: + if asset["name"] == package.name: + request("DELETE", assets_url + "/" + str(asset["id"])) + uploaded = request("POST", assets_url + "?name=" + quote(package.name, safe=""), package=package) + if not isinstance(uploaded, dict): + fail("API returned an invalid uploaded asset") + positive_id(uploaded.get("id")) + print("Packages uploaded to draft release " + tag + "; publication remains manual.") + + +try: + main() +except (ValueError, OSError, KeyError, TypeError) as error: + print("gitea-release: " + str(error), file=sys.stderr) + sys.exit(1) +PY diff --git a/scripts/test-gitea-release.py b/scripts/test-gitea-release.py new file mode 100644 index 0000000..d7b2c9d --- /dev/null +++ b/scripts/test-gitea-release.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python3 +"""Offline regression tests of the real release script using a curl fixture.""" +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +SCRIPT = Path(__file__).with_name("gitea-release.sh").resolve() +FAKE_CURL = r'''#!/usr/bin/env python3 +import json, os, pathlib, stat, sys +args = sys.argv[1:] +def option(name): + return args[args.index(name) + 1] +header = pathlib.Path(option('--header')[1:]) +assert stat.S_IMODE(header.stat().st_mode) == 0o600 +assert header.read_text() == 'Authorization: token fixture-secret\n' +assert 'GITEA_RELEASE_TOKEN' not in os.environ +assert not any('fixture-secret' in arg for arg in args) +assert '--location' not in args and '-L' not in args +assert args[0] == '--disable' +method = option('--request') +url = args[args.index('--write-out') + 2] +record = {'method': method, 'url': url, 'header': str(header)} +if '--data-binary' in args: + record['payload'] = json.loads(pathlib.Path(option('--data-binary')[1:]).read_text()) +if '--form' in args: + record['form'] = option('--form') +with open(os.environ['SPY'], 'a') as spy: + spy.write(json.dumps(record) + '\n') +mode = os.environ.get('MODE', 'create') +if mode == 'transport-fail': + sys.stderr.write('curl: (60) TLS certificate failed: fixture-secret\n\x1b' + 'x' * 1000) + sys.exit(60) +status, body = '200', None +release = {'id': 7, 'tag_name': os.environ['GITHUB_REF'][10:], 'draft': mode != 'published'} +if mode == 'mismatched': release['tag_name'] = 'v-other' +if mode == 'invalid-release-id': release['id'] = True +if method == 'GET' and '/tags/' in url: + status, body = ('404', {}) if mode == 'create' else ('200', release) + if mode in ('null-lookup', 'empty-lookup'): body = None + if mode == 'http-error': + status, body = '403', {'message': 'Access denied: fixture-secret\n\x1b' + 'y' * 1000} +elif method == 'POST' and url.endswith('/releases'): + status, body = '201', release +elif method == 'GET' and url.endswith('/assets'): + body = [{'id': 9, 'name': 'package +#.zip'}, {'id': 10, 'name': 'unrelated.zip'}] + if mode == 'invalid-id': body[0]['id'] = '../bad' +elif method == 'DELETE': + status = '500' if mode == 'delete-fail' else '204' +elif method == 'POST' and '/assets?' in url: + status, body = ('500', {}) if mode == 'upload-fail' else ('201', {'id': 11}) +else: + raise AssertionError(record) +pathlib.Path(option('--output')).write_text(json.dumps(body) if body is not None or mode == 'null-lookup' else '') +sys.stdout.write(status) +''' + + +class ReleaseTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.assets = self.root / "assets" + self.assets.mkdir() + self.package = self.assets / "package +#.zip" + self.package.write_bytes(b"package") + self.checksums() + self.bin = self.root / "bin" + self.bin.mkdir() + curl = self.bin / "curl" + curl.write_text(FAKE_CURL) + curl.chmod(0o755) + self.spy = self.root / "spy" + self.env = dict(os.environ, PATH=str(self.bin) + os.pathsep + os.environ['PATH'], + SPY=str(self.spy), MODE="create", GITEA_RELEASE_TOKEN="fixture-secret", + GITHUB_SERVER_URL="https://git.faumaray.ru", GITHUB_REPOSITORY="owner/repo", + GITHUB_REF="refs/tags/v1.0+test", GITHUB_SHA="a" * 40) + + def checksums(self): + (self.assets / "SHA256SUMS").write_text( + hashlib.sha256(self.package.read_bytes()).hexdigest() + " " + self.package.name + "\n") + + def run_script(self, success=True, pre_api=False): + result = subprocess.run(["bash", "-x", str(SCRIPT), str(self.assets)], + env=self.env, text=True, capture_output=True) + self.last_result = result + self.assertEqual(result.returncode == 0, success, result.stderr) + self.assertNotIn("fixture-secret", result.stdout + result.stderr) + calls = [json.loads(line) for line in self.spy.read_text().splitlines()] if self.spy.exists() else [] + if pre_api: + self.assertEqual(calls, []) + for call in calls: + self.assertFalse(Path(call['header']).exists(), "credential file leaked") + self.assertNotEqual(call['method'], 'PATCH', "must never publish") + return calls + + def test_create_draft_and_encoded_upload(self): + calls = self.run_script() + create = next(c for c in calls if 'payload' in c) + self.assertTrue(create['payload']['draft']) + self.assertEqual(create['payload']['target_commitish'], 'a' * 40) + self.assertTrue(calls[0]['url'].endswith('/tags/v1.0%2Btest')) + self.assertTrue(any(c['url'].endswith('?name=package%20%2B%23.zip') for c in calls)) + self.assertEqual(len([c for c in calls if 'form' in c]), 2) + + def test_invalid_successful_lookup_never_creates_release(self): + for mode in ('null-lookup', 'empty-lookup'): + with self.subTest(mode=mode): + self.spy.unlink(missing_ok=True) + self.env['MODE'] = mode + calls = self.run_script(False) + self.assertEqual([c['method'] for c in calls], ['GET']) + + def test_transport_error_is_bounded_and_redacted(self): + self.env['MODE'] = 'transport-fail' + calls = self.run_script(False) + self.assertEqual([c['method'] for c in calls], ['GET']) + stderr = self.last_result.stderr + self.assertIn('GET transport failed (curl 60)', stderr) + self.assertIn('TLS certificate failed: [REDACTED]', stderr) + self.assertNotIn('\x1b', stderr) + self.assertLess(len(stderr), 650) + + def test_http_error_is_bounded_and_redacted(self): + self.env['MODE'] = 'http-error' + calls = self.run_script(False) + self.assertEqual([c['method'] for c in calls], ['GET']) + stderr = self.last_result.stderr + self.assertIn('GET failed (HTTP 403)', stderr) + self.assertIn('Access denied: [REDACTED]', stderr) + self.assertNotIn('\x1b', stderr) + self.assertLess(len(stderr), 650) + + def test_retry_replaces_only_matching_assets(self): + self.env['MODE'] = 'draft' + calls = self.run_script() + self.assertFalse(any('payload' in c for c in calls)) + self.assertEqual([c['url'].split('/')[-1] for c in calls if c['method'] == 'DELETE'], ['9']) + + def test_published_release_is_untouched(self): + self.env['MODE'] = 'published' + calls = self.run_script(False) + self.assertEqual([c['method'] for c in calls], ['GET']) + + def test_mismatched_release_is_untouched(self): + self.env['MODE'] = 'mismatched' + calls = self.run_script(False) + self.assertEqual([c['method'] for c in calls], ['GET']) + + def test_invalid_release_id_is_untouched(self): + self.env['MODE'] = 'invalid-release-id' + calls = self.run_script(False) + self.assertEqual([c['method'] for c in calls], ['GET']) + + def test_form_path_and_url_encoding(self): + renamed = self.package.with_name('quote";,+#.zip') + self.package.rename(renamed) + self.package = renamed + self.checksums() + self.env['GITHUB_REF'] = 'refs/tags/v1/preview' + calls = self.run_script() + self.assertTrue(calls[0]['url'].endswith('/tags/v1%2Fpreview')) + upload = next(c for c in calls if c['url'].endswith('?name=quote%22%3B%2C%2B%23.zip')) + self.assertIn('quote\\";,+#.zip', upload['form']) + self.assertTrue(upload['form'].endswith('"')) + + def test_invalid_environment_before_api(self): + for key, value in [('GITEA_RELEASE_TOKEN', ''), ('GITHUB_REF', 'refs/heads/main'), + ('GITHUB_SERVER_URL', 'http://git.faumaray.ru'), + ('GITHUB_SERVER_URL', 'https://user:pass@git.faumaray.ru'), + ('GITHUB_SERVER_URL', 'https://git.faumaray.ru?query'), + ('GITHUB_REPOSITORY', '../repo'), ('GITHUB_SHA', 'main')]: + with self.subTest(key=key, value=value): + old = self.env[key] + self.env[key] = value + self.run_script(False, pre_api=True) + self.env[key] = old + + def test_checksum_failure_before_api(self): + self.package.write_bytes(b'corrupted') + self.run_script(False, pre_api=True) + + def test_stale_file_before_api(self): + (self.assets / 'stale.zip').write_bytes(b'stale') + self.run_script(False, pre_api=True) + + def test_directory_and_symlink_before_api(self): + extra = self.assets / 'extra' + extra.mkdir() + self.run_script(False, pre_api=True) + extra.rmdir() + extra.symlink_to(self.package) + self.run_script(False, pre_api=True) + + def test_missing_manifest_before_api(self): + (self.assets / 'SHA256SUMS').unlink() + self.run_script(False, pre_api=True) + + def test_upload_failure_stays_draft_and_cleans_token(self): + self.env['MODE'] = 'upload-fail' + calls = self.run_script(False) + self.assertEqual(len([c for c in calls if 'form' in c]), 1) + + def test_delete_failure_stops_before_replacement(self): + self.env['MODE'] = 'delete-fail' + calls = self.run_script(False) + self.assertEqual(calls[-1]['method'], 'DELETE') + self.assertFalse(any('package%20' in c['url'] for c in calls)) + + def test_invalid_api_id_stops_before_mutation(self): + self.env['MODE'] = 'invalid-id' + calls = self.run_script(False) + self.assertTrue(all(c['method'] == 'GET' for c in calls)) + + +if __name__ == '__main__': + unittest.main()