Compare commits

..
Author SHA1 Message Date
Kevin Yue 86c8d188c4 feat: add connection dashboard and improve desktop authentication
Add tunnel configuration reporting, an optional CLI dashboard, manual browser authentication, native authentication controls, and broader client identity support. Improve TLS recovery, certificate validation, desktop notifications, and platform integration.
2026-10-19 23:26:38 +08:00
67 changed files with 365 additions and 4823 deletions

No files matched your search

@@ -1,35 +0,0 @@
name: Checkout private source quietly
description: Fetch private source without printing Git diagnostics or retaining credentials.
inputs:
token:
required: true
description: Token with read access to the private repository
ref:
required: true
description: Branch, tag, or full commit SHA
path:
required: true
description: Destination within the workspace
runs:
using: composite
steps:
- shell: bash
env:
PRIVATE_TOKEN: ${{ inputs.token }}
PRIVATE_REF: ${{ inputs.ref }}
PRIVATE_PATH: ${{ inputs.path }}
run: |
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private source checkout failed; diagnostics suppressed."; fi' EXIT
(
set -euo pipefail
export GIT_TERMINAL_PROMPT=0
export GIT_CONFIG_COUNT=1
export GIT_CONFIG_KEY_0=http.https://github.com/.extraheader
GIT_CONFIG_VALUE_0="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$PRIVATE_TOKEN" | base64 | tr -d '\n')"
export GIT_CONFIG_VALUE_0
git init "$PRIVATE_PATH"
git -C "$PRIVATE_PATH" remote add origin https://github.com/yuezk/gpgui
git -C "$PRIVATE_PATH" fetch --no-tags --depth=1 -- origin "$PRIVATE_REF"
git -C "$PRIVATE_PATH" checkout --detach FETCH_HEAD
) >/dev/null 2>&1
echo "Private source checkout passed."
+17 -46
View File
@@ -51,37 +51,20 @@ jobs:
ref: ${{ inputs.gp_ref }}
path: gpgui-source/gp
submodules: recursive
- name: Checkout CI helpers
- name: Checkout gpgui
uses: actions/checkout@v6
with:
path: .ci
persist-credentials: false
- name: Checkout gpgui
uses: ./.ci/.github/actions/checkout-private
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ inputs.gpgui_ref }}
path: gpgui-source/gpgui
- name: Verify Linux desktop assets
if: matrix.os.arch == 'amd64' && inputs.verify_desktop_assets
run: |
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
(
set -euo pipefail
gpgui-source/gp/scripts/verify-linux-desktop-assets.sh gpgui-source/gpgui
) >/dev/null 2>&1
echo "Private operation passed."
run: gpgui-source/gp/scripts/verify-linux-desktop-assets.sh gpgui-source/gpgui
- name: Tarball
run: |
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
(
set -euo pipefail
cd gpgui-source
tar -czf gpgui.tar.gz gpgui gp
) >/dev/null 2>&1
echo "Private operation passed."
cd gpgui-source
tar -czf gpgui.tar.gz gpgui gp
- name: Build gpgui in Docker
env:
GPGUI_BUILDER: ${{ inputs.builder }}
@@ -89,34 +72,22 @@ jobs:
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
run: |
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
(
set -euo pipefail
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-e GPGUI_BUILD_VERSION \
-e GPGUI_UPDATE_CHANNEL \
-e GPGUI_LICENSE_SIGNING_KEYS \
-v "$(pwd)/gpgui-source:/workspace" "yuezk/gpdev:$GPGUI_BUILDER"
) >/dev/null 2>&1
echo "Private operation passed."
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-e GPGUI_BUILD_VERSION \
-e GPGUI_UPDATE_CHANNEL \
-e GPGUI_LICENSE_SIGNING_KEYS \
-v "$(pwd)/gpgui-source:/workspace" "yuezk/gpdev:$GPGUI_BUILDER"
- name: Install gpgui in Docker
env:
GPGUI_BUILDER: ${{ inputs.builder }}
run: |
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
(
set -euo pipefail
cd gpgui-source
tar -xJf ./*.bin.tar.xz
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v "$(pwd):/workspace" "yuezk/gpdev:$GPGUI_BUILDER" \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
) >/dev/null 2>&1
echo "Private operation passed."
cd gpgui-source
tar -xJf ./*.bin.tar.xz
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v "$(pwd):/workspace" "yuezk/gpdev:$GPGUI_BUILDER" \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui
uses: actions/upload-artifact@v7
with:
+175 -432
View File
@@ -16,11 +16,11 @@ on:
gp_branch:
description: 'GlobalProtect-openconnect ref to build (use the matching tag for stable builds)'
required: true
default: release/next
default: dev
gpgui_branch:
description: 'gpgui branch or tag to build and test (use the matching tag for stable builds)'
description: 'gpgui ref to build (use the matching tag for stable builds)'
required: true
default: release/next
default: dev
build_macos:
description: 'Build Apple Silicon artifacts for this run'
required: true
@@ -54,12 +54,6 @@ concurrency:
jobs:
validate-inputs:
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
outputs:
gp_sha: ${{ steps.sources.outputs.gp_sha }}
gpgui_sha: ${{ steps.sources.outputs.gpgui_sha }}
steps:
- name: Validate stable refs
env:
@@ -75,53 +69,6 @@ jobs:
fi
fi
- name: Checkout CI helpers
uses: actions/checkout@v6
- name: Restore selected sources on retry
id: restored
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
artifacts="$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/artifacts?per_page=100")"
existing="$(jq -r '.artifacts[] | select(.name == "build-source-refs") | .id' <<<"$artifacts")"
if [[ -n "$existing" ]]; then
gh run download "$GITHUB_RUN_ID" --repo "$GITHUB_REPOSITORY" \
--name build-source-refs --dir selected-sources
echo "cached=true" >> "$GITHUB_OUTPUT"
elif [[ "$GITHUB_RUN_ATTEMPT" -gt 1 ]]; then
echo "Retained source refs are unavailable; start a fresh dispatch." >&2
exit 1
else
echo "cached=false" >> "$GITHUB_OUTPUT"
fi
- name: Select public source
if: steps.restored.outputs.cached != 'true'
uses: actions/checkout@v6
with:
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.sha }}
path: selected/gp
- name: Select private source
if: steps.restored.outputs.cached != 'true'
uses: ./.github/actions/checkout-private
with:
token: ${{ secrets.GH_PAT }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: selected/gpgui
- name: Record selected sources
id: sources
run: |
python3 scripts/record-build-sources.py selected-sources/sources.json \
--gp selected/gp --gpgui selected/gpgui
- name: Retain selected sources for retries
if: steps.restored.outputs.cached != 'true'
uses: actions/upload-artifact@v7
with:
name: build-source-refs
path: selected-sources/sources.json
retention-days: 30
test-gp:
needs: validate-inputs
runs-on: ubuntu-latest
@@ -131,7 +78,7 @@ jobs:
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ needs.validate-inputs.outputs.gp_sha }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
submodules: recursive
- name: Run Rust tests as a non-root user with focused privilege checks
run: |
@@ -160,36 +107,6 @@ jobs:
--bin gpservice device_anchor::tests
'
test-gpgui:
needs: validate-inputs
runs-on: ubuntu-latest
timeout-minutes: 85
permissions:
contents: read
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
repository: yuezk/GlobalProtect-openconnect
ref: ${{ needs.validate-inputs.outputs.gp_sha }}
submodules: recursive
path: source/gp
persist-credentials: false
- name: Checkout CI helpers
uses: actions/checkout@v6
with:
path: .ci
persist-credentials: false
- name: Checkout gpgui
uses: ./.ci/.github/actions/checkout-private
with:
token: ${{ secrets.GH_PAT }}
ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
path: source/gpgui
- name: Run frontend and Rust unit tests as an ordinary user
timeout-minutes: 80
run: bash .ci/scripts/test-private-desktop.sh "$PWD/source"
tarball:
needs: validate-inputs
runs-on: ubuntu-latest
@@ -205,7 +122,7 @@ jobs:
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ needs.validate-inputs.outputs.gp_sha }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: source/gp
submodules: recursive
@@ -335,7 +252,6 @@ jobs:
build-gp-${{ matrix.package }}/artifacts/*
build-docker-image:
needs: validate-inputs
if: ${{ !(startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
strategy:
fail-fast: false
@@ -356,7 +272,7 @@ jobs:
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ needs.validate-inputs.outputs.gp_sha }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
submodules: recursive
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
@@ -418,8 +334,8 @@ jobs:
name: build-gpgui (glibc)
uses: ./.github/workflows/build-gpgui-linux.yaml
with:
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
gp_ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
gpgui_ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
builder: gpgui-builder-tauri2
verify_desktop_assets: true
@@ -431,8 +347,8 @@ jobs:
name: build-gpgui (musl)
uses: ./.github/workflows/build-gpgui-linux.yaml
with:
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
gp_ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
gpgui_ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
builder: gpgui-alpine-builder-tauri2
artifact_suffix: -musl
@@ -440,7 +356,7 @@ jobs:
GH_PAT: ${{ secrets.GH_PAT }}
nix-source:
needs: [validate-inputs, build-gpgui-glibc]
needs: [build-gpgui-glibc]
strategy:
fail-fast: false
matrix:
@@ -461,7 +377,7 @@ jobs:
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
ref: ${{ needs.validate-inputs.outputs.gp_sha }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
submodules: recursive
path: gp
- name: Download current GUI artifact
@@ -489,7 +405,7 @@ jobs:
--extra-experimental-features "nix-command flakes" --print-build-logs
nix-prebuilt:
needs: [validate-inputs, build-gp, build-gpgui-glibc]
needs: [build-gp, build-gpgui-glibc]
strategy:
fail-fast: false
matrix:
@@ -511,7 +427,7 @@ jobs:
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
ref: ${{ needs.validate-inputs.outputs.gp_sha }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
submodules: recursive
path: gp
- name: Download current Linux binary artifact
@@ -551,279 +467,94 @@ jobs:
nix build --impure --file gp/nix/ci.nix runtime-prebuilt \
--extra-experimental-features "nix-command flakes" --print-build-logs
build-macos:
name: build-macos
needs: [validate-inputs, test-gp, test-gpgui]
trigger-gpgui-macos:
needs: test-gp
if: ${{ (github.event_name == 'workflow_dispatch' && inputs.build_macos) || (startsWith(github.ref, 'refs/tags/') && vars.BUILD_MACOS_ON_TAG == 'true') }}
permissions:
contents: read
concurrency:
group: macos-build
cancel-in-progress: false
runs-on: ${{ vars.MACOS_RUNNER || 'macos-15' }}
environment: macos-release
timeout-minutes: 120
runs-on: ubuntu-latest
name: trigger private macOS build
outputs:
run_id: ${{ steps.dispatch.outputs.run_id }}
run_url: ${{ steps.dispatch.outputs.run_url }}
steps:
- name: Verify runner architecture
run: test "$(uname -m)" = arm64
- name: Select Xcode toolchain
env:
DEVELOPER_DIR: /Applications/Xcode_26.3.app/Contents/Developer
run: |
set -euo pipefail
xcodebuild -version
xcrun swift --version
echo "DEVELOPER_DIR=$DEVELOPER_DIR" >> "$GITHUB_ENV"
- uses: pnpm/action-setup@v5
with:
version: 9.15.1
- name: Checkout CI helpers
uses: actions/checkout@v6
with:
path: .ci
persist-credentials: false
- name: Checkout gpgui source
uses: ./.ci/.github/actions/checkout-private
with:
token: ${{ secrets.GH_PAT }}
ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
path: source/gpgui
- name: Checkout GlobalProtect-openconnect source
uses: actions/checkout@v6
with:
repository: yuezk/GlobalProtect-openconnect
ref: ${{ needs.validate-inputs.outputs.gp_sha }}
path: source/gp
submodules: recursive
- name: Verify stable source commits
if: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') == 'stable' }}
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
RELEASE_TAG: ${{ (github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name) }}
run: |
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Stable source tag verification failed; diagnostics suppressed."; fi' EXIT
(
set -euo pipefail
git -C source/gp fetch --no-tags origin "refs/tags/$RELEASE_TAG"
test "$(git -C source/gp rev-parse HEAD)" = "$(git -C source/gp rev-parse 'FETCH_HEAD^{commit}')"
tagged_gui_commit="$(gh api "repos/yuezk/gpgui/commits/$RELEASE_TAG" --jq .sha)"
test "$(git -C source/gpgui rev-parse HEAD)" = "$tagged_gui_commit"
) >/dev/null 2>&1
echo "Stable source tags verified."
- uses: actions/setup-node@v6
with:
node-version: 22
- name: Prepare release metadata
env:
FEED_URL: ${{ vars.SPARKLE_FEED_URL }}
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
RELEASE_TAG: ${{ (github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name) }}
BUILD_VERSION: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
run: |
set -euo pipefail
gp_version="$(sed -n 's/^version = "\([^"]*\)"/\1/p' source/gp/Cargo.toml | head -1)"
gpgui_version="$(sed -n 's/^version = "\([^"]*\)"/\1/p' source/gpgui/Cargo.toml | head -1)"
if [[ -z "$gp_version" || "$gp_version" != "$gpgui_version" ]]; then
echo "gp and gpgui versions must match: gp=$gp_version, gpgui=$gpgui_version" >&2
exit 1
fi
if [[ "$FEED_URL" != https://*/appcast.xml ]]; then
echo "SPARKLE_FEED_URL must be an HTTPS URL ending in /appcast.xml" >&2
exit 1
fi
if [[ "$CHANNEL" == "stable" ]]; then
artifact_version="$gpgui_version"
if [[ "$RELEASE_TAG" != "v$gpgui_version" ]]; then
echo "Release tag does not match gpgui version $gpgui_version" >&2
exit 1
fi
else
artifact_version="${gpgui_version}-snapshot.${BUILD_VERSION}"
fi
{
echo "MACOS_BUILD_NUMBER=$BUILD_VERSION"
echo "MACOS_ARTIFACT_VERSION=$artifact_version"
echo "SPARKLE_FEED_URL=$FEED_URL"
echo "SPARKLE_UPDATE_CHANNEL=$CHANNEL"
} >> "$GITHUB_ENV"
- name: Install build dependencies
run: |
brew install \
autoconf \
automake \
create-dmg \
dylibbundler \
gettext \
libtool \
meson \
ninja \
pkgconf \
python
- name: Import signing identity
env:
MACOS_CERTIFICATE_P12: ${{ secrets.MACOS_CERTIFICATE_P12 }}
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
APPLE_NOTARY_KEY_P8: ${{ secrets.APPLE_NOTARY_KEY_P8 }}
APPLE_NOTARY_KEY_ID: ${{ secrets.APPLE_NOTARY_KEY_ID }}
APPLE_NOTARY_ISSUER_ID: ${{ secrets.APPLE_NOTARY_ISSUER_ID }}
run: |
set -euo pipefail
for variable in \
MACOS_CERTIFICATE_P12 \
MACOS_CERTIFICATE_PASSWORD; do
if [[ -z "${!variable:-}" ]]; then
echo "$variable is not configured" >&2
exit 1
fi
done
for variable in \
APPLE_NOTARY_KEY_P8 \
APPLE_NOTARY_KEY_ID \
APPLE_NOTARY_ISSUER_ID; do
if [[ -z "${!variable:-}" ]]; then
echo "$variable is not configured" >&2
exit 1
fi
done
keychain="$RUNNER_TEMP/gp-connect.keychain-db"
keychain_password="$(uuidgen)"
certificate="$RUNNER_TEMP/signing-identity.p12"
printf '%s' "$MACOS_CERTIFICATE_P12" | base64 -D > "$certificate"
chmod 600 "$certificate"
security create-keychain -p "$keychain_password" "$keychain"
security set-keychain-settings -lut 21600 "$keychain"
security unlock-keychain -p "$keychain_password" "$keychain"
security import "$certificate" -k "$keychain" \
-P "$MACOS_CERTIFICATE_PASSWORD" -A -t cert -f pkcs12
security set-key-partition-list -S apple-tool:,apple: \
-s -k "$keychain_password" "$keychain"
security list-keychains -d user -s "$keychain" login.keychain-db
identity="$(security find-identity -v -p codesigning "$keychain" \
| sed -n 's/.*"\(Developer ID Application:.*\)"/\1/p' | head -1)"
if [[ -z "$identity" ]]; then
echo "A Developer ID Application signing identity was not found" >&2
exit 1
fi
{
echo "CI_KEYCHAIN=$keychain"
echo "MACOS_SIGN_IDENTITY=$identity"
} >> "$GITHUB_ENV"
notary_key="$RUNNER_TEMP/AuthKey.p8"
notary_profile="gp-connect-ci"
printf '%s' "$APPLE_NOTARY_KEY_P8" > "$notary_key"
chmod 600 "$notary_key"
xcrun notarytool store-credentials "$notary_profile" \
--key "$notary_key" \
--key-id "$APPLE_NOTARY_KEY_ID" \
--issuer "$APPLE_NOTARY_ISSUER_ID" \
--keychain "$keychain"
{
echo "APPLE_NOTARY_PROFILE=$notary_profile"
echo "APPLE_NOTARY_KEYCHAIN=$keychain"
} >> "$GITHUB_ENV"
- name: Build macOS release artifacts
- name: Dispatch private macOS build
id: dispatch
env:
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
PUBLIC_GH_TOKEN: ${{ github.token }}
CHANNEL: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
SPARKLE_PUBLIC_KEY: ${{ vars.SPARKLE_PUBLIC_KEY }}
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
run: |
set -euo pipefail
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
(
set -euo pipefail
if [[ "$CHANNEL" == "snapshot" ]]; then
export GPGUI_RELEASE_DEVTOOLS=1
fi
source/gpgui/scripts/build-macos.sh dmg release
) 2>&1 | awk '
/^MACOS_STAGE: (Native dependencies|Components|Frontend|Application|Bundle|Bundle icons|Bundle metadata|Bundle licenses|Bundle libraries|Bundle frameworks|Bundle optimization|Signing|Validation|App notarization|Update archive|Disk image|Disk image notarization|Complete)$/ {
print "::notice::" $0
fflush()
}
'
echo "Private operation passed."
- name: Prepare release assets
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
GP_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref_name }}
GPGUI_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
REQUEST_ID: ${{ github.run_id }}.${{ github.run_attempt }}.macos
run: |
set -euo pipefail
artifact_dir="release-assets"
rm -rf "$artifact_dir"
mkdir -p "$artifact_dir"
dmg_name="GPConnect_${MACOS_ARTIFACT_VERSION}_arm64.dmg"
archive_name="GPConnect_${MACOS_ARTIFACT_VERSION}_arm64.zip"
mv "source/gpgui/target/release/bundle/dmg/GP Connect.dmg" \
"$artifact_dir/$dmg_name"
mv "source/gpgui/target/release/bundle/sparkle/$archive_name" \
"$artifact_dir/$archive_name"
(
cd "$artifact_dir"
for file in *; do
shasum -a 256 "$file" > "$file.sha256"
done
)
- name: Record build identity
env:
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
RELEASE_TAG: ${{ (github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name) }}
REQUEST_ID: ${{ format('{0}.{1}.macos', github.run_id, github.run_attempt) }}
BUILD_VERSION: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
WORKFLOW_SHA: ${{ github.sha }}
run: |
GP_REF="$(git -C source/gp rev-parse HEAD)"
GPGUI_REF="$(git -C source/gpgui rev-parse HEAD)"
export GP_REF GPGUI_REF
python3 - <<'PYTHON'
import hashlib
import json
import os
from pathlib import Path
directory = Path("release-assets")
metadata = {key.lower(): os.environ[key] for key in (
"CHANNEL", "RELEASE_TAG", "GP_REF", "GPGUI_REF", "REQUEST_ID", "BUILD_VERSION", "WORKFLOW_SHA")}
metadata["artifact_version"] = os.environ["MACOS_ARTIFACT_VERSION"]
metadata["assets"] = {
file.name: hashlib.sha256(file.read_bytes()).hexdigest()
for file in directory.iterdir() if file.is_file()
}
(directory / "release-build.json").write_text(json.dumps(metadata, indent=2) + "\n")
PYTHON
- name: Upload macOS build artifact
uses: actions/upload-artifact@v7
with:
name: macos-release-${{ format('{0}.{1}.macos', github.run_id, github.run_attempt) }}
if-no-files-found: error
overwrite: true
retention-days: 30
path: release-assets/*
- name: Remove signing keychain
if: ${{ always() }}
run: |
if [[ -n "${CI_KEYCHAIN:-}" && -f "$CI_KEYCHAIN" ]]; then
security delete-keychain "$CI_KEYCHAIN"
if [[ -z "${GH_TOKEN:-}" ]]; then
echo "GPGUI_ACTIONS_TOKEN is not configured" >&2
exit 1
fi
gp_ref_path="$(jq -rn --arg ref "$GP_REF" '$ref | @uri')"
gpgui_ref_path="$(jq -rn --arg ref "$GPGUI_REF" '$ref | @uri')"
gp_sha="$(GH_TOKEN="$PUBLIC_GH_TOKEN" gh api \
"repos/yuezk/GlobalProtect-openconnect/commits/$gp_ref_path" --jq .sha)"
gpgui_sha="$(gh api "repos/yuezk/gpgui/commits/$gpgui_ref_path" --jq .sha)"
if [[ -z "$gp_sha" || -z "$gpgui_sha" ]]; then
echo "Could not resolve release source refs" >&2
exit 1
fi
expected_title="macOS build $CHANNEL $RELEASE_TAG ($REQUEST_ID)"
jq -n \
--arg workflow_ref "$GPGUI_REF" \
--arg request_id "$REQUEST_ID" \
--arg build_version "$BUILD_VERSION" \
--arg channel "$CHANNEL" \
--arg release_tag "$RELEASE_TAG" \
--arg gp_ref "$gp_sha" \
--arg gpgui_ref "$gpgui_sha" \
'{
ref: $workflow_ref,
inputs: {
request_id: $request_id,
build_version: $build_version,
channel: $channel,
release_tag: $release_tag,
gp_ref: $gp_ref,
gpgui_ref: $gpgui_ref
}
}' | gh api --method POST \
repos/yuezk/gpgui/actions/workflows/build-macos.yaml/dispatches \
--input -
run_id=""
run_url=""
for _ in {1..40}; do
runs="$(gh api \
'repos/yuezk/gpgui/actions/workflows/build-macos.yaml/runs?event=workflow_dispatch&per_page=50')"
run_id="$(jq -r --arg title "$expected_title" \
'[.workflow_runs[] | select(.display_title == $title)] | first | .id // empty' \
<<<"$runs")"
run_url="$(jq -r --arg title "$expected_title" \
'[.workflow_runs[] | select(.display_title == $title)] | first | .html_url // empty' \
<<<"$runs")"
if [[ -n "$run_id" ]]; then
{
echo "run_id=$run_id"
echo "run_url=$run_url"
} >> "$GITHUB_OUTPUT"
echo "Triggered private workflow: $run_url"
exit 0
fi
sleep 3
done
echo "Could not locate the dispatched private workflow run" >&2
exit 1
setup-bsd-matrix:
needs: validate-inputs
runs-on: ubuntu-latest
@@ -869,7 +600,7 @@ jobs:
PY
build-gpgui-frontend:
needs: [validate-inputs, setup-bsd-matrix]
needs: setup-bsd-matrix
if: ${{ needs.setup-bsd-matrix.outputs.enabled == 'true' }}
runs-on: ubuntu-latest
steps:
@@ -883,31 +614,21 @@ jobs:
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ needs.validate-inputs.outputs.gp_sha }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: gpgui-frontend/gp
submodules: recursive
- name: Checkout CI helpers
- name: Checkout gpgui
uses: actions/checkout@v6
with:
path: .ci
persist-credentials: false
- name: Checkout gpgui
uses: ./.ci/.github/actions/checkout-private
with:
token: ${{ secrets.GH_PAT }}
ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: gpgui-frontend/gpgui
- name: Build gpgui frontend
run: |
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
(
set -euo pipefail
cd gpgui-frontend/gpgui/apps/desktop
pnpm install --frozen-lockfile
pnpm build
) >/dev/null 2>&1
echo "Private operation passed."
cd gpgui-frontend/gpgui/apps/desktop
pnpm install --frozen-lockfile
pnpm build
- name: Upload gpgui frontend
uses: actions/upload-artifact@v7
with:
@@ -917,7 +638,6 @@ jobs:
build-bsd:
needs:
- validate-inputs
- setup-bsd-matrix
- build-gpgui-frontend
if: ${{ needs.setup-bsd-matrix.outputs.enabled == 'true' }}
@@ -934,19 +654,15 @@ jobs:
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ needs.validate-inputs.outputs.gp_sha }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: ${{ matrix.workspace }}/gp
submodules: recursive
- name: Checkout CI helpers
- name: Checkout gpgui
uses: actions/checkout@v6
with:
path: .ci
persist-credentials: false
- name: Checkout gpgui
uses: ./.ci/.github/actions/checkout-private
with:
token: ${{ secrets.GH_PAT }}
ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: ${{ matrix.workspace }}/gpgui
- name: Download gpgui frontend
uses: actions/download-artifact@v8
@@ -983,28 +699,24 @@ jobs:
webkit2-gtk_41
run: |
set -eu
(
set -eu
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
cd "${{ matrix.workspace }}/gp"
cargo build --release --workspace
cd "${{ matrix.workspace }}/gp"
cargo build --release --workspace
cd ../gpgui/apps/desktop/src-tauri
cargo build --release --workspace
cd ../gpgui/apps/desktop/src-tauri
cargo build --release --workspace
cd ../../../../gp
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
pkg install -y ".build/${{ matrix.artifact_dir }}"/artifacts/*.pkg
gpclient --version
gpauth --version
gpgui --version
rm -rf target ../gpgui/target
find ".build/${{ matrix.artifact_dir }}" -mindepth 1 -maxdepth 1 ! -name artifacts -exec rm -rf {} +
) >/dev/null 2>&1
echo "BSD build passed."
cd ../../../../gp
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
pkg install -y ".build/${{ matrix.artifact_dir }}"/artifacts/*.pkg
gpclient --version
gpauth --version
gpgui --version
rm -rf target ../gpgui/target
find ".build/${{ matrix.artifact_dir }}" -mindepth 1 -maxdepth 1 ! -name artifacts -exec rm -rf {} +
- name: Build on OpenBSD
if: ${{ matrix.os == 'openbsd' }}
uses: vmactions/openbsd-vm@v1
@@ -1042,30 +754,26 @@ jobs:
ln -sf /usr/local/bin/automake-1.17 /usr/local/bin/automake
run: |
set -eu
(
set -eu
export AUTOCONF_VERSION=2.72
export AUTOMAKE_VERSION=1.17
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
export AUTOCONF_VERSION=2.72
export AUTOMAKE_VERSION=1.17
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
cd "${{ matrix.workspace }}/gp"
cargo build --release --workspace
cd "${{ matrix.workspace }}/gp"
cargo build --release --workspace
cd ../gpgui/apps/desktop/src-tauri
cargo build --release --workspace
cd ../gpgui/apps/desktop/src-tauri
cargo build --release --workspace
cd ../../../../gp
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
pkg_add -D unsigned ".build/${{ matrix.artifact_dir }}"/artifacts/*.tgz
gpclient --version
gpauth --version
gpgui --version
rm -rf target ../gpgui/target
find ".build/${{ matrix.artifact_dir }}" -mindepth 1 -maxdepth 1 ! -name artifacts -exec rm -rf {} +
) >/dev/null 2>&1
echo "BSD build passed."
cd ../../../../gp
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
pkg_add -D unsigned ".build/${{ matrix.artifact_dir }}"/artifacts/*.tgz
gpclient --version
gpauth --version
gpgui --version
rm -rf target ../gpgui/target
find ".build/${{ matrix.artifact_dir }}" -mindepth 1 -maxdepth 1 ! -name artifacts -exec rm -rf {} +
- name: Upload BSD package
uses: actions/upload-artifact@v7
with:
@@ -1084,9 +792,7 @@ jobs:
attestations: write
artifact-metadata: write
needs:
- validate-inputs
- test-gp
- test-gpgui
- nix-source
- nix-prebuilt
- tarball
@@ -1142,7 +848,7 @@ jobs:
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ needs.validate-inputs.outputs.gp_sha }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: gh-release/gp
submodules: recursive
@@ -1190,11 +896,48 @@ jobs:
run: |
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
wait-gpgui-macos:
if: ${{ !cancelled() && needs.trigger-gpgui-macos.result == 'success' }}
needs:
- trigger-gpgui-macos
runs-on: ubuntu-latest
timeout-minutes: 130
steps:
- name: Wait for private macOS build
env:
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
PRIVATE_RUN_ID: ${{ needs.trigger-gpgui-macos.outputs.run_id }}
PRIVATE_RUN_URL: ${{ needs.trigger-gpgui-macos.outputs.run_url }}
run: |
set -euo pipefail
if [[ -z "$PRIVATE_RUN_ID" ]]; then
echo "The private macOS workflow was not started" >&2
exit 1
fi
for _ in $(seq 1 480); do
run="$(gh api "repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID")"
status="$(jq -r '.status' <<<"$run")"
conclusion="$(jq -r '.conclusion // ""' <<<"$run")"
if [[ "$status" == "completed" ]]; then
echo "Private macOS build completed: $PRIVATE_RUN_URL"
if [[ "$conclusion" != "success" ]]; then
echo "Private macOS build concluded with: $conclusion" >&2
exit 1
fi
exit 0
fi
sleep 15
done
gh api --method POST \
"repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID/cancel" >/dev/null || true
echo "Private macOS build timed out: $PRIVATE_RUN_URL" >&2
exit 1
publish-docker-image:
needs:
- validate-inputs
- test-gp
- test-gpgui
- build-docker-image
if: ${{ (github.event_name == 'workflow_dispatch' && !inputs.build_only) || (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')) }}
runs-on: ubuntu-latest
-34
View File
@@ -1,34 +0,0 @@
name: Desktop icon compatibility
on:
pull_request:
paths:
- '.github/workflows/desktop-icons.yaml'
- 'scripts/tests/test_desktop_icon.py'
- 'packaging/files/usr/share/icons/**'
- 'apps/gpgui-helper/src-tauri/icons/**'
push:
branches: [main]
paths:
- '.github/workflows/desktop-icons.yaml'
- 'scripts/tests/test_desktop_icon.py'
- 'packaging/files/usr/share/icons/**'
- 'apps/gpgui-helper/src-tauri/icons/**'
permissions:
contents: read
jobs:
render:
strategy:
matrix:
os: [ubuntu-22.04, ubuntu-24.04]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v6
- name: Install the distro SVG loader
run: |
sudo apt-get update
sudo apt-get install -y python3-gi gir1.2-gdkpixbuf-2.0 librsvg2-common
- name: Render desktop icons
run: /usr/bin/python3 -m unittest discover -s scripts/tests -p test_desktop_icon.py
-10
View File
@@ -3,8 +3,6 @@ name: Nix
on:
pull_request:
paths:
- "Cargo.toml"
- "scripts/validate-release-version.py"
- "flake.nix"
- "flake.lock"
- "nix/**"
@@ -13,8 +11,6 @@ on:
branches:
- main
paths:
- "Cargo.toml"
- "scripts/validate-release-version.py"
- "flake.nix"
- "flake.lock"
- "nix/**"
@@ -48,9 +44,6 @@ jobs:
--extra-experimental-features "nix-command flakes" \
--print-build-logs
- name: Check installed release versions
run: python3 scripts/validate-release-version.py --package result
- name: Inspect prebuilt package
run: |
test -x result/bin/gpclient
@@ -116,9 +109,6 @@ jobs:
package
'
- name: Check installed release versions
run: python3 scripts/validate-release-version.py --package result
- name: Inspect module package
run: |
test -x result/bin/gpclient
-135
View File
@@ -1,135 +0,0 @@
name: Publish macOS assets
on:
workflow_dispatch:
inputs:
build_run_id:
description: 'Public gp Build run ID with a successful build-macos job'
required: true
type: string
release_tag:
description: 'Existing public release tag (vX.Y.Z or snapshot)'
required: true
type: string
concurrency:
group: publish-macos-assets
cancel-in-progress: false
permissions:
contents: write
actions: read
jobs:
publish:
runs-on: ubuntu-latest
environment: macos-release
timeout-minutes: 15
steps:
- uses: actions/checkout@v6
- name: Check completed build and public release
id: build
env:
GH_TOKEN: ${{ github.token }}
BUILD_REPOSITORY: yuezk/GlobalProtect-openconnect
BUILD_RUN_ID: ${{ inputs.build_run_id }}
RELEASE_TAG: ${{ inputs.release_tag }}
run: |
set -euo pipefail
[[ "$BUILD_RUN_ID" =~ ^[0-9]+$ ]]
[[ "$RELEASE_TAG" == snapshot || "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]
run="$(gh api "repos/$BUILD_REPOSITORY/actions/runs/$BUILD_RUN_ID")"
jq -e '(.event == "workflow_dispatch" or .event == "push") and
.path == ".github/workflows/build.yaml"' <<<"$run" >/dev/null
attempt="$(jq -r '.run_attempt' <<<"$run")"
artifact_name="$(bash scripts/select-macos-artifact.sh "$BUILD_REPOSITORY" "$BUILD_RUN_ID" "$attempt")"
{
echo "artifact=$artifact_name"
echo "workflow_commit=$(jq -r '.head_sha' <<<"$run")"
} >> "$GITHUB_OUTPUT"
gh release view "$RELEASE_TAG" \
--repo yuezk/GlobalProtect-openconnect --json isDraft,isPrerelease \
--jq 'select(.isDraft == false and .isPrerelease == false)' | jq -e .
- name: Download completed build artifacts
uses: actions/download-artifact@v8
with:
repository: yuezk/GlobalProtect-openconnect
github-token: ${{ github.token }}
run-id: ${{ inputs.build_run_id }}
name: ${{ steps.build.outputs.artifact }}
path: release-assets
- name: Validate build identity and checksums
id: metadata
env:
RELEASE_TAG: ${{ inputs.release_tag }}
WORKFLOW_COMMIT: ${{ steps.build.outputs.workflow_commit }}
ARTIFACT_NAME: ${{ steps.build.outputs.artifact }}
run: |
set -euo pipefail
metadata="$(python3 scripts/validate-macos-release.py release-assets \
--release-tag "$RELEASE_TAG" --workflow-commit "$WORKFLOW_COMMIT")"
[[ "$ARTIFACT_NAME" == "macos-release-$(jq -r '.request_id' <<<"$metadata")" ]]
{
echo "gp_ref=$(jq -r '.gp_ref' <<<"$metadata")"
echo "gpgui_ref=$(jq -r '.gpgui_ref' <<<"$metadata")"
echo "channel=$(jq -r '.channel' <<<"$metadata")"
} >> "$GITHUB_OUTPUT"
- name: Checkout public upload helper
uses: actions/checkout@v6
with:
repository: yuezk/GlobalProtect-openconnect
ref: ${{ steps.metadata.outputs.gp_ref }}
path: gp-release
- name: Check stable tags
if: ${{ steps.metadata.outputs.channel == 'stable' }}
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
RELEASE_TAG: ${{ inputs.release_tag }}
GP_REF: ${{ steps.metadata.outputs.gp_ref }}
GPGUI_REF: ${{ steps.metadata.outputs.gpgui_ref }}
run: |
set -euo pipefail
git -C gp-release fetch --no-tags origin "refs/tags/$RELEASE_TAG"
if [[ "$(git -C gp-release rev-parse 'FETCH_HEAD^{commit}')" != "$GP_REF" ]]; then
echo "gp source commit does not match $RELEASE_TAG" >&2
exit 1
fi
if ! tagged_gui_commit="$(gh api "repos/yuezk/gpgui/commits/$RELEASE_TAG" --jq .sha 2>/dev/null)"; then
echo "Private source tag verification failed; diagnostics suppressed." >&2
exit 1
fi
if [[ "$tagged_gui_commit" != "$GPGUI_REF" ]]; then
echo "gpgui source commit does not match $RELEASE_TAG" >&2
exit 1
fi
- name: Publish and verify macOS assets
env:
GH_TOKEN: ${{ github.token }}
RELEASE_REPOSITORY: yuezk/GlobalProtect-openconnect
RELEASE_TAG: ${{ inputs.release_tag }}
CHANNEL: ${{ steps.metadata.outputs.channel }}
run: |
set -euo pipefail
files=(release-assets/*.dmg release-assets/*.zip release-assets/*.sha256)
args=()
if [[ "$CHANNEL" == snapshot ]]; then
args+=(--clobber)
fi
gp-release/scripts/upload-release-assets.sh "${args[@]}" "$RELEASE_TAG" "${files[@]}"
gh release download "$RELEASE_TAG" --repo yuezk/GlobalProtect-openconnect \
--pattern 'GPConnect_*_arm64.*' --dir published-assets
python3 - <<'PY'
import hashlib
import json
from pathlib import Path
metadata = json.loads(Path("release-assets/release-build.json").read_text())
for name, digest in metadata["assets"].items():
if hashlib.sha256((Path("published-assets") / name).read_bytes()).hexdigest() != digest:
raise SystemExit(f"Published asset checksum mismatch: {name}")
PY
echo "Published verified macOS assets to $RELEASE_TAG" >> "$GITHUB_STEP_SUMMARY"
-621
View File
@@ -1,621 +0,0 @@
name: Publish update feeds
on:
workflow_call:
secrets:
GH_PAT:
required: true
CLOUDFLARE_ACCOUNT_ID:
required: false
CLOUDFLARE_API_TOKEN:
required: false
SPARKLE_PRIVATE_KEY:
required: false
inputs:
gpgui_ref:
required: true
type: string
channel:
required: true
type: string
release_tag:
required: true
type: string
archive_name:
required: false
type: string
gp_ref:
required: true
type: string
highlights:
required: false
type: string
unix_platforms:
required: false
default: linux,freebsd,openbsd
type: string
workflow_dispatch:
inputs:
gpgui_ref:
description: gpgui ref containing the update feed Worker
required: true
default: main
type: string
channel:
description: Update channel
required: true
type: choice
options:
- stable
- snapshot
release_tag:
description: Release containing the macOS update archive
required: true
type: string
archive_name:
description: Exact ZIP asset name; leave empty when the release has one macOS update archive
required: false
type: string
gp_ref:
description: GlobalProtect-openconnect ref containing release helpers
required: true
default: main
type: string
highlights:
description: Stable release highlights, one per line
required: false
type: string
unix_platforms:
description: Comma-separated Unix platforms with published assets (linux,freebsd,openbsd)
required: true
default: linux,freebsd,openbsd
type: string
concurrency:
group: update-feeds
cancel-in-progress: false
jobs:
publish:
runs-on: ${{ vars.MACOS_RUNNER || 'macos-15' }}
environment: macos-release
permissions:
contents: write
env:
REPOSITORY: yuezk/GlobalProtect-openconnect
RELEASE_TAG: ${{ inputs.release_tag }}
CHANNEL: ${{ inputs.channel }}
REQUESTED_ARCHIVE: ${{ inputs.archive_name }}
FEED_URL: ${{ vars.SPARKLE_FEED_URL }}
EXPECTED_TEAM_ID: ${{ vars.MACOS_TEAM_ID }}
UPDATES_WORKER_NAME: ${{ vars.UPDATES_WORKER_NAME || 'gp-updates' }}
SPARKLE_VERSION: 2.9.2
UPDATE_HIGHLIGHTS: ${{ inputs.highlights }}
UNIX_PLATFORMS: ${{ inputs.unix_platforms }}
SPARKLE_ARCHIVE_SHA256: b83e37436774556ed055e0244b297ef2c790e0737393bf65bf495fcbba6eed65
steps:
- name: Validate inputs
env:
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
run: |
set -euo pipefail
if [[ "$CHANNEL" != "stable" && "$CHANNEL" != "snapshot" ]]; then
echo "channel must be stable or snapshot" >&2
exit 1
fi
if [[ ! "$UNIX_PLATFORMS" =~ ^(linux|freebsd|openbsd)(,(linux|freebsd|openbsd))*$ ]]; then
echo "unix_platforms must list published Unix targets separated by commas" >&2
exit 1
fi
if [[ "$CHANNEL" == "snapshot" && "$RELEASE_TAG" != "snapshot" ]]; then
echo "The snapshot channel must publish to the snapshot release" >&2
exit 1
fi
if [[ "$CHANNEL" == "stable" && "$RELEASE_TAG" == "snapshot" ]]; then
echo "The stable channel cannot publish to the snapshot release" >&2
exit 1
fi
if [[ "$CHANNEL" == "stable" && -z "${UPDATE_HIGHLIGHTS//[$'\t\r\n ']/}" ]]; then
echo "Stable updates require at least one release highlight" >&2
exit 1
fi
if [[ -z "$SPARKLE_PRIVATE_KEY" ]]; then
echo "SPARKLE_PRIVATE_KEY is not configured" >&2
exit 1
fi
if [[ -z "$EXPECTED_TEAM_ID" ]]; then
echo "MACOS_TEAM_ID is not configured" >&2
exit 1
fi
for variable in CLOUDFLARE_ACCOUNT_ID CLOUDFLARE_API_TOKEN; do
if [[ -z "${!variable:-}" ]]; then
echo "$variable is not configured" >&2
exit 1
fi
done
if [[ "$FEED_URL" != https://*/appcast.xml ]]; then
echo "SPARKLE_FEED_URL must be an HTTPS URL ending in /appcast.xml" >&2
exit 1
fi
- name: Checkout release infrastructure
uses: actions/checkout@v6
- name: Checkout public release helpers
uses: actions/checkout@v6
with:
repository: yuezk/GlobalProtect-openconnect
ref: ${{ inputs.gp_ref }}
path: gp-release
- name: Checkout update feed Worker
uses: ./.github/actions/checkout-private
with:
token: ${{ secrets.GH_PAT }}
ref: ${{ inputs.gpgui_ref }}
path: gpgui
- uses: pnpm/action-setup@v5
with:
version: 9.15.1
- uses: actions/setup-node@v6
with:
node-version: 22
- name: Install Worker tooling
run: |
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
(
set -euo pipefail
pnpm --dir gpgui/apps/update-feed-worker install --frozen-lockfile --ignore-scripts
) >/dev/null 2>&1
echo "Private operation passed."
- name: Prepare Sparkle tools
run: |
set -euo pipefail
archive="$RUNNER_TEMP/Sparkle.zip"
curl --fail --location --silent --show-error \
"https://github.com/sparkle-project/Sparkle/releases/download/$SPARKLE_VERSION/Sparkle-for-Swift-Package-Manager.zip" \
--output "$archive"
echo "$SPARKLE_ARCHIVE_SHA256 $archive" | shasum -a 256 --check
ditto -x -k "$archive" "$RUNNER_TEMP/sparkle"
test -x "$RUNNER_TEMP/sparkle/bin/generate_appcast"
- name: Validate GitHub release
id: release
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
release="$(gh release view "$RELEASE_TAG" --repo "$REPOSITORY" \
--json tagName,isDraft,isPrerelease,publishedAt)"
if [[ "$(jq -r '.tagName' <<<"$release")" != "$RELEASE_TAG" ]] || \
[[ "$(jq -r '.isDraft' <<<"$release")" != "false" ]]; then
echo "Release must be published with the requested tag" >&2
exit 1
fi
is_prerelease="$(jq -r '.isPrerelease' <<<"$release")"
if [[ "$is_prerelease" != "false" ]]; then
echo "Updates require a non-prerelease GitHub release" >&2
exit 1
fi
published_at="$(jq -r '.publishedAt' <<<"$release")"
if [[ ! "$published_at" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T ]]; then
echo "Release has no valid publication date" >&2
exit 1
fi
echo "released_at=${published_at%%T*}" >> "$GITHUB_OUTPUT"
- name: Download update archive
id: archive
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
mkdir -p "$RUNNER_TEMP/updates"
archive_name="$REQUESTED_ARCHIVE"
if [[ -z "$archive_name" ]]; then
archive_name="$(gh release view "$RELEASE_TAG" --repo "$REPOSITORY" --json assets \
--jq '[.assets[] | select(.name | test("^GPConnect_[0-9A-Za-z._-]+_arm64\\.zip$"))] | sort_by(.createdAt) | last | .name // ""')"
if [[ -z "$archive_name" ]]; then
echo "No macOS update archive found on $RELEASE_TAG" >&2
exit 1
fi
fi
if [[ ! "$archive_name" =~ ^GPConnect_[0-9A-Za-z._-]+_arm64\.zip$ ]]; then
echo "Invalid macOS update archive name: $archive_name" >&2
exit 1
fi
gh release download "$RELEASE_TAG" --repo "$REPOSITORY" \
--pattern "$archive_name" \
--pattern "$archive_name.sha256" \
--dir "$RUNNER_TEMP/updates"
{
echo "name=$archive_name"
echo "path=$RUNNER_TEMP/updates/$archive_name"
echo "checksum_path=$RUNNER_TEMP/updates/$archive_name.sha256"
} >> "$GITHUB_OUTPUT"
- name: Verify update archive
id: bundle
env:
ARCHIVE_PATH: ${{ steps.archive.outputs.path }}
CHECKSUM_PATH: ${{ steps.archive.outputs.checksum_path }}
run: |
set -euo pipefail
expected_digest="$(awk 'NR == 1 { print $1 }' "$CHECKSUM_PATH")"
actual_digest="$(shasum -a 256 "$ARCHIVE_PATH" | awk '{ print $1 }')"
if [[ -z "$expected_digest" || "$actual_digest" != "$expected_digest" ]]; then
echo "Update archive checksum does not match its release checksum" >&2
exit 1
fi
extract_dir="$RUNNER_TEMP/extracted"
ditto -x -k "$ARCHIVE_PATH" "$extract_dir"
app="$extract_dir/GP Connect.app"
test -d "$app"
codesign --verify --deep --strict --verbose=2 "$app"
signing_info="$(codesign -d --verbose=4 "$app" 2>&1)"
xcrun stapler validate "$app"
grep -q '^Authority=Developer ID Application:' <<<"$signing_info"
grep -q '^CodeDirectory .*flags=.*runtime' <<<"$signing_info"
team_identifier="$(sed -n 's/^TeamIdentifier=//p' <<<"$signing_info")"
if [[ "$team_identifier" != "$EXPECTED_TEAM_ID" ]]; then
echo "Unexpected Apple Team Identifier: $team_identifier" >&2
exit 1
fi
identifier="$(sed -n 's/^Identifier=//p' <<<"$signing_info")"
if [[ "$identifier" != "com.yuezk.gpgui" ]]; then
echo "Unexpected bundle identifier: $identifier" >&2
exit 1
fi
file "$app/Contents/MacOS/gpgui" | grep -q 'arm64'
feed_url="$(plutil -extract SUFeedURL raw "$app/Contents/Info.plist")"
if [[ "$feed_url" != "$FEED_URL" ]]; then
echo "Unexpected Sparkle feed URL: $feed_url" >&2
exit 1
fi
update_channel="$(plutil -extract GPUpdateChannel raw "$app/Contents/Info.plist")"
if [[ "$update_channel" != "$CHANNEL" ]]; then
echo "Unexpected update channel: $update_channel" >&2
exit 1
fi
bundle_version="$(plutil -extract CFBundleVersion raw "$app/Contents/Info.plist")"
short_version="$(plutil -extract CFBundleShortVersionString raw "$app/Contents/Info.plist")"
if [[ ! "$bundle_version" =~ ^[0-9]+(\.[0-9]+){0,2}$ ]]; then
echo "Invalid bundle version: $bundle_version" >&2
exit 1
fi
if [[ "$CHANNEL" == "stable" ]]; then
expected_tag="v$short_version"
expected_archive="GPConnect_${short_version}_arm64.zip"
else
expected_tag="snapshot"
expected_archive="GPConnect_${short_version}-snapshot.${bundle_version}_arm64.zip"
fi
if [[ "$RELEASE_TAG" != "$expected_tag" ]]; then
echo "Release tag $RELEASE_TAG does not match $expected_tag" >&2
exit 1
fi
if [[ "${{ steps.archive.outputs.name }}" != "$expected_archive" ]]; then
echo "Archive name does not match packaged version: $expected_archive" >&2
exit 1
fi
echo "version=$bundle_version" >> "$GITHUB_OUTPUT"
echo "short_version=$short_version" >> "$GITHUB_OUTPUT"
- name: Prepare Unix update manifest
env:
RELEASED_AT: ${{ steps.release.outputs.released_at }}
run: |
set -euo pipefail
manifest="$RUNNER_TEMP/updates/latest.json"
current_manifest="$RUNNER_TEMP/current-latest.json"
latest_url="${FEED_URL%/appcast.xml}/latest.json"
status="$(curl --location --silent --show-error \
--output "$current_manifest" --write-out '%{http_code}' "$latest_url")"
generate_args=(
--repository "$REPOSITORY"
--channel "$CHANNEL"
--version "${{ steps.bundle.outputs.short_version }}"
)
IFS=',' read -r -a platforms <<<"$UNIX_PLATFORMS"
for platform in "${platforms[@]}"; do
generate_args+=(--platform "$platform")
done
case "$status" in
200)
python3 scripts/validate-update-manifest.py validate "$current_manifest" \
--repository "$REPOSITORY"
generate_args+=(--input "$current_manifest")
;;
404)
;;
*)
echo "Could not check the current Unix update manifest: HTTP $status" >&2
exit 1
;;
esac
highlights="$RUNNER_TEMP/update-highlights.txt"
if [[ "$CHANNEL" == "stable" ]]; then
printf '%s\n' "$UPDATE_HIGHLIGHTS" > "$highlights"
released_at="$RELEASED_AT"
else
printf 'Development snapshot after %s.\n' \
"${{ steps.bundle.outputs.short_version }}" > "$highlights"
generate_args+=(--build "${{ steps.bundle.outputs.version }}")
released_at="$(date -u +%F)"
fi
python3 scripts/validate-update-manifest.py generate \
"${generate_args[@]}" \
--released-at "$released_at" \
--highlights-file "$highlights" \
--output "$manifest"
- name: Fetch current appcast
id: current-appcast
env:
ARCHIVE_NAME: ${{ steps.archive.outputs.name }}
run: |
set -euo pipefail
appcast="$RUNNER_TEMP/updates/appcast.xml"
archive_url="https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/$ARCHIVE_NAME"
status="$(curl --location --silent --show-error \
--output "$appcast" --write-out '%{http_code}' "$FEED_URL")"
case "$status" in
200)
test -s "$appcast"
decision="$(python3 scripts/validate-macos-appcast.py status "$appcast" \
--repository "$REPOSITORY" \
--build-version "${{ steps.bundle.outputs.version }}")"
if [[ "$decision" == "older" ]]; then
echo "Candidate build is older than the published appcast" >&2
exit 1
fi
if [[ "$decision" == "same" ]]; then
python3 scripts/validate-macos-appcast.py validate "$appcast" \
--repository "$REPOSITORY" \
--build-version "${{ steps.bundle.outputs.version }}" \
--short-version "${{ steps.bundle.outputs.short_version }}" \
--channel "$CHANNEL" \
--archive-url "$archive_url"
fi
echo "decision=$decision" >> "$GITHUB_OUTPUT"
;;
404)
rm -f "$appcast"
echo "decision=newer" >> "$GITHUB_OUTPUT"
;;
*)
echo "Could not fetch the current appcast: HTTP $status" >&2
exit 1
;;
esac
- name: Generate appcast
if: ${{ steps.current-appcast.outputs.decision == 'newer' }}
env:
ARCHIVE_NAME: ${{ steps.archive.outputs.name }}
SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
run: |
set -euo pipefail
embedded_public_key="$(plutil -extract SUPublicEDKey raw \
"$RUNNER_TEMP/extracted/GP Connect.app/Contents/Info.plist")"
derived_public_key="$(swift -e '
import Foundation
import CryptoKit
let encoded = ProcessInfo.processInfo.environment["SPARKLE_PRIVATE_KEY"]!
.trimmingCharacters(in: .whitespacesAndNewlines)
let privateKey = try Curve25519.Signing.PrivateKey(
rawRepresentation: Data(base64Encoded: encoded)!)
print(privateKey.publicKey.rawRepresentation.base64EncodedString())
')"
if [[ "$derived_public_key" != "$embedded_public_key" ]]; then
echo "Sparkle private key does not match the public key embedded in the application" >&2
exit 1
fi
download_prefix="https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/"
generate_args=(
--download-url-prefix "$download_prefix"
--full-release-notes-url "https://github.com/$REPOSITORY/releases/tag/$RELEASE_TAG"
--maximum-deltas 0
--maximum-versions 1
--versions "${{ steps.bundle.outputs.version }}"
--ed-key-file -
)
if [[ "$CHANNEL" == "snapshot" ]]; then
generate_args+=(--channel snapshot)
fi
printf '%s' "$SPARKLE_PRIVATE_KEY" | \
"$RUNNER_TEMP/sparkle/bin/generate_appcast" \
"${generate_args[@]}" "$RUNNER_TEMP/updates"
appcast="$RUNNER_TEMP/updates/appcast.xml"
test -s "$appcast"
python3 scripts/validate-macos-appcast.py validate "$appcast" \
--repository "$REPOSITORY" \
--build-version "${{ steps.bundle.outputs.version }}" \
--short-version "${{ steps.bundle.outputs.short_version }}" \
--channel "$CHANNEL" \
--archive-url "$download_prefix$ARCHIVE_NAME"
- name: Publish appcast
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
appcast="$RUNNER_TEMP/updates/appcast.xml"
archive_url="https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/${{ steps.archive.outputs.name }}"
if [[ "$CHANNEL" == "stable" ]] && \
gh release view "$RELEASE_TAG" --repo "$REPOSITORY" --json assets \
--jq '.assets[].name' | grep -Fx appcast.xml >/dev/null; then
existing="$RUNNER_TEMP/existing-release-appcast.xml"
gh release download "$RELEASE_TAG" --repo "$REPOSITORY" \
--pattern appcast.xml --output "$existing"
python3 scripts/validate-macos-appcast.py validate "$existing" \
--repository "$REPOSITORY" \
--build-version "${{ steps.bundle.outputs.version }}" \
--short-version "${{ steps.bundle.outputs.short_version }}" \
--channel "$CHANNEL" \
--archive-url "$archive_url"
cp "$existing" "$appcast"
else
if [[ "$CHANNEL" == "snapshot" ]]; then
RELEASE_REPOSITORY="$REPOSITORY" \
gp-release/scripts/upload-release-assets.sh \
--clobber "$RELEASE_TAG" "$appcast"
else
RELEASE_REPOSITORY="$REPOSITORY" \
gp-release/scripts/upload-release-assets.sh "$RELEASE_TAG" "$appcast"
fi
fi
- name: Validate final appcast
env:
ARCHIVE_NAME: ${{ steps.archive.outputs.name }}
run: |
python3 scripts/validate-macos-appcast.py validate \
"$RUNNER_TEMP/updates/appcast.xml" \
--repository "$REPOSITORY" \
--build-version "${{ steps.bundle.outputs.version }}" \
--short-version "${{ steps.bundle.outputs.short_version }}" \
--channel "$CHANNEL" \
--archive-url "https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/$ARCHIVE_NAME"
- name: Deploy update feed worker
env:
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
run: |
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
(
set -euo pipefail
cp "$RUNNER_TEMP/updates/appcast.xml" gpgui/apps/update-feed-worker/public/appcast.xml
if [[ -f "$RUNNER_TEMP/updates/latest.json" ]]; then
cp "$RUNNER_TEMP/updates/latest.json" gpgui/apps/update-feed-worker/public/latest.json
fi
pnpm --dir gpgui/apps/update-feed-worker exec wrangler deploy \
--config wrangler.jsonc \
--name "$UPDATES_WORKER_NAME"
) >/dev/null 2>&1
echo "Private operation passed."
- name: Verify published appcast
env:
ARCHIVE_NAME: ${{ steps.archive.outputs.name }}
run: |
set -euo pipefail
published_appcast="$RUNNER_TEMP/published-appcast.xml"
for _ in 1 2 3 4 5 6 7 8 9 10; do
if curl --fail --location --silent --show-error \
--output "$published_appcast" "$FEED_URL" && \
python3 scripts/validate-macos-appcast.py validate "$published_appcast" \
--repository "$REPOSITORY" \
--build-version "${{ steps.bundle.outputs.version }}" \
--short-version "${{ steps.bundle.outputs.short_version }}" \
--channel "$CHANNEL" \
--archive-url "https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/$ARCHIVE_NAME"; then
exit 0
fi
sleep 3
done
echo "Published appcast did not become available at $FEED_URL" >&2
exit 1
- name: Verify published Unix update manifest
run: |
set -euo pipefail
latest_url="${FEED_URL%/appcast.xml}/latest.json"
published_manifest="$RUNNER_TEMP/published-latest.json"
expected=(
--channel "$CHANNEL"
--version "${{ steps.bundle.outputs.short_version }}"
)
if [[ "$CHANNEL" == "snapshot" ]]; then
expected+=(--build "${{ steps.bundle.outputs.version }}")
fi
for _ in 1 2 3 4 5 6 7 8 9 10; do
if curl --fail --location --silent --show-error \
--output "$published_manifest" "$latest_url" && \
python3 scripts/validate-update-manifest.py validate "$published_manifest" \
--repository "$REPOSITORY" "${expected[@]}"; then
if ! cmp --silent "$RUNNER_TEMP/updates/latest.json" "$published_manifest"; then
sleep 3
continue
fi
exit 0
fi
sleep 3
done
echo "Published Unix update manifest did not become available at $latest_url" >&2
exit 1
- name: Prune expired snapshot assets
if: ${{ inputs.channel == 'snapshot' }}
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
assets="$RUNNER_TEMP/snapshot-assets.json"
delete_list="$RUNNER_TEMP/delete-snapshot-assets.txt"
gh release view snapshot --repo "$REPOSITORY" --json assets > "$assets"
ASSETS="$assets" python3 - <<'PY' > "$delete_list"
import json
import os
import re
with open(os.environ["ASSETS"], encoding="utf-8") as file:
assets = json.load(file)["assets"]
archive_pattern = re.compile(
r"^(GPConnect_.+-snapshot\.(\d+(?:\.\d+){1,2}))_arm64\.zip$"
)
asset_pattern = re.compile(
r"^(GPConnect_.+-snapshot\.\d+(?:\.\d+){1,2})_arm64\.(?:zip|dmg)(?:\.sha256)?$"
)
builds = []
for asset in assets:
match = archive_pattern.match(asset["name"])
if match:
builds.append((tuple(map(int, match.group(2).split("."))), match.group(1)))
keep = {stem for _, stem in sorted(builds, reverse=True)[:2]}
for asset in assets:
match = asset_pattern.match(asset["name"])
if match and not any(asset["name"].startswith(stem + "_arm64.") for stem in keep):
print(asset["name"])
PY
while IFS= read -r asset; do
if [[ -n "$asset" ]] && ! gh release delete-asset snapshot "$asset" \
--repo "$REPOSITORY" --yes; then
echo "::warning::Could not remove expired snapshot asset: $asset" >&2
fi
done < "$delete_list"
-39
View File
@@ -4,44 +4,18 @@ on:
pull_request:
paths:
- '.github/workflows/**'
- '.github/actions/**'
- 'scripts/record-build-sources.py'
- 'scripts/validate-release-version.py'
- 'scripts/publish-flake-test-branch.sh'
- 'scripts/prepare-release-promotion.sh'
- 'scripts/tests/test_release_flow.py'
- 'scripts/select-macos-artifact.sh'
- 'scripts/test-private-desktop.sh'
- 'scripts/tests/test_private_ci.py'
- 'scripts/wait-for-publication.py'
- 'scripts/select-publication-targets.py'
- 'scripts/verify-docker-publication.sh'
- 'scripts/tests/test_*publication.py'
- 'scripts/validate-macos-release.py'
- 'scripts/validate-macos-appcast.py'
- 'scripts/validate-update-manifest.py'
- 'scripts/tests/test_validate_*.py'
push:
branches: [main]
paths:
- '.github/workflows/**'
- '.github/actions/**'
- 'scripts/record-build-sources.py'
- 'scripts/validate-release-version.py'
- 'scripts/publish-flake-test-branch.sh'
- 'scripts/prepare-release-promotion.sh'
- 'scripts/tests/test_release_flow.py'
- 'scripts/select-macos-artifact.sh'
- 'scripts/test-private-desktop.sh'
- 'scripts/tests/test_private_ci.py'
- 'scripts/wait-for-publication.py'
- 'scripts/select-publication-targets.py'
- 'scripts/verify-docker-publication.sh'
- 'scripts/tests/test_*publication.py'
- 'scripts/validate-macos-release.py'
- 'scripts/validate-macos-appcast.py'
- 'scripts/validate-update-manifest.py'
- 'scripts/tests/test_validate_*.py'
permissions:
contents: read
@@ -62,16 +36,3 @@ jobs:
shellcheck scripts/verify-docker-publication.sh
- name: Test publication verification
run: python3 -m unittest discover -s scripts/tests -p 'test_*publication.py'
- name: Test macOS publication and update feed validation
run: python3 -m unittest discover -s scripts/tests -p 'test_validate_*.py'
- name: Check private CI and macOS artifact selection
run: |
bash -n scripts/select-macos-artifact.sh
shellcheck scripts/select-macos-artifact.sh scripts/test-private-desktop.sh
bash -n scripts/test-private-desktop.sh
python3 -m unittest discover -s scripts/tests -p 'test_private_ci.py'
- name: Test release promotion and source selection
run: |
bash -n scripts/prepare-release-promotion.sh scripts/publish-flake-test-branch.sh
shellcheck scripts/prepare-release-promotion.sh scripts/publish-flake-test-branch.sh
python3 -m unittest discover -s scripts/tests -p 'test_release_flow.py'
-23
View File
@@ -1,23 +0,0 @@
name: Release version consistency
on:
pull_request:
branches: [main]
push:
branches: [main]
permissions:
contents: read
jobs:
release-version:
runs-on: ubuntu-latest
steps:
# The default PR checkout is the candidate merged with the current base.
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Check main release version
env:
BASE_REF: ${{ github.event.pull_request.base.sha || github.event.before }}
run: python3 scripts/validate-release-version.py --base-ref "$BASE_REF"
+7 -20
View File
@@ -73,7 +73,6 @@ jobs:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.result }}
docker_matrix: ${{ steps.set-matrix.outputs.docker_matrix }}
steps:
- name: Set up matrix
id: set-matrix
@@ -89,12 +88,6 @@ jobs:
"arm64": ["ubuntu-24.04-arm"]
}
const docker = [
{ runner: 'ubuntu-latest', platform: 'linux/amd64' },
{ runner: 'ubuntu-24.04-arm', platform: 'linux/arm64' },
].filter(item => osMap[arch].includes(item.runner))
core.setOutput('docker_matrix', JSON.stringify({ include: docker }))
const package = Object.entries(inputs)
.filter(([key, value]) => key.startsWith('release-') && key !== 'release-docker' && value)
.map(([key, value]) => key.replace('release-', ''))
@@ -152,11 +145,15 @@ jobs:
build-docker-image:
needs:
- check
- setup-matrix
if: ${{ inputs.release-docker }}
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.setup-matrix.outputs.docker_matrix) }}
matrix:
include:
- runner: ubuntu-latest
platform: linux/amd64
- runner: ubuntu-24.04-arm
platform: linux/arm64
runs-on: ${{ matrix.runner }}
steps:
- name: Prepare
@@ -238,17 +235,6 @@ jobs:
IMAGE: yuezk/globalprotect-openconnect
TAG: ${{ inputs.tag }}
run: |
# Reject an incomplete or unexpected selection before writing any tag.
shopt -s nullglob
digest_files=(*)
expected_count=1
if [[ "${{ inputs.arch }}" == all ]]; then
expected_count=2
fi
[[ ${#digest_files[@]} -eq $expected_count ]]
for digest in "${digest_files[@]}"; do
[[ "$digest" =~ ^[0-9a-f]{64}$ ]]
done
VERSION="${TAG#v}"
tags=(-t "$IMAGE:$TAG")
@@ -349,6 +335,7 @@ jobs:
if: ${{ inputs.release-binary && inputs.arch == 'all' && needs.gh-release.outputs.stable_version != '' }}
permissions:
contents: write
pull-requests: write
uses: ./.github/workflows/update-flake-hashes.yaml
with:
version: ${{ needs.gh-release.outputs.stable_version }}
+10 -52
View File
@@ -20,47 +20,14 @@ on:
permissions:
contents: write
pull-requests: write
jobs:
update-flake-hashes:
runs-on: ubuntu-latest
outputs:
version: ${{ steps.release.outputs.version }}
release_tag: ${{ steps.release.outputs.release_tag }}
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
ref: ${{ github.sha }}
- name: Resolve candidate release
id: release
env:
RELEASE_VERSION: ${{ inputs.version }}
RELEASE_TAG: ${{ inputs.release_tag }}
run: |
python3 - <<'PYRELEASE'
import json, os, re, runpy, subprocess
from pathlib import Path
helpers = runpy.run_path('scripts/validate-release-version.py')
version = os.environ['RELEASE_VERSION'].removeprefix('v') or helpers['cargo_version'](Path('.'))
tag = os.environ['RELEASE_TAG'] or f'v{version}'
if not re.fullmatch(r'(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)', version) or tag not in (f'v{version}', 'snapshot'):
raise SystemExit('Expected a stable version and its matching release tag, or snapshot')
source_slug = re.sub(r'[^A-Za-z0-9._-]', '', re.sub(r'[/\s]+', '-', os.environ['GITHUB_REF_NAME'])).strip('-')
test_branch = f'chore/flake-{source_slug}'
expected_head = ''
if tag == 'snapshot':
remote = subprocess.check_output(['git', 'ls-remote', '--heads', 'origin', f'refs/heads/{test_branch}'], text=True)
expected_head = remote.split()[0] if remote.strip() else ''
with open(os.environ['GITHUB_OUTPUT'], 'a') as output:
output.write(f'version={version}\nrelease_tag={tag}\n')
Path('release-candidate.json').write_text(json.dumps({
'version': version, 'releaseTag': tag, 'sourceSha': os.environ['GITHUB_SHA'],
'workflowRunId': os.environ['GITHUB_RUN_ID'],
'testBranch': test_branch, 'expectedTestHead': expected_head,
}, indent=2) + '\n')
PYRELEASE
- name: Install Nix
uses: cachix/install-nix-action@v31
@@ -72,8 +39,8 @@ jobs:
- name: Update flake hashes
env:
RELEASE_VERSION: ${{ steps.release.outputs.version }}
RELEASE_TAG: ${{ steps.release.outputs.release_tag }}
RELEASE_VERSION: ${{ inputs.version }}
RELEASE_TAG: ${{ inputs.release_tag }}
run: |
if [[ -n "$RELEASE_VERSION" ]]; then
scripts/update-flake-hashes.sh "$RELEASE_VERSION" "$RELEASE_TAG"
@@ -88,7 +55,6 @@ jobs:
path: |
flake.nix
flake.lock
release-candidate.json
if-no-files-found: error
validate-nix-prebuilt:
@@ -113,8 +79,6 @@ jobs:
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
ref: ${{ github.sha }}
- name: Download updated flake
uses: actions/download-artifact@v8
@@ -140,12 +104,6 @@ jobs:
--print-build-logs
fi
- name: Validate installed release versions
run: |
python3 scripts/validate-release-version.py \
--version '${{ needs.update-flake-hashes.outputs.version }}' \
--release-tag '${{ needs.update-flake-hashes.outputs.release_tag }}' --package result
- name: Inspect prebuilt Nix package
run: |
test -x result/bin/gpclient
@@ -168,15 +126,13 @@ jobs:
- name: Verify desktop authorization runs on the host
run: bash scripts/tests/nix-desktop-authorization.sh result
publish-test-branch:
if: needs.update-flake-hashes.outputs.release_tag == 'snapshot'
needs: [update-flake-hashes, validate-nix-prebuilt]
open-pull-request:
needs:
- validate-nix-prebuilt
runs-on: ubuntu-latest
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
ref: ${{ github.sha }}
- name: Download updated flake
uses: actions/download-artifact@v8
@@ -184,7 +140,9 @@ jobs:
name: updated-flake
path: .
- name: Publish branch for snapshot testing
- name: Open pull request
env:
GH_TOKEN: ${{ github.token }}
run: scripts/publish-flake-test-branch.sh
RELEASE_VERSION: ${{ inputs.version }}
RELEASE_TAG: ${{ inputs.release_tag }}
run: scripts/open-flake-hashes-pr.sh "$RELEASE_VERSION" "$RELEASE_TAG"
Generated
+12 -12
View File
@@ -253,7 +253,7 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "auth"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"anyhow",
"block2",
@@ -508,7 +508,7 @@ dependencies = [
[[package]]
name = "browser-launcher"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"anyhow",
"log",
@@ -860,7 +860,7 @@ dependencies = [
[[package]]
name = "common"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"tempfile",
]
@@ -2050,7 +2050,7 @@ dependencies = [
[[package]]
name = "gpapi"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"anyhow",
"base64 0.23.1",
@@ -2104,7 +2104,7 @@ dependencies = [
[[package]]
name = "gpauth"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"anyhow",
"auth",
@@ -2123,7 +2123,7 @@ dependencies = [
[[package]]
name = "gpclient"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"anyhow",
"clap",
@@ -2155,7 +2155,7 @@ dependencies = [
[[package]]
name = "gpgui-helper"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"anyhow",
"clap",
@@ -2176,7 +2176,7 @@ dependencies = [
[[package]]
name = "gphip"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"anyhow",
"askama",
@@ -2193,7 +2193,7 @@ dependencies = [
[[package]]
name = "gpservice"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"anyhow",
"axum",
@@ -2228,7 +2228,7 @@ dependencies = [
[[package]]
name = "gptunnel"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"gpapi",
"log",
@@ -2240,7 +2240,7 @@ dependencies = [
[[package]]
name = "gpvpnc"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"log",
]
@@ -3727,7 +3727,7 @@ dependencies = [
[[package]]
name = "openconnect"
version = "3.2.0"
version = "3.0.6"
dependencies = [
"autotools",
"cc",
+1 -1
View File
@@ -11,7 +11,7 @@ members = [
[workspace.package]
rust-version = "1.91"
version = "3.2.0"
version = "3.0.6"
authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024"
+1 -5
View File
@@ -3,11 +3,7 @@
A GlobalProtect VPN client built on OpenConnect with support for SSO authentication. It provides command-line tools and the GP Connect desktop application for macOS, Linux, FreeBSD, and OpenBSD.
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/images/gp-connect-showcase-dark.png">
<source media="(prefers-color-scheme: light)" srcset="docs/images/gp-connect-showcase-light.png">
<img alt="GP Connect Desktop" src="docs/images/gp-connect-showcase-light.png" width="640">
</picture>
<img width="300" src="https://github.com/user-attachments/assets/2fb6116c-dc57-43f2-af75-9c3d97ab7122">
</p>
> **Inspired by** [gp-saml-gui](https://github.com/dlenski/gp-saml-gui)
+9 -37
View File
@@ -2,7 +2,6 @@
//! No process is forked after authentication or OpenConnect has started its threads.
use std::{
cell::RefCell,
ffi::OsString,
fs::{File, OpenOptions},
io::{self, Write},
@@ -28,8 +27,7 @@ use tokio::{io::AsyncReadExt, process::Command};
const READY: u8 = 1;
pub(crate) struct BackgroundWorker {
// Consumed after detachment; later tunnels stay in the same background session.
ready: RefCell<Option<UnixStream>>,
ready: UnixStream,
log: File,
input: File,
}
@@ -84,17 +82,10 @@ impl BackgroundWorker {
"Background log must not be readable or writable by other users"
);
let input = File::open("/dev/null")?;
Ok(Self {
ready: RefCell::new(Some(ready)),
log,
input,
})
Ok(Self { ready, log, input })
}
pub(crate) fn redirect_stdio(&self) -> anyhow::Result<BackgroundStdio> {
if self.ready.borrow().is_none() {
return Ok(BackgroundStdio { saved: None });
}
io::stdout().flush()?;
io::stderr().flush()?;
let save = |fd| -> anyhow::Result<OwnedFd> {
@@ -116,18 +107,13 @@ impl BackgroundWorker {
}
pub(crate) fn detach(&self, stdio: &mut BackgroundStdio) -> anyhow::Result<()> {
let mut ready = self.ready.borrow_mut();
let Some(socket) = ready.as_mut() else {
return Ok(());
};
// The worker inherited the launcher's foreground group, so it can prompt normally.
// It becomes a session leader only when sign-in and tunnel configuration are done.
setsid().context("Cannot detach the VPN session from the terminal")?;
socket
(&self.ready)
.write_all(&[READY])
.context("Background launcher exited before tunnel setup")?;
stdio.saved.take();
ready.take();
Ok(())
}
}
@@ -219,13 +205,12 @@ mod tests {
}
#[tokio::test]
async fn detached_worker_reconnects_after_launcher_exits() {
async fn detached_worker_survives_launcher_and_disconnects_by_pid() {
let directory = tempfile::tempdir().unwrap();
tokio::time::timeout(Duration::from_secs(5), launch(fixture(directory.path()), &[]))
.await
.unwrap()
.unwrap();
std::fs::write(directory.path().join("reconnect"), "").unwrap();
let pid = std::fs::read_to_string(directory.path().join("pid"))
.unwrap()
.parse::<i32>()
@@ -237,19 +222,18 @@ mod tests {
"Worker must own a terminal-independent session"
);
kill(pid, None).unwrap();
let reconnected = tokio::time::timeout(Duration::from_secs(5), async {
tokio::time::timeout(Duration::from_secs(5), async {
while !std::fs::read_to_string(directory.path().join("worker.log"))
.unwrap()
.contains("reconnected-output")
.contains("helper-output")
{
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await;
.await
.unwrap();
let log = std::fs::read_to_string(directory.path().join("worker.log")).unwrap();
assert!(reconnected.is_ok(), "Worker did not reconnect:\n{log}");
assert!(log.contains("failed-attempt-output"));
assert!(log.contains("helper-output"));
assert!(!log.contains("restored-foreground-output"));
#[derive(clap::Parser)]
struct Disconnect {
@@ -311,20 +295,8 @@ mod tests {
worker.detach(&mut stdio).unwrap();
println!("detached-output");
io::stdout().flush().unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while !directory.join("reconnect").exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
helper.wait().unwrap();
let mut stdio = worker.redirect_stdio().unwrap();
worker.detach(&mut stdio).unwrap();
assert_eq!(getsid(None).unwrap(), getpid());
println!("reconnected-output");
io::stdout().flush().unwrap();
interrupt.recv().await;
helper.wait().unwrap();
std::fs::write(directory.join("stopped"), "stopped").unwrap();
}
}
+1 -33
View File
@@ -112,15 +112,7 @@ pub(crate) struct ConnectArgs {
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
pub(super) mtu: Option<u32>,
#[arg(
long,
value_enum,
default_value = "auto",
help = "Choose which IP version to try first when connecting to the gateway"
)]
pub(super) ip_preference: gpapi::gateway::GatewayIpPreference,
#[arg(long, help = "Use only IPv4 for traffic inside the VPN tunnel")]
#[arg(long, help = "Do not ask for IPv6 connectivity")]
pub(super) disable_ipv6: bool,
#[arg(long = "user-agent", hide = true)]
@@ -477,28 +469,4 @@ mod tests {
assert!(!cli.args.cookie_only);
}
#[test]
fn ip_preference_parses_independently_of_tunnel_ipv6() {
use clap::Parser;
use gpapi::gateway::GatewayIpPreference;
let default = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).unwrap();
assert_eq!(default.args.ip_preference, GatewayIpPreference::Auto);
for (value, expected) in [
("auto", GatewayIpPreference::Auto),
("ipv4", GatewayIpPreference::Ipv4),
("ipv6", GatewayIpPreference::Ipv6),
] {
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--ip-preference",
value,
"--disable-ipv6",
])
.unwrap();
assert_eq!(cli.args.ip_preference, expected);
assert!(cli.args.disable_ipv6);
}
}
}
-5
View File
@@ -452,11 +452,6 @@ impl ConnectHandler<'_> {
.reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu)
.disable_ipv6(self.args.disable_ipv6)
.gateway_ip_preference(match self.args.ip_preference {
gpapi::gateway::GatewayIpPreference::Auto => openconnect::GatewayIpPreference::Auto,
gpapi::gateway::GatewayIpPreference::Ipv4 => openconnect::GatewayIpPreference::Ipv4,
gpapi::gateway::GatewayIpPreference::Ipv6 => openconnect::GatewayIpPreference::Ipv6,
})
.no_dtls(self.args.no_dtls)
.local_hostname(self.args.local_hostname.clone())
.dpd_interval(self.args.dpd_interval.unwrap_or(0))
+2 -11
View File
@@ -18,20 +18,11 @@
<clipPath id="globe-clip">
<circle cx="512" cy="455" r="315"/>
</clipPath>
<!-- Use SVG 1.1 primitives: feDropShadow needs librsvg >= 2.55.91. -->
<filter id="globe-shadow" x="150" y="90" width="730" height="760" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feGaussianBlur in="SourceAlpha" stdDeviation="12" result="blur"/>
<feOffset in="blur" dx="0" dy="8" result="offsetBlur"/>
<feFlood flood-color="#174d6f" flood-opacity=".14" result="shadowColor"/>
<feComposite in="shadowColor" in2="offsetBlur" operator="in" result="shadow"/>
<feMerge><feMergeNode in="shadow"/><feMergeNode in="SourceGraphic"/></feMerge>
<feDropShadow dx="0" dy="8" stdDeviation="12" flood-color="#174d6f" flood-opacity=".14"/>
</filter>
<filter id="lock-shadow" x="280" y="210" width="470" height="540" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feGaussianBlur in="SourceAlpha" stdDeviation="18" result="blur"/>
<feOffset in="blur" dx="0" dy="18" result="offsetBlur"/>
<feFlood flood-color="#70430c" flood-opacity=".2" result="shadowColor"/>
<feComposite in="shadowColor" in2="offsetBlur" operator="in" result="shadow"/>
<feMerge><feMergeNode in="shadow"/><feMergeNode in="SourceGraphic"/></feMerge>
<feDropShadow dx="0" dy="18" stdDeviation="18" flood-color="#70430c" flood-opacity=".2"/>
</filter>
</defs>

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

+2 -9
View File
@@ -3,7 +3,6 @@ use std::{
path::{Path, PathBuf},
sync::Arc,
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use anyhow::{Context, bail};
use log::{info, warn};
@@ -44,20 +43,14 @@ impl CredentialServer {
tokio::select! {
_ = cancel.cancelled() => break,
accepted = listener.accept() => {
let (mut stream, _) = accepted?;
let (stream, _) = accepted?;
if peer_uid(&stream)? != 0 {
warn!("Rejected non-root broker credential client");
continue;
}
let registry = Arc::clone(&self.registry);
tokio::spawn(async move {
let identity = tokio::time::timeout(std::time::Duration::from_secs(5), stream.read_u32()).await;
let uid = match identity {
Ok(Ok(0)) => { let _ = stream.write_u8(1).await; return; }
Ok(Ok(uid)) => uid,
_ => { warn!("Invalid desktop identity from broker"); return; }
};
if let Err(err) = credential_lease::serve(stream, registry, Some(uid)).await {
if let Err(err) = credential_lease::serve(stream, registry, None).await {
warn!("Broker credential lease ended: {err}");
}
});
+1 -28
View File
@@ -138,9 +138,7 @@ impl RequestDispatcher {
authority
.registry
.reserve_connection(authority.session_id, authority.generation, non_tunnel, || {
self
.lifecycle
.reserve_connect(request.restart_of().map(|attempt| (attempt, authority.session_id)))
self.lifecycle.reserve_connect()
})?;
let preparation = ConnectionPreparation {
authority,
@@ -601,29 +599,4 @@ mod tests {
Err("macOS does not support custom HIP scripts")
);
}
#[test]
#[ignore = "requires GP_TEST_GUI_BINARY pointing to a built gpgui"]
fn installs_single_gui_binary_for_fresh_and_upgrade_downloads() {
let binary = std::fs::read(std::env::var("GP_TEST_GUI_BINARY").expect("GP_TEST_GUI_BINARY")).unwrap();
let archive = compressed_gui_archive(&binary);
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let temporary = tempfile::tempdir().unwrap();
let output = std::env::var_os("GP_TEST_GUI_INSTALL_DIR")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| temporary.path().to_owned());
std::fs::create_dir_all(&output).unwrap();
std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o755)).unwrap();
let target = output.join("gpclient/gpgui");
for upgrade in [false, true] {
if upgrade {
std::fs::write(&target, b"old GUI").unwrap();
}
install_gui_at(archive.path(), &checksum, &target).unwrap();
assert_eq!(std::fs::read_dir(target.parent().unwrap()).unwrap().count(), 1);
assert_eq!(std::fs::read(&target).unwrap(), binary);
let result = std::process::Command::new(&target).arg("--version").output().unwrap();
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
assert!(String::from_utf8_lossy(&result.stdout).contains(env!("CARGO_PKG_VERSION")));
}
}
}
+7 -18
View File
@@ -190,10 +190,6 @@ impl SessionRegistry {
Ok(None)
}
pub fn service_instance_id(&self) -> Uuid {
self.service_instance_id
}
pub fn new(service_instance_id: Uuid) -> Self {
Self {
service_instance_id,
@@ -429,13 +425,6 @@ impl SessionRegistry {
}
}
pub fn has_session(&self, session_id: Uuid) -> bool {
self
.sessions
.lock()
.is_ok_and(|sessions| sessions.contains_key(&session_id))
}
pub fn is_current(&self, session_id: Uuid, generation: u64) -> bool {
let Ok(sessions) = self.sessions.lock() else {
return false;
@@ -664,7 +653,7 @@ mod tests {
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
let reservation = registry
.reserve_connection(session, 1, true, || lifecycle.reserve_connect(None))
.reserve_connection(session, 1, true, || lifecycle.reserve_connect())
.unwrap();
let drain = reservation.drain();
let cancel = reservation.cancellation();
@@ -680,7 +669,7 @@ mod tests {
assert!(!drain.is_complete());
assert!(
registry
.reserve_connection(session, 2, true, || lifecycle.reserve_connect(None))
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
.is_err()
);
assert!(matches!(
@@ -691,7 +680,7 @@ mod tests {
drain.wait().await;
let next_reservation = registry
.reserve_connection(session, 2, true, || lifecycle.reserve_connect(None))
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
.unwrap();
assert!(
registry
@@ -721,7 +710,7 @@ mod tests {
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
let reservation = registry
.reserve_connection(session, 1, true, || lifecycle.reserve_connect(None))
.reserve_connection(session, 1, true, || lifecycle.reserve_connect())
.unwrap();
let drain = registry.stop_non_tunnel_attachment(session, 1, id).unwrap().unwrap();
assert!(reservation.cancellation().is_cancelled());
@@ -739,7 +728,7 @@ mod tests {
);
assert!(
registry
.reserve_connection(session, 1, false, || lifecycle.reserve_connect(None))
.reserve_connection(session, 1, false, || lifecycle.reserve_connect())
.is_ok()
);
}
@@ -759,7 +748,7 @@ mod tests {
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
let tunnel = registry
.reserve_connection(session, 1, false, || lifecycle.reserve_connect(None))
.reserve_connection(session, 1, false, || lifecycle.reserve_connect())
.unwrap();
registry.disconnect_if_current(session, 1);
assert!(!tunnel.cancellation().is_cancelled());
@@ -776,7 +765,7 @@ mod tests {
.commit_attach(&permit, ConnectionControl::new(Uuid::new_v4(), tx).0)
.unwrap();
let session_work = registry
.reserve_connection(session, 2, true, || lifecycle.reserve_connect(None))
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
.unwrap();
registry.revoke(session);
assert!(session_work.cancellation().is_cancelled());
+10 -98
View File
@@ -27,14 +27,12 @@ mod non_tunnel;
mod preparation;
pub(crate) use preparation::{PreparedConnection, prepare_connection};
mod runtime;
mod script_tun;
#[derive(Clone)]
pub(crate) struct LifecycleHandle {
events: mpsc::Sender<LifecycleEvent>,
admissions: Arc<Mutex<Admissions>>,
tunnel: watch::Sender<TunnelBinding>,
state: watch::Sender<VpnState>,
}
#[derive(Clone, Default)]
@@ -48,7 +46,7 @@ impl LifecycleHandle {
pub fn subscribe_tunnel(&self) -> watch::Receiver<TunnelBinding> {
self.tunnel.subscribe()
}
pub fn reserve_connect(&self, restart: Option<(u64, Uuid)>) -> Result<ConnectReservation, ServiceResult> {
pub fn reserve_connect(&self) -> Result<ConnectReservation, ServiceResult> {
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
if admissions.closed {
return Err(ServiceResult::rejected(
@@ -62,13 +60,6 @@ impl LifecycleHandle {
"A VPN connection is already in progress",
));
}
if restart.is_some() && admissions.restart != restart {
return Err(ServiceResult::rejected(
ServiceErrorCode::InvalidRequest,
"Reconnect request is no longer current",
));
}
admissions.restart = None;
let attempt = admissions.next_attempt;
admissions.next_attempt += 1;
let cancellation = CancellationToken::new();
@@ -95,7 +86,7 @@ impl LifecycleHandle {
edited_report: Option<Arc<str>>,
session_id: Option<Uuid>,
) -> ServiceResult {
match self.reserve_connect(None) {
match self.reserve_connect() {
Ok(reservation) => reservation.commit(
PreparedConnection::lifecycle_fixture(request),
desktop_uid,
@@ -108,9 +99,7 @@ impl LifecycleHandle {
pub fn request_disconnect(&self) -> ServiceResult {
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
admissions.restart = None;
let Some(admission) = admissions.current.as_mut() else {
self.state.send_replace(VpnState::Disconnected);
return ServiceResult::Accepted;
};
if admission.stop_requested {
@@ -366,7 +355,6 @@ struct Admissions {
closed: bool,
next_attempt: u64,
current: Option<Admission>,
restart: Option<(u64, Uuid)>,
}
#[derive(Clone)]
@@ -407,12 +395,6 @@ enum LifecycleEvent {
Stop {
attempt: u64,
},
ScriptTunSuspended {
attempt: u64,
},
ReconnectRequired {
attempt: u64,
},
Established {
attempt: u64,
session: VpnSessionInfo,
@@ -440,7 +422,6 @@ struct ActiveAttempt {
cancellation: CancellationToken,
task: tokio::task::JoinHandle<()>,
failure: Option<String>,
reconnect_required: bool,
}
pub(crate) struct VpnTask {
@@ -464,7 +445,6 @@ impl VpnTask {
events: events_tx,
admissions: Arc::new(Mutex::new(Admissions::default())),
tunnel: watch::channel(TunnelBinding::default()).0,
state: vpn_state_tx.clone(),
};
let task = Self {
events,
@@ -559,21 +539,6 @@ impl VpnTask {
active.failure = Some(reason);
}
}
LifecycleEvent::ScriptTunSuspended { attempt } => {
if let Some(active) = self
.active
.as_mut()
.filter(|a| a.attempt == attempt && !a.cancellation.is_cancelled())
{
let info = active.info.clone();
self.send_state(VpnState::Connecting(Box::new(info)));
}
}
LifecycleEvent::ReconnectRequired { attempt } => {
if let Some(active) = self.active.as_mut().filter(|a| a.attempt == attempt) {
active.reconnect_required = true;
}
}
LifecycleEvent::PreparationReleased => {}
}
}
@@ -597,14 +562,7 @@ impl VpnTask {
.iter()
.all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel),
});
let mut info = connection.request.info().clone();
if let gpapi::script_tun::PacketDelivery::ScriptTun(request) = connection.request.args().packet_delivery() {
info.set_script_tun_identity(gpapi::script_tun::Identity {
service_instance: self.registry.service_instance_id(),
attempt,
launch_id: request.launch_id,
});
}
let info = connection.request.info().clone();
let allow_extend_session = connection.request.args().allow_extend_session();
let cancellation = self.lifecycle.attempt_cancellation(attempt);
if !activated {
@@ -632,7 +590,6 @@ impl VpnTask {
cancellation,
task,
failure: None,
reconnect_required: false,
});
if activated {
self.send_state(VpnState::Connecting(Box::new(info)));
@@ -746,33 +703,7 @@ impl VpnTask {
..Default::default()
});
}
if active.reconnect_required
&& !active.cancellation.is_cancelled()
&& active.session_id.is_some_and(|id| self.registry.has_session(id))
{
let mut admissions = self
.lifecycle
.admissions
.lock()
.expect("VPN lifecycle admissions mutex poisoned");
if let Some(admission) = admissions.current.take() {
if !admission.cancellation.is_cancelled() && !admission.stop_requested {
let owner = active.session_id.unwrap();
admissions.restart = Some((attempt, owner));
self.send_state(VpnState::ReconnectRequired(Box::new(
gpapi::service::vpn_state::ReconnectRequest {
attempt,
owner,
info: active.info,
},
)));
} else {
self.send_state(VpnState::Disconnected);
}
admission.completion.completed.store(true, Ordering::Release);
admission.completion.notify.notify_waiters();
}
} else if let Some(reason) = active.failure {
if let Some(reason) = active.failure {
self.send_state(VpnState::Failed(reason));
self.lifecycle.clear_attempt(attempt);
} else {
@@ -987,12 +918,12 @@ mod tests {
fn shutdown_cancels_preparation_despite_a_full_queue_and_rejects_commit() {
let (state, _state_rx) = watch::channel(VpnState::Disconnected);
let (_task, lifecycle) = VpnTask::new(state, false, registry());
let reservation = lifecycle.reserve_connect(None).unwrap();
let reservation = lifecycle.reserve_connect().unwrap();
let cancellation = reservation.cancellation();
while lifecycle.events.try_send(LifecycleEvent::PreparationReleased).is_ok() {}
lifecycle.close_admission();
assert!(cancellation.is_cancelled());
assert!(lifecycle.reserve_connect(None).is_err());
assert!(lifecycle.reserve_connect().is_err());
let request = test_connect_request(ConnectInfo::new(
"portal.example.com".into(),
gpapi::gateway::Gateway::new("vpn".into(), "vpn.example.com".into()),
@@ -1003,35 +934,19 @@ mod tests {
ServiceResult::Rejected(..)
));
assert!(!lifecycle.has_attempt(0));
assert!(lifecycle.reserve_connect(None).is_err());
assert!(lifecycle.reserve_connect().is_err());
}
#[test]
fn disconnect_cancels_preparation_even_when_stop_notification_queue_is_full() {
let (state, _state_rx) = watch::channel(VpnState::Disconnected);
let (_task, lifecycle) = VpnTask::new(state, false, registry());
let reservation = lifecycle.reserve_connect(None).unwrap();
let reservation = lifecycle.reserve_connect().unwrap();
while lifecycle.events.try_send(LifecycleEvent::PreparationReleased).is_ok() {}
assert_eq!(lifecycle.request_disconnect(), ServiceResult::Accepted);
assert!(reservation.cancellation().is_cancelled());
assert!(!reservation.drain().is_complete());
assert!(lifecycle.reserve_connect(None).is_err());
}
#[test]
fn reconnect_admission_is_owned_single_use_and_cancelled_by_disconnect() {
let lifecycle = LifecycleHandle::for_tests();
let owner = Uuid::new_v4();
lifecycle.admissions.lock().unwrap().restart = Some((42, owner));
assert!(lifecycle.reserve_connect(Some((42, Uuid::new_v4()))).is_err());
assert!(lifecycle.reserve_connect(Some((41, owner))).is_err());
let reservation = lifecycle.reserve_connect(Some((42, owner))).unwrap();
drop(reservation);
assert!(lifecycle.reserve_connect(Some((42, owner))).is_err());
lifecycle.admissions.lock().unwrap().restart = Some((43, owner));
assert_eq!(lifecycle.request_disconnect(), ServiceResult::Accepted);
assert!(lifecycle.reserve_connect(Some((43, owner))).is_err());
assert!(lifecycle.reserve_connect(None).is_ok());
assert!(lifecycle.reserve_connect().is_err());
}
#[tokio::test]
@@ -1040,7 +955,7 @@ mod tests {
let (mut task, lifecycle) = VpnTask::new(state, false, registry());
let gateway = gpapi::gateway::Gateway::new("vpn".into(), "vpn.example.com".into());
let info = ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![]);
let reservation = lifecycle.reserve_connect(None).unwrap();
let reservation = lifecycle.reserve_connect().unwrap();
let cancellation = reservation.cancellation();
assert_eq!(
reservation.commit(
@@ -1061,7 +976,6 @@ mod tests {
cancellation,
task: tokio::spawn(async {}),
failure: None,
reconnect_required: false,
});
task.send_state(VpnState::Connecting(Box::new(info)));
let mut member = gpapi::session::GatewaySessionSummary {
@@ -1116,7 +1030,6 @@ mod tests {
cancellation: cancellation.clone(),
task: worker,
failure: None,
reconnect_required: false,
});
assert_eq!(lifecycle.request_disconnect(), ServiceResult::Accepted);
let stop = task.events.recv().await.unwrap();
@@ -1163,7 +1076,6 @@ mod tests {
cancellation: cancellation.clone(),
task: tokio::spawn(async {}),
failure: None,
reconnect_required: false,
});
task.send_state(VpnState::Connecting(Box::new(
task.active.as_ref().unwrap().info.clone(),
@@ -151,7 +151,7 @@ async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response(
let (state, state_rx) = watch::channel(VpnState::Disconnected);
let (mut task, lifecycle) = VpnTask::new(state, false, registry.clone());
let reservation = registry
.reserve_connection(session_id, 1, true, || lifecycle.reserve_connect(None))
.reserve_connection(session_id, 1, true, || lifecycle.reserve_connect())
.unwrap();
assert_eq!(
registry.commit_connection(session_id, 1, true, || reservation.commit(
@@ -178,7 +178,7 @@ async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response(
.unwrap();
assert!(lifecycle.has_attempt(0));
assert!(!drain_waiter.is_finished());
assert!(lifecycle.reserve_connect(None).is_err());
assert!(lifecycle.reserve_connect().is_err());
assert!(!task.active.as_ref().unwrap().task.is_finished());
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
release.send(()).unwrap();
@@ -191,7 +191,7 @@ async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response(
}
assert!(!lifecycle.has_attempt(0));
drain_waiter.await.unwrap();
assert!(lifecycle.reserve_connect(None).is_ok());
assert!(lifecycle.reserve_connect().is_ok());
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
let request = server.await.unwrap();
assert!(request.starts_with("POST /ssl-vpn/logout.esp "));
@@ -31,17 +31,7 @@ pub(crate) async fn prepare_connection(
brokered_macos: bool,
cancellation: CancellationToken,
) -> anyhow::Result<PreparedConnection> {
let mode = request.args().packet_delivery().clone();
let request = request.with_packet_delivery(mode);
let args = request.args();
if let gpapi::script_tun::PacketDelivery::ScriptTun(consumer) = args.packet_delivery() {
consumer.validate()?;
anyhow::ensure!(
request.plan().members().len() == 1
&& request.plan().members()[0].authentication.mode() == gpapi::session::SessionMode::Tunnel,
"Script-tun requires a tunnel gateway"
);
}
let non_tunnel = request
.plan()
.members()
+23 -80
View File
@@ -31,12 +31,10 @@ struct TunnelInput {
source: Arc<openconnect::HipSource>,
session_id: Option<Uuid>,
registry: Arc<crate::session_registry::SessionRegistry>,
desktop_uid: Option<u32>,
}
struct PreparedTunnel {
vpn: Arc<Vpn>,
script_tun: Option<super::script_tun::PreparedScriptTun>,
}
/// The accepted attempt owns cleanup through fallible setup. Non-tunnel workers
@@ -49,6 +47,13 @@ pub(super) fn spawn(
) -> JoinHandle<()> {
tokio::spawn(async move {
let attempt = input.attempt;
let non_tunnel = input
.connection
.request
.plan()
.members()
.iter()
.all(|member| member.authentication.mode() == SessionMode::NonTunnel);
let mut failure = None;
let mut approval = None;
if !cancellation.is_cancelled() {
@@ -105,65 +110,24 @@ pub(super) fn spawn(
source,
session_id: input.session_id,
registry: input.registry.clone(),
desktop_uid: input.desktop_uid,
};
input.connection.request.release_script_tun_bootstrap();
let setup_cancel = cancellation.clone();
let prepared = tokio::task::spawn_blocking(move || prepare_tunnel(tunnel_input, &setup_cancel)).await;
match prepared {
Ok(Ok(mut prepared)) => {
if let Some(script_tun) = prepared.script_tun.take() {
if let Some(session_id) = input.session_id {
match super::script_tun::run(
gpapi::script_tun::Identity {
service_instance: input.registry.service_instance_id(),
attempt,
launch_id: match input.connection.request.args().packet_delivery() {
gpapi::script_tun::PacketDelivery::ScriptTun(request) => request.launch_id,
_ => unreachable!(),
},
},
prepared.vpn.clone(),
script_tun,
guard,
&input.lifecycle,
cancellation.clone(),
events.clone(),
session_id,
input.registry.clone(),
&mut input.connection.sessions,
)
.await
{
Ok(()) => {}
Err(error) if error.is::<super::script_tun::NetworkChanged>() && !cancellation.is_cancelled() => {
let _ = events.send(LifecycleEvent::ReconnectRequired { attempt }).await;
}
Err(error) if !cancellation.is_cancelled() => {
failure = Some(error.to_string());
}
Err(_) => {}
}
}
} else {
run_tunnel(
attempt,
&prepared,
guard,
&input.lifecycle,
&mut input.connection.sessions,
cancellation.clone(),
events.clone(),
)
.await;
}
}
Ok(Err(error)) => {
failure = Some(format!("Failed to prepare tunnel: {error:#}"));
}
Err(error) => {
failure = Some(format!("Tunnel setup worker failed: {error}"));
Ok(Ok(prepared)) => {
run_tunnel(
attempt,
&prepared,
guard,
&input.lifecycle,
&mut input.connection.sessions,
cancellation.clone(),
events.clone(),
)
.await
}
Ok(Err(error)) => warn!("Failed to prepare tunnel: {error:#}"),
Err(error) => warn!("Tunnel setup worker failed: {error}"),
}
}
}
@@ -181,7 +145,7 @@ pub(super) fn spawn(
// Identity and approval remain alive through worker drain and logout. Ended
// only releases admission after the actor also joins this task.
drop(approval);
if !cancellation.is_cancelled() {
if non_tunnel && !cancellation.is_cancelled() {
if let Some(reason) = failure {
let _ = events.send(LifecycleEvent::Failed { attempt, reason }).await;
}
@@ -246,24 +210,8 @@ fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyho
);
let member = &input.request.plan().members()[0];
let identity_files = &input.resources.identity_files;
let (builder, script_tun) = match args.packet_delivery() {
gpapi::script_tun::PacketDelivery::System => (
crate::vpn_script::builder(member.gateway.server(), member.authentication.cookie(), args)?,
None,
),
gpapi::script_tun::PacketDelivery::ScriptTun(request) => {
ensure!(input.session_id.is_some(), "Script-tun requires a desktop session");
let (builder, script_tun) = super::script_tun::builder(
member.gateway.server(),
member.authentication.cookie(),
request,
input.desktop_uid.context("Desktop identity is unavailable")?,
)?;
(builder, Some(script_tun))
}
};
let vpn = Arc::new(
builder
crate::vpn_script::builder(member.gateway.server(), member.authentication.cookie(), args)?
.user_agent(args.user_agent())
.os(args.openconnect_os())
.os_version(args.os_version())
@@ -283,11 +231,6 @@ fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyho
.reconnect_timeout(args.reconnect_timeout())
.mtu(args.mtu())
.disable_ipv6(args.disable_ipv6())
.gateway_ip_preference(match args.gateway_ip_preference() {
gpapi::gateway::GatewayIpPreference::Auto => openconnect::GatewayIpPreference::Auto,
gpapi::gateway::GatewayIpPreference::Ipv4 => openconnect::GatewayIpPreference::Ipv4,
gpapi::gateway::GatewayIpPreference::Ipv6 => openconnect::GatewayIpPreference::Ipv6,
})
.no_dtls(args.no_dtls())
.local_hostname(args.local_hostname())
.dpd_interval(args.force_dpd())
@@ -304,7 +247,7 @@ fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyho
}
});
}
Ok(PreparedTunnel { vpn, script_tun })
Ok(PreparedTunnel { vpn })
}
async fn run_tunnel(
-247
View File
@@ -1,247 +0,0 @@
//! Supervision of an unprivileged script-tun consumer; payload semantics belong to the caller.
use super::{LifecycleEvent, LifecycleHandle};
use anyhow::{Context, bail, ensure};
use gpapi::script_tun::{Bootstrap, Identity, Message, ScriptTunRequest, receive, send as send_message};
use openconnect::{Vpn, VpnBuilder, tunnel::Event};
use std::{sync::Arc, time::Duration};
use tokio::{net::UnixStream, sync::mpsc, time::Instant};
use tokio_util::sync::CancellationToken;
pub(super) struct PreparedScriptTun {
pub control: std::os::unix::net::UnixStream,
pub bootstrap: Bootstrap,
}
pub(super) fn builder(
server: &str,
cookie: &str,
request: &ScriptTunRequest,
uid: u32,
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
request.validate()?;
ensure!(uid != 0, "Script-tun worker requires a desktop user");
let (control, child) = std::os::unix::net::UnixStream::pair()?;
let builder = Vpn::builder(server, cookie).script_tun_program(
request.program.to_str().context("Program is not UTF-8")?,
&request.args,
uid,
child.into(),
)?;
Ok((
builder,
PreparedScriptTun {
control,
bootstrap: request.bootstrap.clone(),
},
))
}
#[derive(Debug)]
pub(super) struct NetworkChanged;
impl std::fmt::Display for NetworkChanged {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("VPN network configuration changed")
}
}
impl std::error::Error for NetworkChanged {}
enum Native {
Event(Event),
Established(openconnect::VpnSessionInfo),
}
pub(super) async fn run(
identity: Identity,
vpn: Arc<Vpn>,
prepared: PreparedScriptTun,
approval: &crate::hip_source::HipApproval,
lifecycle: &LifecycleHandle,
cancellation: CancellationToken,
events: mpsc::Sender<LifecycleEvent>,
session_id: uuid::Uuid,
registry: Arc<crate::session_registry::SessionRegistry>,
sessions: &mut gpapi::session::GatewaySessions,
) -> anyhow::Result<()> {
let attempt = identity.attempt;
let (native_tx, native) = mpsc::channel(64);
let observed = native_tx.clone();
let overflow = cancellation.clone();
let monitor = gptunnel::TunnelMonitor::attach_with_observer(vpn.clone(), move |event| {
if !matches!(event, Event::Statistics(_)) && observed.try_send(Native::Event(event.clone())).is_err() {
overflow.cancel();
}
});
let event_result = events
.send(LifecycleEvent::TunnelMonitor {
attempt,
monitor: monitor.clone(),
})
.await;
if event_result.is_err() {
monitor.stop().await;
return Ok(());
}
let worker_vpn = vpn.clone();
std::mem::take(sessions).relinquish();
let worker = tokio::task::spawn_blocking(move || {
worker_vpn.connect(move |session| {
let _ = native_tx.try_send(Native::Established(session));
})
});
tokio::pin!(worker);
let mut worker_done = false;
let stop = cancellation.child_token();
let supervisor = supervise(identity, prepared, native, stop.clone(), events);
tokio::pin!(supervisor);
let mut supervisor_done = false;
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
let result = loop {
tokio::select! {
biased;
result = &mut supervisor => { supervisor_done = true; break result; }
result = &mut worker => { worker_done = true; break Err(anyhow::anyhow!("VPN worker ended: {:?}", result)); }
_ = approval_poll.tick() => {
if !approval.approval_is_valid() || !registry.has_session(session_id) {
super::runtime::stop_for_revoked_approval(lifecycle, &cancellation);
}
}
}
};
stop.cancel();
if !supervisor_done {
let _ = supervisor.await;
}
vpn.disconnect();
if !worker_done {
let _ = worker.await;
}
monitor.stop().await;
result
}
#[derive(Debug, PartialEq, Eq)]
enum WorkerState {
Preparing,
Ready,
Activating,
Active,
Suspending,
}
// The same control loop runs against native observations in production and a
// generic socket consumer in tests; VPN ownership stays in run().
async fn supervise(
identity: Identity,
mut prepared: PreparedScriptTun,
mut native: mpsc::Receiver<Native>,
cancellation: CancellationToken,
events: mpsc::Sender<LifecycleEvent>,
) -> anyhow::Result<()> {
let attempt = identity.attempt;
prepared.control.set_nonblocking(true)?;
let control = UnixStream::from_std(prepared.control)?;
let (mut input, mut output) = control.into_split();
let (messages_tx, mut messages) = mpsc::channel(8);
let reader = tokio::spawn(async move {
loop {
let message = receive(&mut input).await;
let failed = message.is_err();
if messages_tx.send(message).await.is_err() || failed {
break;
}
}
});
let mut network = None;
let mut session = None;
let mut worker = WorkerState::Preparing;
let mut online = false;
let mut was_connected = false;
let mut deadline: Option<Instant> = None;
let result = async {
loop {
tokio::select! {
biased;
_ = cancellation.cancelled() => break,
_ = async { if let Some(at) = deadline { tokio::time::sleep_until(at).await } else { std::future::pending().await } } => bail!("Script-tun worker activation timed out"),
message = messages.recv() => match message.context("Script-tun control reader stopped")?? {
Message::Ready if worker == WorkerState::Preparing && network.is_some() => {
worker = WorkerState::Ready;
}
Message::Activated if worker == WorkerState::Activating => {
ensure!(online, "Script-tun activation completed while VPN was offline");
ensure!(!cancellation.is_cancelled(), "Script-tun startup cancelled");
events.send(LifecycleEvent::Established { attempt, session: session.clone().context("Native session is missing")? }).await?;
worker = WorkerState::Active; was_connected = true; deadline = None;
}
Message::Suspended if worker == WorkerState::Suspending => { worker = WorkerState::Ready; deadline = None; }
Message::Error { message } => bail!("Script-tun worker: {message}"),
_ => bail!("Unexpected script-tun consumer message"),
},
event = native.recv() => match event.context("Native event stream ended")? {
Native::Established(value) => { session = Some(value); online = true; deadline.get_or_insert(Instant::now() + Duration::from_secs(10)); }
Native::Event(Event::Configuration(config)) => {
let observed = config.context("VPN configuration is absent").and_then(observed_network);
if was_connected && (observed.is_err() || network.as_ref().is_some_and(|old| observed.as_ref().is_ok_and(|new| old != new))) { return Err(NetworkChanged.into()); }
let observed = observed?;
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
else {
send(&mut output, &Message::Configure { identity, bootstrap: std::mem::take(&mut prepared.bootstrap), network: observed.clone() }).await?;
network = Some(observed);
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Native::Event(Event::Reconnecting) => {
ensure!(worker != WorkerState::Activating, "VPN connection interrupted during script-tun activation; reconnect the VPN");
online = false;
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
send(&mut output, &Message::Suspend).await?; worker = WorkerState::Suspending;
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Native::Event(Event::Reconnected) => online = true,
Native::Event(_) => {},
}
}
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
send(&mut output, &Message::Activate).await?; worker = WorkerState::Activating;
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Ok(())
}.await;
let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut output, &Message::Stop)).await;
drop(output);
reader.abort();
let _ = reader.await;
result
}
fn observed_network(
config: openconnect::tunnel::Configuration,
) -> anyhow::Result<gpapi::session::tunnel::NegotiatedNetwork> {
ensure!(
!config.truncated && !config.dns.truncated && !config.search_domains.truncated,
"VPN configuration is truncated"
);
Ok(gpapi::session::tunnel::NegotiatedNetwork {
addresses: [config.ipv4, config.ipv6.or(config.netmask6)]
.into_iter()
.flatten()
.map(|a| a.split('/').next().unwrap().parse())
.collect::<Result<_, _>>()?,
dns: config.dns.items.iter().map(|a| a.parse()).collect::<Result<_, _>>()?,
search: config.search_domains.items,
mtu: config.mtu.context("VPN MTU is absent")? as usize,
})
}
async fn send(writer: &mut (impl tokio::io::AsyncWrite + Unpin), message: &Message) -> anyhow::Result<()> {
tokio::time::timeout(Duration::from_secs(10), send_message(writer, message))
.await
.context("Script-tun control write timed out")??;
Ok(())
}
#[cfg(test)]
mod tests;
@@ -1,293 +0,0 @@
use super::*;
use openconnect::{VpnSessionInfo, tunnel::Configuration};
use tokio::io::AsyncWriteExt;
// A generic consumer, with no proxy settings or private worker protocol.
struct Consumer {
control: UnixStream,
native: mpsc::Sender<Native>,
events: mpsc::Receiver<LifecycleEvent>,
cancel: CancellationToken,
task: tokio::task::JoinHandle<anyhow::Result<()>>,
identity: Identity,
}
impl Consumer {
fn new() -> Self {
let (control, child) = std::os::unix::net::UnixStream::pair().unwrap();
child.set_nonblocking(true).unwrap();
let (native, observations) = mpsc::channel(64);
let (events, notifications) = mpsc::channel(8);
let identity = Identity {
service_instance: uuid::Uuid::new_v4(),
attempt: 7,
launch_id: uuid::Uuid::new_v4(),
};
let cancel = CancellationToken::new();
let task = tokio::spawn(supervise(
identity,
PreparedScriptTun {
control,
bootstrap: Bootstrap::new(b"consumer bootstrap").unwrap(),
},
observations,
cancel.clone(),
events,
));
Self {
control: UnixStream::from_std(child).unwrap(),
native,
events: notifications,
cancel,
task,
identity,
}
}
async fn message(&mut self) -> Message {
tokio::time::timeout(Duration::from_secs(2), receive(&mut self.control))
.await
.unwrap()
.unwrap()
}
async fn event(&mut self) -> LifecycleEvent {
tokio::time::timeout(Duration::from_secs(2), self.events.recv())
.await
.unwrap()
.unwrap()
}
async fn configure(&mut self) {
self
.native
.send(Native::Event(Event::Configuration(Some(configuration()))))
.await
.unwrap();
let Message::Configure {
identity,
network,
bootstrap,
} = self.message().await
else {
panic!("expected Configure")
};
assert_eq!(identity, self.identity);
assert_eq!(network.addresses, vec!["10.0.0.2".parse::<std::net::IpAddr>().unwrap()]);
assert_eq!(network.mtu, 1400);
assert_eq!(bootstrap.decode().unwrap(), b"consumer bootstrap");
}
async fn activate(&mut self) {
self.configure().await;
self
.native
.send(Native::Established(VpnSessionInfo::default()))
.await
.unwrap();
send_message(&mut self.control, &Message::Ready).await.unwrap();
assert!(matches!(self.message().await, Message::Activate));
send_message(&mut self.control, &Message::Activated).await.unwrap();
assert!(matches!(
self.event().await,
LifecycleEvent::Established { attempt: 7, .. }
));
}
async fn finish(&mut self) -> anyhow::Result<()> {
tokio::time::timeout(Duration::from_secs(2), &mut self.task)
.await
.unwrap()
.unwrap()
}
}
impl Drop for Consumer {
fn drop(&mut self) {
self.cancel.cancel();
self.task.abort();
}
}
fn configuration() -> Configuration {
Configuration {
ipv4: Some("10.0.0.2".into()),
mtu: Some(1400),
..Default::default()
}
}
#[tokio::test]
async fn connected_requires_native_establishment_and_consumer_acknowledgment() {
let mut consumer = Consumer::new();
consumer.configure().await;
send_message(&mut consumer.control, &Message::Ready).await.unwrap();
assert!(
tokio::time::timeout(Duration::from_millis(30), receive(&mut consumer.control))
.await
.is_err()
);
assert!(consumer.events.try_recv().is_err());
let session = VpnSessionInfo {
lifetime_secs: Some(3600),
..Default::default()
};
consumer
.native
.send(Native::Established(session.clone()))
.await
.unwrap();
assert!(matches!(consumer.message().await, Message::Activate));
assert!(consumer.events.try_recv().is_err());
send_message(&mut consumer.control, &Message::Activated).await.unwrap();
let LifecycleEvent::Established {
attempt,
session: reported,
} = consumer.event().await
else {
panic!("expected Established")
};
assert_eq!(attempt, consumer.identity.attempt);
assert_eq!(reported, session);
consumer.cancel.cancel();
assert!(matches!(consumer.message().await, Message::Stop));
consumer.finish().await.unwrap();
assert!(receive(&mut consumer.control).await.is_err());
}
#[tokio::test]
async fn unchanged_reconnect_waits_for_suspension_before_reactivation() {
let mut consumer = Consumer::new();
consumer.activate().await;
consumer.native.send(Native::Event(Event::Reconnecting)).await.unwrap();
assert!(matches!(
consumer.event().await,
LifecycleEvent::ScriptTunSuspended { attempt: 7 }
));
assert!(matches!(consumer.message().await, Message::Suspend));
consumer
.native
.send(Native::Event(Event::Configuration(Some(configuration()))))
.await
.unwrap();
consumer.native.send(Native::Event(Event::Reconnected)).await.unwrap();
assert!(
tokio::time::timeout(Duration::from_millis(30), receive(&mut consumer.control))
.await
.is_err()
);
send_message(&mut consumer.control, &Message::Suspended).await.unwrap();
assert!(matches!(consumer.message().await, Message::Activate));
assert!(consumer.events.try_recv().is_err());
send_message(&mut consumer.control, &Message::Activated).await.unwrap();
assert!(matches!(
consumer.event().await,
LifecycleEvent::Established { attempt: 7, .. }
));
consumer.cancel.cancel();
assert!(matches!(consumer.message().await, Message::Stop));
consumer.finish().await.unwrap();
}
#[tokio::test]
async fn changed_reconnect_stops_consumer_and_returns_network_changed() {
let mut consumer = Consumer::new();
consumer.activate().await;
consumer.native.send(Native::Event(Event::Reconnecting)).await.unwrap();
assert!(matches!(
consumer.event().await,
LifecycleEvent::ScriptTunSuspended { .. }
));
assert!(matches!(consumer.message().await, Message::Suspend));
send_message(&mut consumer.control, &Message::Suspended).await.unwrap();
let mut changed = configuration();
changed.ipv4 = Some("10.0.0.3".into());
consumer
.native
.send(Native::Event(Event::Configuration(Some(changed))))
.await
.unwrap();
assert!(matches!(consumer.message().await, Message::Stop));
assert!(consumer.finish().await.unwrap_err().is::<NetworkChanged>());
assert!(
!consumer.cancel.is_cancelled(),
"restart must not look like explicit cancellation"
);
assert!(consumer.events.try_recv().is_err());
assert!(receive(&mut consumer.control).await.is_err());
}
#[tokio::test]
async fn cancellation_during_activation_prevents_connected() {
let mut consumer = Consumer::new();
consumer.configure().await;
consumer
.native
.send(Native::Established(VpnSessionInfo::default()))
.await
.unwrap();
send_message(&mut consumer.control, &Message::Ready).await.unwrap();
assert!(matches!(consumer.message().await, Message::Activate));
consumer.cancel.cancel();
// A late acknowledgment must not publish Connected after cancellation.
let _ = send_message(&mut consumer.control, &Message::Activated).await;
assert!(matches!(consumer.message().await, Message::Stop));
consumer.finish().await.unwrap();
assert!(consumer.events.try_recv().is_err());
}
#[tokio::test]
async fn consumer_eof_ends_startup_and_active_sessions() {
for active in [false, true] {
let mut consumer = Consumer::new();
if active {
consumer.activate().await;
} else {
consumer.configure().await;
}
consumer.control.shutdown().await.unwrap();
assert!(consumer.finish().await.is_err());
assert!(consumer.events.try_recv().is_err());
}
}
#[tokio::test]
async fn unexpected_acknowledgment_fails_before_connected() {
let mut consumer = Consumer::new();
consumer.configure().await;
send_message(&mut consumer.control, &Message::Activated).await.unwrap();
assert!(matches!(consumer.message().await, Message::Stop));
assert!(consumer.finish().await.unwrap_err().to_string().contains("Unexpected"));
assert!(consumer.events.try_recv().is_err());
}
#[test]
fn prepares_worker_for_current_desktop_user_without_enumerating_groups() {
let uid = unsafe { nix::libc::getuid() };
if uid == 0 {
return;
}
let request = ScriptTunRequest {
launch_id: uuid::Uuid::new_v4(),
program: "/usr/bin/true".into(),
args: vec![],
bootstrap: Bootstrap::default(),
};
builder("https://vpn.example", "test", &request, uid).unwrap();
}
#[tokio::test]
async fn reconnect_during_activation_returns_clear_error_without_connected() {
let mut consumer = Consumer::new();
consumer.configure().await;
consumer
.native
.send(Native::Established(VpnSessionInfo::default()))
.await
.unwrap();
send_message(&mut consumer.control, &Message::Ready).await.unwrap();
assert!(matches!(consumer.message().await, Message::Activate));
consumer.native.send(Native::Event(Event::Reconnecting)).await.unwrap();
assert!(matches!(consumer.message().await, Message::Stop));
assert!(
consumer
.finish()
.await
.unwrap_err()
.to_string()
.contains("during script-tun activation")
);
assert!(consumer.events.try_recv().is_err());
}
+7 -44
View File
@@ -1,54 +1,17 @@
# Changelog
## 3.2.0
## 3.0.6
### Added
### Changed
- Added Local Proxy mode with configurable SOCKS5 and HTTP listeners, so selected apps can use the VPN without changing system routes or DNS.
- Added a gateway IP preference for trying IPv4 or IPv6 first, available in Settings and through `gpclient connect --ip-preference`.
### Improved
- Enabled switching between the macOS main window and menu bar popover without restarting the app.
- Refined gateway selection, connection status, and proxy listener details.
- Made numeric settings validation clearer before saving.
- Embedded macOS VPN network configuration and added configuration logs for troubleshooting.
### Fixed
- Fixed VPN shutdown waiting too long when a gateway stops responding to logout.
- Fixed segmented controls sometimes losing the selected option when clicked.
- Fixed app shortcuts failing to open with some Linux and BSD desktop launchers.
- Fixed invisible desktop icons on systems using older versions of librsvg.
## 3.1.0
### Added
- Added a Connection Details panel showing VPN information and live upload and download activity.
- Added an optional terminal dashboard showing connection status and logs, enabled with `--dashboard`.
- Added client certificate setup in Settings, with guidance when a VPN requires a certificate.
### Improved
- Refreshed Settings and dialogs, with automatic saving for most settings and Save and Cancel buttons for detailed edits.
- Made sign-in errors clearer and added recovery options within the app.
- Added a website address bar to the sign-in window.
- Expanded support for client certificate files, including password-protected files, with clearer file and password errors.
- Improved license activation error messages and troubleshooting logs.
### Fixed
- Fixed sign-in retries losing the selected VPN server after a security error.
- Fixed mismatched certificate and key files being accepted and replacing a working certificate setup.
- Fixed failed saves discarding certificate details or custom device report (HIP) edits, allowing a retry without re-entering changes.
- Fixed theme, automatic-update, and logging settings appearing saved when saving had failed; errors are now shown and previous settings remain in use.
- Fixed notifications disappearing too quickly on GNOME and clarified notification sender names and update titles.
- Fixed connection failures with some VPN gateways.
### Command-line notes
- Renamed copy-and-paste browser sign-in to `--browser manual`; existing commands using `--browser remote` still work.
- Removed the unneeded `--fix-openssl` option on macOS; existing macOS commands and scripts must omit it.
- Fixed desktop notifications disappearing immediately on GNOME.
- Corrected the notification sender to GP Connect and clarified update notification titles on Linux and BSD.
- Fixed ESP tunnel setup when a gateway reports a zero address, including load-balanced gateways.
- Removed obsolete OpenConnect package dependencies from the AUR package.
## 3.0.5
-10
View File
@@ -57,16 +57,6 @@ pub enum GatewaySelection {
Manual,
}
#[derive(Debug, Default, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "camelCase")]
pub enum GatewayIpPreference {
#[default]
Auto,
Ipv4,
Ipv6,
}
impl GatewaySelection {
pub fn as_login_param(self) -> &'static str {
match self {
-2
View File
@@ -20,5 +20,3 @@ pub mod logger;
#[cfg(feature = "clap")]
pub mod clap;
pub mod script_tun;
-139
View File
@@ -1,139 +0,0 @@
use crate::session::tunnel::NegotiatedNetwork;
use serde::{Deserialize, Serialize};
use std::{io, path::PathBuf};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use uuid::Uuid;
const MAX_MESSAGE: usize = 60 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
pub struct Identity {
pub service_instance: Uuid,
#[serde(with = "crate::session::tunnel::decimal")]
#[specta(type = String)]
pub attempt: u64,
pub launch_id: Uuid,
}
#[derive(Clone, Default, Serialize, Deserialize, specta::Type)]
#[serde(transparent)]
pub struct Bootstrap(String);
impl std::fmt::Debug for Bootstrap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("[redacted bootstrap]")
}
}
impl Bootstrap {
pub fn new(bytes: &[u8]) -> anyhow::Result<Self> {
anyhow::ensure!(bytes.len() <= 16 * 1024, "Script-tun bootstrap too large");
use base64::Engine;
Ok(Self(base64::engine::general_purpose::STANDARD.encode(bytes)))
}
pub fn decode(&self) -> anyhow::Result<Vec<u8>> {
anyhow::ensure!(self.0.len() <= 21848, "Script-tun bootstrap too large");
use base64::Engine;
let bytes = base64::engine::general_purpose::STANDARD.decode(&self.0)?;
anyhow::ensure!(bytes.len() <= 16 * 1024, "Script-tun bootstrap too large");
Ok(bytes)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, specta::Type)]
pub struct ScriptTunRequest {
pub launch_id: Uuid,
pub program: PathBuf,
pub args: Vec<String>,
pub bootstrap: Bootstrap,
}
impl ScriptTunRequest {
pub fn validate(&self) -> anyhow::Result<()> {
let program = self
.program
.to_str()
.ok_or_else(|| anyhow::anyhow!("Executable path must be UTF-8"))?;
anyhow::ensure!(
self.program.is_absolute() && !program.contains('\0'),
"Script-tun requires an absolute executable path"
);
anyhow::ensure!(
self.args.len() <= 64
&& self.args.iter().all(|a| !a.contains('\0'))
&& program.len() + self.args.iter().map(String::len).sum::<usize>() <= 16 * 1024,
"Invalid script-tun arguments"
);
self.bootstrap.decode()?;
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, specta::Type)]
#[serde(tag = "type", content = "value", rename_all = "camelCase")]
pub enum PacketDelivery {
#[default]
System,
ScriptTun(ScriptTunRequest),
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum PacketDeliveryKind {
#[default]
System,
ScriptTun,
}
impl PacketDelivery {
pub fn kind(&self) -> PacketDeliveryKind {
match self {
Self::System => PacketDeliveryKind::System,
Self::ScriptTun(_) => PacketDeliveryKind::ScriptTun,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
pub enum Message {
Configure {
identity: Identity,
network: NegotiatedNetwork,
bootstrap: Bootstrap,
},
Ready,
Activate,
Activated,
Suspend,
Suspended,
Stop,
Error {
message: String,
},
}
pub async fn send(stream: &mut (impl AsyncWrite + Unpin), message: &Message) -> io::Result<()> {
let bytes = serde_json::to_vec(message)?;
if bytes.len() > MAX_MESSAGE {
return Err(io::Error::other("Script-tun control message too large"));
}
stream.write_u32(bytes.len() as u32).await?;
stream.write_all(&bytes).await
}
pub async fn receive(stream: &mut (impl AsyncRead + Unpin)) -> io::Result<Message> {
let length = stream.read_u32().await? as usize;
if length > MAX_MESSAGE {
return Err(io::Error::other("Script-tun control message too large"));
}
let mut bytes = vec![0; length];
stream.read_exact(&mut bytes).await?;
serde_json::from_slice(&bytes).map_err(io::Error::from)
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn rejects_oversized_unknown_and_truncated_frames() {
let oversized = (MAX_MESSAGE as u32 + 1).to_be_bytes();
assert!(receive(&mut oversized.as_slice()).await.is_err());
for payload in [br#"{"type":"UnknownCommand"}"#.as_slice(), b"not JSON"] {
let mut frame = (payload.len() as u32).to_be_bytes().to_vec();
frame.extend_from_slice(payload);
assert!(receive(&mut frame.as_slice()).await.is_err());
}
let truncated = [0, 0, 0, 10, b'{'];
assert!(receive(&mut truncated.as_slice()).await.is_err());
}
}
-67
View File
@@ -58,8 +58,6 @@ impl LaunchGuiRequest {
#[derive(Deserialize, Serialize, Type, Clone)]
pub struct ConnectArgs {
#[serde(default)]
packet_delivery: crate::script_tun::PacketDelivery,
vpnc_script: Option<String>,
host_identity: Option<HostIdentity>,
ignore_tls_errors: bool,
@@ -81,8 +79,6 @@ pub struct ConnectArgs {
reconnect_timeout: u32,
mtu: u32,
disable_ipv6: bool,
#[serde(default)]
gateway_ip_preference: crate::gateway::GatewayIpPreference,
no_dtls: bool,
local_hostname: Option<String>,
force_dpd: u32,
@@ -92,13 +88,8 @@ pub struct ConnectArgs {
}
impl ConnectArgs {
pub fn packet_delivery(&self) -> &crate::script_tun::PacketDelivery {
&self.packet_delivery
}
fn new() -> Self {
Self {
packet_delivery: Default::default(),
vpnc_script: None,
host_identity: None,
ignore_tls_errors: false,
@@ -116,7 +107,6 @@ impl ConnectArgs {
reconnect_timeout: 300,
mtu: 0,
disable_ipv6: false,
gateway_ip_preference: Default::default(),
no_dtls: false,
local_hostname: None,
force_dpd: 0,
@@ -205,10 +195,6 @@ impl ConnectArgs {
self.disable_ipv6
}
pub fn gateway_ip_preference(&self) -> crate::gateway::GatewayIpPreference {
self.gateway_ip_preference
}
pub fn no_dtls(&self) -> bool {
self.no_dtls
}
@@ -246,7 +232,6 @@ impl fmt::Debug for ConnectArgs {
.field("reconnect_timeout", &self.reconnect_timeout)
.field("mtu", &self.mtu)
.field("disable_ipv6", &self.disable_ipv6)
.field("gateway_ip_preference", &self.gateway_ip_preference)
.field("no_dtls", &self.no_dtls)
.field("allow_extend_session", &self.allow_extend_session)
.finish_non_exhaustive()
@@ -263,40 +248,17 @@ impl Drop for ConnectArgs {
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectRequest {
#[serde(default)]
restart_of: Option<u64>,
info: ConnectInfo,
plan: ConnectionPlan,
args: ConnectArgs,
}
impl ConnectRequest {
pub fn with_restart_of(mut self, attempt: Option<u64>) -> Self {
self.restart_of = attempt;
self
}
pub fn restart_of(&self) -> Option<u64> {
self.restart_of
}
/// Release the one-shot payload once tunnel setup has taken ownership of it.
pub fn release_script_tun_bootstrap(&mut self) {
if let crate::script_tun::PacketDelivery::ScriptTun(request) = &mut self.args.packet_delivery {
request.bootstrap = Default::default();
}
}
pub fn with_packet_delivery(mut self, mode: crate::script_tun::PacketDelivery) -> Self {
self.info.set_packet_delivery(mode.kind());
self.args.packet_delivery = mode;
self
}
pub fn new(info: ConnectInfo, plan: ConnectionPlan) -> Self {
Self {
info,
plan,
args: ConnectArgs::new(),
restart_of: None,
}
}
@@ -365,11 +327,6 @@ impl ConnectRequest {
self
}
pub fn with_gateway_ip_preference(mut self, preference: crate::gateway::GatewayIpPreference) -> Self {
self.args.gateway_ip_preference = preference;
self
}
pub fn with_no_dtls(mut self, no_dtls: bool) -> Self {
self.args.no_dtls = no_dtls;
self
@@ -501,30 +458,6 @@ mod tests {
assert_eq!(value["args"]["allowExtendSession"], json!(true));
}
#[test]
fn gateway_preference_round_trips_and_defaults_for_existing_requests() {
use crate::gateway::GatewayIpPreference;
for preference in [
GatewayIpPreference::Auto,
GatewayIpPreference::Ipv4,
GatewayIpPreference::Ipv6,
] {
let request = test_request(test_connect_info())
.with_disable_ipv6(true)
.with_gateway_ip_preference(preference);
let value = serde_json::to_value(&request).unwrap();
let decoded: ConnectRequest = serde_json::from_value(value).unwrap();
assert_eq!(decoded.args().gateway_ip_preference(), preference);
assert!(decoded.args().disable_ipv6());
}
let request = test_request(test_connect_info()).with_disable_ipv6(true);
let mut value = serde_json::to_value(request).unwrap();
value["args"].as_object_mut().unwrap().remove("gateway_ip_preference");
let decoded: ConnectRequest = serde_json::from_value(value).unwrap();
assert_eq!(decoded.args().gateway_ip_preference(), GatewayIpPreference::Auto);
assert!(decoded.args().disable_ipv6());
}
#[test]
fn with_os_profile_sets_user_agent_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
-32
View File
@@ -10,10 +10,6 @@ use crate::{
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectInfo {
#[serde(default)]
packet_delivery: crate::script_tun::PacketDeliveryKind,
#[serde(default)]
script_tun_identity: Option<crate::script_tun::Identity>,
portal: String,
gateway: Gateway,
gateways: Vec<Gateway>,
@@ -75,33 +71,14 @@ fn unix_timestamp() -> u32 {
}
impl ConnectInfo {
pub fn script_tun_identity(&self) -> Option<crate::script_tun::Identity> {
self.script_tun_identity
}
pub fn set_script_tun_identity(&mut self, identity: crate::script_tun::Identity) {
self.script_tun_identity = Some(identity);
}
pub fn packet_delivery(&self) -> &crate::script_tun::PacketDeliveryKind {
&self.packet_delivery
}
pub fn set_packet_delivery(&mut self, mode: crate::script_tun::PacketDeliveryKind) {
self.packet_delivery = mode;
self.script_tun_identity = None;
}
pub fn new(portal: String, gateway: Gateway, gateways: Vec<Gateway>) -> Self {
Self {
packet_delivery: Default::default(),
script_tun_identity: None,
portal,
gateway,
gateways,
}
}
pub fn portal(&self) -> &str {
&self.portal
}
pub fn gateway(&self) -> &Gateway {
&self.gateway
}
@@ -110,7 +87,6 @@ impl ConnectInfo {
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum VpnState {
ReconnectRequired(Box<ReconnectRequest>),
Disconnected,
Failed(String),
Connecting(Box<ConnectInfo>),
@@ -143,11 +119,3 @@ mod tests {
assert!(value["connected"]["connectedAt"].as_u64().is_some());
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Type)]
#[serde(rename_all = "camelCase")]
pub struct ReconnectRequest {
pub attempt: u64,
pub owner: uuid::Uuid,
pub info: ConnectInfo,
}
+1 -9
View File
@@ -276,7 +276,7 @@ impl TunnelStatisticsSnapshot {
}
}
pub(crate) mod decimal {
mod decimal {
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(value: &u64, serializer: S) -> Result<S::Ok, S::Error> {
@@ -351,11 +351,3 @@ mod tests {
);
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NegotiatedNetwork {
pub addresses: Vec<std::net::IpAddr>,
pub dns: Vec<std::net::IpAddr>,
pub search: Vec<String>,
pub mtu: usize,
}
-7
View File
@@ -293,12 +293,6 @@ pub struct TunnelMonitor {
impl TunnelMonitor {
pub fn attach(vpn: Arc<Vpn>) -> Arc<Self> {
Self::attach_with_observer(vpn, |_| {})
}
/// Observe every native transition as well as the coalesced telemetry stream.
/// The callback runs on the native worker and must not block.
pub fn attach_with_observer(vpn: Arc<Vpn>, on_event: impl Fn(&Event) + Send + Sync + 'static) -> Arc<Self> {
let observation = Observation::new();
let (updates, _) = watch::channel(observation.project(Instant::now()));
let monitor = Arc::new(Self {
@@ -310,7 +304,6 @@ impl TunnelMonitor {
});
let observer = Arc::downgrade(&monitor);
monitor.vpn.set_tunnel_observer(move |event| {
on_event(&event);
if let Some(monitor) = observer.upgrade() {
monitor.observe(event);
}
-127
View File
@@ -1,127 +0,0 @@
use std::{
ffi::{c_char, c_int},
ptr,
};
/// Resolve with the system's normal policy, then prefer one family without
/// discarding alternatives. The returned list remains owned by libc and is
/// released by OpenConnect with freeaddrinfo.
///
/// # Safety
/// Arguments must satisfy getaddrinfo's pointer and lifetime requirements.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn vpn_resolve_gateway(
node: *const c_char,
service: *const c_char,
hints: *const libc::addrinfo,
result: *mut *mut libc::addrinfo,
preference: u32,
) -> c_int {
// SAFETY: The OpenConnect callback forwards valid getaddrinfo arguments.
let status = unsafe { libc::getaddrinfo(node, service, hints, result) };
if status != 0 {
return status;
}
let family = match preference {
4 => libc::AF_INET,
6 => libc::AF_INET6,
_ => return 0,
};
// SAFETY: A successful getaddrinfo call returns an owned, writable list.
unsafe { *result = prefer_family(*result, family) };
0
}
/// # Safety
/// `head` must be an exclusively owned, writable addrinfo list with no cycles.
unsafe fn prefer_family(head: *mut libc::addrinfo, family: c_int) -> *mut libc::addrinfo {
let mut addresses = Vec::new();
let mut current = head;
// SAFETY: The caller owns every node; sorting only changes the list links.
unsafe {
while !current.is_null() {
addresses.push(current);
current = (*current).ai_next;
}
addresses.sort_by_key(|address| (**address).ai_family != family);
for (index, address) in addresses.iter().enumerate() {
(**address).ai_next = addresses.get(index + 1).copied().unwrap_or(ptr::null_mut());
}
}
addresses.first().copied().unwrap_or(ptr::null_mut())
}
#[cfg(test)]
mod tests {
use super::*;
fn ordered_indices(families: &[c_int], preferred: c_int) -> Vec<usize> {
let mut addresses: Vec<libc::addrinfo> = families
.iter()
.enumerate()
.map(|(index, family)| {
// SAFETY: All-zero addrinfo has null pointers; these fixtures own no OS data.
let mut address: libc::addrinfo = unsafe { std::mem::zeroed() };
address.ai_family = *family;
address.ai_flags = index as c_int;
address
})
.collect();
for index in 1..addresses.len() {
addresses[index - 1].ai_next = &mut addresses[index];
}
let head = if addresses.is_empty() {
ptr::null_mut()
} else {
addresses.as_mut_ptr()
};
// SAFETY: The fixture owns stable nodes throughout sorting and traversal.
unsafe {
let mut current = prefer_family(head, preferred);
let mut indices = Vec::new();
while !current.is_null() {
assert!(indices.len() < addresses.len(), "address list contains a cycle");
indices.push((*current).ai_flags as usize);
current = (*current).ai_next;
}
indices
}
}
#[test]
fn preferences_retain_all_addresses_and_order_within_each_family() {
let mixed = [libc::AF_INET6, libc::AF_INET, libc::AF_INET6, libc::AF_INET];
assert_eq!(ordered_indices(&mixed, libc::AF_INET), [1, 3, 0, 2]);
assert_eq!(ordered_indices(&mixed, libc::AF_INET6), [0, 2, 1, 3]);
assert_eq!(
ordered_indices(&[libc::AF_INET6, libc::AF_INET6], libc::AF_INET),
[0, 1]
);
assert_eq!(ordered_indices(&[libc::AF_INET, libc::AF_INET], libc::AF_INET6), [0, 1]);
assert!(ordered_indices(&[], libc::AF_INET).is_empty());
}
#[test]
fn native_lookup_preserves_errors_and_returns_freeable_results() {
let mut hints: libc::addrinfo = unsafe { std::mem::zeroed() };
hints.ai_socktype = libc::SOCK_STREAM;
hints.ai_flags = libc::AI_NUMERICHOST;
for preference in [0, 4, 6] {
let mut result = ptr::null_mut();
// SAFETY: Static NUL-terminated inputs, initialized hints and a writable output.
unsafe {
assert_ne!(
vpn_resolve_gateway(c"invalid".as_ptr(), c"443".as_ptr(), &hints, &mut result, preference),
0
);
assert_eq!(
vpn_resolve_gateway(c"::1".as_ptr(), c"443".as_ptr(), &hints, &mut result, preference),
0
);
assert!(!result.is_null());
assert_eq!((*result).ai_family, libc::AF_INET6);
libc::freeaddrinfo(result);
}
}
}
}
-13
View File
@@ -1,4 +1,3 @@
mod gateway;
mod hip;
mod network_configuration;
mod tunnel;
@@ -12,16 +11,6 @@ pub(crate) use network_configuration::{VpnOptionRaw, configure_network};
use std::ffi::{c_char, c_int, c_long, c_void};
use std::panic::{AssertUnwindSafe, catch_unwind};
/// Borrowed launch data; layout must match openconnect_script_tun_launch in openconnect.h.
#[repr(C)]
#[derive(Debug)]
pub(crate) struct ScriptTunLaunchRaw {
pub program: *const c_char,
pub argv: *const *const c_char,
pub uid: u32,
pub control_fd: c_int,
}
/// ConnectOptions struct for FFI, the field names and order must match the C definition.
#[repr(C)]
#[derive(Debug)]
@@ -43,7 +32,6 @@ pub(crate) struct ConnectOptions {
pub configure_network: Option<unsafe extern "C" fn(*mut c_void, *const c_char, *const VpnOptionRaw) -> c_int>,
pub interface: *const c_char,
pub script_tun: u32,
pub script_tun_launch: *const ScriptTunLaunchRaw,
pub certificate: *const c_char,
pub sslkey: *const c_char,
@@ -56,7 +44,6 @@ pub(crate) struct ConnectOptions {
pub reconnect_timeout: u32,
pub mtu: u32,
pub disable_ipv6: u32,
pub gateway_ip_preference: u32,
pub no_dtls: u32,
pub dpd_interval: u32,
+3 -25
View File
@@ -15,21 +15,13 @@ struct vpn_context {
vpn_connected_callback on_connected;
};
static int resolve_gateway(void *private_data, const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **result)
{
struct vpn_context *context = private_data;
return vpn_resolve_gateway(node, service, hints, result,
context->options->gateway_ip_preference);
}
static void observe_configuration(struct vpn_context *context)
{
const struct oc_ip_info *info = NULL;
if (openconnect_get_ip_info(context->vpninfo, &info, NULL, NULL))
info = NULL;
vpn_tunnel_configuration(context->options->user_data,
context->options->script_tun ? NULL : openconnect_get_ifname(context->vpninfo), info);
openconnect_get_ifname(context->vpninfo), info);
}
static void observe_reconnected(void *private_data)
@@ -83,13 +75,7 @@ static void setup_tun_handler(void *private_data)
const vpn_options *options = context->options;
int ret;
if (options->script_tun) {
const struct openconnect_script_tun_launch *launch = options->script_tun_launch;
if (launch) {
ret = openconnect_setup_tun_script_exec(_vpninfo, launch);
vpn_script_started(options->user_data);
} else {
ret = openconnect_setup_tun_script(_vpninfo, options->script);
}
ret = openconnect_setup_tun_script(_vpninfo, options->script);
} else {
ret = openconnect_setup_tun_device(_vpninfo, options->script,
options->interface);
@@ -128,19 +114,13 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
INFO("OS: %s", options->os);
INFO("CLIENT_VERSION: %s", options->client_version);
INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
const char *configuration = options->script;
if (options->configure_network)
configuration = "callback";
else if (options->script_tun_launch)
configuration = options->script_tun_launch->program;
INFO("Network configuration: %s", configuration);
INFO("Network configuration: %s", options->configure_network ? "callback" : options->script);
INFO("SCRIPT_TUN: %d", options->script_tun);
INFO("CSD_USER: %d", options->hip_script.uid);
INFO("CSD_WRAPPER: %s", options->hip_script.path);
INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
INFO("MTU: %d", options->mtu);
INFO("DISABLE_IPV6: %d", options->disable_ipv6);
INFO("GATEWAY_IP_PREFERENCE: %d", options->gateway_ip_preference);
INFO("NO_DTLS: %d", options->no_dtls);
INFO("DPD_INTERVAL: %d", options->dpd_interval);
INFO("NO_XMLPOST: %d", options->no_xmlpost);
@@ -177,8 +157,6 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_init_ssl();
openconnect_set_protocol(vpninfo, "gp");
openconnect_parse_url(vpninfo, options->server);
if (options->gateway_ip_preference)
openconnect_override_getaddrinfo(vpninfo, resolve_gateway);
openconnect_set_cookie(vpninfo, options->cookie);
openconnect_set_useragent(vpninfo, options->user_agent);
-5
View File
@@ -47,7 +47,6 @@ typedef struct vpn_options {
openconnect_configure_tun_fn configure_network;
const char *interface;
const int script_tun;
const struct openconnect_script_tun_launch *script_tun_launch;
const char *certificate;
const char *sslkey;
@@ -60,7 +59,6 @@ typedef struct vpn_options {
const int reconnect_timeout;
const int mtu;
const int disable_ipv6;
const int gateway_ip_preference;
const int no_dtls;
const int dpd_interval;
@@ -68,14 +66,11 @@ typedef struct vpn_options {
} vpn_options;
int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
extern int vpn_resolve_gateway(const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **result, unsigned int preference);
int vpn_collect_hip_report(const vpn_hip_script *, const struct openconnect_gp_hip_request *,
const struct openconnect_gp_hip_control *, openconnect_gp_hip_generate_fn, void *, char *, size_t, size_t *);
extern int vpn_attach_command_pipe(void *user_data, int fd);
extern void vpn_detach_command_pipe(void *user_data);
extern void vpn_script_started(void *user_data);
enum vpn_tunnel_event {
VPN_TUNNEL_ESTABLISHED = 5,
VPN_TUNNEL_RECONNECTED,
-3
View File
@@ -9,6 +9,3 @@ pub use hip::*;
pub use network_configuration::*;
pub use vpn::*;
pub use vpn_utils::*;
#[cfg(all(test, unix))]
mod script_child_tests;
@@ -1,140 +0,0 @@
use std::{
ffi::{CString, c_char, c_int, c_void},
process::Command,
time::{Duration, Instant},
};
unsafe extern "C" {
fn openconnect_vpninfo_new(
agent: *const c_char,
validate: Option<unsafe extern "C" fn(*mut c_void, *const c_char) -> c_int>,
config: Option<unsafe extern "C" fn(*mut c_void, *const c_char, c_int) -> c_int>,
auth: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int>,
progress: Option<unsafe extern "C" fn(*mut c_void, c_int, *const c_char, ...)>,
data: *mut c_void,
) -> *mut c_void;
fn openconnect_setup_tun_script(info: *mut c_void, script: *const c_char) -> c_int;
fn openconnect_vpninfo_free(info: *mut c_void);
fn openconnect_set_loglevel(info: *mut c_void, level: c_int);
}
#[test]
fn script_children_are_reaped_including_term_resistant_children_without_reaping_others() {
for resistant in [false, true] {
let directory = tempfile::tempdir().unwrap();
let pid_file = directory.path().join("pid");
let behavior = if resistant {
"trap '' TERM; echo $$ >"
} else {
"echo $$ >"
};
let suffix = if resistant {
"; while :; do sleep 1; done"
} else {
"; exit 0"
};
let command = CString::new(format!("{behavior} '{}' {suffix}", pid_file.display())).unwrap();
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
assert!(!info.is_null());
// This raw fixture has no progress callback; suppress native logging.
unsafe { openconnect_set_loglevel(info, -1) };
assert_eq!(unsafe { openconnect_setup_tun_script(info, command.as_ptr()) }, 0);
let started = Instant::now();
let pid: i32 = loop {
if let Ok(text) = std::fs::read_to_string(&pid_file) {
if let Ok(pid) = text.trim().parse() {
break pid;
}
}
assert!(started.elapsed() < Duration::from_secs(3));
std::thread::sleep(Duration::from_millis(5));
};
let mut unrelated = Command::new("/bin/sh").args(["-c", "exit 17"]).spawn().unwrap();
let stop = Instant::now();
unsafe { openconnect_vpninfo_free(info) };
assert!(stop.elapsed() < Duration::from_secs(4));
assert_eq!(unsafe { libc::waitpid(pid, std::ptr::null_mut(), libc::WNOHANG) }, -1);
assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::ECHILD));
assert_eq!(unrelated.wait().unwrap().code(), Some(17));
}
}
unsafe extern "C" {
fn openconnect_setup_tun_script_exec(info: *mut c_void, launch: *const crate::ffi::ScriptTunLaunchRaw) -> c_int;
}
// Invoked by the native launcher in a fresh process, after credentials and FDs change.
#[test]
fn identity_probe() {
use std::{io::Write, os::fd::FromRawFd};
let Ok(fd) = std::env::var("IDENTITY_PROBE_FD") else {
return;
};
assert_eq!(std::env::var("OPENCONNECT_SCRIPT_TUN_CONTROL_FD").unwrap(), fd);
assert_ne!(unsafe { libc::getuid() }, 0);
assert_eq!(unsafe { libc::getuid() }, unsafe { libc::geteuid() });
assert_eq!(unsafe { libc::getgid() }, unsafe { libc::getegid() });
assert_eq!(unsafe { libc::setuid(0) }, -1);
assert_eq!(unsafe { libc::fcntl(500, libc::F_GETFD) }, -1);
let mut groups = vec![0; unsafe { libc::getgroups(0, std::ptr::null_mut()) } as usize];
assert_eq!(
unsafe { libc::getgroups(groups.len() as i32, groups.as_mut_ptr()) },
groups.len() as i32
);
groups.sort();
let expected = std::env::var("IDENTITY_PROBE_GROUPS").unwrap();
assert_eq!(
groups.iter().map(ToString::to_string).collect::<Vec<_>>().join(","),
expected
);
let mut control = unsafe { std::os::unix::net::UnixStream::from_raw_fd(fd.parse().unwrap()) };
control.write_all(b"identity verified").unwrap();
}
#[test]
fn identity_launcher_drops_credentials_and_excludes_unrelated_descriptors() {
use std::{io::Read, os::fd::AsRawFd};
let uid = std::env::var("GP_TEST_UID")
.ok()
.map(|s| s.parse().unwrap())
.unwrap_or_else(|| unsafe { libc::getuid() });
assert_ne!(uid, 0, "root runs must set GP_TEST_UID");
let user = unsafe { libc::getpwuid(uid) };
assert!(!user.is_null());
let gid = unsafe { (*user).pw_gid };
let mut groups = if unsafe { libc::geteuid() } == 0 {
vec![gid]
} else {
let n = unsafe { libc::getgroups(0, std::ptr::null_mut()) };
assert!(n >= 0);
let mut groups = vec![0; n as usize];
assert_eq!(unsafe { libc::getgroups(n, groups.as_mut_ptr()) }, n);
groups
};
groups.sort();
let groups: Vec<u32> = groups.into_iter().map(|g| g as u32).collect();
let (mut parent, child) = std::os::unix::net::UnixStream::pair().unwrap();
parent.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
let unrelated = std::fs::File::open("/dev/null").unwrap();
assert_eq!(unsafe { libc::dup2(unrelated.as_raw_fd(), 500) }, 500);
let executable = std::env::current_exe().unwrap();
let command = CString::new(format!("DYLD_FALLBACK_LIBRARY_PATH='{}' IDENTITY_PROBE_FD={} IDENTITY_PROBE_GROUPS='{}' exec '{}' --exact script_child_tests::identity_probe --nocapture", std::env::var("DYLD_FALLBACK_LIBRARY_PATH").unwrap_or_default(), child.as_raw_fd(), groups.iter().map(ToString::to_string).collect::<Vec<_>>().join(","), executable.display())).unwrap();
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
assert!(!info.is_null());
unsafe { openconnect_set_loglevel(info, -1) };
let argv = [c"/bin/sh".as_ptr(), c"-c".as_ptr(), command.as_ptr(), std::ptr::null()];
let launch = crate::ffi::ScriptTunLaunchRaw {
program: c"/bin/sh".as_ptr(),
argv: argv.as_ptr(),
uid,
control_fd: child.as_raw_fd(),
};
let result = unsafe { openconnect_setup_tun_script_exec(info, &launch) };
unsafe { libc::close(500) };
assert_eq!(result, 0);
drop(child);
let mut response = [0; 17];
parent.read_exact(&mut response).unwrap();
assert_eq!(&response, b"identity verified");
unsafe { openconnect_vpninfo_free(info) };
}
-112
View File
@@ -1,7 +1,6 @@
use std::{
ffi::{CStr, CString, c_char},
fmt, io,
os::fd::{AsRawFd, OwnedFd},
sync::{Arc, Mutex, RwLock},
};
@@ -125,15 +124,6 @@ impl Cancellation {
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum GatewayIpPreference {
#[default]
Auto = 0,
Ipv4 = 4,
Ipv6 = 6,
}
pub struct Vpn {
cancellation: Cancellation,
server: CString,
@@ -150,7 +140,6 @@ pub struct Vpn {
pub(crate) network_configuration_handler: Option<Arc<NetworkConfigurationHandler>>,
interface: Option<CString>,
script_tun: bool,
script_tun_launch: Option<ScriptTunLaunch>,
certificate: Option<CString>,
sslkey: Option<CString>,
@@ -162,7 +151,6 @@ pub struct Vpn {
reconnect_timeout: u32,
mtu: u32,
disable_ipv6: bool,
gateway_ip_preference: GatewayIpPreference,
no_dtls: bool,
dpd_interval: u32,
@@ -232,20 +220,6 @@ impl Vpn {
}
self.callback.write().unwrap().replace(Box::new(on_connected));
let mut options = self.build_connect_options();
let mut argv = Vec::new();
let launch = self.script_tun_launch.as_ref().map(|launch| {
argv.push(launch.program.as_ptr());
argv.extend(launch.arguments.iter().map(|s| s.as_ptr()));
argv.push(std::ptr::null());
ffi::ScriptTunLaunchRaw {
program: launch.program.as_ptr(),
argv: argv.as_ptr(),
uid: launch.uid,
control_fd: launch.control.lock().unwrap().as_ref().map_or(-1, AsRawFd::as_raw_fd),
}
});
// Both the borrowed launch record and argv remain alive through native connect.
options.script_tun_launch = launch.as_ref().map_or(std::ptr::null(), |launch| launch);
let environment = match self.hip_source.as_ref() {
HipSource::Script(script) => ffi::script_environment(script),
_ => Vec::new(),
@@ -313,7 +287,6 @@ impl Vpn {
.map(|_| ffi::configure_network as _),
interface: Self::option_to_ptr(&self.interface),
script_tun: self.script_tun as u32,
script_tun_launch: std::ptr::null(),
certificate: Self::option_to_ptr(&self.certificate),
sslkey: Self::option_to_ptr(&self.sslkey),
@@ -332,7 +305,6 @@ impl Vpn {
reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu,
disable_ipv6: self.disable_ipv6 as u32,
gateway_ip_preference: self.gateway_ip_preference as u32,
no_dtls: self.no_dtls as u32,
dpd_interval: self.dpd_interval,
no_xmlpost: self.no_xmlpost as u32,
@@ -366,13 +338,6 @@ impl fmt::Display for VpnError {
impl std::error::Error for VpnError {}
struct ScriptTunLaunch {
program: CString,
arguments: Vec<CString>,
uid: u32,
control: Mutex<Option<OwnedFd>>,
}
pub struct VpnBuilder {
server: String,
cookie: String,
@@ -381,7 +346,6 @@ pub struct VpnBuilder {
script_is_path: bool,
interface: Option<String>,
script_tun: bool,
script_tun_launch: Option<ScriptTunLaunch>,
user_agent: Option<String>,
os: Option<String>,
@@ -399,7 +363,6 @@ pub struct VpnBuilder {
reconnect_timeout: u32,
mtu: u32,
disable_ipv6: bool,
gateway_ip_preference: GatewayIpPreference,
no_dtls: bool,
dpd_interval: u32,
@@ -416,7 +379,6 @@ impl VpnBuilder {
script_is_path: false,
interface: None,
script_tun: false,
script_tun_launch: None,
user_agent: None,
os: None,
@@ -434,7 +396,6 @@ impl VpnBuilder {
reconnect_timeout: 300,
mtu: 0,
disable_ipv6: false,
gateway_ip_preference: GatewayIpPreference::Auto,
no_dtls: false,
dpd_interval: 0,
no_xmlpost: false,
@@ -469,32 +430,6 @@ impl VpnBuilder {
self
}
pub fn script_tun_program(
mut self,
program: &str,
arguments: &[String],
uid: u32,
inherited: OwnedFd,
) -> Result<Self, VpnError> {
if !std::path::Path::new(program).is_absolute() || program.contains('\0') {
return Err(VpnError::new("Script-tun requires an absolute executable path".into()));
}
let arguments = arguments
.iter()
.map(|arg| CString::new(arg.as_str()).map_err(|_| VpnError::new("Script-tun argument contains NUL".into())))
.collect::<Result<_, _>>()?;
self.script = None;
self.script_tun = true;
self.script_is_path = false;
self.script_tun_launch = Some(ScriptTunLaunch {
program: CString::new(program).expect("program was checked for NUL"),
arguments,
uid,
control: Mutex::new(Some(inherited)),
});
Ok(self)
}
pub fn script_tun(mut self, script_tun: bool) -> Self {
self.script_tun = script_tun;
self
@@ -560,18 +495,11 @@ impl VpnBuilder {
self
}
/// Request IPv4-only connectivity inside the VPN tunnel.
pub fn disable_ipv6(mut self, disable_ipv6: bool) -> Self {
self.disable_ipv6 = disable_ipv6;
self
}
/// Order gateway addresses without excluding either IP family.
pub fn gateway_ip_preference(mut self, preference: GatewayIpPreference) -> Self {
self.gateway_ip_preference = preference;
self
}
pub fn no_dtls(mut self, no_dtls: bool) -> Self {
self.no_dtls = no_dtls;
self
@@ -596,9 +524,6 @@ impl VpnBuilder {
}
return Ok(None);
}
if self.script_tun_launch.is_some() {
return Ok(None);
}
let script = match &self.script {
Some(script) => {
if self.script_is_path && !std::path::Path::new(script).exists() {
@@ -618,9 +543,6 @@ impl VpnBuilder {
}
pub fn build(self) -> Result<Vpn, VpnError> {
if self.script_tun_launch.is_some() && !self.script_tun {
return Err(VpnError::new("Child identity requires script-tun".into()));
}
let script = self.resolve_script()?;
let user_agent = self.user_agent.unwrap_or_default();
@@ -642,7 +564,6 @@ impl VpnBuilder {
network_configuration_handler: self.network_configuration_handler,
interface: self.interface.as_deref().map(Self::to_cstring),
script_tun: self.script_tun,
script_tun_launch: self.script_tun_launch,
certificate: self.certificate.as_deref().map(Self::to_cstring),
sslkey: self.sslkey.as_deref().map(Self::to_cstring),
@@ -654,7 +575,6 @@ impl VpnBuilder {
reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu,
disable_ipv6: self.disable_ipv6,
gateway_ip_preference: self.gateway_ip_preference,
no_dtls: self.no_dtls,
dpd_interval: self.dpd_interval,
no_xmlpost: self.no_xmlpost,
@@ -774,7 +694,6 @@ mod tests {
network_configuration_handler: None,
interface: None,
script_tun: false,
script_tun_launch: None,
certificate: None,
sslkey: None,
key_password: None,
@@ -783,7 +702,6 @@ mod tests {
reconnect_timeout: 300,
mtu: 0,
disable_ipv6: false,
gateway_ip_preference: GatewayIpPreference::Auto,
no_dtls: false,
dpd_interval: 0,
no_xmlpost: false,
@@ -799,27 +717,6 @@ mod tests {
assert_eq!(host_id, "profile-host-id");
}
#[test]
fn gateway_preference_and_tunnel_ipv6_are_independent_in_native_options() {
for preference in [
GatewayIpPreference::Auto,
GatewayIpPreference::Ipv4,
GatewayIpPreference::Ipv6,
] {
for disable_ipv6 in [false, true] {
let vpn = Vpn::builder("https://gateway.example", "fixture")
.script_path("/bin/sh".to_string())
.disable_ipv6(disable_ipv6)
.gateway_ip_preference(preference)
.build()
.unwrap();
let options = vpn.build_connect_options();
assert_eq!(options.gateway_ip_preference, preference as u32);
assert_eq!(options.disable_ipv6, disable_ipv6 as u32);
}
}
}
#[test]
fn hip_report_callback_copies_only_bounded_utf8() {
let vpn = Vpn::builder("vpn.example.com", "cookie")
@@ -1076,12 +973,3 @@ mod tests {
cancellation.detach();
}
}
#[unsafe(no_mangle)]
extern "C" fn vpn_script_started(data: *mut std::ffi::c_void) {
// Native setup has forked or failed; only the child may retain this endpoint.
let vpn = unsafe { &*(data as *const Vpn) };
if let Some(launch) = &vpn.script_tun_launch {
launch.control.lock().unwrap().take();
}
}
-81
View File
@@ -13,38 +13,6 @@ struct peer {
};
struct policy { int accept, calls, unsafe_renegotiation_denied; };
struct stalled_logout_peer {
int listener, stop, complete_tls;
gnutls_certificate_credentials_t credentials;
};
static void *stall_logout(void *data)
{
struct stalled_logout_peer *peer = data;
struct timeval timeout = { .tv_sec = 7 };
fd_set reads;
gnutls_session_t session = NULL;
int fd = accept(peer->listener, NULL, NULL);
assert(fd >= 0);
if (peer->complete_tls) {
assert(!gnutls_init(&session, GNUTLS_SERVER));
assert(!gnutls_set_default_priority(session));
assert(!gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, peer->credentials));
gnutls_transport_set_int(session, fd);
gnutls_handshake_set_timeout(session, 5000);
assert(!gnutls_handshake(session));
}
/* Stall either the TLS handshake or the HTTP logout response. The watchdog
* lets the regression fail without leaving either peer blocked forever. */
FD_ZERO(&reads);
FD_SET(peer->stop, &reads);
select(peer->stop + 1, &reads, NULL, NULL, &timeout);
if (session)
gnutls_deinit(session);
close(fd);
return NULL;
}
static void progress(void *data, int level, const char *format, ...)
{
va_list args;
@@ -67,53 +35,6 @@ static int certificate_policy(void *data, const char *reason)
return policy->accept ? 0 : -EINVAL;
}
static void logout_finishes_when_gateway_stalls(const char *cert, const char *key, int complete_tls)
{
struct stalled_logout_peer peer;
struct policy policy = { .accept = 1 };
struct sockaddr_in address = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
socklen_t length = sizeof(address);
struct timespec start, end;
struct openconnect_info *client;
pthread_t thread;
char url[128];
int stop[2];
double elapsed;
assert(!pipe(stop));
peer.complete_tls = complete_tls;
assert(!gnutls_certificate_allocate_credentials(&peer.credentials));
assert(!gnutls_certificate_set_x509_key_file(peer.credentials, cert, key, GNUTLS_X509_FMT_PEM));
peer.stop = stop[0];
peer.listener = socket(AF_INET, SOCK_STREAM, 0);
assert(peer.listener >= 0);
assert(!bind(peer.listener, (struct sockaddr *)&address, sizeof(address)));
assert(!getsockname(peer.listener, (struct sockaddr *)&address, &length));
assert(!listen(peer.listener, 1));
assert(!pthread_create(&thread, NULL, stall_logout, &peer));
client = openconnect_vpninfo_new("Logout timeout regression", certificate_policy, NULL, NULL, progress, &policy);
assert(client);
snprintf(url, sizeof(url), "https://127.0.0.1:%u/", ntohs(address.sin_port));
assert(!openconnect_parse_url(client, url));
assert(!openconnect_set_protocol(client, "gp"));
assert(!openconnect_set_cookie(client, "user=fixture&authcookie=fixture"));
/* Enter the same cleanup branch as a consumed OC_CMD_CANCEL. */
client->quit_reason = "Aborted by caller";
assert(!clock_gettime(CLOCK_MONOTONIC, &start));
assert(openconnect_mainloop(client, 0, 0) < 0);
assert(!client->https_deadline.tv_sec && !client->https_deadline.tv_nsec);
assert(!clock_gettime(CLOCK_MONOTONIC, &end));
elapsed = end.tv_sec - start.tv_sec + (end.tv_nsec - start.tv_nsec) / 1e9;
(void)write(stop[1], "x", 1);
assert(!pthread_join(thread, NULL));
close(stop[0]);
close(stop[1]);
close(peer.listener);
gnutls_certificate_free_credentials(peer.credentials);
openconnect_vpninfo_free(client);
assert(elapsed < 6.0);
}
static void *serve(void *data)
{
struct peer *peer = data;
@@ -213,8 +134,6 @@ int main(int argc, char **argv)
assert(argc == 6);
signal(SIGPIPE, SIG_IGN);
assert(!openconnect_init_ssl());
logout_finishes_when_gateway_stalls(argv[1], argv[2], 0);
logout_finishes_when_gateway_stalls(argv[1], argv[2], 1);
#ifdef __APPLE__
/* Read-only check of the source-built library's native Keychain integration.
* Local fixture trust is tested separately, without changing OS trust settings. */
Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Generated
+3 -3
View File
@@ -63,11 +63,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1793494649,
"narHash": "sha256-Thn0OE71NF80ZfOMGCgJvKtbCcnnz0fToT/qsvb/Gtc=",
"lastModified": 1791487292,
"narHash": "sha256-tqM7xDEsaeK1p6VvRygeZ9LkQRpUUkbRT02BHv6hnTM=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "d357a2b54f0b6dc4aeb4e993190a52cf151b6f24",
"rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30",
"type": "github"
},
"original": {
+6 -6
View File
@@ -29,8 +29,8 @@
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
pname = "globalprotect-openconnect";
version = cargoToml.workspace.package.version;
releaseTag = "snapshot";
releaseVersion = "3.2.0";
releaseTag = "v3.0.5";
releaseVersion = "3.0.5";
toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
@@ -55,8 +55,8 @@
cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name;
gpguiHashes = {
x86_64 = "sha256-W0ijBnwPmbkyLQgVwB1cwfgbKDe+o8KD+gm/zw+KXK4=";
aarch64 = "sha256-uuAFFYMVbxbNzCtI9SBXu/v24iNNqHFoNaYP5PlJRVE=";
x86_64 = "sha256-b0hqpAr/Sz9z+UTCmAGV3eIO8sNUjrH34NZZYcLyzzw=";
aarch64 = "sha256-QQh/T/fknvPeZ1UdRCo2idiIBX1LTJHSwQ2MK/j3Gm0=";
};
gpguiArchive = pkgs.fetchurl {
@@ -70,8 +70,8 @@
};
binaryHashes = {
x86_64 = "sha256-uc6D7tbU5/xS5KBUd1L4ssygVo8b372c/eX5w6lxsOE=";
aarch64 = "sha256-/4IbFqtt6hVATSKHxmMyxRDfFaBfYtZMYIo+bXE6KFo=";
x86_64 = "sha256-zbs/StUxfD3nf5mjUiGTu3CUI96SkB+r0DD6kcvCqjY=";
aarch64 = "sha256-QGuTJvAlj9maV++LFQGdjSZCUYafFx60AzyZjulnEes=";
};
binaryArchive = pkgs.fetchurl {
@@ -18,20 +18,11 @@
<clipPath id="globe-clip">
<circle cx="512" cy="455" r="315"/>
</clipPath>
<!-- Use SVG 1.1 primitives: feDropShadow needs librsvg >= 2.55.91. -->
<filter id="globe-shadow" x="150" y="90" width="730" height="760" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feGaussianBlur in="SourceAlpha" stdDeviation="12" result="blur"/>
<feOffset in="blur" dx="0" dy="8" result="offsetBlur"/>
<feFlood flood-color="#174d6f" flood-opacity=".14" result="shadowColor"/>
<feComposite in="shadowColor" in2="offsetBlur" operator="in" result="shadow"/>
<feMerge><feMergeNode in="shadow"/><feMergeNode in="SourceGraphic"/></feMerge>
<feDropShadow dx="0" dy="8" stdDeviation="12" flood-color="#174d6f" flood-opacity=".14"/>
</filter>
<filter id="lock-shadow" x="280" y="210" width="470" height="540" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feGaussianBlur in="SourceAlpha" stdDeviation="18" result="blur"/>
<feOffset in="blur" dx="0" dy="18" result="offsetBlur"/>
<feFlood flood-color="#70430c" flood-opacity=".2" result="shadowColor"/>
<feComposite in="shadowColor" in2="offsetBlur" operator="in" result="shadow"/>
<feMerge><feMergeNode in="shadow"/><feMergeNode in="SourceGraphic"/></feMerge>
<feDropShadow dx="0" dy="18" stdDeviation="18" flood-color="#70430c" flood-opacity=".2"/>
</filter>
</defs>

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env bash
set -euo pipefail
release_version="${1:-}"
release_tag="${2:-}"
if git diff --quiet -- flake.nix flake.lock; then
echo "flake hashes and lock are already up to date"
exit 0
fi
if [[ -z "$release_version" ]]; then
release_version="$(grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')"
fi
version="${release_version#v}"
if [[ -z "$release_tag" ]]; then
release_tag="v$version"
fi
branch_suffix="v${version}"
title="chore: update flake hashes for v${version}"
body="Updates the Nix flake fetchurl hashes for v${version} release assets and refreshes the Nixpkgs lock."
if [[ "$release_tag" != "v$version" ]]; then
branch_suffix="${branch_suffix}-${release_tag}"
title="chore: update flake hashes for v${version} from ${release_tag}"
body="Updates the Nix flake fetchurl hashes for v${version} using ${release_tag} release assets and refreshes the Nixpkgs lock."
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
if [[ "$release_tag" == "snapshot" ]]; then
source_branch="${GITHUB_REF_NAME:-$(git branch --show-current)}"
source_branch_slug="$(printf '%s' "$source_branch" | sed -E 's#[/[:space:]]+#-#g; s#[^A-Za-z0-9._-]##g; s#^-+##; s#-+$##')"
branch="chore/flake-${source_branch_slug}"
git switch -C "$branch"
git add flake.nix flake.lock
git commit -m "$title"
git push --force origin "$branch"
echo "Updated snapshot flake hashes on branch $branch from $source_branch; skipping PR creation"
exit 0
fi
branch="chore/update-flake-hashes-${branch_suffix}"
git switch -C "$branch"
git add flake.nix flake.lock
git commit -m "$title"
git push --force origin "$branch"
pr_number="$(gh pr list --head "$branch" --state open --json number --jq '.[0].number')"
if [[ -n "$pr_number" ]]; then
gh pr edit "$pr_number" --title "$title" --body "$body"
else
gh pr create --title "$title" --body "$body" --base main --head "$branch"
fi
-48
View File
@@ -1,48 +0,0 @@
#!/usr/bin/env bash
# Prepare a reviewable main candidate; publishing and merging remain explicit.
set -euo pipefail
tag="${1:?Usage: prepare-release-promotion.sh <vX.Y.Z> <updated-flake-directory>}"
artifact_dir="$(cd "${2:?Updated flake artifact directory is required}" && pwd)"
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ ! "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "A stable release tag is required" >&2
exit 1
fi
if [[ -n "$(git status --porcelain)" ]]; then
echo "Start with a clean working tree" >&2
exit 1
fi
python3 - "$artifact_dir/release-candidate.json" "$tag" <<'PY'
import json, sys
from pathlib import Path
candidate = json.loads(Path(sys.argv[1]).read_text())
if candidate['releaseTag'] != sys.argv[2] or candidate['version'] != sys.argv[2][1:]:
raise SystemExit('Flake artifact does not belong to the requested release')
PY
python3 "$script_dir/validate-release-version.py" --root "$artifact_dir" --version "${tag#v}"
git fetch origin refs/heads/main:refs/remotes/origin/main
git fetch origin "refs/tags/$tag"
release_sha="$(git rev-parse 'FETCH_HEAD^{commit}')"
python3 - "$tag" <<'PY'
import re, subprocess, sys
cargo = subprocess.check_output(['git', 'show', 'origin/main:Cargo.toml'], text=True)
version = re.search(r'^version\s*=\s*"([0-9.]+)"', cargo, re.M)[1]
if tuple(map(int, sys.argv[1][1:].split('.'))) < tuple(map(int, version.split('.'))):
raise SystemExit('Refusing to prepare a release older than main')
PY
branch="chore/promote-$tag"
git switch -c "$branch" origin/main
git merge --no-commit --no-ff "$release_sha"
cp "$artifact_dir/flake.nix" "$artifact_dir/flake.lock" .
python3 "$script_dir/validate-release-version.py" --version "${tag#v}"
# Check against Cargo too: overriding the expectation above is only for artifacts.
python3 "$script_dir/validate-release-version.py"
git add flake.nix flake.lock
if ! git diff --cached --quiet || [[ -f "$(git rev-parse --git-path MERGE_HEAD)" ]]; then
git commit -m "release: promote $tag sources and Nix packages together"
fi
echo "Prepared $branch. Review the candidate, push normally, and open one PR against main."
-36
View File
@@ -1,36 +0,0 @@
#!/usr/bin/env bash
# Publish a tested snapshot flake beside its source branch; never open a main PR.
set -euo pipefail
source_branch="${GITHUB_REF_NAME:?Run this workflow from the source branch}"
read -r branch expected version < <(python3 - <<'PYMETA'
import json, re
from pathlib import Path
metadata = json.loads(Path('release-candidate.json').read_text())
if metadata['releaseTag'] != 'snapshot':
raise SystemExit('Only snapshot test branches can be published')
head = metadata['expectedTestHead']
if head and not re.fullmatch('[0-9a-f]{40}', head):
raise SystemExit('Invalid test branch lease')
print(metadata['testBranch'], head or '-', metadata['version'])
PYMETA
)
if [[ "$expected" == - ]]; then
expected=""
fi
git check-ref-format "refs/heads/$branch"
python3 scripts/validate-release-version.py --version "$version" --release-tag snapshot
if git diff --quiet -- flake.nix flake.lock; then
echo "Snapshot flake files are already up to date"
exit 0
fi
# The lease was captured before candidate generation and Nix validation.
# Concurrent or delayed runs cannot replace a newer branch update.
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git switch -c "$branch"
git add flake.nix flake.lock
git commit -m "test: prepare snapshot flake for $source_branch"
git push --force-with-lease="refs/heads/$branch:$expected" origin "HEAD:refs/heads/$branch"
echo "Published $branch from $source_branch for Nix testing"
-46
View File
@@ -1,46 +0,0 @@
#!/usr/bin/env python3
"""Retain one source pair per build run so retries cannot move branch refs."""
import argparse
import json
import os
import re
import subprocess
from pathlib import Path
def record(path, gp, gpgui, output):
if path.exists():
sources = json.loads(path.read_text())
else:
sources = {
name: subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"],
text=True, stderr=subprocess.DEVNULL).strip()
for name, root in (("gp_sha", gp), ("gpgui_sha", gpgui))
}
if set(sources) != {"gp_sha", "gpgui_sha"} or any(
not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{40}", value)
for value in sources.values()
):
raise ValueError("invalid retained build source refs")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(sources, indent=2) + "\n")
with output.open("a") as stream:
for name, sha in sources.items():
stream.write(f"{name}={sha}\n")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("path", type=Path)
parser.add_argument("--gp", type=Path, required=True)
parser.add_argument("--gpgui", type=Path, required=True)
args = parser.parse_args()
try:
record(args.path, args.gp, args.gpgui, Path(os.environ["GITHUB_OUTPUT"]))
except (OSError, ValueError, subprocess.CalledProcessError):
parser.exit(1, "Could not retain the selected build source refs.\n")
if __name__ == "__main__":
main()
+1 -5
View File
@@ -9,11 +9,7 @@ escape_replacement() {
}
# Each integration format has its own quoting rules.
desktop_prefix=$(printf '%s' "$prefix" | sed -e 's/\\/\\\\\\\\/g' -e 's/["`$]/\\\\&/g' -e 's/%/%%/g')
# Avoid unnecessary quotes for older xdg-open parsers.
case "$prefix/bin/gpclient" in
*[!A-Za-z0-9_./-]*) desktop_command=$(escape_replacement "\"$desktop_prefix/bin/gpclient\"") ;;
*) desktop_command=$(escape_replacement "$desktop_prefix/bin/gpclient") ;;
esac
desktop_command=$(escape_replacement "\"$desktop_prefix/bin/gpclient\"")
shell_prefix=$(printf '%s' "$prefix" | sed "s/'/'\\\\''/g")
shell_command=$(escape_replacement "'$shell_prefix/bin/gpclient'")
xml_prefix=$(printf '%s' "$prefix" | sed -e 's/\&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g')
-32
View File
@@ -1,32 +0,0 @@
#!/usr/bin/env bash
# Find the latest execution of build-macos, retaining builds across unrelated reruns.
set -euo pipefail
repository=$1
run_id=$2
latest_attempt=$3
[[ "$run_id" =~ ^[0-9]+$ && "$latest_attempt" =~ ^[1-9][0-9]*$ ]]
for ((attempt = latest_attempt; attempt >= 1; attempt--)); do
jobs=$(gh api --paginate "repos/$repository/actions/runs/$run_id/attempts/$attempt/jobs" \
--jq '.jobs[] | select(.name == "build-macos")' | jq -s .)
if [[ $(jq length <<<"$jobs") == 0 ]]; then
continue
fi
if ! jq -e 'length == 1 and .[0].status == "completed" and .[0].conclusion == "success"' <<<"$jobs" >/dev/null; then
echo "The latest macOS job must have completed successfully." >&2
exit 1
fi
artifact_name="macos-release-$run_id.$attempt.macos"
artifacts=$(gh api --paginate "repos/$repository/actions/runs/$run_id/artifacts" \
--jq '.artifacts[]' | jq -s --arg name "$artifact_name" '[.[] | select(.name == $name)]')
if ! jq -e 'length == 1 and .[0].expired == false' <<<"$artifacts" >/dev/null; then
echo "The latest macOS build must have one unexpired artifact." >&2
exit 1
fi
echo "$artifact_name"
exit 0
done
echo "No macOS job was found in this run." >&2
exit 1
-54
View File
@@ -1,54 +0,0 @@
#!/usr/bin/env bash
# Emit only host-owned stage names; never forward private command output.
set -euo pipefail
source_directory=$1
container="gp-private-tests-$$"
trap 'timeout --kill-after=5s 30s docker rm --force "$container" >/dev/null 2>&1 || true' EXIT
run_stage() {
local name=$1 limit=$2 status started=$SECONDS
shift 2
echo "$name: started (limit $limit)."
if timeout --kill-after=30s "$limit" "$@" >/dev/null 2>&1; then
echo "$name: passed ($((SECONDS - started))s)."
else
status=$?
if [[ "$status" == 124 ]]; then
echo "::error::$name: timed out after $((SECONDS - started))s (limit $limit); diagnostics suppressed."
elif [[ "$status" == 137 ]]; then
echo "::error::$name: killed after $((SECONDS - started))s (possible timeout or memory pressure); diagnostics suppressed."
else
echo "::error::$name: failed after $((SECONDS - started))s (exit $status); diagnostics suppressed."
fi
exit "$status"
fi
}
run_stage 'Start test container' 5m docker run --detach --rm \
--name "$container" \
--user vscode \
-e HOME=/home/vscode \
-e CARGO_TARGET_DIR=/tmp/gpgui-test-target \
-e COREPACK_INTEGRITY_KEYS=0 \
-e LIBXML2_STATIC=1 \
-v "$source_directory:/source:ro" \
yuezk/gpdev:binary-builder-tauri2 sleep infinity
# Tauri writes schemas into the checkout; keep the host source read-only.
# shellcheck disable=SC2016 # Expand id inside the container, not on the host.
run_stage 'Prepare test workspace' 5m docker exec "$container" sh -ec '
test "$(id -u)" -ne 0
cp -R /source /tmp/gpgui-test-workspace
'
workspace=/tmp/gpgui-test-workspace/gpgui
run_stage 'Install frontend dependencies' 10m \
docker exec --workdir "$workspace" "$container" pnpm install --frozen-lockfile
run_stage 'Frontend tests' 5m \
docker exec --workdir "$workspace" "$container" pnpm --filter gpgui test
run_stage 'Frontend build' 10m \
docker exec --workdir "$workspace" "$container" pnpm --filter gpgui build
run_stage 'Compile Rust tests' 30m \
docker exec --workdir "$workspace" "$container" cargo test --workspace --locked --no-run
run_stage 'Rust tests' 10m \
docker exec --workdir "$workspace" "$container" cargo test --workspace --locked
+1 -1
View File
@@ -24,7 +24,7 @@ for platform in linux bsd; do
installed="$stage/custom/gp"
test -x "$installed/bin/gpclient"
test -x "$installed/libexec/gpclient/gp-vpnc-script-installer"
grep -Fxq 'Exec=/custom/gp/bin/gpclient launch-gui %u' "$installed/share/applications/gpgui.desktop"
grep -q 'Exec="/custom/gp/bin/gpclient" ' "$installed/share/applications/gpgui.desktop"
grep -q '>/custom/gp/bin/gpservice<' "$installed/share/polkit-1/actions/com.yuezk.gpgui.policy"
grep -q '>/custom/gp/libexec/gpclient/gp-hip-script-installer<' "$installed/share/polkit-1/actions/com.yuezk.gpgui.policy"
! grep -F "$stage" "$installed/share/applications/gpgui.desktop"
-49
View File
@@ -1,49 +0,0 @@
"""Render desktop icons through the distro's GdkPixbuf/librsvg loader.
Run with /usr/bin/python3; requires python3-gi and gir1.2-gdkpixbuf-2.0.
"""
from pathlib import Path
import unittest
import gi
gi.require_version("GdkPixbuf", "2.0")
from gi.repository import GdkPixbuf
ROOT = Path(__file__).resolve().parents[2]
ICONS = (
ROOT / "packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg",
ROOT / "apps/gpgui-helper/src-tauri/icons/icon.svg",
)
class DesktopIconTests(unittest.TestCase):
def test_packaged_and_helper_icons_match(self):
self.assertEqual(ICONS[0].read_bytes(), ICONS[1].read_bytes())
def test_icons_render_visible_artwork(self):
# Unsupported filter primitives can load successfully yet produce an
# entirely transparent icon, so successful decoding alone is not enough.
for icon in ICONS:
for size in (32, 48, 128, 256, 512):
with self.subTest(icon=icon, size=size):
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
str(icon), size, size, True
)
self.assertEqual((pixbuf.get_width(), pixbuf.get_height()), (size, size))
self.assertTrue(pixbuf.get_has_alpha())
pixels = pixbuf.get_pixels()
stride = pixbuf.get_rowstride()
channels = pixbuf.get_n_channels()
visible = sum(
pixels[y * stride + x * channels + channels - 1] > 128
for y in range(size)
for x in range(size)
)
self.assertGreater(visible, size * size * 0.4)
if __name__ == "__main__":
unittest.main()
-215
View File
@@ -1,215 +0,0 @@
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
import textwrap
import unittest
ROOT = Path(__file__).resolve().parents[2]
def run_block(path, step=None):
source = (ROOT / path).read_text()
if step:
source = source.split('- name: ' + step + '\n', 1)[1]
match = re.search(r'(?m)^( +)run: \|\n', source)
indent = len(match[1]) + 2
lines = []
for line in source[match.end():].splitlines():
if line.strip() and len(line) - len(line.lstrip()) < indent:
break
lines.append(line[indent:])
return '\n'.join(lines)
class PrivateOutputTests(unittest.TestCase):
def test_private_checkout_supports_branch_tag_and_sha_without_retaining_token(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
origin = root / 'origin'
subprocess.run(['git', 'init', '-b', 'main', str(origin)], check=True, capture_output=True)
git_env = dict(os.environ, GIT_AUTHOR_NAME='Test', GIT_AUTHOR_EMAIL='[email protected]',
GIT_COMMITTER_NAME='Test', GIT_COMMITTER_EMAIL='[email protected]')
subprocess.run(['git', '-C', str(origin), 'commit', '--allow-empty', '-m', 'PRIVATE_SUBJECT'],
env=git_env, check=True, capture_output=True)
subprocess.run(['git', '-C', str(origin), 'tag', 'v1.0.0'], check=True)
sha = subprocess.check_output(['git', '-C', str(origin), 'rev-parse', 'HEAD'], text=True).strip()
config = root / 'gitconfig'
config.write_text(f'[url "{origin.as_uri()}"]\n insteadOf = https://github.com/yuezk/gpgui\n')
for index, ref in enumerate(('main', 'v1.0.0', sha)):
destination = root / f'checkout-{index}'
env = dict(os.environ, GIT_CONFIG_GLOBAL=str(config), PRIVATE_TOKEN='test-token',
PRIVATE_REF=ref, PRIVATE_PATH=str(destination))
result = subprocess.run(['bash', '-e', '-o', 'pipefail', '-c',
run_block('.github/actions/checkout-private/action.yaml')],
env=env, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertNotIn('PRIVATE_SUBJECT', result.stdout + result.stderr)
self.assertNotIn('test-token', (destination / '.git/config').read_text())
self.assertNotIn('extraheader', (destination / '.git/config').read_text())
actual = subprocess.check_output(['git', '-C', str(destination), 'rev-parse', 'HEAD'], text=True)
self.assertEqual(actual.strip(), sha)
def test_private_commands_hide_stdout_and_stderr_and_preserve_failure(self):
cases = [
('.github/workflows/build.yaml', 'Build macOS release artifacts'),
('.github/workflows/build.yaml', 'Build gpgui frontend'),
('.github/workflows/build-gpgui-linux.yaml', 'Build gpgui in Docker'),
('.github/workflows/publish-update-feeds.yaml', 'Install Worker tooling'),
('.github/workflows/publish-update-feeds.yaml', 'Deploy update feed worker'),
('.github/actions/checkout-private/action.yaml', None),
]
for path, step in cases:
for status in (0, 19):
with self.subTest(step=step, status=status), tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
stub = '#!/bin/sh\necho PRIVATE_STDOUT\necho PRIVATE_STDERR >&2\necho \"MACOS_STAGE: Signing\"\necho \"MACOS_STAGE: Signing PRIVATE_DETAIL\"\nexit "$TEST_STATUS"\n'
for command in ('git', 'docker', 'pnpm', 'source/gpgui/scripts/build-macos.sh'):
executable = root / command
executable.parent.mkdir(parents=True, exist_ok=True)
executable.write_text(stub)
executable.chmod(0o755)
(root / 'gpgui-frontend/gpgui/apps/desktop').mkdir(parents=True)
(root / 'gpgui/apps/update-feed-worker/public').mkdir(parents=True)
(root / 'updates').mkdir()
(root / 'updates/appcast.xml').write_text('fixture')
env = dict(os.environ, PATH=f'{root}:{os.environ["PATH"]}',
TEST_STATUS=str(status), CHANNEL='snapshot', GPGUI_BUILDER='fixture',
RUNNER_TEMP=str(root), UPDATES_WORKER_NAME='fixture',
PRIVATE_TOKEN='test-token', PRIVATE_REF='test-ref', PRIVATE_PATH='private')
result = subprocess.run(['bash', '-e', '-c', run_block(path, step)],
cwd=root, env=env, text=True, capture_output=True)
self.assertEqual(result.returncode, status, result.stdout + result.stderr)
self.assertNotIn('PRIVATE_STD', result.stdout + result.stderr)
self.assertNotIn('PRIVATE_DETAIL', result.stdout + result.stderr)
if step == 'Build macOS release artifacts':
self.assertIn('::notice::MACOS_STAGE: Signing', result.stdout)
self.assertNotIn('test-token', result.stdout + result.stderr)
self.assertIn('passed' if status == 0 else 'failed', result.stdout)
class PrivateTestStageTests(unittest.TestCase):
def run_stages(self, mode):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
docker = root / 'docker'
docker.write_text(textwrap.dedent('''\
#!/usr/bin/env python3
import json, os, sys, time
with open(os.environ['CALLS'], 'a') as output:
output.write(json.dumps(sys.argv[1:]) + '\\n')
print('PRIVATE_STDOUT')
print('PRIVATE_STDERR', file=sys.stderr)
if 'cargo' in sys.argv and '--no-run' not in sys.argv:
if os.environ['MODE'] == 'hang':
time.sleep(60)
if os.environ['MODE'] == 'fail':
sys.exit(19)
'''))
timeout = root / 'timeout'
timeout.write_text(textwrap.dedent('''\
#!/usr/bin/env python3
import subprocess, sys
assert sys.argv[1].startswith('--kill-after=')
assert sys.argv[2].endswith(('m', 's'))
try:
result = subprocess.run(sys.argv[3:], timeout=2)
sys.exit(result.returncode)
except subprocess.TimeoutExpired:
sys.exit(124)
'''))
for executable in (docker, timeout):
executable.write_text(executable.read_text().replace("#!/usr/bin/env python3", f"#!{sys.executable}"))
executable.chmod(0o755)
calls = root / 'calls.jsonl'
env = dict(os.environ, PATH=f'{root}:{os.environ["PATH"]}', MODE=mode, CALLS=str(calls))
result = subprocess.run(['bash', str(ROOT / 'scripts/test-private-desktop.sh'), str(root)],
env=env, text=True, capture_output=True, timeout=10)
self.assertNotIn('PRIVATE_STD', result.stdout + result.stderr)
recorded = [json.loads(line) for line in calls.read_text().splitlines()]
self.assertEqual(recorded[-1][:2], ['rm', '--force'])
return result
def test_success_reports_each_stage(self):
result = self.run_stages('success')
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertEqual(result.stdout.count(': started'), 7)
self.assertEqual(result.stdout.count(': passed'), 7)
self.assertIn('Compile Rust tests: passed', result.stdout)
self.assertIn('Rust tests: passed', result.stdout)
def test_failure_names_stage_and_preserves_exit(self):
result = self.run_stages('fail')
self.assertEqual(result.returncode, 19)
self.assertIn('Rust tests: failed', result.stdout)
self.assertNotRegex(result.stdout, r'(?m)^Rust tests: passed')
def test_hung_tests_report_timeout_and_cleanup(self):
result = self.run_stages('hang')
self.assertEqual(result.returncode, 124)
self.assertIn('Rust tests: timed out', result.stdout)
self.assertNotRegex(result.stdout, r'(?m)^Rust tests: passed')
class MacOSArtifactSelectionTests(unittest.TestCase):
def select(self, jobs, artifacts=None):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
gh = root / 'gh'
gh.write_text(textwrap.dedent('''\
#!/usr/bin/env python3
import json, os, re, sys
endpoint = sys.argv[3]
if endpoint.endswith('/artifacts'):
records = json.loads(os.environ['ARTIFACTS'])
else:
attempt = re.search(r'/attempts/([0-9]+)/jobs', endpoint)[1]
records = json.loads(os.environ['JOBS']).get(attempt, [])
for record in records:
print(json.dumps(record))
'''))
gh.chmod(0o755)
env = dict(os.environ, PATH=f'{root}:{os.environ["PATH"]}', JOBS=json.dumps(jobs),
ARTIFACTS=json.dumps(artifacts if artifacts is not None else [
{'name': 'macos-release-42.1.macos', 'expired': False}]))
return subprocess.run(['bash', str(ROOT / 'scripts/select-macos-artifact.sh'), 'owner/repo', '42', '3'],
env=env, capture_output=True, text=True)
def job(self, conclusion='success', status='completed'):
return {'name': 'build-macos', 'status': status, 'conclusion': conclusion}
def test_unrelated_reruns_reuse_successful_macos_attempt(self):
result = self.select({'1': [self.job()]})
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.strip(), 'macos-release-42.1.macos')
def test_newer_macos_execution_wins(self):
result = self.select({'1': [self.job()], '3': [self.job()]}, [
{'name': f'macos-release-42.{attempt}.macos', 'expired': False} for attempt in (1, 3)])
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.strip(), 'macos-release-42.3.macos')
def test_never_falls_back_past_failed_cancelled_skipped_or_running_macos(self):
for conclusion, status in [('failure', 'completed'), ('cancelled', 'completed'),
('skipped', 'completed'), (None, 'in_progress')]:
with self.subTest(conclusion=conclusion):
result = self.select({'1': [self.job()], '2': [self.job(conclusion, status)]})
self.assertNotEqual(result.returncode, 0)
self.assertEqual(result.stdout, '')
def test_missing_expired_or_duplicate_artifacts_are_rejected(self):
valid = {'name': 'macos-release-42.1.macos', 'expired': False}
for artifacts in ([], [dict(valid, expired=True)], [valid, valid]):
with self.subTest(artifacts=artifacts):
self.assertNotEqual(self.select({'1': [self.job()]}, artifacts).returncode, 0)
def test_missing_macos_job_is_rejected(self):
self.assertNotEqual(self.select({}).returncode, 0)
if __name__ == '__main__':
unittest.main()
-218
View File
@@ -1,218 +0,0 @@
import importlib.util
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
def load(name):
spec = importlib.util.spec_from_file_location(name, ROOT / 'scripts' / f'{name}.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
versions = load('validate-release-version')
sources = load('record-build-sources')
def git(root, *args):
return subprocess.check_output(['git', '-C', str(root), *args], text=True,
stderr=subprocess.DEVNULL).strip()
def initialize(root):
root.mkdir(parents=True, exist_ok=True)
git(root, 'init', '-b', 'main')
git(root, 'config', 'user.name', 'Release Test')
git(root, 'config', 'user.email', '[email protected]')
def write_version(root, cargo='3.1.0', flake=None, tag=None):
flake = flake or cargo
(root / 'Cargo.toml').write_text(f'[workspace.package]\nversion = "{cargo}"\n')
(root / 'flake.nix').write_text(f'releaseVersion = "{flake}";\nreleaseTag = "{tag or "v" + flake}";\n')
(root / 'flake.lock').write_text('{}\n')
def commit(root, title):
git(root, 'add', '.')
git(root, 'commit', '-m', title)
return git(root, 'rev-parse', 'HEAD')
class ReleaseVersionTests(unittest.TestCase):
def test_main_rejects_old_new_and_snapshot_flakes(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
for selected, tag in [('3.1.0', 'v3.1.0'), ('3.3.0', 'v3.3.0'), ('3.2.0', 'snapshot')]:
write_version(root, '3.2.0', selected, tag)
with self.subTest(selected=selected, tag=tag), self.assertRaises(ValueError):
versions.validate(root)
write_version(root, '3.2.0')
self.assertEqual(versions.validate(root), '3.2.0')
def test_snapshot_candidate_is_allowed_outside_main(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
write_version(root, '3.2.0', tag='snapshot')
self.assertEqual(versions.validate(root, release_tag='snapshot'), '3.2.0')
def test_rollback_of_both_version_fields_is_rejected(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
initialize(root)
write_version(root, '3.3.0')
base = commit(root, 'new main')
write_version(root, '3.2.0')
with self.assertRaisesRegex(ValueError, 'older'):
versions.validate(root, base_ref=base)
def test_actual_package_version_must_match(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
write_version(root, '3.2.0')
package = root / 'result'
(package / 'bin').mkdir(parents=True)
for name in ('gpclient', 'gpservice', 'gpauth', 'gpgui'):
tool = package / 'bin' / name
tool.write_text(f'#!/bin/sh\necho "{name} 3.2.0 (PRIVATE_IDENTITY)"\n')
tool.chmod(0o755)
versions.validate(root, package=package)
(package / 'bin/gpgui').write_text('#!/bin/sh\necho "gpgui 3.1.0 PRIVATE_DETAIL"\n')
with self.assertRaisesRegex(ValueError, 'gpgui'):
versions.validate(root, package=package)
class SourceSelectionTests(unittest.TestCase):
def test_retry_uses_original_sources_after_both_branches_advance(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
paths = [root / 'gp', root / 'gpgui']
for repo in paths:
initialize(repo)
(repo / 'source').write_text('first')
commit(repo, 'first')
path, output = root / 'sources.json', root / 'output'
sources.record(path, *paths, output)
original = json.loads(path.read_text())
for repo in paths:
(repo / 'source').write_text('second')
commit(repo, 'second')
sources.record(path, *paths, output)
self.assertEqual(json.loads(path.read_text()), original)
self.assertEqual(output.read_text().count(f"gp_sha={original['gp_sha']}"), 2)
def test_corrupt_retained_sources_do_not_resolve_again(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
path = root / 'sources.json'
path.write_text('{"gp_sha":"main","gpgui_sha":"main"}')
with self.assertRaises(ValueError):
sources.record(path, root, root, root / 'output')
class PromotionTests(unittest.TestCase):
def test_sources_and_flake_are_committed_together_preserving_main_work(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
repo, origin, artifact = root / 'repo', root / 'origin.git', root / 'artifact'
initialize(repo)
write_version(repo)
old = commit(repo, '3.1')
git(repo, 'switch', '-c', 'release/next')
write_version(repo, '3.2.0', '3.1.0')
(repo / 'feature').write_text('released product feature')
release = commit(repo, '3.2 source')
git(repo, 'tag', 'v3.2.0')
git(repo, 'switch', 'main')
(repo / 'infrastructure').write_text('preserve newer main work')
main = commit(repo, 'main infrastructure')
git(root, 'init', '--bare', str(origin))
git(repo, 'remote', 'add', 'origin', str(origin))
git(repo, 'push', 'origin', 'main', 'v3.2.0')
artifact.mkdir()
write_version(artifact, '3.2.0')
(artifact / 'release-candidate.json').write_text(json.dumps({'version': '3.2.0', 'releaseTag': 'v3.2.0'}))
result = subprocess.run(['bash', str(ROOT / 'scripts/prepare-release-promotion.sh'),
'v3.2.0', str(artifact)], cwd=repo, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertEqual(versions.validate(repo), '3.2.0')
self.assertEqual(git(repo, 'rev-parse', 'main'), main)
self.assertEqual(git(repo, 'rev-parse', 'v3.2.0'), release)
self.assertEqual(git(repo, 'show', f'{old}:Cargo.toml'), '[workspace.package]\nversion = "3.1.0"')
self.assertTrue((repo / 'infrastructure').exists())
self.assertTrue((repo / 'feature').exists())
self.assertEqual(git(repo, 'rev-list', '--parents', '-1', 'HEAD').split()[1:], [main, release])
self.assertEqual(git(repo, 'status', '--porcelain'), '')
class SnapshotBranchTests(unittest.TestCase):
def run_publish(self, root, expected, version='3.2.0'):
write_version(root, version, tag='snapshot')
metadata = {'releaseTag': 'snapshot', 'version': version,
'testBranch': 'chore/flake-feature-example', 'expectedTestHead': expected}
(root / 'release-candidate.json').write_text(json.dumps(metadata))
env = dict(os.environ, GITHUB_REF_NAME='feature/example')
# CI checks out the same helper at its selected SHA. Use the real validator here.
(root / 'scripts').mkdir(exist_ok=True)
validator = root / 'scripts/validate-release-version.py'
validator.write_bytes((ROOT / 'scripts/validate-release-version.py').read_bytes())
return subprocess.run(['bash', str(ROOT / 'scripts/publish-flake-test-branch.sh')],
cwd=root, env=env, capture_output=True, text=True)
def test_branch_publication_and_stale_lease(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
repo, origin = root / 'repo', root / 'origin.git'
initialize(repo)
write_version(repo, '3.2.0')
base = commit(repo, 'source')
git(root, 'init', '--bare', str(origin))
git(repo, 'remote', 'add', 'origin', str(origin))
first = self.run_publish(repo, '')
self.assertEqual(first.returncode, 0, first.stdout + first.stderr)
head = git(repo, 'rev-parse', 'HEAD')
self.assertEqual(git(origin, 'rev-parse', 'refs/heads/chore/flake-feature-example'), head)
git(repo, 'switch', '--detach', base)
git(repo, 'branch', '-D', 'chore/flake-feature-example')
# Another run already created the branch after this run captured an absent head.
stale = self.run_publish(repo, '', '3.2.1')
self.assertNotEqual(stale.returncode, 0)
self.assertIn('stale info', stale.stderr)
self.assertEqual(git(origin, 'rev-parse', 'refs/heads/chore/flake-feature-example'), head)
git(repo, 'switch', '--detach', base)
git(repo, 'branch', '-D', 'chore/flake-feature-example')
fresh = self.run_publish(repo, head, '3.2.1')
self.assertEqual(fresh.returncode, 0, fresh.stdout + fresh.stderr)
self.assertNotEqual(git(origin, 'rev-parse', 'refs/heads/chore/flake-feature-example'), head)
self.assertEqual(git(origin, 'branch', '--list', 'main'), '')
class DockerMatrixTests(unittest.TestCase):
def test_workflow_matrix_follows_all_architecture_choices(self):
source = (ROOT / '.github/workflows/release.yaml').read_text()
block = source.split(' const inputs = ${{ toJson(inputs) }}\n', 1)[1].split('\n build:', 1)[0]
# Execute the actual github-script block, including both returned matrices.
lines = []
for line in block.splitlines():
if line.strip() and not line.startswith(' '):
break
lines.append(line[10:])
js = '\n'.join(lines)
for arch, expected in [('all', ['linux/amd64', 'linux/arm64']),
('x86_64', ['linux/amd64']), ('arm64', ['linux/arm64'])]:
harness = 'const core={setOutput:(k,v)=>console.log(v)}; const inputs=' + json.dumps({'arch': arch}) + ';\n'
result = subprocess.check_output(['node', '-e', harness + '(function(){\n' + js + '\n})();'], text=True)
matrix = json.loads(result.splitlines()[0])
self.assertEqual([row['platform'] for row in matrix['include']], expected)
if __name__ == '__main__':
unittest.main()
@@ -1,171 +0,0 @@
import os
import shutil
import subprocess
import sys
import tempfile
import textwrap
import unittest
from pathlib import Path
from test_private_ci import run_block
REPOSITORY = "yuezk/GlobalProtect-openconnect"
SCRIPT = Path(__file__).parents[1] / "validate-macos-appcast.py"
def item(version, short_version, archive, channel=None):
channel_xml = f"<sparkle:channel>{channel}</sparkle:channel>" if channel else ""
return f"""
<item>
<sparkle:version>{version}</sparkle:version>
<sparkle:shortVersionString>{short_version}</sparkle:shortVersionString>
{channel_xml}
<enclosure url="{archive}" length="100" sparkle:edSignature="signature" />
</item>
"""
def appcast(*items):
return f"""<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle">
<channel>{''.join(items)}</channel>
</rss>
"""
class ValidateMacosAppcastTests(unittest.TestCase):
def run_validator(self, content, *arguments):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "appcast.xml"
path.write_text(content, encoding="utf-8")
return subprocess.run(
["python3", str(SCRIPT), *arguments, str(path), "--repository", REPOSITORY],
check=False,
capture_output=True,
text=True,
)
def test_reports_candidate_status(self):
archive = f"https://github.com/{REPOSITORY}/releases/download/v2.6.4/GPConnect_2.6.4_arm64.zip"
content = appcast(item("806.1", "2.6.4", archive))
same = self.run_validator(
content, "status", "--build-version", "806.1"
)
newer = self.run_validator(
content, "status", "--build-version", "807.1"
)
older = self.run_validator(
content, "status", "--build-version", "805.1"
)
self.assertEqual((same.returncode, same.stdout.strip()), (0, "same"))
self.assertEqual((newer.returncode, newer.stdout.strip()), (0, "newer"))
self.assertEqual((older.returncode, older.stdout.strip()), (0, "older"))
def test_validates_stable_and_snapshot_items(self):
stable = f"https://github.com/{REPOSITORY}/releases/download/v2.6.4/GPConnect_2.6.4_arm64.zip"
snapshot = (
f"https://github.com/{REPOSITORY}/releases/download/snapshot/"
"GPConnect_2.6.4-snapshot.807.1_arm64.zip"
)
content = appcast(
item("806.1", "2.6.4", stable),
item("807.1", "2.6.4", snapshot, "snapshot"),
)
result = self.run_validator(
content,
"validate",
"--build-version",
"807.1",
"--short-version",
"2.6.4",
"--channel",
"snapshot",
"--archive-url",
snapshot,
)
self.assertEqual(result.returncode, 0, result.stderr)
def test_compares_builds_across_channels(self):
stable = f"https://github.com/{REPOSITORY}/releases/download/v2.6.4/GPConnect_2.6.4_arm64.zip"
snapshot = (
f"https://github.com/{REPOSITORY}/releases/download/snapshot/"
"GPConnect_2.6.4-snapshot.807.1_arm64.zip"
)
content = appcast(
item("2.6.4", "2.6.4", stable),
item("807.1", "2.6.4", snapshot, "snapshot"),
)
result = self.run_validator(
content, "status", "--build-version", "2.7.0"
)
self.assertEqual((result.returncode, result.stdout.strip()), (0, "older"))
def test_rejects_external_archive_urls(self):
content = appcast(item("806.1", "2.6.4", "https://example.com/update.zip"))
result = self.run_validator(
content, "status", "--build-version", "807.1"
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("unexpected update archive URL", result.stderr)
class PublishMacosAppcastTests(unittest.TestCase):
def test_retry_reuses_existing_stable_appcast_without_uploading(self):
archive = f"https://github.com/{REPOSITORY}/releases/download/v2.6.4/GPConnect_2.6.4_arm64.zip"
existing = appcast(item("806.1", "2.6.4", archive))
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "updates").mkdir()
(root / "updates/appcast.xml").write_text("newly generated candidate")
(root / "existing.xml").write_text(existing)
(root / "scripts").mkdir()
shutil.copy(SCRIPT, root / "scripts/validate-macos-appcast.py")
(root / "python3").symlink_to(sys.executable)
gh = root / "gh"
gh.write_text(f"#!{sys.executable}\n" + textwrap.dedent('''\
import os, shutil, signal, sys
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
if sys.argv[1:3] == ['release', 'view']:
print('appcast.xml', flush=True)
for number in range(10000):
print(f'other-asset-{number}')
elif sys.argv[1:3] == ['release', 'download']:
shutil.copy(os.environ['EXISTING_APPCAST'],
sys.argv[sys.argv.index('--output') + 1])
else:
sys.exit(99)
'''))
gh.chmod(0o755)
uploader = root / "gp-release/scripts/upload-release-assets.sh"
uploader.parent.mkdir(parents=True)
uploader.write_text("#!/bin/sh\ntouch upload-attempted\nexit 7\n")
uploader.chmod(0o755)
command = run_block('.github/workflows/publish-update-feeds.yaml', 'Publish appcast')
for expression, value in {
'${{ steps.archive.outputs.name }}': 'GPConnect_2.6.4_arm64.zip',
'${{ steps.bundle.outputs.version }}': '806.1',
'${{ steps.bundle.outputs.short_version }}': '2.6.4',
}.items():
command = command.replace(expression, value)
result = subprocess.run(['bash', '-e', '-o', 'pipefail', '-c', command], cwd=root,
env=dict(os.environ, PATH=f'{root}:{os.environ["PATH"]}',
RUNNER_TEMP=str(root), CHANNEL='stable',
RELEASE_TAG='v2.6.4', REPOSITORY=REPOSITORY,
EXISTING_APPCAST=str(root / 'existing.xml')),
capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertFalse((root / 'upload-attempted').exists())
self.assertEqual((root / 'updates/appcast.xml').read_text(), existing)
if __name__ == "__main__":
unittest.main()
@@ -1,99 +0,0 @@
import hashlib
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
spec = importlib.util.spec_from_file_location("macos_release", Path(__file__).parents[1] / "validate-macos-release.py")
release = importlib.util.module_from_spec(spec)
spec.loader.exec_module(release)
class MacOSReleaseTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.directory = Path(self.temp.name)
self.commit = "a" * 40
self.metadata = {"gp_ref": "b" * 40, "gpgui_ref": "d" * 40, "workflow_sha": self.commit, "channel": "stable",
"release_tag": "v3.0.1", "artifact_version": "3.0.1",
"request_id": "42.1.macos", "build_version": "903.1", "assets": {}}
for extension in ("dmg", "zip"):
name = f"GPConnect_3.0.1_arm64.{extension}"
content = b"signed artifact"
digest = hashlib.sha256(content).hexdigest()
(self.directory / name).write_bytes(content)
checksum = f"{digest} {name}\n".encode()
(self.directory / (name + ".sha256")).write_bytes(checksum)
self.metadata["assets"][name] = digest
self.metadata["assets"][name + ".sha256"] = hashlib.sha256(checksum).hexdigest()
self.save()
def save(self):
(self.directory / "release-build.json").write_text(json.dumps(self.metadata))
def test_matching_build_passes(self):
self.assertEqual(release.validate(self.directory, "v3.0.1", self.commit), self.metadata)
def test_another_release_cannot_use_this_build(self):
with self.assertRaisesRegex(ValueError, "release tag"):
release.validate(self.directory, "v3.0.2", self.commit)
def test_another_run_commit_cannot_use_this_build(self):
with self.assertRaisesRegex(ValueError, "public workflow"):
release.validate(self.directory, "v3.0.1", "c" * 40)
def test_source_commit_cannot_replace_workflow_identity(self):
with self.assertRaisesRegex(ValueError, "public workflow"):
release.validate(self.directory, "v3.0.1", self.metadata["gp_ref"])
def test_invalid_workflow_commit_is_rejected(self):
self.metadata["workflow_sha"] = "short"
self.save()
with self.assertRaisesRegex(ValueError, "Invalid workflow_sha"):
release.validate(self.directory, "v3.0.1", "short")
def test_corrupt_download_is_rejected(self):
(self.directory / "GPConnect_3.0.1_arm64.zip").write_bytes(b"changed")
with self.assertRaisesRegex(ValueError, "checksum mismatch"):
release.validate(self.directory, "v3.0.1", self.commit)
def test_unexpected_file_is_rejected(self):
(self.directory / "unexpected.dmg").write_bytes(b"extra")
with self.assertRaisesRegex(ValueError, "Unexpected"):
release.validate(self.directory, "v3.0.1", self.commit)
def test_missing_checksum_is_rejected(self):
self.metadata["assets"].pop("GPConnect_3.0.1_arm64.zip.sha256")
self.save()
with self.assertRaisesRegex(ValueError, "exactly"):
release.validate(self.directory, "v3.0.1", self.commit)
def test_snapshot_requires_matching_build_identity(self):
self.metadata.update(channel="snapshot", release_tag="snapshot",
artifact_version="3.0.1-snapshot.903.2")
self.save()
with self.assertRaisesRegex(ValueError, "snapshot artifact version"):
release.validate(self.directory, "snapshot", self.commit)
def test_matching_snapshot_passes(self):
version = "3.0.1-snapshot.903.1"
assets = {}
for name in self.metadata["assets"]:
file = self.directory / name
new_name = name.replace("3.0.1", version)
content = file.read_bytes()
if name.endswith(".sha256"):
content = content.replace(b"3.0.1", version.encode())
file.unlink()
(self.directory / new_name).write_bytes(content)
assets[new_name] = hashlib.sha256(content).hexdigest()
self.metadata.update(channel="snapshot", release_tag="snapshot",
artifact_version=version, assets=assets)
self.save()
self.assertEqual(release.validate(self.directory, "snapshot", self.commit), self.metadata)
if __name__ == "__main__":
unittest.main()
@@ -1,177 +0,0 @@
import importlib.util
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
MODULE_PATH = Path(__file__).parents[1] / "validate-update-manifest.py"
SPEC = importlib.util.spec_from_file_location("validate_update_manifest", MODULE_PATH)
MODULE = importlib.util.module_from_spec(SPEC)
assert SPEC.loader is not None
SPEC.loader.exec_module(MODULE)
REPOSITORY = "yuezk/GlobalProtect-openconnect"
class UpdateManifestTests(unittest.TestCase):
def stable(self, version="2.6.5"):
return {
"version": version,
"releasedAt": "2026-08-01",
"releaseUrl": f"https://github.com/{REPOSITORY}/releases/tag/v{version}",
"platforms": ["linux", "freebsd", "openbsd"],
"highlights": ["Stable release."],
}
def snapshot(self, base_version="2.6.5", build="17.1"):
return {
"baseVersion": base_version,
"build": build,
"releasedAt": "2026-08-07",
"releaseUrl": f"https://github.com/{REPOSITORY}/releases/tag/snapshot",
"platforms": ["linux", "freebsd", "openbsd"],
"highlights": ["Development snapshot."],
}
def manifest(self):
return {"schemaVersion": 1, "stable": self.stable(), "snapshot": self.snapshot()}
def generate(self, directory, channel, version, build=None, input_manifest=None):
directory = Path(directory)
highlights = directory / f"{channel}-highlights.txt"
output = directory / "latest.json"
highlights.write_text(f"{channel.title()} change.\n", encoding="utf-8")
args = type(
"Args",
(),
{
"repository": REPOSITORY,
"channel": channel,
"version": version,
"build": build,
"platform": None,
"released_at": "2026-08-07",
"highlights_file": highlights,
"input": input_manifest,
"output": output,
},
)()
MODULE.generate(args)
return json.loads(output.read_text(encoding="utf-8"))
def test_validates_catalog_with_both_channels(self):
result = MODULE.validate_manifest(self.manifest(), REPOSITORY)
self.assertEqual(result["stable"]["version"], "2.6.5")
self.assertEqual(result["snapshot"]["build"], "17.1")
def test_accepts_catalog_with_one_channel(self):
manifest = self.manifest()
manifest["stable"] = None
MODULE.validate_manifest(manifest, REPOSITORY)
def test_rejects_empty_catalog_and_unknown_fields(self):
with self.assertRaisesRegex(ValueError, "stable or snapshot"):
MODULE.validate_manifest({"schemaVersion": 1, "stable": None, "snapshot": None}, REPOSITORY)
manifest = self.manifest()
manifest["extra"] = True
with self.assertRaisesRegex(ValueError, "top-level"):
MODULE.validate_manifest(manifest, REPOSITORY)
def test_rejects_invalid_channel_urls(self):
manifest = self.manifest()
manifest["stable"]["releaseUrl"] = f"https://github.com/{REPOSITORY}/releases/tag/snapshot"
with self.assertRaisesRegex(ValueError, "stable releaseUrl"):
MODULE.validate_manifest(manifest, REPOSITORY)
manifest = self.manifest()
manifest["snapshot"]["releaseUrl"] = f"https://github.com/{REPOSITORY}/releases/tag/v2.6.5"
with self.assertRaisesRegex(ValueError, "snapshot releaseUrl"):
MODULE.validate_manifest(manifest, REPOSITORY)
def test_rejects_invalid_snapshot_build(self):
for build in ("", "17.beta", "01.1", "1.2.3.4", f"{2**64}.1"):
with self.subTest(build=build):
manifest = self.manifest()
manifest["snapshot"]["build"] = build
with self.assertRaisesRegex(ValueError, "snapshot build"):
MODULE.validate_manifest(manifest, REPOSITORY)
def test_rejects_version_components_larger_than_the_client_supports(self):
manifest = self.manifest()
manifest["stable"] = self.stable(f"{2**64}.0.0")
with self.assertRaisesRegex(ValueError, "integer range"):
MODULE.validate_manifest(manifest, REPOSITORY)
def test_rejects_unknown_and_duplicate_platforms(self):
manifest = self.manifest()
manifest["stable"]["platforms"] = ["linux", "netbsd"]
with self.assertRaisesRegex(ValueError, "unsupported"):
MODULE.validate_manifest(manifest, REPOSITORY)
manifest["stable"]["platforms"] = ["linux", "linux"]
with self.assertRaisesRegex(ValueError, "duplicates"):
MODULE.validate_manifest(manifest, REPOSITORY)
def test_generates_and_merges_channels(self):
with tempfile.TemporaryDirectory() as directory:
generated = self.generate(directory, "stable", "2.6.5")
self.assertIsNone(generated["snapshot"])
self.assertEqual(generated["stable"]["platforms"], ["linux", "freebsd", "openbsd"])
current = Path(directory) / "current.json"
current.write_text(json.dumps(generated), encoding="utf-8")
generated = self.generate(directory, "snapshot", "2.6.5", "17.1", current)
self.assertEqual(generated["stable"]["version"], "2.6.5")
self.assertEqual(generated["snapshot"]["baseVersion"], "2.6.5")
self.assertEqual(generated["snapshot"]["build"], "17.1")
def test_cli_limits_stable_to_published_platforms_and_preserves_snapshot(self):
with tempfile.TemporaryDirectory() as directory:
directory = Path(directory)
current = directory / "current.json"
current.write_text(json.dumps(self.manifest()), encoding="utf-8")
highlights = directory / "highlights.txt"
highlights.write_text("Refreshed client icons.\n", encoding="utf-8")
output = directory / "latest.json"
result = subprocess.run(
[sys.executable, str(MODULE_PATH), "generate", "--repository", REPOSITORY,
"--channel", "stable", "--version", "3.0.5", "--platform", "linux",
"--released-at", "2026-10-13", "--highlights-file", str(highlights),
"--input", str(current), "--output", str(output)],
capture_output=True, text=True,
)
self.assertEqual(result.returncode, 0, result.stderr)
generated = json.loads(output.read_text(encoding="utf-8"))
self.assertEqual(generated["stable"]["platforms"], ["linux"])
self.assertEqual(generated["snapshot"], self.snapshot())
def test_rejects_stable_and_snapshot_rollbacks(self):
with tempfile.TemporaryDirectory() as directory:
current = Path(directory) / "current.json"
current.write_text(json.dumps(self.manifest()), encoding="utf-8")
with self.assertRaisesRegex(ValueError, "stable version"):
self.generate(directory, "stable", "2.6.4", input_manifest=current)
with self.assertRaisesRegex(ValueError, "snapshot release"):
self.generate(directory, "snapshot", "2.6.5", "16.1", current)
def test_allows_new_stable_to_supersede_snapshot_base(self):
with tempfile.TemporaryDirectory() as directory:
current = Path(directory) / "current.json"
current.write_text(json.dumps(self.manifest()), encoding="utf-8")
generated = self.generate(directory, "stable", "2.6.6", input_manifest=current)
self.assertEqual(generated["stable"]["version"], "2.6.6")
self.assertEqual(generated["snapshot"]["baseVersion"], "2.6.5")
if __name__ == "__main__":
unittest.main()
-142
View File
@@ -1,142 +0,0 @@
#!/usr/bin/env python3
import argparse
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
SPARKLE_NAMESPACE = "http://www.andymatuschak.org/xml-namespaces/sparkle"
SUPPORTED_CHANNELS = {None, "snapshot"}
@dataclass(frozen=True)
class AppcastItem:
version: str
short_version: str
channel: Optional[str]
archive_url: str
signature: str
def parse_version(value: str) -> tuple[int, int, int]:
parts = value.split(".")
if not 1 <= len(parts) <= 3 or any(not part.isdigit() for part in parts):
raise ValueError(f"invalid build version: {value}")
numbers = tuple(map(int, parts))
return numbers + (0,) * (3 - len(numbers))
def parse_appcast(path: Path, repository: str) -> list[AppcastItem]:
try:
root = ET.parse(path)
except (ET.ParseError, OSError) as error:
raise ValueError(f"invalid appcast XML: {error}") from error
download_prefix = f"https://github.com/{repository}/releases/download/"
items = []
channel_counts: dict[Optional[str], int] = {}
versions = set()
for element in root.findall("./channel/item"):
version = element.findtext(f"{{{SPARKLE_NAMESPACE}}}version") or ""
short_version = element.findtext(f"{{{SPARKLE_NAMESPACE}}}shortVersionString") or ""
channel = element.findtext(f"{{{SPARKLE_NAMESPACE}}}channel")
enclosure = element.find("enclosure")
if not version or not short_version or enclosure is None:
raise ValueError("appcast item is missing required version or enclosure metadata")
parse_version(version)
if channel not in SUPPORTED_CHANNELS:
raise ValueError(f"unsupported Sparkle channel: {channel}")
archive_url = enclosure.get("url", "")
signature = enclosure.get(f"{{{SPARKLE_NAMESPACE}}}edSignature", "")
length = enclosure.get("length", "")
if not archive_url.startswith(download_prefix):
raise ValueError(f"unexpected update archive URL: {archive_url}")
if not signature:
raise ValueError(f"update archive {archive_url} has no EdDSA signature")
if not length.isdigit() or int(length) <= 0:
raise ValueError(f"update archive {archive_url} has an invalid length")
if version in versions:
raise ValueError(f"duplicate build version in appcast: {version}")
versions.add(version)
channel_counts[channel] = channel_counts.get(channel, 0) + 1
items.append(AppcastItem(version, short_version, channel, archive_url, signature))
if not items:
raise ValueError("appcast contains no update items")
for channel, count in channel_counts.items():
if count > 1:
name = channel or "stable"
raise ValueError(f"appcast contains more than one {name} update")
return items
def command_status(args: argparse.Namespace) -> None:
candidate = parse_version(args.build_version)
published = max(
parse_version(item.version)
for item in parse_appcast(args.appcast, args.repository)
)
if candidate < published:
print("older")
elif candidate == published:
print("same")
else:
print("newer")
def command_validate(args: argparse.Namespace) -> None:
expected_channel = None if args.channel == "stable" else args.channel
matches = [
item
for item in parse_appcast(args.appcast, args.repository)
if parse_version(item.version) == parse_version(args.build_version)
]
if len(matches) != 1:
raise ValueError(f"expected one appcast item for build {args.build_version}")
item = matches[0]
if item.version != args.build_version:
raise ValueError(f"appcast uses a non-canonical build version: {item.version}")
if item.short_version != args.short_version:
raise ValueError(f"unexpected short version: {item.short_version}")
if item.channel != expected_channel:
raise ValueError(f"unexpected Sparkle channel: {item.channel}")
if item.archive_url != args.archive_url:
raise ValueError(f"unexpected update archive URL: {item.archive_url}")
def parser() -> argparse.ArgumentParser:
root = argparse.ArgumentParser(description="Validate the GP Connect Sparkle appcast")
subcommands = root.add_subparsers(dest="command", required=True)
status = subcommands.add_parser("status", help="compare a candidate build with the published feed")
status.add_argument("appcast", type=Path)
status.add_argument("--repository", required=True)
status.add_argument("--build-version", required=True)
status.set_defaults(handler=command_status)
validate = subcommands.add_parser("validate", help="validate a specific update item and the complete feed")
validate.add_argument("appcast", type=Path)
validate.add_argument("--repository", required=True)
validate.add_argument("--build-version", required=True)
validate.add_argument("--short-version", required=True)
validate.add_argument("--channel", choices=("stable", "snapshot"), required=True)
validate.add_argument("--archive-url", required=True)
validate.set_defaults(handler=command_validate)
return root
def main() -> None:
args = parser().parse_args()
try:
args.handler(args)
except ValueError as error:
raise SystemExit(str(error)) from error
if __name__ == "__main__":
main()
-67
View File
@@ -1,67 +0,0 @@
#!/usr/bin/env python3
"""Validate the identity and checksums of a completed public macOS build."""
import argparse
import hashlib
import json
from pathlib import Path
import re
def validate(directory, release_tag, workflow_commit):
metadata = json.loads((directory / "release-build.json").read_text())
for name in ("gp_ref", "gpgui_ref", "workflow_sha"):
if not re.fullmatch(r"[0-9a-f]{40}", metadata[name]):
raise ValueError(f"Invalid {name}")
if metadata["workflow_sha"] != workflow_commit:
raise ValueError("Artifact identity does not match its public workflow run")
if metadata["release_tag"] != release_tag:
raise ValueError("Artifact release tag does not match the requested release")
if not re.fullmatch(r"[0-9]+\.[0-9]+", metadata["build_version"]):
raise ValueError("Invalid build version")
if not re.fullmatch(r"[0-9]+\.[0-9]+\.macos", metadata["request_id"]):
raise ValueError("Invalid build request ID")
version = metadata["artifact_version"]
if metadata["channel"] == "stable":
if not re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+", release_tag):
raise ValueError("Invalid stable tag")
if version != release_tag[1:]:
raise ValueError("Artifact version does not match the stable tag")
elif metadata["channel"] == "snapshot":
if release_tag != "snapshot" or not re.fullmatch(
r"[0-9]+\.[0-9]+\.[0-9]+-snapshot\." + re.escape(metadata["build_version"]), version
):
raise ValueError("Invalid snapshot artifact version")
else:
raise ValueError("Invalid channel")
expected = {f"GPConnect_{version}_arm64.{extension}" for extension in ("dmg", "zip")}
expected |= {name + ".sha256" for name in expected}
if set(metadata["assets"]) != expected:
raise ValueError("Build must contain exactly the DMG, ZIP, and their checksums")
if {file.name for file in directory.iterdir()} != expected | {"release-build.json"}:
raise ValueError("Unexpected or missing artifact files")
for name, digest in metadata["assets"].items():
file = directory / name
if file.is_symlink() or hashlib.sha256(file.read_bytes()).hexdigest() != digest:
raise ValueError(f"Artifact checksum mismatch: {name}")
for name in expected:
if name.endswith(".sha256"):
fields = (directory / name).read_text().split()
if fields != [metadata["assets"][name[:-7]], name[:-7]]:
raise ValueError(f"Invalid checksum file: {name}")
return metadata
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("directory", type=Path)
parser.add_argument("--release-tag", required=True)
parser.add_argument("--workflow-commit", required=True)
args = parser.parse_args()
try:
result = validate(args.directory, args.release_tag, args.workflow_commit)
except (ValueError, KeyError, OSError) as error:
parser.exit(1, f"{error}\n")
print(json.dumps(result))
-70
View File
@@ -1,70 +0,0 @@
#!/usr/bin/env python3
"""Check the release selected by a flake and, optionally, its installed tools."""
import argparse
import re
import subprocess
from pathlib import Path
def cargo_version(root, cargo=None):
if cargo is None:
cargo = (root / "Cargo.toml").read_text()
workspace = re.search(r"(?ms)^\[workspace\.package\]\s*\n(.*?)(?=^\[|\Z)", cargo)
if workspace is None:
raise ValueError("Cargo.toml has no workspace.package section")
return field(workspace[1], "version")
def field(text, name):
matches = re.findall(rf'^\s*{name}\s*=\s*"([^"]+)"\s*;?\s*$', text, re.M)
if len(matches) != 1:
raise ValueError(f"expected one {name} declaration")
return matches[0]
def validate(root, version=None, release_tag=None, package=None, base_ref=None):
expected = version or cargo_version(root)
if not re.fullmatch(r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)", expected):
raise ValueError("expected a stable X.Y.Z version")
tag = release_tag or f"v{expected}"
if tag not in (f"v{expected}", "snapshot"):
raise ValueError("release tag does not match the expected version")
flake = (root / "flake.nix").read_text()
if field(flake, "releaseVersion") != expected or field(flake, "releaseTag") != tag:
raise ValueError(f"flake must select {tag} at version {expected}")
if base_ref:
cargo = subprocess.check_output(["git", "-C", str(root), "show", f"{base_ref}:Cargo.toml"],
text=True, stderr=subprocess.DEVNULL)
base = cargo_version(root, cargo)
if tuple(map(int, expected.split("."))) < tuple(map(int, base.split("."))):
raise ValueError("candidate release is older than the main base")
if package:
for name in ("gpclient", "gpservice", "gpauth", "gpgui"):
result = subprocess.run([str(package / "bin" / name), "--version"],
capture_output=True, text=True, check=True)
# Keep private source identity and other command output out of logs.
match = re.match(rf"{name}\s+(\d+\.\d+\.\d+)(?:\s|$)", result.stdout)
if match is None or match[1] != expected:
raise ValueError(f"installed {name} does not report version {expected}")
return expected
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path("."))
parser.add_argument("--version", help="Explicit candidate version; defaults to Cargo.toml")
parser.add_argument("--release-tag", help="Explicit candidate tag; defaults to v<version>")
parser.add_argument("--package", type=Path)
parser.add_argument("--base-ref", help="Reject a release older than this main commit")
args = parser.parse_args()
try:
version = validate(args.root, args.version, args.release_tag, args.package, args.base_ref)
except (OSError, ValueError, subprocess.CalledProcessError) as error:
# CalledProcessError does not include captured stdout/stderr in its string.
parser.exit(1, f"Release version check failed: {error}\n")
print(f"Verified release version {version}")
if __name__ == "__main__":
main()
-219
View File
@@ -1,219 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import datetime
import json
import re
import unicodedata
from pathlib import Path
from urllib.parse import urlparse
ALLOWED_PLATFORMS = {"linux", "freebsd", "openbsd"}
SEMVER = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")
BUILD = re.compile(r"^(0|[1-9][0-9]*)(?:\.(0|[1-9][0-9]*)){0,2}$")
EXPECTED_TOP_LEVEL_KEYS = {"schemaVersion", "stable", "snapshot"}
EXPECTED_STABLE_KEYS = {"version", "releasedAt", "releaseUrl", "platforms", "highlights"}
EXPECTED_SNAPSHOT_KEYS = {"baseVersion", "build", "releasedAt", "releaseUrl", "platforms", "highlights"}
MAX_U64 = 2**64 - 1
def version_tuple(version: str) -> tuple[int, int, int]:
match = SEMVER.fullmatch(version)
if not match:
raise ValueError("version must be stable semantic versioning")
parts = tuple(int(part) for part in match.groups())
if any(part > MAX_U64 for part in parts):
raise ValueError("version component exceeds the supported integer range")
return parts
def build_tuple(build: str) -> tuple[int, int, int]:
if not BUILD.fullmatch(build):
raise ValueError("snapshot build must contain one to three numeric components")
parts = [int(part) for part in build.split(".")]
if any(part > MAX_U64 for part in parts):
raise ValueError("snapshot build component exceeds the supported integer range")
parts.extend([0] * (3 - len(parts)))
return parts[0], parts[1], parts[2]
def validate_release_fields(release: dict) -> None:
try:
datetime.date.fromisoformat(release["releasedAt"])
except (TypeError, ValueError) as error:
raise ValueError("releasedAt must be an ISO calendar date") from error
parsed_url = urlparse(release["releaseUrl"])
if parsed_url.scheme != "https" or parsed_url.hostname != "github.com":
raise ValueError("releaseUrl must use GitHub HTTPS")
platforms = release["platforms"]
if not isinstance(platforms, list) or not platforms:
raise ValueError("platforms must be a non-empty list")
if any(not isinstance(platform, str) or platform not in ALLOWED_PLATFORMS for platform in platforms):
raise ValueError("platforms contains an unsupported target")
if len(set(platforms)) != len(platforms):
raise ValueError("platforms contains duplicates")
highlights = release["highlights"]
if not isinstance(highlights, list) or not 1 <= len(highlights) <= 6:
raise ValueError("highlights must contain between one and six entries")
for highlight in highlights:
if not isinstance(highlight, str) or not highlight.strip():
raise ValueError("highlights must be non-empty strings")
if len(highlight) > 160:
raise ValueError("highlight exceeds 160 characters")
if any(unicodedata.category(character) == "Cc" for character in highlight):
raise ValueError("highlight contains control characters")
def validate_stable(release: object, repository: str) -> dict | None:
if release is None:
return None
if not isinstance(release, dict) or set(release) != EXPECTED_STABLE_KEYS:
raise ValueError("stable release has unexpected fields")
version = release["version"]
if not isinstance(version, str):
raise ValueError("stable version must be a string")
version_tuple(version)
expected_url = f"https://github.com/{repository}/releases/tag/v{version}"
if release["releaseUrl"] != expected_url:
raise ValueError(f"stable releaseUrl must be {expected_url}")
validate_release_fields(release)
return release
def validate_snapshot(release: object, repository: str) -> dict | None:
if release is None:
return None
if not isinstance(release, dict) or set(release) != EXPECTED_SNAPSHOT_KEYS:
raise ValueError("snapshot release has unexpected fields")
base_version = release["baseVersion"]
if not isinstance(base_version, str):
raise ValueError("snapshot baseVersion must be a string")
version_tuple(base_version)
build = release["build"]
if not isinstance(build, str):
raise ValueError("snapshot build must be a string")
build_tuple(build)
expected_url = f"https://github.com/{repository}/releases/tag/snapshot"
if release["releaseUrl"] != expected_url:
raise ValueError(f"snapshot releaseUrl must be {expected_url}")
validate_release_fields(release)
return release
def validate_manifest(data: object, repository: str) -> dict:
if not isinstance(data, dict) or set(data) != EXPECTED_TOP_LEVEL_KEYS:
raise ValueError("manifest has unexpected top-level fields")
if type(data["schemaVersion"]) is not int or data["schemaVersion"] != 1:
raise ValueError("unsupported schemaVersion")
stable = validate_stable(data["stable"], repository)
snapshot = validate_snapshot(data["snapshot"], repository)
if stable is None and snapshot is None:
raise ValueError("manifest must contain a stable or snapshot release")
return data
def load_highlights(path: Path) -> list[str]:
highlights = [line.strip() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
if not highlights:
raise ValueError("at least one release highlight is required")
return highlights
def generate(args: argparse.Namespace) -> None:
if args.input is None:
data = {"schemaVersion": 1, "stable": None, "snapshot": None}
else:
data = validate_manifest(json.loads(args.input.read_text(encoding="utf-8")), args.repository)
common = {
"releasedAt": args.released_at,
"platforms": args.platform if args.platform is not None else ["linux", "freebsd", "openbsd"],
"highlights": load_highlights(args.highlights_file),
}
if args.channel == "stable":
if args.build is not None:
raise ValueError("stable releases must not specify a snapshot build")
current = data["stable"]
if current is not None and version_tuple(args.version) < version_tuple(current["version"]):
raise ValueError(f"stable version {args.version} is older than {current['version']}")
data["stable"] = {
"version": args.version,
"releaseUrl": f"https://github.com/{args.repository}/releases/tag/v{args.version}",
**common,
}
else:
if args.build is None:
raise ValueError("snapshot releases require a build")
candidate = (version_tuple(args.version), build_tuple(args.build))
current = data["snapshot"]
if current is not None:
published = (version_tuple(current["baseVersion"]), build_tuple(current["build"]))
if candidate < published:
raise ValueError("snapshot release is older than the published snapshot")
data["snapshot"] = {
"baseVersion": args.version,
"build": args.build,
"releaseUrl": f"https://github.com/{args.repository}/releases/tag/snapshot",
**common,
}
validate_manifest(data, args.repository)
args.output.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
def validate(args: argparse.Namespace) -> None:
data = validate_manifest(json.loads(args.manifest.read_text(encoding="utf-8")), args.repository)
if args.channel is None:
return
release = data[args.channel]
if release is None:
raise ValueError(f"manifest does not contain a {args.channel} release")
version_key = "version" if args.channel == "stable" else "baseVersion"
if args.version is not None and release[version_key] != args.version:
raise ValueError(f"{args.channel} version {release[version_key]} does not match {args.version}")
if args.build is not None:
if args.channel != "snapshot":
raise ValueError("only snapshot releases have a build")
if release["build"] != args.build:
raise ValueError(f"snapshot build {release['build']} does not match {args.build}")
def main() -> None:
parser = argparse.ArgumentParser(description="Generate and validate the GP Connect update catalog")
subcommands = parser.add_subparsers(required=True)
generate_parser = subcommands.add_parser("generate")
generate_parser.add_argument("--repository", required=True)
generate_parser.add_argument("--channel", choices=("stable", "snapshot"), required=True)
generate_parser.add_argument("--version", required=True)
generate_parser.add_argument("--platform", action="append", choices=sorted(ALLOWED_PLATFORMS),
help="Published Unix target; repeat for multiple targets (default: all)")
generate_parser.add_argument("--build")
generate_parser.add_argument("--released-at", required=True)
generate_parser.add_argument("--highlights-file", required=True, type=Path)
generate_parser.add_argument("--input", type=Path)
generate_parser.add_argument("--output", required=True, type=Path)
generate_parser.set_defaults(handler=generate)
validate_parser = subcommands.add_parser("validate")
validate_parser.add_argument("manifest", type=Path)
validate_parser.add_argument("--repository", required=True)
validate_parser.add_argument("--channel", choices=("stable", "snapshot"))
validate_parser.add_argument("--version")
validate_parser.add_argument("--build")
validate_parser.set_defaults(handler=validate)
args = parser.parse_args()
try:
args.handler(args)
except (OSError, ValueError, json.JSONDecodeError) as error:
parser.error(str(error))
if __name__ == "__main__":
main()