Compare commits

..
15 Commits
Author SHA1 Message Date
Kevin Yue 18ed6bac1a feat: prepare 3.0.5 with refreshed icons and dependency updates 2026-10-13 16:34:10 +08:00
github-actions[bot] 10139e0f2c chore: update flake hashes for v3.0.4 (#675)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-13 00:45:05 +08:00
Kevin Yue ff1ea259d9 feat: release 3.0.4 with background connections and service startup improvements 2026-10-12 23:53:21 +08:00
Kevin Yue 57322e3cf3 fix: skip macOS waiter without a successful dispatch 2026-10-12 15:03:34 +08:00
github-actions[bot] 9532374805 chore: update flake hashes for v3.0.3 (#673)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-12 14:42:20 +08:00
Kevin Yue 90faa58811 chore: prepare 3.0.3 release 2026-10-12 13:44:27 +08:00
Kevin Yue 93504eaec2 fix: improve authentication recovery and diagnostics
Recognize real GTK Wayland crash messages and keep remote
authentication prompts readable. Preserve device identifiers
without initializing OpenSSL, validate diagnostic executable
paths, and improve release automation.

Fixes #669
2026-10-12 13:37:15 +08:00
Ihar Hrachyshka d73b712dd3 chore: add make install-gpclient target (#672)
This is useful in build environments where gpclient is a separate
artifact from other binaries (this is the case in nixpkgs).
2026-10-12 10:53:37 +08:00
Finley Holt be111a671a fix(cli): let gpauth read the pasted callback with --browser remote (#671) 2026-10-12 10:36:38 +08:00
Ihar HrachyshkaandKevin Yue f9965f8a35 macOS: make openconnect relocatable; drive installation through make install (#668)
Co-authored-by: Kevin Yue <[email protected]>
2026-10-12 10:12:17 +08:00
Kevin Yue f7649898fd fix(ci): honor build-only for manually dispatched tag refs 2026-10-12 01:14:30 +08:00
github-actions[bot] e6910060df chore: update flake hashes for v3.0.2 (#667)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-12 01:07:34 +08:00
Kevin Yue f41a429a5e Merge release 3.0.2 2026-10-12 00:28:04 +08:00
Kevin Yue 888f288c0d Release 3.0.2 2026-10-12 00:26:32 +08:00
github-actions[bot] f0292a9292 chore: update flake hashes for v3.0.1 (#665)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-11 00:44:28 +08:00
104 changed files with 6178 additions and 1289 deletions

No files matched your search

-30
View File
@@ -1,30 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Logs**
- For the GUI version, you can find the logs at `~/.local/share/gpclient/gpclient.log`
- For the CLI version, copy the output of the `gpclient` command.
**Environment:**
- OS: [e.g. Ubuntu 22.04]
- Desktop Environment: [e.g. GNOME or KDE]
- Output of `ps aux | grep 'gnome-keyring\|kwalletd5' | grep -v grep`: [Required for secure store error]
- Is remote SSH? [Yes/No]
**Additional context**
Add any other context about the problem here.
+115
View File
@@ -0,0 +1,115 @@
name: Bug report
description: Report a problem with GP Connect or gpclient.
body:
- type: markdown
attributes:
value: |
Thank you for reporting a problem. You can report against your installed version; you do not need to upgrade first.
Review everything before posting. Remove passwords, cookies, tokens, SAML payloads, and private VPN addresses. Do not attach a complete environment dump.
- type: dropdown
id: component
attributes:
label: Affected component
options:
- CLI connection
- GP Connect GUI
- Login window or browser authentication
- Installation or update
- Credential storage
- Other or unsure
validations:
required: true
- type: input
id: version
attributes:
label: Application version
description: Run gpclient --version, or use the version shown in the GUI's About dialog. Include helper versions if relevant.
placeholder: "For example: gpclient 3.0.1"
validations:
required: true
- type: dropdown
id: installation
attributes:
label: Installation method
options:
- APT
- AUR
- RPM package or repository
- Nix
- Homebrew
- Downloaded release package
- FreeBSD or OpenBSD package
- Source build
- Other or unknown
validations:
required: true
- type: input
id: os
attributes:
label: Operating system and version
description: Include the Linux distribution, macOS version, or FreeBSD/OpenBSD version, and architecture if known.
placeholder: "For example: Fedora 43 x86_64, macOS 26 arm64, or FreeBSD 14.4 amd64"
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Steps to reproduce
description: Include the exact command and options, or the GUI steps. Replace private portal names with a placeholder and omit credentials.
placeholder: |
1. Run sudo gpclient connect <portal> --browser
2. ...
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual behavior
description: Describe the failure and any error message.
validations:
required: true
- type: textarea
id: regression
attributes:
label: Last working version and recent changes
description: If this worked before, give the last working app version and any recent OS, desktop, graphics driver, or package updates. It is okay if you do not know.
- type: textarea
id: diagnostics
attributes:
label: Diagnostics
description: Run gpclient diagnostics as your normal desktop user, without sudo. If the command is unavailable, use the standalone script linked below or provide the relevant information manually. Reports include raw desktop identifiers and are not guaranteed anonymous; review before posting.
render: text
- type: markdown
attributes:
value: |
**Older versions:** download and inspect the [standalone diagnostic script](https://github.com/yuezk/GlobalProtect-openconnect/blob/dev/scripts/collect-diagnostics.sh), then run it with `sh collect-diagnostics.sh`. See [collection instructions](https://github.com/yuezk/GlobalProtect-openconnect/blob/dev/docs/diagnostics.md). Do not pipe a download directly into a shell.
If you cannot run either collector, provide the relevant details below. You do not need graphics details for unrelated connection problems.
- type: textarea
id: rendering
attributes:
label: Window or rendering failures only
description: Desktop/compositor and version; Wayland or X11; GPU and driver version; GTK/WebKitGTK version when available; VM or remote session; any rendering environment overrides. Skip for unrelated problems. The diagnostics report may already contain this information.
- type: textarea
id: authentication
attributes:
label: Authentication or credential storage failures only
description: Embedded login window or external browser (name/version)? At what stage does it stop? For credential storage errors, include the keyring implementation or macOS Keychain error. Omit cookies, tokens, passwords, and SAML data.
- type: textarea
id: logs
attributes:
label: Relevant logs
description: For the CLI, paste relevant terminal output. For the GUI, use its built-in option to open or export logs, if available. Review and remove sensitive authentication data before posting; avoid full verbose logs unless requested.
render: text
- type: textarea
id: screenshots
attributes:
label: Screenshots and additional context
description: Attach screenshots if helpful. Hide private portal names, account details, and other sensitive content.
+98
View File
@@ -0,0 +1,98 @@
name: Build Linux GUI
on:
workflow_call:
inputs:
gp_ref:
required: true
type: string
gpgui_ref:
required: true
type: string
channel:
required: true
type: string
builder:
required: true
type: string
artifact_suffix:
default: ""
type: string
verify_desktop_assets:
default: false
type: boolean
secrets:
GH_PAT:
required: true
jobs:
build:
strategy:
fail-fast: false
matrix:
os:
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
runs-on: ${{ matrix.os.runner }}
name: build (${{ matrix.os.arch }})
steps:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Prepare workspace
run: rm -rf gpgui-source && mkdir gpgui-source
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ inputs.gp_ref }}
path: gpgui-source/gp
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
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: gpgui-source/gp/scripts/verify-linux-desktop-assets.sh gpgui-source/gpgui
- name: Tarball
run: |
cd gpgui-source
tar -czf gpgui.tar.gz gpgui gp
- name: Build gpgui in Docker
env:
GPGUI_BUILDER: ${{ inputs.builder }}
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
run: |
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: |
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:
name: artifact-gpgui${{ inputs.artifact_suffix }}-${{ matrix.os.arch }}
if-no-files-found: error
path: |
gpgui-source/*.bin.tar.xz
gpgui-source/*.bin.tar.xz.sha256
+115 -130
View File
@@ -2,31 +2,37 @@ name: Build
on:
workflow_dispatch:
inputs:
channel:
description: 'Build channel. Stable builds require matching vX.Y.Z refs in both repositories.'
required: true
default: snapshot
type: choice
options: [snapshot, stable]
build_only:
description: 'Build and test artifacts without publishing releases, images, or update feeds'
required: true
default: false
type: boolean
gp_branch:
description: 'GlobalProtect-openconnect branch to use for the snapshot release'
description: 'GlobalProtect-openconnect ref to build (use the matching tag for stable builds)'
required: true
default: dev
gpgui_branch:
description: 'gpgui branch to use for the snapshot release'
description: 'gpgui ref to build (use the matching tag for stable builds)'
required: true
default: dev
build_macos:
description: 'Build Apple Silicon artifacts for the snapshot release'
description: 'Build Apple Silicon artifacts for this run'
required: true
default: false
type: boolean
build_bsd:
description: 'Build FreeBSD/OpenBSD packages for the snapshot release'
description: 'Build FreeBSD/OpenBSD packages for this run'
required: true
default: false
type: boolean
build_bsd_arm64:
description: 'Build optional FreeBSD/OpenBSD arm64 packages for the snapshot release. Slow and disabled by default'
description: 'Build optional FreeBSD/OpenBSD arm64 packages for this run. Slow and disabled by default'
required: true
default: false
type: boolean
@@ -49,7 +55,25 @@ concurrency:
cancel-in-progress: ${{ github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/') }}
jobs:
validate-inputs:
runs-on: ubuntu-latest
steps:
- name: Validate stable refs
env:
EVENT: ${{ github.event_name }}
CHANNEL: ${{ inputs.channel }}
GP_REF: ${{ inputs.gp_branch }}
GPGUI_REF: ${{ inputs.gpgui_branch }}
run: |
if [[ "$EVENT" == workflow_dispatch && "$CHANNEL" == stable ]]; then
if [[ ! "$GP_REF" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || "$GP_REF" != "$GPGUI_REF" ]]; then
echo "Stable builds require matching vX.Y.Z refs" >&2
exit 1
fi
fi
test-gp:
needs: validate-inputs
runs-on: ubuntu-latest
steps:
- name: Checkout GlobalProtect-openconnect
@@ -59,19 +83,35 @@ jobs:
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
submodules: recursive
- name: Run Rust tests in Docker
- name: Run Rust tests as a non-root user with focused privilege checks
run: |
docker run --rm \
--user root \
--user vscode \
-e HOME=/home/vscode \
-e CARGO_TARGET_DIR=/tmp/gp-test-target \
-e COREPACK_INTEGRITY_KEYS=0 \
-e LIBXML2_STATIC=1 \
-e PKEXEC_UID=1000 \
-v "$(pwd):/workspace" \
-v "$(pwd):/workspace:ro" \
-w /workspace \
yuezk/gpdev:binary-builder-tauri2 \
cargo test --workspace
sh -ec '
test "$(id -u)" -ne 0
# Tauri generates schemas in the source tree. Keep the host checkout read-only.
cp -R /workspace /tmp/gp-test-workspace
cd /tmp/gp-test-workspace
cargo test --workspace --locked
# Exercise only the paths that require an actual root process.
sudo -E env PATH="$PATH" PKEXEC_UID="$(id -u)" cargo test --locked -p gpapi \
process::auth_launcher::tests::custom_authenticator_crash_does_not_request_recovery -- --exact
sudo -E env PATH="$PATH" PKEXEC_UID="$(id -u)" cargo test --locked -p gpapi \
process::collection::tests::root_owned_sticky_directories_protect_collectors_without_trusting_writable_files -- --exact
sudo -E env PATH="$PATH" PKEXEC_UID="$(id -u)" cargo test --locked -p gpservice \
--bin gpservice device_anchor::tests
'
tarball:
needs: validate-inputs
runs-on: ubuntu-latest
steps:
- uses: pnpm/action-setup@v5
@@ -90,10 +130,12 @@ jobs:
submodules: recursive
- name: Create tarball
env:
IS_SNAPSHOT: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel == 'snapshot') || (github.event_name != 'workflow_dispatch' && !startsWith(github.ref, 'refs/tags/')) }}
run: |
cd source/gp
# Generate the SNAPSHOT file for non-tagged commits
if [[ "${{ github.ref }}" != "refs/tags/"* ]]; then
# Stable manual builds use tagged source even when dispatched from main.
if [[ "$IS_SNAPSHOT" == true ]]; then
touch SNAPSHOT
fi
make tarball
@@ -102,7 +144,7 @@ jobs:
- name: Generate RPM spec file
env:
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
run: |
cd source/gp
@@ -162,7 +204,7 @@ jobs:
if-no-files-found: error
build-gp:
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
if: ${{ !(startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
needs:
- tarball
strategy:
@@ -213,7 +255,7 @@ jobs:
build-gp-${{ matrix.package }}/artifacts/*
build-docker-image:
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
if: ${{ !(startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
strategy:
fail-fast: false
matrix:
@@ -290,81 +332,34 @@ jobs:
if-no-files-found: error
retention-days: 1
build-gpgui:
strategy:
fail-fast: false
matrix:
os:
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
libc:
- name: glibc
builder: gpgui-builder-tauri2
artifact_suffix: ""
- name: musl
builder: gpgui-alpine-builder-tauri2
artifact_suffix: "-musl"
runs-on: ${{ matrix.os.runner }}
name: build-gpgui (${{ matrix.libc.name }}, ${{ matrix.os.arch }})
steps:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Prepare workspace
run: rm -rf gpgui-source && mkdir gpgui-source
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: gpgui-source/gp
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: gpgui-source/gpgui
- name: Verify Linux desktop assets
if: matrix.os.arch == 'amd64' && matrix.libc.name == 'glibc'
run: gpgui-source/gp/scripts/verify-linux-desktop-assets.sh gpgui-source/gpgui
- name: Tarball
run: |
cd gpgui-source
tar -czf gpgui.tar.gz gpgui gp
- name: Build gpgui in Docker
env:
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
run: |
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-e GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }} \
-e GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }} \
-e GPGUI_LICENSE_SIGNING_KEYS \
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:${{ matrix.libc.builder }}
- name: Install gpgui in Docker
run: |
cd gpgui-source
tar -xJf *.bin.tar.xz
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd):/workspace yuezk/gpdev:${{ matrix.libc.builder }} \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui
uses: actions/upload-artifact@v7
with:
name: artifact-gpgui${{ matrix.libc.artifact_suffix }}-${{ matrix.os.arch }}
if-no-files-found: error
path: |
gpgui-source/*.bin.tar.xz
gpgui-source/*.bin.tar.xz.sha256
build-gpgui-glibc:
needs: validate-inputs
name: build-gpgui (glibc)
uses: ./.github/workflows/build-gpgui-linux.yaml
with:
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
secrets:
GH_PAT: ${{ secrets.GH_PAT }}
build-gpgui-musl:
needs: validate-inputs
name: build-gpgui (musl)
uses: ./.github/workflows/build-gpgui-linux.yaml
with:
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
secrets:
GH_PAT: ${{ secrets.GH_PAT }}
nix-source:
needs: [build-gpgui]
needs: [build-gpgui-glibc]
strategy:
fail-fast: false
matrix:
@@ -413,7 +408,7 @@ jobs:
--extra-experimental-features "nix-command flakes" --print-build-logs
nix-prebuilt:
needs: [build-gp, build-gpgui]
needs: [build-gp, build-gpgui-glibc]
strategy:
fail-fast: false
matrix:
@@ -477,27 +472,26 @@ jobs:
trigger-gpgui-macos:
needs: test-gp
if: ${{ startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.build_macos) }}
if: ${{ (github.event_name == 'workflow_dispatch' && inputs.build_macos) || (startsWith(github.ref, 'refs/tags/') && vars.BUILD_MACOS_ON_TAG == 'true') }}
permissions:
contents: read
runs-on: ubuntu-latest
name: trigger private macOS release
name: trigger private macOS build
outputs:
run_id: ${{ steps.dispatch.outputs.run_id }}
run_url: ${{ steps.dispatch.outputs.run_url }}
steps:
- name: Dispatch private macOS release
- 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' && 'snapshot' || 'stable' }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
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 }}
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
BUILD_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
run: |
set -euo pipefail
@@ -516,7 +510,7 @@ jobs:
exit 1
fi
expected_title="macOS $CHANNEL $RELEASE_TAG ($REQUEST_ID)"
expected_title="macOS build $CHANNEL $RELEASE_TAG ($REQUEST_ID)"
jq -n \
--arg workflow_ref "$GPGUI_REF" \
--arg request_id "$REQUEST_ID" \
@@ -525,7 +519,6 @@ jobs:
--arg release_tag "$RELEASE_TAG" \
--arg gp_ref "$gp_sha" \
--arg gpgui_ref "$gpgui_sha" \
--argjson build_only "$BUILD_ONLY" \
'{
ref: $workflow_ref,
inputs: {
@@ -534,18 +527,17 @@ jobs:
channel: $channel,
release_tag: $release_tag,
gp_ref: $gp_ref,
gpgui_ref: $gpgui_ref,
build_only: $build_only
gpgui_ref: $gpgui_ref
}
}' | gh api --method POST \
repos/yuezk/gpgui/actions/workflows/release-macos.yaml/dispatches \
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/release-macos.yaml/runs?event=workflow_dispatch&per_page=50')"
'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")"
@@ -567,6 +559,7 @@ jobs:
exit 1
setup-bsd-matrix:
needs: validate-inputs
runs-on: ubuntu-latest
outputs:
enabled: ${{ steps.matrix.outputs.enabled }}
@@ -575,7 +568,7 @@ jobs:
- name: Build matrix
id: matrix
env:
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
BUILD_BSD_ON_TAG: ${{ startsWith(github.ref, 'refs/tags/') && vars.BUILD_BSD_ON_TAG == 'true' }}
BUILD_BSD: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd }}
BUILD_BSD_ARM64: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd_arm64 }}
run: |
@@ -583,7 +576,7 @@ jobs:
import json
import os
build_bsd = os.environ["IS_TAG"] == "true" or os.environ["BUILD_BSD"] == "true"
build_bsd = os.environ["BUILD_BSD_ON_TAG"] == "true" or os.environ["BUILD_BSD"] == "true"
build_bsd_arm64 = os.environ["BUILD_BSD_ARM64"] == "true"
include = []
@@ -710,7 +703,7 @@ jobs:
run: |
set -eu
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
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"
@@ -767,7 +760,7 @@ jobs:
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' && 'snapshot' || 'stable' }}
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"
@@ -793,7 +786,7 @@ jobs:
${{ matrix.workspace }}/gp/.build/${{ matrix.artifact_dir }}/artifacts/*
gh-release:
if: ${{ always() && ((github.event_name == 'workflow_dispatch' && !inputs.build_only) || startsWith(github.ref, 'refs/tags/')) }}
if: ${{ always() && ((github.event_name == 'workflow_dispatch' && !inputs.build_only) || (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))) }}
runs-on: ubuntu-latest
permissions:
actions: read
@@ -809,7 +802,8 @@ jobs:
- tarball-offline
- build-gp
- build-docker-image
- build-gpgui
- build-gpgui-glibc
- build-gpgui-musl
- setup-bsd-matrix
- build-gpgui-frontend
- build-bsd
@@ -819,7 +813,7 @@ jobs:
env:
NEEDS_JSON: ${{ toJson(needs) }}
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
IS_STABLE: ${{ (startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
run: |
python3 - <<'PY'
import json
@@ -828,14 +822,14 @@ jobs:
needs = json.loads(os.environ["NEEDS_JSON"])
bsd_matrix_enabled = os.environ["BSD_MATRIX_ENABLED"] == "true"
is_tag = os.environ["IS_TAG"] == "true"
is_stable = os.environ["IS_STABLE"] == "true"
failed = []
for name, data in needs.items():
result = data["result"]
if result in {"failure", "cancelled"}:
failed.append(f"{name}: {result}")
elif name in {"build-gp", "build-docker-image", "nix-prebuilt"} and result == "skipped" and is_tag:
elif name in {"build-gp", "build-docker-image", "nix-prebuilt"} and result == "skipped" and is_stable:
continue
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
continue
@@ -879,7 +873,7 @@ jobs:
- name: Generate release asset checksums
env:
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
run: |
cd gh-release/gp
mkdir -p .build
@@ -901,23 +895,20 @@ jobs:
- name: Create GH release
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
run: |
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
wait-gpgui-macos:
if: ${{ always() && needs.trigger-gpgui-macos.result != 'skipped' }}
if: ${{ !cancelled() && needs.trigger-gpgui-macos.result == 'success' }}
needs:
- gh-release
- trigger-gpgui-macos
runs-on: ubuntu-latest
timeout-minutes: 130
steps:
- name: Wait for private macOS release
- name: Wait for private macOS build
env:
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
PUBLIC_RELEASE_RESULT: ${{ needs.gh-release.result }}
BUILD_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
PRIVATE_RUN_ID: ${{ needs.trigger-gpgui-macos.outputs.run_id }}
PRIVATE_RUN_URL: ${{ needs.trigger-gpgui-macos.outputs.run_url }}
run: |
@@ -927,21 +918,14 @@ jobs:
echo "The private macOS workflow was not started" >&2
exit 1
fi
if [[ "$BUILD_ONLY" != "true" && "$PUBLIC_RELEASE_RESULT" != "success" ]]; then
gh api --method POST \
"repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID/cancel" >/dev/null || true
echo "The public release failed; cancelled $PRIVATE_RUN_URL" >&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 workflow completed: $PRIVATE_RUN_URL"
echo "Private macOS build completed: $PRIVATE_RUN_URL"
if [[ "$conclusion" != "success" ]]; then
echo "Private macOS workflow concluded with: $conclusion" >&2
echo "Private macOS build concluded with: $conclusion" >&2
exit 1
fi
exit 0
@@ -951,16 +935,17 @@ jobs:
gh api --method POST \
"repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID/cancel" >/dev/null || true
echo "Private macOS workflow timed out: $PRIVATE_RUN_URL" >&2
echo "Private macOS build timed out: $PRIVATE_RUN_URL" >&2
exit 1
publish-docker-image:
needs:
- test-gp
- build-docker-image
if: ${{ (github.event_name == 'workflow_dispatch' && !inputs.build_only) || startsWith(github.ref, 'refs/tags/') }}
if: ${{ (github.event_name == 'workflow_dispatch' && !inputs.build_only) || (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')) }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Download digests
uses: actions/download-artifact@v8
with:
@@ -978,9 +963,9 @@ jobs:
working-directory: /tmp/digests
env:
IMAGE: yuezk/globalprotect-openconnect
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
run: |
docker buildx imagetools create -t "$IMAGE:$RELEASE_TAG" \
$(printf "$IMAGE@sha256:%s " *)
docker buildx imagetools inspect "$IMAGE:$RELEASE_TAG"
"$GITHUB_WORKSPACE/scripts/verify-docker-publication.sh" "$IMAGE:$RELEASE_TAG" /tmp/digests all
+70 -7
View File
@@ -11,6 +11,18 @@ on:
type: string
required: true
default: "1"
build_id:
description: 'Existing Copr build ID to verify; leave empty to submit a new build'
type: string
required: false
distros:
description: 'Space-separated distro releases, e.g. fedora-44 fedora-45; all configured architectures are included'
type: string
required: false
concurrency:
group: publish-copr
cancel-in-progress: false
permissions:
contents: read
@@ -19,9 +31,14 @@ jobs:
publish-copr:
runs-on: ubuntu-latest
container: fedora:latest
timeout-minutes: 210
defaults:
run:
shell: bash
steps:
- name: Install tools
run: dnf install -y copr-cli gh
run: dnf install -y copr-cli gh python3 zstd
- uses: actions/checkout@v6
- name: Check inputs
env:
@@ -29,14 +46,28 @@ jobs:
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
run: |
if [[ ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
echo "Revision must be a positive integer" >&2
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
exit 1
fi
gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null
- name: Resolve publication distros
id: targets
env:
DISTROS: ${{ inputs.distros }}
BUILD_ID: ${{ inputs.build_id }}
run: |
build_args=()
if [[ -n "$BUILD_ID" ]]; then
build_args+=(--build-id "$BUILD_ID")
fi
python3 scripts/select-publication-targets.py copr \
--distros "$DISTROS" "${build_args[@]}"
- name: Download published spec
if: ${{ inputs.build_id == '' }}
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
@@ -49,6 +80,7 @@ jobs:
--dir publish-copr
- name: Set package revision
if: ${{ inputs.build_id == '' }}
env:
REVISION: ${{ inputs.revision }}
run: |
@@ -66,6 +98,7 @@ jobs:
grep '^Release:' "$spec"
- name: Configure COPR authentication
if: ${{ inputs.build_id == '' }}
env:
COPR_CONFIG: ${{ secrets.COPR_CONFIG }}
run: |
@@ -73,8 +106,38 @@ jobs:
printf '%s\n' "$COPR_CONFIG" > "$HOME/.config/copr"
chmod 600 "$HOME/.config/copr"
- name: Build and publish COPR package
- name: Submit or select Copr build
id: build
env:
EXISTING_BUILD_ID: ${{ inputs.build_id }}
CHROOTS: ${{ steps.targets.outputs.targets }}
run: |
copr-cli build \
yuezk/globalprotect-openconnect \
publish-copr/globalprotect-openconnect.spec
set -euo pipefail
build_id="$EXISTING_BUILD_ID"
if [[ -z "$build_id" ]]; then
read -r -a chroots <<< "$CHROOTS"
chroot_args=()
for chroot in "${chroots[@]}"; do
chroot_args+=(--chroot "$chroot")
done
copr-cli build --nowait yuezk/globalprotect-openconnect \
"${chroot_args[@]}" \
publish-copr/globalprotect-openconnect.spec | tee copr-submission.log
build_id="$(sed -n 's/^Created builds: \([0-9][0-9]*\)$/\1/p' copr-submission.log)"
fi
[[ "$build_id" =~ ^[0-9]+$ ]]
echo "id=$build_id" >> "$GITHUB_OUTPUT"
echo "Copr build: https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/build/$build_id/" \
>> "$GITHUB_STEP_SUMMARY"
- name: Wait for Copr builds and public repositories
env:
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
BUILD_ID: ${{ steps.build.outputs.id }}
CHROOTS: ${{ steps.targets.outputs.targets }}
run: |
read -r -a chroots <<< "$CHROOTS"
python3 scripts/wait-for-publication.py copr \
--chroots "${chroots[@]}" \
--build-id "$BUILD_ID" --version "${TAG#v}" --revision "$REVISION"
+42 -2
View File
@@ -11,6 +11,18 @@ on:
type: string
required: true
default: "1"
verify_only:
description: 'Verify the existing source and publication without uploading again'
type: boolean
default: false
repositories:
description: 'Space-separated distro repositories, e.g. 16.0 openSUSE_Tumbleweed; empty keeps enabled targets'
type: string
required: false
concurrency:
group: publish-obs
cancel-in-progress: false
permissions:
contents: read
@@ -18,15 +30,19 @@ permissions:
jobs:
publish-obs:
runs-on: ubuntu-latest
timeout-minutes: 210
steps:
- uses: actions/checkout@v6
- name: Install metadata decompressor
run: sudo apt-get update && sudo apt-get install -y zstd
- name: Check inputs
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
run: |
if [[ ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
echo "Revision must be a positive integer" >&2
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
exit 1
fi
@@ -61,7 +77,22 @@ jobs:
"$source_dir/.build/rpm/globalprotect-openconnect.changes" \
publish-obs/files/
- name: Select OBS publication targets
env:
REPOSITORIES: ${{ inputs.repositories }}
VERIFY_ONLY: ${{ inputs.verify_only }}
OBS_USERNAME: yuezk
OBS_PASSWORD: ${{ secrets.OBS_PASSWORD }}
run: |
verify_args=()
if [[ "$VERIFY_ONLY" == 'true' ]]; then
verify_args+=(--verify-only)
fi
python3 scripts/select-publication-targets.py obs \
--repositories "$REPOSITORIES" "${verify_args[@]}" --output publish-obs/targets.json
- name: Publish OBS package
if: ${{ !inputs.verify_only }}
uses: yuezk/publish-obs-package@main
with:
project: home:yuezk
@@ -70,3 +101,12 @@ jobs:
password: ${{ secrets.OBS_PASSWORD }}
files: ./publish-obs/files/*
commit_message: 'Release ${{ inputs.tag }}-${{ inputs.revision }}'
- name: Wait for OBS builds and public repositories
env:
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
run: |
python3 scripts/wait-for-publication.py obs \
--targets-file publish-obs/targets.json \
--version "${TAG#v}" --revision "$REVISION" --files publish-obs/files
+49 -4
View File
@@ -20,6 +20,18 @@ on:
type: "string"
required: true
default: "1.91"
verify_only:
description: 'Verify an existing upload without building or uploading source again'
type: boolean
default: false
concurrency:
group: publish-ppa
cancel-in-progress: false
defaults:
run:
shell: bash
jobs:
check:
runs-on: ubuntu-latest
@@ -28,7 +40,12 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
run: |
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
exit 1
fi
if ! gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null 2>&1; then
echo "Tag $TAG does not exist"
exit 1
@@ -67,8 +84,14 @@ jobs:
exit 1
fi
declare -A seen=()
for item in "${series[@]}"; do
ubuntu-distro-info --series "$item" >/dev/null
if [[ -n "${seen[$item]+present}" ]]; then
echo "Duplicate Ubuntu series: $item" >&2
exit 1
fi
seen[$item]=1
done
matrix="$(printf '%s\n' "${series[@]}" | jq -R . | jq -s -c '{series: .}')"
@@ -79,6 +102,7 @@ jobs:
needs: [check, resolve-series]
name: publish-ppa (${{ matrix.series }})
runs-on: ubuntu-latest
timeout-minutes: 210
container:
image: ubuntu:${{ matrix.series }}
strategy:
@@ -88,7 +112,7 @@ jobs:
- name: Install container tools
run: |
apt-get update
apt-get install -y ca-certificates curl gpg sudo
apt-get install -y ca-certificates curl gpg sudo python3 distro-info distro-info-data
mkdir -p /etc/apt/keyrings
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
| gpg --dearmor -o /etc/apt/keyrings/githubcli-archive-keyring.gpg
@@ -97,9 +121,12 @@ jobs:
> /etc/apt/sources.list.d/github-cli.list
apt-get update
apt-get install -y gh
- uses: actions/checkout@v6
- name: Prepare workspace
if: ${{ !inputs.verify_only }}
run: rm -rf publish-ppa && mkdir publish-ppa
- name: Download ${{ inputs.tag }} offline source code
if: ${{ !inputs.verify_only }}
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
@@ -108,17 +135,23 @@ jobs:
--pattern '*.offline.tar.gz' \
--dir publish-ppa
- name: Patch the source code
if: ${{ !inputs.verify_only }}
run: |
cd publish-ppa
# Rename the source tarball without the offline suffix
mv -v *.tar.gz $(basename *.tar.gz .offline.tar.gz).tar.gz
archives=(./*.offline.tar.gz)
[[ "${#archives[@]}" -eq 1 && -f "${archives[0]}" ]]
archive="${archives[0]%.offline.tar.gz}.tar.gz"
mv -v -- "${archives[0]}" "$archive"
# Extract the source tarball
tar -xzf *.tar.gz
tar -xzf "$archive"
# Prepare the debian directory with custom files
cd globalprotect-openconnect-*/
source_dirs=(./globalprotect-openconnect-*/)
[[ "${#source_dirs[@]}" -eq 1 && -d "${source_dirs[0]}" ]]
cd "${source_dirs[0]}"
# Prepare the debian directory with custom files
mkdir -p .build/debian
@@ -137,6 +170,7 @@ jobs:
sed -i "s/DISABLE_RUST_TOOLCHAIN = 0/DISABLE_RUST_TOOLCHAIN = 1/g" .build/debian/rules
- name: Publish to PPA
if: ${{ !inputs.verify_only }}
uses: yuezk/publish-ppa-package@main
with:
repository: "yuezk/globalprotect-openconnect"
@@ -149,3 +183,14 @@ jobs:
extra_ppa: "yuezk/globalprotect-openconnect"
series: ${{ matrix.series }}
revision: ${{ inputs.revision }}
- name: Wait for Launchpad builds and public package indexes
if: ${{ inputs.verify_only }}
env:
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
SERIES: ${{ matrix.series }}
run: |
ubuntu_version="$(ubuntu-distro-info --series "$SERIES" --release | cut -d' ' -f1)"
python3 scripts/wait-for-publication.py ppa --series "$SERIES" \
--version "${TAG#v}-ppa${REVISION}~ubuntu${ubuntu_version}"
+38
View File
@@ -0,0 +1,38 @@
name: Release infrastructure checks
on:
pull_request:
paths:
- '.github/workflows/**'
- 'scripts/wait-for-publication.py'
- 'scripts/select-publication-targets.py'
- 'scripts/verify-docker-publication.sh'
- 'scripts/tests/test_*publication.py'
push:
branches: [main]
paths:
- '.github/workflows/**'
- 'scripts/wait-for-publication.py'
- 'scripts/select-publication-targets.py'
- 'scripts/verify-docker-publication.sh'
- 'scripts/tests/test_*publication.py'
permissions:
contents: read
jobs:
release-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Validate workflow expressions and schema
run: |
docker run --rm -v "$PWD:/repo" -w /repo \
rhysd/actionlint:1.7.12@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667 \
-shellcheck='' -pyflakes=''
- name: Check Docker publication script
run: |
bash -n scripts/verify-docker-publication.sh
shellcheck scripts/verify-docker-publication.sh
- name: Test publication verification
run: python3 -m unittest discover -s scripts/tests -p 'test_*publication.py'
+29 -1
View File
@@ -215,6 +215,7 @@ jobs:
if: ${{ inputs.release-docker }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Download digests
uses: actions/download-artifact@v8
with:
@@ -244,13 +245,20 @@ jobs:
docker buildx imagetools create "${tags[@]}" \
$(printf "$IMAGE@sha256:%s " *)
docker buildx imagetools inspect "$IMAGE:$TAG"
"$GITHUB_WORKSPACE/scripts/verify-docker-publication.sh" "$IMAGE:$TAG" /tmp/digests "${{ inputs.arch }}"
if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
for alias in "$VERSION" latest; do
"$GITHUB_WORKSPACE/scripts/verify-docker-publication.sh" "$IMAGE:$alias" /tmp/digests "${{ inputs.arch }}"
done
fi
gh-release:
needs:
- build
runs-on: ubuntu-latest
if: ${{ inputs.gh-release }}
outputs:
stable_version: ${{ steps.stable-release.outputs.version }}
permissions:
actions: read
contents: read
@@ -312,3 +320,23 @@ jobs:
else
gh-release/gp/scripts/upload-release-assets.sh "${{ inputs.tag }}" "${files[@]}"
fi
- name: Resolve stable release version
id: stable-release
env:
TAG: ${{ inputs.tag }}
run: |
if [[ "$TAG" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
echo "version=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT"
fi
update-flake-hashes:
needs: gh-release
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 }}
release_tag: ${{ inputs.tag }}
@@ -1,6 +1,14 @@
name: Update flake hashes
on:
workflow_call:
inputs:
version:
required: true
type: string
release_tag:
required: true
type: string
workflow_dispatch:
inputs:
version:
Generated
+357 -434
View File
File diff suppressed because it is too large. Load diff
+13 -13
View File
@@ -11,7 +11,7 @@ members = [
[workspace.package]
rust-version = "1.91"
version = "3.0.1"
version = "3.0.5"
authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024"
@@ -19,47 +19,47 @@ license = "GPL-3.0"
[workspace.dependencies]
anyhow = "1.0"
askama = "0.16"
base64 = "0.22"
askama = { version = "0.16", default-features = false, features = ["std", "derive", "config"] }
base64 = { version = "0.23", default-features = false, features = ["std"] }
chrono = "0.4"
clap = { version = "4", features = ["derive"] }
clap-verbosity-flag = "3"
ctrlc = "3.4"
directories = "6.0"
dns-lookup = "3"
dns-lookup = "4.0.2"
env_logger = "0.11"
is_executable = "1.0"
log = "0.4"
regex = "1"
reqwest = { version = "0.13", default-features = false, features = ["native-tls", "charset", "http2", "system-proxy", "json", "form", "query"] }
openssl = "0.10"
pem = "3"
pem = "4"
xmltree = { version = "0.12", features = ["attribute-order"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
# Use 0.36 as newer versions requires Rust 1.88+
sysinfo = "0.36"
# The 0.39 series requires Rust 1.95, above the workspace minimum.
sysinfo = { version = "0.38.4", default-features = false, features = ["system"] }
tempfile = "3.8"
tokio = { version = "1" }
tokio-util = "0.7"
url = "2.4"
urlencoding = "2.1.3"
axum = "0.8"
futures = "0.3"
axum = { version = "0.8", default-features = false, features = ["http1", "tokio"] }
futures = { version = "0.3", default-features = false, features = ["std"] }
futures-util = "0.3"
uzers = "0.12"
whoami = "2"
thiserror = "2"
redact-engine = "0.1"
compile-time = "0.2"
compile-time = "0.4"
serde_urlencoded = "0.7"
md5 = "0.8"
sha256 = "1"
sha256 = { version = "1", default-features = false }
which = "8"
uuid = "1"
netdev = "0.40"
netdev = "0.46.3"
humantime = "2"
snow = { version = "0.10", default-features = false, features = ["std", "use-getrandom", "use-curve25519", "use-chacha20poly1305", "use-sha2"] }
snow = { version = "0.10", default-features = false, features = ["use-getrandom", "use-curve25519", "use-chacha20poly1305", "use-sha2"] }
zeroize = "1"
# Tauri dependencies
+114 -105
View File
@@ -3,6 +3,8 @@ SHELL := /bin/sh
INCLUDE_GUI ?= 0
CARGO ?= cargo
CARGO_TARGET_DIR ?= target
CARGO_RELEASE_DIR ?= $(CARGO_TARGET_DIR)/$(if $(CARGO_BUILD_TARGET),$(CARGO_BUILD_TARGET)/)release
DISABLE_RUST_TOOLCHAIN ?= 0
RUST_VERSION ?= 1.91
IGNORE_RUST_VERSION ?= 0
@@ -33,7 +35,14 @@ BUILD_GUI_HELPER ?= 1
# Indicates whether to build embedded webview auth support into gpauth
BUILD_WEBVIEW_AUTH ?= 1
ifeq ($(shell uname -s),Linux)
PREFIX ?= /usr
GPGUI_BINARY ?= $(wildcard .build/gpgui/gpgui_*/gpgui)
else ifeq ($(shell uname -s)-$(shell uname -m),Darwin-arm64)
PREFIX ?= /opt/homebrew
else
PREFIX ?= /usr/local
endif
BSD_FLAVOR ?= $(shell uname -s | tr '[:upper:]' '[:lower:]')
GPGUI_BINARY ?= ../gpgui/target/release/gpgui
@@ -139,86 +148,74 @@ clean:
rm -rf .vendor
rm -rf apps/gpgui-helper/node_modules
install:
@echo "Installing $(PKG_NAME)..."
ifeq ($(shell uname -s),Darwin)
install: install-macos
install-gpclient: install-gpclient-macos
else ifneq ($(filter FreeBSD OpenBSD,$(shell uname -s)),)
install: install-bsd
install-gpclient: install-gpclient-unix
else
install: install-linux
install-gpclient: install-gpclient-unix
endif
install -Dm755 target/release/gpclient $(DESTDIR)/usr/bin/gpclient
install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth
install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice
install -Dm755 target/release/gp-hip-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer
install -Dm755 target/release/gp-vpnc-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
install-gpclient-unix:
install -d "$(DESTDIR)$(PREFIX)/bin" "$(DESTDIR)$(PREFIX)/libexec/gpclient"
install -m 755 "$(CARGO_RELEASE_DIR)/gpclient" "$(DESTDIR)$(PREFIX)/bin/"
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script "$(DESTDIR)$(PREFIX)/libexec/gpclient/"
# Install the GUI components if BUILD_GUI_HELPER is set to 1
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
install -Dm755 target/release/gpgui-helper $(DESTDIR)/usr/bin/gpgui-helper; \
install-gpclient-macos:
install -d "$(DESTDIR)$(PREFIX)/bin" "$(DESTDIR)$(PREFIX)/lib/gpclient" "$(DESTDIR)$(PREFIX)/libexec/gpclient"
install -m 755 "$(CARGO_RELEASE_DIR)/gpclient" "$(DESTDIR)$(PREFIX)/bin/"
set -e; library=$$(sh scripts/macos-openconnect-library.sh "$(CARGO_RELEASE_DIR)/gpclient"); \
install -m 755 "$$library" "$(DESTDIR)$(PREFIX)/lib/gpclient/"; \
install_name_tool -delete_rpath "$$(dirname "$$library")" "$(DESTDIR)$(PREFIX)/bin/gpclient"; \
codesign --force --sign - "$(DESTDIR)$(PREFIX)/bin/gpclient"
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script "$(DESTDIR)$(PREFIX)/libexec/gpclient/"
install-macos: install-gpclient-macos
install -m 755 "$(CARGO_RELEASE_DIR)/gpauth" "$(DESTDIR)$(PREFIX)/bin/"
# Common executable and icon installation uses portable install options on Linux/BSD.
install-unix: install-gpclient-unix
set -e; for binary in gpauth gpservice; do \
install -m 755 "$(CARGO_RELEASE_DIR)/$$binary" "$(DESTDIR)$(PREFIX)/bin/"; \
done
set -e; for binary in gp-hip-script-installer gp-vpnc-script-installer; do \
install -m 755 "$(CARGO_RELEASE_DIR)/$$binary" "$(DESTDIR)$(PREFIX)/libexec/gpclient/"; \
done
set -e; if [ "$(BUILD_GUI_HELPER)" = "1" ]; then \
install -m 755 "$(CARGO_RELEASE_DIR)/gpgui-helper" "$(DESTDIR)$(PREFIX)/bin/"; \
fi
if [ -f .build/gpgui/gpgui_*/gpgui ]; then \
install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \
set -e; if [ -f "$(GPGUI_BINARY)" ]; then \
install -m 755 "$(GPGUI_BINARY)" "$(DESTDIR)$(PREFIX)/bin/gpgui"; \
fi
set -e; for file in packaging/files/usr/share/icons/hicolor/*/apps/gpgui.* \
packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-*.svg; do \
destination="$(DESTDIR)$(PREFIX)/$${file#packaging/files/usr/}"; \
install -d "$$(dirname "$$destination")"; \
install -m 644 "$$file" "$$destination"; \
done
install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script
install-linux: install-unix
@echo "Installing Linux integration under $(PREFIX)..."
set -e; for file in share/applications/gpgui.desktop \
share/polkit-1/actions/com.yuezk.gpgui.policy \
lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down \
lib/NetworkManager/dispatcher.d/gpclient-nm-hook; do \
mode=644; case "$$file" in lib/*) mode=755 ;; esac; \
destination="$(DESTDIR)$(PREFIX)/$$file"; \
install -d "$$(dirname "$$destination")"; \
install -m "$$mode" "packaging/files/usr/$$file" "$$destination"; \
done
sh scripts/relocate-install-paths.sh "$(PREFIX)" /usr "$(DESTDIR)$(PREFIX)"
# Install the disconnect hooks
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
install -Dm644 packaging/files/usr/share/applications/gpgui.desktop $(DESTDIR)/usr/share/applications/gpgui.desktop
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
install -Dm644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
install -Dm644 packaging/files/usr/share/icons/hicolor/128x128/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/128x128/apps/gpgui.png
install -Dm644 packaging/files/usr/share/icons/hicolor/256x256/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/256x256/apps/gpgui.png
install -Dm644 packaging/files/usr/share/icons/hicolor/256x256@2/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/256x256@2/apps/gpgui.png
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connected-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connected-symbolic.svg
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-disconnected-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-disconnected-symbolic.svg
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-1-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-1-symbolic.svg
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-2-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-2-symbolic.svg
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-3-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-3-symbolic.svg
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-4-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-4-symbolic.svg
install -Dm644 packaging/files/usr/share/polkit-1/actions/com.yuezk.gpgui.policy $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
install-bsd:
@echo "Installing $(PKG_NAME) for BSD under $(PREFIX)..."
install -d $(DESTDIR)$(PREFIX)/bin
install -m 755 target/release/gpclient $(DESTDIR)$(PREFIX)/bin/gpclient
install -m 755 target/release/gpauth $(DESTDIR)$(PREFIX)/bin/gpauth
install -m 755 target/release/gpservice $(DESTDIR)$(PREFIX)/bin/gpservice
if [ "$(BUILD_GUI_HELPER)" = "1" ]; then \
install -m 755 target/release/gpgui-helper $(DESTDIR)$(PREFIX)/bin/gpgui-helper; \
fi
if [ -x "$(GPGUI_BINARY)" ]; then \
install -m 755 "$(GPGUI_BINARY)" $(DESTDIR)$(PREFIX)/bin/gpgui; \
fi
install -d $(DESTDIR)$(PREFIX)/libexec/gpclient
install -m 755 target/release/gp-hip-script-installer $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-hip-script-installer
install -m 755 target/release/gp-vpnc-script-installer $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-vpnc-script-installer
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)$(PREFIX)/libexec/gpclient/vpnc-script
install -d $(DESTDIR)$(PREFIX)/share/applications
install -m 644 packaging/bsd/gpgui.desktop $(DESTDIR)$(PREFIX)/share/applications/gpgui.desktop
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256@2/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps/gpgui.svg
install -m 644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps/gpgui.png
install -m 644 packaging/files/usr/share/icons/hicolor/128x128/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps/gpgui.png
install -m 644 packaging/files/usr/share/icons/hicolor/256x256/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256/apps/gpgui.png
install -m 644 packaging/files/usr/share/icons/hicolor/256x256@2/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256@2/apps/gpgui.png
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connected-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-connected-symbolic.svg
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-disconnected-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-disconnected-symbolic.svg
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-1-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-connecting-1-symbolic.svg
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-2-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-connecting-2-symbolic.svg
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-3-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-connecting-3-symbolic.svg
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-4-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-connecting-4-symbolic.svg
install -d $(DESTDIR)$(PREFIX)/share/polkit-1/actions
install -m 644 packaging/bsd/com.yuezk.gpgui.policy $(DESTDIR)$(PREFIX)/share/polkit-1/actions/com.yuezk.gpgui.policy
install-bsd: install-unix
@echo "Installing BSD integration under $(PREFIX)..."
install -d "$(DESTDIR)$(PREFIX)/share/applications" "$(DESTDIR)$(PREFIX)/share/polkit-1/actions"
install -m 644 packaging/bsd/gpgui.desktop "$(DESTDIR)$(PREFIX)/share/applications/"
install -m 644 packaging/bsd/com.yuezk.gpgui.policy "$(DESTDIR)$(PREFIX)/share/polkit-1/actions/"
sh scripts/relocate-install-paths.sh "$(PREFIX)" /usr/local "$(DESTDIR)$(PREFIX)"
clean-bsd-package:
rm -rf .build/$(BSD_FLAVOR)
@@ -290,42 +287,54 @@ package-openbsd: clean-bsd-package
.build/openbsd/artifacts/$(PKG_NAME)-$(VERSION)-openbsd-$$openbsd_arch.tgz
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)"
uninstall:
@echo "Uninstalling $(PKG_NAME)..."
ifeq ($(shell uname -s),Darwin)
uninstall: uninstall-macos
else ifneq ($(filter FreeBSD OpenBSD,$(shell uname -s)),)
uninstall: uninstall-bsd
else
uninstall: uninstall-linux
endif
rm -f $(DESTDIR)/usr/bin/gpclient
rm -f $(DESTDIR)/usr/bin/gpauth
rm -f $(DESTDIR)/usr/bin/gpservice
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer
rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui
.PHONY: install install-gpclient install-macos install-unix install-linux install-bsd \
install-gpclient-macos install-gpclient-unix \
uninstall uninstall-macos uninstall-unix uninstall-linux uninstall-bsd
rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
uninstall-macos:
@echo "Uninstalling $(PKG_NAME) for macOS under $(PREFIX)..."
rm -f "$(DESTDIR)$(PREFIX)/bin/gpclient" "$(DESTDIR)$(PREFIX)/bin/gpauth" \
"$(DESTDIR)$(PREFIX)/libexec/gpclient/vpnc-script" \
"$(DESTDIR)$(PREFIX)/lib/gpclient/"libopenconnect.*.dylib
rmdir "$(DESTDIR)$(PREFIX)/lib/gpclient" "$(DESTDIR)$(PREFIX)/libexec/gpclient" 2>/dev/null || true
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
uninstall-unix:
@echo "Uninstalling $(PKG_NAME) under $(PREFIX)..."
set -e; for binary in gpclient gpauth gpservice gpgui-helper gpgui; do \
rm -f "$(DESTDIR)$(PREFIX)/bin/$$binary"; \
done
set -e; for file in gp-hip-script-installer gp-vpnc-script-installer vpnc-script; do \
rm -f "$(DESTDIR)$(PREFIX)/libexec/gpclient/$$file"; \
done
set -e; for file in packaging/files/usr/share/icons/hicolor/*/apps/gpgui.* \
packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-*.svg; do \
rm -f "$(DESTDIR)$(PREFIX)/$${file#packaging/files/usr/}"; \
done
rm -f "$(DESTDIR)$(PREFIX)/share/applications/gpgui.desktop" \
"$(DESTDIR)$(PREFIX)/share/polkit-1/actions/com.yuezk.gpgui.policy"
rmdir "$(DESTDIR)$(PREFIX)/libexec/gpclient" 2>/dev/null || true
rm -f $(DESTDIR)/usr/share/applications/gpgui.desktop
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
rm -f $(DESTDIR)/usr/share/icons/hicolor/128x128/apps/gpgui.png
rm -f $(DESTDIR)/usr/share/icons/hicolor/256x256/apps/gpgui.png
rm -f $(DESTDIR)/usr/share/icons/hicolor/256x256@2/apps/gpgui.png
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connected-symbolic.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-disconnected-symbolic.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-1-symbolic.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-2-symbolic.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-3-symbolic.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-4-symbolic.svg
rm -f $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
uninstall-linux: uninstall-unix
rm -f "$(DESTDIR)$(PREFIX)/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down" \
"$(DESTDIR)$(PREFIX)/lib/NetworkManager/dispatcher.d/gpclient-nm-hook"
rm -f "$(DESTDIR)/var/lib/gpclient/gpgui" \
"$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script" \
"$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script.metadata"
rmdir "$(DESTDIR)/var/lib/gpclient/scripts" "$(DESTDIR)/var/lib/gpclient" 2>/dev/null || true
rm -f $(DESTDIR)/var/lib/gpclient/gpgui \
$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script \
$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script.metadata || \
echo "Warning: failed to remove gpclient runtime files" >&2
rmdir $(DESTDIR)/var/lib/gpclient/scripts 2>/dev/null || true
rmdir $(DESTDIR)/var/lib/gpclient 2>/dev/null || true
uninstall-bsd: uninstall-unix
rm -f "$(DESTDIR)/usr/local/libexec/gpclient/gpgui" \
"$(DESTDIR)/var/db/gpclient/scripts/vpnc-script" \
"$(DESTDIR)/var/db/gpclient/scripts/vpnc-script.metadata"
rmdir "$(DESTDIR)/var/db/gpclient/scripts" "$(DESTDIR)/var/db/gpclient" 2>/dev/null || true
clean-debian:
rm -rf .build/deb
+2
View File
@@ -519,6 +519,8 @@ Verify the CLI client is working correctly:
## Frequently Asked Questions
When reporting a problem, follow the [diagnostics collection instructions](docs/diagnostics.md). A standalone script is available for versions without the diagnostics command; you do not need to upgrade first.
### Q: How do I resolve the "Secure Storage not ready" error?
Unlock your desktop keyring and ensure the application can access it. On Linux and BSD, check that a keyring service such as GNOME Keyring is installed and running in your desktop session. On macOS, check Keychain access.
+1 -2
View File
@@ -24,8 +24,7 @@ tokio = { workspace = true, features = ["rt-multi-thread"] }
tempfile.workspace = true
compile-time.workspace = true
# Pin to specific version due to MSRV
home = "=0.5.11"
home = "0.5.12"
# webview auth dependencies
tauri = { workspace = true, optional = true }
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 56 KiB

+1
View File
@@ -17,6 +17,7 @@ clap.workspace = true
env_logger.workspace = true
inquire = "0.9"
log.workspace = true
nix = { version = "0.31", features = ["fs", "signal", "process"] }
tokio = { workspace = true, features = ["rt-multi-thread"] }
tokio-util.workspace = true
sysinfo.workspace = true
+9
View File
@@ -4,6 +4,15 @@ const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
// Installed OpenConnect lives in the private ../lib/gpclient directory.
// Build executables also locate their exact Cargo library; installers remove that rpath.
#[cfg(target_os = "macos")]
{
println!("cargo:rustc-link-arg=-Wl,-rpath,@executable_path/../lib/gpclient");
let library_dir = env::var("DEP_OPENCONNECT_LIB_DIR").expect("OpenConnect exports its build library directory");
println!("cargo:rustc-link-arg=-Wl,-rpath,{library_dir}");
}
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GPCLIENT_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
+302
View File
@@ -0,0 +1,302 @@
//! Re-exec a worker in the foreground for sign-in, then detach only after tunnel setup.
//! No process is forked after authentication or OpenConnect has started its threads.
use std::{
ffi::OsString,
fs::{File, OpenOptions},
io::{self, Write},
os::{
fd::{AsRawFd, FromRawFd, OwnedFd},
unix::{
fs::{MetadataExt, OpenOptionsExt, PermissionsExt},
net::UnixStream,
},
},
path::Path,
process::{ExitStatus, Stdio},
};
use anyhow::{Context, bail};
use nix::{
fcntl::{FcntlArg, FdFlag, OFlag, fcntl},
sys::signal::{Signal, kill},
unistd::{Pid, dup2_stderr, dup2_stdin, dup2_stdout, setsid},
};
use tokio::{io::AsyncReadExt, process::Command};
const READY: u8 = 1;
pub(crate) struct BackgroundWorker {
ready: UnixStream,
log: File,
input: File,
}
// Keep sign-in interactive again if a tunnel attempt fails before detachment.
pub(crate) struct BackgroundStdio {
saved: Option<[OwnedFd; 3]>,
}
impl Drop for BackgroundStdio {
fn drop(&mut self) {
if let Some([input, output, error]) = &self.saved {
let _ = io::stdout().flush();
let _ = io::stderr().flush();
let result = dup2_stdin(input)
.and_then(|_| dup2_stdout(output))
.and_then(|_| dup2_stderr(error));
if let Err(error) = result {
log::warn!("Cannot restore foreground standard streams: {error}");
}
}
}
}
impl BackgroundWorker {
pub(crate) fn new(fd: i32, log_path: &Path) -> anyhow::Result<Self> {
anyhow::ensure!(fd >= 3, "Invalid background readiness descriptor");
// Validate the raw descriptor before taking ownership; malformed internal args
// must return an error rather than violate OwnedFd's validity requirement.
if unsafe { nix::libc::fcntl(fd, nix::libc::F_GETFD) } == -1 {
return Err(io::Error::last_os_error().into());
}
// The launcher passes its own readiness socket across exec, without authentication state.
let ready = unsafe { UnixStream::from_raw_fd(fd) };
ready.peer_addr().context("Invalid background readiness socket")?;
fcntl(&ready, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC))?;
let log = OpenOptions::new()
.create(true)
.append(true)
.mode(0o600)
.custom_flags(OFlag::O_NOFOLLOW.bits() | OFlag::O_NONBLOCK.bits())
.open(log_path)
.with_context(|| format!("Cannot open background log {}", log_path.display()))?;
let metadata = log.metadata()?;
anyhow::ensure!(metadata.is_file(), "Background log must be a regular file");
anyhow::ensure!(
metadata.uid() == uzers::get_effective_uid(),
"Background log must be owned by the user running gpclient"
);
anyhow::ensure!(
metadata.permissions().mode() & 0o077 == 0,
"Background log must not be readable or writable by other users"
);
let input = File::open("/dev/null")?;
Ok(Self { ready, log, input })
}
pub(crate) fn redirect_stdio(&self) -> anyhow::Result<BackgroundStdio> {
io::stdout().flush()?;
io::stderr().flush()?;
let save = |fd| -> anyhow::Result<OwnedFd> {
// Duplicate atomically with close-on-exec so helpers never inherit the terminal copies.
let saved = unsafe { nix::libc::fcntl(fd, nix::libc::F_DUPFD_CLOEXEC, 3) };
if saved == -1 {
return Err(io::Error::last_os_error().into());
}
Ok(unsafe { OwnedFd::from_raw_fd(saved) })
};
let stdio = BackgroundStdio {
saved: Some([save(0)?, save(1)?, save(2)?]),
};
// Redirect before tunnel setup, which can start a persistent --script-tun helper.
dup2_stdin(&self.input)?;
dup2_stdout(&self.log)?;
dup2_stderr(&self.log)?;
Ok(stdio)
}
pub(crate) fn detach(&self, stdio: &mut BackgroundStdio) -> anyhow::Result<()> {
// 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")?;
(&self.ready)
.write_all(&[READY])
.context("Background launcher exited before tunnel setup")?;
stdio.saved.take();
Ok(())
}
}
pub(crate) async fn start(log_path: &Path, format: gpapi::log_format::LogFormat) -> anyhow::Result<()> {
let command = Command::new(std::env::current_exe()?);
let arguments = std::env::args_os().skip(1).collect::<Vec<_>>();
launch(command, &arguments)
.await
.with_context(|| format!("Background VPN startup failed; log file: {}", log_path.display()))?;
gpapi::clap::report(
format,
log::Level::Info,
&format!("VPN is running in the background. Logs: {}", log_path.display()),
);
Ok(())
}
async fn launch(mut command: Command, arguments: &[OsString]) -> anyhow::Result<()> {
let (parent, worker) = UnixStream::pair()?;
parent.set_nonblocking(true)?;
let mut ready = tokio::net::UnixStream::from_std(parent)?;
let fd = worker.as_raw_fd();
command.arg("--background-worker-fd").arg(fd.to_string());
// Internal options precede user arguments, which can include the `--` terminator.
command.args(arguments);
command
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
// Only async-signal-safe descriptor setup runs between spawn's fork and exec.
unsafe {
command.pre_exec(move || {
fcntl(&worker, FcntlArg::F_SETFD(FdFlag::empty())).map_err(io::Error::from)?;
Ok(())
});
}
let mut child = command.spawn().context("Cannot start background VPN worker")?;
// Release our copy of the worker's socket so EOF reports startup failure.
drop(command);
let pid = Pid::from_raw(child.id().context("Background worker has no PID")? as i32);
let outcome = tokio::select! {
result = ready.read_u8() => result.map_err(anyhow::Error::from),
status = child.wait() => return startup_exit(status?),
_ = gpapi::utils::shutdown_signal() => {
let _ = kill(pid, Signal::SIGINT);
child.wait().await?;
bail!("Background connection cancelled");
}
};
match outcome {
Ok(READY) => Ok(()),
_ => {
let _ = kill(pid, Signal::SIGINT);
startup_exit(child.wait().await?)
}
}
}
fn startup_exit(status: ExitStatus) -> anyhow::Result<()> {
bail!("Background VPN exited before the tunnel was established ({status})")
}
#[cfg(test)]
mod tests {
use super::*;
use nix::unistd::{getpid, getsid};
use std::time::Duration;
// Re-exec the test binary so the test exercises real process/session/descriptor setup.
// The shell consumes launch's internal FD argument instead of giving it to libtest.
fn fixture(directory: &Path) -> Command {
let mut command = Command::new("sh");
command.args(["-c", "export GPCLIENT_TEST_FD=\"$2\"; exec \"$GPCLIENT_TEST_EXE\" --exact background::tests::worker_fixture --nocapture", "fixture"])
.env("GPCLIENT_TEST_EXE", std::env::current_exe().unwrap())
.env("GPCLIENT_TEST_DIR", directory);
command
}
#[tokio::test]
async fn startup_failure_is_not_reported_as_a_background_connection() {
let mut command = Command::new("sh");
command.args(["-c", "exit 7"]);
let error = tokio::time::timeout(Duration::from_secs(5), launch(command, &[]))
.await
.unwrap()
.unwrap_err();
assert!(error.to_string().contains("before the tunnel was established"));
}
#[tokio::test]
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();
let pid = std::fs::read_to_string(directory.path().join("pid"))
.unwrap()
.parse::<i32>()
.unwrap();
let pid = Pid::from_raw(pid);
assert_eq!(
getsid(Some(pid)).unwrap(),
pid,
"Worker must own a terminal-independent session"
);
kill(pid, None).unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while !std::fs::read_to_string(directory.path().join("worker.log"))
.unwrap()
.contains("helper-output")
{
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
let log = std::fs::read_to_string(directory.path().join("worker.log")).unwrap();
assert!(log.contains("failed-attempt-output"));
assert!(!log.contains("restored-foreground-output"));
#[derive(clap::Parser)]
struct Disconnect {
#[command(flatten)]
args: crate::disconnect::DisconnectArgs,
}
let args = <Disconnect as clap::Parser>::parse_from(["test"]);
crate::disconnect::DisconnectHandler::new(&args.args, &directory.path().join("pid"))
.handle()
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while !directory.path().join("stopped").exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
}
#[tokio::test]
async fn unsafe_log_path_fails_before_detaching() {
let directory = tempfile::tempdir().unwrap();
std::os::unix::fs::symlink(directory.path().join("target"), directory.path().join("worker.log")).unwrap();
let result = tokio::time::timeout(Duration::from_secs(5), launch(fixture(directory.path()), &[]))
.await
.unwrap();
assert!(result.is_err());
assert!(!directory.path().join("target").exists());
}
#[tokio::test]
async fn worker_fixture() {
let Ok(fd) = std::env::var("GPCLIENT_TEST_FD") else {
return;
};
let directory = std::path::PathBuf::from(std::env::var_os("GPCLIENT_TEST_DIR").unwrap());
let worker = match BackgroundWorker::new(fd.parse().unwrap(), &directory.join("worker.log")) {
Ok(worker) => worker,
Err(error) => {
eprintln!("{error:#}");
std::process::exit(1);
}
};
let mut interrupt = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()).unwrap();
std::fs::write(directory.join("pid"), getpid().to_string()).unwrap();
// A failed attempt must restore foreground streams before another sign-in.
{
let _stdio = worker.redirect_stdio().unwrap();
println!("failed-attempt-output");
}
println!("restored-foreground-output");
let mut stdio = worker.redirect_stdio().unwrap();
// Like OpenConnect's script-tun helper, this child starts before readiness.
let mut helper = std::process::Command::new("sh")
.args(["-c", "sleep 0.1; echo helper-output"])
.spawn()
.unwrap();
worker.detach(&mut stdio).unwrap();
println!("detached-output");
io::stdout().flush().unwrap();
interrupt.recv().await;
helper.wait().unwrap();
std::fs::write(directory.join("stopped"), "stopped").unwrap();
}
}
+93 -1
View File
@@ -18,6 +18,7 @@ use tokio::fs;
use crate::{
GP_CLIENT_LOCK_FILE,
connect::{ConnectArgs, ConnectHandler},
diagnostics::DiagnosticsArgs,
disconnect::{DisconnectArgs, DisconnectHandler},
hip::{HipArgs, HipHandler},
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
@@ -50,6 +51,8 @@ enum CliCommand {
LaunchGui(LaunchGuiArgs),
#[command(about = "Generate HIP report")]
Hip(HipArgs),
#[command(about = "Collect system diagnostics for a bug report without connecting to a VPN")]
Diagnostics(DiagnosticsArgs),
#[command(hide = true)]
DetectInternalHost {
#[arg(long)]
@@ -104,6 +107,9 @@ struct Cli {
)]
lock_file: PathBuf,
#[arg(long, hide = true, global = true)]
background_worker_fd: Option<i32>,
#[arg(
long,
value_enum,
@@ -168,11 +174,35 @@ impl Cli {
}
async fn run(&self) -> anyhow::Result<()> {
if self.background_worker_fd.is_some() && !matches!(&self.command, CliCommand::Connect(args) if args.background) {
bail!("Background worker requires connect --background");
}
if let CliCommand::Diagnostics(args) = &self.command {
return args.run(VERSION).await;
}
// check if an instance is running
if !self.can_run_alongside_client() && self.is_running().await {
bail!("Another instance of the client is already running");
}
let background_worker = if let CliCommand::Connect(args) = &self.command {
if args.background {
let log_file = args
.log_file
.as_deref()
.unwrap_or_else(|| Path::new("/var/log/gpclient.log"));
match self.background_worker_fd {
Some(fd) => Some(crate::background::BackgroundWorker::new(fd, log_file)?),
None => return crate::background::start(log_file, self.log_format).await,
}
} else {
None
}
} else {
None
};
// The temp file will be dropped automatically when the file handle is dropped
// So, declare it here to ensure it's not dropped
let _file = self.fix_openssl()?;
@@ -189,10 +219,16 @@ impl Cli {
}
match &self.command {
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await,
CliCommand::Connect(args) => {
ConnectHandler::new(args, &shared_args)
.with_background(background_worker)
.handle()
.await
}
CliCommand::Disconnect(args) => DisconnectHandler::new(args, shared_args.lock_file).handle().await,
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
CliCommand::Diagnostics(_) => unreachable!("diagnostics is dispatched before VPN setup"),
CliCommand::DetectInternalHost { address, hostname } => {
let internal = gpapi::session::network::native::detect_in_helper(*address, hostname)?;
println!("{}", serde_json::to_string(&internal)?);
@@ -248,6 +284,62 @@ mod tests {
use super::*;
#[test]
fn background_worker_option_precedes_user_option_terminator() {
let cli = Cli::try_parse_from([
"gpclient",
"--background-worker-fd",
"3",
"connect",
"--background",
"--",
"portal.example.com",
])
.unwrap();
assert_eq!(cli.background_worker_fd, Some(3));
assert!(matches!(cli.command, CliCommand::Connect(args) if args.background));
}
#[test]
fn background_mode_rejects_cookie_only_and_requires_background_for_log_file() {
assert!(
Cli::try_parse_from([
"gpclient",
"connect",
"portal.example.com",
"--background",
"--cookie-only"
])
.is_err()
);
assert!(Cli::try_parse_from(["gpclient", "connect", "portal.example.com", "--log-file", "/tmp/gp.log"]).is_err());
assert!(
Cli::try_parse_from([
"gpclient",
"connect",
"portal.example.com",
"--background",
"--passwd-on-stdin"
])
.is_ok()
);
}
#[test]
fn diagnostics_accepts_output_options_and_runs_alongside_the_client() {
let cli = Cli::try_parse_from([
"gpclient",
"--fix-openssl",
"diagnostics",
"--json",
"--output",
"report.json",
])
.unwrap();
assert!(matches!(cli.command, CliCommand::Diagnostics(_)));
assert!(cli.can_run_alongside_client());
}
#[test]
fn resolver_helper_runs_alongside_client_and_is_hidden_from_help() {
let cli = Cli::try_parse_from([
+14
View File
@@ -13,6 +13,20 @@ pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
pub(super) server: String,
#[arg(
long,
conflicts_with = "cookie_only",
help = "Complete sign-in, then keep the VPN running after this command exits"
)]
pub(crate) background: bool,
#[arg(
long,
requires = "background",
help = "Background log file (default: /var/log/gpclient.log)"
)]
pub(crate) log_file: Option<PathBuf>,
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
pub(super) gateway: Option<String>,
+63
View File
@@ -11,6 +11,14 @@ use log::info;
use super::ConnectHandler;
/// Replaces only the child launch boundary in workflow tests.
#[cfg(test)]
#[derive(Default)]
pub(super) struct AuthAttemptFixture {
pub(super) outcomes: std::collections::VecDeque<anyhow::Result<Credential>>,
pub(super) observed: Vec<(String, bool, bool)>,
}
#[derive(Default)]
pub(super) struct CleanAuthState {
requested: bool,
@@ -44,6 +52,47 @@ impl ConnectHandler<'_> {
Ok(())
}
pub(super) async fn obtain_credential_with_recovery(
&self,
mut response: Prelogin,
server: &str,
browser_allowed: bool,
) -> anyhow::Result<(Prelogin, Credential)> {
loop {
self.check_cancelled()?;
let result = self.obtain_credential(&response, server, browser_allowed).await;
self.check_cancelled()?;
match result {
Ok(credential) => return Ok((response, credential)),
Err(error) => {
if !self.auth_recovery.borrow_mut().recover(&error) {
return Err(self.auth_recovery.borrow().terminal(error));
}
log::warn!("Authenticator exited with a Wayland rendering error; retrying with DMABUF disabled");
let refreshed = self
.refresh_auth_prelogin(server, response.is_gateway(), browser_allowed)
.await;
response = refreshed.map_err(|error| self.auth_recovery.borrow().terminal(error))?;
}
}
}
}
pub(super) async fn refresh_auth_prelogin(
&self,
server: &str,
is_gateway: bool,
browser_allowed: bool,
) -> anyhow::Result<Prelogin> {
let mut params = self.build_gp_params();
params.set_is_gateway(is_gateway);
tokio::select! {
biased;
_ = self.cancellation.cancelled() => Err(gpapi::auth::AuthenticationCancelled.into()),
result = gpapi::portal::prelogin(server, &params, self.prelogin_options(browser_allowed)) => result,
}
}
pub(super) async fn obtain_credential(
&self,
prelogin: &Prelogin,
@@ -76,6 +125,7 @@ impl ConnectHandler<'_> {
let os_profile = self.os_profile.borrow().clone();
let key_password = self.latest_key_password.borrow().clone();
let auth_launcher = SamlAuthLauncher::new(server)
.dmabuf_disabled(self.auth_recovery.borrow().dmabuf_disabled())
.gateway(is_gateway)
.saml_request(prelogin.saml_request())
.os_profile(&os_profile)
@@ -116,6 +166,19 @@ impl ConnectHandler<'_> {
.clean(clean_auth)
.default_browser(use_default_browser);
#[cfg(test)]
{
let mut fixture = self.auth_attempt_fixture.borrow_mut();
if let Some(outcome) = fixture.outcomes.pop_front() {
fixture.observed.push((
prelogin.saml_request().to_owned(),
self.auth_recovery.borrow().dmabuf_disabled(),
clean_auth,
));
return outcome;
}
}
let cred = auth_launcher.cancellation(&self.cancellation).launch().await?;
self.check_cancelled()?;
Ok(cred)
+347
View File
@@ -171,3 +171,350 @@ async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_reject
assert!(requests[1].contains("rejected-cookie"));
assert!(requests[2].contains("gateway-password"));
}
#[tokio::test]
async fn rendering_recovery_fetches_new_prelogin_metadata_and_preserves_gateway_mode() {
let (origin, worker) = gateway(vec![
(
"200 OK",
"<prelogin-response><status>Success</status><region>old</region></prelogin-response>".into(),
),
(
"200 OK",
"<prelogin-response><status>Success</status><region>replacement</region></prelogin-response>".into(),
),
])
.await;
let args = TestArgs::parse_from(["test", &origin]).connect;
let directory = tempfile::tempdir().unwrap();
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
let original = handler.refresh_auth_prelogin(&origin, true, true).await.unwrap();
let replacement = handler
.refresh_auth_prelogin(&origin, original.is_gateway(), true)
.await
.unwrap();
assert_eq!(original.region(), "old");
assert_eq!(replacement.region(), "replacement");
assert!(replacement.is_gateway());
let requests = worker.await.unwrap();
assert_eq!(requests.len(), 2);
assert!(
requests
.iter()
.all(|request| request.starts_with("POST /ssl-vpn/prelogin.esp"))
);
}
#[cfg(feature = "webview-auth")]
#[tokio::test]
async fn cancellation_during_recovery_prelogin_stops_request() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let args = TestArgs::parse_from(["test", &origin]).connect;
let directory = tempfile::tempdir().unwrap();
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
handler
.auth_attempt_fixture
.borrow_mut()
.outcomes
.push_back(Err(rendering_crash()));
let (result, ()) = tokio::time::timeout(Duration::from_secs(3), async {
tokio::join!(
async {
let original = handler.refresh_auth_prelogin(&origin, false, false).await?;
handler.obtain_credential_with_recovery(original, &origin, false).await
},
async {
let (mut socket, _) = listener.accept().await.unwrap();
let mut byte = [0];
socket.read_exact(&mut byte).await.unwrap();
handler.cancellation.cancel();
}
)
})
.await
.unwrap();
assert!(
result
.unwrap_err()
.downcast_ref::<gpapi::auth::AuthenticationCancelled>()
.is_some()
);
}
#[cfg(feature = "webview-auth")]
fn rendering_crash() -> anyhow::Error {
use std::os::unix::process::ExitStatusExt;
gpapi::process::rendering_recovery::RenderingCrash {
status: std::process::ExitStatus::from_raw(71 << 8),
}
.into()
}
#[cfg(feature = "webview-auth")]
fn saml_prelogin_response(region: &str, encoded_request: &str) -> String {
format!(
"<prelogin-response><status>Success</status><region>{region}</region><saml-auth-method>POST</saml-auth-method><saml-request>{encoded_request}</saml-request></prelogin-response>"
)
}
#[cfg(feature = "webview-auth")]
#[tokio::test]
async fn auth_crash_uses_fresh_saml_and_clean_once_with_shared_budget() {
use gpapi::credential::{Credential, PreloginCredential};
let (origin, worker) = gateway(vec![
("200 OK", saml_prelogin_response("old-region", "b2xk")),
("200 OK", saml_prelogin_response("new-region", "bmV3")),
("200 OK", saml_prelogin_response("gateway-region", "Z2F0ZXdheQ==")),
])
.await;
let args = TestArgs::parse_from(["test", &origin, "--clean"]).connect;
let directory = tempfile::tempdir().unwrap();
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
handler.auth_attempt_fixture.borrow_mut().outcomes.extend([
Err(rendering_crash()),
Ok(Credential::Prelogin(PreloginCredential::new(
"alice",
Some("new-cookie"),
None,
None,
))),
Err(rendering_crash()),
]);
let original = handler.refresh_auth_prelogin(&origin, false, false).await.unwrap();
let (replacement, credential) = handler
.obtain_credential_with_recovery(original, &origin, false)
.await
.unwrap();
assert_eq!(replacement.region(), "new-region");
assert_eq!(credential.username(), "alice");
assert!(matches!(credential, Credential::Prelogin(ref value) if value.prelogin_cookie() == Some("new-cookie")));
let gateway_prelogin = handler.refresh_auth_prelogin(&origin, true, false).await.unwrap();
let error = handler
.obtain_credential_with_recovery(gateway_prelogin, &origin, false)
.await
.unwrap_err();
assert!(
error
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
.is_some()
);
assert_eq!(
handler.auth_attempt_fixture.borrow().observed,
[
("old".into(), false, true),
("new".into(), true, false),
("gateway".into(), true, false),
]
);
assert_eq!(worker.await.unwrap().len(), 3);
}
#[cfg(feature = "webview-auth")]
#[tokio::test]
async fn exhausted_auth_recovery_is_terminal_before_portal_gateway_fallback() {
let (origin, worker) = gateway(vec![
("200 OK", saml_prelogin_response("old-region", "b2xk")),
("200 OK", saml_prelogin_response("new-region", "bmV3")),
])
.await;
let args = TestArgs::parse_from(["test", &origin, "--clean"]).connect;
let directory = tempfile::tempdir().unwrap();
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
handler.auth_attempt_fixture.borrow_mut().outcomes.extend([
Err(rendering_crash()),
Err(anyhow::anyhow!(gpapi::error::PortalError::PreloginError(
"second failure".into()
))),
]);
let error = handler.handle_impl().await.unwrap_err();
assert!(
error
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
.is_some()
);
assert_eq!(handler.auth_attempt_fixture.borrow().observed.len(), 2);
assert_eq!(worker.await.unwrap().len(), 2);
}
#[cfg(all(
feature = "webview-auth",
any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")
))]
mod gtk_retry {
use super::*;
#[tokio::test]
async fn real_gtk_crash_retries_bundled_authenticator() {
// Environment overrides belong to a separate test process, never the parallel test runner.
if let Some(directory) = std::env::var_os("GP_TEST_GTK_AUTH_DIR") {
verify_real_authenticator_retry(std::path::Path::new(&directory)).await;
} else {
run_real_authenticator_retry(false);
}
}
#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires non-interactive sudo authorization and a running Wayland desktop session"]
fn sudo_gtk_crash_retries_after_restoring_desktop_environment() {
run_real_authenticator_retry(true);
}
fn run_real_authenticator_retry(sudo: bool) {
use std::{fs, os::unix::fs::PermissionsExt, process::Command};
let directory = tempfile::tempdir().unwrap();
let executable = directory.path().join("gpauth");
// Fixtures contain only dummy data and must remain accessible after a root test drops privileges.
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o755)).unwrap();
let attempts_path = directory.path().join("attempts");
fs::write(&attempts_path, "").unwrap();
fs::set_permissions(&attempts_path, fs::Permissions::from_mode(0o666)).unwrap();
fs::write(&executable, r#"#!/bin/sh
set -eu
request=
while [ "$#" -gt 0 ]; do
if [ "$1" = '--saml-request' ]; then
shift
request=$1
fi
shift
done
printf '%s|%s|%s|%s\n' "$(id -u)" "${WAYLAND_DISPLAY:-}" "${WEBKIT_DISABLE_DMABUF_RENDERER-unset}" "$request" >> "$GP_TEST_GTK_AUTH_DIR/attempts"
if [ "$request" = 'old' ]; then
printf 'Gdk-Message: 10:49:22.617: Error 71 (Protocol error) dispatching to Wayland display.\n' >&2
exit 1
fi
[ "$request" = 'new' ] && [ "${WEBKIT_DISABLE_DMABUF_RENDERER:-}" = '1' ] || exit 2
printf '%s\n' '{"success":{"username":"alice","preloginCookie":"new-cookie"}}'
"#).unwrap();
fs::set_permissions(&executable, fs::Permissions::from_mode(0o755)).unwrap();
let mut command = if sudo {
assert_ne!(
uzers::get_effective_uid(),
0,
"run this test as the Wayland desktop user"
);
let mut command = Command::new("sudo");
command.args([
"-n",
"env",
"-u",
"WAYLAND_DISPLAY",
"-u",
"DISPLAY",
"-u",
"XDG_SESSION_TYPE",
"-u",
"WEBKIT_DISABLE_DMABUF_RENDERER",
]);
command.arg("GP_TEST_EXPECT_ROOT=1");
command
} else {
let mut command = Command::new("env");
command.arg("-u").arg("WEBKIT_DISABLE_DMABUF_RENDERER");
command.arg("WAYLAND_DISPLAY=wayland-test");
command
};
command.arg(format!("GP_AUTH_BINARY={}", executable.display()));
command.arg(format!("GP_TEST_GTK_AUTH_DIR={}", directory.path().display()));
command.arg(std::env::current_exe().unwrap()).args([
"--exact",
"connect::flow_tests::gtk_retry::real_gtk_crash_retries_bundled_authenticator",
"--nocapture",
]);
let output = command.output().unwrap();
assert!(
output.status.success(),
"retry subprocess failed: {}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let expected_uid = gpapi::process::users::get_non_root_user().unwrap().uid().to_string();
let attempts = fs::read_to_string(attempts_path).unwrap();
let attempts: Vec<Vec<&str>> = attempts.lines().map(|line| line.split('|').collect()).collect();
assert_eq!(attempts.len(), 2, "expected exactly one retry");
for attempt in &attempts {
assert_eq!(attempt[0], expected_uid, "authenticator must run as the desktop user");
assert!(!attempt[1].is_empty(), "authenticator must receive WAYLAND_DISPLAY");
}
assert_eq!(&attempts[0][2..], ["unset", "old"]);
assert_eq!(&attempts[1][2..], ["1", "new"]);
}
async fn verify_real_authenticator_retry(directory: &std::path::Path) {
use gpapi::credential::Credential;
if std::env::var_os("GP_TEST_EXPECT_ROOT").is_some() {
assert_eq!(uzers::get_effective_uid(), 0);
assert!(std::env::var_os("SUDO_UID").is_some());
assert!(std::env::var_os("WAYLAND_DISPLAY").is_none());
}
let (origin, worker) = gateway(vec![
("200 OK", saml_prelogin_response("old-region", "b2xk")),
("200 OK", saml_prelogin_response("new-region", "bmV3")),
])
.await;
let args = TestArgs::parse_from(["test", &origin]).connect;
let lock = directory.join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
let original = handler.refresh_auth_prelogin(&origin, false, false).await.unwrap();
let (replacement, credential) = handler
.obtain_credential_with_recovery(original, &origin, false)
.await
.unwrap();
assert_eq!(replacement.region(), "new-region");
assert!(matches!(credential, Credential::Prelogin(ref value) if value.prelogin_cookie() == Some("new-cookie")));
assert_eq!(
worker.await.unwrap().len(),
2,
"recovery must fetch fresh prelogin data"
);
}
}
+129 -10
View File
@@ -170,8 +170,8 @@ impl ConnectHandler<'_> {
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
result = prelogin(gateway, &gp_params, self.direct_gateway_prelogin_options()) => result?,
};
let cred = self
.obtain_credential(&prelogin, gateway, gateway_browser_auth_allowed)
let (_, cred) = self
.obtain_credential_with_recovery(prelogin, gateway, gateway_browser_auth_allowed)
.await?;
let login_session = self
@@ -262,6 +262,13 @@ impl ConnectHandler<'_> {
}
Err(error) => {
self.check_cancelled()?;
let error = self.auth_recovery.borrow().terminal(error);
if error
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
.is_some()
{
return Err(error);
}
if error
.downcast_ref::<gpapi::gateway::GatewayLoginProtocolError>()
.is_some()
@@ -273,8 +280,8 @@ impl ConnectHandler<'_> {
}
}
let credential = self
.obtain_credential(&gateway_prelogin, gateway, browser_allowed)
let (_, credential) = self
.obtain_credential_with_recovery(gateway_prelogin, gateway, browser_allowed)
.await
.inspect_err(|_| self.print_direct_gateway_recommendation(gateway))?;
self.check_cancelled()?;
@@ -477,6 +484,13 @@ impl ConnectHandler<'_> {
let disconnect_requested_on_signal = Arc::clone(&disconnect_requested);
let cancellation = self.cancellation.clone();
let mut background_stdio = self
.background
.as_ref()
.map(|background| background.redirect_stdio())
.transpose()
.map_err(GatewayConnectError::before_establishment)?;
let disconnect_task = tokio::spawn(async move {
cancellation.cancelled().await;
info!("Received the interrupt signal, disconnecting...");
@@ -490,7 +504,7 @@ impl ConnectHandler<'_> {
let session_cancellation = self.cancellation.clone();
let (established_tx, established_rx) = tokio::sync::oneshot::channel();
self.sessions.borrow_mut().relinquish_gateway(gateway);
let worker = tokio::task::spawn_blocking(move || {
let mut worker = tokio::task::spawn_blocking(move || {
vpn.connect(move |vpn_session_info| {
if session_cancellation.is_cancelled() {
return;
@@ -509,7 +523,7 @@ impl ConnectHandler<'_> {
session_task_on_connect.lock().unwrap().replace(task);
})
});
tokio::pin!(worker);
let mut background_error = None;
let connect_result = tokio::select! {
result = &mut worker => result,
established = established_rx => {
@@ -518,11 +532,26 @@ impl ConnectHandler<'_> {
.filter(|session| session.gateway.server() != gateway)
.map(|session| session.gateway.server().to_owned())
.collect::<Vec<_>>();
for server in unused {
self.logout_gateway(&server).await;
}
wait_for_tunnel_exit(&mut worker, async {
for server in unused {
self.logout_gateway(&server).await;
}
}, || {
if let (Some(background), Some(stdio)) = (&self.background, &mut background_stdio) {
let detach = if self.pid_written.load(Ordering::SeqCst) {
background.detach(stdio)
} else {
Err(anyhow::anyhow!("Cannot detach without a writable PID lock file"))
};
if let Err(error) = detach {
self.cancellation.cancel();
background_error = Some(error);
}
}
}).await
} else {
(&mut worker).await
}
(&mut worker).await
}
};
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
@@ -535,6 +564,10 @@ impl ConnectHandler<'_> {
let _ = task.await;
}
if let Some(error) = background_error {
return Err(GatewayConnectError::after_establishment(error));
}
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
let connect_result = connect_result.map_err(|error| GatewayConnectError::after_establishment(error.into()))?;
classify_openconnect_result(connect_result, tunnel_established, disconnect_requested)
@@ -577,6 +610,28 @@ impl ConnectHandler<'_> {
}
}
async fn wait_for_tunnel_exit(
worker: &mut JoinHandle<i32>,
cleanup: impl std::future::Future<Output = ()>,
on_ready: impl FnOnce(),
) -> Result<i32, tokio::task::JoinError> {
tokio::pin!(cleanup);
tokio::select! {
// A finished tunnel must not publish readiness, including when cleanup is
// also ready in the same poll.
biased;
result = &mut *worker => {
// Logout temporarily owns the session registry. Complete it even when
// the tunnel exits, so cancelling this future cannot discard sessions.
cleanup.await;
return result;
},
_ = &mut cleanup => {},
}
on_ready();
worker.await
}
fn classify_openconnect_result(
exit_code: i32,
tunnel_established: bool,
@@ -634,6 +689,70 @@ fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
mod tests {
use super::*;
#[tokio::test]
async fn tunnel_exit_during_startup_cleanup_does_not_publish_readiness() {
let (cleanup_started_tx, cleanup_started_rx) = tokio::sync::oneshot::channel();
let (worker_exited_tx, worker_exited_rx) = tokio::sync::oneshot::channel();
let mut worker = tokio::spawn(async move {
cleanup_started_rx.await.unwrap();
worker_exited_tx.send(()).unwrap();
7
});
let mut ready = false;
let result = tokio::time::timeout(
std::time::Duration::from_secs(5),
wait_for_tunnel_exit(
&mut worker,
async {
cleanup_started_tx.send(()).unwrap();
worker_exited_rx.await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
},
|| ready = true,
),
)
.await
.expect("Tunnel exit must preserve completed cleanup")
.unwrap();
assert_eq!(result, 7);
assert!(!ready, "An exited tunnel must not report background startup success");
}
#[tokio::test]
async fn finished_tunnel_takes_priority_over_finished_startup_cleanup() {
let mut worker = tokio::spawn(async { 7 });
while !worker.is_finished() {
tokio::task::yield_now().await;
}
let mut ready = false;
let result = wait_for_tunnel_exit(&mut worker, async {}, || ready = true)
.await
.unwrap();
assert_eq!(result, 7);
assert!(!ready, "A ready cleanup must not conceal a finished tunnel");
}
#[tokio::test]
async fn running_tunnel_publishes_readiness_after_startup_cleanup() {
let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
let mut worker = tokio::spawn(async move {
ready_rx.await.unwrap();
0
});
let cleanup_complete = AtomicBool::new(false);
let result = wait_for_tunnel_exit(
&mut worker,
async { cleanup_complete.store(true, Ordering::SeqCst) },
|| {
assert!(cleanup_complete.load(Ordering::SeqCst));
ready_tx.send(()).unwrap();
},
)
.await
.unwrap();
assert_eq!(result, 0);
}
#[test]
fn hip_script_defaults_to_inherited_process_identity() {
assert_eq!(get_uid(&None).unwrap(), None);
+7
View File
@@ -26,6 +26,10 @@ impl ConnectHandler<'_> {
first_session: super::gateway::GatewayLoginSession,
remaining: &[&Gateway],
) -> anyhow::Result<()> {
ensure!(
self.background.is_none(),
"--background requires a VPN tunnel; internal non-tunnel sessions must run in the foreground"
);
ensure!(remaining.len() < 64, "Too many internal non-tunnel candidates");
let mut hosts = std::collections::HashSet::new();
for gateway in std::iter::once(first_gateway).chain(remaining.iter().copied()) {
@@ -57,6 +61,9 @@ impl ConnectHandler<'_> {
Err(error) => {
self.logout_gateway(gateway.server()).await;
self.check_cancelled()?;
if self.auth_recovery.borrow().dmabuf_disabled() {
return Err(self.auth_recovery.borrow().terminal(error));
}
warn!("Internal gateway {gateway} authentication failed: {error}");
}
}
+36 -5
View File
@@ -41,8 +41,12 @@ pub(crate) struct ConnectHandler<'a> {
password_from_stdin: RefCell<Option<String>>,
cookie_from_stdin: RefCell<Option<String>>,
clean_auth_state: RefCell<CleanAuthState>,
#[cfg(test)]
auth_attempt_fixture: RefCell<credential::AuthAttemptFixture>,
auth_recovery: RefCell<gpapi::process::rendering_recovery::RecoveryState>,
sessions: RefCell<GatewaySessions>,
pid_written: Arc<AtomicBool>,
background: Option<crate::background::BackgroundWorker>,
}
impl<'a> ConnectHandler<'a> {
@@ -63,11 +67,20 @@ impl<'a> ConnectHandler<'a> {
password_from_stdin: Default::default(),
cookie_from_stdin: Default::default(),
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
#[cfg(test)]
auth_attempt_fixture: Default::default(),
auth_recovery: RefCell::default(),
sessions: RefCell::default(),
pid_written: Arc::default(),
background: None,
}
}
pub(crate) fn with_background(mut self, background: Option<crate::background::BackgroundWorker>) -> Self {
self.background = background;
self
}
fn build_gp_params(&self) -> GpParams {
let mut builder = GpParams::builder(self.os_profile.borrow().clone());
builder
@@ -112,6 +125,7 @@ impl<'a> ConnectHandler<'a> {
gpapi::utils::shutdown_signal().await;
cancellation.cancel();
});
self.auth_recovery.replace(Default::default());
let result = self.handle_attempt().await;
let sessions = self.sessions.take();
if self.args.cookie_only && result.is_ok() {
@@ -153,10 +167,17 @@ impl<'a> ConnectHandler<'a> {
loop {
self.check_cancelled()?;
let Err(err) = self.handle_impl().await else {
let result = self.handle_impl().await;
let Err(err) = self.auth_recovery.borrow().finish(result) else {
return Ok(());
};
if err
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
.is_some()
{
return Err(err);
}
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
return Err(err);
};
@@ -212,6 +233,13 @@ impl<'a> ConnectHandler<'a> {
return Ok(());
};
let err = self.auth_recovery.borrow().terminal(err);
if err
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
.is_some()
{
return Err(err);
}
warn!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow...");
@@ -238,7 +266,7 @@ impl<'a> ConnectHandler<'a> {
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
let gp_params = self.build_gp_params();
let prelogin = tokio::select! {
let mut prelogin = tokio::select! {
biased;
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
result = prelogin(portal, &gp_params, self.prelogin_options(false)) => result?,
@@ -260,7 +288,10 @@ impl<'a> ConnectHandler<'a> {
let (cred, mut portal_config) = match cached_config {
Some(result) => result,
None => {
let cred = self.obtain_credential(&prelogin, portal, false).await?;
let (replacement, cred) = self
.obtain_credential_with_recovery(prelogin.clone(), portal, false)
.await?;
prelogin = replacement;
self.check_cancelled()?;
let config = retrieve_config(portal, &cred, &gp_params, &self.cancellation).await?;
(cred, config)
@@ -305,8 +336,8 @@ impl<'a> ConnectHandler<'a> {
Ok(()) => return Ok(()),
Err(err) => {
self.logout_gateway(gateway.server()).await;
if !err.is_before_establishment() {
return Err(err.into_error());
if self.auth_recovery.borrow().dmabuf_disabled() || !err.is_before_establishment() {
return Err(self.auth_recovery.borrow().terminal(err.into_error()));
}
warn!(
"Auto-gateway: gateway {} failed before session establishment: {}",
+285
View File
@@ -0,0 +1,285 @@
use std::{
collections::BTreeMap, fs::OpenOptions, io::Write, os::unix::fs::OpenOptionsExt, path::PathBuf, process::Stdio,
};
use anyhow::{Context, ensure};
use clap::Args;
use common::binary_paths;
use serde::Serialize;
use tokio::{io::AsyncWriteExt, process::Command};
const COLLECTOR: &str = include_str!("../../../scripts/collect-diagnostics.sh");
const MAX_REPORT_BYTES: usize = 64 * 1024;
const FIELDS: &[&str] = &[
"os",
"os_version",
"kernel",
"architecture",
"execution_user",
"ssh_session",
"virtualization",
"gpclient_path",
"gpclient_version",
"gpauth_path",
"gpauth_version",
"gpgui_path",
"gpgui_version",
"display_protocol",
"graphics",
"graphics_packages",
"desktop_version",
"env.XDG_CURRENT_DESKTOP",
"env.XDG_SESSION_DESKTOP",
"env.XDG_SESSION_TYPE",
"env.DESKTOP_SESSION",
"env.WEBKIT_DISABLE_DMABUF_RENDERER",
"env.WEBKIT_DISABLE_COMPOSITING_MODE",
"env.LIBGL_ALWAYS_SOFTWARE",
"env.__NV_DISABLE_EXPLICIT_SYNC",
"env.GDK_BACKEND",
"env.GDK_GL",
];
#[derive(Args)]
pub(crate) struct DiagnosticsArgs {
/// Print the report as JSON instead of text
#[arg(long)]
json: bool,
/// Save the report to a new file instead of stdout (existing files are preserved)
#[arg(long, value_name = "PATH")]
output: Option<PathBuf>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
enum ProbeStatus {
Ok,
Unset,
Unavailable,
Failed,
TimedOut,
NotApplicable,
}
#[derive(Debug, Serialize)]
struct DiagnosticField {
status: ProbeStatus,
value: Option<String>,
}
#[derive(Debug, Serialize)]
struct DiagnosticsReport {
schema_version: u32,
fields: BTreeMap<String, DiagnosticField>,
}
impl DiagnosticsReport {
fn parse(bytes: &[u8]) -> anyhow::Result<Self> {
ensure!(
bytes.len() <= MAX_REPORT_BYTES,
"Diagnostics report exceeds its size limit"
);
let mut fields = BTreeMap::new();
let mut schema_version = None;
for raw_line in bytes.split(|byte| *byte == b'\n').filter(|line| !line.is_empty()) {
let line = String::from_utf8_lossy(raw_line);
let (name, rest) = line.split_once(": ").context("Invalid diagnostics record")?;
let (status, value) = rest.split_once(": ").context("Invalid diagnostics status")?;
let raw_value_length = raw_line
.len()
.checked_sub(name.len() + status.len() + 4)
.context("Invalid diagnostics framing")?;
ensure!(raw_value_length <= 512, "Diagnostics field exceeds its size limit");
ensure!(
!value.chars().any(|c| c.is_ascii_control()),
"Invalid diagnostics value"
);
let status = match status {
"ok" => ProbeStatus::Ok,
"unset" => ProbeStatus::Unset,
"unavailable" => ProbeStatus::Unavailable,
"failed" => ProbeStatus::Failed,
"timed_out" => ProbeStatus::TimedOut,
"not_applicable" => ProbeStatus::NotApplicable,
_ => anyhow::bail!("Unknown diagnostics status"),
};
if name == "schema_version" {
ensure!(schema_version.is_none(), "Duplicate diagnostics schema version");
ensure!(
matches!(status, ProbeStatus::Ok) && value == "1",
"Unsupported diagnostics schema"
);
schema_version = Some(1);
continue;
}
ensure!(FIELDS.contains(&name), "Unknown diagnostics field");
let value = if matches!(status, ProbeStatus::Ok) {
let mut normalized = String::new();
for character in value.chars() {
let character = if character.is_control() { ' ' } else { character };
if normalized.len() + character.len_utf8() > 512 {
break;
}
normalized.push(character);
}
Some(normalized)
} else {
ensure!(value.is_empty(), "Unexpected value for unavailable diagnostics field");
None
};
ensure!(
fields
.insert(name.to_owned(), DiagnosticField { status, value })
.is_none(),
"Duplicate diagnostics field"
);
}
ensure!(fields.len() == FIELDS.len(), "Incomplete diagnostics report");
Ok(Self {
schema_version: schema_version.context("Missing diagnostics schema version")?,
fields,
})
}
fn text(&self) -> String {
let mut text = format!("schema_version: ok: {}\n", self.schema_version);
for name in FIELDS {
let field = &self.fields[*name];
let status = match field.status {
ProbeStatus::Ok => "ok",
ProbeStatus::Unset => "unset",
ProbeStatus::Unavailable => "unavailable",
ProbeStatus::Failed => "failed",
ProbeStatus::TimedOut => "timed_out",
ProbeStatus::NotApplicable => "not_applicable",
};
text.push_str(&format!(
"{name}: {status}: {}\n",
field.value.as_deref().unwrap_or_default()
));
}
text
}
}
impl DiagnosticsArgs {
pub(crate) async fn run(&self, version: &str) -> anyhow::Result<()> {
let mut child = Command::new("/bin/sh")
.args(["-s", "--", "--client-version", version, "--client-path"])
.arg(std::env::current_exe().context("Cannot locate gpclient")?)
.arg("--auth-path")
.arg(binary_paths::gpauth())
.arg("--gui-path")
.arg(binary_paths::gpgui())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true)
.spawn()
.context("Cannot start diagnostics collector")?;
let mut input = child.stdin.take().context("Collector input is unavailable")?;
let (_, output) = tokio::try_join!(
async move {
input.write_all(COLLECTOR.as_bytes()).await?;
drop(input);
Ok::<_, std::io::Error>(())
},
child.wait_with_output(),
)
.context("Diagnostics collection failed")?;
ensure!(
output.status.success(),
"Diagnostics collector exited with {}",
output.status
);
let report = DiagnosticsReport::parse(&output.stdout)?;
let content = if self.json {
format!("{}\n", serde_json::to_string_pretty(&report)?)
} else {
report.text()
};
if let Some(path) = &self.output {
save_report(path, &content)?;
} else {
std::io::stdout().lock().write_all(content.as_bytes())?;
}
Ok(())
}
}
fn save_report(path: &std::path::Path, content: &str) -> anyhow::Result<()> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
.context("Cannot create diagnostics file; use a new path")?;
file
.write_all(content.as_bytes())
.context("Cannot save diagnostics report")
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_report() -> String {
let mut text = String::from("schema_version: ok: 1\n");
for name in FIELDS {
text.push_str(&format!("{name}: unavailable: \n"));
}
text
}
#[test]
fn json_preserves_collected_values_and_distinguishes_missing_probes() {
let text = sample_report().replace("os: unavailable: ", "os: ok: FreeBSD");
let report = DiagnosticsReport::parse(text.as_bytes()).unwrap();
let json = serde_json::to_value(report).unwrap();
assert_eq!(json["schema_version"], 1);
assert_eq!(json["fields"]["os"]["value"], "FreeBSD");
assert_eq!(json["fields"]["graphics"]["status"], "unavailable");
assert!(json["fields"]["graphics"]["value"].is_null());
}
#[test]
fn malformed_or_injected_records_are_rejected() {
let good = sample_report();
for bad in [
good.replace("os: unavailable: ", "os: mystery: "),
good.replace("os: unavailable: ", "os: ok: text\u{1b}[31m"),
good.replace("os: unavailable: ", "os: ok: value\nsecret: ok: token"),
format!("{good}os: ok: duplicate\n"),
good.replace("schema_version: ok: 1", "schema_version: ok: 2"),
good.replace("os: unavailable: \n", ""),
] {
assert!(DiagnosticsReport::parse(bad.as_bytes()).is_err());
}
}
#[test]
fn invalid_utf8_and_unicode_controls_produce_a_bounded_readable_value() {
let mut bytes = sample_report()
.replace("os: unavailable: ", "os: ok: REPLACE")
.into_bytes();
let start = bytes.windows(7).position(|value| value == b"REPLACE").unwrap();
bytes.splice(start..start + 7, [0xff; 500]);
let report = DiagnosticsReport::parse(&bytes).unwrap();
let value = report.fields["os"].value.as_ref().unwrap();
assert!(value.len() <= 512);
assert!(value.starts_with('\u{fffd}'));
let text = sample_report().replace("os: unavailable: ", "os: ok: Test\u{85}OS");
let report = DiagnosticsReport::parse(text.as_bytes()).unwrap();
assert_eq!(report.fields["os"].value.as_deref(), Some("Test OS"));
assert!(report.text().contains("os: ok: Test OS"));
}
#[test]
fn saving_a_report_does_not_overwrite_existing_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("diagnostics.txt");
save_report(&path, "first").unwrap();
assert!(save_report(&path, "second").is_err());
assert_eq!(std::fs::read_to_string(path).unwrap(), "first");
}
}
+10 -9
View File
@@ -26,16 +26,19 @@ impl<'a> DisconnectHandler<'a> {
pub async fn handle(&self) -> anyhow::Result<()> {
// Try to disconnect the CLI client
if let Ok(c) = fs::read_to_string(self.lock_file) {
send_signal(c.trim(), Signal::Interrupt).unwrap_or_else(|err| {
let cli_signalled = match fs::read_to_string(self.lock_file) {
Ok(c) => send_signal(c.trim(), Signal::Interrupt).unwrap_or_else(|err| {
warn!("Failed to send signal to client: {}", err);
});
false
}),
Err(_) => false,
};
// Try to disconnect the GUI service
if let Ok(c) = gpservice_lock_info().await {
if !cli_signalled && let Ok(c) = gpservice_lock_info().await {
send_signal(&c.pid.to_string(), Signal::User1).unwrap_or_else(|err| {
warn!("Failed to send signal to service: {}", err);
false
});
};
@@ -48,16 +51,14 @@ impl<'a> DisconnectHandler<'a> {
}
}
fn send_signal(pid: &str, signal: Signal) -> anyhow::Result<()> {
fn send_signal(pid: &str, signal: Signal) -> anyhow::Result<bool> {
let s = System::new_all();
let pid = Pid::from_str(pid)?;
if let Some(process) = s.process(pid) {
info!("Found process {}, sending signal...", pid);
if process.kill_with(signal).is_none() {
warn!("Failed to kill process {}", pid);
}
return Ok(process.kill_with(signal).unwrap_or(false));
}
Ok(())
Ok(false)
}
+2
View File
@@ -1,5 +1,7 @@
mod background;
mod cli;
mod connect;
mod diagnostics;
mod disconnect;
mod hip;
mod launch_gui;
+71
View File
@@ -0,0 +1,71 @@
use std::{os::unix::fs::PermissionsExt, process::Stdio, time::Duration};
use tokio::process::Command;
fn executable(dir: &std::path::Path, name: &str, body: &str) {
let path = dir.join(name);
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
#[tokio::test]
async fn embedded_collector_reports_missing_helpers_without_recursing_or_exposing_private_environment() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("bin");
std::fs::create_dir(&bin).unwrap();
executable(
&bin,
"uname",
"case \"$1\" in -s) echo Linux ;; -m) echo aarch64 ;; *) echo test-kernel ;; esac",
);
executable(&bin, "gpclient", "echo unexpected-recursion >&2; exit 99");
executable(&bin, "systemd-detect-virt", "echo kvm");
executable(
&bin,
"lspci",
"echo '00:02.0 VGA compatible controller: Test GPU'; echo ' Kernel driver in use: test'",
);
executable(&bin, "pacman", "echo 'gtk3 test-version'");
let report_file = dir.path().join("report.json");
let output = tokio::time::timeout(
Duration::from_secs(30),
Command::new(env!("CARGO_BIN_EXE_gpclient"))
.args(["--fix-openssl", "diagnostics", "--json", "--output"])
.arg(&report_file)
.env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
.env("GP_AUTH_BINARY", dir.path().join("missing-gpauth"))
.env("GP_GUI_BINARY", dir.path().join("missing-gpgui"))
.env("GP_DIAGNOSTICS_PRIVATE_TOKEN", "secret-value-must-not-appear")
.env("XDG_CURRENT_DESKTOP", "TestDesktop\nInjected: secret")
.stdin(Stdio::null())
.kill_on_drop(true)
.output(),
)
.await
.expect("collector must close stdin and terminate")
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
assert!(output.stdout.is_empty());
let text = std::fs::read_to_string(&report_file).unwrap();
assert!(!text.contains("secret-value-must-not-appear"));
assert!(!String::from_utf8_lossy(&output.stderr).contains("unexpected-recursion"));
let report: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(report["schema_version"], 1);
assert_eq!(report["fields"]["os"]["value"], "Linux");
assert_eq!(report["fields"]["gpclient_path"]["status"], "ok");
for field in ["gpauth_path", "gpauth_version", "gpgui_path", "gpgui_version"] {
assert_eq!(report["fields"][field]["status"], "unavailable");
assert!(report["fields"][field]["value"].is_null());
}
assert!(
report["fields"]["gpclient_version"]["value"]
.as_str()
.unwrap()
.starts_with(env!("CARGO_PKG_VERSION"))
);
assert_eq!(
report["fields"]["env.XDG_CURRENT_DESKTOP"]["value"],
"TestDesktop Injected: secret"
);
assert!(!String::from_utf8_lossy(&output.stderr).contains("Using 'UnsafeLegacyServerConnect'"));
}
-9
View File
@@ -1,9 +0,0 @@
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=e((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function ee(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,x||(x=!0,ie());else{var t=n(l);t!==null&&se(ee,t.startTime-e)}}}var x=!1,te=-1,ne=5,S=-1;function re(){return g?!0:!(e.unstable_now()-S<ne)}function C(){if(g=!1,x){var t=e.unstable_now();S=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(te),te=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&re());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&se(ee,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?ie():x=!1}}}var ie;if(typeof y==`function`)ie=function(){y(C)};else if(typeof MessageChannel<`u`){var ae=new MessageChannel,oe=ae.port2;ae.port1.onmessage=C,ie=function(){oe.postMessage(null)}}else ie=function(){_(C,0)};function se(t,n){te=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):ne=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(te),te=-1):h=!0,se(ee,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,x||(x=!0,ie()))),r},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),n=e(((e,n)=>{n.exports=t()})),r=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){Line truncated
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
`+ze+e+Be}var He=!1;function Ue(e,t){if(!e||He)return``;He=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}n=!1;try{var i=Object.getOwnPropertyDescriptor(e.prototype,`props`);Object.defineProperty(e.prototype,"props",{configurable:!0,set:function(){throw Error()}}),n=!0,new e}finally{n&&(i===void 0?delete e.prototype.props:Object.defineProperty(e.prototype,"props",i))}}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
`),l=s.split(`
`);for(i=r=0;r<c.length&&!c[r].includes(`DetermineComponentFrameRoot`);)r++;for(;i<l.length&&!l[i].includes(`DetermineComponentFrameRoot`);)i++;if(r===c.length||i===l.length)for(r=c.length-1,i=l.length-1;1<=r&&0<=i&&c[r]!==l[i];)i--;for(;1<=r&&0<=i;r--,i--)if(c[r]!==l[i]){if(r!==1||i!==1)do if(r--,i--,0>i||c[r]!==l[i]){var u=`
`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(`<anonymous>`)&&(u=u.replace(`<anonymous>`,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{He=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Ve(n):``}function We(e,t){switch(e.tag){case 26:case 27:case 5:return Ve(e.type);case 16:return Ve(`Lazy`);case 13:return e.child!==t&&t!==null?Ve(`Suspense Fallback`):Ve(`Suspense`);case 19:return Ve(`SuspenseList`);case 0:case 15:return Ue(e.type,!1);case 11:return Ue(e.type.render,!1);case 1:return Ue(e.type,!0);case 31:return Ve(`Activity`);case 30:return Ve(`ViewTransition`);default:return``}}function Ge(e){try{var t=``,n=null;do t+=We(e,n),n=e,e=e.return;while(e);return t}catch(e){return`
Error generating stack: `+e.message+`
`+e.stack}}var Ke=Object.prototype.hasOwnProperty,qe=t.unstable_scheduleCallback,Je=t.unstable_cancelCallback,Ye=t.unstable_shouldYield,Xe=t.unstable_requestPaint,Ze=t.unstable_now,Qe=t.unstable_getCurrentPriorityLevel,$e=t.unstable_ImmediatePriority,et=t.unstable_UserBlockingPriority,tt=t.unstable_NormalPriority,nt=t.unstable_LowPriority,rt=t.unstable_IdlePriority,it=t.log,at=t.unstable_setDisableYieldValue,ot=null,st=null;function ct(e){if(typeof it==`function`&&at(e),st&&typeof st.setStrictMode==`function`)try{st.setStrictMode(ot,e)}catch{}}var lt=Math.clz32?Math.clz32:ft,ut=Math.log,dt=Math.LN2;function ft(e){return e>>>=0,e===0?32:31-(ut(e)/dt|0)|0}var pt=256,mt=262144,ht=4194304;function gt(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function _t(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=gt(n))):i=gt(o):i=gt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=gt(n))):i=gt(o)):i=gt(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function vt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function yt(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0<n;){var r=31-lt(n),i=1<<r;t|=e[r],n&=~i}return t}function bt(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function xt(){var e=ht;return ht<<=1,!(ht&62914560)&&(ht=4194304),e}function St(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ct(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function wt(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0<n;){var u=31-lt(n),d=1<<u;s[u]=0,c[u]=-1;var f=l[u];if(f!==null)for(l[u]=null,u=0;u<f.length;u++){var p=f[u];p!==null&&(p.lane&=-536870913)}n&=~d}r!==0&&Tt(e,r,0),a!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=a&~(o&~t))}function Tt(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-lt(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function Et(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-lt(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function Dt(e,t){var n=t&-t;return n=n&42?1:Ot(n),(n&(e.suspendedLanes|t))===0?n:0}function Ot(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function kt(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function At(){var e=E.p;return e===0?(e=window.event,e===void 0?32:Ch(e.type)):e}function jt(e,t){var n=E.p;try{return E.p=e,t()}finally{E.p=n}}var Mt=Math.random().toString(36).slice(2),Nt=`__reactFiber$`+Mt,Pt=`__reactProps$`+Mt,Ft=`__reactContainer$`+Mt,It=`__reactEvents$`+Mt,Lt=`__reactListeners$`+Mt,Rt=`__reactHandles$`+Mt,zt=`__reactResources$`+Mt,Bt=`__reactMarker$`+Mt,Vt=`__reactLoad$`+Mt;function Ht(e){delete e[Nt],delete e[Pt],delete e[Lt],delete e[Rt]}function Ut(e){var t;if(t=e[Nt])return t;for(var n=e.parentNode;n;){if(t=n[Ft]||n[Nt]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=fm(e);e!==null;){if(n=e[Nt])return n;e=fm(e)}return t}e=n,n=e.parentNode}return null}function Wt(e){if(e=e[Nt]||e[Ft]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function Gt(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(s(33))}function Kt(e){var t=e[zt];return t||=e[zt]={hoistableStyles:new Map,hoistableScripts:new Map},t}function qt(e){e[Bt]=!0}function Jt(e){e[Vt]=void 0}var Yt=new Set,Xt={};function Zt(e,t){Qt(e,t),Qt(e+`Capture`,t)}function Qt(e,t){for(Xt[e]=t,e=0;e<t.le Line truncated
`).replace(Qf,``)}function ep(e,t){return t=$f(t),$f(e)===t}function $(e,t,n,r,i,a){switch(n){case`children`:if(typeof r==`string`)t===`body`||t===`textarea`&&r===``||xn(e,r);else if(typeof r==`number`||typeof r==`bigint`)t!==`body`&&xn(e,``+r);else return;break;case`className`:on(e,`class`,r);break;case`tabIndex`:on(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:on(e,n,r);break;case`style`:wn(e,r,a);return;case`data`:if(t!==`object`){on(e,`data`,r);break}case`src`:case`href`:if(r===``&&(t!==`a`||n!==`href`)){e.removeAttribute(n);break}if(r==null||typeof r==`function`||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=On(r),e.setAttribute(n,r);break;case`action`:case`formAction`:if(typeof r==`function`){e.setAttribute(n,`javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')`);break}if(typeof a==`function`&&(n===`formAction`?(t!==`input`&&$(e,t,`name`,i.name,i,null),$(e,t,`formEncType`,i.formEncType,i,null),$(e,t,`formMethod`,i.formMethod,i,null),$(e,t,`formTarget`,i.formTarget,i,null)):($(e,t,`encType`,i.encType,i,null),$(e,t,`method`,i.method,i,null),$(e,t,`target`,i.target,i,null))),r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=On(r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=kn);return;case`onScroll`:r!=null&&Q(`scroll`,e);return;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);return;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(s(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(s(60));a?.__html!==n&&(e.innerHTML=n)}}break;case`multiple`:e.multiple=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`muted`:e.muted=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`defaultValue`:case`defaultChecked`:case`innerHTML`:case`ref`:break;case`autoFocus`:break;case`xlinkHref`:if(r==null||typeof r==`function`||typeof r==`boolean`||typeof r==`symbol`){e.removeAttribute(`xlink:href`);break}n=On(r),e.setAttributeNS(`http://www.w3.org/1999/xlink`,`xlink:href`,n);break;case`contentEditable`:case`spellCheck`:case`draggable`:case`value`:case`autoReverse`:case`externalResourcesRequired`:case`focusable`:case`preserveAlpha`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`inert`:case`allowFullScreen`:case`async`:case`autoPlay`:case`controls`:case`credentialless`:case`default`:case`defer`:case`disabled`:case`disablePictureInPicture`:case`disableRemotePlayback`:case`formNoValidate`:case`hidden`:case`loop`:case`noModule`:case`noValidate`:case`open`:case`playsInline`:case`readOnly`:case`required`:case`reversed`:case`scoped`:case`seamless`:case`itemScope`:r&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``):e.removeAttribute(n);break;case`capture`:case`download`:!0===r?e.setAttribute(n,``):!1!==r&&r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`cols`:case`rows`:case`size`:case`span`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case`rowSpan`:case`start`:r==null||typeof r==`function`||typeof r==`symbol`||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case`popover`:Q(`beforetoggle`,e),Q(`toggle`,e),an(e,`popover`,r);break;case`xlinkActuate`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:an(e,`is`,r);break;case`innerText`:case`textContent`:return;default:if(!(2<n.length)||n[0]!==`o`&&n[0]!==`O`||n[1]!==`n`&&n[1]!==`N`)n=En.get(n)||n,an(e,n,r);else return}O=!0}function tp(e,t,n,r,i,a){switch(n){case`style`:wn(e,r,a);return;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(s(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(s(60));a?.__html!==n&&(e.innerHTML=n)}}break;case`children`:if(typeof r==`string`)xn(e,r);else if(typeof r==`number`||typeof r==`bigint`)xn(e,``+r);else return;break;case`onScroll`:r!=null&&Q(`scroll`,e);return;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);return;case`onClick`:r!=null&&(e.onclick=k Line truncated
+9
View File
@@ -0,0 +1,9 @@
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=e((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function ee(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,x||(x=!0,ie());else{var t=n(l);t!==null&&se(ee,t.startTime-e)}}}var x=!1,te=-1,ne=5,S=-1;function re(){return g?!0:!(e.unstable_now()-S<ne)}function C(){if(g=!1,x){var t=e.unstable_now();S=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(te),te=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&re());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&se(ee,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?ie():x=!1}}}var ie;if(typeof y==`function`)ie=function(){y(C)};else if(typeof MessageChannel<`u`){var ae=new MessageChannel,oe=ae.port2;ae.port1.onmessage=C,ie=function(){oe.postMessage(null)}}else ie=function(){_(C,0)};function se(t,n){te=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):ne=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(te),te=-1):h=!0,se(ee,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,x||(x=!0,ie()))),r},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),n=e(((e,n)=>{n.exports=t()})),r=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){Line truncated
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
`+ze+e+Be}var He=!1;function Ue(e,t){if(!e||He)return``;He=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}n=!1;try{var i=Object.getOwnPropertyDescriptor(e.prototype,`props`);Object.defineProperty(e.prototype,"props",{configurable:!0,set:function(){throw Error()}}),n=!0,new e}finally{n&&(i===void 0?delete e.prototype.props:Object.defineProperty(e.prototype,"props",i))}}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
`),l=s.split(`
`);for(i=r=0;r<c.length&&!c[r].includes(`DetermineComponentFrameRoot`);)r++;for(;i<l.length&&!l[i].includes(`DetermineComponentFrameRoot`);)i++;if(r===c.length||i===l.length)for(r=c.length-1,i=l.length-1;1<=r&&0<=i&&c[r]!==l[i];)i--;for(;1<=r&&0<=i;r--,i--)if(c[r]!==l[i]){if(r!==1||i!==1)do if(r--,i--,0>i||c[r]!==l[i]){var u=`
`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(`<anonymous>`)&&(u=u.replace(`<anonymous>`,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{He=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Ve(n):``}function We(e,t){switch(e.tag){case 26:case 27:case 5:return Ve(e.type);case 16:return Ve(`Lazy`);case 13:return e.child!==t&&t!==null?Ve(`Suspense Fallback`):Ve(`Suspense`);case 19:return Ve(`SuspenseList`);case 0:case 15:return Ue(e.type,!1);case 11:return Ue(e.type.render,!1);case 1:return Ue(e.type,!0);case 31:return Ve(`Activity`);case 30:return Ve(`ViewTransition`);default:return``}}function Ge(e){try{var t=``,n=null;do t+=We(e,n),n=e,e=e.return;while(e);return t}catch(e){return`
Error generating stack: `+e.message+`
`+e.stack}}var Ke=Object.prototype.hasOwnProperty,qe=t.unstable_scheduleCallback,Je=t.unstable_cancelCallback,Ye=t.unstable_shouldYield,Xe=t.unstable_requestPaint,Ze=t.unstable_now,Qe=t.unstable_getCurrentPriorityLevel,$e=t.unstable_ImmediatePriority,et=t.unstable_UserBlockingPriority,tt=t.unstable_NormalPriority,nt=t.unstable_LowPriority,rt=t.unstable_IdlePriority,it=t.log,at=t.unstable_setDisableYieldValue,ot=null,st=null;function ct(e){if(typeof it==`function`&&at(e),st&&typeof st.setStrictMode==`function`)try{st.setStrictMode(ot,e)}catch{}}var lt=Math.clz32?Math.clz32:ft,ut=Math.log,dt=Math.LN2;function ft(e){return e>>>=0,e===0?32:31-(ut(e)/dt|0)|0}var pt=256,mt=262144,ht=4194304;function gt(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function _t(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=gt(n))):i=gt(o):i=gt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=gt(n))):i=gt(o)):i=gt(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function vt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function yt(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0<n;){var r=31-lt(n),i=1<<r;t|=e[r],n&=~i}return t}function bt(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function xt(){var e=ht;return ht<<=1,!(ht&62914560)&&(ht=4194304),e}function St(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ct(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function wt(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0<n;){var u=31-lt(n),d=1<<u;s[u]=0,c[u]=-1;var f=l[u];if(f!==null)for(l[u]=null,u=0;u<f.length;u++){var p=f[u];p!==null&&(p.lane&=-536870913)}n&=~d}r!==0&&Tt(e,r,0),a!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=a&~(o&~t))}function Tt(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-lt(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function Et(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-lt(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function Dt(e,t){var n=t&-t;return n=n&42?1:Ot(n),(n&(e.suspendedLanes|t))===0?n:0}function Ot(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function kt(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function At(){var e=E.p;return e===0?(e=window.event,e===void 0?32:Ch(e.type)):e}function jt(e,t){var n=E.p;try{return E.p=e,t()}finally{E.p=n}}var Mt=Math.random().toString(36).slice(2),Nt=`__reactFiber$`+Mt,Pt=`__reactProps$`+Mt,Ft=`__reactContainer$`+Mt,It=`__reactEvents$`+Mt,Lt=`__reactListeners$`+Mt,Rt=`__reactHandles$`+Mt,zt=`__reactResources$`+Mt,Bt=`__reactMarker$`+Mt,Vt=`__reactLoad$`+Mt;function Ht(e){delete e[Nt],delete e[Pt],delete e[Lt],delete e[Rt]}function Ut(e){var t;if(t=e[Nt])return t;for(var n=e.parentNode;n;){if(t=n[Ft]||n[Nt]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=fm(e);e!==null;){if(n=e[Nt])return n;e=fm(e)}return t}e=n,n=e.parentNode}return null}function Wt(e){if(e=e[Nt]||e[Ft]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function Gt(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(s(33))}function Kt(e){var t=e[zt];return t||=e[zt]={hoistableStyles:new Map,hoistableScripts:new Map},t}function qt(e){e[Bt]=!0}function Jt(e){e[Vt]=void 0}var Yt=new Set,Xt={};function Zt(e,t){Qt(e,t),Qt(e+`Capture`,t)}function Qt(e,t){for(Xt[e]=t,e=0;e<t.le Line truncated
`).replace(Qf,``)}function ep(e,t){return t=$f(t),$f(e)===t}function $(e,t,n,r,i,a){switch(n){case`children`:if(typeof r==`string`)t===`body`||t===`textarea`&&r===``||xn(e,r);else if(typeof r==`number`||typeof r==`bigint`)t!==`body`&&xn(e,``+r);else return;break;case`className`:on(e,`class`,r);break;case`tabIndex`:on(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:on(e,n,r);break;case`style`:wn(e,r,a);return;case`data`:if(t!==`object`){on(e,`data`,r);break}case`src`:case`href`:if(r===``&&(t!==`a`||n!==`href`)||r==null||typeof r==`function`||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=On(r),e.setAttribute(n,r);break;case`action`:case`formAction`:if(typeof r==`function`){e.setAttribute(n,`javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')`);break}if(typeof a==`function`&&(n===`formAction`?(t!==`input`&&$(e,t,`name`,i.name,i,null),$(e,t,`formEncType`,i.formEncType,i,null),$(e,t,`formMethod`,i.formMethod,i,null),$(e,t,`formTarget`,i.formTarget,i,null)):($(e,t,`encType`,i.encType,i,null),$(e,t,`method`,i.method,i,null),$(e,t,`target`,i.target,i,null))),r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=On(r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=kn);return;case`onScroll`:r!=null&&Q(`scroll`,e);return;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);return;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(s(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(s(60));a?.__html!==n&&(e.innerHTML=n)}}break;case`multiple`:e.multiple=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`muted`:e.muted=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`defaultValue`:case`defaultChecked`:case`innerHTML`:case`ref`:break;case`autoFocus`:break;case`xlinkHref`:if(r==null||typeof r==`function`||typeof r==`boolean`||typeof r==`symbol`){e.removeAttribute(`xlink:href`);break}n=On(r),e.setAttributeNS(`http://www.w3.org/1999/xlink`,`xlink:href`,n);break;case`contentEditable`:case`spellCheck`:case`draggable`:case`value`:case`autoReverse`:case`externalResourcesRequired`:case`focusable`:case`preserveAlpha`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`inert`:case`allowFullScreen`:case`async`:case`autoPlay`:case`controls`:case`credentialless`:case`default`:case`defer`:case`disabled`:case`disablePictureInPicture`:case`disableRemotePlayback`:case`formNoValidate`:case`hidden`:case`loop`:case`noModule`:case`noValidate`:case`open`:case`playsInline`:case`readOnly`:case`required`:case`reversed`:case`scoped`:case`seamless`:case`itemScope`:r&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``):e.removeAttribute(n);break;case`capture`:case`download`:!0===r?e.setAttribute(n,``):!1!==r&&r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`cols`:case`rows`:case`size`:case`span`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case`rowSpan`:case`start`:r==null||typeof r==`function`||typeof r==`symbol`||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case`popover`:Q(`beforetoggle`,e),Q(`toggle`,e),an(e,`popover`,r);break;case`xlinkActuate`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:an(e,`is`,r);break;case`innerText`:case`textContent`:return;default:if(!(2<n.length)||n[0]!==`o`&&n[0]!==`O`||n[1]!==`n`&&n[1]!==`N`)n=En.get(n)||n,an(e,n,r);else return}O=!0}function tp(e,t,n,r,i,a){switch(n){case`style`:wn(e,r,a);return;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(s(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(s(60));a?.__html!==n&&(e.innerHTML=n)}}break;case`children`:if(typeof r==`string`)xn(e,r);else if(typeof r==`number`||typeof r==`bigint`)xn(e,``+r);else return;break;case`onScroll`:r!=null&&Q(`scroll`,e);return;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);return;case`onClick`:r!=null&&(e.onclick=kn);return;case`suppressContent Line truncated
+1 -1
View File
@@ -5,7 +5,7 @@
<link rel="icon" type="image/svg+xml" href="/assets/icon-small-BO4dlTNl.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GPGUI Downloader</title>
<script type="module" crossorigin src="/assets/main-B7u6_mhO.js"></script>
<script type="module" crossorigin src="/assets/main-BU3mus1z.js"></script>
<link rel="stylesheet" crossorigin href="/assets/main-DiWGniCh.css">
</head>
<body>
+7 -7
View File
@@ -9,25 +9,25 @@
"tauri": "tauri"
},
"dependencies": {
"@tauri-apps/api": "^2.12.1",
"@tauri-apps/api": "^2.12.3",
"react": "^19.3.0",
"react-dom": "^19.3.0"
},
"devDependencies": {
"@tauri-apps/cli": "^2.12.1",
"@types/node": "^26.6.4",
"@tauri-apps/cli": "^2.12.2",
"@types/node": "^26.6.5",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@typescript-eslint/eslint-plugin": "^8.71.1",
"@typescript-eslint/parser": "^8.71.1",
"@typescript-eslint/eslint-plugin": "^8.71.2",
"@typescript-eslint/parser": "^8.71.2",
"@vitejs/plugin-react": "^6.1.2",
"eslint": "^9.39.5",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.1.1",
"prettier": "3.9.9",
"prettier": "3.9.10",
"typescript": "^6.0.3",
"vite": "^8.3.3"
"vite": "^8.3.4"
},
"packageManager": "[email protected]"
}
+237 -237
View File
@@ -9,8 +9,8 @@ importers:
.:
dependencies:
'@tauri-apps/api':
specifier: ^2.12.1
version: 2.12.1
specifier: ^2.12.3
version: 2.12.3
react:
specifier: ^19.3.0
version: 19.3.0
@@ -19,11 +19,11 @@ importers:
version: 19.3.0([email protected])
devDependencies:
'@tauri-apps/cli':
specifier: ^2.12.1
version: 2.12.1
specifier: ^2.12.2
version: 2.12.2
'@types/node':
specifier: ^26.6.4
version: 26.6.4
specifier: ^26.6.5
version: 26.6.5
'@types/react':
specifier: ^19.3.0
version: 19.3.0
@@ -31,14 +31,14 @@ importers:
specifier: ^19.3.0
version: 19.3.0(@types/[email protected])
'@typescript-eslint/eslint-plugin':
specifier: ^8.71.1
version: 8.71.1(@typescript-eslint/[email protected].1([email protected])([email protected]))([email protected])([email protected])
specifier: ^8.71.2
version: 8.71.2(@typescript-eslint/[email protected].2([email protected])([email protected]))([email protected])([email protected])
'@typescript-eslint/parser':
specifier: ^8.71.1
version: 8.71.1([email protected])([email protected])
specifier: ^8.71.2
version: 8.71.2([email protected])([email protected])
'@vitejs/plugin-react':
specifier: ^6.1.2
version: 6.1.2([email protected].3(@types/[email protected].4)([email protected]))
version: 6.1.2([email protected].4(@types/[email protected].5)([email protected]))
eslint:
specifier: ^9.39.5
version: 9.39.5
@@ -52,14 +52,14 @@ importers:
specifier: ^7.1.1
version: 7.1.1([email protected])
prettier:
specifier: 3.9.9
version: 3.9.9
specifier: 3.9.10
version: 3.9.10
typescript:
specifier: ^6.0.3
version: 6.0.3
vite:
specifier: ^8.3.3
version: 8.3.3(@types/[email protected].4)([email protected])
specifier: ^8.3.4
version: 8.3.4(@types/[email protected].5)([email protected])
packages:
@@ -109,8 +109,8 @@ packages:
resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==}
engines: {node: '>=6.9.0'}
'@babel/[email protected].7':
resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==}
'@babel/[email protected].10':
resolution: {integrity: sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg==}
engines: {node: '>=6.9.0'}
'@babel/[email protected]':
@@ -122,8 +122,8 @@ packages:
resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==}
engines: {node: '>=6.9.0'}
'@babel/[email protected].8':
resolution: {integrity: sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==}
'@babel/[email protected].10':
resolution: {integrity: sha512-B3lYAs2nkKskbgQ1nfy8Ma9ao9Q1rntTAQHrzzyDuj+TSO+X3le6PfWwqDvodsb+OumE10eMFfuMCTQSQ5iuIQ==}
engines: {node: '>=6.9.0'}
'@babel/[email protected]':
@@ -360,95 +360,95 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
'@oxc-project/[email protected]2.0':
resolution: {integrity: sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==}
'@oxc-project/[email protected]3.0':
resolution: {integrity: sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==}
'@rolldown/[email protected]2':
resolution: {integrity: sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [android]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
'@rolldown/[email protected]2':
resolution: {integrity: sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==}
'@rolldown/[email protected]3':
resolution: {integrity: sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
@@ -456,77 +456,77 @@ packages:
'@rolldown/[email protected]':
resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-DeyFHa3wynpyoqTDikDEDGTJIq4LQ5USfolQGRmGIWT6JMADyxZBTDa5cAdT3tDg73rUXufPaCwN7aXBos4OnQ==}
'@tauri-apps/[email protected].3':
resolution: {integrity: sha512-9s0PKw0p4r3kFq92jhpivYSp+cSht15o0gXpZxuQd0+dV9KCexEVkNaLELVoLdJWyoH4KlfQo5h3W2LIM8siJg==}
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-8bMnbpJ2jKO/ufrOPL65EMHC3ptw7fzeraoQkwibyfGLqIl+UCWsC0152kmNbW6r9NvVQduXqAZF5mH1QgTWhw==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-Lk3zaBTfzNvA7670Al5PNgo2M/95uaDPe1yp+ILJeDOmol87XiYuK5E5+FUbK5e6U6OORx9qpZdOo2U+5tETtQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-G+2qte8GNqNlEZ9ftd21rbu/APVkl3r/nzNDI7LVxEoqJWVNe9GbEgQUMH1r4PHT20Z2UxR3KjCkltIb0e/Wjg==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-2CyYjJ833JB3sKRz4B0W/Tv4oOVC16ws1bxdSCWj1XvrmanWwvZi99e5tNIoCHwHhcOm0jh+sh0PCGQyls6Z+w==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-5b3n4DaTW+A1Zntnh4Yn44VyLrlPEpB8kMOBRfWkzNnzolBk+AYhKIfKjCLmoC8Mob3ETodxAEOMkE2YPKEWzQ==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-uvt2xbone4JftKarelssi86Kqnl7JiG1Smh5+Ae+nZmtM+JUhTGmqkcqfUPXRW8Ygwog92POZvd4oGDN9j8eXQ==}
engines: {node: '>= 10'}
cpu: [arm]
os: [linux]
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-APArHhDu+8pXSCkCQmvaz1nD3d8WTmlCoSS/oG475TJ6AATBvyQOAmf5qELgsQ4s2+8MOsop0Zd699RKELF1Cw==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-DZlDJ24u3tlocKOYqzR+b2M+Qr+5WFcoMBZ7EfdhHN5j3ZXwBBpms4G4gyNvPCrak5vMzmdZ65ecBXPJcC+5sA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-JaCxcLoV0oGtllVkLr4UAHWG/wTfkEunnUqnsEsGYOp0VRxnUwHg63wFBD0jU2ul5eFfSLIDS4RF2gfzsSo5Jg==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-pb+RTZUYH/p0gR4j4ecCCq+FNfz3W3eKuUQvVEBn7MQZx6DzfLO7FaYzt2NyDKWpdNN3lP10mdzOvw3R5P5aAQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-K5+VXM7+SGVDwZleA2+lMgvbTVuA5e1tkiVEawu1Yxj26ZyEfO8h8xTC1rBdRX2xgJDSwCk6vPUBCS6i+Z5slQ==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-nidEvDUJyHYNbIv9MUk6KiEix8IXfRh4Wj2G2SA5g8nFmgbBCwazUNWYiG/LhNeNbfZpBMLerRBUtoQ5K0GidA==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-Z1QGPr49HJZMktu+Spu6Q1b/f9ANadXvqZZZt2645ua1x1ev6prOgp85eiGv2jRzohFEMLo6aJyaLjLUX5KIvA==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-gkXyYn3w+Xfc8nz/DleEbkm1M7bBuU2cejqUXNmI98cA2P5kp+oPmS4ALTorb1FaNWjpsKoYZBWsbS9BXxYFkQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-nHuEhRPOMSJ/8RRhtMRxB9B9lVr7xxpe4DapBz8x1GIau3vdzjHHJ1hAfmw+PyayPLZ6XoaVIHPgI17rX6ii8w==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-MrjgoZ09s8Hsn99XvxSNvK8NQTZxi7XiyK3FxxytzfHgz2jb3qUT69CZtsokRkN/zdi9rCgrMtq+w9XNICjcfQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-I0oPk2uGh86R8dAs2X5OxSP+/GqSc8jh1Px3l8EqrocSNivsRHDTh2k3PVOqdv163dlV6PIVvmhZAbH/lPfZrA==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-BR+CYM7iF3lkfyTtVkwMQU/s9hwegLpj3UqDjaxKCPmixQCa1csBBPy3C75V+FhLtOjIXNna4Gt6Vm9oxbV+qA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-baNZRBfepAJ5qNFRMwzgBk94xQmkcmTZrNDjZjnzrq2vAaTC3NAhallb/zo3hyoCGQlMS13sdovktrg46NZz6Q==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-zODJo9l3TbNBM+GrO/yPqGeELNMK5cjIc+QHh1WQc3l8tD+jDZGTQyYuAxViCsM6Uh5uWJ//RnCZG9LXrvsXww==}
engines: {node: '>= 10'}
cpu: [ia32]
os: [win32]
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-dIFaKslrzcbesb+bBh+E1R9km241pHyj32w6D9FPtvQeYpRUFbiCLEa/2S+S0UnIytfxepp4P+X8IerGqnXeYg==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-cQXI2ZaZmwBDt0XATCqASVanYizxkEE3ceQVlVHXaQ51HzsQUWA04c9Nz7LrrY2lgAu3jFMyat+8Yz3Z2R2qBA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
'@tauri-apps/[email protected].1':
resolution: {integrity: sha512-kEDEiGzG+yAc5FeLxtXpES/VN+F2C8H0r4gDVtfRLKxT9np9101d9REG/Kgo2lr0hKi0IpDsODiHnU3+naOmLg==}
'@tauri-apps/[email protected].2':
resolution: {integrity: sha512-PMSppzAnlT+BvZtRKuidxjRSm2r5t8kDpJ/czmmQUa0AtDNTwrjLE8vApK3phCWGg7isfnYL46Dl1jB4ArI0hA==}
engines: {node: '>= 10'}
hasBin: true
@@ -536,8 +536,8 @@ packages:
'@types/[email protected]':
resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
'@types/[email protected].4':
resolution: {integrity: sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg==}
'@types/[email protected].5':
resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==}
'@types/[email protected]':
resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==}
@@ -547,63 +547,63 @@ packages:
'@types/[email protected]':
resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}
'@typescript-eslint/[email protected].1':
resolution: {integrity: sha512-nNlBf6HuotqMgZvSkWD5hNdemiBIxQ2NmrlgfcUIeZRs+BbakjscCQRq/Hb74EFVnFiSWWdL12JruqwBy3ERDw==}
'@typescript-eslint/[email protected].2':
resolution: {integrity: sha512-K72/pvT7qpm8q3k8G5u93NCSN1RcLxX5h7Gw0bQpbMXviBHeY6Nx1WEwmk9wP+eKTSQ8ecxvcgt/ZX/rB938xQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
'@typescript-eslint/parser': ^8.71.1
'@typescript-eslint/parser': ^8.71.2
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/[email protected].1':
resolution: {integrity: sha512-oM/5sAqz/l1v/zYK1qTOPrn2+JIrBGC1V6uNYucRO5gh6eT9vWJ/RhPbGE59byvZEUQ4VP6XkLBaS5Jti5jpvw==}
'@typescript-eslint/[email protected].2':
resolution: {integrity: sha512-aTtmZjp/x3gsGHkDs04/1I8kNogBJkpQaeGaN0PfiG43NzDEmW2n+OP5im9wfsvyX0yP1UZWBrAGtDBfH9jEVw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/[email protected].1':
resolution: {integrity: sha512-Oijc9RUsohHjncg6iGi7gCtjnEjYt9FWv9u6ygK8uKcHK5eLjLAkqERQ9BaytbpceOFdk6kifPCS/zAZE+A99g==}
'@typescript-eslint/[email protected].2':
resolution: {integrity: sha512-Pd68GsLVh5ZXlcEccFPdhSOvtHZ/2WU0XsA8zmXOS3F158lVlcTLhfQ6qvtL1RzbMie0Kp8xtbVwAg4nejKPHw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/[email protected].1':
resolution: {integrity: sha512-1YUDZXdTnXLlob03SFHBipdyMBsDVm7zoSz0ytTJ39dk5J1TgsTK03VlR/dLXG/RLLUrPcYbD4rp23BmHxHP0w==}
'@typescript-eslint/[email protected].2':
resolution: {integrity: sha512-YF4wgg5iUX5Obywoac27B56FhozMNFhdJSbh11H5GBAwmBtfyRhmgTQqW9tRNNmHDvsZ2CX6UGzoz+YfYn2Leg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@typescript-eslint/[email protected].1':
resolution: {integrity: sha512-oTvkml5SxXhgg+WWKhod5qWQICDXtOB+/Hi9VdPKFAANJ2b7YOgMffgvzXuqog7R6A/JtrzRf128dsxummyWhg==}
'@typescript-eslint/[email protected].2':
resolution: {integrity: sha512-jz49TAWokm/7yWD9/o837nYax9DyALxIPOImdImvVzo6canBCZYzin8zJyqNR5k1j9K1DE0bVvr0XYB+99uAdg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/[email protected].1':
resolution: {integrity: sha512-kH3t3jZCYv2PZSBEWPKTariLrCaoF1CLoPitYFBJOhAGEwWnSRAtGEifrfrpBa4K9JlwWNZotgA5w3/wLSk/FQ==}
'@typescript-eslint/[email protected].2':
resolution: {integrity: sha512-cC8UaalCViJkb3rH/xLIvidEwoFRtMZMUqDjjJMGEKaTFwYRHYBcoczlEGHuvkHEO8svRDrgZ0yQgOArFmwang==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/[email protected].1':
resolution: {integrity: sha512-ybYnPTUwg3VQQOFEiBPLs8Jxl1ry2vXdn1kVKguomBbvxpetdu3MKTNDqFNUrlG8ylP9MpZosmXMFYlGQHk1oQ==}
'@typescript-eslint/[email protected].2':
resolution: {integrity: sha512-y5Ukl3oVp7e/VGxqIoEXoeb/Roj71PAJ4WG/N/RGj+eeDvKRLM15kGr9MijLbN0i03S52zxu31Z98E5gWChJKw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@typescript-eslint/[email protected].1':
resolution: {integrity: sha512-pSKSEK1JJpHs6KiKVtABCE4iJK5d7FLFzDXQNBQ2oRY7LEd3UwOt3TZemTgu9syTIf56dJWlTn/pdmrO9oKUXQ==}
'@typescript-eslint/[email protected].2':
resolution: {integrity: sha512-DgNOEsl4pdYzwSL+N/Cl33tX1Hlw3FvId73LnKXfq7jnrF2viOEn7X+P7RBkkSWCVm92gnWd28GIC5vJuLREeA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/[email protected].1':
resolution: {integrity: sha512-CBjT6gfAz3DW2j9Q4moFnqt208Aq+506sVGXfpRcyAeqn0EpayL0mjdWoCO2t3RC7GewNrFxdeehuEaPg6DMzQ==}
'@typescript-eslint/[email protected].2':
resolution: {integrity: sha512-RyKa1G1M9rKHDhrk+HJtiF1MvLD5Ux2JW3TSkzw+02pRALdpJb+QzG1Y5em+LvCgzGwgg8H7mBRFKljNz7ImPw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.1.0'
'@typescript-eslint/[email protected].1':
resolution: {integrity: sha512-0GxiUGqMU0qXJt58cBsiG3DP8lUmBaFo2vChtUX+CT7PnR3v/VGLLrzVP4K9r1lNiZXjHYefMBbPunplr09v6w==}
'@typescript-eslint/[email protected].2':
resolution: {integrity: sha512-zozlN0UA32bSG2zkKAgQyRYSbEISVoyU6vvkKYo2aSny74D8Jh4e+POkJ6Lk0dlezZi5x7TtD+88Xb06IB8nhg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@vitejs/[email protected]':
@@ -685,8 +685,8 @@ packages:
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
engines: {node: 18 || 20 || >=22}
[email protected]7:
resolution: {integrity: sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==}
[email protected]8:
resolution: {integrity: sha512-br0LOmjJqr6Rt4AEkadbcNf67Zpo7EPwKsWbjnRrJIa1QYFHQBqM4C7F2WTbV8ahTEcg1Eo+Y0aWjjORInYFyA==}
engines: {node: '>=6.0.0'}
hasBin: true
@@ -718,8 +718,8 @@ packages:
resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}
engines: {node: '>=6'}
[email protected]4:
resolution: {integrity: sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==}
[email protected]5:
resolution: {integrity: sha512-uDybUEyfgbyJJ93J1vikTylBX31AkdVYeVPeffMQpf8XN7hSfr0oZOn4VFOIMNvtU5+rHvC5Udg2TgtJKHm23Q==}
[email protected]:
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
@@ -789,8 +789,8 @@ packages:
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
engines: {node: '>= 0.4'}
[email protected]49:
resolution: {integrity: sha512-dKeYk/3SFQz+nXi5whp3OuJzeWABEG4zCtkWJ9+Vby1E1iFM2y0gElRtQvNXRPJTsj8WAF4HMP7hvP790QtJ9g==}
[email protected]52:
resolution: {integrity: sha512-cVvk1YBSj6571VmV6hdJTqj94Y79xSu8cj6Y9t6ae4Y4431z8/7EJFvu3rVp90xhfuv9BpPKUmaLfTo4+FOGBg==}
[email protected]:
resolution: {integrity: sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg==}
@@ -1304,8 +1304,8 @@ packages:
resolution: {integrity: sha512-kXs9Go0cah0qHVV2v389IXQLdLCeE1xfFtjOAF+iobu0OIoG1pje8At2vMHyaPMiPMnG/LWP50twML21eMcAag==}
engines: {node: '>= 0.4'}
[email protected]7:
resolution: {integrity: sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==}
[email protected]8:
resolution: {integrity: sha512-BdiKAgbfRlvfMq/XzO/AF9NPmaA8a+YpLAyAFTVFBj3gARrAIfWvNq7Q7NE4se3KgFu0KkrvQMxTS0XVnsGzHg==}
engines: {node: '>=18'}
[email protected]:
@@ -1386,8 +1386,8 @@ packages:
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
engines: {node: '>= 0.8.0'}
[email protected].9:
resolution: {integrity: sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg==}
[email protected].10:
resolution: {integrity: sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==}
engines: {node: '>=14'}
hasBin: true
@@ -1427,8 +1427,8 @@ packages:
engines: {node: '>= 0.4'}
hasBin: true
[email protected]2:
resolution: {integrity: sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==}
[email protected]3:
resolution: {integrity: sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
@@ -1573,8 +1573,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==}
[email protected].3:
resolution: {integrity: sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==}
[email protected].4:
resolution: {integrity: sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==}
hasBin: true
peerDependencies:
browserslist: '>= 4.21.0'
@@ -1582,8 +1582,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
[email protected].3:
resolution: {integrity: sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg==}
[email protected].4:
resolution: {integrity: sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
peerDependencies:
@@ -1663,8 +1663,8 @@ packages:
peerDependencies:
zod: ^3.25.0 || ^4.0.0
[email protected].5:
resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==}
[email protected].6:
resolution: {integrity: sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA==}
snapshots:
@@ -1682,10 +1682,10 @@ snapshots:
'@babel/generator': 7.29.8
'@babel/helper-compilation-targets': 7.29.7
'@babel/helper-module-transforms': 7.29.7(@babel/[email protected])
'@babel/helpers': 7.29.7
'@babel/helpers': 7.29.10
'@babel/parser': 7.29.9
'@babel/template': 7.29.7
'@babel/traverse': 7.29.8
'@babel/traverse': 7.29.10
'@babel/types': 7.29.8
'@jridgewell/remapping': 2.3.5
convert-source-map: 2.0.0
@@ -1716,7 +1716,7 @@ snapshots:
'@babel/[email protected]':
dependencies:
'@babel/traverse': 7.29.8
'@babel/traverse': 7.29.10
'@babel/types': 7.29.8
transitivePeerDependencies:
- supports-color
@@ -1726,7 +1726,7 @@ snapshots:
'@babel/core': 7.29.7
'@babel/helper-module-imports': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
'@babel/traverse': 7.29.8
'@babel/traverse': 7.29.10
transitivePeerDependencies:
- supports-color
@@ -1736,7 +1736,7 @@ snapshots:
'@babel/[email protected]': {}
'@babel/[email protected].7':
'@babel/[email protected].10':
dependencies:
'@babel/template': 7.29.7
'@babel/types': 7.29.8
@@ -1751,7 +1751,7 @@ snapshots:
'@babel/parser': 7.29.9
'@babel/types': 7.29.8
'@babel/[email protected].8':
'@babel/[email protected].10':
dependencies:
'@babel/code-frame': 7.29.7
'@babel/generator': 7.29.8
@@ -1927,109 +1927,109 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.6.0
'@oxc-project/[email protected]2.0': {}
'@oxc-project/[email protected]3.0': {}
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]2':
'@rolldown/[email protected]3':
optional: true
'@rolldown/[email protected]': {}
'@tauri-apps/[email protected].1': {}
'@tauri-apps/[email protected].3': {}
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optional: true
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optional: true
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optional: true
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optional: true
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optional: true
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optional: true
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optional: true
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optional: true
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optional: true
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optional: true
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optional: true
'@tauri-apps/[email protected].1':
'@tauri-apps/[email protected].2':
optionalDependencies:
'@tauri-apps/cli-darwin-arm64': 2.12.1
'@tauri-apps/cli-darwin-x64': 2.12.1
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.1
'@tauri-apps/cli-linux-arm64-gnu': 2.12.1
'@tauri-apps/cli-linux-arm64-musl': 2.12.1
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.1
'@tauri-apps/cli-linux-x64-gnu': 2.12.1
'@tauri-apps/cli-linux-x64-musl': 2.12.1
'@tauri-apps/cli-win32-arm64-msvc': 2.12.1
'@tauri-apps/cli-win32-ia32-msvc': 2.12.1
'@tauri-apps/cli-win32-x64-msvc': 2.12.1
'@tauri-apps/cli-darwin-arm64': 2.12.2
'@tauri-apps/cli-darwin-x64': 2.12.2
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.2
'@tauri-apps/cli-linux-arm64-gnu': 2.12.2
'@tauri-apps/cli-linux-arm64-musl': 2.12.2
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.2
'@tauri-apps/cli-linux-x64-gnu': 2.12.2
'@tauri-apps/cli-linux-x64-musl': 2.12.2
'@tauri-apps/cli-win32-arm64-msvc': 2.12.2
'@tauri-apps/cli-win32-ia32-msvc': 2.12.2
'@tauri-apps/cli-win32-x64-msvc': 2.12.2
'@types/[email protected]': {}
'@types/[email protected]': {}
'@types/[email protected].4':
'@types/[email protected].5':
dependencies:
undici-types: 8.9.0
@@ -2041,14 +2041,14 @@ snapshots:
dependencies:
csstype: 3.2.3
'@typescript-eslint/[email protected].1(@typescript-eslint/[email protected].1([email protected])([email protected]))([email protected])([email protected])':
'@typescript-eslint/[email protected].2(@typescript-eslint/[email protected].2([email protected])([email protected]))([email protected])([email protected])':
dependencies:
'@eslint-community/regexpp': 4.12.2
'@typescript-eslint/parser': 8.71.1([email protected])([email protected])
'@typescript-eslint/scope-manager': 8.71.1
'@typescript-eslint/type-utils': 8.71.1([email protected])([email protected])
'@typescript-eslint/utils': 8.71.1([email protected])([email protected])
'@typescript-eslint/visitor-keys': 8.71.1
'@typescript-eslint/parser': 8.71.2([email protected])([email protected])
'@typescript-eslint/scope-manager': 8.71.2
'@typescript-eslint/type-utils': 8.71.2([email protected])([email protected])
'@typescript-eslint/utils': 8.71.2([email protected])([email protected])
'@typescript-eslint/visitor-keys': 8.71.2
eslint: 9.39.5
ignore: 7.0.12
natural-compare: 1.4.0
@@ -2057,41 +2057,41 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@typescript-eslint/[email protected].1([email protected])([email protected])':
'@typescript-eslint/[email protected].2([email protected])([email protected])':
dependencies:
'@typescript-eslint/scope-manager': 8.71.1
'@typescript-eslint/types': 8.71.1
'@typescript-eslint/typescript-estree': 8.71.1([email protected])
'@typescript-eslint/visitor-keys': 8.71.1
'@typescript-eslint/scope-manager': 8.71.2
'@typescript-eslint/types': 8.71.2
'@typescript-eslint/typescript-estree': 8.71.2([email protected])
'@typescript-eslint/visitor-keys': 8.71.2
debug: 4.4.3
eslint: 9.39.5
typescript: 6.0.3
transitivePeerDependencies:
- supports-color
'@typescript-eslint/[email protected].1([email protected])':
'@typescript-eslint/[email protected].2([email protected])':
dependencies:
'@typescript-eslint/tsconfig-utils': 8.71.1([email protected])
'@typescript-eslint/types': 8.71.1
'@typescript-eslint/tsconfig-utils': 8.71.2([email protected])
'@typescript-eslint/types': 8.71.2
debug: 4.4.3
typescript: 6.0.3
transitivePeerDependencies:
- supports-color
'@typescript-eslint/[email protected].1':
'@typescript-eslint/[email protected].2':
dependencies:
'@typescript-eslint/types': 8.71.1
'@typescript-eslint/visitor-keys': 8.71.1
'@typescript-eslint/types': 8.71.2
'@typescript-eslint/visitor-keys': 8.71.2
'@typescript-eslint/[email protected].1([email protected])':
'@typescript-eslint/[email protected].2([email protected])':
dependencies:
typescript: 6.0.3
'@typescript-eslint/[email protected].1([email protected])([email protected])':
'@typescript-eslint/[email protected].2([email protected])([email protected])':
dependencies:
'@typescript-eslint/types': 8.71.1
'@typescript-eslint/typescript-estree': 8.71.1([email protected])
'@typescript-eslint/utils': 8.71.1([email protected])([email protected])
'@typescript-eslint/types': 8.71.2
'@typescript-eslint/typescript-estree': 8.71.2([email protected])
'@typescript-eslint/utils': 8.71.2([email protected])([email protected])
debug: 4.4.3
eslint: 9.39.5
ts-api-utils: 2.5.0([email protected])
@@ -2099,14 +2099,14 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@typescript-eslint/[email protected].1': {}
'@typescript-eslint/[email protected].2': {}
'@typescript-eslint/[email protected].1([email protected])':
'@typescript-eslint/[email protected].2([email protected])':
dependencies:
'@typescript-eslint/project-service': 8.71.1([email protected])
'@typescript-eslint/tsconfig-utils': 8.71.1([email protected])
'@typescript-eslint/types': 8.71.1
'@typescript-eslint/visitor-keys': 8.71.1
'@typescript-eslint/project-service': 8.71.2([email protected])
'@typescript-eslint/tsconfig-utils': 8.71.2([email protected])
'@typescript-eslint/types': 8.71.2
'@typescript-eslint/visitor-keys': 8.71.2
debug: 4.4.3
minimatch: 10.2.6
semver: 7.8.5
@@ -2116,26 +2116,26 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@typescript-eslint/[email protected].1([email protected])([email protected])':
'@typescript-eslint/[email protected].2([email protected])([email protected])':
dependencies:
'@eslint-community/eslint-utils': 4.10.1([email protected])
'@typescript-eslint/scope-manager': 8.71.1
'@typescript-eslint/types': 8.71.1
'@typescript-eslint/typescript-estree': 8.71.1([email protected])
'@typescript-eslint/scope-manager': 8.71.2
'@typescript-eslint/types': 8.71.2
'@typescript-eslint/typescript-estree': 8.71.2([email protected])
eslint: 9.39.5
typescript: 6.0.3
transitivePeerDependencies:
- supports-color
'@typescript-eslint/[email protected].1':
'@typescript-eslint/[email protected].2':
dependencies:
'@typescript-eslint/types': 8.71.1
'@typescript-eslint/types': 8.71.2
eslint-visitor-keys: 5.0.1
'@vitejs/[email protected]([email protected].3(@types/[email protected].4)([email protected]))':
'@vitejs/[email protected]([email protected].4(@types/[email protected].5)([email protected]))':
dependencies:
'@rolldown/pluginutils': 1.0.1
vite: 8.3.3(@types/[email protected].4)([email protected])
vite: 8.3.4(@types/[email protected].5)([email protected])
[email protected]([email protected]):
dependencies:
@@ -2223,7 +2223,7 @@ snapshots:
[email protected]: {}
[email protected]7: {}
[email protected]8: {}
[email protected]:
dependencies:
@@ -2236,11 +2236,11 @@ snapshots:
[email protected]:
dependencies:
baseline-browser-mapping: 2.11.27
caniuse-lite: 1.0.30001814
electron-to-chromium: 1.5.449
node-releases: 2.0.57
update-browserslist-db: 1.3.3([email protected])
baseline-browser-mapping: 2.11.28
caniuse-lite: 1.0.30001815
electron-to-chromium: 1.5.452
node-releases: 2.0.58
update-browserslist-db: 1.3.4([email protected])
[email protected]:
dependencies:
@@ -2261,7 +2261,7 @@ snapshots:
[email protected]: {}
[email protected]4: {}
[email protected]5: {}
[email protected]:
dependencies:
@@ -2334,7 +2334,7 @@ snapshots:
es-errors: 1.3.0
gopd: 1.2.0
[email protected]49: {}
[email protected]52: {}
[email protected]:
dependencies:
@@ -2491,8 +2491,8 @@ snapshots:
'@babel/parser': 7.29.9
eslint: 9.39.5
hermes-parser: 0.25.1
zod: 4.6.5
zod-validation-error: 4.0.2([email protected].5)
zod: 4.6.6
zod-validation-error: 4.0.2([email protected].6)
transitivePeerDependencies:
- supports-color
@@ -2962,7 +2962,7 @@ snapshots:
object.entries: 1.1.9
semver: 6.3.1
[email protected]7: {}
[email protected]8: {}
[email protected]: {}
@@ -3048,7 +3048,7 @@ snapshots:
[email protected]: {}
[email protected].9: {}
[email protected].10: {}
[email protected]:
dependencies:
@@ -3098,26 +3098,26 @@ snapshots:
path-parse: 1.0.7
supports-preserve-symlinks-flag: 1.0.0
[email protected]2:
[email protected]3:
dependencies:
'@oxc-project/types': 0.152.0
'@oxc-project/types': 0.153.0
'@rolldown/pluginutils': 1.0.1
optionalDependencies:
'@rolldown/binding-android-arm-eabi': 1.2.12
'@rolldown/binding-android-arm64': 1.2.12
'@rolldown/binding-darwin-arm64': 1.2.12
'@rolldown/binding-darwin-x64': 1.2.12
'@rolldown/binding-freebsd-x64': 1.2.12
'@rolldown/binding-linux-arm-gnueabihf': 1.2.12
'@rolldown/binding-linux-arm64-gnu': 1.2.12
'@rolldown/binding-linux-arm64-musl': 1.2.12
'@rolldown/binding-linux-ppc64-gnu': 1.2.12
'@rolldown/binding-linux-s390x-gnu': 1.2.12
'@rolldown/binding-linux-x64-gnu': 1.2.12
'@rolldown/binding-linux-x64-musl': 1.2.12
'@rolldown/binding-openharmony-arm64': 1.2.12
'@rolldown/binding-win32-arm64-msvc': 1.2.12
'@rolldown/binding-win32-x64-msvc': 1.2.12
'@rolldown/binding-android-arm-eabi': 1.2.13
'@rolldown/binding-android-arm64': 1.2.13
'@rolldown/binding-darwin-arm64': 1.2.13
'@rolldown/binding-darwin-x64': 1.2.13
'@rolldown/binding-freebsd-x64': 1.2.13
'@rolldown/binding-linux-arm-gnueabihf': 1.2.13
'@rolldown/binding-linux-arm64-gnu': 1.2.13
'@rolldown/binding-linux-arm64-musl': 1.2.13
'@rolldown/binding-linux-ppc64-gnu': 1.2.13
'@rolldown/binding-linux-s390x-gnu': 1.2.13
'@rolldown/binding-linux-x64-gnu': 1.2.13
'@rolldown/binding-linux-x64-musl': 1.2.13
'@rolldown/binding-openharmony-arm64': 1.2.13
'@rolldown/binding-win32-arm64-msvc': 1.2.13
'@rolldown/binding-win32-x64-msvc': 1.2.13
[email protected]:
dependencies:
@@ -3316,7 +3316,7 @@ snapshots:
[email protected]: {}
[email protected].3([email protected]):
[email protected].4([email protected]):
dependencies:
browserslist: 4.29.3
escalade: 3.2.0
@@ -3326,15 +3326,15 @@ snapshots:
dependencies:
punycode: 2.3.1
[email protected].3(@types/[email protected].4)([email protected]):
[email protected].4(@types/[email protected].5)([email protected]):
dependencies:
lightningcss: 1.33.0
picomatch: 4.0.7
postcss: 8.5.29
rolldown: 1.2.12
rolldown: 1.2.13
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 26.6.4
'@types/node': 26.6.5
esbuild: 0.27.2
fsevents: 2.3.3
@@ -3389,8 +3389,8 @@ snapshots:
[email protected]: {}
[email protected]([email protected].5):
[email protected]([email protected].6):
dependencies:
zod: 4.6.5
zod: 4.6.6
[email protected].5: {}
[email protected].6: {}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 56 KiB

+1 -1
View File
@@ -19,7 +19,7 @@
<circle cx="512" cy="455" r="315"/>
</clipPath>
<filter id="globe-shadow" x="150" y="90" width="730" height="760" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#174d6f" flood-opacity=".14"/>
<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">
<feDropShadow dx="0" dy="18" stdDeviation="18" flood-color="#70430c" flood-opacity=".2"/>

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

+1 -1
View File
@@ -29,7 +29,7 @@ uuid = { workspace = true, features = ["v4"] }
zeroize.workspace = true
tempfile.workspace = true
getrandom = "0.4"
mac_address = "1"
mac_address = "1.2.1"
[target.'cfg(unix)'.dependencies]
nix = { version = "0.31", features = ["fs", "socket", "user"] }
+9
View File
@@ -4,6 +4,15 @@ const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
// Installed OpenConnect lives in the private ../lib/gpclient directory.
// Build executables also locate their exact Cargo library; installers remove that rpath.
#[cfg(target_os = "macos")]
{
println!("cargo:rustc-link-arg=-Wl,-rpath,@executable_path/../lib/gpclient");
let library_dir = env::var("DEP_OPENCONNECT_LIB_DIR").expect("OpenConnect exports its build library directory");
println!("cargo:rustc-link-arg=-Wl,-rpath,{library_dir}");
}
println!("cargo:rerun-if-env-changed=GPSERVICE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
+87 -2
View File
@@ -152,13 +152,16 @@ impl Cli {
let vpn_task_cancel_token = vpn_task.cancel_token();
let server_token = ws_server.cancel_token();
#[cfg(target_os = "macos")]
let (credential_ready_tx, credential_ready_rx) = tokio::sync::oneshot::channel();
#[cfg(target_os = "macos")]
if externally_brokered {
let credential_server = crate::macos_broker::CredentialServer::new(Arc::clone(&registry));
let credential_token = server_token.clone();
let credential_shutdown = shutdown_tx.clone();
tokio::spawn(async move {
if let Err(err) = credential_server.start(credential_token).await {
if let Err(err) = credential_server.start(credential_token, credential_ready_tx).await {
warn!("Broker credential server stopped: {err}");
let _ = credential_shutdown.send(()).await;
}
@@ -206,8 +209,22 @@ impl Cli {
let (ws_ready_tx, ws_ready_rx) = tokio::sync::oneshot::channel();
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone, ws_ready_tx).await });
#[cfg(target_os = "macos")]
let ws_ready_rx = if externally_brokered {
await_broker_readiness(ws_ready_rx, credential_ready_rx).await?;
report_broker_readiness(&mut std::io::stdout().lock())?;
None
} else {
Some(ws_ready_rx)
};
#[cfg(not(target_os = "macos"))]
let ws_ready_rx = Some(ws_ready_rx);
let desktop_client_handle = if let Some(channel) = desktop_channel {
ws_ready_rx.await.context("WebSocket server failed to start")?;
ws_ready_rx
.context("WebSocket readiness receiver is unavailable")?
.await
.context("WebSocket server failed to start")?;
let desktop_uid = desktop_uid.context("Desktop user is unavailable")?;
Some(tokio::spawn(async move {
if let Err(err) = channel
@@ -395,3 +412,71 @@ pub async fn run() {
std::process::exit(1);
}
}
#[cfg(target_os = "macos")]
fn report_broker_readiness(output: &mut impl std::io::Write) -> std::io::Result<()> {
output.write_all(b"GP_CONNECT_SERVICE_READY\n")?;
output.flush()
}
#[cfg(all(test, target_os = "macos"))]
mod readiness_tests {
use super::*;
#[tokio::test]
async fn readiness_waits_for_both_endpoints() {
let (ws_tx, ws_rx) = tokio::sync::oneshot::channel();
let (credential_tx, credential_rx) = tokio::sync::oneshot::channel();
let mut ready = tokio::spawn(await_broker_readiness(ws_rx, credential_rx));
ws_tx.send(()).unwrap();
assert!(
tokio::time::timeout(Duration::from_millis(20), &mut ready)
.await
.is_err()
);
credential_tx.send(()).unwrap();
ready.await.unwrap().unwrap();
}
#[tokio::test]
async fn failed_endpoint_aborts_readiness_even_if_other_endpoint_is_pending() {
let (ws_tx, ws_rx) = tokio::sync::oneshot::channel();
let (_credential_tx, credential_rx) = tokio::sync::oneshot::channel();
drop(ws_tx);
let result = tokio::time::timeout(Duration::from_secs(1), await_broker_readiness(ws_rx, credential_rx)).await;
assert!(result.unwrap().is_err());
}
#[test]
fn readiness_signal_is_exact_and_flushed() {
#[derive(Default)]
struct Output {
data: Vec<u8>,
flushed: bool,
}
impl std::io::Write for Output {
fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
self.data.extend_from_slice(data);
Ok(data.len())
}
fn flush(&mut self) -> std::io::Result<()> {
self.flushed = true;
Ok(())
}
}
let mut output = Output::default();
report_broker_readiness(&mut output).unwrap();
assert_eq!(output.data, b"GP_CONNECT_SERVICE_READY\n");
assert!(output.flushed);
}
}
#[cfg(target_os = "macos")]
async fn await_broker_readiness(
websocket: tokio::sync::oneshot::Receiver<()>,
credential: tokio::sync::oneshot::Receiver<()>,
) -> anyhow::Result<()> {
tokio::try_join!(async { websocket.await }, async { credential.await })
.context("Brokered service endpoints failed to start")?;
Ok(())
}
+65 -11
View File
@@ -17,6 +17,7 @@ use tokio::io::unix::AsyncFd;
use tokio_util::sync::CancellationToken;
use crate::session_registry::SessionRegistry;
use gpapi::service::transport::{DESKTOP_GUI_EXITED, DESKTOP_RENDERING_RETRY};
/// Private parent/service pipes; credentials never pass through argv, environment or files.
pub(crate) struct DesktopClient {
@@ -58,19 +59,28 @@ impl DesktopClient {
restart: Arc<AtomicBool>,
cancel: CancellationToken,
) -> anyhow::Result<()> {
let mut rendering_renewed = false;
loop {
let credential = registry.issue(env!("CARGO_PKG_VERSION"), Some(uid))?;
let session_id = credential.session_id();
let result = tokio::select! {
_ = cancel.cancelled() => Ok(false),
_ = cancel.cancelled() => Ok(None),
result = async {
self.write_frame(&credential.encode_frame()?).await?;
self.gui_exited().await
} => result,
};
registry.revoke(session_id);
if !result? || !restart.swap(false, Ordering::SeqCst) {
return Ok(());
let requested = restart.swap(false, Ordering::SeqCst);
match result? {
None => return Ok(()),
Some(DESKTOP_GUI_EXITED) if requested => {}
Some(DESKTOP_GUI_EXITED) => return Ok(()),
Some(DESKTOP_RENDERING_RETRY) => {
ensure!(!rendering_renewed, "Rendering recovery already requested");
rendering_renewed = true;
}
Some(_) => anyhow::bail!("Invalid desktop control message"),
}
}
}
@@ -90,17 +100,16 @@ impl DesktopClient {
Ok(())
}
async fn gui_exited(&self) -> anyhow::Result<bool> {
async fn gui_exited(&self) -> anyhow::Result<Option<u8>> {
loop {
let mut ready = self.input.readable().await?;
let mut byte = [0];
match ready.try_io(|fd| read(fd.get_ref(), &mut byte).map_err(io::Error::from)) {
Ok(result) => {
if result.context("Desktop control pipe failed")? == 0 {
return Ok(false);
return Ok(None);
}
ensure!(byte[0] == 0, "Invalid desktop control message");
return Ok(true);
return Ok(Some(byte[0]));
}
Err(_) => continue,
}
@@ -165,7 +174,7 @@ mod tests {
#[tokio::test]
async fn desktop_channel_revokes_and_reissues_on_restart_then_closes_on_parent_exit() {
let (channel, control, reader) = pipes();
let registry = Arc::new(SessionRegistry::new(uuid::Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(uuid::Uuid::new_v4()));
let restart = Arc::new(AtomicBool::new(false));
let task = tokio::spawn(channel.serve(registry.clone(), 1000, restart.clone(), CancellationToken::new()));
let (reader, first) = credential(reader).await;
@@ -183,10 +192,55 @@ mod tests {
assert!(registry.last_successful_hip_report(second.session_id()).is_err());
}
#[tokio::test]
async fn rendering_renewal_revokes_credentials_and_consumes_old_restart_intent() {
let (channel, control, reader) = pipes();
let registry = Arc::new(SessionRegistry::for_tests(uuid::Uuid::new_v4()));
let restart = Arc::new(AtomicBool::new(true));
let task = tokio::spawn(channel.serve(registry.clone(), 1000, restart.clone(), CancellationToken::new()));
let (reader, first) = credential(reader).await;
write(&control, &[DESKTOP_RENDERING_RETRY]).unwrap();
let (_, second) = credential(reader).await;
assert_ne!(first.session_id(), second.session_id());
assert!(registry.last_successful_hip_report(first.session_id()).is_err());
assert!(!restart.load(Ordering::SeqCst));
write(&control, &[DESKTOP_GUI_EXITED]).unwrap();
tokio::time::timeout(Duration::from_secs(1), task)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(registry.last_successful_hip_report(second.session_id()).is_err());
}
#[tokio::test]
async fn repeated_rendering_renewal_fails_closed() {
let (channel, control, reader) = pipes();
let registry = Arc::new(SessionRegistry::for_tests(uuid::Uuid::new_v4()));
let task = tokio::spawn(channel.serve(
registry.clone(),
1000,
Arc::new(AtomicBool::new(false)),
CancellationToken::new(),
));
let (reader, _) = credential(reader).await;
write(&control, &[DESKTOP_RENDERING_RETRY]).unwrap();
let (_, second) = credential(reader).await;
write(&control, &[DESKTOP_RENDERING_RETRY]).unwrap();
assert!(
tokio::time::timeout(Duration::from_secs(1), task)
.await
.unwrap()
.unwrap()
.is_err()
);
assert!(registry.last_successful_hip_report(second.session_id()).is_err());
}
#[tokio::test]
async fn desktop_channel_shutdown_cancels_pipe_wait_and_revokes_credential() {
let (channel, _control, reader) = pipes();
let registry = Arc::new(SessionRegistry::new(uuid::Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(uuid::Uuid::new_v4()));
let cancel = CancellationToken::new();
let task = tokio::spawn(channel.serve(registry.clone(), 1000, Arc::new(AtomicBool::new(false)), cancel.clone()));
let (_, issued) = credential(reader).await;
@@ -202,7 +256,7 @@ mod tests {
#[tokio::test]
async fn desktop_channel_rejects_invalid_control_messages_and_revokes() {
let (channel, control, reader) = pipes();
let registry = Arc::new(SessionRegistry::new(uuid::Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(uuid::Uuid::new_v4()));
let task = tokio::spawn(channel.serve(
registry.clone(),
1000,
@@ -210,7 +264,7 @@ mod tests {
CancellationToken::new(),
));
let (_, issued) = credential(reader).await;
write(&control, &[1]).unwrap();
write(&control, &[255]).unwrap();
assert!(
tokio::time::timeout(Duration::from_secs(1), task)
.await
+1 -1
View File
@@ -186,7 +186,7 @@ mod tests {
#[tokio::test]
async fn anchor_eof_revokes_issued_credential() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let (service, mut client) = UnixStream::pair().unwrap();
let task = tokio::spawn(credential_lease::serve(service, Arc::clone(&registry), Some(1234)));
+1 -1
View File
@@ -233,7 +233,7 @@ mod tests {
"serial".into(),
"00:11:22:33:44:55".into(),
),
registry: Arc::new(SessionRegistry::new(Uuid::new_v4())),
registry: Arc::new(SessionRegistry::for_tests(Uuid::new_v4())),
connection,
}
}
+6 -1
View File
@@ -23,7 +23,11 @@ impl CredentialServer {
Self { registry }
}
pub(crate) async fn start(self, cancel: CancellationToken) -> anyhow::Result<()> {
pub(crate) async fn start(
self,
cancel: CancellationToken,
ready: tokio::sync::oneshot::Sender<()>,
) -> anyhow::Result<()> {
if !Uid::effective().is_root() {
bail!("macOS brokered mode requires root privileges");
}
@@ -33,6 +37,7 @@ impl CredentialServer {
.with_context(|| format!("Failed to bind broker credential socket at {}", path.display()))?;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
info!("Broker credential socket listening at {}", path.display());
let _ = ready.send(());
loop {
tokio::select! {
+52 -10
View File
@@ -84,6 +84,8 @@ struct AttachmentAttempt {
pub struct SessionRegistry {
service_instance_id: Uuid,
sessions: Mutex<HashMap<Uuid, SessionRecord>>,
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
resolve_device_anchor: fn() -> anyhow::Result<gpapi::device_anchor::DeviceAnchor>,
}
fn unavailable_connection() -> ServiceResult {
@@ -192,6 +194,25 @@ impl SessionRegistry {
Self {
service_instance_id,
sessions: Mutex::new(HashMap::new()),
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
resolve_device_anchor: crate::device_anchor::resolve,
}
}
/// Session tests use an explicit anchor fixture; persistence and permissions
/// are exercised separately by the device_anchor tests.
#[cfg(test)]
pub(crate) fn for_tests(service_instance_id: Uuid) -> Self {
Self {
service_instance_id,
sessions: Mutex::new(HashMap::new()),
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
resolve_device_anchor: || {
Ok(gpapi::device_anchor::DeviceAnchor::derive(
gpapi::device_anchor::AnchorSource::UnixRandom,
b"session-registry-test-anchor",
))
},
}
}
@@ -218,7 +239,7 @@ impl SessionRegistry {
SessionCredential::generate(self.service_instance_id, product_version).map_err(|_| SessionError::Unavailable)?;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
let credential = {
let anchor = crate::device_anchor::resolve().map_err(|error| {
let anchor = (self.resolve_device_anchor)().map_err(|error| {
log::warn!("GUI device anchor unavailable: {error:#}");
SessionError::Unavailable
})?;
@@ -596,9 +617,30 @@ mod tests {
ConnectionControl::new(Uuid::new_v4(), tx).0
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[test]
fn unavailable_device_anchor_does_not_issue_a_session() {
let mut registry = SessionRegistry::for_tests(Uuid::new_v4());
registry.resolve_device_anchor = || anyhow::bail!("fixture anchor unavailable");
assert!(matches!(
registry.issue("fixture", None),
Err(SessionError::Unavailable)
));
assert!(registry.sessions.lock().unwrap().is_empty());
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[test]
fn issued_credential_carries_the_resolved_device_anchor() {
let registry = SessionRegistry::for_tests(Uuid::new_v4());
let expected = (registry.resolve_device_anchor)().unwrap();
let credential = registry.issue("fixture", Some(1000)).unwrap();
assert_eq!(credential.device_anchor(), Some(&expected));
}
#[tokio::test]
async fn attachment_replacement_cancels_preparation_and_retains_drain_until_release() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let credential = registry.issue("fixture", None).unwrap();
let session = credential.session_id();
let first = registry
@@ -655,7 +697,7 @@ mod tests {
#[tokio::test]
async fn scoped_stop_closes_attachment_to_delayed_starts_without_receipt_history() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let credential = registry.issue("fixture", None).unwrap();
let session = credential.session_id();
let permit = registry
@@ -693,7 +735,7 @@ mod tests {
#[tokio::test]
async fn tunnel_reservation_survives_attachment_loss_but_non_tunnel_revocation_cancels() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let credential = registry.issue("fixture", None).unwrap();
let session = credential.session_id();
let permit = registry
@@ -732,7 +774,7 @@ mod tests {
#[test]
fn credential_retains_verified_desktop_user_across_reconnect() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let credential = registry.issue("2.6.4", Some(1000)).unwrap();
let first = registry
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
@@ -769,7 +811,7 @@ mod tests {
panic!("upload did not complete")
}
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let first_credential = registry.issue("2.6.4", Some(1000)).unwrap();
let second_credential = registry.issue("2.6.4", Some(1001)).unwrap();
for credential in [&first_credential, &second_credential] {
@@ -813,7 +855,7 @@ mod tests {
#[test]
fn submitted_report_changes_only_after_success_callback_and_is_session_bound() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let credential = registry.issue("2.6.4", Some(1000)).unwrap();
let permit = registry
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
@@ -866,7 +908,7 @@ mod tests {
#[test]
fn reconnect_uses_generation_compare_and_swap() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let credential = registry.issue("2.6.4", None).unwrap();
let first = registry
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
@@ -887,7 +929,7 @@ mod tests {
#[test]
fn failed_initial_handshake_only_revokes_its_own_reservation() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let credential = registry.issue("2.6.4", None).unwrap();
let first = registry
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
@@ -901,7 +943,7 @@ mod tests {
#[test]
fn failed_reconnect_keeps_active_connection_authoritative() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let credential = registry.issue("2.6.4", None).unwrap();
let first = registry
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
+2 -2
View File
@@ -212,7 +212,7 @@ impl LifecycleHandle {
#[cfg(test)]
pub(crate) fn for_tests() -> Self {
let (vpn_state_tx, _vpn_state_rx) = watch::channel(VpnState::Disconnected);
let registry = Arc::new(crate::session_registry::SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(crate::session_registry::SessionRegistry::for_tests(Uuid::new_v4()));
let (_task, lifecycle) = VpnTask::new(vpn_state_tx, false, registry);
lifecycle
}
@@ -782,7 +782,7 @@ mod tests {
use crate::session_registry::SessionRegistry;
fn registry() -> Arc<SessionRegistry> {
Arc::new(SessionRegistry::new(Uuid::new_v4()))
Arc::new(SessionRegistry::for_tests(Uuid::new_v4()))
}
fn identity_request() -> ConnectRequest {
@@ -56,7 +56,7 @@ async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response(
let mut gateway = serde_json::to_value(Gateway::new("fixture".into(), server_name.clone())).unwrap();
gateway["kind"] = serde_json::json!("internal");
let gateway: Gateway = serde_json::from_value(gateway).unwrap();
let registry = Arc::new(crate::session_registry::SessionRegistry::new(uuid::Uuid::new_v4()));
let registry = Arc::new(crate::session_registry::SessionRegistry::for_tests(uuid::Uuid::new_v4()));
let credential = registry.issue("fixture", None).unwrap();
let session_id = credential.session_id();
let permit = registry
+1 -1
View File
@@ -589,7 +589,7 @@ mod tests {
#[tokio::test]
async fn authenticates_attaches_and_replies_to_a_request() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
let dispatcher = Arc::new(RequestDispatcher::new(
crate::vpn_task::LifecycleHandle::for_tests(),
+2 -2
View File
@@ -287,7 +287,7 @@ mod tests {
#[tokio::test]
async fn resync_snapshot_is_ordered_with_state_events() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
let permit = registry
.begin_handshake(
@@ -344,7 +344,7 @@ mod tests {
#[tokio::test]
async fn removed_prepared_candidate_cannot_commit_takeover() {
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
let dispatcher = Arc::new(RequestDispatcher::new(
crate::vpn_task::LifecycleHandle::for_tests(),
+45
View File
@@ -1,5 +1,50 @@
# Changelog
## 3.0.5
### Added
- Added adaptive macOS app icons for light and dark appearances.
### Fixed
- Fixed macOS browser sign-in by automatically selecting the installed callback handler.
- Improved app icon proportions in Finder and across the app, installer, and website.
## 3.0.4
### Added
- Added `gpclient connect --background` with connection logs and graceful disconnect.
### Fixed
- Improved macOS service startup, relaunch, and quit responsiveness.
- Updated app icons for clearer artwork across platforms.
## 3.0.3
### Fixed
- Improved Wayland crash recovery on Linux and BSD.
- Fixed pasted callbacks and prompts for remote browser sign-in.
- Fixed legacy TLS configuration while preserving device identities.
- Fixed diagnostics when optional tools are unavailable.
- Fixed bundled macOS library paths and polished release notes in About.
## 3.0.2
### Added
- Added `gpclient diagnostics` to collect system and client information for troubleshooting.
### Fixed
- Recognized WebKit Wayland rendering crashes now trigger one retry with DMABUF disabled when opening the GUI, first-time setup, or embedded browser sign-in.
- Improved desktop rendering with opaque windows to reduce transparency-related flickering on Linux and BSD.
- Browser sign-in retries refresh authentication data, and repeated failures report both attempts instead of leaving the client waiting.
- Cancelling startup or sign-in now stops pending desktop child processes and version checks.
## 3.0.1
### Fixed
+1 -1
View File
@@ -25,7 +25,7 @@ uzers = { workspace = true, optional = true }
tauri = { workspace = true, optional = true }
regex = { workspace = true, optional = true }
tokio-util = { workspace = true, optional = true }
html-escape = { version = "0.2.13", optional = true }
html-escape = { version = "0.3", optional = true }
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
webkit2gtk = { version = "2", optional = true }
+3 -3
View File
@@ -14,7 +14,9 @@ impl AuthServer {
let server = Server::http(addr).map_err(|err| anyhow::anyhow!(err))?;
let auth_id = Uuid::new_v4().to_string();
Ok(Self { server, auth_id })
let auth_server = Self { server, auth_id };
info!("auth server started at: {}", auth_server.auth_url());
Ok(auth_server)
}
pub fn auth_url(&self) -> String {
@@ -22,8 +24,6 @@ impl AuthServer {
}
pub fn serve_request(&self, auth_request: &str) {
info!("auth server started at: {}", self.auth_url());
for req in self.server.incoming_requests() {
info!("received request, method: {}, url: {}", req.method(), req.url());
+9 -2
View File
@@ -1,4 +1,7 @@
use std::net::{IpAddr, SocketAddr};
use std::{
io::Write,
net::{IpAddr, SocketAddr},
};
use browser_launcher::Browser as LaunchBrowser;
use gpapi::auth::SamlAuthData;
@@ -34,7 +37,7 @@ impl<'a> BrowserAuthenticator<'a> {
let auth_url = auth_server.auth_url();
let auth_request = self.auth_request.to_string();
tokio::spawn(async move {
let auth_server_task = tokio::task::spawn_blocking(move || {
auth_server.serve_request(&auth_request);
});
@@ -55,6 +58,7 @@ Note that the URL is only valid for a single use.
"#,
auth_url
);
auth_server_task.await?;
return read_auth_data_from_stdin();
}
@@ -95,6 +99,9 @@ async fn detect_local_ip() -> anyhow::Result<IpAddr> {
}
fn read_auth_data_from_stdin() -> anyhow::Result<SamlAuthData> {
eprint!("\nAuthentication callback (paste and press Enter): ");
std::io::stderr().flush()?;
let mut data = String::new();
std::io::stdin().read_line(&mut data)?;
+40 -19
View File
@@ -1,8 +1,9 @@
use std::{ffi::OsStr, os::raw::c_void, path::PathBuf, thread, time::Duration};
use std::{ffi::OsStr, os::raw::c_void, path::PathBuf, sync::mpsc};
use anyhow::{Context, bail};
use block2::RcBlock;
use objc2_app_kit::NSWorkspace;
use objc2_foundation::{NSBundle, NSString, NSURL};
use objc2_foundation::{NSBundle, NSDate, NSError, NSRunLoop, NSString, NSURL};
const CALLBACK_SCHEME: &str = "globalprotectcallback";
const CALLBACK_URL: &str = "globalprotectcallback:";
@@ -15,18 +16,19 @@ unsafe extern "C" {
}
pub(super) fn ensure_auth_callback_handler() -> anyhow::Result<()> {
set_auth_callback_handler().map_err(|error| {
log::warn!("Failed to set up browser sign-in: {error:#}");
anyhow::anyhow!("Couldn’t set up browser sign-in. Please try again.")
})
}
fn set_auth_callback_handler() -> anyhow::Result<()> {
let workspace = NSWorkspace::sharedWorkspace();
let app_paths = callback_app_paths();
let selected_handler = current_handler(&workspace);
match selected_handler.as_ref() {
Some((handler, path))
if handler == HANDLER_BUNDLE_ID && app_paths.iter().any(|candidate| same_path(candidate, path)) =>
{
return Ok(());
}
Some((handler, _)) if handler == HANDLER_BUNDLE_ID => {}
None => {}
Some((handler, _)) => bail!("The globalprotectcallback URL scheme is owned by {handler}"),
if current_handler(&workspace).is_some_and(|(handler, path)| {
handler == HANDLER_BUNDLE_ID && app_paths.iter().any(|candidate| same_path(candidate, &path))
}) {
return Ok(());
}
let app_path = app_paths
@@ -34,21 +36,40 @@ pub(super) fn ensure_auth_callback_handler() -> anyhow::Result<()> {
.context("GP Connect Login.app is required for external-browser authentication; install GP Connect")?;
let app_url = file_url(app_path);
register_app(&app_url)?;
let (sender, receiver) = mpsc::channel();
let completion = RcBlock::new(move |error: *mut NSError| {
// The error is valid for the duration of Apple's completion callback.
let result = match unsafe { error.as_ref() } {
Some(error) => Err(anyhow::anyhow!("{}", error.localizedDescription())),
None => Ok(()),
};
let _ = sender.send(result);
});
workspace.setDefaultApplicationAtURL_toOpenURLsWithScheme_completionHandler(
&app_url,
&NSString::from_str(CALLBACK_SCHEME),
None,
Some(&completion),
);
for _ in 0..50 {
if current_handler(&workspace)
.is_some_and(|(handler, path)| handler == HANDLER_BUNDLE_ID && same_path(app_path, &path))
{
return Ok(());
// macOS may ask for consent. Keep its run loop active until the operation
// completes rather than imposing a deadline on the user's response.
let run_loop = NSRunLoop::currentRunLoop();
loop {
match receiver.try_recv() {
Ok(result) => {
result?;
break;
}
Err(mpsc::TryRecvError::Empty) => run_loop.runUntilDate(&NSDate::dateWithTimeIntervalSinceNow(0.1)),
Err(mpsc::TryRecvError::Disconnected) => bail!("The URL handler setup completion was lost"),
}
thread::sleep(Duration::from_millis(100));
}
if current_handler(&workspace)
.is_some_and(|(handler, path)| handler == HANDLER_BUNDLE_ID && same_path(app_path, &path))
{
return Ok(());
}
bail!("The globalprotectcallback URL handler registration did not take effect")
}
+23
View File
@@ -93,6 +93,12 @@ fn sibling_binary_for_executable(executable: &Path, binary_name: &str) -> Option
if is_file(&binary) {
return Some(binary);
}
if matches!(binary_name, "gp-vpnc-script-installer" | "gp-hip-script-installer") {
let binary = bin_dir.parent()?.join("libexec/gpclient").join(binary_name);
if is_file(&binary) {
return Some(binary);
}
}
#[cfg(target_os = "macos")]
if let Some(binary) = macos::helper_path(&executable, binary_name)
&& is_file(&binary)
@@ -121,6 +127,23 @@ fn is_file(path: &Path) -> bool {
mod tests {
use super::*;
#[test]
fn script_installers_follow_the_installed_prefix() {
let directory = tempfile::tempdir().unwrap();
let bin = directory.path().join("bin");
let libexec = directory.path().join("libexec/gpclient");
std::fs::create_dir_all(&bin).unwrap();
std::fs::create_dir_all(&libexec).unwrap();
std::fs::write(bin.join("gpclient"), "").unwrap();
for name in ["gp-vpnc-script-installer", "gp-hip-script-installer"] {
std::fs::write(libexec.join(name), "").unwrap();
assert_eq!(
sibling_binary_for_executable(&bin.join("gpclient"), name),
Some(libexec.canonicalize().unwrap().join(name))
);
}
}
#[test]
#[cfg(target_os = "macos")]
fn desktop_resolves_helpers_in_the_actual_app_bundle_layout() {
+3 -2
View File
@@ -20,13 +20,13 @@ xmltree.workspace = true
serde.workspace = true
specta = { workspace = true, features = ["derive", "uuid"] }
urlencoding.workspace = true
tokio = { workspace = true, features = ["process", "signal", "macros"] }
tokio = { workspace = true, features = ["fs", "process", "signal", "macros"] }
tokio-util.workspace = true
serde_json.workspace = true
whoami.workspace = true
tempfile.workspace = true
thiserror.workspace = true
chacha20poly1305 = { version = "0.10", features = ["std"] }
chacha20poly1305 = { version = "0.11", features = ["zeroize"] }
redact-engine.workspace = true
url.workspace = true
regex.workspace = true
@@ -34,6 +34,7 @@ uzers.workspace = true
serde_urlencoded.workspace = true
md5.workspace = true
sha256.workspace = true
sha2 = { version = "0.11", default-features = false }
uuid = { workspace = true, features = ["v4", "v5", "serde"] }
chrono.workspace = true
humantime.workspace = true
+28 -2
View File
@@ -1,6 +1,7 @@
//! Neutral device-anchor transport model and deterministic derivation.
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -68,7 +69,7 @@ impl DeviceAnchor {
let mut input = domain.to_vec();
input.extend_from_slice(seed.as_ref());
Self {
hardware_id: URL_SAFE_NO_PAD.encode(openssl::sha::sha256(&input)),
hardware_id: URL_SAFE_NO_PAD.encode(Sha256::digest(&input)),
source,
}
}
@@ -78,11 +79,36 @@ impl DeviceAnchor {
mod tests {
use super::*;
#[test]
fn preserves_existing_hardware_ids_for_all_sources() {
let cases: [(AnchorSource, &[u8], &str); 3] = [
(
AnchorSource::UnixMac,
&[0, 17, 34, 51, 68, 85],
"UWDOx4AVJEuCAYfJBaPioyGtRfAkJBhMYSi8LuFsE1A",
),
(
AnchorSource::UnixRandom,
&[0, 17, 34, 51, 68, 85],
"fYXFpivIFuD9Z4I6qSNxUIMTljeLvw4xuqXgg0VJAu0",
),
(
AnchorSource::MacosIokit,
b"12345678-1234-5678-9abc-def012345678",
"K1KMtAwiOiXKQvQuRmTDKPA6-ZPF5QKUWZzmvRzeP34",
),
];
for (source, seed, expected) in cases {
let anchor = DeviceAnchor::derive(source, seed);
assert_eq!(anchor.hardware_id, expected, "{source:?}");
assert!(anchor.validate());
}
}
#[test]
fn hashes_original_seed_order_with_stable_domain_separation() {
let mac = DeviceAnchor::derive(AnchorSource::UnixMac, [0, 17, 34, 51, 68, 85]);
assert!(mac.validate());
assert_eq!(mac.hardware_id, "UWDOx4AVJEuCAYfJBaPioyGtRfAkJBhMYSi8LuFsE1A");
assert_ne!(
mac.hardware_id,
DeviceAnchor::derive(AnchorSource::UnixMac, [85, 68, 51, 34, 17, 0]).hardware_id
+148 -10
View File
@@ -12,7 +12,12 @@ use tokio_util::sync::CancellationToken;
use crate::auth::AuthWindowTheme;
use crate::{auth::SamlAuthResult, credential::Credential, log_format::LogFormat, os_profile::OsProfile};
use super::{command_runner::run_controlled, command_traits::CommandExt};
use super::{
command_runner::{ChildInput, run_observed},
command_traits::CommandExt,
};
use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_crash_exit};
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
@@ -44,6 +49,7 @@ pub struct SamlAuthLauncher<'a> {
browser_listen: Option<IpAddr>,
verbose: Option<&'a str>,
log_format: LogFormat,
dmabuf_disabled: bool,
}
impl<'a> SamlAuthLauncher<'a> {
@@ -76,9 +82,15 @@ impl<'a> SamlAuthLauncher<'a> {
browser_listen: None,
verbose: None,
log_format: LogFormat::Text,
dmabuf_disabled: false,
}
}
pub fn dmabuf_disabled(mut self, disabled: bool) -> Self {
self.dmabuf_disabled = disabled;
self
}
pub fn auth_executable(mut self, auth_executable: Option<&'a str>) -> Self {
self.auth_executable = auth_executable;
self
@@ -282,8 +294,17 @@ impl<'a> SamlAuthLauncher<'a> {
.unwrap_or_else(binary_paths::gpauth);
let auth_cmd = self.build_command(&program);
let command = auth_cmd.into_non_root()?.into_std();
let cancellation = self.cancellation;
let mut command = auth_cmd.into_non_root()?.into_std();
let embedded = cfg!(feature = "webview-auth") && self.browser.is_none();
#[cfg(feature = "webview-auth")]
let embedded = embedded && !self.default_browser;
let bundled = is_bundled_authenticator(&program, &binary_paths::gpauth());
let can_recover = embedded && bundled && eligible(&command);
if embedded && bundled && self.dmabuf_disabled {
command.env("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
}
let stdin = auth_stdin(self.browser);
let cancellation = self.cancellation.clone();
let output = tokio::task::spawn_blocking(move || {
let check = || {
if cancellation.is_cancelled() {
@@ -295,10 +316,19 @@ impl<'a> SamlAuthLauncher<'a> {
Ok(())
}
};
run_controlled(command, &check, MAX_AUTH_RESULT_BYTES)
let mut diagnostic = StderrDiagnostic::default();
let output = run_observed(
command,
&check,
Some(MAX_AUTH_RESULT_BYTES),
&mut |bytes| diagnostic.push(bytes),
&mut std::io::stderr(),
stdin,
)?;
Ok::<_, std::io::Error>((output.output, diagnostic.matched()))
})
.await?;
let output = match output {
let (output, rendering_diagnostic) = match output {
Ok(output) => output,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
return Err(crate::auth::AuthenticationCancelled.into());
@@ -306,14 +336,41 @@ impl<'a> SamlAuthLauncher<'a> {
Err(error) => return Err(error.into()),
};
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
bail!("Failed to parse auth data")
};
Credential::try_from(auth_result)
if self.cancellation.is_cancelled() {
return Err(crate::auth::AuthenticationCancelled.into());
}
decode_auth_output(output, can_recover && rendering_diagnostic)
}
}
/// `gpauth --browser remote` reads the pasted `globalprotectcallback:` data from the user's terminal.
fn auth_stdin(browser: Option<&str>) -> ChildInput<'static> {
match browser {
Some(browser) if browser.eq_ignore_ascii_case("remote") => ChildInput::Terminal,
_ => ChildInput::Null,
}
}
fn is_bundled_authenticator(program: &Path, bundled: &Path) -> bool {
match (program.canonicalize(), bundled.canonicalize()) {
(Ok(program), Ok(bundled)) => program == bundled,
_ => false,
}
}
fn decode_auth_output(output: std::process::Output, rendering_failure: bool) -> anyhow::Result<Credential> {
if !output.status.success() {
if rendering_failure && is_crash_exit(output.status) {
return Err(RenderingCrash { status: output.status }.into());
}
bail!("Authenticator exited unsuccessfully: {}", output.status);
}
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
bail!("Failed to parse auth data")
};
Credential::try_from(auth_result)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -404,4 +461,85 @@ mod tests {
assert_eq!(launcher.browser_listen, Some(listen_ip));
}
#[test]
fn only_a_remote_browser_reads_the_terminal() {
assert!(matches!(auth_stdin(Some("remote")), ChildInput::Terminal));
assert!(matches!(auth_stdin(Some("REMOTE")), ChildInput::Terminal));
assert!(matches!(auth_stdin(Some("firefox")), ChildInput::Null));
assert!(matches!(auth_stdin(None), ChildInput::Null));
}
#[test]
fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() {
use std::os::unix::process::ExitStatusExt;
for stdout in [b"{partial".to_vec(), br#"{"cancelled":null}"#.to_vec()] {
let error = decode_auth_output(
std::process::Output {
status: std::process::ExitStatus::from_raw(71 << 8),
stdout,
stderr: Vec::new(),
},
true,
)
.unwrap_err();
assert!(error.downcast_ref::<RenderingCrash>().is_some());
}
}
#[test]
fn successful_malformed_auth_output_is_not_a_rendering_crash() {
use std::os::unix::process::ExitStatusExt;
let error = decode_auth_output(
std::process::Output {
status: std::process::ExitStatus::from_raw(0),
stdout: b"partial".to_vec(),
stderr: Vec::new(),
},
true,
)
.unwrap_err();
assert!(error.downcast_ref::<RenderingCrash>().is_none());
assert_eq!(error.to_string(), "Failed to parse auth data");
}
#[tokio::test]
async fn custom_authenticator_crash_does_not_request_recovery() {
use std::os::unix::fs::PermissionsExt;
let directory = tempfile::tempdir().unwrap();
let executable = directory.path().join("auth-fixture");
std::fs::write(
&executable,
"#!/bin/sh\nprintf 'Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display.\\n' >&2\nexit 1\n",
)
.unwrap();
// The launcher drops root privileges in CI; its child must be able to
// traverse the fixture directory and execute this non-sensitive script.
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
let error = SamlAuthLauncher::new("fixture.invalid")
.auth_executable(executable.to_str())
.dmabuf_disabled(true)
.launch()
.await
.unwrap_err();
assert!(error.downcast_ref::<RenderingCrash>().is_none());
assert!(
error.to_string().starts_with("Authenticator exited unsuccessfully:"),
"unexpected launch error: {error:#}"
);
}
#[test]
fn service_provided_bundled_path_is_not_a_custom_authenticator() {
let directory = tempfile::tempdir().unwrap();
let bundled = directory.path().join("gpauth");
let custom = directory.path().join("custom");
std::fs::write(&bundled, "bundled").unwrap();
std::fs::write(&custom, "custom").unwrap();
assert!(is_bundled_authenticator(&bundled, &bundled));
assert!(!is_bundled_authenticator(&custom, &bundled));
let alias = directory.path().join("auth-alias");
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
assert!(is_bundled_authenticator(&alias, &bundled));
}
}
+1 -1
View File
@@ -179,7 +179,7 @@ mod tests {
#[test]
fn root_owned_sticky_directories_protect_collectors_without_trusting_writable_files() {
// CI runs Rust tests as root; an unprivileged process cannot create these fixtures.
// A focused privileged CI check runs this test; the ordinary suite cannot create root-owned fixtures.
if uzers::get_effective_uid() != 0 {
return;
}
+308 -35
View File
@@ -1,9 +1,9 @@
use std::{
io::{self, Read},
io::{self, Read, Write},
os::unix::process::CommandExt,
process::{Child, Command, Output, Stdio},
thread,
time::Duration,
time::{Duration, Instant},
};
use nix::{
@@ -14,71 +14,344 @@ use nix::{
use super::collection::CollectionControl;
/// Execute an already configured command. Environment, identity and executable
/// trust belong to its caller. This worker owns the process group until reaped;
/// its asynchronous caller must cancel and await it instead of dropping it.
/// What the child reads on stdin.
pub(crate) enum ChildInput<'a> {
Null,
Frame(&'a [u8]),
/// The caller's own stdin, for a child that prompts the user.
Terminal,
}
/// Owns and reaps the command's process group. Its async caller must cancel and await this worker.
pub(crate) fn run_controlled(
mut command: Command,
command: Command,
control: &dyn CollectionControl,
output_limit: usize,
) -> io::Result<Output> {
control.check()?;
let child = command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.process_group(0)
.spawn()?;
let mut child = ControlledChild(child);
let mut stdout = child.0.stdout.take().expect("controlled stdout was piped");
let flags = fcntl(&stdout, FcntlArg::F_GETFL).map_err(io::Error::from)?;
run(command, control, Some(output_limit), None, ChildInput::Null).map(|observed| observed.output)
}
#[derive(Debug)]
pub(crate) struct ObservedOutput {
pub output: Output,
pub input_error: Option<io::Error>,
}
pub(crate) fn run_observed(
command: Command,
control: &dyn CollectionControl,
output_limit: Option<usize>,
observer: &mut dyn FnMut(&[u8]),
stderr_sink: &mut dyn Write,
stdin: ChildInput<'_>,
) -> io::Result<ObservedOutput> {
run(command, control, output_limit, Some((observer, stderr_sink)), stdin)
}
fn nonblocking(fd: &impl std::os::fd::AsFd) -> io::Result<()> {
let flags = fcntl(fd, FcntlArg::F_GETFL).map_err(io::Error::from)?;
fcntl(
&stdout,
fd,
FcntlArg::F_SETFL(OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK),
)
.map_err(io::Error::from)?;
Ok(())
}
fn run(
mut command: Command,
control: &dyn CollectionControl,
output_limit: Option<usize>,
mut observation: Option<(&mut dyn FnMut(&[u8]), &mut dyn Write)>,
stdin: ChildInput<'_>,
) -> io::Result<ObservedOutput> {
control.check()?;
command.stdout(if output_limit.is_some() {
Stdio::piped()
} else {
Stdio::inherit()
});
// A child in a process group of its own is a background job, so reading the terminal would stop it with SIGTTIN.
let own_group = !matches!(stdin, ChildInput::Terminal);
if own_group {
command.process_group(0);
}
let (stdio, stdin_frame) = match stdin {
ChildInput::Null => (Stdio::null(), None),
ChildInput::Frame(frame) => (Stdio::piped(), Some(frame)),
ChildInput::Terminal => (Stdio::inherit(), None),
};
command.stdin(stdio);
if observation.is_some() {
command.stderr(Stdio::piped());
}
let mut child = ControlledChild {
process: command.spawn()?,
own_group,
stopped: false,
};
let mut stdout = child.process.stdout.take();
if let Some(pipe) = &stdout {
nonblocking(pipe)?;
}
let mut stderr = if observation.is_some() {
child.process.stderr.take()
} else {
None
};
if let Some(pipe) = &stderr {
nonblocking(pipe)?;
}
let mut input = child.process.stdin.take();
if let Some(pipe) = &input {
nonblocking(pipe)?;
}
let mut input_offset = 0;
let mut input_error = None;
let mut output = Vec::new();
let mut buffer = [0u8; 8192];
let mut eof = false;
let mut stdout_eof = stdout.is_none();
let mut stderr_eof = stderr.is_none();
let mut status = None;
let mut exited_at = None;
loop {
control.check()?;
if !eof {
match stdout.read(&mut buffer) {
Ok(0) => eof = true,
let mut progressed = false;
if let (Some(frame), Some(pipe)) = (stdin_frame, &mut input) {
if input_offset < frame.len() && input_error.is_none() {
match pipe.write(&frame[input_offset..]) {
Ok(0) => input_error = Some(io::Error::new(io::ErrorKind::WriteZero, "Credential input pipe closed")),
Ok(length) => {
input_offset += length;
progressed = true;
}
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
Err(error) => input_error = Some(error),
}
}
}
if !stdout_eof {
match stdout.as_mut().unwrap().read(&mut buffer) {
Ok(0) => stdout_eof = true,
Ok(length) => {
if length > output_limit.saturating_sub(output.len()) {
if length > output_limit.unwrap().saturating_sub(output.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Command output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
continue;
progressed = true;
}
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
Err(error) => return Err(error),
}
}
if status.is_none() {
status = child.0.try_wait()?;
if !stderr_eof {
match stderr.as_mut().unwrap().read(&mut buffer) {
Ok(0) => stderr_eof = true,
Ok(length) => {
let (observer, sink) = observation.as_mut().unwrap();
observer(&buffer[..length]);
sink.write_all(&buffer[..length])?;
progressed = true;
}
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
Err(error) => return Err(error),
}
}
if eof && let Some(status) = status {
return Ok(Output {
status,
stdout: output,
stderr: Vec::new(),
});
if status.is_none()
&& let Some(exit_status) = child.process.try_wait()?
{
status = Some(exit_status);
exited_at = Some(Instant::now());
child.stop_helpers();
}
if let Some(status) = status {
if (stdout_eof && stderr_eof) || exited_at.unwrap().elapsed() >= Duration::from_millis(250) {
if stdin_frame.is_some_and(|frame| input_offset < frame.len()) && input_error.is_none() {
input_error = Some(io::Error::new(
io::ErrorKind::BrokenPipe,
"Child exited before receiving its credential",
));
}
return Ok(ObservedOutput {
output: Output {
status,
stdout: output,
stderr: Vec::new(),
},
input_error,
});
}
}
if !progressed {
thread::sleep(Duration::from_millis(10));
}
thread::sleep(Duration::from_millis(10));
}
}
struct ControlledChild(Child);
struct ControlledChild {
process: Child,
own_group: bool,
stopped: bool,
}
impl ControlledChild {
fn stop_helpers(&mut self) {
if !self.stopped {
if self.own_group {
let _ = killpg(Pid::from_raw(self.process.id() as i32), Signal::SIGKILL);
} else {
let _ = self.process.kill();
}
self.stopped = true;
}
}
}
impl Drop for ControlledChild {
fn drop(&mut self) {
// Reap the direct child and stop helpers retaining stdout after it exits.
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
let _ = self.0.wait();
self.stop_helpers();
let _ = self.process.wait();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn drains_both_pipes_and_reaps_helpers_that_hold_them_open() {
let mut command = Command::new("sh");
command.args(["-c", "printf auth; printf diagnostic >&2; sleep 30 & exit 1"]);
let mut seen = Vec::new();
let mut sink = Vec::new();
let start = Instant::now();
let output = run_observed(
command,
&|| Ok(()),
Some(1024),
&mut |bytes| seen.extend_from_slice(bytes),
&mut sink,
ChildInput::Null,
)
.unwrap();
assert!(!output.output.status.success());
assert_eq!(output.output.stdout, b"auth");
assert_eq!(seen, b"diagnostic");
assert_eq!(sink, seen);
assert!(start.elapsed() < Duration::from_secs(2));
}
#[test]
fn continuous_stderr_does_not_starve_cancellation_or_stdout() {
let mut command = Command::new("sh");
command.args(["-c", "printf auth; while :; do printf 'diagnostic\\n' >&2; done"]);
let start = Instant::now();
let control = || {
if start.elapsed() > Duration::from_millis(100) {
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
} else {
Ok(())
}
};
let error = run_observed(
command,
&control,
Some(1024),
&mut |_| {},
&mut io::sink(),
ChildInput::Null,
)
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
assert!(start.elapsed() < Duration::from_secs(2));
}
#[test]
fn retains_broken_input_pipe_for_failed_child_without_a_diagnostic() {
let mut command = Command::new("sh");
command.args(["-c", "exec 0<&-; exit 2"]);
let observed = run_observed(
command,
&|| Ok(()),
None,
&mut |_| {},
&mut io::sink(),
ChildInput::Frame(&vec![0; 128 * 1024]),
)
.unwrap();
assert_eq!(observed.output.status.code(), Some(2));
assert!(observed.input_error.is_some());
}
#[test]
fn cancellation_interrupts_a_blocked_credential_write() {
let mut command = Command::new("sh");
command.args(["-c", "sleep 30"]);
let start = Instant::now();
let control = || {
if start.elapsed() > Duration::from_millis(100) {
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
} else {
Ok(())
}
};
let error = run_observed(
command,
&control,
None,
&mut |_| {},
&mut io::sink(),
ChildInput::Frame(&vec![0; 128 * 1024]),
)
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
assert!(start.elapsed() < Duration::from_secs(2));
}
#[cfg(target_os = "linux")]
#[test]
fn terminal_input_shares_the_callers_stdin_and_process_group() {
let mut command = Command::new("sh");
command.args(["-c", "readlink /proc/$$/fd/0; cut -d' ' -f5 /proc/$$/stat"]);
let observed = run_observed(
command,
&|| Ok(()),
Some(1024),
&mut |_| {},
&mut io::sink(),
ChildInput::Terminal,
)
.unwrap();
let stdout = String::from_utf8(observed.output.stdout).unwrap();
let stdin = std::fs::read_link("/proc/self/fd/0").unwrap();
assert_eq!(stdout, format!("{}\n{}\n", stdin.display(), nix::unistd::getpgrp()));
}
#[test]
fn cancellation_kills_a_terminal_child() {
let mut command = Command::new("sleep");
command.arg("30");
let start = Instant::now();
let control = || {
if start.elapsed() > Duration::from_millis(100) {
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
} else {
Ok(())
}
};
let error = run_observed(
command,
&control,
None,
&mut |_| {},
&mut io::sink(),
ChildInput::Terminal,
)
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
assert!(start.elapsed() < Duration::from_secs(2));
}
}
+71
View File
@@ -0,0 +1,71 @@
use super::{
command_runner::{ChildInput, run_observed},
rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible_with_inheritance, is_crash_exit},
};
use crate::service::transport::SessionCredential;
use anyhow::Context;
use std::{
collections::HashMap,
fs::OpenOptions,
path::PathBuf,
process::{Command, ExitStatus},
};
use tokio_util::sync::CancellationToken;
/// Monitor a credential-bearing desktop child; the owner cancels and joins this attempt.
pub(super) async fn launch_desktop_child(
name: &'static str,
command: Command,
envs: Option<&HashMap<String, String>>,
credential: &SessionCredential,
cancellation: &CancellationToken,
) -> anyhow::Result<ExitStatus> {
let retry_eligible = eligible_with_inheritance(&command, envs.is_none());
let log_file = match envs {
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from),
};
let mut sink: Box<dyn std::io::Write + Send> = match log_file {
Some(path) => Box::new(
OpenOptions::new()
.append(true)
.open(&path)
.with_context(|| format!("Failed to open GUI log file: {}", path.display()))?,
),
None => Box::new(std::io::stderr()),
};
let frame = credential.encode_frame()?;
let cancellation = cancellation.clone();
tokio::task::spawn_blocking(move || {
let check = || {
if cancellation.is_cancelled() {
Err(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"Desktop child launch cancelled",
))
} else {
Ok(())
}
};
let mut diagnostic = StderrDiagnostic::default();
let observed = run_observed(
command,
&check,
None,
&mut |bytes| diagnostic.push(bytes),
&mut sink,
ChildInput::Frame(&frame),
)?;
let output = observed.output;
if is_crash_exit(output.status) && retry_eligible && diagnostic.matched() {
return Err(RenderingCrash { status: output.status }.into());
}
if let Some(error) = observed.input_error {
return Err(error.into());
}
anyhow::ensure!(output.status.success(), "{name} exited with {}", output.status);
Ok(output.status)
})
.await?
}
+91 -25
View File
@@ -6,12 +6,16 @@ use std::{
sync::Arc,
};
use super::rendering_recovery::RecoveryState;
use crate::service::transport::{DESKTOP_GUI_EXITED, DESKTOP_RENDERING_RETRY};
use anyhow::{Context, ensure};
use common::binary_paths;
use log::warn;
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
process::Command,
};
use tokio_util::sync::CancellationToken;
use zeroize::Zeroizing;
use super::{CommandExt, gui_launcher::GuiLauncher};
@@ -64,34 +68,96 @@ impl<'a> DesktopLauncher<'a> {
.context("Service credential pipe is unavailable")?;
let mut received_credential = false;
let mut cancelled = false;
let result = tokio::select! {
_ = crate::utils::shutdown_signal() => { cancelled = true; Ok(()) },
result = async {
let mut minimized = self.minimized;
loop {
let credential = read_credential(&mut output).await?;
let Some(credential) = credential else { return Ok(()); };
received_credential = true;
ensure!(credential.product_version() == self.version, "Service product version mismatch");
let mut envs: HashMap<String, String> = std::env::vars().collect();
if let Some(path) = &self.log_file {
envs.insert("GP_LOG_FILE".into(), path.clone());
}
let launcher = GuiLauncher::new(self.version, Arc::new(credential)).envs(envs).minimized(minimized);
let mut unexpected = [0];
tokio::select! {
result = launcher.launch() => { result?; }
status = service.wait() => { anyhow::bail!("The privileged service exited while the GUI was running: {}", status?); }
result = output.read(&mut unexpected) => {
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
anyhow::bail!("The privileged service closed its credential channel");
let cancellation = CancellationToken::new();
let mut recovery = RecoveryState::default();
let result = {
let operation = async {
let mut minimized = self.minimized;
let mut expecting_renewal = false;
let mut program = None;
loop {
let credential = tokio::select! {
biased;
_ = cancellation.cancelled() => return Ok(()),
result = read_credential(&mut output) => result?,
};
let Some(credential) = credential else {
ensure!(
!expecting_renewal,
"Service closed before issuing the recovery credential"
);
return Ok(());
};
expecting_renewal = false;
received_credential = true;
ensure!(
credential.product_version() == self.version,
"Service product version mismatch"
);
let mut envs: HashMap<String, String> = std::env::vars().collect();
if recovery.dmabuf_disabled() {
envs.insert("WEBKIT_DISABLE_DMABUF_RENDERER".into(), "1".into());
}
if let Some(path) = &self.log_file {
envs.insert("GP_LOG_FILE".into(), path.clone());
}
let launcher = GuiLauncher::new(self.version, Arc::new(credential))
.envs(envs)
.minimized(minimized);
let mut unexpected = [0];
// Program resolution may launch the WebKit download helper. Keep it under
// the same cancellation, service ownership and recovery budget as gpgui.
let attempt = async {
if program.is_none() {
program = Some(launcher.resolve_program(&cancellation).await?);
}
launcher.launch_program(program.as_ref().unwrap(), &cancellation).await
};
tokio::pin!(attempt);
let outcome = tokio::select! {
biased;
_ = cancellation.cancelled() => { let _ = attempt.await; return Ok(()); }
result = &mut attempt => result,
status = service.wait() => {
cancellation.cancel(); let _ = attempt.await;
anyhow::bail!("The privileged service exited while the GUI was running: {}", status?);
}
result = output.read(&mut unexpected) => {
cancellation.cancel(); let _ = attempt.await;
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
anyhow::bail!("The privileged service closed its credential channel");
}
};
if cancellation.is_cancelled() {
return Ok(());
}
match outcome {
Err(error) if recovery.recover(&error) => {
warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows");
expecting_renewal = true;
input.write_all(&[DESKTOP_RENDERING_RETRY]).await?;
}
Err(error) => return Err(recovery.terminal(error)),
Ok(_) => {
input.write_all(&[DESKTOP_GUI_EXITED]).await?;
minimized = false;
}
}
}
input.write_all(&[0]).await?;
minimized = false;
}
} => result,
};
tokio::pin!(operation);
let result = tokio::select! {
biased;
_ = crate::utils::shutdown_signal() => {
cancelled = true;
cancellation.cancel();
operation.await
},
result = &mut operation => result,
};
result
};
let result = recovery.finish(result);
// EOF lets the service revoke the credential and disconnect the VPN gracefully.
drop(input);
if cancelled && !received_credential {
+108 -21
View File
@@ -1,9 +1,9 @@
use std::{collections::HashMap, path::PathBuf, process::Stdio};
use std::{collections::HashMap, path::PathBuf};
use anyhow::bail;
use common::binary_paths;
use log::info;
use tokio::{io::AsyncWriteExt, process::Command};
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
use crate::service::transport::SessionCredential;
@@ -34,7 +34,7 @@ impl<'a> GuiHelperLauncher<'a> {
self
}
pub async fn launch(&self) -> anyhow::Result<()> {
pub async fn launch(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
let mut cmd = Command::new(&self.program);
if let Some(envs) = self.envs {
@@ -53,23 +53,110 @@ impl<'a> GuiHelperLauncher<'a> {
uzers::get_effective_uid() != 0,
"The desktop GUI must not be launched by root"
);
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
};
let Some(mut stdin) = child.stdin.take() else {
bail!("Failed to open stdin");
};
let frame = self.credential.encode_frame()?;
stdin.write_all(&frame).await?;
let exit_status = child.wait().await?;
drop(stdin);
info!("gpgui-helper exited with: {}", exit_status);
super::desktop_child::launch_desktop_child(
"gpgui-helper",
cmd.into_std(),
self.envs,
self.credential,
cancellation,
)
.await?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::process::rendering_recovery::RenderingCrash;
use std::{fs, os::unix::fs::PermissionsExt};
fn fixture(dir: &tempfile::TempDir, credential: &SessionCredential, body: &str) -> PathBuf {
let path = dir.path().join("helper");
let length = credential.encode_frame().unwrap().len();
fs::write(
&path,
format!("#!/bin/sh\ndd bs=1 count={length} of=/dev/null 2>/dev/null || exit 1\n{body}\n"),
)
.unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
path
}
#[tokio::test]
async fn propagates_helper_failure_and_preserves_stderr_in_desktop_log() {
let dir = tempfile::TempDir::new().unwrap();
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
let path = fixture(&dir, &credential, "printf 'download failed\\n' >&2; exit 23");
let log = dir.path().join("desktop.log");
fs::write(&log, "").unwrap();
let envs = HashMap::from([("GP_LOG_FILE".into(), log.to_str().unwrap().into())]);
let launcher = GuiHelperLauncher {
program: path,
envs: Some(&envs),
credential: &credential,
gui_version: None,
};
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
assert!(error.to_string().contains("gpgui-helper exited with"), "{error:#}");
assert!(error.to_string().contains("23"));
assert_eq!(fs::read_to_string(log).unwrap(), "download failed\n");
}
#[tokio::test]
async fn recognizes_helper_rendering_crash_and_respects_explicit_override() {
let dir = tempfile::TempDir::new().unwrap();
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
let path = fixture(
&dir,
&credential,
"printf '(gpgui-helper:42): Gdk-Message: 12:00:00: Error 71 (Protocol error) dispatching to Wayland display.\\n' >&2; exit 1",
);
let mut envs = HashMap::from([("WAYLAND_DISPLAY".into(), "wayland-0".into())]);
for override_value in [None, Some(""), Some("0"), Some("1")] {
if let Some(value) = override_value {
envs.insert("WEBKIT_DISABLE_DMABUF_RENDERER".into(), value.into());
}
let launcher = GuiHelperLauncher {
program: path.clone(),
envs: Some(&envs),
credential: &credential,
gui_version: None,
};
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
let eligible =
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")) && override_value.is_none();
assert_eq!(error.downcast_ref::<RenderingCrash>().is_some(), eligible, "{error:#}");
}
}
#[tokio::test]
async fn cancellation_joins_helper_before_returning() {
let dir = tempfile::TempDir::new().unwrap();
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
let pid_file = dir.path().join("pid");
let body = format!("echo $$ > '{}'; exec sleep 30", pid_file.display());
let path = fixture(&dir, &credential, &body);
let envs = HashMap::new();
let launcher = GuiHelperLauncher {
program: path,
envs: Some(&envs),
credential: &credential,
gui_version: None,
};
let cancellation = CancellationToken::new();
let attempt = launcher.launch(&cancellation);
tokio::pin!(attempt);
tokio::select! {
result = &mut attempt => panic!("helper exited early: {result:?}"),
_ = async { while !pid_file.exists() { tokio::time::sleep(std::time::Duration::from_millis(10)).await; } } => {}
}
cancellation.cancel();
assert!(attempt.await.is_err());
let pid: i32 = fs::read_to_string(pid_file).unwrap().trim().parse().unwrap();
assert_eq!(
nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None),
Err(nix::errno::Errno::ESRCH)
);
}
}
+97 -53
View File
@@ -1,15 +1,15 @@
use std::{
collections::HashMap,
fs::OpenOptions,
path::{Path, PathBuf},
process::{ExitStatus, Stdio},
process::ExitStatus,
sync::Arc,
};
use anyhow::{Context, bail};
use anyhow::bail;
use common::binary_paths;
use log::info;
use tokio::{io::AsyncWriteExt, process::Command};
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport::SessionCredential};
@@ -50,20 +50,26 @@ impl<'a> GuiLauncher<'a> {
self
}
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
pub(crate) async fn resolve_program(&self, cancellation: &CancellationToken) -> anyhow::Result<PathBuf> {
anyhow::ensure!(
uzers::get_effective_uid() != 0,
"The desktop GUI must not be launched by root"
);
if let Some(program) = self.find_compatible_program().await {
return self.launch_program(&program).await;
if let Some(program) = tokio::select! {
biased;
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
result = self.find_compatible_program() => result,
} {
return Ok(program);
}
self.download_program().await?;
self.download_program(cancellation).await?;
let program = binary_paths::gpgui_update_target();
self.check_version(&program).await?;
self.launch_program(&program).await
tokio::select! {
biased;
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
result = self.check_version(&program) => result?,
}
Ok(program)
}
async fn find_compatible_program(&self) -> Option<PathBuf> {
@@ -80,50 +86,28 @@ impl<'a> GuiLauncher<'a> {
None
}
async fn launch_program(&self, program: &Path) -> anyhow::Result<ExitStatus> {
pub(crate) async fn launch_program(
&self,
program: &Path,
cancellation: &CancellationToken,
) -> anyhow::Result<ExitStatus> {
let mut cmd = Command::new(program);
if let Some(envs) = &self.envs {
cmd.env_clear();
cmd.envs(envs);
cmd.env_clear().envs(envs);
}
let log_file = match &self.envs {
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from),
};
if let Some(path) = log_file {
let file = OpenOptions::new()
.append(true)
.open(&path)
.with_context(|| format!("Failed to open GUI log file: {}", path.display()))?;
cmd.stderr(Stdio::from(file));
}
cmd.arg("--service-credential-on-stdin");
if self.minimized {
cmd.arg("--minimized");
}
info!("Launching gpgui");
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", program.display(), err),
};
let Some(mut stdin) = child.stdin.take() else {
bail!("Failed to open stdin");
};
let frame = self.credential.encode_frame()?;
stdin.write_all(&frame).await?;
let exit_status = child.wait().await?;
drop(stdin);
Ok(exit_status)
super::desktop_child::launch_desktop_child(
"gpgui",
cmd.into_std(),
self.envs.as_ref(),
&self.credential,
cancellation,
)
.await
}
async fn check_version(&self, program: &Path) -> anyhow::Result<()> {
@@ -132,7 +116,7 @@ impl<'a> GuiLauncher<'a> {
cmd.env_clear();
cmd.envs(envs);
}
cmd.arg("--version");
cmd.kill_on_drop(true).arg("--version");
let output = cmd.output().await?;
if !output.status.success() {
bail!("Version command exited with {}", output.status);
@@ -153,13 +137,13 @@ impl<'a> GuiLauncher<'a> {
Ok(())
}
async fn download_program(&self) -> anyhow::Result<()> {
async fn download_program(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
let gui_helper = GuiHelperLauncher::new(&self.credential);
gui_helper
.envs(self.envs.as_ref())
.gui_version(Some(self.version))
.launch()
.launch(cancellation)
.await
}
}
@@ -218,14 +202,74 @@ mod tests {
.unwrap();
fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
assert!(launcher.launch_program(&program).await.unwrap().success());
assert!(launcher.launch_program(&program).await.unwrap().success());
assert!(
launcher
.launch_program(&program, &CancellationToken::new())
.await
.unwrap()
.success()
);
assert!(
launcher
.launch_program(&program, &CancellationToken::new())
.await
.unwrap()
.success()
);
assert_eq!(
fs::read_to_string(log_file).unwrap(),
"[gpservice] started\n[gpgui] initialized\n[gpgui] initialized\n"
);
}
#[tokio::test]
async fn cancellation_stops_a_hung_version_probe_before_other_candidates() {
let dir = TempDir::new().unwrap();
let pid_file = dir.path().join("version.pid");
let next_marker = dir.path().join("next-probe");
let first = dir.path().join("hung");
let second = dir.path().join("next");
fs::write(
&first,
format!("#!/bin/sh\necho $$ > '{}'; exec sleep 30\n", pid_file.display()),
)
.unwrap();
fs::write(
&second,
format!(
"#!/bin/sh\ntouch '{}'; echo 'gpgui test-version'\n",
next_marker.display()
),
)
.unwrap();
for path in [&first, &second] {
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
}
let launcher = launcher(VERSION, vec![first, second]);
let cancellation = CancellationToken::new();
let attempt = launcher.resolve_program(&cancellation);
tokio::pin!(attempt);
tokio::select! {
result = &mut attempt => panic!("version probe exited early: {result:?}"),
ready = tokio::time::timeout(std::time::Duration::from_secs(5), async {
while !pid_file.exists() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
}) => ready.unwrap(),
}
cancellation.cancel();
assert!(attempt.await.unwrap_err().to_string().contains("cancelled"));
assert!(!next_marker.exists());
let pid: i32 = fs::read_to_string(pid_file).unwrap().trim().parse().unwrap();
tokio::time::timeout(std::time::Duration::from_secs(5), async {
while nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None).is_ok() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.unwrap();
}
#[tokio::test]
async fn prefers_the_first_compatible_program() {
let dir = TempDir::new().unwrap();
+3
View File
@@ -1,5 +1,6 @@
mod command_runner;
mod command_traits;
mod desktop_child;
mod desktop_session_env;
pub(crate) mod gui_helper_launcher;
@@ -11,3 +12,5 @@ pub mod gui_launcher;
pub mod users;
pub mod collection;
pub mod rendering_recovery;
@@ -0,0 +1,226 @@
use std::process::{Command, ExitStatus};
const DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";
const DIAGNOSTIC: &[u8] = b"Error 71 (Protocol error) dispatching to Wayland display";
#[derive(Debug, thiserror::Error)]
#[error("WebKit Wayland rendering process exited with {status}")]
pub struct RenderingCrash {
pub status: ExitStatus,
}
#[derive(Debug, thiserror::Error)]
#[error("Rendering recovery failed: {0:#}. Collect diagnostics for a bug report")]
pub struct RecoveryFailed(#[source] anyhow::Error);
#[derive(Default)]
pub struct RecoveryState {
first_failure: Option<String>,
}
impl RecoveryState {
pub fn dmabuf_disabled(&self) -> bool {
self.first_failure.is_some()
}
pub fn recover(&mut self, error: &anyhow::Error) -> bool {
if self.first_failure.is_none() && error.downcast_ref::<RenderingCrash>().is_some() {
self.first_failure = Some(error.to_string());
true
} else {
false
}
}
pub fn terminal(&self, error: anyhow::Error) -> anyhow::Error {
if error.downcast_ref::<crate::auth::AuthenticationCancelled>().is_some()
|| error.downcast_ref::<RecoveryFailed>().is_some()
{
return error;
}
match &self.first_failure {
Some(first) => RecoveryFailed(error.context(format!("First attempt: {first}"))).into(),
None => error,
}
}
pub fn finish<T>(&self, result: anyhow::Result<T>) -> anyhow::Result<T> {
result.map_err(|error| self.terminal(error))
}
}
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
use std::os::unix::process::ExitStatusExt;
!status.success() && !matches!(status.signal(), Some(1 | 2 | 9 | 15))
}
pub fn eligible(command: &Command) -> bool {
eligible_with_inheritance(command, true)
}
pub(crate) fn eligible_with_inheritance(command: &Command, inherits: bool) -> bool {
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))
&& effective_env(command, "WAYLAND_DISPLAY", inherits).is_some_and(|value| !value.is_empty())
&& effective_env(command, DMABUF, inherits).is_none()
}
fn effective_env(command: &Command, key: &str, inherits: bool) -> Option<std::ffi::OsString> {
for (name, value) in command.get_envs() {
if name == key {
return value.map(ToOwned::to_owned);
}
}
inherits.then(|| std::env::var_os(key)).flatten()
}
/// Observes diagnostic lines without retaining arbitrary application output.
#[derive(Default)]
pub(crate) struct StderrDiagnostic {
line: Vec<u8>,
overflow: bool,
matched: bool,
}
impl StderrDiagnostic {
pub(crate) fn push(&mut self, bytes: &[u8]) {
for &byte in bytes {
if byte == b'\n' {
self.check_line();
self.line.clear();
self.overflow = false;
} else if self.line.len() < 1024 {
self.line.push(byte);
} else {
self.overflow = true;
}
}
}
fn check_line(&mut self) {
let line = self.line.trim_ascii_end();
let message = line.strip_suffix(b".").unwrap_or(line);
if !self.overflow
&& (line.starts_with(b"Gdk-Message:")
|| line.starts_with(b"(gpgui:")
|| line.starts_with(b"(gpauth:")
|| line.starts_with(b"(gpgui-helper:"))
&& line.windows(b"Gdk-Message:".len()).any(|part| part == b"Gdk-Message:")
&& message.ends_with(DIAGNOSTIC)
{
self.matched = true;
}
}
pub(crate) fn matched(&mut self) -> bool {
self.check_line();
self.matched
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn recognizes_split_diagnostic_without_matching_quoted_warning() {
let mut observer = StderrDiagnostic::default();
observer.push(b"warning: Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display.\n");
assert!(!observer.matched());
observer.push(b"Gdk-Message: 12:00:00: Error 71 (Protocol error) dispat");
observer.push(b"ching to Wayland display.\n");
assert!(observer.matched());
}
#[test]
fn recognizes_real_gtk_diagnostic_with_prefix_and_line_endings() {
for prefix in [
"Gdk-Message:",
"(gpauth:42): Gdk-Message:",
"(gpgui:42): Gdk-Message:",
"(gpgui-helper:42): Gdk-Message:",
] {
for punctuation in ["", "."] {
for ending in ["\n", "\r\n", "", " \t\n"] {
let line = format!(
"{prefix} 10:49:22.617: Error 71 (Protocol error) dispatching to Wayland display{punctuation}{ending}"
);
let mut observer = StderrDiagnostic::default();
for chunk in line.as_bytes().chunks(7) {
observer.push(chunk);
}
assert!(observer.matched(), "unrecognized GTK diagnostic: {line:?}");
}
}
}
}
#[test]
fn rejects_quoted_or_extended_gtk_diagnostic() {
for line in [
"warning: Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display.\n",
"Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display. Retry suggested\n",
"Gdk-Message: Error 70 (Communication error) dispatching to Wayland display.\n",
] {
let mut observer = StderrDiagnostic::default();
observer.push(line.as_bytes());
assert!(!observer.matched(), "incorrectly recognized: {line:?}");
}
}
#[test]
fn oversized_lines_do_not_grow_or_match() {
let mut observer = StderrDiagnostic::default();
observer.push(&vec![b'x'; 100_000]);
assert_eq!(observer.line.len(), 1024);
observer.push(DIAGNOSTIC);
assert!(!observer.matched());
}
#[test]
fn respects_explicit_overrides_and_x11_environment() {
let mut command = Command::new("fixture");
command.env_clear().env("WAYLAND_DISPLAY", "wayland-0");
let platform = cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"));
assert_eq!(eligible_with_inheritance(&command, false), platform);
for value in ["", "0", "1"] {
command.env(DMABUF, value);
assert!(!eligible_with_inheritance(&command, false));
}
command
.env_remove(DMABUF)
.env_remove("WAYLAND_DISPLAY")
.env("DISPLAY", ":0");
assert!(!eligible_with_inheritance(&command, false));
}
#[test]
fn recovery_is_once_and_preserves_cancellation_and_both_failures() {
use std::os::unix::process::ExitStatusExt;
let mut recovery = RecoveryState::default();
let first = RenderingCrash {
status: ExitStatus::from_raw(71 << 8),
}
.into();
assert!(recovery.recover(&first));
assert!(!recovery.recover(&first));
assert!(
recovery
.terminal(crate::auth::AuthenticationCancelled.into())
.downcast_ref::<crate::auth::AuthenticationCancelled>()
.is_some()
);
let error = recovery.terminal(anyhow::anyhow!("second exit 72"));
assert!(error.downcast_ref::<RecoveryFailed>().is_some());
assert!(error.to_string().contains("71"));
assert!(error.to_string().contains("second exit 72"));
}
#[test]
fn explicit_termination_is_not_a_rendering_crash() {
use std::os::unix::process::ExitStatusExt;
for signal in [1, 2, 9, 15] {
assert!(!is_crash_exit(ExitStatus::from_raw(signal)));
}
assert!(is_crash_exit(ExitStatus::from_raw(6)));
assert!(is_crash_exit(ExitStatus::from_raw(71 << 8)));
assert!(!is_crash_exit(ExitStatus::from_raw(0)));
}
}
@@ -17,3 +17,7 @@ pub const HIP_PROTOCOL_VERSION: u16 = 1;
pub const MAX_PLAINTEXT: usize = 60 * 1024;
pub const MAX_WS_MESSAGE: usize = u16::MAX as usize;
pub const MAX_SERVICE_MESSAGE: usize = 256;
/// Private desktop control messages; never carry credentials.
pub const DESKTOP_GUI_EXITED: u8 = 0;
pub const DESKTOP_RENDERING_RETRY: u8 = 1;
+28 -7
View File
@@ -1,11 +1,11 @@
use chacha20poly1305::{
AeadCore, ChaCha20Poly1305, Key, KeyInit,
aead::{Aead, OsRng},
ChaCha20Poly1305, Key, KeyInit, Nonce,
aead::{Aead, Generate},
};
use serde::{Serialize, de::DeserializeOwned};
pub fn generate_key() -> Key {
ChaCha20Poly1305::generate_key(&mut OsRng)
Key::generate()
}
pub fn encrypt<T>(key: &Key, value: &T) -> anyhow::Result<Vec<u8>>
@@ -13,7 +13,7 @@ where
T: Serialize,
{
let cipher = ChaCha20Poly1305::new(key);
let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
let nonce = Nonce::generate();
let data = serde_json::to_vec(value)?;
let cipher_text = cipher.encrypt(&nonce, data.as_ref())?;
@@ -34,7 +34,7 @@ where
let nonce = &encrypted[..12];
let cipher_text = &encrypted[12..];
let plaintext = cipher.decrypt(nonce.into(), cipher_text)?;
let plaintext = cipher.decrypt(nonce.try_into()?, cipher_text)?;
let value = serde_json::from_slice(&plaintext)?;
@@ -52,14 +52,14 @@ impl Crypto {
pub fn encrypt<T: Serialize>(&self, plain: T) -> anyhow::Result<Vec<u8>> {
let key: &[u8] = &self.key;
let encrypted_data = encrypt(key.into(), &plain)?;
let encrypted_data = encrypt(key.try_into()?, &plain)?;
Ok(encrypted_data)
}
pub fn decrypt<T: DeserializeOwned>(&self, encrypted: Vec<u8>) -> anyhow::Result<T> {
let key: &[u8] = &self.key;
decrypt(key.into(), encrypted)
decrypt(key.try_into()?, encrypted)
}
pub fn encrypt_to<T: Serialize>(&self, path: &std::path::Path, plain: T) -> anyhow::Result<()> {
@@ -105,4 +105,25 @@ mod tests {
Ok(())
}
#[test]
fn decrypts_settings_written_with_chacha20poly1305_0_10() -> anyhow::Result<()> {
// Fixed key and ciphertext are test data produced with version 0.10.1.
let key = [7_u8; 32];
let encrypted =
crate::utils::base64::decode_to_vec("AwMDAwMDAwMDAwMDkIQjBvvxesN7T/Suv8tEE53zfpGGup/QlB6Dbj1ah+NIXCDMOv/4eg==")?;
let user: User = decrypt((&key).into(), encrypted.clone())?;
assert_eq!(user.name, "test");
assert_eq!(user.age, 18);
// The nonce prefix and appended authentication tag retain their existing format.
let cipher = ChaCha20Poly1305::new((&key).into());
let ciphertext = cipher.encrypt(encrypted[..12].try_into()?, serde_json::to_vec(&user)?.as_slice())?;
assert_eq!(ciphertext, encrypted[12..]);
let mut tampered = encrypted;
*tampered.last_mut().unwrap() ^= 1;
assert!(decrypt::<User>((&key).into(), tampered).is_err());
Ok(())
}
}
+3
View File
@@ -15,3 +15,6 @@ cc = "1"
autotools = "0.2"
pkg-config = "0.3"
fs_extra = "1"
[dev-dependencies]
tempfile = "3"
+21
View File
@@ -137,6 +137,27 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let lib_dir = dst.join("lib");
let include_dir = dst.join("include");
#[cfg(target_os = "macos")]
{
// Do not embed Cargo's temporary build directory in consumers of this library.
let library = std::fs::canonicalize(lib_dir.join("libopenconnect.dylib")).unwrap();
let library_name = library.file_name().unwrap().to_str().unwrap();
let status = std::process::Command::new("install_name_tool")
.arg("-id")
.arg(format!("@rpath/{library_name}"))
.arg(&library)
.status()
.expect("Failed to update the OpenConnect dylib install name");
assert!(status.success(), "Failed to update the OpenConnect dylib install name");
let status = std::process::Command::new("codesign")
.args(["--force", "--sign", "-"])
.arg(&library)
.status()
.expect("Failed to sign the OpenConnect dylib");
assert!(status.success(), "Failed to sign the OpenConnect dylib");
println!("cargo:lib_dir={}", lib_dir.display());
}
println!("cargo:rustc-link-search=native={}", lib_dir.display());
#[cfg(target_os = "macos")]
+34
View File
@@ -34,9 +34,23 @@ pub fn find_vpnc_script() -> Option<String> {
if let Some(path) = std::env::var_os("GP_VPNC_SCRIPT").filter(|path| !path.is_empty()) {
return configured_script(Path::new(&path));
}
if let Ok(executable) = std::env::current_exe()
&& let Some(script) = installed_vpnc_script(&executable)
{
return Some(script);
}
find_executable(VPNC_SCRIPT_LOCATIONS).map(str::to_owned)
}
fn installed_vpnc_script(executable: &Path) -> Option<String> {
let executable = executable.canonicalize().ok()?;
let bin = executable.parent()?;
if bin.file_name()? != "bin" {
return None;
}
configured_script(&bin.parent()?.join("libexec/gpclient/vpnc-script"))
}
fn configured_script(path: &Path) -> Option<String> {
if path.is_absolute() && path.is_file() && path.is_executable() {
return path.to_str().map(str::to_owned);
@@ -62,6 +76,26 @@ pub fn check_executable(file: &str) -> Result<(), io::Error> {
mod tests {
use super::*;
#[test]
fn installed_script_follows_the_executable_prefix_through_symlinks() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("prefix/bin");
let libexec = dir.path().join("prefix/libexec/gpclient");
std::fs::create_dir_all(&bin).unwrap();
std::fs::create_dir_all(&libexec).unwrap();
std::fs::write(bin.join("gpclient"), "").unwrap();
let script = libexec.join("vpnc-script");
std::fs::write(&script, "#!/bin/sh\n").unwrap();
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
let link = dir.path().join("gpclient-link");
std::os::unix::fs::symlink(bin.join("gpclient"), &link).unwrap();
assert_eq!(
installed_vpnc_script(&link),
Some(script.canonicalize().unwrap().to_str().unwrap().to_owned())
);
}
#[test]
fn configured_script_requires_an_absolute_executable_path() {
assert_eq!(configured_script(Path::new("/bin/sh")), Some("/bin/sh".to_owned()));
+130
View File
@@ -0,0 +1,130 @@
# WebKitGTK crash recovery
Status: implemented and independently reviewed; KDE VM verification recorded below.
## Outcome and evidence
When a bundled GTK/WebKit app terminates with the recognized Wayland protocol error, retry once with `WEBKIT_DISABLE_DMABUF_RENDERER=1`. GP Connect uses opaque windows in that mode so recovery does not introduce the KDE redraw failure. Normal launches keep their existing rendering behavior.
The KDE VM comparison used the same newly built binaries: transparent windows lost content with DMABUF disabled; opaque main and settings windows remained drawn during focus changes and reopening. The experiment changed native transparency, backing backgrounds, outer corner rounding and modal clipping together. It validates this combination on Fedora KDE/VMware, not the reporter's NVIDIA startup failure. Recorded versions and reproduction commands are in the workspace's `gp_logs/kde-opaque-test-2026-10-11/README.md`.
References: [GP issue #666](https://github.com/yuezk/GlobalProtect-openconnect/issues/666), [Tauri PR #16226](https://github.com/tauri-apps/tauri/pull/16226), and [rendering investigation](../webkit-rendering.md). The upstream PR proposes a warning, not automatic recovery. A protocol error does not prove DMABUF caused the failure; this is a narrowly selected recovery attempt.
## Scope and retry rules
Apply the policy on Linux, FreeBSD and OpenBSD builds using GTK/WebKit. macOS behavior is unchanged. Use the effective child environment after desktop-session restoration and privilege drop, rather than the parent shell environment, to determine eligibility. Nonempty WAYLAND_DISPLAY is required; XDG_SESSION_TYPE alone is insufficient. DISPLAY may coexist with WAYLAND_DISPLAY, so it does not disqualify recovery.
A retry requires all of these:
- The directly monitored bundled gpgui, gpgui-helper or embedded-mode gpauth process exited unsuccessfully (nonzero status or signal).
- Its stderr contained a GDK diagnostic with `Error 71 (Protocol error) dispatching to Wayland display`. Match the diagnostic line, not arbitrary occurrences in an application log, preflight warning or quoted suggestion.
- DMABUF override is absent in the effective child environment. Any explicit value, including `0`, empty or `1`, prevents automatic replacement.
- No cancellation, explicit termination or service shutdown is in progress, and the recovery budget has not been spent.
Do not retry ordinary authentication rejection, successful exit with malformed output, generic crashes, missing executables, version checks, ordinary download helper failures, external-browser auth, callback-handler commands, or a WebKit subprocess crash while the monitored parent survives. Do not use WebKit version, GPU vendor or desktop name as a trigger. No timeout-based detection of flicker or hangs.
For the desktop, allow at most one automatic rendering recovery during a DesktopLauncher lifetime, including the download helper and GUI-requested restarts. Program resolution and helper execution run inside the supervised attempt; a recognized helper crash requests a fresh service credential before resolving again. The helper and GUI share the same observed child runner, log destination, cancellation ownership and single retry budget. The helper already uses an opaque native window. Once selected, the recovered rendering environment remains in effect for later legitimate GUI restarts in that desktop session; nothing is persisted to disk. A second crash is reported and terminates that launch session.
For authentication, allow at most one rendering recovery in one top-level connection attempt, shared across portal and gateway authentication. Keep this budget and selected auth rendering mode in the owning connection workflow. Create a fresh budget at each serialized top-level run_connection_attempt, including existing startup/resume attempts; never reset within portal/gateway fallback or authentication loops. This feature does not schedule new connection attempts or add an automatic reconnect loop. Concurrent connections do not share mutable global recovery state. If the GUI itself already runs with DMABUF disabled, its auth child inherits that setting and has no additional override retry.
The retry preserves the original executable, identity, certificate/TLS options and environment except the DMABUF setting. Do not automatically set WEBKIT_DISABLE_COMPOSITING_MODE, __NV_DISABLE_EXPLICIT_SYNC, or change LIBGL_ALWAYS_SOFTWARE. Keep any user-supplied values unchanged.
## GUI entrypoints
Cover both public launch commands on Linux/FreeBSD/OpenBSD:
- `gpclient launch-gui` starts DesktopLauncher directly.
- A release-build `gpgui` without `--service-credential-on-stdin` delegates to `gpclient launch-gui` through gpgui's existing app::launch_gui function. This wrapper runs before App::new, runtime environment patching and webview initialization. It inherits the caller environment, forwards --minimized, replaces the bootstrap process with gpclient on Linux/FreeBSD/OpenBSD, so signals, cleanup and final exit status belong to the supervisor. macOS retains its existing launch behavior. Keep this handoff: the same DesktopLauncher supervises and retries the actual GUI child, so no second retry loop belongs in the gpgui wrapper.
DesktopLauncher launches the actual GUI with `--service-credential-on-stdin`; that child must not delegate back to gpclient. Test this guard explicitly to prevent recursion. Existing GUI activation via either public command must return without starting another service, GUI or recovery budget. Desktop-file launch entries that use either command receive the same recovery behavior. The current Linux desktop file uses /usr/bin/gpclient launch-gui %u and the BSD desktop file uses /usr/local/bin/gpclient launch-gui %u. Cover these shipped entrypoints; authentication callback URLs remain routed through the existing callback handler without GUI crash recovery.
Release-path verification must run `gpgui` and `gpgui --minimized`, in addition to `gpclient launch-gui`, with a synthetic recognized crash in the actual child. Confirm one service authorization/session owner, one recovery, fresh credentials, propagated rendering environment, cancellation cleanup and final failure status. Test manual DMABUF override through the public gpgui command too. The earlier VM experiment used debug binaries through gpclient and does not verify this release-only delegation branch.
Debug `gpgui` without stdin credentials intentionally uses the development bootstrap socket and runs directly, with no DesktopLauncher supervisor. Opaque appearance still applies when the override is supplied, but automatic desktop crash retry is a release-launch feature; do not add a separate self-restart loop for the development path. Direct internal launches with `--service-credential-on-stdin` require their existing supervising caller. macOS app-bundle launch remains unchanged.
## Process observation module
Put the classifier and bounded stderr observer under gpapi::process, alongside the current launchers. Keep policy independent of gpservice transport models. GUI and auth launchers use the same classifier; their owners control retry sequencing and budgets.
Capture and continuously drain stderr while the child runs. Forward the original bytes to the existing destination: inherited stderr for auth, append-only GP_LOG_FILE for GUI when supplied, otherwise inherited stderr. Do not route stderr through stdout: gpauth stdout is the bounded credential JSON channel. Do not duplicate child messages through the Rust logger. Emit the parent's retry/final-failure records through the existing logger and selected log format.
The observer retains only a fixed-size rolling diagnostic fragment and a match flag, not full stderr. It handles read chunks splitting a diagnostic and lines exceeding the bound without unbounded allocations. Matching does not require storing a username, SAML request or cookie. A stderr observer read/forwarding error is a launch error, not a crash classification. A GUI credential-write BrokenPipe can be a consequence of the early abort: retain that error while observing and reaping the child. If the unsuccessful exit and GDK diagnostic confirm the rendering failure, return that classification; otherwise return the original write error. Never treat BrokenPipe alone as a recovery trigger. Drain both stdout and stderr concurrently for auth to avoid pipe deadlocks; keep the current auth stdout size limit. Do not change generic controlled command execution into a WebKit-specific runner: add only the output observation seam needed by the auth launcher, retaining its process-group cancellation and reaping guarantees.
Represent completion as exit status plus a classified rendering failure, rather than parsing anyhow display text. Launch errors remain errors. Check exit status before decoding credential JSON so an aborted authenticator reports its failure rather than only "Failed to parse auth data". Discard partial credential output on every failed attempt.
Cancellation must close/kill and reap the owned process group, finish or cancel and join the pipe readers, and never start the retry. GUI launch futures currently use kill_on_drop; any new reader tasks need explicit ownership and cleanup when DesktopLauncher's select cancels them. Pipe draining after direct-child exit is bounded: inherited pipes held open by helpers must not block completion indefinitely; stop owned helpers and finish readers. User cancellation wins a race with classification at the retry decision.
## Desktop GUI recovery
GuiLauncher owns one GUI attempt: version resolution, process spawning, credential writing and observation. It returns the attempt outcome; DesktopLauncher owns the retry decision, rendering mode and lifetime budget. Resolve the executable once for the initial attempt and use that same selected executable on recovery; do not download another GUI after a rendering crash.
Do not resend an old service credential. Extend the private desktop control pipe with a named rendering-retry message, distinct from the existing GUI-exited message. After the failed child and its readers have stopped, DesktopLauncher sends that message. DesktopClient revokes the old session and issues a fresh credential, without requiring gui_restart_requested. Rendering renewal consumes and clears any pending gui_restart_requested intent from the old session, rather than leaving it to authorize a later unintended restart. It limits this explicit rendering renewal to once per desktop channel. Invalid/repeated recovery messages fail closed. Keep the existing ordinary restart message behavior and EOF shutdown behavior.
The parent then launches the same GUI with the fresh credential and child-only DMABUF override. Continue monitoring service exit and credential-channel errors throughout renewal and retry. Preserve initial minimized intent for startup recovery; legitimate later GUI restarts retain current non-minimized semantics. If renewal or retry fails, close the control input and let the service shut down normally. Report the original rendering failure plus the recovery failure, including exit statuses, without credential bytes.
Rendering recovery is not VPN recovery. No portal login, tunnel reconnection or restoration of an interrupted authentication is initiated by restarting the GUI. Revoking the old session follows existing service ownership/disconnect rules; do not promise uninterrupted VPN traffic after a GUI crash.
## Authentication recovery
SamlAuthLauncher owns one attempt and reports a typed recognized rendering failure after draining output and reaping the process group. Automatic auth retry is allowed only for the bundled embedded authenticator; a configured custom executable must not be restarted or overridden. External-browser and callback paths are unchanged.
The CLI connection workflow and gpgui PortalConnector own the auth recovery. On the typed failure, spend the connection's retry budget, select DMABUF-disabled auth mode, discard partial output, and obtain a fresh prelogin for the same portal/gateway with the existing profile, client certificate options and cancellation token. Re-evaluate the server's authentication mode from the fresh response. If it now chooses standard or external-browser auth, follow that path without imposing an embedded WebKit retry. Return the replacement Prelogin together with its Credential from the owning prelogin/auth operation, so callers use refreshed region and authentication metadata instead of keeping the original Prelogin. Preserve existing gateway standard-auth password fallback when fresh prelogin changes to Standard. Do not replay an already navigated SAML request, and do not repeat portal config retrieval or gateway login after they have succeeded.
Pass the selected child rendering mode through SamlAuthLauncher, applying it after into_non_root desktop restoration. Subsequent embedded auth windows in that connection use the selected mode but cannot spend another recovery budget. Preserve the one-shot --clean behavior: do not clear browser state again if the first attempt already consumed it. If the fresh prelogin fails or auth fails again, return that error with rendering-recovery context. Explicit cancellation remains AuthenticationCancelled rather than a crash error. Wrap every failure after spending the recovery budget in a typed terminal recovery error (except cancellation, which keeps its existing type). Every fallback owner must preserve and stop on this type: portal-to-gateway fallback, cached-credential fallback, automatic gateway candidate iteration, internal gateway iteration, and the GUI stops_gateway_attempts decision. Do not inspect anyhow message text. Exhausted recovery must never cause another authentication window through those paths.
The existing gpauth native auth window is opaque; confirm all embedded windows and backing surfaces remain opaque under this setting. GP Connect's GUI also launches gpauth through SamlAuthLauncher, so both caller paths are covered.
## Opaque window appearance
In gpgui, derive immutable process rendering mode at startup on Linux/BSD: WEBKIT_DISABLE_DMABUF_RENDERER exactly `1` means opaque windows. This applies equally to manual overrides and automatic recovery. No extra production environment variable or persisted setting is needed; remove the VM-only GP_TEST_OPAQUE mechanism when implementing production behavior.
Extend the existing WindowAppearance value with `opaqueWindow`. One resolved value supplies main, settings and update native builders, initial URL data, generated bindings and runtime appearance notifications. Set native transparency false before creating any webview, disable outer corner rounding regardless of the saved preference, and remove outer modal clipping. Do not mutate the saved rounded-corner preference. Disable the corner preference control while opaque mode is active so it does not promise an unavailable effect.
Use the existing theme background token for HTML, body and root, including first paint, light/dark mode and runtime theme switches. The inline head bootstrap in each of the three HTML entrypoints reads opaqueWindow and applies the initial appearance before AppShell CSS or React loads; renderToRoot initialization alone is too late to guarantee the first paint. Native backing color must agree with the initial theme where supported, without a transparent flash. The existing Rust theme application path owns native background updates for all existing windows, including system-theme change events, while frontend theme handling updates the shared CSS tokens. New windows resolve the current theme before construction; AppHandle.set_theme alone is not sufficient for explicit native backing colors. Internal buttons/cards retain their normal rounding. Keep custom title bars and their dimensions. An update window created later receives the same immutable rendering mode. macOS panel configuration is unchanged.
## Logging and diagnostics
Log one warning before recovery: the app exited with a Wayland rendering error and is being restarted with DMABUF disabled (opaque windows for GUI). Preserve the failed-attempt stderr in the normal log destination. On second failure, report both attempts' exit statuses and a useful instruction to attach diagnostics; never dump auth stdout, command arguments or environment maps. Add the effective DMABUF setting to diagnostics only if not already collected. Do not send new telemetry or persist an automatic override.
## Verification before implementation is accepted
- Process fixtures emit the real diagnostic across chunk boundaries and with large stdout/stderr. Verify no deadlock, one retry, unchanged stdout JSON, original stderr delivery, bounds and actual final errors.
- Negative fixtures: preflight warning quoting the diagnostic, normal exit, nonzero auth rejection, unrelated abort, explicit override values, custom auth executable, external browser, X11, cancellation and exhausted retry budget.
- Desktop pipe integration: fresh credential/session ID on rendering renewal; old credential revoked; repeated renewal rejected; ordinary restart still works; a pending ordinary restart followed by rendering renewal does not authorize another unrequested exit/restart; service EOF/error during renewal does not hang or leave a child. Test cancellation at spawn, credential write, reader wait and retry transition.
- Auth workflow fixtures for CLI and GUI: two distinct prelogin requests, no SAML request replay, recovery shared across portal/gateway, no new clean-state reset, no outer fallback after terminal rendering failure, valid second credential used once, and cancellation during fresh prelogin.
- Opaque appearance tests and frontend build: theme-aware backgrounds, all window types, saved corner preference retained but forced off, no macOS effect.
- Run targeted gp Rust checks/tests and gpgui Rust check/frontend build using the actual sibling gp checkout.
- Repeat the KDE transparent/opaque comparison with production code: main/settings/update, hover, input focus, hide/show and theme changes. Use a synthetic child crash to exercise supervision on the VM; report separately from real rendering tests.
- Confirm the real crash workaround on the affected NVIDIA system when available. Linux KDE testing does not prove FreeBSD/OpenBSD behavior; perform supported cross-target checks and explicitly report remaining runtime gaps.
## Implementation order
1. Shared classification/observation and attempt outcomes with process fixtures.
2. Desktop credential renewal and bounded GUI recovery.
3. Theme-aware opaque appearance in gpgui and verification on KDE.
4. Fresh-prelogin auth recovery in both owning workflows.
5. End-to-end cancellation/negative tests, diagnostics/docs and independent implementation review.
No release or deployment is included in this change.
## Design review outcome
Three independent agents reviewed process/service lifecycle, authentication workflows, and GUI appearance against the current code. Their findings were incorporated and the revised sections reviewed again. All three reported no remaining blocking design findings.
Changes from review: retain early credential BrokenPipe long enough to classify a confirmed crash; clear old-session restart intent during credential renewal; propagate replacement prelogin metadata and preserve standard gateway password reuse; stop every fallback path on terminal recovery failure; define budgets per serialized connection attempt; initialize opacity before CSS loads; and keep native backing colors synchronized through existing theme ownership.
Design review preceded implementation. Three independent implementation reviews covered process/service lifecycle, authentication workflows and GUI appearance. Findings were fixed and re-reviewed with no remaining blockers.
Entrypoint follow-up: code inspection confirmed the release gpgui command delegates before creating a webview. The design now explicitly covers that route, its stdin recursion guard, minimized/environment forwarding and release-build verification; debug direct-launch supervision remains outside the production retry scope.
## Implementation verification
Both repos compile against the actual sibling checkout. Targeted checks passed: 41 gpapi process tests; six desktop-service tests (one subprocess helper ignored); six CLI auth-flow tests; four GUI auth recovery tests; 16 GUI utility tests; nine frontend appearance/settings tests and the frontend build.
On Fedora 44 KDE Wayland (Plasma/KWin 6.6.4, WebKitGTK 2.54.1, VMware vmwgfx), a VM-only fixture emitted the reported GDK protocol-error diagnostic and aborted the first supervised child. Both public launch paths recovered once, delivered a fresh credential/session ID and launched the real opaque GUI. Main/settings remained fully rendered during focus changes. Minimized intent survived retry, and activating the existing GUI did not start another child. Explicit DMABUF=0 prevented retry. Two recognized crashes stopped with both failures visible. Ctrl+C cleanup passed through both public paths after Linux/BSD gpgui bootstrap was changed to process replacement.
This validates supervision using a simulated crash, not the actual NVIDIA failure. The VM build used release entrypoints with optimization disabled. Update-window runtime appearance, live system-theme changes, affected NVIDIA hardware and FreeBSD/OpenBSD runtime remain unverified; window construction and appearance behavior are covered by inspection and targeted tests. Detailed evidence is in workspace gp_logs/kde-crash-recovery-2026-10-11/.
Manual KDE confirmation: after the simulated first-launch crash, the user tested the recovered real GUI and reported no flickering. This confirms the tested VM behavior; affected NVIDIA hardware and BSD runtime remain separate verification gaps.
Helper follow-up: two independent implementation reviews found no blockers. The helper shares the GUI's monitored child runner and desktop recovery budget. Local process tests passed (45), Linux VM process tests passed (48), and the sibling gpgui check passed. A simulated helper GDK error/SIGABRT renewed the credential and launched the real opaque helper with DMABUF disabled. Clicking and changing keyboard focus preserved its content. Cancellation reaped the test children; repeated crashes stopped after two attempts; ordinary failures and an explicit DMABUF override did not retry. The VM used a mock service credential channel and blocked downloads to avoid changing the installed application, so successful installation and the complete helper-to-GUI transition were not tested. Evidence is in workspace gp_logs/helper-crash-recovery-2026-10-12/.
+103
View File
@@ -0,0 +1,103 @@
# Diagnostics collection design
## Purpose
`gpclient diagnostics` collects support information without starting a VPN,
opening a window, accessing credentials, reading logs, or making network
requests. A standalone script provides the same collection for older releases.
Users review the report before attaching it to a public issue.
## Interface
- `gpclient diagnostics`: readable report on stdout, no sudo needed.
- `gpclient diagnostics --json`: the same fields as a JSON object, with a schema
version. It contains information, not log events.
- `gpclient diagnostics --output PATH`: save the selected format to a new file;
refuse to overwrite an existing file.
- `sh collect-diagnostics.sh`: the same readable report for older installations.
- `sh collect-diagnostics.sh --output PATH`: save to a new file. The standalone
script needs only POSIX shell and common base utilities, not Python or jq.
The script is shipped in `scripts/collect-diagnostics.sh`. The CLI embeds that
exact file at compile time and runs it with `/bin/sh`; no installed script is
needed. It supplies its own build version instead of recursively invoking
`gpclient`. JSON formatting and file output are responsibilities of the Rust
command. The script emits stable `field: status: value` lines; values are
flattened to one line. JSON has `schema_version: 1` and `fields`, a map of field
names to `{status, value}` objects. Status is `ok`, `unset`, `unavailable`,
`failed`, `timed_out`, or `not_applicable`; absent values become null. Unknown
fields, statuses or duplicate keys are rejected by the Rust parser. Fields
cover system, app paths/versions, GUI metadata, execution context, desktop,
graphics/packages, and the environment allowlist below.
## Collection and platform coverage
Common fields: report schema, OS/kernel release and architecture, gpclient and
gpauth versions, executable locations, normal-user versus root execution,
presence of an SSH session, VM indicators when available, and installation
location hints. A location hint does not claim a package-manager provenance
that cannot be verified. Executable paths replace the home directory with `~`.
Only known version options are invoked; the GUI application is not launched to
discover its version.
Linux, FreeBSD and OpenBSD: raw desktop/session identifiers, display protocol
inferred from presence of display variables (their socket values are excluded),
graphics device/driver summaries, available package versions for WebKitGTK,
GTK and graphics drivers. Linux reads selected `/etc/os-release` fields and
uses available package-manager queries. BSD uses its own base utilities and
package names, rather than assuming Linux `/proc`, `lspci`, or `pacman` exist.
macOS uses `sw_vers`, bundle paths and a filtered graphics model probe; Linux
graphics and desktop fields are marked not applicable.
Environment allowlist: `XDG_CURRENT_DESKTOP`, `XDG_SESSION_DESKTOP`,
`XDG_SESSION_TYPE`, `DESKTOP_SESSION`, `WEBKIT_DISABLE_DMABUF_RENDERER`,
`WEBKIT_DISABLE_COMPOSITING_MODE`, `LIBGL_ALWAYS_SOFTWARE`,
`__NV_DISABLE_EXPLICIT_SYNC`, `GDK_BACKEND`, `GDK_GL`. Values are capped and
flattened; HOME, DISPLAY, WAYLAND_DISPLAY, DBUS addresses, hostname, username,
machine IDs, network configuration and arbitrary environment variables are
excluded. Desktop identifiers are raw user-controlled strings, so reports are
not guaranteed anonymous and must be reviewed before sharing.
Parse OS-release assignments as data without sourcing them. Strip control bytes
and line breaks, cap each value at 512 bytes, and decode invalid UTF-8 lossily
in Rust. Reports are capped at 64 KiB. Diagnostics dispatches before generic
OpenSSL setup even if global CLI compatibility flags are supplied.
Optional probes report `unavailable`, `timed_out`, or `failed` without stopping
collection. Each external probe has a three-second timeout and a 64-KiB output
cap. A watchdog terminates the probe and its discoverable descendants using
PID/parent-PID snapshots, and the collector reaps the direct child and cancels
the watchdog. Signal cleanup also stops active probes and watchdogs. This is
best-effort tree cleanup for trusted local system utilities: a process that
deliberately reparents/daemonizes can escape it. No such probes are selected.
Tests cover descendants, ignored TERM, output flooding and interruption. Probe
stderr is discarded rather than pasted into the report. No packages are
installed. No privilege escalation or rendering workaround is applied.
## Issue form
Replace the Markdown template with a GitHub YAML issue form. Require affected
component, app version, installation method, OS, and reproduction steps including
expected and actual behavior. Ask for last working version/system changes,
diagnostics, relevant logs and screenshots as optional fields. Provide the new
command and a download/review/run path for the standalone script. Reporters may
instead enter desktop, GPU/driver and WebKit information manually. Authentication
reports should name embedded/external browser and the failure stage; credential
storage details are requested only when relevant. Warn against sharing passwords,
cookies, tokens, SAML payloads or complete environment dumps. Do not require
running workaround flags or upgrading before reporting a regression.
## Verification
Test the shared collector with controlled command/environment fixtures: missing
tools, hung probes, sensitive data excluded, home path sanitization, version
recursion avoided, and OS-specific selection for Linux/FreeBSD/OpenBSD/macOS.
Test CLI parsing, schema/JSON conversion and overwrite refusal. Run shell syntax
checks, targeted Rust checks/tests, and a real local macOS report. BSD/Linux fixture
coverage validates selection/parsing; it is not native runtime verification.
## Scope
No log bundling, uploading, connectivity tests, package installation, configuration
changes, GUI integration or crash recovery. The diagnostics module owns collection
and formatting; existing session/service transport models are not involved.
+89
View File
@@ -0,0 +1,89 @@
# Collect diagnostics for a bug report
The diagnostic collector gathers app and system versions, desktop and graphics
information, and a small set of rendering environment variables. It does not
connect to a VPN, launch the GUI, read credentials or logs, upload a report, or
change settings.
Run it from a terminal in your normal desktop session, **without sudo**, so it
can see the desktop environment used by the application. Linux, macOS, FreeBSD,
and OpenBSD are supported. Missing tools or unavailable information are reported
without preventing collection.
## Installed versions with the diagnostics command
```sh
gpclient diagnostics
```
To save a report to a new file:
```sh
gpclient diagnostics --output diagnostics.txt
```
For structured output:
```sh
gpclient diagnostics --json --output diagnostics.json
```
The collector refuses to overwrite an existing file. Choose another filename or
remove the previous report yourself before collecting again.
This command is available in 3.0.2 and later. If your installed version says the
command is unknown, use the standalone script below. You do not need to upgrade
before reporting a problem.
## Older versions: standalone script
The standalone script collects the same information in a readable format. It
requires a POSIX shell and common system utilities, without Python or jq.
Download the script to a local file:
```sh
curl --fail --location \
https://raw.githubusercontent.com/yuezk/GlobalProtect-openconnect/dev/scripts/collect-diagnostics.sh \
--output collect-diagnostics.sh
```
Open `collect-diagnostics.sh` in a text editor and review it before running it.
Then, as your normal desktop user:
```sh
sh collect-diagnostics.sh
```
Or save the report to a new file:
```sh
sh collect-diagnostics.sh --output diagnostics.txt
```
The download points to the development branch because this collector was added
after 3.0.1. It becomes available there when the change is published. From a
local checkout containing the change, run
`sh scripts/collect-diagnostics.sh` instead. Do not pipe a downloaded script
directly into a shell.
## Review before sharing
Read the report before pasting it into an issue or attaching the saved file.
It includes executable paths with your home directory shortened to `~`, raw
desktop/session identifiers, and selected rendering overrides. These values can
contain identifying information, so the report is **not guaranteed anonymous**.
Remove any private information before posting. Never share passwords, cookies,
tokens, SAML payloads, private VPN addresses, or a complete environment dump.
Diagnostics do not include logs. For CLI issues, share the relevant terminal
output separately after reviewing it. For GUI issues, use the app's built-in
option to open or export logs, if available. Avoid posting full verbose logs
unless requested, as authentication output can contain sensitive data.
Include your installation method and the exact command or GUI steps that fail.
Replace private portal names with `<portal>` and omit credentials. If you cannot
run the collector, provide the app version, OS, and relevant desktop,
GPU/driver, or WebKitGTK details manually. Graphics details are useful for
window failures but are not needed for every connection problem.
+87
View File
@@ -0,0 +1,87 @@
# WebKitGTK rendering investigation
## KDE redraw failure with either WebKit override
On October 11, 2026, local KDE tests reproduced GUI flickering and incomplete
redraws with either override alone and with both overrides enabled. All three
commands exhibited the problem:
```sh
WEBKIT_DISABLE_DMABUF_RENDERER=1 gpclient launch-gui -vv
WEBKIT_DISABLE_COMPOSITING_MODE=1 gpclient launch-gui -vv
WEBKIT_DISABLE_COMPOSITING_MODE=1 \
WEBKIT_DISABLE_DMABUF_RENDERER=1 \
gpclient launch-gui -vv
```
The window intermittently loses most of its content. Hovering a button or
focusing an input redraws that control while other regions remain missing.
The supplied screenshots show the desktop behind missing regions of the GUI,
with only some controls still visible. Earlier testing reported normal
rendering after removing the overrides.
Each override independently triggers the observed problem on the tested KDE
setup. The tests do not establish the underlying rendering defect or whether
other graphics configurations are affected. The exact application version,
KDE version, display protocol,
GPU/driver, and WebKitGTK version were not recorded with this test.
Do not recommend either override as a general GUI workaround. Close the app
completely between rendering tests so each launch uses the intended environment.
These command-scoped settings do not persist after the application exits.
## KDE test with NVIDIA explicit sync disabled
On the same KDE setup, the following command did not cause the flickering or
incomplete redraws observed with either WebKit override:
```sh
__NV_DISABLE_EXPLICIT_SYNC=1 gpclient launch-gui -vv
```
This establishes that the setting did not reproduce the redraw problem in this
local test. It does not establish whether it fixes the authentication-window
failure in #666 or whether the tested graphics driver uses this setting.
## Relationship to the authentication-window investigation
[Issue #666](https://github.com/yuezk/GlobalProtect-openconnect/issues/666)
reports a separate authentication-window failure on Hyprland with
`Error 71 (Protocol error) dispatching to Wayland display`. Whether that failure
shares a cause with this KDE redraw problem is not confirmed.
The automatic `WEBKIT_DISABLE_COMPOSITING_MODE=1` and
`WEBKIT_DISABLE_DMABUF_RENDERER=1` settings were removed in 3.0.0. Automatically
setting `LIBGL_ALWAYS_SOFTWARE=1` when missing on Wayland remains in place.
Restoring either WebKit override globally would risk reintroducing the observed
redraw failure.
[WebKit bug #280210, comment 14](https://bugs.webkit.org/show_bug.cgi?id=280210#c14)
also describes incomplete rendering with DMABUF disabled on an NVIDIA/KWin
setup. It reports `__NV_DISABLE_EXPLICIT_SYNC=1` as an alternative that retains
DMABUF rendering. Other comments report flickering with that alternative, so it
requires testing on the affected machine; it is not a validated general fix
for GP Connect. The local KDE test above found no redraw failure with this
alternative, but the reporter's crash still needs a separate test.
## Opaque GUI recovery verification
The local implementation selects `WEBKIT_DISABLE_DMABUF_RENDERER=1` only for a
single retry after a recognized Wayland GDK rendering crash. An explicit caller
setting prevents automatic selection. With that value exactly `1`, the GUI uses
opaque, square main/settings/update windows while retaining the saved corner
preference. It does not select `WEBKIT_DISABLE_COMPOSITING_MODE`.
On the Fedora 44 KDE Wayland VM (Plasma/KWin 6.6.4, WebKitGTK 2.54.1,
VMware vmwgfx), a simulated GDK crash followed by the real opaque GUI rendered
the main and settings windows fully during focus changes through both public
launch commands. This supports the opaque approach on this VM; it does not
prove the original NVIDIA crash is resolved or establish behavior on every
KDE setup. See [the recovery design](design/webkit-crash-recovery.md) for the
retry boundaries and remaining verification gaps. The earlier warning about
general overrides concerns the transparent-window behavior tested above.
The user also manually tested the recovered GUI on this VM and confirmed no
flickering.
Generated
+3 -3
View File
@@ -63,11 +63,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1791366222,
"narHash": "sha256-o0N4g6uSOIppU7CGToNvGlMf5vC+B6O6ukFHKY/TKOY=",
"lastModified": 1791487292,
"narHash": "sha256-tqM7xDEsaeK1p6VvRygeZ9LkQRpUUkbRT02BHv6hnTM=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "39ad350a0602fa0a58a544344e3e9187526ea45c",
"rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30",
"type": "github"
},
"original": {
+15 -63
View File
@@ -29,8 +29,8 @@
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
pname = "globalprotect-openconnect";
version = cargoToml.workspace.package.version;
releaseTag = "v3.0.0";
releaseVersion = "3.0.0";
releaseTag = "v3.0.4";
releaseVersion = "3.0.4";
toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
@@ -55,8 +55,8 @@
cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name;
gpguiHashes = {
x86_64 = "sha256-MdY+50LtG/AmJEcJdXbXFcvyl0R4jQMOmJfQ6rlAd6c=";
aarch64 = "sha256-a8/YtYQct6/UUjbNVDN/54fHxdnRFhKahprBLyVz0xk=";
x86_64 = "sha256-T14EbI8ja9i9kbVP/LirAjGupPeUtrVQx41ls02dx2U=";
aarch64 = "sha256-DWR9uLMlmjai8LRarbhmxPr1Cg3ejtGkcxmxkfwwfEA=";
};
gpguiArchive = pkgs.fetchurl {
@@ -70,8 +70,8 @@
};
binaryHashes = {
x86_64 = "sha256-/PsNsK2IY/qnsVQVF3o8EFnBRP9LpjxZm7e09d8/Xig=";
aarch64 = "sha256-W51Ek28cA0mnE3G4d7DqhDAtvqmq17QQ+i155dxarUw=";
x86_64 = "sha256-TqOqrWhanDX9IHKcRxT0+3s5kSHr/pSqXDdMH/v+Bwg=";
aarch64 = "sha256-EhoJ4GvJX0/+HmZVuDCXMfiTRgiFmb0QvB5jDNvEb1I=";
};
binaryArchive = pkgs.fetchurl {
@@ -118,6 +118,7 @@
[
libxml2
zlib
openssl
lz4
gnutls
p11-kit
@@ -130,30 +131,10 @@
libsoup_3
webkitgtk_4_1
glib-networking
openssl
libsecret
libayatana-appindicator
];
rewriteSourceInstallPaths = lib.optionalString pkgs.stdenv.isLinux ''
substituteInPlace $out/share/applications/gpgui.desktop \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \
--replace-fail /usr/bin/gpservice $out/bin/gpservice \
--replace-fail /usr/libexec/gpclient/gp-vpnc-script-installer $out/libexec/gpclient/gp-vpnc-script-installer
if [ -f $out/libexec/gpclient/gp-hip-script-installer ]; then
substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \
--replace-fail /usr/libexec/gpclient/gp-hip-script-installer $out/libexec/gpclient/gp-hip-script-installer
fi
if [ -f $out/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down ]; then
substituteInPlace $out/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
fi
'';
installNixosPolkitRule = ''
chmod u+w $out/share $out/share/polkit-1 2>/dev/null || true
install -d $out/share/polkit-1/rules.d
@@ -182,6 +163,9 @@
# Must be set to true to avoid issues with the Tauri build process
singleStep = true;
# The Makefile installs executables together with their supporting files.
copyBins = false;
cargoBuildOptions =
old:
old
@@ -202,6 +186,9 @@
libtool
pkg-config
]
++ lib.optionals stdenv.isDarwin [
darwin.sigtool
]
++ lib.optionals stdenv.isLinux [
autoPatchelfHook
wrapGAppsHook4
@@ -211,49 +198,14 @@
preFixup = nativeRuntimeWrapping;
overrideMain =
{ ... }:
{
postPatch = ''
substituteInPlace crates/openconnect/src/vpn_utils.rs \
--replace-fail /usr/libexec/gpclient/vpnc-script $out/libexec/gpclient/vpnc-script
substituteInPlace crates/common/src/constants.rs \
--replace-fail /usr/bin/gpclient $out/bin/gpclient \
--replace-fail /usr/bin/gpauth $out/bin/gpauth \
--replace-fail /opt/homebrew/ $out/
''
+ lib.optionalString pkgs.stdenv.isLinux ''
substituteInPlace crates/common/src/constants.rs \
--replace-fail /usr/bin/gpservice $out/bin/gpservice \
--replace-fail /usr/bin/gpgui-helper $out/bin/gpgui-helper \
--replace-fail /usr/bin/gpgui $out/bin/gpgui
substituteInPlace crates/common/src/constants.rs \
--replace-fail /usr/libexec/gpclient/gp-hip-script-installer $out/libexec/gpclient/gp-hip-script-installer
'';
};
postInstall = ''
cp -r packaging/files/usr/libexec $out/libexec
make install PREFIX="$out" ${lib.optionalString pkgs.stdenv.isLinux ''GPGUI_BINARY="${gui}/gpgui"''}
''
+ lib.optionalString pkgs.stdenv.isLinux ''
for installer in gp-vpnc-script-installer gp-hip-script-installer; do
install -Dm755 "$out/bin/$installer" "$out/libexec/gpclient/$installer"
done
# Copy the prebuilt gpgui binary to the output bin directory
cp ${gui}/gpgui $out/bin/gpgui
chmod +x $out/bin/gpgui
cp -r packaging/files/usr/share $out/share
cp -r packaging/files/usr/lib $out/lib
${installNixosPolkitRule}
''
+ ''
${rewriteVpncScriptToolPaths}
${rewriteSourceInstallPaths}
'';
}) {};
@@ -288,7 +240,7 @@
install -Dm755 ${gui}/gpgui $out/bin/gpgui
${rewriteVpncScriptToolPaths}
${rewriteSourceInstallPaths}
sh ${./scripts/relocate-install-paths.sh} "$out" /usr "$out"
${installNixosPolkitRule}
runHook postInstall
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

@@ -19,7 +19,7 @@
<circle cx="512" cy="455" r="315"/>
</clipPath>
<filter id="globe-shadow" x="150" y="90" width="730" height="760" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#174d6f" flood-opacity=".14"/>
<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">
<feDropShadow dx="0" dy="18" stdDeviation="18" flood-color="#70430c" flood-opacity=".2"/>

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

+191
View File
@@ -0,0 +1,191 @@
#!/bin/sh
# Read-only support metadata. No network requests, logs or credential collection.
# Process-tree cleanup is best effort; deliberately daemonized probes can escape it.
umask 077
LC_ALL=C
export LC_ALL
GP_DIAGNOSTICS_HOME=$(printf '%s' "${HOME:-}" | tr '\000-\037\177' ' ')
export GP_DIAGNOSTICS_HOME
client_version= client_path= auth_path= gui_path= output=
while [ "$#" -gt 0 ]; do
case "$1" in
--help) printf '%s\n' 'Usage: sh collect-diagnostics.sh [--output PATH]' 'Collect local support metadata; review before sharing. No sudo required.'; exit 0 ;;
--output|--client-version|--client-path|--auth-path|--gui-path)
[ "$#" -ge 2 ] || { printf '%s\n' 'Missing option value' >&2; exit 2; }
case "$1" in
--output) output=$2 ;; --client-version) client_version=$2 ;;
--client-path) client_path=$2 ;; --auth-path) auth_path=$2 ;; --gui-path) gui_path=$2 ;;
esac
shift 2 ;;
*) printf '%s\n' 'Unknown option' >&2; exit 2 ;;
esac
done
if [ -n "$output" ]; then
set -C
exec 3> "$output" || exit 1
set +C
exec 1>&3
fi
work=$(mktemp -d "${TMPDIR:-/tmp}/gp-diagnostics.XXXXXXXX") || exit 1
chmod 700 "$work" || exit 1
active= timer=
# Use a fixed PID/PPID snapshot, never full process arguments.
stop_tree() {
tree_root=$1
ps -axo pid=,ppid= > "$work/tree.$tree_root" 2>/dev/null || :
tree_pids=$(awk -v root="$tree_root" '
{parent[$1]=$2} END {
marked[root]=1
for (i=0;i<100;i++) {changed=0; for (pid in parent) if (marked[parent[pid]] && !marked[pid]) {marked[pid]=1; changed=1} if (!changed) break}
for (pid in marked) if (marked[pid] && pid != root) print pid
}' "$work/tree.$tree_root")
# Stop descendants before the direct child: reaping the child must not race
# cancellation of a watchdog which is still terminating descendants.
for tree_pid in $tree_pids; do kill -TERM "$tree_pid" 2>/dev/null || :; done
for tree_pid in $tree_pids; do kill -KILL "$tree_pid" 2>/dev/null || :; done
kill -TERM "$tree_root" 2>/dev/null || :
kill -KILL "$tree_root" 2>/dev/null || :
}
cleanup() {
[ -z "$active" ] || { stop_tree "$active"; wait "$active" 2>/dev/null || :; }
[ -z "$timer" ] || { stop_tree "$timer"; wait "$timer" 2>/dev/null || :; }
rm -rf "$work"
}
trap cleanup 0
trap 'exit 130' INT
trap 'exit 143' TERM HUP
emit() {
# HOME is matched literally, never used as a regular expression.
[ "$2" = ok ] || { printf '%s: %s: \n' "$1" "$2"; return; }
clean=$(printf '%s' "$3" | tr '\000-\037\177' ' ' | awk '
BEGIN {home=ENVIRON["GP_DIAGNOSTICS_HOME"]}
{text=$0; result=""; while (length(home)>0 && (pos=index(text,home))>0) {
tail=substr(text,pos+length(home)); result=result substr(text,1,pos-1)
if (tail=="" || substr(tail,1,1)=="/") result=result "~"; else result=result home
text=tail
} text=result text; printf "%s",substr(text,1,500)}')
printf '%s: %s: %s\n' "$1" "$2" "$clean"
}
probe() {
probe_status= probe_value=
if ! command -v "$1" >/dev/null 2>&1; then probe_status=unavailable; return; fi
rm -f "$work/timed"
# ulimit -f is POSIX and limits stdout's regular file to at most 64 KiB.
(trap - 0 INT TERM HUP; ulimit -f 64; exec "$@") < /dev/null > "$work/out" 2>/dev/null &
active=$!
(
trap - 0 INT TERM HUP
watchdog_sleep=
trap '[ -z "$watchdog_sleep" ] || { kill "$watchdog_sleep" 2>/dev/null || :; wait "$watchdog_sleep" 2>/dev/null || :; }; exit' TERM HUP INT
sleep 3 &
watchdog_sleep=$!
wait "$watchdog_sleep"
: > "$work/timed"
stop_tree "$active"
) 2>/dev/null &
timer=$!
if wait "$active" 2>/dev/null; then probe_status=ok; else probe_status=failed; fi
active=
# Cancel immediately; a process-tree snapshot here could itself cross the
# timeout deadline after a successful probe. The watchdog reaps its sleep.
kill -TERM "$timer" 2>/dev/null || :
wait "$timer" 2>/dev/null || :
timer=
if [ "$probe_status" = failed ] && [ -f "$work/timed" ]; then probe_status=timed_out; fi
if [ "$probe_status" != timed_out ]; then probe_value=$(cat "$work/out"); fi
}
field_probe() { field_key=$1; shift; probe "$@"; emit "$field_key" "$probe_status" "$probe_value"; }
emit schema_version ok 1
probe uname -s
os=$probe_value
emit os "$probe_status" "$os"
field_probe kernel uname -r
field_probe architecture uname -m
probe id -u
case "$probe_status:$probe_value" in ok:0) emit execution_user ok root ;; ok:*) emit execution_user ok normal_user ;; *) emit execution_user "$probe_status" '' ;; esac
if [ -n "${SSH_CONNECTION:-}${SSH_CLIENT:-}${SSH_TTY:-}" ]; then emit ssh_session ok yes; else emit ssh_session ok no; fi
case "$os" in
Linux)
if [ -r /etc/os-release ]; then
probe awk -F= '$1=="PRETTY_NAME" {value=substr($0,index($0,"=")+1); if (value ~ /^".*"$/ || value ~ /^\047.*\047$/) value=substr(value,2,length(value)-2); print value; exit}' /etc/os-release
if [ "$probe_status" = ok ] && [ -z "$probe_value" ]; then probe_status=unavailable; fi
emit os_version "$probe_status" "$probe_value"
else emit os_version unavailable ''; fi
probe systemd-detect-virt
if [ "$probe_status" = failed ] && [ "$probe_value" = none ]; then probe_status=ok; fi
emit virtualization "$probe_status" "$probe_value" ;;
Darwin) field_probe os_version sw_vers -productVersion; emit virtualization unavailable '' ;;
FreeBSD|OpenBSD) field_probe os_version uname -r; field_probe virtualization sysctl -n kern.vm_guest ;;
*) emit os_version unavailable ''; emit virtualization unavailable '' ;;
esac
# Helpers accept only known safe version switches. Never invoke GUI binaries.
[ -n "$client_path" ] || client_path=$(command -v gpclient 2>/dev/null || :)
[ -n "$auth_path" ] || auth_path=$(command -v gpauth 2>/dev/null || :)
[ -n "$gui_path" ] || gui_path=$(command -v gpgui 2>/dev/null || :)
if [ "$os" = Darwin ]; then
bundle=/Applications/GP\ Connect.app/Contents
gui_bundle=
case "$gui_path" in *.app/Contents/MacOS/*) gui_bundle=${gui_path%/MacOS/*}; bundle=$gui_bundle ;; esac
[ -n "$client_path" ] || { [ ! -x "$bundle/Helpers/gpclient" ] || client_path=$bundle/Helpers/gpclient; }
[ -n "$auth_path" ] || { [ ! -x "$bundle/Helpers/gpauth" ] || auth_path=$bundle/Helpers/gpauth; }
[ -n "$gui_path" ] || { [ ! -d "$bundle" ] || { gui_path=$bundle/MacOS/gpgui; gui_bundle=$bundle; }; }
fi
is_executable_file() { [ -f "$1" ] && [ -x "$1" ]; }
is_executable_file "$client_path" || client_path=
is_executable_file "$auth_path" || auth_path=
is_executable_file "$gui_path" || gui_path=
for component in gpclient gpauth gpgui; do
case "$component" in gpclient) location=$client_path ;; gpauth) location=$auth_path ;; gpgui) location=$gui_path ;; esac
if [ -n "$location" ]; then emit "${component}_path" ok "$location"; else emit "${component}_path" unavailable ''; fi
done
if [ -n "$client_version" ]; then emit gpclient_version ok "$client_version"; elif [ -n "$client_path" ]; then field_probe gpclient_version "$client_path" --version; else emit gpclient_version unavailable ''; fi
if [ -n "$auth_path" ]; then field_probe gpauth_version "$auth_path" --version; else emit gpauth_version unavailable ''; fi
if [ "$os" = Darwin ] && [ -n "$gui_path" ] && [ -n "$gui_bundle" ]; then
field_probe gpgui_version /usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$gui_bundle/Info.plist"
else
emit gpgui_version unavailable ''
fi
case "$os" in
Darwin) emit display_protocol not_applicable ''; probe system_profiler SPDisplaysDataType; graphics_value=$(printf '%s\n' "$probe_value" | awk '/Chipset Model:/ {print}'); emit graphics "$probe_status" "$graphics_value" ;;
*)
if [ -n "${WAYLAND_DISPLAY:-}" ]; then emit display_protocol ok wayland; elif [ -n "${DISPLAY:-}" ]; then emit display_protocol ok x11; else emit display_protocol unset ''; fi
case "$os" in
Linux) probe lspci -nnk; graphics_status=$probe_status; graphics_value=$(printf '%s\n' "$probe_value" | awk '/^[^ \t]/ {show=($0 ~ /VGA|3D controller|Display controller/)} show {print}') ;;
FreeBSD) probe pciconf -lv; graphics_status=$probe_status; graphics_value=$(printf '%s\n' "$probe_value" | awk '/^[^ \t]/ {show=($0 ~ /^vgapci/)} show {print}') ;;
OpenBSD) probe pcidump; graphics_status=$probe_status; graphics_value=$(printf '%s\n' "$probe_value" | awk '/VGA|Display|Graphics/ {print}') ;;
*) graphics_status=not_applicable; graphics_value= ;;
esac
emit graphics "$graphics_status" "$graphics_value" ;;
esac
case "$os" in
Linux)
if command -v pacman >/dev/null 2>&1; then probe pacman -Q webkit2gtk-4.1 gtk3 mesa nvidia-utils nvidia-open nvidia egl-wayland
elif command -v dpkg-query >/dev/null 2>&1; then probe dpkg-query -W '-f=${binary:Package} ${Version}\n' 'libwebkit2gtk*' 'libgtk-3-0*' 'libegl-mesa*' 'libgl1-mesa*' 'nvidia-driver*' 'libnvidia-egl-wayland*'
elif command -v rpm >/dev/null 2>&1; then probe rpm -q webkit2gtk4.1 gtk3 mesa-dri-drivers mesa-libEGL xorg-x11-drv-nvidia egl-wayland
else probe_status=unavailable; probe_value=; fi
probe_value=$(printf '%s\n' "$probe_value" | awk '$1 ~ /^(webkit2gtk|libwebkit2gtk|gtk3|libgtk-3|mesa|libegl-mesa|libgl1-mesa|nvidia|xorg-x11-drv-nvidia|egl-wayland|libnvidia-egl-wayland)/ && $0 !~ /not installed|no packages found|unknown package/ {print}')
[ -z "$probe_value" ] || probe_status=ok
emit graphics_packages "$probe_status" "$probe_value"
;;
FreeBSD) probe pkg query -a '%n %v'; package_value=$(printf '%s\n' "$probe_value" | awk '$1 ~ /^(webkit2-gtk3|webkit2-gtk_41|gtk3|mesa-dri|nvidia-driver)(-|$)/'); emit graphics_packages "$probe_status" "$package_value" ;;
OpenBSD) probe pkg_info -a; package_value=$(printf '%s\n' "$probe_value" | awk '$1 ~ /^(webkitgtk|webkitgtk41|gtk\+3|mesa|nvidia)-/'); emit graphics_packages "$probe_status" "$package_value" ;;
*) emit graphics_packages not_applicable '' ;;
esac
# Desktop binaries are not launched: version information comes from package metadata.
case "$os" in
Linux)
if command -v pacman >/dev/null 2>&1; then probe pacman -Q plasma-workspace hyprland sway gnome-shell cosmic-comp
elif command -v dpkg-query >/dev/null 2>&1; then probe dpkg-query -W '-f=${binary:Package} ${Version}\n' plasma-workspace hyprland sway gnome-shell cosmic-comp
elif command -v rpm >/dev/null 2>&1; then probe rpm -q plasma-workspace hyprland sway gnome-shell cosmic-comp
else probe_status=unavailable; probe_value=; fi
probe_value=$(printf '%s\n' "$probe_value" | awk '$1 ~ /^(plasma-workspace|hyprland|sway|gnome-shell|cosmic-comp)/ && $0 !~ /not installed|no packages found|unknown package/ {print}')
[ -z "$probe_value" ] || probe_status=ok
emit desktop_version "$probe_status" "$probe_value" ;;
FreeBSD) probe pkg query -a '%n %v'; package_value=$(printf '%s\n' "$probe_value" | awk '$1 ~ /^(plasma6-plasma-workspace|hyprland|sway|gnome-shell)(-|$)/'); emit desktop_version "$probe_status" "$package_value" ;;
OpenBSD) probe pkg_info -a; package_value=$(printf '%s\n' "$probe_value" | awk '$1 ~ /^(plasma|hyprland|sway|gnome-shell)-/'); emit desktop_version "$probe_status" "$package_value" ;;
*) emit desktop_version not_applicable '' ;;
esac
for name in XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP XDG_SESSION_TYPE DESKTOP_SESSION WEBKIT_DISABLE_DMABUF_RENDERER WEBKIT_DISABLE_COMPOSITING_MODE LIBGL_ALWAYS_SOFTWARE __NV_DISABLE_EXPLICIT_SYNC GDK_BACKEND GDK_GL; do
eval 'present=${'"$name"'+yes}; value=${'"$name"'-}'
if [ "$present" = yes ]; then emit "env.$name" ok "$value"; else emit "env.$name" unset ''; fi
done
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# Resolve the library used by this build, rather than choosing a stale Cargo output.
set -eu
binary=$1
library=$(otool -L "$binary" | awk '/^[[:space:]]+@rpath\/libopenconnect\..*\.dylib / { sub("@rpath/", "", $1); print $1 }')
test -n "$library" || { echo "No OpenConnect dependency in $binary" >&2; exit 1; }
rpaths=$(otool -l "$binary" | awk '/cmd LC_RPATH/ { rpath=1; next } rpath && $1 == "path" { sub(/^[[:space:]]*path /, ""); sub(/ \(offset [0-9]+\)$/, ""); print; rpath=0 }')
while IFS= read -r directory; do
case "$directory" in /*) ;; *) continue ;; esac
if [ -f "$directory/$library" ]; then
printf '%s\n' "$directory/$library"
exit 0
fi
done <<EOF
$rpaths
EOF
echo "Cannot resolve the OpenConnect build library for $binary" >&2
exit 1
+38
View File
@@ -0,0 +1,38 @@
#!/bin/sh
# Integration files use the runtime prefix, never the packaging staging directory.
set -eu
prefix=$1
source_prefix=$2
directory=$3
escape_replacement() {
printf '%s' "$1" | sed 's/[\\&|]/\\&/g'
}
# Each integration format has its own quoting rules.
desktop_prefix=$(printf '%s' "$prefix" | sed -e 's/\\/\\\\\\\\/g' -e 's/["`$]/\\\\&/g' -e 's/%/%%/g')
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')
xml_replacement=$(escape_replacement "$xml_prefix")
temporary=$(mktemp)
trap 'rm -f "$temporary"' EXIT HUP INT TERM
for file in share/applications/gpgui.desktop \
share/polkit-1/actions/com.yuezk.gpgui.policy \
lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down \
lib/NetworkManager/dispatcher.d/gpclient-nm-hook; do
path="$directory/$file"
[ -f "$path" ] || continue
case "$file" in
share/applications/*)
sed "s|$source_prefix/bin/gpclient|$desktop_command|g" "$path" > "$temporary" ;;
share/polkit-1/*)
sed -e "s|$source_prefix/bin/|$xml_replacement/bin/|g" \
-e "s|$source_prefix/libexec/gpclient/|$xml_replacement/libexec/gpclient/|g" \
"$path" > "$temporary" ;;
lib/*)
sed "s|$source_prefix/bin/gpclient|$shell_command|g" "$path" > "$temporary" ;;
esac
mode=644
case "$file" in lib/*) mode=755 ;; esac
install -m "$mode" "$temporary" "$path"
done
+158
View File
@@ -0,0 +1,158 @@
#!/usr/bin/env python3
"""Restrict distribution submissions to the targets selected for this rollout."""
import argparse
import base64
import json
import os
from pathlib import Path
import re
import sys
import time
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen
import xml.etree.ElementTree as ET
def request(url, data=None):
headers = {"User-Agent": "gp-release-target-selector", "Cache-Control": "no-cache"}
if data is not None:
credentials = f"{os.environ['OBS_USERNAME']}:{os.environ['OBS_PASSWORD']}"
headers["Authorization"] = "Basic " + base64.b64encode(credentials.encode()).decode()
headers["Content-Type"] = "application/xml"
method = "PUT" if data is not None else "GET"
with urlopen(Request(url, data=data, headers=headers, method=method), timeout=30) as response:
return response.read()
def selection(values, available):
if not values:
values = sorted(available)
if not values or len(values) != len(set(values)):
raise ValueError("Select at least one target, without duplicates")
unknown = set(values) - set(available)
if unknown:
raise ValueError(f"Unknown targets: {', '.join(sorted(unknown))}; available: {', '.join(sorted(available))}")
return sorted(values)
def copr(args):
if args.build_id:
if args.build_id <= 0:
raise ValueError("Copr build ID must be positive")
build = json.loads(request(f"https://copr.fedorainfracloud.org/api_3/build/{args.build_id}"))
if build["ownername"] != args.owner or build["projectname"] != args.project:
raise ValueError("Copr build belongs to another project")
available = build["chroots"]
else:
query = urlencode({"ownername": args.owner, "projectname": args.project})
project = json.loads(request(f"https://copr.fedorainfracloud.org/api_3/project?{query}"))
available = project["chroot_repos"]
if any(not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", name) for name in available):
raise ValueError("Copr returned an invalid chroot name")
distros = selection(args.distros, {chroot.rsplit("-", 1)[0] for chroot in available})
return sorted(chroot for chroot in available if chroot.rsplit("-", 1)[0] in distros)
def obs_results(project, package):
query = urlencode({"package": package, "view": "status"})
root = ET.fromstring(request(f"https://api.opensuse.org/public/build/{project}/_result?{query}"))
return {f"{result.get('repository')}/{result.get('arch')}": result.find("status").get("code")
for result in root if result.find("status") is not None}
def obs_metadata(metadata, targets):
# Keep publication flags for unselected targets so their existing binaries stay available.
build = metadata.find("build")
if build is None:
build = ET.SubElement(metadata, "build")
build.clear()
ET.SubElement(build, "disable")
publish = metadata.find("publish")
if publish is None:
publish = ET.SubElement(metadata, "publish")
for target in targets:
repo, arch = target.split("/")
attributes = {"repository": repo, "arch": arch}
ET.SubElement(build, "enable", attributes)
for flag in list(publish):
if flag.attrib == attributes:
publish.remove(flag)
ET.SubElement(publish, "enable", attributes)
return metadata
def obs(args):
project = quote(args.project, safe=":")
package = quote(args.package, safe="")
project_metadata = ET.fromstring(request(f"https://api.opensuse.org/public/source/{project}/_meta"))
available = {f"{repo.get('name')}/{arch.text}" for repo in project_metadata.findall("repository")
for arch in repo.findall("arch")}
states = obs_results(project, package)
active = {target for target, state in states.items() if state not in {"disabled", "excluded"}}
if args.repositories:
repositories = selection(args.repositories, {target.split("/")[0] for target in available})
targets = sorted(target for target in available if target.split("/")[0] in repositories)
else:
targets = selection(sorted(active), available)
if args.verify_only:
if set(targets) != active:
raise ValueError("OBS enabled targets differ from the requested verification selection; no flags changed")
elif args.repositories:
# Do not let an already-running unselected build publish during a rollout change.
busy = {target for target in active - set(targets)
if states[target] not in {"succeeded", "failed", "broken", "unresolvable"}}
if busy:
raise ValueError(f"Unselected OBS targets are still active: {', '.join(sorted(busy))}; wait before changing selection")
url = f"https://api.opensuse.org/source/{project}/{package}/_meta"
public_url = f"https://api.opensuse.org/public/source/{project}/{package}/_meta"
metadata = ET.fromstring(request(public_url))
updated = obs_metadata(metadata, targets)
request(url, ET.tostring(updated, encoding="utf-8"))
# Confirm the scheduler applied the allowlist before committing new source.
deadline = time.monotonic() + 120
while True:
states = obs_results(project, package)
active = {target for target, state in states.items() if state not in {"disabled", "excluded"}}
if active == set(targets):
break
if time.monotonic() >= deadline:
raise ValueError("OBS target flags have not taken effect; source was not uploaded; flags remain selected")
time.sleep(5)
args.output.write_text(json.dumps(targets) + "\n")
return targets
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="service", required=True)
copr_parser = commands.add_parser("copr")
copr_parser.add_argument("--distros", type=str.split, default=[])
copr_parser.add_argument("--owner", default="yuezk")
copr_parser.add_argument("--project", default="globalprotect-openconnect")
copr_parser.add_argument("--build-id", type=int)
obs_parser = commands.add_parser("obs")
obs_parser.add_argument("--repositories", type=str.split, default=[])
obs_parser.add_argument("--project", default="home:yuezk")
obs_parser.add_argument("--package", default="globalprotect-openconnect")
obs_parser.add_argument("--verify-only", action="store_true")
obs_parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
try:
targets = {"copr": copr, "obs": obs}[args.service](args)
except (ValueError, KeyError, OSError, ET.ParseError) as error:
print(str(error), file=sys.stderr)
return 1
message = f"Selected {args.service} targets: {' '.join(targets)}"
print(message)
if output := os.environ.get("GITHUB_OUTPUT"):
with open(output, "a") as file:
file.write(f"targets={' '.join(targets)}\n")
if summary := os.environ.get("GITHUB_STEP_SUMMARY"):
with open(summary, "a") as file:
file.write(message + "\n")
return 0
if __name__ == "__main__":
sys.exit(main())
+219
View File
@@ -0,0 +1,219 @@
#!/bin/sh
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
collector=$root/scripts/collect-diagnostics.sh
fixtures=$(mktemp -d "${TMPDIR:-/tmp}/gp-diagnostics-tests.XXXXXXXX")
trap 'rm -rf "$fixtures"' 0
trap 'exit 130' INT
trap 'exit 143' TERM HUP
mkdir "$fixtures/bin"
for tool in sh awk tr cat chmod mktemp rm ps sleep; do
ln -s "$(command -v "$tool")" "$fixtures/bin/$tool"
done
cat > "$fixtures/bin/uname" <<'MOCK'
#!/bin/sh
case "$1" in
-s) printf '%s\n' "$TEST_OS" ;;
-m) printf '%s\n' fixture-architecture ;;
-r)
case "${TEST_PROBE:-}" in
timeout)
sh -c 'trap "" TERM; echo $$ > "$TEST_CHILD_PID"; while :; do sleep 1; done' &
wait ;;
flood) awk 'BEGIN {while (1) print "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"}' ;;
*) printf '%s\n' fixture-kernel ;;
esac ;;
esac
MOCK
cat > "$fixtures/bin/id" <<'MOCK'
#!/bin/sh
printf '%s\n' 1000
MOCK
cat > "$fixtures/bin/gpclient" <<'MOCK'
#!/bin/sh
[ "$1" = --version ] || exit 2
printf '%s\n' 'gpclient 2.6.5'
MOCK
cat > "$fixtures/bin/gpauth" <<'MOCK'
#!/bin/sh
[ "$1" = --version ] || exit 2
printf '%s\n' 'gpauth 2.6.5'
MOCK
cat > "$fixtures/bin/gpgui" <<'MOCK'
#!/bin/sh
printf '%s\n' 'GUI WAS LAUNCHED' > "$TEST_GUI_MARKER"
exit 1
MOCK
cat > "$fixtures/bin/lspci" <<'MOCK'
#!/bin/sh
cat <<'DATA'
00:00.0 Host bridge: OMIT-BRIDGE
00:01.0 VGA compatible controller: Fixture GPU
Kernel driver in use: fixture-driver
00:02.0 Network controller: OMIT-NETWORK
Kernel driver in use: OMIT-NETWORK-DRIVER
DATA
MOCK
cat > "$fixtures/bin/pciconf" <<'MOCK'
#!/bin/sh
cat <<'DATA'
vgapci0@pci0:0:1:0: class=0x030000
device = 'BSD Fixture GPU'
nic0@pci0:0:2:0: class=0x020000
device = 'OMIT-NETWORK'
DATA
MOCK
cat > "$fixtures/bin/pcidump" <<'MOCK'
#!/bin/sh
printf '%s\n' '0:1:0: VGA Fixture GPU' '0:2:0: OMIT-NETWORK'
MOCK
cat > "$fixtures/bin/system_profiler" <<'MOCK'
#!/bin/sh
printf '%s\n' ' Chipset Model: Fixture Mac GPU' ' Serial Number: OMIT-SERIAL'
MOCK
cat > "$fixtures/bin/sw_vers" <<'MOCK'
#!/bin/sh
printf '%s\n' fixture-macos-version
MOCK
cat > "$fixtures/bin/sysctl" <<'MOCK'
#!/bin/sh
printf '%s\n' kvm
MOCK
cat > "$fixtures/bin/systemd-detect-virt" <<'MOCK'
#!/bin/sh
if [ "${TEST_PROBE:-}" = baremetal ]; then printf '%s\n' none; exit 1; fi
printf '%s\n' kvm
MOCK
cat > "$fixtures/bin/pkg" <<'MOCK'
#!/bin/sh
[ "$1" = query ] && [ "$2" = -a ] || exit 2
printf '%s\n' 'webkit2-gtk_41 2.52.6' 'gtk3 3.24.52' 'mesa-dri 26.2.4' 'hyprland 0.56.2' 'plasma6-plasma-workspace 6.4.4' 'private-package 1.0'
MOCK
cat > "$fixtures/bin/pkg_info" <<'MOCK'
#!/bin/sh
[ "$1" = -a ] || exit 2
printf '%s\n' 'webkitgtk41-2.52.6 WebKitGTK browser engine' 'gtk+3-3.24.52 GTK3 toolkit' 'sway-1.11 Wayland compositor' 'private-package-1.0 Do not collect'
MOCK
chmod +x "$fixtures/bin/"*
mkdir "$fixtures/home[regex]"
ln -s "$fixtures/bin/gpclient" "$fixtures/home[regex]/gpclient"
run() {
env PATH="$fixtures/bin" HOME="$fixtures/home[regex]" TMPDIR="$fixtures" \
TEST_OS="$1" TEST_PROBE="${2:-}" TEST_CHILD_PID="$fixtures/child.pid" \
TEST_GUI_MARKER="$fixtures/gui-launched" \
PRIVATE_SECRET=OMIT-SECRET DISPLAY=OMIT-DISPLAY WAYLAND_DISPLAY=OMIT-SOCKET \
DBUS_SESSION_BUS_ADDRESS=OMIT-DBUS SSH_CONNECTION=OMIT-SSH \
XDG_CURRENT_DESKTOP='KDE' DESKTOP_SESSION="$fixtures/home[regex]/desktop" \
sh "$collector" --client-version embedded-version --client-path "$fixtures/home[regex]/gpclient" > "$fixtures/report"
}
assert_contains() {
awk -v text="$1" 'index($0,text) {found=1} END {exit !found}' "$fixtures/report" || { printf 'Missing: %s\n' "$1" >&2; cat "$fixtures/report" >&2; exit 1; }
}
for os in Linux FreeBSD OpenBSD Darwin; do
run "$os"
assert_contains "os: ok: $os"
assert_contains 'gpclient_version: ok: embedded-version'
assert_contains 'gpclient_path: ok: ~/gpclient'
assert_contains 'env.DESKTOP_SESSION: ok: ~/desktop'
assert_contains 'env.XDG_CURRENT_DESKTOP: ok: KDE'
assert_contains 'ssh_session: ok: yes'
awk 'index($0,"OMIT-") {exit 1} END {if (NR != 28) exit 1}' "$fixtures/report"
[ ! -e "$fixtures/gui-launched" ]
awk 'index($0,"private-package") {exit 1}' "$fixtures/report"
case "$os" in
Linux) assert_contains 'Fixture GPU'; assert_contains 'fixture-driver' ;;
FreeBSD) assert_contains 'BSD Fixture GPU'; assert_contains 'graphics_packages: ok: webkit2-gtk_41 2.52.6'; assert_contains 'desktop_version: ok: hyprland 0.56.2 plasma6-plasma-workspace 6.4.4' ;;
OpenBSD) assert_contains 'VGA Fixture GPU'; assert_contains 'graphics_packages: ok: webkitgtk41-2.52.6'; assert_contains 'desktop_version: ok: sway-1.11' ;;
Darwin) assert_contains 'Fixture Mac GPU'; assert_contains 'display_protocol: not_applicable:' ;;
esac
printf 'PASS: %s fixture selection and privacy\n' "$os"
done
env PATH="$fixtures/bin" TEST_OS=Darwin TEST_GUI_MARKER="$fixtures/gui-launched" \
sh "$collector" --client-version fixture --gui-path "$fixtures/bin/gpgui" > "$fixtures/report"
assert_contains "gpgui_path: ok: $fixtures/bin/gpgui"
assert_contains 'gpgui_version: unavailable:'
[ ! -e "$fixtures/gui-launched" ]
printf '%s\n' 'PASS: nonbundle GUI path never borrows another installed app version'
mkdir "$fixtures/not-a-file"
printf '#!/bin/sh\nexit 0\n' > "$fixtures/not-executable"
chmod 644 "$fixtures/not-executable"
ln -s "$fixtures/missing" "$fixtures/broken-link"
for os in Linux FreeBSD OpenBSD Darwin; do
for invalid in missing not-a-file not-executable broken-link; do
env PATH="$fixtures/bin" TEST_OS="$os" TEST_GUI_MARKER="$fixtures/gui-launched" \
sh "$collector" --client-path "$fixtures/$invalid" \
--auth-path "$fixtures/$invalid" --gui-path "$fixtures/$invalid" > "$fixtures/report"
for component in gpclient gpauth gpgui; do
assert_contains "${component}_path: unavailable:"
assert_contains "${component}_version: unavailable:"
done
done
done
[ ! -e "$fixtures/gui-launched" ]
printf '%s\n' 'PASS: missing files, directories, nonexecutables and broken links are unavailable on all platforms'
# Successful probes must cancel their watchdog before doing any process-tree
# traversal. A slow snapshot used to let a finished probe become timed_out.
mv "$fixtures/bin/ps" "$fixtures/real-ps"
cat > "$fixtures/bin/ps" <<'MOCK'
#!/bin/sh
sleep 4
exit 1
MOCK
chmod +x "$fixtures/bin/ps"
run Linux
assert_contains 'os: ok: Linux'
assert_contains 'kernel: ok: fixture-kernel'
assert_contains 'graphics: ok:'
rm "$fixtures/bin/ps"
mv "$fixtures/real-ps" "$fixtures/bin/ps"
printf '%s\n' 'PASS: successful watchdog cancellation does not wait for process snapshots'
run Linux baremetal
assert_contains 'virtualization: ok: none'
printf '%s\n' 'PASS: bare-metal virtualization status'
long_value=$(awk 'BEGIN {for (i=0;i<700;i++) printf "x"; printf "\nsecond\tline"}')
env PATH="$fixtures/bin" TEST_OS=Linux XDG_CURRENT_DESKTOP="$long_value" \
sh "$collector" --client-version fixture > "$fixtures/report"
awk 'index($0,"env.XDG_CURRENT_DESKTOP: ok: ")==1 {if (length($0)-length("env.XDG_CURRENT_DESKTOP: ok: ")>500) exit 1; found=1} END {if (NR!=28 || !found) exit 1}' "$fixtures/report"
printf '%s\n' 'PASS: control flattening and value cap'
# No internal version supplied: old installations use their safe --version switch.
env PATH="$fixtures/bin" TEST_OS=Linux sh "$collector" > "$fixtures/report"
assert_contains 'gpclient_version: ok: gpclient 2.6.5'
printf '%s\n' 'PASS: standalone version discovery'
run Linux timeout
assert_contains 'kernel: timed_out:'
child=$(cat "$fixtures/child.pid")
# A reaped-or-zombie descendant is no longer running; some init implementations
# do not promptly reap an orphan after its parent is killed.
state=$(ps -p "$child" -o stat= 2>/dev/null || :)
case "$state" in ''|Z*) ;; *) printf 'Descendant still running: %s\n' "$state" >&2; exit 1 ;; esac
printf '%s\n' 'PASS: timeout and descendant termination'
run Linux flood
assert_contains 'kernel: failed:'
[ "$(wc -c < "$fixtures/report")" -lt 65536 ]
printf '%s\n' 'PASS: output flood is bounded'
rm -f "$fixtures/child.pid"
env PATH="$fixtures/bin" TEST_OS=Linux TEST_PROBE=timeout TEST_CHILD_PID="$fixtures/child.pid" \
sh "$collector" > "$fixtures/interrupted" 2>/dev/null &
collector_pid=$!
for attempt in 1 2 3 4 5; do [ ! -f "$fixtures/child.pid" ] || break; sleep 1; done
[ -f "$fixtures/child.pid" ]
kill -TERM "$collector_pid"
if wait "$collector_pid"; then exit 1; fi
child=$(cat "$fixtures/child.pid")
state=$(ps -p "$child" -o stat= 2>/dev/null || :)
case "$state" in ''|Z*) ;; *) printf 'Interrupted descendant still running: %s\n' "$state" >&2; exit 1 ;; esac
printf '%s\n' 'PASS: interruption terminates descendants'
mv "$fixtures/bin/gpauth" "$fixtures/gpauth"
run Linux
assert_contains 'gpauth_version: unavailable:'
mv "$fixtures/gpauth" "$fixtures/bin/gpauth"
printf '%s\n' 'PASS: missing optional helper'
env PATH="$fixtures/bin" TEST_OS=Linux sh "$collector" --output "$fixtures/saved" >/dev/null
cp "$fixtures/saved" "$fixtures/original"
if env PATH="$fixtures/bin" TEST_OS=Linux sh "$collector" --output "$fixtures/saved" >/dev/null 2>&1; then exit 1; fi
cmp "$fixtures/saved" "$fixtures/original"
sh "$collector" --help > "$fixtures/help"
[ -s "$fixtures/help" ]
if sh "$collector" --unknown >/dev/null 2>&1; then exit 1; fi
printf '%s\n' 'PASS: output refuses overwrite, help, argument validation'
+174
View File
@@ -0,0 +1,174 @@
#!/bin/sh
set -eu
root=$(CDPATH= cd -- "$(dirname "$0")/../.." && pwd)
cd "$root"
temp=$(mktemp -d)
trap 'rm -rf "$temp"' EXIT HUP INT TERM
mkdir -p "$temp/release"
for binary in gpclient gpauth gpservice gpgui gpgui-helper gp-vpnc-script-installer gp-hip-script-installer; do
printf '#!/bin/sh\nexit 0\n' > "$temp/release/$binary"
chmod 755 "$temp/release/$binary"
done
mkdir -p "$temp/client-release"
cp "$temp/release/gpclient" "$temp/client-release/"
make install-gpclient-unix PREFIX='/custom/gp install' DESTDIR="$temp/client-stage" \
CARGO_RELEASE_DIR="$temp/client-release" > "$temp/client.log"
installed="$temp/client-stage/custom/gp install"
test -x "$installed/bin/gpclient"
test -x "$installed/libexec/gpclient/vpnc-script"
test "$(find "$installed" -type f | wc -l | tr -d ' ')" = 2
for platform in linux bsd; do
stage="$temp/$platform-stage"
make "install-$platform" PREFIX=/custom/gp DESTDIR="$stage" \
CARGO_RELEASE_DIR="$temp/release" GPGUI_BINARY="$temp/release/gpgui" > "$temp/$platform.log"
installed="$stage/custom/gp"
test -x "$installed/bin/gpclient"
test -x "$installed/libexec/gpclient/gp-vpnc-script-installer"
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"
if [ "$platform" = bsd ]; then
test ! -d "$installed/lib/NetworkManager"
else
test -x "$installed/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down"
fi
runtime="$stage/var/lib/gpclient"
if [ "$platform" = bsd ]; then
runtime="$stage/var/db/gpclient"
mkdir -p "$stage/usr/local/libexec/gpclient"
cp "$temp/release/gpgui" "$stage/usr/local/libexec/gpclient/gpgui"
else
mkdir -p "$runtime"
cp "$temp/release/gpgui" "$runtime/gpgui"
fi
mkdir -p "$runtime/scripts"
touch "$runtime/scripts/vpnc-script" "$runtime/scripts/vpnc-script.metadata"
find "$stage" -type f > "$temp/$platform-installed-files"
touch "$installed/bin/unrelated" "$installed/libexec/gpclient/unrelated" "$runtime/scripts/unrelated"
# Repeat removal to cover an already-uninstalled or partial installation.
for attempt in 1 2; do
make "uninstall-$platform" PREFIX=/custom/gp DESTDIR="$stage" > "$temp/$platform-uninstall.log"
done
while IFS= read -r file; do test ! -e "$file"; done < "$temp/$platform-installed-files"
test -f "$installed/bin/unrelated"
test -f "$installed/libexec/gpclient/unrelated"
test -f "$runtime/scripts/unrelated"
done
mv "$temp/release/gpclient" "$temp/release/gpclient.saved"
if make install-linux PREFIX=/custom/gp DESTDIR="$temp/missing-client-stage" \
CARGO_RELEASE_DIR="$temp/release" > "$temp/missing-client.log" 2>&1; then
echo 'FAIL: installation succeeded without gpclient' >&2
exit 1
fi
test ! -e "$temp/missing-client-stage/custom/gp/bin/gpauth"
mv "$temp/release/gpclient.saved" "$temp/release/gpclient"
make install-linux PREFIX='/custom/gp install' DESTDIR="$temp/spaces-stage" \
CARGO_RELEASE_DIR="$temp/release" GPGUI_BINARY="$temp/release/gpgui" > "$temp/spaces-install.log"
find "$temp/spaces-stage" -type f > "$temp/spaces-installed-files"
make uninstall-linux PREFIX='/custom/gp install' DESTDIR="$temp/spaces-stage" > "$temp/spaces-uninstall.log"
while IFS= read -r file; do test ! -e "$file"; done < "$temp/spaces-installed-files"
# Execute generated commands against a harmless CLI fixture at a spaced prefix.
integration="$temp/integration prefix"
mkdir -p "$integration/bin" "$integration/share/applications" "$integration/lib/NetworkManager/dispatcher.d/pre-down.d"
printf '#!/bin/sh\nprintf "%%s\\n" "$@"\n' > "$integration/bin/gpclient"
chmod 755 "$integration/bin/gpclient"
cp packaging/files/usr/share/applications/gpgui.desktop "$integration/share/applications/"
cp packaging/files/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down "$integration/lib/NetworkManager/dispatcher.d/pre-down.d/"
sh scripts/relocate-install-paths.sh "$integration" /usr "$integration"
desktop_command=$(sed -n 's/^Exec=//p' "$integration/share/applications/gpgui.desktop")
test "$desktop_command" = "\"$integration/bin/gpclient\" launch-gui %u"
test "$(sh -c "$desktop_command")" = "$(printf 'launch-gui\n%%u')"
test "$(sh "$integration/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down")" = "$(printf 'disconnect\n--wait\n3')"
mkdir -p "$temp/tools"
for os in FreeBSD OpenBSD; do
printf '#!/bin/sh\ncase "$1" in -s) echo %s ;; -m) echo amd64 ;; esac\n' "$os" > "$temp/tools/uname"
chmod 755 "$temp/tools/uname"
PATH="$temp/tools:$PATH" make -n install PREFIX=/custom/gp \
CARGO_RELEASE_DIR="$temp/release" BUILD_GUI_HELPER=0 GPGUI_BINARY= > "$temp/$os.log"
grep -q 'Installing BSD integration' "$temp/$os.log"
! grep -q 'Installing Linux integration' "$temp/$os.log"
PATH="$temp/tools:$PATH" make -n uninstall > "$temp/$os-uninstall.log"
grep -q '/usr/local/bin/' "$temp/$os-uninstall.log"
grep -q '/var/db/gpclient/' "$temp/$os-uninstall.log"
! grep -q 'NetworkManager' "$temp/$os-uninstall.log"
done
for platform in Linux Darwin-arm64 Darwin-x86_64; do
os=Darwin
arch=${platform#Darwin-}
prefix=/usr/local
case "$platform" in
Linux) os=Linux; arch=x86_64; prefix=/usr ;;
Darwin-arm64) prefix=/opt/homebrew ;;
esac
printf '#!/bin/sh\ncase "$1" in -s) echo %s ;; -m) echo %s ;; esac\n' "$os" "$arch" > "$temp/tools/uname"
PATH="$temp/tools:$PATH" make -n uninstall > "$temp/$platform-uninstall.log"
grep -q "$prefix/bin/" "$temp/$platform-uninstall.log"
if [ "$os" = Darwin ]; then
grep -q "$prefix/lib/gpclient/" "$temp/$platform-uninstall.log"
! grep -q 'NetworkManager\|/var/lib/gpclient' "$temp/$platform-uninstall.log"
else
grep -q '/var/lib/gpclient/' "$temp/$platform-uninstall.log"
fi
done
if [ "$(uname -s)" = Darwin ]; then
mkdir -p "$temp/build-library" "$temp/unreferenced-library" "$temp/App/Contents/Helpers"
printf 'int fixture(void) { return 0; }\n' > "$temp/lib.c"
printf 'extern int fixture(void); int main(void) { return fixture(); }\n' > "$temp/main.c"
library="$temp/build-library/libopenconnect.5.dylib"
cc -dynamiclib "$temp/lib.c" -Wl,-install_name,@rpath/libopenconnect.5.dylib -o "$library"
printf 'int main(void) { return 0; }\n' > "$temp/no-library.c"
cc "$temp/no-library.c" -o "$temp/release/gpclient"
if make install-macos PREFIX=/custom/gp DESTDIR="$temp/no-library-stage" \
CARGO_RELEASE_DIR="$temp/release" > "$temp/no-library.log" 2>&1; then
echo 'FAIL: macOS installation succeeded without an OpenConnect dependency' >&2
exit 1
fi
test ! -e "$temp/no-library-stage/custom/gp/libexec/gpclient/vpnc-script"
cc "$temp/main.c" "$library" -Wl,-rpath,@executable_path/../lib/gpclient \
-Wl,-rpath,"$temp/build-library" -o "$temp/release/gpclient"
printf 'stale library must never be selected\n' > "$temp/unreferenced-library/libopenconnect.5.dylib"
test "$(sh scripts/macos-openconnect-library.sh "$temp/release/gpclient")" = "$library"
cp "$temp/release/gpclient" "$temp/client-release/"
make install-gpclient PREFIX='/custom/gp install' DESTDIR="$temp/macos-client-stage" \
CARGO_RELEASE_DIR="$temp/client-release" > "$temp/macos-client.log"
installed="$temp/macos-client-stage/custom/gp install"
test -x "$installed/bin/gpclient"
test -x "$installed/libexec/gpclient/vpnc-script"
test -f "$installed/lib/gpclient/libopenconnect.5.dylib"
test "$(find "$installed" -type f | wc -l | tr -d ' ')" = 3
installed="$temp/macos-stage/custom/gp"
mkdir -p "$installed/lib" "$temp/homebrew-cellar"
printf 'Homebrew-owned library\n' > "$temp/homebrew-cellar/libopenconnect.5.dylib"
ln -s "$temp/homebrew-cellar/libopenconnect.5.dylib" "$installed/lib/libopenconnect.5.dylib"
make install-macos PREFIX=/custom/gp DESTDIR="$temp/macos-stage" \
CARGO_RELEASE_DIR="$temp/release" > "$temp/macos.log"
test -f "$installed/lib/gpclient/libopenconnect.5.dylib"
test -L "$installed/lib/libopenconnect.5.dylib"
test "$(cat "$temp/homebrew-cellar/libopenconnect.5.dylib")" = 'Homebrew-owned library'
! otool -l "$temp/macos-stage/custom/gp/bin/gpclient" | grep -F "$temp/build-library"
cp "$temp/release/gpclient" "$temp/App/Contents/Helpers/gpclient"
install_name_tool -delete_rpath "$temp/build-library" "$temp/App/Contents/Helpers/gpclient"
dylibbundler --overwrite-dir --bundle-deps --search-path "$temp/build-library" \
--install-path @executable_path/../Frameworks --dest-dir "$temp/App/Contents/Frameworks" \
--fix-file "$temp/App/Contents/Helpers/gpclient" > "$temp/bundle.log"
codesign --force --sign - "$temp/App/Contents/Frameworks/libopenconnect.5.dylib"
codesign --force --sign - "$temp/App/Contents/Helpers/gpclient"
mv "$temp/build-library" "$temp/removed-build-library"
"$temp/macos-stage/custom/gp/bin/gpclient"
"$temp/macos-client-stage/custom/gp install/bin/gpclient"
"$temp/App/Contents/Helpers/gpclient"
touch "$installed/lib/gpclient/unrelated" "$installed/libexec/gpclient/unrelated"
for attempt in 1 2; do
make uninstall PREFIX=/custom/gp DESTDIR="$temp/macos-stage" > "$temp/macos-uninstall.log"
done
test ! -e "$installed/bin/gpclient"
test ! -e "$installed/bin/gpauth"
test ! -e "$installed/lib/gpclient/libopenconnect.5.dylib"
test ! -e "$installed/libexec/gpclient/vpnc-script"
test -f "$installed/lib/gpclient/unrelated"
test -f "$installed/libexec/gpclient/unrelated"
test -L "$installed/lib/libopenconnect.5.dylib"
test "$(cat "$temp/homebrew-cellar/libopenconnect.5.dylib")" = 'Homebrew-owned library'
fi
echo 'PASS: install/uninstall paths, unrelated-file preservation, and native macOS library relocation'
+72
View File
@@ -0,0 +1,72 @@
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).parents[1] / "verify-docker-publication.sh"
AMD64 = "sha256:" + "a" * 64
ARM64 = "sha256:" + "b" * 64
INDEX = "sha256:" + "c" * 64
def manifest(digest, architecture):
platform_os = "unknown" if architecture == "unknown" else "linux"
return {"digest": digest, "platform": {"os": platform_os, "architecture": architecture}}
class DockerPublicationTests(unittest.TestCase):
def run_verifier(self, images, source_index=True, selection="all"):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
digests = root / "digests"
digests.mkdir()
(digests / (INDEX if source_index else AMD64)[7:]).touch()
if selection == "all":
(digests / ARM64[7:]).touch()
responses = {
"example/image:3.0.1": {"manifests": images},
"example/image@" + INDEX: {"manifests": [manifest(AMD64, "amd64"), manifest("sha256:attestation", "unknown")]},
"example/image@" + AMD64: {"config": {}},
"example/image@" + ARM64: {"config": {}},
}
(root / "responses.json").write_text(json.dumps(responses))
docker = root / "docker"
docker.write_text("#!/usr/bin/env python3\nimport json, os, sys\n"
"print(json.dumps(json.load(open(os.environ['RESPONSES']))[sys.argv[4]]))\n")
docker.chmod(0o755)
sleep = root / "sleep"
sleep.write_text("#!/bin/sh\nexit 0\n")
sleep.chmod(0o755)
env = {**os.environ, "PATH": str(root) + os.pathsep + os.environ["PATH"],
"RESPONSES": str(root / "responses.json")}
return subprocess.run(["bash", str(SCRIPT), "example/image:3.0.1", str(digests), selection],
env=env, capture_output=True, text=True)
def test_attested_sources_match_the_published_platform_digests(self):
result = self.run_verifier([manifest(AMD64, "amd64"), manifest(ARM64, "arm64"),
manifest("sha256:attestation", "unknown")])
self.assertEqual(result.returncode, 0, result.stderr)
def test_missing_architecture_cannot_pass(self):
result = self.run_verifier([manifest(AMD64, "amd64")])
self.assertNotEqual(result.returncode, 0)
self.assertIn("did not match", result.stderr)
def test_another_build_of_same_platforms_cannot_pass(self):
result = self.run_verifier([manifest("sha256:" + "d" * 64, "amd64"), manifest(ARM64, "arm64")])
self.assertNotEqual(result.returncode, 0)
def test_unselected_platform_cannot_pass(self):
result = self.run_verifier([manifest(AMD64, "amd64"), manifest(ARM64, "arm64"),
manifest("sha256:extra", "riscv64")])
self.assertNotEqual(result.returncode, 0)
def test_selected_single_architecture_is_supported(self):
result = self.run_verifier([manifest(AMD64, "amd64")], source_index=False, selection="x86_64")
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == "__main__":
unittest.main()
+120
View File
@@ -0,0 +1,120 @@
import argparse
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import MagicMock, patch
import xml.etree.ElementTree as ET
spec = importlib.util.spec_from_file_location("selector", Path(__file__).parents[1] / "select-publication-targets.py")
selector = importlib.util.module_from_spec(spec)
spec.loader.exec_module(selector)
class SelectionTests(unittest.TestCase):
def test_unknown_and_duplicate_targets_fail(self):
for values in (["typo"], ["fedora-44", "fedora-44"]):
with self.assertRaises(ValueError):
selector.selection(values, {"fedora-44", "fedora-45"})
def test_obs_metadata_uses_authenticated_put_without_authenticating_public_reads(self):
response = MagicMock()
response.__enter__.return_value.read.return_value = b"ok"
with patch.object(selector, "urlopen", return_value=response) as opening, \
patch.dict(selector.os.environ, {"OBS_USERNAME": "test", "OBS_PASSWORD": "test"}):
selector.request("https://api.opensuse.org/source/project/package/_meta", b"<package/>")
upload = opening.call_args.args[0]
self.assertEqual(upload.get_method(), "PUT")
self.assertIsNotNone(upload.get_header("Authorization"))
selector.request("https://api.opensuse.org/public/source/project/package/_meta")
public = opening.call_args.args[0]
self.assertEqual(public.get_method(), "GET")
self.assertIsNone(public.get_header("Authorization"))
def test_copr_expands_selected_distro_to_all_its_configured_architectures(self):
args = argparse.Namespace(owner="yuezk", project="globalprotect-openconnect",
distros=["fedora-44"], build_id=None)
response = json.dumps({"chroot_repos": {"fedora-44-aarch64": "url", "fedora-44-x86_64": "url",
"fedora-45-x86_64": "url"}}).encode()
with patch.object(selector, "request", return_value=response):
self.assertEqual(selector.copr(args), ["fedora-44-aarch64", "fedora-44-x86_64"])
args.distros = ["fedora-typo"]
with self.assertRaisesRegex(ValueError, "Unknown targets"):
selector.copr(args)
def test_copr_recovery_uses_original_build_targets_even_if_project_changed(self):
args = argparse.Namespace(owner="yuezk", project="globalprotect-openconnect", distros=[], build_id=42)
response = json.dumps({"ownername": args.owner, "projectname": args.project,
"chroots": ["fedora-43-x86_64"]}).encode()
with patch.object(selector, "request", return_value=response) as request:
self.assertEqual(selector.copr(args), ["fedora-43-x86_64"])
self.assertIn("/build/42", request.call_args.args[0])
class OBSSelectionTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.args = argparse.Namespace(project="home:yuezk", package="globalprotect-openconnect",
repositories=["16.0"], verify_only=False,
output=Path(self.directory.name) / "targets.json")
self.targets = ["16.0/aarch64", "16.0/x86_64"]
self.project = b'''<project><repository name="16.0"><arch>x86_64</arch><arch>aarch64</arch></repository>
<repository name="15.6"><arch>x86_64</arch><arch>aarch64</arch></repository></project>'''
self.package = b'''<package><title>Keep me</title><build><disable repository="old"/></build>
<publish><disable repository="old"/><disable repository="16.0" arch="x86_64"/></publish>
<useforbuild><disable arch="armv7l"/></useforbuild></package>'''
def test_metadata_changes_build_allowlist_but_keeps_other_publication_flags(self):
metadata = selector.obs_metadata(ET.fromstring(self.package), self.targets)
self.assertEqual(metadata.findtext("title"), "Keep me")
self.assertIsNotNone(metadata.find("build/disable"))
self.assertEqual([flag.attrib for flag in metadata.findall("build/enable")],
[{"repository": "16.0", "arch": "aarch64"},
{"repository": "16.0", "arch": "x86_64"}])
self.assertEqual(metadata.find("publish/disable").attrib, {"repository": "old"})
self.assertEqual(len(metadata.findall("publish/disable")), 1)
self.assertEqual(metadata.find("useforbuild/disable").get("arch"), "armv7l")
def test_selection_is_applied_before_source_can_be_uploaded(self):
before = {"16.0/x86_64": "succeeded", "16.0/aarch64": "succeeded",
"15.6/x86_64": "succeeded", "15.6/aarch64": "succeeded"}
after = {"16.0/x86_64": "succeeded", "16.0/aarch64": "succeeded",
"15.6/x86_64": "disabled", "15.6/aarch64": "disabled"}
with patch.object(selector, "request", side_effect=[self.project, self.package, b"ok"]) as request, \
patch.object(selector, "obs_results", side_effect=[before, after]):
selector.obs(self.args)
self.assertEqual(json.loads(self.args.output.read_text()), self.targets)
self.assertIn("/source/home:yuezk/globalprotect-openconnect/_meta", request.call_args.args[0])
uploaded = ET.fromstring(request.call_args.args[1])
self.assertEqual({flag.get("arch") for flag in uploaded.findall("build/enable")}, {"x86_64", "aarch64"})
def test_busy_unselected_target_prevents_mutation(self):
states = {"16.0/x86_64": "succeeded", "16.0/aarch64": "succeeded", "15.6/aarch64": "building"}
with patch.object(selector, "request", return_value=self.project) as request, \
patch.object(selector, "obs_results", return_value=states):
with self.assertRaisesRegex(ValueError, "still active"):
selector.obs(self.args)
self.assertEqual(request.call_count, 1)
def test_verify_only_does_not_mutate_to_hide_an_unselected_build(self):
self.args.verify_only = True
states = {"16.0/x86_64": "succeeded", "16.0/aarch64": "succeeded", "15.6/aarch64": "succeeded"}
with patch.object(selector, "request", return_value=self.project) as request, \
patch.object(selector, "obs_results", return_value=states):
with self.assertRaisesRegex(ValueError, "differ"):
selector.obs(self.args)
self.assertEqual(request.call_count, 1)
def test_empty_selection_preserves_current_flags(self):
self.args.repositories = []
states = {"16.0/x86_64": "succeeded", "16.0/aarch64": "disabled"}
with patch.object(selector, "request", return_value=self.project) as request, \
patch.object(selector, "obs_results", return_value=states):
self.assertEqual(selector.obs(self.args), ["16.0/x86_64"])
self.assertEqual(request.call_count, 1)
if __name__ == "__main__":
unittest.main()
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more