Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4faa2ecb0d | ||
|
|
18ed6bac1a | ||
|
|
10139e0f2c | ||
|
|
ff1ea259d9 | ||
|
|
57322e3cf3 | ||
|
|
9532374805 | ||
|
|
90faa58811 | ||
|
|
93504eaec2 | ||
|
|
d73b712dd3 | ||
|
|
be111a671a | ||
|
|
f9965f8a35 | ||
|
|
f7649898fd | ||
|
|
e6910060df | ||
|
|
f41a429a5e | ||
|
|
888f288c0d | ||
|
|
f0292a9292 | ||
|
|
580b81e7bb |
No files matched your search
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -38,9 +44,6 @@ on:
|
||||
- .devcontainer
|
||||
branches:
|
||||
- main
|
||||
- hotfix/*
|
||||
- feature/*
|
||||
- release/*
|
||||
tags:
|
||||
- v*.*.*
|
||||
|
||||
@@ -49,7 +52,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 +80,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 +127,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 +141,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 +201,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 +252,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 +329,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 +405,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 +469,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 +507,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 +516,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 +524,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 +556,7 @@ jobs:
|
||||
exit 1
|
||||
|
||||
setup-bsd-matrix:
|
||||
needs: validate-inputs
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
enabled: ${{ steps.matrix.outputs.enabled }}
|
||||
@@ -575,7 +565,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 +573,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 +700,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 +757,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 +783,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 +799,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 +810,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 +819,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 +870,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 +892,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 +915,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 +932,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 +960,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
|
||||
@@ -44,23 +44,34 @@ jobs:
|
||||
run: |
|
||||
pacman -Syu --noconfirm --needed \
|
||||
appmenu-gtk-module \
|
||||
autoconf \
|
||||
automake \
|
||||
cargo \
|
||||
curl \
|
||||
desktop-file-utils \
|
||||
file \
|
||||
git \
|
||||
gettext \
|
||||
gmp \
|
||||
gnutls \
|
||||
libappindicator-gtk3 \
|
||||
libp11-kit \
|
||||
libsecret \
|
||||
libtool \
|
||||
libxml2 \
|
||||
lz4 \
|
||||
make \
|
||||
namcap \
|
||||
openconnect \
|
||||
nettle \
|
||||
openssl \
|
||||
patch \
|
||||
pkgconf \
|
||||
librsvg \
|
||||
shared-mime-info \
|
||||
vpnc \
|
||||
wget \
|
||||
webkit2gtk-4.1
|
||||
webkit2gtk-4.1 \
|
||||
xdg-utils \
|
||||
zlib
|
||||
|
||||
- name: Save committed .SRCINFO
|
||||
if: ${{ github.event_name == 'push' }}
|
||||
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -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}"
|
||||
@@ -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'
|
||||
@@ -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:
|
||||
|
||||
@@ -11,7 +11,7 @@ members = [
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.91"
|
||||
version = "3.0.0"
|
||||
version = "3.1.0"
|
||||
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"
|
||||
# RUST_LOG accepts user-supplied Unicode property filters through env_logger.
|
||||
regex = { version = "1", default-features = false, features = ["std", "perf", "unicode"] }
|
||||
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"
|
||||
sha2 = { version = "0.11", 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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -73,6 +73,8 @@ Options:
|
||||
-V, --version Print version
|
||||
```
|
||||
|
||||
The `--fix-openssl` option is available on Linux, FreeBSD, and OpenBSD. macOS uses native TLS and GnuTLS and does not accept this option.
|
||||
|
||||
> **Tip:** Use `gpclient help <command>` for detailed information on a specific command.
|
||||
|
||||
#### HIP reports
|
||||
@@ -95,6 +97,8 @@ Use `gpclient` directly for browser-based authentication. It opens the browser a
|
||||
sudo gpclient connect <portal> --browser
|
||||
```
|
||||
|
||||
For standalone CLI installations, use `--browser manual` (`--browser remote` before v3.0.6): open the printed URL and paste the resulting `globalprotectcallback:…` data into the terminal.
|
||||
|
||||
To reuse a saved portal cookie for later connections, add `--cookie-cache`:
|
||||
|
||||
```bash
|
||||
@@ -109,10 +113,9 @@ sudo gpclient connect <portal> --browser --cookie-cache=/absolute/path/to/cookie
|
||||
|
||||
**Browser Options:**
|
||||
|
||||
- Use `--browser` to try your recognized default browser first, then another detected browser, and finally the system URL handler
|
||||
- Use `--browser default` to use the system default browser
|
||||
- Use `--browser` to automatically select an available browser
|
||||
- Use `--browser <browser>` to specify a browser (e.g., `firefox`, `chrome`)
|
||||
- Use `--browser remote` for headless servers – this provides a URL you can access from another machine to complete authentication
|
||||
- Use `--browser manual` for standalone CLI installations or headless servers
|
||||
|
||||
### Graphical User Interface
|
||||
|
||||
@@ -365,18 +368,18 @@ docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
connect <portal>
|
||||
```
|
||||
|
||||
For browser authentication in a headless environment, use remote browser authentication:
|
||||
For browser authentication in a headless environment, use manual browser authentication:
|
||||
|
||||
```bash
|
||||
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:<version> \
|
||||
connect <portal> --browser remote
|
||||
connect <portal> --browser manual
|
||||
```
|
||||
|
||||
On a host with multiple network interfaces, use `--browser-listen` to select the IP address reachable from the browser machine:
|
||||
|
||||
```bash
|
||||
gpclient connect <portal> --browser remote --browser-listen 192.168.107.15
|
||||
gpclient connect <portal> --browser manual --browser-listen 192.168.107.15
|
||||
```
|
||||
|
||||
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
|
||||
@@ -384,7 +387,7 @@ On a Linux host, add host networking if the VPN routes should affect the host ne
|
||||
```bash
|
||||
docker run --rm -it --network host --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:<version> \
|
||||
connect <portal> --browser remote
|
||||
connect <portal> --browser manual
|
||||
```
|
||||
|
||||
Without `--network host`, the VPN connection stays inside the container's network namespace. Docker Desktop on macOS and Windows does not make the host use the VPN through `--network host`; run `gpclient` on the host or use a container gateway setup for host traffic.
|
||||
@@ -513,12 +516,14 @@ Verify the CLI client is working correctly:
|
||||
### Build Options
|
||||
|
||||
- `BUILD_GUI_HELPER=0` – Skip building and installing the GUI helper
|
||||
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication; use an external or remote browser
|
||||
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication; use an external browser or manual authentication
|
||||
- `INCLUDE_GUI=1` – Download the matching published Linux desktop application for installation
|
||||
- `OFFLINE=1` – Build in offline mode using vendored dependencies
|
||||
|
||||
## 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.
|
||||
@@ -537,7 +542,7 @@ sudo gpclient connect <portal> --browser
|
||||
|
||||
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||
|
||||
On a headless server, use `--browser remote` and complete authentication from another machine.
|
||||
On a headless server, use `--browser manual` and complete authentication from another machine.
|
||||
|
||||
## NetworkManager Integration
|
||||
|
||||
|
||||
@@ -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 }
|
||||
|
||||
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 27 KiB After Width: | Height: | Size: 26 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 57 KiB After Width: | Height: | Size: 56 KiB |
@@ -6,17 +6,21 @@ use clap::Parser;
|
||||
use clap::Subcommand;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use gpapi::auth::AuthWindowTheme;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use gpapi::utils::openssl;
|
||||
use gpapi::{
|
||||
auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult},
|
||||
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
|
||||
error::ServerTlsError,
|
||||
gp_params::GpParams,
|
||||
log_format::LogFormat,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
utils::{normalize_server, openssl},
|
||||
utils::normalize_server,
|
||||
};
|
||||
use log::info;
|
||||
use serde_json::json;
|
||||
use std::net::IpAddr;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
const VERSION: &str = concat!(
|
||||
@@ -84,6 +88,7 @@ struct Cli {
|
||||
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
|
||||
key_password: Option<String>,
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[arg(long, help = "Get around the OpenSSL `unsafe legacy renegotiation` error")]
|
||||
fix_openssl: bool,
|
||||
|
||||
@@ -104,13 +109,13 @@ struct Cli {
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser or `remote` for headless servers.",
|
||||
help = "Use a browser; omit the value to auto-select. Use `manual` to open the URL and paste the callback.",
|
||||
default_missing_value = "auto",
|
||||
num_args=0..=1
|
||||
)]
|
||||
browser: Option<String>,
|
||||
|
||||
#[arg(long, help = "Listen on this IP address when using '--browser remote'")]
|
||||
#[arg(long, help = "Listen on this IP address when using '--browser manual'")]
|
||||
browser_listen: Option<IpAddr>,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
@@ -144,6 +149,7 @@ enum CliCommand {
|
||||
}
|
||||
|
||||
impl Args for Cli {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> bool {
|
||||
self.fix_openssl
|
||||
}
|
||||
@@ -158,10 +164,8 @@ impl Args for Cli {
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
fn prepare_env(&self) -> anyhow::Result<Option<NamedTempFile>> {
|
||||
#[cfg(feature = "webview-auth")]
|
||||
gpapi::utils::env_utils::patch_gui_runtime_env(self.hidpi);
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn prepare_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
|
||||
if self.fix_openssl {
|
||||
info!("Fixing OpenSSL environment");
|
||||
let file = openssl::fix_openssl_env()?;
|
||||
@@ -174,16 +178,19 @@ impl Cli {
|
||||
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
if self.browser_listen.is_some()
|
||||
&& !matches!(self.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote"))
|
||||
&& !matches!(self.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("manual") || browser.eq_ignore_ascii_case("remote"))
|
||||
{
|
||||
anyhow::bail!("The '--browser-listen' option requires '--browser remote'");
|
||||
anyhow::bail!("The '--browser-listen' option requires '--browser manual'");
|
||||
}
|
||||
|
||||
if self.ignore_tls_errors {
|
||||
info!("TLS errors will be ignored");
|
||||
}
|
||||
|
||||
let openssl_conf = self.prepare_env()?;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
gpapi::utils::env_utils::patch_gui_runtime_env(self.hidpi);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let openssl_conf = self.prepare_openssl()?;
|
||||
|
||||
let server = normalize_server(self.server.as_deref().expect("server is required for authentication"))?;
|
||||
let gp_params = self.build_gp_params();
|
||||
@@ -194,7 +201,17 @@ impl Cli {
|
||||
|
||||
let auth_request = match self.saml_request.as_deref() {
|
||||
Some(auth_request) => auth_request.to_string(),
|
||||
None => auth_prelogin(&server, &gp_params, self.external_browser_requested(), self.gateway).await?,
|
||||
None => match auth_prelogin(&server, &gp_params, self.external_browser_requested(), self.gateway).await {
|
||||
Ok(request) => request,
|
||||
Err(error) => {
|
||||
let Some(tls) = error.downcast_ref::<ServerTlsError>().cloned() else {
|
||||
return Err(error);
|
||||
};
|
||||
handle_error(error, self);
|
||||
print_auth_result(Err(tls.into()), None);
|
||||
return Ok(());
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
@@ -213,7 +230,7 @@ impl Cli {
|
||||
|
||||
print_auth_result(auth_result, Some(&auth_host_id));
|
||||
|
||||
// explicitly drop openssl_conf to avoid the unused variable warning
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
drop(openssl_conf);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -226,6 +243,7 @@ impl Cli {
|
||||
self.clean,
|
||||
self.window_title.clone(),
|
||||
self.window_theme,
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
openssl_conf,
|
||||
)
|
||||
.await?;
|
||||
@@ -298,7 +316,11 @@ pub async fn run() {
|
||||
}
|
||||
|
||||
pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>) {
|
||||
let auth_result = match auth_result {
|
||||
println!("{}", json!(auth_outcome(auth_result, host_id)));
|
||||
}
|
||||
|
||||
fn auth_outcome(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>) -> SamlAuthResult {
|
||||
match auth_result {
|
||||
Ok(auth_data) => {
|
||||
let auth_data = match host_id {
|
||||
Some(host_id) => auth_data.with_host_id(host_id),
|
||||
@@ -307,16 +329,54 @@ pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Opt
|
||||
SamlAuthResult::Success(auth_data)
|
||||
}
|
||||
Err(err) if err.downcast_ref::<AuthenticationCancelled>().is_some() => SamlAuthResult::Cancelled,
|
||||
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
|
||||
};
|
||||
|
||||
println!("{}", json!(auth_result));
|
||||
Err(err) => match err.downcast::<ServerTlsError>() {
|
||||
Ok(tls) => SamlAuthResult::ServerTlsError(tls),
|
||||
Err(err) => SamlAuthResult::Failure(err.to_string()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn openssl_option_is_available_only_on_supported_platforms() {
|
||||
let result = Cli::try_parse_from(["gpauth", "portal.example.com", "--fix-openssl"]);
|
||||
assert_eq!(result.is_ok(), !cfg!(target_os = "macos"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn result_keeps_server_tls_kind_and_generic_failure_format() {
|
||||
use gpapi::error::ServerTlsErrorKind;
|
||||
let tls = ServerTlsError {
|
||||
server: "https://vpn.example.com".into(),
|
||||
kind: ServerTlsErrorKind::LegacyRenegotiation,
|
||||
};
|
||||
let outcome = auth_outcome(Err(anyhow::Error::new(tls).context("retry failed")), None);
|
||||
assert_eq!(
|
||||
serde_json::to_value(outcome).unwrap(),
|
||||
json!({"serverTlsError": {"server": "https://vpn.example.com", "kind": "legacyRenegotiation"}})
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(auth_outcome(Err(anyhow::anyhow!("rejected")), None)).unwrap(),
|
||||
json!({"failure": "rejected"})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_result_preserves_client_certificate_requirement() {
|
||||
let error = ServerTlsError {
|
||||
server: "https://vpn.example.com".into(),
|
||||
kind: gpapi::error::ServerTlsErrorKind::ClientCertificateRequired,
|
||||
};
|
||||
let outcome = auth_outcome(Err(anyhow::Error::new(error).context("retry failed")), None);
|
||||
assert_eq!(
|
||||
serde_json::to_value(outcome).unwrap(),
|
||||
json!({"serverTlsError": {"server": "https://vpn.example.com", "kind": "clientCertificateRequired"}})
|
||||
);
|
||||
}
|
||||
|
||||
/// gpauth's own result already goes to stdout as JSON; this makes its *logs*
|
||||
/// readable the same way, so a caller driving it does not have to parse prose
|
||||
/// on stderr to find out why an attempt failed.
|
||||
@@ -399,7 +459,7 @@ mod tests {
|
||||
"gpauth",
|
||||
"portal.example.com",
|
||||
"--browser",
|
||||
"remote",
|
||||
"manual",
|
||||
"--browser-listen",
|
||||
"192.168.107.15",
|
||||
])
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use auth::{WebviewAuthenticator, apply_auth_theme};
|
||||
use gpapi::{auth::AuthWindowTheme, gp_params::GpParams};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use log::info;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use tauri::RunEvent;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
use crate::cli::print_auth_result;
|
||||
@@ -13,7 +16,7 @@ pub async fn authenticate(
|
||||
clean: bool,
|
||||
window_title: Option<String>,
|
||||
window_theme: AuthWindowTheme,
|
||||
mut openssl_conf: Option<NamedTempFile>,
|
||||
#[cfg(not(target_os = "macos"))] mut openssl_conf: Option<NamedTempFile>,
|
||||
) -> anyhow::Result<()> {
|
||||
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
|
||||
|
||||
@@ -43,8 +46,9 @@ pub async fn authenticate(
|
||||
Ok(())
|
||||
})
|
||||
.build(crate::tauri_context::get())?
|
||||
.run(move |_app_handle, event| {
|
||||
if let RunEvent::Exit = event {
|
||||
.run(move |_app_handle, _event| {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if let RunEvent::Exit = _event {
|
||||
if let Some(file) = openssl_conf.take() {
|
||||
if let Err(err) = file.close() {
|
||||
info!("Error closing OpenSSL config file: {}", err);
|
||||
|
||||
@@ -11,12 +11,17 @@ common = { path = "../../crates/common" }
|
||||
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
|
||||
gphip = { path = "../../crates/gphip" }
|
||||
openconnect = { path = "../../crates/openconnect" }
|
||||
gptunnel = { path = "../../crates/gptunnel" }
|
||||
|
||||
anyhow.workspace = true
|
||||
clap.workspace = true
|
||||
env_logger.workspace = true
|
||||
inquire = "0.9"
|
||||
log.workspace = true
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process", "poll", "term"] }
|
||||
ratatui = { version = "=0.30.2", default-features = false, features = ["crossterm", "unstable-rendered-line-info"] }
|
||||
crossterm = { version = "0.29", features = ["use-dev-tty"] }
|
||||
strip-ansi-escapes = "0.2"
|
||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||
tokio-util.workspace = true
|
||||
sysinfo.workspace = true
|
||||
@@ -32,3 +37,6 @@ uzers.workspace = true
|
||||
[features]
|
||||
default = ["webview-auth"]
|
||||
webview-auth = ["gpapi/webview-auth"]
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
gpvpnc = { path = "../../crates/gpvpnc" }
|
||||
@@ -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");
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -5,19 +5,22 @@ use std::{
|
||||
|
||||
use anyhow::bail;
|
||||
use clap::{Parser, Subcommand};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use gpapi::utils::openssl;
|
||||
use gpapi::{
|
||||
clap::{Args, InfoLevelVerbosity, handle_error},
|
||||
log_format::{LogFormat, write_json_record},
|
||||
utils::openssl,
|
||||
};
|
||||
use log::info;
|
||||
use sysinfo::{Pid, System};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use tempfile::NamedTempFile;
|
||||
use tokio::fs;
|
||||
|
||||
use crate::{
|
||||
GP_CLIENT_LOCK_FILE,
|
||||
connect::{ConnectArgs, ConnectHandler},
|
||||
diagnostics::DiagnosticsArgs,
|
||||
disconnect::{DisconnectArgs, DisconnectHandler},
|
||||
hip::{HipArgs, HipHandler},
|
||||
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
|
||||
@@ -33,6 +36,7 @@ const VERSION: &str = concat!(
|
||||
);
|
||||
|
||||
pub(crate) struct SharedArgs<'a> {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub(crate) fix_openssl: bool,
|
||||
pub(crate) ignore_tls_errors: bool,
|
||||
pub(crate) lock_file: &'a Path,
|
||||
@@ -50,6 +54,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)]
|
||||
@@ -89,6 +95,7 @@ struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: CliCommand,
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[arg(
|
||||
long,
|
||||
help = "Uses extended compatibility mode for OpenSSL operations to support a broader range of systems and formats."
|
||||
@@ -104,6 +111,9 @@ struct Cli {
|
||||
)]
|
||||
lock_file: PathBuf,
|
||||
|
||||
#[arg(long, hide = true, global = true)]
|
||||
background_worker_fd: Option<i32>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
@@ -117,6 +127,7 @@ struct Cli {
|
||||
}
|
||||
|
||||
impl Args for Cli {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> bool {
|
||||
self.fix_openssl
|
||||
}
|
||||
@@ -158,6 +169,7 @@ impl Cli {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
|
||||
if self.fix_openssl {
|
||||
let file = openssl::fix_openssl_env()?;
|
||||
@@ -168,15 +180,46 @@ impl Cli {
|
||||
}
|
||||
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
if let CliCommand::Connect(args) = &self.command {
|
||||
if args.dashboard {
|
||||
crate::dashboard::validate(self.log_format)?;
|
||||
}
|
||||
}
|
||||
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
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _file = self.fix_openssl()?;
|
||||
let shared_args = SharedArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: self.fix_openssl,
|
||||
ignore_tls_errors: self.ignore_tls_errors,
|
||||
lock_file: &self.lock_file,
|
||||
@@ -189,10 +232,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)?);
|
||||
@@ -227,7 +276,13 @@ fn build_logger(cli: &Cli) -> env_logger::Builder {
|
||||
pub(crate) async fn run() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
build_logger(&cli).init();
|
||||
if matches!(&cli.command, CliCommand::Connect(args) if args.dashboard) {
|
||||
let logger = build_logger(&cli).build();
|
||||
log::set_max_level(logger.filter());
|
||||
log::set_boxed_logger(Box::new(crate::dashboard::NoticeLogger::new(logger))).expect("failed to initialize logger");
|
||||
} else {
|
||||
build_logger(&cli).init();
|
||||
}
|
||||
|
||||
info!("gpclient started: {}", VERSION);
|
||||
|
||||
@@ -248,6 +303,94 @@ 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 dashboard_is_opt_in_and_conflicts_with_noninteractive_connection_modes() {
|
||||
for option in ["--background", "--cookie-only"] {
|
||||
assert!(Cli::try_parse_from(["gpclient", "connect", "portal.example.com", "--dashboard", option]).is_err());
|
||||
}
|
||||
assert!(Cli::try_parse_from(["gpclient", "connect", "portal.example.com", "--stats"]).is_err());
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"connect",
|
||||
"portal.example.com",
|
||||
"--dashboard",
|
||||
"--cookie-on-stdin",
|
||||
])
|
||||
.unwrap();
|
||||
assert!(matches!(cli.command, CliCommand::Connect(args) if args.dashboard));
|
||||
let cli = Cli::try_parse_from(["gpclient", "connect", "portal.example.com"]).unwrap();
|
||||
assert!(matches!(cli.command, CliCommand::Connect(args) if !args.dashboard));
|
||||
assert!(
|
||||
crate::dashboard::validate(LogFormat::Json)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("--log-format json")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openssl_option_is_available_only_on_supported_platforms() {
|
||||
let result = Cli::try_parse_from(["gpclient", "--fix-openssl", "diagnostics"]);
|
||||
assert_eq!(result.is_ok(), !cfg!(target_os = "macos"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostics_accepts_output_options_and_runs_alongside_the_client() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
"--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([
|
||||
@@ -409,6 +552,40 @@ mod tests {
|
||||
captured.contents()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_property_log_filters_keep_matching_and_excluding_records() {
|
||||
for (pattern, matching, excluded) in [
|
||||
(r"\p{Greek}", "α", "plain ASCII"),
|
||||
(r"\p{Mark}", "\u{0301}", "plain ASCII"),
|
||||
(r"\p{Alphabetic}", "α", "123"),
|
||||
(r"\p{Grapheme_Extend}", "\u{0301}", "plain ASCII"),
|
||||
] {
|
||||
let captured = Captured::default();
|
||||
let logger = build_logger(&parse_cli(&["gpclient", "disconnect"]))
|
||||
.parse_filters(&format!("info/{pattern}"))
|
||||
.target(env_logger::Target::Pipe(Box::new(captured.clone())))
|
||||
.build();
|
||||
for message in [excluded, matching] {
|
||||
logger.log(
|
||||
&log::Record::builder()
|
||||
.level(log::Level::Info)
|
||||
.target("gpclient")
|
||||
.args(format_args!("{message}"))
|
||||
.build(),
|
||||
);
|
||||
}
|
||||
let output = captured.contents();
|
||||
assert!(
|
||||
output.contains(matching),
|
||||
"filter {pattern} dropped its matching record"
|
||||
);
|
||||
assert!(
|
||||
!output.contains(excluded),
|
||||
"filter {pattern} allowed an excluded record"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The point of the flag: with `json`, a caller gets fields, and gets them one
|
||||
/// record per line so the stream can be read incrementally.
|
||||
#[test]
|
||||
|
||||
@@ -13,6 +13,27 @@ 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,
|
||||
conflicts_with_all = ["background", "cookie_only"],
|
||||
help = "Show an interactive connection dashboard after sign-in (requires a foreground terminal)"
|
||||
)]
|
||||
pub(crate) dashboard: 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>,
|
||||
|
||||
@@ -144,13 +165,13 @@ pub(crate) struct ConnectArgs {
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser or `remote` for headless servers.",
|
||||
help = "Use a browser; omit the value to auto-select. Use `manual` to open the URL and paste the callback.",
|
||||
default_missing_value = "auto",
|
||||
num_args=0..=1
|
||||
)]
|
||||
pub(super) browser: Option<String>,
|
||||
|
||||
#[arg(long, help = "Listen on this IP address when using '--browser remote'")]
|
||||
#[arg(long, help = "Listen on this IP address when using '--browser manual'")]
|
||||
pub(super) browser_listen: Option<IpAddr>,
|
||||
|
||||
#[arg(
|
||||
@@ -285,7 +306,7 @@ mod tests {
|
||||
"test",
|
||||
"portal.example.com",
|
||||
"--browser",
|
||||
"remote",
|
||||
"manual",
|
||||
"--browser-listen",
|
||||
"192.168.107.15",
|
||||
])
|
||||
|
||||
@@ -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, ¶ms, self.prelogin_options(browser_allowed)) => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn obtain_credential(
|
||||
&self,
|
||||
prelogin: &Prelogin,
|
||||
@@ -76,10 +125,10 @@ 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)
|
||||
.fix_openssl(self.shared_args.fix_openssl)
|
||||
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
|
||||
.certificate(self.args.certificate.as_deref())
|
||||
.sslkey(self.args.sslkey.as_deref())
|
||||
@@ -89,6 +138,9 @@ impl ConnectHandler<'_> {
|
||||
.log_format(self.shared_args.log_format)
|
||||
.verbose(verbose);
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let auth_launcher = auth_launcher.fix_openssl(self.shared_args.fix_openssl);
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
let use_default_browser = external_browser_supported && self.args.default_browser;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
@@ -116,6 +168,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)
|
||||
|
||||
@@ -98,6 +98,7 @@ async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
@@ -143,6 +144,7 @@ async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_reject
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
@@ -171,3 +173,355 @@ 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 {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
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 {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
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 {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
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 {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
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 {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -20,14 +20,14 @@ use gpapi::{
|
||||
};
|
||||
use inquire::Text;
|
||||
use log::{Level, info, warn};
|
||||
use openconnect::{HipScript, HipSource, Vpn, VpnBuilder};
|
||||
use openconnect::{HipScript, HipSource, VpnBuilder};
|
||||
use tokio::{runtime::Handle, task::JoinHandle};
|
||||
|
||||
use crate::session::{
|
||||
SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info,
|
||||
};
|
||||
|
||||
use super::{ConnectHandler, args::cookie_cache_path};
|
||||
use super::{ConnectHandler, args::cookie_cache_path, vpn_script};
|
||||
|
||||
const OPENCONNECT_INTERRUPTED_EXIT_CODE: i32 = -4;
|
||||
|
||||
@@ -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()?;
|
||||
@@ -436,10 +443,8 @@ impl ConnectHandler<'_> {
|
||||
disable_ipv6: self.args.disable_ipv6,
|
||||
extension_auth: Some(extension_auth),
|
||||
});
|
||||
let vpn_builder = Vpn::builder(gateway, cookie)
|
||||
.script(self.args.script.clone())
|
||||
let vpn_builder = vpn_script::builder(gateway, cookie, self.args)
|
||||
.interface(self.args.interface.clone())
|
||||
.script_tun(self.args.script_tun)
|
||||
.certificate(certificate)
|
||||
.sslkey(sslkey)
|
||||
.key_password(key_password)
|
||||
@@ -451,15 +456,6 @@ impl ConnectHandler<'_> {
|
||||
.local_hostname(self.args.local_hostname.clone())
|
||||
.dpd_interval(self.args.dpd_interval.unwrap_or(0))
|
||||
.no_xmlpost(self.args.no_xmlpost);
|
||||
#[cfg(target_os = "macos")]
|
||||
let vpn_builder = if self.args.script.is_none()
|
||||
&& std::env::var_os("GP_VPNC_SCRIPT").is_none_or(|value| value.is_empty())
|
||||
&& let Some(script) = common::binary_paths::bundled_vpnc_script()
|
||||
{
|
||||
vpn_builder.script_path(script.to_string_lossy().into_owned())
|
||||
} else {
|
||||
vpn_builder
|
||||
};
|
||||
let vpn = apply_os_profile(vpn_builder, &os_profile)
|
||||
.build()
|
||||
.map_err(|err| GatewayConnectError::before_establishment(err.into()))?;
|
||||
@@ -477,6 +473,23 @@ 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 mut dashboard = if self.args.dashboard {
|
||||
Some(
|
||||
crate::dashboard::Dashboard::prepare(gateway.to_owned(), self.cancellation.clone())
|
||||
.map_err(GatewayConnectError::before_establishment)?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let monitor = gptunnel::TunnelMonitor::attach(vpn.clone());
|
||||
|
||||
let disconnect_task = tokio::spawn(async move {
|
||||
cancellation.cancelled().await;
|
||||
info!("Received the interrupt signal, disconnecting...");
|
||||
@@ -490,7 +503,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 +522,7 @@ impl ConnectHandler<'_> {
|
||||
session_task_on_connect.lock().unwrap().replace(task);
|
||||
})
|
||||
});
|
||||
tokio::pin!(worker);
|
||||
let mut output_error = None;
|
||||
let connect_result = tokio::select! {
|
||||
result = &mut worker => result,
|
||||
established = established_rx => {
|
||||
@@ -518,13 +531,40 @@ 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(dashboard) = &mut dashboard {
|
||||
if let Err(error) = dashboard.start_tunnel(monitor.clone()) {
|
||||
self.cancellation.cancel();
|
||||
output_error = Some(error);
|
||||
}
|
||||
}
|
||||
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();
|
||||
output_error = Some(error);
|
||||
}
|
||||
}
|
||||
}).await
|
||||
} else {
|
||||
(&mut worker).await
|
||||
}
|
||||
(&mut worker).await
|
||||
}
|
||||
};
|
||||
monitor.stop().await;
|
||||
if let Some(dashboard) = &mut dashboard {
|
||||
if let Err(error) = dashboard.finish() {
|
||||
output_error = Some(error);
|
||||
}
|
||||
}
|
||||
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
|
||||
disconnect_task.abort();
|
||||
let _ = disconnect_task.await;
|
||||
@@ -535,6 +575,10 @@ impl ConnectHandler<'_> {
|
||||
let _ = task.await;
|
||||
}
|
||||
|
||||
if let Some(error) = output_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 +621,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 +700,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);
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -105,6 +112,18 @@ impl ConnectHandler<'_> {
|
||||
let source = Arc::new(source);
|
||||
let validate_network = network.clone();
|
||||
let validate_detection = detection.clone();
|
||||
let members = crate::dashboard::InternalMembers::default();
|
||||
let dashboard_members = members.clone();
|
||||
let (established_tx, established_rx) = tokio::sync::oneshot::channel();
|
||||
let established_tx = std::sync::Mutex::new(Some(established_tx));
|
||||
let mut dashboard = if self.args.dashboard {
|
||||
Some(crate::dashboard::Dashboard::prepare(
|
||||
authenticated[0].0.server().to_owned(),
|
||||
cancellation.clone(),
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let callbacks = SessionCallbacks {
|
||||
produce_report: Arc::new(move |request, control| {
|
||||
control.check()?;
|
||||
@@ -136,12 +155,23 @@ impl ConnectHandler<'_> {
|
||||
)
|
||||
}),
|
||||
report_submitted: Arc::new(|_, _| {}),
|
||||
status_changed: Arc::new(|member| match member.maintenance {
|
||||
MaintenanceState::Healthy => info!(
|
||||
"Internal network — authenticated: {} (IPv4: {:?}, IPv6: {:?})",
|
||||
member.gateway, member.client_ip, member.client_ipv6
|
||||
),
|
||||
state => info!("Internal gateway {}: {state:?}", member.gateway),
|
||||
status_changed: Arc::new(move |member| {
|
||||
match member.maintenance {
|
||||
MaintenanceState::Healthy => {
|
||||
info!(
|
||||
"Internal network — authenticated: {} (IPv4: {:?}, IPv6: {:?})",
|
||||
member.gateway, member.client_ip, member.client_ipv6
|
||||
);
|
||||
if let Some(established) = established_tx.lock().unwrap().take() {
|
||||
let _ = established.send(());
|
||||
}
|
||||
}
|
||||
state => info!("Internal gateway {}: {state:?}", member.gateway),
|
||||
}
|
||||
members.lock().unwrap().insert(
|
||||
member.gateway.server().to_owned(),
|
||||
format!("{}: {:?}", member.gateway, member.maintenance),
|
||||
);
|
||||
}),
|
||||
validate_network: Arc::new(move |cancellation| {
|
||||
let network = validate_network.clone();
|
||||
@@ -176,13 +206,38 @@ impl ConnectHandler<'_> {
|
||||
std::sync::atomic::Ordering::SeqCst,
|
||||
);
|
||||
let mut sessions = self.sessions.take();
|
||||
let result = maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation, async move {
|
||||
network_signal.await.unwrap_or(SessionEndReason::NetworkChanged)
|
||||
})
|
||||
.await;
|
||||
let mut dashboard_error = None;
|
||||
let result = {
|
||||
let maintenance = maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation, async move {
|
||||
network_signal.await.unwrap_or(SessionEndReason::NetworkChanged)
|
||||
});
|
||||
tokio::pin!(maintenance);
|
||||
tokio::select! {
|
||||
result = &mut maintenance => result,
|
||||
established = established_rx => {
|
||||
if established.is_ok() {
|
||||
if let Some(dashboard) = &mut dashboard {
|
||||
if let Err(error) = dashboard.start_internal(dashboard_members) {
|
||||
self.cancellation.cancel();
|
||||
dashboard_error = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
maintenance.await
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(dashboard) = &mut dashboard {
|
||||
if let Err(error) = dashboard.finish() {
|
||||
dashboard_error = Some(error);
|
||||
}
|
||||
}
|
||||
self.sessions.replace(sessions);
|
||||
monitor_cancel.cancel();
|
||||
monitor.await.context("Internal network monitor failed")?;
|
||||
if let Some(error) = dashboard_error {
|
||||
return Err(error);
|
||||
}
|
||||
match result? {
|
||||
SessionExit::Disconnected => Ok(()),
|
||||
SessionExit::Failed(reason) => bail!("Internal session ended: {reason:?}. Connect again to authenticate."),
|
||||
|
||||
@@ -4,6 +4,7 @@ mod credential;
|
||||
mod flow_tests;
|
||||
mod gateway;
|
||||
mod internal;
|
||||
mod vpn_script;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::{
|
||||
@@ -41,8 +42,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 +68,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 +126,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() {
|
||||
@@ -139,9 +154,9 @@ impl<'a> ConnectHandler<'a> {
|
||||
|
||||
async fn handle_attempt(&self) -> anyhow::Result<()> {
|
||||
if self.args.browser_listen.is_some()
|
||||
&& !matches!(self.args.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote"))
|
||||
&& !matches!(self.args.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("manual") || browser.eq_ignore_ascii_case("remote"))
|
||||
{
|
||||
bail!("The '--browser-listen' option requires '--browser remote'");
|
||||
bail!("The '--browser-listen' option requires '--browser manual'");
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
@@ -153,15 +168,29 @@ 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(());
|
||||
};
|
||||
|
||||
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
|
||||
if err
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
let Some(identity_error) = err.downcast_ref::<RequestIdentityError>() else {
|
||||
return Err(err);
|
||||
};
|
||||
|
||||
match root_cause {
|
||||
match identity_error {
|
||||
RequestIdentityError::UnsupportedEncryption
|
||||
| RequestIdentityError::LegacyKeyConversion(_)
|
||||
| RequestIdentityError::UnsupportedKeyFormat
|
||||
| RequestIdentityError::InvalidKey
|
||||
| RequestIdentityError::InvalidCertificate
|
||||
| RequestIdentityError::IncompletePkcs12
|
||||
| RequestIdentityError::InvalidPkcs12(_) => return Err(err),
|
||||
RequestIdentityError::NoKey => {
|
||||
let format = self.shared_args.log_format;
|
||||
report(
|
||||
@@ -212,6 +241,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 +274,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 +296,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 +344,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: {}",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
|
||||
use crate::connect::ConnectArgs;
|
||||
|
||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> VpnBuilder {
|
||||
Vpn::builder(server, cookie)
|
||||
.script(args.script.clone())
|
||||
.script_tun(args.script_tun)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
use std::ffi::OsStr;
|
||||
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
|
||||
use crate::connect::ConnectArgs;
|
||||
|
||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> VpnBuilder {
|
||||
let configured_script = std::env::var_os("GP_VPNC_SCRIPT");
|
||||
configure_builder(server, cookie, args, configured_script.as_deref())
|
||||
}
|
||||
|
||||
fn configure_builder(server: &str, cookie: &str, args: &ConnectArgs, configured_script: Option<&OsStr>) -> VpnBuilder {
|
||||
let builder = Vpn::builder(server, cookie)
|
||||
.script(args.script.clone())
|
||||
.script_tun(args.script_tun);
|
||||
let has_environment_script = configured_script.is_some_and(|value| !value.is_empty());
|
||||
if args.script.is_none() && !args.script_tun && !has_environment_script {
|
||||
builder.network_configuration_handler(|configuration| {
|
||||
gpvpnc::macos::configure_network(&configuration.reason, &configuration.environment)
|
||||
})
|
||||
} else {
|
||||
builder
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use clap::Parser;
|
||||
|
||||
#[derive(Parser)]
|
||||
struct TestCli {
|
||||
#[command(flatten)]
|
||||
args: ConnectArgs,
|
||||
}
|
||||
|
||||
fn args(options: &[&str]) -> ConnectArgs {
|
||||
TestCli::try_parse_from(
|
||||
["connect", "vpn.example.com"]
|
||||
.into_iter()
|
||||
.chain(options.iter().copied()),
|
||||
)
|
||||
.unwrap()
|
||||
.args
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_does_not_require_an_installed_script() {
|
||||
for configured in [None, Some(OsStr::new(""))] {
|
||||
assert!(
|
||||
configure_builder("server", "cookie", &args(&[]), configured)
|
||||
.build()
|
||||
.is_ok()
|
||||
);
|
||||
assert!(
|
||||
configure_builder("server", "cookie", &args(&[]), configured)
|
||||
.script("/bin/sh".to_string())
|
||||
.script_tun(true)
|
||||
.build()
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_commands_and_script_tunnels_remain_supported() {
|
||||
for options in [
|
||||
vec!["--script", "exec /bin/sh"],
|
||||
vec!["--script", "/bin/sh", "--script-tun"],
|
||||
] {
|
||||
assert!(
|
||||
configure_builder("server", "cookie", &args(&options), None)
|
||||
.build()
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environment_override_does_not_install_default_callback() {
|
||||
let builder = configure_builder("server", "cookie", &args(&[]), Some(OsStr::new("/bin/sh")));
|
||||
// Converting the selected builder to an explicit packet script would fail
|
||||
// if the embedded configuration callback had replaced the environment override.
|
||||
assert!(builder.script("/bin/sh".to_string()).script_tun(true).build().is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "macos.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
|
||||
pub(super) use platform::builder;
|
||||
@@ -0,0 +1,625 @@
|
||||
//! Dashboard presentation only; connection ownership and sampling stay outside this module.
|
||||
use crossterm::event::KeyCode;
|
||||
use gpapi::session::tunnel::{TunnelList, TunnelPhase, TunnelState, TunnelStatisticsSnapshot, TunnelStatisticsState};
|
||||
use ratatui::{
|
||||
Frame,
|
||||
buffer::Buffer,
|
||||
layout::Rect,
|
||||
style::{Color, Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Paragraph, Widget, Wrap},
|
||||
};
|
||||
|
||||
use super::output::plain_text;
|
||||
|
||||
const MAX_CONTENT_WIDTH: u16 = 120;
|
||||
const LABEL_WIDTH: usize = 12;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct DetailScroll {
|
||||
offset: u16,
|
||||
maximum: u16,
|
||||
page: u16,
|
||||
}
|
||||
|
||||
impl DetailScroll {
|
||||
pub(super) fn handle_key(&mut self, key: KeyCode) {
|
||||
self.offset = match key {
|
||||
KeyCode::Up => self.offset.saturating_sub(1),
|
||||
KeyCode::Down => self.offset.saturating_add(1),
|
||||
KeyCode::PageUp => self.offset.saturating_sub(self.page),
|
||||
KeyCode::PageDown => self.offset.saturating_add(self.page),
|
||||
KeyCode::Home => 0,
|
||||
KeyCode::End => self.maximum,
|
||||
_ => self.offset,
|
||||
}
|
||||
.min(self.maximum);
|
||||
}
|
||||
|
||||
pub(super) fn can_scroll(&self) -> bool {
|
||||
self.maximum > 0
|
||||
}
|
||||
|
||||
fn update(&mut self, content_height: u16, viewport_height: u16) {
|
||||
self.maximum = if viewport_height == 0 {
|
||||
0
|
||||
} else {
|
||||
content_height.saturating_sub(viewport_height)
|
||||
};
|
||||
self.offset = self.offset.min(self.maximum);
|
||||
self.page = viewport_height.saturating_sub(1).max(1);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn phase_label(phase: TunnelPhase) -> &'static str {
|
||||
match phase {
|
||||
TunnelPhase::Establishing => "Establishing",
|
||||
TunnelPhase::Connected => "Connected",
|
||||
TunnelPhase::Reconnecting => "Reconnecting",
|
||||
TunnelPhase::Ended => "Disconnected",
|
||||
}
|
||||
}
|
||||
|
||||
fn uptime(milliseconds: u64) -> String {
|
||||
let seconds = milliseconds / 1000;
|
||||
format!("{:02}:{:02}:{:02}", seconds / 3600, (seconds / 60) % 60, seconds % 60)
|
||||
}
|
||||
|
||||
fn bytes(value: u64) -> String {
|
||||
const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
|
||||
let mut amount = value as f64;
|
||||
let mut unit = 0;
|
||||
while amount >= 1024.0 && unit < UNITS.len() - 1 {
|
||||
amount /= 1024.0;
|
||||
unit += 1;
|
||||
}
|
||||
if unit == 0 {
|
||||
format!("{value} B")
|
||||
} else {
|
||||
format!("{amount:.1} {}", UNITS[unit])
|
||||
}
|
||||
}
|
||||
|
||||
fn muted(text: impl Into<String>) -> Span<'static> {
|
||||
Span::styled(text.into(), Style::default().fg(Color::DarkGray))
|
||||
}
|
||||
|
||||
fn heading(text: impl Into<String>) -> Line<'static> {
|
||||
Line::styled(
|
||||
text.into(),
|
||||
Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn row(label: &str, value: impl Into<String>) -> Line<'static> {
|
||||
Line::from(vec![
|
||||
muted(format!("{label:<LABEL_WIDTH$} ")),
|
||||
Span::raw(plain_text(value.into().as_bytes())),
|
||||
])
|
||||
}
|
||||
|
||||
fn paragraph(lines: Vec<Line<'static>>) -> Paragraph<'static> {
|
||||
Paragraph::new(lines).wrap(Wrap { trim: false })
|
||||
}
|
||||
|
||||
fn summary(server: &str, state: &TunnelState, width: u16) -> Paragraph<'static> {
|
||||
let status = Span::styled(
|
||||
format!("{:<LABEL_WIDTH$} ", phase_label(state.phase)),
|
||||
Style::default().fg(if state.phase == TunnelPhase::Connected {
|
||||
Color::Green
|
||||
} else {
|
||||
Color::Yellow
|
||||
}),
|
||||
);
|
||||
let mut lines = if width >= 64 {
|
||||
vec![Line::from(vec![
|
||||
status,
|
||||
Span::raw(format!(
|
||||
"{} Uptime {}",
|
||||
state.transport.label(),
|
||||
uptime(state.elapsed_ms)
|
||||
)),
|
||||
])]
|
||||
} else {
|
||||
vec![
|
||||
Line::from(status),
|
||||
row("Transport", state.transport.label()),
|
||||
row("Uptime", uptime(state.elapsed_ms)),
|
||||
]
|
||||
};
|
||||
lines.insert(0, row("Server", server));
|
||||
paragraph(lines)
|
||||
}
|
||||
|
||||
fn traffic(statistics: &TunnelStatisticsSnapshot, width: u16) -> Paragraph<'static> {
|
||||
let mut lines = vec![heading("TRAFFIC")];
|
||||
if let Some(view) = statistics.view() {
|
||||
let label = match view.state {
|
||||
TunnelStatisticsState::Disabled => "disabled",
|
||||
TunnelStatisticsState::Waiting => "waiting for sample",
|
||||
TunnelStatisticsState::Fresh => "live",
|
||||
TunnelStatisticsState::Stale => "stale",
|
||||
TunnelStatisticsState::Ended => "ended",
|
||||
};
|
||||
lines[0] = heading(format!("TRAFFIC · {label}"));
|
||||
if let Some(sample) = &view.sample {
|
||||
if width >= 56 {
|
||||
let rows = [
|
||||
("Bytes", bytes(sample.received_bytes), bytes(sample.sent_bytes)),
|
||||
(
|
||||
"Packets",
|
||||
sample.received_packets.to_string(),
|
||||
sample.sent_packets.to_string(),
|
||||
),
|
||||
];
|
||||
// Size to the values, while keeping room for full u64 counters and a
|
||||
// visible gap even when both numeric columns are filled.
|
||||
let numeric_width = rows
|
||||
.iter()
|
||||
.flat_map(|(_, received, sent)| [received.len(), sent.len()])
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
.max(10);
|
||||
lines.push(Line::from(muted(format!(
|
||||
"{:<10}{:>numeric_width$} {:>numeric_width$}",
|
||||
"", "Received", "Sent"
|
||||
))));
|
||||
for (label, received, sent) in rows {
|
||||
lines.push(Line::from(vec![
|
||||
muted(format!("{label:<10}")),
|
||||
Span::raw(format!("{received:>numeric_width$} {sent:>numeric_width$}")),
|
||||
]));
|
||||
}
|
||||
} else {
|
||||
lines.push(row("Received", bytes(sample.received_bytes)));
|
||||
lines.push(row("Sent", bytes(sample.sent_bytes)));
|
||||
lines.push(row("Packets in", sample.received_packets.to_string()));
|
||||
lines.push(row("Packets out", sample.sent_packets.to_string()));
|
||||
}
|
||||
if view.state != TunnelStatisticsState::Fresh {
|
||||
if let Some(age) = view.sample_age_ms {
|
||||
lines.push(row("Sample age", format!("{} seconds", age / 1000)));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
lines.push(row("Statistics", "unavailable"));
|
||||
}
|
||||
paragraph(lines)
|
||||
}
|
||||
|
||||
fn list_rows(lines: &mut Vec<Line<'static>>, label: &str, value: &TunnelList) {
|
||||
if value.items.is_empty() && !value.truncated {
|
||||
lines.push(row(label, "none"));
|
||||
} else {
|
||||
for (index, item) in value.items.iter().enumerate() {
|
||||
lines.push(row(if index == 0 { label } else { "" }, item));
|
||||
}
|
||||
if value.truncated {
|
||||
lines.push(row("", format!("[truncated; {} total]", value.total_count)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn routes(lines: &mut Vec<Line<'static>>, label: &str, list: &TunnelList, width: u16) {
|
||||
lines.push(row(label, list.total_count.to_string()));
|
||||
// Only whole entries move between columns. Long individual entries wrap through
|
||||
// Paragraph rather than disappearing off the edge of a narrow terminal.
|
||||
let entries: Vec<_> = list.items.iter().map(|item| plain_text(item.as_bytes())).collect();
|
||||
let cell_width = entries.iter().map(|item| Line::raw(item).width()).max().unwrap_or(0) + 3;
|
||||
let columns = (width as usize / cell_width).clamp(1, 3);
|
||||
for chunk in entries.chunks(columns) {
|
||||
let mut spans = Vec::new();
|
||||
for (index, entry) in chunk.iter().enumerate() {
|
||||
spans.push(Span::raw(entry.clone()));
|
||||
if index + 1 < chunk.len() {
|
||||
spans.push(Span::raw(" ".repeat(cell_width - Line::raw(entry).width())));
|
||||
}
|
||||
}
|
||||
lines.push(Line::from(spans));
|
||||
}
|
||||
if list.truncated {
|
||||
lines.push(Line::raw(format!(
|
||||
"[truncated; showing {} of {}]",
|
||||
list.items.len(),
|
||||
list.total_count
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
fn details(state: &TunnelState, statistics: &TunnelStatisticsSnapshot, width: u16) -> Buffer {
|
||||
let traffic = traffic(statistics, width);
|
||||
let traffic_height = traffic.line_count(width) as u16;
|
||||
let mut tunnel = vec![heading("TUNNEL")];
|
||||
let mut dns = vec![heading("DNS")];
|
||||
let mut route_lines = vec![heading("ROUTES")];
|
||||
if let Some(config) = &state.configuration {
|
||||
tunnel.extend([
|
||||
row("Interface", config.interface.as_deref().unwrap_or("none")),
|
||||
row(
|
||||
"IPv4",
|
||||
config
|
||||
.ipv4
|
||||
.as_ref()
|
||||
.map(|address| address.display())
|
||||
.unwrap_or_else(|| "none".into()),
|
||||
),
|
||||
row(
|
||||
"IPv6",
|
||||
config
|
||||
.ipv6
|
||||
.as_ref()
|
||||
.map(|address| address.display())
|
||||
.unwrap_or_else(|| "none".into()),
|
||||
),
|
||||
row("Gateway", config.server_ip.as_deref().unwrap_or("none")),
|
||||
row(
|
||||
"MTU",
|
||||
config.mtu.map(|mtu| mtu.to_string()).unwrap_or_else(|| "none".into()),
|
||||
),
|
||||
]);
|
||||
list_rows(&mut dns, "Servers", &config.dns);
|
||||
list_rows(&mut dns, "Domains", &config.search_domains);
|
||||
list_rows(&mut dns, "Split DNS", &config.split_dns);
|
||||
routes(&mut route_lines, "Included", &config.included_routes, width);
|
||||
routes(&mut route_lines, "Excluded", &config.excluded_routes, width);
|
||||
if config.truncated {
|
||||
route_lines.push(row("Configuration", "truncated"));
|
||||
}
|
||||
} else {
|
||||
tunnel.push(row("Configuration", "unavailable"));
|
||||
}
|
||||
let tunnel = paragraph(tunnel);
|
||||
let dns = paragraph(dns);
|
||||
let routes = paragraph(route_lines);
|
||||
let columns = width >= 88;
|
||||
let column_width = if columns { (width - 4) / 2 } else { width };
|
||||
let tunnel_height = tunnel.line_count(column_width) as u16;
|
||||
let dns_height = dns.line_count(column_width) as u16;
|
||||
let network_height = if columns {
|
||||
tunnel_height.max(dns_height)
|
||||
} else {
|
||||
tunnel_height + 1 + dns_height
|
||||
};
|
||||
let network_y = traffic_height + 1;
|
||||
let routes_y = network_y + network_height + 1;
|
||||
let height = routes_y + routes.line_count(width) as u16;
|
||||
let mut buffer = Buffer::empty(Rect::new(0, 0, width, height));
|
||||
traffic.render(Rect::new(0, 0, width, traffic_height), &mut buffer);
|
||||
tunnel.render(Rect::new(0, network_y, column_width, tunnel_height), &mut buffer);
|
||||
let (dns_x, dns_y) = if columns {
|
||||
(column_width + 4, network_y)
|
||||
} else {
|
||||
(0, network_y + tunnel_height + 1)
|
||||
};
|
||||
dns.render(Rect::new(dns_x, dns_y, column_width, dns_height), &mut buffer);
|
||||
routes.render(Rect::new(0, routes_y, width, height - routes_y), &mut buffer);
|
||||
buffer
|
||||
}
|
||||
|
||||
pub(super) fn render_tunnel(
|
||||
frame: &mut Frame,
|
||||
area: Rect,
|
||||
server: &str,
|
||||
state: &TunnelState,
|
||||
statistics: &TunnelStatisticsSnapshot,
|
||||
scroll: &mut DetailScroll,
|
||||
) {
|
||||
if area.is_empty() {
|
||||
return;
|
||||
}
|
||||
let area = Rect {
|
||||
width: area.width.min(MAX_CONTENT_WIDTH),
|
||||
..area
|
||||
};
|
||||
let full_summary = summary(server, state, area.width);
|
||||
let summary = if full_summary.line_count(area.width) + 2 > area.height as usize {
|
||||
Paragraph::new(phase_label(state.phase))
|
||||
} else {
|
||||
full_summary
|
||||
};
|
||||
let summary_height = (summary.line_count(area.width) as u16).min(area.height);
|
||||
frame.render_widget(summary, Rect::new(area.x, area.y, area.width, summary_height));
|
||||
let body_y = summary_height.saturating_add(1).min(area.height);
|
||||
let viewport = Rect::new(area.x, area.y + body_y, area.width, area.height - body_y);
|
||||
let buffer = details(state, statistics, area.width);
|
||||
scroll.update(buffer.area.height, viewport.height);
|
||||
// Render the full detail layout with Ratatui, then expose just the scrolled rows.
|
||||
// This preserves wrapped fields and aligned columns through terminal resizes.
|
||||
for y in 0..viewport.height {
|
||||
if y + scroll.offset >= buffer.area.height {
|
||||
break;
|
||||
}
|
||||
for x in 0..viewport.width {
|
||||
frame.buffer_mut()[(viewport.x + x, viewport.y + y)] = buffer[(x, y + scroll.offset)].clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpapi::session::tunnel::{TunnelStatistics, TunnelStatisticsView, TunnelTransport};
|
||||
use ratatui::{Terminal, backend::TestBackend};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn state() -> TunnelState {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"tunnelId": "00000000-0000-0000-0000-000000000001",
|
||||
"sequence": "1", "phase": "connected", "configurationRevision": "1",
|
||||
"transport": "ipsecEsp", "elapsedMs": "177000",
|
||||
"configuration": {
|
||||
"interface": "tun0", "serverIp": "220.191.185.154",
|
||||
"ipv4": {"address": "10.197.121.152", "prefixLength": 32, "netmask": null},
|
||||
"ipv6": null, "mtu": 1439, "truncated": false,
|
||||
"dns": {"items": ["10.197.82.140", "10.15.70.11"], "totalCount": 2, "truncated": false},
|
||||
"searchDomains": {"items": ["corp.microstrategy.com"], "totalCount": 1, "truncated": false},
|
||||
"splitDns": {"items": [], "totalCount": 0, "truncated": false},
|
||||
"includedRoutes": {"items": ["10.15.70.11/32", "10.197.82.140/32", "185.199.108.0/22", "2001:db8:1234:5678::/64"], "totalCount": 5, "truncated": true},
|
||||
"excludedRoutes": {"items": ["192.168.0.0/16"], "totalCount": 1, "truncated": false}
|
||||
}
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
fn statistics(state: &TunnelState) -> TunnelStatisticsSnapshot {
|
||||
TunnelStatisticsSnapshot::Available(TunnelStatisticsView {
|
||||
sequence: 1,
|
||||
tunnel_id: state.tunnel_id,
|
||||
state_sequence: 1,
|
||||
phase: state.phase,
|
||||
transport: TunnelTransport::IpsecEsp,
|
||||
state: TunnelStatisticsState::Fresh,
|
||||
elapsed_ms: state.elapsed_ms,
|
||||
sample_age_ms: Some(0),
|
||||
sample: Some(TunnelStatistics {
|
||||
tunnel_id: state.tunnel_id,
|
||||
sequence: 1,
|
||||
state_sequence: 1,
|
||||
configuration_revision: 1,
|
||||
elapsed_ms: state.elapsed_ms,
|
||||
received_bytes: 1_258_291,
|
||||
sent_bytes: 71_578,
|
||||
received_packets: u64::MAX,
|
||||
sent_packets: 702,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
fn text(buffer: &Buffer) -> String {
|
||||
(0..buffer.area.height)
|
||||
.map(|y| {
|
||||
(0..buffer.area.width)
|
||||
.map(|x| buffer[(x, y)].symbol())
|
||||
.collect::<String>()
|
||||
.trim_end()
|
||||
.to_string()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_and_transport_share_a_column_through_status_changes() {
|
||||
let mut state = state();
|
||||
for width in [40, 64, 120] {
|
||||
for phase in [
|
||||
TunnelPhase::Establishing,
|
||||
TunnelPhase::Connected,
|
||||
TunnelPhase::Reconnecting,
|
||||
TunnelPhase::Ended,
|
||||
] {
|
||||
state.phase = phase;
|
||||
let mut buffer = Buffer::empty(Rect::new(0, 0, width, 8));
|
||||
summary("vpn.example.com", &state, width).render(buffer.area, &mut buffer);
|
||||
let rendered = text(&buffer);
|
||||
let server = rendered.lines().find(|line| line.contains("vpn.example.com")).unwrap();
|
||||
let transport = rendered.lines().find(|line| line.contains("IPsec (ESP)")).unwrap();
|
||||
assert_eq!(server.find("vpn.example.com"), Some(14));
|
||||
assert_eq!(
|
||||
transport.find("IPsec (ESP)"),
|
||||
server.find("vpn.example.com"),
|
||||
"{phase:?} at width {width}"
|
||||
);
|
||||
assert!(rendered.lines().any(|line| line.starts_with(phase_label(phase))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_layout_groups_settings_and_keeps_routes_and_counters_intact() {
|
||||
let state = state();
|
||||
let buffer = details(&state, &statistics(&state), 100);
|
||||
let text = text(&buffer);
|
||||
let headings = text.lines().find(|line| line.starts_with("TUNNEL")).unwrap();
|
||||
assert!(headings.contains("DNS"));
|
||||
assert!(text.contains("18446744073709551615"));
|
||||
assert!(text.contains("1.2 MiB"));
|
||||
assert!(text.contains("69.9 KiB"));
|
||||
assert!(text.contains("2001:db8:1234:5678::/64"));
|
||||
assert!(text.contains("[truncated; showing 4 of 5]"));
|
||||
assert!(text.contains("192.168.0.0/16"));
|
||||
let received_column = text
|
||||
.lines()
|
||||
.find(|line| line.contains("Received"))
|
||||
.unwrap()
|
||||
.find("Received")
|
||||
.unwrap()
|
||||
+ "Received".len();
|
||||
let bytes_column = text
|
||||
.lines()
|
||||
.find(|line| line.starts_with("Bytes"))
|
||||
.unwrap()
|
||||
.find("1.2 MiB")
|
||||
.unwrap()
|
||||
+ "1.2 MiB".len();
|
||||
assert_eq!(received_column, bytes_column);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traffic_columns_stay_compact_with_a_visible_gap() {
|
||||
let state = state();
|
||||
let mut stats = statistics(&state);
|
||||
let TunnelStatisticsSnapshot::Available(view) = &mut stats else {
|
||||
unreachable!()
|
||||
};
|
||||
view.sample.as_mut().unwrap().received_packets = 6518;
|
||||
let mut buffer = Buffer::empty(Rect::new(0, 0, 120, 4));
|
||||
traffic(&stats, 120).render(buffer.area, &mut buffer);
|
||||
let rendered = text(&buffer);
|
||||
for line in rendered.lines() {
|
||||
assert!(
|
||||
line.len() <= 40,
|
||||
"traffic row should not expand with the terminal: {line}"
|
||||
);
|
||||
}
|
||||
let TunnelStatisticsSnapshot::Available(view) = &mut stats else {
|
||||
unreachable!()
|
||||
};
|
||||
view.sample.as_mut().unwrap().received_packets = u64::MAX;
|
||||
view.sample.as_mut().unwrap().sent_packets = u64::MAX;
|
||||
let mut buffer = Buffer::empty(Rect::new(0, 0, 56, 4));
|
||||
traffic(&stats, 56).render(buffer.area, &mut buffer);
|
||||
assert!(text(&buffer).contains("18446744073709551615 18446744073709551615"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_terminal_keeps_content_left_aligned_and_within_120_columns() {
|
||||
let state = state();
|
||||
let stats = statistics(&state);
|
||||
let mut terminal = Terminal::new(TestBackend::new(220, 40)).unwrap();
|
||||
let mut scroll = DetailScroll::default();
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &stats, &mut scroll))
|
||||
.unwrap();
|
||||
let wide = terminal.backend().buffer().clone();
|
||||
terminal.backend_mut().resize(120, 40);
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &stats, &mut scroll))
|
||||
.unwrap();
|
||||
for y in 0..40 {
|
||||
for x in 0..220 {
|
||||
if x < 120 {
|
||||
assert_eq!(wide[(x, y)], terminal.backend().buffer()[(x, y)]);
|
||||
} else {
|
||||
assert_eq!(wide[(x, y)].symbol(), " ");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routes_use_at_most_three_columns_and_keep_every_entry() {
|
||||
let list = TunnelList {
|
||||
items: (1..=7).map(|n| format!("10.0.{n}.0/24")).collect(),
|
||||
total_count: 7,
|
||||
truncated: false,
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
routes(&mut lines, "Included", &list, 220);
|
||||
let mut buffer = Buffer::empty(Rect::new(0, 0, 220, 4));
|
||||
paragraph(lines).render(buffer.area, &mut buffer);
|
||||
let rendered = text(&buffer);
|
||||
let route_rows: Vec<_> = rendered.lines().skip(1).collect();
|
||||
assert_eq!(route_rows.len(), 3);
|
||||
for line in route_rows {
|
||||
assert!(line.split_whitespace().count() <= 3);
|
||||
}
|
||||
for entry in &list.items {
|
||||
assert!(rendered.contains(entry));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_layout_stacks_sections_without_losing_routes() {
|
||||
let state = state();
|
||||
for width in [24, 60, 87] {
|
||||
let text = text(&details(&state, &statistics(&state), width));
|
||||
assert!(text.lines().any(|line| line == "TUNNEL"));
|
||||
assert!(text.lines().any(|line| line == "DNS"));
|
||||
assert!(text.contains("2001:db8:1234:5678::/64"));
|
||||
assert!(text.contains("192.168.0.0/16"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrolling_reaches_last_route_and_resize_clamps_offset_with_summary_pinned() {
|
||||
let state = state();
|
||||
let statistics = statistics(&state);
|
||||
let mut terminal = Terminal::new(TestBackend::new(60, 14)).unwrap();
|
||||
let mut scroll = DetailScroll::default();
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &statistics, &mut scroll))
|
||||
.unwrap();
|
||||
assert!(scroll.can_scroll());
|
||||
scroll.handle_key(KeyCode::End);
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &statistics, &mut scroll))
|
||||
.unwrap();
|
||||
let rendered = text(terminal.backend().buffer());
|
||||
assert!(rendered.contains("Connected"));
|
||||
assert!(rendered.contains("vpn.example.com"));
|
||||
assert!(rendered.contains("192.168.0.0/16"));
|
||||
terminal.backend_mut().resize(100, 50);
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &statistics, &mut scroll))
|
||||
.unwrap();
|
||||
assert!(!scroll.can_scroll());
|
||||
assert_eq!(scroll.offset, 0);
|
||||
assert!(text(terminal.backend().buffer()).contains("TRAFFIC · live"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn very_short_body_keeps_status_and_scrollable_details_visible() {
|
||||
let state = state();
|
||||
for (width, height) in [(60, 6), (24, 3)] {
|
||||
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
|
||||
let mut scroll = DetailScroll::default();
|
||||
let stats = statistics(&state);
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &stats, &mut scroll))
|
||||
.unwrap();
|
||||
assert!(text(terminal.backend().buffer()).contains("Connected"));
|
||||
assert!(text(terminal.backend().buffer()).contains("TRAFFIC"));
|
||||
scroll.handle_key(KeyCode::End);
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &stats, &mut scroll))
|
||||
.unwrap();
|
||||
assert!(text(terminal.backend().buffer()).contains("192.168.0.0/16"));
|
||||
scroll.handle_key(KeyCode::PageUp);
|
||||
let page_up = scroll.offset;
|
||||
assert!(page_up < scroll.maximum);
|
||||
scroll.handle_key(KeyCode::Up);
|
||||
assert!(scroll.offset < page_up);
|
||||
scroll.handle_key(KeyCode::Down);
|
||||
assert_eq!(scroll.offset, page_up);
|
||||
scroll.handle_key(KeyCode::PageDown);
|
||||
assert_eq!(scroll.offset, scroll.maximum);
|
||||
scroll.handle_key(KeyCode::Home);
|
||||
assert_eq!(scroll.offset, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_and_missing_configuration_remain_explicit() {
|
||||
let mut state = state();
|
||||
let mut statistics = statistics(&state);
|
||||
let TunnelStatisticsSnapshot::Available(view) = &mut statistics else {
|
||||
unreachable!()
|
||||
};
|
||||
view.state = TunnelStatisticsState::Stale;
|
||||
view.sample_age_ms = Some(12_000);
|
||||
state.configuration = None;
|
||||
let rendered = text(&details(&state, &statistics, 100));
|
||||
assert!(rendered.contains("TRAFFIC · stale"));
|
||||
assert!(rendered.contains("12 seconds"));
|
||||
assert!(rendered.contains("unavailable"));
|
||||
assert!(rendered.contains("1.2 MiB"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn units_and_long_sessions_are_explicit() {
|
||||
assert_eq!(bytes(1024), "1.0 KiB");
|
||||
assert_eq!(bytes(0), "0 B");
|
||||
assert_eq!(uptime(90_061_000), "25:01:01");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
//! Optional foreground presentation. Connection ownership stays with ConnectHandler.
|
||||
mod layout;
|
||||
mod notice;
|
||||
mod output;
|
||||
mod restoration;
|
||||
mod screen;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
io::IsTerminal,
|
||||
os::fd::AsRawFd,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc,
|
||||
},
|
||||
thread::JoinHandle,
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::log_format::LogFormat;
|
||||
use nix::unistd::{getpgrp, tcgetpgrp};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(crate) use notice::{NoticeLogger, session_notice};
|
||||
use output::OutputRouting;
|
||||
|
||||
pub(crate) type InternalMembers = Arc<Mutex<std::collections::BTreeMap<String, String>>>;
|
||||
|
||||
pub(crate) fn validate(format: LogFormat) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
format == LogFormat::Text,
|
||||
"--dashboard conflicts with --log-format json"
|
||||
);
|
||||
ensure!(
|
||||
std::env::var_os("TERM").is_some_and(|term| term != "dumb"),
|
||||
"--dashboard requires a capable terminal (TERM must not be dumb)"
|
||||
);
|
||||
let tty = terminal()?;
|
||||
ensure!(
|
||||
std::io::stderr().is_terminal(),
|
||||
"--dashboard requires stderr attached to the controlling terminal"
|
||||
);
|
||||
let stderr = output::duplicate(2)?;
|
||||
ensure!(
|
||||
same_terminal(&stderr, &tty),
|
||||
"--dashboard requires stderr attached to the controlling terminal"
|
||||
);
|
||||
ensure!(
|
||||
tcgetpgrp(&tty)? == getpgrp(),
|
||||
"--dashboard requires a foreground terminal"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn terminal() -> anyhow::Result<File> {
|
||||
OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open("/dev/tty")
|
||||
.context("--dashboard requires a controlling terminal")
|
||||
}
|
||||
|
||||
fn same_terminal(first: &File, second: &File) -> bool {
|
||||
// /dev/tty is a multiplexor node, so its st_rdev differs from the underlying
|
||||
// PTY. A session has one controlling terminal; compare terminal session IDs.
|
||||
let first_session = unsafe { nix::libc::tcgetsid(first.as_raw_fd()) };
|
||||
let second_session = unsafe { nix::libc::tcgetsid(second.as_raw_fd()) };
|
||||
first_session >= 0 && first_session == second_session
|
||||
}
|
||||
|
||||
pub(super) enum Content {
|
||||
Tunnel(Arc<gptunnel::TunnelMonitor>),
|
||||
Internal(InternalMembers),
|
||||
}
|
||||
|
||||
pub(super) enum Command {
|
||||
Suspend,
|
||||
Resume,
|
||||
}
|
||||
|
||||
pub(crate) struct Dashboard {
|
||||
routing: OutputRouting,
|
||||
server: String,
|
||||
cancellation: CancellationToken,
|
||||
stop: Arc<AtomicBool>,
|
||||
worker: Option<JoinHandle<()>>,
|
||||
signals: Vec<tokio::task::JoinHandle<()>>,
|
||||
error: Arc<Mutex<Option<String>>>,
|
||||
}
|
||||
|
||||
impl Dashboard {
|
||||
/// Install before native startup so persistent children inherit captured descriptors.
|
||||
pub(crate) fn prepare(server: String, cancellation: CancellationToken) -> anyhow::Result<Self> {
|
||||
let capture_stdout =
|
||||
std::io::stdout().is_terminal() && same_terminal(&output::duplicate(1)?, &output::duplicate(2)?);
|
||||
Ok(Self {
|
||||
routing: OutputRouting::install(capture_stdout, cancellation.clone())?,
|
||||
server,
|
||||
cancellation,
|
||||
stop: Arc::default(),
|
||||
worker: None,
|
||||
signals: Vec::new(),
|
||||
error: Arc::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn start_tunnel(&mut self, monitor: Arc<gptunnel::TunnelMonitor>) -> anyhow::Result<()> {
|
||||
self.start(Content::Tunnel(monitor.clone()))?;
|
||||
monitor.set_statistics_enabled(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn start_internal(&mut self, members: InternalMembers) -> anyhow::Result<()> {
|
||||
self.start(Content::Internal(members))
|
||||
}
|
||||
|
||||
fn start(&mut self, content: Content) -> anyhow::Result<()> {
|
||||
ensure!(self.worker.is_none(), "Dashboard already started");
|
||||
let (commands, receiver) = mpsc::channel();
|
||||
for (kind, command) in [
|
||||
(
|
||||
tokio::signal::unix::SignalKind::from_raw(nix::libc::SIGTSTP),
|
||||
Command::Suspend,
|
||||
),
|
||||
(
|
||||
tokio::signal::unix::SignalKind::from_raw(nix::libc::SIGCONT),
|
||||
Command::Resume,
|
||||
),
|
||||
] {
|
||||
let mut signal = tokio::signal::unix::signal(kind)?;
|
||||
let commands = commands.clone();
|
||||
self.signals.push(tokio::spawn(async move {
|
||||
while signal.recv().await.is_some() {
|
||||
let command = match command {
|
||||
Command::Suspend => Command::Suspend,
|
||||
Command::Resume => Command::Resume,
|
||||
};
|
||||
if commands.send(command).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
let mut hangup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())?;
|
||||
let cancellation = self.cancellation.clone();
|
||||
self.signals.push(tokio::spawn(async move {
|
||||
if hangup.recv().await.is_some() {
|
||||
cancellation.cancel();
|
||||
}
|
||||
}));
|
||||
let (ready, started) = mpsc::sync_channel(1);
|
||||
let context = screen::Context {
|
||||
terminal: terminal()?,
|
||||
output: self.routing.original_error.clone(),
|
||||
saved_stdout: self.routing.saved_output(),
|
||||
saved_stdin_flags: self.routing.saved_input_flags(),
|
||||
history: self.routing.history(),
|
||||
passthrough: self.routing.passthrough(),
|
||||
gate: self.routing.gate(),
|
||||
stop: self.stop.clone(),
|
||||
cancellation: self.cancellation.clone(),
|
||||
notice: notice::slot(),
|
||||
server: self.server.clone(),
|
||||
content,
|
||||
commands: receiver,
|
||||
};
|
||||
let error = self.error.clone();
|
||||
let cancellation = self.cancellation.clone();
|
||||
self.worker = Some(std::thread::Builder::new().name("dashboard".into()).spawn(move || {
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| screen::run(context, ready)));
|
||||
let failure = match result {
|
||||
Ok(Ok(())) => None,
|
||||
Ok(Err(failure)) => Some(format!("{failure:#}")),
|
||||
Err(_) => Some("Dashboard renderer panicked".into()),
|
||||
};
|
||||
if let Some(failure) = failure {
|
||||
*error.lock().unwrap_or_else(|error| error.into_inner()) = Some(failure);
|
||||
cancellation.cancel();
|
||||
}
|
||||
})?);
|
||||
started.recv().context("Dashboard stopped during initialization")??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Called after native shutdown and network cleanup, while capture still drains.
|
||||
pub(crate) fn finish(&mut self) -> anyhow::Result<()> {
|
||||
self.stop.store(true, Ordering::Release);
|
||||
if let Some(worker) = self.worker.take() {
|
||||
let _ = worker.join();
|
||||
}
|
||||
for signal in self.signals.drain(..) {
|
||||
signal.abort();
|
||||
}
|
||||
self.routing.restore();
|
||||
if let Some(error) = self.routing.take_error() {
|
||||
anyhow::bail!("Dashboard failed: {error}");
|
||||
}
|
||||
if let Some(error) = self.error.lock().unwrap_or_else(|error| error.into_inner()).take() {
|
||||
anyhow::bail!("Dashboard failed: {error}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dashboard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.finish();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use log::{Level, Log};
|
||||
|
||||
use super::output::plain_text;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Notice {
|
||||
pub(super) level: Level,
|
||||
pub(super) message: String,
|
||||
}
|
||||
|
||||
pub(super) type NoticeSlot = Arc<Mutex<Option<Notice>>>;
|
||||
static NOTICES: OnceLock<NoticeSlot> = OnceLock::new();
|
||||
|
||||
pub(super) fn slot() -> NoticeSlot {
|
||||
NOTICES.get_or_init(Arc::default).clone()
|
||||
}
|
||||
|
||||
pub(crate) fn session_notice(level: Level, message: &str) {
|
||||
if let Some(slot) = NOTICES.get() {
|
||||
let mut end = message.len().min(8192);
|
||||
while !message.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
*slot.lock().unwrap_or_else(|error| error.into_inner()) = Some(Notice {
|
||||
level,
|
||||
message: plain_text(message[..end].as_bytes()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata goes to the notice slot; descriptor capture owns the sole history entry.
|
||||
pub(crate) struct NoticeLogger {
|
||||
inner: env_logger::Logger,
|
||||
}
|
||||
|
||||
impl NoticeLogger {
|
||||
pub(crate) fn new(inner: env_logger::Logger) -> Self {
|
||||
let _ = slot();
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl Log for NoticeLogger {
|
||||
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
|
||||
self.inner.enabled(metadata)
|
||||
}
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
if self.inner.matches(record) {
|
||||
if record.level() <= Level::Warn {
|
||||
session_notice(record.level(), &record.args().to_string());
|
||||
}
|
||||
self.inner.log(record);
|
||||
}
|
||||
}
|
||||
fn flush(&self) {
|
||||
self.inner.flush();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn notice_tap_honors_message_filters_and_keeps_warning_severity() {
|
||||
let logger = NoticeLogger::new(
|
||||
env_logger::Builder::new()
|
||||
.parse_filters("warn/allowed")
|
||||
.target(env_logger::Target::Pipe(Box::new(std::io::sink())))
|
||||
.build(),
|
||||
);
|
||||
session_notice(Level::Info, "previous event");
|
||||
logger.log(
|
||||
&log::Record::builder()
|
||||
.level(Level::Warn)
|
||||
.args(format_args!("filtered warning"))
|
||||
.build(),
|
||||
);
|
||||
assert_eq!(slot().lock().unwrap().as_ref().unwrap().message, "previous event");
|
||||
logger.log(
|
||||
&log::Record::builder()
|
||||
.level(Level::Warn)
|
||||
.args(format_args!("allowed warning"))
|
||||
.build(),
|
||||
);
|
||||
let current = slot();
|
||||
let notice = current.lock().unwrap();
|
||||
assert_eq!(notice.as_ref().unwrap().level, Level::Warn);
|
||||
assert_eq!(notice.as_ref().unwrap().message, "allowed warning");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
//! Own terminal output while the native worker and its children are running.
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
fs::File,
|
||||
io::{self, Read, Write},
|
||||
os::fd::{AsFd, FromRawFd},
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
thread::{self, JoinHandle},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, FdFlag, OFlag, fcntl},
|
||||
poll::{PollFd, PollFlags, poll},
|
||||
unistd::{dup2_stderr, dup2_stdout},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const MAX_LINES: usize = 2_000;
|
||||
const MAX_BYTES: usize = 1_048_576;
|
||||
const MAX_LINE_BYTES: usize = 8_192;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct History {
|
||||
lines: VecDeque<String>,
|
||||
bytes: usize,
|
||||
discarded: u64,
|
||||
partial: [String; 2],
|
||||
}
|
||||
|
||||
impl History {
|
||||
fn push(&mut self, line: String) {
|
||||
self.bytes += line.len();
|
||||
self.lines.push_back(line);
|
||||
while self.lines.len() > MAX_LINES || self.bytes > MAX_BYTES {
|
||||
if let Some(line) = self.lines.pop_front() {
|
||||
self.bytes -= line.len();
|
||||
self.discarded = self.discarded.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn tail(&self, count: usize) -> Vec<String> {
|
||||
if count == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut lines = Vec::new();
|
||||
if self.discarded > 0 {
|
||||
lines.push(format!("[{} older log lines discarded]", self.discarded));
|
||||
}
|
||||
let partial_count = self.partial.iter().filter(|line| !line.is_empty()).count();
|
||||
let retained_count = count.saturating_sub(lines.len() + partial_count);
|
||||
lines.extend(
|
||||
self
|
||||
.lines
|
||||
.iter()
|
||||
.skip(self.lines.len().saturating_sub(retained_count))
|
||||
.cloned(),
|
||||
);
|
||||
lines.extend(self.partial.iter().filter(|line| !line.is_empty()).cloned());
|
||||
lines.truncate(count);
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn plain_text(bytes: &[u8]) -> String {
|
||||
String::from_utf8_lossy(&strip_ansi_escapes::strip(bytes))
|
||||
.chars()
|
||||
.filter(|ch| !ch.is_control() || *ch == '\t')
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct LineDecoder {
|
||||
bytes: Vec<u8>,
|
||||
truncated: bool,
|
||||
stream: usize,
|
||||
}
|
||||
|
||||
impl LineDecoder {
|
||||
fn new(stream: usize) -> Self {
|
||||
Self {
|
||||
bytes: Vec::new(),
|
||||
truncated: false,
|
||||
stream,
|
||||
}
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
let suffix = if self.truncated { " [line truncated]" } else { "" };
|
||||
format!("{}{suffix}", plain_text(&self.bytes))
|
||||
}
|
||||
|
||||
fn ingest(&mut self, bytes: &[u8], history: &mut History) {
|
||||
for byte in bytes {
|
||||
if *byte == b'\n' {
|
||||
history.push(self.text());
|
||||
self.bytes.clear();
|
||||
self.truncated = false;
|
||||
} else if self.bytes.len() < MAX_LINE_BYTES {
|
||||
self.bytes.push(*byte);
|
||||
} else {
|
||||
self.truncated = true;
|
||||
}
|
||||
}
|
||||
history.partial[self.stream] = if self.bytes.is_empty() && !self.truncated {
|
||||
String::new()
|
||||
} else {
|
||||
self.text()
|
||||
};
|
||||
}
|
||||
|
||||
fn finish(&mut self, history: &mut History) {
|
||||
if !self.bytes.is_empty() || self.truncated {
|
||||
history.push(self.text());
|
||||
}
|
||||
history.partial[self.stream].clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// The duplicate is close-on-exec: helpers inherit the capture pipe, never the renderer.
|
||||
pub(super) fn duplicate(fd: i32) -> io::Result<File> {
|
||||
let duplicate = unsafe { nix::libc::fcntl(fd, nix::libc::F_DUPFD_CLOEXEC, 3) };
|
||||
if duplicate < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(unsafe { File::from_raw_fd(duplicate) })
|
||||
}
|
||||
|
||||
pub(super) struct OutputRouting {
|
||||
pub(super) original_error: Arc<File>,
|
||||
original_input_flags: FdFlag,
|
||||
original_output: Option<Arc<File>>,
|
||||
history: Arc<Mutex<History>>,
|
||||
passthrough: Arc<AtomicBool>,
|
||||
stop: Arc<AtomicBool>,
|
||||
readers: Vec<JoinHandle<()>>,
|
||||
gate: Arc<Mutex<()>>,
|
||||
error: Arc<Mutex<Option<String>>>,
|
||||
restored: bool,
|
||||
}
|
||||
|
||||
impl OutputRouting {
|
||||
pub(super) fn install(capture_stdout: bool, cancellation: CancellationToken) -> anyhow::Result<Self> {
|
||||
io::stdout().flush()?;
|
||||
io::stderr().flush()?;
|
||||
unsafe {
|
||||
nix::libc::fflush(std::ptr::null_mut());
|
||||
}
|
||||
let mut routing = Self {
|
||||
original_error: Arc::new(duplicate(2)?),
|
||||
original_input_flags: FdFlag::from_bits_truncate(fcntl(io::stdin(), FcntlArg::F_GETFD)?),
|
||||
original_output: capture_stdout.then(|| duplicate(1).map(Arc::new)).transpose()?,
|
||||
history: Arc::default(),
|
||||
passthrough: Arc::new(AtomicBool::new(true)),
|
||||
stop: Arc::default(),
|
||||
readers: Vec::new(),
|
||||
gate: Arc::default(),
|
||||
error: Arc::default(),
|
||||
restored: false,
|
||||
};
|
||||
routing.capture(1, routing.original_error.clone(), cancellation.clone())?;
|
||||
if let Some(original) = routing.original_output.clone() {
|
||||
routing.capture(0, original, cancellation)?;
|
||||
}
|
||||
// Authentication may have initialized Crossterm's global reader with fd 0.
|
||||
// Keep that descriptor stable, but do not let executed helpers inherit it.
|
||||
// Script-TUN packet I/O continues through its separate VPNFD socket.
|
||||
fcntl(
|
||||
io::stdin(),
|
||||
FcntlArg::F_SETFD(routing.original_input_flags | FdFlag::FD_CLOEXEC),
|
||||
)?;
|
||||
Ok(routing)
|
||||
}
|
||||
|
||||
fn capture(&mut self, stream: usize, destination: Arc<File>, cancellation: CancellationToken) -> anyhow::Result<()> {
|
||||
let (reader, writer) = io::pipe()?;
|
||||
// Polling plus nonblocking reads lets teardown bound inherited pipe lifetimes.
|
||||
fcntl(&reader, FcntlArg::F_SETFL(OFlag::O_NONBLOCK))?;
|
||||
let history = self.history.clone();
|
||||
let passthrough = self.passthrough.clone();
|
||||
let stop = self.stop.clone();
|
||||
let gate = self.gate.clone();
|
||||
let error = self.error.clone();
|
||||
let thread = thread::Builder::new()
|
||||
.name(format!("dashboard-output-{stream}"))
|
||||
.spawn(move || {
|
||||
let mut reader = reader;
|
||||
let mut decoder = LineDecoder::new(stream);
|
||||
let mut buffer = [0; 4096];
|
||||
let mut deadline = None;
|
||||
loop {
|
||||
if stop.load(Ordering::Acquire) && deadline.is_none() {
|
||||
deadline = Some(Instant::now() + Duration::from_millis(250));
|
||||
}
|
||||
if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
|
||||
break;
|
||||
}
|
||||
let mut descriptors = [PollFd::new(reader.as_fd(), PollFlags::POLLIN)];
|
||||
match poll(&mut descriptors, 50u16) {
|
||||
Ok(0) => {
|
||||
if deadline.is_some() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(nix::errno::Errno::EINTR) => continue,
|
||||
Err(failure) => {
|
||||
*error.lock().unwrap_or_else(|error| error.into_inner()) =
|
||||
Some(format!("Cannot poll dashboard output: {failure}"));
|
||||
cancellation.cancel();
|
||||
break;
|
||||
}
|
||||
}
|
||||
match reader.read(&mut buffer) {
|
||||
Ok(0) => break,
|
||||
Ok(length) => {
|
||||
{
|
||||
let _gate = gate.lock().unwrap_or_else(|error| error.into_inner());
|
||||
if passthrough.load(Ordering::Acquire) {
|
||||
if let Err(failure) = (&*destination).write_all(&buffer[..length]) {
|
||||
*error.lock().unwrap_or_else(|error| error.into_inner()) =
|
||||
Some(format!("Cannot forward dashboard output: {failure}"));
|
||||
cancellation.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
decoder.ingest(
|
||||
&buffer[..length],
|
||||
&mut history.lock().unwrap_or_else(|error| error.into_inner()),
|
||||
);
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => continue,
|
||||
Err(failure) => {
|
||||
*error.lock().unwrap_or_else(|error| error.into_inner()) =
|
||||
Some(format!("Cannot read dashboard output: {failure}"));
|
||||
cancellation.cancel();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
decoder.finish(&mut history.lock().unwrap_or_else(|error| error.into_inner()));
|
||||
})
|
||||
.context("Cannot start dashboard output reader")?;
|
||||
self.readers.push(thread);
|
||||
if stream == 0 {
|
||||
dup2_stdout(&writer)?;
|
||||
} else {
|
||||
dup2_stderr(&writer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn history(&self) -> Arc<Mutex<History>> {
|
||||
self.history.clone()
|
||||
}
|
||||
pub(super) fn passthrough(&self) -> Arc<AtomicBool> {
|
||||
self.passthrough.clone()
|
||||
}
|
||||
pub(super) fn gate(&self) -> Arc<Mutex<()>> {
|
||||
self.gate.clone()
|
||||
}
|
||||
pub(super) fn saved_output(&self) -> Option<Arc<File>> {
|
||||
self.original_output.clone()
|
||||
}
|
||||
pub(super) fn saved_input_flags(&self) -> FdFlag {
|
||||
self.original_input_flags
|
||||
}
|
||||
pub(super) fn take_error(&self) -> Option<String> {
|
||||
self.error.lock().unwrap_or_else(|error| error.into_inner()).take()
|
||||
}
|
||||
|
||||
pub(super) fn restore(&mut self) {
|
||||
if self.restored {
|
||||
return;
|
||||
}
|
||||
let _ = io::stdout().flush();
|
||||
let _ = io::stderr().flush();
|
||||
unsafe {
|
||||
nix::libc::fflush(std::ptr::null_mut());
|
||||
}
|
||||
let _ = dup2_stderr(&*self.original_error);
|
||||
let _ = fcntl(io::stdin(), FcntlArg::F_SETFD(self.original_input_flags));
|
||||
if let Some(output) = &self.original_output {
|
||||
let _ = dup2_stdout(&**output);
|
||||
}
|
||||
self.stop.store(true, Ordering::Release);
|
||||
for reader in self.readers.drain(..) {
|
||||
let _ = reader.join();
|
||||
}
|
||||
self.restored = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OutputRouting {
|
||||
fn drop(&mut self) {
|
||||
self.restore();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn split_utf8_and_unterminated_lines_are_preserved_without_escape_commands() {
|
||||
for stream in [0, 1] {
|
||||
let mut history = History::default();
|
||||
let mut decoder = LineDecoder::new(stream);
|
||||
let bytes = "connected 日本語\x1b[2J\npartial".as_bytes();
|
||||
for byte in bytes {
|
||||
decoder.ingest(&[*byte], &mut history);
|
||||
}
|
||||
assert_eq!(history.tail(10), ["connected 日本語", "partial"]);
|
||||
decoder.finish(&mut history);
|
||||
assert_eq!(history.tail(10), ["connected 日本語", "partial"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_long_lines_and_history_are_bounded() {
|
||||
let mut history = History::default();
|
||||
let mut decoder = LineDecoder::new(0);
|
||||
decoder.ingest(&vec![b'x'; MAX_LINE_BYTES * 3], &mut history);
|
||||
decoder.ingest(b"\n", &mut history);
|
||||
assert!(history.lines[0].ends_with("[line truncated]"));
|
||||
for _ in 0..MAX_LINES + 10 {
|
||||
decoder.ingest(b"line\n", &mut history);
|
||||
}
|
||||
assert!(history.lines.len() <= MAX_LINES);
|
||||
assert!(history.bytes <= MAX_BYTES);
|
||||
assert!(history.tail(10)[0].contains("discarded"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Panic restoration must remain independent of renderer and output-ingestion locks.
|
||||
use std::{
|
||||
fs::File,
|
||||
io,
|
||||
os::fd::AsRawFd,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
pub(super) struct TerminalRestoration {
|
||||
terminal: File,
|
||||
error: Arc<File>,
|
||||
output: Option<Arc<File>>,
|
||||
input_flags: nix::fcntl::FdFlag,
|
||||
termios: nix::libc::termios,
|
||||
active: AtomicBool,
|
||||
}
|
||||
|
||||
impl TerminalRestoration {
|
||||
pub(super) fn install(
|
||||
terminal: File,
|
||||
error: Arc<File>,
|
||||
output: Option<Arc<File>>,
|
||||
input_flags: nix::fcntl::FdFlag,
|
||||
) -> io::Result<Arc<Self>> {
|
||||
let mut termios = std::mem::MaybeUninit::uninit();
|
||||
if unsafe { nix::libc::tcgetattr(terminal.as_raw_fd(), termios.as_mut_ptr()) } != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let restoration = Arc::new(Self {
|
||||
terminal,
|
||||
error,
|
||||
output,
|
||||
input_flags,
|
||||
termios: unsafe { termios.assume_init() },
|
||||
active: AtomicBool::new(false),
|
||||
});
|
||||
let previous = std::panic::take_hook();
|
||||
let panic_restoration = restoration.clone();
|
||||
std::panic::set_hook(Box::new(move |panic| {
|
||||
panic_restoration.restore();
|
||||
previous(panic);
|
||||
}));
|
||||
Ok(restoration)
|
||||
}
|
||||
|
||||
pub(super) fn arm(&self) {
|
||||
self.active.store(true, Ordering::Release);
|
||||
}
|
||||
pub(super) fn disarm(&self) {
|
||||
self.active.store(false, Ordering::Release);
|
||||
}
|
||||
|
||||
pub(super) fn restore(&self) {
|
||||
if !self.active.swap(false, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
unsafe {
|
||||
nix::libc::tcsetattr(self.terminal.as_raw_fd(), nix::libc::TCSANOW, &self.termios);
|
||||
let sequence = b"\x1b[?25h\x1b[?1049l";
|
||||
nix::libc::write(self.error.as_raw_fd(), sequence.as_ptr().cast(), sequence.len());
|
||||
nix::libc::dup2(self.error.as_raw_fd(), 2);
|
||||
nix::libc::fcntl(0, nix::libc::F_SETFD, self.input_flags.bits());
|
||||
if let Some(output) = &self.output {
|
||||
nix::libc::dup2(output.as_raw_fd(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
use std::{
|
||||
fs::File,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc,
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use anyhow::{Context as _, ensure};
|
||||
use crossterm::{
|
||||
cursor::Show,
|
||||
event::{self, Event, KeyCode, KeyEventKind, KeyModifiers},
|
||||
execute,
|
||||
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
|
||||
};
|
||||
use gpapi::session::tunnel::TunnelPhase;
|
||||
use log::Level;
|
||||
use nix::unistd::{getpgrp, tcgetpgrp};
|
||||
use ratatui::{
|
||||
Terminal,
|
||||
backend::CrosstermBackend,
|
||||
layout::{Constraint, Layout},
|
||||
style::{Color, Modifier, Style},
|
||||
text::Line,
|
||||
widgets::{Block, Borders, Paragraph, Wrap},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{
|
||||
Command, Content,
|
||||
layout::{DetailScroll, phase_label, render_tunnel, row},
|
||||
notice::{Notice, NoticeSlot},
|
||||
output::{History, plain_text},
|
||||
restoration::TerminalRestoration,
|
||||
};
|
||||
|
||||
pub(super) struct Context {
|
||||
pub(super) terminal: File,
|
||||
pub(super) output: Arc<File>,
|
||||
pub(super) saved_stdout: Option<Arc<File>>,
|
||||
pub(super) saved_stdin_flags: nix::fcntl::FdFlag,
|
||||
pub(super) history: Arc<Mutex<History>>,
|
||||
pub(super) passthrough: Arc<AtomicBool>,
|
||||
pub(super) gate: Arc<Mutex<()>>,
|
||||
pub(super) stop: Arc<AtomicBool>,
|
||||
pub(super) cancellation: CancellationToken,
|
||||
pub(super) notice: NoticeSlot,
|
||||
pub(super) server: String,
|
||||
pub(super) content: Content,
|
||||
pub(super) commands: mpsc::Receiver<Command>,
|
||||
}
|
||||
|
||||
struct Screen {
|
||||
terminal: Terminal<CrosstermBackend<File>>,
|
||||
restore: Arc<TerminalRestoration>,
|
||||
controlling_terminal: File,
|
||||
passthrough: Arc<AtomicBool>,
|
||||
gate: Arc<Mutex<()>>,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl Screen {
|
||||
fn new(context: &Context) -> anyhow::Result<Self> {
|
||||
let restore = TerminalRestoration::install(
|
||||
context.terminal.try_clone()?,
|
||||
context.output.clone(),
|
||||
context.saved_stdout.clone(),
|
||||
context.saved_stdin_flags,
|
||||
)?;
|
||||
let terminal = Terminal::new(CrosstermBackend::new(context.output.try_clone()?))?;
|
||||
let mut screen = Self {
|
||||
terminal,
|
||||
restore,
|
||||
controlling_terminal: context.terminal.try_clone()?,
|
||||
passthrough: context.passthrough.clone(),
|
||||
gate: context.gate.clone(),
|
||||
active: false,
|
||||
};
|
||||
screen.enter()?;
|
||||
Ok(screen)
|
||||
}
|
||||
|
||||
fn enter(&mut self) -> anyhow::Result<()> {
|
||||
if self.active {
|
||||
return Ok(());
|
||||
}
|
||||
ensure!(
|
||||
tcgetpgrp(&self.controlling_terminal)? == getpgrp(),
|
||||
"Dashboard is no longer in the foreground"
|
||||
);
|
||||
let _gate = self.gate.lock().unwrap_or_else(|error| error.into_inner());
|
||||
self.passthrough.store(false, Ordering::Release);
|
||||
// Arm before changing termios, including partial initialization failures.
|
||||
self.restore.arm();
|
||||
self.active = true;
|
||||
enable_raw_mode()?;
|
||||
execute!(self.terminal.backend_mut(), EnterAlternateScreen)?;
|
||||
// Terminal::clear queries cursor position through process stdout. Fullscreen
|
||||
// resize clears and resets buffers through our saved terminal backend only.
|
||||
self.terminal.resize(self.terminal.size()?.into())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn leave(&mut self) {
|
||||
if !self.active {
|
||||
return;
|
||||
}
|
||||
let _gate = self.gate.lock().unwrap_or_else(|error| error.into_inner());
|
||||
let _ = disable_raw_mode();
|
||||
let _ = execute!(self.terminal.backend_mut(), Show, LeaveAlternateScreen);
|
||||
self.restore.disarm();
|
||||
self.passthrough.store(true, Ordering::Release);
|
||||
self.active = false;
|
||||
}
|
||||
|
||||
fn suspend(&mut self) {
|
||||
self.leave();
|
||||
// SIGSTOP avoids recursion through our SIGTSTP listener. The shell resumes us.
|
||||
unsafe {
|
||||
nix::libc::raise(nix::libc::SIGSTOP);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Screen {
|
||||
fn drop(&mut self) {
|
||||
self.leave();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run(context: Context, ready: mpsc::SyncSender<anyhow::Result<()>>) -> anyhow::Result<()> {
|
||||
let screen = Screen::new(&context);
|
||||
let mut screen = match screen {
|
||||
Ok(screen) => {
|
||||
let _ = ready.send(Ok(()));
|
||||
screen
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = ready.send(Err(anyhow::anyhow!("{error:#}")));
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let mut logs = false;
|
||||
let mut scroll = DetailScroll::default();
|
||||
let mut next_draw = Instant::now();
|
||||
let mut dirty = true;
|
||||
while !context.stop.load(Ordering::Acquire) {
|
||||
for command in context.commands.try_iter() {
|
||||
match command {
|
||||
Command::Suspend => screen.suspend(),
|
||||
Command::Resume => {}
|
||||
}
|
||||
}
|
||||
if !screen.active {
|
||||
if tcgetpgrp(&context.terminal)? == getpgrp() {
|
||||
screen.enter()?;
|
||||
} else {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if dirty || Instant::now() >= next_draw {
|
||||
draw(&mut screen.terminal, &context, logs, &mut scroll)?;
|
||||
next_draw = Instant::now() + Duration::from_secs(1);
|
||||
dirty = false;
|
||||
}
|
||||
if event::poll(Duration::from_millis(100)).context("Cannot read dashboard input")? {
|
||||
if let Event::Key(key) = event::read()? {
|
||||
if key.kind != KeyEventKind::Press {
|
||||
continue;
|
||||
}
|
||||
match key.code {
|
||||
KeyCode::Tab | KeyCode::BackTab => {
|
||||
logs = !logs;
|
||||
dirty = true;
|
||||
}
|
||||
KeyCode::Up | KeyCode::Down | KeyCode::PageUp | KeyCode::PageDown | KeyCode::Home | KeyCode::End if !logs => {
|
||||
scroll.handle_key(key.code);
|
||||
dirty = true;
|
||||
}
|
||||
KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
context.cancellation.cancel();
|
||||
dirty = true;
|
||||
}
|
||||
KeyCode::Char('z') if key.modifiers.contains(KeyModifiers::CONTROL) => screen.suspend(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn draw(
|
||||
terminal: &mut Terminal<CrosstermBackend<File>>,
|
||||
context: &Context,
|
||||
logs: bool,
|
||||
scroll: &mut DetailScroll,
|
||||
) -> anyhow::Result<()> {
|
||||
terminal.draw(|frame| {
|
||||
let area = frame.area();
|
||||
if area.height < 8 || area.width < 24 {
|
||||
frame.render_widget(
|
||||
Paragraph::new("GP Connect\nCtrl+C Disconnect").wrap(Wrap { trim: false }),
|
||||
area,
|
||||
);
|
||||
return;
|
||||
}
|
||||
let compact = area.height < 18;
|
||||
let footer_height = if area.width < 80 { 2 } else { 1 };
|
||||
let [header, body, notice, footer] = Layout::vertical([
|
||||
Constraint::Length(2),
|
||||
Constraint::Min(1),
|
||||
Constraint::Length(if compact { 1 } else { 3 }),
|
||||
Constraint::Length(footer_height),
|
||||
])
|
||||
.areas(area);
|
||||
let view = if logs { "Live logs" } else { "Dashboard" };
|
||||
frame.render_widget(
|
||||
Paragraph::new(format!(" GP Connect · {view}"))
|
||||
.style(Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD))
|
||||
.block(Block::default().borders(Borders::BOTTOM)),
|
||||
header,
|
||||
);
|
||||
let mut lines = vec![row("Server", context.server.clone()), Line::default()];
|
||||
if logs {
|
||||
let history = context.history.lock().unwrap_or_else(|error| error.into_inner());
|
||||
let tail = history.tail(body.height as usize);
|
||||
lines = tail.into_iter().map(Line::raw).collect();
|
||||
let skip = lines.len().saturating_sub(body.height as usize);
|
||||
lines.drain(..skip);
|
||||
} else {
|
||||
match &context.content {
|
||||
Content::Tunnel(monitor) => {
|
||||
render_tunnel(
|
||||
frame,
|
||||
body,
|
||||
&context.server,
|
||||
&monitor.state(),
|
||||
&monitor.statistics(),
|
||||
scroll,
|
||||
);
|
||||
}
|
||||
Content::Internal(members) => {
|
||||
lines.push(row("Status", "Internal network session"));
|
||||
lines.push(Line::raw("Tunnel statistics unavailable (non-tunnel session)"));
|
||||
lines.push(Line::default());
|
||||
lines.extend(
|
||||
members
|
||||
.lock()
|
||||
.unwrap_or_else(|error| error.into_inner())
|
||||
.values()
|
||||
.map(|member| Line::raw(plain_text(member.as_bytes()))),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if logs || matches!(context.content, Content::Internal(_)) {
|
||||
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), body);
|
||||
}
|
||||
let current = context.notice.lock().unwrap_or_else(|error| error.into_inner()).clone();
|
||||
let current = match &context.content {
|
||||
Content::Tunnel(monitor) => {
|
||||
let state = monitor.state();
|
||||
Some(notice_for_status(current, state.phase, state.transport))
|
||||
}
|
||||
Content::Internal(_) => current,
|
||||
};
|
||||
if let Some(current) = current {
|
||||
let color = if current.level <= Level::Warn {
|
||||
Color::Yellow
|
||||
} else {
|
||||
Color::Gray
|
||||
};
|
||||
let block = if compact {
|
||||
Block::default()
|
||||
} else {
|
||||
Block::default().title("Latest event").borders(Borders::TOP)
|
||||
};
|
||||
frame.render_widget(
|
||||
Paragraph::new(current.message)
|
||||
.style(Style::default().fg(color))
|
||||
.wrap(Wrap { trim: false })
|
||||
.block(block),
|
||||
notice,
|
||||
);
|
||||
}
|
||||
let ending = if context.cancellation.is_cancelled() {
|
||||
"Disconnecting…"
|
||||
} else {
|
||||
"Ctrl+C Disconnect"
|
||||
};
|
||||
frame.render_widget(
|
||||
footer_text(logs, ending, scroll.can_scroll(), area.width).style(Style::default().fg(Color::DarkGray)),
|
||||
footer,
|
||||
);
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn footer_text(logs: bool, ending: &str, scrollable: bool, width: u16) -> Paragraph<'static> {
|
||||
let view = if logs { "Dashboard" } else { "Logs" };
|
||||
let scrolling = scrollable && !logs;
|
||||
let text = if width < 80 {
|
||||
format!("{ending}\nTab {view}{}", if scrolling { " ↑↓ Scroll" } else { "" })
|
||||
} else {
|
||||
format!(
|
||||
"Tab {view} {ending}{}",
|
||||
if scrolling { " ↑↓/PgUp/PgDn Scroll" } else { "" }
|
||||
)
|
||||
};
|
||||
Paragraph::new(text)
|
||||
}
|
||||
|
||||
fn notice_for_status(
|
||||
notice: Option<Notice>,
|
||||
phase: TunnelPhase,
|
||||
transport: gpapi::session::tunnel::TunnelTransport,
|
||||
) -> Notice {
|
||||
notice.unwrap_or_else(|| Notice {
|
||||
level: Level::Info,
|
||||
message: format!("{} · {}", phase_label(phase), transport.label()),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn narrow_footer_keeps_disconnect_switch_and_scroll_hints_visible() {
|
||||
use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
|
||||
let area = Rect::new(0, 0, 24, 2);
|
||||
let mut buffer = Buffer::empty(area);
|
||||
footer_text(false, "Ctrl+C Disconnect", true, area.width).render(area, &mut buffer);
|
||||
let lines: Vec<String> = (0..2)
|
||||
.map(|y| (0..24).map(|x| buffer[(x, y)].symbol()).collect())
|
||||
.collect();
|
||||
assert!(lines[0].contains("Ctrl+C Disconnect"));
|
||||
assert!(lines[1].contains("Tab Logs"));
|
||||
assert!(lines[1].contains("↑↓ Scroll"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_transitions_cannot_overwrite_an_existing_warning() {
|
||||
use gpapi::session::tunnel::TunnelTransport;
|
||||
let warning = Notice {
|
||||
level: Level::Warn,
|
||||
message: "ESP unavailable; using SSL".into(),
|
||||
};
|
||||
let first = notice_for_status(Some(warning), TunnelPhase::Connected, TunnelTransport::SslTls);
|
||||
let reconnecting = notice_for_status(Some(first), TunnelPhase::Reconnecting, TunnelTransport::Unavailable);
|
||||
let resumed = notice_for_status(Some(reconnecting), TunnelPhase::Connected, TunnelTransport::IpsecEsp);
|
||||
assert_eq!(resumed.level, Level::Warn);
|
||||
assert_eq!(resumed.message, "ESP unavailable; using SSL");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
//! Terminal integration runs in child test processes so descriptor/signal changes
|
||||
//! cannot capture another test's output or change its controlling terminal.
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{self, Read, Write},
|
||||
os::unix::process::CommandExt,
|
||||
process::{Child, Command, Stdio},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, OFlag, fcntl},
|
||||
pty::{Winsize, openpty},
|
||||
sys::signal::{Signal, kill},
|
||||
unistd::Pid,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
struct Fixture {
|
||||
child: Child,
|
||||
master: File,
|
||||
slave: File,
|
||||
output: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn start(piped: bool) -> Self {
|
||||
Self::start_mode(if piped { "piped" } else { "terminal" }, piped)
|
||||
}
|
||||
|
||||
fn start_mode(mode: &str, piped: bool) -> Self {
|
||||
let mut command = Command::new(std::env::current_exe().unwrap());
|
||||
command
|
||||
.args([
|
||||
"--exact",
|
||||
"dashboard::tests::terminal_fixture",
|
||||
"--ignored",
|
||||
"--nocapture",
|
||||
])
|
||||
.env("GPCLIENT_DASHBOARD_FIXTURE", mode);
|
||||
Self::spawn(command, piped)
|
||||
}
|
||||
|
||||
fn spawn(mut command: Command, piped: bool) -> Self {
|
||||
let pty = openpty(
|
||||
Some(&Winsize {
|
||||
ws_row: 40,
|
||||
ws_col: 100,
|
||||
ws_xpixel: 0,
|
||||
ws_ypixel: 0,
|
||||
}),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let master = File::from(pty.master);
|
||||
let slave = File::from(pty.slave);
|
||||
fcntl(&master, FcntlArg::F_SETFL(OFlag::O_NONBLOCK)).unwrap();
|
||||
command
|
||||
.env("TERM", "xterm-256color")
|
||||
.stdin(if piped {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::from(slave.try_clone().unwrap())
|
||||
})
|
||||
.stdout(if piped {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::from(slave.try_clone().unwrap())
|
||||
})
|
||||
.stderr(Stdio::from(slave.try_clone().unwrap()));
|
||||
unsafe {
|
||||
command.pre_exec(|| {
|
||||
if nix::libc::setsid() < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if nix::libc::ioctl(2, nix::libc::TIOCSCTTY as _, 0) < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let no_core = nix::libc::rlimit {
|
||||
rlim_cur: 0,
|
||||
rlim_max: 0,
|
||||
};
|
||||
nix::libc::setrlimit(nix::libc::RLIMIT_CORE, &no_core);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let mut child = command.spawn().unwrap();
|
||||
if piped {
|
||||
child.stdin.take().unwrap().write_all(b"fixture-cookie\n").unwrap();
|
||||
}
|
||||
Self {
|
||||
child,
|
||||
master,
|
||||
slave,
|
||||
output: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn drain(&mut self) {
|
||||
let mut bytes = [0; 8192];
|
||||
loop {
|
||||
match self.master.read(&mut bytes) {
|
||||
Ok(0) => break,
|
||||
Ok(length) => self.output.extend_from_slice(&bytes[..length]),
|
||||
Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
|
||||
Err(error) if error.raw_os_error() == Some(nix::libc::EIO) => break,
|
||||
Err(error) => panic!("PTY read: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_text(&mut self, text: &str) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
self.drain();
|
||||
let plain = strip_ansi_escapes::strip(&self.output);
|
||||
if String::from_utf8_lossy(&plain).contains(text) {
|
||||
return;
|
||||
}
|
||||
if let Some(status) = self.child.try_wait().unwrap() {
|
||||
panic!(
|
||||
"Fixture exited {status} before {text:?}: {}",
|
||||
String::from_utf8_lossy(&self.output)
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"Missing {text:?}: {}",
|
||||
String::from_utf8_lossy(&self.output)
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&mut self) {
|
||||
self.wait_text("DASHBOARD_RESTORED");
|
||||
let attrs = nix::sys::termios::tcgetattr(&self.slave).unwrap();
|
||||
assert!(attrs.local_flags.contains(nix::sys::termios::LocalFlags::ICANON));
|
||||
assert!(attrs.local_flags.contains(nix::sys::termios::LocalFlags::ECHO));
|
||||
self.master.write_all(b"\n").unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
self.drain();
|
||||
if let Some(status) = self.child.try_wait().unwrap() {
|
||||
assert!(
|
||||
status.success(),
|
||||
"Fixture failed {status}: {}",
|
||||
String::from_utf8_lossy(&self.output)
|
||||
);
|
||||
self.drain();
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "Fixture did not restore/exit");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert!(String::from_utf8_lossy(&self.output).contains("DASHBOARD_RESTORED"));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// A failed assertion must not leave a suspended child or its helper alive.
|
||||
let _ = kill(Pid::from_raw(self.child.id() as i32), Signal::SIGCONT);
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_switches_to_captured_child_logs_and_ctrl_c_restores_terminal() {
|
||||
let mut fixture = Fixture::start(false);
|
||||
fixture.wait_text("Internal");
|
||||
fixture.master.write_all(b"\t").unwrap();
|
||||
fixture.wait_text("Live logs");
|
||||
fixture.wait_text("child-stderr-after-entry");
|
||||
fixture.master.write_all(b"\x03").unwrap();
|
||||
fixture.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warning_before_first_tunnel_frame_remains_visible() {
|
||||
let mut fixture = Fixture::start_mode("tunnel", false);
|
||||
fixture.wait_text("initial-fallback-warning");
|
||||
fixture.master.write_all(b"\x03").unwrap();
|
||||
fixture.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connected_tunnel_samples_statistics_and_accepts_ctrl_c() {
|
||||
let mut fixture = Fixture::start_mode("active-tunnel", false);
|
||||
fixture.wait_text("IPsec");
|
||||
fixture.wait_text("(ESP)");
|
||||
fixture.wait_text("Received");
|
||||
fixture.wait_text("4.0");
|
||||
fixture.master.write_all(b"\x03").unwrap();
|
||||
fixture.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authenticated_terminal_input_remains_usable_after_dashboard_entry() {
|
||||
let mut fixture = Fixture::start_mode("prompted-tunnel", false);
|
||||
fixture.wait_text("Received");
|
||||
fixture.master.write_all(b"\t").unwrap();
|
||||
fixture.wait_text("Live logs");
|
||||
fixture.master.write_all(b"\x03").unwrap();
|
||||
fixture.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn piped_credentials_and_stdout_redirection_preserve_their_streams() {
|
||||
let mut fixture = Fixture::start(true);
|
||||
fixture.wait_text("Internal");
|
||||
fixture.master.write_all(b"\x03").unwrap();
|
||||
fixture.finish();
|
||||
let mut output = String::new();
|
||||
fixture
|
||||
.child
|
||||
.stdout
|
||||
.take()
|
||||
.unwrap()
|
||||
.read_to_string(&mut output)
|
||||
.unwrap();
|
||||
assert!(output.contains("redirected-stdout"));
|
||||
assert!(!output.contains('\x1b'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_termination_and_suspend_resume_restore_terminal() {
|
||||
let mut fixture = Fixture::start(false);
|
||||
fixture.wait_text("Internal");
|
||||
kill(Pid::from_raw(fixture.child.id() as i32), Signal::SIGTSTP).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let attrs = nix::sys::termios::tcgetattr(&fixture.slave).unwrap();
|
||||
if attrs.local_flags.contains(nix::sys::termios::LocalFlags::ICANON) {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "suspend did not restore termios");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
kill(Pid::from_raw(fixture.child.id() as i32), Signal::SIGCONT).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
kill(Pid::from_raw(fixture.child.id() as i32), Signal::SIGTERM).unwrap();
|
||||
fixture.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_panic_hook_restores_terminal_with_panic_abort() {
|
||||
let dependencies = std::env::current_exe().unwrap().parent().unwrap().to_path_buf();
|
||||
let nix = std::fs::read_dir(&dependencies)
|
||||
.unwrap()
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.find(|path| {
|
||||
path.file_name().unwrap().to_string_lossy().starts_with("libnix-")
|
||||
&& path.extension().is_some_and(|ext| ext == "rlib")
|
||||
})
|
||||
.expect("compiled nix rlib");
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let binary = directory.path().join("dashboard-abort");
|
||||
let build = Command::new("rustc")
|
||||
.args(["--edition=2024", "-C", "panic=abort", "-A", "dead_code"])
|
||||
.arg(format!(
|
||||
"{}/tests/fixtures/dashboard_abort.rs",
|
||||
env!("CARGO_MANIFEST_DIR")
|
||||
))
|
||||
.arg("--extern")
|
||||
.arg(format!("nix={}", nix.display()))
|
||||
.arg("-L")
|
||||
.arg(format!("dependency={}", dependencies.display()))
|
||||
.arg("-o")
|
||||
.arg(&binary)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
build.status.success(),
|
||||
"Abort fixture compilation failed: {}",
|
||||
String::from_utf8_lossy(&build.stderr)
|
||||
);
|
||||
let mut fixture = Fixture::spawn(Command::new(binary), false);
|
||||
fixture.wait_text("ABORT_FIXTURE_READY");
|
||||
fixture.master.write_all(b"x").unwrap();
|
||||
fixture.wait_text("ABORT_HOOK_RESTORED");
|
||||
let attrs = nix::sys::termios::tcgetattr(&fixture.slave).unwrap();
|
||||
assert!(attrs.local_flags.contains(nix::sys::termios::LocalFlags::ICANON));
|
||||
assert!(attrs.local_flags.contains(nix::sys::termios::LocalFlags::ECHO));
|
||||
fixture.master.write_all(b"\n").unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
fixture.drain();
|
||||
if let Some(status) = fixture.child.try_wait().unwrap() {
|
||||
assert!(!status.success(), "panic=abort fixture unexpectedly succeeded");
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "abort fixture did not exit");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
fixture.drain();
|
||||
assert!(String::from_utf8_lossy(&fixture.output).contains("intentional abort-hook fixture panic"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "runs in an isolated PTY subprocess"]
|
||||
fn terminal_fixture() {
|
||||
let mode = std::env::var("GPCLIENT_DASHBOARD_FIXTURE").expect("subprocess fixture only");
|
||||
if mode == "active-tunnel" || mode == "prompted-tunnel" {
|
||||
env_logger::builder()
|
||||
.filter_level(log::LevelFilter::Info)
|
||||
.try_init()
|
||||
.unwrap();
|
||||
}
|
||||
if mode == "piped" {
|
||||
let mut credentials = String::new();
|
||||
std::io::stdin().read_to_string(&mut credentials).unwrap();
|
||||
assert_eq!(credentials, "fixture-cookie\n");
|
||||
}
|
||||
validate(LogFormat::Text).unwrap();
|
||||
if mode == "prompted-tunnel" {
|
||||
// Authentication prompts use Crossterm before dashboard output routing.
|
||||
// Exercise its real global reader initialization while stdin is the TTY.
|
||||
let _ = crossterm::event::poll(Duration::from_millis(1)).unwrap();
|
||||
}
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
runtime.block_on(async {
|
||||
let cancellation = CancellationToken::new();
|
||||
let signal_cancel = cancellation.clone();
|
||||
let signals = tokio::spawn(async move {
|
||||
gpapi::utils::shutdown_signal().await;
|
||||
signal_cancel.cancel();
|
||||
});
|
||||
let input_flags = fcntl(std::io::stdin(), FcntlArg::F_GETFD).unwrap();
|
||||
let mut dashboard = Dashboard::prepare("vpn.example.com".into(), cancellation.clone()).unwrap();
|
||||
eprintln!("child-stderr-before-entry");
|
||||
// Native VPN helpers exec /bin/sh without Rust's standard-fd repair.
|
||||
let mut child = Command::new("/bin/sh")
|
||||
.args([
|
||||
"-c",
|
||||
r#"
|
||||
sleep 1
|
||||
if test -t 0; then exit 1; fi
|
||||
if read -r input 2>/dev/null; then exit 1; fi
|
||||
printf '%s\n' child-stderr-after-entry >&2
|
||||
"#,
|
||||
])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let members = InternalMembers::default();
|
||||
members
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert("internal.example.com".into(), "internal.example.com: Healthy".into());
|
||||
let mut native = None;
|
||||
let monitor = if mode == "tunnel" || mode == "active-tunnel" || mode == "prompted-tunnel" {
|
||||
let vpn = Arc::new(
|
||||
openconnect::Vpn::builder("vpn.example.com", "fixture-cookie")
|
||||
.network_configuration_handler(|_| Ok(()))
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
let monitor = gptunnel::TunnelMonitor::attach(vpn.clone());
|
||||
if mode == "active-tunnel" || mode == "prompted-tunnel" {
|
||||
native = Some(active_native_fixture(vpn, cancellation.clone()));
|
||||
}
|
||||
let _ = notice::slot();
|
||||
session_notice(log::Level::Warn, "initial-fallback-warning");
|
||||
dashboard.start_tunnel(monitor.clone()).unwrap();
|
||||
Some(monitor)
|
||||
} else {
|
||||
dashboard.start_internal(members).unwrap();
|
||||
None
|
||||
};
|
||||
println!("redirected-stdout");
|
||||
tokio::time::timeout(Duration::from_secs(15), cancellation.cancelled())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
child.wait().unwrap().success(),
|
||||
"helper must not inherit dashboard input"
|
||||
);
|
||||
if let Some(monitor) = monitor {
|
||||
monitor.stop().await;
|
||||
}
|
||||
if let Some(native) = native {
|
||||
native.join().unwrap();
|
||||
}
|
||||
dashboard.finish().unwrap();
|
||||
assert_eq!(fcntl(std::io::stdin(), FcntlArg::F_GETFD).unwrap(), input_flags);
|
||||
signals.abort();
|
||||
eprintln!("DASHBOARD_RESTORED");
|
||||
let mut acknowledgement = String::new();
|
||||
let mut tty = std::fs::OpenOptions::new().read(true).open("/dev/tty").unwrap();
|
||||
use std::io::BufRead;
|
||||
std::io::BufReader::new(&mut tty)
|
||||
.read_line(&mut acknowledgement)
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
fn active_native_fixture(vpn: Arc<openconnect::Vpn>, cancellation: CancellationToken) -> std::thread::JoinHandle<()> {
|
||||
use std::{
|
||||
ffi::{c_int, c_void},
|
||||
os::fd::AsRawFd,
|
||||
os::unix::net::UnixStream,
|
||||
};
|
||||
#[repr(C)]
|
||||
struct Statistics {
|
||||
tx_pkts: u64,
|
||||
tx_bytes: u64,
|
||||
rx_pkts: u64,
|
||||
rx_bytes: u64,
|
||||
}
|
||||
unsafe extern "C" {
|
||||
fn vpn_attach_command_pipe(vpn: *mut c_void, fd: c_int) -> c_int;
|
||||
fn vpn_detach_command_pipe(vpn: *mut c_void);
|
||||
fn vpn_tunnel_event(vpn: *mut c_void, event: c_int);
|
||||
fn vpn_tunnel_statistics(vpn: *mut c_void, statistics: *const Statistics);
|
||||
}
|
||||
let (sender, mut receiver) = UnixStream::pair().unwrap();
|
||||
receiver.set_nonblocking(true).unwrap();
|
||||
let pointer = Arc::as_ptr(&vpn).cast_mut().cast();
|
||||
// SAFETY: the fixture retains Vpn and both endpoints through detach; event
|
||||
// numbers and statistics layout match the native bridge used in production.
|
||||
unsafe {
|
||||
assert_eq!(vpn_attach_command_pipe(pointer, sender.as_raw_fd()), 0);
|
||||
vpn_tunnel_event(pointer, 1);
|
||||
vpn_tunnel_event(pointer, 5);
|
||||
}
|
||||
std::thread::spawn(move || {
|
||||
let pointer = Arc::as_ptr(&vpn).cast_mut().cast();
|
||||
let mut command = [0];
|
||||
while !cancellation.is_cancelled() {
|
||||
match receiver.read(&mut command) {
|
||||
Ok(1) if command[0] == b's' => unsafe {
|
||||
vpn_tunnel_statistics(
|
||||
pointer,
|
||||
&Statistics {
|
||||
tx_pkts: 2,
|
||||
tx_bytes: 1024,
|
||||
rx_pkts: 4,
|
||||
rx_bytes: 4096,
|
||||
},
|
||||
);
|
||||
},
|
||||
Err(error) if error.kind() == io::ErrorKind::WouldBlock => std::thread::sleep(Duration::from_millis(10)),
|
||||
other => panic!("Unexpected native fixture command: {other:?}"),
|
||||
}
|
||||
}
|
||||
// SAFETY: all native observations finish before the retained Vpn is freed.
|
||||
unsafe {
|
||||
vpn_detach_command_pipe(pointer);
|
||||
vpn_tunnel_event(pointer, 7);
|
||||
}
|
||||
drop(sender);
|
||||
})
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
mod background;
|
||||
mod cli;
|
||||
mod connect;
|
||||
mod dashboard;
|
||||
mod diagnostics;
|
||||
mod disconnect;
|
||||
mod hip;
|
||||
mod launch_gui;
|
||||
|
||||
@@ -75,6 +75,7 @@ async fn run_session_runtime(session_ctx: SessionContext, mut session_info: Sess
|
||||
|
||||
tokio::time::sleep(schedule.delay).await;
|
||||
|
||||
crate::dashboard::session_notice(Level::Warn, &schedule.message);
|
||||
report(log_format, Level::Warn, &format!("\nWARNING: {}", schedule.message));
|
||||
|
||||
if !schedule.should_auto_extend {
|
||||
@@ -90,6 +91,7 @@ async fn run_session_runtime(session_ctx: SessionContext, mut session_info: Sess
|
||||
return;
|
||||
};
|
||||
|
||||
crate::dashboard::session_notice(Level::Info, "Session extended.");
|
||||
report(log_format, Level::Info, "Session extended.");
|
||||
session_info = next_session_info;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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([
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
"--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'"));
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Compiled by the PTY test with -C panic=abort against the production hook.
|
||||
#[path = "../../src/dashboard/restoration.rs"]
|
||||
mod restoration;
|
||||
|
||||
use std::{fs::{File, OpenOptions}, io::{Read, Write}, os::fd::{AsRawFd, FromRawFd}, sync::Arc};
|
||||
|
||||
fn main() {
|
||||
let tty = OpenOptions::new().read(true).write(true).open("/dev/tty").unwrap();
|
||||
let error = Arc::new(unsafe { File::from_raw_fd(nix::libc::fcntl(2, nix::libc::F_DUPFD_CLOEXEC, 3)) });
|
||||
let input_flags = nix::fcntl::FdFlag::from_bits_truncate(unsafe { nix::libc::fcntl(0, nix::libc::F_GETFD) });
|
||||
let previous = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |panic| {
|
||||
assert_eq!(unsafe { nix::libc::fcntl(0, nix::libc::F_GETFD) }, input_flags.bits());
|
||||
previous(panic);
|
||||
eprintln!("ABORT_HOOK_RESTORED");
|
||||
let mut acknowledgement = String::new();
|
||||
std::io::stdin().read_line(&mut acknowledgement).unwrap();
|
||||
}));
|
||||
let restore = restoration::TerminalRestoration::install(tty.try_clone().unwrap(), error.clone(), None, input_flags).unwrap();
|
||||
restore.arm();
|
||||
unsafe { nix::libc::fcntl(0, nix::libc::F_SETFD, input_flags.bits() | nix::libc::FD_CLOEXEC); }
|
||||
let mut termios = std::mem::MaybeUninit::uninit();
|
||||
unsafe {
|
||||
assert_eq!(nix::libc::tcgetattr(tty.as_raw_fd(), termios.as_mut_ptr()), 0);
|
||||
let mut raw = termios.assume_init();
|
||||
nix::libc::cfmakeraw(&mut raw);
|
||||
assert_eq!(nix::libc::tcsetattr(tty.as_raw_fd(), nix::libc::TCSANOW, &raw), 0);
|
||||
}
|
||||
(&*error).write_all(b"\x1b[?1049hABORT_FIXTURE_READY").unwrap();
|
||||
let mut trigger = [0];
|
||||
(&tty).read_exact(&mut trigger).unwrap();
|
||||
panic!("intentional abort-hook fixture panic");
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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>
|
||||
|
||||
@@ -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]"
|
||||
}
|
||||
@@ -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: {}
|
||||
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 27 KiB After Width: | Height: | Size: 26 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 57 KiB After Width: | Height: | Size: 56 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 |
@@ -250,7 +250,7 @@ async fn run_installer_connection(
|
||||
};
|
||||
let _ = command.reply.send(result);
|
||||
}
|
||||
ServerMessage::Event { .. } | ServerMessage::Snapshot { .. } => {}
|
||||
ServerMessage::Event { .. } | ServerMessage::Snapshot { .. } | ServerMessage::TunnelStatistics { .. } => {}
|
||||
ServerMessage::Attached { .. } => bail!("Service sent a duplicate attach response"),
|
||||
},
|
||||
Message::Ping(data) => socket.send(Message::Pong(data)).await?,
|
||||
@@ -631,6 +631,7 @@ mod tests {
|
||||
current_revision: 0,
|
||||
snapshot: VpnEnv {
|
||||
vpn_state: VpnState::Disconnected,
|
||||
tunnel_state: None,
|
||||
vpnc_script: None,
|
||||
auth_executable: String::new(),
|
||||
host_info: HostInfo {
|
||||
|
||||
@@ -8,8 +8,8 @@ license.workspace = true
|
||||
common = { path = "../../crates/common" }
|
||||
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
|
||||
gphip = { path = "../../crates/gphip" }
|
||||
gptunnel = { path = "../../crates/gptunnel" }
|
||||
base64.workspace = true
|
||||
sha256.workspace = true
|
||||
openconnect = { path = "../../crates/openconnect" }
|
||||
clap.workspace = true
|
||||
anyhow.workspace = true
|
||||
@@ -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"] }
|
||||
@@ -37,3 +37,6 @@ nix = { version = "0.31", features = ["fs", "socket", "user"] }
|
||||
[dev-dependencies]
|
||||
openssl.workspace = true
|
||||
tokio-tungstenite = "0.29"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
gpvpnc = { path = "../../crates/gpvpnc" }
|
||||
@@ -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");
|
||||
|
||||
@@ -119,23 +119,13 @@ impl Cli {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let brokered_scripts_dir = if externally_brokered {
|
||||
let executable = std::env::current_exe().context("Failed to locate the gpservice executable")?;
|
||||
let contents_dir = executable
|
||||
.parent()
|
||||
.and_then(std::path::Path::parent)
|
||||
.context("gpservice is not inside a macOS application bundle")?;
|
||||
Some(contents_dir.join("Resources/Scripts"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (mut vpn_task, lifecycle) = VpnTask::new(vpn_state_tx, externally_brokered, Arc::clone(®istry));
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
lifecycle.clone(),
|
||||
Arc::clone(&gui_restart_requested),
|
||||
Arc::clone(&redaction),
|
||||
!externally_brokered,
|
||||
brokered_scripts_dir,
|
||||
externally_brokered,
|
||||
));
|
||||
#[cfg(target_os = "macos")]
|
||||
let idle_vpn_state_rx = vpn_state_rx.clone();
|
||||
@@ -152,13 +142,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(®istry));
|
||||
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 +199,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 +402,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(())
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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(®istry), Some(1234)));
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::{
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use gpapi::hip::HipApprovalStatus;
|
||||
use gpapi::{hip::HipApprovalStatus, utils::checksum::sha256_hex};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tempfile::Builder;
|
||||
use uuid::Uuid;
|
||||
@@ -169,7 +169,7 @@ fn install_at(
|
||||
let info = ApprovalInfo {
|
||||
approval_id: approval_id.clone(),
|
||||
owner_uid: approving_uid,
|
||||
sha256: sha256::digest(contents),
|
||||
sha256: sha256_hex(contents),
|
||||
original_path,
|
||||
};
|
||||
let staged = Builder::new().prefix(".install-").tempdir_in(base)?;
|
||||
@@ -232,7 +232,7 @@ fn resolve_at_with_control(
|
||||
}
|
||||
ensure!(!contents.is_empty(), "Approved HIP script is empty");
|
||||
ensure!(
|
||||
sha256::digest(&contents) == info.sha256,
|
||||
sha256_hex(&contents) == info.sha256,
|
||||
"Approved HIP script digest mismatch"
|
||||
);
|
||||
control.check()?;
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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! {
|
||||
|
||||
@@ -78,16 +78,19 @@ pub struct RequestDispatcher {
|
||||
redaction: Arc<Redaction>,
|
||||
install_lock: Mutex<()>,
|
||||
gui_management_enabled: bool,
|
||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
||||
externally_brokered: bool,
|
||||
}
|
||||
|
||||
impl RequestDispatcher {
|
||||
pub fn subscribe_tunnel(&self) -> tokio::sync::watch::Receiver<crate::vpn_task::TunnelBinding> {
|
||||
self.lifecycle.subscribe_tunnel()
|
||||
}
|
||||
pub fn new(
|
||||
lifecycle: crate::vpn_task::LifecycleHandle,
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
redaction: Arc<Redaction>,
|
||||
gui_management_enabled: bool,
|
||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
||||
externally_brokered: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
lifecycle,
|
||||
@@ -95,7 +98,7 @@ impl RequestDispatcher {
|
||||
redaction,
|
||||
install_lock: Mutex::new(()),
|
||||
gui_management_enabled,
|
||||
brokered_scripts_dir,
|
||||
externally_brokered,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +111,7 @@ impl RequestDispatcher {
|
||||
) -> Result<PendingDispatch, ServiceResult> {
|
||||
match request {
|
||||
WsRequest::Connect(request) => {
|
||||
if let Err(message) = self.validate_connect_paths(&request) {
|
||||
if let Err(message) = self.validate_connect_request(&request) {
|
||||
return Err(ServiceResult::rejected(ServiceErrorCode::InvalidRequest, message));
|
||||
}
|
||||
let redaction_values = request
|
||||
@@ -197,12 +200,8 @@ impl RequestDispatcher {
|
||||
desktop_uid,
|
||||
edited_report,
|
||||
} => {
|
||||
let prepared = crate::vpn_task::prepare_connection(
|
||||
*request,
|
||||
self.brokered_scripts_dir.is_some(),
|
||||
preparation.cancellation(),
|
||||
)
|
||||
.await;
|
||||
let prepared =
|
||||
crate::vpn_task::prepare_connection(*request, self.externally_brokered, preparation.cancellation()).await;
|
||||
return match prepared {
|
||||
Ok(connection) => preparation.commit(connection, desktop_uid, edited_report),
|
||||
Err(error) => {
|
||||
@@ -271,19 +270,19 @@ impl RequestDispatcher {
|
||||
| WsRequest::PreviewHipReport(_)
|
||||
| WsRequest::GetHipApprovalStatus { .. }
|
||||
| WsRequest::ReadHipPreviewChunk(_)
|
||||
| WsRequest::GetLastSubmittedHipReport => {
|
||||
| WsRequest::GetLastSubmittedHipReport
|
||||
| WsRequest::SetTunnelStatisticsEnabled { .. } => {
|
||||
unreachable!("session-bound request was already dispatched")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_connect_paths(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
|
||||
let Some(scripts) = &self.brokered_scripts_dir else {
|
||||
fn validate_connect_request(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
|
||||
if !self.externally_brokered {
|
||||
return Ok(());
|
||||
};
|
||||
let expected_script = scripts.join("vpnc-script").to_string_lossy().into_owned();
|
||||
if request.args().vpnc_script().as_deref() != Some(expected_script.as_str()) {
|
||||
return Err("macOS VPN script must be the bundled script");
|
||||
}
|
||||
if request.args().vpnc_script().is_some() {
|
||||
return Err("macOS does not support custom VPN scripts");
|
||||
}
|
||||
if matches!(
|
||||
request.args().hip_source(),
|
||||
@@ -520,7 +519,7 @@ mod tests {
|
||||
#[test]
|
||||
fn installs_gui_at_the_supplied_target() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = sha256::try_digest(archive.path()).unwrap();
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpclient/gpgui");
|
||||
|
||||
@@ -549,7 +548,7 @@ mod tests {
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
false,
|
||||
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
|
||||
true,
|
||||
);
|
||||
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::RestartGui).await else {
|
||||
panic!("brokered mode accepted GUI restart");
|
||||
@@ -558,9 +557,7 @@ mod tests {
|
||||
|
||||
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
||||
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
||||
let request = test_request(info)
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||
.with_certificate(Some("/Users/example/client.pem".to_string()));
|
||||
let request = test_request(info).with_certificate(Some("/Users/example/client.pem".to_string()));
|
||||
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::Connect(Box::new(request))).await else {
|
||||
panic!("brokered mode accepted a root-readable identity path");
|
||||
};
|
||||
@@ -568,33 +565,37 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brokered_mode_accepts_only_resource_script_paths() {
|
||||
fn brokered_mode_rejects_script_overrides() {
|
||||
let dispatcher = RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
false,
|
||||
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
|
||||
true,
|
||||
);
|
||||
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
||||
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
||||
let bundled =
|
||||
test_request(info.clone()).with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()));
|
||||
assert_eq!(dispatcher.validate_connect_paths(&bundled), Ok(()));
|
||||
let embedded = test_request(info.clone());
|
||||
assert_eq!(dispatcher.validate_connect_request(&embedded), Ok(()));
|
||||
|
||||
let old_layout = test_request(info.clone()).with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()));
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_paths(&old_layout),
|
||||
Err("macOS VPN script must be the bundled script")
|
||||
);
|
||||
for script in [
|
||||
"/app/Contents/Resources/Scripts/vpnc-script",
|
||||
"/tmp/custom-vpnc-script",
|
||||
"echo untrusted",
|
||||
"",
|
||||
] {
|
||||
let custom = test_request(info.clone()).with_vpnc_script(Some(script.to_string()));
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_request(&custom),
|
||||
Err("macOS does not support custom VPN scripts")
|
||||
);
|
||||
}
|
||||
|
||||
let custom = test_request(info)
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||
.with_hip_source(gpapi::hip::HipSource::UserScript {
|
||||
path: "/tmp/hip.sh".into(),
|
||||
});
|
||||
let custom = test_request(info).with_hip_source(gpapi::hip::HipSource::UserScript {
|
||||
path: "/tmp/hip.sh".into(),
|
||||
});
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_paths(&custom),
|
||||
dispatcher.validate_connect_request(&custom),
|
||||
Err("macOS does not support custom HIP scripts")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
use gpapi::service::request::ConnectArgs;
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
|
||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result<VpnBuilder> {
|
||||
anyhow::ensure!(
|
||||
args.vpnc_script().is_none(),
|
||||
"macOS does not support custom VPN scripts"
|
||||
);
|
||||
Ok(
|
||||
Vpn::builder(server, cookie).network_configuration_handler(|configuration| {
|
||||
gpvpnc::macos::configure_network(&configuration.reason, &configuration.environment)
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,15 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[path = "privileged_unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "macos.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(any(
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "macos"
|
||||
)))]
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
|
||||
@@ -32,9 +32,20 @@ mod runtime;
|
||||
pub(crate) struct LifecycleHandle {
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
admissions: Arc<Mutex<Admissions>>,
|
||||
tunnel: watch::Sender<TunnelBinding>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct TunnelBinding {
|
||||
pub attempt: u64,
|
||||
pub monitor: Option<Arc<gptunnel::TunnelMonitor>>,
|
||||
pub non_tunnel: bool,
|
||||
}
|
||||
|
||||
impl LifecycleHandle {
|
||||
pub fn subscribe_tunnel(&self) -> watch::Receiver<TunnelBinding> {
|
||||
self.tunnel.subscribe()
|
||||
}
|
||||
pub fn reserve_connect(&self) -> Result<ConnectReservation, ServiceResult> {
|
||||
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
|
||||
if admissions.closed {
|
||||
@@ -212,7 +223,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
|
||||
}
|
||||
@@ -370,6 +381,10 @@ enum AdmissionPhase {
|
||||
}
|
||||
|
||||
enum LifecycleEvent {
|
||||
TunnelMonitor {
|
||||
attempt: u64,
|
||||
monitor: Arc<gptunnel::TunnelMonitor>,
|
||||
},
|
||||
Start {
|
||||
attempt: u64,
|
||||
connection: PreparedConnection,
|
||||
@@ -429,6 +444,7 @@ impl VpnTask {
|
||||
let lifecycle = LifecycleHandle {
|
||||
events: events_tx,
|
||||
admissions: Arc::new(Mutex::new(Admissions::default())),
|
||||
tunnel: watch::channel(TunnelBinding::default()).0,
|
||||
};
|
||||
let task = Self {
|
||||
events,
|
||||
@@ -493,6 +509,16 @@ impl VpnTask {
|
||||
|
||||
async fn handle_event(&mut self, event: LifecycleEvent) {
|
||||
match event {
|
||||
LifecycleEvent::TunnelMonitor { attempt, monitor } => {
|
||||
if self.active.as_ref().is_some_and(|active| active.attempt == attempt) {
|
||||
let non_tunnel = false;
|
||||
self.lifecycle.tunnel.send_replace(TunnelBinding {
|
||||
attempt,
|
||||
monitor: Some(monitor),
|
||||
non_tunnel,
|
||||
});
|
||||
}
|
||||
}
|
||||
LifecycleEvent::Start {
|
||||
attempt,
|
||||
connection,
|
||||
@@ -526,6 +552,16 @@ impl VpnTask {
|
||||
session_id: Option<Uuid>,
|
||||
) {
|
||||
let activated = self.lifecycle.activate_attempt(attempt);
|
||||
self.lifecycle.tunnel.send_replace(TunnelBinding {
|
||||
attempt,
|
||||
monitor: None,
|
||||
non_tunnel: connection
|
||||
.request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel),
|
||||
});
|
||||
let info = connection.request.info().clone();
|
||||
let allow_extend_session = connection.request.args().allow_extend_session();
|
||||
let cancellation = self.lifecycle.attempt_cancellation(attempt);
|
||||
@@ -661,6 +697,12 @@ impl VpnTask {
|
||||
if let Some(session_id) = active.session_id {
|
||||
self.registry.clear_successful_hip_report(session_id);
|
||||
}
|
||||
if self.lifecycle.tunnel.borrow().monitor.is_none() {
|
||||
self.lifecycle.tunnel.send_replace(TunnelBinding {
|
||||
attempt,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
if let Some(reason) = active.failure {
|
||||
self.send_state(VpnState::Failed(reason));
|
||||
self.lifecycle.clear_attempt(attempt);
|
||||
@@ -782,7 +824,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 {
|
||||
@@ -815,49 +857,22 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn identity_material() -> (openssl::pkey::PKey<openssl::pkey::Private>, openssl::x509::X509) {
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
hash::MessageDigest,
|
||||
pkey::PKey,
|
||||
rsa::Rsa,
|
||||
x509::{X509, X509NameBuilder},
|
||||
};
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
name.append_entry_by_text("CN", "service-identity-fixture").unwrap();
|
||||
let name = name.build();
|
||||
let mut certificate = X509::builder().unwrap();
|
||||
certificate.set_version(2).unwrap();
|
||||
certificate.set_subject_name(&name).unwrap();
|
||||
certificate.set_issuer_name(&name).unwrap();
|
||||
certificate.set_pubkey(&key).unwrap();
|
||||
certificate
|
||||
.set_not_before(&Asn1Time::days_from_now(0).unwrap())
|
||||
.unwrap();
|
||||
certificate.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
certificate.sign(&key, MessageDigest::sha256()).unwrap();
|
||||
(key, certificate.build())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tunnel_identity_paths_allow_large_files_and_retain_loaded_material() {
|
||||
let (key, certificate) = identity_material();
|
||||
let certificate = include_bytes!("../../../crates/gpapi/tests/files/client-identity/rsa-cert.pem");
|
||||
let key = include_bytes!("../../../crates/gpapi/tests/files/client-identity/rsa-pkcs8.pem");
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("identity.pem");
|
||||
let mut pem = certificate.to_pem().unwrap();
|
||||
pem.extend(key.private_key_to_pem_pkcs8().unwrap());
|
||||
let mut pem = certificate.to_vec();
|
||||
pem.extend(key);
|
||||
pem.resize(gpapi::service::request::MAX_CLIENT_IDENTITY_DATA + 1, b'\n');
|
||||
std::fs::write(&path, pem).unwrap();
|
||||
let request = identity_request().with_certificate(Some(path.to_str().unwrap().into()));
|
||||
let identity = prepare_identity(request.args(), false).unwrap().unwrap();
|
||||
std::fs::remove_file(path).unwrap();
|
||||
assert_eq!(identity.certificate_data(), certificate.to_pem().unwrap());
|
||||
assert_eq!(identity.certificate_data(), certificate);
|
||||
let files = identity.write_files(None).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read(files.certificate()).unwrap(),
|
||||
certificate.to_pem().unwrap()
|
||||
);
|
||||
assert_eq!(std::fs::read(files.certificate()).unwrap(), certificate);
|
||||
assert!(files.key().is_some());
|
||||
}
|
||||
|
||||
@@ -881,17 +896,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn protected_pkcs12_import_retains_password_and_single_file_material() {
|
||||
use openssl::pkcs12::Pkcs12;
|
||||
let (key, certificate) = identity_material();
|
||||
let password = "service-fixture-password";
|
||||
let p12 = Pkcs12::builder()
|
||||
.name("fixture")
|
||||
.pkey(&key)
|
||||
.cert(&certificate)
|
||||
.build2(password)
|
||||
.unwrap()
|
||||
.to_der()
|
||||
.unwrap();
|
||||
let password = "fixture-password";
|
||||
let p12 = include_bytes!("../../../crates/gpapi/tests/files/client-identity/modern.p12").to_vec();
|
||||
let request = identity_request()
|
||||
.with_certificate_data(Some(p12.clone()))
|
||||
.with_key_password(Some(password.into()));
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -262,6 +262,18 @@ async fn run_tunnel(
|
||||
if cancellation.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
let monitor = gptunnel::TunnelMonitor::attach(prepared.vpn.clone());
|
||||
if events
|
||||
.send(LifecycleEvent::TunnelMonitor {
|
||||
attempt,
|
||||
monitor: monitor.clone(),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
monitor.stop().await;
|
||||
return;
|
||||
}
|
||||
let vpn = prepared.vpn.clone();
|
||||
// The native tunnel keeps its reconnect endpoint and cookie current and owns
|
||||
// normal logout. The ledger remains responsible only before native execution.
|
||||
@@ -291,6 +303,7 @@ async fn run_tunnel(
|
||||
Ok(code) => warn!("Tunnel worker exited with status {code}"),
|
||||
Err(error) => warn!("Tunnel worker failed: {error}"),
|
||||
}
|
||||
monitor.stop().await;
|
||||
}
|
||||
|
||||
pub(super) fn stop_for_revoked_approval(lifecycle: &LifecycleHandle, cancellation: &CancellationToken) {
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
use std::{collections::HashSet, sync::Arc, time::Duration};
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use axum::extract::ws::{CloseFrame, Message, Utf8Bytes, WebSocket};
|
||||
use futures::StreamExt;
|
||||
@@ -34,6 +41,9 @@ pub(crate) struct ConnectionControl {
|
||||
connection_id: Uuid,
|
||||
tx: mpsc::Sender<ConnectionCommand>,
|
||||
close_tx: watch::Sender<Option<CloseReason>>,
|
||||
statistics: watch::Sender<Option<gpapi::session::tunnel::TunnelStatisticsSnapshot>>,
|
||||
statistics_enabled: Arc<AtomicBool>,
|
||||
committed: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl ConnectionControl {
|
||||
@@ -44,6 +54,9 @@ impl ConnectionControl {
|
||||
connection_id,
|
||||
tx,
|
||||
close_tx,
|
||||
statistics: watch::channel(None).0,
|
||||
statistics_enabled: Arc::new(AtomicBool::new(false)),
|
||||
committed: Arc::new(AtomicBool::new(false)),
|
||||
},
|
||||
close_rx,
|
||||
)
|
||||
@@ -62,9 +75,43 @@ impl ConnectionControl {
|
||||
}
|
||||
|
||||
pub fn close(&self, reason: CloseReason) {
|
||||
self.set_statistics_enabled(false);
|
||||
self.close_tx.send_replace(Some(reason));
|
||||
}
|
||||
|
||||
pub fn mark_committed(&self) {
|
||||
self.committed.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn is_committed(&self) -> bool {
|
||||
self.committed.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn statistics_enabled(&self) -> bool {
|
||||
self.statistics_enabled.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn set_statistics_enabled(&self, enabled: bool) {
|
||||
self.statistics_enabled.store(enabled, Ordering::Release);
|
||||
if !enabled {
|
||||
self.statistics.send_replace(None);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_statistics(&self) {
|
||||
self.statistics.send_replace(None);
|
||||
}
|
||||
|
||||
pub fn publish_statistics(&self, snapshot: gpapi::session::tunnel::TunnelStatisticsSnapshot) {
|
||||
if self.statistics_enabled() && !self.is_closed() {
|
||||
self.statistics.send_replace(Some(snapshot));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subscribe_statistics(&self) -> watch::Receiver<Option<gpapi::session::tunnel::TunnelStatisticsSnapshot>> {
|
||||
self.statistics.subscribe()
|
||||
}
|
||||
|
||||
pub async fn send_reply(&self, id: Uuid, result: ServiceResult) {
|
||||
let _ = self.tx.send(ConnectionCommand::Reply { id, result }).await;
|
||||
}
|
||||
@@ -96,12 +143,14 @@ impl WsConnection {
|
||||
|
||||
info!("Authenticated GUI connection {}", control.connection_id());
|
||||
let mut pending_requests = HashSet::new();
|
||||
let mut statistics_rx = control.subscribe_statistics();
|
||||
let mut heartbeat = tokio::time::interval(Duration::from_secs(1));
|
||||
let mut last_outbound = Instant::now();
|
||||
let mut pong_deadline = None;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
command = command_rx.recv() => {
|
||||
let Some(command) = command else { break };
|
||||
match command {
|
||||
@@ -181,6 +230,16 @@ impl WsConnection {
|
||||
pong_deadline = Some(now + PONG_TIMEOUT);
|
||||
}
|
||||
}
|
||||
changed = statistics_rx.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
let snapshot = statistics_rx.borrow_and_update().clone();
|
||||
if control.statistics_enabled() {
|
||||
if let Some(snapshot) = snapshot {
|
||||
if send_encrypted(&mut socket, &mut noise, &ServerMessage::TunnelStatistics { snapshot }).await.is_err() { break; }
|
||||
last_outbound = Instant::now();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,6 +400,14 @@ async fn handle_client_message(
|
||||
return Err(());
|
||||
}
|
||||
|
||||
if let WsRequest::SetTunnelStatisticsEnabled { enabled } = request {
|
||||
let result = ctx
|
||||
.set_statistics_enabled(control, session_id, generation, enabled)
|
||||
.await;
|
||||
control.send(ConnectionCommand::Reply { id, result }).map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::StoreEditedHipReportChunk(report) = request {
|
||||
let upload_id = report.upload_id.as_deref().and_then(|id| Uuid::parse_str(id).ok());
|
||||
let result = if report.upload_id.is_some() && upload_id.is_none() {
|
||||
@@ -589,14 +656,14 @@ 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(),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
None,
|
||||
false,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
@@ -669,6 +736,23 @@ mod tests {
|
||||
} if id == request_id
|
||||
));
|
||||
|
||||
let statistics_id = Uuid::new_v4();
|
||||
let request = ClientMessage::Request {
|
||||
id: statistics_id,
|
||||
request: WsRequest::SetTunnelStatisticsEnabled { enabled: true },
|
||||
};
|
||||
socket
|
||||
.send(ClientFrame::Binary(noise.encrypt(&request).unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
let reply = noise
|
||||
.decrypt::<ServerMessage>(&receive_client_binary(&mut socket).await)
|
||||
.unwrap();
|
||||
assert!(matches!(reply, ServerMessage::Reply {
|
||||
id,
|
||||
result: ServiceResult::TunnelStatisticsSnapshot(gpapi::session::tunnel::TunnelStatisticsSnapshot::Unavailable { reason: gpapi::session::tunnel::TunnelUnavailableReason::NoTunnel }),
|
||||
} if id == statistics_id));
|
||||
|
||||
let update_id = Uuid::new_v4();
|
||||
let update_file = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(update_file.path(), b"invalid archive").unwrap();
|
||||
|
||||
@@ -9,6 +9,7 @@ use gpapi::{
|
||||
vpn_env::{HostInfo, VpnEnv},
|
||||
vpn_state::VpnState,
|
||||
},
|
||||
session::tunnel::{TunnelStatisticsSnapshot, TunnelUnavailableReason},
|
||||
utils::lock_file::LockFile,
|
||||
};
|
||||
use log::{info, warn};
|
||||
@@ -31,6 +32,28 @@ struct ServiceState {
|
||||
revision: u64,
|
||||
snapshot: VpnEnv,
|
||||
connections: HashMap<Uuid, ConnectionControl>,
|
||||
tunnel: crate::vpn_task::TunnelBinding,
|
||||
}
|
||||
|
||||
impl ServiceState {
|
||||
fn refresh_demand(&self) {
|
||||
if let Some(monitor) = &self.tunnel.monitor {
|
||||
monitor.set_statistics_enabled(
|
||||
self
|
||||
.connections
|
||||
.values()
|
||||
.any(|connection| connection.statistics_enabled() && !connection.is_closed()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(&self) -> VpnEnv {
|
||||
let mut snapshot = self.snapshot.clone();
|
||||
if let Some(monitor) = &self.tunnel.monitor {
|
||||
snapshot.tunnel_state = Some(monitor.state());
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct WsServerContext {
|
||||
@@ -57,6 +80,7 @@ impl WsServerContext {
|
||||
revision: 0,
|
||||
snapshot: build_snapshot(vpn_state_rx.borrow().clone()),
|
||||
connections: HashMap::new(),
|
||||
tunnel: Default::default(),
|
||||
}),
|
||||
handshake_slots: Arc::new(Semaphore::new(16)),
|
||||
hip_previews: crate::hip_preview::HipPreviews::new(),
|
||||
@@ -91,12 +115,14 @@ impl WsServerContext {
|
||||
let mut state = self.state.lock().await;
|
||||
let prepared = self.registry.prepare_attach(permit)?;
|
||||
|
||||
let mut attached = ServerMessage::Attached {
|
||||
connection_id: control.connection_id(),
|
||||
current_revision: state.revision,
|
||||
snapshot: state.snapshot(),
|
||||
};
|
||||
fit_snapshot_message(&mut attached).map_err(|_| SessionError::Unavailable)?;
|
||||
control
|
||||
.send(ConnectionCommand::Send(ServerMessage::Attached {
|
||||
connection_id: control.connection_id(),
|
||||
current_revision: state.revision,
|
||||
snapshot: state.snapshot.clone(),
|
||||
}))
|
||||
.send(ConnectionCommand::Send(attached))
|
||||
.map_err(|_| SessionError::Unavailable)?;
|
||||
state.connections.insert(control.connection_id(), control);
|
||||
Ok(prepared)
|
||||
@@ -117,42 +143,49 @@ impl WsServerContext {
|
||||
}
|
||||
match self.registry.commit_attach(permit, connection.clone()) {
|
||||
Ok(replaced) => {
|
||||
connection.mark_committed();
|
||||
if let Some(replaced) = &replaced {
|
||||
replaced.set_statistics_enabled(false);
|
||||
state.connections.remove(&replaced.connection_id());
|
||||
}
|
||||
state.refresh_demand();
|
||||
Ok(replaced)
|
||||
}
|
||||
Err(err) => {
|
||||
state.connections.remove(&connection.connection_id());
|
||||
state.refresh_demand();
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn abandon_connection(&self, connection_id: Uuid) {
|
||||
self.state.lock().await.connections.remove(&connection_id);
|
||||
let mut state = self.state.lock().await;
|
||||
state.connections.remove(&connection_id);
|
||||
state.refresh_demand();
|
||||
}
|
||||
|
||||
pub async fn remove_closed_connections(&self) {
|
||||
self
|
||||
.state
|
||||
.lock()
|
||||
.await
|
||||
.connections
|
||||
.retain(|_, connection| !connection.is_closed());
|
||||
let mut state = self.state.lock().await;
|
||||
state.connections.retain(|_, connection| !connection.is_closed());
|
||||
state.refresh_demand();
|
||||
}
|
||||
|
||||
pub async fn send_snapshot(&self, control: &ConnectionControl) -> Result<(), ()> {
|
||||
let state = self.state.lock().await;
|
||||
control.send(ConnectionCommand::Send(ServerMessage::Snapshot {
|
||||
let mut message = ServerMessage::Snapshot {
|
||||
current_revision: state.revision,
|
||||
snapshot: state.snapshot.clone(),
|
||||
}))
|
||||
snapshot: state.snapshot(),
|
||||
};
|
||||
fit_snapshot_message(&mut message)?;
|
||||
control.send(ConnectionCommand::Send(message))
|
||||
}
|
||||
|
||||
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
||||
self.registry.disconnect_if_current(session_id, generation);
|
||||
self.state.lock().await.connections.remove(&connection_id);
|
||||
let mut state = self.state.lock().await;
|
||||
state.connections.remove(&connection_id);
|
||||
state.refresh_demand();
|
||||
}
|
||||
|
||||
pub async fn send_event(&self, event: WsEvent) {
|
||||
@@ -161,6 +194,8 @@ impl WsServerContext {
|
||||
state.snapshot = env.clone();
|
||||
} else if let WsEvent::VpnState(vpn_state) = &event {
|
||||
state.snapshot.vpn_state = vpn_state.clone();
|
||||
} else if let WsEvent::TunnelState(tunnel) = &event {
|
||||
state.snapshot.tunnel_state = tunnel.clone();
|
||||
}
|
||||
|
||||
let Some(revision) = state.revision.checked_add(1) else {
|
||||
@@ -168,6 +203,7 @@ impl WsServerContext {
|
||||
connection.close(CloseReason::InternalError);
|
||||
}
|
||||
state.connections.clear();
|
||||
state.refresh_demand();
|
||||
return;
|
||||
};
|
||||
state.revision = revision;
|
||||
@@ -186,6 +222,97 @@ impl WsServerContext {
|
||||
false
|
||||
}
|
||||
});
|
||||
state.refresh_demand();
|
||||
}
|
||||
|
||||
pub async fn set_statistics_enabled(
|
||||
&self,
|
||||
control: &ConnectionControl,
|
||||
session_id: Uuid,
|
||||
generation: u64,
|
||||
enabled: bool,
|
||||
) -> gpapi::service::transport::ServiceResult {
|
||||
use gpapi::service::transport::{ServiceErrorCode, ServiceResult};
|
||||
let state = self.state.lock().await;
|
||||
if !control.is_committed()
|
||||
|| control.is_closed()
|
||||
|| !state.connections.contains_key(&control.connection_id())
|
||||
|| !self.registry.is_current(session_id, generation)
|
||||
{
|
||||
return ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"Service attachment is no longer active",
|
||||
);
|
||||
}
|
||||
control.set_statistics_enabled(enabled);
|
||||
state.refresh_demand();
|
||||
let snapshot = match &state.tunnel.monitor {
|
||||
Some(monitor) => monitor.statistics(),
|
||||
None => TunnelStatisticsSnapshot::Unavailable {
|
||||
reason: if state.tunnel.non_tunnel {
|
||||
TunnelUnavailableReason::NonTunnel
|
||||
} else {
|
||||
TunnelUnavailableReason::NoTunnel
|
||||
},
|
||||
},
|
||||
};
|
||||
ServiceResult::TunnelStatisticsSnapshot(if enabled { snapshot } else { snapshot.disabled() })
|
||||
}
|
||||
|
||||
async fn bind_tunnel(&self, binding: crate::vpn_task::TunnelBinding) {
|
||||
let mut state = self.state.lock().await;
|
||||
if let Some(previous) = &state.tunnel.monitor {
|
||||
previous.set_statistics_enabled(false);
|
||||
}
|
||||
state.tunnel = binding;
|
||||
for connection in state.connections.values() {
|
||||
connection.clear_statistics();
|
||||
}
|
||||
state.refresh_demand();
|
||||
let tunnel_state = state.tunnel.monitor.as_ref().map(|monitor| monitor.state());
|
||||
drop(state);
|
||||
self.send_event(WsEvent::TunnelState(tunnel_state)).await;
|
||||
let state = self.state.lock().await;
|
||||
let snapshot = match &state.tunnel.monitor {
|
||||
Some(monitor) => monitor.statistics(),
|
||||
None => TunnelStatisticsSnapshot::unavailable(if state.tunnel.non_tunnel {
|
||||
TunnelUnavailableReason::NonTunnel
|
||||
} else {
|
||||
TunnelUnavailableReason::NoTunnel
|
||||
}),
|
||||
};
|
||||
for connection in state.connections.values() {
|
||||
connection.publish_statistics(snapshot.clone());
|
||||
}
|
||||
}
|
||||
|
||||
async fn publish_tunnel(&self, attempt: u64) {
|
||||
let state = self.state.lock().await;
|
||||
if state.tunnel.attempt != attempt {
|
||||
return;
|
||||
}
|
||||
let Some(monitor) = &state.tunnel.monitor else {
|
||||
return;
|
||||
};
|
||||
let current = monitor.state();
|
||||
let changed = state
|
||||
.snapshot
|
||||
.tunnel_state
|
||||
.as_ref()
|
||||
.is_none_or(|previous| previous.tunnel_id != current.tunnel_id || previous.sequence != current.sequence);
|
||||
drop(state);
|
||||
if changed {
|
||||
self.send_event(WsEvent::TunnelState(Some(current))).await;
|
||||
}
|
||||
let state = self.state.lock().await;
|
||||
if state.tunnel.attempt != attempt {
|
||||
return;
|
||||
}
|
||||
if let Some(monitor) = &state.tunnel.monitor {
|
||||
for connection in state.connections.values() {
|
||||
connection.publish_statistics(monitor.statistics());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,6 +367,7 @@ impl WsServer {
|
||||
_ = watch_vpn_state(self.vpn_state_rx.clone(), Arc::clone(&self.ctx)) => {
|
||||
info!("VPN state watch task completed");
|
||||
}
|
||||
_ = watch_tunnel(self.ctx.dispatcher.subscribe_tunnel(), Arc::clone(&self.ctx)) => {}
|
||||
result = axum::serve(listener, routes::routes(Arc::clone(&self.ctx))) => {
|
||||
if let Err(err) = result {
|
||||
warn!("WS server stopped: {err}");
|
||||
@@ -264,6 +392,7 @@ impl WsServer {
|
||||
|
||||
fn build_snapshot(vpn_state: VpnState) -> VpnEnv {
|
||||
VpnEnv {
|
||||
tunnel_state: None,
|
||||
vpn_state,
|
||||
vpnc_script: find_vpnc_script(),
|
||||
auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(),
|
||||
@@ -273,6 +402,36 @@ fn build_snapshot(vpn_state: VpnState) -> VpnEnv {
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the observation's explicit truncation policy to the space remaining in
|
||||
/// a complete envelope. Existing host/connection facts are never shortened.
|
||||
fn fit_snapshot_message(message: &mut ServerMessage) -> Result<(), ()> {
|
||||
let encoded_size = serde_json::to_vec(&message).map_err(|_| ())?.len();
|
||||
let Some(excess) = encoded_size.checked_sub(gpapi::service::transport::MAX_PLAINTEXT) else {
|
||||
return Ok(());
|
||||
};
|
||||
if excess == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let snapshot = match message {
|
||||
ServerMessage::Attached { snapshot, .. } | ServerMessage::Snapshot { snapshot, .. } => snapshot,
|
||||
_ => return Err(()),
|
||||
};
|
||||
let configuration = snapshot
|
||||
.tunnel_state
|
||||
.as_mut()
|
||||
.and_then(|state| state.configuration.as_mut())
|
||||
.ok_or(())?;
|
||||
let configuration_size = serde_json::to_vec(&configuration).map_err(|_| ())?.len();
|
||||
let remaining = configuration_size.checked_sub(excess).ok_or(())?;
|
||||
if !configuration.limit_encoded_size(remaining) {
|
||||
return Err(());
|
||||
}
|
||||
if serde_json::to_vec(message).map_err(|_| ())?.len() > gpapi::service::transport::MAX_PLAINTEXT {
|
||||
return Err(());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
@@ -285,9 +444,174 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
fn context() -> (Arc<WsServerContext>, Arc<SessionRegistry>) {
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
false,
|
||||
));
|
||||
let (_, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
(
|
||||
Arc::new(WsServerContext::new(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
registry.clone(),
|
||||
dispatcher,
|
||||
&state_rx,
|
||||
)),
|
||||
registry,
|
||||
)
|
||||
}
|
||||
|
||||
async fn attach(
|
||||
context: &WsServerContext,
|
||||
registry: &Arc<SessionRegistry>,
|
||||
) -> (ConnectionControl, Uuid, u64, mpsc::Receiver<ConnectionCommand>) {
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
let permit = registry
|
||||
.begin_handshake(
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.product_version(),
|
||||
)
|
||||
.unwrap();
|
||||
let (tx, mut rx) = mpsc::channel(8);
|
||||
let (control, _) = ConnectionControl::new(Uuid::new_v4(), tx);
|
||||
let prepared = context.prepare_connection(&permit, control.clone()).await.unwrap();
|
||||
rx.recv().await.unwrap();
|
||||
context.commit_connection(&permit, &control).await.unwrap();
|
||||
(control, credential.session_id(), prepared.generation, rx)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn statistics_demand_is_per_attachment_and_does_not_consume_revisions() {
|
||||
use gpapi::service::transport::ServiceResult;
|
||||
use gpapi::session::tunnel::TunnelStatisticsState;
|
||||
let (context, registry) = context();
|
||||
let (a, a_session, a_generation, _a_rx) = attach(&context, ®istry).await;
|
||||
let (b, b_session, b_generation, _b_rx) = attach(&context, ®istry).await;
|
||||
let vpn = Arc::new(
|
||||
openconnect::Vpn::builder("vpn.example.com", "cookie")
|
||||
.network_configuration_handler(|_| Ok(()))
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
let monitor = gptunnel::TunnelMonitor::attach(vpn);
|
||||
context
|
||||
.bind_tunnel(crate::vpn_task::TunnelBinding {
|
||||
attempt: 1,
|
||||
monitor: Some(monitor.clone()),
|
||||
non_tunnel: false,
|
||||
})
|
||||
.await;
|
||||
let revision = context.state.lock().await.revision;
|
||||
for (connection, session, generation) in [(&a, a_session, a_generation), (&b, b_session, b_generation)] {
|
||||
assert!(matches!(
|
||||
context
|
||||
.set_statistics_enabled(connection, session, generation, true)
|
||||
.await,
|
||||
ServiceResult::TunnelStatisticsSnapshot(_)
|
||||
));
|
||||
}
|
||||
assert_eq!(
|
||||
monitor.statistics().view().unwrap().state,
|
||||
TunnelStatisticsState::Waiting
|
||||
);
|
||||
let ServiceResult::TunnelStatisticsSnapshot(disabled) =
|
||||
context.set_statistics_enabled(&b, b_session, b_generation, false).await
|
||||
else {
|
||||
panic!("expected snapshot");
|
||||
};
|
||||
assert_eq!(disabled.view().unwrap().state, TunnelStatisticsState::Disabled);
|
||||
assert_eq!(
|
||||
monitor.statistics().view().unwrap().state,
|
||||
TunnelStatisticsState::Waiting
|
||||
);
|
||||
context
|
||||
.remove_connection(a.connection_id(), a_session, a_generation)
|
||||
.await;
|
||||
assert_eq!(
|
||||
monitor.statistics().view().unwrap().state,
|
||||
TunnelStatisticsState::Disabled
|
||||
);
|
||||
assert_eq!(context.state.lock().await.revision, revision);
|
||||
monitor.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sample_slot_coalesces_without_consuming_control_queue_and_disable_clears_it() {
|
||||
let (context, registry) = context();
|
||||
let (control, session, generation, mut commands) = attach(&context, ®istry).await;
|
||||
context
|
||||
.set_statistics_enabled(&control, session, generation, true)
|
||||
.await;
|
||||
let mut samples = control.subscribe_statistics();
|
||||
let snapshot = TunnelStatisticsSnapshot::unavailable(TunnelUnavailableReason::NoTunnel);
|
||||
for _ in 0..1000 {
|
||||
control.publish_statistics(snapshot.clone());
|
||||
}
|
||||
assert_eq!(samples.borrow_and_update().as_ref(), Some(&snapshot));
|
||||
assert!(commands.try_recv().is_err());
|
||||
context
|
||||
.set_statistics_enabled(&control, session, generation, false)
|
||||
.await;
|
||||
assert!(samples.borrow().is_none());
|
||||
control.publish_statistics(snapshot);
|
||||
assert!(samples.borrow().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_budget_trims_observation_without_changing_existing_metadata() {
|
||||
use gpapi::session::tunnel::{TunnelConfiguration, TunnelPhase, TunnelState, TunnelTransport};
|
||||
let mut snapshot = build_snapshot(VpnState::Disconnected);
|
||||
let mut configuration = TunnelConfiguration::default();
|
||||
configuration.included_routes.items = vec!["r".repeat(1000); 15];
|
||||
configuration.included_routes.total_count = 15;
|
||||
snapshot.tunnel_state = Some(TunnelState {
|
||||
tunnel_id: Uuid::nil(),
|
||||
sequence: 4,
|
||||
phase: TunnelPhase::Connected,
|
||||
configuration_revision: 1,
|
||||
configuration: Some(configuration),
|
||||
transport: TunnelTransport::IpsecEsp,
|
||||
elapsed_ms: 600_000,
|
||||
});
|
||||
let original_metadata = "a".repeat(52_000);
|
||||
snapshot.auth_executable = original_metadata.clone();
|
||||
let mut message = ServerMessage::Snapshot {
|
||||
current_revision: 9,
|
||||
snapshot,
|
||||
};
|
||||
assert!(serde_json::to_vec(&message).unwrap().len() > gpapi::service::transport::MAX_PLAINTEXT);
|
||||
fit_snapshot_message(&mut message).unwrap();
|
||||
assert!(serde_json::to_vec(&message).unwrap().len() <= gpapi::service::transport::MAX_PLAINTEXT);
|
||||
let ServerMessage::Snapshot {
|
||||
mut snapshot,
|
||||
current_revision,
|
||||
} = message
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(current_revision, 9);
|
||||
assert_eq!(snapshot.auth_executable, original_metadata);
|
||||
let configuration = snapshot.tunnel_state.as_ref().unwrap().configuration.as_ref().unwrap();
|
||||
assert!(configuration.included_routes.truncated);
|
||||
assert_eq!(configuration.included_routes.total_count, 15);
|
||||
snapshot.auth_executable = "a".repeat(gpapi::service::transport::MAX_PLAINTEXT);
|
||||
assert!(
|
||||
fit_snapshot_message(&mut ServerMessage::Snapshot {
|
||||
current_revision: 9,
|
||||
snapshot
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[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(
|
||||
@@ -301,7 +625,7 @@ mod tests {
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
None,
|
||||
false,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
@@ -344,14 +668,14 @@ 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(),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
None,
|
||||
false,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
@@ -397,3 +721,32 @@ async fn watch_vpn_state(mut vpn_state_rx: watch::Receiver<VpnState>, ctx: Arc<W
|
||||
ctx.send_event(WsEvent::VpnState(vpn_state)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn watch_tunnel(mut binding_rx: watch::Receiver<crate::vpn_task::TunnelBinding>, ctx: Arc<WsServerContext>) {
|
||||
loop {
|
||||
let binding = binding_rx.borrow_and_update().clone();
|
||||
let mut updates = binding.monitor.as_ref().map(|monitor| monitor.subscribe());
|
||||
let attempt = binding.attempt;
|
||||
ctx.bind_tunnel(binding).await;
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
changed = binding_rx.changed() => {
|
||||
if changed.is_err() { return; }
|
||||
break;
|
||||
}
|
||||
changed = async {
|
||||
match &mut updates {
|
||||
Some(receiver) => receiver.changed().await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
} => {
|
||||
if changed.is_err() { break; }
|
||||
// Fence an update against a new lifecycle binding already published.
|
||||
if binding_rx.has_changed().unwrap_or(true) { break; }
|
||||
ctx.publish_tunnel(attempt).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,91 @@
|
||||
# Changelog
|
||||
|
||||
## 3.1.0
|
||||
|
||||
### Added
|
||||
|
||||
- Added a Connection Details panel showing VPN information and live upload and download activity.
|
||||
- Added an optional terminal dashboard showing connection status and logs, enabled with `--dashboard`.
|
||||
- Added client certificate setup in Settings, with guidance when a VPN requires a certificate.
|
||||
|
||||
### Improved
|
||||
|
||||
- Refreshed Settings and dialogs, with automatic saving for most settings and Save and Cancel buttons for detailed edits.
|
||||
- Made sign-in errors clearer and added recovery options within the app.
|
||||
- Added a website address bar to the sign-in window.
|
||||
- Expanded support for client certificate files, including password-protected files, with clearer file and password errors.
|
||||
- Improved license activation error messages and troubleshooting logs.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed sign-in retries losing the selected VPN server after a security error.
|
||||
- Fixed mismatched certificate and key files being accepted and replacing a working certificate setup.
|
||||
- Fixed failed saves discarding certificate details or custom device report (HIP) edits, allowing a retry without re-entering changes.
|
||||
- Fixed theme, automatic-update, and logging settings appearing saved when saving had failed; errors are now shown and previous settings remain in use.
|
||||
- Fixed notifications disappearing too quickly on GNOME and clarified notification sender names and update titles.
|
||||
- Fixed connection failures with some VPN gateways.
|
||||
|
||||
### Command-line notes
|
||||
|
||||
- Renamed copy-and-paste browser sign-in to `--browser manual`; existing commands using `--browser remote` still work.
|
||||
- Removed the unneeded `--fix-openssl` option on macOS; existing macOS commands and scripts must omit it.
|
||||
|
||||
## 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
|
||||
|
||||
- Fixed the bundled macOS CLI when launched through Homebrew.
|
||||
- Fixed browser sign-in failures leaving the CLI waiting without an error.
|
||||
- Fixed first-time startup on Linux and BSD when no system keyring is available.
|
||||
- Improved tray menu behavior on Linux and BSD.
|
||||
- Added clearer results when manually checking for updates.
|
||||
- Improved desktop dialogs, settings, keyboard focus, and Linux window controls.
|
||||
|
||||
## 3.0.0
|
||||
|
||||
### Added
|
||||
|
||||
@@ -25,10 +25,12 @@ 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 }
|
||||
url = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
|
||||
webkit2gtk = { version = "2", optional = true }
|
||||
gtk = { version = "0.18", optional = true }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = { version = "0.6", optional = true }
|
||||
@@ -36,6 +38,7 @@ objc2 = { version = "0.6", optional = true }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "block2"], optional = true }
|
||||
objc2-foundation = { version = "0.3", optional = true }
|
||||
objc2-web-kit = { version = "0.3", optional = true }
|
||||
objc2-security = { version = "0.3", default-features = false, features = ["std", "SecBase", "SecTrust", "SecCertificate"], optional = true }
|
||||
|
||||
[features]
|
||||
browser-auth = [
|
||||
@@ -54,11 +57,36 @@ webview-auth = [
|
||||
"dep:regex",
|
||||
"dep:tokio-util",
|
||||
"dep:html-escape",
|
||||
"dep:url",
|
||||
"dep:gtk",
|
||||
"dep:webkit2gtk",
|
||||
"dep:block2",
|
||||
"dep:objc2",
|
||||
"dep:objc2-foundation",
|
||||
"dep:objc2-web-kit",
|
||||
"dep:objc2-security",
|
||||
"objc2-app-kit/NSAlert",
|
||||
"dep:objc2-app-kit",
|
||||
"objc2-app-kit/NSView",
|
||||
"objc2-app-kit/NSText",
|
||||
"objc2-app-kit/NSTextView",
|
||||
"objc2-app-kit/NSTextContainer",
|
||||
"objc2-app-kit/NSParagraphStyle",
|
||||
"objc2-app-kit/NSFont",
|
||||
"objc2-app-kit/NSBox",
|
||||
"objc2-app-kit/NSButton",
|
||||
"objc2-app-kit/NSButtonCell",
|
||||
"objc2-app-kit/NSEvent",
|
||||
"objc2-app-kit/NSTextField",
|
||||
"objc2-app-kit/NSProgressIndicator",
|
||||
"objc2-app-kit/NSColor",
|
||||
"objc2-app-kit/NSResponder",
|
||||
"objc2-app-kit/NSAccessibilityProtocols",
|
||||
"objc2-app-kit/NSWindow",
|
||||
"objc2-app-kit/NSToolbar",
|
||||
"objc2-app-kit/NSToolbarItem",
|
||||
"objc2-app-kit/NSLayoutAnchor",
|
||||
"objc2-app-kit/NSLayoutConstraint",
|
||||
]
|
||||
release-devtools = ["webview-auth", "tauri/devtools"]
|
||||
|
||||
|
||||
@@ -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());
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -23,7 +26,7 @@ impl<'a> BrowserAuthenticator<'a> {
|
||||
}
|
||||
|
||||
pub async fn authenticate(&self) -> anyhow::Result<SamlAuthData> {
|
||||
let callback_receiver = if is_remote_browser(self.browser) {
|
||||
let callback_receiver = if is_manual_browser(self.browser) {
|
||||
None
|
||||
} else {
|
||||
ensure_auth_callback_handler()?;
|
||||
@@ -34,11 +37,11 @@ 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);
|
||||
});
|
||||
|
||||
if is_remote_browser(self.browser) {
|
||||
if is_manual_browser(self.browser) {
|
||||
info!(
|
||||
r#"
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -65,7 +69,7 @@ Note that the URL is only valid for a single use.
|
||||
}
|
||||
|
||||
async fn determine_addr(&self) -> anyhow::Result<SocketAddr> {
|
||||
if is_remote_browser(self.browser) {
|
||||
if is_manual_browser(self.browser) {
|
||||
let local_ip = match self.browser_listen {
|
||||
Some(ip) => ip,
|
||||
None => detect_local_ip().await?,
|
||||
@@ -77,8 +81,8 @@ Note that the URL is only valid for a single use.
|
||||
}
|
||||
}
|
||||
|
||||
fn is_remote_browser(browser: &str) -> bool {
|
||||
browser.eq_ignore_ascii_case("remote")
|
||||
fn is_manual_browser(browser: &str) -> bool {
|
||||
browser.eq_ignore_ascii_case("manual") || browser.eq_ignore_ascii_case("remote")
|
||||
}
|
||||
|
||||
/// Detect the local IP address by creating a UDP socket and connecting to an external address
|
||||
@@ -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)?;
|
||||
|
||||
@@ -113,20 +120,24 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_remote_remains_auth_specific() {
|
||||
assert!(is_remote_browser("remote"));
|
||||
assert!(is_remote_browser("REMOTE"));
|
||||
assert_ne!(LaunchBrowser::from_name("remote"), LaunchBrowser::Default);
|
||||
fn browser_manual_remains_auth_specific() {
|
||||
assert!(is_manual_browser("manual"));
|
||||
assert!(is_manual_browser("MANUAL"));
|
||||
assert!(is_manual_browser("remote"));
|
||||
assert!(is_manual_browser("REMOTE"));
|
||||
assert_ne!(LaunchBrowser::from_name("manual"), LaunchBrowser::Default);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_browser_uses_explicit_listen_address() {
|
||||
async fn manual_browser_uses_explicit_listen_address() {
|
||||
let listen_ip = "192.168.107.15".parse().unwrap();
|
||||
let authenticator = BrowserAuthenticator::new("request", "remote", Some(listen_ip));
|
||||
for browser in ["manual", "MANUAL", "remote", "REMOTE"] {
|
||||
let authenticator = BrowserAuthenticator::new("request", browser, Some(listen_ip));
|
||||
|
||||
assert_eq!(
|
||||
authenticator.determine_addr().await.unwrap(),
|
||||
SocketAddr::new(listen_ip, 0)
|
||||
);
|
||||
assert_eq!(
|
||||
authenticator.determine_addr().await.unwrap(),
|
||||
SocketAddr::new(listen_ip, 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
mod address_bar;
|
||||
mod auth_messenger;
|
||||
mod recovery;
|
||||
mod tls;
|
||||
mod webview_auth;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
pub const TOOLBAR_HEIGHT: f64 = 40.0;
|
||||
pub const LOADING_ADDRESS: &str = "Loading sign-in page…";
|
||||
|
||||
/// Display web addresses with query strings and fragments, but without credentials.
|
||||
pub fn display_address(uri: Option<&str>) -> String {
|
||||
let Some(mut url) = uri.and_then(|uri| url::Url::parse(uri).ok()) else {
|
||||
return LOADING_ADDRESS.to_string();
|
||||
};
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||
return LOADING_ADDRESS.to_string();
|
||||
}
|
||||
|
||||
let _ = url.set_username("");
|
||||
let _ = url.set_password(None);
|
||||
url.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hides_credentials_but_preserves_query_and_fragment() {
|
||||
assert_eq!(
|
||||
display_address(Some(
|
||||
"https://user:[email protected]:8443/saml?SAMLRequest=secret#token"
|
||||
)),
|
||||
"https://login.example:8443/saml?SAMLRequest=secret#token"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_scheme_host_and_encoded_path() {
|
||||
assert_eq!(
|
||||
display_address(Some("http://example.com/a%20b")),
|
||||
"http://example.com/a%20b"
|
||||
);
|
||||
assert_eq!(display_address(Some("https://[::1]:8443/")), "https://[::1]:8443/");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_placeholder_for_local_pages_and_callbacks() {
|
||||
for uri in [
|
||||
None,
|
||||
Some(""),
|
||||
Some("invalid"),
|
||||
Some("about:blank"),
|
||||
Some("data:text/html,secret"),
|
||||
Some("globalprotectcallback:secret"),
|
||||
] {
|
||||
assert_eq!(display_address(uri), LOADING_ADDRESS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
use super::tls::TlsFailure;
|
||||
use anyhow::bail;
|
||||
use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
|
||||
use log::{error, info};
|
||||
use regex::Regex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use tokio::sync::{RwLock, mpsc};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
@@ -14,36 +16,30 @@ pub(crate) enum AuthDataLocation {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum AuthError {
|
||||
/// Failed to load page due to TLS error
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
TlsError,
|
||||
/// 1. Found auth data in headers/body but it's invalid
|
||||
/// 2. Loaded an empty page, failed to load page. etc.
|
||||
/// A certificate or TLS handshake failure in the native webview.
|
||||
Tls(TlsFailure),
|
||||
/// The authentication service returned a temporary failure.
|
||||
TemporarilyUnavailable,
|
||||
/// A sign-in request could not be loaded.
|
||||
LoadFailed(anyhow::Error),
|
||||
/// Found auth data in headers/body but it's invalid.
|
||||
Invalid(anyhow::Error, AuthDataLocation),
|
||||
/// No auth data found in headers/body
|
||||
NotFound(AuthDataLocation),
|
||||
}
|
||||
|
||||
impl AuthError {
|
||||
pub fn invalid_from_body(err: anyhow::Error) -> Self {
|
||||
Self::Invalid(err, AuthDataLocation::Body)
|
||||
}
|
||||
|
||||
pub fn not_found_in_body() -> Self {
|
||||
Self::NotFound(AuthDataLocation::Body)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
impl AuthError {
|
||||
pub fn not_found_in_headers() -> Self {
|
||||
Self::NotFound(AuthDataLocation::Headers)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum AuthEvent {
|
||||
Data(SamlAuthData, AuthDataLocation),
|
||||
Error(AuthError),
|
||||
Data(u64, SamlAuthData, AuthDataLocation),
|
||||
Error(u64, AuthError),
|
||||
NoAuthData(u64, AuthDataLocation),
|
||||
PageLoaded(u64),
|
||||
Retry,
|
||||
RequestTlsException,
|
||||
TlsAccepted(u64),
|
||||
RaiseWindow,
|
||||
Close,
|
||||
}
|
||||
@@ -52,6 +48,7 @@ pub struct AuthMessenger {
|
||||
tx: mpsc::UnboundedSender<AuthEvent>,
|
||||
rx: RwLock<mpsc::UnboundedReceiver<AuthEvent>>,
|
||||
raise_window_cancel_token: RwLock<Option<CancellationToken>>,
|
||||
generation: AtomicU64,
|
||||
}
|
||||
|
||||
impl AuthMessenger {
|
||||
@@ -62,6 +59,7 @@ impl AuthMessenger {
|
||||
tx,
|
||||
rx: RwLock::new(rx),
|
||||
raise_window_cancel_token: Default::default(),
|
||||
generation: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,12 +77,12 @@ impl AuthMessenger {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_auth_error(&self, err: AuthError) {
|
||||
self.send_auth_event(AuthEvent::Error(err));
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn send_auth_data(&self, data: SamlAuthData, location: AuthDataLocation) {
|
||||
self.send_auth_event(AuthEvent::Data(data, location));
|
||||
pub fn begin_attempt(&self) {
|
||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn schedule_raise_window(&self, delay: u64) {
|
||||
@@ -132,9 +130,9 @@ impl AuthMessenger {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_from_html(&self, html: &str) {
|
||||
pub fn read_from_html(&self, html: &str, generation: u64) {
|
||||
if html.contains("Temporarily Unavailable") {
|
||||
return self.send_auth_error(AuthError::invalid_from_body(anyhow::anyhow!("Temporarily Unavailable")));
|
||||
return self.send_auth_event(AuthEvent::Error(generation, AuthError::TemporarilyUnavailable));
|
||||
}
|
||||
|
||||
let auth_result = SamlAuthData::from_html(html).or_else(|err| {
|
||||
@@ -149,18 +147,20 @@ impl AuthMessenger {
|
||||
});
|
||||
|
||||
match auth_result {
|
||||
Ok(data) => self.send_auth_data(data, AuthDataLocation::Body),
|
||||
Err(AuthDataParseError::NotFound) => self.send_auth_error(AuthError::not_found_in_body()),
|
||||
Err(err) => self.send_auth_error(AuthError::invalid_from_body(err.into())),
|
||||
Ok(data) => self.send_auth_event(AuthEvent::Data(generation, data, AuthDataLocation::Body)),
|
||||
Err(AuthDataParseError::NotFound) => {
|
||||
self.send_auth_event(AuthEvent::NoAuthData(generation, AuthDataLocation::Body))
|
||||
}
|
||||
Err(err) => self.send_auth_event(AuthEvent::Error(generation, AuthError::invalid_from_body(err.into()))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader) {
|
||||
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader, generation: u64) {
|
||||
use log::warn;
|
||||
|
||||
let Some(status) = auth_response.get_header("saml-auth-status") else {
|
||||
return self.send_auth_error(AuthError::not_found_in_headers());
|
||||
return self.send_auth_event(AuthEvent::NoAuthData(generation, AuthDataLocation::Headers));
|
||||
};
|
||||
|
||||
// Do not send auth error when reading from headers, as the html body may contain the auth data
|
||||
@@ -174,7 +174,7 @@ impl AuthMessenger {
|
||||
let portal_userauthcookie = auth_response.get_header("portal-userauthcookie");
|
||||
|
||||
match SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie) {
|
||||
Ok(auth_data) => self.send_auth_data(auth_data, AuthDataLocation::Headers),
|
||||
Ok(auth_data) => self.send_auth_event(AuthEvent::Data(generation, auth_data, AuthDataLocation::Headers)),
|
||||
Err(err) => {
|
||||
warn!("Failed to read auth data from headers: {}", err);
|
||||
}
|
||||
@@ -193,6 +193,43 @@ fn extract_gpcallback(html: &str) -> Option<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_sign_in_page_is_an_observation_with_its_original_generation() {
|
||||
let messenger = AuthMessenger::new();
|
||||
messenger.read_from_html("<html><h1>Sign in</h1></html>", 7);
|
||||
assert!(matches!(
|
||||
messenger.subscribe().await.unwrap(),
|
||||
AuthEvent::NoAuthData(7, AuthDataLocation::Body)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn distinguishes_temporary_failure_from_rejected_authentication() {
|
||||
let messenger = AuthMessenger::new();
|
||||
messenger.read_from_html("<html>Temporarily Unavailable</html>", 0);
|
||||
assert!(matches!(
|
||||
messenger.subscribe().await.unwrap(),
|
||||
AuthEvent::Error(0, AuthError::TemporarilyUnavailable)
|
||||
));
|
||||
messenger.read_from_html("<saml-auth-status>0</saml-auth-status>", 0);
|
||||
assert!(matches!(
|
||||
messenger.subscribe().await.unwrap(),
|
||||
AuthEvent::Error(0, AuthError::Invalid(..))
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn html_callbacks_keep_the_generation_that_started_the_read() {
|
||||
let messenger = AuthMessenger::new();
|
||||
let generation = messenger.generation();
|
||||
messenger.begin_attempt();
|
||||
messenger.read_from_html("<html>Temporarily Unavailable</html>", generation);
|
||||
match messenger.subscribe().await.unwrap() {
|
||||
AuthEvent::Error(generation, _) => assert_ne!(generation, messenger.generation()),
|
||||
_ => panic!("Expected an authentication error"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_gpcallback_some() {
|
||||
let html = r#"
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use std::sync::Arc;
|
||||
use std::{cell::Cell, rc::Rc, sync::Arc};
|
||||
|
||||
use anyhow::bail;
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::utils::redact::redact_uri;
|
||||
use log::warn;
|
||||
use gtk::prelude::*;
|
||||
use log::{info, warn};
|
||||
use tauri::webview::PlatformWebview;
|
||||
use webkit2gtk::{
|
||||
LoadEvent, SettingsExt, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt,
|
||||
@@ -10,10 +11,26 @@ use webkit2gtk::{
|
||||
};
|
||||
|
||||
use super::{
|
||||
auth_messenger::AuthError,
|
||||
auth_messenger::{AuthError, AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
webview_auth::{GetHeader, PlatformWebviewExt},
|
||||
};
|
||||
|
||||
#[path = "gtk_recovery.rs"]
|
||||
mod recovery_row;
|
||||
#[path = "gtk_tls.rs"]
|
||||
mod tls;
|
||||
|
||||
fn action_button(label: &str) -> anyhow::Result<gtk::Button> {
|
||||
let button = gtk::Button::with_label(label);
|
||||
let spacing = gtk::CssProvider::new();
|
||||
spacing.load_from_data(b"button { padding: 4px 12px; }")?;
|
||||
button
|
||||
.style_context()
|
||||
.add_provider(&spacing, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
|
||||
Ok(button)
|
||||
}
|
||||
|
||||
impl GetHeader for WebResource {
|
||||
fn get_header(&self, key: &str) -> Option<String> {
|
||||
self
|
||||
@@ -25,6 +42,62 @@ impl GetHeader for WebResource {
|
||||
}
|
||||
|
||||
impl PlatformWebviewExt for PlatformWebview {
|
||||
fn install_auth_controls(&self, window: &tauri::WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
use super::address_bar::display_address;
|
||||
|
||||
let entry = gtk::Entry::new();
|
||||
entry.set_editable(false);
|
||||
entry.set_can_focus(true);
|
||||
entry.set_direction(gtk::TextDirection::Ltr);
|
||||
entry.set_text(&display_address(self.inner().uri().as_deref()));
|
||||
let header = gtk::Box::new(gtk::Orientation::Vertical, 4);
|
||||
header.style_context().add_class(gtk::STYLE_CLASS_TOOLBAR);
|
||||
header.style_context().add_class(gtk::STYLE_CLASS_PRIMARY_TOOLBAR);
|
||||
header.style_context().add_class("gpauth-header");
|
||||
// One native header owns the outer padding and the gap between its rows.
|
||||
// Keep theme colors, borders, focus styling, and natural button sizes.
|
||||
let spacing = gtk::CssProvider::new();
|
||||
spacing.load_from_data(b".gpauth-header { padding: 6px; } entry { min-height: 22px; padding: 2px 6px; }")?;
|
||||
entry
|
||||
.style_context()
|
||||
.add_provider(&spacing, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
|
||||
header
|
||||
.style_context()
|
||||
.add_provider(&spacing, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
|
||||
header.pack_start(&entry, false, false, 0);
|
||||
header.show_all();
|
||||
recovery_row::install(&self.inner(), &header, Arc::clone(&messenger))?;
|
||||
let container = window.default_vbox()?;
|
||||
container.pack_start(&header, false, false, 0);
|
||||
container.reorder_child(&header, 0);
|
||||
let separator = gtk::Separator::new(gtk::Orientation::Horizontal);
|
||||
container.pack_start(&separator, false, false, 0);
|
||||
container.reorder_child(&separator, 1);
|
||||
separator.show();
|
||||
|
||||
// Observe the top-level URI, including redirects and history API changes.
|
||||
let address = entry.clone();
|
||||
self.inner().connect_uri_notify(move |webview| {
|
||||
address.set_text(&display_address(webview.uri().as_deref()));
|
||||
address.set_position(0);
|
||||
});
|
||||
tls::install(&self.inner(), Arc::clone(&messenger));
|
||||
install_navigation_observers(&self.inner(), messenger, entry);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
recovery_row::update(&self.inner(), status)
|
||||
}
|
||||
|
||||
fn stop_loading(&self) {
|
||||
self.inner().stop_loading();
|
||||
}
|
||||
|
||||
fn confirm_tls_exception(&self) -> anyhow::Result<()> {
|
||||
tls::confirm(&self.inner())
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
|
||||
if let Some(manager) = self.inner().website_data_manager() {
|
||||
manager.set_tls_errors_policy(TLSErrorsPolicy::Ignore);
|
||||
@@ -34,7 +107,7 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
}
|
||||
|
||||
fn user_agent(&self) -> anyhow::Result<String> {
|
||||
let Some(settings) = self.inner().settings() else {
|
||||
let Some(settings) = WebViewExt::settings(&self.inner()) else {
|
||||
bail!("Failed to get webview settings");
|
||||
};
|
||||
|
||||
@@ -45,7 +118,7 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
}
|
||||
|
||||
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> {
|
||||
let Some(settings) = self.inner().settings() else {
|
||||
let Some(settings) = WebViewExt::settings(&self.inner()) else {
|
||||
bail!("Failed to get webview settings");
|
||||
};
|
||||
|
||||
@@ -54,72 +127,188 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
}
|
||||
|
||||
fn load_url(&self, url: &str) -> anyhow::Result<()> {
|
||||
prepare_navigation(&self.inner())?;
|
||||
self.inner().load_uri(url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_html(&self, html: &str) -> anyhow::Result<()> {
|
||||
prepare_navigation(&self.inner())?;
|
||||
self.inner().load_html(html, None);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>) {
|
||||
let script = "document.documentElement.outerHTML";
|
||||
self
|
||||
.inner()
|
||||
.evaluate_javascript(script, None, None, Cancellable::NONE, move |result| match result {
|
||||
Ok(value) => callback(Ok(value.to_string())),
|
||||
Err(err) => callback(Err(anyhow::anyhow!(err))),
|
||||
});
|
||||
const NAVIGATION_KEY: &str = "gpauth-navigation";
|
||||
|
||||
#[derive(Default)]
|
||||
struct NavigationAttempts {
|
||||
pending: Cell<Option<u64>>,
|
||||
current: Cell<Option<u64>>,
|
||||
}
|
||||
|
||||
impl NavigationAttempts {
|
||||
fn started(&self, generation: u64) {
|
||||
self.current.set(Some(self.pending.take().unwrap_or(generation)));
|
||||
}
|
||||
}
|
||||
|
||||
pub trait PlatformWebviewOnResponse {
|
||||
fn on_response(&self, callback: Box<dyn Fn(anyhow::Result<WebResource, AuthError>) + 'static>);
|
||||
struct NavigationObserver {
|
||||
attempts: NavigationAttempts,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
}
|
||||
|
||||
impl PlatformWebviewOnResponse for PlatformWebview {
|
||||
fn on_response(&self, callback: Box<dyn Fn(anyhow::Result<WebResource, AuthError>) + 'static>) {
|
||||
let wv = self.inner();
|
||||
let callback = Arc::new(callback);
|
||||
let callback_clone = Arc::clone(&callback);
|
||||
fn prepare_navigation(webview: &webkit2gtk::WebView) -> anyhow::Result<()> {
|
||||
let observer =
|
||||
unsafe { webview.data::<Rc<NavigationObserver>>(NAVIGATION_KEY) }.context("Navigation observer is unavailable")?;
|
||||
let observer = unsafe { observer.as_ref() };
|
||||
observer.attempts.pending.set(Some(observer.messenger.generation()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
wv.connect_load_changed(move |wv, event| {
|
||||
if event != LoadEvent::Finished {
|
||||
return;
|
||||
fn install_navigation_observers(webview: &webkit2gtk::WebView, messenger: Arc<AuthMessenger>, address: gtk::Entry) {
|
||||
let observer = Rc::new(NavigationObserver {
|
||||
attempts: NavigationAttempts::default(),
|
||||
messenger,
|
||||
});
|
||||
unsafe {
|
||||
webview.set_data(NAVIGATION_KEY, Rc::clone(&observer));
|
||||
}
|
||||
let loading = Rc::clone(&observer);
|
||||
webview.connect_load_changed(move |webview, event| {
|
||||
match event {
|
||||
LoadEvent::Started => {
|
||||
loading.attempts.started(loading.messenger.generation());
|
||||
loading.messenger.cancel_raise_window();
|
||||
}
|
||||
|
||||
let Some(web_resource) = wv.main_resource() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let uri = web_resource.uri().unwrap_or("".into());
|
||||
if uri.is_empty() {
|
||||
callback_clone(Err(AuthError::invalid_from_body(anyhow::anyhow!("Empty URI"))));
|
||||
} else {
|
||||
callback_clone(Ok(web_resource));
|
||||
LoadEvent::Committed => {
|
||||
if let Some(generation) = loading.attempts.current.get() {
|
||||
info!(
|
||||
"Started loading page: {}",
|
||||
redact_uri(webview.uri().as_deref().unwrap_or_default())
|
||||
);
|
||||
read_navigation_html(webview, Arc::clone(&loading.messenger), generation);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
wv.connect_load_failed_with_tls_errors(move |_wv, uri, cert, err| {
|
||||
let redacted_uri = redact_uri(uri);
|
||||
warn!(
|
||||
"Failed to load uri: {} with error: {}, cert: {}",
|
||||
redacted_uri, err, cert
|
||||
);
|
||||
|
||||
callback(Err(AuthError::TlsError));
|
||||
true
|
||||
});
|
||||
|
||||
wv.connect_load_failed(move |_wv, _event, uri, err| {
|
||||
let redacted_uri = redact_uri(uri);
|
||||
if !uri.starts_with("globalprotectcallback:") {
|
||||
warn!("Failed to load uri: {} with error: {}", redacted_uri, err);
|
||||
LoadEvent::Finished => {
|
||||
// WebKitGTK finishes a cancelled load before starting its replacement.
|
||||
// Retain that load's generation instead of relabeling it at callback time.
|
||||
let Some(generation) = loading.attempts.current.take() else {
|
||||
return;
|
||||
};
|
||||
info!(
|
||||
"Finished loading page: {}",
|
||||
redact_uri(webview.uri().as_deref().unwrap_or_default())
|
||||
);
|
||||
read_navigation_html(webview, Arc::clone(&loading.messenger), generation);
|
||||
if let Some(resource) = webview.main_resource() {
|
||||
let uri = resource.uri().unwrap_or_default();
|
||||
if uri.is_empty() {
|
||||
loading.messenger.send_auth_event(AuthEvent::Error(
|
||||
generation,
|
||||
AuthError::invalid_from_body(anyhow::anyhow!("Empty URI")),
|
||||
));
|
||||
} else {
|
||||
loading.messenger.read_from_response(&resource, generation);
|
||||
}
|
||||
}
|
||||
loading.messenger.send_auth_event(AuthEvent::PageLoaded(generation));
|
||||
}
|
||||
// NOTE: Don't send error here, since load_changed event will be triggered after this
|
||||
// true to stop other handlers from being invoked for the event. false to propagate the event further.
|
||||
true
|
||||
});
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
|
||||
let tls = Rc::clone(&observer);
|
||||
let tls_address = address.clone();
|
||||
webview.connect_load_failed_with_tls_errors(move |webview, uri, cert, err| {
|
||||
warn!(
|
||||
"Failed to load uri: {} with error: {}, cert: {}",
|
||||
redact_uri(uri),
|
||||
err,
|
||||
cert
|
||||
);
|
||||
if let Some(generation) = tls.attempts.current.take() {
|
||||
if generation != tls.messenger.generation() {
|
||||
return true;
|
||||
}
|
||||
show_failed_address(&tls_address, uri);
|
||||
let failure = tls::record_failure(webview, uri, cert, err, generation);
|
||||
tls
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::Error(generation, AuthError::Tls(failure)));
|
||||
}
|
||||
true
|
||||
});
|
||||
|
||||
webview.connect_load_failed(move |_webview, _event, uri, err| {
|
||||
if let Some(generation) = observer.attempts.current.take() {
|
||||
if generation != observer.messenger.generation() {
|
||||
return true;
|
||||
}
|
||||
if !uri.starts_with("globalprotectcallback:") && !err.matches(webkit2gtk::NetworkError::Cancelled) {
|
||||
warn!("Failed to load uri: {} with error: {}", redact_uri(uri), err);
|
||||
show_failed_address(&address, uri);
|
||||
let error = if err.kind::<webkit2gtk::gio::TlsError>().is_some() {
|
||||
AuthError::Tls(super::tls::TlsFailure {
|
||||
host: url::Url::parse(uri)
|
||||
.ok()
|
||||
.and_then(|uri| uri.host_str().map(str::to_owned))
|
||||
.unwrap_or_default(),
|
||||
reason: super::tls::TlsFailureReason::Handshake,
|
||||
can_continue: false,
|
||||
})
|
||||
} else {
|
||||
AuthError::LoadFailed(anyhow::anyhow!("{}", err))
|
||||
};
|
||||
observer.messenger.send_auth_event(AuthEvent::Error(generation, error));
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
// A failed provisional load may leave WebView.uri unset.
|
||||
fn show_failed_address(entry: >k::Entry, uri: &str) {
|
||||
entry.set_text(&super::address_bar::display_address(Some(uri)));
|
||||
entry.set_position(0);
|
||||
}
|
||||
|
||||
fn read_navigation_html(webview: &webkit2gtk::WebView, messenger: Arc<AuthMessenger>, generation: u64) {
|
||||
webview.evaluate_javascript(
|
||||
"document.documentElement.outerHTML",
|
||||
None,
|
||||
None,
|
||||
Cancellable::NONE,
|
||||
move |result| match result {
|
||||
Ok(value) => messenger.read_from_html(&value.to_string(), generation),
|
||||
Err(err) => warn!("Failed to get html: {}", err),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::NavigationAttempts;
|
||||
|
||||
#[test]
|
||||
fn cancelled_load_keeps_its_generation_until_replacement_starts() {
|
||||
let attempts = NavigationAttempts::default();
|
||||
attempts.started(0);
|
||||
attempts.pending.set(Some(2));
|
||||
// The previous load's cancellation/finish arrives after retry generation advances.
|
||||
assert_eq!(attempts.current.take(), Some(0));
|
||||
attempts.started(2);
|
||||
assert_eq!(attempts.current.take(), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requested_generation_survives_attempt_changes_before_native_start() {
|
||||
let attempts = NavigationAttempts::default();
|
||||
attempts.pending.set(Some(2));
|
||||
attempts.started(3);
|
||||
assert_eq!(attempts.current.take(), Some(2));
|
||||
// User navigation after that load starts in the current attempt.
|
||||
attempts.started(3);
|
||||
assert_eq!(attempts.current.take(), Some(3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context;
|
||||
use gtk::prelude::*;
|
||||
use webkit2gtk::WebView;
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
};
|
||||
|
||||
const CONTROLS_KEY: &str = "gpauth-recovery-controls";
|
||||
|
||||
struct RecoveryRow {
|
||||
row: gtk::Box,
|
||||
spinner: gtk::Spinner,
|
||||
label: gtk::Label,
|
||||
retry: gtk::Button,
|
||||
proceed: gtk::Button,
|
||||
cancel: gtk::Button,
|
||||
detail: gtk::Label,
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WebView, header: >k::Box, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let row = gtk::Box::new(gtk::Orientation::Horizontal, 8);
|
||||
// Align status text with the address text's 6px inset and native 1px border.
|
||||
row.set_margin_start(7);
|
||||
let spinner = gtk::Spinner::new();
|
||||
spinner.set_valign(gtk::Align::Center);
|
||||
let label = gtk::Label::new(None);
|
||||
label.set_xalign(0.0);
|
||||
label.set_ellipsize(gtk::pango::EllipsizeMode::End);
|
||||
let detail = gtk::Label::new(None);
|
||||
detail.set_xalign(0.0);
|
||||
detail.set_ellipsize(gtk::pango::EllipsizeMode::End);
|
||||
detail.style_context().add_class("dim-label");
|
||||
detail.set_no_show_all(true);
|
||||
let copy = gtk::Box::new(gtk::Orientation::Vertical, 2);
|
||||
copy.set_valign(gtk::Align::Center);
|
||||
copy.pack_start(&label, false, false, 0);
|
||||
copy.pack_start(&detail, false, false, 0);
|
||||
copy.show();
|
||||
let retry = super::action_button("Try Again")?;
|
||||
retry.set_valign(gtk::Align::Center);
|
||||
let proceed = super::action_button("Continue Anyway…")?;
|
||||
proceed.set_valign(gtk::Align::Center);
|
||||
proceed.set_no_show_all(true);
|
||||
let cancel = super::action_button("Cancel")?;
|
||||
cancel.set_valign(gtk::Align::Center);
|
||||
// Showing or raising the window must not override recovery-state visibility.
|
||||
row.set_no_show_all(true);
|
||||
spinner.set_no_show_all(true);
|
||||
retry.set_no_show_all(true);
|
||||
label.show();
|
||||
cancel.set_no_show_all(true);
|
||||
let retry_messenger = Arc::clone(&messenger);
|
||||
retry.connect_clicked(move |_| retry_messenger.send_auth_event(AuthEvent::Retry));
|
||||
let proceed_messenger = Arc::clone(&messenger);
|
||||
proceed.connect_clicked(move |_| proceed_messenger.send_auth_event(AuthEvent::RequestTlsException));
|
||||
cancel.connect_clicked(move |_| messenger.send_auth_event(AuthEvent::Close));
|
||||
row.pack_start(&spinner, false, false, 0);
|
||||
row.pack_start(©, true, true, 0);
|
||||
row.pack_start(&retry, false, false, 0);
|
||||
row.pack_start(&proceed, false, false, 0);
|
||||
row.pack_start(&cancel, false, false, 0);
|
||||
header.pack_start(&row, false, false, 0);
|
||||
// The WebView owns the controls for exactly its native lifetime, on the GTK thread.
|
||||
unsafe {
|
||||
webview.set_data(
|
||||
CONTROLS_KEY,
|
||||
RecoveryRow {
|
||||
row,
|
||||
spinner,
|
||||
label,
|
||||
retry,
|
||||
proceed,
|
||||
cancel,
|
||||
detail,
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn update(webview: &WebView, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
let controls = unsafe { webview.data::<RecoveryRow>(CONTROLS_KEY) }.context("Recovery controls are unavailable")?;
|
||||
let controls = unsafe { controls.as_ref() };
|
||||
controls.label.set_text(status.message());
|
||||
controls.detail.set_text(status.detail());
|
||||
controls.detail.set_visible(!status.detail().is_empty());
|
||||
controls.retry.set_visible(status.can_retry());
|
||||
controls.proceed.set_visible(status.can_continue());
|
||||
controls.cancel.set_visible(status.blocks_page());
|
||||
controls.spinner.set_visible(status.is_busy());
|
||||
if status.is_busy() {
|
||||
controls.spinner.start();
|
||||
} else {
|
||||
controls.spinner.stop();
|
||||
}
|
||||
controls.row.set_visible(status != RecoveryStatus::Hidden);
|
||||
webview.set_sensitive(!status.blocks_page());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use gtk::prelude::*;
|
||||
use webkit2gtk::{
|
||||
WebContextExt, WebView, WebViewExt,
|
||||
gio::{TlsCertificate, TlsCertificateFlags},
|
||||
};
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthEvent, AuthMessenger},
|
||||
tls::{TlsFailure, TlsFailureReason},
|
||||
};
|
||||
|
||||
const TLS_KEY: &str = "gpauth-tls";
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PendingCertificate {
|
||||
generation: u64,
|
||||
certificate: TlsCertificate,
|
||||
failure: TlsFailure,
|
||||
}
|
||||
|
||||
struct TlsState {
|
||||
pending: RefCell<Option<PendingCertificate>>,
|
||||
confirmation_open: Cell<bool>,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WebView, messenger: Arc<AuthMessenger>) {
|
||||
unsafe {
|
||||
webview.set_data(
|
||||
TLS_KEY,
|
||||
Rc::new(TlsState {
|
||||
pending: RefCell::new(None),
|
||||
confirmation_open: Cell::new(false),
|
||||
messenger,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn state(webview: &WebView) -> anyhow::Result<Rc<TlsState>> {
|
||||
let data = unsafe { webview.data::<Rc<TlsState>>(TLS_KEY) }.context("TLS controls are unavailable")?;
|
||||
Ok(unsafe { data.as_ref() }.clone())
|
||||
}
|
||||
|
||||
pub(super) fn record_failure(
|
||||
webview: &WebView,
|
||||
uri: &str,
|
||||
certificate: &TlsCertificate,
|
||||
flags: TlsCertificateFlags,
|
||||
generation: u64,
|
||||
) -> TlsFailure {
|
||||
let reason = if flags.contains(TlsCertificateFlags::EXPIRED) {
|
||||
TlsFailureReason::Expired
|
||||
} else if flags.contains(TlsCertificateFlags::NOT_ACTIVATED) {
|
||||
TlsFailureReason::NotYetValid
|
||||
} else if flags.contains(TlsCertificateFlags::BAD_IDENTITY) {
|
||||
TlsFailureReason::HostnameMismatch
|
||||
} else if flags.contains(TlsCertificateFlags::UNKNOWN_CA) {
|
||||
TlsFailureReason::Untrusted
|
||||
} else {
|
||||
TlsFailureReason::InvalidCertificate
|
||||
};
|
||||
let host = url::Url::parse(uri)
|
||||
.ok()
|
||||
.filter(|uri| uri.scheme() == "https")
|
||||
.and_then(|uri| uri.host_str().map(str::to_owned));
|
||||
let failure = TlsFailure {
|
||||
host: host.clone().unwrap_or_default(),
|
||||
reason,
|
||||
can_continue: reason.is_certificate_error() && host.is_some(),
|
||||
};
|
||||
if let Ok(state) = state(webview) {
|
||||
*state.pending.borrow_mut() = host.map(|_| PendingCertificate {
|
||||
generation,
|
||||
certificate: certificate.clone(),
|
||||
failure: failure.clone(),
|
||||
});
|
||||
}
|
||||
failure
|
||||
}
|
||||
|
||||
pub(super) fn confirm(webview: &WebView) -> anyhow::Result<()> {
|
||||
let state = state(webview)?;
|
||||
let pending = state
|
||||
.pending
|
||||
.borrow()
|
||||
.clone()
|
||||
.context("No certificate error is awaiting confirmation")?;
|
||||
if pending.generation != state.messenger.generation() || state.confirmation_open.get() {
|
||||
return Ok(());
|
||||
}
|
||||
let parent = webview
|
||||
.toplevel()
|
||||
.and_then(|widget| widget.downcast::<gtk::Window>().ok())
|
||||
.context("Auth window is unavailable")?;
|
||||
let dialog = gtk::Dialog::builder()
|
||||
.transient_for(&parent)
|
||||
.modal(true)
|
||||
.destroy_with_parent(true)
|
||||
.title("Certificate Warning")
|
||||
.use_header_bar(0)
|
||||
.resizable(false)
|
||||
.build();
|
||||
let content = dialog.content_area();
|
||||
content.set_spacing(12);
|
||||
content.set_margin_top(18);
|
||||
content.set_margin_bottom(18);
|
||||
content.set_margin_start(18);
|
||||
content.set_margin_end(18);
|
||||
let title = gtk::Label::new(None);
|
||||
title.set_markup(&format!(
|
||||
"<b>{}</b>",
|
||||
gtk::glib::markup_escape_text(&pending.failure.confirmation_title())
|
||||
));
|
||||
let message = gtk::Label::new(Some(&pending.failure.confirmation_message()));
|
||||
for label in [&title, &message] {
|
||||
label.set_xalign(0.0);
|
||||
label.set_line_wrap(true);
|
||||
label.set_line_wrap_mode(gtk::pango::WrapMode::WordChar);
|
||||
label.set_max_width_chars(48);
|
||||
content.pack_start(label, false, false, 0);
|
||||
}
|
||||
let actions = gtk::ButtonBox::new(gtk::Orientation::Horizontal);
|
||||
actions.set_layout(gtk::ButtonBoxStyle::End);
|
||||
actions.set_spacing(8);
|
||||
actions.set_margin_top(6);
|
||||
content.pack_start(&actions, false, false, 0);
|
||||
for (label, response) in [
|
||||
("Cancel", gtk::ResponseType::Cancel),
|
||||
("Continue Anyway", gtk::ResponseType::Accept),
|
||||
] {
|
||||
let button = super::action_button(label)?;
|
||||
button.set_can_default(true);
|
||||
let weak_dialog = dialog.downgrade();
|
||||
button.connect_clicked(move |_| {
|
||||
if let Some(dialog) = weak_dialog.upgrade() {
|
||||
dialog.response(response);
|
||||
}
|
||||
});
|
||||
actions.pack_start(&button, false, false, 0);
|
||||
actions.set_child_non_homogeneous(&button, true);
|
||||
if response == gtk::ResponseType::Cancel {
|
||||
dialog.set_default(Some(&button));
|
||||
}
|
||||
}
|
||||
state.confirmation_open.set(true);
|
||||
let weak = webview.downgrade();
|
||||
dialog.connect_response(move |dialog, response| {
|
||||
state.confirmation_open.set(false);
|
||||
if response == gtk::ResponseType::Accept && pending.generation == state.messenger.generation() {
|
||||
if let Some(webview) = weak.upgrade() {
|
||||
let current = state.pending.borrow().as_ref().is_some_and(|current| {
|
||||
current.generation == pending.generation
|
||||
&& current.certificate == pending.certificate
|
||||
&& current.failure.host == pending.failure.host
|
||||
});
|
||||
if current {
|
||||
if let Some(context) = webview.context() {
|
||||
// This single-window auth process discards its WebContext on exit.
|
||||
context.allow_tls_certificate_for_host(&pending.certificate, &pending.failure.host);
|
||||
state.pending.borrow_mut().take();
|
||||
state
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::TlsAccepted(pending.generation));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dialog.close();
|
||||
});
|
||||
dialog.show_all();
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,58 +1,149 @@
|
||||
use std::{ffi::c_void, ptr};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::HashMap,
|
||||
ffi::c_void,
|
||||
ptr,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use block2::{DynBlock, RcBlock};
|
||||
use gpapi::utils::redact::redact_uri;
|
||||
use log::{info, warn};
|
||||
use objc2::{
|
||||
DefinedClass, MainThreadOnly, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_setAssociatedObject},
|
||||
DefinedClass, MainThreadOnly, Message, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_getAssociatedObject, objc_setAssociatedObject},
|
||||
msg_send,
|
||||
rc::Retained,
|
||||
runtime::{AnyObject, ProtocolObject, Sel},
|
||||
sel,
|
||||
};
|
||||
use objc2_foundation::{
|
||||
MainThreadMarker, NSError, NSObject, NSObjectNSKeyValueCoding, NSObjectProtocol, NSString, NSURL,
|
||||
NSURLAuthenticationChallenge, NSURLAuthenticationMethodServerTrust, NSURLCredential, NSURLRequest,
|
||||
NSURLAuthenticationChallenge, NSURLAuthenticationMethodServerTrust, NSURLCredential, NSURLErrorCancelled,
|
||||
NSURLErrorDomain, NSURLErrorFailingURLErrorKey, NSURLErrorUnsupportedURL, NSURLRequest,
|
||||
NSURLSessionAuthChallengeDisposition,
|
||||
};
|
||||
use objc2_web_kit::{WKNavigationDelegate, WKWebView};
|
||||
use objc2_web_kit::{WKNavigation, WKNavigationDelegate, WKWebView};
|
||||
use tauri::webview::PlatformWebview;
|
||||
|
||||
use super::webview_auth::PlatformWebviewExt;
|
||||
use super::{
|
||||
auth_messenger::{AuthError, AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
webview_auth::PlatformWebviewExt,
|
||||
};
|
||||
|
||||
static TLS_NAVIGATION_DELEGATE_KEY: u8 = 0;
|
||||
#[path = "macos/address_bar.rs"]
|
||||
mod address_bar;
|
||||
#[path = "macos/recovery_row.rs"]
|
||||
mod recovery_row;
|
||||
#[path = "macos/tls.rs"]
|
||||
mod tls;
|
||||
|
||||
struct TlsNavigationDelegateIvars {
|
||||
static AUTH_NAVIGATION_DELEGATE_KEY: u8 = 0;
|
||||
|
||||
struct AuthNavigationDelegateIvars {
|
||||
original: Retained<ProtocolObject<dyn WKNavigationDelegate>>,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
ignore_tls_errors: Cell<bool>,
|
||||
navigations: RefCell<HashMap<usize, (Retained<WKNavigation>, u64)>>,
|
||||
tls: RefCell<tls::TlsState>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = TlsNavigationDelegateIvars]
|
||||
struct TlsNavigationDelegate;
|
||||
#[ivars = AuthNavigationDelegateIvars]
|
||||
struct AuthNavigationDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for TlsNavigationDelegate {}
|
||||
unsafe impl NSObjectProtocol for AuthNavigationDelegate {}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
unsafe impl WKNavigationDelegate for TlsNavigationDelegate {
|
||||
unsafe impl WKNavigationDelegate for AuthNavigationDelegate {
|
||||
#[unsafe(method(webView:didStartProvisionalNavigation:))]
|
||||
unsafe fn webView_didStartProvisionalNavigation(&self, webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
self.track_navigation(navigation);
|
||||
self.ivars().messenger.cancel_raise_window();
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didStartProvisionalNavigation:)) {
|
||||
unsafe { original.webView_didStartProvisionalNavigation(webview, navigation); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didCommitNavigation:))]
|
||||
unsafe fn webView_didCommitNavigation(&self, webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
if let Some(generation) = self.navigation_generation(navigation) {
|
||||
info!("Started loading page: {}", navigation_address(webview));
|
||||
read_navigation_html(webview, Arc::clone(&self.ivars().messenger), generation);
|
||||
}
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didCommitNavigation:)) {
|
||||
unsafe { original.webView_didCommitNavigation(webview, navigation); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didFinishNavigation:))]
|
||||
unsafe fn webView_didFinishNavigation(&self, webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
if let Some(generation) = self.finish_navigation(navigation) {
|
||||
info!("Finished loading page: {}", navigation_address(webview));
|
||||
read_navigation_html(webview, Arc::clone(&self.ivars().messenger), generation);
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::PageLoaded(generation));
|
||||
}
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didFinishNavigation:)) {
|
||||
unsafe { original.webView_didFinishNavigation(webview, navigation); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didFailProvisionalNavigation:withError:))]
|
||||
unsafe fn webView_didFailProvisionalNavigation_withError(&self, webview: &WKWebView, navigation: Option<&WKNavigation>, error: &NSError) {
|
||||
self.report_load_failure(webview, navigation, error);
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didFailProvisionalNavigation:withError:)) {
|
||||
unsafe { original.webView_didFailProvisionalNavigation_withError(webview, navigation, error); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didFailNavigation:withError:))]
|
||||
unsafe fn webView_didFailNavigation_withError(&self, webview: &WKWebView, navigation: Option<&WKNavigation>, error: &NSError) {
|
||||
self.report_load_failure(webview, navigation, error);
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didFailNavigation:withError:)) {
|
||||
unsafe { original.webView_didFailNavigation_withError(webview, navigation, error); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didReceiveAuthenticationChallenge:completionHandler:))]
|
||||
unsafe fn webView_didReceiveAuthenticationChallenge_completionHandler(
|
||||
&self,
|
||||
_webview: &WKWebView,
|
||||
webview: &WKWebView,
|
||||
challenge: &NSURLAuthenticationChallenge,
|
||||
completion_handler: &DynBlock<dyn Fn(NSURLSessionAuthChallengeDisposition, *mut NSURLCredential)>,
|
||||
) {
|
||||
// Preserve Wry's normal authentication challenge handling unless the caller
|
||||
// approved this certificate or requested the ignore-TLS-errors behavior.
|
||||
let protection_space = challenge.protectionSpace();
|
||||
let is_server_trust = protection_space
|
||||
.authenticationMethod()
|
||||
.isEqualToString(unsafe { NSURLAuthenticationMethodServerTrust });
|
||||
|
||||
let is_server_trust = protection_space.authenticationMethod().isEqualToString(unsafe { NSURLAuthenticationMethodServerTrust });
|
||||
let server_trust: *mut AnyObject = if is_server_trust {
|
||||
msg_send![&*protection_space, serverTrust]
|
||||
} else { ptr::null_mut() };
|
||||
let approved = std::ptr::NonNull::new(server_trust.cast::<objc2_security::SecTrust>()).is_some_and(|trust| {
|
||||
self.ivars().tls.borrow().allows(&protection_space.host().to_string(), unsafe { trust.as_ref() })
|
||||
});
|
||||
if !self.ivars().ignore_tls_errors.get() && !approved {
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didReceiveAuthenticationChallenge:completionHandler:)) {
|
||||
unsafe { original.webView_didReceiveAuthenticationChallenge_completionHandler(webview, challenge, completion_handler); }
|
||||
} else {
|
||||
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if !is_server_trust {
|
||||
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
|
||||
return;
|
||||
}
|
||||
|
||||
let server_trust: *mut AnyObject = msg_send![&*protection_space, serverTrust];
|
||||
if server_trust.is_null() {
|
||||
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
|
||||
return;
|
||||
@@ -64,7 +155,7 @@ define_class!(
|
||||
}
|
||||
}
|
||||
|
||||
impl TlsNavigationDelegate {
|
||||
impl AuthNavigationDelegate {
|
||||
#[unsafe(method(respondsToSelector:))]
|
||||
fn responds_to_selector(&self, selector: Sel) -> bool {
|
||||
let responds: bool = unsafe { msg_send![super(self), respondsToSelector: selector] };
|
||||
@@ -82,10 +173,92 @@ define_class!(
|
||||
}
|
||||
);
|
||||
|
||||
impl TlsNavigationDelegate {
|
||||
fn new(original: Retained<ProtocolObject<dyn WKNavigationDelegate>>, mtm: MainThreadMarker) -> Retained<Self> {
|
||||
let this = Self::alloc(mtm).set_ivars(TlsNavigationDelegateIvars { original });
|
||||
unsafe { msg_send![super(this), init] }
|
||||
impl AuthNavigationDelegate {
|
||||
fn track_navigation(&self, navigation: Option<&WKNavigation>) {
|
||||
if let Some(navigation) = navigation {
|
||||
let key = navigation as *const WKNavigation as usize;
|
||||
self
|
||||
.ivars()
|
||||
.navigations
|
||||
.borrow_mut()
|
||||
.entry(key)
|
||||
.or_insert_with(|| (navigation.retain(), self.ivars().messenger.generation()));
|
||||
}
|
||||
}
|
||||
|
||||
fn navigation_generation(&self, navigation: Option<&WKNavigation>) -> Option<u64> {
|
||||
let key = navigation? as *const WKNavigation as usize;
|
||||
self
|
||||
.ivars()
|
||||
.navigations
|
||||
.borrow()
|
||||
.get(&key)
|
||||
.map(|(_, generation)| *generation)
|
||||
}
|
||||
|
||||
fn finish_navigation(&self, navigation: Option<&WKNavigation>) -> Option<u64> {
|
||||
let key = navigation? as *const WKNavigation as usize;
|
||||
self
|
||||
.ivars()
|
||||
.navigations
|
||||
.borrow_mut()
|
||||
.remove(&key)
|
||||
.map(|(_, generation)| generation)
|
||||
}
|
||||
|
||||
fn report_load_failure(&self, webview: &WKWebView, navigation: Option<&WKNavigation>, error: &NSError) {
|
||||
let Some(generation) = self.finish_navigation(navigation) else {
|
||||
return;
|
||||
};
|
||||
if generation != self.ivars().messenger.generation() {
|
||||
return;
|
||||
}
|
||||
let is_url_error = error.domain().isEqualToString(unsafe { NSURLErrorDomain });
|
||||
if is_url_error && error.code() == NSURLErrorCancelled {
|
||||
return;
|
||||
}
|
||||
if is_url_error && error.code() == NSURLErrorUnsupportedURL {
|
||||
let callback = error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSURLErrorFailingURLErrorKey })
|
||||
.and_then(|value| value.downcast::<NSURL>().ok())
|
||||
.and_then(|url| url.scheme());
|
||||
if callback.is_some_and(|scheme| scheme.to_string() == "globalprotectcallback") {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let messenger = &self.ivars().messenger;
|
||||
if let Some(failure) = self.ivars().tls.borrow_mut().record_failure(webview, error, generation) {
|
||||
messenger.send_auth_event(AuthEvent::Error(generation, failure));
|
||||
return;
|
||||
}
|
||||
// Log codes rather than NSError descriptions, which may contain callback URLs.
|
||||
messenger.send_auth_event(AuthEvent::Error(
|
||||
generation,
|
||||
AuthError::LoadFailed(anyhow::anyhow!(
|
||||
"Navigation failed: {} ({})",
|
||||
error.domain(),
|
||||
error.code()
|
||||
)),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn navigation_delegate(webview: &WKWebView) -> Option<Retained<AuthNavigationDelegate>> {
|
||||
unsafe {
|
||||
let pointer = objc_getAssociatedObject(
|
||||
webview as *const WKWebView as *mut AnyObject,
|
||||
&AUTH_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<AuthNavigationDelegate>();
|
||||
Retained::retain(pointer.cast_mut())
|
||||
}
|
||||
}
|
||||
|
||||
fn track_requested_navigation(webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
let delegate = navigation_delegate(webview);
|
||||
if let Some(delegate) = delegate {
|
||||
delegate.track_navigation(navigation);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,15 +270,22 @@ fn challenge_disposition(is_server_trust: bool) -> NSURLSessionAuthChallengeDisp
|
||||
}
|
||||
}
|
||||
|
||||
fn install_tls_navigation_delegate(webview: &WKWebView) -> anyhow::Result<()> {
|
||||
fn install_navigation_delegate(webview: &WKWebView, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let original = unsafe { webview.navigationDelegate() }.context("WebView navigation delegate is unavailable")?;
|
||||
let mtm = MainThreadMarker::new().context("WebView must be configured on the main thread")?;
|
||||
let delegate = TlsNavigationDelegate::new(original, mtm);
|
||||
let delegate = AuthNavigationDelegate::alloc(mtm).set_ivars(AuthNavigationDelegateIvars {
|
||||
original,
|
||||
messenger,
|
||||
ignore_tls_errors: Cell::new(false),
|
||||
tls: RefCell::new(tls::TlsState::default()),
|
||||
navigations: RefCell::new(HashMap::new()),
|
||||
});
|
||||
let delegate: Retained<AuthNavigationDelegate> = unsafe { msg_send![super(delegate), init] };
|
||||
|
||||
unsafe {
|
||||
objc_setAssociatedObject(
|
||||
webview as *const WKWebView as *mut AnyObject,
|
||||
&TLS_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
|
||||
&AUTH_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
|
||||
Retained::as_ptr(&delegate).cast_mut().cast(),
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
|
||||
);
|
||||
@@ -139,9 +319,47 @@ mod tests {
|
||||
}
|
||||
|
||||
impl PlatformWebviewExt for PlatformWebview {
|
||||
fn install_auth_controls(&self, window: &tauri::WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
address_bar::install(webview)?;
|
||||
install_navigation_delegate(webview, Arc::clone(&messenger))?;
|
||||
recovery_row::install(webview, messenger)?;
|
||||
let window_handle = window.clone();
|
||||
window.on_window_event(move |event| {
|
||||
if matches!(
|
||||
event,
|
||||
tauri::WindowEvent::Resized(_) | tauri::WindowEvent::ScaleFactorChanged { .. }
|
||||
) {
|
||||
let _ = window_handle.with_webview(|webview| {
|
||||
let webview: &WKWebView = unsafe { &*webview.inner().cast() };
|
||||
address_bar::resize(webview);
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
recovery_row::update(webview, status)
|
||||
}
|
||||
|
||||
fn stop_loading(&self) {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
unsafe {
|
||||
webview.stopLoading();
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm_tls_exception(&self) -> anyhow::Result<()> {
|
||||
tls::confirm(unsafe { &*self.inner().cast::<WKWebView>() })
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
install_tls_navigation_delegate(webview)
|
||||
let delegate = navigation_delegate(webview).context("Auth navigation delegate is unavailable")?;
|
||||
delegate.ivars().ignore_tls_errors.set(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn user_agent(&self) -> anyhow::Result<String> {
|
||||
@@ -173,7 +391,8 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
let url = NSURL::URLWithString(&NSString::from_str(url)).ok_or_else(|| anyhow::anyhow!("Invalid URL"))?;
|
||||
let request = NSURLRequest::requestWithURL(&url);
|
||||
|
||||
wv.loadRequest(&request);
|
||||
let navigation = wv.loadRequest(&request);
|
||||
track_requested_navigation(wv, navigation.as_deref());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -182,31 +401,31 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
fn load_html(&self, html: &str) -> anyhow::Result<()> {
|
||||
unsafe {
|
||||
let wv: &WKWebView = &*self.inner().cast();
|
||||
wv.loadHTMLString_baseURL(&NSString::from_str(html), None);
|
||||
let navigation = wv.loadHTMLString_baseURL(&NSString::from_str(html), None);
|
||||
track_requested_navigation(wv, navigation.as_deref());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>) {
|
||||
unsafe {
|
||||
let wv: &WKWebView = &*self.inner().cast();
|
||||
fn navigation_address(webview: &WKWebView) -> String {
|
||||
let url = unsafe { webview.URL() }.and_then(|url| url.absoluteString());
|
||||
redact_uri(&url.map(|url| url.to_string()).unwrap_or_default())
|
||||
}
|
||||
|
||||
let js_callback = RcBlock::new(move |body: *mut AnyObject, err: *mut NSError| {
|
||||
if let Some(err) = err.as_ref() {
|
||||
let code = err.code();
|
||||
let message = err.localizedDescription();
|
||||
callback(Err(anyhow::anyhow!("Error {}: {}", code, message)));
|
||||
} else {
|
||||
let body: &NSString = &*body.cast();
|
||||
callback(Ok(body.to_string()));
|
||||
}
|
||||
});
|
||||
|
||||
wv.evaluateJavaScript_completionHandler(
|
||||
&NSString::from_str("document.documentElement.outerHTML"),
|
||||
Some(&js_callback),
|
||||
);
|
||||
fn read_navigation_html(webview: &WKWebView, messenger: Arc<AuthMessenger>, generation: u64) {
|
||||
let callback = RcBlock::new(move |body: *mut AnyObject, error: *mut NSError| {
|
||||
if let Some(error) = unsafe { error.as_ref() } {
|
||||
warn!("Failed to get html: {} ({})", error.domain(), error.code());
|
||||
} else if let Some(body) = unsafe { body.as_ref() }.and_then(|body| body.downcast_ref::<NSString>()) {
|
||||
messenger.read_from_html(&body.to_string(), generation);
|
||||
}
|
||||
});
|
||||
unsafe {
|
||||
webview.evaluateJavaScript_completionHandler(
|
||||
&NSString::from_str("document.documentElement.outerHTML"),
|
||||
Some(&callback),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
use std::{ffi::c_void, ptr};
|
||||
|
||||
use anyhow::Context;
|
||||
use objc2::{
|
||||
DefinedClass, MainThreadOnly, Message, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_getAssociatedObject, objc_setAssociatedObject},
|
||||
msg_send,
|
||||
rc::Retained,
|
||||
runtime::{AnyObject, ProtocolObject},
|
||||
};
|
||||
use objc2_app_kit::{
|
||||
NSAccessibility, NSAutoresizingMaskOptions, NSBox, NSBoxType, NSColor, NSFont, NSLayoutConstraint,
|
||||
NSLayoutConstraintOrientation, NSLineBreakMode, NSTextView, NSToolbar, NSToolbarDelegate, NSToolbarDisplayMode,
|
||||
NSToolbarItem, NSToolbarItemIdentifier, NSWindowTitleVisibility, NSWindowToolbarStyle,
|
||||
};
|
||||
use objc2_foundation::{
|
||||
MainThreadMarker, NSArray, NSDictionary, NSKeyValueChangeKey, NSKeyValueObservingOptions, NSObject,
|
||||
NSObjectNSKeyValueObserverRegistration, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString,
|
||||
};
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use super::super::address_bar::{LOADING_ADDRESS, display_address};
|
||||
|
||||
static ADDRESS_TOOLBAR_KEY: u8 = 0;
|
||||
const ADDRESS_ITEM_ID: &str = "com.yuezk.gpauth.address";
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSTextView)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
struct AddressView;
|
||||
|
||||
impl AddressView {
|
||||
#[unsafe(method(intrinsicContentSize))]
|
||||
fn intrinsic_content_size(&self) -> NSSize {
|
||||
// URL length must not determine the toolbar item's width.
|
||||
NSSize::new(-1.0, 22.0)
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
struct AddressToolbarIvars {
|
||||
webview: Retained<WKWebView>,
|
||||
address_view: Retained<NSTextView>,
|
||||
separator: Retained<NSBox>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
// The content view retains the delegate because NSToolbar's delegate is weak.
|
||||
// Drop unregisters URL observation before releasing the retained webview.
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = AddressToolbarIvars]
|
||||
struct AddressToolbar;
|
||||
|
||||
unsafe impl NSObjectProtocol for AddressToolbar {}
|
||||
|
||||
unsafe impl NSToolbarDelegate for AddressToolbar {
|
||||
#[unsafe(method_id(toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:))]
|
||||
fn toolbar_item(
|
||||
&self,
|
||||
_toolbar: &NSToolbar,
|
||||
identifier: &NSToolbarItemIdentifier,
|
||||
inserting: bool,
|
||||
) -> Option<Retained<NSToolbarItem>> {
|
||||
if !inserting || !identifier.isEqualToString(&NSString::from_str(ADDRESS_ITEM_ID)) {
|
||||
None
|
||||
} else {
|
||||
let item = NSToolbarItem::initWithItemIdentifier(NSToolbarItem::alloc(self.mtm()), identifier);
|
||||
item.setLabel(&NSString::from_str("Sign-in page address"));
|
||||
item.setBordered(true);
|
||||
item.setView(Some(&self.ivars().address_view));
|
||||
Some(item)
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method_id(toolbarDefaultItemIdentifiers:))]
|
||||
fn default_items(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSToolbarItemIdentifier>> {
|
||||
NSArray::from_retained_slice(&[NSString::from_str(ADDRESS_ITEM_ID)])
|
||||
}
|
||||
|
||||
#[unsafe(method_id(toolbarAllowedItemIdentifiers:))]
|
||||
fn allowed_items(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSToolbarItemIdentifier>> {
|
||||
NSArray::from_retained_slice(&[NSString::from_str(ADDRESS_ITEM_ID)])
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressToolbar {
|
||||
#[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
|
||||
fn observe_url(
|
||||
&self,
|
||||
_key_path: Option<&NSString>,
|
||||
_object: Option<&AnyObject>,
|
||||
_change: Option<&NSDictionary<NSKeyValueChangeKey, AnyObject>>,
|
||||
_context: *mut c_void,
|
||||
) {
|
||||
let uri = unsafe { self.ivars().webview.URL() }.and_then(|url| url.absoluteString());
|
||||
let address = display_address(uri.as_ref().map(|uri| uri.to_string()).as_deref());
|
||||
self.ivars().address_view.setString(&NSString::from_str(&address));
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl Drop for AddressToolbar {
|
||||
fn drop(&mut self) {
|
||||
// This private observer registers only URL and remains on the main thread.
|
||||
unsafe {
|
||||
self
|
||||
.ivars()
|
||||
.webview
|
||||
.removeObserver_forKeyPath(self, &NSString::from_str("URL"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WKWebView) -> anyhow::Result<()> {
|
||||
let mtm = MainThreadMarker::new().context("Toolbar must be installed on the main thread")?;
|
||||
let parent = unsafe { webview.superview() }.context("Webview has no containing view")?;
|
||||
let window = webview.window().context("Webview has no window")?;
|
||||
parent.setWantsLayer(true);
|
||||
let address_view: Retained<AddressView> =
|
||||
unsafe { msg_send![AddressView::alloc(mtm), initWithFrame: NSRect::default()] };
|
||||
// Use one native text layout for display and selection.
|
||||
address_view.setString(&NSString::from_str(LOADING_ADDRESS));
|
||||
address_view.setDrawsBackground(false);
|
||||
// Keep NSTextView's visible-rect cursor tracking inside the address bar.
|
||||
address_view.setClipsToBounds(true);
|
||||
address_view.setRichText(false);
|
||||
address_view.setHorizontallyResizable(false);
|
||||
address_view.setVerticallyResizable(false);
|
||||
address_view.setTextContainerInset(NSSize::new(6.0, 3.0));
|
||||
address_view.setEditable(false);
|
||||
address_view.setSelectable(true);
|
||||
address_view.setFont(Some(&NSFont::systemFontOfSize(12.0)));
|
||||
address_view.setContentHuggingPriority_forOrientation(1.0, NSLayoutConstraintOrientation::Horizontal);
|
||||
address_view.setAccessibilityLabel(Some(&NSString::from_str("Sign-in page address")));
|
||||
if let Some(container) = unsafe { address_view.textContainer() } {
|
||||
container.setWidthTracksTextView(true);
|
||||
container.setLineFragmentPadding(0.0);
|
||||
container.setMaximumNumberOfLines(1);
|
||||
container.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
|
||||
}
|
||||
// AppKit measures the toolbar item's minimum and maximum width from its view.
|
||||
NSLayoutConstraint::activateConstraints(&NSArray::from_retained_slice(&[
|
||||
address_view.widthAnchor().constraintGreaterThanOrEqualToConstant(200.0),
|
||||
address_view.widthAnchor().constraintLessThanOrEqualToConstant(10000.0),
|
||||
address_view.heightAnchor().constraintEqualToConstant(22.0),
|
||||
]));
|
||||
let separator = NSBox::new(mtm);
|
||||
separator
|
||||
.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewMinYMargin);
|
||||
separator.setBoxType(NSBoxType::Custom);
|
||||
separator.setBorderWidth(0.0);
|
||||
separator.setCornerRadius(0.0);
|
||||
separator.setFillColor(&NSColor::separatorColor());
|
||||
parent.addSubview(&separator);
|
||||
let delegate = AddressToolbar::alloc(mtm).set_ivars(AddressToolbarIvars {
|
||||
webview: webview.retain(),
|
||||
address_view: Retained::into_super(address_view),
|
||||
separator,
|
||||
});
|
||||
let delegate: Retained<AddressToolbar> = unsafe { msg_send![super(delegate), init] };
|
||||
// Observe the current URL independently of navigation callbacks.
|
||||
unsafe {
|
||||
webview.addObserver_forKeyPath_options_context(
|
||||
&delegate,
|
||||
&NSString::from_str("URL"),
|
||||
NSKeyValueObservingOptions::Initial,
|
||||
ptr::null_mut(),
|
||||
);
|
||||
objc_setAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&ADDRESS_TOOLBAR_KEY as *const u8 as *const c_void,
|
||||
Retained::as_ptr(&delegate).cast_mut().cast(),
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
|
||||
);
|
||||
}
|
||||
let toolbar = NSToolbar::initWithIdentifier(NSToolbar::alloc(mtm), &NSString::from_str("com.yuezk.gpauth.toolbar"));
|
||||
toolbar.setAllowsUserCustomization(false);
|
||||
toolbar.setDisplayMode(NSToolbarDisplayMode::IconOnly);
|
||||
toolbar.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||
window.setTitleVisibility(NSWindowTitleVisibility::Visible);
|
||||
if objc2::available!(macos = 11.0) {
|
||||
window.setToolbarStyle(NSWindowToolbarStyle::Expanded);
|
||||
}
|
||||
window.setToolbar(Some(&toolbar));
|
||||
window.setInitialFirstResponder(Some(webview));
|
||||
resize(webview);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn address_view(webview: &WKWebView) -> Option<Retained<NSTextView>> {
|
||||
let parent = unsafe { webview.superview() }?;
|
||||
let delegate = unsafe {
|
||||
objc_getAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&ADDRESS_TOOLBAR_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<AddressToolbar>()
|
||||
.as_ref()
|
||||
}?;
|
||||
Some(delegate.ivars().address_view.clone())
|
||||
}
|
||||
|
||||
pub(super) fn show_address(webview: &WKWebView, uri: &str) {
|
||||
if let Some(view) = address_view(webview) {
|
||||
view.setString(&NSString::from_str(&display_address(Some(uri))));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn resize(webview: &WKWebView) {
|
||||
let Some(parent) = (unsafe { webview.superview() }) else {
|
||||
return;
|
||||
};
|
||||
let Some(window) = webview.window() else {
|
||||
return;
|
||||
};
|
||||
// Keep the native separator outside WebKit so page backgrounds cannot cover it.
|
||||
let content = parent.convertRect_fromView(window.contentLayoutRect(), None);
|
||||
let separator_height = 1.0 / window.backingScaleFactor();
|
||||
let recovery_height = super::recovery_row::layout(webview, content);
|
||||
let page_height = (content.size.height - recovery_height - separator_height).max(0.0);
|
||||
let delegate = unsafe {
|
||||
objc_getAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&ADDRESS_TOOLBAR_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<AddressToolbar>()
|
||||
.as_ref()
|
||||
};
|
||||
if let Some(delegate) = delegate {
|
||||
delegate.ivars().separator.setFrame(NSRect::new(
|
||||
NSPoint::new(content.origin.x, content.origin.y + page_height),
|
||||
NSSize::new(content.size.width, separator_height),
|
||||
));
|
||||
}
|
||||
webview.setFrame(NSRect::new(
|
||||
content.origin,
|
||||
NSSize::new(content.size.width, page_height),
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
ffi::c_void,
|
||||
ptr,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use block2::RcBlock;
|
||||
use objc2::{
|
||||
DefinedClass, MainThreadOnly, Message, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_getAssociatedObject, objc_setAssociatedObject},
|
||||
msg_send,
|
||||
rc::{Retained, Weak},
|
||||
runtime::AnyObject,
|
||||
sel,
|
||||
};
|
||||
use objc2_app_kit::{
|
||||
NSAutoresizingMaskOptions, NSBezelStyle, NSBox, NSBoxType, NSButton, NSColor, NSControlSize, NSEvent, NSEventMask,
|
||||
NSEventModifierFlags, NSFont, NSLineBreakMode, NSProgressIndicator, NSProgressIndicatorStyle, NSTextField,
|
||||
NSTitlePosition, NSView,
|
||||
};
|
||||
use objc2_foundation::{MainThreadMarker, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString};
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
};
|
||||
|
||||
static RECOVERY_ROW_KEY: u8 = 0;
|
||||
|
||||
struct RecoveryRowIvars {
|
||||
webview: Retained<WKWebView>,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
row: Retained<NSBox>,
|
||||
blocker: Retained<NSView>,
|
||||
label: Retained<NSTextField>,
|
||||
detail: Retained<NSTextField>,
|
||||
proceed: Retained<NSButton>,
|
||||
status: Cell<RecoveryStatus>,
|
||||
spinner: Retained<NSProgressIndicator>,
|
||||
retry: Retained<NSButton>,
|
||||
cancel: Retained<NSButton>,
|
||||
keyboard_monitor: RefCell<Option<Retained<AnyObject>>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = RecoveryRowIvars]
|
||||
struct RecoveryRow;
|
||||
|
||||
unsafe impl NSObjectProtocol for RecoveryRow {}
|
||||
|
||||
impl RecoveryRow {
|
||||
#[unsafe(method(retry:))]
|
||||
fn retry(&self, _sender: &AnyObject) {
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::Retry);
|
||||
}
|
||||
|
||||
#[unsafe(method(continueTls:))]
|
||||
fn continue_tls(&self, _sender: &AnyObject) {
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::RequestTlsException);
|
||||
}
|
||||
|
||||
#[unsafe(method(cancel:))]
|
||||
fn cancel(&self, _sender: &AnyObject) {
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::Close);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl Drop for RecoveryRow {
|
||||
fn drop(&mut self) {
|
||||
if let Some(monitor) = self.ivars().keyboard_monitor.borrow_mut().take() {
|
||||
unsafe {
|
||||
NSEvent::removeMonitor(&monitor);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RecoveryRow {
|
||||
fn handle_key(&self, event: &NSEvent) -> bool {
|
||||
let controls = self.ivars();
|
||||
if !controls.status.get().blocks_page() {
|
||||
return false;
|
||||
}
|
||||
let Some(window) = controls.webview.window() else {
|
||||
return false;
|
||||
};
|
||||
if window.attachedSheet().is_some() || event.window(self.mtm()).as_deref() != Some(&*window) {
|
||||
return false;
|
||||
}
|
||||
let responder = window.firstResponder();
|
||||
let modifiers = event.modifierFlags();
|
||||
if event.keyCode() == 48 && !modifiers.intersects(NSEventModifierFlags::Command | NSEventModifierFlags::Control) {
|
||||
// Explicit traversal also works when the system skips buttons in its default key loop.
|
||||
let Some(address) = super::address_bar::address_view(&controls.webview) else {
|
||||
return false;
|
||||
};
|
||||
let mut views: Vec<&NSView> = vec![&address];
|
||||
if !controls.retry.isHidden() {
|
||||
views.push(&controls.retry);
|
||||
}
|
||||
if !controls.proceed.isHidden() {
|
||||
views.push(&controls.proceed);
|
||||
}
|
||||
views.push(&controls.cancel);
|
||||
let current = responder.as_ref().and_then(|responder| {
|
||||
views.iter().position(|view| {
|
||||
ptr::eq(
|
||||
(*view) as *const NSView as *const c_void,
|
||||
Retained::as_ptr(responder).cast(),
|
||||
)
|
||||
})
|
||||
});
|
||||
let next = match current {
|
||||
Some(index) if modifiers.contains(NSEventModifierFlags::Shift) => (index + views.len() - 1) % views.len(),
|
||||
Some(index) => (index + 1) % views.len(),
|
||||
None => views.len() - 1,
|
||||
};
|
||||
window.makeFirstResponder(Some(views[next]));
|
||||
return true;
|
||||
}
|
||||
// If WebKit regains focus programmatically, do not deliver keys to the covered page.
|
||||
if responder
|
||||
.as_deref()
|
||||
.and_then(|responder| responder.downcast_ref::<NSView>())
|
||||
.is_some_and(|view| view.isDescendantOf(&controls.webview))
|
||||
{
|
||||
window.makeFirstResponder(Some(&controls.cancel));
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WKWebView, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let mtm = MainThreadMarker::new().context("Recovery controls require the main thread")?;
|
||||
let parent = unsafe { webview.superview() }.context("Webview has no containing view")?;
|
||||
let row = NSBox::new(mtm);
|
||||
// AppKit may resize the parent after the application's window resize callback.
|
||||
row.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewMinYMargin);
|
||||
row.setBoxType(NSBoxType::Custom);
|
||||
row.setTitlePosition(NSTitlePosition::NoTitle);
|
||||
row.setContentViewMargins(NSSize::new(0.0, 0.0));
|
||||
row.setBorderWidth(0.0);
|
||||
row.setCornerRadius(0.0);
|
||||
row.setFillColor(&NSColor::windowBackgroundColor());
|
||||
let label = NSTextField::labelWithString(&NSString::new(), mtm);
|
||||
label.setFont(Some(&NSFont::systemFontOfSize(12.0)));
|
||||
label.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
|
||||
label.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
|
||||
let detail = NSTextField::labelWithString(&NSString::new(), mtm);
|
||||
detail.setFont(Some(&NSFont::systemFontOfSize(11.0)));
|
||||
detail.setTextColor(Some(&NSColor::secondaryLabelColor()));
|
||||
detail.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
|
||||
detail.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
|
||||
let spinner = NSProgressIndicator::new(mtm);
|
||||
spinner.setStyle(NSProgressIndicatorStyle::Spinning);
|
||||
spinner.setControlSize(NSControlSize::Small);
|
||||
spinner.setIndeterminate(true);
|
||||
let retry = unsafe { NSButton::buttonWithTitle_target_action(&NSString::from_str("Try Again"), None, None, mtm) };
|
||||
let cancel = unsafe { NSButton::buttonWithTitle_target_action(&NSString::from_str("Cancel"), None, None, mtm) };
|
||||
let proceed =
|
||||
unsafe { NSButton::buttonWithTitle_target_action(&NSString::from_str("Continue Anyway…"), None, None, mtm) };
|
||||
for button in [&retry, &proceed, &cancel] {
|
||||
button.setAutoresizingMask(NSAutoresizingMaskOptions::ViewMinXMargin);
|
||||
button.setBezelStyle(NSBezelStyle::Push);
|
||||
button.setControlSize(NSControlSize::Small);
|
||||
button.setFont(Some(&NSFont::systemFontOfSize(12.0)));
|
||||
row.addSubview(button);
|
||||
}
|
||||
row.addSubview(&label);
|
||||
row.addSubview(&detail);
|
||||
row.addSubview(&spinner);
|
||||
let blocker = NSView::new(mtm);
|
||||
blocker
|
||||
.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewHeightSizable);
|
||||
parent.addSubview(&blocker);
|
||||
parent.addSubview(&row);
|
||||
row.setHidden(true);
|
||||
blocker.setHidden(true);
|
||||
let controller = RecoveryRow::alloc(mtm).set_ivars(RecoveryRowIvars {
|
||||
webview: webview.retain(),
|
||||
messenger,
|
||||
row,
|
||||
blocker,
|
||||
label,
|
||||
detail,
|
||||
proceed,
|
||||
status: Cell::new(RecoveryStatus::Hidden),
|
||||
spinner,
|
||||
retry,
|
||||
cancel,
|
||||
keyboard_monitor: RefCell::new(None),
|
||||
});
|
||||
let controller: Retained<RecoveryRow> = unsafe { msg_send![super(controller), init] };
|
||||
let weak_controller = Weak::from_retained(&controller);
|
||||
let handler = RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
|
||||
let blocked = weak_controller
|
||||
.load()
|
||||
.is_some_and(|controller| controller.handle_key(unsafe { event.as_ref() }));
|
||||
if blocked { ptr::null_mut() } else { event.as_ptr() }
|
||||
});
|
||||
let monitor = unsafe { NSEvent::addLocalMonitorForEventsMatchingMask_handler(NSEventMask::KeyDown, &handler) }
|
||||
.context("Failed to guard keyboard input during sign-in recovery")?;
|
||||
*controller.ivars().keyboard_monitor.borrow_mut() = Some(monitor);
|
||||
unsafe {
|
||||
controller.ivars().retry.setTarget(Some(&controller));
|
||||
controller.ivars().retry.setAction(Some(sel!(retry:)));
|
||||
controller.ivars().proceed.setTarget(Some(&controller));
|
||||
controller.ivars().proceed.setAction(Some(sel!(continueTls:)));
|
||||
controller.ivars().cancel.setTarget(Some(&controller));
|
||||
controller.ivars().cancel.setAction(Some(sel!(cancel:)));
|
||||
objc_setAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&RECOVERY_ROW_KEY as *const u8 as *const c_void,
|
||||
Retained::as_ptr(&controller).cast_mut().cast(),
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn controller(webview: &WKWebView) -> Option<Retained<RecoveryRow>> {
|
||||
let parent = unsafe { webview.superview() }?;
|
||||
unsafe {
|
||||
let pointer = objc_getAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&RECOVERY_ROW_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<RecoveryRow>();
|
||||
Retained::retain(pointer.cast_mut())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn update(webview: &WKWebView, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
let controller = controller(webview).context("Recovery controls are unavailable")?;
|
||||
let controls = controller.ivars();
|
||||
let was_blocking = controls.status.replace(status).blocks_page();
|
||||
let hidden = status == RecoveryStatus::Hidden;
|
||||
controls.label.setStringValue(&NSString::from_str(status.message()));
|
||||
controls.detail.setStringValue(&NSString::from_str(status.detail()));
|
||||
controls.detail.setHidden(status.detail().is_empty());
|
||||
controls.retry.setHidden(!status.can_retry());
|
||||
controls.proceed.setHidden(!status.can_continue());
|
||||
controls.cancel.setHidden(!status.blocks_page());
|
||||
controls.spinner.setHidden(!status.is_busy());
|
||||
unsafe {
|
||||
if status.is_busy() {
|
||||
controls.spinner.startAnimation(None);
|
||||
} else {
|
||||
controls.spinner.stopAnimation(None);
|
||||
}
|
||||
}
|
||||
controls.row.setHidden(hidden);
|
||||
controls.blocker.setHidden(!status.blocks_page());
|
||||
if was_blocking != status.blocks_page() {
|
||||
if let Some(window) = webview.window() {
|
||||
if !status.blocks_page() {
|
||||
window.makeFirstResponder(Some(webview));
|
||||
} else {
|
||||
window.makeFirstResponder(Some(&controls.cancel));
|
||||
}
|
||||
}
|
||||
}
|
||||
super::address_bar::resize(webview);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Position the row above the page and return the height reserved for it.
|
||||
pub(super) fn layout(webview: &WKWebView, content: NSRect) -> f64 {
|
||||
let Some(controller) = controller(webview) else {
|
||||
return 0.0;
|
||||
};
|
||||
let controls = controller.ivars();
|
||||
if controls.row.isHidden() {
|
||||
return 0.0;
|
||||
}
|
||||
let height = if controls.status.get().detail().is_empty() {
|
||||
36.0
|
||||
} else {
|
||||
52.0
|
||||
};
|
||||
let width = content.size.width;
|
||||
controls.row.setFrame(NSRect::new(
|
||||
NSPoint::new(content.origin.x, content.origin.y + content.size.height - height),
|
||||
NSSize::new(width, height),
|
||||
));
|
||||
controls.blocker.setFrame(NSRect::new(
|
||||
content.origin,
|
||||
NSSize::new(width, (content.size.height - height).max(0.0)),
|
||||
));
|
||||
controls.cancel.setFrame(NSRect::new(
|
||||
NSPoint::new(width - 80.0, (height - 26.0) / 2.0),
|
||||
NSSize::new(72.0, 26.0),
|
||||
));
|
||||
controls.retry.setFrame(NSRect::new(
|
||||
NSPoint::new(
|
||||
width - 162.0 - if controls.proceed.isHidden() { 0.0 } else { 132.0 },
|
||||
(height - 26.0) / 2.0,
|
||||
),
|
||||
NSSize::new(78.0, 26.0),
|
||||
));
|
||||
controls.proceed.setFrame(NSRect::new(
|
||||
NSPoint::new(width - 212.0, (height - 26.0) / 2.0),
|
||||
NSSize::new(128.0, 26.0),
|
||||
));
|
||||
controls
|
||||
.spinner
|
||||
.setFrame(NSRect::new(NSPoint::new(12.0, 10.0), NSSize::new(16.0, 16.0)));
|
||||
let left = if controls.spinner.isHidden() { 12.0 } else { 36.0 };
|
||||
let right = if !controls.proceed.isHidden() {
|
||||
width - 220.0
|
||||
} else if !controls.retry.isHidden() {
|
||||
width - 170.0
|
||||
} else {
|
||||
width - 88.0
|
||||
};
|
||||
controls.label.setFrame(NSRect::new(
|
||||
NSPoint::new(left, height - 26.0),
|
||||
NSSize::new((right - left).max(0.0), 17.0),
|
||||
));
|
||||
controls.detail.setFrame(NSRect::new(
|
||||
NSPoint::new(left, 7.0),
|
||||
NSSize::new((right - left).max(0.0), 15.0),
|
||||
));
|
||||
height
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
use anyhow::Context;
|
||||
use block2::RcBlock;
|
||||
use objc2::{DefinedClass, MainThreadOnly, rc::Weak};
|
||||
use objc2_app_kit::{NSAlert, NSAlertSecondButtonReturn, NSAlertStyle};
|
||||
use objc2_foundation::{
|
||||
NSError, NSString, NSURL, NSURLErrorDomain, NSURLErrorFailingURLErrorKey, NSURLErrorFailingURLPeerTrustErrorKey,
|
||||
NSUnderlyingErrorKey,
|
||||
};
|
||||
use objc2_security::{SecTrust, errSecHostNameMismatch};
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthError, AuthEvent},
|
||||
tls::{TlsFailure, TlsFailureReason},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CertificateException {
|
||||
host: String,
|
||||
certificate: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PendingCertificate {
|
||||
generation: u64,
|
||||
failure: TlsFailure,
|
||||
exception: CertificateException,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct TlsState {
|
||||
pending: Option<PendingCertificate>,
|
||||
exceptions: Vec<CertificateException>,
|
||||
}
|
||||
|
||||
impl TlsState {
|
||||
fn approve(&mut self, pending: &PendingCertificate, generation: u64) -> bool {
|
||||
if pending.generation != generation
|
||||
|| self.pending.as_ref().is_none_or(|current| {
|
||||
current.generation != pending.generation
|
||||
|| current.exception.certificate != pending.exception.certificate
|
||||
|| current.exception.host != pending.exception.host
|
||||
})
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.exceptions.push(pending.exception.clone());
|
||||
self.pending = None;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn record_failure(&mut self, webview: &WKWebView, error: &NSError, generation: u64) -> Option<AuthError> {
|
||||
if !error.domain().isEqualToString(unsafe { NSURLErrorDomain }) {
|
||||
return None;
|
||||
}
|
||||
let reason = match error.code() {
|
||||
-1200 => TlsFailureReason::Handshake,
|
||||
-1201 => TlsFailureReason::Expired,
|
||||
-1202 => TlsFailureReason::InvalidCertificate,
|
||||
-1203 => TlsFailureReason::Untrusted,
|
||||
-1204 => TlsFailureReason::NotYetValid,
|
||||
_ => return None,
|
||||
};
|
||||
let reason = if has_hostname_mismatch(error, 0) {
|
||||
TlsFailureReason::HostnameMismatch
|
||||
} else {
|
||||
reason
|
||||
};
|
||||
let url = error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSURLErrorFailingURLErrorKey })?
|
||||
.downcast::<NSURL>()
|
||||
.ok()?;
|
||||
let host = url.host()?.to_string().to_ascii_lowercase();
|
||||
if let Some(uri) = url.absoluteString() {
|
||||
super::address_bar::show_address(webview, &uri.to_string());
|
||||
}
|
||||
let trust = error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSURLErrorFailingURLPeerTrustErrorKey });
|
||||
let certificate = trust.and_then(|trust| {
|
||||
// Foundation documents this entry as a SecTrustRef.
|
||||
let trust = unsafe { &*(objc2::rc::Retained::as_ptr(&trust).cast::<SecTrust>()) };
|
||||
certificate_data(trust)
|
||||
});
|
||||
let failure = TlsFailure {
|
||||
host: host.clone(),
|
||||
reason,
|
||||
can_continue: reason.is_certificate_error() && certificate.is_some(),
|
||||
};
|
||||
self.pending = certificate
|
||||
.filter(|_| failure.can_continue)
|
||||
.map(|certificate| PendingCertificate {
|
||||
generation,
|
||||
failure: failure.clone(),
|
||||
exception: CertificateException { host, certificate },
|
||||
});
|
||||
Some(AuthError::Tls(failure))
|
||||
}
|
||||
|
||||
pub fn allows(&self, host: &str, trust: &SecTrust) -> bool {
|
||||
if self.exceptions.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(certificate) = certificate_data(trust) else {
|
||||
return false;
|
||||
};
|
||||
self
|
||||
.exceptions
|
||||
.iter()
|
||||
.any(|exception| exception.host.eq_ignore_ascii_case(host) && exception.certificate == certificate)
|
||||
}
|
||||
}
|
||||
|
||||
fn has_hostname_mismatch(error: &NSError, depth: usize) -> bool {
|
||||
if depth > 4 {
|
||||
return false;
|
||||
}
|
||||
if error.code() == errSecHostNameMismatch as isize {
|
||||
return true;
|
||||
}
|
||||
error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSUnderlyingErrorKey })
|
||||
.and_then(|value| value.downcast::<NSError>().ok())
|
||||
.is_some_and(|error| has_hostname_mismatch(&error, depth + 1))
|
||||
}
|
||||
|
||||
fn certificate_data(trust: &SecTrust) -> Option<Vec<u8>> {
|
||||
// Retain the leaf immediately. No trust evaluation or mutation runs here.
|
||||
#[allow(deprecated)]
|
||||
let certificate = unsafe { trust.certificate_at_index(0) }?;
|
||||
Some(unsafe { certificate.data() }.to_vec())
|
||||
}
|
||||
|
||||
pub(super) fn confirm(webview: &WKWebView) -> anyhow::Result<()> {
|
||||
let delegate = super::navigation_delegate(webview).context("Auth navigation delegate is unavailable")?;
|
||||
let pending = delegate
|
||||
.ivars()
|
||||
.tls
|
||||
.borrow()
|
||||
.pending
|
||||
.clone()
|
||||
.context("No certificate error is awaiting confirmation")?;
|
||||
if pending.generation != delegate.ivars().messenger.generation() {
|
||||
return Ok(());
|
||||
}
|
||||
let window = webview.window().context("Auth window is unavailable")?;
|
||||
if window.attachedSheet().is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let alert = NSAlert::new(delegate.mtm());
|
||||
alert.setAlertStyle(NSAlertStyle::Warning);
|
||||
alert.setMessageText(&NSString::from_str(&pending.failure.confirmation_title()));
|
||||
alert.setInformativeText(&NSString::from_str(&pending.failure.confirmation_message()));
|
||||
alert.addButtonWithTitle(&NSString::from_str("Cancel"));
|
||||
alert.addButtonWithTitle(&NSString::from_str("Continue Anyway"));
|
||||
let weak = Weak::from_retained(&delegate);
|
||||
let handler = RcBlock::new(move |response: isize| {
|
||||
let Some(delegate) = weak.load() else {
|
||||
return;
|
||||
};
|
||||
if response != NSAlertSecondButtonReturn || pending.generation != delegate.ivars().messenger.generation() {
|
||||
return;
|
||||
}
|
||||
let mut state = delegate.ivars().tls.borrow_mut();
|
||||
if !state.approve(&pending, delegate.ivars().messenger.generation()) {
|
||||
return;
|
||||
}
|
||||
drop(state);
|
||||
delegate
|
||||
.ivars()
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::TlsAccepted(pending.generation));
|
||||
});
|
||||
alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pending() -> PendingCertificate {
|
||||
PendingCertificate {
|
||||
generation: 1,
|
||||
failure: TlsFailure {
|
||||
host: "login.example".into(),
|
||||
reason: TlsFailureReason::Expired,
|
||||
can_continue: true,
|
||||
},
|
||||
exception: CertificateException {
|
||||
host: "login.example".into(),
|
||||
certificate: vec![1, 2, 3],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_approval_rejects_stale_attempts_and_replacement_certificates() {
|
||||
let original = pending();
|
||||
let mut state = TlsState {
|
||||
pending: Some(original.clone()),
|
||||
..TlsState::default()
|
||||
};
|
||||
assert!(!state.approve(&original, 2));
|
||||
let mut replacement = original.clone();
|
||||
replacement.exception.certificate = vec![4, 5, 6];
|
||||
state.pending = Some(replacement);
|
||||
assert!(!state.approve(&original, 1));
|
||||
assert!(state.exceptions.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_approval_is_specific_to_the_host_and_consumed_once() {
|
||||
let original = pending();
|
||||
let mut state = TlsState {
|
||||
pending: Some(original.clone()),
|
||||
..TlsState::default()
|
||||
};
|
||||
let mut other_host = original.clone();
|
||||
other_host.exception.host = "other.example".into();
|
||||
assert!(!state.approve(&other_host, 1));
|
||||
assert!(state.approve(&original, 1));
|
||||
assert_eq!(state.exceptions.len(), 1);
|
||||
assert!(!state.approve(&original, 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
use super::tls::TlsFailureReason;
|
||||
|
||||
/// Native UI state for recovering an embedded sign-in session.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(super) enum RecoveryStatus {
|
||||
#[default]
|
||||
Hidden,
|
||||
Restarting,
|
||||
Loading,
|
||||
Failed,
|
||||
Rejected,
|
||||
Tls {
|
||||
reason: TlsFailureReason,
|
||||
can_continue: bool,
|
||||
},
|
||||
CertificateBypassed,
|
||||
}
|
||||
|
||||
impl RecoveryStatus {
|
||||
pub fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::Hidden => "",
|
||||
Self::Restarting => "Restarting sign-in…",
|
||||
Self::Loading => "Loading sign-in…",
|
||||
Self::Failed => "Couldn’t restart sign-in.",
|
||||
Self::Rejected => "Sign-in wasn’t completed.",
|
||||
Self::Tls {
|
||||
reason: TlsFailureReason::Handshake,
|
||||
..
|
||||
} => "Secure connection failed.",
|
||||
Self::Tls { .. } => "Cannot verify this server’s identity.",
|
||||
Self::CertificateBypassed => "Certificate verification bypassed in this window.",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detail(self) -> &'static str {
|
||||
match self {
|
||||
Self::Tls { reason, .. } => reason.message(),
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_continue(self) -> bool {
|
||||
match self {
|
||||
Self::Tls { reason, can_continue } => can_continue && reason.is_certificate_error(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn blocks_page(self) -> bool {
|
||||
!matches!(self, Self::Hidden | Self::CertificateBypassed)
|
||||
}
|
||||
|
||||
pub fn accepts_auth_data(self) -> bool {
|
||||
matches!(self, Self::Hidden | Self::Loading | Self::CertificateBypassed)
|
||||
}
|
||||
|
||||
pub fn is_busy(self) -> bool {
|
||||
matches!(self, Self::Restarting | Self::Loading)
|
||||
}
|
||||
|
||||
pub fn can_retry(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Failed
|
||||
| Self::Rejected
|
||||
| Self::Tls {
|
||||
reason: TlsFailureReason::Handshake,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Recovery {
|
||||
status: RecoveryStatus,
|
||||
automatic_retry_used: bool,
|
||||
certificate_bypassed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum RetrySource {
|
||||
FreshPrelogin,
|
||||
SuppliedRequest,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum RetryTiming {
|
||||
Immediate,
|
||||
AutomaticDelay,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct RetryPlan {
|
||||
pub source: RetrySource,
|
||||
pub timing: RetryTiming,
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
pub fn status(&self) -> RecoveryStatus {
|
||||
self.status
|
||||
}
|
||||
|
||||
pub fn loading(&mut self) {
|
||||
self.status = RecoveryStatus::Loading;
|
||||
}
|
||||
|
||||
pub fn load_failed(&mut self) {
|
||||
self.status = RecoveryStatus::Failed;
|
||||
}
|
||||
|
||||
pub fn tls_failed(&mut self, reason: TlsFailureReason, can_continue: bool) {
|
||||
self.status = RecoveryStatus::Tls { reason, can_continue };
|
||||
}
|
||||
|
||||
pub fn certificate_accepted(&mut self) -> Option<RetryPlan> {
|
||||
if !self.status.can_continue() {
|
||||
return None;
|
||||
}
|
||||
self.certificate_bypassed = true;
|
||||
self.status = RecoveryStatus::Restarting;
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::SuppliedRequest,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
}
|
||||
|
||||
/// Temporary service failures get one automatic restart per dialog.
|
||||
/// Duplicate failures while restarting or awaiting user action are ignored.
|
||||
pub fn failure(&mut self, temporary: bool) -> Option<RetryPlan> {
|
||||
if !matches!(
|
||||
self.status,
|
||||
RecoveryStatus::Hidden | RecoveryStatus::Loading | RecoveryStatus::CertificateBypassed
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
if temporary && !self.automatic_retry_used {
|
||||
self.automatic_retry_used = true;
|
||||
self.status = RecoveryStatus::Restarting;
|
||||
return Some(RetryPlan {
|
||||
source: RetrySource::FreshPrelogin,
|
||||
timing: RetryTiming::AutomaticDelay,
|
||||
});
|
||||
}
|
||||
self.status = if temporary {
|
||||
RecoveryStatus::Failed
|
||||
} else {
|
||||
RecoveryStatus::Rejected
|
||||
};
|
||||
None
|
||||
}
|
||||
|
||||
pub fn retry(&mut self) -> Option<RetryPlan> {
|
||||
if !self.status.can_retry() {
|
||||
return None;
|
||||
}
|
||||
let source = if matches!(self.status, RecoveryStatus::Tls { .. }) {
|
||||
RetrySource::SuppliedRequest
|
||||
} else {
|
||||
RetrySource::FreshPrelogin
|
||||
};
|
||||
self.status = RecoveryStatus::Restarting;
|
||||
Some(RetryPlan {
|
||||
source,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn page_loaded(&mut self) {
|
||||
if self.status == RecoveryStatus::Loading {
|
||||
self.status = if self.certificate_bypassed {
|
||||
RecoveryStatus::CertificateBypassed
|
||||
} else {
|
||||
RecoveryStatus::Hidden
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn retry_plans_preserve_request_source_and_timing() {
|
||||
let mut recovery = Recovery::default();
|
||||
assert_eq!(
|
||||
recovery.failure(true),
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::FreshPrelogin,
|
||||
timing: RetryTiming::AutomaticDelay,
|
||||
})
|
||||
);
|
||||
recovery.load_failed();
|
||||
assert_eq!(
|
||||
recovery.retry(),
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::FreshPrelogin,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
);
|
||||
recovery.tls_failed(TlsFailureReason::Expired, true);
|
||||
assert_eq!(
|
||||
recovery.certificate_accepted(),
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::SuppliedRequest,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
);
|
||||
assert!(recovery.certificate_accepted().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tls_failure_blocks_credentials_and_is_not_cleared_by_page_completion() {
|
||||
let mut recovery = Recovery {
|
||||
status: RecoveryStatus::Tls {
|
||||
reason: TlsFailureReason::Expired,
|
||||
can_continue: true,
|
||||
},
|
||||
..Recovery::default()
|
||||
};
|
||||
assert!(recovery.status.blocks_page());
|
||||
assert!(!recovery.status.accepts_auth_data());
|
||||
assert!(recovery.status.can_continue());
|
||||
recovery.page_loaded();
|
||||
assert!(matches!(recovery.status, RecoveryStatus::Tls { .. }));
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert!(matches!(recovery.status, RecoveryStatus::Tls { .. }));
|
||||
assert!(recovery.retry().is_none());
|
||||
assert!(recovery.status.can_continue());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_failures_never_offer_a_certificate_exception() {
|
||||
let status = RecoveryStatus::Tls {
|
||||
reason: TlsFailureReason::Handshake,
|
||||
can_continue: true,
|
||||
};
|
||||
assert!(!status.can_continue());
|
||||
assert!(status.can_retry());
|
||||
assert!(status.blocks_page());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_notice_keeps_successful_page_interactive() {
|
||||
let mut recovery = Recovery {
|
||||
certificate_bypassed: true,
|
||||
status: RecoveryStatus::Loading,
|
||||
..Recovery::default()
|
||||
};
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::CertificateBypassed);
|
||||
assert!(!recovery.status.blocks_page());
|
||||
assert!(recovery.status.accepts_auth_data());
|
||||
assert!(recovery.failure(false).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Rejected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temporary_failure_retries_once_even_after_manual_restarts() {
|
||||
let mut recovery = Recovery::default();
|
||||
assert!(recovery.failure(true).is_some());
|
||||
assert!(recovery.failure(true).is_none());
|
||||
recovery.status = RecoveryStatus::Loading;
|
||||
recovery.page_loaded();
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Failed);
|
||||
assert!(recovery.retry().is_some());
|
||||
recovery.status = RecoveryStatus::Loading;
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_auth_requires_user_action_and_deduplicates_errors() {
|
||||
let mut recovery = Recovery::default();
|
||||
assert!(recovery.failure(false).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Rejected);
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert!(recovery.retry().is_some());
|
||||
assert!(recovery.retry().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_completion_does_not_clear_errors_or_pending_prelogin() {
|
||||
let mut recovery = Recovery::default();
|
||||
recovery.failure(false);
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::Rejected);
|
||||
recovery.retry();
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::Restarting);
|
||||
recovery.status = RecoveryStatus::Loading;
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::Hidden);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/// A TLS failure that can be presented without exposing request parameters.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum TlsFailureReason {
|
||||
Expired,
|
||||
NotYetValid,
|
||||
Untrusted,
|
||||
HostnameMismatch,
|
||||
InvalidCertificate,
|
||||
Handshake,
|
||||
}
|
||||
|
||||
impl TlsFailureReason {
|
||||
pub fn is_certificate_error(self) -> bool {
|
||||
self != Self::Handshake
|
||||
}
|
||||
|
||||
pub fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::Expired => "The certificate has expired.",
|
||||
Self::NotYetValid => "The certificate is not valid yet.",
|
||||
Self::Untrusted => "The certificate was issued by an untrusted authority.",
|
||||
Self::HostnameMismatch => "The certificate does not match this server’s hostname.",
|
||||
Self::InvalidCertificate => "The server’s certificate could not be verified.",
|
||||
Self::Handshake => "The server could not establish a compatible TLS connection.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct TlsFailure {
|
||||
pub host: String,
|
||||
pub reason: TlsFailureReason,
|
||||
pub can_continue: bool,
|
||||
}
|
||||
|
||||
impl TlsFailure {
|
||||
pub fn confirmation_title(&self) -> String {
|
||||
format!("Continue to {}?", self.host)
|
||||
}
|
||||
|
||||
pub fn confirmation_message(&self) -> String {
|
||||
format!(
|
||||
"{} Your sign-in information could be intercepted.\n\nThis exception applies only to this host until this sign-in window closes.",
|
||||
self.reason.message()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::bail;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use gpapi::utils::window::{WindowTypeHint, set_window_type_hint};
|
||||
use gpapi::{
|
||||
auth::{AuthWindowTheme, AuthenticationCancelled, SamlAuthData},
|
||||
error::ServerTlsError,
|
||||
gp_params::GpParams,
|
||||
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
|
||||
utils::{redact::redact_uri, window::get_title_bar_height},
|
||||
@@ -12,17 +13,26 @@ use gpapi::{
|
||||
use log::{info, warn};
|
||||
#[cfg(target_os = "macos")]
|
||||
use tauri::Manager;
|
||||
use tauri::{
|
||||
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
|
||||
webview::{PageLoadEvent, PageLoadPayload},
|
||||
};
|
||||
use tauri::{AppHandle, WebviewUrl, WebviewWindow, WindowEvent};
|
||||
use tokio::{sync::oneshot, time};
|
||||
|
||||
use crate::auth_prelogin;
|
||||
|
||||
use super::address_bar::TOOLBAR_HEIGHT;
|
||||
use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
|
||||
use super::recovery::{Recovery, RecoveryStatus, RetryPlan, RetrySource, RetryTiming};
|
||||
|
||||
const RESTART_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
pub trait PlatformWebviewExt {
|
||||
fn install_auth_controls(&self, window: &WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()>;
|
||||
|
||||
fn stop_loading(&self);
|
||||
|
||||
fn confirm_tls_exception(&self) -> anyhow::Result<()>;
|
||||
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()>;
|
||||
|
||||
fn user_agent(&self) -> anyhow::Result<String>;
|
||||
@@ -33,8 +43,6 @@ pub trait PlatformWebviewExt {
|
||||
|
||||
fn load_html(&self, html: &str) -> anyhow::Result<()>;
|
||||
|
||||
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>);
|
||||
|
||||
fn load_auth_request(&self, auth_request: &str) -> anyhow::Result<()> {
|
||||
if auth_request.starts_with("http") {
|
||||
info!("Loading auth request as URL: {}", redact_uri(auth_request));
|
||||
@@ -59,8 +67,6 @@ pub struct WebviewAuthenticator<'a> {
|
||||
clean: bool,
|
||||
window_title: &'a str,
|
||||
window_theme: AuthWindowTheme,
|
||||
|
||||
is_retrying: tokio::sync::RwLock<bool>,
|
||||
}
|
||||
|
||||
fn native_theme(theme: AuthWindowTheme) -> Option<tauri::Theme> {
|
||||
@@ -89,7 +95,6 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
clean: false,
|
||||
window_title: "GlobalProtect Login",
|
||||
window_theme: AuthWindowTheme::System,
|
||||
is_retrying: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,39 +125,13 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
|
||||
let auth_messenger = Arc::new(AuthMessenger::new());
|
||||
let auth_messenger_clone = Arc::clone(&auth_messenger);
|
||||
|
||||
let on_page_load = move |auth_window: WebviewWindow, event: PageLoadPayload<'_>| {
|
||||
let auth_messenger_clone = Arc::clone(&auth_messenger_clone);
|
||||
let redacted_url = redact_uri(event.url().as_str());
|
||||
|
||||
match event.event() {
|
||||
PageLoadEvent::Started => {
|
||||
info!("Started loading page: {}", redacted_url);
|
||||
auth_messenger_clone.cancel_raise_window();
|
||||
}
|
||||
PageLoadEvent::Finished => {
|
||||
info!("Finished loading page: {}", redacted_url);
|
||||
}
|
||||
}
|
||||
|
||||
// Read auth data from the page no matter whether it's finished loading or not
|
||||
// Because we found that the finished event may not be triggered in some cases (e.g., on macOS)
|
||||
let _ = auth_window.with_webview(move |wv| {
|
||||
wv.get_html(Box::new(move |html| match html {
|
||||
Ok(html) => auth_messenger_clone.read_from_html(&html),
|
||||
Err(err) => warn!("Failed to get html: {}", err),
|
||||
}));
|
||||
});
|
||||
};
|
||||
|
||||
let auth_window_builder = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
|
||||
.on_page_load(on_page_load)
|
||||
.title(self.window_title)
|
||||
.theme(native_theme(self.window_theme))
|
||||
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
|
||||
let auth_window = auth_window_builder
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height())
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height() + TOOLBAR_HEIGHT)
|
||||
.min_inner_size(400.0, 300.0)
|
||||
.focused(true)
|
||||
.visible(false)
|
||||
.center()
|
||||
@@ -161,38 +140,169 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?;
|
||||
|
||||
self
|
||||
.setup_auth_window(&auth_window, Arc::clone(&auth_messenger))
|
||||
.await?;
|
||||
|
||||
if present_after_setup(self.clean) {
|
||||
self.raise_window(&auth_window);
|
||||
let messenger = Arc::clone(&auth_messenger);
|
||||
let raise_task = tokio::spawn(async move {
|
||||
time::sleep(Duration::from_secs(10)).await;
|
||||
messenger.send_auth_event(AuthEvent::RaiseWindow);
|
||||
});
|
||||
let result = async {
|
||||
self
|
||||
.setup_auth_window(&auth_window, Arc::clone(&auth_messenger))
|
||||
.await?;
|
||||
if present_after_setup(self.clean) {
|
||||
self.raise_window(&auth_window);
|
||||
}
|
||||
self.wait_for_auth(&auth_window, Arc::clone(&auth_messenger)).await
|
||||
}
|
||||
.await;
|
||||
|
||||
raise_task.abort();
|
||||
auth_messenger.begin_attempt();
|
||||
auth_messenger.cancel_raise_window();
|
||||
// Preserve the authentication outcome even if native teardown fails.
|
||||
if let Err(error) = auth_window.close() {
|
||||
warn!("Failed to close authentication window: {error}");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn wait_for_auth(
|
||||
&self,
|
||||
auth_window: &WebviewWindow,
|
||||
auth_messenger: Arc<AuthMessenger>,
|
||||
) -> anyhow::Result<SamlAuthData> {
|
||||
let mut recovery = Recovery::default();
|
||||
let mut restart: Option<Pin<Box<dyn Future<Output = anyhow::Result<String>> + Send + '_>>> = None;
|
||||
let mut loading_deadline = None;
|
||||
|
||||
loop {
|
||||
match auth_messenger.subscribe().await? {
|
||||
AuthEvent::Close => bail!(AuthenticationCancelled),
|
||||
AuthEvent::RaiseWindow => self.raise_window(&auth_window),
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
AuthEvent::Error(AuthError::TlsError) => bail!(gpapi::error::PortalError::TlsError),
|
||||
AuthEvent::Error(AuthError::NotFound(location)) => {
|
||||
let event = tokio::select! {
|
||||
event = auth_messenger.subscribe() => event?,
|
||||
result = async {
|
||||
match restart.as_mut() {
|
||||
Some(restart) => restart.await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
} => {
|
||||
restart = None;
|
||||
match result {
|
||||
Ok(auth_request) => {
|
||||
// Fence off reads and cancellation notifications from the old page.
|
||||
auth_messenger.begin_attempt();
|
||||
recovery.loading();
|
||||
loading_deadline = Some(time::Instant::now() + RESTART_TIMEOUT);
|
||||
self.load_restarted_sign_in(auth_window, &auth_messenger, auth_request)?;
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Failed to restart sign-in: {}", err);
|
||||
if err.downcast_ref::<ServerTlsError>().is_some() {
|
||||
return Err(err);
|
||||
}
|
||||
recovery.load_failed();
|
||||
}
|
||||
}
|
||||
self.update_recovery(auth_window, recovery.status())?;
|
||||
continue;
|
||||
}
|
||||
_ = async {
|
||||
match loading_deadline {
|
||||
Some(deadline) => time::sleep_until(deadline).await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
} => {
|
||||
loading_deadline = None;
|
||||
recovery.load_failed();
|
||||
self.update_recovery(auth_window, recovery.status())?;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut retry_plan = None;
|
||||
match event {
|
||||
AuthEvent::Close => {
|
||||
bail!(AuthenticationCancelled);
|
||||
}
|
||||
AuthEvent::RaiseWindow => self.raise_window(auth_window),
|
||||
AuthEvent::Data(generation, ..)
|
||||
| AuthEvent::Error(generation, _)
|
||||
| AuthEvent::NoAuthData(generation, _)
|
||||
| AuthEvent::PageLoaded(generation)
|
||||
| AuthEvent::TlsAccepted(generation)
|
||||
if generation != auth_messenger.generation() =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
AuthEvent::Error(_, AuthError::Tls(failure)) => {
|
||||
warn!("TLS failure for {}: {}", failure.host, failure.reason.message());
|
||||
restart = None;
|
||||
loading_deadline = None;
|
||||
recovery.tls_failed(failure.reason, failure.can_continue);
|
||||
}
|
||||
AuthEvent::RequestTlsException => {
|
||||
if recovery.status().can_continue() {
|
||||
auth_window.with_webview(|wv| {
|
||||
if let Err(err) = wv.confirm_tls_exception() {
|
||||
warn!("Failed to confirm certificate exception: {}", err);
|
||||
}
|
||||
})?;
|
||||
}
|
||||
}
|
||||
AuthEvent::TlsAccepted(_) => {
|
||||
retry_plan = recovery.certificate_accepted();
|
||||
}
|
||||
AuthEvent::NoAuthData(_, location) => {
|
||||
info!(
|
||||
"No auth data found in {:?}, it may not be the /SAML20/SP/ACS endpoint",
|
||||
location
|
||||
);
|
||||
self.handle_not_found(&auth_window, &auth_messenger);
|
||||
self.handle_not_found(auth_window, &auth_messenger);
|
||||
}
|
||||
AuthEvent::Error(AuthError::Invalid(err, location)) => {
|
||||
AuthEvent::Error(_, AuthError::Invalid(err, location)) => {
|
||||
warn!("Got invalid auth data in {:?}: {}", location, err);
|
||||
self.retry_auth(&auth_window).await;
|
||||
recovery.failure(false);
|
||||
}
|
||||
AuthEvent::Data(auth_data, location) => {
|
||||
AuthEvent::Error(_, AuthError::TemporarilyUnavailable) => {
|
||||
retry_plan = recovery.failure(true);
|
||||
}
|
||||
AuthEvent::Error(_, AuthError::LoadFailed(err)) => {
|
||||
if matches!(
|
||||
recovery.status(),
|
||||
RecoveryStatus::Loading | RecoveryStatus::Hidden | RecoveryStatus::CertificateBypassed
|
||||
) {
|
||||
warn!("Failed to load sign-in: {}", err);
|
||||
recovery.load_failed();
|
||||
loading_deadline = None;
|
||||
}
|
||||
}
|
||||
AuthEvent::Retry => {
|
||||
retry_plan = recovery.retry();
|
||||
}
|
||||
AuthEvent::PageLoaded(_) => {
|
||||
recovery.page_loaded();
|
||||
if !recovery.status().blocks_page() {
|
||||
loading_deadline = None;
|
||||
}
|
||||
}
|
||||
AuthEvent::Data(_, auth_data, location) => {
|
||||
if !recovery.status().accepts_auth_data() {
|
||||
continue;
|
||||
}
|
||||
info!("Got auth data from {:?}", location);
|
||||
|
||||
auth_window.close()?;
|
||||
return Ok(auth_data);
|
||||
}
|
||||
}
|
||||
if let Some(plan) = retry_plan {
|
||||
loading_deadline = None;
|
||||
auth_messenger.begin_attempt();
|
||||
auth_window.with_webview(|wv| wv.stop_loading())?;
|
||||
restart = Some(Box::pin(async move {
|
||||
time::timeout(RESTART_TIMEOUT, self.request_sign_in(plan)).await?
|
||||
}));
|
||||
}
|
||||
if recovery.status() != RecoveryStatus::Loading {
|
||||
loading_deadline = None;
|
||||
}
|
||||
self.update_recovery(auth_window, recovery.status())?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,13 +326,6 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
}
|
||||
});
|
||||
|
||||
// Show the window after 10 seconds, so that the user can see the window if the auth process is stuck
|
||||
let auth_messenger_clone = Arc::clone(&auth_messenger);
|
||||
tokio::spawn(async move {
|
||||
time::sleep(Duration::from_secs(10)).await;
|
||||
auth_messenger_clone.send_auth_event(AuthEvent::RaiseWindow);
|
||||
});
|
||||
|
||||
let auth_request = match self.auth_request {
|
||||
Some(auth_request) => auth_request.to_string(),
|
||||
None => auth_prelogin(&self.server, &self.gp_params, false, false).await?,
|
||||
@@ -231,19 +334,13 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
|
||||
let ignore_tls_errors = self.gp_params.ignore_tls_errors();
|
||||
let webview_user_agent = self.webview_user_agent.clone();
|
||||
let window = auth_window.clone();
|
||||
|
||||
// Set up webview
|
||||
auth_window.with_webview(move |wv| {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
use super::platform_impl::PlatformWebviewOnResponse;
|
||||
wv.on_response(Box::new(move |response| match response {
|
||||
Ok(response) => auth_messenger.read_from_response(&response),
|
||||
Err(err) => auth_messenger.send_auth_error(err),
|
||||
}));
|
||||
}
|
||||
|
||||
let controls_messenger = Arc::clone(&auth_messenger);
|
||||
let result = || -> anyhow::Result<()> {
|
||||
wv.install_auth_controls(&window, controls_messenger)?;
|
||||
if ignore_tls_errors {
|
||||
wv.ignore_tls_errors()?;
|
||||
}
|
||||
@@ -271,49 +368,48 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
auth_messenger.schedule_raise_window(2);
|
||||
}
|
||||
|
||||
async fn retry_auth(&self, auth_window: &WebviewWindow) {
|
||||
let mut is_retrying = self.is_retrying.write().await;
|
||||
if *is_retrying {
|
||||
info!("Already retrying authentication, skipping...");
|
||||
return;
|
||||
fn update_recovery(&self, auth_window: &WebviewWindow, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
if status != RecoveryStatus::Hidden {
|
||||
self.raise_window(auth_window);
|
||||
}
|
||||
|
||||
*is_retrying = true;
|
||||
drop(is_retrying);
|
||||
|
||||
if let Err(err) = self.retry_auth_impl(auth_window).await {
|
||||
warn!("Failed to retry authentication: {}", err);
|
||||
}
|
||||
|
||||
*self.is_retrying.write().await = false;
|
||||
}
|
||||
|
||||
async fn retry_auth_impl(&self, auth_window: &WebviewWindow) -> anyhow::Result<()> {
|
||||
info!("Retrying authentication...");
|
||||
|
||||
auth_window.eval( r#"
|
||||
var loading = document.createElement("div");
|
||||
loading.innerHTML = '<div style="position: absolute; width: 100%; text-align: center; font-size: 20px; font-weight: bold; top: 50%; left: 50%; transform: translate(-50%, -50%);">Got invalid token, retrying...</div>';
|
||||
loading.style = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 99999;";
|
||||
document.body.appendChild(loading);
|
||||
"#)?;
|
||||
|
||||
let auth_request = auth_prelogin(&self.server, &self.gp_params, false, false).await?;
|
||||
|
||||
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
|
||||
let webview_user_agent = self.webview_user_agent.clone();
|
||||
auth_window.with_webview(move |wv| {
|
||||
let result = || -> anyhow::Result<()> {
|
||||
load_auth_request_with_user_agent(&wv, webview_user_agent.as_ref(), &auth_request)
|
||||
}();
|
||||
|
||||
if let Err(result) = tx.send(result) {
|
||||
warn!("Failed to send retry auth result: {:?}", result);
|
||||
if let Err(err) = wv.set_recovery_status(status) {
|
||||
warn!("Failed to update sign-in status: {}", err);
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
rx.await??;
|
||||
async fn request_sign_in(&self, plan: RetryPlan) -> anyhow::Result<String> {
|
||||
info!("Restarting sign-in...");
|
||||
if plan.timing == RetryTiming::AutomaticDelay {
|
||||
time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
if plan.source == RetrySource::SuppliedRequest {
|
||||
if let Some(request) = self.auth_request {
|
||||
return Ok(request.to_owned());
|
||||
}
|
||||
}
|
||||
auth_prelogin(self.server, self.gp_params, false, false).await
|
||||
}
|
||||
|
||||
fn load_restarted_sign_in(
|
||||
&self,
|
||||
auth_window: &WebviewWindow,
|
||||
messenger: &Arc<AuthMessenger>,
|
||||
auth_request: String,
|
||||
) -> anyhow::Result<()> {
|
||||
let webview_user_agent = self.webview_user_agent.clone();
|
||||
let generation = messenger.generation();
|
||||
let messenger = Arc::clone(messenger);
|
||||
auth_window.with_webview(move |wv| {
|
||||
if generation != messenger.generation() {
|
||||
return;
|
||||
}
|
||||
if let Err(err) = load_auth_request_with_user_agent(&wv, webview_user_agent.as_ref(), &auth_request) {
|
||||
messenger.send_auth_event(AuthEvent::Error(generation, AuthError::LoadFailed(err)));
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -102,17 +108,6 @@ fn sibling_binary_for_executable(executable: &Path, binary_name: &str) -> Option
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn bundled_vpnc_script() -> Option<PathBuf> {
|
||||
bundled_vpnc_script_for_executable(&env::current_exe().ok()?)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn bundled_vpnc_script_for_executable(executable: &Path) -> Option<PathBuf> {
|
||||
let executable = executable.canonicalize().ok()?;
|
||||
macos::vpnc_script_path(&executable)
|
||||
}
|
||||
|
||||
fn is_file(path: &Path) -> bool {
|
||||
path.is_file()
|
||||
}
|
||||
@@ -121,6 +116,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() {
|
||||
@@ -151,18 +163,6 @@ mod tests {
|
||||
sibling_binary_for_executable(&bin.join("gpclient"), "gpauth"),
|
||||
Some(helpers.canonicalize().unwrap().join("gpauth"))
|
||||
);
|
||||
#[cfg(target_os = "macos")]
|
||||
assert_eq!(
|
||||
bundled_vpnc_script_for_executable(&bin.join("gpclient")),
|
||||
Some(
|
||||
helpers
|
||||
.canonicalize()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join("Resources/Scripts/vpnc-script")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -17,29 +17,3 @@ fn contents_dir(executable: &Path) -> Option<&Path> {
|
||||
pub(super) fn helper_path(executable: &Path, binary_name: &str) -> Option<PathBuf> {
|
||||
Some(contents_dir(executable)?.join("Helpers").join(binary_name))
|
||||
}
|
||||
|
||||
pub(super) fn vpnc_script_path(executable: &Path) -> Option<PathBuf> {
|
||||
Some(contents_dir(executable)?.join("Resources/Scripts/vpnc-script"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bundle_entry_points_use_their_own_vpnc_script() {
|
||||
for executable in [
|
||||
"/Applications/GP Connect.app/Contents/Helpers/gpclient",
|
||||
"/Applications/GP Connect.app/Contents/MacOS/gpgui",
|
||||
] {
|
||||
assert_eq!(
|
||||
vpnc_script_path(Path::new(executable)),
|
||||
Some(PathBuf::from(
|
||||
"/Applications/GP Connect.app/Contents/Resources/Scripts/vpnc-script"
|
||||
))
|
||||
);
|
||||
}
|
||||
assert!(vpnc_script_path(Path::new("/opt/homebrew/bin/gpclient")).is_none());
|
||||
assert!(vpnc_script_path(Path::new("/tmp/Contents/Helpers/gpclient")).is_none());
|
||||
}
|
||||
}
|
||||