Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ebe61de62 | ||
|
|
dbab0150fe | ||
|
|
1c9bef6e63 | ||
|
|
59102edfb5 | ||
|
|
aa41998e58 | ||
|
|
a3397e81a7 | ||
|
|
2910870371 | ||
|
|
fb82bb4b8d | ||
|
|
630e8ec0de | ||
|
|
890daea78f | ||
|
|
8e57f5723b | ||
|
|
bfb27a279f | ||
|
|
b33701a83f | ||
|
|
193dfc247f | ||
|
|
08389271f0 | ||
|
|
842df3201b | ||
|
|
cd8eb1d9eb | ||
|
|
32cd228c02 | ||
|
|
8b4821948d | ||
|
|
79b7837189 | ||
|
|
b62db0e9a1 | ||
|
|
581710a770 | ||
|
|
c92bdaed1d | ||
|
|
58738f6fd7 | ||
|
|
ada320044b | ||
|
|
fb35e6ee1c | ||
|
|
4cfa9a9b5b | ||
|
|
d1d9f0c6fc | ||
|
|
cc4d35c228 | ||
|
|
17d1555155 | ||
|
|
588790f2d5 | ||
|
|
918abeb9bc | ||
|
|
812965f020 | ||
|
|
5c3b7d118a | ||
|
|
4fdcb15629 | ||
|
|
88f4623f52 | ||
|
|
3d2dfe4be0 | ||
|
|
8c831b1fc2 | ||
|
|
912bf3046d | ||
|
|
4a12de6156 | ||
|
|
b0b8e5ec32 | ||
|
|
cfe8430cae | ||
|
|
7ae09aad8c | ||
|
|
40b35804e7 | ||
|
|
6999b2725e | ||
|
|
0a528b4aae | ||
|
|
7134d92ee8 | ||
|
|
d21b909a0d | ||
|
|
e066362c92 | ||
|
|
fd9b48cd90 | ||
|
|
2c29dda2ac | ||
|
|
d3845678ab | ||
|
|
355f8d82aa | ||
|
|
2ca6b80728 | ||
|
|
c0c517806e | ||
|
|
537e12d706 | ||
|
|
4197927f56 | ||
|
|
1b7380d2f2 | ||
|
|
090e479e20 | ||
|
|
cbce8b5609 | ||
|
|
6edd3408aa | ||
|
|
5da7b45407 | ||
|
|
bd064713a8 | ||
|
|
822d10528f | ||
|
|
ce8cc5b8dd | ||
|
|
b407c56239 | ||
|
|
9c1428fb72 | ||
|
|
ce97729984 | ||
|
|
3817227942 | ||
|
|
88975379bf | ||
|
|
11b410f1d9 | ||
|
|
917e1091a1 | ||
|
|
68f35cc582 | ||
|
|
293cd56930 | ||
|
|
ca221e3488 | ||
|
|
6e01164a56 | ||
|
|
d83bb22c58 | ||
|
|
e808ccbdb5 | ||
|
|
f17dd27d55 | ||
|
|
2b7b97f0e4 | ||
|
|
3a2398e677 | ||
|
|
7a373813ce | ||
|
|
8a41765c53 | ||
|
|
7a16e6bce8 | ||
|
|
6d23d41797 | ||
|
|
5263c03889 | ||
|
|
c44be546c3 | ||
|
|
63c873a906 | ||
|
|
3c16026acc | ||
|
|
81fcd253d3 | ||
|
|
4f94a28ad2 | ||
|
|
f403f19164 | ||
|
|
ab10af726b | ||
|
|
52f719d192 | ||
|
|
6723685385 | ||
|
|
aa14c67e92 | ||
|
|
fa14b94520 | ||
|
|
ded66586b2 | ||
|
|
cb1716ba9c | ||
|
|
25cca2831b |
No files matched your search
@@ -0,0 +1,30 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,115 +0,0 @@
|
||||
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.
|
||||
@@ -1,98 +0,0 @@
|
||||
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,37 +2,26 @@ 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 ref to build (use the matching tag for stable builds)'
|
||||
description: 'GlobalProtect-openconnect branch to use for the snapshot release'
|
||||
required: true
|
||||
default: dev
|
||||
gpgui_branch:
|
||||
description: 'gpgui ref to build (use the matching tag for stable builds)'
|
||||
description: 'gpgui branch to use for the snapshot release'
|
||||
required: true
|
||||
default: dev
|
||||
build_macos:
|
||||
description: 'Build Apple Silicon artifacts for this run'
|
||||
description: 'Build Apple Silicon artifacts for the snapshot release'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
build_bsd:
|
||||
description: 'Build FreeBSD/OpenBSD packages for this run'
|
||||
description: 'Build FreeBSD/OpenBSD packages for the snapshot release'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
build_bsd_arm64:
|
||||
description: 'Build optional FreeBSD/OpenBSD arm64 packages for this run. Slow and disabled by default'
|
||||
description: 'Build optional FreeBSD/OpenBSD arm64 packages for the snapshot release. Slow and disabled by default'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
@@ -44,33 +33,18 @@ on:
|
||||
- .devcontainer
|
||||
branches:
|
||||
- main
|
||||
- hotfix/*
|
||||
- feature/*
|
||||
- release/*
|
||||
tags:
|
||||
- v*.*.*
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && (inputs.build_only && github.run_id || 'release') || github.ref }}
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && 'release' || github.ref }}
|
||||
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
|
||||
@@ -80,35 +54,19 @@ jobs:
|
||||
repository: yuezk/GlobalProtect-openconnect
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
|
||||
submodules: recursive
|
||||
- name: Run Rust tests as a non-root user with focused privilege checks
|
||||
- name: Run Rust tests in Docker
|
||||
run: |
|
||||
docker run --rm \
|
||||
--user vscode \
|
||||
-e HOME=/home/vscode \
|
||||
-e CARGO_TARGET_DIR=/tmp/gp-test-target \
|
||||
--user root \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-e LIBXML2_STATIC=1 \
|
||||
-v "$(pwd):/workspace:ro" \
|
||||
-e PKEXEC_UID=1000 \
|
||||
-v "$(pwd):/workspace" \
|
||||
-w /workspace \
|
||||
yuezk/gpdev:binary-builder-tauri2 \
|
||||
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
|
||||
'
|
||||
cargo test --workspace
|
||||
|
||||
tarball:
|
||||
needs: validate-inputs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: pnpm/action-setup@v5
|
||||
@@ -127,12 +85,10 @@ 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
|
||||
# Stable manual builds use tagged source even when dispatched from main.
|
||||
if [[ "$IS_SNAPSHOT" == true ]]; then
|
||||
# Generate the SNAPSHOT file for non-tagged commits
|
||||
if [[ "${{ github.ref }}" != "refs/tags/"* ]]; then
|
||||
touch SNAPSHOT
|
||||
fi
|
||||
make tarball
|
||||
@@ -141,7 +97,7 @@ jobs:
|
||||
|
||||
- name: Generate RPM spec file
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
|
||||
run: |
|
||||
cd source/gp
|
||||
|
||||
@@ -201,7 +157,7 @@ jobs:
|
||||
if-no-files-found: error
|
||||
|
||||
build-gp:
|
||||
if: ${{ !(startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
needs:
|
||||
- tarball
|
||||
strategy:
|
||||
@@ -252,7 +208,7 @@ jobs:
|
||||
build-gp-${{ matrix.package }}/artifacts/*
|
||||
|
||||
build-docker-image:
|
||||
if: ${{ !(startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -277,13 +233,11 @@ jobs:
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
- name: Login to Docker Hub
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_HUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
- name: Build and push by digest
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
|
||||
id: build
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
@@ -291,37 +245,20 @@ jobs:
|
||||
file: packaging/docker/alpine/Dockerfile
|
||||
platforms: ${{ matrix.platform }}
|
||||
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
|
||||
- name: Build local image for verification
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: packaging/docker/alpine/Dockerfile
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: yuezk/globalprotect-openconnect:build-test
|
||||
load: true
|
||||
push: false
|
||||
- name: Verify CLI tools
|
||||
env:
|
||||
IMAGE: yuezk/globalprotect-openconnect
|
||||
DIGEST: ${{ steps.build.outputs.digest }}
|
||||
BUILD_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
|
||||
run: |
|
||||
image_ref="$IMAGE@$DIGEST"
|
||||
if [[ "$BUILD_ONLY" == "true" ]]; then
|
||||
image_ref="$IMAGE:build-test"
|
||||
fi
|
||||
docker run --rm "$image_ref" --help
|
||||
docker run --rm --entrypoint gpauth "$image_ref" --help
|
||||
docker run --rm --entrypoint sh "$image_ref" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
|
||||
docker run --rm "$IMAGE@$DIGEST" --help
|
||||
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
|
||||
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
|
||||
- name: Export digest
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
|
||||
run: |
|
||||
mkdir -p /tmp/digests
|
||||
digest="${{ steps.build.outputs.digest }}"
|
||||
touch "/tmp/digests/${digest#sha256:}"
|
||||
- name: Upload digest
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: digests-${{ env.PLATFORM_PAIR }}
|
||||
@@ -329,162 +266,93 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
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-glibc]
|
||||
build-gpgui:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform:
|
||||
os:
|
||||
- runner: ubuntu-latest
|
||||
system: x86_64-linux
|
||||
artifact_arch: amd64
|
||||
arch: amd64
|
||||
- runner: ubuntu-24.04-arm
|
||||
system: aarch64-linux
|
||||
artifact_arch: ubuntu-24.04-arm
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
name: nix-source (${{ matrix.platform.system }})
|
||||
env:
|
||||
NIX_SYSTEM: ${{ matrix.platform.system }}
|
||||
NIXPKGS: locked
|
||||
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:
|
||||
- name: Checkout source and dependencies
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
|
||||
submodules: recursive
|
||||
path: gp
|
||||
- name: Download current GUI artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: artifact-gpgui-${{ matrix.platform.artifact_arch }}
|
||||
path: nix-artifacts/gui
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
- name: Configure current source and GUI inputs
|
||||
run: |
|
||||
echo "GP_SOURCE=$PWD/gp" >> "$GITHUB_ENV"
|
||||
gui_archive=$(find "$PWD/nix-artifacts/gui" -name '*.bin.tar.xz' -type f)
|
||||
test -f "$gui_archive"
|
||||
echo "GP_GUI_ARCHIVE=$gui_archive" >> "$GITHUB_ENV"
|
||||
- name: Build source package
|
||||
run: |
|
||||
nix build --impure --file gp/nix/ci.nix source \
|
||||
--extra-experimental-features "nix-command flakes" --print-build-logs
|
||||
bash gp/scripts/tests/nix-desktop-authorization.sh result
|
||||
- name: Test source runtime in NixOS
|
||||
if: matrix.platform.system == 'x86_64-linux'
|
||||
run: |
|
||||
nix build --impure --file gp/nix/ci.nix runtime-source \
|
||||
--extra-experimental-features "nix-command flakes" --print-build-logs
|
||||
|
||||
nix-prebuilt:
|
||||
needs: [build-gp, build-gpgui-glibc]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform:
|
||||
- runner: ubuntu-latest
|
||||
system: x86_64-linux
|
||||
artifact_arch: amd64
|
||||
- runner: ubuntu-24.04-arm
|
||||
system: aarch64-linux
|
||||
artifact_arch: ubuntu-24.04-arm
|
||||
nixpkgs: [locked, nixos-25.11, nixos-26.05, nixpkgs-unstable]
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
name: nix-prebuilt (${{ matrix.platform.system }}, ${{ matrix.nixpkgs }})
|
||||
env:
|
||||
NIX_SYSTEM: ${{ matrix.platform.system }}
|
||||
NIXPKGS: ${{ matrix.nixpkgs }}
|
||||
steps:
|
||||
- name: Checkout packaging and tests
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
|
||||
submodules: recursive
|
||||
path: gp
|
||||
- name: Download current Linux binary artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: artifact-gp-binary-${{ matrix.platform.artifact_arch }}
|
||||
path: nix-artifacts/binaries
|
||||
- name: Download current GUI artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: artifact-gpgui-${{ matrix.platform.artifact_arch }}
|
||||
path: nix-artifacts/gui
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
- name: Configure current artifact inputs
|
||||
run: |
|
||||
echo "GP_SOURCE=$PWD/gp" >> "$GITHUB_ENV"
|
||||
binary_archive=$(find "$PWD/nix-artifacts/binaries" -name '*.bin.tar.xz' -type f)
|
||||
gui_archive=$(find "$PWD/nix-artifacts/gui" -name '*.bin.tar.xz' -type f)
|
||||
test -f "$binary_archive"
|
||||
test -f "$gui_archive"
|
||||
echo "GP_BINARY_ARCHIVE=$binary_archive" >> "$GITHUB_ENV"
|
||||
echo "GP_GUI_ARCHIVE=$gui_archive" >> "$GITHUB_ENV"
|
||||
- name: Build package through host NixOS module
|
||||
run: |
|
||||
nix build --impure --file gp/nix/ci.nix module \
|
||||
--extra-experimental-features "nix-command flakes" --print-build-logs
|
||||
bash gp/scripts/tests/nix-desktop-authorization.sh result
|
||||
- name: Build standalone prebuilt package
|
||||
if: matrix.nixpkgs == 'locked'
|
||||
run: |
|
||||
nix build --impure --file gp/nix/ci.nix prebuilt \
|
||||
--extra-experimental-features "nix-command flakes" --print-build-logs
|
||||
- name: Test prebuilt runtime in NixOS
|
||||
if: matrix.nixpkgs == 'locked' && matrix.platform.system == 'x86_64-linux'
|
||||
run: |
|
||||
nix build --impure --file gp/nix/ci.nix runtime-prebuilt \
|
||||
--extra-experimental-features "nix-command flakes" --print-build-logs
|
||||
- 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
|
||||
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' }} \
|
||||
-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
|
||||
|
||||
trigger-gpgui-macos:
|
||||
needs: test-gp
|
||||
if: ${{ (github.event_name == 'workflow_dispatch' && inputs.build_macos) || (startsWith(github.ref, 'refs/tags/') && vars.BUILD_MACOS_ON_TAG == 'true') }}
|
||||
if: ${{ startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.build_macos) }}
|
||||
permissions:
|
||||
contents: read
|
||||
runs-on: ubuntu-latest
|
||||
name: trigger private macOS build
|
||||
name: trigger private macOS release
|
||||
outputs:
|
||||
run_id: ${{ steps.dispatch.outputs.run_id }}
|
||||
run_url: ${{ steps.dispatch.outputs.run_url }}
|
||||
steps:
|
||||
- name: Dispatch private macOS build
|
||||
- name: Dispatch private macOS release
|
||||
id: dispatch
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
|
||||
PUBLIC_GH_TOKEN: ${{ github.token }}
|
||||
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 }}
|
||||
CHANNEL: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && '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 }}
|
||||
@@ -507,7 +375,7 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
expected_title="macOS build $CHANNEL $RELEASE_TAG ($REQUEST_ID)"
|
||||
expected_title="macOS $CHANNEL $RELEASE_TAG ($REQUEST_ID)"
|
||||
jq -n \
|
||||
--arg workflow_ref "$GPGUI_REF" \
|
||||
--arg request_id "$REQUEST_ID" \
|
||||
@@ -527,14 +395,14 @@ jobs:
|
||||
gpgui_ref: $gpgui_ref
|
||||
}
|
||||
}' | gh api --method POST \
|
||||
repos/yuezk/gpgui/actions/workflows/build-macos.yaml/dispatches \
|
||||
repos/yuezk/gpgui/actions/workflows/release-macos.yaml/dispatches \
|
||||
--input -
|
||||
|
||||
run_id=""
|
||||
run_url=""
|
||||
for _ in {1..40}; do
|
||||
runs="$(gh api \
|
||||
'repos/yuezk/gpgui/actions/workflows/build-macos.yaml/runs?event=workflow_dispatch&per_page=50')"
|
||||
'repos/yuezk/gpgui/actions/workflows/release-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")"
|
||||
@@ -556,7 +424,6 @@ jobs:
|
||||
exit 1
|
||||
|
||||
setup-bsd-matrix:
|
||||
needs: validate-inputs
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
enabled: ${{ steps.matrix.outputs.enabled }}
|
||||
@@ -565,7 +432,7 @@ jobs:
|
||||
- name: Build matrix
|
||||
id: matrix
|
||||
env:
|
||||
BUILD_BSD_ON_TAG: ${{ startsWith(github.ref, 'refs/tags/') && vars.BUILD_BSD_ON_TAG == 'true' }}
|
||||
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||
BUILD_BSD: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd }}
|
||||
BUILD_BSD_ARM64: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd_arm64 }}
|
||||
run: |
|
||||
@@ -573,7 +440,7 @@ jobs:
|
||||
import json
|
||||
import os
|
||||
|
||||
build_bsd = os.environ["BUILD_BSD_ON_TAG"] == "true" or os.environ["BUILD_BSD"] == "true"
|
||||
build_bsd = os.environ["IS_TAG"] == "true" or os.environ["BUILD_BSD"] == "true"
|
||||
build_bsd_arm64 = os.environ["BUILD_BSD_ARM64"] == "true"
|
||||
include = []
|
||||
|
||||
@@ -700,8 +567,7 @@ jobs:
|
||||
run: |
|
||||
set -eu
|
||||
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
|
||||
|
||||
cd "${{ matrix.workspace }}/gp"
|
||||
cargo build --release --workspace
|
||||
@@ -725,23 +591,22 @@ jobs:
|
||||
arch: ${{ matrix.arch }}
|
||||
usesh: true
|
||||
prepare: |
|
||||
set -eu
|
||||
pkg_add -u -I
|
||||
pkg_add -I \
|
||||
pkg_add -z \
|
||||
git \
|
||||
rust \
|
||||
libiconv \
|
||||
gettext-tools \
|
||||
autoconf%2.72 \
|
||||
automake%1.17 \
|
||||
autoconf-2.72 \
|
||||
automake-1.17 \
|
||||
libtool \
|
||||
patch \
|
||||
gmake \
|
||||
pkgconf \
|
||||
libxml \
|
||||
gnutls \
|
||||
p11-kit \
|
||||
nettle \
|
||||
gmp \
|
||||
lz4 \
|
||||
dbus \
|
||||
gnome-keyring \
|
||||
polkit \
|
||||
webkitgtk41 \
|
||||
@@ -757,8 +622,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' && inputs.channel || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
|
||||
|
||||
cd "${{ matrix.workspace }}/gp"
|
||||
cargo build --release --workspace
|
||||
@@ -783,7 +647,7 @@ jobs:
|
||||
${{ matrix.workspace }}/gp/.build/${{ matrix.artifact_dir }}/artifacts/*
|
||||
|
||||
gh-release:
|
||||
if: ${{ always() && ((github.event_name == 'workflow_dispatch' && !inputs.build_only) || (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))) }}
|
||||
if: ${{ always() && (github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/')) }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
@@ -792,15 +656,11 @@ jobs:
|
||||
attestations: write
|
||||
artifact-metadata: write
|
||||
needs:
|
||||
- test-gp
|
||||
- nix-source
|
||||
- nix-prebuilt
|
||||
- tarball
|
||||
- tarball-offline
|
||||
- build-gp
|
||||
- build-docker-image
|
||||
- build-gpgui-glibc
|
||||
- build-gpgui-musl
|
||||
- build-gpgui
|
||||
- setup-bsd-matrix
|
||||
- build-gpgui-frontend
|
||||
- build-bsd
|
||||
@@ -810,7 +670,7 @@ jobs:
|
||||
env:
|
||||
NEEDS_JSON: ${{ toJson(needs) }}
|
||||
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
|
||||
IS_STABLE: ${{ (startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
|
||||
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
@@ -819,14 +679,14 @@ jobs:
|
||||
|
||||
needs = json.loads(os.environ["NEEDS_JSON"])
|
||||
bsd_matrix_enabled = os.environ["BSD_MATRIX_ENABLED"] == "true"
|
||||
is_stable = os.environ["IS_STABLE"] == "true"
|
||||
is_tag = os.environ["IS_TAG"] == "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_stable:
|
||||
elif name in {"build-gp", "build-docker-image"} and result == "skipped" and is_tag:
|
||||
continue
|
||||
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
|
||||
continue
|
||||
@@ -870,7 +730,7 @@ jobs:
|
||||
|
||||
- name: Generate release asset checksums
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
|
||||
run: |
|
||||
cd gh-release/gp
|
||||
mkdir -p .build
|
||||
@@ -892,20 +752,22 @@ jobs:
|
||||
- name: Create GH release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
|
||||
run: |
|
||||
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
|
||||
|
||||
wait-gpgui-macos:
|
||||
if: ${{ !cancelled() && needs.trigger-gpgui-macos.result == 'success' }}
|
||||
if: ${{ always() && needs.trigger-gpgui-macos.result != 'skipped' }}
|
||||
needs:
|
||||
- gh-release
|
||||
- trigger-gpgui-macos
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 130
|
||||
steps:
|
||||
- name: Wait for private macOS build
|
||||
- name: Wait for private macOS release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
|
||||
PUBLIC_RELEASE_RESULT: ${{ needs.gh-release.result }}
|
||||
PRIVATE_RUN_ID: ${{ needs.trigger-gpgui-macos.outputs.run_id }}
|
||||
PRIVATE_RUN_URL: ${{ needs.trigger-gpgui-macos.outputs.run_url }}
|
||||
run: |
|
||||
@@ -915,14 +777,21 @@ jobs:
|
||||
echo "The private macOS workflow was not started" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$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 build completed: $PRIVATE_RUN_URL"
|
||||
echo "Private macOS workflow completed: $PRIVATE_RUN_URL"
|
||||
if [[ "$conclusion" != "success" ]]; then
|
||||
echo "Private macOS build concluded with: $conclusion" >&2
|
||||
echo "Private macOS workflow concluded with: $conclusion" >&2
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
||||
@@ -932,17 +801,15 @@ jobs:
|
||||
|
||||
gh api --method POST \
|
||||
"repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID/cancel" >/dev/null || true
|
||||
echo "Private macOS build timed out: $PRIVATE_RUN_URL" >&2
|
||||
echo "Private macOS workflow 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) || (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')) }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -960,9 +827,9 @@ jobs:
|
||||
working-directory: /tmp/digests
|
||||
env:
|
||||
IMAGE: yuezk/globalprotect-openconnect
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
|
||||
run: |
|
||||
docker buildx imagetools create -t "$IMAGE:$RELEASE_TAG" \
|
||||
$(printf "$IMAGE@sha256:%s " *)
|
||||
|
||||
"$GITHUB_WORKSPACE/scripts/verify-docker-publication.sh" "$IMAGE:$RELEASE_TAG" /tmp/digests all
|
||||
docker buildx imagetools inspect "$IMAGE:$RELEASE_TAG"
|
||||
@@ -1,118 +0,0 @@
|
||||
name: Nix
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "flake.nix"
|
||||
- "flake.lock"
|
||||
- "nix/**"
|
||||
- ".github/workflows/nix.yaml"
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "flake.nix"
|
||||
- "flake.lock"
|
||||
- "nix/**"
|
||||
- ".github/workflows/nix.yaml"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
standalone-package:
|
||||
name: standalone-package (${{ matrix.platform.system }})
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform:
|
||||
- runner: ubuntu-latest
|
||||
system: x86_64-linux
|
||||
- runner: ubuntu-24.04-arm
|
||||
system: aarch64-linux
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
steps:
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
|
||||
- name: Build standalone prebuilt package
|
||||
run: |
|
||||
nix build .#prebuilt \
|
||||
--extra-experimental-features "nix-command flakes" \
|
||||
--print-build-logs
|
||||
|
||||
- name: Inspect prebuilt package
|
||||
run: |
|
||||
test -x result/bin/gpclient
|
||||
test -x result/bin/gpauth
|
||||
test -x result/bin/gpservice
|
||||
test -x result/bin/gpgui-helper
|
||||
test -x result/bin/gpgui
|
||||
|
||||
nixos-module:
|
||||
name: nixos-module (${{ matrix.platform.system }}, ${{ matrix.nixpkgs }})
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform:
|
||||
- runner: ubuntu-latest
|
||||
system: x86_64-linux
|
||||
- runner: ubuntu-24.04-arm
|
||||
system: aarch64-linux
|
||||
nixpkgs:
|
||||
- nixos-25.11
|
||||
- nixos-26.05
|
||||
- nixpkgs-unstable
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
steps:
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
|
||||
- name: Build package through host NixOS module
|
||||
env:
|
||||
NIXPKGS_URL: github:NixOS/nixpkgs/${{ matrix.nixpkgs }}
|
||||
NIX_SYSTEM: ${{ matrix.platform.system }}
|
||||
run: |
|
||||
nix build \
|
||||
--impure \
|
||||
--extra-experimental-features "nix-command flakes" \
|
||||
--print-build-logs \
|
||||
--expr '
|
||||
let
|
||||
gp = builtins.getFlake (toString ./.);
|
||||
hostNixpkgs =
|
||||
builtins.getFlake (builtins.getEnv "NIXPKGS_URL");
|
||||
|
||||
hostSystem = hostNixpkgs.lib.nixosSystem {
|
||||
system = builtins.getEnv "NIX_SYSTEM";
|
||||
modules = [
|
||||
gp.nixosModules.default
|
||||
{
|
||||
programs.globalprotect-openconnect.enable = true;
|
||||
system.stateVersion = "25.11";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
package =
|
||||
hostSystem.config.programs.globalprotect-openconnect.package;
|
||||
in
|
||||
assert builtins.elem package
|
||||
hostSystem.config.environment.systemPackages;
|
||||
assert hostSystem.config.services.ayatana-indicators.enable;
|
||||
package
|
||||
'
|
||||
|
||||
- name: Inspect module package
|
||||
run: |
|
||||
test -x result/bin/gpclient
|
||||
test -x result/bin/gpauth
|
||||
test -x result/bin/gpservice
|
||||
test -x result/bin/gpgui-helper
|
||||
test -x result/bin/gpgui
|
||||
@@ -44,34 +44,23 @@ 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 \
|
||||
nettle \
|
||||
openconnect \
|
||||
openssl \
|
||||
patch \
|
||||
pkgconf \
|
||||
librsvg \
|
||||
shared-mime-info \
|
||||
vpnc \
|
||||
wget \
|
||||
webkit2gtk-4.1 \
|
||||
xdg-utils \
|
||||
zlib
|
||||
webkit2gtk-4.1
|
||||
|
||||
- name: Save committed .SRCINFO
|
||||
if: ${{ github.event_name == 'push' }}
|
||||
|
||||
@@ -11,18 +11,6 @@ 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
|
||||
@@ -31,14 +19,9 @@ 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 python3 zstd
|
||||
- uses: actions/checkout@v6
|
||||
run: dnf install -y copr-cli gh
|
||||
|
||||
- name: Check inputs
|
||||
env:
|
||||
@@ -46,28 +29,14 @@ jobs:
|
||||
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
|
||||
if [[ ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Revision must be a positive integer" >&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 }}
|
||||
@@ -80,7 +49,6 @@ jobs:
|
||||
--dir publish-copr
|
||||
|
||||
- name: Set package revision
|
||||
if: ${{ inputs.build_id == '' }}
|
||||
env:
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
@@ -98,7 +66,6 @@ jobs:
|
||||
grep '^Release:' "$spec"
|
||||
|
||||
- name: Configure COPR authentication
|
||||
if: ${{ inputs.build_id == '' }}
|
||||
env:
|
||||
COPR_CONFIG: ${{ secrets.COPR_CONFIG }}
|
||||
run: |
|
||||
@@ -106,38 +73,8 @@ jobs:
|
||||
printf '%s\n' "$COPR_CONFIG" > "$HOME/.config/copr"
|
||||
chmod 600 "$HOME/.config/copr"
|
||||
|
||||
- name: Submit or select Copr build
|
||||
id: build
|
||||
env:
|
||||
EXISTING_BUILD_ID: ${{ inputs.build_id }}
|
||||
CHROOTS: ${{ steps.targets.outputs.targets }}
|
||||
- name: Build and publish COPR package
|
||||
run: |
|
||||
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"
|
||||
copr-cli build \
|
||||
yuezk/globalprotect-openconnect \
|
||||
publish-copr/globalprotect-openconnect.spec
|
||||
@@ -11,18 +11,6 @@ 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
|
||||
@@ -30,19 +18,15 @@ 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 [[ ! "$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
|
||||
if [[ ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Revision must be a positive integer" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -77,22 +61,7 @@ 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
|
||||
@@ -101,12 +70,3 @@ 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
|
||||
@@ -19,19 +19,7 @@ on:
|
||||
description: 'Rust version to use'
|
||||
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
|
||||
|
||||
default: "1.89"
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -40,12 +28,7 @@ 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
|
||||
@@ -84,14 +67,8 @@ 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: .}')"
|
||||
@@ -102,7 +79,6 @@ jobs:
|
||||
needs: [check, resolve-series]
|
||||
name: publish-ppa (${{ matrix.series }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 210
|
||||
container:
|
||||
image: ubuntu:${{ matrix.series }}
|
||||
strategy:
|
||||
@@ -112,7 +88,7 @@ jobs:
|
||||
- name: Install container tools
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y ca-certificates curl gpg sudo python3 distro-info distro-info-data
|
||||
apt-get install -y ca-certificates curl gpg sudo
|
||||
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
|
||||
@@ -121,12 +97,9 @@ 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: |
|
||||
@@ -135,23 +108,17 @@ 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
|
||||
archives=(./*.offline.tar.gz)
|
||||
[[ "${#archives[@]}" -eq 1 && -f "${archives[0]}" ]]
|
||||
archive="${archives[0]%.offline.tar.gz}.tar.gz"
|
||||
mv -v -- "${archives[0]}" "$archive"
|
||||
mv -v *.tar.gz $(basename *.tar.gz .offline.tar.gz).tar.gz
|
||||
|
||||
# Extract the source tarball
|
||||
tar -xzf "$archive"
|
||||
tar -xzf *.tar.gz
|
||||
|
||||
# Prepare the debian directory with custom files
|
||||
source_dirs=(./globalprotect-openconnect-*/)
|
||||
[[ "${#source_dirs[@]}" -eq 1 && -d "${source_dirs[0]}" ]]
|
||||
cd "${source_dirs[0]}"
|
||||
cd globalprotect-openconnect-*/
|
||||
|
||||
# Prepare the debian directory with custom files
|
||||
mkdir -p .build/debian
|
||||
@@ -170,7 +137,6 @@ 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"
|
||||
@@ -183,14 +149,3 @@ 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}"
|
||||
@@ -1,38 +0,0 @@
|
||||
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,7 +215,6 @@ jobs:
|
||||
if: ${{ inputs.release-docker }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -245,20 +244,13 @@ jobs:
|
||||
docker buildx imagetools create "${tags[@]}" \
|
||||
$(printf "$IMAGE@sha256:%s " *)
|
||||
|
||||
"$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
|
||||
docker buildx imagetools inspect "$IMAGE:$TAG"
|
||||
|
||||
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
|
||||
@@ -320,23 +312,3 @@ 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,14 +1,6 @@
|
||||
name: Update flake hashes
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
version:
|
||||
required: true
|
||||
type: string
|
||||
release_tag:
|
||||
required: true
|
||||
type: string
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
@@ -32,11 +24,6 @@ jobs:
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
|
||||
- name: Update Nixpkgs lock
|
||||
run: |
|
||||
nix flake update nixpkgs \
|
||||
--extra-experimental-features "nix-command flakes"
|
||||
|
||||
- name: Update flake hashes
|
||||
env:
|
||||
RELEASE_VERSION: ${{ inputs.version }}
|
||||
@@ -52,9 +39,7 @@ jobs:
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: updated-flake
|
||||
path: |
|
||||
flake.nix
|
||||
flake.lock
|
||||
path: flake.nix
|
||||
if-no-files-found: error
|
||||
|
||||
validate-nix-prebuilt:
|
||||
@@ -63,22 +48,22 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
runner:
|
||||
- ubuntu-latest
|
||||
- ubuntu-24.04-arm
|
||||
nixpkgs:
|
||||
- locked
|
||||
- nixos-25.11
|
||||
- nixos-26.05
|
||||
- nixpkgs-unstable
|
||||
exclude:
|
||||
include:
|
||||
- runner: ubuntu-latest
|
||||
nixpkgs: nixos-25.11
|
||||
- runner: ubuntu-latest
|
||||
nixpkgs: nixos-26.05
|
||||
- runner: ubuntu-24.04-arm
|
||||
nixpkgs: locked
|
||||
nixpkgs: nixos-25.11
|
||||
- runner: ubuntu-24.04-arm
|
||||
nixpkgs: nixos-26.05
|
||||
name: validate-nix-prebuilt (${{ matrix.nixpkgs }}, ${{ matrix.runner }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Download updated flake
|
||||
uses: actions/download-artifact@v8
|
||||
@@ -90,19 +75,11 @@ jobs:
|
||||
uses: cachix/install-nix-action@v31
|
||||
|
||||
- name: Build prebuilt Nix package
|
||||
env:
|
||||
NIXPKGS: ${{ matrix.nixpkgs }}
|
||||
run: |
|
||||
if [[ "$NIXPKGS" == "locked" ]]; then
|
||||
nix build .#prebuilt \
|
||||
--extra-experimental-features "nix-command flakes" \
|
||||
--print-build-logs
|
||||
else
|
||||
nix build .#prebuilt \
|
||||
--override-input nixpkgs "github:NixOS/nixpkgs/$NIXPKGS" \
|
||||
--extra-experimental-features "nix-command flakes" \
|
||||
--print-build-logs
|
||||
fi
|
||||
nix build .#prebuilt \
|
||||
--override-input nixpkgs "github:NixOS/nixpkgs/${{ matrix.nixpkgs }}" \
|
||||
--extra-experimental-features "nix-command flakes" \
|
||||
--print-build-logs
|
||||
|
||||
- name: Inspect prebuilt Nix package
|
||||
run: |
|
||||
@@ -112,19 +89,14 @@ jobs:
|
||||
test -x result/bin/gpgui-helper
|
||||
test -x result/bin/gpgui
|
||||
test ! -L result/bin/gpservice
|
||||
test -x result/libexec/gpclient/gp-vpnc-script-installer
|
||||
test -x result/libexec/gpclient/gp-hip-script-installer
|
||||
result/bin/gpclient --version
|
||||
result/bin/gpservice --version
|
||||
result/bin/gpauth --version
|
||||
head -n1 result/bin/gpclient | grep '^#!'
|
||||
head -n1 result/bin/gpservice | grep '^#!'
|
||||
grep -q '/run/wrappers/bin/pkexec' result/bin/gpclient
|
||||
grep -q 'gpservice_public=.*/bin/gpservice' result/bin/gpclient
|
||||
grep -q 'exec .*/bin/gpservice' result/bin/gpservice
|
||||
! grep -q '@gpservice_public@\|@gpservice_fhs@\|\$out/bin/gpservice' result/bin/gpclient result/bin/gpservice
|
||||
|
||||
if grep -R '/usr/bin/gp' result/share; then
|
||||
echo "Desktop assets contain paths outside the Nix package" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Verify desktop authorization runs on the host
|
||||
run: bash scripts/tests/nix-desktop-authorization.sh result
|
||||
! grep -R '/usr/bin/gp' result/share
|
||||
|
||||
open-pull-request:
|
||||
needs:
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
.idea
|
||||
.DS_Store
|
||||
/target
|
||||
.pnpm-store
|
||||
.env
|
||||
@@ -16,3 +15,5 @@ gen
|
||||
|
||||
# Nix files
|
||||
result
|
||||
|
||||
.DS_Store
|
||||
@@ -10,8 +10,8 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.91"
|
||||
version = "3.0.6"
|
||||
rust-version = "1.89"
|
||||
version = "2.6.5"
|
||||
authors = ["Kevin Yue <[email protected]>"]
|
||||
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
edition = "2024"
|
||||
@@ -19,47 +19,47 @@ license = "GPL-3.0"
|
||||
|
||||
[workspace.dependencies]
|
||||
anyhow = "1.0"
|
||||
askama = { version = "0.16", default-features = false, features = ["std", "derive", "config"] }
|
||||
base64 = { version = "0.23", default-features = false, features = ["std"] }
|
||||
askama = "0.16"
|
||||
base64 = "0.22"
|
||||
chrono = "0.4"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
clap-verbosity-flag = "3"
|
||||
ctrlc = "3.4"
|
||||
directories = "6.0"
|
||||
dns-lookup = "4.0.2"
|
||||
dns-lookup = "3"
|
||||
env_logger = "0.11"
|
||||
is_executable = "1.0"
|
||||
log = "0.4"
|
||||
# RUST_LOG accepts user-supplied Unicode property filters through env_logger.
|
||||
regex = { version = "1", default-features = false, features = ["std", "perf", "unicode"] }
|
||||
regex = "1"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["native-tls", "charset", "http2", "system-proxy", "json", "form", "query"] }
|
||||
openssl = "0.10"
|
||||
pem = "4"
|
||||
pem = "3"
|
||||
xmltree = { version = "0.12", features = ["attribute-order"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
# The 0.39 series requires Rust 1.95, above the workspace minimum.
|
||||
sysinfo = { version = "0.38.4", default-features = false, features = ["system"] }
|
||||
# Use 0.36 as newer versions requires Rust 1.88+
|
||||
sysinfo = "0.36"
|
||||
tempfile = "3.8"
|
||||
tokio = { version = "1" }
|
||||
tokio-util = "0.7"
|
||||
url = "2.4"
|
||||
urlencoding = "2.1.3"
|
||||
axum = { version = "0.8", default-features = false, features = ["http1", "tokio"] }
|
||||
futures = { version = "0.3", default-features = false, features = ["std"] }
|
||||
axum = "0.8"
|
||||
futures = "0.3"
|
||||
futures-util = "0.3"
|
||||
uzers = "0.12"
|
||||
whoami = "2"
|
||||
thiserror = "2"
|
||||
compile-time = "0.4"
|
||||
redact-engine = "0.1"
|
||||
compile-time = "0.2"
|
||||
serde_urlencoded = "0.7"
|
||||
md5 = "0.8"
|
||||
sha2 = { version = "0.11", default-features = false }
|
||||
sha256 = "1"
|
||||
which = "8"
|
||||
uuid = "1"
|
||||
netdev = "0.46.3"
|
||||
netdev = "0.40"
|
||||
humantime = "2"
|
||||
snow = { version = "0.10", default-features = false, features = ["use-getrandom", "use-curve25519", "use-chacha20poly1305", "use-sha2"] }
|
||||
snow = { version = "0.10", default-features = false, features = ["std", "use-getrandom", "use-curve25519", "use-chacha20poly1305", "use-sha2"] }
|
||||
zeroize = "1"
|
||||
|
||||
# Tauri dependencies
|
||||
@@ -67,12 +67,6 @@ tauri = { version = "2" }
|
||||
specta = "=2.0.0-rc.20"
|
||||
proptest = "1"
|
||||
|
||||
[patch.crates-io]
|
||||
# Restore BSD GTK resize hit testing until https://github.com/tauri-apps/tao/pull/1356 is released.
|
||||
tao = { git = "https://github.com/yuezk/tao", rev = "1452ae7a42c9f134296ba199f91f514fc9077f61" }
|
||||
# Use one macro source for Tao and Wry so Cargo can vendor the workspace.
|
||||
tao-macros = { git = "https://github.com/yuezk/tao", rev = "1452ae7a42c9f134296ba199f91f514fc9077f61" }
|
||||
|
||||
[profile.release]
|
||||
opt-level = 'z' # Optimize for size
|
||||
lto = true # Enable link-time optimization
|
||||
|
||||
@@ -3,10 +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
|
||||
RUST_VERSION ?= 1.89
|
||||
IGNORE_RUST_VERSION ?= 0
|
||||
|
||||
VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')
|
||||
@@ -35,14 +33,7 @@ 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
|
||||
|
||||
@@ -148,74 +139,73 @@ clean:
|
||||
rm -rf .vendor
|
||||
rm -rf apps/gpgui-helper/node_modules
|
||||
|
||||
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:
|
||||
@echo "Installing $(PKG_NAME)..."
|
||||
|
||||
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 -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-vpnc-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
|
||||
|
||||
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/"; \
|
||||
# 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; \
|
||||
fi
|
||||
set -e; if [ -f "$(GPGUI_BINARY)" ]; then \
|
||||
install -m 755 "$(GPGUI_BINARY)" "$(DESTDIR)$(PREFIX)/bin/gpgui"; \
|
||||
|
||||
if [ -f .build/gpgui/gpgui_*/gpgui ]; then \
|
||||
install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/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-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 -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script
|
||||
install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
|
||||
|
||||
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)"
|
||||
# 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/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-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 -m 755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)$(PREFIX)/libexec/gpclient/hipreport.sh
|
||||
|
||||
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 -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 -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
|
||||
|
||||
clean-bsd-package:
|
||||
rm -rf .build/$(BSD_FLAVOR)
|
||||
@@ -269,7 +259,6 @@ package-openbsd: clean-bsd-package
|
||||
comment=$$(cat .build/openbsd/+COMMENT); \
|
||||
openbsd_arch=$$(uname -m | sed 's/x86_64/amd64/'); \
|
||||
gnome_keyring_pkg=$$(pkg_info -e 'gnome-keyring-*' | sed 's/^inst://' | head -n 1); \
|
||||
dbus_pkg=$$(pkg_info -e 'dbus-*' | sed 's/^inst://' | head -n 1); \
|
||||
polkit_pkg=$$(pkg_info -e 'polkit-*' | sed 's/^inst://' | head -n 1); \
|
||||
webkitgtk_pkg=$$(pkg_info -e 'webkitgtk41-*' | sed 's/^inst://' | head -n 1); \
|
||||
xdg_utils_pkg=$$(pkg_info -e 'xdg-utils-*' | sed 's/^inst://' | head -n 1); \
|
||||
@@ -280,61 +269,42 @@ package-openbsd: clean-bsd-package
|
||||
-f .build/openbsd/PLIST \
|
||||
-p $(PREFIX) \
|
||||
-P x11/gnome/keyring:gnome-keyring-*:$$gnome_keyring_pkg \
|
||||
-P x11/dbus:dbus-*:$$dbus_pkg \
|
||||
-P sysutils/polkit:polkit-*:$$polkit_pkg \
|
||||
-P www/webkitgtk4,webkitgtk41:webkitgtk41-*:$$webkitgtk_pkg \
|
||||
-P devel/xdg-utils:xdg-utils-*:$$xdg_utils_pkg \
|
||||
.build/openbsd/artifacts/$(PKG_NAME)-$(VERSION)-openbsd-$$openbsd_arch.tgz
|
||||
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)"
|
||||
|
||||
ifeq ($(shell uname -s),Darwin)
|
||||
uninstall: uninstall-macos
|
||||
else ifneq ($(filter FreeBSD OpenBSD,$(shell uname -s)),)
|
||||
uninstall: uninstall-bsd
|
||||
else
|
||||
uninstall: uninstall-linux
|
||||
endif
|
||||
uninstall:
|
||||
@echo "Uninstalling $(PKG_NAME)..."
|
||||
|
||||
.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/bin/gpclient
|
||||
rm -f $(DESTDIR)/usr/bin/gpauth
|
||||
rm -f $(DESTDIR)/usr/bin/gpservice
|
||||
rm -f $(DESTDIR)/usr/bin/gpgui-helper
|
||||
rm -f $(DESTDIR)/usr/bin/gpgui
|
||||
|
||||
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/libexec/gpclient/vpnc-script
|
||||
rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
|
||||
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
|
||||
|
||||
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/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
|
||||
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
|
||||
|
||||
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)/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/polkit-1/actions/com.yuezk.gpgui.policy
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
clean-debian:
|
||||
rm -rf .build/deb
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# GlobalProtect-openconnect
|
||||
|
||||
A GlobalProtect VPN client built on OpenConnect with support for SSO authentication. It provides command-line tools and the GP Connect desktop application for macOS, Linux, FreeBSD, and OpenBSD.
|
||||
A modern GlobalProtect VPN client for Linux, built on OpenConnect with full support for SSO authentication. This project provides both command-line and graphical interfaces for seamless VPN connectivity.
|
||||
|
||||
<p align="center">
|
||||
<img width="300" src="https://github.com/user-attachments/assets/2fb6116c-dc57-43f2-af75-9c3d97ab7122">
|
||||
@@ -15,15 +15,12 @@ A GlobalProtect VPN client built on OpenConnect with support for SSO authenticat
|
||||
- [Command-Line Interface](#command-line-interface)
|
||||
- [Graphical User Interface](#graphical-user-interface)
|
||||
- [Installation](#installation)
|
||||
- [macOS](#macos)
|
||||
- [Debian / Ubuntu](#debian--ubuntu)
|
||||
- [Arch Linux / Manjaro](#arch-linux--manjaro)
|
||||
- [Fedora 38+ / Rawhide](#fedora-38--rawhide)
|
||||
- [openSUSE Leap 15.6+ / Tumbleweed](#opensuse-leap-156--tumbleweed)
|
||||
- [Other RPM-based Distributions](#other-rpm-based-distributions)
|
||||
- [Alpine Linux](#alpine-linux)
|
||||
- [FreeBSD](#freebsd)
|
||||
- [OpenBSD](#openbsd)
|
||||
- [Gentoo](#gentoo)
|
||||
- [NixOS](#nixos)
|
||||
- [Official Docker Image](#official-docker-image)
|
||||
@@ -31,11 +28,11 @@ A GlobalProtect VPN client built on OpenConnect with support for SSO authenticat
|
||||
- [Building from Source](#building-from-source)
|
||||
- [Frequently Asked Questions](#frequently-asked-questions)
|
||||
- [NetworkManager Integration](#networkmanager-integration)
|
||||
- [Licensing](#licensing)
|
||||
- [License](#license)
|
||||
|
||||
## Features
|
||||
|
||||
- **Desktop Platform Support** – macOS, Linux, FreeBSD, and OpenBSD
|
||||
- **Cross-Platform Linux Support** – Optimized for various Linux distributions
|
||||
- **Dual Interface** – Available as both CLI and GUI applications
|
||||
- **Flexible Authentication** – Supports SSO, non-SSO, FIDO2 (e.g., YubiKey), and client certificate authentication
|
||||
- **Browser Integration** – Authenticate using your default browser or any specified browser
|
||||
@@ -48,7 +45,7 @@ A GlobalProtect VPN client built on OpenConnect with support for SSO authenticat
|
||||
|
||||
### Command-Line Interface
|
||||
|
||||
The CLI is free and open source. Use it to authenticate, connect to portals or gateways, and generate HIP reports from the terminal.
|
||||
The CLI version is fully open source and feature-rich, providing nearly identical functionality to the GUI version.
|
||||
|
||||
#### Basic Commands
|
||||
|
||||
@@ -65,7 +62,6 @@ Commands:
|
||||
Options:
|
||||
--fix-openssl Uses extended compatibility mode for OpenSSL operations to support a broader range of systems and formats.
|
||||
--ignore-tls-errors Ignore the TLS errors
|
||||
--lock-file <LOCK_FILE> Path to the gpclient PID lock file
|
||||
--log-format <LOG_FORMAT> Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text. [default: text] [possible values: text, json]
|
||||
-v, --verbose... Enable verbose output, -v for debug, -vv for trace
|
||||
-q, --quiet... Decrease logging verbosity, -q for warnings, -qq for errors
|
||||
@@ -73,53 +69,31 @@ 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
|
||||
|
||||
HIP is disabled in the CLI unless enabled explicitly. Use `--hip` to generate reports inside `gpclient`, including later reports requested by the gateway:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --hip
|
||||
```
|
||||
|
||||
Use `--hip=/absolute/path/to/script` for a custom executable. It runs as the `gpclient` process user unless `--hip-user` specifies another user. No installed HIP script is discovered automatically. `--hip-user` applies only to custom executables.
|
||||
|
||||
`gpclient hip` generates a report on demand for inspection; see `gpclient hip --help` for report inputs. The GUI's HIP tab supports generated reports, edited XML, and HIP Off on all desktop platforms. Linux, FreeBSD, and OpenBSD also support desktop-user scripts and explicitly approved root scripts.
|
||||
|
||||
#### External Browser Authentication
|
||||
|
||||
Use `gpclient` directly for browser-based authentication. It opens the browser as your normal desktop user while keeping VPN tunnel setup privileged:
|
||||
For browser-based authentication with the CLI:
|
||||
|
||||
**Method 1:** Using sudo with environment preservation:
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser
|
||||
sudo gpclient connect --browser <portal>
|
||||
```
|
||||
|
||||
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`:
|
||||
|
||||
**Method 2:** Using authentication piping:
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser --cookie-cache
|
||||
```
|
||||
|
||||
Add `--gateway <gateway>` to select a particular gateway. Cookie caching is handled by `gpclient`. Its default cache file is `$HOME/.config/gpclient/cookie.json`, which normally belongs to root when running with `sudo`. To choose a predictable location, specify the path explicitly:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser --cookie-cache=/absolute/path/to/cookie.json
|
||||
gpauth <portal> --browser 2>/dev/null | sudo gpclient connect <portal> --cookie-on-stdin
|
||||
```
|
||||
|
||||
**Browser Options:**
|
||||
|
||||
- Use `--browser` to automatically select an available browser
|
||||
- Use `--browser` to auto-select Chrome, Firefox, then the system default browser
|
||||
- Use `--browser default` to use the system default browser
|
||||
- Use `--browser <browser>` to specify a browser (e.g., `firefox`, `chrome`)
|
||||
- Use `--browser manual` for standalone CLI installations or headless servers
|
||||
- Use `--browser remote` for headless servers – this provides a URL you can access from another machine to complete authentication
|
||||
|
||||
### Graphical User Interface
|
||||
|
||||
GP Connect provides a desktop interface for managing VPN connections. On macOS, open GP Connect from Applications. On Linux, FreeBSD, and OpenBSD, launch it from your application menu or via the terminal:
|
||||
The GUI application provides an intuitive interface for managing VPN connections. Launch it from your application menu or via the terminal:
|
||||
|
||||
```bash
|
||||
gpclient launch-gui
|
||||
@@ -135,26 +109,6 @@ gpclient launch-gui
|
||||
>
|
||||
> For older Linux distributions, use [v2.3.13](https://github.com/yuezk/GlobalProtect-openconnect/releases/tag/v2.3.13) instead of the latest release. It provides release assets for common distro families, including Debian/Ubuntu (`.deb`), Arch Linux / Manjaro (`.pkg.tar.zst`), RPM-based distros such as Fedora / RHEL / Rocky / AlmaLinux / CentOS (`.rpm`), and generic Linux tarballs (`.bin.tar.xz`).
|
||||
|
||||
### macOS
|
||||
|
||||
GP Connect requires Apple silicon and macOS 13 or later. The macOS app includes both the desktop application and the free `gpclient` CLI. The CLI does not require a GUI license.
|
||||
|
||||
#### Option 1: Install with Homebrew
|
||||
|
||||
```bash
|
||||
brew install --cask yuezk/gp-connect/gp-connect
|
||||
```
|
||||
|
||||
Open GP Connect from Applications, or connect from the terminal:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser
|
||||
```
|
||||
|
||||
#### Option 2: Install from DMG
|
||||
|
||||
Download the GP Connect `.dmg` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, open it, and drag GP Connect into Applications.
|
||||
|
||||
### Debian / Ubuntu
|
||||
|
||||
#### Option 1: Install from PPA (Recommended)
|
||||
@@ -177,7 +131,7 @@ sudo apt-get install globalprotect-openconnect
|
||||
Download the latest `.deb` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
sudo apt install --fix-broken ./globalprotect-openconnect_*.deb
|
||||
sudo apt install --fix-broken globalprotect-openconnect_*.deb
|
||||
```
|
||||
|
||||
### Arch Linux / Manjaro
|
||||
@@ -287,11 +241,7 @@ This repository includes a flake for NixOS integration.
|
||||
|
||||
#### Installation Steps
|
||||
|
||||
Add the flake input and NixOS module to your `flake.nix`:
|
||||
|
||||
The module builds the package with your NixOS configuration's `pkgs`, so the
|
||||
GlobalProtect GUI and the system use the same Nixpkgs dependency versions.
|
||||
It also enables Polkit and its setuid `pkexec` wrapper for privileged operations.
|
||||
Add the flake input and package to your `flake.nix`:
|
||||
|
||||
```nix
|
||||
{
|
||||
@@ -310,11 +260,11 @@ It also enables Polkit and its setuid `pkexec` wrapper for privileged operations
|
||||
|
||||
modules = [
|
||||
./configuration.nix
|
||||
globalprotect-openconnect.nixosModules.default
|
||||
{
|
||||
programs.globalprotect-openconnect.enable = true;
|
||||
services.ayatana-indicators.enable = true;
|
||||
|
||||
environment.systemPackages = [
|
||||
globalprotect-openconnect.packages.${system}.default
|
||||
nixpkgs.legacyPackages.${system}.gnomeExtensions.appindicator
|
||||
];
|
||||
}
|
||||
@@ -341,15 +291,6 @@ NixOS does not run an imperative package-uninstall hook when a package is
|
||||
removed from the system configuration. Remove an installed replacement VPN
|
||||
script from the app settings before removing the package.
|
||||
|
||||
The `prebuilt` package and NixOS module use the published release pinned in `flake.nix`. Both `prebuilt` and `fromSource` run natively on the host with packaged dependencies and installer paths. The `fromSource` package builds the current flake checkout, including its Git submodules:
|
||||
|
||||
```bash
|
||||
git submodule update --init --recursive
|
||||
nix build "git+file://$PWD?submodules=1#fromSource"
|
||||
```
|
||||
|
||||
Local source builds require initialized Git submodules and a flake URL with `submodules=1`, as shown above. For a remote source flake, use a Git URL with submodules enabled, such as `git+https://github.com/yuezk/GlobalProtect-openconnect?submodules=1#fromSource`. The `prebuilt` package and NixOS module do not require Git submodules. Build output (`target`, `.build`, and `node_modules`) is excluded from the source input. Updating release asset hashes changes the prebuilt package, independently of source builds.
|
||||
|
||||
### Official Docker Image
|
||||
|
||||
The [official Docker image](https://hub.docker.com/r/yuezk/globalprotect-openconnect) provides the CLI tools on Alpine Linux:
|
||||
@@ -365,21 +306,21 @@ Run it with access to the TUN device:
|
||||
```bash
|
||||
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:<version> \
|
||||
connect <portal>
|
||||
connect <portal> --cookie-on-stdin
|
||||
```
|
||||
|
||||
For browser authentication in a headless environment, use manual browser authentication:
|
||||
For browser authentication in a headless environment, use remote browser authentication:
|
||||
|
||||
```bash
|
||||
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:<version> \
|
||||
connect <portal> --browser manual
|
||||
connect <portal> --browser remote
|
||||
```
|
||||
|
||||
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 manual --browser-listen 192.168.107.15
|
||||
gpclient connect <portal> --browser remote --browser-listen 192.168.107.15
|
||||
```
|
||||
|
||||
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
|
||||
@@ -387,11 +328,21 @@ 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 manual
|
||||
connect <portal> --browser remote
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
Alternatively, pipe `gpauth` remote-browser output into `gpclient`:
|
||||
|
||||
```bash
|
||||
docker run --rm -it --entrypoint gpauth yuezk/globalprotect-openconnect:<version> \
|
||||
<portal> --browser remote 2>/dev/null \
|
||||
| docker run --rm -i --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:<version> \
|
||||
connect <portal> --cookie-on-stdin
|
||||
```
|
||||
|
||||
The image includes `gpclient` and `gpauth` only. It does not include embedded webview authentication, `gpgui-helper`, or `gpgui`.
|
||||
|
||||
### Other Distributions
|
||||
@@ -399,16 +350,14 @@ The image includes `gpclient` and `gpauth` only. It does not include embedded we
|
||||
#### Manual Installation
|
||||
|
||||
1. **Install dependencies:**
|
||||
- WebKitGTK 4.1 (for example, `libwebkit2gtk-4.1-0` on Debian/Ubuntu)
|
||||
- `webkit2gtk`
|
||||
- `libsecret`
|
||||
- `libayatana-appindicator` or `libappindicator-gtk3`
|
||||
- polkit (`pkexec`) for GUI-launched VPN connections
|
||||
|
||||
2. **Download and extract:**
|
||||
Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
```bash
|
||||
tar -xJf globalprotect-openconnect_${version}_${arch}.bin.tar.xz
|
||||
cd globalprotect-openconnect_${version}
|
||||
```
|
||||
|
||||
3. **Install:**
|
||||
@@ -418,11 +367,11 @@ The image includes `gpclient` and `gpauth` only. It does not include embedded we
|
||||
|
||||
## Building from Source
|
||||
|
||||
The instructions below build the open-source components on Linux. For FreeBSD and OpenBSD, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
||||
You can build the application from source using either a DevContainer (recommended) or a local development environment.
|
||||
|
||||
### Method 1: Using DevContainer
|
||||
### Method 1: Using DevContainer (Recommended)
|
||||
|
||||
This project includes a DevContainer configuration for Linux development. The repository's `rust-toolchain.toml` selects the Rust toolchain; rustup may need to download it on the first build.
|
||||
This project includes a DevContainer configuration that provides a consistent, reproducible build environment with all dependencies pre-installed.
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
@@ -446,7 +395,7 @@ This project includes a DevContainer configuration for Linux development. The re
|
||||
|
||||
3. **Build the project:**
|
||||
|
||||
To build the open-source components, including the GUI helper, run:
|
||||
To build everything including the GUI helper run this command:
|
||||
```bash
|
||||
docker run --privileged --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
--tty -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
|
||||
@@ -454,17 +403,13 @@ This project includes a DevContainer configuration for Linux development. The re
|
||||
```
|
||||
To build without the GUI helper run the same command as above, but with `BUILD_GUI_HELPER=0` passed as an argument to `make`.
|
||||
|
||||
4. **Locate build artifacts:**
|
||||
5. **Locate build artifacts:**
|
||||
|
||||
The compiled binaries will be available in `target/release/`:
|
||||
- `gpclient` – CLI client
|
||||
- `gpservice` – Background service
|
||||
- `gpauth` – Authentication helper
|
||||
- `gpgui-helper` – GUI helper
|
||||
- `gp-hip-script-installer` – Privileged HIP script installer
|
||||
- `gp-vpnc-script-installer` – Privileged VPN script installer
|
||||
|
||||
The proprietary GP Connect desktop application is distributed separately. Use `INCLUDE_GUI=1` with `make build` to download its matching published Linux build for installation.
|
||||
|
||||
#### Alternative: Using VS Code
|
||||
|
||||
@@ -479,11 +424,11 @@ This project includes a DevContainer configuration for Linux development. The re
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
- [Rust 1.91 or later](https://www.rust-lang.org/tools/install)
|
||||
- [Rust 1.89 or later](https://www.rust-lang.org/tools/install)
|
||||
- [Tauri dependencies](https://tauri.app/start/prerequisites/)
|
||||
- OpenConnect source-build dependencies: `autoconf`, `automake`, `autopoint`/`gettext`, `libtool`, `patch`, `pkg-config`, `libxml2`, `zlib`, `lz4`, `gnutls`, `p11-kit`, `nettle`, and `gmp` development packages
|
||||
- `pkexec` and `gnome-keyring` (or `pam_kwallet` on KDE)
|
||||
- Node.js and pnpm if rebuilding the GUI helper frontend
|
||||
- `nodejs` and `pnpm` (optional)
|
||||
|
||||
#### Build Steps
|
||||
|
||||
@@ -503,7 +448,7 @@ This project includes a DevContainer configuration for Linux development. The re
|
||||
sudo make install
|
||||
```
|
||||
|
||||
To stage the files for packaging instead of installing them into the system, use `make install DESTDIR=/absolute/path/to/staging`.
|
||||
> **Note:** `DESTDIR` is not currently supported.
|
||||
|
||||
### Testing Your Build
|
||||
|
||||
@@ -515,35 +460,29 @@ 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 browser or manual authentication
|
||||
- `INCLUDE_GUI=1` – Download the matching published Linux desktop application for installation
|
||||
- `BUILD_GUI_HELPER=0` – Build CLI components only (excludes GUI)
|
||||
- `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.
|
||||
**Solution 1:** Update to version 2.2.0 or later, which includes a file-based storage fallback.
|
||||
|
||||
Linux and BSD can use file storage when secure storage is unavailable during initial setup. An existing configuration that uses the keyring still needs access to that keyring.
|
||||
**Solution 2:** Install the `gnome-keyring` package and restart your system.
|
||||
|
||||
See related issues: [#321](https://github.com/yuezk/GlobalProtect-openconnect/issues/321), [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||
|
||||
### Q: How do I fix the "cannot open display" error when using CLI?
|
||||
|
||||
Run the client from a terminal in your normal desktop session and use an external browser:
|
||||
If you encounter `(gpauth:18869): Gtk-WARNING **: 10:33:37.566: cannot open display:`, try running the command with `sudo -E`:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser
|
||||
sudo -E gpclient connect <portal>
|
||||
```
|
||||
|
||||
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||
|
||||
On a headless server, use `--browser manual` and complete authentication from another machine.
|
||||
|
||||
## NetworkManager Integration
|
||||
|
||||
- [WMP/GlobalProtect-SAML-NetworkManager](https://github.com/WMP/GlobalProtect-SAML-NetworkManager) – NetworkManager VPN plugin with SAML/SSO support for GNOME and KDE Plasma
|
||||
@@ -554,7 +493,7 @@ On a headless server, use `--browser manual` and complete authentication from an
|
||||
### Trial and Pricing
|
||||
|
||||
The **CLI version** is completely free and open source.
|
||||
The **GUI version** is a paid application with a **7-day trial**. Start the trial in the app by verifying your email address with a one-time code. Installing the app alone does not start the trial.
|
||||
The **GUI version** is a paid application with a **7-day trial period** after installation.
|
||||
|
||||
### Open Source Licenses
|
||||
|
||||
|
||||
@@ -24,7 +24,8 @@ tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||
tempfile.workspace = true
|
||||
compile-time.workspace = true
|
||||
|
||||
home = "0.5.12"
|
||||
# Pin to specific version due to MSRV
|
||||
home = "=0.5.11"
|
||||
|
||||
# webview auth dependencies
|
||||
tauri = { workspace = true, optional = true }
|
||||
|
||||
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 56 KiB After Width: | Height: | Size: 57 KiB |
@@ -6,21 +6,17 @@ 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,
|
||||
utils::{normalize_server, openssl},
|
||||
};
|
||||
use log::info;
|
||||
use serde_json::json;
|
||||
use std::net::IpAddr;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
const VERSION: &str = concat!(
|
||||
@@ -88,7 +84,6 @@ 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,
|
||||
|
||||
@@ -109,13 +104,13 @@ struct Cli {
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Use a browser; omit the value to auto-select. Use `manual` to open the URL and paste the callback.",
|
||||
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.",
|
||||
default_missing_value = "auto",
|
||||
num_args=0..=1
|
||||
)]
|
||||
browser: Option<String>,
|
||||
|
||||
#[arg(long, help = "Listen on this IP address when using '--browser manual'")]
|
||||
#[arg(long, help = "Listen on this IP address when using '--browser remote'")]
|
||||
browser_listen: Option<IpAddr>,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
@@ -149,7 +144,6 @@ enum CliCommand {
|
||||
}
|
||||
|
||||
impl Args for Cli {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> bool {
|
||||
self.fix_openssl
|
||||
}
|
||||
@@ -164,8 +158,10 @@ impl Args for Cli {
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn prepare_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
|
||||
fn prepare_env(&self) -> anyhow::Result<Option<NamedTempFile>> {
|
||||
#[cfg(feature = "webview-auth")]
|
||||
gpapi::utils::env_utils::patch_gui_runtime_env(self.hidpi);
|
||||
|
||||
if self.fix_openssl {
|
||||
info!("Fixing OpenSSL environment");
|
||||
let file = openssl::fix_openssl_env()?;
|
||||
@@ -178,19 +174,16 @@ 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("manual") || browser.eq_ignore_ascii_case("remote"))
|
||||
&& !matches!(self.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote"))
|
||||
{
|
||||
anyhow::bail!("The '--browser-listen' option requires '--browser manual'");
|
||||
anyhow::bail!("The '--browser-listen' option requires '--browser remote'");
|
||||
}
|
||||
|
||||
if self.ignore_tls_errors {
|
||||
info!("TLS errors will be ignored");
|
||||
}
|
||||
|
||||
#[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 openssl_conf = self.prepare_env()?;
|
||||
|
||||
let server = normalize_server(self.server.as_deref().expect("server is required for authentication"))?;
|
||||
let gp_params = self.build_gp_params();
|
||||
@@ -201,17 +194,7 @@ impl Cli {
|
||||
|
||||
let auth_request = match self.saml_request.as_deref() {
|
||||
Some(auth_request) => auth_request.to_string(),
|
||||
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(());
|
||||
}
|
||||
},
|
||||
None => auth_prelogin(&server, &gp_params, self.external_browser_requested(), self.gateway).await?,
|
||||
};
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
@@ -230,7 +213,7 @@ impl Cli {
|
||||
|
||||
print_auth_result(auth_result, Some(&auth_host_id));
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
// explicitly drop openssl_conf to avoid the unused variable warning
|
||||
drop(openssl_conf);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -243,7 +226,6 @@ impl Cli {
|
||||
self.clean,
|
||||
self.window_title.clone(),
|
||||
self.window_theme,
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
openssl_conf,
|
||||
)
|
||||
.await?;
|
||||
@@ -316,11 +298,7 @@ pub async fn run() {
|
||||
}
|
||||
|
||||
pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>) {
|
||||
println!("{}", json!(auth_outcome(auth_result, host_id)));
|
||||
}
|
||||
|
||||
fn auth_outcome(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>) -> SamlAuthResult {
|
||||
match auth_result {
|
||||
let auth_result = match auth_result {
|
||||
Ok(auth_data) => {
|
||||
let auth_data = match host_id {
|
||||
Some(host_id) => auth_data.with_host_id(host_id),
|
||||
@@ -329,54 +307,16 @@ fn auth_outcome(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>
|
||||
SamlAuthResult::Success(auth_data)
|
||||
}
|
||||
Err(err) if err.downcast_ref::<AuthenticationCancelled>().is_some() => SamlAuthResult::Cancelled,
|
||||
Err(err) => match err.downcast::<ServerTlsError>() {
|
||||
Ok(tls) => SamlAuthResult::ServerTlsError(tls),
|
||||
Err(err) => SamlAuthResult::Failure(err.to_string()),
|
||||
},
|
||||
}
|
||||
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
|
||||
};
|
||||
|
||||
println!("{}", json!(auth_result));
|
||||
}
|
||||
|
||||
#[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.
|
||||
@@ -459,7 +399,7 @@ mod tests {
|
||||
"gpauth",
|
||||
"portal.example.com",
|
||||
"--browser",
|
||||
"manual",
|
||||
"remote",
|
||||
"--browser-listen",
|
||||
"192.168.107.15",
|
||||
])
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
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;
|
||||
@@ -16,7 +13,7 @@ pub async fn authenticate(
|
||||
clean: bool,
|
||||
window_title: Option<String>,
|
||||
window_theme: AuthWindowTheme,
|
||||
#[cfg(not(target_os = "macos"))] mut openssl_conf: Option<NamedTempFile>,
|
||||
mut openssl_conf: Option<NamedTempFile>,
|
||||
) -> anyhow::Result<()> {
|
||||
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
|
||||
|
||||
@@ -46,9 +43,8 @@ pub async fn authenticate(
|
||||
Ok(())
|
||||
})
|
||||
.build(crate::tauri_context::get())?
|
||||
.run(move |_app_handle, _event| {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if let RunEvent::Exit = _event {
|
||||
.run(move |_app_handle, event| {
|
||||
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);
|
||||
|
||||
@@ -9,34 +9,29 @@ license.workspace = true
|
||||
[dependencies]
|
||||
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
|
||||
askama.workspace = true
|
||||
chrono.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
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_urlencoded.workspace = true
|
||||
whoami.workspace = true
|
||||
tempfile.workspace = true
|
||||
reqwest.workspace = true
|
||||
directories.workspace = true
|
||||
compile-time.workspace = true
|
||||
uzers.workspace = true
|
||||
netdev.workspace = true
|
||||
xmltree.workspace = true
|
||||
uuid = { workspace = true, features = ["v5"] }
|
||||
|
||||
[features]
|
||||
default = ["webview-auth"]
|
||||
webview-auth = ["gpapi/webview-auth"]
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
gpvpnc = { path = "../../crates/gpvpnc" }
|
||||
@@ -4,15 +4,6 @@ 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");
|
||||
|
||||
@@ -1,302 +0,0 @@
|
||||
//! 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,22 +5,19 @@ 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},
|
||||
@@ -36,7 +33,6 @@ 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,
|
||||
@@ -54,23 +50,6 @@ 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)]
|
||||
address: std::net::IpAddr,
|
||||
#[arg(long)]
|
||||
hostname: String,
|
||||
},
|
||||
#[command(hide = true)]
|
||||
ResolveGateway {
|
||||
host: String,
|
||||
#[arg(long, default_value_t = 443)]
|
||||
port: u16,
|
||||
#[arg(long)]
|
||||
disable_ipv6: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
@@ -95,7 +74,6 @@ 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."
|
||||
@@ -111,9 +89,6 @@ struct Cli {
|
||||
)]
|
||||
lock_file: PathBuf,
|
||||
|
||||
#[arg(long, hide = true, global = true)]
|
||||
background_worker_fd: Option<i32>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
@@ -127,7 +102,6 @@ struct Cli {
|
||||
}
|
||||
|
||||
impl Args for Cli {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> bool {
|
||||
self.fix_openssl
|
||||
}
|
||||
@@ -144,9 +118,9 @@ impl Args for Cli {
|
||||
impl Cli {
|
||||
fn can_run_alongside_client(&self) -> bool {
|
||||
match &self.command {
|
||||
CliCommand::Connect(_) => false,
|
||||
CliCommand::Disconnect(_) => true,
|
||||
CliCommand::LaunchGui(args) => args.is_auth_callback(),
|
||||
_ => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,7 +143,6 @@ 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()?;
|
||||
@@ -180,46 +153,15 @@ 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,
|
||||
@@ -232,30 +174,10 @@ impl Cli {
|
||||
}
|
||||
|
||||
match &self.command {
|
||||
CliCommand::Connect(args) => {
|
||||
ConnectHandler::new(args, &shared_args)
|
||||
.with_background(background_worker)
|
||||
.handle()
|
||||
.await
|
||||
}
|
||||
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).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)?);
|
||||
Ok(())
|
||||
}
|
||||
CliCommand::ResolveGateway {
|
||||
host,
|
||||
port,
|
||||
disable_ipv6,
|
||||
} => {
|
||||
let addresses = gpapi::session::network::native::lookup_in_helper(host, *port, *disable_ipv6)?;
|
||||
println!("{}", serde_json::to_string(&addresses)?);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -276,13 +198,7 @@ fn build_logger(cli: &Cli) -> env_logger::Builder {
|
||||
pub(crate) async fn run() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
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();
|
||||
}
|
||||
build_logger(&cli).init();
|
||||
|
||||
info!("gpclient started: {}", VERSION);
|
||||
|
||||
@@ -303,111 +219,6 @@ 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([
|
||||
"gpclient",
|
||||
"resolve-gateway",
|
||||
"localhost",
|
||||
"--port",
|
||||
"444",
|
||||
"--disable-ipv6",
|
||||
])
|
||||
.unwrap();
|
||||
assert!(cli.can_run_alongside_client());
|
||||
use clap::CommandFactory;
|
||||
let help = Cli::command().render_help().to_string();
|
||||
assert!(!help.contains("resolve-gateway"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_file_defaults_to_standard_path() {
|
||||
let cli = Cli::try_parse_from(["gpclient", "connect", "portal.example.com"]).expect("cli should parse");
|
||||
@@ -429,25 +240,6 @@ mod tests {
|
||||
assert_eq!(cli.lock_file, PathBuf::from("/tmp/gpclient-portal.lock"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hip_can_run_alongside_connected_client() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"hip",
|
||||
"--client-version",
|
||||
"6.2.4-49",
|
||||
"--client-os",
|
||||
"Mac",
|
||||
"--cookie",
|
||||
"user=alice",
|
||||
"--md5",
|
||||
"test",
|
||||
])
|
||||
.expect("HIP arguments should parse");
|
||||
|
||||
assert!(cli.can_run_alongside_client());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn launch_gui_accepts_auth_callback() {
|
||||
@@ -552,40 +344,6 @@ 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,27 +13,6 @@ 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>,
|
||||
|
||||
@@ -75,16 +54,13 @@ pub(crate) struct ConnectArgs {
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Enable HIP (Host Information Profile), optionally specify a custom executable",
|
||||
help = "Use HIP (Host Integrity Protection) extension, optionally specify the HIP script path",
|
||||
default_missing_value = "",
|
||||
num_args=0..=1
|
||||
)]
|
||||
pub(super) hip: Option<String>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Run a custom HIP executable as this user; otherwise inherit the process user"
|
||||
)]
|
||||
#[arg(long, help = "The user used to run the HIP script")]
|
||||
pub(super) hip_user: Option<String>,
|
||||
|
||||
#[arg(
|
||||
@@ -165,22 +141,14 @@ pub(crate) struct ConnectArgs {
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Use a browser; omit the value to auto-select. Use `manual` to open the URL and paste the callback.",
|
||||
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.",
|
||||
default_missing_value = "auto",
|
||||
num_args=0..=1
|
||||
)]
|
||||
pub(super) browser: Option<String>,
|
||||
|
||||
#[arg(long, help = "Listen on this IP address when using '--browser manual'")]
|
||||
#[arg(long, help = "Listen on this IP address when using '--browser remote'")]
|
||||
pub(super) browser_listen: Option<IpAddr>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Authenticate and print the gateway cookie to stdout, then exit without starting the \
|
||||
VPN tunnel. Outputs two lines: COOKIE='<value>' and HOST='<gateway>'. Combine with \
|
||||
--cookie-cache to avoid re-authenticating when the portal session is still valid."
|
||||
)]
|
||||
pub(super) cookie_only: bool,
|
||||
}
|
||||
|
||||
pub(super) fn build_os_profile(args: &ConnectArgs) -> OsProfile {
|
||||
@@ -306,7 +274,7 @@ mod tests {
|
||||
"test",
|
||||
"portal.example.com",
|
||||
"--browser",
|
||||
"manual",
|
||||
"remote",
|
||||
"--browser-listen",
|
||||
"192.168.107.15",
|
||||
])
|
||||
@@ -450,23 +418,4 @@ mod tests {
|
||||
};
|
||||
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_only_flag_parses() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-only"])
|
||||
.expect("--cookie-only should parse");
|
||||
|
||||
assert!(cli.args.cookie_only);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_only_is_disabled_by_default() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
|
||||
|
||||
assert!(!cli.args.cookie_only);
|
||||
}
|
||||
}
|
||||
@@ -11,14 +11,6 @@ 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,
|
||||
@@ -52,47 +44,6 @@ 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,
|
||||
@@ -125,10 +76,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())
|
||||
@@ -138,9 +89,6 @@ 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")]
|
||||
@@ -168,21 +116,7 @@ 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()?;
|
||||
let cred = auth_launcher.launch().await?;
|
||||
Ok(cred)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,527 +0,0 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Parser;
|
||||
use gpapi::{
|
||||
cookie_store::{self, StoredCookie},
|
||||
credential::AuthCookieCredential,
|
||||
gateway::{Gateway, GatewayLoginContext, GatewaySelection},
|
||||
log_format::LogFormat,
|
||||
session::SessionMode,
|
||||
};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use super::{ConnectArgs, ConnectHandler};
|
||||
use crate::cli::SharedArgs;
|
||||
|
||||
#[derive(Parser)]
|
||||
struct TestArgs {
|
||||
#[command(flatten)]
|
||||
connect: ConnectArgs,
|
||||
}
|
||||
|
||||
fn login_response() -> String {
|
||||
let mut fields = [""; 20];
|
||||
fields[1] = "issued-cookie";
|
||||
fields[3] = "gateway";
|
||||
fields[4] = "alice";
|
||||
fields[5] = "fixture-auth";
|
||||
fields[6] = "vsys1";
|
||||
fields[12] = "tunnel";
|
||||
format!(
|
||||
"<jnlp><application-desc>{}</application-desc></jnlp>",
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| format!("<argument>{field}</argument>"))
|
||||
.collect::<String>()
|
||||
)
|
||||
}
|
||||
|
||||
async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let worker = tokio::spawn(async move {
|
||||
tokio::time::timeout(Duration::from_secs(5), async move {
|
||||
let mut requests = Vec::new();
|
||||
for (status, body) in responses {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0; 4096];
|
||||
let count = stream.read(&mut buf).await.unwrap();
|
||||
assert_ne!(count, 0, "Request ended before its body");
|
||||
request.extend_from_slice(&buf[..count]);
|
||||
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||
.unwrap_or(0);
|
||||
if request.len() >= end + 4 + length {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
requests.push(String::from_utf8(request).unwrap());
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
requests
|
||||
})
|
||||
.await
|
||||
.expect("Gateway fixture timed out")
|
||||
});
|
||||
(origin, worker)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
|
||||
let (gateway, worker) = gateway(vec![("200 OK", login_response())]).await;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let cache = directory.path().join("cookie.json");
|
||||
let args = TestArgs::parse_from([
|
||||
"test",
|
||||
"http://unavailable-portal.invalid",
|
||||
"--cookie-only",
|
||||
"--cookie-cache",
|
||||
cache.to_str().unwrap(),
|
||||
])
|
||||
.connect;
|
||||
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);
|
||||
cookie_store::save(
|
||||
&cache,
|
||||
&StoredCookie::new(
|
||||
args.server.clone(),
|
||||
"alice".into(),
|
||||
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||
gateway,
|
||||
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
handler.handle_impl().await.unwrap();
|
||||
let requests = worker.await.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert!(requests[0].starts_with("POST /ssl-vpn/login.esp "));
|
||||
assert!(requests[0].contains("portal-cookie"));
|
||||
assert_eq!(
|
||||
handler.sessions.borrow().members()[0].transport.authentication().mode(),
|
||||
SessionMode::Tunnel
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
|
||||
let (origin, worker) = gateway(vec![
|
||||
(
|
||||
"200 OK",
|
||||
"<prelogin-response><status>Success</status></prelogin-response>".into(),
|
||||
),
|
||||
("403 Forbidden", "<response><error>rejected</error></response>".into()),
|
||||
("200 OK", login_response()),
|
||||
])
|
||||
.await;
|
||||
let args = TestArgs::parse_from(["test", &origin, "--user", "alice", "--passwd-on-stdin"]).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.password_from_stdin.replace(Some("gateway-password".into()));
|
||||
let mut value = serde_json::to_value(Gateway::new("internal".into(), origin.clone())).unwrap();
|
||||
value["kind"] = serde_json::json!("internal");
|
||||
let gateway: Gateway = serde_json::from_value(value).unwrap();
|
||||
let session = handler
|
||||
.authenticate_gateway(
|
||||
&origin,
|
||||
&origin,
|
||||
&AuthCookieCredential::new("alice", "rejected-cookie", ""),
|
||||
false,
|
||||
GatewayLoginContext::new(&gateway, GatewaySelection::Auto),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(session.authentication.mode(), SessionMode::Tunnel);
|
||||
assert!(session.extension_auth.binding().is_none());
|
||||
let requests = worker.await.unwrap();
|
||||
assert_eq!(requests.len(), 3);
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,35 +11,35 @@ use gpapi::{
|
||||
clap::report,
|
||||
cookie_store,
|
||||
credential::{AuthCookieCredential, Credential},
|
||||
gateway::{Gateway, GatewayLogin, GatewayLoginClient, GatewayLoginContext, GatewaySelection, SessionExtensionAuth},
|
||||
gateway::{GatewayLogin, GatewayLoginContext, SessionExtensionAuth, gateway_login, gateway_login_with_context},
|
||||
gp_params::GpParams,
|
||||
os_profile::OsProfile,
|
||||
portal::{PortalConfig, prelogin},
|
||||
process::users::get_user_by_name,
|
||||
session::{GatewayAuthentication, SessionMode},
|
||||
portal::prelogin,
|
||||
process::users::{get_non_root_user, get_user_by_name},
|
||||
utils::shutdown_signal,
|
||||
};
|
||||
use inquire::Text;
|
||||
use log::{Level, info, warn};
|
||||
use openconnect::{HipScript, HipSource, VpnBuilder};
|
||||
use openconnect::{Vpn, 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, vpn_script};
|
||||
use super::{ConnectHandler, args::cookie_cache_path};
|
||||
|
||||
const OPENCONNECT_INTERRUPTED_EXIT_CODE: i32 = -4;
|
||||
|
||||
pub(super) struct GatewayLoginSession {
|
||||
pub(super) authentication: GatewayAuthentication,
|
||||
pub(super) extension_auth: SessionExtensionAuth,
|
||||
struct GatewayLoginSession {
|
||||
cookie: String,
|
||||
extension_auth: SessionExtensionAuth,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum GatewayConnectFailureStage {
|
||||
BeforeEstablishment,
|
||||
AfterEstablishment,
|
||||
BeforeTunnel,
|
||||
AfterTunnel,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -49,22 +49,22 @@ pub(super) struct GatewayConnectError {
|
||||
}
|
||||
|
||||
impl GatewayConnectError {
|
||||
fn before_establishment(error: anyhow::Error) -> Self {
|
||||
fn before_tunnel(error: anyhow::Error) -> Self {
|
||||
Self {
|
||||
stage: GatewayConnectFailureStage::BeforeEstablishment,
|
||||
stage: GatewayConnectFailureStage::BeforeTunnel,
|
||||
error,
|
||||
}
|
||||
}
|
||||
|
||||
fn after_establishment(error: anyhow::Error) -> Self {
|
||||
fn after_tunnel(error: anyhow::Error) -> Self {
|
||||
Self {
|
||||
stage: GatewayConnectFailureStage::AfterEstablishment,
|
||||
stage: GatewayConnectFailureStage::AfterTunnel,
|
||||
error,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn is_before_establishment(&self) -> bool {
|
||||
self.stage == GatewayConnectFailureStage::BeforeEstablishment
|
||||
pub(super) fn is_before_tunnel(&self) -> bool {
|
||||
self.stage == GatewayConnectFailureStage::BeforeTunnel
|
||||
}
|
||||
|
||||
pub(super) fn as_error(&self) -> &anyhow::Error {
|
||||
@@ -77,81 +77,59 @@ impl GatewayConnectError {
|
||||
}
|
||||
|
||||
impl ConnectHandler<'_> {
|
||||
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<anyhow::Result<()>> {
|
||||
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<()> {
|
||||
let path = cookie_cache_path(self.args)?;
|
||||
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
|
||||
let stored = cookie_store::load(&path, server, &host_id)?;
|
||||
|
||||
if !stored.auth_cookie.can_authenticate_gateway() {
|
||||
warn!(
|
||||
"Cached portal cookie for {} is not usable for gateway authentication. Clearing cache.",
|
||||
stored.server
|
||||
);
|
||||
cookie_store::clear(&path);
|
||||
return None;
|
||||
}
|
||||
let credential = (&stored.auth_cookie).into();
|
||||
let mut params = self.build_gp_params();
|
||||
params.set_is_gateway(true);
|
||||
let session = match self
|
||||
.login_gateway(&stored.last_gateway, &credential, ¶ms, None)
|
||||
.await
|
||||
{
|
||||
|
||||
info!(
|
||||
"Using cached portal cookie for {} (saved_at={}, gateway={})",
|
||||
stored.server, stored.saved_at, stored.last_gateway
|
||||
);
|
||||
|
||||
let cred: Credential = (&stored.auth_cookie).into();
|
||||
let mut gp_params = self.build_gp_params();
|
||||
gp_params.set_is_gateway(true);
|
||||
|
||||
let login_session = match self.login_gateway(&stored.last_gateway, &cred, &gp_params, None).await {
|
||||
Ok(session) => session,
|
||||
Err(error) => {
|
||||
if self.cancellation.is_cancelled()
|
||||
|| error
|
||||
.downcast_ref::<gpapi::gateway::GatewayLoginProtocolError>()
|
||||
.is_some()
|
||||
{
|
||||
return Some(Err(error));
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"Cached portal cookie rejected by gateway {}: {}. Clearing cache and falling back to portal auth.",
|
||||
stored.last_gateway, err
|
||||
);
|
||||
cookie_store::clear(&path);
|
||||
warn!("Cached gateway authentication failed: {error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if session.authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only {
|
||||
self.logout_gateway(&stored.last_gateway).await;
|
||||
info!("Cached non-tunnel login requires fresh portal discovery");
|
||||
return None;
|
||||
}
|
||||
let result = self
|
||||
|
||||
match self
|
||||
.connect_gateway(
|
||||
server,
|
||||
&stored.last_gateway,
|
||||
&session.authentication,
|
||||
&login_session.cookie,
|
||||
false,
|
||||
session.extension_auth,
|
||||
login_session.extension_auth,
|
||||
)
|
||||
.await;
|
||||
match result {
|
||||
Ok(()) => Some(Ok(())),
|
||||
Err(error) if self.cancellation.is_cancelled() => Some(Err(error.into_error())),
|
||||
Err(error) => {
|
||||
self.logout_gateway(&stored.last_gateway).await;
|
||||
warn!("Cached gateway connection failed: {}", error.as_error());
|
||||
.await
|
||||
{
|
||||
Ok(()) => Some(()),
|
||||
Err(err) => {
|
||||
warn!("Gateway connect failed after cached-cookie login: {}", err.as_error());
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cached_portal_credential(&self, server: &str) -> Option<Credential> {
|
||||
if self.args.cookie_on_stdin {
|
||||
return None;
|
||||
}
|
||||
let path = cookie_cache_path(self.args)?;
|
||||
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
|
||||
let stored = cookie_store::load(&path, server, &host_id)?;
|
||||
if !stored.auth_cookie.can_authenticate_gateway() {
|
||||
cookie_store::clear(&path);
|
||||
return None;
|
||||
}
|
||||
info!("Using cached credential for fresh portal discovery");
|
||||
Some((&stored.auth_cookie).into())
|
||||
}
|
||||
|
||||
pub(super) fn clear_cookie_cache(&self) {
|
||||
if let Some(path) = cookie_cache_path(self.args) {
|
||||
cookie_store::clear(&path);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn connect_gateway_with_prelogin(
|
||||
&self,
|
||||
portal: &str,
|
||||
@@ -165,13 +143,9 @@ impl ConnectHandler<'_> {
|
||||
gp_params.set_is_gateway(true);
|
||||
|
||||
let gateway_browser_auth_allowed = true;
|
||||
let prelogin = tokio::select! {
|
||||
biased;
|
||||
_ = 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_with_recovery(prelogin, gateway, gateway_browser_auth_allowed)
|
||||
let prelogin = prelogin(gateway, &gp_params, self.direct_gateway_prelogin_options()).await?;
|
||||
let cred = self
|
||||
.obtain_credential(&prelogin, gateway, gateway_browser_auth_allowed)
|
||||
.await?;
|
||||
|
||||
let login_session = self
|
||||
@@ -182,7 +156,7 @@ impl ConnectHandler<'_> {
|
||||
.connect_gateway(
|
||||
portal,
|
||||
gateway,
|
||||
&login_session.authentication,
|
||||
&login_session.cookie,
|
||||
allow_extend_session,
|
||||
login_session.extension_auth,
|
||||
)
|
||||
@@ -190,108 +164,94 @@ impl ConnectHandler<'_> {
|
||||
.map_err(GatewayConnectError::into_error)
|
||||
}
|
||||
|
||||
/// Connect to a gateway using the official client's auth flow:
|
||||
///
|
||||
/// 1. Call gateway prelogin and retain the response (SAML data is held as a fallback).
|
||||
/// 2. If the portal provided auth cookies, attempt gateway login using them.
|
||||
/// 3. If that login succeeds, proceed directly to the VPN connection.
|
||||
/// 4. If no portal auth cookies exist or portal-cookie login fails, use the retained gateway prelogin response to authenticate
|
||||
/// against the gateway (SAML or username/password) and obtain a gateway-issued
|
||||
/// credential.
|
||||
/// 5. Retry gateway login with the gateway credential (now carrying the gateway's
|
||||
/// `prelogin-cookie`) and connect on success.
|
||||
pub(super) async fn connect_gateway_with_fallback(
|
||||
&self,
|
||||
portal: &str,
|
||||
gateway: &Gateway,
|
||||
portal_cred: &AuthCookieCredential,
|
||||
config: &PortalConfig,
|
||||
selection: GatewaySelection,
|
||||
remaining: &[&Gateway],
|
||||
) -> Result<(), GatewayConnectError> {
|
||||
let session = self
|
||||
.authenticate_gateway(
|
||||
portal,
|
||||
gateway.server(),
|
||||
portal_cred,
|
||||
config.default_browser().unwrap_or(false),
|
||||
GatewayLoginContext::new(gateway, selection).with_connect_method(config.connect_method()),
|
||||
)
|
||||
.await
|
||||
.map_err(GatewayConnectError::before_establishment)?;
|
||||
if !self.args.cookie_only && session.authentication.mode() == SessionMode::NonTunnel {
|
||||
if gateway.kind() != gpapi::gateway::GatewayKind::Internal {
|
||||
return Err(GatewayConnectError::after_establishment(anyhow::anyhow!(
|
||||
"Non-tunnel authentication requires freshly discovered internal gateways"
|
||||
)));
|
||||
}
|
||||
return self
|
||||
.connect_internal_gateways(portal, config, portal_cred, gateway, session, remaining)
|
||||
.await
|
||||
.map_err(GatewayConnectError::after_establishment);
|
||||
}
|
||||
self
|
||||
.connect_gateway(
|
||||
portal,
|
||||
gateway.server(),
|
||||
&session.authentication,
|
||||
config.allow_extend_session().unwrap_or(false),
|
||||
session.extension_auth,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn authenticate_gateway(
|
||||
&self,
|
||||
portal: &str,
|
||||
gateway: &str,
|
||||
portal_cred: &AuthCookieCredential,
|
||||
allow_extend_session: bool,
|
||||
portal_config_default_browser: bool,
|
||||
gateway_context: GatewayLoginContext,
|
||||
) -> anyhow::Result<GatewayLoginSession> {
|
||||
self.check_cancelled()?;
|
||||
) -> Result<(), GatewayConnectError> {
|
||||
info!("Connecting to gateway with portal-cookie first, gateway prelogin fallback...");
|
||||
|
||||
let mut gp_params = self.build_gp_params();
|
||||
gp_params.set_is_gateway(true);
|
||||
let browser_allowed = self.gateway_browser_auth_allowed(portal_config_default_browser);
|
||||
let gateway_prelogin = tokio::select! {
|
||||
biased;
|
||||
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||
result = prelogin(gateway, &gp_params, self.prelogin_options(browser_allowed)) => result?,
|
||||
};
|
||||
self.check_cancelled()?;
|
||||
let gateway_browser_auth_allowed = self.gateway_browser_auth_allowed(portal_config_default_browser);
|
||||
|
||||
let gateway_prelogin = prelogin(gateway, &gp_params, self.prelogin_options(gateway_browser_auth_allowed))
|
||||
.await
|
||||
.map_err(GatewayConnectError::before_tunnel)?;
|
||||
|
||||
if portal_cred.can_authenticate_gateway() {
|
||||
let credential: Credential = portal_cred.into();
|
||||
let portal_cred_for_login: Credential = portal_cred.into();
|
||||
match self
|
||||
.login_gateway(gateway, &credential, &gp_params, Some(&gateway_context))
|
||||
.login_gateway(gateway, &portal_cred_for_login, &gp_params, Some(&gateway_context))
|
||||
.await
|
||||
{
|
||||
Ok(session) => {
|
||||
Ok(login_session) => {
|
||||
info!("Gateway login with portal auth cookies succeeded");
|
||||
self.save_cookie_cache(portal, gateway, portal_cred);
|
||||
return Ok(session);
|
||||
return self
|
||||
.connect_gateway(
|
||||
portal,
|
||||
gateway,
|
||||
&login_session.cookie,
|
||||
allow_extend_session,
|
||||
login_session.extension_auth,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
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()
|
||||
{
|
||||
return Err(error);
|
||||
}
|
||||
info!("Portal cookie login failed; using gateway prelogin authentication: {error}");
|
||||
Err(err) => {
|
||||
info!("Gateway login with portal auth cookies failed: {}", err);
|
||||
info!("Falling back to gateway prelogin authentication...");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
info!("Portal config did not provide gateway auth cookies; using gateway prelogin flow");
|
||||
}
|
||||
|
||||
let (_, credential) = self
|
||||
.obtain_credential_with_recovery(gateway_prelogin, gateway, browser_allowed)
|
||||
let gateway_cred = match self
|
||||
.obtain_credential(&gateway_prelogin, gateway, gateway_browser_auth_allowed)
|
||||
.await
|
||||
{
|
||||
Ok(cred) => cred,
|
||||
Err(err) => {
|
||||
self.print_direct_gateway_recommendation(gateway);
|
||||
return Err(GatewayConnectError::before_tunnel(err));
|
||||
}
|
||||
};
|
||||
|
||||
let login_session = match self
|
||||
.login_gateway(gateway, &gateway_cred, &gp_params, Some(&gateway_context))
|
||||
.await
|
||||
{
|
||||
Ok(login_session) => login_session,
|
||||
Err(err) => {
|
||||
self.print_direct_gateway_recommendation(gateway);
|
||||
return Err(GatewayConnectError::before_tunnel(err));
|
||||
}
|
||||
};
|
||||
|
||||
self
|
||||
.connect_gateway(
|
||||
portal,
|
||||
gateway,
|
||||
&login_session.cookie,
|
||||
allow_extend_session,
|
||||
login_session.extension_auth,
|
||||
)
|
||||
.await
|
||||
.inspect_err(|_| self.print_direct_gateway_recommendation(gateway))?;
|
||||
self.check_cancelled()?;
|
||||
let result = self
|
||||
.login_gateway(gateway, &credential, &gp_params, Some(&gateway_context))
|
||||
.await;
|
||||
if result.is_err() {
|
||||
self.print_direct_gateway_recommendation(gateway);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn save_cookie_cache(&self, portal: &str, gateway: &str, auth_cookie: &AuthCookieCredential) {
|
||||
@@ -348,39 +308,24 @@ impl ConnectHandler<'_> {
|
||||
gateway_context: Option<&GatewayLoginContext>,
|
||||
) -> anyhow::Result<GatewayLoginSession> {
|
||||
let mut gp_params = gp_params.clone();
|
||||
gp_params.prepare_client_identity()?;
|
||||
let cancellation = self.cancellation.clone();
|
||||
let internal = gateway_context.is_some_and(|context| context.kind() == gpapi::gateway::GatewayKind::Internal);
|
||||
let mut client = GatewayLoginClient::new(gateway, gp_params)?;
|
||||
|
||||
loop {
|
||||
self.check_cancelled()?;
|
||||
let login = client.login(cred, gateway_context, &cancellation).await?;
|
||||
let login = match gateway_context {
|
||||
Some(context) => gateway_login_with_context(gateway, cred, &gp_params, context).await?,
|
||||
None => gateway_login(gateway, cred, &gp_params).await?,
|
||||
};
|
||||
|
||||
match login {
|
||||
GatewayLogin::Authenticated(authentication) => {
|
||||
let descriptor = Gateway::new(gateway.to_string(), gateway.to_string());
|
||||
client.register_session(
|
||||
descriptor.clone(),
|
||||
authentication.clone(),
|
||||
&mut self.sessions.borrow_mut(),
|
||||
);
|
||||
self.check_cancelled()?;
|
||||
if internal && authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only {
|
||||
client
|
||||
.bind_non_tunnel(self.args.disable_ipv6, None, &cancellation)
|
||||
.await
|
||||
.map_err(|error| error.context(gpapi::gateway::GatewayLoginProtocolError))?;
|
||||
client.update_registered_session(&descriptor, &authentication, &mut self.sessions.borrow_mut());
|
||||
}
|
||||
GatewayLogin::Cookie(cookie) => {
|
||||
return Ok(GatewayLoginSession {
|
||||
authentication,
|
||||
extension_auth: SessionExtensionAuth::new(cred.clone(), client),
|
||||
cookie,
|
||||
extension_auth: SessionExtensionAuth::new(cred.clone(), gp_params),
|
||||
});
|
||||
}
|
||||
GatewayLogin::Mfa(message, input_str) => {
|
||||
let otp = Text::new(&message).prompt()?;
|
||||
client.respond_mfa(&input_str, &otp);
|
||||
gp_params.set_input_str(&input_str);
|
||||
gp_params.set_otp(&otp);
|
||||
|
||||
info!("Retrying gateway login with MFA...");
|
||||
}
|
||||
@@ -388,67 +333,41 @@ impl ConnectHandler<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn connect_gateway(
|
||||
async fn connect_gateway(
|
||||
&self,
|
||||
portal: &str,
|
||||
gateway: &str,
|
||||
authentication: &GatewayAuthentication,
|
||||
cookie: &str,
|
||||
allow_extend_session: bool,
|
||||
extension_auth: SessionExtensionAuth,
|
||||
) -> Result<(), GatewayConnectError> {
|
||||
let cookie = authentication.cookie();
|
||||
// --cookie-only: print the gateway cookie and exit without opening a tunnel.
|
||||
// No tun device is allocated, no root is required, and no logout is issued
|
||||
// against the gateway — the cookie remains valid for subsequent use.
|
||||
// Output format matches openconnect --authenticate for easy shell consumption.
|
||||
if self.args.cookie_only {
|
||||
println!("COOKIE='{}'", cookie);
|
||||
println!("HOST='{}'", gateway);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if authentication.mode() != SessionMode::Tunnel {
|
||||
return Err(GatewayConnectError::after_establishment(anyhow::anyhow!(
|
||||
"Non-tunnel authentication requires fresh internal portal discovery"
|
||||
)));
|
||||
}
|
||||
self
|
||||
.check_cancelled()
|
||||
.map_err(GatewayConnectError::after_establishment)?;
|
||||
let identity_files = extension_auth
|
||||
.client_identity()
|
||||
.map(|identity| identity.write_files(None))
|
||||
.transpose()
|
||||
.map_err(GatewayConnectError::before_establishment)?;
|
||||
let certificate = identity_files.as_ref().map(|files| files.certificate().to_owned());
|
||||
let sslkey = identity_files.as_ref().and_then(|files| files.key().map(str::to_owned));
|
||||
let key_password = extension_auth
|
||||
.client_identity()
|
||||
.and_then(|identity| identity.key_password())
|
||||
.map(str::to_owned);
|
||||
let mtu = self.args.mtu.unwrap_or(0);
|
||||
let (hip, csd_wrapper) = self.determine_hip_script();
|
||||
let hip_user = self.determine_hip_user();
|
||||
let csd_uid = get_uid(&hip_user).map_err(GatewayConnectError::before_tunnel)?;
|
||||
let os_profile = self.os_profile.borrow().clone();
|
||||
let hip_source = self
|
||||
.hip_source(os_profile.clone())
|
||||
.map_err(GatewayConnectError::before_establishment)?;
|
||||
|
||||
let session_ctx = build_session_context(SessionContextInput {
|
||||
portal: portal.to_string(),
|
||||
gateway: gateway.to_string(),
|
||||
cookie: cookie.to_string(),
|
||||
os_profile: os_profile.clone(),
|
||||
certificate: certificate.clone(),
|
||||
sslkey: sslkey.clone(),
|
||||
key_password: key_password.clone(),
|
||||
certificate: self.args.certificate.clone(),
|
||||
sslkey: self.args.sslkey.clone(),
|
||||
key_password: self.latest_key_password.borrow().clone(),
|
||||
disable_ipv6: self.args.disable_ipv6,
|
||||
extension_auth: Some(extension_auth),
|
||||
});
|
||||
let vpn_builder = vpn_script::builder(gateway, cookie, self.args)
|
||||
let vpn_builder = Vpn::builder(gateway, cookie)
|
||||
.script(self.args.script.clone())
|
||||
.interface(self.args.interface.clone())
|
||||
.certificate(certificate)
|
||||
.sslkey(sslkey)
|
||||
.key_password(key_password)
|
||||
.hip_source(hip_source)
|
||||
.script_tun(self.args.script_tun)
|
||||
.certificate(self.args.certificate.clone())
|
||||
.sslkey(self.args.sslkey.clone())
|
||||
.key_password(self.latest_key_password.borrow().clone())
|
||||
.hip(hip)
|
||||
.csd_uid(csd_uid)
|
||||
.csd_wrapper(csd_wrapper)
|
||||
.reconnect_timeout(self.args.reconnect_timeout)
|
||||
.mtu(mtu)
|
||||
.disable_ipv6(self.args.disable_ipv6)
|
||||
@@ -458,7 +377,7 @@ impl ConnectHandler<'_> {
|
||||
.no_xmlpost(self.args.no_xmlpost);
|
||||
let vpn = apply_os_profile(vpn_builder, &os_profile)
|
||||
.build()
|
||||
.map_err(|err| GatewayConnectError::before_establishment(err.into()))?;
|
||||
.map_err(|err| GatewayConnectError::before_tunnel(err.into()))?;
|
||||
|
||||
let vpn = Arc::new(vpn);
|
||||
let vpn_clone = vpn.clone();
|
||||
@@ -471,145 +390,55 @@ impl ConnectHandler<'_> {
|
||||
let tunnel_established_on_connect = Arc::clone(&tunnel_established);
|
||||
let disconnect_requested = Arc::new(AtomicBool::new(false));
|
||||
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;
|
||||
tokio::spawn(async move {
|
||||
shutdown_signal().await;
|
||||
info!("Received the interrupt signal, disconnecting...");
|
||||
disconnect_requested_on_signal.store(true, Ordering::SeqCst);
|
||||
vpn_clone.disconnect();
|
||||
});
|
||||
|
||||
let lock_file_on_connect = self.shared_args.lock_file.to_path_buf();
|
||||
let pid_written = self.pid_written.clone();
|
||||
let lock_file = self.shared_args.lock_file.to_path_buf();
|
||||
let lock_file_on_connect = lock_file.clone();
|
||||
let log_format = self.shared_args.log_format;
|
||||
let session_cancellation = self.cancellation.clone();
|
||||
let (established_tx, established_rx) = tokio::sync::oneshot::channel();
|
||||
self.sessions.borrow_mut().relinquish_gateway(gateway);
|
||||
let mut worker = tokio::task::spawn_blocking(move || {
|
||||
vpn.connect(move |vpn_session_info| {
|
||||
if session_cancellation.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
tunnel_established_on_connect.store(true, Ordering::SeqCst);
|
||||
pid_written.store(write_pid_file(&lock_file_on_connect), Ordering::SeqCst);
|
||||
let _ = established_tx.send(());
|
||||
let connect_result = vpn.connect(move |vpn_session_info| {
|
||||
tunnel_established_on_connect.store(true, Ordering::SeqCst);
|
||||
write_pid_file(&lock_file_on_connect);
|
||||
|
||||
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
|
||||
return;
|
||||
};
|
||||
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
|
||||
info!("VPN session info: {}", session_info.log_summary());
|
||||
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
|
||||
return;
|
||||
};
|
||||
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
|
||||
info!("VPN session info: {}", session_info.log_summary());
|
||||
|
||||
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info, log_format);
|
||||
session_task_on_connect.lock().unwrap().replace(task);
|
||||
})
|
||||
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info, log_format);
|
||||
session_task_on_connect.lock().unwrap().replace(task);
|
||||
});
|
||||
let mut output_error = None;
|
||||
let connect_result = tokio::select! {
|
||||
result = &mut worker => result,
|
||||
established = established_rx => {
|
||||
if established.is_ok() {
|
||||
let unused = self.sessions.borrow().members().iter()
|
||||
.filter(|session| session.gateway.server() != gateway)
|
||||
.map(|session| session.gateway.server().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
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
|
||||
}
|
||||
}
|
||||
};
|
||||
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;
|
||||
|
||||
let session_task = { session_task.lock().unwrap().take() };
|
||||
if let Some(task) = session_task {
|
||||
if let Some(task) = session_task.lock().unwrap().take() {
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
}
|
||||
|
||||
if let Some(error) = output_error {
|
||||
return Err(GatewayConnectError::after_establishment(error));
|
||||
if fs::metadata(&lock_file).is_ok() {
|
||||
info!("Removing PID file");
|
||||
fs::remove_file(&lock_file).map_err(|err| GatewayConnectError::after_tunnel(err.into()))?;
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
pub(super) fn hip_source(&self, profile: OsProfile) -> anyhow::Result<HipSource> {
|
||||
let user = self.determine_hip_user();
|
||||
let script = self.args.hip.as_ref().or(self.args.csd_wrapper.as_ref());
|
||||
match script {
|
||||
Some(path) if !path.is_empty() => Ok(HipSource::Script(HipScript::new(path.clone(), get_uid(&user)?)?)),
|
||||
Some(_) => {
|
||||
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
|
||||
Ok(HipSource::Generator(Arc::new(move |request, control| {
|
||||
let input = gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context: gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
},
|
||||
};
|
||||
gphip::generate_report_with_control(&input, &|| control.check())
|
||||
.map_err(|error| error.downcast::<std::io::Error>().unwrap_or_else(std::io::Error::other))
|
||||
})))
|
||||
}
|
||||
None => {
|
||||
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
|
||||
Ok(HipSource::Disabled)
|
||||
}
|
||||
fn determine_hip_script(&self) -> (bool, Option<String>) {
|
||||
if let Some(hip) = &self.args.hip {
|
||||
return if hip.is_empty() {
|
||||
(true, None)
|
||||
} else {
|
||||
(true, Some(hip.clone()))
|
||||
};
|
||||
}
|
||||
|
||||
(self.args.csd_wrapper.is_some(), self.args.csd_wrapper.clone())
|
||||
}
|
||||
|
||||
fn determine_hip_user(&self) -> Option<String> {
|
||||
@@ -621,28 +450,6 @@ 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,
|
||||
@@ -658,9 +465,9 @@ fn classify_openconnect_result(
|
||||
|
||||
let error = anyhow::anyhow!("OpenConnect exited with status {}", exit_code);
|
||||
if tunnel_established {
|
||||
Err(GatewayConnectError::after_establishment(error))
|
||||
Err(GatewayConnectError::after_tunnel(error))
|
||||
} else {
|
||||
Err(GatewayConnectError::before_establishment(error))
|
||||
Err(GatewayConnectError::before_tunnel(error))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -668,23 +475,22 @@ fn direct_gateway_command(gateway: &str) -> String {
|
||||
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
|
||||
}
|
||||
|
||||
pub(super) fn write_pid_file(lock_file: &Path) -> bool {
|
||||
fn write_pid_file(lock_file: &Path) {
|
||||
let pid = std::process::id();
|
||||
|
||||
if let Err(err) = fs::write(lock_file, pid.to_string()) {
|
||||
warn!("Failed to write PID file: {}", err);
|
||||
false
|
||||
} else {
|
||||
info!("Wrote PID {} to {}", pid, lock_file.display());
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn get_uid(user: &Option<String>) -> anyhow::Result<Option<u32>> {
|
||||
user
|
||||
.as_ref()
|
||||
.map(|user| get_user_by_name(user).map(|user| user.uid()))
|
||||
.transpose()
|
||||
fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
|
||||
if let Some(user) = user {
|
||||
get_user_by_name(user).map(|user| user.uid())
|
||||
} else {
|
||||
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
|
||||
@@ -700,87 +506,6 @@ 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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_hip_user_must_exist() {
|
||||
assert!(get_uid(&Some("gpclient-nonexistent-hip-user".to_string())).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_hip_user_resolves_to_the_selected_account() {
|
||||
let current = uzers::get_user_by_uid(uzers::get_effective_uid()).unwrap();
|
||||
let name = current.name().to_string_lossy().into_owned();
|
||||
assert_eq!(get_uid(&Some(name)).unwrap(), Some(current.uid()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openconnect_success_is_not_a_gateway_failure() {
|
||||
assert!(classify_openconnect_result(0, false, false).is_ok());
|
||||
@@ -791,14 +516,14 @@ mod tests {
|
||||
fn openconnect_failure_before_callback_is_retryable_gateway_failure() {
|
||||
let err = classify_openconnect_result(1, false, false).expect_err("nonzero exit should fail");
|
||||
|
||||
assert!(err.is_before_establishment());
|
||||
assert!(err.is_before_tunnel());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openconnect_failure_after_callback_is_terminal_gateway_failure() {
|
||||
let err = classify_openconnect_result(1, true, false).expect_err("nonzero exit should fail");
|
||||
|
||||
assert!(!err.is_before_establishment());
|
||||
assert!(!err.is_before_tunnel());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -811,7 +536,7 @@ mod tests {
|
||||
let err = classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, false)
|
||||
.expect_err("unexpected interrupt should fail");
|
||||
|
||||
assert!(!err.is_before_establishment());
|
||||
assert!(!err.is_before_tunnel());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,281 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use gpapi::{
|
||||
credential::AuthCookieCredential,
|
||||
gateway::{Gateway, GatewayLoginContext, GatewaySelection},
|
||||
portal::PortalConfig,
|
||||
process::collection::CollectionControl,
|
||||
session::{
|
||||
MaintenanceState, SessionEndReason, SessionMode,
|
||||
network::PhysicalNetwork,
|
||||
non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions},
|
||||
},
|
||||
};
|
||||
use log::{info, warn};
|
||||
|
||||
use super::ConnectHandler;
|
||||
|
||||
impl ConnectHandler<'_> {
|
||||
pub(super) async fn connect_internal_gateways(
|
||||
&self,
|
||||
portal: &str,
|
||||
config: &PortalConfig,
|
||||
credential: &AuthCookieCredential,
|
||||
first_gateway: &Gateway,
|
||||
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()) {
|
||||
ensure!(
|
||||
gateway.kind() == gpapi::gateway::GatewayKind::Internal,
|
||||
"Non-tunnel candidates must be internal"
|
||||
);
|
||||
ensure!(
|
||||
hosts.insert(gpapi::utils::normalize_server(gateway.server())?),
|
||||
"Duplicate internal gateway"
|
||||
);
|
||||
}
|
||||
let mut authenticated = vec![(first_gateway, first_session)];
|
||||
for gateway in remaining.iter().copied() {
|
||||
self.check_cancelled()?;
|
||||
let context =
|
||||
GatewayLoginContext::new(gateway, GatewaySelection::Auto).with_connect_method(config.connect_method());
|
||||
match self
|
||||
.authenticate_gateway(
|
||||
portal,
|
||||
gateway.server(),
|
||||
credential,
|
||||
config.default_browser().unwrap_or(false),
|
||||
context,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(session) => authenticated.push((gateway, session)),
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
self.check_cancelled()?;
|
||||
let modes = authenticated.iter().map(|(_, session)| session.authentication.mode());
|
||||
ensure!(
|
||||
internal_session_mode(modes)? == SessionMode::NonTunnel,
|
||||
"Expected non-tunnel authentication"
|
||||
);
|
||||
self.run_internal_session(config, &authenticated).await
|
||||
}
|
||||
|
||||
async fn run_internal_session(
|
||||
&self,
|
||||
config: &PortalConfig,
|
||||
authenticated: &[(&gpapi::gateway::Gateway, super::gateway::GatewayLoginSession)],
|
||||
) -> anyhow::Result<()> {
|
||||
let cancellation = self.cancellation.clone();
|
||||
let network = Arc::new(PhysicalNetwork::capture_controlled(&cancellation).await?);
|
||||
let detection = config.internal_detection().cloned();
|
||||
let bindings = authenticated
|
||||
.iter()
|
||||
.map(|(_, session)| {
|
||||
session
|
||||
.extension_auth
|
||||
.binding()
|
||||
.cloned()
|
||||
.context("Non-tunnel binding is missing")
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
for binding in &bindings {
|
||||
network
|
||||
.validate_internal_binding(binding, detection.as_ref(), &cancellation)
|
||||
.await?;
|
||||
}
|
||||
let policy = config
|
||||
.internal_session_policy()
|
||||
.context("Invalid internal session policy")?;
|
||||
let profile = self.os_profile.borrow().clone();
|
||||
let source = if policy.collect_hip_data() {
|
||||
self.hip_source(profile.clone())?
|
||||
} else {
|
||||
openconnect::HipSource::Disabled
|
||||
};
|
||||
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()?;
|
||||
if matches!(source.as_ref(), openconnect::HipSource::Disabled) {
|
||||
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context: gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
},
|
||||
})
|
||||
.map_err(std::io::Error::other);
|
||||
}
|
||||
source.collect(
|
||||
&openconnect::HipRequest {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
client_version: profile.client_version().into(),
|
||||
client_os: profile.client_os().as_str().into(),
|
||||
os_version: profile.os_version().into(),
|
||||
host_id: Some(profile.host_id().into()),
|
||||
local_hostname: Some(profile.computer().into()),
|
||||
},
|
||||
&|| control.check(),
|
||||
)
|
||||
}),
|
||||
report_submitted: Arc::new(|_, _| {}),
|
||||
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();
|
||||
let detection = validate_detection.clone();
|
||||
let bindings = bindings.clone();
|
||||
Box::pin(async move {
|
||||
for binding in &bindings {
|
||||
network
|
||||
.validate_internal_binding(binding, detection.as_ref(), &cancellation)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}),
|
||||
};
|
||||
let monitor_cancel = cancellation.child_token();
|
||||
let monitor_token = monitor_cancel.clone();
|
||||
let (network_changed, network_signal) = tokio::sync::oneshot::channel();
|
||||
let monitor = tokio::spawn(async move {
|
||||
match network.wait_for_change(detection, monitor_token).await {
|
||||
Ok(false) => {}
|
||||
Ok(true) | Err(_) => {
|
||||
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// The PID spans maintenance and cleanup, including initialization before the
|
||||
// first successful HIP exchange. The outer handler owns final session logout.
|
||||
self.pid_written.store(
|
||||
super::gateway::write_pid_file(self.shared_args.lock_file),
|
||||
std::sync::atomic::Ordering::SeqCst,
|
||||
);
|
||||
let mut sessions = self.sessions.take();
|
||||
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."),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn logout_gateway(&self, gateway: &str) {
|
||||
let mut sessions = self.sessions.take();
|
||||
sessions.logout_gateway(gateway).await;
|
||||
self.sessions.replace(sessions);
|
||||
}
|
||||
}
|
||||
|
||||
fn internal_session_mode(modes: impl Iterator<Item = SessionMode>) -> anyhow::Result<SessionMode> {
|
||||
let mut modes = modes;
|
||||
let mode = modes.next().context("No internal gateway authenticated successfully")?;
|
||||
ensure!(
|
||||
modes.all(|candidate| candidate == mode),
|
||||
"Mixed tunnel and non-tunnel internal gateways are unsupported; select a gateway explicitly"
|
||||
);
|
||||
Ok(mode)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn internal_modes_reject_mixed_and_empty_sets() {
|
||||
assert!(internal_session_mode([].into_iter()).is_err());
|
||||
assert!(internal_session_mode([SessionMode::Tunnel, SessionMode::NonTunnel].into_iter()).is_err());
|
||||
assert_eq!(
|
||||
internal_session_mode([SessionMode::NonTunnel, SessionMode::NonTunnel].into_iter()).unwrap(),
|
||||
SessionMode::NonTunnel
|
||||
);
|
||||
assert_eq!(
|
||||
internal_session_mode([SessionMode::Tunnel].into_iter()).unwrap(),
|
||||
SessionMode::Tunnel
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,17 @@
|
||||
mod args;
|
||||
mod credential;
|
||||
#[cfg(test)]
|
||||
mod flow_tests;
|
||||
mod gateway;
|
||||
mod internal;
|
||||
mod vpn_script;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use gpapi::{
|
||||
clap::report,
|
||||
error::PortalError,
|
||||
gateway::GatewaySelection,
|
||||
gateway::{GatewayLoginContext, GatewaySelection},
|
||||
gp_params::GpParams,
|
||||
os_profile::OsProfile,
|
||||
portal::{PreloginOptions, prelogin, retrieve_config},
|
||||
session::GatewaySessions,
|
||||
utils::request::RequestIdentityError,
|
||||
};
|
||||
use inquire::{Password, PasswordDisplayMode, Select};
|
||||
@@ -34,7 +25,6 @@ use credential::CleanAuthState;
|
||||
use gateway::GatewayConnectError;
|
||||
|
||||
pub(crate) struct ConnectHandler<'a> {
|
||||
cancellation: tokio_util::sync::CancellationToken,
|
||||
args: &'a ConnectArgs,
|
||||
shared_args: &'a SharedArgs<'a>,
|
||||
os_profile: RefCell<OsProfile>,
|
||||
@@ -42,12 +32,6 @@ 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> {
|
||||
@@ -60,7 +44,6 @@ impl<'a> ConnectHandler<'a> {
|
||||
let clean_auth = false;
|
||||
|
||||
Self {
|
||||
cancellation: tokio_util::sync::CancellationToken::new(),
|
||||
args,
|
||||
shared_args,
|
||||
os_profile: RefCell::new(build_os_profile(args)),
|
||||
@@ -68,20 +51,9 @@ 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
|
||||
@@ -121,42 +93,10 @@ impl<'a> ConnectHandler<'a> {
|
||||
}
|
||||
|
||||
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
||||
let cancellation = self.cancellation.clone();
|
||||
let signal = tokio::spawn(async move {
|
||||
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() {
|
||||
sessions.relinquish();
|
||||
} else {
|
||||
sessions.logout().await;
|
||||
}
|
||||
if self.pid_written.load(Ordering::SeqCst) {
|
||||
if let Err(error) = std::fs::remove_file(self.shared_args.lock_file) {
|
||||
warn!("Failed to remove PID file: {error}");
|
||||
}
|
||||
}
|
||||
signal.abort();
|
||||
let _ = signal.await;
|
||||
result
|
||||
}
|
||||
|
||||
fn check_cancelled(&self) -> anyhow::Result<()> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
Err(gpapi::auth::AuthenticationCancelled.into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
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("manual") || browser.eq_ignore_ascii_case("remote"))
|
||||
&& !matches!(self.args.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote"))
|
||||
{
|
||||
bail!("The '--browser-listen' option requires '--browser manual'");
|
||||
bail!("The '--browser-listen' option requires '--browser remote'");
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
@@ -167,30 +107,15 @@ impl<'a> ConnectHandler<'a> {
|
||||
self.latest_key_password.replace(self.args.key_password.clone());
|
||||
|
||||
loop {
|
||||
self.check_cancelled()?;
|
||||
let result = self.handle_impl().await;
|
||||
let Err(err) = self.auth_recovery.borrow().finish(result) else {
|
||||
let Err(err) = self.handle_impl().await else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if err
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
let Some(identity_error) = err.downcast_ref::<RequestIdentityError>() else {
|
||||
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
|
||||
return Err(err);
|
||||
};
|
||||
|
||||
match identity_error {
|
||||
RequestIdentityError::UnsupportedEncryption
|
||||
| RequestIdentityError::LegacyKeyConversion(_)
|
||||
| RequestIdentityError::UnsupportedKeyFormat
|
||||
| RequestIdentityError::InvalidKey
|
||||
| RequestIdentityError::InvalidCertificate
|
||||
| RequestIdentityError::IncompletePkcs12
|
||||
| RequestIdentityError::InvalidPkcs12(_) => return Err(err),
|
||||
match root_cause {
|
||||
RequestIdentityError::NoKey => {
|
||||
let format = self.shared_args.log_format;
|
||||
report(
|
||||
@@ -219,7 +144,6 @@ impl<'a> ConnectHandler<'a> {
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
|
||||
self.check_cancelled()?;
|
||||
let server = self.args.server.as_str();
|
||||
let as_gateway = self.args.as_gateway;
|
||||
|
||||
@@ -231,23 +155,15 @@ impl<'a> ConnectHandler<'a> {
|
||||
}
|
||||
|
||||
if !self.args.cookie_on_stdin {
|
||||
if let Some(result) = self.try_cached_cookie(server).await {
|
||||
return result;
|
||||
if let Some(()) = self.try_cached_cookie(server).await {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
self.check_cancelled()?;
|
||||
|
||||
let Err(err) = self.connect_portal_with_prelogin(server).await else {
|
||||
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...");
|
||||
@@ -274,38 +190,10 @@ impl<'a> ConnectHandler<'a> {
|
||||
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
|
||||
let gp_params = self.build_gp_params();
|
||||
|
||||
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?,
|
||||
};
|
||||
let prelogin = prelogin(portal, &gp_params, self.prelogin_options(false)).await?;
|
||||
|
||||
let cached = self.cached_portal_credential(portal);
|
||||
let cached_config = match cached {
|
||||
Some(cred) => match retrieve_config(portal, &cred, &gp_params, &self.cancellation).await {
|
||||
Ok(config) => Some((cred, config)),
|
||||
Err(error) => {
|
||||
self.check_cancelled()?;
|
||||
warn!("Cached portal authentication failed: {error}");
|
||||
self.clear_cookie_cache();
|
||||
None
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let (cred, mut portal_config) = match cached_config {
|
||||
Some(result) => result,
|
||||
None => {
|
||||
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)
|
||||
}
|
||||
};
|
||||
self.check_cancelled()?;
|
||||
let cred = self.obtain_credential(&prelogin, portal, false).await?;
|
||||
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
|
||||
|
||||
portal_config.sort_gateways(prelogin.region());
|
||||
|
||||
@@ -313,6 +201,7 @@ impl<'a> ConnectHandler<'a> {
|
||||
Some(password) => portal_config.auth_cookie().clone().with_password(password),
|
||||
None => portal_config.auth_cookie().clone(),
|
||||
};
|
||||
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
|
||||
let portal_config_default_browser = portal_config.default_browser().unwrap_or(false);
|
||||
info!("Portal config default-browser: {}", portal_config_default_browser);
|
||||
|
||||
@@ -328,27 +217,29 @@ impl<'a> ConnectHandler<'a> {
|
||||
);
|
||||
|
||||
let mut last_err: Option<anyhow::Error> = None;
|
||||
for (index, gateway) in gateways.iter().enumerate() {
|
||||
for gateway in &gateways {
|
||||
info!("Auto-gateway: attempting gateway {}", gateway);
|
||||
let gateway_context =
|
||||
GatewayLoginContext::new(gateway, GatewaySelection::Auto).with_connect_method(portal_config.connect_method());
|
||||
|
||||
match self
|
||||
.connect_gateway_with_fallback(
|
||||
portal,
|
||||
gateway,
|
||||
gateway.server(),
|
||||
&auth_cookie,
|
||||
&portal_config,
|
||||
GatewaySelection::Auto,
|
||||
&gateways[index + 1..],
|
||||
allow_extend_session,
|
||||
portal_config_default_browser,
|
||||
gateway_context,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => return Ok(()),
|
||||
Err(err) => {
|
||||
self.logout_gateway(gateway.server()).await;
|
||||
if self.auth_recovery.borrow().dmabuf_disabled() || !err.is_before_establishment() {
|
||||
return Err(self.auth_recovery.borrow().terminal(err.into_error()));
|
||||
if !err.is_before_tunnel() {
|
||||
return Err(err.into_error());
|
||||
}
|
||||
warn!(
|
||||
"Auto-gateway: gateway {} failed before session establishment: {}",
|
||||
"Auto-gateway: gateway {} failed before tunnel setup: {}",
|
||||
gateway,
|
||||
err.as_error()
|
||||
);
|
||||
@@ -379,9 +270,6 @@ impl<'a> ConnectHandler<'a> {
|
||||
None => {
|
||||
let gateways = portal_config.gateways();
|
||||
|
||||
if gateways.is_empty() {
|
||||
bail!("No gateways available in portal configuration");
|
||||
}
|
||||
if gateways.len() > 1 {
|
||||
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
|
||||
.with_vim_mode(true)
|
||||
@@ -395,14 +283,18 @@ impl<'a> ConnectHandler<'a> {
|
||||
}
|
||||
};
|
||||
|
||||
let gateway = selected_gateway.server();
|
||||
let gateway_context =
|
||||
GatewayLoginContext::new(selected_gateway, gateway_selection).with_connect_method(portal_config.connect_method());
|
||||
|
||||
self
|
||||
.connect_gateway_with_fallback(
|
||||
portal,
|
||||
selected_gateway,
|
||||
gateway,
|
||||
&auth_cookie,
|
||||
&portal_config,
|
||||
gateway_selection,
|
||||
&[],
|
||||
allow_extend_session,
|
||||
portal_config_default_browser,
|
||||
gateway_context,
|
||||
)
|
||||
.await
|
||||
.map_err(GatewayConnectError::into_error)
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "macos.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
|
||||
pub(super) use platform::builder;
|
||||
@@ -1,625 +0,0 @@
|
||||
//! 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");
|
||||
}
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
//! 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();
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,338 +0,0 @@
|
||||
//! 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"));
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,359 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,456 +0,0 @@
|
||||
//! 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);
|
||||
})
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
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,19 +26,16 @@ impl<'a> DisconnectHandler<'a> {
|
||||
|
||||
pub async fn handle(&self) -> anyhow::Result<()> {
|
||||
// Try to disconnect the CLI client
|
||||
let cli_signalled = match fs::read_to_string(self.lock_file) {
|
||||
Ok(c) => send_signal(c.trim(), Signal::Interrupt).unwrap_or_else(|err| {
|
||||
if let Ok(c) = fs::read_to_string(self.lock_file) {
|
||||
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 !cli_signalled && let Ok(c) = gpservice_lock_info().await {
|
||||
if 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
|
||||
});
|
||||
};
|
||||
|
||||
@@ -51,14 +48,16 @@ impl<'a> DisconnectHandler<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn send_signal(pid: &str, signal: Signal) -> anyhow::Result<bool> {
|
||||
fn send_signal(pid: &str, signal: Signal) -> anyhow::Result<()> {
|
||||
let s = System::new_all();
|
||||
let pid = Pid::from_str(pid)?;
|
||||
|
||||
if let Some(process) = s.process(pid) {
|
||||
info!("Found process {}, sending signal...", pid);
|
||||
|
||||
return Ok(process.kill_with(signal).unwrap_or(false));
|
||||
if process.kill_with(signal).is_none() {
|
||||
warn!("Failed to kill process {}", pid);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,12 +1,122 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use askama::Template;
|
||||
use clap::Args;
|
||||
use gpapi::{
|
||||
clap::args::Os,
|
||||
os_profile::{ClientOs, OsProfileBuilder},
|
||||
process::collection::CollectionBudget,
|
||||
os_profile::{ClientOs, OsProfile, OsProfileBuilder},
|
||||
};
|
||||
use gphip::{ReportContext, ReportInput, generate_report_with_control};
|
||||
use log::debug;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::process::Command;
|
||||
use xmltree::Element;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "hip_report.xml")]
|
||||
struct HipReportTemplate<'a> {
|
||||
client_version: &'a str,
|
||||
generate_time: String,
|
||||
day: String,
|
||||
month: String,
|
||||
year: String,
|
||||
user_name: &'a str,
|
||||
host_info: HostInfo,
|
||||
md5: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct DefenderInfo {
|
||||
#[serde(rename = "appVersion")]
|
||||
app_version: String,
|
||||
#[serde(rename = "engineVersion")]
|
||||
engine_version: String,
|
||||
#[serde(rename = "definitionsVersion")]
|
||||
definitions_version: String,
|
||||
#[serde(rename = "realTimeProtectionEnabled")]
|
||||
real_time_protection_enabled: RealTimeProtection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct RealTimeProtection {
|
||||
value: bool,
|
||||
}
|
||||
|
||||
/// Host information for HIP reporting
|
||||
struct HostInfo {
|
||||
/// Common for all OSes, e.g., "Apple", "Microsoft", "Linux"
|
||||
os_vendor: String,
|
||||
/// Common for all OSes, e.g., "Linux Ubuntu 20.04", "Apple Mac OS X 10.15.7", etc.
|
||||
os_version: String,
|
||||
/// Per-OS machine identifier (UUID for Linux/Windows, MAC for macOS)
|
||||
host_id: String,
|
||||
/// Common for all OSes
|
||||
host_name: String,
|
||||
/// Only for macOS and Windows, e.g., "10.15.7", "10.0.19044.2130"
|
||||
software_version: String,
|
||||
domain: String,
|
||||
network_interfaces: Vec<NetworkInterface>,
|
||||
defender: Option<DefenderInfo>,
|
||||
}
|
||||
|
||||
impl HostInfo {
|
||||
/// Get the first available IPv4 address from network interfaces
|
||||
pub fn default_ipv4(&self) -> &str {
|
||||
self
|
||||
.network_interfaces
|
||||
.first()
|
||||
.and_then(|iface| iface.ipv4.as_deref())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Get the first available IPv6 address from network interfaces
|
||||
pub fn default_ipv6(&self) -> &str {
|
||||
self
|
||||
.network_interfaces
|
||||
.first()
|
||||
.and_then(|iface| iface.ipv6.as_deref())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Network interface information
|
||||
#[derive(Clone)]
|
||||
struct NetworkInterface {
|
||||
name: String,
|
||||
description: String,
|
||||
mac_address: Option<String>,
|
||||
ipv4: Option<String>,
|
||||
ipv6: Option<String>,
|
||||
}
|
||||
|
||||
impl NetworkInterface {
|
||||
/// Create a new network interface with basic information
|
||||
fn new(name: String, description: String) -> Self {
|
||||
Self {
|
||||
name,
|
||||
description,
|
||||
mac_address: None,
|
||||
ipv4: None,
|
||||
ipv6: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set MAC address
|
||||
fn with_mac(mut self, mac: Option<String>) -> Self {
|
||||
self.mac_address = mac;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set IPv4 address
|
||||
fn with_ipv4(mut self, ipv4: Option<String>) -> Self {
|
||||
self.ipv4 = ipv4;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set IPv6 address
|
||||
fn with_ipv6(mut self, ipv6: Option<String>) -> Self {
|
||||
self.ipv6 = ipv6;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub(crate) struct HipArgs {
|
||||
@@ -37,33 +147,434 @@ pub(crate) struct HipArgs {
|
||||
|
||||
pub(crate) struct HipHandler<'a> {
|
||||
args: &'a HipArgs,
|
||||
profile: OsProfile,
|
||||
}
|
||||
|
||||
impl<'a> HipHandler<'a> {
|
||||
pub(crate) fn new(args: &'a HipArgs) -> Self {
|
||||
Self { args }
|
||||
let profile = build_os_profile(args);
|
||||
Self { args, profile }
|
||||
}
|
||||
|
||||
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let client_os = ClientOs::from(self.args.client_os);
|
||||
let mut builder = OsProfileBuilder::new(client_os).client_version(self.args.client_version.clone());
|
||||
if let Some(os_version) = self.args.os_version.as_deref() {
|
||||
builder = builder.os_version(os_version);
|
||||
}
|
||||
if let Some(host_id) = self.args.host_id.as_deref() {
|
||||
builder = builder.host_id_override(host_id);
|
||||
}
|
||||
let input = ReportInput {
|
||||
profile: builder.build_with_control(&budget)?,
|
||||
context: ReportContext::Connected {
|
||||
cookie: self.args.cookie.clone(),
|
||||
client_ip: self.args.client_ip.clone(),
|
||||
client_ipv6: self.args.client_ipv6.clone(),
|
||||
md5: self.args.md5.clone(),
|
||||
},
|
||||
};
|
||||
println!("{}", generate_report_with_control(&input, &budget)?);
|
||||
let cookie_params = self.parse_cookie();
|
||||
let report = self.generate_hip_report(&cookie_params)?;
|
||||
|
||||
debug!("Generated HIP report:\n{}", report);
|
||||
println!("{}", report);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_cookie(&self) -> HashMap<String, String> {
|
||||
// Parse URL-encoded cookie string using serde_urlencoded
|
||||
serde_urlencoded::from_str(&self.args.cookie).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Generate the complete HIP report XML
|
||||
fn generate_hip_report(&self, cookie_params: &HashMap<String, String>) -> anyhow::Result<String> {
|
||||
let (generate_time, day, month, year) = get_current_time_components();
|
||||
let user_name = cookie_params.get("user").map(|s| s.as_str()).unwrap_or("");
|
||||
let host_info = self.collect_host_info(cookie_params);
|
||||
|
||||
let template = HipReportTemplate {
|
||||
client_version: &self.args.client_version,
|
||||
generate_time,
|
||||
day,
|
||||
month,
|
||||
year,
|
||||
user_name,
|
||||
host_info,
|
||||
md5: &self.args.md5,
|
||||
};
|
||||
|
||||
let report = template.render()?;
|
||||
format_xml(&report)
|
||||
}
|
||||
|
||||
/// Collect host information using the configured OsProfile.
|
||||
fn collect_host_info(&self, cookie_params: &'a HashMap<String, String>) -> HostInfo {
|
||||
HostInfoCollector::new(&self.profile, self.args, cookie_params).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct an `OsProfile` from CLI args, falling back to per-OS defaults
|
||||
/// for any value not supplied on the command line.
|
||||
fn build_os_profile(args: &HipArgs) -> OsProfile {
|
||||
let client_os = ClientOs::from(args.client_os);
|
||||
let mut builder = OsProfileBuilder::new(client_os).client_version(args.client_version.clone());
|
||||
if let Some(host_id) = args.host_id.as_deref() {
|
||||
debug!("HIP host-id override supplied: {}", host_id);
|
||||
builder = builder.host_id_override(host_id);
|
||||
}
|
||||
let profile = builder.build();
|
||||
debug!(
|
||||
"HIP OS profile host-id: runtime={}, projected={}, client_os={}",
|
||||
profile.host_identity().host_id(),
|
||||
profile.host_id(),
|
||||
client_os.as_str()
|
||||
);
|
||||
profile
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Host Information Collector
|
||||
// ============================================================================
|
||||
|
||||
/// Helper struct for collecting host information.
|
||||
///
|
||||
/// Identity values (vendor, host_id, computer name, software version) come
|
||||
/// from the configured `OsProfile`, while runtime state (network interfaces,
|
||||
/// IP addresses) is enumerated here from the underlying machine.
|
||||
struct HostInfoCollector<'p, 'a> {
|
||||
profile: &'p OsProfile,
|
||||
args: &'a HipArgs,
|
||||
cookie_params: &'a HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl<'p, 'a> HostInfoCollector<'p, 'a> {
|
||||
fn new(profile: &'p OsProfile, args: &'a HipArgs, cookie_params: &'a HashMap<String, String>) -> Self {
|
||||
Self {
|
||||
profile,
|
||||
args,
|
||||
cookie_params,
|
||||
}
|
||||
}
|
||||
|
||||
/// Domain belongs to the runtime user/session, not the simulated OS, so
|
||||
/// it is sourced from the auth cookie when available.
|
||||
fn get_domain(&self) -> String {
|
||||
self
|
||||
.cookie_params
|
||||
.get("domain")
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Collect network interface information with fallback
|
||||
fn collect_network_interface(&self) -> NetworkInterface {
|
||||
match netdev::get_default_interface() {
|
||||
Ok(iface) => NetworkInterface::new(
|
||||
iface.name.clone(),
|
||||
iface.description.unwrap_or_else(|| iface.name.clone()),
|
||||
)
|
||||
.with_mac(iface.mac_addr.map(|mac| mac.address()))
|
||||
.with_ipv4(iface.ipv4.first().map(|ip| ip.addr().to_string()))
|
||||
.with_ipv6(iface.ipv6.first().map(|ip| ip.addr().to_string())),
|
||||
|
||||
Err(_) => NetworkInterface::new("unknown".to_string(), "unknown".to_string())
|
||||
.with_ipv4(self.args.client_ip.clone())
|
||||
.with_ipv6(self.args.client_ipv6.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Single entry point for collecting host info — dispatches per-OS
|
||||
/// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`.
|
||||
fn collect(&self) -> HostInfo {
|
||||
let runtime_iface = self.collect_network_interface();
|
||||
let primary = self.adapt_primary_interface(&runtime_iface);
|
||||
|
||||
let mut interfaces = vec![primary.clone()];
|
||||
interfaces.extend(self.extra_interfaces(&primary));
|
||||
|
||||
HostInfo {
|
||||
os_vendor: self.profile.os_vendor().to_string(),
|
||||
os_version: self.profile.os_version().to_string(),
|
||||
host_id: self.profile.host_id().to_string(),
|
||||
host_name: self.profile.computer().to_string(),
|
||||
software_version: self.profile.software_version().to_string(),
|
||||
domain: self.domain_for_profile(),
|
||||
network_interfaces: interfaces,
|
||||
defender: self.defender_for_profile(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the primary network interface with OS-appropriate naming and
|
||||
/// MAC formatting. When emulating a different OS, the runtime interface
|
||||
/// name/description are replaced with the canonical placeholder for the
|
||||
/// target OS.
|
||||
fn adapt_primary_interface(&self, runtime: &NetworkInterface) -> NetworkInterface {
|
||||
let (name, description) = if self.profile.is_native() {
|
||||
(runtime.name.clone(), runtime.description.clone())
|
||||
} else {
|
||||
placeholder_interface_for(self.profile, runtime)
|
||||
};
|
||||
|
||||
NetworkInterface {
|
||||
name,
|
||||
description,
|
||||
mac_address: format_mac_for(self.profile, runtime.mac_address.clone()),
|
||||
ipv4: runtime.ipv4.clone(),
|
||||
ipv6: runtime.ipv6.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional interfaces appended after the primary. Only Windows
|
||||
/// emits the software loopback interface in HIP reports.
|
||||
fn extra_interfaces(&self, primary: &NetworkInterface) -> Vec<NetworkInterface> {
|
||||
match self.profile.client_os() {
|
||||
ClientOs::Windows => vec![NetworkInterface {
|
||||
name: derive_windows_network_name(self.profile.host_id(), primary),
|
||||
description: "Software Loopback Interface 1".to_string(),
|
||||
mac_address: Some(String::new()),
|
||||
ipv4: Some("127.0.0.1".to_string()),
|
||||
ipv6: Some("::1".to_string()),
|
||||
}],
|
||||
ClientOs::Linux | ClientOs::Mac => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Linux HIP reports omit the domain field; macOS/Windows include it
|
||||
/// from the auth cookie.
|
||||
fn domain_for_profile(&self) -> String {
|
||||
match self.profile.client_os() {
|
||||
ClientOs::Linux => String::new(),
|
||||
ClientOs::Mac | ClientOs::Windows => self.get_domain(),
|
||||
}
|
||||
}
|
||||
|
||||
fn defender_for_profile(&self) -> Option<DefenderInfo> {
|
||||
match self.profile.client_os() {
|
||||
ClientOs::Linux => detect_microsoft_defender_blocking(),
|
||||
ClientOs::Mac | ClientOs::Windows => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn detect_microsoft_defender_blocking() -> Option<DefenderInfo> {
|
||||
let output = Command::new("mdatp")
|
||||
.arg("health")
|
||||
.arg("--output")
|
||||
.arg("json")
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
if !output.status.success() {
|
||||
debug!("mdatp health command failed");
|
||||
return None;
|
||||
}
|
||||
|
||||
let json = String::from_utf8(output.stdout).ok()?;
|
||||
let defender = parse_defender_info(&json)?;
|
||||
|
||||
debug!("Detected Microsoft Defender: {:?}", defender);
|
||||
Some(defender)
|
||||
}
|
||||
|
||||
fn parse_defender_info(json: &str) -> Option<DefenderInfo> {
|
||||
serde_json::from_str(json).ok()
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Per-OS interface helpers (selected via OsProfile, not cfg)
|
||||
// ============================================================================
|
||||
|
||||
/// Canonical interface name/description for the target OS when the runtime
|
||||
/// is a different OS (i.e. emulation).
|
||||
fn placeholder_interface_for(profile: &OsProfile, runtime: &NetworkInterface) -> (String, String) {
|
||||
match profile.client_os() {
|
||||
ClientOs::Linux => ("enp1s0f0".to_string(), "enp1s0f0".to_string()),
|
||||
ClientOs::Mac => ("en0".to_string(), "en0".to_string()),
|
||||
ClientOs::Windows => (
|
||||
derive_windows_network_name(profile.host_id(), runtime),
|
||||
"PANGP Virtual Ethernet Adapter Secure".to_string(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// MAC address formatting per target OS. Windows uses hyphen separators;
|
||||
/// Linux and macOS preserve the colon-separated form returned by the
|
||||
/// platform.
|
||||
fn format_mac_for(profile: &OsProfile, mac: Option<String>) -> Option<String> {
|
||||
match profile.client_os() {
|
||||
ClientOs::Windows => mac.map(|m| m.replace(':', "-")),
|
||||
ClientOs::Linux | ClientOs::Mac => mac,
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Utility Functions
|
||||
// ============================================================================
|
||||
|
||||
/// Get current time components for HIP report
|
||||
fn get_current_time_components() -> (String, String, String, String) {
|
||||
let now = chrono::Local::now();
|
||||
(
|
||||
now.format("%m/%d/%Y %H:%M:%S").to_string(),
|
||||
now.format("%d").to_string(),
|
||||
now.format("%m").to_string(),
|
||||
now.format("%Y").to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Format XML string with proper indentation
|
||||
fn format_xml(xml_str: &str) -> anyhow::Result<String> {
|
||||
let xml = Element::parse(xml_str.as_bytes())?;
|
||||
|
||||
let config = xmltree::EmitterConfig::new().perform_indent(true);
|
||||
let mut xml_buf = Vec::new();
|
||||
xml.write_with_config(&mut xml_buf, config)?;
|
||||
|
||||
Ok(String::from_utf8(xml_buf)?)
|
||||
}
|
||||
|
||||
fn derive_windows_network_name(host_id: &str, iface: &NetworkInterface) -> String {
|
||||
let seed = format!(
|
||||
"{}-{}-{}",
|
||||
host_id,
|
||||
iface.mac_address.as_deref().unwrap_or("00:00:00:00:00:00"),
|
||||
iface.name
|
||||
);
|
||||
|
||||
format!(
|
||||
"{{{}}}",
|
||||
uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_DNS, seed.as_bytes())
|
||||
.to_string()
|
||||
.to_uppercase()
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpapi::os_profile::runtime_client_os;
|
||||
|
||||
fn make_hip_args(client_os: Os) -> HipArgs {
|
||||
HipArgs {
|
||||
client_version: "6.2.4-49".to_string(),
|
||||
client_os,
|
||||
os_version: Some("test-os-version".to_string()),
|
||||
host_id: None,
|
||||
cookie: String::new(),
|
||||
client_ip: None,
|
||||
client_ipv6: None,
|
||||
md5: "deadbeef".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn make_profile(client_os: ClientOs) -> OsProfile {
|
||||
OsProfileBuilder::new(client_os).build()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_info_os_vendor_is_linux_for_linux_profile() {
|
||||
let args = make_hip_args(Os::Linux);
|
||||
let profile = make_profile(ClientOs::Linux);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
|
||||
|
||||
assert_eq!(info.os_vendor, "Linux");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_info_os_vendor_is_apple_for_mac_profile() {
|
||||
let args = make_hip_args(Os::Mac);
|
||||
let profile = make_profile(ClientOs::Mac);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
|
||||
|
||||
assert_eq!(info.os_vendor, "Apple");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_info_os_vendor_is_microsoft_for_windows_profile() {
|
||||
let args = make_hip_args(Os::Windows);
|
||||
let profile = make_profile(ClientOs::Windows);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
|
||||
|
||||
assert_eq!(info.os_vendor, "Microsoft");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_info_host_id_comes_from_os_profile() {
|
||||
let args = make_hip_args(Os::Linux);
|
||||
let profile = make_profile(ClientOs::Linux);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
|
||||
|
||||
assert_eq!(info.host_id, profile.host_id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_info_host_id_independent_of_runtime_for_each_os() {
|
||||
// host_id should reflect the OsProfile's machine identity for every
|
||||
// simulated OS, regardless of the runtime platform.
|
||||
for (client_os, os_arg) in [
|
||||
(ClientOs::Linux, Os::Linux),
|
||||
(ClientOs::Mac, Os::Mac),
|
||||
(ClientOs::Windows, Os::Windows),
|
||||
] {
|
||||
let args = make_hip_args(os_arg);
|
||||
let profile = make_profile(client_os);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
|
||||
|
||||
assert_eq!(info.host_id, profile.host_id());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hip_os_version_argument_is_ignored() {
|
||||
let args = make_hip_args(Os::Linux);
|
||||
let profile = build_os_profile(&args);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
|
||||
|
||||
assert_eq!(info.os_version, profile.os_version());
|
||||
assert_ne!(info.os_version, "test-os-version");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_id_argument_sets_profile_runtime_identity() {
|
||||
let mut args = make_hip_args(Os::default());
|
||||
args.host_id = Some("auth-host-id".to_string());
|
||||
|
||||
let profile = build_os_profile(&args);
|
||||
|
||||
assert_eq!(profile.client_os(), runtime_client_os());
|
||||
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_info_uses_host_id_argument_for_native_profile() {
|
||||
let mut args = make_hip_args(Os::default());
|
||||
args.host_id = Some("auth-host-id".to_string());
|
||||
let profile = build_os_profile(&args);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
|
||||
|
||||
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
|
||||
assert_eq!(info.host_id, profile.host_id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_microsoft_defender_health_json() {
|
||||
let defender = parse_defender_info(
|
||||
r#"{
|
||||
"appVersion": "101.25042.0000",
|
||||
"engineVersion": "1.1.25040.2",
|
||||
"definitionsVersion": "1.429.201.0",
|
||||
"realTimeProtectionEnabled": { "value": true }
|
||||
}"#,
|
||||
)
|
||||
.expect("defender health json should parse");
|
||||
|
||||
assert_eq!(defender.app_version, "101.25042.0000");
|
||||
assert_eq!(defender.engine_version, "1.1.25040.2");
|
||||
assert_eq!(defender.definitions_version, "1.429.201.0");
|
||||
assert!(defender.real_time_protection_enabled.value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_microsoft_defender_health_json() {
|
||||
assert!(parse_defender_info("{}").is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{fs, path::PathBuf};
|
||||
use std::{collections::HashMap, fs, path::PathBuf};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use std::process::{Command, ExitStatus};
|
||||
@@ -11,7 +11,10 @@ use clap::Args;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use common::binary_paths;
|
||||
use directories::ProjectDirs;
|
||||
use gpapi::{process::desktop_launcher::DesktopLauncher, utils::endpoint::http_endpoint};
|
||||
use gpapi::{
|
||||
process::service_launcher::ServiceLauncher,
|
||||
utils::{endpoint::http_endpoint, env_utils, shutdown_signal},
|
||||
};
|
||||
use log::info;
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -66,13 +69,27 @@ impl<'a> LaunchGuiHandler<'a> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
tokio::spawn(async move {
|
||||
shutdown_signal().await;
|
||||
info!("Shutting down...");
|
||||
});
|
||||
|
||||
let log_file = get_log_file()?;
|
||||
let log_file_path = log_file.to_string_lossy().to_string();
|
||||
|
||||
info!("Log file: {}", log_file_path);
|
||||
|
||||
let exit_status = DesktopLauncher::new(env!("CARGO_PKG_VERSION"))
|
||||
let mut extra_envs = HashMap::<String, String>::new();
|
||||
extra_envs.insert("GP_LOG_FILE".into(), log_file_path.clone());
|
||||
|
||||
// Persist the environment variables to a file
|
||||
let env_file = env_utils::persist_env_vars(Some(extra_envs))?;
|
||||
let env_file = env_file.into_temp_path();
|
||||
let env_file_path = env_file.to_string_lossy().to_string();
|
||||
|
||||
let exit_status = ServiceLauncher::new()
|
||||
.minimized(self.args.minimized)
|
||||
.env_file(&env_file_path)
|
||||
.log_file(&log_file_path)
|
||||
.launch()
|
||||
.await?;
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
mod background;
|
||||
mod cli;
|
||||
mod connect;
|
||||
mod dashboard;
|
||||
mod diagnostics;
|
||||
mod disconnect;
|
||||
mod hip;
|
||||
mod launch_gui;
|
||||
|
||||
@@ -75,7 +75,6 @@ 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 {
|
||||
@@ -91,7 +90,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -139,15 +139,6 @@
|
||||
{% elif host_info.os_vendor == "Apple" -%}
|
||||
<entry name="anti-malware">
|
||||
<list>
|
||||
{% if let Some(sentinel) = &host_info.sentinel %}
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod vendor="SentinelOne" name="Sentinel Agent" version="{{ sentinel.version }}" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
|
||||
<real-time-protection>{% if sentinel.real_time_protection %}yes{% else %}no{% endif %}</real-time-protection>
|
||||
<last-full-scan-time>n/a</last-full-scan-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
{% endif -%}
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod vendor="Apple Inc." name="Xprotect" version="2167" defver="235000000000000" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
|
||||
@@ -199,16 +190,6 @@
|
||||
</entry>
|
||||
<entry name="firewall">
|
||||
<list>
|
||||
{% if let Some(sentinel) = &host_info.sentinel %}
|
||||
{% if let Some(firewall_enabled) = sentinel.firewall_enabled %}
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod vendor="SentinelOne" name="Sentinel Agent" version="{{ sentinel.version }}"/>
|
||||
<is-enabled>{% if firewall_enabled %}yes{% else %}no{% endif %}</is-enabled>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
{% endif -%}
|
||||
{% endif -%}
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod vendor="Apple Inc." name="Mac OS X Builtin Firewall" version="{{ host_info.software_version }}"/>
|
||||
@@ -237,17 +218,8 @@
|
||||
</entry>
|
||||
{% elif host_info.os_vendor == "Linux" -%}
|
||||
<entry name="anti-malware">
|
||||
{% if let Some(defender) = &host_info.defender -%}
|
||||
<list>
|
||||
{% if let Some(sentinel) = &host_info.sentinel %}
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod vendor="SentinelOne" name="Sentinel Agent" version="{{ sentinel.version }}" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="1"/>
|
||||
<real-time-protection>{% if sentinel.real_time_protection %}yes{% else %}no{% endif %}</real-time-protection>
|
||||
<last-full-scan-time>n/a</last-full-scan-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
{% endif -%}
|
||||
{% if let Some(defender) = &host_info.defender %}
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Microsoft Defender ATP" version="{{ defender.app_version }}" defver="{{ defender.definitions_version }}" prodType="3" engver="{{ defender.engine_version }}" osType="1" vendor="Microsoft Corporation" dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
|
||||
@@ -256,17 +228,10 @@
|
||||
<last-full-scan-time>n/a</last-full-scan-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
{% endif -%}
|
||||
{% if let Some(clamav) = &host_info.clamav %}
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod vendor="Cisco Systems, Inc." name="ClamAV" version="{{ clamav.version }}"{% if let Some(definitions_version) = &clamav.definitions_version %} defver="{{ definitions_version }}"{% endif %} engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="1"/>
|
||||
<real-time-protection>{% if clamav.real_time_protection %}yes{% else %}no{% endif %}</real-time-protection>
|
||||
<last-full-scan-time>n/a</last-full-scan-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
{% endif -%}
|
||||
</list>
|
||||
{% else -%}
|
||||
<list/>
|
||||
{% endif -%}
|
||||
</entry>
|
||||
<entry name="disk-backup">
|
||||
<list/>
|
||||
@@ -289,14 +254,6 @@
|
||||
</entry>
|
||||
<entry name="firewall">
|
||||
<list>
|
||||
{% if let Some(ufw) = &host_info.ufw %}
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod vendor="Canonical Ltd." name="UFW" version="{{ ufw.version }}"/>
|
||||
<is-enabled>{% if ufw.is_enabled %}yes{% else %}no{% endif %}</is-enabled>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
{% endif -%}
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="IPTables" version="1.8.4" vendor="IPTables">
|
||||
@@ -1,77 +0,0 @@
|
||||
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'"));
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
//! 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");
|
||||
}
|
||||
@@ -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),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`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 x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,re());else{var t=n(l);t!==null&&oe(x,t.startTime-e)}}var S=!1,C=-1,w=5,ee=-1;function te(){return g?!0:!(e.unstable_now()-ee<w)}function ne(){if(g=!1,S){var t=e.unstable_now();ee=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(C),C=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&te());){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&&oe(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?re():S=!1}}}var re;if(typeof y==`function`)re=function(){y(ne)};else if(typeof MessageChannel<`u`){var ie=new MessageChannel,ae=ie.port2;ie.port1.onmessage=ne,re=function(){ae.postMessage(null)}}else re=function(){_(ne,0)};function oe(t,n){C=_(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`):w=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(C),C=-1):h=!0,oe(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,re()))),r},e.unstable_shouldYield=te,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.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.Line truncated
|
||||
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
|
||||
`+Se+e+Ce}var Te=!1;function Ee(e,t){if(!e||Te)return``;Te=!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}e.call(n.prototype)}}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{Te=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?we(n):``}function De(e,t){switch(e.tag){case 26:case 27:case 5:return we(e.type);case 16:return we(`Lazy`);case 13:return e.child!==t&&t!==null?we(`Suspense Fallback`):we(`Suspense`);case 19:return we(`SuspenseList`);case 0:case 15:return Ee(e.type,!1);case 11:return Ee(e.type.render,!1);case 1:return Ee(e.type,!0);case 31:return we(`Activity`);default:return``}}function Oe(e){try{var t=``,n=null;do t+=De(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,Ae=t.unstable_scheduleCallback,je=t.unstable_cancelCallback,Me=t.unstable_shouldYield,Ne=t.unstable_requestPaint,Pe=t.unstable_now,Fe=t.unstable_getCurrentPriorityLevel,Ie=t.unstable_ImmediatePriority,Le=t.unstable_UserBlockingPriority,Re=t.unstable_NormalPriority,ze=t.unstable_LowPriority,Be=t.unstable_IdlePriority,Ve=t.log,He=t.unstable_setDisableYieldValue,Ue=null,We=null;function Ge(e){if(typeof Ve==`function`&&He(e),We&&typeof We.setStrictMode==`function`)try{We.setStrictMode(Ue,e)}catch{}}var Ke=Math.clz32?Math.clz32:Ye,qe=Math.log,Je=Math.LN2;function Ye(e){return e>>>=0,e===0?32:31-(qe(e)/Je|0)|0}var Xe=256,Ze=262144,Qe=4194304;function $e(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&261888;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 et(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=$e(n))):i=$e(o):i=$e(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=$e(n))):i=$e(o)):i=$e(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 tt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function nt(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 rt(){var e=Qe;return Qe<<=1,!(Qe&62914560)&&(Qe=4194304),e}function it(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function at(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function ot(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-Ke(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&&st(e,r,0),a!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=a&~(o&~t))}function st(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-Ke(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function ct(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-Ke(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function lt(e,t){var n=t&-t;return n=n&42?1:ut(n),(n&(e.suspendedLanes|t))===0?n:0}function ut(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 dt(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function ft(){var e=E.p;return e===0?(e=window.event,e===void 0?32:mp(e.type)):e}function pt(e,t){var n=E.p;try{return E.p=e,t()}finally{E.p=n}}var mt=Math.random().toString(36).slice(2),ht=`__reactFiber$`+mt,gt=`__reactProps$`+mt,_t=`__reactContainer$`+mt,vt=`__reactEvents$`+mt,yt=`__reactListeners$`+mt,bt=`__reactHandles$`+mt,xt=`__reactResources$`+mt,St=`__reactMarker$`+mt;function Ct(e){delete e[ht],delete e[gt],delete e[vt],delete e[yt],delete e[bt]}function wt(e){var t=e[ht];if(t)return t;for(var n=e.parentNode;n;){if(t=n[_t]||n[ht]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=df(e);e!==null;){if(n=e[ht])return n;e=df(e)}return t}e=n,n=e.parentNode}return null}function Tt(e){if(e=e[ht]||e[_t]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function Et(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(s(33))}function Dt(e){var t=e[xt];return t||=e[xt]={hoistableStyles:new Map,hoistableScripts:new Map},t}function Ot(e){e[St]=!0}var kt=new Set,At={};function jt(e,t){Mt(e,t),Mt(e+`Capture`,t)}function Mt(e,t){for(At[e]=t,e=0;e<t.length;e++)kt.add(t[e])}var Nt=RegExp(`^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001Line truncated
|
||||
`).replace(Ad,``)}function Md(e,t){return t=jd(t),jd(e)===t}function $(e,t,n,r,i,a){switch(n){case`children`:typeof r==`string`?t===`body`||t===`textarea`&&r===``||en(e,r):(typeof r==`number`||typeof r==`bigint`)&&t!==`body`&&en(e,``+r);break;case`className`:Rt(e,`class`,r);break;case`tabIndex`:Rt(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:Rt(e,n,r);break;case`style`:rn(e,r,a);break;case`data`:if(t!==`object`){Rt(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=cn(``+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}else 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)));if(r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=cn(``+r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=ln);break;case`onScroll`:r!=null&&Q(`scroll`,e);break;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);break;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));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=cn(``+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`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),Lt(e,`popover`,r);break;case`xlinkActuate`:zt(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:zt(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:zt(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:zt(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:zt(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:zt(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:zt(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:zt(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:zt(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:Lt(e,`is`,r);break;case`innerText`:case`textContent`:break;default:(!(2<n.length)||n[0]!==`o`&&n[0]!==`O`||n[1]!==`n`&&n[1]!==`N`)&&(n=on.get(n)||n,Lt(e,n,r))}}function Nd(e,t,n,r,i,a){switch(n){case`style`:rn(e,r,a);break;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));e.innerHTML=n}}break;case`children`:typeof r==`string`?en(e,r):(typeof r==`number`||typeof r==`bigint`)&&en(e,``+r);break;case`onScroll`:r!=null&&Q(`scroll`,e);break;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);break;case`onClick`:r!=null&&(e.onclick=ln);break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`innerHTML`:case`re
Line truncated
|
||||
@@ -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`)||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-BU3mus1z.js"></script>
|
||||
<script type="module" crossorigin src="/assets/main-BD0fDtWU.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.3",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0"
|
||||
"@tauri-apps/api": "^2.11.1",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@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.2",
|
||||
"@typescript-eslint/parser": "^8.71.2",
|
||||
"@vitejs/plugin-react": "^6.1.2",
|
||||
"eslint": "^9.39.5",
|
||||
"@tauri-apps/cli": "^2.11.2",
|
||||
"@types/node": "^25.9.4",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@typescript-eslint/eslint-plugin": "^8.61.1",
|
||||
"@typescript-eslint/parser": "^8.61.1",
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"prettier": "3.9.10",
|
||||
"prettier": "3.8.3",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^8.3.4"
|
||||
"vite": "^8.0.16"
|
||||
},
|
||||
"packageManager": "[email protected]"
|
||||
}
|
||||
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 56 KiB After Width: | Height: | Size: 57 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="8" stdDeviation="12" flood-color="#174d6f" flood-opacity=".14"/>
|
||||
<feDropShadow dx="0" dy="18" stdDeviation="22" 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 |
@@ -246,11 +246,13 @@ async fn run_installer_connection(
|
||||
rejection.code(),
|
||||
rejection.message()
|
||||
)),
|
||||
_ => Err(anyhow::anyhow!("Service sent an unexpected GUI installation reply")),
|
||||
ServiceResult::VpncScriptMetadata(_) => {
|
||||
Err(anyhow::anyhow!("Service sent an unexpected VPNC script metadata reply"))
|
||||
}
|
||||
};
|
||||
let _ = command.reply.send(result);
|
||||
}
|
||||
ServerMessage::Event { .. } | ServerMessage::Snapshot { .. } | ServerMessage::TunnelStatistics { .. } => {}
|
||||
ServerMessage::Event { .. } | ServerMessage::Snapshot { .. } => {}
|
||||
ServerMessage::Attached { .. } => bail!("Service sent a duplicate attach response"),
|
||||
},
|
||||
Message::Ping(data) => socket.send(Message::Pong(data)).await?,
|
||||
@@ -299,7 +301,6 @@ async fn connect_installer_at(
|
||||
let (mut socket, _) = connect_async_with_config(endpoint, Some(config), false).await?;
|
||||
let prelude = ClientPrelude {
|
||||
product_version: credential.product_version().to_owned(),
|
||||
hip_protocol_version: gpapi::service::transport::HIP_PROTOCOL_VERSION,
|
||||
service_instance_id: credential.service_instance_id(),
|
||||
session_id: credential.session_id(),
|
||||
};
|
||||
@@ -631,8 +632,8 @@ mod tests {
|
||||
current_revision: 0,
|
||||
snapshot: VpnEnv {
|
||||
vpn_state: VpnState::Disconnected,
|
||||
tunnel_state: None,
|
||||
vpnc_script: None,
|
||||
csd_wrapper: None,
|
||||
auth_executable: String::new(),
|
||||
host_info: HostInfo {
|
||||
host_identity: HostIdentity::collect(),
|
||||
|
||||
@@ -22,7 +22,7 @@ export default defineConfig(async () => {
|
||||
build: {
|
||||
rolldownOptions: {
|
||||
input: {
|
||||
main: resolve(import.meta.dirname, "index.html"),
|
||||
main: resolve(__dirname, "index.html"),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -7,9 +7,6 @@ license.workspace = true
|
||||
[dependencies]
|
||||
common = { path = "../../crates/common" }
|
||||
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
|
||||
gphip = { path = "../../crates/gphip" }
|
||||
gptunnel = { path = "../../crates/gptunnel" }
|
||||
base64.workspace = true
|
||||
openconnect = { path = "../../crates/openconnect" }
|
||||
clap.workspace = true
|
||||
anyhow.workspace = true
|
||||
@@ -28,15 +25,10 @@ thiserror.workspace = true
|
||||
uuid = { workspace = true, features = ["v4"] }
|
||||
zeroize.workspace = true
|
||||
tempfile.workspace = true
|
||||
getrandom = "0.4"
|
||||
mac_address = "1.2.1"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
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" }
|
||||
sha256.workspace = true
|
||||
@@ -4,15 +4,6 @@ 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");
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
#[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")))]
|
||||
#[path = "unsupported.rs"]
|
||||
mod platform;
|
||||
|
||||
fn main() {
|
||||
platform::run();
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
use std::io::Read;
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use clap::{Parser, Subcommand};
|
||||
use gpservice::hip_approval::{self, InstallRequest};
|
||||
use nix::unistd::Uid;
|
||||
|
||||
const MAX_INSTALL_REQUEST_SIZE: u64 = 2 * 1024 * 1024;
|
||||
|
||||
#[derive(Parser)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
Install,
|
||||
Revoke { approval_id: String },
|
||||
}
|
||||
|
||||
fn try_run() -> anyhow::Result<()> {
|
||||
ensure!(Uid::effective().is_root(), "HIP script installer must run as root");
|
||||
let approving_uid = std::env::var("PKEXEC_UID")
|
||||
.context("HIP script installer requires pkexec authorization")?
|
||||
.parse::<u32>()
|
||||
.context("Invalid pkexec user identity")?;
|
||||
ensure!(approving_uid != 0, "HIP script installer requires a desktop user");
|
||||
|
||||
match Cli::parse().command {
|
||||
Command::Install => {
|
||||
let mut input = Vec::new();
|
||||
std::io::stdin()
|
||||
.lock()
|
||||
.take(MAX_INSTALL_REQUEST_SIZE + 1)
|
||||
.read_to_end(&mut input)?;
|
||||
ensure!(
|
||||
input.len() as u64 <= MAX_INSTALL_REQUEST_SIZE,
|
||||
"HIP install request is too large"
|
||||
);
|
||||
let request: InstallRequest = serde_json::from_slice(&input).context("Invalid HIP install request")?;
|
||||
let info = hip_approval::install(request, approving_uid)?;
|
||||
serde_json::to_writer(std::io::stdout().lock(), &info)?;
|
||||
println!();
|
||||
}
|
||||
Command::Revoke { approval_id } => hip_approval::revoke(&approval_id, approving_uid)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn run() {
|
||||
if let Err(err) = try_run() {
|
||||
eprintln!("HIP approval failed: {err:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
pub(super) fn run() {
|
||||
eprintln!("Root HIP script approvals are unavailable on this platform");
|
||||
std::process::exit(1);
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::time::Duration;
|
||||
use std::{collections::HashMap, io::Write};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use clap::Parser;
|
||||
@@ -12,8 +15,9 @@ use gpapi::logger;
|
||||
#[cfg(debug_assertions)]
|
||||
use gpapi::utils::lock_file::dev_service_lock_file_path;
|
||||
use gpapi::{
|
||||
service::vpn_state::VpnState,
|
||||
utils::{lock_file::LockFile, redact::Redaction, shutdown_signal},
|
||||
process::gui_launcher::GuiLauncher,
|
||||
service::{request::WsRequest, vpn_state::VpnState},
|
||||
utils::{env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
use log::{Log, Metadata, Record};
|
||||
@@ -60,9 +64,9 @@ impl Log for RedactingMacosLogger {
|
||||
#[command(version = VERSION)]
|
||||
struct Cli {
|
||||
#[clap(long)]
|
||||
#[cfg_attr(debug_assertions, clap(conflicts_with = "dev_standalone"))]
|
||||
#[cfg_attr(target_os = "macos", clap(conflicts_with = "macos_brokered"))]
|
||||
desktop_credentials: bool,
|
||||
minimized: bool,
|
||||
#[clap(long)]
|
||||
env_file: Option<String>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[clap(long, requires_all = ["dev_uid", "dev_bootstrap_socket"])]
|
||||
dev_standalone: bool,
|
||||
@@ -91,42 +95,33 @@ impl Cli {
|
||||
bail!("Another instance of the service is already running");
|
||||
}
|
||||
|
||||
// Channel for receiving VPN state from the lifecycle actor
|
||||
// Channel for sending requests to the VPN task
|
||||
let (ws_req_tx, ws_req_rx) = mpsc::channel::<WsRequest>(32);
|
||||
// Channel for receiving the VPN state from the VPN task
|
||||
let (vpn_state_tx, vpn_state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let gui_restart_requested = Arc::new(AtomicBool::new(false));
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let externally_brokered = self.externally_brokered();
|
||||
let desktop_uid = if self.desktop_credentials {
|
||||
anyhow::ensure!(
|
||||
nix::unistd::Uid::effective().is_root(),
|
||||
"Desktop credentials require a privileged service"
|
||||
);
|
||||
let uid: u32 = std::env::var("PKEXEC_UID")
|
||||
.context("Desktop credentials require a pkexec-authenticated user")?
|
||||
.parse()
|
||||
.context("Invalid pkexec user")?;
|
||||
anyhow::ensure!(uid != 0, "Desktop credentials require a non-root user");
|
||||
anyhow::ensure!(
|
||||
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.is_some(),
|
||||
"Desktop user is unavailable"
|
||||
);
|
||||
Some(uid)
|
||||
} else {
|
||||
crate::runtime_user::desktop_uid()
|
||||
};
|
||||
let desktop_channel = if self.desktop_credentials {
|
||||
Some(crate::desktop_client::DesktopClient::from_stdio()?)
|
||||
let trusted_csd_uid = crate::runtime_user::trusted_csd_uid()?;
|
||||
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(),
|
||||
ws_req_tx.clone(),
|
||||
Arc::clone(&gui_restart_requested),
|
||||
Arc::clone(&redaction),
|
||||
!externally_brokered,
|
||||
externally_brokered,
|
||||
brokered_scripts_dir,
|
||||
));
|
||||
|
||||
let mut vpn_task = VpnTask::new(ws_req_rx, vpn_state_tx, externally_brokered, trusted_csd_uid);
|
||||
#[cfg(target_os = "macos")]
|
||||
let idle_vpn_state_rx = vpn_state_rx.clone();
|
||||
let ws_server = WsServer::new(
|
||||
@@ -142,16 +137,13 @@ 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, credential_ready_tx).await {
|
||||
if let Err(err) = credential_server.start(credential_token).await {
|
||||
warn!("Broker credential server stopped: {err}");
|
||||
let _ = credential_shutdown.send(()).await;
|
||||
}
|
||||
@@ -187,48 +179,32 @@ impl Cli {
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let lifecycle = lifecycle.clone();
|
||||
let vpn_ctx = vpn_task.context();
|
||||
let ws_ctx = ws_server.context();
|
||||
|
||||
tokio::spawn(async move { signals::handle_signals(lifecycle, ws_ctx).await });
|
||||
tokio::spawn(async move { signals::handle_signals(vpn_ctx, ws_ctx).await });
|
||||
}
|
||||
|
||||
let desktop_cancel = server_token.clone();
|
||||
let shutdown_token = server_token.clone();
|
||||
let vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).await });
|
||||
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);
|
||||
#[cfg(debug_assertions)]
|
||||
let launch_managed_gui = !self.dev_standalone && !externally_brokered;
|
||||
#[cfg(not(debug_assertions))]
|
||||
let launch_managed_gui = !externally_brokered;
|
||||
|
||||
let desktop_client_handle = if let Some(channel) = desktop_channel {
|
||||
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
|
||||
.serve(registry, desktop_uid, gui_restart_requested, desktop_cancel)
|
||||
.await
|
||||
{
|
||||
warn!("Desktop credential channel ended: {err}");
|
||||
}
|
||||
if launch_managed_gui {
|
||||
ws_ready_rx.await.context("WebSocket server failed to start")?;
|
||||
let envs = self.env_file.as_ref().map(env_utils::load_env_vars).transpose()?;
|
||||
let minimized = self.minimized;
|
||||
tokio::spawn(async move {
|
||||
launch_gui(envs, registry, minimized, gui_restart_requested).await;
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
}))
|
||||
});
|
||||
} else {
|
||||
info!("Running with an externally launched GUI");
|
||||
None
|
||||
};
|
||||
info!("Running with a separately started debug GUI");
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = shutdown_signal() => {
|
||||
@@ -240,11 +216,7 @@ impl Cli {
|
||||
}
|
||||
|
||||
vpn_task_cancel_token.cancel();
|
||||
shutdown_token.cancel();
|
||||
let _ = tokio::join!(vpn_task_handle, ws_server_handle);
|
||||
if let Some(handle) = desktop_client_handle {
|
||||
let _ = handle.await;
|
||||
}
|
||||
|
||||
lock_file.unlock()?;
|
||||
|
||||
@@ -332,7 +304,7 @@ async fn wait_for_brokered_idle(
|
||||
_ = interval.tick() => {},
|
||||
}
|
||||
|
||||
let idle = matches!(*vpn_state_rx.borrow(), VpnState::Disconnected | VpnState::Failed(_)) && registry.is_empty();
|
||||
let idle = matches!(*vpn_state_rx.borrow(), VpnState::Disconnected) && registry.is_empty();
|
||||
if !idle {
|
||||
idle_since = None;
|
||||
continue;
|
||||
@@ -352,12 +324,12 @@ mod signals {
|
||||
|
||||
use log::{info, warn};
|
||||
|
||||
use crate::vpn_task::LifecycleHandle;
|
||||
use crate::vpn_task::VpnTaskContext;
|
||||
use crate::ws_server::WsServerContext;
|
||||
|
||||
const DISCONNECTED_PID_FILE: &str = "/tmp/gpservice_disconnected.pid";
|
||||
|
||||
pub async fn handle_signals(lifecycle: LifecycleHandle, ws_ctx: Arc<WsServerContext>) {
|
||||
pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
|
||||
use gpapi::service::event::WsEvent;
|
||||
use tokio::signal::unix::{Signal, SignalKind, signal};
|
||||
|
||||
@@ -377,7 +349,7 @@ mod signals {
|
||||
tokio::select! {
|
||||
_ = user_sig1.recv() => {
|
||||
info!("Received SIGUSR1 signal");
|
||||
if lifecycle.disconnect_and_wait().await {
|
||||
if vpn_ctx.disconnect().await {
|
||||
// Write the PID to a dedicated file to indicate that the VPN task is disconnected via SIGUSR1
|
||||
let pid = std::process::id();
|
||||
if let Err(err) = tokio::fs::write(DISCONNECTED_PID_FILE, pid.to_string()).await {
|
||||
@@ -394,6 +366,46 @@ mod signals {
|
||||
}
|
||||
}
|
||||
|
||||
async fn launch_gui(
|
||||
envs: Option<HashMap<String, String>>,
|
||||
registry: Arc<SessionRegistry>,
|
||||
mut minimized: bool,
|
||||
restart_requested: Arc<AtomicBool>,
|
||||
) {
|
||||
loop {
|
||||
let credential = match registry.issue(env!("CARGO_PKG_VERSION")) {
|
||||
Ok(credential) => credential,
|
||||
Err(err) => {
|
||||
warn!("Failed to issue GUI credential: {err}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
let session_id = credential.session_id();
|
||||
let gui_launcher = GuiLauncher::new(env!("CARGO_PKG_VERSION"), credential)
|
||||
.envs(envs.clone())
|
||||
.minimized(minimized);
|
||||
|
||||
match gui_launcher.launch().await {
|
||||
Ok(exit_status) => {
|
||||
registry.revoke(session_id);
|
||||
let should_restart = restart_requested.swap(false, Ordering::SeqCst);
|
||||
if !should_restart {
|
||||
info!("GUI exited with code {:?}", exit_status.code());
|
||||
break;
|
||||
}
|
||||
|
||||
info!("GUI restart requested, restarting");
|
||||
minimized = false;
|
||||
}
|
||||
Err(err) => {
|
||||
registry.revoke(session_id);
|
||||
warn!("Failed to launch GUI: {}", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run() {
|
||||
let mut cli = Cli::parse();
|
||||
|
||||
@@ -402,71 +414,3 @@ 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(())
|
||||
}
|
||||
@@ -7,12 +7,8 @@ use tokio::{
|
||||
|
||||
use crate::session_registry::SessionRegistry;
|
||||
|
||||
pub(crate) async fn serve(
|
||||
mut stream: UnixStream,
|
||||
registry: Arc<SessionRegistry>,
|
||||
desktop_uid: Option<u32>,
|
||||
) -> anyhow::Result<()> {
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), desktop_uid)?;
|
||||
pub(crate) async fn serve(mut stream: UnixStream, registry: Arc<SessionRegistry>) -> anyhow::Result<()> {
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"))?;
|
||||
let session_id = credential.session_id();
|
||||
let result = async {
|
||||
stream.write_all(&credential.encode_frame()?).await?;
|
||||
|
||||
@@ -1,277 +0,0 @@
|
||||
use std::{
|
||||
io,
|
||||
os::fd::OwnedFd,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, FdFlag, OFlag, fcntl},
|
||||
sys::stat::{SFlag, fstat},
|
||||
unistd::{dup, read, write},
|
||||
};
|
||||
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 {
|
||||
input: AsyncFd<OwnedFd>,
|
||||
output: AsyncFd<OwnedFd>,
|
||||
}
|
||||
|
||||
impl DesktopClient {
|
||||
pub(crate) fn from_stdio() -> anyhow::Result<Self> {
|
||||
let channel = Self::new(dup(std::io::stdin())?, dup(std::io::stdout())?)?;
|
||||
// Only the owned CLOEXEC descriptors carry credentials. VPN subprocesses inherit /dev/null.
|
||||
let null = std::fs::OpenOptions::new().read(true).write(true).open("/dev/null")?;
|
||||
nix::unistd::dup2_stdin(&null)?;
|
||||
nix::unistd::dup2_stdout(&null)?;
|
||||
Ok(channel)
|
||||
}
|
||||
|
||||
fn new(input: OwnedFd, output: OwnedFd) -> anyhow::Result<Self> {
|
||||
fn pipe(fd: OwnedFd) -> anyhow::Result<AsyncFd<OwnedFd>> {
|
||||
ensure!(
|
||||
SFlag::from_bits_truncate(fstat(&fd)?.st_mode).contains(SFlag::S_IFIFO),
|
||||
"Desktop credentials require private pipes"
|
||||
);
|
||||
fcntl(&fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC))?;
|
||||
let flags = OFlag::from_bits_truncate(fcntl(&fd, FcntlArg::F_GETFL)?);
|
||||
fcntl(&fd, FcntlArg::F_SETFL(flags | OFlag::O_NONBLOCK))?;
|
||||
Ok(AsyncFd::new(fd)?)
|
||||
}
|
||||
Ok(Self {
|
||||
input: pipe(input)?,
|
||||
output: pipe(output)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn serve(
|
||||
self,
|
||||
registry: Arc<SessionRegistry>,
|
||||
uid: u32,
|
||||
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(None),
|
||||
result = async {
|
||||
self.write_frame(&credential.encode_frame()?).await?;
|
||||
self.gui_exited().await
|
||||
} => result,
|
||||
};
|
||||
registry.revoke(session_id);
|
||||
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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn write_frame(&self, mut bytes: &[u8]) -> anyhow::Result<()> {
|
||||
while !bytes.is_empty() {
|
||||
let mut ready = self.output.writable().await?;
|
||||
match ready.try_io(|fd| write(fd.get_ref(), bytes).map_err(io::Error::from)) {
|
||||
Ok(result) => {
|
||||
let length = result?;
|
||||
ensure!(length != 0, "Desktop credential pipe closed");
|
||||
bytes = &bytes[length..];
|
||||
}
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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(None);
|
||||
}
|
||||
return Ok(Some(byte[0]));
|
||||
}
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn credential_stdio_is_not_inherited_by_subprocesses() {
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--ignored", "--exact", "desktop_client::tests::stdio_child"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(text.contains("PRIVATE_FRAME"));
|
||||
assert!(!text.contains("CHILD_OUTPUT"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "subprocess fixture for credential_stdio_is_not_inherited_by_subprocesses"]
|
||||
async fn stdio_child() {
|
||||
let channel = DesktopClient::from_stdio().unwrap();
|
||||
assert!(
|
||||
std::process::Command::new("/bin/sh")
|
||||
.args(["-c", "printf CHILD_OUTPUT"])
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
channel.write_frame(b"PRIVATE_FRAME").await.unwrap();
|
||||
}
|
||||
use gpapi::service::transport::SessionCredential;
|
||||
use nix::unistd::pipe;
|
||||
use std::{fs::File, io::Read, time::Duration};
|
||||
|
||||
fn pipes() -> (DesktopClient, OwnedFd, File) {
|
||||
let (input, control) = pipe().unwrap();
|
||||
let (credentials, output) = pipe().unwrap();
|
||||
(DesktopClient::new(input, output).unwrap(), control, credentials.into())
|
||||
}
|
||||
|
||||
async fn credential(mut reader: File) -> (File, SessionCredential) {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut header = [0; 2];
|
||||
reader.read_exact(&mut header).unwrap();
|
||||
let mut frame = zeroize::Zeroizing::new(vec![0; usize::from(u16::from_be_bytes(header)) + 2]);
|
||||
frame[..2].copy_from_slice(&header);
|
||||
reader.read_exact(&mut frame[2..]).unwrap();
|
||||
let credential = SessionCredential::decode_frame(&frame).unwrap();
|
||||
(reader, credential)
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[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::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;
|
||||
restart.store(true, Ordering::SeqCst);
|
||||
write(&control, &[0]).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());
|
||||
drop(control);
|
||||
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 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::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;
|
||||
cancel.cancel();
|
||||
tokio::time::timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(registry.last_successful_hip_report(issued.session_id()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn desktop_channel_rejects_invalid_control_messages_and_revokes() {
|
||||
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 (_, issued) = credential(reader).await;
|
||||
write(&control, &[255]).unwrap();
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
assert!(registry.last_successful_hip_report(issued.session_id()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ impl DevBootstrap {
|
||||
}
|
||||
let registry = Arc::clone(&self.registry);
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = credential_lease::serve(stream, registry, Some(self.allowed_uid)).await {
|
||||
if let Err(err) = credential_lease::serve(stream, registry).await {
|
||||
warn!("Debug credential client ended: {err}");
|
||||
}
|
||||
});
|
||||
@@ -186,9 +186,9 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn anchor_eof_revokes_issued_credential() {
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let (service, mut client) = UnixStream::pair().unwrap();
|
||||
let task = tokio::spawn(credential_lease::serve(service, Arc::clone(®istry), Some(1234)));
|
||||
let task = tokio::spawn(credential_lease::serve(service, Arc::clone(®istry)));
|
||||
|
||||
let mut header = [0_u8; 2];
|
||||
client.read_exact(&mut header).await.unwrap();
|
||||
|
||||
@@ -1,380 +0,0 @@
|
||||
//! Root-owned Unix installation identity. Failure affects GUI issuance only.
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::device_anchor::{AnchorSource, DeviceAnchor};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Record {
|
||||
version: u32,
|
||||
anchor: DeviceAnchor,
|
||||
}
|
||||
|
||||
pub fn resolve() -> anyhow::Result<DeviceAnchor> {
|
||||
resolve_in(Path::new("/var/lib/gp"), 0, collect_unix).context("cannot resolve persistent GUI device anchor")
|
||||
}
|
||||
|
||||
fn collect_unix() -> anyhow::Result<DeviceAnchor> {
|
||||
collect_from(mac_address::get_mac_address()?, || {
|
||||
let mut random = [0_u8; 32];
|
||||
getrandom::fill(&mut random).map_err(|_| anyhow::anyhow!("cannot initialize device anchor"))?;
|
||||
Ok(random)
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_from(
|
||||
mac: Option<mac_address::MacAddress>,
|
||||
random: impl FnOnce() -> anyhow::Result<[u8; 32]>,
|
||||
) -> anyhow::Result<DeviceAnchor> {
|
||||
if let Some(mac) = mac {
|
||||
let bytes = mac.bytes();
|
||||
if bytes != [0; 6] && bytes[0] & 1 == 0 {
|
||||
return Ok(DeviceAnchor::derive(AnchorSource::UnixMac, bytes));
|
||||
}
|
||||
}
|
||||
Ok(DeviceAnchor::derive(AnchorSource::UnixRandom, random()?))
|
||||
}
|
||||
|
||||
fn validate_metadata(metadata: &fs::Metadata, owner: u32, directory: bool) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
if directory {
|
||||
metadata.is_dir()
|
||||
} else {
|
||||
metadata.is_file()
|
||||
},
|
||||
"unexpected device anchor state type"
|
||||
);
|
||||
ensure!(metadata.uid() == owner, "unexpected device anchor state owner");
|
||||
ensure!(
|
||||
metadata.permissions().mode() & 0o777 == if directory { 0o700 } else { 0o600 },
|
||||
"unsafe device anchor state permissions"
|
||||
);
|
||||
if !directory {
|
||||
ensure!(metadata.nlink() == 1, "device anchor state must not have hard links");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_record(path: &Path, owner: u32) -> anyhow::Result<Option<DeviceAnchor>> {
|
||||
let mut file = match OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(nix::libc::O_NOFOLLOW | nix::libc::O_NONBLOCK)
|
||||
.open(path)
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
validate_metadata(&file.metadata()?, owner, false)?;
|
||||
ensure!(file.metadata()?.len() <= 4096, "oversized device anchor record");
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes)?;
|
||||
let record: Record = serde_json::from_slice(&bytes).context("malformed device anchor record")?;
|
||||
ensure!(
|
||||
record.version == 1 && record.anchor.validate(),
|
||||
"unsupported or invalid device anchor record"
|
||||
);
|
||||
ensure!(
|
||||
matches!(record.anchor.source, AnchorSource::UnixMac | AnchorSource::UnixRandom),
|
||||
"invalid Unix device anchor source"
|
||||
);
|
||||
Ok(Some(record.anchor))
|
||||
}
|
||||
|
||||
fn resolve_in(
|
||||
directory: &Path,
|
||||
owner: u32,
|
||||
collect: impl FnOnce() -> anyhow::Result<DeviceAnchor>,
|
||||
) -> anyhow::Result<DeviceAnchor> {
|
||||
match fs::DirBuilder::new().mode(0o700).create(directory) {
|
||||
Ok(()) => {
|
||||
if let Some(parent) = directory.parent() {
|
||||
File::open(parent)?.sync_all()?;
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
validate_metadata(&fs::symlink_metadata(directory)?, owner, true)?;
|
||||
let path = directory.join("hardware-id");
|
||||
let lock = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.mode(0o600)
|
||||
.custom_flags(nix::libc::O_NOFOLLOW | nix::libc::O_NONBLOCK)
|
||||
.open(directory.join("hardware-id.lock"))?;
|
||||
validate_metadata(&lock.metadata()?, owner, false)?;
|
||||
lock.lock()?;
|
||||
if let Some(anchor) = read_record(&path, owner)? {
|
||||
return Ok(anchor);
|
||||
}
|
||||
let anchor = collect()?;
|
||||
ensure!(
|
||||
anchor.validate() && matches!(anchor.source, AnchorSource::UnixMac | AnchorSource::UnixRandom),
|
||||
"invalid collected Unix device anchor"
|
||||
);
|
||||
let mut temporary = tempfile::NamedTempFile::new_in(directory)?;
|
||||
temporary.as_file().set_permissions(fs::Permissions::from_mode(0o600))?;
|
||||
temporary.write_all(&serde_json::to_vec(&Record {
|
||||
version: 1,
|
||||
anchor: anchor.clone(),
|
||||
})?)?;
|
||||
temporary.as_file().sync_all()?;
|
||||
temporary.persist_noclobber(&path)?;
|
||||
File::open(directory)?.sync_all()?;
|
||||
Ok(anchor)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn anchor() -> anyhow::Result<DeviceAnchor> {
|
||||
Ok(DeviceAnchor {
|
||||
hardware_id: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_owned(),
|
||||
source: AnchorSource::UnixMac,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistence_reuses_the_existing_record_without_rediscovery() {
|
||||
let _ = resolve as fn() -> anyhow::Result<DeviceAnchor>;
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let path = temporary.path().join("state");
|
||||
let owner = nix::unistd::Uid::current().as_raw();
|
||||
assert_eq!(resolve_in(&path, owner, anchor).unwrap(), anchor().unwrap());
|
||||
assert_eq!(
|
||||
resolve_in(&path, owner, || anyhow::bail!("must not rediscover")).unwrap(),
|
||||
anchor().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_preserves_an_eligible_mac_and_randomizes_ineligible_addresses() {
|
||||
use mac_address::MacAddress;
|
||||
|
||||
let eligible = collect_from(Some(MacAddress::new([0, 17, 34, 51, 68, 85])), || {
|
||||
anyhow::bail!("must not randomize")
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
eligible,
|
||||
DeviceAnchor::derive(AnchorSource::UnixMac, [0, 17, 34, 51, 68, 85])
|
||||
);
|
||||
|
||||
for rejected in [[0; 6], [1, 2, 3, 4, 5, 6], [0xff; 6]] {
|
||||
assert_eq!(
|
||||
collect_from(Some(MacAddress::new(rejected)), || Ok([9; 32])).unwrap(),
|
||||
DeviceAnchor::derive(AnchorSource::UnixRandom, [9; 32])
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
collect_from(None, || Ok([8; 32])).unwrap(),
|
||||
DeviceAnchor::derive(AnchorSource::UnixRandom, [8; 32])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_record_recreates_the_same_mac_anchor() {
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let path = temporary.path().join("state");
|
||||
let owner = nix::unistd::Uid::current().as_raw();
|
||||
let first = resolve_in(&path, owner, anchor).unwrap();
|
||||
fs::remove_file(path.join("hardware-id")).unwrap();
|
||||
assert_eq!(resolve_in(&path, owner, anchor).unwrap(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parallel_first_start_converges_on_one_record() {
|
||||
use std::sync::{Arc, Barrier};
|
||||
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let path = Arc::new(temporary.path().join("state"));
|
||||
fs::create_dir(&*path).unwrap();
|
||||
fs::set_permissions(&*path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let owner = nix::unistd::Uid::current().as_raw();
|
||||
let barrier = Arc::new(Barrier::new(2));
|
||||
let handles: Vec<_> = [AnchorSource::UnixMac, AnchorSource::UnixRandom]
|
||||
.into_iter()
|
||||
.map(|source| {
|
||||
let path = Arc::clone(&path);
|
||||
let barrier = Arc::clone(&barrier);
|
||||
std::thread::spawn(move || {
|
||||
barrier.wait();
|
||||
resolve_in(&path, owner, || Ok(DeviceAnchor::derive(source, [source.into()])))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let results: Vec<_> = handles
|
||||
.into_iter()
|
||||
.map(|handle| handle.join().unwrap().unwrap())
|
||||
.collect();
|
||||
assert_eq!(results[0], results[1]);
|
||||
assert_eq!(
|
||||
read_record(&path.join("hardware-id"), owner).unwrap(),
|
||||
Some(results[0].clone())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_linked_and_unsafe_records() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let owner = nix::unistd::Uid::current().as_raw();
|
||||
for case in ["malformed", "symlink", "hard-link", "permissions"] {
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let record = directory.join("hardware-id");
|
||||
match case {
|
||||
"malformed" => fs::write(&record, b"not-json").unwrap(),
|
||||
"symlink" => {
|
||||
let target = temporary.path().join("target");
|
||||
fs::write(
|
||||
&target,
|
||||
serde_json::to_vec(&Record {
|
||||
version: 1,
|
||||
anchor: anchor().unwrap(),
|
||||
})
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
symlink(target, &record).unwrap();
|
||||
}
|
||||
"hard-link" => {
|
||||
fs::write(
|
||||
&record,
|
||||
serde_json::to_vec(&Record {
|
||||
version: 1,
|
||||
anchor: anchor().unwrap(),
|
||||
})
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::hard_link(&record, temporary.path().join("second-link")).unwrap();
|
||||
}
|
||||
"permissions" => {
|
||||
fs::write(
|
||||
&record,
|
||||
serde_json::to_vec(&Record {
|
||||
version: 1,
|
||||
anchor: anchor().unwrap(),
|
||||
})
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&record, fs::Permissions::from_mode(0o644)).unwrap();
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
if case != "symlink" && case != "permissions" {
|
||||
fs::set_permissions(&record, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
assert!(resolve_in(&directory, owner, anchor).is_err(), "accepted {case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovers_with_an_interrupted_temporary_file_present() {
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
fs::write(directory.join(".hardware-id.interrupted"), b"partial").unwrap();
|
||||
assert_eq!(
|
||||
resolve_in(&directory, nix::unistd::Uid::current().as_raw(), anchor).unwrap(),
|
||||
anchor().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unsafe_directory_and_lock_metadata_and_read_only_storage() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let owner = nix::unistd::Uid::current().as_raw();
|
||||
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert!(resolve_in(&directory, owner, anchor).is_err());
|
||||
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
assert!(resolve_in(&directory, owner.wrapping_add(1), anchor).is_err());
|
||||
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::write(&directory, b"not-a-directory").unwrap();
|
||||
assert!(resolve_in(&directory, owner, anchor).is_err());
|
||||
|
||||
for case in ["symlink", "hard-link", "permissions"] {
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let lock = directory.join("hardware-id.lock");
|
||||
match case {
|
||||
"symlink" => {
|
||||
let target = temporary.path().join("target");
|
||||
fs::write(&target, b"").unwrap();
|
||||
symlink(target, &lock).unwrap();
|
||||
}
|
||||
"hard-link" => {
|
||||
fs::write(&lock, b"").unwrap();
|
||||
fs::set_permissions(&lock, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
fs::hard_link(&lock, temporary.path().join("second-link")).unwrap();
|
||||
}
|
||||
"permissions" => {
|
||||
fs::write(&lock, b"").unwrap();
|
||||
fs::set_permissions(&lock, fs::Permissions::from_mode(0o644)).unwrap();
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
assert!(resolve_in(&directory, owner, anchor).is_err(), "accepted {case} lock");
|
||||
}
|
||||
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o500)).unwrap();
|
||||
assert!(resolve_in(&directory, owner, anchor).is_err());
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_serializes_source_as_a_number_and_rejects_unknown_codes() {
|
||||
let record = Record {
|
||||
version: 1,
|
||||
anchor: anchor().unwrap(),
|
||||
};
|
||||
let json = serde_json::to_value(&record).unwrap();
|
||||
assert_eq!(json["anchor"]["source"], 1);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&record).unwrap(),
|
||||
r#"{"version":1,"anchor":{"hardware_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","source":1}}"#
|
||||
);
|
||||
|
||||
for source in [0, 4] {
|
||||
let json = serde_json::json!({
|
||||
"version": 1,
|
||||
"anchor": {
|
||||
"hardware_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||
"source": source
|
||||
}
|
||||
});
|
||||
assert!(serde_json::from_value::<Record>(json).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,463 +0,0 @@
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use gpapi::{hip::HipApprovalStatus, utils::checksum::sha256_hex};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tempfile::Builder;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const APPROVAL_DIRECTORY: &str = "/var/lib/gpclient/hip-approvals";
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub const APPROVAL_DIRECTORY: &str = "/var/db/gpclient/hip-approvals";
|
||||
pub const MAX_SCRIPT_SIZE: usize = common::constants::MAX_HIP_SCRIPT_SIZE;
|
||||
const MAX_METADATA_SIZE: u64 = 8 * 1024;
|
||||
const METADATA_VERSION: u8 = 1;
|
||||
const SCRIPT_NAME: &str = "script";
|
||||
const METADATA_NAME: &str = "metadata.json";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InstallRequest {
|
||||
pub original_path: String,
|
||||
pub contents_base64: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ApprovalInfo {
|
||||
pub approval_id: String,
|
||||
pub owner_uid: u32,
|
||||
pub sha256: String,
|
||||
pub original_path: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ApprovedScript {
|
||||
pub info: ApprovalInfo,
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct StoredMetadata {
|
||||
version: u8,
|
||||
info: ApprovalInfo,
|
||||
}
|
||||
|
||||
impl InstallRequest {
|
||||
fn contents(&self) -> anyhow::Result<Vec<u8>> {
|
||||
ensure!(self.original_path.len() <= 4096, "HIP script path is too long");
|
||||
ensure!(
|
||||
Path::new(&self.original_path).is_absolute(),
|
||||
"HIP script path must be absolute"
|
||||
);
|
||||
ensure!(
|
||||
!self.original_path.contains('\0'),
|
||||
"HIP script path contains a NUL byte"
|
||||
);
|
||||
ensure!(
|
||||
self.contents_base64.len() <= (MAX_SCRIPT_SIZE + 2).div_ceil(3) * 4,
|
||||
"HIP script exceeds 1 MiB"
|
||||
);
|
||||
let contents = STANDARD
|
||||
.decode(&self.contents_base64)
|
||||
.context("Invalid HIP script content encoding")?;
|
||||
ensure!(
|
||||
!contents.is_empty() && contents.len() <= MAX_SCRIPT_SIZE,
|
||||
"HIP script must be 1 MiB or smaller"
|
||||
);
|
||||
Ok(contents)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn install(request: InstallRequest, approving_uid: u32) -> anyhow::Result<ApprovalInfo> {
|
||||
ensure!(approving_uid != 0, "Root cannot approve a desktop HIP script");
|
||||
let contents = request.contents()?;
|
||||
let base = Path::new(APPROVAL_DIRECTORY);
|
||||
fs::create_dir_all(base).context("Cannot create HIP approval directory")?;
|
||||
validate_approval_ancestors(base)?;
|
||||
fs::set_permissions(base, fs::Permissions::from_mode(0o700))?;
|
||||
install_at(base, &contents, request.original_path, approving_uid, 0)
|
||||
}
|
||||
|
||||
pub fn resolve(approval_id: &str, desktop_uid: u32) -> anyhow::Result<ApprovedScript> {
|
||||
let budget = gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60));
|
||||
resolve_with_control(approval_id, desktop_uid, &budget)
|
||||
}
|
||||
|
||||
pub fn resolve_with_control(
|
||||
approval_id: &str,
|
||||
desktop_uid: u32,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
) -> anyhow::Result<ApprovedScript> {
|
||||
control.check()?;
|
||||
ensure!(desktop_uid != 0, "Root is not a desktop HIP approval owner");
|
||||
let base = Path::new(APPROVAL_DIRECTORY);
|
||||
validate_approval_ancestors(base)?;
|
||||
resolve_at_with_control(base, approval_id, desktop_uid, 0, control)
|
||||
}
|
||||
|
||||
pub fn revoke(approval_id: &str, approving_uid: u32) -> anyhow::Result<()> {
|
||||
ensure!(approving_uid != 0, "Root cannot revoke another user's HIP approval");
|
||||
let base = Path::new(APPROVAL_DIRECTORY);
|
||||
validate_approval_ancestors(base)?;
|
||||
revoke_at(base, approval_id, approving_uid, 0)
|
||||
}
|
||||
|
||||
pub fn status(approval_id: &str, desktop_uid: u32) -> anyhow::Result<HipApprovalStatus> {
|
||||
status_at(Path::new(APPROVAL_DIRECTORY), approval_id, desktop_uid, 0, true)
|
||||
}
|
||||
|
||||
fn status_at(
|
||||
base: &Path,
|
||||
approval_id: &str,
|
||||
desktop_uid: u32,
|
||||
file_owner: u32,
|
||||
validate_root_ancestors: bool,
|
||||
) -> anyhow::Result<HipApprovalStatus> {
|
||||
ensure!(desktop_uid != 0, "HIP approval status requires a desktop user");
|
||||
validate_id(approval_id)?;
|
||||
for path in [
|
||||
base.to_path_buf(),
|
||||
base.join(approval_id),
|
||||
base.join(approval_id).join(METADATA_NAME),
|
||||
] {
|
||||
match fs::symlink_metadata(&path) {
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(HipApprovalStatus::Revoked),
|
||||
Err(_) => return Ok(HipApprovalStatus::Corrupt),
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
if validate_private_dir(base, file_owner).is_err()
|
||||
|| (validate_root_ancestors && validate_approval_ancestors(base).is_err())
|
||||
{
|
||||
return Ok(HipApprovalStatus::Corrupt);
|
||||
}
|
||||
let info = match read_metadata_unbound_at(base, approval_id, file_owner) {
|
||||
Ok(info) => info,
|
||||
Err(_) => return Ok(HipApprovalStatus::Corrupt),
|
||||
};
|
||||
if info.owner_uid != desktop_uid {
|
||||
return Ok(HipApprovalStatus::OtherUser);
|
||||
}
|
||||
Ok(if resolve_at(base, approval_id, desktop_uid, file_owner).is_ok() {
|
||||
HipApprovalStatus::Valid
|
||||
} else {
|
||||
HipApprovalStatus::Corrupt
|
||||
})
|
||||
}
|
||||
|
||||
fn install_at(
|
||||
base: &Path,
|
||||
contents: &[u8],
|
||||
original_path: String,
|
||||
approving_uid: u32,
|
||||
file_owner: u32,
|
||||
) -> anyhow::Result<ApprovalInfo> {
|
||||
validate_private_dir(base, file_owner)?;
|
||||
ensure!(
|
||||
!contents.is_empty() && contents.len() <= MAX_SCRIPT_SIZE,
|
||||
"HIP script must be 1 MiB or smaller"
|
||||
);
|
||||
let approval_id = Uuid::new_v4().to_string();
|
||||
let info = ApprovalInfo {
|
||||
approval_id: approval_id.clone(),
|
||||
owner_uid: approving_uid,
|
||||
sha256: sha256_hex(contents),
|
||||
original_path,
|
||||
};
|
||||
let staged = Builder::new().prefix(".install-").tempdir_in(base)?;
|
||||
fs::set_permissions(staged.path(), fs::Permissions::from_mode(0o700))?;
|
||||
validate_private_dir(staged.path(), file_owner)?;
|
||||
|
||||
let script = staged.path().join(SCRIPT_NAME);
|
||||
write_new(&script, contents, 0o500)?;
|
||||
let metadata = staged.path().join(METADATA_NAME);
|
||||
let stored = StoredMetadata {
|
||||
version: METADATA_VERSION,
|
||||
info: info.clone(),
|
||||
};
|
||||
let encoded = serde_json::to_vec(&stored)?;
|
||||
ensure!(
|
||||
encoded.len() as u64 <= MAX_METADATA_SIZE,
|
||||
"HIP approval metadata is too large"
|
||||
);
|
||||
write_new(&metadata, &encoded, 0o600)?;
|
||||
File::open(staged.path())?.sync_all()?;
|
||||
|
||||
let target = base.join(&approval_id);
|
||||
ensure!(!target.exists(), "HIP approval ID collision");
|
||||
fs::rename(staged.path(), &target).context("Cannot publish HIP approval")?;
|
||||
File::open(base)?.sync_all()?;
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
fn resolve_at(base: &Path, approval_id: &str, desktop_uid: u32, file_owner: u32) -> anyhow::Result<ApprovedScript> {
|
||||
let budget = gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60));
|
||||
resolve_at_with_control(base, approval_id, desktop_uid, file_owner, &budget)
|
||||
}
|
||||
|
||||
fn resolve_at_with_control(
|
||||
base: &Path,
|
||||
approval_id: &str,
|
||||
desktop_uid: u32,
|
||||
file_owner: u32,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
) -> anyhow::Result<ApprovedScript> {
|
||||
control.check()?;
|
||||
let info = read_metadata_at(base, approval_id, desktop_uid, file_owner)?;
|
||||
control.check()?;
|
||||
let script = base.join(approval_id).join(SCRIPT_NAME);
|
||||
validate_file(&script, file_owner, 0o500, MAX_SCRIPT_SIZE as u64)?;
|
||||
let mut file = File::open(&script)?;
|
||||
let mut contents = Vec::new();
|
||||
let mut chunk = [0_u8; 8192];
|
||||
loop {
|
||||
control.check()?;
|
||||
let read = file.read(&mut chunk)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
contents.len() + read <= MAX_SCRIPT_SIZE,
|
||||
"Approved HIP script is too large"
|
||||
);
|
||||
contents.extend_from_slice(&chunk[..read]);
|
||||
}
|
||||
ensure!(!contents.is_empty(), "Approved HIP script is empty");
|
||||
ensure!(
|
||||
sha256_hex(&contents) == info.sha256,
|
||||
"Approved HIP script digest mismatch"
|
||||
);
|
||||
control.check()?;
|
||||
Ok(ApprovedScript { info, path: script })
|
||||
}
|
||||
|
||||
fn read_metadata_at(base: &Path, approval_id: &str, desktop_uid: u32, file_owner: u32) -> anyhow::Result<ApprovalInfo> {
|
||||
let info = read_metadata_unbound_at(base, approval_id, file_owner)?;
|
||||
ensure!(info.owner_uid == desktop_uid, "HIP approval belongs to another user");
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
fn read_metadata_unbound_at(base: &Path, approval_id: &str, file_owner: u32) -> anyhow::Result<ApprovalInfo> {
|
||||
validate_id(approval_id)?;
|
||||
validate_private_dir(base, file_owner)?;
|
||||
let directory = base.join(approval_id);
|
||||
validate_private_dir(&directory, file_owner)?;
|
||||
let metadata_path = directory.join(METADATA_NAME);
|
||||
validate_file(&metadata_path, file_owner, 0o600, MAX_METADATA_SIZE)?;
|
||||
let stored: StoredMetadata = serde_json::from_slice(&fs::read(metadata_path)?)?;
|
||||
ensure!(stored.version == METADATA_VERSION, "Unsupported HIP approval version");
|
||||
ensure!(stored.info.approval_id == approval_id, "HIP approval ID mismatch");
|
||||
ensure!(
|
||||
stored.info.sha256.len() == 64 && stored.info.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()),
|
||||
"Invalid HIP approval digest"
|
||||
);
|
||||
|
||||
Ok(stored.info)
|
||||
}
|
||||
|
||||
fn revoke_at(base: &Path, approval_id: &str, approving_uid: u32, file_owner: u32) -> anyhow::Result<()> {
|
||||
validate_id(approval_id)?;
|
||||
let directory = base.join(approval_id);
|
||||
// The GUI may retry after removal succeeds but saving its settings fails.
|
||||
if let Err(err) = fs::symlink_metadata(&directory) {
|
||||
if err.kind() == std::io::ErrorKind::NotFound {
|
||||
return Ok(());
|
||||
}
|
||||
return Err(err).context("Cannot inspect HIP approval directory");
|
||||
}
|
||||
read_metadata_at(base, approval_id, approving_uid, file_owner)?;
|
||||
// Renaming first makes revocation atomic for the runner. Cleanup is separate:
|
||||
// a failed cleanup cannot make this approval executable again.
|
||||
let revoked = base.join(format!(".revoked-{approval_id}"));
|
||||
fs::rename(&directory, &revoked).context("Cannot revoke HIP approval")?;
|
||||
File::open(base)?.sync_all()?;
|
||||
if let Err(err) = fs::remove_dir_all(&revoked) {
|
||||
log::warn!("HIP approval was revoked but its snapshot could not be removed: {err}");
|
||||
} else {
|
||||
File::open(base)?.sync_all()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_new(path: &Path, bytes: &[u8], mode: u32) -> anyhow::Result<()> {
|
||||
let mut file = OpenOptions::new().write(true).create_new(true).mode(mode).open(path)?;
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_id(value: &str) -> anyhow::Result<()> {
|
||||
let parsed = Uuid::parse_str(value).context("Invalid HIP approval ID")?;
|
||||
ensure!(parsed.to_string() == value, "HIP approval ID must use canonical form");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_private_dir(path: &Path, owner_uid: u32) -> anyhow::Result<()> {
|
||||
let metadata = fs::symlink_metadata(path).with_context(|| format!("Cannot inspect {}", path.display()))?;
|
||||
ensure!(
|
||||
metadata.is_dir() && !metadata.file_type().is_symlink(),
|
||||
"HIP approval directory is not a directory"
|
||||
);
|
||||
ensure!(
|
||||
metadata.uid() == owner_uid && metadata.permissions().mode() & 0o077 == 0,
|
||||
"HIP approval directory {} is not private (owner {}, mode {:o})",
|
||||
path.display(),
|
||||
metadata.uid(),
|
||||
metadata.permissions().mode() & 0o777
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_file(path: &Path, owner_uid: u32, mode: u32, max_size: u64) -> anyhow::Result<()> {
|
||||
let metadata = fs::symlink_metadata(path).with_context(|| format!("Cannot inspect {}", path.display()))?;
|
||||
ensure!(
|
||||
metadata.is_file() && !metadata.file_type().is_symlink(),
|
||||
"HIP approval file is not regular"
|
||||
);
|
||||
ensure!(
|
||||
metadata.uid() == owner_uid && metadata.permissions().mode() & 0o777 == mode,
|
||||
"HIP approval file has unsafe ownership or mode"
|
||||
);
|
||||
ensure!(metadata.len() <= max_size, "HIP approval file is too large");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check every component because a trusted file below a writable parent can
|
||||
/// be replaced before a later HIP refresh.
|
||||
fn validate_approval_ancestors(path: &Path) -> anyhow::Result<()> {
|
||||
ensure!(path.is_absolute(), "HIP approval path must be absolute");
|
||||
for component in path.ancestors().take_while(|part| part.as_os_str() != "/") {
|
||||
let metadata =
|
||||
fs::symlink_metadata(component).with_context(|| format!("Cannot inspect {}", component.display()))?;
|
||||
ensure!(
|
||||
!metadata.file_type().is_symlink(),
|
||||
"HIP approval path contains a symlink"
|
||||
);
|
||||
ensure!(metadata.uid() == 0, "HIP approval path is not root-owned");
|
||||
ensure!(
|
||||
metadata.permissions().mode() & 0o022 == 0,
|
||||
"HIP approval path is writable by another user"
|
||||
);
|
||||
ensure!(metadata.is_dir(), "HIP approval parent is not a directory");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fixture() -> (tempfile::TempDir, u32) {
|
||||
let base = tempfile::tempdir().unwrap();
|
||||
fs::set_permissions(base.path(), fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let owner = fs::symlink_metadata(base.path()).unwrap().uid();
|
||||
(base, owner)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_request_rejects_oversized_or_relative_script() {
|
||||
let request = InstallRequest {
|
||||
original_path: "hip.sh".into(),
|
||||
contents_base64: STANDARD.encode(b"#!/bin/sh\n"),
|
||||
};
|
||||
assert!(request.contents().is_err());
|
||||
let oversized = InstallRequest {
|
||||
original_path: "/home/user/hip.sh".into(),
|
||||
contents_base64: STANDARD.encode(vec![b'x'; MAX_SCRIPT_SIZE + 1]),
|
||||
};
|
||||
assert!(oversized.contents().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approval_binds_owner_and_exact_script_digest() {
|
||||
let (base, owner) = fixture();
|
||||
let info = install_at(
|
||||
base.path(),
|
||||
b"#!/bin/sh\necho ok\n",
|
||||
"/home/user/hip.sh".into(),
|
||||
1000,
|
||||
owner,
|
||||
)
|
||||
.unwrap();
|
||||
let approved = resolve_at(base.path(), &info.approval_id, 1000, owner).unwrap();
|
||||
assert_eq!(approved.info.sha256, info.sha256);
|
||||
assert!(resolve_at(base.path(), &info.approval_id, 1001, owner).is_err());
|
||||
fs::set_permissions(&approved.path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
fs::write(&approved.path, b"#!/bin/sh\necho changed\n").unwrap();
|
||||
fs::set_permissions(&approved.path, fs::Permissions::from_mode(0o500)).unwrap();
|
||||
assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revoked_approval_is_unavailable() {
|
||||
let (base, owner) = fixture();
|
||||
let info = install_at(base.path(), b"#!/bin/sh\n", "/home/user/hip.sh".into(), 1000, owner).unwrap();
|
||||
assert!(revoke_at(base.path(), &info.approval_id, 1001, owner).is_err());
|
||||
revoke_at(base.path(), &info.approval_id, 1000, owner).unwrap();
|
||||
revoke_at(base.path(), &info.approval_id, 1000, owner).unwrap();
|
||||
assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_distinguishes_owner_corruption_and_revocation() {
|
||||
let (base, owner) = fixture();
|
||||
let info = install_at(
|
||||
base.path(),
|
||||
b"#!/bin/sh\necho ok\n",
|
||||
"/home/user/hip.sh".into(),
|
||||
1000,
|
||||
owner,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
status_at(base.path(), &info.approval_id, 1000, owner, false).unwrap(),
|
||||
HipApprovalStatus::Valid
|
||||
);
|
||||
assert_eq!(
|
||||
status_at(base.path(), &info.approval_id, 1001, owner, false).unwrap(),
|
||||
HipApprovalStatus::OtherUser
|
||||
);
|
||||
let script = base.path().join(&info.approval_id).join(SCRIPT_NAME);
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
assert_eq!(
|
||||
status_at(base.path(), &info.approval_id, 1000, owner, false).unwrap(),
|
||||
HipApprovalStatus::Corrupt
|
||||
);
|
||||
fs::remove_file(base.path().join(&info.approval_id).join(METADATA_NAME)).unwrap();
|
||||
assert_eq!(
|
||||
status_at(base.path(), &info.approval_id, 1000, owner, false).unwrap(),
|
||||
HipApprovalStatus::Revoked
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revoke_succeeds_if_script_was_corrupted() {
|
||||
let (base, owner) = fixture();
|
||||
let info = install_at(base.path(), b"#!/bin/sh\n", "/home/user/hip.sh".into(), 1000, owner).unwrap();
|
||||
let script = base.path().join(&info.approval_id).join(SCRIPT_NAME);
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
fs::write(&script, b"changed").unwrap();
|
||||
assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err());
|
||||
revoke_at(base.path(), &info.approval_id, 1000, owner).unwrap();
|
||||
assert!(!base.path().join(&info.approval_id).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_symlinked_script() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let (base, owner) = fixture();
|
||||
let info = install_at(base.path(), b"#!/bin/sh\n", "/home/user/hip.sh".into(), 1000, owner).unwrap();
|
||||
let script = base.path().join(&info.approval_id).join(SCRIPT_NAME);
|
||||
fs::remove_file(&script).unwrap();
|
||||
symlink("/bin/sh", &script).unwrap();
|
||||
assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,309 +0,0 @@
|
||||
use std::{collections::HashMap, io, sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use gpapi::{
|
||||
hip::HipSource,
|
||||
os_profile::HostIdentity,
|
||||
service::{
|
||||
request::PreviewHipReportRequest,
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
};
|
||||
use openconnect::HipRequest;
|
||||
use tokio::{
|
||||
sync::{Mutex, Semaphore},
|
||||
task::JoinHandle,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{session_registry::SessionRegistry, ws_connection::ConnectionControl};
|
||||
|
||||
const PREVIEW_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
const MAX_ACTIVE_PREVIEWS: usize = 4;
|
||||
|
||||
struct PreviewTask {
|
||||
connection_id: Uuid,
|
||||
cancellation: CancellationToken,
|
||||
worker: JoinHandle<()>,
|
||||
}
|
||||
|
||||
pub(crate) struct PreviewJob {
|
||||
pub session_id: Uuid,
|
||||
pub request_id: Uuid,
|
||||
pub request: PreviewHipReportRequest,
|
||||
pub edited_report: Option<Arc<str>>,
|
||||
pub desktop_uid: Option<u32>,
|
||||
pub identity: HostIdentity,
|
||||
pub registry: Arc<SessionRegistry>,
|
||||
pub connection: ConnectionControl,
|
||||
}
|
||||
|
||||
pub(crate) struct HipPreviews {
|
||||
tasks: Mutex<HashMap<Uuid, PreviewTask>>,
|
||||
slots: Arc<Semaphore>,
|
||||
shutdown: CancellationToken,
|
||||
}
|
||||
|
||||
impl HipPreviews {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
tasks: Mutex::new(HashMap::new()),
|
||||
slots: Arc::new(Semaphore::new(MAX_ACTIVE_PREVIEWS)),
|
||||
shutdown: CancellationToken::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn start(&self, job: PreviewJob) -> bool {
|
||||
let PreviewJob {
|
||||
session_id,
|
||||
request_id,
|
||||
request,
|
||||
edited_report,
|
||||
desktop_uid,
|
||||
identity,
|
||||
registry,
|
||||
connection,
|
||||
} = job;
|
||||
let mut tasks = self.tasks.lock().await;
|
||||
if self.shutdown.is_cancelled() || tasks.get(&session_id).is_some_and(|task| !task.worker.is_finished()) {
|
||||
return false;
|
||||
}
|
||||
if let Some(completed) = tasks.remove(&session_id) {
|
||||
let _ = completed.worker.await;
|
||||
}
|
||||
let Ok(slot) = Arc::clone(&self.slots).try_acquire_owned() else {
|
||||
return false;
|
||||
};
|
||||
let cancellation = self.shutdown.child_token();
|
||||
let worker_cancellation = cancellation.clone();
|
||||
let connection_id = connection.connection_id();
|
||||
let worker = tokio::spawn(async move {
|
||||
let _slot = slot;
|
||||
let generated = tokio::task::spawn_blocking(move || {
|
||||
generate(request, edited_report, desktop_uid, identity, worker_cancellation)
|
||||
})
|
||||
.await;
|
||||
let result = match generated {
|
||||
Ok(Ok(xml)) => preview_result(®istry, session_id, xml),
|
||||
Ok(Err(error)) => {
|
||||
log::warn!("HIP preview failed: {error:#}");
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!("HIP preview worker failed: {error}");
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
|
||||
}
|
||||
};
|
||||
// A bounded connection queue must not prevent preview teardown.
|
||||
let _ = connection.send(crate::ws_connection::ConnectionCommand::Reply { id: request_id, result });
|
||||
});
|
||||
tasks.insert(
|
||||
session_id,
|
||||
PreviewTask {
|
||||
connection_id,
|
||||
cancellation,
|
||||
worker,
|
||||
},
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) async fn cancel_connection(&self, session_id: Uuid, connection_id: Uuid) {
|
||||
let mut tasks = self.tasks.lock().await;
|
||||
if !tasks
|
||||
.get(&session_id)
|
||||
.is_some_and(|task| task.connection_id == connection_id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(task) = tasks.remove(&session_id) {
|
||||
task.cancellation.cancel();
|
||||
let _ = task.worker.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
self.shutdown.cancel();
|
||||
let tasks = std::mem::take(&mut *self.tasks.lock().await);
|
||||
for task in tasks.into_values() {
|
||||
let _ = task.worker.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_result(registry: &SessionRegistry, session_id: Uuid, xml: String) -> ServiceResult {
|
||||
let result = registry.store_hip_preview(session_id, xml).and_then(|preview_id| {
|
||||
registry
|
||||
.hip_preview_chunk(session_id, preview_id, 0)
|
||||
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
})
|
||||
});
|
||||
result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"))
|
||||
}
|
||||
|
||||
fn generate(
|
||||
request: PreviewHipReportRequest,
|
||||
edited_report: Option<Arc<str>>,
|
||||
desktop_uid: Option<u32>,
|
||||
identity: HostIdentity,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<String> {
|
||||
ensure!(request.client_version.len() <= 64, "Invalid HIP client version");
|
||||
ensure!(
|
||||
request.host_id.as_ref().is_none_or(|id| id.len() <= 256),
|
||||
"Invalid HIP host ID"
|
||||
);
|
||||
let budget = gpapi::process::collection::CollectionBudget::new(PREVIEW_TIMEOUT);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(io::Error::new(io::ErrorKind::Interrupted, "HIP preview cancelled"));
|
||||
}
|
||||
gpapi::process::collection::CollectionControl::check(&budget)
|
||||
};
|
||||
check()?;
|
||||
let profile = crate::hip_source::profile(
|
||||
&identity,
|
||||
request.client_os,
|
||||
Some(request.client_version.clone()),
|
||||
None,
|
||||
request.host_id.clone(),
|
||||
None,
|
||||
&check,
|
||||
)?;
|
||||
let input = HipRequest {
|
||||
cookie: "user=preview&domain=preview&computer=preview".into(),
|
||||
client_ip: Some("192.0.2.1".into()),
|
||||
client_ipv6: None,
|
||||
md5: "00000000000000000000000000000000".into(),
|
||||
client_version: request.client_version,
|
||||
client_os: request.client_os.as_str().into(),
|
||||
os_version: profile.os_version().into(),
|
||||
host_id: request.host_id,
|
||||
local_hostname: Some(profile.computer().into()),
|
||||
};
|
||||
let xml = match &request.source {
|
||||
HipSource::Disabled => bail!("HIP is disabled"),
|
||||
HipSource::Generated => crate::hip_source::generate(&profile, None, &input, &check, true)?,
|
||||
HipSource::Edited { .. } => {
|
||||
let xml = edited_report.context("Edited HIP report is unavailable")?;
|
||||
crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)?
|
||||
}
|
||||
source => {
|
||||
let execution = crate::hip_source::resolve(source, desktop_uid, false, None, Some(profile))?;
|
||||
let openconnect::HipSource::Script(script) = execution.source else {
|
||||
bail!("HIP preview executable is unavailable");
|
||||
};
|
||||
let xml = script.collect(&input, &check)?;
|
||||
gphip::validate_edited_report(&xml).context("Custom HIP script did not emit a valid HIP report")?;
|
||||
xml
|
||||
}
|
||||
};
|
||||
check()?;
|
||||
Ok(xml)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpapi::os_profile::ClientOs;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
fn job(session_id: Uuid) -> PreviewJob {
|
||||
let (tx, _) = tokio::sync::mpsc::channel(1);
|
||||
let (connection, _) = ConnectionControl::new(Uuid::new_v4(), tx);
|
||||
PreviewJob {
|
||||
session_id,
|
||||
request_id: Uuid::new_v4(),
|
||||
request: PreviewHipReportRequest {
|
||||
source: HipSource::Generated,
|
||||
client_os: ClientOs::Linux,
|
||||
client_version: "6.3.3".into(),
|
||||
host_id: None,
|
||||
},
|
||||
edited_report: None,
|
||||
desktop_uid: None,
|
||||
identity: HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"host".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
),
|
||||
registry: Arc::new(SessionRegistry::for_tests(Uuid::new_v4())),
|
||||
connection,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preview_admission_rejects_duplicate_session_and_global_capacity() {
|
||||
let previews = HipPreviews::new();
|
||||
let session_id = Uuid::new_v4();
|
||||
let cancellation = previews.shutdown.child_token();
|
||||
let worker_cancellation = cancellation.clone();
|
||||
let worker = tokio::spawn(async move { worker_cancellation.cancelled().await });
|
||||
let connection_id = Uuid::new_v4();
|
||||
previews.tasks.lock().await.insert(
|
||||
session_id,
|
||||
PreviewTask {
|
||||
connection_id,
|
||||
cancellation,
|
||||
worker,
|
||||
},
|
||||
);
|
||||
assert!(!previews.start(job(session_id)).await);
|
||||
previews.cancel_connection(session_id, connection_id).await;
|
||||
let _all_slots = Arc::clone(&previews.slots)
|
||||
.acquire_many_owned(MAX_ACTIVE_PREVIEWS as u32)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!previews.start(job(Uuid::new_v4())).await);
|
||||
previews.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_preview_owner_waits_for_worker_teardown() {
|
||||
let previews = HipPreviews::new();
|
||||
let session_id = Uuid::new_v4();
|
||||
let connection_id = Uuid::new_v4();
|
||||
let cancellation = previews.shutdown.child_token();
|
||||
let worker_cancellation = cancellation.clone();
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let worker_stopped = Arc::clone(&stopped);
|
||||
let worker = tokio::spawn(async move {
|
||||
worker_cancellation.cancelled().await;
|
||||
tokio::task::yield_now().await;
|
||||
worker_stopped.store(true, Ordering::SeqCst);
|
||||
});
|
||||
previews.tasks.lock().await.insert(
|
||||
session_id,
|
||||
PreviewTask {
|
||||
connection_id,
|
||||
cancellation,
|
||||
worker,
|
||||
},
|
||||
);
|
||||
previews.cancel_connection(session_id, Uuid::new_v4()).await;
|
||||
assert!(!stopped.load(Ordering::SeqCst));
|
||||
previews.cancel_connection(session_id, connection_id).await;
|
||||
assert!(stopped.load(Ordering::SeqCst));
|
||||
assert!(previews.tasks.lock().await.is_empty());
|
||||
previews.shutdown().await;
|
||||
assert!(!previews.start(job(session_id)).await);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_preview_does_not_start_collection() {
|
||||
let preview = job(Uuid::new_v4());
|
||||
let cancelled = CancellationToken::new();
|
||||
cancelled.cancel();
|
||||
let error = generate(preview.request, None, None, preview.identity, cancelled).unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast_ref::<io::Error>().unwrap().kind(),
|
||||
io::ErrorKind::Interrupted
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,277 +0,0 @@
|
||||
use std::{fs, io, os::unix::fs::PermissionsExt, path::PathBuf, sync::Arc};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
hip::HipSource,
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder},
|
||||
};
|
||||
use gphip::{ReportContext, ReportInput};
|
||||
use openconnect::{HipRequest, HipScript, HipScriptEnvironment};
|
||||
|
||||
pub(crate) struct HipExecution {
|
||||
pub source: openconnect::HipSource,
|
||||
approval: HipApproval,
|
||||
}
|
||||
|
||||
impl HipExecution {
|
||||
pub(crate) fn into_parts(self) -> (openconnect::HipSource, HipApproval) {
|
||||
(self.source, self.approval)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct HipApproval {
|
||||
identity: Option<(String, u32)>,
|
||||
}
|
||||
|
||||
impl HipApproval {
|
||||
pub(crate) fn approval_is_valid(&self) -> bool {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
if let Some((id, uid)) = &self.identity {
|
||||
return gpservice::hip_approval::resolve(id, *uid).is_ok();
|
||||
}
|
||||
self.identity.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve(
|
||||
source: &HipSource,
|
||||
desktop_uid: Option<u32>,
|
||||
brokered_macos: bool,
|
||||
edited_report: Option<Arc<str>>,
|
||||
profile: Option<OsProfile>,
|
||||
) -> anyhow::Result<HipExecution> {
|
||||
let approval;
|
||||
let source = match source {
|
||||
HipSource::Disabled => {
|
||||
approval = None;
|
||||
openconnect::HipSource::Disabled
|
||||
}
|
||||
HipSource::Generated | HipSource::Edited { .. } => {
|
||||
let profile = profile.context("HIP generator identity is unavailable")?;
|
||||
approval = None;
|
||||
let xml = match source {
|
||||
HipSource::Edited { .. } => {
|
||||
let xml = edited_report.context("Edited HIP report was not uploaded for this connection")?;
|
||||
gphip::validate_edited_report(&xml)?;
|
||||
Some(xml)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
openconnect::HipSource::Generator(Arc::new(move |request, control| {
|
||||
generate(&profile, xml.as_deref(), request, &|| control.check(), false).map_err(generation_error)
|
||||
}))
|
||||
}
|
||||
HipSource::UserScript { path } => {
|
||||
approval = None;
|
||||
ensure_custom_available(brokered_macos)?;
|
||||
let uid = desktop_uid.context("HIP custom scripts require a verified desktop user")?;
|
||||
ensure!(uid != 0, "HIP custom scripts require a non-root desktop user");
|
||||
let path = PathBuf::from(path);
|
||||
ensure!(path.is_absolute(), "HIP custom script path must be absolute");
|
||||
let metadata = fs::symlink_metadata(&path).context("Failed to inspect the HIP script")?;
|
||||
ensure!(
|
||||
metadata.is_file() && !metadata.file_type().is_symlink() && metadata.permissions().mode() & 0o111 != 0,
|
||||
"HIP custom script must be an executable regular file"
|
||||
);
|
||||
let script =
|
||||
HipScript::new(path.to_string_lossy().into_owned(), Some(uid))?.with_environment(script_environment(uid)?)?;
|
||||
openconnect::HipSource::Script(script)
|
||||
}
|
||||
HipSource::ApprovedRootScript { approval_id } => {
|
||||
ensure_custom_available(brokered_macos)?;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
let owner_uid = desktop_uid.context("Root HIP scripts require a verified desktop user")?;
|
||||
let approved = gpservice::hip_approval::resolve(approval_id, owner_uid)?;
|
||||
let id = approval_id.clone();
|
||||
let path = approved.path;
|
||||
let expected = path.clone();
|
||||
let script = HipScript::new(path.to_string_lossy().into_owned(), Some(0))?
|
||||
.with_environment(script_environment(0)?)?
|
||||
.with_validator(move |control| {
|
||||
control.check()?;
|
||||
let current = gpservice::hip_approval::resolve_with_control(&id, owner_uid, &|| control.check())
|
||||
.map_err(generation_error)?;
|
||||
if current.path != expected {
|
||||
return Err(io::Error::other("Approved HIP executable changed"));
|
||||
}
|
||||
control.check()
|
||||
});
|
||||
approval = Some((approval_id.clone(), owner_uid));
|
||||
openconnect::HipSource::Script(script)
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
{
|
||||
let _ = (approval_id, desktop_uid);
|
||||
anyhow::bail!("Root HIP script approvals are unavailable on this platform")
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(HipExecution {
|
||||
source,
|
||||
approval: HipApproval { identity: approval },
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_custom_available(brokered_macos: bool) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
!cfg!(target_os = "macos") && !brokered_macos,
|
||||
"Custom HIP scripts are unavailable on macOS"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn generate(
|
||||
profile: &OsProfile,
|
||||
edited: Option<&str>,
|
||||
request: &HipRequest,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
preview: bool,
|
||||
) -> anyhow::Result<String> {
|
||||
control.check()?;
|
||||
let context = if preview {
|
||||
ReportContext::Preview
|
||||
} else {
|
||||
ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
}
|
||||
};
|
||||
let input = ReportInput {
|
||||
profile: profile.clone(),
|
||||
context,
|
||||
};
|
||||
match edited {
|
||||
Some(xml) => gphip::refresh_edited_report_with_control(xml, &input, control),
|
||||
None => gphip::generate_report_with_control(&input, control),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn script_environment(uid: u32) -> anyhow::Result<HipScriptEnvironment> {
|
||||
let user =
|
||||
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.context("HIP execution user is unavailable")?;
|
||||
let home = user.dir.to_string_lossy().into_owned();
|
||||
Ok(HipScriptEnvironment {
|
||||
variables: vec![
|
||||
(
|
||||
"PATH".into(),
|
||||
gpapi::process::collection::command_path(uid == 0)?
|
||||
.into_string()
|
||||
.map_err(|_| anyhow::anyhow!("HIP command path is not valid UTF-8"))?,
|
||||
),
|
||||
("LC_ALL".into(), "C".into()),
|
||||
("HOME".into(), home.clone()),
|
||||
("USER".into(), user.name.clone()),
|
||||
("LOGNAME".into(), user.name),
|
||||
],
|
||||
cwd: home,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn profile(
|
||||
identity: &HostIdentity,
|
||||
os: ClientOs,
|
||||
version: Option<String>,
|
||||
os_version: Option<String>,
|
||||
host_id: Option<String>,
|
||||
hostname: Option<String>,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
) -> io::Result<OsProfile> {
|
||||
let identity = HostIdentity::from_parts(
|
||||
hostname.unwrap_or_else(|| identity.computer().into()),
|
||||
host_id.unwrap_or_else(|| identity.host_id().into()),
|
||||
identity.serialno().into(),
|
||||
identity.mac_addr().into(),
|
||||
);
|
||||
let mut builder = OsProfileBuilder::new(os).host_identity(identity);
|
||||
if let Some(version) = version {
|
||||
builder = builder.client_version(version);
|
||||
}
|
||||
if let Some(os_version) = os_version {
|
||||
builder = builder.os_version(os_version);
|
||||
}
|
||||
builder.build_with_control(control)
|
||||
}
|
||||
|
||||
fn generation_error(error: anyhow::Error) -> io::Error {
|
||||
match error.downcast::<io::Error>() {
|
||||
Ok(error) => error,
|
||||
Err(error) => io::Error::other(error),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpapi::os_profile::ClientOs;
|
||||
|
||||
fn fixture_profile() -> OsProfile {
|
||||
profile(
|
||||
&HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"host".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
),
|
||||
ClientOs::Linux,
|
||||
Some("6.3.3".into()),
|
||||
Some("negotiated-version".into()),
|
||||
None,
|
||||
None,
|
||||
&gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_configuration_needs_no_files_or_root_identity() {
|
||||
let generated = resolve(&HipSource::Generated, None, true, None, Some(fixture_profile())).unwrap();
|
||||
assert!(matches!(generated.source, openconnect::HipSource::Generator(_)));
|
||||
let disabled = resolve(&HipSource::Disabled, None, true, None, Some(fixture_profile())).unwrap();
|
||||
assert!(matches!(disabled.source, openconnect::HipSource::Disabled));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_retains_negotiated_identity_and_os_version() {
|
||||
let identity = HostIdentity::from_parts(
|
||||
"original".into(),
|
||||
"original-id".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let profile = profile(
|
||||
&identity,
|
||||
ClientOs::Mac,
|
||||
Some("6.3.3".into()),
|
||||
Some("negotiated-os".into()),
|
||||
Some("negotiated-host".into()),
|
||||
Some("negotiated-name".into()),
|
||||
&gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(profile.os_version(), "negotiated-os");
|
||||
assert_eq!(profile.host_identity().host_id(), "negotiated-host");
|
||||
assert_eq!(profile.host_identity().computer(), "negotiated-name");
|
||||
assert_eq!(profile.host_identity().serialno(), "serial");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_errors_preserve_cancellation() {
|
||||
let error = generation_error(io::Error::new(io::ErrorKind::Interrupted, "cancelled").into());
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_source_cannot_run_on_macos_or_choose_root_without_approval() {
|
||||
let source = HipSource::UserScript {
|
||||
path: "/tmp/hip.sh".into(),
|
||||
};
|
||||
assert!(resolve(&source, None, false, None, None).is_err());
|
||||
assert!(resolve(&source, Some(0), false, None, None).is_err());
|
||||
assert!(resolve(&source, Some(1000), true, None, Some(fixture_profile())).is_err());
|
||||
#[cfg(target_os = "macos")]
|
||||
assert!(resolve(&source, Some(1000), false, None, None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,2 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub mod hip_approval;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub mod vpnc_script;
|
||||
@@ -23,11 +23,7 @@ impl CredentialServer {
|
||||
Self { registry }
|
||||
}
|
||||
|
||||
pub(crate) async fn start(
|
||||
self,
|
||||
cancel: CancellationToken,
|
||||
ready: tokio::sync::oneshot::Sender<()>,
|
||||
) -> anyhow::Result<()> {
|
||||
pub(crate) async fn start(self, cancel: CancellationToken) -> anyhow::Result<()> {
|
||||
if !Uid::effective().is_root() {
|
||||
bail!("macOS brokered mode requires root privileges");
|
||||
}
|
||||
@@ -37,7 +33,6 @@ 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! {
|
||||
@@ -50,7 +45,7 @@ impl CredentialServer {
|
||||
}
|
||||
let registry = Arc::clone(&self.registry);
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = credential_lease::serve(stream, registry, None).await {
|
||||
if let Err(err) = credential_lease::serve(stream, registry).await {
|
||||
warn!("Broker credential lease ended: {err}");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
mod cli;
|
||||
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
|
||||
mod credential_lease;
|
||||
mod desktop_client;
|
||||
#[cfg(debug_assertions)]
|
||||
mod dev_bootstrap;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))]
|
||||
mod device_anchor;
|
||||
mod handlers;
|
||||
mod hip_preview;
|
||||
mod hip_source;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos_broker;
|
||||
mod request_dispatcher;
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::{
|
||||
use common::binary_paths;
|
||||
use gpapi::{
|
||||
service::{
|
||||
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
|
||||
request::{UpdateGuiRequest, WsRequest},
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
utils::{checksum::verify_checksum, redact::Redaction},
|
||||
@@ -17,211 +17,41 @@ use gpapi::{
|
||||
use log::{info, warn};
|
||||
use tar::Archive;
|
||||
use tempfile::NamedTempFile;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
use xz2::read::XzDecoder;
|
||||
|
||||
const MAX_GUI_ARCHIVE_SIZE: u64 = 256 * 1024 * 1024;
|
||||
const MAX_GUI_ARCHIVE_CONTENT_SIZE: u64 = 512 * 1024 * 1024;
|
||||
const MAX_GUI_BINARY_SIZE: u64 = 256 * 1024 * 1024;
|
||||
|
||||
pub(crate) struct SessionAuthority {
|
||||
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
pub session_id: uuid::Uuid,
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
pub(crate) enum PendingDispatch {
|
||||
Connect {
|
||||
preparation: ConnectionPreparation,
|
||||
request: Box<gpapi::service::request::ConnectRequest>,
|
||||
desktop_uid: Option<u32>,
|
||||
edited_report: Option<Arc<str>>,
|
||||
},
|
||||
Drain(Option<crate::vpn_task::AttemptDrain>),
|
||||
Other(WsRequest),
|
||||
}
|
||||
|
||||
pub(crate) struct ConnectionPreparation {
|
||||
authority: SessionAuthority,
|
||||
non_tunnel: bool,
|
||||
reservation: Option<crate::vpn_task::ConnectReservation>,
|
||||
}
|
||||
|
||||
impl ConnectionPreparation {
|
||||
fn cancellation(&self) -> tokio_util::sync::CancellationToken {
|
||||
self
|
||||
.reservation
|
||||
.as_ref()
|
||||
.expect("preparation retains reservation")
|
||||
.cancellation()
|
||||
}
|
||||
|
||||
fn commit(
|
||||
mut self,
|
||||
connection: crate::vpn_task::PreparedConnection,
|
||||
desktop_uid: Option<u32>,
|
||||
edited_report: Option<Arc<str>>,
|
||||
) -> ServiceResult {
|
||||
let reservation = self.reservation.take().expect("preparation retains reservation");
|
||||
self.authority.registry.commit_connection(
|
||||
self.authority.session_id,
|
||||
self.authority.generation,
|
||||
self.non_tunnel,
|
||||
|| reservation.commit(connection, desktop_uid, edited_report, Some(self.authority.session_id)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RequestDispatcher {
|
||||
lifecycle: crate::vpn_task::LifecycleHandle,
|
||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
redaction: Arc<Redaction>,
|
||||
install_lock: Mutex<()>,
|
||||
gui_management_enabled: bool,
|
||||
externally_brokered: bool,
|
||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
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,
|
||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
redaction: Arc<Redaction>,
|
||||
gui_management_enabled: bool,
|
||||
externally_brokered: bool,
|
||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
||||
) -> Self {
|
||||
Self {
|
||||
lifecycle,
|
||||
ws_req_tx,
|
||||
gui_restart_requested,
|
||||
redaction,
|
||||
install_lock: Mutex::new(()),
|
||||
gui_management_enabled,
|
||||
externally_brokered,
|
||||
brokered_scripts_dir,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dispatch_lifecycle(
|
||||
&self,
|
||||
request: WsRequest,
|
||||
desktop_uid: Option<u32>,
|
||||
edited_report: Option<Arc<str>>,
|
||||
authority: Option<SessionAuthority>,
|
||||
) -> Result<PendingDispatch, ServiceResult> {
|
||||
match request {
|
||||
WsRequest::Connect(request) => {
|
||||
if let Err(message) = self.validate_connect_request(&request) {
|
||||
return Err(ServiceResult::rejected(ServiceErrorCode::InvalidRequest, message));
|
||||
}
|
||||
let redaction_values = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.flat_map(|member| [member.gateway.server(), member.authentication.cookie()])
|
||||
.collect::<Vec<_>>();
|
||||
if let Err(err) = self.redaction.add_values(&redaction_values) {
|
||||
warn!("Failed to update log redaction: {err}");
|
||||
return Err(ServiceResult::rejected(
|
||||
ServiceErrorCode::Internal,
|
||||
"Request could not be accepted",
|
||||
));
|
||||
}
|
||||
let authority = authority
|
||||
.ok_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection session is missing"))?;
|
||||
let non_tunnel = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel);
|
||||
let reservation =
|
||||
authority
|
||||
.registry
|
||||
.reserve_connection(authority.session_id, authority.generation, non_tunnel, || {
|
||||
self.lifecycle.reserve_connect()
|
||||
})?;
|
||||
let preparation = ConnectionPreparation {
|
||||
authority,
|
||||
non_tunnel,
|
||||
reservation: Some(reservation),
|
||||
};
|
||||
let edited_report = if let gpapi::hip::HipSource::Edited { report_id } = request.args().hip_source() {
|
||||
let report_id = uuid::Uuid::parse_str(report_id)
|
||||
.map_err(|_| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report ID"))?;
|
||||
Some(
|
||||
preparation
|
||||
.authority
|
||||
.registry
|
||||
.edited_hip_report(preparation.authority.session_id, report_id)
|
||||
.map_err(|_| {
|
||||
ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"HIP report is unavailable for this session",
|
||||
)
|
||||
})?,
|
||||
)
|
||||
} else {
|
||||
edited_report
|
||||
};
|
||||
Ok(PendingDispatch::Connect {
|
||||
preparation,
|
||||
request,
|
||||
desktop_uid,
|
||||
edited_report,
|
||||
})
|
||||
}
|
||||
WsRequest::StopNonTunnelAttachment { connection_id } => {
|
||||
let authority = authority
|
||||
.ok_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection session is missing"))?;
|
||||
let drain =
|
||||
authority
|
||||
.registry
|
||||
.stop_non_tunnel_attachment(authority.session_id, authority.generation, connection_id)?;
|
||||
Ok(PendingDispatch::Drain(drain))
|
||||
}
|
||||
WsRequest::Disconnect(_) => Err(self.lifecycle.request_disconnect()),
|
||||
request => Ok(PendingDispatch::Other(request)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub async fn dispatch(&self, request: WsRequest) -> ServiceResult {
|
||||
match self.dispatch_lifecycle(request, None, None, None) {
|
||||
Ok(request) => self.dispatch_pending(request).await,
|
||||
Err(result) => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn dispatch_pending(&self, request: PendingDispatch) -> ServiceResult {
|
||||
let request = match request {
|
||||
PendingDispatch::Connect {
|
||||
preparation,
|
||||
request,
|
||||
desktop_uid,
|
||||
edited_report,
|
||||
} => {
|
||||
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) => {
|
||||
warn!("Connection preparation failed: {error:#}");
|
||||
ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"Connection resources could not be prepared",
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
PendingDispatch::Drain(drain) => {
|
||||
if let Some(drain) = drain {
|
||||
drain.wait().await;
|
||||
}
|
||||
return ServiceResult::Accepted;
|
||||
}
|
||||
PendingDispatch::Other(request) => request,
|
||||
};
|
||||
|
||||
match request {
|
||||
WsRequest::RestartGui => {
|
||||
if !self.gui_management_enabled {
|
||||
@@ -255,40 +85,44 @@ impl RequestDispatcher {
|
||||
ServiceResult::VpncScriptMetadata(None)
|
||||
}
|
||||
}
|
||||
WsRequest::UpdateLogLevel(UpdateLogLevelRequest(level)) => {
|
||||
let level = level.parse().unwrap_or(log::Level::Info);
|
||||
info!("Updating log level to: {level}");
|
||||
if let Err(err) = gpapi::logger::set_max_level(level) {
|
||||
warn!("Failed to update log level: {err}");
|
||||
request => {
|
||||
if let WsRequest::Connect(ref connect) = request {
|
||||
if let Err(message) = self.validate_connect_paths(connect) {
|
||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, message);
|
||||
}
|
||||
if let Err(err) = self
|
||||
.redaction
|
||||
.add_values(&[connect.gateway().server(), connect.args().cookie()])
|
||||
{
|
||||
warn!("Failed to update log redaction: {err}");
|
||||
return ServiceResult::rejected(ServiceErrorCode::Internal, "Request could not be accepted");
|
||||
}
|
||||
}
|
||||
|
||||
match self.ws_req_tx.try_send(request) {
|
||||
Ok(()) => ServiceResult::Accepted,
|
||||
Err(mpsc::error::TrySendError::Full(_)) => {
|
||||
ServiceResult::rejected(ServiceErrorCode::Busy, "Service request queue is full")
|
||||
}
|
||||
Err(mpsc::error::TrySendError::Closed(_)) => {
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "VPN task is unavailable")
|
||||
}
|
||||
}
|
||||
ServiceResult::Accepted
|
||||
}
|
||||
WsRequest::Connect(_)
|
||||
| WsRequest::StopNonTunnelAttachment { .. }
|
||||
| WsRequest::Disconnect(_)
|
||||
| WsRequest::StoreEditedHipReportChunk(_)
|
||||
| WsRequest::PreviewHipReport(_)
|
||||
| WsRequest::GetHipApprovalStatus { .. }
|
||||
| WsRequest::ReadHipPreviewChunk(_)
|
||||
| WsRequest::GetLastSubmittedHipReport
|
||||
| WsRequest::SetTunnelStatisticsEnabled { .. } => {
|
||||
unreachable!("session-bound request was already dispatched")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_connect_request(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
|
||||
if !self.externally_brokered {
|
||||
fn validate_connect_paths(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
|
||||
let Some(scripts) = &self.brokered_scripts_dir else {
|
||||
return Ok(());
|
||||
};
|
||||
let expected_script = scripts.join("vpnc-script").to_string_lossy().into_owned();
|
||||
let expected_wrapper = scripts.join("hipreport.sh").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(),
|
||||
gpapi::hip::HipSource::UserScript { .. } | gpapi::hip::HipSource::ApprovedRootScript { .. }
|
||||
) {
|
||||
return Err("macOS does not support custom HIP scripts");
|
||||
if request.args().csd_wrapper().as_deref() != Some(expected_wrapper.as_str()) {
|
||||
return Err("macOS HIP wrapper must be the bundled wrapper");
|
||||
}
|
||||
if request.args().certificate().is_some() || request.args().sslkey().is_some() {
|
||||
return Err("macOS client identity must be provided as protected data, not root-readable paths");
|
||||
@@ -429,12 +263,14 @@ fn extract_gui_binary<R: Read>(archive: &mut Archive<R>, dir: &Path) -> Result<N
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::vpn_task::test_connect_request as test_request;
|
||||
use std::{io::Cursor, os::unix::fs::PermissionsExt};
|
||||
|
||||
use gpapi::{
|
||||
gateway::Gateway,
|
||||
service::transport::{ServiceErrorCode, ServiceResult},
|
||||
service::{
|
||||
request::ConnectRequest,
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
};
|
||||
use tar::{Builder, EntryType, Header};
|
||||
use xz2::write::XzEncoder;
|
||||
@@ -519,7 +355,7 @@ mod tests {
|
||||
#[test]
|
||||
fn installs_gui_at_the_supplied_target() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let checksum = sha256::try_digest(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpclient/gpgui");
|
||||
|
||||
@@ -543,12 +379,13 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() {
|
||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
||||
let dispatcher = RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
request_tx,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
false,
|
||||
true,
|
||||
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
|
||||
);
|
||||
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::RestartGui).await else {
|
||||
panic!("brokered mode accepted GUI restart");
|
||||
@@ -557,7 +394,10 @@ 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_certificate(Some("/Users/example/client.pem".to_string()));
|
||||
let request = ConnectRequest::new(info, "cookie".into())
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||
.with_csd_wrapper(Some("/app/Contents/Resources/Scripts/hipreport.sh".to_string()))
|
||||
.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");
|
||||
};
|
||||
@@ -565,38 +405,28 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brokered_mode_rejects_script_overrides() {
|
||||
fn brokered_mode_accepts_only_resource_script_paths() {
|
||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
||||
let dispatcher = RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
request_tx,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
false,
|
||||
true,
|
||||
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
|
||||
);
|
||||
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 embedded = test_request(info.clone());
|
||||
assert_eq!(dispatcher.validate_connect_request(&embedded), Ok(()));
|
||||
let bundled = ConnectRequest::new(info.clone(), "cookie".into())
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||
.with_csd_wrapper(Some("/app/Contents/Resources/Scripts/hipreport.sh".to_string()));
|
||||
assert_eq!(dispatcher.validate_connect_paths(&bundled), Ok(()));
|
||||
|
||||
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_hip_source(gpapi::hip::HipSource::UserScript {
|
||||
path: "/tmp/hip.sh".into(),
|
||||
});
|
||||
let old_layout = ConnectRequest::new(info, "cookie".into())
|
||||
.with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()))
|
||||
.with_csd_wrapper(Some("/app/Contents/Helpers/hipreport.sh".to_string()));
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_request(&custom),
|
||||
Err("macOS does not support custom HIP scripts")
|
||||
dispatcher.validate_connect_paths(&old_layout),
|
||||
Err("macOS VPN script must be the bundled script")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,3 @@
|
||||
pub(crate) fn desktop_uid() -> Option<u32> {
|
||||
None
|
||||
pub(crate) fn trusted_csd_uid() -> anyhow::Result<Option<u32>> {
|
||||
Ok(None)
|
||||
}
|
||||
@@ -5,4 +5,4 @@ mod platform;
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
|
||||
pub(crate) use platform::desktop_uid;
|
||||
pub(crate) use platform::trusted_csd_uid;
|
||||
@@ -1,9 +1,7 @@
|
||||
pub(crate) fn desktop_uid() -> Option<u32> {
|
||||
match gpapi::process::users::get_non_root_user() {
|
||||
Ok(user) => Some(user.uid()),
|
||||
Err(err) => {
|
||||
log::warn!("No verified desktop user is available for custom HIP scripts: {err}");
|
||||
None
|
||||
}
|
||||
pub(crate) fn trusted_csd_uid() -> anyhow::Result<Option<u32>> {
|
||||
let uid = gpapi::process::users::get_non_root_user()?.uid();
|
||||
if uid == 0 {
|
||||
anyhow::bail!("The HIP script user must not be root");
|
||||
}
|
||||
Ok(Some(uid))
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use std::{
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use gpapi::service::transport::{ServiceErrorCode, ServiceResult, SessionCredential};
|
||||
use gpapi::service::transport::SessionCredential;
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
use zeroize::Zeroizing;
|
||||
@@ -13,11 +13,9 @@ use crate::ws_connection::ConnectionControl;
|
||||
|
||||
const ACTIVATION_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const MAX_PENDING_SESSIONS: usize = 16;
|
||||
const HIP_PREVIEW_CHUNK_BYTES: usize = 16 * 1024;
|
||||
|
||||
pub struct HandshakePermit {
|
||||
pub session_id: Uuid,
|
||||
pub desktop_uid: Option<u32>,
|
||||
pub observed_generation: u64,
|
||||
pub secret: Zeroizing<[u8; 32]>,
|
||||
token: Uuid,
|
||||
@@ -40,13 +38,6 @@ pub enum SessionError {
|
||||
ReconnectSuperseded,
|
||||
#[error("session registry is unavailable")]
|
||||
Unavailable,
|
||||
#[error("invalid HIP report upload")]
|
||||
InvalidHipUpload,
|
||||
}
|
||||
|
||||
pub enum HipUploadResult {
|
||||
Progress(Uuid),
|
||||
Stored(Uuid),
|
||||
}
|
||||
|
||||
enum SessionStatus {
|
||||
@@ -62,161 +53,25 @@ enum SessionStatus {
|
||||
}
|
||||
|
||||
struct SessionRecord {
|
||||
non_tunnel: Option<AttachmentAttempt>,
|
||||
closed_attachment: Option<Uuid>,
|
||||
secret: Zeroizing<[u8; 32]>,
|
||||
product_version: String,
|
||||
desktop_uid: Option<u32>,
|
||||
edited_hip_report: Option<(Uuid, Arc<str>)>,
|
||||
edited_hip_upload: Option<(Uuid, String)>,
|
||||
hip_preview: Option<(Uuid, Arc<str>)>,
|
||||
last_successful_hip_report: Option<Arc<str>>,
|
||||
status: SessionStatus,
|
||||
}
|
||||
|
||||
/// Only live preparation/execution is retained, never acceptance history.
|
||||
struct AttachmentAttempt {
|
||||
generation: u64,
|
||||
connection_id: Uuid,
|
||||
drain: crate::vpn_task::AttemptDrain,
|
||||
}
|
||||
|
||||
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 {
|
||||
ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection attachment is unavailable")
|
||||
}
|
||||
|
||||
fn current_connection(record: &SessionRecord, expected: u64) -> Result<Uuid, ServiceResult> {
|
||||
match &record.status {
|
||||
SessionStatus::Active {
|
||||
generation,
|
||||
connection: Some(connection),
|
||||
..
|
||||
} if *generation == expected && !connection.is_closed() => Ok(connection.connection_id()),
|
||||
_ => Err(unavailable_connection()),
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionRegistry {
|
||||
pub(crate) fn reserve_connection(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
generation: u64,
|
||||
non_tunnel: bool,
|
||||
reserve: impl FnOnce() -> Result<crate::vpn_task::ConnectReservation, ServiceResult>,
|
||||
) -> Result<crate::vpn_task::ConnectReservation, ServiceResult> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| unavailable_connection())?;
|
||||
let record = sessions.get_mut(&session_id).ok_or_else(unavailable_connection)?;
|
||||
let connection_id = current_connection(record, generation)?;
|
||||
if non_tunnel && record.closed_attachment == Some(connection_id) {
|
||||
return Err(ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"Non-tunnel attachment is closing",
|
||||
));
|
||||
}
|
||||
if record
|
||||
.non_tunnel
|
||||
.as_ref()
|
||||
.is_some_and(|attempt| attempt.drain.is_complete())
|
||||
{
|
||||
record.non_tunnel = None;
|
||||
}
|
||||
let reservation = reserve()?;
|
||||
if non_tunnel {
|
||||
record.non_tunnel = Some(AttachmentAttempt {
|
||||
generation,
|
||||
connection_id,
|
||||
drain: reservation.drain(),
|
||||
});
|
||||
}
|
||||
Ok(reservation)
|
||||
}
|
||||
|
||||
pub(crate) fn commit_connection(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
generation: u64,
|
||||
non_tunnel: bool,
|
||||
commit: impl FnOnce() -> ServiceResult,
|
||||
) -> ServiceResult {
|
||||
let Ok(sessions) = self.sessions.lock() else {
|
||||
return unavailable_connection();
|
||||
};
|
||||
let Some(record) = sessions.get(&session_id) else {
|
||||
return unavailable_connection();
|
||||
};
|
||||
if non_tunnel {
|
||||
let connection_id = match current_connection(record, generation) {
|
||||
Ok(id) => id,
|
||||
Err(result) => return result,
|
||||
};
|
||||
if record.closed_attachment == Some(connection_id) {
|
||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Non-tunnel attachment is closing");
|
||||
}
|
||||
} else if !matches!(record.status, SessionStatus::Active { .. }) {
|
||||
return unavailable_connection();
|
||||
}
|
||||
// Non-tunnel attachment invalidation takes this same lock. An authorized
|
||||
// tunnel reservation survives attachment loss as before; revoked sessions
|
||||
// cannot commit either mode. Queue insertion transfers cleanup ownership.
|
||||
commit()
|
||||
}
|
||||
|
||||
pub(crate) fn stop_non_tunnel_attachment(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
generation: u64,
|
||||
connection_id: Uuid,
|
||||
) -> Result<Option<crate::vpn_task::AttemptDrain>, ServiceResult> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| unavailable_connection())?;
|
||||
let record = sessions.get_mut(&session_id).ok_or_else(unavailable_connection)?;
|
||||
let current_id = current_connection(record, generation)?;
|
||||
if current_id == connection_id {
|
||||
record.closed_attachment = Some(connection_id);
|
||||
}
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
if attempt.connection_id == connection_id {
|
||||
attempt.drain.cancel();
|
||||
return Ok(Some(attempt.drain.clone()));
|
||||
}
|
||||
}
|
||||
// No retained live work belongs to that attachment. Never stop a successor.
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn new(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: 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",
|
||||
))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn issue(&self, product_version: &str, desktop_uid: Option<u32>) -> Result<Arc<SessionCredential>, SessionError> {
|
||||
pub fn issue(&self, product_version: &str) -> Result<Arc<SessionCredential>, SessionError> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let now = Instant::now();
|
||||
sessions.retain(|_, record| {
|
||||
@@ -235,31 +90,14 @@ impl SessionRegistry {
|
||||
return Err(SessionError::TooManyPending);
|
||||
}
|
||||
|
||||
let credential =
|
||||
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 = (self.resolve_device_anchor)().map_err(|error| {
|
||||
log::warn!("GUI device anchor unavailable: {error:#}");
|
||||
SessionError::Unavailable
|
||||
})?;
|
||||
credential
|
||||
.with_device_anchor(anchor)
|
||||
.map_err(|_| SessionError::Unavailable)?
|
||||
};
|
||||
let credential = Arc::new(credential);
|
||||
let credential = Arc::new(
|
||||
SessionCredential::generate(self.service_instance_id, product_version).map_err(|_| SessionError::Unavailable)?,
|
||||
);
|
||||
sessions.insert(
|
||||
credential.session_id(),
|
||||
SessionRecord {
|
||||
non_tunnel: None,
|
||||
closed_attachment: None,
|
||||
secret: Zeroizing::new(*credential.secret()),
|
||||
product_version: credential.product_version().to_owned(),
|
||||
desktop_uid,
|
||||
edited_hip_report: None,
|
||||
edited_hip_upload: None,
|
||||
hip_preview: None,
|
||||
last_successful_hip_report: None,
|
||||
status: SessionStatus::Pending {
|
||||
activation_deadline: Instant::now() + ACTIVATION_TIMEOUT,
|
||||
handshake_token: None,
|
||||
@@ -338,7 +176,6 @@ impl SessionRegistry {
|
||||
let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
Ok(HandshakePermit {
|
||||
session_id,
|
||||
desktop_uid: record.desktop_uid,
|
||||
observed_generation,
|
||||
secret: Zeroizing::new(*record.secret),
|
||||
token,
|
||||
@@ -391,10 +228,6 @@ impl SessionRegistry {
|
||||
connection: current,
|
||||
reconnect_token,
|
||||
} if *generation == permit.observed_generation && *reconnect_token == Some(permit.token) => {
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
attempt.drain.cancel();
|
||||
}
|
||||
record.closed_attachment = None;
|
||||
*generation = generation.checked_add(1).ok_or(SessionError::Unavailable)?;
|
||||
*reconnect_token = None;
|
||||
Ok(current.replace(connection))
|
||||
@@ -435,133 +268,10 @@ impl SessionRegistry {
|
||||
)
|
||||
}
|
||||
|
||||
pub fn append_edited_hip_report_chunk(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
upload_id: Option<Uuid>,
|
||||
offset: usize,
|
||||
chunk: String,
|
||||
complete: bool,
|
||||
) -> Result<HipUploadResult, SessionError> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get_mut(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
if !matches!(record.status, SessionStatus::Active { .. }) {
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
if upload_id.is_none() {
|
||||
if offset != 0 {
|
||||
return Err(SessionError::InvalidHipUpload);
|
||||
}
|
||||
record.edited_hip_upload = Some((Uuid::new_v4(), String::new()));
|
||||
}
|
||||
let (current_id, xml) = record
|
||||
.edited_hip_upload
|
||||
.as_mut()
|
||||
.ok_or(SessionError::InvalidHipUpload)?;
|
||||
if upload_id.is_some_and(|id| id != *current_id) || offset != xml.len() || chunk.len() > 8 * 1024 {
|
||||
return Err(SessionError::InvalidHipUpload);
|
||||
}
|
||||
if xml.len() + chunk.len() > gphip::MAX_EDITED_REPORT_BYTES {
|
||||
record.edited_hip_upload = None;
|
||||
return Err(SessionError::InvalidHipUpload);
|
||||
}
|
||||
xml.push_str(&chunk);
|
||||
if !complete {
|
||||
return Ok(HipUploadResult::Progress(*current_id));
|
||||
}
|
||||
if gphip::validate_edited_report(xml).is_err() {
|
||||
record.edited_hip_upload = None;
|
||||
return Err(SessionError::InvalidHipUpload);
|
||||
}
|
||||
let (_, xml) = record.edited_hip_upload.take().ok_or(SessionError::InvalidHipUpload)?;
|
||||
let report_id = Uuid::new_v4();
|
||||
record.edited_hip_report = Some((report_id, Arc::from(xml)));
|
||||
Ok(HipUploadResult::Stored(report_id))
|
||||
}
|
||||
|
||||
pub fn edited_hip_report(&self, session_id: Uuid, report_id: Uuid) -> Result<Arc<str>, SessionError> {
|
||||
let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
record
|
||||
.edited_hip_report
|
||||
.as_ref()
|
||||
.filter(|(id, _)| *id == report_id)
|
||||
.map(|(_, xml)| Arc::clone(xml))
|
||||
.ok_or(SessionError::Unauthorized)
|
||||
}
|
||||
|
||||
pub fn store_hip_preview(&self, session_id: Uuid, xml: String) -> Result<Uuid, SessionError> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get_mut(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
if !matches!(record.status, SessionStatus::Active { .. }) {
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
let preview_id = Uuid::new_v4();
|
||||
record.hip_preview = Some((preview_id, Arc::from(xml)));
|
||||
Ok(preview_id)
|
||||
}
|
||||
|
||||
pub fn hip_preview_chunk(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
preview_id: Uuid,
|
||||
offset: usize,
|
||||
) -> Result<(String, bool), SessionError> {
|
||||
let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
let (_, xml) = record
|
||||
.hip_preview
|
||||
.as_ref()
|
||||
.filter(|(id, _)| *id == preview_id)
|
||||
.ok_or(SessionError::Unauthorized)?;
|
||||
if offset > xml.len() || !xml.is_char_boundary(offset) {
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
let mut end = (offset + HIP_PREVIEW_CHUNK_BYTES).min(xml.len());
|
||||
while !xml.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
Ok((xml[offset..end].to_owned(), end == xml.len()))
|
||||
}
|
||||
|
||||
pub fn store_successful_hip_report(&self, session_id: Uuid, xml: &str) -> Result<(), SessionError> {
|
||||
if xml.len() > 1024 * 1024 {
|
||||
return Err(SessionError::Unavailable);
|
||||
}
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get_mut(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
if !matches!(record.status, SessionStatus::Active { .. }) {
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
record.last_successful_hip_report = Some(Arc::from(xml));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn last_successful_hip_report(&self, session_id: Uuid) -> Result<Option<Arc<str>>, SessionError> {
|
||||
let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
Ok(record.last_successful_hip_report.as_ref().map(Arc::clone))
|
||||
}
|
||||
|
||||
pub fn clear_successful_hip_report(&self, session_id: Uuid) {
|
||||
if let Ok(mut sessions) = self.sessions.lock()
|
||||
&& let Some(record) = sessions.get_mut(&session_id)
|
||||
{
|
||||
record.last_successful_hip_report = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn disconnect_if_current(&self, session_id: Uuid, generation: u64) {
|
||||
let Ok(mut sessions) = self.sessions.lock() else {
|
||||
return;
|
||||
};
|
||||
if let Some(record) = sessions.get_mut(&session_id) {
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
if attempt.generation == generation {
|
||||
attempt.drain.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(SessionRecord {
|
||||
status: SessionStatus::Active {
|
||||
generation: current,
|
||||
@@ -582,14 +292,9 @@ impl SessionRegistry {
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut sessions| sessions.remove(&session_id))
|
||||
.and_then(|record| {
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
attempt.drain.cancel();
|
||||
}
|
||||
match record.status {
|
||||
SessionStatus::Active { connection, .. } => connection,
|
||||
SessionStatus::Pending { .. } => None,
|
||||
}
|
||||
.and_then(|record| match record.status {
|
||||
SessionStatus::Active { connection, .. } => connection,
|
||||
SessionStatus::Pending { .. } => None,
|
||||
});
|
||||
if let Some(connection) = connection {
|
||||
connection.close(gpapi::service::transport::CloseReason::Unauthorized);
|
||||
@@ -617,299 +322,10 @@ 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::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("fixture", None).unwrap();
|
||||
let session = credential.session_id();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(4);
|
||||
let first_control = ConnectionControl::new(Uuid::new_v4(), tx).0;
|
||||
let old_id = first_control.connection_id();
|
||||
registry.commit_attach(&first, first_control).unwrap();
|
||||
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||
let reservation = registry
|
||||
.reserve_connection(session, 1, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
let drain = reservation.drain();
|
||||
let cancel = reservation.cancellation();
|
||||
|
||||
let next = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _next_rx) = mpsc::channel(4);
|
||||
registry
|
||||
.commit_attach(&next, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||
.unwrap();
|
||||
assert!(cancel.is_cancelled());
|
||||
assert!(!drain.is_complete());
|
||||
assert!(
|
||||
registry
|
||||
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||
.is_err()
|
||||
);
|
||||
assert!(matches!(
|
||||
registry.commit_connection(session, 1, true, || panic!("stale start committed")),
|
||||
ServiceResult::Rejected(_)
|
||||
));
|
||||
drop(reservation);
|
||||
drain.wait().await;
|
||||
|
||||
let next_reservation = registry
|
||||
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
assert!(
|
||||
registry
|
||||
.stop_non_tunnel_attachment(session, 2, old_id)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(!next_reservation.cancellation().is_cancelled());
|
||||
registry.disconnect_if_current(session, 1);
|
||||
assert!(!next_reservation.cancellation().is_cancelled());
|
||||
registry.disconnect_if_current(session, 2);
|
||||
assert!(next_reservation.cancellation().is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scoped_stop_closes_attachment_to_delayed_starts_without_receipt_history() {
|
||||
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
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(4);
|
||||
let connection = ConnectionControl::new(Uuid::new_v4(), tx).0;
|
||||
let id = connection.connection_id();
|
||||
registry.commit_attach(&permit, connection).unwrap();
|
||||
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||
let reservation = registry
|
||||
.reserve_connection(session, 1, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
let drain = registry.stop_non_tunnel_attachment(session, 1, id).unwrap().unwrap();
|
||||
assert!(reservation.cancellation().is_cancelled());
|
||||
assert!(matches!(
|
||||
registry.commit_connection(session, 1, true, || panic!("closing start committed")),
|
||||
ServiceResult::Rejected(_)
|
||||
));
|
||||
assert!(!drain.is_complete());
|
||||
drop(reservation);
|
||||
drain.wait().await;
|
||||
assert!(
|
||||
registry
|
||||
.reserve_connection(session, 1, true, || panic!("closed attachment reserved"))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.reserve_connection(session, 1, false, || lifecycle.reserve_connect())
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tunnel_reservation_survives_attachment_loss_but_non_tunnel_revocation_cancels() {
|
||||
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
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(4);
|
||||
registry
|
||||
.commit_attach(&permit, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||
.unwrap();
|
||||
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||
let tunnel = registry
|
||||
.reserve_connection(session, 1, false, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
registry.disconnect_if_current(session, 1);
|
||||
assert!(!tunnel.cancellation().is_cancelled());
|
||||
assert_eq!(
|
||||
registry.commit_connection(session, 1, false, || ServiceResult::Accepted),
|
||||
ServiceResult::Accepted
|
||||
);
|
||||
drop(tunnel);
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _next_rx) = mpsc::channel(4);
|
||||
registry
|
||||
.commit_attach(&permit, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||
.unwrap();
|
||||
let session_work = registry
|
||||
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
registry.revoke(session);
|
||||
assert!(session_work.cancellation().is_cancelled());
|
||||
assert!(!session_work.drain().is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_retains_verified_desktop_user_across_reconnect() {
|
||||
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")
|
||||
.unwrap();
|
||||
assert_eq!(first.desktop_uid, Some(1000));
|
||||
registry.commit_attach(&first, control()).unwrap();
|
||||
|
||||
let reconnect = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
assert_eq!(reconnect.desktop_uid, Some(1000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edited_hip_report_is_session_bound_and_replaced_without_affecting_pinned_content() {
|
||||
fn upload(registry: &SessionRegistry, session_id: Uuid, xml: &str) -> Uuid {
|
||||
let mut upload_id = None;
|
||||
let mut offset = 0;
|
||||
while offset < xml.len() {
|
||||
let mut end = (offset + 8 * 1024).min(xml.len());
|
||||
while !xml.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
let complete = end == xml.len();
|
||||
match registry
|
||||
.append_edited_hip_report_chunk(session_id, upload_id, offset, xml[offset..end].into(), complete)
|
||||
.unwrap()
|
||||
{
|
||||
HipUploadResult::Progress(id) => upload_id = Some(id),
|
||||
HipUploadResult::Stored(id) => return id,
|
||||
}
|
||||
offset = end;
|
||||
}
|
||||
panic!("upload did not complete")
|
||||
}
|
||||
|
||||
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] {
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
registry.commit_attach(&permit, control()).unwrap();
|
||||
}
|
||||
|
||||
let valid = gphip::generate_report(&gphip::ReportInput {
|
||||
profile: gpapi::os_profile::OsProfile::builder(gpapi::os_profile::ClientOs::Linux).build(),
|
||||
context: gphip::ReportContext::Preview,
|
||||
})
|
||||
.unwrap();
|
||||
let first_id = upload(®istry, first_credential.session_id(), &valid);
|
||||
let pinned = registry
|
||||
.edited_hip_report(first_credential.session_id(), first_id)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
registry.edited_hip_report(second_credential.session_id(), first_id),
|
||||
Err(SessionError::Unauthorized)
|
||||
));
|
||||
let second_id = upload(®istry, first_credential.session_id(), &valid);
|
||||
assert!(matches!(
|
||||
registry.edited_hip_report(first_credential.session_id(), first_id),
|
||||
Err(SessionError::Unauthorized)
|
||||
));
|
||||
assert_eq!(
|
||||
&*registry
|
||||
.edited_hip_report(first_credential.session_id(), second_id)
|
||||
.unwrap(),
|
||||
valid
|
||||
);
|
||||
assert_eq!(&*pinned, valid);
|
||||
registry.revoke(first_credential.session_id());
|
||||
assert!(matches!(
|
||||
registry.edited_hip_report(first_credential.session_id(), second_id),
|
||||
Err(SessionError::Unauthorized)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submitted_report_changes_only_after_success_callback_and_is_session_bound() {
|
||||
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")
|
||||
.unwrap();
|
||||
registry.commit_attach(&permit, control()).unwrap();
|
||||
assert!(
|
||||
registry
|
||||
.last_successful_hip_report(credential.session_id())
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
registry
|
||||
.store_successful_hip_report(credential.session_id(), "first")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
registry
|
||||
.last_successful_hip_report(credential.session_id())
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some("first")
|
||||
);
|
||||
let preview_id = registry
|
||||
.store_hip_preview(credential.session_id(), "é".repeat(8193))
|
||||
.unwrap();
|
||||
let (first_chunk, complete) = registry
|
||||
.hip_preview_chunk(credential.session_id(), preview_id, 0)
|
||||
.unwrap();
|
||||
assert!(!complete);
|
||||
assert!(first_chunk.len() <= HIP_PREVIEW_CHUNK_BYTES);
|
||||
assert!(
|
||||
registry
|
||||
.hip_preview_chunk(credential.session_id(), preview_id, 1)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
registry
|
||||
.last_successful_hip_report(credential.session_id())
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some("first")
|
||||
);
|
||||
registry.clear_successful_hip_report(credential.session_id());
|
||||
assert!(
|
||||
registry
|
||||
.last_successful_hip_report(credential.session_id())
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnect_uses_generation_compare_and_swap() {
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4").unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
@@ -929,8 +345,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn failed_initial_handshake_only_revokes_its_own_reservation() {
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4").unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
@@ -943,8 +359,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn failed_reconnect_keeps_active_connection_authoritative() {
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4").unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
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,15 +1,7 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[path = "privileged_unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "macos.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(any(
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "macos"
|
||||
)))]
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::Context;
|
||||
use gpapi::process::collection::CollectionControl;
|
||||
use gpapi::session::{
|
||||
GatewaySessionSummary, MaintenanceState, SessionEndReason,
|
||||
non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions},
|
||||
};
|
||||
use log::warn;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{
|
||||
LifecycleEvent,
|
||||
runtime::{AttemptInput, stop_for_revoked_approval},
|
||||
};
|
||||
|
||||
/// Borrow the accepted ledger. The outer attempt owner retains identity/source
|
||||
/// resources and joins this runtime before draining the remaining members.
|
||||
pub(super) async fn run(
|
||||
input: &mut AttemptInput,
|
||||
source: Arc<openconnect::HipSource>,
|
||||
approval: &crate::hip_source::HipApproval,
|
||||
cancellation: CancellationToken,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
) -> anyhow::Result<SessionExit> {
|
||||
let request = &input.connection.request;
|
||||
let args = request.args();
|
||||
let resources = &input.connection.resources;
|
||||
let sessions = &mut input.connection.sessions;
|
||||
let network = resources
|
||||
.network
|
||||
.as_ref()
|
||||
.context("Physical network context is missing")?;
|
||||
let posture_enabled =
|
||||
request.plan().policy().collect_hip_data() && !matches!(args.hip_source(), gpapi::hip::HipSource::Disabled);
|
||||
let profile = resources.profile.clone();
|
||||
let initial = sessions
|
||||
.members()
|
||||
.iter()
|
||||
.map(|session| GatewaySessionSummary {
|
||||
gateway: session.gateway.clone(),
|
||||
mode: gpapi::session::SessionMode::NonTunnel,
|
||||
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
|
||||
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
|
||||
maintenance: MaintenanceState::Authenticated,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let (status, mut changed) = watch::channel(initial);
|
||||
let registry = input.registry.clone();
|
||||
let session_id = input.session_id;
|
||||
let validation_network = network.clone();
|
||||
let validation_detection = request.plan().internal_detection().cloned();
|
||||
let callbacks = SessionCallbacks {
|
||||
validate_network: Arc::new(move |cancel| {
|
||||
let network = validation_network.clone();
|
||||
let detection = validation_detection.clone();
|
||||
Box::pin(async move { network.validate_internal(detection.as_ref(), &cancel).await })
|
||||
}),
|
||||
produce_report: Arc::new(move |request, control| {
|
||||
control.check()?;
|
||||
let context = gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
};
|
||||
if !posture_enabled {
|
||||
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context,
|
||||
})
|
||||
.map_err(std::io::Error::other);
|
||||
}
|
||||
source.collect(
|
||||
&openconnect::HipRequest {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
client_version: profile.client_version().into(),
|
||||
client_os: profile.client_os().as_str().into(),
|
||||
os_version: profile.os_version().into(),
|
||||
host_id: Some(profile.host_id().into()),
|
||||
local_hostname: Some(profile.computer().into()),
|
||||
},
|
||||
&|| control.check(),
|
||||
)
|
||||
}),
|
||||
report_submitted: Arc::new(move |_, xml| {
|
||||
if let Some(session_id) = session_id {
|
||||
if let Err(error) = registry.store_successful_hip_report(session_id, xml) {
|
||||
warn!("Could not retain submitted HIP report: {error}");
|
||||
}
|
||||
}
|
||||
}),
|
||||
status_changed: Arc::new(move |summary| {
|
||||
status.send_modify(|members| {
|
||||
if let Some(member) = members
|
||||
.iter_mut()
|
||||
.find(|member| member.gateway.server() == summary.gateway.server())
|
||||
{
|
||||
*member = summary;
|
||||
}
|
||||
});
|
||||
}),
|
||||
};
|
||||
let monitor_cancel = cancellation.child_token();
|
||||
let monitor_token = monitor_cancel.clone();
|
||||
let network = network.clone();
|
||||
let detection = request.plan().internal_detection().cloned();
|
||||
let (network_changed, network_signal) = tokio::sync::oneshot::channel();
|
||||
let monitor = tokio::spawn(async move {
|
||||
match network.wait_for_change(detection, monitor_token).await {
|
||||
Ok(false) => {}
|
||||
Ok(true) => {
|
||||
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("Physical network inspection failed: {error}");
|
||||
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut approval_revoked = false;
|
||||
let result = {
|
||||
let lifecycle_cancel = cancellation.clone();
|
||||
let maintenance = maintain_non_tunnel_sessions(
|
||||
sessions,
|
||||
request.plan().policy(),
|
||||
callbacks,
|
||||
lifecycle_cancel,
|
||||
async move { network_signal.await.unwrap_or(SessionEndReason::NetworkChanged) },
|
||||
);
|
||||
tokio::pin!(maintenance);
|
||||
let mut approval_poll = tokio::time::interval(Duration::from_secs(1));
|
||||
let mut publish = true;
|
||||
let result = loop {
|
||||
if publish && !cancellation.is_cancelled() {
|
||||
let members = changed.borrow_and_update().clone();
|
||||
let _ = events
|
||||
.send(LifecycleEvent::MembersChanged {
|
||||
attempt: input.attempt,
|
||||
members,
|
||||
failures: request.plan().failures().to_vec(),
|
||||
})
|
||||
.await;
|
||||
publish = false;
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut maintenance => break result,
|
||||
_ = approval_poll.tick() => if !approval.approval_is_valid() {
|
||||
approval_revoked = true;
|
||||
stop_for_revoked_approval(&input.lifecycle, &cancellation);
|
||||
},
|
||||
result = changed.changed() => { if result.is_ok() { publish = true; } },
|
||||
}
|
||||
};
|
||||
// Maintenance can invalidate every member and finish in the same poll.
|
||||
// Forward that last snapshot before monitor/remote cleanup, even when the
|
||||
// completed maintenance branch won over the watch notification.
|
||||
if !cancellation.is_cancelled() {
|
||||
let members = changed.borrow_and_update().clone();
|
||||
let _ = events
|
||||
.send(LifecycleEvent::MembersChanged {
|
||||
attempt: input.attempt,
|
||||
members,
|
||||
failures: request.plan().failures().to_vec(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
result
|
||||
};
|
||||
monitor_cancel.cancel();
|
||||
monitor.await.context("Network monitor worker failed")?;
|
||||
if approval_revoked {
|
||||
let _ = events
|
||||
.send(LifecycleEvent::Failed {
|
||||
attempt: input.attempt,
|
||||
reason: "HIP script approval was revoked".into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
// resources and approval remain owned until maintenance/logout and monitor
|
||||
// inspection are drained. Deliberate disconnect wins throughout cleanup.
|
||||
if cancellation.is_cancelled() {
|
||||
Ok(SessionExit::Disconnected)
|
||||
} else {
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use gpapi::{
|
||||
gateway::Gateway,
|
||||
gp_params::GpParams,
|
||||
service::{
|
||||
transport::ServiceResult,
|
||||
vpn_state::{ConnectInfo, VpnState},
|
||||
},
|
||||
session::{ClientAddresses, GatewayAuthentication, GatewaySession, GatewaySessions, transport::GatewayTransport},
|
||||
};
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
hash::MessageDigest,
|
||||
pkey::PKey,
|
||||
rsa::Rsa,
|
||||
ssl::{SslAcceptor, SslMethod},
|
||||
x509::{X509, X509NameBuilder},
|
||||
};
|
||||
use tokio::sync::{oneshot, watch};
|
||||
|
||||
use super::{LifecycleEvent, PreparedConnection, VpnTask, test_connect_request};
|
||||
|
||||
fn tls_acceptor() -> SslAcceptor {
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
name.append_entry_by_text("CN", "localhost").unwrap();
|
||||
let name = name.build();
|
||||
let mut cert = X509::builder().unwrap();
|
||||
cert.set_version(2).unwrap();
|
||||
cert.set_subject_name(&name).unwrap();
|
||||
cert.set_issuer_name(&name).unwrap();
|
||||
cert.set_pubkey(&key).unwrap();
|
||||
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
|
||||
cert.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
cert.sign(&key, MessageDigest::sha256()).unwrap();
|
||||
let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||
acceptor.set_private_key(&key).unwrap();
|
||||
acceptor.set_certificate(&cert.build()).unwrap();
|
||||
acceptor.check_private_key().unwrap();
|
||||
acceptor.build()
|
||||
}
|
||||
|
||||
/// Exercise the real HTTPS logout transport without any production network,
|
||||
/// host collectors, or user identity files. The response gate proves admission
|
||||
/// stays owned until the server request finishes.
|
||||
#[tokio::test]
|
||||
async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let endpoint = listener.local_addr().unwrap();
|
||||
let server_name = format!("https://{endpoint}");
|
||||
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::for_tests(uuid::Uuid::new_v4()));
|
||||
let credential = registry.issue("fixture", None).unwrap();
|
||||
let session_id = credential.session_id();
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), session_id, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = tokio::sync::mpsc::channel(4);
|
||||
let control = crate::ws_connection::ConnectionControl::new(uuid::Uuid::new_v4(), tx).0;
|
||||
let connection_id = control.connection_id();
|
||||
registry.commit_attach(&permit, control).unwrap();
|
||||
let fixture = test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![]));
|
||||
let mut member = fixture.plan().members()[0].clone();
|
||||
member.authentication =
|
||||
GatewayAuthentication::new("authcookie=fixture&user=fixture".into(), "internal".into()).unwrap();
|
||||
let plan = gpapi::session::ConnectionPlan::new(vec![member], vec![], fixture.plan().policy()).unwrap();
|
||||
let request = gpapi::service::request::ConnectRequest::new(fixture.info().clone(), plan);
|
||||
let mut prepared = PreparedConnection::lifecycle_fixture(request);
|
||||
let mut params = GpParams::builder(prepared.resources.profile.clone());
|
||||
params.ignore_tls_errors(true);
|
||||
prepared.sessions = GatewaySessions::new(vec![GatewaySession {
|
||||
gateway,
|
||||
transport: GatewayTransport::new(
|
||||
&server_name,
|
||||
prepared.request.plan().members()[0].authentication.clone(),
|
||||
¶ms.build(),
|
||||
prepared.request.plan().members()[0].binding.as_ref(),
|
||||
)
|
||||
.unwrap(),
|
||||
addresses: ClientAddresses::default(),
|
||||
}]);
|
||||
let acceptor = tls_acceptor();
|
||||
let (arrived, arrival) = oneshot::channel();
|
||||
let (release, response_gate) = oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (socket, _) = tokio::time::timeout(Duration::from_secs(3), listener.accept())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let socket = socket.into_std().unwrap();
|
||||
socket.set_nonblocking(false).unwrap();
|
||||
socket.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
socket.set_write_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let request = tokio::task::spawn_blocking(move || {
|
||||
let mut stream = acceptor.accept(socket).unwrap();
|
||||
let mut bytes = Vec::new();
|
||||
let (headers_end, body_len) = loop {
|
||||
let mut chunk = [0; 1024];
|
||||
let count = stream.read(&mut chunk).unwrap();
|
||||
assert_ne!(count, 0);
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
if let Some(position) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
|
||||
let headers = std::str::from_utf8(&bytes[..position]).unwrap();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let (key, value) = line.split_once(':')?;
|
||||
key
|
||||
.eq_ignore_ascii_case("content-length")
|
||||
.then(|| value.trim().parse::<usize>().unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
break (position + 4, length);
|
||||
}
|
||||
};
|
||||
while bytes.len() < headers_end + body_len {
|
||||
let mut chunk = [0; 1024];
|
||||
let count = stream.read(&mut chunk).unwrap();
|
||||
assert_ne!(count, 0);
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
}
|
||||
arrived.send(()).unwrap();
|
||||
response_gate.blocking_recv().unwrap();
|
||||
let body = "<response status=\"success\"/>";
|
||||
write!(
|
||||
stream,
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.unwrap();
|
||||
stream.flush().unwrap();
|
||||
String::from_utf8(bytes).unwrap()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// A single accepted authentication must produce a single logout.
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
request
|
||||
});
|
||||
let (state, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let (mut task, lifecycle) = VpnTask::new(state, false, registry.clone());
|
||||
let reservation = registry
|
||||
.reserve_connection(session_id, 1, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
registry.commit_connection(session_id, 1, true, || reservation.commit(
|
||||
prepared,
|
||||
None,
|
||||
None,
|
||||
Some(session_id)
|
||||
)),
|
||||
ServiceResult::Accepted
|
||||
);
|
||||
let drain = registry
|
||||
.stop_non_tunnel_attachment(session_id, 1, connection_id)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let drain_waiter = tokio::spawn(async move {
|
||||
drain.wait().await;
|
||||
});
|
||||
let start = task.events.recv().await.unwrap();
|
||||
assert!(matches!(&start, LifecycleEvent::Start { .. }));
|
||||
task.handle_event(start).await;
|
||||
tokio::time::timeout(Duration::from_secs(3), arrival)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(lifecycle.has_attempt(0));
|
||||
assert!(!drain_waiter.is_finished());
|
||||
assert!(lifecycle.reserve_connect().is_err());
|
||||
assert!(!task.active.as_ref().unwrap().task.is_finished());
|
||||
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
|
||||
release.send(()).unwrap();
|
||||
while task.active.is_some() {
|
||||
let event = tokio::time::timeout(Duration::from_secs(3), task.events.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
task.handle_event(event).await;
|
||||
}
|
||||
assert!(!lifecycle.has_attempt(0));
|
||||
drain_waiter.await.unwrap();
|
||||
assert!(lifecycle.reserve_connect().is_ok());
|
||||
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
|
||||
let request = server.await.unwrap();
|
||||
assert!(request.starts_with("POST /ssl-vpn/logout.esp "));
|
||||
let form = request.split_once("\r\n\r\n").unwrap().1;
|
||||
let fields = url_form(form);
|
||||
assert_eq!(fields.get("user").map(String::as_str), Some("fixture"));
|
||||
assert_eq!(fields.get("computer").map(String::as_str), Some("fixture"));
|
||||
assert_eq!(fields.get("clientos").map(String::as_str), Some("Linux"));
|
||||
}
|
||||
|
||||
fn url_form(form: &str) -> std::collections::HashMap<String, String> {
|
||||
form
|
||||
.split('&')
|
||||
.map(|field| {
|
||||
let (key, value) = field.split_once('=').unwrap();
|
||||
(key.to_owned(), value.to_owned())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::Context;
|
||||
use gpapi::{
|
||||
gp_params::GpParams,
|
||||
os_profile::OsProfile,
|
||||
process::collection::{CollectionBudget, CollectionControl},
|
||||
service::request::ConnectRequest,
|
||||
session::{GatewaySession, GatewaySessions, network::PhysicalNetwork, transport::GatewayTransport},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(crate) struct PreparedConnection {
|
||||
pub(super) request: ConnectRequest,
|
||||
pub(super) resources: Arc<ConnectionResources>,
|
||||
pub(super) sessions: GatewaySessions,
|
||||
}
|
||||
|
||||
pub(super) struct ConnectionResources {
|
||||
pub profile: OsProfile,
|
||||
pub identity: Option<gpapi::utils::request::ClientIdentity>,
|
||||
pub identity_files: Option<gpapi::utils::request::ClientIdentityFiles>,
|
||||
pub network: Option<PhysicalNetwork>,
|
||||
}
|
||||
|
||||
/// Preparation sends no authenticated gateway requests. Rejection leaves the
|
||||
/// authentication owner responsible for logout; only queued admission transfers
|
||||
/// the complete ledger and its retained identity resources to the service.
|
||||
pub(crate) async fn prepare_connection(
|
||||
request: ConnectRequest,
|
||||
brokered_macos: bool,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<PreparedConnection> {
|
||||
let args = request.args();
|
||||
let non_tunnel = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel);
|
||||
anyhow::ensure!(
|
||||
non_tunnel || request.plan().members().len() == 1,
|
||||
"Only one selected tunnel gateway can execute"
|
||||
);
|
||||
for member in request.plan().members() {
|
||||
if non_tunnel {
|
||||
let binding = member.binding.as_ref().context("Internal gateway binding is missing")?;
|
||||
anyhow::ensure!(
|
||||
!args.disable_ipv6() || (binding.endpoint().is_ipv4() && binding.addresses().ipv6.is_none()),
|
||||
"IPv6 gateway transport or identity is disabled"
|
||||
);
|
||||
}
|
||||
}
|
||||
let setup_request = request.clone();
|
||||
let setup_cancel = cancellation.clone();
|
||||
let resources = tokio::task::spawn_blocking(move || {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let check = || {
|
||||
if setup_cancel.is_cancelled() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Connection preparation cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
check()?;
|
||||
let args = setup_request.args();
|
||||
let identity = super::prepare_identity(args, brokered_macos || non_tunnel)?;
|
||||
let directory = brokered_macos.then(|| std::path::Path::new("/var/run/com.yuezk.gpgui"));
|
||||
let identity_files = identity
|
||||
.as_ref()
|
||||
.map(|identity| identity.write_files(directory))
|
||||
.transpose()?;
|
||||
let host = args.host_identity().context("Authenticated host identity is missing")?;
|
||||
let profile = crate::hip_source::profile(
|
||||
host,
|
||||
args.os().context("Authenticated client OS is missing")?,
|
||||
args.client_version(),
|
||||
args.os_version(),
|
||||
args.host_id(),
|
||||
args.local_hostname(),
|
||||
&check,
|
||||
)?;
|
||||
let network = if non_tunnel {
|
||||
Some(PhysicalNetwork::capture(&check)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
check()?;
|
||||
Ok::<_, anyhow::Error>(Arc::new(ConnectionResources {
|
||||
profile,
|
||||
identity,
|
||||
identity_files,
|
||||
network,
|
||||
}))
|
||||
})
|
||||
.await??;
|
||||
let args = request.args();
|
||||
let mut builder = GpParams::builder(resources.profile.clone());
|
||||
builder
|
||||
.ignore_tls_errors(args.ignore_tls_errors())
|
||||
.client_identity(resources.identity.clone());
|
||||
let params = builder.build();
|
||||
let mut sessions = Vec::new();
|
||||
for member in request.plan().members() {
|
||||
let binding = if non_tunnel {
|
||||
Some(member.binding.as_ref().context("Internal gateway binding is missing")?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(network) = &resources.network {
|
||||
network
|
||||
.validate_internal_binding(
|
||||
binding.context("Internal gateway binding is missing")?,
|
||||
request.plan().internal_detection(),
|
||||
&cancellation,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let transport = GatewayTransport::new(member.gateway.server(), member.authentication.clone(), ¶ms, binding)?;
|
||||
sessions.push(GatewaySession {
|
||||
gateway: member.gateway.clone(),
|
||||
transport,
|
||||
addresses: binding.map(|binding| binding.addresses()).unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
if let Some(network) = &resources.network {
|
||||
network.ensure_current(&cancellation).await?;
|
||||
}
|
||||
Ok(PreparedConnection {
|
||||
request,
|
||||
resources,
|
||||
sessions: GatewaySessions::new(sessions),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl PreparedConnection {
|
||||
/// Lifecycle-only fixtures own no issued server sessions. Protocol ownership
|
||||
/// checks use actual gateway transports rather than this actor-state fixture.
|
||||
pub(crate) fn lifecycle_fixture(request: ConnectRequest) -> Self {
|
||||
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Linux)
|
||||
.host_identity(gpapi::os_profile::HostIdentity::from_parts(
|
||||
"fixture".into(),
|
||||
"fixture-host".into(),
|
||||
"fixture-serial".into(),
|
||||
"02:00:00:00:00:01".into(),
|
||||
))
|
||||
.build();
|
||||
Self {
|
||||
request,
|
||||
resources: Arc::new(ConnectionResources {
|
||||
profile,
|
||||
identity: None,
|
||||
identity_files: None,
|
||||
network: None,
|
||||
}),
|
||||
sessions: GatewaySessions::new(vec![]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo};
|
||||
|
||||
#[tokio::test]
|
||||
async fn brokered_macos_and_non_tunnel_identity_reject_path_handoff() {
|
||||
for (brokered_macos, non_tunnel) in [(true, false), (false, true), (true, true)] {
|
||||
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
|
||||
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||
.with_certificate(Some("/identity.pem".into()));
|
||||
let mut wire = serde_json::to_value(request).unwrap();
|
||||
if non_tunnel {
|
||||
wire["plan"]["members"][0]["gateway"]["kind"] = serde_json::json!("internal");
|
||||
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
||||
}
|
||||
let request = serde_json::from_value(wire).unwrap();
|
||||
let error = prepare_connection(request, brokered_macos, CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.to_string(), "Client identity must be a protected snapshot");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_ipv6_rejects_ipv6_report_identity_before_setup() {
|
||||
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
|
||||
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||
.with_disable_ipv6(true);
|
||||
let mut wire = serde_json::to_value(request).unwrap();
|
||||
wire["plan"]["members"][0]["gateway"]["kind"] = serde_json::json!("internal");
|
||||
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
||||
wire["plan"]["members"][0]["binding"]["addresses"]["ipv6"] = serde_json::json!("2001:db8::5");
|
||||
let request: ConnectRequest = serde_json::from_value(wire).unwrap();
|
||||
// The fixture has no host identity or usable physical interface. Policy
|
||||
// rejection must happen before those collectors or transport setup run.
|
||||
let error = prepare_connection(request, false, CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.to_string(), "IPv6 gateway transport or identity is disabled");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_tunnel_preparation_needs_no_physical_binding_or_resolver() {
|
||||
let gateway = Gateway::new("fixture".into(), "does-not-resolve.invalid".into());
|
||||
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Linux)
|
||||
.host_identity(gpapi::os_profile::HostIdentity::from_parts(
|
||||
"fixture".into(),
|
||||
"fixture-host".into(),
|
||||
"fixture-serial".into(),
|
||||
"02:00:00:00:00:01".into(),
|
||||
))
|
||||
.build();
|
||||
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||
.with_os_profile(&profile)
|
||||
.with_disable_ipv6(true);
|
||||
let mut wire = serde_json::to_value(request).unwrap();
|
||||
wire["plan"]["members"][0]["binding"] = serde_json::Value::Null;
|
||||
let request: ConnectRequest = serde_json::from_value(wire).unwrap();
|
||||
let prepared = prepare_connection(request, false, CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(prepared.resources.network.is_none());
|
||||
assert_eq!(prepared.sessions.members().len(), 1);
|
||||
assert!(prepared.sessions.members()[0].addresses.ipv4.is_none());
|
||||
assert!(prepared.sessions.members()[0].addresses.ipv6.is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
process::collection::{CollectionBudget, CollectionControl},
|
||||
service::request::ConnectRequest,
|
||||
session::SessionMode,
|
||||
};
|
||||
use log::warn;
|
||||
use openconnect::Vpn;
|
||||
use tokio::{sync::mpsc, task::JoinHandle};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{LifecycleEvent, LifecycleHandle, PreparedConnection, preparation::ConnectionResources};
|
||||
|
||||
pub(super) struct AttemptInput {
|
||||
pub attempt: u64,
|
||||
pub connection: PreparedConnection,
|
||||
pub desktop_uid: Option<u32>,
|
||||
pub edited_report: Option<Arc<str>>,
|
||||
pub session_id: Option<Uuid>,
|
||||
pub brokered_macos: bool,
|
||||
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
pub lifecycle: LifecycleHandle,
|
||||
}
|
||||
|
||||
struct TunnelInput {
|
||||
request: ConnectRequest,
|
||||
resources: Arc<ConnectionResources>,
|
||||
source: Arc<openconnect::HipSource>,
|
||||
session_id: Option<Uuid>,
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
}
|
||||
|
||||
struct PreparedTunnel {
|
||||
vpn: Arc<Vpn>,
|
||||
}
|
||||
|
||||
/// The accepted attempt owns cleanup through fallible setup. Non-tunnel workers
|
||||
/// borrow that ledger; a native tunnel takes its cleanup ownership when started.
|
||||
/// Cancellation joins execution before draining any remaining issued sessions.
|
||||
pub(super) fn spawn(
|
||||
mut input: AttemptInput,
|
||||
cancellation: CancellationToken,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
) -> JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
let attempt = input.attempt;
|
||||
let non_tunnel = input
|
||||
.connection
|
||||
.request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == SessionMode::NonTunnel);
|
||||
let mut failure = None;
|
||||
let mut approval = None;
|
||||
if !cancellation.is_cancelled() {
|
||||
let request = input.connection.request.clone();
|
||||
let resources = input.connection.resources.clone();
|
||||
let desktop_uid = input.desktop_uid;
|
||||
let brokered = input.brokered_macos;
|
||||
let edited = input.edited_report.clone();
|
||||
let setup_cancel = cancellation.clone();
|
||||
let execution = tokio::task::spawn_blocking(move || {
|
||||
prepare_execution(request, resources, desktop_uid, brokered, edited, &setup_cancel)
|
||||
})
|
||||
.await;
|
||||
match execution {
|
||||
Ok(Ok(execution)) => {
|
||||
let (source, guard) = execution.into_parts();
|
||||
approval = Some(guard);
|
||||
let source = Arc::new(source);
|
||||
let guard = approval.as_ref().expect("execution approval is retained");
|
||||
if input
|
||||
.connection
|
||||
.request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == SessionMode::NonTunnel)
|
||||
{
|
||||
match super::non_tunnel::run(&mut input, source, guard, cancellation.clone(), events.clone()).await {
|
||||
Ok(gpapi::session::non_tunnel::SessionExit::Disconnected) => {}
|
||||
Ok(gpapi::session::non_tunnel::SessionExit::Failed(reason)) => {
|
||||
let message = match reason {
|
||||
gpapi::session::SessionEndReason::InvalidCookie => {
|
||||
"Internal gateway authentication expired; connect again"
|
||||
}
|
||||
gpapi::session::SessionEndReason::NetworkChanged => {
|
||||
"Physical network changed or could not be verified; connect again"
|
||||
}
|
||||
gpapi::session::SessionEndReason::AllMembersFailed => {
|
||||
"All internal gateway sessions failed; connect again"
|
||||
}
|
||||
gpapi::session::SessionEndReason::AuthorizationRevoked => "HIP execution authorization was revoked",
|
||||
};
|
||||
failure = Some(message.into());
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("Non-tunnel maintenance failed: {error:#}");
|
||||
failure = Some("Internal session maintenance failed".into());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let tunnel_input = TunnelInput {
|
||||
request: input.connection.request.clone(),
|
||||
resources: input.connection.resources.clone(),
|
||||
source,
|
||||
session_id: input.session_id,
|
||||
registry: input.registry.clone(),
|
||||
};
|
||||
let setup_cancel = cancellation.clone();
|
||||
let prepared = tokio::task::spawn_blocking(move || prepare_tunnel(tunnel_input, &setup_cancel)).await;
|
||||
match prepared {
|
||||
Ok(Ok(prepared)) => {
|
||||
run_tunnel(
|
||||
attempt,
|
||||
&prepared,
|
||||
guard,
|
||||
&input.lifecycle,
|
||||
&mut input.connection.sessions,
|
||||
cancellation.clone(),
|
||||
events.clone(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
Ok(Err(error)) => warn!("Failed to prepare tunnel: {error:#}"),
|
||||
Err(error) => warn!("Tunnel setup worker failed: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
warn!("Failed to prepare HIP execution: {error:#}");
|
||||
failure = Some("HIP execution could not be prepared".into());
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("HIP setup worker failed: {error}");
|
||||
failure = Some("HIP setup worker failed".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
input.connection.sessions.logout().await;
|
||||
// Identity and approval remain alive through worker drain and logout. Ended
|
||||
// only releases admission after the actor also joins this task.
|
||||
drop(approval);
|
||||
if non_tunnel && !cancellation.is_cancelled() {
|
||||
if let Some(reason) = failure {
|
||||
let _ = events.send(LifecycleEvent::Failed { attempt, reason }).await;
|
||||
}
|
||||
}
|
||||
let _ = events.send(LifecycleEvent::Ended { attempt }).await;
|
||||
})
|
||||
}
|
||||
|
||||
fn prepare_execution(
|
||||
request: ConnectRequest,
|
||||
resources: Arc<ConnectionResources>,
|
||||
desktop_uid: Option<u32>,
|
||||
brokered: bool,
|
||||
edited: Option<Arc<str>>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<crate::hip_source::HipExecution> {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"HIP setup cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
check()?;
|
||||
let args = request.args();
|
||||
let pure_non_tunnel = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == SessionMode::NonTunnel);
|
||||
let disabled = pure_non_tunnel && !request.plan().policy().collect_hip_data();
|
||||
let source = if disabled {
|
||||
&gpapi::hip::HipSource::Disabled
|
||||
} else {
|
||||
args.hip_source()
|
||||
};
|
||||
let execution = crate::hip_source::resolve(source, desktop_uid, brokered, edited, Some(resources.profile.clone()))?;
|
||||
check()?;
|
||||
Ok(execution)
|
||||
}
|
||||
|
||||
fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyhow::Result<PreparedTunnel> {
|
||||
let args = input.request.args();
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Tunnel setup cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
check()?;
|
||||
ensure!(
|
||||
input.request.plan().members().len() == 1
|
||||
&& input.request.plan().members()[0].authentication.mode() == SessionMode::Tunnel,
|
||||
"Tunnel execution requires one selected tunnel gateway"
|
||||
);
|
||||
let member = &input.request.plan().members()[0];
|
||||
let identity_files = &input.resources.identity_files;
|
||||
let vpn = Arc::new(
|
||||
crate::vpn_script::builder(member.gateway.server(), member.authentication.cookie(), args)?
|
||||
.user_agent(args.user_agent())
|
||||
.os(args.openconnect_os())
|
||||
.os_version(args.os_version())
|
||||
.client_version(args.client_version())
|
||||
.host_id(args.host_id())
|
||||
.certificate(identity_files.as_ref().map(|files| files.certificate().to_owned()))
|
||||
.sslkey(identity_files.as_ref().and_then(|files| files.key()).map(str::to_owned))
|
||||
.key_password(
|
||||
input
|
||||
.resources
|
||||
.identity
|
||||
.as_ref()
|
||||
.and_then(|identity| identity.key_password())
|
||||
.map(str::to_owned),
|
||||
)
|
||||
.hip_source(input.source)
|
||||
.reconnect_timeout(args.reconnect_timeout())
|
||||
.mtu(args.mtu())
|
||||
.disable_ipv6(args.disable_ipv6())
|
||||
.no_dtls(args.no_dtls())
|
||||
.local_hostname(args.local_hostname())
|
||||
.dpd_interval(args.force_dpd())
|
||||
.no_xmlpost(args.no_xmlpost())
|
||||
.build()
|
||||
.context("Failed to create tunnel worker")?,
|
||||
);
|
||||
check()?;
|
||||
if let Some(session_id) = input.session_id {
|
||||
let registry = input.registry;
|
||||
vpn.set_hip_report_callback(move |xml| {
|
||||
if let Err(error) = registry.store_successful_hip_report(session_id, xml) {
|
||||
warn!("Could not retain submitted HIP report: {error}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(PreparedTunnel { vpn })
|
||||
}
|
||||
|
||||
async fn run_tunnel(
|
||||
attempt: u64,
|
||||
prepared: &PreparedTunnel,
|
||||
approval: &crate::hip_source::HipApproval,
|
||||
lifecycle: &LifecycleHandle,
|
||||
sessions: &mut gpapi::session::GatewaySessions,
|
||||
cancellation: CancellationToken,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
) {
|
||||
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.
|
||||
// Service admission permits exactly one tunnel member.
|
||||
std::mem::take(sessions).relinquish();
|
||||
let worker = tokio::task::spawn_blocking(move || {
|
||||
vpn.connect(move |session| {
|
||||
let _ = events.blocking_send(LifecycleEvent::Established { attempt, session });
|
||||
})
|
||||
});
|
||||
tokio::pin!(worker);
|
||||
let mut approval_poll = tokio::time::interval(Duration::from_secs(1));
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => { prepared.vpn.disconnect(); break (&mut worker).await; },
|
||||
result = &mut worker => break result,
|
||||
_ = approval_poll.tick() => if !approval.approval_is_valid() {
|
||||
stop_for_revoked_approval(lifecycle, &cancellation);
|
||||
prepared.vpn.disconnect();
|
||||
break (&mut worker).await;
|
||||
},
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(0 | -4) => {}
|
||||
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) {
|
||||
let result = lifecycle.request_disconnect();
|
||||
if !matches!(result, gpapi::service::transport::ServiceResult::Accepted) {
|
||||
warn!("Could not enqueue approval revocation stop: {result:?}");
|
||||
}
|
||||
cancellation.cancel();
|
||||
}
|
||||
@@ -1,19 +1,11 @@
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use std::{collections::HashSet, sync::Arc, time::Duration};
|
||||
|
||||
use axum::extract::ws::{CloseFrame, Message, Utf8Bytes, WebSocket};
|
||||
use futures::StreamExt;
|
||||
use gpapi::service::transport::{
|
||||
ClientMessage, ClientPrelude, CloseReason, HandshakeRejection, NoiseResponder, NoiseTransport, ServerMessage,
|
||||
ServerPrelude, ServiceErrorCode, ServiceResult,
|
||||
ServerPrelude, ServiceResult,
|
||||
};
|
||||
use gpapi::{hip::HipSource, service::request::WsRequest};
|
||||
use log::{info, warn};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio::time::Instant;
|
||||
@@ -41,9 +33,6 @@ 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 {
|
||||
@@ -54,9 +43,6 @@ 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,
|
||||
)
|
||||
@@ -71,45 +57,11 @@ impl ConnectionControl {
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.tx.is_closed() || self.close_tx.borrow().is_some()
|
||||
self.tx.is_closed()
|
||||
}
|
||||
|
||||
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()
|
||||
let _ = self.close_tx.send(Some(reason));
|
||||
}
|
||||
|
||||
pub async fn send_reply(&self, id: Uuid, result: ServiceResult) {
|
||||
@@ -143,14 +95,12 @@ 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 {
|
||||
@@ -198,7 +148,6 @@ impl WsConnection {
|
||||
&ctx,
|
||||
&control,
|
||||
permit.session_id,
|
||||
permit.desktop_uid,
|
||||
generation,
|
||||
&mut pending_requests,
|
||||
).await.is_err() {
|
||||
@@ -230,26 +179,12 @@ 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ctx
|
||||
.remove_connection(control.connection_id(), permit.session_id, generation)
|
||||
.await;
|
||||
ctx
|
||||
.hip_previews
|
||||
.cancel_connection(permit.session_id, control.connection_id())
|
||||
.await;
|
||||
info!("GUI connection {} closed", control.connection_id());
|
||||
}
|
||||
}
|
||||
@@ -280,17 +215,6 @@ async fn establish(
|
||||
.await?;
|
||||
return Err(CloseReason::VersionMismatch);
|
||||
}
|
||||
if prelude.hip_protocol_version != gpapi::service::transport::HIP_PROTOCOL_VERSION {
|
||||
send_server_prelude(
|
||||
socket,
|
||||
ServerPrelude::Rejected(HandshakeRejection::HipProtocolMismatch {
|
||||
client: prelude.hip_protocol_version,
|
||||
service: gpapi::service::transport::HIP_PROTOCOL_VERSION,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
return Err(CloseReason::VersionMismatch);
|
||||
}
|
||||
|
||||
let permit = match ctx.registry().begin_handshake(
|
||||
prelude.service_instance_id,
|
||||
@@ -384,7 +308,6 @@ async fn handle_client_message(
|
||||
ctx: &Arc<WsServerContext>,
|
||||
control: &ConnectionControl,
|
||||
session_id: Uuid,
|
||||
desktop_uid: Option<u32>,
|
||||
generation: u64,
|
||||
pending_requests: &mut HashSet<Uuid>,
|
||||
) -> Result<(), ()> {
|
||||
@@ -400,183 +323,10 @@ 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() {
|
||||
ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP upload ID")
|
||||
} else {
|
||||
match ctx.registry().append_edited_hip_report_chunk(
|
||||
session_id,
|
||||
upload_id,
|
||||
report.offset,
|
||||
report.xml,
|
||||
report.complete,
|
||||
) {
|
||||
Ok(crate::session_registry::HipUploadResult::Progress(upload_id)) => ServiceResult::HipUploadProgress {
|
||||
upload_id: upload_id.to_string(),
|
||||
},
|
||||
Ok(crate::session_registry::HipUploadResult::Stored(report_id)) => ServiceResult::StoredHipReport {
|
||||
report_id: report_id.to_string(),
|
||||
},
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report upload"),
|
||||
}
|
||||
};
|
||||
if control.send(ConnectionCommand::Reply { id, result }).is_err() {
|
||||
pending_requests.remove(&id);
|
||||
control.close(CloseReason::InternalError);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::ReadHipPreviewChunk(chunk) = request {
|
||||
let result = Uuid::parse_str(&chunk.preview_id)
|
||||
.ok()
|
||||
.and_then(|preview_id| {
|
||||
ctx
|
||||
.registry()
|
||||
.hip_preview_chunk(session_id, preview_id, chunk.offset)
|
||||
.ok()
|
||||
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: chunk.offset,
|
||||
xml,
|
||||
complete,
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP preview is unavailable"));
|
||||
control.send(ConnectionCommand::Reply { id, result }).map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::GetLastSubmittedHipReport = request {
|
||||
let result = match ctx.registry().last_successful_hip_report(session_id) {
|
||||
Ok(Some(report)) => match ctx.registry().store_hip_preview(session_id, report.to_string()) {
|
||||
Ok(preview_id) => match ctx.registry().hip_preview_chunk(session_id, preview_id, 0) {
|
||||
Ok((xml, complete)) => ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
},
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"),
|
||||
},
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"),
|
||||
},
|
||||
Ok(None) => ServiceResult::NoSubmittedHipReport,
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Session is unavailable"),
|
||||
};
|
||||
control.send(ConnectionCommand::Reply { id, result }).map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::GetHipApprovalStatus { approval_id } = request {
|
||||
let result = if let Some(uid) = desktop_uid.filter(|uid| *uid != 0) {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
match gpservice::hip_approval::status(&approval_id, uid) {
|
||||
Ok(status) => ServiceResult::HipApprovalStatus(status),
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP approval ID"),
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
{
|
||||
let _ = (uid, approval_id);
|
||||
ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP script approvals are unavailable")
|
||||
}
|
||||
} else {
|
||||
ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Desktop user is unavailable")
|
||||
};
|
||||
control.send(ConnectionCommand::Reply { id, result }).map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::PreviewHipReport(preview) = request {
|
||||
let edited_report = if let HipSource::Edited { report_id } = &preview.source {
|
||||
let report_id = match Uuid::parse_str(report_id) {
|
||||
Ok(id) => id,
|
||||
Err(_) => {
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report ID"),
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
match ctx.registry().edited_hip_report(session_id, report_id) {
|
||||
Ok(report) => Some(report),
|
||||
Err(_) => {
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"HIP report is unavailable for this session",
|
||||
),
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if !ctx
|
||||
.hip_previews
|
||||
.start(crate::hip_preview::PreviewJob {
|
||||
session_id,
|
||||
request_id: id,
|
||||
request: preview,
|
||||
edited_report,
|
||||
desktop_uid,
|
||||
identity: ctx.host_identity().await,
|
||||
registry: Arc::clone(ctx.registry()),
|
||||
connection: control.clone(),
|
||||
})
|
||||
.await
|
||||
{
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::rejected(ServiceErrorCode::Busy, "HIP preview is already running"),
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let dispatcher = ctx.dispatcher();
|
||||
let request = match dispatcher.dispatch_lifecycle(
|
||||
request,
|
||||
desktop_uid,
|
||||
None,
|
||||
Some(crate::request_dispatcher::SessionAuthority {
|
||||
registry: Arc::clone(ctx.registry()),
|
||||
session_id,
|
||||
generation,
|
||||
}),
|
||||
) {
|
||||
Ok(request) => request,
|
||||
Err(result) => {
|
||||
if control.send(ConnectionCommand::Reply { id, result }).is_err() {
|
||||
pending_requests.remove(&id);
|
||||
control.close(CloseReason::InternalError);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let control = control.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = dispatcher.dispatch_pending(request).await;
|
||||
let result = dispatcher.dispatch(request).await;
|
||||
control.send_reply(id, result).await;
|
||||
});
|
||||
Ok(())
|
||||
@@ -646,7 +396,7 @@ mod tests {
|
||||
},
|
||||
utils::redact::Redaction,
|
||||
};
|
||||
use tokio::sync::watch;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio_tungstenite::{connect_async, tungstenite::Message as ClientFrame};
|
||||
|
||||
use super::*;
|
||||
@@ -656,14 +406,15 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn authenticates_attaches_and_replies_to_a_request() {
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap();
|
||||
let (request_tx, mut request_rx) = mpsc::channel(4);
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
request_tx,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
false,
|
||||
None,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
@@ -681,7 +432,6 @@ mod tests {
|
||||
let (mut socket, _) = connect_async(format!("ws://{address}/ws")).await.unwrap();
|
||||
let prelude = ClientPrelude {
|
||||
product_version: env!("CARGO_PKG_VERSION").to_owned(),
|
||||
hip_protocol_version: gpapi::service::transport::HIP_PROTOCOL_VERSION,
|
||||
service_instance_id: credential.service_instance_id(),
|
||||
session_id: credential.session_id(),
|
||||
};
|
||||
@@ -725,6 +475,7 @@ mod tests {
|
||||
.send(ClientFrame::Binary(noise.encrypt(&request).unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(request_rx.recv().await, Some(WsRequest::UpdateLogLevel(_))));
|
||||
let reply = noise
|
||||
.decrypt::<ServerMessage>(&receive_client_binary(&mut socket).await)
|
||||
.unwrap();
|
||||
@@ -736,23 +487,6 @@ 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,11 +9,10 @@ use gpapi::{
|
||||
vpn_env::{HostInfo, VpnEnv},
|
||||
vpn_state::VpnState,
|
||||
},
|
||||
session::tunnel::{TunnelStatisticsSnapshot, TunnelUnavailableReason},
|
||||
utils::lock_file::LockFile,
|
||||
};
|
||||
use log::{info, warn};
|
||||
use openconnect::find_vpnc_script;
|
||||
use openconnect::{find_csd_wrapper, find_vpnc_script};
|
||||
use tokio::{
|
||||
net::TcpListener,
|
||||
sync::{Mutex, Semaphore, mpsc, oneshot, watch},
|
||||
@@ -32,28 +31,6 @@ 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 {
|
||||
@@ -62,7 +39,6 @@ pub(crate) struct WsServerContext {
|
||||
dispatcher: Arc<RequestDispatcher>,
|
||||
state: Mutex<ServiceState>,
|
||||
handshake_slots: Arc<Semaphore>,
|
||||
pub(crate) hip_previews: crate::hip_preview::HipPreviews,
|
||||
}
|
||||
|
||||
impl WsServerContext {
|
||||
@@ -80,10 +56,8 @@ 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,10 +65,6 @@ impl WsServerContext {
|
||||
self.product_version
|
||||
}
|
||||
|
||||
pub async fn host_identity(&self) -> HostIdentity {
|
||||
self.state.lock().await.snapshot.host_info.host_identity.clone()
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Arc<SessionRegistry> {
|
||||
&self.registry
|
||||
}
|
||||
@@ -115,14 +85,12 @@ 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(attached))
|
||||
.send(ConnectionCommand::Send(ServerMessage::Attached {
|
||||
connection_id: control.connection_id(),
|
||||
current_revision: state.revision,
|
||||
snapshot: state.snapshot.clone(),
|
||||
}))
|
||||
.map_err(|_| SessionError::Unavailable)?;
|
||||
state.connections.insert(control.connection_id(), control);
|
||||
Ok(prepared)
|
||||
@@ -143,49 +111,42 @@ 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) {
|
||||
let mut state = self.state.lock().await;
|
||||
state.connections.remove(&connection_id);
|
||||
state.refresh_demand();
|
||||
self.state.lock().await.connections.remove(&connection_id);
|
||||
}
|
||||
|
||||
pub async fn remove_closed_connections(&self) {
|
||||
let mut state = self.state.lock().await;
|
||||
state.connections.retain(|_, connection| !connection.is_closed());
|
||||
state.refresh_demand();
|
||||
self
|
||||
.state
|
||||
.lock()
|
||||
.await
|
||||
.connections
|
||||
.retain(|_, connection| !connection.is_closed());
|
||||
}
|
||||
|
||||
pub async fn send_snapshot(&self, control: &ConnectionControl) -> Result<(), ()> {
|
||||
let state = self.state.lock().await;
|
||||
let mut message = ServerMessage::Snapshot {
|
||||
control.send(ConnectionCommand::Send(ServerMessage::Snapshot {
|
||||
current_revision: state.revision,
|
||||
snapshot: state.snapshot(),
|
||||
};
|
||||
fit_snapshot_message(&mut message)?;
|
||||
control.send(ConnectionCommand::Send(message))
|
||||
snapshot: state.snapshot.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
||||
self.state.lock().await.connections.remove(&connection_id);
|
||||
self.registry.disconnect_if_current(session_id, generation);
|
||||
let mut state = self.state.lock().await;
|
||||
state.connections.remove(&connection_id);
|
||||
state.refresh_demand();
|
||||
}
|
||||
|
||||
pub async fn send_event(&self, event: WsEvent) {
|
||||
@@ -194,8 +155,6 @@ 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 {
|
||||
@@ -203,7 +162,6 @@ impl WsServerContext {
|
||||
connection.close(CloseReason::InternalError);
|
||||
}
|
||||
state.connections.clear();
|
||||
state.refresh_demand();
|
||||
return;
|
||||
};
|
||||
state.revision = revision;
|
||||
@@ -222,97 +180,6 @@ 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,7 +234,6 @@ 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}");
|
||||
@@ -377,7 +243,6 @@ impl WsServer {
|
||||
info!("WS server cancelled");
|
||||
}
|
||||
}
|
||||
self.ctx.hip_previews.shutdown().await;
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
}
|
||||
|
||||
@@ -392,9 +257,9 @@ impl WsServer {
|
||||
|
||||
fn build_snapshot(vpn_state: VpnState) -> VpnEnv {
|
||||
VpnEnv {
|
||||
tunnel_state: None,
|
||||
vpn_state,
|
||||
vpnc_script: find_vpnc_script(),
|
||||
vpnc_script: find_vpnc_script().map(ToOwned::to_owned),
|
||||
csd_wrapper: find_csd_wrapper().map(ToOwned::to_owned),
|
||||
auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(),
|
||||
host_info: HostInfo {
|
||||
host_identity: HostIdentity::collect(),
|
||||
@@ -402,36 +267,6 @@ 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};
|
||||
@@ -444,175 +279,10 @@ 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::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap();
|
||||
let permit = registry
|
||||
.begin_handshake(
|
||||
credential.service_instance_id(),
|
||||
@@ -620,12 +290,13 @@ mod tests {
|
||||
credential.product_version(),
|
||||
)
|
||||
.unwrap();
|
||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
request_tx,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
false,
|
||||
None,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
@@ -668,14 +339,15 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn removed_prepared_candidate_cannot_commit_takeover() {
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap();
|
||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
request_tx,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
false,
|
||||
None,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
@@ -721,32 +393,3 @@ 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,97 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## 3.0.6
|
||||
|
||||
### Changed
|
||||
|
||||
- Embedded macOS VPN network configuration and added configuration logs for troubleshooting.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed desktop notifications disappearing immediately on GNOME.
|
||||
- Corrected the notification sender to GP Connect and clarified update notification titles on Linux and BSD.
|
||||
- Fixed ESP tunnel setup when a gateway reports a zero address, including load-balanced gateways.
|
||||
- Removed obsolete OpenConnect package dependencies from the AUR package.
|
||||
|
||||
## 3.0.5
|
||||
|
||||
### 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
|
||||
|
||||
- GP Connect for Apple silicon Macs running macOS 13 or later.
|
||||
- Support for internal gateways that authenticate your device without creating a VPN tunnel.
|
||||
- More control over device compliance reports (HIP), including generated reports and custom scripts.
|
||||
- Desktop update notifications, with in-app updates on macOS and links to new releases on Linux and BSD.
|
||||
- JSON log output for CLI integrations and automation.
|
||||
|
||||
### Changed
|
||||
|
||||
- Refreshed the desktop connection view, gateway selection, and session details.
|
||||
- Improved browser sign-in, including opening your normal user's browser when the CLI runs with elevated privileges.
|
||||
- Improved session expiry warnings and session extension when allowed by your VPN administrator.
|
||||
- Updated license activation and recovery. Start the seven-day desktop trial by verifying your email address in the app.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Improved cancellation, disconnect, and cached sign-in handling.
|
||||
- Improved desktop window and tray behavior across macOS, Linux, FreeBSD, and OpenBSD.
|
||||
- Improved package installation and desktop integration on Linux and BSD.
|
||||
|
||||
## 2.6.5
|
||||
|
||||
### Fixed
|
||||
|
||||