mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 14:06:14 -05:00
Compare commits
73
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
812965f020 | ||
|
|
5c3b7d118a | ||
|
|
4fdcb15629 | ||
|
|
88f4623f52 | ||
|
|
0c2d4830b5 | ||
|
|
3d2dfe4be0 | ||
|
|
3c49eab0c8 | ||
|
|
13ec7dfc37 | ||
|
|
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 | ||
|
|
66f48b3ff6 | ||
|
|
0f7d065628 |
No files matched your search
+24
-187
@@ -2,11 +2,6 @@ name: Build
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build_only:
|
||||
description: 'Build and test artifacts without publishing releases, images, or update feeds'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
gp_branch:
|
||||
description: 'GlobalProtect-openconnect branch to use for the snapshot release'
|
||||
required: true
|
||||
@@ -45,7 +40,7 @@ on:
|
||||
- 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:
|
||||
@@ -65,7 +60,6 @@ jobs:
|
||||
--user root \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-e LIBXML2_STATIC=1 \
|
||||
-e PKEXEC_UID=1000 \
|
||||
-v "$(pwd):/workspace" \
|
||||
-w /workspace \
|
||||
yuezk/gpdev:binary-builder-tauri2 \
|
||||
@@ -238,13 +232,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:
|
||||
@@ -252,37 +244,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 }}
|
||||
@@ -337,14 +312,9 @@ jobs:
|
||||
cd gpgui-source
|
||||
tar -czf gpgui.tar.gz gpgui gp
|
||||
- name: Build gpgui in Docker
|
||||
env:
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
run: |
|
||||
docker run --rm \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-e GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }} \
|
||||
-e GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }} \
|
||||
-e GPGUI_LICENSE_SIGNING_KEYS \
|
||||
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:${{ matrix.libc.builder }}
|
||||
- name: Install gpgui in Docker
|
||||
run: |
|
||||
@@ -363,120 +333,7 @@ jobs:
|
||||
gpgui-source/*.bin.tar.xz
|
||||
gpgui-source/*.bin.tar.xz.sha256
|
||||
|
||||
nix-source:
|
||||
needs: [build-gpgui]
|
||||
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
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
name: nix-source (${{ matrix.platform.system }})
|
||||
env:
|
||||
NIX_SYSTEM: ${{ matrix.platform.system }}
|
||||
NIXPKGS: locked
|
||||
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]
|
||||
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
|
||||
|
||||
trigger-gpgui-macos:
|
||||
needs: test-gp
|
||||
if: ${{ startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.build_macos) }}
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -495,9 +352,7 @@ jobs:
|
||||
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 }}
|
||||
REQUEST_ID: ${{ github.run_id }}.${{ github.run_attempt }}.macos
|
||||
BUILD_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -518,24 +373,19 @@ jobs:
|
||||
|
||||
expected_title="macOS $CHANNEL $RELEASE_TAG ($REQUEST_ID)"
|
||||
jq -n \
|
||||
--arg workflow_ref "$GPGUI_REF" \
|
||||
--arg request_id "$REQUEST_ID" \
|
||||
--arg build_version "$BUILD_VERSION" \
|
||||
--arg channel "$CHANNEL" \
|
||||
--arg release_tag "$RELEASE_TAG" \
|
||||
--arg gp_ref "$gp_sha" \
|
||||
--arg gpgui_ref "$gpgui_sha" \
|
||||
--argjson build_only "$BUILD_ONLY" \
|
||||
'{
|
||||
ref: $workflow_ref,
|
||||
ref: "main",
|
||||
inputs: {
|
||||
request_id: $request_id,
|
||||
build_version: $build_version,
|
||||
channel: $channel,
|
||||
release_tag: $release_tag,
|
||||
gp_ref: $gp_ref,
|
||||
gpgui_ref: $gpgui_ref,
|
||||
build_only: $build_only
|
||||
gpgui_ref: $gpgui_ref
|
||||
}
|
||||
}' | gh api --method POST \
|
||||
repos/yuezk/gpgui/actions/workflows/release-macos.yaml/dispatches \
|
||||
@@ -636,7 +486,7 @@ jobs:
|
||||
path: gpgui-frontend/gpgui
|
||||
- name: Build gpgui frontend
|
||||
run: |
|
||||
cd gpgui-frontend/gpgui/apps/desktop
|
||||
cd gpgui-frontend/gpgui/app
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm build
|
||||
- name: Upload gpgui frontend
|
||||
@@ -644,7 +494,7 @@ jobs:
|
||||
with:
|
||||
name: bsd-gpgui-frontend
|
||||
if-no-files-found: error
|
||||
path: gpgui-frontend/gpgui/apps/desktop/dist/**
|
||||
path: gpgui-frontend/gpgui/app/dist/**
|
||||
|
||||
build-bsd:
|
||||
needs:
|
||||
@@ -678,7 +528,7 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: bsd-gpgui-frontend
|
||||
path: ${{ matrix.workspace }}/gpgui/apps/desktop/dist
|
||||
path: ${{ matrix.workspace }}/gpgui/app/dist
|
||||
- name: Build on FreeBSD
|
||||
if: ${{ matrix.os == 'freebsd' }}
|
||||
uses: vmactions/freebsd-vm@v1
|
||||
@@ -709,17 +559,14 @@ jobs:
|
||||
webkit2-gtk_41
|
||||
run: |
|
||||
set -eu
|
||||
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
|
||||
cd "${{ matrix.workspace }}/gp"
|
||||
cargo build --release --workspace
|
||||
|
||||
cd ../gpgui/apps/desktop/src-tauri
|
||||
cd ../gpgui/app/src-tauri
|
||||
cargo build --release --workspace
|
||||
|
||||
cd ../../../../gp
|
||||
cd ../../../gp
|
||||
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
|
||||
pkg install -y ".build/${{ matrix.artifact_dir }}"/artifacts/*.pkg
|
||||
gpclient --version
|
||||
@@ -735,27 +582,25 @@ 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 \
|
||||
xdg-utils
|
||||
webkitgtk41
|
||||
ln -sf /usr/local/bin/autoreconf-2.72 /usr/local/bin/autoreconf
|
||||
ln -sf /usr/local/bin/autoconf-2.72 /usr/local/bin/autoconf
|
||||
ln -sf /usr/local/bin/autoheader-2.72 /usr/local/bin/autoheader
|
||||
@@ -766,17 +611,14 @@ jobs:
|
||||
set -eu
|
||||
export AUTOCONF_VERSION=2.72
|
||||
export AUTOMAKE_VERSION=1.17
|
||||
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
|
||||
cd "${{ matrix.workspace }}/gp"
|
||||
cargo build --release --workspace
|
||||
|
||||
cd ../gpgui/apps/desktop/src-tauri
|
||||
cd ../gpgui/app/src-tauri
|
||||
cargo build --release --workspace
|
||||
|
||||
cd ../../../../gp
|
||||
cd ../../../gp
|
||||
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
|
||||
pkg_add -D unsigned ".build/${{ matrix.artifact_dir }}"/artifacts/*.tgz
|
||||
gpclient --version
|
||||
@@ -793,7 +635,7 @@ jobs:
|
||||
${{ matrix.workspace }}/gp/.build/${{ matrix.artifact_dir }}/artifacts/*
|
||||
|
||||
gh-release:
|
||||
if: ${{ always() && ((github.event_name == 'workflow_dispatch' && !inputs.build_only) || startsWith(github.ref, 'refs/tags/')) }}
|
||||
if: ${{ always() && (github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/')) }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
@@ -802,9 +644,6 @@ jobs:
|
||||
attestations: write
|
||||
artifact-metadata: write
|
||||
needs:
|
||||
- test-gp
|
||||
- nix-source
|
||||
- nix-prebuilt
|
||||
- tarball
|
||||
- tarball-offline
|
||||
- build-gp
|
||||
@@ -835,7 +674,7 @@ jobs:
|
||||
result = data["result"]
|
||||
if result in {"failure", "cancelled"}:
|
||||
failed.append(f"{name}: {result}")
|
||||
elif name in {"build-gp", "build-docker-image", "nix-prebuilt"} and result == "skipped" and is_tag:
|
||||
elif name in {"build-gp", "build-docker-image"} and result == "skipped" and is_tag:
|
||||
continue
|
||||
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
|
||||
continue
|
||||
@@ -917,7 +756,6 @@ jobs:
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
|
||||
PUBLIC_RELEASE_RESULT: ${{ needs.gh-release.result }}
|
||||
BUILD_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
|
||||
PRIVATE_RUN_ID: ${{ needs.trigger-gpgui-macos.outputs.run_id }}
|
||||
PRIVATE_RUN_URL: ${{ needs.trigger-gpgui-macos.outputs.run_url }}
|
||||
run: |
|
||||
@@ -927,7 +765,7 @@ jobs:
|
||||
echo "The private macOS workflow was not started" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$BUILD_ONLY" != "true" && "$PUBLIC_RELEASE_RESULT" != "success" ]]; then
|
||||
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
|
||||
@@ -956,9 +794,8 @@ jobs:
|
||||
|
||||
publish-docker-image:
|
||||
needs:
|
||||
- test-gp
|
||||
- build-docker-image
|
||||
if: ${{ (github.event_name == 'workflow_dispatch' && !inputs.build_only) || startsWith(github.ref, 'refs/tags/') }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Download digests
|
||||
|
||||
@@ -24,8 +24,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Validate AUR package
|
||||
aur:
|
||||
runs-on: ubuntu-latest
|
||||
container: archlinux:base-devel
|
||||
defaults:
|
||||
@@ -33,6 +32,7 @@ jobs:
|
||||
shell: bash
|
||||
env:
|
||||
AUR_PACKAGE_DIR: packaging/aur/globalprotect-openconnect-git
|
||||
AUR_REPO: ssh://[email protected]/globalprotect-openconnect-git.git
|
||||
steps:
|
||||
- name: Install checkout tools
|
||||
run: pacman -Syu --noconfirm --needed git openssh
|
||||
@@ -102,42 +102,8 @@ jobs:
|
||||
cd "$AUR_PACKAGE_DIR"
|
||||
runuser -u builder -- makepkg --noconfirm --clean --cleanbuild
|
||||
|
||||
- name: Upload AUR package metadata
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: aur-package-metadata
|
||||
path: |
|
||||
${{ env.AUR_PACKAGE_DIR }}/PKGBUILD
|
||||
${{ env.AUR_PACKAGE_DIR }}/.SRCINFO
|
||||
${{ env.AUR_PACKAGE_DIR }}/gp.install
|
||||
if-no-files-found: error
|
||||
include-hidden-files: true
|
||||
overwrite: true
|
||||
|
||||
publish:
|
||||
name: Publish to AUR
|
||||
needs: validate
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
|
||||
runs-on: ubuntu-latest
|
||||
container: archlinux:base-devel
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
AUR_PACKAGE_DIR: /tmp/aur-package
|
||||
AUR_REPO: ssh://[email protected]/globalprotect-openconnect-git.git
|
||||
steps:
|
||||
- name: Install publish tools
|
||||
run: pacman -Syu --noconfirm --needed git openssh
|
||||
|
||||
- name: Download AUR package metadata
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: aur-package-metadata
|
||||
path: ${{ env.AUR_PACKAGE_DIR }}
|
||||
|
||||
- name: Configure SSH
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
|
||||
env:
|
||||
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||
run: |
|
||||
@@ -152,6 +118,7 @@ jobs:
|
||||
ssh-keyscan -t rsa,ecdsa,ed25519 aur.archlinux.org > ~/.ssh/known_hosts
|
||||
|
||||
- name: Publish to AUR
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
|
||||
env:
|
||||
GIT_SSH_COMMAND: ssh -i /github/home/.ssh/aur -o UserKnownHostsFile=/github/home/.ssh/known_hosts -o StrictHostKeyChecking=yes
|
||||
run: |
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
name: Publish COPR
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Tag to publish'
|
||||
required: true
|
||||
revision:
|
||||
description: 'Package revision'
|
||||
type: string
|
||||
required: true
|
||||
default: "1"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish-copr:
|
||||
runs-on: ubuntu-latest
|
||||
container: fedora:latest
|
||||
steps:
|
||||
- name: Install tools
|
||||
run: dnf install -y copr-cli gh
|
||||
|
||||
- name: Check inputs
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
if [[ ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Revision must be a positive integer" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null
|
||||
|
||||
- name: Download published spec
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
mkdir -p publish-copr
|
||||
|
||||
gh release download "$TAG" \
|
||||
--repo "${{ github.repository }}" \
|
||||
--pattern globalprotect-openconnect.spec \
|
||||
--dir publish-copr
|
||||
|
||||
- name: Set package revision
|
||||
env:
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
spec=publish-copr/globalprotect-openconnect.spec
|
||||
|
||||
if [[ "$(grep -c '^Release:' "$spec")" -ne 1 ]]; then
|
||||
echo "Expected exactly one Release field in $spec" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sed -Ei \
|
||||
"s/^Release:[[:space:]]+.*/Release: ${REVISION}%{?dist}/" \
|
||||
"$spec"
|
||||
|
||||
grep '^Release:' "$spec"
|
||||
|
||||
- name: Configure COPR authentication
|
||||
env:
|
||||
COPR_CONFIG: ${{ secrets.COPR_CONFIG }}
|
||||
run: |
|
||||
install -d -m 700 "$HOME/.config"
|
||||
printf '%s\n' "$COPR_CONFIG" > "$HOME/.config/copr"
|
||||
chmod 600 "$HOME/.config/copr"
|
||||
|
||||
- name: Build and publish COPR package
|
||||
run: |
|
||||
copr-cli build \
|
||||
yuezk/globalprotect-openconnect \
|
||||
publish-copr/globalprotect-openconnect.spec
|
||||
@@ -1,72 +0,0 @@
|
||||
name: Publish OBS
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Tag to publish'
|
||||
required: true
|
||||
revision:
|
||||
description: 'Package revision'
|
||||
type: string
|
||||
required: true
|
||||
default: "1"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish-obs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check inputs
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
if [[ ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Revision must be a positive integer" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null
|
||||
|
||||
- name: Prepare OBS package
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
version="${TAG#v}"
|
||||
archive="globalprotect-openconnect-${version}.offline.tar.gz"
|
||||
source_dir="publish-obs/source/globalprotect-openconnect-${version}"
|
||||
|
||||
mkdir -p publish-obs/files publish-obs/source
|
||||
|
||||
gh release download "$TAG" \
|
||||
--repo "${{ github.repository }}" \
|
||||
--pattern "$archive" \
|
||||
--dir publish-obs
|
||||
|
||||
tar -xzf "publish-obs/$archive" -C publish-obs/source
|
||||
|
||||
make -C "$source_dir" init-rpm \
|
||||
REVISION="$REVISION" \
|
||||
RPM_SOURCE='%{name}.tar.gz'
|
||||
|
||||
mv "publish-obs/$archive" \
|
||||
publish-obs/files/globalprotect-openconnect.tar.gz
|
||||
cp "$source_dir/.build/rpm/globalprotect-openconnect.spec" \
|
||||
"$source_dir/.build/rpm/globalprotect-openconnect.changes" \
|
||||
publish-obs/files/
|
||||
|
||||
- name: Publish OBS package
|
||||
uses: yuezk/publish-obs-package@main
|
||||
with:
|
||||
project: home:yuezk
|
||||
package: globalprotect-openconnect
|
||||
username: yuezk
|
||||
password: ${{ secrets.OBS_PASSWORD }}
|
||||
files: ./publish-obs/files/*
|
||||
commit_message: 'Release ${{ inputs.tag }}-${{ inputs.revision }}'
|
||||
@@ -19,7 +19,7 @@ on:
|
||||
description: 'Rust version to use'
|
||||
type: "string"
|
||||
required: true
|
||||
default: "1.91"
|
||||
default: "1.89"
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -24,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 }}
|
||||
@@ -44,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:
|
||||
@@ -55,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
|
||||
@@ -82,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: |
|
||||
@@ -104,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:
|
||||
|
||||
+2
-1
@@ -1,5 +1,4 @@
|
||||
.idea
|
||||
.DS_Store
|
||||
/target
|
||||
.pnpm-store
|
||||
.env
|
||||
@@ -16,3 +15,5 @@ gen
|
||||
|
||||
# Nix files
|
||||
result
|
||||
|
||||
.DS_Store
|
||||
Generated
+609
-697
File diff suppressed because it is too large.
Load diff
+2
-8
@@ -10,8 +10,8 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.91"
|
||||
version = "3.0.0"
|
||||
rust-version = "1.89"
|
||||
version = "2.6.5"
|
||||
authors = ["Kevin Yue <[email protected]>"]
|
||||
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
edition = "2024"
|
||||
@@ -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
|
||||
|
||||
@@ -4,7 +4,7 @@ SHELL := /bin/sh
|
||||
INCLUDE_GUI ?= 0
|
||||
CARGO ?= cargo
|
||||
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/')
|
||||
@@ -145,7 +145,6 @@ install:
|
||||
install -Dm755 target/release/gpclient $(DESTDIR)/usr/bin/gpclient
|
||||
install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth
|
||||
install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice
|
||||
install -Dm755 target/release/gp-hip-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer
|
||||
install -Dm755 target/release/gp-vpnc-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
|
||||
|
||||
# Install the GUI components if BUILD_GUI_HELPER is set to 1
|
||||
@@ -158,23 +157,19 @@ install:
|
||||
fi
|
||||
|
||||
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 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/applications/gpauth.desktop $(DESTDIR)/usr/share/applications/gpauth.desktop
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/128x128/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/128x128/apps/gpgui.png
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/256x256/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/256x256/apps/gpgui.png
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/256x256@2/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/256x256@2/apps/gpgui.png
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connected-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connected-symbolic.svg
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-disconnected-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-disconnected-symbolic.svg
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-1-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-1-symbolic.svg
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-2-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-2-symbolic.svg
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-3-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-3-symbolic.svg
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-4-symbolic.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-4-symbolic.svg
|
||||
install -Dm644 packaging/files/usr/share/polkit-1/actions/com.yuezk.gpgui.policy $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
|
||||
|
||||
install-bsd:
|
||||
@@ -194,9 +189,9 @@ install-bsd:
|
||||
fi
|
||||
|
||||
install -d $(DESTDIR)$(PREFIX)/libexec/gpclient
|
||||
install -m 755 target/release/gp-hip-script-installer $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-hip-script-installer
|
||||
install -m 755 target/release/gp-vpnc-script-installer $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-vpnc-script-installer
|
||||
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)$(PREFIX)/libexec/gpclient/vpnc-script
|
||||
install -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
|
||||
@@ -205,18 +200,11 @@ install-bsd:
|
||||
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps
|
||||
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256/apps
|
||||
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256@2/apps
|
||||
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status
|
||||
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps/gpgui.svg
|
||||
install -m 644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps/gpgui.png
|
||||
install -m 644 packaging/files/usr/share/icons/hicolor/128x128/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps/gpgui.png
|
||||
install -m 644 packaging/files/usr/share/icons/hicolor/256x256/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256/apps/gpgui.png
|
||||
install -m 644 packaging/files/usr/share/icons/hicolor/256x256@2/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256@2/apps/gpgui.png
|
||||
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connected-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-connected-symbolic.svg
|
||||
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-disconnected-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-disconnected-symbolic.svg
|
||||
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-1-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-connecting-1-symbolic.svg
|
||||
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-2-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-connecting-2-symbolic.svg
|
||||
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-3-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-connecting-3-symbolic.svg
|
||||
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-connecting-4-symbolic.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/status/gpgui-connecting-4-symbolic.svg
|
||||
install -d $(DESTDIR)$(PREFIX)/share/polkit-1/actions
|
||||
install -m 644 packaging/bsd/com.yuezk.gpgui.policy $(DESTDIR)$(PREFIX)/share/polkit-1/actions/com.yuezk.gpgui.policy
|
||||
|
||||
@@ -263,19 +251,15 @@ package-openbsd: clean-bsd-package
|
||||
cp packaging/bsd/openbsd/COMMENT .build/openbsd/+COMMENT
|
||||
cp packaging/bsd/openbsd/DESC .build/openbsd/+DESC
|
||||
{ \
|
||||
echo '@unexec-delete /bin/rm -f /usr/local/libexec/gpclient/gpgui /var/db/gpclient/scripts/vpnc-script /var/db/gpclient/scripts/vpnc-script.metadata || echo "Warning: failed to remove gpclient runtime files" >&2'; \
|
||||
echo '@unexec-delete /bin/rmdir /usr/local/libexec/gpclient 2>/dev/null || true'; \
|
||||
echo '@unexec-delete /bin/rm -f /var/db/gpclient/scripts/vpnc-script /var/db/gpclient/scripts/vpnc-script.metadata || echo "Warning: failed to remove the installed VPN script" >&2'; \
|
||||
echo '@unexec-delete /bin/rmdir /var/db/gpclient/scripts 2>/dev/null || true'; \
|
||||
echo '@unexec-delete /bin/rmdir /var/db/gpclient 2>/dev/null || true'; \
|
||||
find .build/openbsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/openbsd/pkgroot$(PREFIX)/||' | sort; \
|
||||
} > .build/openbsd/PLIST
|
||||
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); \
|
||||
pkg_create \
|
||||
-B .build/openbsd/pkgroot \
|
||||
-D COMMENT="$$comment" \
|
||||
@@ -283,10 +267,8 @@ 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)"
|
||||
|
||||
@@ -296,36 +278,29 @@ uninstall:
|
||||
rm -f $(DESTDIR)/usr/bin/gpclient
|
||||
rm -f $(DESTDIR)/usr/bin/gpauth
|
||||
rm -f $(DESTDIR)/usr/bin/gpservice
|
||||
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer
|
||||
rm -f $(DESTDIR)/usr/bin/gpgui-helper
|
||||
rm -f $(DESTDIR)/usr/bin/gpgui
|
||||
|
||||
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
|
||||
|
||||
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
|
||||
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
|
||||
|
||||
rm -f $(DESTDIR)/usr/share/applications/gpgui.desktop
|
||||
rm -f $(DESTDIR)/usr/share/applications/gpauth.desktop
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/128x128/apps/gpgui.png
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/256x256/apps/gpgui.png
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/256x256@2/apps/gpgui.png
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connected-symbolic.svg
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-disconnected-symbolic.svg
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-1-symbolic.svg
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-2-symbolic.svg
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-3-symbolic.svg
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/status/gpgui-connecting-4-symbolic.svg
|
||||
rm -f $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
|
||||
|
||||
rm -f $(DESTDIR)/var/lib/gpclient/gpgui \
|
||||
$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script \
|
||||
rm -f $(DESTDIR)/var/lib/gpclient/scripts/vpnc-script \
|
||||
$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script.metadata || \
|
||||
echo "Warning: failed to remove gpclient runtime files" >&2
|
||||
echo "Warning: failed to remove the installed VPN script" >&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 for Linux, FreeBSD, and OpenBSD, 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
|
||||
|
||||
@@ -59,64 +56,40 @@ Commands:
|
||||
connect Connect to a portal server
|
||||
disconnect Disconnect from the server
|
||||
launch-gui Launch the GUI
|
||||
hip Generate HIP report
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
|
||||
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
|
||||
-h, --help Print help (see more with '--help')
|
||||
-V, --version Print version
|
||||
--fix-openssl Get around the OpenSSL 'unsafe legacy renegotiation' error
|
||||
--ignore-tls-errors Ignore TLS errors
|
||||
-h, --help Print help
|
||||
-V, --version Print version
|
||||
```
|
||||
|
||||
> **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>
|
||||
```
|
||||
|
||||
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 try your recognized default browser first, then another detected browser, and finally the system URL handler
|
||||
- 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 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
|
||||
@@ -132,10 +105,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
|
||||
|
||||
Download the GP Connect `.dmg` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, open it, and drag GP Connect into Applications. The macOS build requires Apple silicon and macOS 13 or later.
|
||||
|
||||
### Debian / Ubuntu
|
||||
|
||||
#### Option 1: Install from PPA (Recommended)
|
||||
@@ -158,7 +127,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
|
||||
@@ -268,11 +237,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
|
||||
{
|
||||
@@ -291,11 +256,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
|
||||
];
|
||||
}
|
||||
@@ -322,15 +287,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:
|
||||
@@ -346,7 +302,7 @@ 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 remote browser authentication:
|
||||
@@ -357,12 +313,6 @@ docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
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 remote --browser-listen 192.168.107.15
|
||||
```
|
||||
|
||||
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
|
||||
|
||||
```bash
|
||||
@@ -373,6 +323,16 @@ docker run --rm -it --network host --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
|
||||
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
|
||||
@@ -380,16 +340,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:**
|
||||
@@ -399,11 +357,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
|
||||
|
||||
@@ -427,7 +385,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 \
|
||||
@@ -435,17 +393,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
|
||||
|
||||
@@ -460,11 +414,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
|
||||
|
||||
@@ -484,7 +438,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
|
||||
|
||||
@@ -496,33 +450,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 or remote browser
|
||||
- `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
|
||||
|
||||
### 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 remote` 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
|
||||
@@ -533,7 +483,7 @@ On a headless server, use `--browser remote` 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
|
||||
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>LSUIElement</key>
|
||||
<true/>
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>GlobalProtect authentication callback</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>globalprotectcallback</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,58 +0,0 @@
|
||||
use std::{
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use tauri::RunEvent;
|
||||
|
||||
pub fn run() -> anyhow::Result<()> {
|
||||
let handled = Arc::new(AtomicBool::new(false));
|
||||
let timeout_handled = Arc::clone(&handled);
|
||||
let app = tauri::Builder::default()
|
||||
.setup(move |app| {
|
||||
#[cfg(target_os = "macos")]
|
||||
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
|
||||
|
||||
let app_handle = app.handle().clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||
if !timeout_handled.swap(true, Ordering::AcqRel) {
|
||||
app_handle.exit(1);
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
})
|
||||
.build(crate::tauri_context::get())?;
|
||||
|
||||
app.run(move |app_handle, event| {
|
||||
let RunEvent::Opened { urls } = event else {
|
||||
return;
|
||||
};
|
||||
let Some(callback) = urls
|
||||
.into_iter()
|
||||
.find(|url| url.scheme().eq_ignore_ascii_case("globalprotectcallback"))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if handled.swap(true, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
|
||||
let app_handle = app_handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let exit_code = match auth::forward_auth_callback(callback.as_str()).await {
|
||||
Ok(()) => 0,
|
||||
Err(err) => {
|
||||
eprintln!("Failed to forward authentication callback: {err}");
|
||||
1
|
||||
}
|
||||
};
|
||||
app_handle.exit(exit_code);
|
||||
});
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+9
-112
@@ -1,22 +1,16 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use auth::forward_auth_callback;
|
||||
use auth::{BrowserAuthenticator, auth_prelogin};
|
||||
use clap::Parser;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use clap::Subcommand;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use gpapi::auth::AuthWindowTheme;
|
||||
use gpapi::{
|
||||
auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult},
|
||||
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
|
||||
gp_params::GpParams,
|
||||
log_format::LogFormat,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
utils::{normalize_server, openssl},
|
||||
};
|
||||
use log::info;
|
||||
use serde_json::json;
|
||||
use std::net::IpAddr;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
const VERSION: &str = concat!(
|
||||
@@ -33,8 +27,6 @@ const VERSION: &str = concat!(
|
||||
version = VERSION,
|
||||
author,
|
||||
about = "The authentication component for the GlobalProtect VPN client, supports the SSO authentication method.",
|
||||
args_conflicts_with_subcommands = true,
|
||||
subcommand_negates_reqs = true,
|
||||
help_template = "\
|
||||
{before-help}{name} {version}
|
||||
{author}
|
||||
@@ -49,12 +41,8 @@ See 'gpauth -h' for more information.
|
||||
"
|
||||
)]
|
||||
struct Cli {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[command(subcommand)]
|
||||
command: Option<CliCommand>,
|
||||
|
||||
#[arg(required = true, help = "The portal server to authenticate")]
|
||||
server: Option<String>,
|
||||
#[arg(help = "The portal server to authenticate")]
|
||||
server: String,
|
||||
|
||||
#[arg(long, help = "Treating the server as a gateway")]
|
||||
gateway: bool,
|
||||
@@ -90,29 +78,18 @@ struct Cli {
|
||||
#[arg(long, help = "Ignore TLS errors")]
|
||||
ignore_tls_errors: bool,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
default_value_t = LogFormat::Text,
|
||||
help = "Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text."
|
||||
)]
|
||||
log_format: LogFormat,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, help = "Use the default browser for authentication")]
|
||||
default_browser: bool,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser or `remote` for headless servers.",
|
||||
help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser.",
|
||||
default_missing_value = "auto",
|
||||
num_args=0..=1
|
||||
)]
|
||||
browser: Option<String>,
|
||||
|
||||
#[arg(long, help = "Listen on this IP address when using '--browser remote'")]
|
||||
browser_listen: Option<IpAddr>,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
|
||||
hidpi: bool,
|
||||
@@ -133,16 +110,6 @@ struct Cli {
|
||||
verbose: InfoLevelVerbosity,
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[derive(Subcommand)]
|
||||
enum CliCommand {
|
||||
#[command(hide = true)]
|
||||
AuthCallback {
|
||||
#[arg(help = "The globalprotectcallback URL to forward")]
|
||||
callback: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl Args for Cli {
|
||||
fn fix_openssl(&self) -> bool {
|
||||
self.fix_openssl
|
||||
@@ -151,10 +118,6 @@ impl Args for Cli {
|
||||
fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
|
||||
fn log_format(&self) -> LogFormat {
|
||||
self.log_format
|
||||
}
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
@@ -173,19 +136,13 @@ impl Cli {
|
||||
}
|
||||
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
if self.browser_listen.is_some()
|
||||
&& !matches!(self.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote"))
|
||||
{
|
||||
anyhow::bail!("The '--browser-listen' option requires '--browser remote'");
|
||||
}
|
||||
|
||||
if self.ignore_tls_errors {
|
||||
info!("TLS errors will be ignored");
|
||||
}
|
||||
|
||||
let openssl_conf = self.prepare_env()?;
|
||||
|
||||
let server = normalize_server(self.server.as_deref().expect("server is required for authentication"))?;
|
||||
let server = normalize_server(&self.server)?;
|
||||
let gp_params = self.build_gp_params();
|
||||
info!(
|
||||
"gpauth auth host-id: {}",
|
||||
@@ -208,7 +165,7 @@ impl Cli {
|
||||
|
||||
if let Some(browser) = browser {
|
||||
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
|
||||
let authenticator = BrowserAuthenticator::new(&auth_request, browser, self.browser_listen);
|
||||
let authenticator = BrowserAuthenticator::new(&auth_request, browser);
|
||||
let auth_result = authenticator.authenticate().await;
|
||||
|
||||
print_auth_result(auth_result, Some(&auth_host_id));
|
||||
@@ -268,26 +225,16 @@ impl Cli {
|
||||
}
|
||||
|
||||
fn init_logger(cli: &Cli) {
|
||||
let Some(level) = cli.verbose.log_level_filter().to_level() else {
|
||||
if let Some(level) = cli.verbose.log_level_filter().to_level() {
|
||||
gpapi::logger::init(level, "com.yuezk.gpgui", "gpauth");
|
||||
} else {
|
||||
log::set_max_level(log::LevelFilter::Off);
|
||||
return;
|
||||
};
|
||||
|
||||
gpapi::logger::init(level, "com.yuezk.gpgui", "gpauth", cli.log_format);
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
if let Some(CliCommand::AuthCallback { callback }) = &cli.command {
|
||||
if let Err(err) = forward_auth_callback(callback).await {
|
||||
eprintln!("Failed to forward authentication callback: {err}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
init_logger(&cli);
|
||||
info!("gpauth started: {}", VERSION);
|
||||
|
||||
@@ -317,24 +264,6 @@ pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Opt
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 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.
|
||||
#[test]
|
||||
fn log_format_defaults_to_text() {
|
||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com"]).expect("gpauth args should parse");
|
||||
|
||||
assert_eq!(cli.log_format, LogFormat::Text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_format_accepts_json() {
|
||||
let cli =
|
||||
Cli::try_parse_from(["gpauth", "portal.example.com", "--log-format", "json"]).expect("gpauth args should parse");
|
||||
|
||||
assert_eq!(cli.log_format, LogFormat::Json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_defaults_to_runtime_os() {
|
||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com"]).expect("gpauth args should parse");
|
||||
@@ -342,23 +271,6 @@ mod tests {
|
||||
assert_eq!(cli.os, Os::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn callback_arguments_parse_separately() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpauth",
|
||||
"auth-callback",
|
||||
"globalprotectcallback:cas-as=1&[email protected]&token=token",
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
cli.command,
|
||||
Some(CliCommand::AuthCallback { callback }) if callback.starts_with("globalprotectcallback:")
|
||||
));
|
||||
assert!(cli.server.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_id_arg_sets_profile_host_id_seed() {
|
||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--host-id", "host-seed"])
|
||||
@@ -393,21 +305,6 @@ mod tests {
|
||||
assert!(cli.external_browser_requested());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_listen_accepts_ip_address() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpauth",
|
||||
"portal.example.com",
|
||||
"--browser",
|
||||
"remote",
|
||||
"--browser-listen",
|
||||
"192.168.107.15",
|
||||
])
|
||||
.expect("gpauth args should parse");
|
||||
|
||||
assert_eq!(cli.browser_listen, Some("192.168.107.15".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_version_arg_sets_profile_client_version() {
|
||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--client-version", "legacy-client"])
|
||||
|
||||
@@ -2,34 +2,10 @@
|
||||
|
||||
mod cli;
|
||||
|
||||
#[cfg(all(target_os = "macos", feature = "webview-auth"))]
|
||||
mod callback_app;
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
mod tauri_context;
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
mod webview_auth;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
#[cfg(all(target_os = "macos", feature = "webview-auth"))]
|
||||
if is_callback_app_launch() {
|
||||
if let Err(err) = callback_app::run() {
|
||||
eprintln!("Failed to handle authentication callback: {err}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
cli::run().await;
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "macos", feature = "webview-auth"))]
|
||||
fn is_callback_app_launch() -> bool {
|
||||
std::env::args_os().len() == 1
|
||||
&& std::env::current_exe().is_ok_and(|executable| {
|
||||
executable
|
||||
.ancestors()
|
||||
.any(|path| path.extension().is_some_and(|extension| extension == "app"))
|
||||
})
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
pub fn get() -> tauri::Context<tauri::Wry> {
|
||||
tauri::generate_context!()
|
||||
}
|
||||
@@ -19,9 +19,6 @@ pub async fn authenticate(
|
||||
|
||||
tauri::Builder::default()
|
||||
.setup(move |app| {
|
||||
#[cfg(target_os = "macos")]
|
||||
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
|
||||
|
||||
apply_auth_theme(app.handle(), window_theme);
|
||||
let app_handle = app.handle().clone();
|
||||
|
||||
@@ -42,7 +39,7 @@ pub async fn authenticate(
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.build(crate::tauri_context::get())?
|
||||
.build(tauri::generate_context!())?
|
||||
.run(move |_app_handle, event| {
|
||||
if let RunEvent::Exit = event {
|
||||
if let Some(file) = openssl_conf.take() {
|
||||
|
||||
@@ -9,25 +9,28 @@ license.workspace = true
|
||||
[dependencies]
|
||||
common = { path = "../../crates/common" }
|
||||
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
|
||||
gphip = { path = "../../crates/gphip" }
|
||||
openconnect = { path = "../../crates/openconnect" }
|
||||
|
||||
anyhow.workspace = true
|
||||
askama.workspace = true
|
||||
chrono.workspace = true
|
||||
clap.workspace = true
|
||||
env_logger.workspace = true
|
||||
inquire = "0.9"
|
||||
log.workspace = true
|
||||
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"]
|
||||
|
||||
+15
-233
@@ -1,4 +1,6 @@
|
||||
use std::{
|
||||
env::temp_dir,
|
||||
fs::File,
|
||||
path::{Path, PathBuf},
|
||||
str::FromStr,
|
||||
};
|
||||
@@ -7,7 +9,6 @@ use anyhow::bail;
|
||||
use clap::{Parser, Subcommand};
|
||||
use gpapi::{
|
||||
clap::{Args, InfoLevelVerbosity, handle_error},
|
||||
log_format::{LogFormat, write_json_record},
|
||||
utils::openssl,
|
||||
};
|
||||
use log::info;
|
||||
@@ -37,7 +38,6 @@ pub(crate) struct SharedArgs<'a> {
|
||||
pub(crate) ignore_tls_errors: bool,
|
||||
pub(crate) lock_file: &'a Path,
|
||||
pub(crate) verbose: &'a InfoLevelVerbosity,
|
||||
pub(crate) log_format: LogFormat,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
@@ -50,21 +50,6 @@ enum CliCommand {
|
||||
LaunchGui(LaunchGuiArgs),
|
||||
#[command(about = "Generate HIP report")]
|
||||
Hip(HipArgs),
|
||||
#[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)]
|
||||
@@ -104,14 +89,6 @@ struct Cli {
|
||||
)]
|
||||
lock_file: PathBuf,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
default_value_t = LogFormat::Text,
|
||||
help = "Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text."
|
||||
)]
|
||||
log_format: LogFormat,
|
||||
|
||||
#[command(flatten)]
|
||||
verbose: InfoLevelVerbosity,
|
||||
}
|
||||
@@ -124,21 +101,9 @@ impl Args for Cli {
|
||||
fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
|
||||
fn log_format(&self) -> LogFormat {
|
||||
self.log_format
|
||||
}
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
fn can_run_alongside_client(&self) -> bool {
|
||||
match &self.command {
|
||||
CliCommand::Connect(_) => false,
|
||||
CliCommand::LaunchGui(args) => args.is_auth_callback(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
async fn is_running(&self) -> bool {
|
||||
let Ok(c) = fs::read_to_string(&self.lock_file).await else {
|
||||
return false;
|
||||
@@ -169,7 +134,7 @@ impl Cli {
|
||||
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
// check if an instance is running
|
||||
if !self.can_run_alongside_client() && self.is_running().await {
|
||||
if !matches!(self.command, CliCommand::Disconnect(_)) && self.is_running().await {
|
||||
bail!("Another instance of the client is already running");
|
||||
}
|
||||
|
||||
@@ -181,7 +146,6 @@ impl Cli {
|
||||
ignore_tls_errors: self.ignore_tls_errors,
|
||||
lock_file: &self.lock_file,
|
||||
verbose: &self.verbose,
|
||||
log_format: self.log_format,
|
||||
};
|
||||
|
||||
if self.ignore_tls_errors {
|
||||
@@ -193,41 +157,32 @@ impl Cli {
|
||||
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::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(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_logger(cli: &Cli) -> env_logger::Builder {
|
||||
fn init_logger(cli: &Cli) {
|
||||
let mut builder = env_logger::builder();
|
||||
builder.filter_level(cli.verbose.log_level_filter());
|
||||
|
||||
// Text is env_logger's own format, so leave it untouched rather than
|
||||
// reimplementing it.
|
||||
if cli.log_format == LogFormat::Json {
|
||||
builder.format(write_json_record);
|
||||
// Output the log messages to a file if the command is the auth callback
|
||||
if let CliCommand::LaunchGui(args) = &cli.command {
|
||||
let auth_data = args.auth_data.as_deref().unwrap_or_default();
|
||||
if !auth_data.is_empty()
|
||||
&& let Ok(log_file) = File::create(temp_dir().join("gpcallback.log"))
|
||||
{
|
||||
let target = Box::new(log_file);
|
||||
builder.target(env_logger::Target::Pipe(target));
|
||||
}
|
||||
}
|
||||
|
||||
builder
|
||||
builder.init();
|
||||
}
|
||||
|
||||
pub(crate) async fn run() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
build_logger(&cli).init();
|
||||
init_logger(&cli);
|
||||
|
||||
info!("gpclient started: {}", VERSION);
|
||||
|
||||
@@ -239,32 +194,8 @@ pub(crate) async fn run() {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io::Write,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use log::Log;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[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");
|
||||
@@ -285,153 +216,4 @@ 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() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"launch-gui",
|
||||
"globalprotectcallback:cas-as=1&[email protected]&token=token",
|
||||
])
|
||||
.expect("authentication callback should parse");
|
||||
|
||||
assert!(matches!(
|
||||
&cli.command,
|
||||
CliCommand::LaunchGui(args) if args.is_auth_callback()
|
||||
));
|
||||
assert!(cli.can_run_alongside_client());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn launch_gui_rejects_callback_with_minimized() {
|
||||
assert!(Cli::try_parse_from(["gpclient", "launch-gui", "globalprotectcallback:token", "--minimized",]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn launch_gui_rejects_non_callback_positional() {
|
||||
assert!(Cli::try_parse_from(["gpclient", "launch-gui", "https://example.com/callback"]).is_err());
|
||||
}
|
||||
|
||||
fn parse_cli(args: &[&str]) -> Cli {
|
||||
Cli::try_parse_from(args).expect("arguments should parse")
|
||||
}
|
||||
|
||||
/// Text stays the default: a plain `gpclient connect` must keep the output it
|
||||
/// has always had, or every existing user's terminal changes under them.
|
||||
#[test]
|
||||
fn log_format_defaults_to_text() {
|
||||
assert_eq!(parse_cli(&["gpclient", "disconnect"]).log_format, LogFormat::Text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_format_accepts_json() {
|
||||
assert_eq!(
|
||||
parse_cli(&["gpclient", "--log-format", "json", "disconnect"]).log_format,
|
||||
LogFormat::Json
|
||||
);
|
||||
}
|
||||
|
||||
/// An unknown value is a mistake worth reporting rather than silently
|
||||
/// falling back to text, which would leave a caller parsing prose.
|
||||
#[test]
|
||||
fn log_format_rejects_an_unknown_value() {
|
||||
// `.err()` rather than `unwrap_err()`: the Ok side is `Cli`, which is not
|
||||
// `Debug`, and it is not worth deriving it just to print an error we expect.
|
||||
let err = Cli::try_parse_from(["gpclient", "--log-format", "yaml", "disconnect"])
|
||||
.err()
|
||||
.expect("an unknown log format should be rejected");
|
||||
let msg = err.to_string();
|
||||
assert!(msg.contains("yaml"), "error should name the input: {msg}");
|
||||
assert!(msg.contains("json"), "error should list the valid values: {msg}");
|
||||
}
|
||||
|
||||
/// A `Write` that keeps what was written, so the logger can be driven for
|
||||
/// real instead of asserting on how it was configured.
|
||||
#[derive(Clone, Default)]
|
||||
struct Captured(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl Captured {
|
||||
fn contents(&self) -> String {
|
||||
String::from_utf8(self.0.lock().unwrap().clone()).expect("log output should be UTF-8")
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for Captured {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn log_one_record(args: &[&str]) -> String {
|
||||
let captured = Captured::default();
|
||||
let logger = build_logger(&parse_cli(args))
|
||||
.target(env_logger::Target::Pipe(Box::new(captured.clone())))
|
||||
.build();
|
||||
|
||||
// Drive the logger directly: `init()` installs a global that a second test
|
||||
// could not replace.
|
||||
logger.log(
|
||||
&log::Record::builder()
|
||||
.level(log::Level::Info)
|
||||
.target("gpclient")
|
||||
.args(format_args!("connected to {}", "vpn.example.com"))
|
||||
.build(),
|
||||
);
|
||||
logger.flush();
|
||||
|
||||
captured.contents()
|
||||
}
|
||||
|
||||
/// 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]
|
||||
fn json_format_emits_one_json_object_per_record() {
|
||||
let out = log_one_record(&["gpclient", "--log-format", "json", "disconnect"]);
|
||||
|
||||
let lines: Vec<_> = out.lines().collect();
|
||||
assert_eq!(lines.len(), 1, "expected exactly one line, got: {out:?}");
|
||||
|
||||
let v: serde_json::Value = serde_json::from_str(lines[0]).unwrap_or_else(|e| panic!("not JSON: {out:?} ({e})"));
|
||||
assert_eq!(v["level"], "INFO");
|
||||
assert_eq!(v["target"], "gpclient");
|
||||
assert_eq!(v["message"], "connected to vpn.example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_format_is_left_alone() {
|
||||
let out = log_one_record(&["gpclient", "disconnect"]);
|
||||
|
||||
assert!(out.contains("connected to vpn.example.com"), "message missing: {out:?}");
|
||||
assert!(
|
||||
serde_json::from_str::<serde_json::Value>(out.trim()).is_err(),
|
||||
"text output should not be JSON: {out:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use gpapi::{
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
};
|
||||
use log::warn;
|
||||
use std::{net::IpAddr, path::PathBuf};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Args)]
|
||||
pub(crate) struct ConnectArgs {
|
||||
@@ -54,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(
|
||||
@@ -149,17 +146,6 @@ pub(crate) struct ConnectArgs {
|
||||
num_args=0..=1
|
||||
)]
|
||||
pub(super) browser: Option<String>,
|
||||
|
||||
#[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 {
|
||||
@@ -277,23 +263,6 @@ mod tests {
|
||||
assert_eq!(cli.args.browser.as_deref(), Some("default"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_listen_accepts_ip_address() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from([
|
||||
"test",
|
||||
"portal.example.com",
|
||||
"--browser",
|
||||
"remote",
|
||||
"--browser-listen",
|
||||
"192.168.107.15",
|
||||
])
|
||||
.expect("connect args should parse");
|
||||
|
||||
assert_eq!(cli.args.browser_listen, Some("192.168.107.15".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_defaults_to_runtime_os() {
|
||||
use clap::Parser;
|
||||
@@ -429,23 +398,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);
|
||||
}
|
||||
}
|
||||
@@ -85,8 +85,6 @@ impl ConnectHandler<'_> {
|
||||
.sslkey(self.args.sslkey.as_deref())
|
||||
.key_password(key_password.as_deref())
|
||||
.browser(browser)
|
||||
.browser_listen(self.args.browser_listen)
|
||||
.log_format(self.shared_args.log_format)
|
||||
.verbose(verbose);
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
@@ -116,8 +114,7 @@ impl ConnectHandler<'_> {
|
||||
.clean(clean_auth)
|
||||
.default_browser(use_default_browser);
|
||||
|
||||
let cred = auth_launcher.cancellation(&self.cancellation).launch().await?;
|
||||
self.check_cancelled()?;
|
||||
let cred = auth_launcher.launch().await?;
|
||||
Ok(cred)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,173 +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 {
|
||||
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 {
|
||||
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"));
|
||||
}
|
||||
@@ -8,19 +8,18 @@ use std::{
|
||||
};
|
||||
|
||||
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, Vpn, VpnBuilder};
|
||||
use log::{info, warn};
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
use tokio::{runtime::Handle, task::JoinHandle};
|
||||
|
||||
use crate::session::{
|
||||
@@ -31,15 +30,15 @@ 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 +48,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 +76,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,11 +142,7 @@ 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 prelogin = prelogin(gateway, &gp_params, self.direct_gateway_prelogin_options()).await?;
|
||||
let cred = self
|
||||
.obtain_credential(&prelogin, gateway, gateway_browser_auth_allowed)
|
||||
.await?;
|
||||
@@ -182,7 +155,7 @@ impl ConnectHandler<'_> {
|
||||
.connect_gateway(
|
||||
portal,
|
||||
gateway,
|
||||
&login_session.authentication,
|
||||
&login_session.cookie,
|
||||
allow_extend_session,
|
||||
login_session.extension_auth,
|
||||
)
|
||||
@@ -190,101 +163,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()?;
|
||||
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(&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) {
|
||||
@@ -315,22 +281,9 @@ impl ConnectHandler<'_> {
|
||||
return;
|
||||
}
|
||||
|
||||
let format = self.shared_args.log_format;
|
||||
report(
|
||||
format,
|
||||
Level::Warn,
|
||||
"\nNOTE: Gateway authentication failed after portal login.",
|
||||
);
|
||||
report(
|
||||
format,
|
||||
Level::Warn,
|
||||
"NOTE: If this server also accepts direct gateway login, try:",
|
||||
);
|
||||
report(
|
||||
format,
|
||||
Level::Warn,
|
||||
&format!("NOTE: {}", direct_gateway_command(gateway)),
|
||||
);
|
||||
eprintln!("\nNOTE: Gateway authentication failed after portal login.");
|
||||
eprintln!("NOTE: If this server also accepts direct gateway login, try:");
|
||||
eprintln!("NOTE: {}", direct_gateway_command(gateway));
|
||||
}
|
||||
|
||||
async fn login_gateway(
|
||||
@@ -341,39 +294,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...");
|
||||
}
|
||||
@@ -381,58 +319,28 @@ 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),
|
||||
});
|
||||
@@ -440,10 +348,12 @@ impl ConnectHandler<'_> {
|
||||
.script(self.args.script.clone())
|
||||
.interface(self.args.interface.clone())
|
||||
.script_tun(self.args.script_tun)
|
||||
.certificate(certificate)
|
||||
.sslkey(sslkey)
|
||||
.key_password(key_password)
|
||||
.hip_source(hip_source)
|
||||
.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)
|
||||
@@ -453,7 +363,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();
|
||||
@@ -466,97 +376,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 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 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 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 lock_file = self.shared_args.lock_file.to_path_buf();
|
||||
let lock_file_on_connect = lock_file.clone();
|
||||
|
||||
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 connect_result = vpn.connect(move |vpn_session_info| {
|
||||
tunnel_established_on_connect.store(true, Ordering::SeqCst);
|
||||
write_pid_file(&lock_file_on_connect);
|
||||
|
||||
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info, log_format);
|
||||
session_task_on_connect.lock().unwrap().replace(task);
|
||||
})
|
||||
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);
|
||||
session_task_on_connect.lock().unwrap().replace(task);
|
||||
});
|
||||
tokio::pin!(worker);
|
||||
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<_>>();
|
||||
for server in unused {
|
||||
self.logout_gateway(&server).await;
|
||||
}
|
||||
}
|
||||
(&mut worker).await
|
||||
}
|
||||
};
|
||||
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 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> {
|
||||
@@ -583,9 +451,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))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -593,23 +461,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 {
|
||||
@@ -625,23 +492,6 @@ fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[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());
|
||||
@@ -652,14 +502,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]
|
||||
@@ -672,7 +522,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,226 +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!(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()?;
|
||||
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 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(|member| match member.maintenance {
|
||||
MaintenanceState::Healthy => info!(
|
||||
"Internal network — authenticated: {} (IPv4: {:?}, IPv6: {:?})",
|
||||
member.gateway, member.client_ip, member.client_ipv6
|
||||
),
|
||||
state => info!("Internal gateway {}: {state:?}", member.gateway),
|
||||
}),
|
||||
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 result = maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation, async move {
|
||||
network_signal.await.unwrap_or(SessionEndReason::NetworkChanged)
|
||||
})
|
||||
.await;
|
||||
self.sessions.replace(sessions);
|
||||
monitor_cancel.cancel();
|
||||
monitor.await.context("Internal network monitor failed")?;
|
||||
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,29 +1,20 @@
|
||||
mod args;
|
||||
mod credential;
|
||||
#[cfg(test)]
|
||||
mod flow_tests;
|
||||
mod gateway;
|
||||
mod internal;
|
||||
|
||||
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};
|
||||
use log::{Level, info, warn};
|
||||
use log::{info, warn};
|
||||
|
||||
use crate::cli::SharedArgs;
|
||||
|
||||
@@ -33,7 +24,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>,
|
||||
@@ -41,8 +31,6 @@ pub(crate) struct ConnectHandler<'a> {
|
||||
password_from_stdin: RefCell<Option<String>>,
|
||||
cookie_from_stdin: RefCell<Option<String>>,
|
||||
clean_auth_state: RefCell<CleanAuthState>,
|
||||
sessions: RefCell<GatewaySessions>,
|
||||
pid_written: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl<'a> ConnectHandler<'a> {
|
||||
@@ -55,7 +43,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)),
|
||||
@@ -63,8 +50,6 @@ impl<'a> ConnectHandler<'a> {
|
||||
password_from_stdin: Default::default(),
|
||||
cookie_from_stdin: Default::default(),
|
||||
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
|
||||
sessions: RefCell::default(),
|
||||
pid_written: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,43 +92,6 @@ 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();
|
||||
});
|
||||
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("remote"))
|
||||
{
|
||||
bail!("The '--browser-listen' option requires '--browser remote'");
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
if self.args.default_browser && self.args.browser.is_some() {
|
||||
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
|
||||
@@ -152,7 +100,6 @@ impl<'a> ConnectHandler<'a> {
|
||||
self.latest_key_password.replace(self.args.key_password.clone());
|
||||
|
||||
loop {
|
||||
self.check_cancelled()?;
|
||||
let Err(err) = self.handle_impl().await else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -163,17 +110,8 @@ impl<'a> ConnectHandler<'a> {
|
||||
|
||||
match root_cause {
|
||||
RequestIdentityError::NoKey => {
|
||||
let format = self.shared_args.log_format;
|
||||
report(
|
||||
format,
|
||||
Level::Error,
|
||||
"ERROR: No private key found in the certificate file",
|
||||
);
|
||||
report(
|
||||
format,
|
||||
Level::Error,
|
||||
"ERROR: Please provide the private key file using the `-k` option",
|
||||
);
|
||||
eprintln!("ERROR: No private key found in the certificate file");
|
||||
eprintln!("ERROR: Please provide the private key file using the `-k` option");
|
||||
return Ok(());
|
||||
}
|
||||
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
|
||||
@@ -190,7 +128,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;
|
||||
|
||||
@@ -202,11 +139,10 @@ 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(());
|
||||
@@ -217,17 +153,8 @@ impl<'a> ConnectHandler<'a> {
|
||||
info!("Trying the gateway authentication workflow...");
|
||||
self.connect_gateway_with_prelogin(server, server, false, None).await?;
|
||||
|
||||
let format = self.shared_args.log_format;
|
||||
report(
|
||||
format,
|
||||
Level::Warn,
|
||||
"\nNOTE: the server may be a gateway, not a portal.",
|
||||
);
|
||||
report(
|
||||
format,
|
||||
Level::Warn,
|
||||
"NOTE: try to use the `--as-gateway` option if you were authenticated twice.",
|
||||
);
|
||||
eprintln!("\nNOTE: the server may be a gateway, not a portal.");
|
||||
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -238,35 +165,10 @@ impl<'a> ConnectHandler<'a> {
|
||||
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
|
||||
let gp_params = self.build_gp_params();
|
||||
|
||||
let prelogin = tokio::select! {
|
||||
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 cred = self.obtain_credential(&prelogin, portal, false).await?;
|
||||
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());
|
||||
|
||||
@@ -274,6 +176,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);
|
||||
|
||||
@@ -289,27 +192,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 !err.is_before_establishment() {
|
||||
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()
|
||||
);
|
||||
@@ -340,9 +245,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)
|
||||
@@ -356,14 +258,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)
|
||||
|
||||
+536
-25
@@ -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,45 +1,26 @@
|
||||
use std::{fs, path::PathBuf};
|
||||
use std::{collections::HashMap, env::temp_dir, fs, path::PathBuf};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use std::process::{Command, ExitStatus};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use anyhow::Context;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use anyhow::bail;
|
||||
use clap::Args;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use common::binary_paths;
|
||||
use common::constants::GP_CALLBACK_PORT_FILENAME;
|
||||
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;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
#[derive(Args)]
|
||||
pub(crate) struct LaunchGuiArgs {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[arg(
|
||||
required = false,
|
||||
conflicts_with = "minimized",
|
||||
value_parser = parse_auth_callback,
|
||||
help = "The external-browser authentication callback URL"
|
||||
help = "The authentication data, used for the default browser authentication"
|
||||
)]
|
||||
callback: Option<String>,
|
||||
pub auth_data: Option<String>,
|
||||
#[arg(long, help = "Launch the GUI minimized")]
|
||||
minimized: bool,
|
||||
}
|
||||
|
||||
impl LaunchGuiArgs {
|
||||
pub(crate) fn is_auth_callback(&self) -> bool {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
return self.callback.is_some();
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct LaunchGuiHandler<'a> {
|
||||
args: &'a LaunchGuiArgs,
|
||||
}
|
||||
@@ -56,9 +37,11 @@ impl<'a> LaunchGuiHandler<'a> {
|
||||
anyhow::bail!("`launch-gui` cannot be run as root");
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
if let Some(callback) = &self.args.callback {
|
||||
return forward_auth_callback(callback);
|
||||
let auth_data = self.args.auth_data.as_deref().unwrap_or_default();
|
||||
if !auth_data.is_empty() {
|
||||
info!("Received auth callback data");
|
||||
// Process the authentication data, its format is `globalprotectcallback:<data>`
|
||||
return feed_auth_data(auth_data).await;
|
||||
}
|
||||
|
||||
if try_active_gui().await.is_ok() {
|
||||
@@ -66,13 +49,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?;
|
||||
@@ -83,36 +80,24 @@ impl<'a> LaunchGuiHandler<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
let status = auth_callback_command(callback)
|
||||
.status()
|
||||
.context("Failed to start the authentication callback handler")?;
|
||||
ensure_auth_callback_succeeded(status)
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn auth_callback_command(callback: &str) -> Command {
|
||||
let mut command = Command::new(binary_paths::gpauth());
|
||||
command.args(["auth-callback", callback]);
|
||||
command
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn ensure_auth_callback_succeeded(status: ExitStatus) -> anyhow::Result<()> {
|
||||
if !status.success() {
|
||||
bail!("Authentication callback handler exited with {status}");
|
||||
async fn feed_auth_data(auth_data: &str) -> anyhow::Result<()> {
|
||||
if let Err(err) = feed_auth_data_cli(auth_data).await {
|
||||
info!("Failed to feed auth data to the CLI: {}", err);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn parse_auth_callback(callback: &str) -> Result<String, String> {
|
||||
callback
|
||||
.starts_with("globalprotectcallback:")
|
||||
.then(|| callback.to_owned())
|
||||
.ok_or_else(|| "callback URL must use the globalprotectcallback scheme".to_owned())
|
||||
async fn feed_auth_data_cli(auth_data: &str) -> anyhow::Result<()> {
|
||||
info!("Feeding auth data to the CLI");
|
||||
|
||||
let port_file = temp_dir().join(GP_CALLBACK_PORT_FILENAME);
|
||||
let port = tokio::fs::read_to_string(port_file).await?;
|
||||
let mut stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{}", port.trim())).await?;
|
||||
|
||||
stream.write_all(auth_data.as_bytes()).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn try_active_gui() -> anyhow::Result<()> {
|
||||
@@ -135,34 +120,3 @@ fn get_log_file() -> anyhow::Result<PathBuf> {
|
||||
|
||||
Ok(dirs.data_dir().join("gpclient.log"))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
use super::*;
|
||||
|
||||
const CALLBACK: &str = "globalprotectcallback:cas-as=1&[email protected]&token=token";
|
||||
|
||||
#[test]
|
||||
fn callback_command_preserves_callback_argument() {
|
||||
let command = auth_callback_command(CALLBACK);
|
||||
let args = command
|
||||
.get_args()
|
||||
.map(|argument| argument.to_str().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(args, ["auth-callback", CALLBACK]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_command_status_is_propagated() {
|
||||
assert!(ensure_auth_callback_succeeded(ExitStatus::from_raw(0)).is_ok());
|
||||
assert!(ensure_auth_callback_succeeded(ExitStatus::from_raw(1 << 8)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_callback_url() {
|
||||
assert!(parse_auth_callback("https://example.com/callback").is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,11 @@
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use gpapi::{
|
||||
clap::report,
|
||||
gateway::{SessionContext, SessionExtensionAuth, extend_session},
|
||||
log_format::LogFormat,
|
||||
os_profile::OsProfile,
|
||||
session::{SessionInfo, SessionRequestArgs, SessionWarning},
|
||||
};
|
||||
use log::{Level, info, warn};
|
||||
use log::{info, warn};
|
||||
use openconnect::VpnSessionInfo;
|
||||
use tokio::{runtime::Handle, task::JoinHandle};
|
||||
|
||||
@@ -61,12 +59,11 @@ pub(crate) fn spawn_session_runtime_with_info(
|
||||
handle: &Handle,
|
||||
session_ctx: SessionContext,
|
||||
session_info: SessionInfo,
|
||||
log_format: LogFormat,
|
||||
) -> JoinHandle<()> {
|
||||
handle.spawn(run_session_runtime(session_ctx, session_info, log_format))
|
||||
handle.spawn(run_session_runtime(session_ctx, session_info))
|
||||
}
|
||||
|
||||
async fn run_session_runtime(session_ctx: SessionContext, mut session_info: SessionInfo, log_format: LogFormat) {
|
||||
async fn run_session_runtime(session_ctx: SessionContext, mut session_info: SessionInfo) {
|
||||
loop {
|
||||
let Some(schedule) = build_session_warning_schedule(&session_info) else {
|
||||
info!("No session warning schedule provided by the gateway");
|
||||
@@ -75,7 +72,7 @@ async fn run_session_runtime(session_ctx: SessionContext, mut session_info: Sess
|
||||
|
||||
tokio::time::sleep(schedule.delay).await;
|
||||
|
||||
report(log_format, Level::Warn, &format!("\nWARNING: {}", schedule.message));
|
||||
eprintln!("\nWARNING: {}", schedule.message);
|
||||
|
||||
if !schedule.should_auto_extend {
|
||||
info!("Session extension is not allowed by the gateway");
|
||||
@@ -90,16 +87,12 @@ async fn run_session_runtime(session_ctx: SessionContext, mut session_info: Sess
|
||||
return;
|
||||
};
|
||||
|
||||
report(log_format, Level::Info, "Session extended.");
|
||||
eprintln!("Session extended.");
|
||||
session_info = next_session_info;
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Failed to extend session: {}", err);
|
||||
report(
|
||||
log_format,
|
||||
Level::Warn,
|
||||
&format!("WARNING: Failed to extend session: {}", err),
|
||||
);
|
||||
eprintln!("WARNING: Failed to extend session: {}", err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,9 +0,0 @@
|
||||
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=e((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function ee(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,x||(x=!0,ie());else{var t=n(l);t!==null&&se(ee,t.startTime-e)}}}var x=!1,te=-1,ne=5,S=-1;function re(){return g?!0:!(e.unstable_now()-S<ne)}function C(){if(g=!1,x){var t=e.unstable_now();S=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(te),te=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&re());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&se(ee,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?ie():x=!1}}}var ie;if(typeof y==`function`)ie=function(){y(C)};else if(typeof MessageChannel<`u`){var ae=new MessageChannel,oe=ae.port2;ae.port1.onmessage=C,ie=function(){oe.postMessage(null)}}else ie=function(){_(C,0)};function se(t,n){te=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):ne=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(te),te=-1):h=!0,se(ee,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,x||(x=!0,ie()))),r},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),n=e(((e,n)=>{n.exports=t()})),r=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){Line truncated
|
||||
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
|
||||
`+ze+e+Be}var He=!1;function Ue(e,t){if(!e||He)return``;He=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}n=!1;try{var i=Object.getOwnPropertyDescriptor(e.prototype,`props`);Object.defineProperty(e.prototype,"props",{configurable:!0,set:function(){throw Error()}}),n=!0,new e}finally{n&&(i===void 0?delete e.prototype.props:Object.defineProperty(e.prototype,"props",i))}}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
|
||||
`),l=s.split(`
|
||||
`);for(i=r=0;r<c.length&&!c[r].includes(`DetermineComponentFrameRoot`);)r++;for(;i<l.length&&!l[i].includes(`DetermineComponentFrameRoot`);)i++;if(r===c.length||i===l.length)for(r=c.length-1,i=l.length-1;1<=r&&0<=i&&c[r]!==l[i];)i--;for(;1<=r&&0<=i;r--,i--)if(c[r]!==l[i]){if(r!==1||i!==1)do if(r--,i--,0>i||c[r]!==l[i]){var u=`
|
||||
`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(`<anonymous>`)&&(u=u.replace(`<anonymous>`,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{He=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Ve(n):``}function We(e,t){switch(e.tag){case 26:case 27:case 5:return Ve(e.type);case 16:return Ve(`Lazy`);case 13:return e.child!==t&&t!==null?Ve(`Suspense Fallback`):Ve(`Suspense`);case 19:return Ve(`SuspenseList`);case 0:case 15:return Ue(e.type,!1);case 11:return Ue(e.type.render,!1);case 1:return Ue(e.type,!0);case 31:return Ve(`Activity`);case 30:return Ve(`ViewTransition`);default:return``}}function Ge(e){try{var t=``,n=null;do t+=We(e,n),n=e,e=e.return;while(e);return t}catch(e){return`
|
||||
Error generating stack: `+e.message+`
|
||||
`+e.stack}}var Ke=Object.prototype.hasOwnProperty,qe=t.unstable_scheduleCallback,Je=t.unstable_cancelCallback,Ye=t.unstable_shouldYield,Xe=t.unstable_requestPaint,Ze=t.unstable_now,Qe=t.unstable_getCurrentPriorityLevel,$e=t.unstable_ImmediatePriority,et=t.unstable_UserBlockingPriority,tt=t.unstable_NormalPriority,nt=t.unstable_LowPriority,rt=t.unstable_IdlePriority,it=t.log,at=t.unstable_setDisableYieldValue,ot=null,st=null;function ct(e){if(typeof it==`function`&&at(e),st&&typeof st.setStrictMode==`function`)try{st.setStrictMode(ot,e)}catch{}}var lt=Math.clz32?Math.clz32:ft,ut=Math.log,dt=Math.LN2;function ft(e){return e>>>=0,e===0?32:31-(ut(e)/dt|0)|0}var pt=256,mt=262144,ht=4194304;function gt(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function _t(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=gt(n))):i=gt(o):i=gt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=gt(n))):i=gt(o)):i=gt(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function vt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function yt(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0<n;){var r=31-lt(n),i=1<<r;t|=e[r],n&=~i}return t}function bt(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function xt(){var e=ht;return ht<<=1,!(ht&62914560)&&(ht=4194304),e}function St(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ct(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function wt(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0<n;){var u=31-lt(n),d=1<<u;s[u]=0,c[u]=-1;var f=l[u];if(f!==null)for(l[u]=null,u=0;u<f.length;u++){var p=f[u];p!==null&&(p.lane&=-536870913)}n&=~d}r!==0&&Tt(e,r,0),a!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=a&~(o&~t))}function Tt(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-lt(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function Et(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-lt(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function Dt(e,t){var n=t&-t;return n=n&42?1:Ot(n),(n&(e.suspendedLanes|t))===0?n:0}function Ot(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function kt(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function At(){var e=E.p;return e===0?(e=window.event,e===void 0?32:Ch(e.type)):e}function jt(e,t){var n=E.p;try{return E.p=e,t()}finally{E.p=n}}var Mt=Math.random().toString(36).slice(2),Nt=`__reactFiber$`+Mt,Pt=`__reactProps$`+Mt,Ft=`__reactContainer$`+Mt,It=`__reactEvents$`+Mt,Lt=`__reactListeners$`+Mt,Rt=`__reactHandles$`+Mt,zt=`__reactResources$`+Mt,Bt=`__reactMarker$`+Mt,Vt=`__reactLoad$`+Mt;function Ht(e){delete e[Nt],delete e[Pt],delete e[Lt],delete e[Rt]}function Ut(e){var t;if(t=e[Nt])return t;for(var n=e.parentNode;n;){if(t=n[Ft]||n[Nt]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=fm(e);e!==null;){if(n=e[Nt])return n;e=fm(e)}return t}e=n,n=e.parentNode}return null}function Wt(e){if(e=e[Nt]||e[Ft]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function Gt(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(s(33))}function Kt(e){var t=e[zt];return t||=e[zt]={hoistableStyles:new Map,hoistableScripts:new Map},t}function qt(e){e[Bt]=!0}function Jt(e){e[Vt]=void 0}var Yt=new Set,Xt={};function Zt(e,t){Qt(e,t),Qt(e+`Capture`,t)}function Qt(e,t){for(Xt[e]=t,e=0;e<t.le
Line truncated
|
||||
`).replace(Qf,``)}function ep(e,t){return t=$f(t),$f(e)===t}function $(e,t,n,r,i,a){switch(n){case`children`:if(typeof r==`string`)t===`body`||t===`textarea`&&r===``||xn(e,r);else if(typeof r==`number`||typeof r==`bigint`)t!==`body`&&xn(e,``+r);else return;break;case`className`:on(e,`class`,r);break;case`tabIndex`:on(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:on(e,n,r);break;case`style`:wn(e,r,a);return;case`data`:if(t!==`object`){on(e,`data`,r);break}case`src`:case`href`:if(r===``&&(t!==`a`||n!==`href`)){e.removeAttribute(n);break}if(r==null||typeof r==`function`||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=On(r),e.setAttribute(n,r);break;case`action`:case`formAction`:if(typeof r==`function`){e.setAttribute(n,`javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')`);break}if(typeof a==`function`&&(n===`formAction`?(t!==`input`&&$(e,t,`name`,i.name,i,null),$(e,t,`formEncType`,i.formEncType,i,null),$(e,t,`formMethod`,i.formMethod,i,null),$(e,t,`formTarget`,i.formTarget,i,null)):($(e,t,`encType`,i.encType,i,null),$(e,t,`method`,i.method,i,null),$(e,t,`target`,i.target,i,null))),r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=On(r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=kn);return;case`onScroll`:r!=null&&Q(`scroll`,e);return;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);return;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(s(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(s(60));a?.__html!==n&&(e.innerHTML=n)}}break;case`multiple`:e.multiple=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`muted`:e.muted=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`defaultValue`:case`defaultChecked`:case`innerHTML`:case`ref`:break;case`autoFocus`:break;case`xlinkHref`:if(r==null||typeof r==`function`||typeof r==`boolean`||typeof r==`symbol`){e.removeAttribute(`xlink:href`);break}n=On(r),e.setAttributeNS(`http://www.w3.org/1999/xlink`,`xlink:href`,n);break;case`contentEditable`:case`spellCheck`:case`draggable`:case`value`:case`autoReverse`:case`externalResourcesRequired`:case`focusable`:case`preserveAlpha`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`inert`:case`allowFullScreen`:case`async`:case`autoPlay`:case`controls`:case`credentialless`:case`default`:case`defer`:case`disabled`:case`disablePictureInPicture`:case`disableRemotePlayback`:case`formNoValidate`:case`hidden`:case`loop`:case`noModule`:case`noValidate`:case`open`:case`playsInline`:case`readOnly`:case`required`:case`reversed`:case`scoped`:case`seamless`:case`itemScope`:r&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``):e.removeAttribute(n);break;case`capture`:case`download`:!0===r?e.setAttribute(n,``):!1!==r&&r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`cols`:case`rows`:case`size`:case`span`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case`rowSpan`:case`start`:r==null||typeof r==`function`||typeof r==`symbol`||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case`popover`:Q(`beforetoggle`,e),Q(`toggle`,e),an(e,`popover`,r);break;case`xlinkActuate`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:an(e,`is`,r);break;case`innerText`:case`textContent`:return;default:if(!(2<n.length)||n[0]!==`o`&&n[0]!==`O`||n[1]!==`n`&&n[1]!==`N`)n=En.get(n)||n,an(e,n,r);else return}O=!0}function tp(e,t,n,r,i,a){switch(n){case`style`:wn(e,r,a);return;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(s(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(s(60));a?.__html!==n&&(e.innerHTML=n)}}break;case`children`:if(typeof r==`string`)xn(e,r);else if(typeof r==`number`||typeof r==`bigint`)xn(e,``+r);else return;break;case`onScroll`:r!=null&&Q(`scroll`,e);return;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);return;case`onClick`:r!=null&&(e.onclick=k
Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
html,body,#root{-webkit-user-select:none;user-select:none;cursor:default;height:100%;margin:0;padding:0}
|
||||
@@ -1 +0,0 @@
|
||||
html,body,#root{box-sizing:border-box;-webkit-user-select:none;user-select:none;cursor:default;height:100%;margin:0;padding:0;overflow:hidden}body{color:#2e3436;background:#f6f5f4;font-family:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}button{font:inherit}.update-window{box-sizing:border-box;background:#f6f5f4;align-items:center;gap:15px;width:100%;height:100%;padding:16px 18px;display:flex}.update-logo{flex:none;width:48px;height:48px}.update-content,.update-status{width:100%;min-width:0}.update-title{color:#2e3436;letter-spacing:-.01em;margin:0;font-size:16px;font-weight:600;line-height:1.25}.update-description{color:#5e5c64;margin:3px 0 0;font-size:12px;line-height:1.4}.progress-summary{justify-content:space-between;align-items:baseline;gap:12px;margin-top:3px;display:flex}.progress-summary .update-description{margin:0}.progress-bar{background-color:#d5d3d1;border-radius:3px;width:100%;height:6px;margin-top:9px;position:relative;overflow:hidden}.progress-fill{background:#3584e4;border-radius:3px;height:100%;transition:width .18s ease-out}.progress-bar-indeterminate .progress-fill{width:35%;animation:1.4s ease-in-out infinite progress-indeterminate}@keyframes progress-indeterminate{0%{transform:translate(-110%)}to{transform:translate(300%)}}@media (prefers-reduced-motion:reduce){.progress-fill{transition:none}.progress-bar-indeterminate .progress-fill{animation:none;transform:translate(90%)}}.progress-label{color:#3d3846;font-variant-numeric:tabular-nums;text-align:right;white-space:nowrap;flex:none;font-size:12px;font-weight:500}.error-status{justify-content:space-between;align-items:center;gap:16px;display:flex}.error-status .update-title{color:#9c2f2f}.error-copy{min-width:0}.retry-button{color:#fff;cursor:pointer;background:#1c71d8;border:0;border-radius:8px;min-width:68px;padding:4px 14px;font-size:12px;font-weight:600;line-height:1.5}.retry-button:hover{background:#1a5fb4}.retry-button:active{background:#174a8b}.retry-button:focus-visible{outline-offset:2px;outline:2px solid #1a5fb4}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));(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 l=o((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}}}})),u=o(((e,t)=>{t.exports=l()})),d=o((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.
Line truncated
|
||||
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
|
||||
`+be+e+xe}var Ce=!1;function we(e,t){if(!e||Ce)return``;Ce=!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{Ce=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Se(n):``}function Te(e,t){switch(e.tag){case 26:case 27:case 5:return Se(e.type);case 16:return Se(`Lazy`);case 13:return e.child!==t&&t!==null?Se(`Suspense Fallback`):Se(`Suspense`);case 19:return Se(`SuspenseList`);case 0:case 15:return we(e.type,!1);case 11:return we(e.type.render,!1);case 1:return we(e.type,!0);case 31:return Se(`Activity`);default:return``}}function Ee(e){try{var t=``,n=null;do t+=Te(e,n),n=e,e=e.return;while(e);return t}catch(e){return`
|
||||
Error generating stack: `+e.message+`
|
||||
`+e.stack}}var De=Object.prototype.hasOwnProperty,Oe=t.unstable_scheduleCallback,ke=t.unstable_cancelCallback,Ae=t.unstable_shouldYield,je=t.unstable_requestPaint,Me=t.unstable_now,Ne=t.unstable_getCurrentPriorityLevel,Pe=t.unstable_ImmediatePriority,Fe=t.unstable_UserBlockingPriority,Ie=t.unstable_NormalPriority,Le=t.unstable_LowPriority,Re=t.unstable_IdlePriority,ze=t.log,Be=t.unstable_setDisableYieldValue,Ve=null,He=null;function Ue(e){if(typeof ze==`function`&&Be(e),He&&typeof He.setStrictMode==`function`)try{He.setStrictMode(Ve,e)}catch{}}var We=Math.clz32?Math.clz32:qe,Ge=Math.log,Ke=Math.LN2;function qe(e){return e>>>=0,e===0?32:31-(Ge(e)/Ke|0)|0}var Je=256,Ye=262144,Xe=4194304;function Ze(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 Qe(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=Ze(n))):i=Ze(o):i=Ze(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Ze(n))):i=Ze(o)):i=Ze(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 $e(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function et(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 tt(){var e=Xe;return Xe<<=1,!(Xe&62914560)&&(Xe=4194304),e}function nt(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function rt(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function it(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-We(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&&at(e,r,0),a!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=a&~(o&~t))}function at(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-We(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function ot(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-We(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function st(e,t){var n=t&-t;return n=n&42?1:ct(n),(n&(e.suspendedLanes|t))===0?n:0}function ct(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 lt(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function ut(){var e=O.p;return e===0?(e=window.event,e===void 0?32:mp(e.type)):e}function dt(e,t){var n=O.p;try{return O.p=e,t()}finally{O.p=n}}var ft=Math.random().toString(36).slice(2),pt=`__reactFiber$`+ft,mt=`__reactProps$`+ft,ht=`__reactContainer$`+ft,gt=`__reactEvents$`+ft,_t=`__reactListeners$`+ft,vt=`__reactHandles$`+ft,yt=`__reactResources$`+ft,bt=`__reactMarker$`+ft;function xt(e){delete e[pt],delete e[mt],delete e[gt],delete e[_t],delete e[vt]}function St(e){var t=e[pt];if(t)return t;for(var n=e.parentNode;n;){if(t=n[ht]||n[pt]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=df(e);e!==null;){if(n=e[pt])return n;e=df(e)}return t}e=n,n=e.parentNode}return null}function Ct(e){if(e=e[pt]||e[ht]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function wt(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(i(33))}function Tt(e){var t=e[yt];return t||=e[yt]={hoistableStyles:new Map,hoistableScripts:new Map},t}function Et(e){e[bt]=!0}var Dt=new Set,Ot={};function kt(e,t){At(e,t),At(e+`Capture`,t)}function At(e,t){for(Ot[e]=t,e=0;e<t.length;e++)Dt.add(t[e])}var jt=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,a,o){switch(n){case`children`:typeof r==`string`?t===`body`||t===`textarea`&&r===``||Zt(e,r):(typeof r==`number`||typeof r==`bigint`)&&t!==`body`&&Zt(e,``+r);break;case`className`:Ft(e,`class`,r);break;case`tabIndex`:Ft(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:Ft(e,n,r);break;case`style`:en(e,r,o);break;case`data`:if(t!==`object`){Ft(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=an(``+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 o==`function`&&(n===`formAction`?(t!==`input`&&$(e,t,`name`,a.name,a,null),$(e,t,`formEncType`,a.formEncType,a,null),$(e,t,`formMethod`,a.formMethod,a,null),$(e,t,`formTarget`,a.formTarget,a,null)):($(e,t,`encType`,a.encType,a,null),$(e,t,`method`,a.method,a,null),$(e,t,`target`,a.target,a,null)));if(r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=an(``+r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=on);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(i(61));if(n=r.__html,n!=null){if(a.children!=null)throw Error(i(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=an(``+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),Pt(e,`popover`,r);break;case`xlinkActuate`:It(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:It(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:It(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:It(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:It(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:It(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:Pt(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=nn.get(n)||n,Pt(e,n,r))}}function Nd(e,t,n,r,a,o){switch(n){case`style`:en(e,r,o);break;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(i(61));if(n=r.__html,n!=null){if(a.children!=null)throw Error(i(60));e.innerHTML=n}}break;case`children`:typeof r==`string`?Zt(e,r):(typeof r==`number`||typeof r==`bigint`)&&Zt(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=on);break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`innerHTML`:case`re
Line truncated
|
||||
|
||||
const theme = ${JSON.stringify(t,null,2)};
|
||||
|
||||
theme.breakpoints = createBreakpoints(theme.breakpoints || {});
|
||||
theme.transitions = createTransitions(theme.transitions || {});
|
||||
|
||||
export default theme;`}function xa(e){return typeof e==`number`?`${(e*100).toFixed(0)}%`:`calc((${e}) * 100%)`}var Sa=e=>{if(!Number.isNaN(+e))return+e;let t=e.match(/\d*\.?\d+/g);if(!t)return 0;let n=0;for(let e=0;e<t.length;e+=1)n+=+t[e];return n};function Ca(e){Object.assign(e,{alpha(t,n){let r=this||e;return r.colorSpace?`oklch(from ${t} l c h / ${typeof n==`string`?`calc(${n})`:n})`:r.vars?`rgba(${t.replace(/var\(--([^,\s)]+)(?:,[^)]+)?\)+/g,`var(--$1Channel)`)} / ${typeof n==`string`?`calc(${n})`:n})`:bi(t,Sa(n))},lighten(t,n){let r=this||e;return r.colorSpace?`color-mix(in ${r.colorSpace}, ${t}, #fff ${xa(n)})`:Ci(t,n)},darken(t,n){let r=this||e;return r.colorSpace?`color-mix(in ${r.colorSpace}, ${t}, #000 ${xa(n)})`:Si(t,n)}})}function wa(e={},...t){let{breakpoints:n,mixins:r={},spacing:i,palette:a={},transitions:o={},typography:s={},shape:c,colorSpace:l,...u}=e;if(e.vars&&e.generateThemeVars===void 0)throw Error(ee(20));let d=na({...a,colorSpace:l}),f=Nr(e),p=vn(f,{mixins:ia(f.breakpoints,r),palette:d,shadows:fa.slice(),typography:ca(d,s),transitions:_a(o),zIndex:{...va}});return p=vn(p,u),p=t.reduce((e,t)=>vn(e,t),p),p.unstable_sxConfig={...Dr,...u?.unstable_sxConfig},p.unstable_sx=function(e){return jr({sx:e,theme:this})},p.toRuntimeSource=ba,Ca(p),p}function Ta(e){let t;return t=e<1?5.11916*e**2:4.5*Math.log(e+1)+2,Math.round(t*10)/1e3}var Ea=[...Array(25)].map((e,t)=>{if(t===0)return`none`;let n=Ta(t);return`linear-gradient(rgba(255 255 255 / ${n}), rgba(255 255 255 / ${n}))`});function Da(e){return{inputPlaceholder:e===`dark`?.5:.42,inputUnderline:e===`dark`?.7:.42,switchTrackDisabled:e===`dark`?.2:.12,switchTrack:e===`dark`?.3:.38}}function Oa(e){return e===`dark`?Ea:[]}function ka(e){let{palette:t={mode:`light`},opacity:n,overlays:r,colorSpace:i,...a}=e,o=na({...t,colorSpace:i});return{palette:o,opacity:{...Da(o.mode),...n},overlays:r||Oa(o.mode),...a}}function Aa(e){return!!e[0].match(/(cssVarPrefix|colorSchemeSelector|modularCssLayers|rootSelector|typography|mixins|breakpoints|direction|transitions)/)||!!e[0].match(/sxConfig$/)||e[0]===`palette`&&!!e[1]?.match(/(mode|contrastThreshold|tonalOffset)/)}var ja=e=>[...[...Array(25)].map((t,n)=>`--${e?`${e}-`:``}overlays-${n}`),`--${e?`${e}-`:``}palette-AppBar-darkBg`,`--${e?`${e}-`:``}palette-AppBar-darkColor`],Ma=e=>(t,n)=>{let r=e.rootSelector||`:root`,i=e.colorSchemeSelector,a=i;if(i===`class`&&(a=`.%s`),i===`data`&&(a=`[data-%s]`),i?.startsWith(`data-`)&&!i.includes(`%s`)&&(a=`[${i}="%s"]`),e.defaultColorScheme===t){if(t===`dark`){let i={};return ja(e.cssVarPrefix).forEach(e=>{i[e]=n[e],delete n[e]}),a===`media`?{[r]:n,"@media (prefers-color-scheme: dark)":{[r]:i}}:a?{[a.replace(`%s`,t)]:i,[`${r}, ${a.replace(`%s`,t)}`]:n}:{[r]:{...n,...i}}}if(a&&a!==`media`)return`${r}, ${a.replace(`%s`,String(t))}`}else if(t){if(a===`media`)return{[`@media (prefers-color-scheme: ${String(t)})`]:{[r]:n}};if(a)return a.replace(`%s`,String(t))}return r};function Na(e,t){t.forEach(t=>{e[t]||(e[t]={})})}function B(e,t,n){!e[t]&&n&&(e[t]=n)}function Pa(e){return typeof e!=`string`||!e.startsWith(`hsl`)?e:_i(e)}function Fa(e,t){`${t}Channel`in e||(e[`${t}Channel`]=hi(Pa(e[t]),`MUI: Can't create \`palette.${t}Channel\` because \`palette.${t}\` is not one of these formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color().
|
||||
To suppress this warning, you need to explicitly provide the \`palette.${t}Channel\` as a string (in rgb format, for example "12 12 12") or undefined if you want to remove the channel token.`))}function Ia(e){return typeof e==`number`?`${e}px`:typeof e==`string`||typeof e==`function`||Array.isArray(e)?e:`8px`}var La=e=>{try{return e()}catch{}},Ra=(e=`mui`)=>R(e);function za(e,t,n,r,i){if(!n)return;n=n===!0?{}:n;let a=i===`dark`?`dark`:`light`;if(!r){t[i]=ka({...n,palette:{mode:a,...n?.palette},colorSpace:e});return}let{palette:o,...s}=wa({...r,palette:{mode:a,...n?.palette},colorSpace:e});return t[i]={...n,palette:o,opacity:{...Da(a),...n?.opacity},overlays:n?.overlays||Oa(a)},s}function Ba(e={},...t){let{colorSchemes:n={light:!0},defaultColorScheme:r,disableCssColorScheme:i=!1,cssVarPrefix:a=`mui`,nativeColor:o=!1,shouldSkipGeneratingVar:s=Aa,colorSchemeSelector:c=n.light&&n.dark?`media`:void 0,rootSelector:l=`:root`,...u}=e,d=Object.keys(n)[0],f=r||(n.light&&d!==`light`?`light`:d),p=Ra(a),{[f]:m,light:h,dark:g,..._}=n,v={..._},y=m;if((f===`dark`&&!(`dark`in n)||f===`light`&&!(`light`in n))&&(y=!0),!y)throw Error(ee(21,f));let b;o&&(b=`oklch`);let x=za(b,v,y,u,f);h&&!v.light&&za(b,v,h,void 0,`light`),g&&!v.dark&&za(b,v,g,void 0,`dark`);let S={defaultColorScheme:f,...x,cssVarPrefix:a,colorSchemeSelector:c,rootSelector:l,getCssVar:p,colorSchemes:v,font:{...ra(x.typography),...x.font},spacing:Ia(u.spacing)};Object.keys(S.colorSchemes).forEach(e=>{let t=S.colorSchemes[e].palette,n=e=>{let n=e.split(`-`),r=n[1],i=n[2];return p(e,t[r][i])};t.mode===`light`&&(B(t.common,`background`,`#fff`),B(t.common,`onBackground`,`#000`)),t.mode===`dark`&&(B(t.common,`background`,`#000`),B(t.common,`onBackground`,`#fff`));function r(e,t,n){if(b){let r;return e===xi&&(r=`transparent ${((1-n)*100).toFixed(0)}%`),e===F&&(r=`#000 ${(n*100).toFixed(0)}%`),e===I&&(r=`#fff ${(n*100).toFixed(0)}%`),`color-mix(in ${b}, ${t}, ${r})`}return e(t,n)}if(Na(t,[`Alert`,`AppBar`,`Avatar`,`Button`,`Chip`,`FilledInput`,`LinearProgress`,`Skeleton`,`Slider`,`SnackbarContent`,`SpeedDialAction`,`StepConnector`,`StepContent`,`Switch`,`TableCell`,`Tooltip`]),t.mode===`light`){B(t.Alert,`errorColor`,r(F,o?p(`palette-error-light`):t.error.light,.6)),B(t.Alert,`infoColor`,r(F,o?p(`palette-info-light`):t.info.light,.6)),B(t.Alert,`successColor`,r(F,o?p(`palette-success-light`):t.success.light,.6)),B(t.Alert,`warningColor`,r(F,o?p(`palette-warning-light`):t.warning.light,.6)),B(t.Alert,`errorFilledBg`,n(`palette-error-main`)),B(t.Alert,`infoFilledBg`,n(`palette-info-main`)),B(t.Alert,`successFilledBg`,n(`palette-success-main`)),B(t.Alert,`warningFilledBg`,n(`palette-warning-main`)),B(t.Alert,`errorFilledColor`,La(()=>t.getContrastText(t.error.main))),B(t.Alert,`infoFilledColor`,La(()=>t.getContrastText(t.info.main))),B(t.Alert,`successFilledColor`,La(()=>t.getContrastText(t.success.main))),B(t.Alert,`warningFilledColor`,La(()=>t.getContrastText(t.warning.main))),B(t.Alert,`errorStandardBg`,r(I,o?p(`palette-error-light`):t.error.light,.9)),B(t.Alert,`infoStandardBg`,r(I,o?p(`palette-info-light`):t.info.light,.9)),B(t.Alert,`successStandardBg`,r(I,o?p(`palette-success-light`):t.success.light,.9)),B(t.Alert,`warningStandardBg`,r(I,o?p(`palette-warning-light`):t.warning.light,.9)),B(t.Alert,`errorIconColor`,n(`palette-error-main`)),B(t.Alert,`infoIconColor`,n(`palette-info-main`)),B(t.Alert,`successIconColor`,n(`palette-success-main`)),B(t.Alert,`warningIconColor`,n(`palette-warning-main`)),B(t.AppBar,`defaultBg`,n(`palette-grey-100`)),B(t.Avatar,`defaultBg`,n(`palette-grey-400`)),B(t.Button,`inheritContainedBg`,n(`palette-grey-300`)),B(t.Button,`inheritContainedHoverBg`,n(`palette-grey-A100`)),B(t.Chip,`defaultBorder`,n(`palette-grey-400`)),B(t.Chip,`defaultAvatarColor`,n(`palette-grey-700`)),B(t.Chip,`defaultIconColor`,n(`palette-grey-700`)),B(t.FilledInput,`bg`,`rgba(0, 0, 0, 0.06)`),B(t.FilledInput,`hoverBg`,`rgba(0, 0, 0, 0.09)`),B(t.FilledInput,`disabledBg`,`rgba(0, 0, 0, 0.12)`),B(t.LinearProgress,`primaryBg`,r(I,o?p(`palette-primary-main`):t.primary.main,.62)),B(t.LinearProgress,`secondaryBg`,r(I,o?p(`palette-secondary-main`):t.secondary.main,.62)),B(t.LinearProgress,`errorBg`,r(I,o?p(`palette-error-main`):t.error.main,.62)),B(t.LinearProgress,`infoBg`,r(I,o?p(`palette-info-main`):t.info.main,.62)),B(t.LinearProgress,`successBg`,r(I,o?p(`palette-success-main`):t.success.main,.62)),B(t.LinearProgress,`warningBg`,r(I,o?p(`palette-warning-light`):t.warning.main,.62)),B(t.Skeleton,`bg`,b?r(xi,o?p(`palette-text-primary`):t.text.primary,.11):`rgba(${n(`palette-text-primaryChannel`)} / 0.11)`),B(t.Slider,`primaryTrack`,r(I,o?p(`palette-primary-main`):t.primary.main,.62)),B(t.Slider,`secondaryTrack`,r(I,o?p(`palette-secondary-main`):t.secondary.main,.62)),B(t.Slider,`errorTrack`,r(I,o?p(`palette-error-main`):t.error.main,.62)),B(t.Slider,`infoTrack`,r(I,o?p(`palette-info-main`):t.info.main,.62)),B(t.Slider,`successTrack`,r(I,o?p(`palette-success-main`):t.succLine truncated
|
||||
0% {
|
||||
transform: scale(0);
|
||||
opacity: 0.1;
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: scale(1);
|
||||
opacity: 0.3;
|
||||
}
|
||||
`,ko=Jt`
|
||||
0% {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
`,Ao=Jt`
|
||||
0% {
|
||||
transform: scale(1);
|
||||
}
|
||||
|
||||
50% {
|
||||
transform: scale(0.92);
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: scale(1);
|
||||
}
|
||||
`,jo=Ka(`span`,{name:`MuiTouchRipple`,slot:`Root`})({overflow:`hidden`,pointerEvents:`none`,position:`absolute`,zIndex:0,top:0,right:0,bottom:0,left:0,borderRadius:`inherit`}),Mo=Ka(To,{name:`MuiTouchRipple`,slot:`Ripple`})`
|
||||
opacity: 0;
|
||||
position: absolute;
|
||||
|
||||
&.${Eo.rippleVisible} {
|
||||
opacity: 0.3;
|
||||
transform: scale(1);
|
||||
animation-name: ${Oo};
|
||||
animation-duration: ${Do}ms;
|
||||
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
|
||||
}
|
||||
|
||||
&.${Eo.ripplePulsate} {
|
||||
animation-duration: ${({theme:e})=>e.transitions.duration.shorter}ms;
|
||||
}
|
||||
|
||||
& .${Eo.child} {
|
||||
opacity: 1;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
background-color: currentColor;
|
||||
}
|
||||
|
||||
& .${Eo.childLeaving} {
|
||||
opacity: 0;
|
||||
animation-name: ${ko};
|
||||
animation-duration: ${Do}ms;
|
||||
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
|
||||
}
|
||||
|
||||
& .${Eo.childPulsate} {
|
||||
position: absolute;
|
||||
/* @noflip */
|
||||
left: 0px;
|
||||
top: 0;
|
||||
animation-name: ${Ao};
|
||||
animation-duration: 2500ms;
|
||||
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
|
||||
animation-iteration-count: infinite;
|
||||
animation-delay: 200ms;
|
||||
}
|
||||
`,No=M.forwardRef(function(e,t){let{center:n=!1,classes:r={},className:i,...a}=Za({props:e,name:`MuiTouchRipple`}),[o,s]=M.useState([]),c=M.useRef(0),l=M.useRef(null);M.useEffect(()=>{l.current&&=(l.current(),null)},[o]);let u=M.useRef(!1),d=bo(),f=M.useRef(null),p=M.useRef(null),m=M.useCallback(e=>{let{pulsate:t,rippleX:n,rippleY:i,rippleSize:a,cb:o}=e;s(e=>[...e,(0,N.jsx)(Mo,{classes:{ripple:Gr(r.ripple,Eo.ripple),rippleVisible:Gr(r.rippleVisible,Eo.rippleVisible),ripplePulsate:Gr(r.ripplePulsate,Eo.ripplePulsate),child:Gr(r.child,Eo.child),childLeaving:Gr(r.childLeaving,Eo.childLeaving),childPulsate:Gr(r.childPulsate,Eo.childPulsate)},timeout:Do,pulsate:t,rippleX:n,rippleY:i,rippleSize:a},c.current)]),c.current+=1,l.current=o},[r]),h=M.useCallback((e={},t={},r=()=>{})=>{let{pulsate:i=!1,center:a=n||t.pulsate,fakeElement:o=!1}=t;if(e?.type===`mousedown`&&u.current){u.current=!1;return}e?.type===`touchstart`&&(u.current=!0);let s=o?null:p.current,c=s?s.getBoundingClientRect():{width:0,height:0,left:0,top:0},l,h,g;if(a||e===void 0||e.clientX===0&&e.clientY===0||!e.clientX&&!e.touches)l=Math.round(c.width/2),h=Math.round(c.height/2);else{let{clientX:t,clientY:n}=e.touches&&e.touches.length>0?e.touches[0]:e;l=Math.round(t-c.left),h=Math.round(n-c.top)}if(a)g=Math.sqrt((2*c.width**2+c.height**2)/3),g%2==0&&(g+=1);else{let e=Math.max(Math.abs((s?s.clientWidth:0)-l),l)*2+2,t=Math.max(Math.abs((s?s.clientHeight:0)-h),h)*2+2;g=Math.sqrt(e**2+t**2)}e?.touches?f.current===null&&(f.current=()=>{m({pulsate:i,rippleX:l,rippleY:h,rippleSize:g,cb:r})},d.start(80,()=>{f.current&&=(f.current(),null)})):m({pulsate:i,rippleX:l,rippleY:h,rippleSize:g,cb:r})},[n,m,d]),g=M.useCallback(()=>{h({},{pulsate:!0})},[h]),_=M.useCallback((e,t)=>{if(d.clear(),e?.type===`touchend`&&f.current){f.current(),f.current=null,d.start(0,()=>{_(e,t)});return}f.current=null,s(e=>e.length>0?e.slice(1):e),l.current=t},[d]);return M.useImperativeHandle(t,()=>({pulsate:g,start:h,stop:_}),[g,h,_]),(0,N.jsx)(jo,{className:Gr(Eo.root,r.root,i),ref:p,...a,children:(0,N.jsx)(mo,{component:null,exit:!0,children:o})})});function Po(e){return Jr(`MuiButtonBase`,e)}var Fo=Yr(`MuiButtonBase`,[`root`,`disabled`,`focusVisible`]),Io=e=>{let{disabled:t,focusVisible:n,focusVisibleClassName:r,classes:i}=e,a=Hi({root:[`root`,t&&`disabled`,n&&`focusVisible`]},Po,i);return n&&r&&(a.root+=` ${r}`),a},Lo=Ka(`button`,{name:`MuiButtonBase`,slot:`Root`})({display:`inline-flex`,alignItems:`center`,justifyContent:`center`,position:`relative`,boxSizing:`border-box`,WebkitTapHighlightColor:`transparent`,backgroundColor:`transparent`,outline:0,border:0,margin:0,borderRadius:0,padding:0,cursor:`pointer`,userSelect:`none`,verticalAlign:`middle`,MozAppearance:`none`,WebkitAppearance:`none`,textDecoration:`none`,color:`inherit`,"&::-moz-focus-inner":{borderStyle:`none`},[`&.${Fo.disabled}`]:{pointerEvents:`none`,cursor:`default`},"@media print":{colorAdjust:`exact`}}),Ro=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiButtonBase`}),{action:r,centerRipple:i=!1,children:a,className:o,component:s=`button`,disabled:c=!1,disableRipple:l=!1,disableTouchRipple:u=!1,focusRipple:d=!1,focusVisibleClassName:f,LinkComponent:p=`a`,onBlur:m,onClick:h,onContextMenu:g,onDragLeave:_,onFocus:v,onFocusVisible:y,onKeyDown:b,onKeyUp:x,onMouseDown:S,onMouseLeave:C,onMouseUp:w,onTouchEnd:ee,onTouchMove:te,onTouchStart:ne,tabIndex:re=0,TouchRippleProps:ie,touchRippleRef:ae,type:oe,...T}=n,se=M.useRef(null),E=Co(),ce=no(E.ref,ae),[D,O]=M.useState(!1);c&&D&&O(!1),M.useImperativeHandle(r,()=>({focusVisible:()=>{O(!0),se.current.focus()}}),[]);let le=E.shouldMount&&!l&&!c;M.useEffect(()=>{D&&d&&!l&&E.pulsate()},[l,d,D,E]);let ue=zo(E,`start`,S,u),de=zo(E,`stop`,g,u),fe=zo(E,`stop`,_,u),pe=zo(E,`stop`,w,u),k=zo(E,`stop`,e=>{D&&e.preventDefault(),C&&C(e)},u),me=zo(E,`start`,ne,u),he=zo(E,`stop`,ee,u),ge=zo(E,`stop`,te,u),A=zo(E,`stop`,e=>{xo(e.target)||O(!1),m&&m(e)},!1),_e=eo(e=>{se.current||=e.currentTarget,xo(e.target)&&(O(!0),y&&y(e)),v&&v(e)}),j=()=>{let e=se.current;return e?e.tagName===`BUTTON`?!1:!(e.tagName===`A`&&e.href):s&&s!==`button`},ve=eo(e=>{d&&!e.repeat&&D&&e.key===` `&&E.stop(e,()=>{E.start(e)}),e.target===e.currentTarget&&j()&&e.key===` `&&e.preventDefault(),b&&b(e),e.target===e.currentTarget&&j()&&e.key===`Enter`&&!c&&(e.preventDefault(),h&&h(e))}),ye=eo(e=>{d&&e.key===` `&&D&&!e.defaultPrevented&&E.stop(e,()=>{E.pulsate(e)}),x&&x(e),h&&e.target===e.currentTarget&&j()&&e.key===` `&&!e.defaultPrevented&&!c&&h(e)}),be=s;be===`button`&&(T.href||T.to)&&(be=p);let xe={};if(be===`button`){let e=!!T.formAction;xe.type=oe===void 0&&!e?`button`:oe,xe.disabled=c}else !T.href&&!T.to&&(xe.role=`button`),c&&(xe[`aria-disabled`]=c);let Se=no(t,se),Ce={...n,centerRipple:i,component:s,disabled:c,disableRipple:l,disableTouchRipple:u,focusRipple:d,tabIndex:re,focusVisible:D},we=Io(Ce);return(0,N.jsxs)(Lo,{as:be,className:Gr(we.root,o),ownerState:Ce,onBlur:A,onClick:h,onContextMenu:de,onFocus:_e,onKeyDown
Line truncated
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
`,Ko=Jt`
|
||||
0% {
|
||||
stroke-dasharray: 1px, 200px;
|
||||
stroke-dashoffset: 0;
|
||||
}
|
||||
|
||||
50% {
|
||||
stroke-dasharray: 100px, 200px;
|
||||
stroke-dashoffset: -15px;
|
||||
}
|
||||
|
||||
100% {
|
||||
stroke-dasharray: 1px, 200px;
|
||||
stroke-dashoffset: -126px;
|
||||
}
|
||||
`,qo=typeof Go==`string`?null:qt`
|
||||
animation: ${Go} 1.4s linear infinite;
|
||||
`,Jo=typeof Ko==`string`?null:qt`
|
||||
animation: ${Ko} 1.4s ease-in-out infinite;
|
||||
`,Yo=e=>{let{classes:t,variant:n,color:r,disableShrink:i}=e;return Hi({root:[`root`,n,`color${V(r)}`],svg:[`svg`],track:[`track`],circle:[`circle`,`circle${V(n)}`,i&&`circleDisableShrink`]},Uo,t)},Xo=Ka(`span`,{name:`MuiCircularProgress`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[n.variant],t[`color${V(n.color)}`]]}})(Xa(({theme:e})=>({display:`inline-block`,variants:[{props:{variant:`determinate`},style:{transition:e.transitions.create(`transform`)}},{props:{variant:`indeterminate`},style:qo||{animation:`${Go} 1.4s linear infinite`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{color:(e.vars||e).palette[t].main}}))]}))),Zo=Ka(`svg`,{name:`MuiCircularProgress`,slot:`Svg`})({display:`block`}),Qo=Ka(`circle`,{name:`MuiCircularProgress`,slot:`Circle`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.circle,t[`circle${V(n.variant)}`],n.disableShrink&&t.circleDisableShrink]}})(Xa(({theme:e})=>({stroke:`currentColor`,variants:[{props:{variant:`determinate`},style:{transition:e.transitions.create(`stroke-dashoffset`)}},{props:{variant:`indeterminate`},style:{strokeDasharray:`80px, 200px`,strokeDashoffset:0}},{props:({ownerState:e})=>e.variant===`indeterminate`&&!e.disableShrink,style:Jo||{animation:`${Ko} 1.4s ease-in-out infinite`}}]}))),$o=Ka(`circle`,{name:`MuiCircularProgress`,slot:`Track`})(Xa(({theme:e})=>({stroke:`currentColor`,opacity:(e.vars||e).palette.action.activatedOpacity}))),es=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiCircularProgress`}),{className:r,color:i=`primary`,disableShrink:a=!1,enableTrackSlot:o=!1,size:s=40,style:c,thickness:l=3.6,value:u=0,variant:d=`indeterminate`,...f}=n,p={...n,color:i,disableShrink:a,size:s,thickness:l,value:u,variant:d,enableTrackSlot:o},m=Yo(p),h={},g={},_={};if(d===`determinate`){let e=2*Math.PI*((Wo-l)/2);h.strokeDasharray=e.toFixed(3),_[`aria-valuenow`]=Math.round(u),h.strokeDashoffset=`${((100-u)/100*e).toFixed(3)}px`,g.transform=`rotate(-90deg)`}return(0,N.jsx)(Xo,{className:Gr(m.root,r),style:{width:s,height:s,...g,...c},ownerState:p,ref:t,role:`progressbar`,..._,...f,children:(0,N.jsxs)(Zo,{className:m.svg,ownerState:p,viewBox:`${Wo/2} ${Wo/2} ${Wo} ${Wo}`,children:[o?(0,N.jsx)($o,{className:m.track,ownerState:p,cx:Wo,cy:Wo,r:(Wo-l)/2,fill:`none`,strokeWidth:l,"aria-hidden":`true`}):null,(0,N.jsx)(Qo,{className:m.circle,style:h,ownerState:p,cx:Wo,cy:Wo,r:(Wo-l)/2,fill:`none`,strokeWidth:l})]})})});function ts(e){return Jr(`MuiTypography`,e)}Yr(`MuiTypography`,[`root`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`subtitle1`,`subtitle2`,`body1`,`body2`,`inherit`,`button`,`caption`,`overline`,`alignLeft`,`alignRight`,`alignCenter`,`alignJustify`,`noWrap`,`gutterBottom`,`paragraph`]);var ns={primary:!0,secondary:!0,error:!0,info:!0,success:!0,warning:!0,textPrimary:!0,textSecondary:!0,textDisabled:!0},rs=Ya(),is=e=>{let{align:t,gutterBottom:n,noWrap:r,paragraph:i,variant:a,classes:o}=e;return Hi({root:[`root`,a,e.align!==`inherit`&&`align${V(t)}`,n&&`gutterBottom`,r&&`noWrap`,i&&`paragraph`]},ts,o)},as=Ka(`span`,{name:`MuiTypography`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,n.variant&&t[n.variant],n.align!==`inherit`&&t[`align${V(n.align)}`],n.noWrap&&t.noWrap,n.gutterBottom&&t.gutterBottom,n.paragraph&&t.paragraph]}})(Xa(({theme:e})=>({margin:0,variants:[{props:{variant:`inherit`},style:{font:`inherit`,lineHeight:`inherit`,letterSpacing:`inherit`}},...Object.entries(e.typography).filter(([e,t])=>e!==`inherit`&&t&&typeof t==`object`).map(([e,t])=>({props:{variant:e},style:t})),...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{color:(e.vars||e).palette[t].main}})),...Object.entries(e.palette?.text||{}).filter(([,e])=>typeof e==`string`).map(([t])=>({props:{color:`text${V(t)}`},style:{color:(e.vars||e).palette.text[t]}})),{props:({ownerState:e})=>e.align!==`inherit`,style:{textAlign:`var(--Typography-textAlign)`}},{props:({ownerState:e})=>e.noWrap,style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`}},{props:({ownerState:e})=>e.gutterBottom,style:{marginBottom:`0.35em`}},{props:({ownerState:e})=>e.paragraph,style:{marginBottom:16}}]}))),os={h1:`h1`,h2:`h2`,h3:`h3`,h4:`h4`,h5:`h5`,h6:`h6`,subtitle1:`h6`,subtitle2:`h6`,body1:`p`,body2:`p`,inherit:`p`},ss=M.forwardRef(function(e,t){let{color:n,...r}=Za({props:e,name:`MuiTypography`}),i=!ns[n],a=rs({...r,...i&&{color:n}}),{align:o=`inherit`,className:s,component:c,gutterBottom:l=!1,noWrap:u=!1,paragraph:d=!1,variant:f=`body1`,variantMapping:p=os,...m}=a,h={...a,align:o,color:n,className:s,component:c,gutterBottom:l,noWrap:u,paragraph:d,variant:f,variantMapping:p};return(0,N.jsx)(as,{as:c||(d?`p`:p[f]||os[f])||`span`,ref:t,className:Gr(is(h).root,s),...m,ownerState:h,style:{...o!==`inherit`&&{"--Typography-textAlign":o},...m.style}})}),cs=Yr(`MuiBox`,[`root`]),ls=Kr({themeId:te,defaultTheme:Ha(),defaultClassName:cs.root,generateClassName:Ur.generate});function us(e){return
Line truncated
|
||||
0% {
|
||||
left: -35%;
|
||||
right: 100%;
|
||||
}
|
||||
|
||||
60% {
|
||||
left: 100%;
|
||||
right: -90%;
|
||||
}
|
||||
|
||||
100% {
|
||||
left: 100%;
|
||||
right: -90%;
|
||||
}
|
||||
`,Ns=typeof Ms==`string`?null:qt`
|
||||
animation: ${Ms} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
|
||||
`,Ps=Jt`
|
||||
0% {
|
||||
left: -200%;
|
||||
right: 100%;
|
||||
}
|
||||
|
||||
60% {
|
||||
left: 107%;
|
||||
right: -8%;
|
||||
}
|
||||
|
||||
100% {
|
||||
left: 107%;
|
||||
right: -8%;
|
||||
}
|
||||
`,Fs=typeof Ps==`string`?null:qt`
|
||||
animation: ${Ps} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
|
||||
`,Is=Jt`
|
||||
0% {
|
||||
opacity: 1;
|
||||
background-position: 0 -23px;
|
||||
}
|
||||
|
||||
60% {
|
||||
opacity: 0;
|
||||
background-position: 0 -23px;
|
||||
}
|
||||
|
||||
100% {
|
||||
opacity: 1;
|
||||
background-position: -200px -23px;
|
||||
}
|
||||
`,Ls=typeof Is==`string`?null:qt`
|
||||
animation: ${Is} 3s infinite linear;
|
||||
`,Rs=e=>{let{classes:t,variant:n,color:r}=e;return Hi({root:[`root`,`color${V(r)}`,n],dashed:[`dashed`,`dashedColor${V(r)}`],bar1:[`bar`,`bar1`,`barColor${V(r)}`,(n===`indeterminate`||n===`query`)&&`bar1Indeterminate`,n===`determinate`&&`bar1Determinate`,n===`buffer`&&`bar1Buffer`],bar2:[`bar`,`bar2`,n!==`buffer`&&`barColor${V(r)}`,n===`buffer`&&`color${V(r)}`,(n===`indeterminate`||n===`query`)&&`bar2Indeterminate`,n===`buffer`&&`bar2Buffer`]},As,t)},zs=(e,t)=>e.vars?e.vars.palette.LinearProgress[`${t}Bg`]:e.palette.mode===`light`?e.lighten(e.palette[t].main,.62):e.darken(e.palette[t].main,.5),Bs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[`color${V(n.color)}`],t[n.variant]]}})(Xa(({theme:e})=>({position:`relative`,overflow:`hidden`,display:`block`,height:4,zIndex:0,"@media print":{colorAdjust:`exact`},variants:[...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{backgroundColor:zs(e,t)}})),{props:({ownerState:e})=>e.color===`inherit`&&e.variant!==`buffer`,style:{"&::before":{content:`""`,position:`absolute`,left:0,top:0,right:0,bottom:0,backgroundColor:`currentColor`,opacity:.3}}},{props:{variant:`buffer`},style:{backgroundColor:`transparent`}},{props:{variant:`query`},style:{transform:`rotate(180deg)`}}]}))),Vs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Dashed`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.dashed,t[`dashedColor${V(n.color)}`]]}})(Xa(({theme:e})=>({position:`absolute`,marginTop:0,height:`100%`,width:`100%`,backgroundSize:`10px 10px`,backgroundPosition:`0 -23px`,variants:[{props:{color:`inherit`},style:{opacity:.3,backgroundImage:`radial-gradient(currentColor 0%, currentColor 16%, transparent 42%)`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>{let n=zs(e,t);return{props:{color:t},style:{backgroundImage:`radial-gradient(${n} 0%, ${n} 16%, transparent 42%)`}}})]})),Ls||{animation:`${Is} 3s infinite linear`}),Hs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Bar1`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.bar,t.bar1,t[`barColor${V(n.color)}`],(n.variant===`indeterminate`||n.variant===`query`)&&t.bar1Indeterminate,n.variant===`determinate`&&t.bar1Determinate,n.variant===`buffer`&&t.bar1Buffer]}})(Xa(({theme:e})=>({width:`100%`,position:`absolute`,left:0,bottom:0,top:0,transition:`transform 0.2s linear`,transformOrigin:`left`,variants:[{props:{color:`inherit`},style:{backgroundColor:`currentColor`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{backgroundColor:(e.vars||e).palette[t].main}})),{props:{variant:`determinate`},style:{transition:`transform .${js}s linear`}},{props:{variant:`buffer`},style:{zIndex:1,transition:`transform .${js}s linear`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:Ns||{animation:`${Ms} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite`}}]}))),Us=Ka(`span`,{name:`MuiLinearProgress`,slot:`Bar2`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.bar,t.bar2,t[`barColor${V(n.color)}`],(n.variant===`indeterminate`||n.variant===`query`)&&t.bar2Indeterminate,n.variant===`buffer`&&t.bar2Buffer]}})(Xa(({theme:e})=>({width:`100%`,position:`absolute`,left:0,bottom:0,top:0,transition:`transform 0.2s linear`,transformOrigin:`left`,variants:[...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{"--LinearProgressBar2-barColor":(e.vars||e).palette[t].main}})),{props:({ownerState:e})=>e.variant!==`buffer`&&e.color!==`inherit`,style:{backgroundColor:`var(--LinearProgressBar2-barColor, currentColor)`}},{props:({ownerState:e})=>e.variant!==`buffer`&&e.color===`inherit`,style:{backgroundColor:`currentColor`}},{props:{color:`inherit`},style:{opacity:.3}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t,variant:`buffer`},style:{backgroundColor:zs(e,t),transition:`transform .${js}s linear`}})),{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:Fs||{animation:`${Ps} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite`}}]}))),Ws=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiLinearProgress`}),{className:r,color:i=`primary`,value:a,valueBuffer:o,variant:s=`indeterminate`,...c}=n,l={...n,color:i,variant:s},u=Rs(l),d=Di(),f={},p={bar1:{},bar2:{}};if((s===`determinate`||s===`buffer`)&&a!==void 0){f[`aria-valuenow`]=Math.round(a),f[`aria-valuemin`]=0,f[`aria-valuemax`]=100;let e=a-100;d&&(e=-e),p.bar1.transform=`translateX(${e}%)`}if(s===`buffer`&&o!==void 0){let e=(o||0)-100;d&&(e=-e),p.bar2.transform=`translateX(${e}%)`}return(0,N.jsxs)(Bs,{className:Gr(u.root,r),ownerState:l,role:`progressbar`,...f,ref:t,...c,children:[s===`buffer`?(0,N.jsx)(Vs,{className:u.dashed,ownerState:l}):null,(0,N.jsx)(Hs,{className:u.bar1,ownerState:l,s
Line truncated
|
||||
Vendored
+3
-3
@@ -4,9 +4,9 @@
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/assets/icon-small-BO4dlTNl.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>GPGUI Downloader</title>
|
||||
<script type="module" crossorigin src="/assets/main-B7u6_mhO.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/main-DiWGniCh.css">
|
||||
<title>GP Connect Helper</title>
|
||||
<script type="module" crossorigin src="/assets/main-yAo_rN_V.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/main-C5muOSVO.css">
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/src/assets/icon-small.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>GPGUI Downloader</title>
|
||||
<title>GP Connect Helper</title>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
|
||||
@@ -9,25 +9,29 @@
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.12.1",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0"
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.1",
|
||||
"@mui/icons-material": "^7.3.11",
|
||||
"@mui/material": "^7.3.11",
|
||||
"@tauri-apps/api": "^2.11.1",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2.12.1",
|
||||
"@types/node": "^26.6.4",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.71.1",
|
||||
"@typescript-eslint/parser": "^8.71.1",
|
||||
"@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.9",
|
||||
"prettier": "3.8.3",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^8.3.3"
|
||||
"vite": "^8.0.16"
|
||||
},
|
||||
"packageManager": "[email protected]"
|
||||
}
|
||||
Generated
+1035
-487
File diff suppressed because it is too large.
Load diff
@@ -41,22 +41,6 @@ const GUI_LIBC_SUFFIX: &str = "-musl";
|
||||
#[cfg(not(target_env = "musl"))]
|
||||
const GUI_LIBC_SUFFIX: &str = "";
|
||||
|
||||
fn gui_asset_name() -> Option<String> {
|
||||
gui_asset_name_for(std::env::consts::OS, std::env::consts::ARCH, GUI_LIBC_SUFFIX)
|
||||
}
|
||||
|
||||
fn gui_asset_name_for(os: &str, arch: &str, libc_suffix: &str) -> Option<String> {
|
||||
let name = match (os, arch) {
|
||||
("linux", "x86_64" | "aarch64") => format!("gpgui_{arch}{libc_suffix}.bin.tar.xz"),
|
||||
("freebsd", "x86_64") => "gpgui_freebsd_amd64.bin.tar.xz".to_owned(),
|
||||
("freebsd", "aarch64") => "gpgui_freebsd_arm64.bin.tar.xz".to_owned(),
|
||||
("openbsd", "x86_64") => "gpgui_openbsd_amd64.bin.tar.xz".to_owned(),
|
||||
("openbsd", "aarch64") => "gpgui_openbsd_arm64.bin.tar.xz".to_owned(),
|
||||
_ => return None,
|
||||
};
|
||||
Some(name)
|
||||
}
|
||||
|
||||
pub struct ProgressNotifier {
|
||||
win: WebviewWindow,
|
||||
}
|
||||
@@ -246,7 +230,9 @@ 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);
|
||||
}
|
||||
@@ -299,7 +285,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(),
|
||||
};
|
||||
@@ -381,10 +366,10 @@ impl GuiUpdater {
|
||||
}
|
||||
|
||||
pub async fn update(&self) {
|
||||
let Some(asset_name) = gui_asset_name() else {
|
||||
info!("GUI updates are not supported on this platform.");
|
||||
if !cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) {
|
||||
info!("GUI version is not supported on this architecture.");
|
||||
return;
|
||||
};
|
||||
}
|
||||
info!("Update GUI, version: {}", self.version);
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
@@ -396,8 +381,16 @@ impl GuiUpdater {
|
||||
format!("v{}", self.version)
|
||||
};
|
||||
|
||||
let file_url =
|
||||
format!("https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{release_tag}/{asset_name}");
|
||||
let arch = if cfg!(target_arch = "x86_64") {
|
||||
"x86_64"
|
||||
} else {
|
||||
"aarch64"
|
||||
};
|
||||
|
||||
let file_url = format!(
|
||||
"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}{}.bin.tar.xz",
|
||||
release_tag, arch, GUI_LIBC_SUFFIX
|
||||
);
|
||||
let checksum_url = format!("{}.sha256", file_url);
|
||||
|
||||
info!("Downloading file: {}", file_url);
|
||||
@@ -501,27 +494,6 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn selects_platform_specific_gui_assets() {
|
||||
assert_eq!(
|
||||
gui_asset_name_for("linux", "x86_64", ""),
|
||||
Some("gpgui_x86_64.bin.tar.xz".to_owned())
|
||||
);
|
||||
assert_eq!(
|
||||
gui_asset_name_for("linux", "aarch64", "-musl"),
|
||||
Some("gpgui_aarch64-musl.bin.tar.xz".to_owned())
|
||||
);
|
||||
assert_eq!(
|
||||
gui_asset_name_for("freebsd", "x86_64", ""),
|
||||
Some("gpgui_freebsd_amd64.bin.tar.xz".to_owned())
|
||||
);
|
||||
assert_eq!(
|
||||
gui_asset_name_for("openbsd", "aarch64", ""),
|
||||
Some("gpgui_openbsd_arm64.bin.tar.xz".to_owned())
|
||||
);
|
||||
assert_eq!(gui_asset_name_for("macos", "aarch64", ""), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_install_reconnects_with_a_fresh_handshake() {
|
||||
let credential = Arc::new(SessionCredential::generate(Uuid::new_v4(), env!("CARGO_PKG_VERSION")).unwrap());
|
||||
@@ -632,6 +604,7 @@ mod tests {
|
||||
snapshot: VpnEnv {
|
||||
vpn_state: VpnState::Disconnected,
|
||||
vpnc_script: None,
|
||||
csd_wrapper: None,
|
||||
auth_executable: String::new(),
|
||||
host_info: HostInfo {
|
||||
host_identity: HostIdentity::collect(),
|
||||
|
||||
@@ -15,15 +15,15 @@
|
||||
},
|
||||
"windows": [
|
||||
{
|
||||
"title": "GPGUI Downloader",
|
||||
"title": "GP Connect Helper",
|
||||
"center": true,
|
||||
"resizable": true,
|
||||
"width": 460,
|
||||
"height": 104,
|
||||
"minWidth": 460,
|
||||
"minHeight": 104,
|
||||
"maxWidth": 460,
|
||||
"maxHeight": 104,
|
||||
"width": 500,
|
||||
"height": 100,
|
||||
"minWidth": 500,
|
||||
"minHeight": 100,
|
||||
"maxWidth": 500,
|
||||
"maxHeight": 100,
|
||||
"label": "main",
|
||||
"decorations": false
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Box, Button, CssBaseline, LinearProgress, Typography } from "@mui/material";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import logo from "../../assets/icon-small.svg";
|
||||
import { useEffect, useState } from "react";
|
||||
@@ -6,112 +7,129 @@ import "./styles.css";
|
||||
|
||||
const appWindow = getCurrentWindow();
|
||||
|
||||
export default function App() {
|
||||
const [error, setError] = useState(false);
|
||||
function useUpdateProgress() {
|
||||
const [progress, setProgress] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const unlisteners: Array<() => void> = [];
|
||||
let disposed = false;
|
||||
|
||||
const startUpdate = async () => {
|
||||
const progressUnlisten = await appWindow.listen("app://update-progress", (event) => {
|
||||
setProgress(event.payload as number);
|
||||
});
|
||||
const errorUnlisten = await appWindow.listen("app://update-error", () => {
|
||||
setError(true);
|
||||
});
|
||||
|
||||
if (disposed) {
|
||||
progressUnlisten();
|
||||
errorUnlisten();
|
||||
return;
|
||||
}
|
||||
|
||||
unlisteners.push(progressUnlisten, errorUnlisten);
|
||||
await appWindow.emit("app://update");
|
||||
};
|
||||
|
||||
void startUpdate();
|
||||
const unlisten = appWindow.listen("app://update-progress", (event) => {
|
||||
setProgress(event.payload as number);
|
||||
});
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
unlisteners.forEach((unlisten) => unlisten());
|
||||
unlisten.then((unlisten) => unlisten());
|
||||
};
|
||||
}, []);
|
||||
|
||||
return progress;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
appWindow.emit("app://update");
|
||||
|
||||
const unlisten = appWindow.listen("app://update-error", () => {
|
||||
setError(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
unlisten.then((unlisten) => unlisten());
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleRetry = () => {
|
||||
setError(false);
|
||||
setProgress(null);
|
||||
appWindow.emit("app://update");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="update-window" data-tauri-drag-region>
|
||||
<img src={logo} alt="" className="update-logo" data-tauri-drag-region />
|
||||
<div className="update-content" data-tauri-drag-region>
|
||||
{error ? (
|
||||
<DownloadFailed onRetry={handleRetry} />
|
||||
) : (
|
||||
<DownloadIndicator progress={progress} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<>
|
||||
<CssBaseline />
|
||||
<Box
|
||||
sx={{ position: "absolute", inset: 0 }}
|
||||
display="flex"
|
||||
alignItems="center"
|
||||
px={2}
|
||||
data-tauri-drag-region
|
||||
>
|
||||
<Box display="flex" alignItems="center" flex="1" data-tauri-drag-region>
|
||||
<Box
|
||||
component="img"
|
||||
src={logo}
|
||||
alt="logo"
|
||||
sx={{ width: "4rem", height: "4rem" }}
|
||||
data-tauri-drag-region
|
||||
/>
|
||||
<Box flex={1} ml={2}>
|
||||
{error ? <DownloadFailed onRetry={handleRetry} /> : <DownloadIndicator />}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DownloadIndicator({ progress }: { progress: number | null }) {
|
||||
function DownloadIndicator() {
|
||||
const progress = useUpdateProgress();
|
||||
|
||||
return (
|
||||
<div className="update-status" data-tauri-drag-region>
|
||||
<h1 className="update-title" data-tauri-drag-region>
|
||||
Getting GP Connect ready
|
||||
</h1>
|
||||
<DownloadProgress value={progress} />
|
||||
</div>
|
||||
<>
|
||||
<Typography variant="h1" fontSize="1rem" data-tauri-drag-region>
|
||||
Updating the GUI components...
|
||||
</Typography>
|
||||
<Box mt={1}>
|
||||
<LinearProgressWithLabel value={progress} />
|
||||
</Box>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DownloadFailed({ onRetry }: { onRetry: () => void }) {
|
||||
return (
|
||||
<div className="update-status error-status" data-tauri-drag-region>
|
||||
<div className="error-copy" role="alert" data-tauri-drag-region>
|
||||
<h1 className="update-title" data-tauri-drag-region>
|
||||
Couldn’t get GP Connect ready
|
||||
</h1>
|
||||
<p className="update-description" data-tauri-drag-region>
|
||||
Please try again.
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" onClick={onRetry} className="retry-button">
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DownloadProgress({ value }: { value: number | null }) {
|
||||
const isDeterminate = value !== null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="progress-summary" data-tauri-drag-region>
|
||||
<p className="update-description" data-tauri-drag-region>
|
||||
This should only take a moment.
|
||||
</p>
|
||||
<span className="progress-label" aria-hidden="true">
|
||||
{isDeterminate ? `${Math.round(value)}%` : "In progress"}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
className={`progress-bar${isDeterminate ? "" : " progress-bar-indeterminate"}`}
|
||||
role="progressbar"
|
||||
aria-label="Update progress"
|
||||
aria-valuemin={isDeterminate ? 0 : undefined}
|
||||
aria-valuemax={isDeterminate ? 100 : undefined}
|
||||
aria-valuenow={isDeterminate ? Math.round(value) : undefined}
|
||||
>
|
||||
<div className="progress-fill" style={isDeterminate ? { width: `${value}%` } : undefined} />
|
||||
</div>
|
||||
<Typography variant="h1" fontSize="1rem" data-tauri-drag-region>
|
||||
Failed to update the GUI components.
|
||||
</Typography>
|
||||
<Box mt={1} data-tauri-drag-region>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
size="small"
|
||||
onClick={onRetry}
|
||||
sx={{
|
||||
textTransform: "none",
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
</Box>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function LinearProgressWithLabel(props: { value: number | null }) {
|
||||
const { value } = props;
|
||||
|
||||
return (
|
||||
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||
<Box flex="1">
|
||||
<LinearProgress
|
||||
variant={value === null ? "indeterminate" : "determinate"}
|
||||
value={value ?? 0}
|
||||
sx={{
|
||||
py: 1.2,
|
||||
".MuiLinearProgress-bar": {
|
||||
transition: "none",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
{value !== null && (
|
||||
<Box sx={{ minWidth: 35, textAlign: "right", ml: 1 }}>
|
||||
<Typography variant="body2" color="text.secondary">{`${Math.round(value)}%`}</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -1,173 +1,10 @@
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
box-sizing: border-box;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
body {
|
||||
background: #f6f5f4;
|
||||
color: #2e3436;
|
||||
font-family:
|
||||
Inter,
|
||||
ui-sans-serif,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
"Segoe UI",
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.update-window {
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 16px 18px;
|
||||
gap: 15px;
|
||||
background: #f6f5f4;
|
||||
}
|
||||
|
||||
.update-logo {
|
||||
flex: 0 0 auto;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
}
|
||||
|
||||
.update-content,
|
||||
.update-status {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.update-title {
|
||||
margin: 0;
|
||||
color: #2e3436;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.update-description {
|
||||
margin: 3px 0 0;
|
||||
color: #5e5c64;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.progress-summary {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-top: 3px;
|
||||
}
|
||||
|
||||
.progress-summary .update-description {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 6px;
|
||||
margin-top: 9px;
|
||||
overflow: hidden;
|
||||
border-radius: 3px;
|
||||
background-color: #d5d3d1;
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
border-radius: 3px;
|
||||
background: #3584e4;
|
||||
transition: width 180ms ease-out;
|
||||
}
|
||||
|
||||
.progress-bar-indeterminate .progress-fill {
|
||||
width: 35%;
|
||||
animation: progress-indeterminate 1.4s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes progress-indeterminate {
|
||||
from {
|
||||
transform: translateX(-110%);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: translateX(300%);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.progress-fill {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.progress-bar-indeterminate .progress-fill {
|
||||
animation: none;
|
||||
transform: translateX(90%);
|
||||
}
|
||||
}
|
||||
|
||||
.progress-label {
|
||||
flex: 0 0 auto;
|
||||
color: #3d3846;
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 500;
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.error-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.error-status .update-title {
|
||||
color: #9c2f2f;
|
||||
}
|
||||
|
||||
.error-copy {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.retry-button {
|
||||
min-width: 68px;
|
||||
padding: 4px 14px;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: #1c71d8;
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.retry-button:hover {
|
||||
background: #1a5fb4;
|
||||
}
|
||||
|
||||
.retry-button:active {
|
||||
background: #174a8b;
|
||||
}
|
||||
|
||||
.retry-button:focus-visible {
|
||||
outline: 2px solid #1a5fb4;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
@@ -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" }
|
||||
base64.workspace = true
|
||||
sha256.workspace = true
|
||||
openconnect = { path = "../../crates/openconnect" }
|
||||
clap.workspace = true
|
||||
anyhow.workspace = true
|
||||
@@ -28,12 +25,9 @@ thiserror.workspace = true
|
||||
uuid = { workspace = true, features = ["v4"] }
|
||||
zeroize.workspace = true
|
||||
tempfile.workspace = true
|
||||
getrandom = "0.4"
|
||||
mac_address = "1"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "socket", "user"] }
|
||||
|
||||
[dev-dependencies]
|
||||
openssl.workspace = true
|
||||
tokio-tungstenite = "0.29"
|
||||
@@ -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);
|
||||
}
|
||||
+77
-58
@@ -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,34 +95,14 @@ 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()?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
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
|
||||
@@ -129,14 +113,15 @@ impl Cli {
|
||||
} 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,
|
||||
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(
|
||||
@@ -194,34 +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 });
|
||||
|
||||
let desktop_client_handle = if let Some(channel) = desktop_channel {
|
||||
#[cfg(debug_assertions)]
|
||||
let launch_managed_gui = !self.dev_standalone && !externally_brokered;
|
||||
#[cfg(not(debug_assertions))]
|
||||
let launch_managed_gui = !externally_brokered;
|
||||
|
||||
if launch_managed_gui {
|
||||
ws_ready_rx.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}");
|
||||
}
|
||||
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() => {
|
||||
@@ -233,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()?;
|
||||
|
||||
@@ -325,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;
|
||||
@@ -345,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};
|
||||
|
||||
@@ -370,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 {
|
||||
@@ -387,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();
|
||||
|
||||
|
||||
@@ -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,223 +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;
|
||||
|
||||
/// 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<()> {
|
||||
loop {
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), Some(uid))?;
|
||||
let session_id = credential.session_id();
|
||||
let result = tokio::select! {
|
||||
_ = cancel.cancelled() => Ok(false),
|
||||
result = async {
|
||||
self.write_frame(&credential.encode_frame()?).await?;
|
||||
self.gui_exited().await
|
||||
} => result,
|
||||
};
|
||||
registry.revoke(session_id);
|
||||
if !result? || !restart.swap(false, Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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<bool> {
|
||||
loop {
|
||||
let mut ready = self.input.readable().await?;
|
||||
let mut byte = [0];
|
||||
match ready.try_io(|fd| read(fd.get_ref(), &mut byte).map_err(io::Error::from)) {
|
||||
Ok(result) => {
|
||||
if result.context("Desktop control pipe failed")? == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
ensure!(byte[0] == 0, "Invalid desktop control message");
|
||||
return Ok(true);
|
||||
}
|
||||
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::new(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 desktop_channel_shutdown_cancels_pipe_wait_and_revokes_credential() {
|
||||
let (channel, _control, reader) = pipes();
|
||||
let registry = Arc::new(SessionRegistry::new(uuid::Uuid::new_v4()));
|
||||
let 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::new(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, &[1]).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}");
|
||||
}
|
||||
});
|
||||
@@ -188,7 +188,7 @@ mod tests {
|
||||
async fn anchor_eof_revokes_issued_credential() {
|
||||
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;
|
||||
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::digest(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::digest(&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::new(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;
|
||||
@@ -45,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,63 +17,15 @@ 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<()>,
|
||||
@@ -83,14 +35,14 @@ pub struct RequestDispatcher {
|
||||
|
||||
impl RequestDispatcher {
|
||||
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,
|
||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
||||
) -> Self {
|
||||
Self {
|
||||
lifecycle,
|
||||
ws_req_tx,
|
||||
gui_restart_requested,
|
||||
redaction,
|
||||
install_lock: Mutex::new(()),
|
||||
@@ -99,130 +51,7 @@ impl RequestDispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
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_paths(&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.brokered_scripts_dir.is_some(),
|
||||
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 {
|
||||
@@ -256,23 +85,29 @@ 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 => {
|
||||
unreachable!("session-bound request was already dispatched")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -282,14 +117,12 @@ impl RequestDispatcher {
|
||||
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 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");
|
||||
@@ -327,10 +160,7 @@ enum GuiInstallError {
|
||||
}
|
||||
|
||||
fn install_gui(src: &str, checksum: &str) -> Result<(), GuiInstallError> {
|
||||
install_gui_at(Path::new(src), checksum, &binary_paths::gpgui_update_target())
|
||||
}
|
||||
|
||||
fn install_gui_at(src: &Path, checksum: &str, target: &Path) -> Result<(), GuiInstallError> {
|
||||
let target = binary_paths::gpgui();
|
||||
let Some(dir) = target.parent() else {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"Failed to get parent directory of GUI binary"
|
||||
@@ -338,7 +168,7 @@ fn install_gui_at(src: &Path, checksum: &str, target: &Path) -> Result<(), GuiIn
|
||||
};
|
||||
fs::create_dir_all(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
|
||||
let staged_archive = stage_gui_archive(src, dir)?;
|
||||
let staged_archive = stage_gui_archive(Path::new(src), dir)?;
|
||||
let archive_path = staged_archive.path().to_string_lossy();
|
||||
verify_checksum(&archive_path, checksum).map_err(GuiInstallError::Checksum)?;
|
||||
|
||||
@@ -430,15 +260,16 @@ 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 std::io::Cursor;
|
||||
|
||||
use gpapi::{
|
||||
gateway::Gateway,
|
||||
service::transport::{ServiceErrorCode, ServiceResult},
|
||||
service::{
|
||||
request::ConnectRequest,
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
};
|
||||
use tar::{Builder, EntryType, Header};
|
||||
use xz2::write::XzEncoder;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -457,17 +288,6 @@ mod tests {
|
||||
data
|
||||
}
|
||||
|
||||
fn compressed_gui_archive(contents: &[u8]) -> NamedTempFile {
|
||||
let tar = archive_with_entry(EntryType::Regular, contents);
|
||||
let mut encoder = XzEncoder::new(Vec::new(), 6);
|
||||
encoder.write_all(&tar).unwrap();
|
||||
let compressed = encoder.finish().unwrap();
|
||||
let mut archive = NamedTempFile::new().unwrap();
|
||||
archive.write_all(&compressed).unwrap();
|
||||
archive.flush().unwrap();
|
||||
archive
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_file_and_empty_gui_entries() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
@@ -517,35 +337,11 @@ mod tests {
|
||||
assert!(extract_gui_binary(&mut archive, output.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_gui_at_the_supplied_target() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = sha256::try_digest(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpclient/gpgui");
|
||||
|
||||
install_gui_at(archive.path(), &checksum, &target).unwrap();
|
||||
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"gui binary");
|
||||
assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o755);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksum_failure_preserves_the_existing_gui() {
|
||||
let archive = compressed_gui_archive(b"replacement");
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpclient/gpgui");
|
||||
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
|
||||
std::fs::write(&target, b"existing").unwrap();
|
||||
|
||||
assert!(install_gui_at(archive.path(), "invalid", &target).is_err());
|
||||
assert_eq!(std::fs::read(target).unwrap(), b"existing");
|
||||
}
|
||||
|
||||
#[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,
|
||||
@@ -558,8 +354,9 @@ 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)
|
||||
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");
|
||||
@@ -569,8 +366,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
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,
|
||||
@@ -578,24 +376,17 @@ 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 bundled =
|
||||
test_request(info.clone()).with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()));
|
||||
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(()));
|
||||
|
||||
let old_layout = test_request(info.clone()).with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()));
|
||||
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_paths(&old_layout),
|
||||
Err("macOS VPN script must be the bundled script")
|
||||
);
|
||||
|
||||
let custom = test_request(info)
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||
.with_hip_source(gpapi::hip::HipSource::UserScript {
|
||||
path: "/tmp/hip.sh".into(),
|
||||
});
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_paths(&custom),
|
||||
Err("macOS does not support custom HIP scripts")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,132 +53,17 @@ 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>>,
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -195,7 +71,7 @@ impl SessionRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
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| {
|
||||
@@ -214,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 = crate::device_anchor::resolve().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,
|
||||
@@ -317,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,
|
||||
@@ -370,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))
|
||||
@@ -414,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,
|
||||
@@ -561,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);
|
||||
@@ -596,278 +322,10 @@ mod tests {
|
||||
ConnectionControl::new(Uuid::new_v4(), tx).0
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attachment_replacement_cancels_preparation_and_retains_drain_until_release() {
|
||||
let registry = Arc::new(SessionRegistry::new(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::new(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::new(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::new(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::new(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::new(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::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let credential = registry.issue("2.6.4").unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
@@ -888,7 +346,7 @@ mod tests {
|
||||
#[test]
|
||||
fn failed_initial_handshake_only_revokes_its_own_reservation() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let credential = registry.issue("2.6.4").unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
@@ -902,7 +360,7 @@ mod tests {
|
||||
#[test]
|
||||
fn failed_reconnect_keeps_active_connection_authoritative() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let credential = registry.issue("2.6.4").unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
|
||||
+230
-1138
File diff suppressed because it is too large.
Load diff
@@ -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::new(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,302 +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 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}"),
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -4,9 +4,8 @@ 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;
|
||||
@@ -58,11 +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.close_tx.send_replace(Some(reason));
|
||||
let _ = self.close_tx.send(Some(reason));
|
||||
}
|
||||
|
||||
pub async fn send_reply(&self, id: Uuid, result: ServiceResult) {
|
||||
@@ -149,7 +148,6 @@ impl WsConnection {
|
||||
&ctx,
|
||||
&control,
|
||||
permit.session_id,
|
||||
permit.desktop_uid,
|
||||
generation,
|
||||
&mut pending_requests,
|
||||
).await.is_err() {
|
||||
@@ -187,10 +185,6 @@ impl WsConnection {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -221,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,
|
||||
@@ -325,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<(), ()> {
|
||||
@@ -341,175 +323,10 @@ async fn handle_client_message(
|
||||
return Err(());
|
||||
}
|
||||
|
||||
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(())
|
||||
@@ -579,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::*;
|
||||
@@ -590,9 +407,10 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn authenticates_attaches_and_replies_to_a_request() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
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,
|
||||
@@ -614,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(),
|
||||
};
|
||||
@@ -658,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();
|
||||
|
||||
@@ -12,7 +12,7 @@ use gpapi::{
|
||||
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},
|
||||
@@ -39,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 {
|
||||
@@ -59,7 +58,6 @@ impl WsServerContext {
|
||||
connections: HashMap::new(),
|
||||
}),
|
||||
handshake_slots: Arc::new(Semaphore::new(16)),
|
||||
hip_previews: crate::hip_preview::HipPreviews::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,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
|
||||
}
|
||||
@@ -151,8 +145,8 @@ impl WsServerContext {
|
||||
}
|
||||
|
||||
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
||||
self.registry.disconnect_if_current(session_id, generation);
|
||||
self.state.lock().await.connections.remove(&connection_id);
|
||||
self.registry.disconnect_if_current(session_id, generation);
|
||||
}
|
||||
|
||||
pub async fn send_event(&self, event: WsEvent) {
|
||||
@@ -249,7 +243,6 @@ impl WsServer {
|
||||
info!("WS server cancelled");
|
||||
}
|
||||
}
|
||||
self.ctx.hip_previews.shutdown().await;
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
}
|
||||
|
||||
@@ -265,7 +258,8 @@ impl WsServer {
|
||||
fn build_snapshot(vpn_state: VpnState) -> VpnEnv {
|
||||
VpnEnv {
|
||||
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(),
|
||||
@@ -288,7 +282,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn resync_snapshot_is_ordered_with_state_events() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap();
|
||||
let permit = registry
|
||||
.begin_handshake(
|
||||
credential.service_instance_id(),
|
||||
@@ -296,8 +290,9 @@ 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,
|
||||
@@ -345,9 +340,10 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn removed_prepared_candidate_cannot_commit_takeover() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
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,
|
||||
|
||||
@@ -1,28 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## 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
|
||||
|
||||
+2
-11
@@ -8,18 +8,18 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
common = { path = "../common" }
|
||||
gpapi = { path = "../gpapi" }
|
||||
|
||||
# Shared dependencies
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
tokio = { workspace = true, features = ["io-util", "net", "time"] }
|
||||
tokio.workspace = true
|
||||
|
||||
# Browser auth dependencies
|
||||
browser-launcher = { path = "../browser-launcher", default-features = false, features = ["launcher"], optional = true }
|
||||
tiny_http = { version = "0.12", optional = true }
|
||||
uuid = { version = "1", optional = true, features = ["v4"] }
|
||||
uzers = { workspace = true, optional = true }
|
||||
|
||||
# Webview auth dependencies
|
||||
tauri = { workspace = true, optional = true }
|
||||
@@ -33,7 +33,6 @@ webkit2gtk = { version = "2", optional = true }
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = { version = "0.6", optional = true }
|
||||
objc2 = { version = "0.6", optional = true }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "block2"], optional = true }
|
||||
objc2-foundation = { version = "0.3", optional = true }
|
||||
objc2-web-kit = { version = "0.3", optional = true }
|
||||
|
||||
@@ -42,11 +41,6 @@ browser-auth = [
|
||||
"dep:browser-launcher",
|
||||
"dep:tiny_http",
|
||||
"dep:uuid",
|
||||
"dep:uzers",
|
||||
"dep:block2",
|
||||
"dep:objc2",
|
||||
"dep:objc2-app-kit",
|
||||
"dep:objc2-foundation",
|
||||
]
|
||||
webview-auth = [
|
||||
"gpapi/tauri",
|
||||
@@ -61,6 +55,3 @@ webview-auth = [
|
||||
"dep:objc2-web-kit",
|
||||
]
|
||||
release-devtools = ["webview-auth", "tauri/devtools"]
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{io::Cursor, net::SocketAddr};
|
||||
use std::io::Cursor;
|
||||
|
||||
use log::info;
|
||||
use tiny_http::{Header, Method, Response, Server};
|
||||
@@ -10,7 +10,7 @@ pub(super) struct AuthServer {
|
||||
}
|
||||
|
||||
impl AuthServer {
|
||||
pub fn new(addr: SocketAddr) -> anyhow::Result<Self> {
|
||||
pub fn new(addr: &str) -> anyhow::Result<Self> {
|
||||
let server = Server::http(addr).map_err(|err| anyhow::anyhow!(err))?;
|
||||
let auth_id = Uuid::new_v4().to_string();
|
||||
|
||||
|
||||
@@ -1,36 +1,29 @@
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt};
|
||||
|
||||
use browser_launcher::Browser as LaunchBrowser;
|
||||
use common::constants::GP_CALLBACK_PORT_FILENAME;
|
||||
use gpapi::auth::SamlAuthData;
|
||||
use log::info;
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::{
|
||||
io::AsyncReadExt,
|
||||
net::{TcpListener, UdpSocket},
|
||||
};
|
||||
|
||||
use crate::{AuthCallbackReceiver, browser::auth_server::AuthServer, ensure_auth_callback_handler};
|
||||
use crate::browser::auth_server::AuthServer;
|
||||
|
||||
pub struct BrowserAuthenticator<'a> {
|
||||
auth_request: &'a str,
|
||||
browser: &'a str,
|
||||
browser_listen: Option<IpAddr>,
|
||||
}
|
||||
|
||||
impl<'a> BrowserAuthenticator<'a> {
|
||||
pub fn new(auth_request: &'a str, browser: &'a str, browser_listen: Option<IpAddr>) -> Self {
|
||||
Self {
|
||||
auth_request,
|
||||
browser,
|
||||
browser_listen,
|
||||
}
|
||||
pub fn new(auth_request: &'a str, browser: &'a str) -> Self {
|
||||
Self { auth_request, browser }
|
||||
}
|
||||
|
||||
pub async fn authenticate(&self) -> anyhow::Result<SamlAuthData> {
|
||||
let callback_receiver = if is_remote_browser(self.browser) {
|
||||
None
|
||||
} else {
|
||||
ensure_auth_callback_handler()?;
|
||||
Some(AuthCallbackReceiver::bind()?)
|
||||
};
|
||||
let addr = self.determine_addr().await?;
|
||||
let auth_server = AuthServer::new(addr)?;
|
||||
let auth_server = AuthServer::new(&addr)?;
|
||||
let auth_url = auth_server.auth_url();
|
||||
|
||||
let auth_request = self.auth_request.to_string();
|
||||
@@ -61,18 +54,15 @@ Note that the URL is only valid for a single use.
|
||||
browser_launcher::open_url(&auth_url, LaunchBrowser::from_name(self.browser))?;
|
||||
|
||||
info!("Please continue the authentication process in the default browser");
|
||||
callback_receiver.unwrap().receive().await
|
||||
wait_auth_data().await
|
||||
}
|
||||
|
||||
async fn determine_addr(&self) -> anyhow::Result<SocketAddr> {
|
||||
async fn determine_addr(&self) -> anyhow::Result<String> {
|
||||
if is_remote_browser(self.browser) {
|
||||
let local_ip = match self.browser_listen {
|
||||
Some(ip) => ip,
|
||||
None => detect_local_ip().await?,
|
||||
};
|
||||
Ok(SocketAddr::new(local_ip, 0))
|
||||
let local_ip = detect_local_ip().await?;
|
||||
Ok(format!("{}:0", local_ip))
|
||||
} else {
|
||||
Ok(SocketAddr::from(([127, 0, 0, 1], 0)))
|
||||
Ok("127.0.0.1:0".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,16 +72,48 @@ fn is_remote_browser(browser: &str) -> bool {
|
||||
}
|
||||
|
||||
/// Detect the local IP address by creating a UDP socket and connecting to an external address
|
||||
async fn detect_local_ip() -> anyhow::Result<IpAddr> {
|
||||
async fn detect_local_ip() -> anyhow::Result<String> {
|
||||
let socket = UdpSocket::bind("0.0.0.0:0").await?;
|
||||
if let Err(err) = socket.connect("1.1.1.1:80").await {
|
||||
anyhow::bail!("Failed to connect to external address to determine local IP: {}", err);
|
||||
}
|
||||
let local_addr = socket.local_addr()?;
|
||||
let ip = local_addr.ip();
|
||||
let ip = local_addr.ip().to_string();
|
||||
info!("Determined local IP address: {}", ip);
|
||||
|
||||
Ok(ip)
|
||||
Ok(ip.to_string())
|
||||
}
|
||||
|
||||
async fn wait_auth_data() -> anyhow::Result<SamlAuthData> {
|
||||
// Start a local server to receive the browser authentication data
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let port_file = temp_dir().join(GP_CALLBACK_PORT_FILENAME);
|
||||
|
||||
// Write the port to a file
|
||||
fs::write(&port_file, port.to_string())?;
|
||||
fs::set_permissions(&port_file, fs::Permissions::from_mode(0o600))?;
|
||||
|
||||
// Remove the previous log file
|
||||
let callback_log = temp_dir().join("gpcallback.log");
|
||||
let _ = fs::remove_file(&callback_log);
|
||||
|
||||
info!("Listening authentication data on port {}", port);
|
||||
info!(
|
||||
"If it hangs, please check the logs at `{}` for more information",
|
||||
callback_log.display()
|
||||
);
|
||||
let (mut socket, _) = listener.accept().await?;
|
||||
|
||||
info!("Received the browser authentication data from the socket");
|
||||
let mut data = String::new();
|
||||
socket.read_to_string(&mut data).await?;
|
||||
|
||||
// Remove the port file
|
||||
fs::remove_file(&port_file)?;
|
||||
|
||||
let auth_data = SamlAuthData::from_gpcallback(&data)?;
|
||||
Ok(auth_data)
|
||||
}
|
||||
|
||||
fn read_auth_data_from_stdin() -> anyhow::Result<SamlAuthData> {
|
||||
@@ -118,15 +140,4 @@ mod tests {
|
||||
assert!(is_remote_browser("REMOTE"));
|
||||
assert_ne!(LaunchBrowser::from_name("remote"), LaunchBrowser::Default);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_browser_uses_explicit_listen_address() {
|
||||
let listen_ip = "192.168.107.15".parse().unwrap();
|
||||
let authenticator = BrowserAuthenticator::new("request", "remote", Some(listen_ip));
|
||||
|
||||
assert_eq!(
|
||||
authenticator.determine_addr().await.unwrap(),
|
||||
SocketAddr::new(listen_ip, 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,512 +0,0 @@
|
||||
use std::{
|
||||
fs::{self, DirBuilder, OpenOptions, TryLockError},
|
||||
io::ErrorKind,
|
||||
os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::auth::SamlAuthData;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::{UnixListener, UnixStream},
|
||||
time::timeout,
|
||||
};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use log::warn;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use std::ffi::OsStr;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const CALLBACK_SCHEME: &str = "globalprotectcallback";
|
||||
const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC";
|
||||
const PROTOCOL_VERSION: u8 = 1;
|
||||
const MAX_CALLBACK_SIZE: usize = 1024 * 1024;
|
||||
const IO_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
const STATUS_ACCEPTED: u8 = 0;
|
||||
const STATUS_INVALID_CALLBACK: u8 = 1;
|
||||
const STATUS_UNSUPPORTED_VERSION: u8 = 2;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
|
||||
pub struct AuthCallbackReceiver {
|
||||
listener: UnixListener,
|
||||
socket_path: PathBuf,
|
||||
_lock_file: fs::File,
|
||||
}
|
||||
|
||||
impl AuthCallbackReceiver {
|
||||
pub fn bind() -> anyhow::Result<Self> {
|
||||
let socket_path = callback_socket_path();
|
||||
prepare_socket_directory(&socket_path)?;
|
||||
Self::bind_at(socket_path)
|
||||
}
|
||||
|
||||
fn bind_at(socket_path: PathBuf) -> anyhow::Result<Self> {
|
||||
let lock_file = acquire_lock(&socket_path)?;
|
||||
match fs::symlink_metadata(&socket_path) {
|
||||
Ok(_) => remove_stale_socket(&socket_path)?,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => {}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
finish_bind(UnixListener::bind(&socket_path)?, socket_path, lock_file)
|
||||
}
|
||||
|
||||
pub async fn receive(&self) -> anyhow::Result<SamlAuthData> {
|
||||
loop {
|
||||
let (mut stream, _) = self.listener.accept().await?;
|
||||
let callback = match timeout(IO_TIMEOUT, read_callback(&mut stream)).await {
|
||||
Ok(callback) => callback,
|
||||
Err(_) => continue,
|
||||
};
|
||||
match callback {
|
||||
Ok(callback) => match SamlAuthData::from_gpcallback(&callback) {
|
||||
Ok(auth_data) => {
|
||||
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
|
||||
return Ok(auth_data);
|
||||
}
|
||||
Err(_) => {
|
||||
let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await;
|
||||
}
|
||||
},
|
||||
Err(CallbackReadError::UnsupportedVersion) => {
|
||||
let _ = write_response(&mut stream, STATUS_UNSUPPORTED_VERSION).await;
|
||||
}
|
||||
Err(CallbackReadError::Invalid) => {
|
||||
let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await;
|
||||
}
|
||||
Err(CallbackReadError::Io) => continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AuthCallbackReceiver {
|
||||
fn drop(&mut self) {
|
||||
if fs::symlink_metadata(&self.socket_path)
|
||||
.is_ok_and(|metadata| metadata.file_type().is_socket() && metadata.uid() == uzers::get_current_uid())
|
||||
{
|
||||
let _ = fs::remove_file(&self.socket_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
validate_callback(callback)?;
|
||||
forward_auth_callback_to(callback, &callback_socket_path()).await
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
|
||||
const MIME_TYPE: &str = "x-scheme-handler/globalprotectcallback";
|
||||
const HANDLER: &str = "gpgui.desktop";
|
||||
|
||||
ensure_lxqt_mime_tool()?;
|
||||
|
||||
let current_handler = query_callback_handler(MIME_TYPE)?;
|
||||
if !should_register_handler(¤t_handler) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let output = Command::new("xdg-mime")
|
||||
.args(["default", HANDLER, MIME_TYPE])
|
||||
.output()
|
||||
.context("xdg-mime is required for external-browser authentication")?;
|
||||
if !output.status.success() {
|
||||
log_command_failure("register callback handler", &output);
|
||||
bail!("Failed to register the globalprotectcallback URL handler");
|
||||
}
|
||||
if query_callback_handler(MIME_TYPE)? != HANDLER {
|
||||
bail!("The globalprotectcallback URL handler registration did not take effect");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn query_callback_handler(mime_type: &str) -> anyhow::Result<String> {
|
||||
let output = Command::new("xdg-mime")
|
||||
.args(["query", "default", mime_type])
|
||||
.output()
|
||||
.context("xdg-mime is required for external-browser authentication")?;
|
||||
if !output.status.success() {
|
||||
log_command_failure("query callback handler", &output);
|
||||
bail!("Failed to query the globalprotectcallback URL handler");
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn ensure_lxqt_mime_tool() -> anyhow::Result<()> {
|
||||
if !is_lxqt_desktop(std::env::var_os("XDG_CURRENT_DESKTOP").as_deref()) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let result = Command::new("qtxdg-mat").args(["defapp", "--help"]).output();
|
||||
match result {
|
||||
Ok(output) if output.status.success() => Ok(()),
|
||||
Ok(output) => {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
warn!(
|
||||
"qtxdg-mat readiness check failed with {}: {}",
|
||||
output.status,
|
||||
stderr.trim()
|
||||
);
|
||||
bail!("Install qtxdg-tools for browser SSO.")
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Failed to run qtxdg-mat readiness check: {err}");
|
||||
bail!("Install qtxdg-tools for browser SSO.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn is_lxqt_desktop(current_desktop: Option<&OsStr>) -> bool {
|
||||
current_desktop
|
||||
.and_then(OsStr::to_str)
|
||||
.is_some_and(|desktop| desktop.split(':').any(|name| name.eq_ignore_ascii_case("lxqt")))
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn log_command_failure(action: &str, output: &Output) {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
warn!("xdg-mime failed to {action} with {}: {}", output.status, stderr.trim());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
|
||||
macos::ensure_auth_callback_handler()
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "macos"
|
||||
)))]
|
||||
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn should_register_handler(current_handler: &str) -> bool {
|
||||
current_handler != "gpgui.desktop"
|
||||
}
|
||||
|
||||
async fn forward_auth_callback_to(callback: &str, socket_path: &Path) -> anyhow::Result<()> {
|
||||
validate_callback(callback)?;
|
||||
|
||||
let (version, status) = timeout(IO_TIMEOUT, async {
|
||||
let mut stream = UnixStream::connect(socket_path)
|
||||
.await
|
||||
.context("No external-browser authentication is waiting for a callback")?;
|
||||
stream.write_all(PROTOCOL_MAGIC).await?;
|
||||
stream.write_u8(PROTOCOL_VERSION).await?;
|
||||
stream.write_u32(callback.len() as u32).await?;
|
||||
stream.write_all(callback.as_bytes()).await?;
|
||||
Ok::<_, anyhow::Error>((stream.read_u8().await?, stream.read_u8().await?))
|
||||
})
|
||||
.await
|
||||
.context("Timed out forwarding the authentication callback")??;
|
||||
if version != PROTOCOL_VERSION {
|
||||
bail!("Authentication callback protocol version mismatch");
|
||||
}
|
||||
|
||||
match status {
|
||||
STATUS_ACCEPTED => Ok(()),
|
||||
STATUS_INVALID_CALLBACK => bail!("Authentication callback was rejected"),
|
||||
STATUS_UNSUPPORTED_VERSION => bail!("Authentication callback protocol version is unsupported"),
|
||||
_ => bail!("Authentication callback handler returned an unknown status"),
|
||||
}
|
||||
}
|
||||
|
||||
fn callback_socket_path() -> PathBuf {
|
||||
let uid = uzers::get_current_uid();
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let runtime_dir = PathBuf::from(format!("/run/user/{uid}"));
|
||||
if fs::symlink_metadata(&runtime_dir).is_ok_and(|metadata| {
|
||||
metadata.is_dir()
|
||||
&& !metadata.file_type().is_symlink()
|
||||
&& metadata.uid() == uid
|
||||
&& metadata.permissions().mode() & 0o077 == 0
|
||||
}) {
|
||||
return runtime_dir.join("gp-connect/auth-callback.sock");
|
||||
}
|
||||
}
|
||||
|
||||
PathBuf::from(format!("/tmp/gp-connect-{uid}/auth-callback.sock"))
|
||||
}
|
||||
|
||||
fn prepare_socket_directory(socket_path: &Path) -> anyhow::Result<()> {
|
||||
let directory = socket_path
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow::anyhow!("Authentication callback socket has no parent directory"))?;
|
||||
|
||||
match DirBuilder::new().mode(0o700).create(directory) {
|
||||
Ok(()) => {}
|
||||
Err(err) if err.kind() == ErrorKind::AlreadyExists => {
|
||||
let metadata = fs::symlink_metadata(directory)?;
|
||||
if !metadata.is_dir() || metadata.file_type().is_symlink() {
|
||||
bail!("Authentication callback runtime path is not a directory");
|
||||
}
|
||||
if metadata.uid() != uzers::get_current_uid() {
|
||||
bail!("Authentication callback runtime directory has the wrong owner");
|
||||
}
|
||||
if metadata.permissions().mode() & 0o077 != 0 {
|
||||
bail!("Authentication callback runtime directory permissions are too broad");
|
||||
}
|
||||
}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish_bind(
|
||||
listener: UnixListener,
|
||||
socket_path: PathBuf,
|
||||
lock_file: fs::File,
|
||||
) -> anyhow::Result<AuthCallbackReceiver> {
|
||||
fs::set_permissions(&socket_path, fs::Permissions::from_mode(0o600))?;
|
||||
Ok(AuthCallbackReceiver {
|
||||
listener,
|
||||
socket_path,
|
||||
_lock_file: lock_file,
|
||||
})
|
||||
}
|
||||
|
||||
fn acquire_lock(socket_path: &Path) -> anyhow::Result<fs::File> {
|
||||
let lock_path = socket_path.with_file_name("auth-callback.lock");
|
||||
let lock_file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.mode(0o600)
|
||||
.open(lock_path)?;
|
||||
lock_file.set_permissions(fs::Permissions::from_mode(0o600))?;
|
||||
|
||||
match lock_file.try_lock() {
|
||||
Ok(()) => Ok(lock_file),
|
||||
Err(TryLockError::WouldBlock) => bail!("Another external-browser authentication is already in progress"),
|
||||
Err(TryLockError::Error(err)) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_stale_socket(socket_path: &Path) -> anyhow::Result<()> {
|
||||
let metadata = fs::symlink_metadata(socket_path)?;
|
||||
if !metadata.file_type().is_socket() || metadata.uid() != uzers::get_current_uid() {
|
||||
bail!("Authentication callback socket is not owned by the current user");
|
||||
}
|
||||
|
||||
fs::remove_file(socket_path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_callback(callback: &str) -> anyhow::Result<()> {
|
||||
if callback.len() > MAX_CALLBACK_SIZE {
|
||||
bail!("Authentication callback exceeds the maximum supported size");
|
||||
}
|
||||
|
||||
let Some((scheme, data)) = callback.split_once(':') else {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
};
|
||||
if scheme != CALLBACK_SCHEME || data.is_empty() {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
enum CallbackReadError {
|
||||
UnsupportedVersion,
|
||||
Invalid,
|
||||
Io,
|
||||
}
|
||||
|
||||
async fn read_callback(stream: &mut UnixStream) -> Result<String, CallbackReadError> {
|
||||
let mut magic = [0_u8; 4];
|
||||
stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?;
|
||||
if &magic != PROTOCOL_MAGIC {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?;
|
||||
if version != PROTOCOL_VERSION {
|
||||
return Err(CallbackReadError::UnsupportedVersion);
|
||||
}
|
||||
|
||||
let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize;
|
||||
if length == 0 || length > MAX_CALLBACK_SIZE {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let mut payload = vec![0; length];
|
||||
stream
|
||||
.read_exact(&mut payload)
|
||||
.await
|
||||
.map_err(|_| CallbackReadError::Io)?;
|
||||
let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?;
|
||||
validate_callback(&callback).map_err(|_| CallbackReadError::Invalid)?;
|
||||
Ok(callback)
|
||||
}
|
||||
|
||||
async fn write_response(stream: &mut UnixStream, status: u8) -> anyhow::Result<()> {
|
||||
stream.write_u8(PROTOCOL_VERSION).await?;
|
||||
stream.write_u8(status).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tempfile::tempdir;
|
||||
|
||||
use super::*;
|
||||
|
||||
const VALID_CALLBACK: &str = "globalprotectcallback:cas-as=1&[email protected]&token=very_long_string";
|
||||
|
||||
#[test]
|
||||
fn validates_supported_callback_scheme() {
|
||||
assert!(validate_callback(VALID_CALLBACK).is_ok());
|
||||
assert!(validate_callback("https://example.com").is_err());
|
||||
assert!(validate_callback("globalprotectcallback:").is_err());
|
||||
assert!(validate_callback(&format!("globalprotectcallback:{}", "x".repeat(MAX_CALLBACK_SIZE))).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaces_any_other_callback_handler() {
|
||||
assert!(!should_register_handler("gpgui.desktop"));
|
||||
assert!(should_register_handler(""));
|
||||
assert!(should_register_handler("gpauth.desktop"));
|
||||
assert!(should_register_handler("other-vpn.desktop"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_lxqt_desktop_session() {
|
||||
assert!(is_lxqt_desktop(Some(OsStr::new("LXQt"))));
|
||||
assert!(is_lxqt_desktop(Some(OsStr::new("LXQt:KDE"))));
|
||||
assert!(is_lxqt_desktop(Some(OsStr::new("lxqt"))));
|
||||
assert!(!is_lxqt_desktop(Some(OsStr::new("LXDE"))));
|
||||
assert!(!is_lxqt_desktop(None));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forwards_callback_to_waiting_receiver() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("callback.sock");
|
||||
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
|
||||
assert_eq!(
|
||||
fs::symlink_metadata(&socket_path).unwrap().permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
|
||||
let sender = tokio::spawn(async move { forward_auth_callback_to(VALID_CALLBACK, &socket_path).await });
|
||||
let auth_data = receiver.receive().await.unwrap();
|
||||
|
||||
sender.await.unwrap().unwrap();
|
||||
assert_eq!(auth_data.username(), "[email protected]");
|
||||
assert_eq!(auth_data.token(), Some("very_long_string"));
|
||||
let socket_path = receiver.socket_path.clone();
|
||||
drop(receiver);
|
||||
assert!(!socket_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_bad_requests_and_keeps_waiting() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("callback.sock");
|
||||
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
|
||||
|
||||
let sender = tokio::spawn(async move {
|
||||
assert_eq!(
|
||||
send_raw_callback(&socket_path, PROTOCOL_VERSION, "https://example.com").await,
|
||||
STATUS_INVALID_CALLBACK
|
||||
);
|
||||
assert_eq!(
|
||||
send_raw_callback(&socket_path, PROTOCOL_VERSION + 1, VALID_CALLBACK).await,
|
||||
STATUS_UNSUPPORTED_VERSION
|
||||
);
|
||||
forward_auth_callback_to(VALID_CALLBACK, &socket_path).await
|
||||
});
|
||||
let auth_data = receiver.receive().await.unwrap();
|
||||
|
||||
sender.await.unwrap().unwrap();
|
||||
assert_eq!(auth_data.username(), "[email protected]");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ignores_sender_that_disconnects_before_sending() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("callback.sock");
|
||||
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
|
||||
|
||||
drop(UnixStream::connect(&socket_path).await.unwrap());
|
||||
let sender = tokio::spawn(async move { forward_auth_callback_to(VALID_CALLBACK, &socket_path).await });
|
||||
let auth_data = receiver.receive().await.unwrap();
|
||||
|
||||
sender.await.unwrap().unwrap();
|
||||
assert_eq!(auth_data.username(), "[email protected]");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replaces_owned_stale_socket() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("callback.sock");
|
||||
drop(std::os::unix::net::UnixListener::bind(&socket_path).unwrap());
|
||||
|
||||
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
|
||||
assert!(socket_path.exists());
|
||||
drop(receiver);
|
||||
assert!(!socket_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reports_when_no_receiver_is_active() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("missing.sock");
|
||||
|
||||
let err = forward_auth_callback_to(VALID_CALLBACK, &socket_path)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("No external-browser authentication"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_runtime_directory_with_broad_permissions() {
|
||||
let directory = tempdir().unwrap();
|
||||
let runtime_dir = directory.path().join("runtime");
|
||||
fs::create_dir(&runtime_dir).unwrap();
|
||||
fs::set_permissions(&runtime_dir, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let err = prepare_socket_directory(&runtime_dir.join("callback.sock")).unwrap_err();
|
||||
assert!(err.to_string().contains("permissions are too broad"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_second_active_receiver() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("callback.sock");
|
||||
let _receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
|
||||
|
||||
let err = AuthCallbackReceiver::bind_at(socket_path).err().unwrap();
|
||||
assert!(err.to_string().contains("already in progress"));
|
||||
}
|
||||
|
||||
async fn send_raw_callback(socket_path: &Path, version: u8, callback: &str) -> u8 {
|
||||
let mut stream = UnixStream::connect(socket_path).await.unwrap();
|
||||
stream.write_all(PROTOCOL_MAGIC).await.unwrap();
|
||||
stream.write_u8(version).await.unwrap();
|
||||
stream.write_u32(callback.len() as u32).await.unwrap();
|
||||
stream.write_all(callback.as_bytes()).await.unwrap();
|
||||
assert_eq!(stream.read_u8().await.unwrap(), PROTOCOL_VERSION);
|
||||
stream.read_u8().await.unwrap()
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
use std::{ffi::OsStr, os::raw::c_void, path::PathBuf, thread, time::Duration};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use objc2_app_kit::NSWorkspace;
|
||||
use objc2_foundation::{NSBundle, NSString, NSURL};
|
||||
|
||||
const CALLBACK_SCHEME: &str = "globalprotectcallback";
|
||||
const CALLBACK_URL: &str = "globalprotectcallback:";
|
||||
const HANDLER_BUNDLE_ID: &str = "com.yuezk.gpauth";
|
||||
const LOGIN_APP_NAME: &str = "GP Connect Login.app";
|
||||
|
||||
#[link(name = "CoreServices", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn LSRegisterURL(url: *const c_void, update: u8) -> i32;
|
||||
}
|
||||
|
||||
pub(super) fn ensure_auth_callback_handler() -> anyhow::Result<()> {
|
||||
let workspace = NSWorkspace::sharedWorkspace();
|
||||
let app_paths = callback_app_paths();
|
||||
let selected_handler = current_handler(&workspace);
|
||||
match selected_handler.as_ref() {
|
||||
Some((handler, path))
|
||||
if handler == HANDLER_BUNDLE_ID && app_paths.iter().any(|candidate| same_path(candidate, path)) =>
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
Some((handler, _)) if handler == HANDLER_BUNDLE_ID => {}
|
||||
None => {}
|
||||
Some((handler, _)) => bail!("The globalprotectcallback URL scheme is owned by {handler}"),
|
||||
}
|
||||
|
||||
let app_path = app_paths
|
||||
.first()
|
||||
.context("GP Connect Login.app is required for external-browser authentication; install GP Connect")?;
|
||||
let app_url = file_url(app_path);
|
||||
register_app(&app_url)?;
|
||||
workspace.setDefaultApplicationAtURL_toOpenURLsWithScheme_completionHandler(
|
||||
&app_url,
|
||||
&NSString::from_str(CALLBACK_SCHEME),
|
||||
None,
|
||||
);
|
||||
|
||||
for _ in 0..50 {
|
||||
if current_handler(&workspace)
|
||||
.is_some_and(|(handler, path)| handler == HANDLER_BUNDLE_ID && same_path(app_path, &path))
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
bail!("The globalprotectcallback URL handler registration did not take effect")
|
||||
}
|
||||
|
||||
fn register_app(app_url: &NSURL) -> anyhow::Result<()> {
|
||||
// A nested application is not necessarily known to LaunchServices until it
|
||||
// has been launched. Register it explicitly before assigning its URL scheme.
|
||||
let status = unsafe { LSRegisterURL(app_url as *const NSURL as *const c_void, 1) };
|
||||
if status != 0 {
|
||||
bail!("Failed to register GP Connect Login.app with LaunchServices (OSStatus {status})");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn current_handler(workspace: &NSWorkspace) -> Option<(String, PathBuf)> {
|
||||
let callback_url = NSURL::URLWithString(&NSString::from_str(CALLBACK_URL))?;
|
||||
let app_url = workspace.URLForApplicationToOpenURL(&callback_url)?;
|
||||
let identifier = bundle_identifier(&app_url)?;
|
||||
let path = app_url.path().map(|path| PathBuf::from(path.to_string()))?;
|
||||
Some((identifier, path))
|
||||
}
|
||||
|
||||
fn callback_app_paths() -> Vec<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
|
||||
if let Ok(executable) = std::env::current_exe() {
|
||||
for path in executable.ancestors() {
|
||||
if path.file_name() == Some(OsStr::new("Helpers")) {
|
||||
candidates.push(path.join(LOGIN_APP_NAME));
|
||||
}
|
||||
if path.extension() == Some(OsStr::new("app")) {
|
||||
candidates.push(path.to_path_buf());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(user_dir) = std::env::var_os("HOME").filter(|path| !path.is_empty()) {
|
||||
let applications = PathBuf::from(user_dir).join("Applications");
|
||||
candidates.push(
|
||||
applications
|
||||
.join("GP Connect.app/Contents/Helpers")
|
||||
.join(LOGIN_APP_NAME),
|
||||
);
|
||||
}
|
||||
|
||||
candidates.push(PathBuf::from("/Applications/GP Connect.app/Contents/Helpers").join(LOGIN_APP_NAME));
|
||||
|
||||
candidates
|
||||
.into_iter()
|
||||
.filter(|path| path.is_dir() && bundle_identifier(&file_url(path)).as_deref() == Some(HANDLER_BUNDLE_ID))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn same_path(left: &std::path::Path, right: &std::path::Path) -> bool {
|
||||
match (left.canonicalize(), right.canonicalize()) {
|
||||
(Ok(left), Ok(right)) => left == right,
|
||||
_ => left == right,
|
||||
}
|
||||
}
|
||||
|
||||
fn file_url(path: &std::path::Path) -> objc2::rc::Retained<NSURL> {
|
||||
NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
|
||||
}
|
||||
|
||||
fn bundle_identifier(app_url: &NSURL) -> Option<String> {
|
||||
NSBundle::bundleWithURL(app_url)?
|
||||
.bundleIdentifier()
|
||||
.map(|identifier| identifier.to_string())
|
||||
}
|
||||
@@ -7,15 +7,9 @@ use gpapi::{
|
||||
#[cfg(feature = "browser-auth")]
|
||||
mod browser;
|
||||
|
||||
#[cfg(feature = "browser-auth")]
|
||||
mod callback;
|
||||
|
||||
#[cfg(feature = "browser-auth")]
|
||||
pub use browser::*;
|
||||
|
||||
#[cfg(feature = "browser-auth")]
|
||||
pub use callback::*;
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
mod webview;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::bail;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use gpapi::utils::window::{WindowTypeHint, set_window_type_hint};
|
||||
use gpapi::{
|
||||
auth::{AuthWindowTheme, AuthenticationCancelled, SamlAuthData},
|
||||
gp_params::GpParams,
|
||||
@@ -10,8 +8,6 @@ use gpapi::{
|
||||
utils::{redact::redact_uri, window::get_title_bar_height},
|
||||
};
|
||||
use log::{info, warn};
|
||||
#[cfg(target_os = "macos")]
|
||||
use tauri::Manager;
|
||||
use tauri::{
|
||||
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
|
||||
webview::{PageLoadEvent, PageLoadPayload},
|
||||
@@ -158,9 +154,6 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
.center()
|
||||
.build()?;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?;
|
||||
|
||||
self
|
||||
.setup_auth_window(&auth_window, Arc::clone(&auth_messenger))
|
||||
.await?;
|
||||
@@ -325,14 +318,6 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
info!("Raising auth window...");
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Err(err) = auth_window
|
||||
.app_handle()
|
||||
.set_activation_policy(tauri::ActivationPolicy::Regular)
|
||||
{
|
||||
warn!("Failed to show the application in the Dock: {}", err);
|
||||
}
|
||||
|
||||
use gpapi::utils::window::WindowExt;
|
||||
let result = auth_window.raise();
|
||||
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
use std::{
|
||||
os::unix::process::CommandExt,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use anyhow::Context;
|
||||
use log::{debug, info, warn};
|
||||
|
||||
use crate::Browser;
|
||||
@@ -15,56 +11,11 @@ const EDGE_BETA_BROWSERS: &[&str] = &["microsoft-edge-beta"];
|
||||
const EDGE_DEV_BROWSERS: &[&str] = &["microsoft-edge-dev"];
|
||||
const FIREFOX_BROWSERS: &[&str] = &["firefox"];
|
||||
const FIREFOX_ESR_BROWSERS: &[&str] = &["firefox-esr"];
|
||||
const BRAVE_BROWSERS: &[&str] = &["brave-browser-stable"];
|
||||
const VIVALDI_BROWSERS: &[&str] = &["vivaldi-stable"];
|
||||
const FALKON_BROWSERS: &[&str] = &["falkon"];
|
||||
const EPIPHANY_BROWSERS: &[&str] = &["epiphany"];
|
||||
const OPERA_BROWSERS: &[&str] = &["opera"];
|
||||
const LIBREWOLF_BROWSERS: &[&str] = &["librewolf"];
|
||||
const WATERFOX_BROWSERS: &[&str] = &["waterfox"];
|
||||
const QUTEBROWSER_BROWSERS: &[&str] = &["qutebrowser"];
|
||||
|
||||
const AUTO_BROWSER_PROGRAMS: &[&[&str]] = &[
|
||||
GOOGLE_CHROME_BROWSERS,
|
||||
CHROMIUM_BROWSERS,
|
||||
EDGE_BROWSERS,
|
||||
EDGE_BETA_BROWSERS,
|
||||
EDGE_DEV_BROWSERS,
|
||||
FIREFOX_BROWSERS,
|
||||
FIREFOX_ESR_BROWSERS,
|
||||
BRAVE_BROWSERS,
|
||||
VIVALDI_BROWSERS,
|
||||
FALKON_BROWSERS,
|
||||
EPIPHANY_BROWSERS,
|
||||
OPERA_BROWSERS,
|
||||
LIBREWOLF_BROWSERS,
|
||||
WATERFOX_BROWSERS,
|
||||
QUTEBROWSER_BROWSERS,
|
||||
];
|
||||
|
||||
const AUTO_BROWSER_FLATPAK_IDS: &[&str] = &[
|
||||
"com.google.Chrome",
|
||||
"org.chromium.Chromium",
|
||||
"com.microsoft.Edge",
|
||||
"org.mozilla.firefox",
|
||||
"com.brave.Browser",
|
||||
"com.vivaldi.Vivaldi",
|
||||
"org.kde.falkon",
|
||||
"org.gnome.Epiphany",
|
||||
"com.opera.Opera",
|
||||
"io.gitlab.librewolf-community",
|
||||
"net.waterfox.waterfox",
|
||||
"org.qutebrowser.qutebrowser",
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum LauncherSpec {
|
||||
Programs(&'static [&'static str]),
|
||||
Flatpak(&'static str),
|
||||
ProgramsOrFlatpak {
|
||||
programs: &'static [&'static str],
|
||||
app_id: &'static str,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -77,27 +28,22 @@ pub(super) fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> {
|
||||
match browser {
|
||||
Browser::Auto => open_auto_browser(url),
|
||||
Browser::Default => open_default_browser(url),
|
||||
Browser::Chrome => open_resolved_browser(url, find_chrome_browser(), "Chrome is not available."),
|
||||
Browser::Edge => open_resolved_browser(url, find_edge_browser(), "Edge is not available."),
|
||||
Browser::Firefox => open_resolved_browser(url, find_firefox_browser(), "Firefox is not available."),
|
||||
Browser::Safari => open_resolved_browser(url, find_program(browser.as_str()), "Safari is not available."),
|
||||
Browser::Other(browser) => open_resolved_browser(
|
||||
url,
|
||||
find_program(browser.trim()),
|
||||
"Configured browser is not available.",
|
||||
),
|
||||
Browser::Chrome => {
|
||||
let browser = find_chrome_browser().unwrap_or_else(|| browser.as_str().to_string());
|
||||
open_with_browser(url, &browser)
|
||||
}
|
||||
Browser::Edge => {
|
||||
let browser = find_edge_browser().unwrap_or_else(|| browser.as_str().to_string());
|
||||
open_with_browser(url, &browser)
|
||||
}
|
||||
Browser::Firefox => {
|
||||
let browser = find_firefox_browser().unwrap_or_else(|| browser.as_str().to_string());
|
||||
open_with_browser(url, &browser)
|
||||
}
|
||||
Browser::Safari | Browser::Other(_) => open_with_browser(url, browser.as_str()),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_resolved_browser(
|
||||
url: &str,
|
||||
executable: Option<String>,
|
||||
unavailable_message: &'static str,
|
||||
) -> anyhow::Result<()> {
|
||||
let executable = executable.context(unavailable_message)?;
|
||||
open_with_browser(url, &executable)
|
||||
}
|
||||
|
||||
fn open_auto_browser(url: &str) -> anyhow::Result<()> {
|
||||
let default_launcher = find_default_browser_launcher();
|
||||
if let Some(launcher) = default_launcher.as_ref() {
|
||||
@@ -142,7 +88,6 @@ fn open_with_launcher(url: &str, launcher: &BrowserLauncher) -> anyhow::Result<(
|
||||
info!("Launching Flatpak browser: {app_id}");
|
||||
Command::new(executable)
|
||||
.args(["run", app_id, url])
|
||||
.process_group(0)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
@@ -201,28 +146,7 @@ fn launcher_spec_for_desktop_id(desktop_id: &str) -> Option<LauncherSpec> {
|
||||
"com.google.Chrome.desktop" => Some(LauncherSpec::Flatpak("com.google.Chrome")),
|
||||
"org.chromium.Chromium.desktop" => Some(LauncherSpec::Flatpak("org.chromium.Chromium")),
|
||||
"com.microsoft.Edge.desktop" => Some(LauncherSpec::Flatpak("com.microsoft.Edge")),
|
||||
"org.mozilla.firefox.desktop" => Some(LauncherSpec::ProgramsOrFlatpak {
|
||||
programs: FIREFOX_BROWSERS,
|
||||
app_id: "org.mozilla.firefox",
|
||||
}),
|
||||
"com.brave.Browser.desktop" => Some(LauncherSpec::Flatpak("com.brave.Browser")),
|
||||
"vivaldi-stable.desktop" => Some(LauncherSpec::Programs(VIVALDI_BROWSERS)),
|
||||
"com.vivaldi.Vivaldi.desktop" => Some(LauncherSpec::Flatpak("com.vivaldi.Vivaldi")),
|
||||
"org.kde.falkon.desktop" => Some(LauncherSpec::ProgramsOrFlatpak {
|
||||
programs: FALKON_BROWSERS,
|
||||
app_id: "org.kde.falkon",
|
||||
}),
|
||||
"org.gnome.Epiphany.desktop" => Some(LauncherSpec::ProgramsOrFlatpak {
|
||||
programs: EPIPHANY_BROWSERS,
|
||||
app_id: "org.gnome.Epiphany",
|
||||
}),
|
||||
"com.opera.Opera.desktop" => Some(LauncherSpec::Flatpak("com.opera.Opera")),
|
||||
"io.gitlab.librewolf-community.desktop" => Some(LauncherSpec::Flatpak("io.gitlab.librewolf-community")),
|
||||
"net.waterfox.waterfox.desktop" => Some(LauncherSpec::Flatpak("net.waterfox.waterfox")),
|
||||
"org.qutebrowser.qutebrowser.desktop" => Some(LauncherSpec::ProgramsOrFlatpak {
|
||||
programs: QUTEBROWSER_BROWSERS,
|
||||
app_id: "org.qutebrowser.qutebrowser",
|
||||
}),
|
||||
"org.mozilla.firefox.desktop" => Some(LauncherSpec::Flatpak("org.mozilla.firefox")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -230,62 +154,20 @@ fn launcher_spec_for_desktop_id(desktop_id: &str) -> Option<LauncherSpec> {
|
||||
fn resolve_launcher(spec: LauncherSpec) -> Option<BrowserLauncher> {
|
||||
match spec {
|
||||
LauncherSpec::Programs(programs) => find_programs(programs).map(BrowserLauncher::Executable),
|
||||
LauncherSpec::Flatpak(app_id) => find_flatpak_browser(app_id),
|
||||
LauncherSpec::ProgramsOrFlatpak { programs, app_id } => find_programs(programs)
|
||||
.map(BrowserLauncher::Executable)
|
||||
.or_else(|| find_flatpak_browser(app_id)),
|
||||
LauncherSpec::Flatpak(app_id) => {
|
||||
find_program("flatpak").map(|executable| BrowserLauncher::Flatpak { executable, app_id })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn find_flatpak_browser(app_id: &'static str) -> Option<BrowserLauncher> {
|
||||
let executable = find_program("flatpak")?;
|
||||
let installed = Command::new(&executable)
|
||||
.args(["info", app_id])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.is_ok_and(|status| status.success());
|
||||
|
||||
installed.then_some(BrowserLauncher::Flatpak { executable, app_id })
|
||||
}
|
||||
|
||||
fn find_auto_browser_launcher() -> Option<BrowserLauncher> {
|
||||
find_auto_browser()
|
||||
.map(BrowserLauncher::Executable)
|
||||
.or_else(find_auto_flatpak_browser)
|
||||
find_auto_browser().map(BrowserLauncher::Executable)
|
||||
}
|
||||
|
||||
fn find_auto_browser() -> Option<String> {
|
||||
AUTO_BROWSER_PROGRAMS
|
||||
.iter()
|
||||
.find_map(|programs| find_programs(programs))
|
||||
}
|
||||
|
||||
fn find_auto_flatpak_browser() -> Option<BrowserLauncher> {
|
||||
let executable = find_program("flatpak")?;
|
||||
let output = Command::new(&executable)
|
||||
.args(["list", "--app", "--columns=application"])
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let installed_apps = String::from_utf8_lossy(&output.stdout);
|
||||
let app_id = find_auto_flatpak_app_id(&installed_apps)?;
|
||||
|
||||
Some(BrowserLauncher::Flatpak { executable, app_id })
|
||||
}
|
||||
|
||||
fn find_auto_flatpak_app_id(installed_apps: &str) -> Option<&'static str> {
|
||||
AUTO_BROWSER_FLATPAK_IDS
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|app_id| installed_apps.lines().any(|installed| installed.trim() == *app_id))
|
||||
find_chrome_browser()
|
||||
.or_else(find_edge_browser)
|
||||
.or_else(find_firefox_browser)
|
||||
}
|
||||
|
||||
fn find_chrome_browser() -> Option<String> {
|
||||
@@ -315,10 +197,15 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn auto_candidates_use_the_expected_order() {
|
||||
let candidates = AUTO_BROWSER_PROGRAMS
|
||||
fn auto_candidates_try_chrome_then_edge_then_firefox() {
|
||||
let candidates = GOOGLE_CHROME_BROWSERS
|
||||
.iter()
|
||||
.flat_map(|programs| programs.iter())
|
||||
.chain(CHROMIUM_BROWSERS)
|
||||
.chain(EDGE_BROWSERS)
|
||||
.chain(EDGE_BETA_BROWSERS)
|
||||
.chain(EDGE_DEV_BROWSERS)
|
||||
.chain(FIREFOX_BROWSERS)
|
||||
.chain(FIREFOX_ESR_BROWSERS)
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -335,32 +222,6 @@ mod tests {
|
||||
"microsoft-edge-dev",
|
||||
"firefox",
|
||||
"firefox-esr",
|
||||
"brave-browser-stable",
|
||||
"vivaldi-stable",
|
||||
"falkon",
|
||||
"epiphany",
|
||||
"opera",
|
||||
"librewolf",
|
||||
"waterfox",
|
||||
"qutebrowser",
|
||||
]
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
AUTO_BROWSER_FLATPAK_IDS,
|
||||
[
|
||||
"com.google.Chrome",
|
||||
"org.chromium.Chromium",
|
||||
"com.microsoft.Edge",
|
||||
"org.mozilla.firefox",
|
||||
"com.brave.Browser",
|
||||
"com.vivaldi.Vivaldi",
|
||||
"org.kde.falkon",
|
||||
"org.gnome.Epiphany",
|
||||
"com.opera.Opera",
|
||||
"io.gitlab.librewolf-community",
|
||||
"net.waterfox.waterfox",
|
||||
"org.qutebrowser.qutebrowser",
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -392,46 +253,7 @@ mod tests {
|
||||
),
|
||||
(
|
||||
"org.mozilla.firefox.desktop",
|
||||
LauncherSpec::ProgramsOrFlatpak {
|
||||
programs: FIREFOX_BROWSERS,
|
||||
app_id: "org.mozilla.firefox",
|
||||
},
|
||||
),
|
||||
("com.brave.Browser.desktop", LauncherSpec::Flatpak("com.brave.Browser")),
|
||||
("vivaldi-stable.desktop", LauncherSpec::Programs(VIVALDI_BROWSERS)),
|
||||
(
|
||||
"com.vivaldi.Vivaldi.desktop",
|
||||
LauncherSpec::Flatpak("com.vivaldi.Vivaldi"),
|
||||
),
|
||||
(
|
||||
"org.kde.falkon.desktop",
|
||||
LauncherSpec::ProgramsOrFlatpak {
|
||||
programs: FALKON_BROWSERS,
|
||||
app_id: "org.kde.falkon",
|
||||
},
|
||||
),
|
||||
(
|
||||
"org.gnome.Epiphany.desktop",
|
||||
LauncherSpec::ProgramsOrFlatpak {
|
||||
programs: EPIPHANY_BROWSERS,
|
||||
app_id: "org.gnome.Epiphany",
|
||||
},
|
||||
),
|
||||
("com.opera.Opera.desktop", LauncherSpec::Flatpak("com.opera.Opera")),
|
||||
(
|
||||
"io.gitlab.librewolf-community.desktop",
|
||||
LauncherSpec::Flatpak("io.gitlab.librewolf-community"),
|
||||
),
|
||||
(
|
||||
"net.waterfox.waterfox.desktop",
|
||||
LauncherSpec::Flatpak("net.waterfox.waterfox"),
|
||||
),
|
||||
(
|
||||
"org.qutebrowser.qutebrowser.desktop",
|
||||
LauncherSpec::ProgramsOrFlatpak {
|
||||
programs: QUTEBROWSER_BROWSERS,
|
||||
app_id: "org.qutebrowser.qutebrowser",
|
||||
},
|
||||
LauncherSpec::Flatpak("org.mozilla.firefox"),
|
||||
),
|
||||
];
|
||||
|
||||
@@ -444,24 +266,4 @@ mod tests {
|
||||
fn unknown_desktop_id_is_not_used() {
|
||||
assert_eq!(launcher_spec_for_desktop_id("code.desktop"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_flatpak_candidates_use_priority_and_exact_ids() {
|
||||
assert_eq!(
|
||||
find_auto_flatpak_app_id("org.kde.falkon\ncom.brave.Browser\n"),
|
||||
Some("com.brave.Browser")
|
||||
);
|
||||
assert_eq!(find_auto_flatpak_app_id("com.brave.Browser.beta\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_custom_browser_returns_an_error() {
|
||||
let err = open_url(
|
||||
"https://example.com",
|
||||
Browser::Other("gpgui-browser-that-does-not-exist"),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(err.to_string(), "Configured browser is not available.");
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,6 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[cfg(all(
|
||||
not(debug_assertions),
|
||||
any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")
|
||||
))]
|
||||
use crate::constants::GP_DOWNLOADED_GUI_BINARY;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use crate::constants::GP_HIP_SCRIPT_INSTALLER_BINARY;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use crate::constants::GP_VPNC_SCRIPT_INSTALLER_BINARY;
|
||||
use crate::constants::{GP_AUTH_BINARY, GP_CLIENT_BINARY, GP_GUI_BINARY, GP_GUI_HELPER_BINARY, GP_SERVICE_BINARY};
|
||||
@@ -31,15 +24,6 @@ pub fn gp_vpnc_script_installer() -> PathBuf {
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn gp_hip_script_installer() -> PathBuf {
|
||||
resolve(
|
||||
"GP_HIP_SCRIPT_INSTALLER_BINARY",
|
||||
"gp-hip-script-installer",
|
||||
GP_HIP_SCRIPT_INSTALLER_BINARY,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn gpauth() -> PathBuf {
|
||||
resolve("GP_AUTH_BINARY", "gpauth", GP_AUTH_BINARY)
|
||||
}
|
||||
@@ -48,24 +32,6 @@ pub fn gpgui() -> PathBuf {
|
||||
resolve("GP_GUI_BINARY", "gpgui", GP_GUI_BINARY)
|
||||
}
|
||||
|
||||
pub fn gpgui_update_target() -> PathBuf {
|
||||
#[cfg(all(
|
||||
not(debug_assertions),
|
||||
any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")
|
||||
))]
|
||||
{
|
||||
PathBuf::from(GP_DOWNLOADED_GUI_BINARY)
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
debug_assertions,
|
||||
not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))
|
||||
))]
|
||||
{
|
||||
gpgui()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn gpgui_helper() -> PathBuf {
|
||||
resolve("GP_GUI_HELPER_BINARY", "gpgui-helper", GP_GUI_HELPER_BINARY)
|
||||
}
|
||||
@@ -82,27 +48,8 @@ fn sibling_binary(binary_name: &str) -> Option<PathBuf> {
|
||||
let current_exe = env::current_exe().ok()?;
|
||||
let bin_dir = current_exe.parent()?;
|
||||
let binary = bin_dir.join(binary_name);
|
||||
if is_file(&binary) {
|
||||
return Some(binary);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(binary) = bundled_helper_path(¤t_exe, binary_name)
|
||||
&& is_file(&binary)
|
||||
{
|
||||
return Some(binary);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn bundled_helper_path(executable: &Path, binary_name: &str) -> Option<PathBuf> {
|
||||
let bin_dir = executable.parent()?;
|
||||
let contents = bin_dir.parent()?;
|
||||
let bundle = contents.parent()?;
|
||||
if bin_dir.file_name()? != "MacOS" || contents.file_name()? != "Contents" || bundle.extension()? != "app" {
|
||||
return None;
|
||||
}
|
||||
Some(contents.join("Helpers").join(binary_name))
|
||||
is_file(&binary).then_some(binary)
|
||||
}
|
||||
|
||||
fn is_file(path: &Path) -> bool {
|
||||
@@ -113,20 +60,6 @@ fn is_file(path: &Path) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn desktop_resolves_helpers_in_the_actual_app_bundle_layout() {
|
||||
assert_eq!(
|
||||
bundled_helper_path(
|
||||
Path::new("/Applications/GP Connect.app/Contents/MacOS/gpgui"),
|
||||
"gpclient"
|
||||
),
|
||||
Some(PathBuf::from("/Applications/GP Connect.app/Contents/Helpers/gpclient"))
|
||||
);
|
||||
assert!(bundled_helper_path(Path::new("/usr/local/bin/gpgui"), "gpclient").is_none());
|
||||
assert!(bundled_helper_path(Path::new("/tmp/Contents/MacOS/gpgui"), "gpclient").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_path_is_used_when_no_sibling_exists() {
|
||||
let path = resolve("GP_TEST_BINARY", "missing-gp-test-binary", "/usr/bin/gp-test");
|
||||
|
||||
@@ -6,10 +6,6 @@ pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const GP_HIP_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-hip-script-installer";
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub const GP_HIP_SCRIPT_INSTALLER_BINARY: &str = "/usr/local/libexec/gpclient/gp-hip-script-installer";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const INSTALLED_VPNC_SCRIPT: &str = "/var/lib/gpclient/scripts/vpnc-script";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const INSTALLED_VPNC_SCRIPT_METADATA: &str = "/var/lib/gpclient/scripts/vpnc-script.metadata";
|
||||
@@ -20,7 +16,7 @@ pub const INSTALLED_VPNC_SCRIPT: &str = "/var/db/gpclient/scripts/vpnc-script";
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub const INSTALLED_VPNC_SCRIPT_METADATA: &str = "/var/db/gpclient/scripts/vpnc-script.metadata";
|
||||
pub const MAX_VPNC_SCRIPT_SIZE: usize = 1024 * 1024;
|
||||
pub const MAX_HIP_SCRIPT_SIZE: usize = 1024 * 1024;
|
||||
pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port";
|
||||
|
||||
// Release binaries - macOS (Apple Silicon Homebrew)
|
||||
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
|
||||
@@ -53,8 +49,6 @@ pub const GP_CLIENT_BINARY: &str = "/usr/local/bin/gpclient";
|
||||
pub const GP_SERVICE_BINARY: &str = "/usr/local/bin/gpservice";
|
||||
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
|
||||
pub const GP_GUI_BINARY: &str = "/usr/local/bin/gpgui";
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub const GP_DOWNLOADED_GUI_BINARY: &str = "/usr/local/libexec/gpclient/gpgui";
|
||||
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
|
||||
pub const GP_GUI_HELPER_BINARY: &str = "/usr/local/bin/gpgui-helper";
|
||||
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
|
||||
@@ -76,8 +70,6 @@ pub const GP_SERVICE_BINARY: &str = "/usr/bin/gpservice";
|
||||
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
|
||||
))]
|
||||
pub const GP_GUI_BINARY: &str = "/usr/bin/gpgui";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const GP_DOWNLOADED_GUI_BINARY: &str = "/var/lib/gpclient/gpgui";
|
||||
#[cfg(all(
|
||||
not(debug_assertions),
|
||||
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
|
||||
|
||||
@@ -6,7 +6,6 @@ edition.workspace = true
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process"] }
|
||||
common = { path = "../common" }
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
@@ -18,10 +17,9 @@ version-compare = "0.2"
|
||||
pem.workspace = true
|
||||
xmltree.workspace = true
|
||||
serde.workspace = true
|
||||
specta = { workspace = true, features = ["derive", "uuid"] }
|
||||
specta = { workspace = true, features = ["derive"] }
|
||||
urlencoding.workspace = true
|
||||
tokio = { workspace = true, features = ["process", "signal", "macros"] }
|
||||
tokio-util.workspace = true
|
||||
serde_json.workspace = true
|
||||
whoami.workspace = true
|
||||
tempfile.workspace = true
|
||||
@@ -38,7 +36,6 @@ uuid = { workspace = true, features = ["v4", "v5", "serde"] }
|
||||
chrono.workspace = true
|
||||
humantime.workspace = true
|
||||
netdev.workspace = true
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
os_info = { version = "3", default-features = false }
|
||||
snow.workspace = true
|
||||
zeroize = { workspace = true, features = ["serde"] }
|
||||
@@ -61,7 +58,6 @@ gtk = { version = "0.18", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest.workspace = true
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[features]
|
||||
tauri = ["dep:tauri", "dep:gtk"]
|
||||
|
||||
@@ -154,6 +154,7 @@ impl SamlAuthData {
|
||||
|
||||
let auth_data: SamlAuthData = serde_urlencoded::from_str(auth_data.borrow()).map_err(|e| {
|
||||
warn!("Failed to parse token auth data: {}", e);
|
||||
warn!("Auth data: {}", auth_data);
|
||||
AuthDataParseError::Invalid(anyhow::anyhow!(e))
|
||||
})?;
|
||||
|
||||
@@ -162,7 +163,7 @@ impl SamlAuthData {
|
||||
}
|
||||
|
||||
let auth_data = decode_to_string(auth_data).map_err(|e| {
|
||||
warn!("Failed to decode SAML auth data: {}", e);
|
||||
warn!("Failed to decode SAML auth data: {}, data: {}", e, data);
|
||||
AuthDataParseError::Invalid(anyhow::anyhow!(e))
|
||||
})?;
|
||||
let auth_data = Self::from_html(&auth_data)?;
|
||||
|
||||
+18
-250
@@ -1,139 +1,33 @@
|
||||
use std::io::{self, Write};
|
||||
|
||||
use clap_verbosity_flag::{LogLevel, Verbosity, VerbosityFilter};
|
||||
use log::Level;
|
||||
|
||||
use crate::{
|
||||
error::PortalError,
|
||||
log_format::{LogFormat, write_json_record},
|
||||
};
|
||||
use crate::error::PortalError;
|
||||
|
||||
pub mod args;
|
||||
|
||||
pub trait Args {
|
||||
fn fix_openssl(&self) -> bool;
|
||||
fn ignore_tls_errors(&self) -> bool;
|
||||
|
||||
/// How this program renders its logs.
|
||||
///
|
||||
/// Required rather than defaulted: a default would let an implementor drop
|
||||
/// the override and silently report failures as prose to a caller that asked
|
||||
/// for JSON, with nothing — not even a warning — to catch it.
|
||||
fn log_format(&self) -> LogFormat;
|
||||
}
|
||||
|
||||
/// Suggestions for re-running the command, for failures that have a known
|
||||
/// workaround. Empty when there is nothing useful to say — including when the
|
||||
/// relevant option is already in use.
|
||||
fn retry_hints(err: &anyhow::Error, args: &impl Args) -> Vec<String> {
|
||||
let Some(err) = err.downcast_ref::<PortalError>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let command_line = || {
|
||||
let argv = std::env::args().collect::<Vec<_>>();
|
||||
let program = argv.first().cloned().unwrap_or_default();
|
||||
let rest = argv.get(1..).map(|rest| rest.join(" ")).unwrap_or_default();
|
||||
|
||||
(program, rest)
|
||||
};
|
||||
|
||||
// The blank line between the sentence and the command is part of the output
|
||||
// users already see; keep it exactly.
|
||||
let mut hints = Vec::new();
|
||||
|
||||
if err.is_legacy_openssl_error() && !args.fix_openssl() {
|
||||
let (program, rest) = command_line();
|
||||
hints.push(format!(
|
||||
"Re-run it with the `--fix-openssl` option to work around this issue, e.g.:\n\n{program} --fix-openssl {rest}"
|
||||
));
|
||||
}
|
||||
|
||||
if err.is_tls_error() && !args.ignore_tls_errors() {
|
||||
let (program, rest) = command_line();
|
||||
hints.push(format!(
|
||||
"Re-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n\n{program} --ignore-tls-errors {rest}"
|
||||
));
|
||||
}
|
||||
|
||||
hints
|
||||
}
|
||||
|
||||
/// Write one message to `w` the way `format` asks for.
|
||||
///
|
||||
/// Text is emitted exactly as it always was, so existing output does not move.
|
||||
/// JSON is written directly rather than through the `log` macros, because these
|
||||
/// are reports rather than log lines: they must survive `--quiet`, which would
|
||||
/// otherwise discard the only explanation of a failed run.
|
||||
///
|
||||
/// The record is rendered into one buffer and written once. `serde_json`'s
|
||||
/// `Display` would otherwise reach the stream in dozens of fragments, and any
|
||||
/// process sharing this stderr — the spawned authenticator, a connect script —
|
||||
/// could land a line inside a half-written record.
|
||||
fn write_message<W: Write>(w: &mut W, format: LogFormat, level: Level, message: &str) -> io::Result<()> {
|
||||
match format {
|
||||
LogFormat::Text => writeln!(w, "{message}"),
|
||||
LogFormat::Json => {
|
||||
// Callers pass the exact text line, blank-line padding included, so the
|
||||
// text form does not move. A record carries its own separation.
|
||||
let message = message.trim_start_matches('\n');
|
||||
let mut line = Vec::new();
|
||||
|
||||
write_json_record(
|
||||
&mut line,
|
||||
&log::Record::builder()
|
||||
.level(level)
|
||||
.target(module_path!())
|
||||
.args(format_args!("{message}"))
|
||||
.build(),
|
||||
)?;
|
||||
|
||||
w.write_all(&line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Report a user-facing line that is not a log record — a note, a warning, or
|
||||
/// advice about what to try next.
|
||||
///
|
||||
/// Callers used `eprintln!` directly, which in JSON mode drops prose into a
|
||||
/// stream the caller is parsing a line at a time. Routing them here keeps one
|
||||
/// answer to "how does this program emit a user-facing line", and leaves the
|
||||
/// text form byte-for-byte unchanged.
|
||||
pub fn report(format: LogFormat, level: Level, message: &str) {
|
||||
let _ = write_message(&mut io::stderr().lock(), format, level, message);
|
||||
}
|
||||
|
||||
fn write_failure<W: Write>(w: &mut W, format: LogFormat, err: &anyhow::Error, hints: &[String]) -> io::Result<()> {
|
||||
match format {
|
||||
LogFormat::Text => {
|
||||
writeln!(w, "\nError: {err:?}")?;
|
||||
|
||||
for hint in hints {
|
||||
writeln!(w, "\n{hint}\n")?;
|
||||
}
|
||||
}
|
||||
LogFormat::Json => {
|
||||
write_message(w, format, Level::Error, &format!("{err:?}"))?;
|
||||
|
||||
for hint in hints {
|
||||
write_message(w, format, Level::Error, hint)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_error_to<W: Write>(w: &mut W, err: anyhow::Error, args: &impl Args) -> io::Result<()> {
|
||||
let hints = retry_hints(&err, args);
|
||||
|
||||
write_failure(w, args.log_format(), &err, &hints)
|
||||
}
|
||||
|
||||
pub fn handle_error(err: anyhow::Error, args: &impl Args) {
|
||||
// Nothing useful to do if stderr itself is gone.
|
||||
let _ = handle_error_to(&mut io::stderr().lock(), err, args);
|
||||
eprintln!("\nError: {:?}", err);
|
||||
|
||||
let Some(err) = err.downcast_ref::<PortalError>() else {
|
||||
return;
|
||||
};
|
||||
|
||||
if err.is_legacy_openssl_error() && !args.fix_openssl() {
|
||||
eprintln!("\nRe-run it with the `--fix-openssl` option to work around this issue, e.g.:\n");
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
eprintln!("{} --fix-openssl {}\n", args[0], args[1..].join(" "));
|
||||
}
|
||||
|
||||
if err.is_tls_error() && !args.ignore_tls_errors() {
|
||||
eprintln!("\nRe-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n");
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
eprintln!("{} --ignore-tls-errors {}\n", args[0], args[1..].join(" "));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -185,129 +79,3 @@ impl ToVerboseArg for Level {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use anyhow::anyhow;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestArgs {
|
||||
fix_openssl: bool,
|
||||
ignore_tls_errors: bool,
|
||||
log_format: LogFormat,
|
||||
}
|
||||
|
||||
impl Args for TestArgs {
|
||||
fn fix_openssl(&self) -> bool {
|
||||
self.fix_openssl
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
|
||||
fn log_format(&self) -> LogFormat {
|
||||
self.log_format
|
||||
}
|
||||
}
|
||||
|
||||
/// The seam that matters: `handle_error` must ask the args which format to
|
||||
/// use. Testing the writer alone would leave a version that always reports as
|
||||
/// prose passing every test.
|
||||
#[test]
|
||||
fn handle_error_honours_the_requested_format() {
|
||||
let args = TestArgs {
|
||||
log_format: LogFormat::Json,
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
|
||||
handle_error_to(&mut out, anyhow!(PortalError::TlsError), &args).expect("writing to a Vec cannot fail");
|
||||
|
||||
let out = String::from_utf8(out).expect("output should be UTF-8");
|
||||
for line in out.lines() {
|
||||
serde_json::from_str::<serde_json::Value>(line).unwrap_or_else(|e| panic!("not JSON: {line:?} ({e})"));
|
||||
}
|
||||
assert!(!out.is_empty(), "the failure must be reported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tls_failure_suggests_ignoring_tls_errors() {
|
||||
let hints = retry_hints(&anyhow!(PortalError::TlsError), &TestArgs::default());
|
||||
|
||||
assert_eq!(hints.len(), 1, "expected one hint, got {hints:?}");
|
||||
assert!(hints[0].contains("--ignore-tls-errors"), "got {:?}", hints[0]);
|
||||
// The command sits on its own line after a blank one, as it always has.
|
||||
assert!(
|
||||
hints[0].contains("e.g.:\n\n"),
|
||||
"blank line before the command: {:?}",
|
||||
hints[0]
|
||||
);
|
||||
}
|
||||
|
||||
/// Suggesting an option the user already passed is noise, and in JSON mode it
|
||||
/// would be an extra record on every failed run.
|
||||
#[test]
|
||||
fn no_hint_when_the_option_is_already_in_use() {
|
||||
let args = TestArgs {
|
||||
ignore_tls_errors: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(retry_hints(&anyhow!(PortalError::TlsError), &args).is_empty());
|
||||
}
|
||||
|
||||
/// Most failures have no known workaround; inventing advice for them would
|
||||
/// mislead.
|
||||
#[test]
|
||||
fn no_hints_for_an_unrelated_error() {
|
||||
let hints = retry_hints(&anyhow!("something else went wrong"), &TestArgs::default());
|
||||
|
||||
assert!(hints.is_empty(), "got {hints:?}");
|
||||
}
|
||||
|
||||
fn failure_output(format: LogFormat) -> String {
|
||||
let hints = vec!["Re-run it with the `--ignore-tls-errors` option".to_string()];
|
||||
let mut out = Vec::new();
|
||||
|
||||
write_failure(&mut out, format, &anyhow!(PortalError::TlsError), &hints).expect("writing to a Vec cannot fail");
|
||||
|
||||
String::from_utf8(out).expect("output should be UTF-8")
|
||||
}
|
||||
|
||||
/// The failure is the program's final report, so in JSON mode it must be one
|
||||
/// more record on the same stream — and it must not be filtered away, which
|
||||
/// is why it does not go through the log macros. A run that fails silently is
|
||||
/// worse than one that fails noisily.
|
||||
#[test]
|
||||
fn the_failure_is_reported_as_records() {
|
||||
let out = failure_output(LogFormat::Json);
|
||||
let lines: Vec<_> = out.lines().collect();
|
||||
assert_eq!(lines.len(), 2, "expected the error and its hint: {out:?}");
|
||||
|
||||
for line in lines {
|
||||
let v: serde_json::Value = serde_json::from_str(line).unwrap_or_else(|e| panic!("not JSON: {line:?} ({e})"));
|
||||
assert_eq!(v["level"], "ERROR");
|
||||
}
|
||||
}
|
||||
|
||||
/// The format has to be honoured, not merely available: reporting the failure
|
||||
/// as prose to a caller that asked for JSON is the defect this whole flag
|
||||
/// exists to remove.
|
||||
#[test]
|
||||
fn the_format_decides_how_the_failure_is_written() {
|
||||
assert!(
|
||||
serde_json::from_str::<serde_json::Value>(failure_output(LogFormat::Json).lines().next().unwrap()).is_ok(),
|
||||
"json mode must not emit prose"
|
||||
);
|
||||
|
||||
let text = failure_output(LogFormat::Text);
|
||||
assert!(text.starts_with("\nError: "), "text mode keeps its shape: {text:?}");
|
||||
assert!(
|
||||
serde_json::from_str::<serde_json::Value>(text.trim()).is_err(),
|
||||
"text mode must not emit JSON: {text:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
//! Neutral device-anchor transport model and deterministic derivation.
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(try_from = "u8", into = "u8")]
|
||||
pub enum AnchorSource {
|
||||
UnixMac,
|
||||
UnixRandom,
|
||||
MacosIokit,
|
||||
}
|
||||
|
||||
impl From<AnchorSource> for u8 {
|
||||
fn from(source: AnchorSource) -> Self {
|
||||
match source {
|
||||
AnchorSource::UnixMac => 1,
|
||||
AnchorSource::UnixRandom => 2,
|
||||
AnchorSource::MacosIokit => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct InvalidAnchorSource(u8);
|
||||
|
||||
impl fmt::Display for InvalidAnchorSource {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "unsupported device anchor source {}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidAnchorSource {}
|
||||
|
||||
impl TryFrom<u8> for AnchorSource {
|
||||
type Error = InvalidAnchorSource;
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
1 => Ok(Self::UnixMac),
|
||||
2 => Ok(Self::UnixRandom),
|
||||
3 => Ok(Self::MacosIokit),
|
||||
value => Err(InvalidAnchorSource(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DeviceAnchor {
|
||||
pub hardware_id: String,
|
||||
pub source: AnchorSource,
|
||||
}
|
||||
|
||||
impl DeviceAnchor {
|
||||
pub fn validate(&self) -> bool {
|
||||
URL_SAFE_NO_PAD
|
||||
.decode(&self.hardware_id)
|
||||
.is_ok_and(|bytes| bytes.len() == 32 && URL_SAFE_NO_PAD.encode(&bytes) == self.hardware_id)
|
||||
}
|
||||
|
||||
pub fn derive(source: AnchorSource, seed: impl AsRef<[u8]>) -> Self {
|
||||
let domain = match source {
|
||||
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
|
||||
AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".as_slice(),
|
||||
AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(),
|
||||
};
|
||||
let mut input = domain.to_vec();
|
||||
input.extend_from_slice(seed.as_ref());
|
||||
Self {
|
||||
hardware_id: URL_SAFE_NO_PAD.encode(openssl::sha::sha256(&input)),
|
||||
source,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hashes_original_seed_order_with_stable_domain_separation() {
|
||||
let mac = DeviceAnchor::derive(AnchorSource::UnixMac, [0, 17, 34, 51, 68, 85]);
|
||||
assert!(mac.validate());
|
||||
assert_eq!(mac.hardware_id, "UWDOx4AVJEuCAYfJBaPioyGtRfAkJBhMYSi8LuFsE1A");
|
||||
assert_ne!(
|
||||
mac.hardware_id,
|
||||
DeviceAnchor::derive(AnchorSource::UnixMac, [85, 68, 51, 34, 17, 0]).hardware_id
|
||||
);
|
||||
assert_ne!(
|
||||
mac.hardware_id,
|
||||
DeviceAnchor::derive(AnchorSource::UnixRandom, [0, 17, 34, 51, 68, 85]).hardware_id
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_uses_stable_numeric_json_codes() {
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::UnixMac).unwrap(), "1");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::UnixRandom).unwrap(), "2");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::MacosIokit).unwrap(), "3");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<AnchorSource>("1").unwrap(),
|
||||
AnchorSource::UnixMac
|
||||
);
|
||||
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>("4").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
net::{SocketAddr, UdpSocket},
|
||||
};
|
||||
use std::{borrow::Cow, net::UdpSocket};
|
||||
|
||||
use anyhow::bail;
|
||||
use log::{debug, info, warn};
|
||||
use reqwest::Client;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use urlencoding::{decode, encode};
|
||||
use xmltree::Element;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::{
|
||||
credential::Credential,
|
||||
@@ -17,238 +12,68 @@ use crate::{
|
||||
gateway::GatewayLoginContext,
|
||||
gp_params::GpParams,
|
||||
params::gateway_login::{self, GatewayLoginInput},
|
||||
session::{
|
||||
GatewayAuthentication,
|
||||
network::GatewayBinding,
|
||||
transport::{bound_client, gateway_origin},
|
||||
},
|
||||
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
|
||||
};
|
||||
|
||||
pub enum GatewayLogin {
|
||||
Authenticated(GatewayAuthentication),
|
||||
Cookie(String),
|
||||
Mfa(String, String),
|
||||
}
|
||||
|
||||
/// Protocol failures cannot be repaired by repeating login with different
|
||||
/// credentials. Issued credentials, when identifiable, are cleaned up first.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Gateway login returned invalid session configuration")]
|
||||
pub struct GatewayLoginProtocolError;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GatewayLoginClient {
|
||||
origin: reqwest::Url,
|
||||
client: Client,
|
||||
params: GpParams,
|
||||
binding: Option<GatewayBinding>,
|
||||
login_endpoint: Option<SocketAddr>,
|
||||
login_url: Option<reqwest::Url>,
|
||||
maintenance_client: Option<Client>,
|
||||
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
|
||||
gateway_login_with_options(gateway, cred, gp_params, None, false).await
|
||||
}
|
||||
|
||||
impl GatewayLoginClient {
|
||||
pub fn register_session(
|
||||
&self,
|
||||
gateway: crate::gateway::Gateway,
|
||||
authentication: GatewayAuthentication,
|
||||
sessions: &mut crate::session::GatewaySessions,
|
||||
) {
|
||||
sessions.register(crate::session::GatewaySession {
|
||||
gateway,
|
||||
transport: self.authenticated_transport(authentication),
|
||||
addresses: self
|
||||
.binding
|
||||
.as_ref()
|
||||
.map(|binding| binding.addresses())
|
||||
.unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
pub fn new(gateway: &str, params: GpParams) -> anyhow::Result<Self> {
|
||||
let origin = reqwest::Url::parse(&normalize_server(gateway)?)?;
|
||||
let client = Client::try_from(¶ms)?;
|
||||
Ok(Self {
|
||||
origin,
|
||||
client,
|
||||
params,
|
||||
binding: None,
|
||||
login_endpoint: None,
|
||||
login_url: None,
|
||||
maintenance_client: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Only called after an authenticated non-tunnel response and registration in
|
||||
/// the caller's cleanup ledger. Tunnel login never inspects physical routing.
|
||||
pub async fn bind_non_tunnel(
|
||||
&mut self,
|
||||
disable_ipv6: bool,
|
||||
detection: Option<&crate::session::network::InternalHostDetection>,
|
||||
cancellation: &tokio_util::sync::CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
let origin = gateway_origin(self.origin.as_str())?;
|
||||
let response_url = self
|
||||
.login_url
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Authenticated response endpoint is unavailable"))?;
|
||||
anyhow::ensure!(
|
||||
response_url.origin() == origin.origin(),
|
||||
"Redirected non-tunnel authentication is unsupported"
|
||||
);
|
||||
let endpoint = self
|
||||
.login_endpoint
|
||||
.ok_or_else(|| anyhow::anyhow!("Non-tunnel authentication has no direct peer address"))?;
|
||||
let network = crate::session::network::PhysicalNetwork::capture_controlled(cancellation).await?;
|
||||
let binding = network
|
||||
.bind_authenticated_endpoint(origin.as_str(), endpoint, disable_ipv6, cancellation)
|
||||
.await?;
|
||||
network
|
||||
.validate_internal_binding(&binding, detection, cancellation)
|
||||
.await?;
|
||||
let client = bound_client(origin.as_str(), &self.params, &binding)?;
|
||||
self.binding = Some(binding);
|
||||
self.maintenance_client = Some(client);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_registered_session(
|
||||
&self,
|
||||
gateway: &crate::gateway::Gateway,
|
||||
authentication: &GatewayAuthentication,
|
||||
sessions: &mut crate::session::GatewaySessions,
|
||||
) {
|
||||
sessions.update(crate::session::GatewaySession {
|
||||
gateway: gateway.clone(),
|
||||
transport: self.authenticated_transport(authentication.clone()),
|
||||
addresses: self
|
||||
.binding
|
||||
.as_ref()
|
||||
.map(|binding| binding.addresses())
|
||||
.unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn authenticated_transport(
|
||||
&self,
|
||||
authentication: GatewayAuthentication,
|
||||
) -> crate::session::transport::GatewayTransport {
|
||||
crate::session::transport::GatewayTransport::from_authenticated_login(
|
||||
self.maintenance_client.as_ref().unwrap_or(&self.client).clone(),
|
||||
self.origin.clone(),
|
||||
authentication,
|
||||
self.params.os_profile().clone(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn binding(&self) -> Option<&GatewayBinding> {
|
||||
self.binding.as_ref()
|
||||
}
|
||||
pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> {
|
||||
self.params.client_identity()
|
||||
}
|
||||
pub(crate) fn request_client(&self) -> &Client {
|
||||
&self.client
|
||||
}
|
||||
pub(crate) fn origin(&self) -> &reqwest::Url {
|
||||
&self.origin
|
||||
}
|
||||
|
||||
pub fn respond_mfa(&mut self, input: &str, otp: &str) {
|
||||
self.params.set_input_str(input);
|
||||
self.params.set_otp(otp);
|
||||
}
|
||||
|
||||
pub async fn login(
|
||||
&mut self,
|
||||
cred: &Credential,
|
||||
context: Option<&GatewayLoginContext>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<GatewayLogin> {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
let client_ip = context.and_then(|context| {
|
||||
context
|
||||
.client_ip()
|
||||
.map(str::to_owned)
|
||||
.or_else(|| detect_local_ipv4(context.host()))
|
||||
});
|
||||
let request = receive_gateway_login(
|
||||
&self.origin,
|
||||
&self.client,
|
||||
cred,
|
||||
&self.params,
|
||||
context,
|
||||
client_ip.as_deref(),
|
||||
false,
|
||||
);
|
||||
let response = tokio::select! {
|
||||
biased;
|
||||
response = request => response?,
|
||||
_ = cancellation.cancelled() => return Err(crate::auth::AuthenticationCancelled.into()),
|
||||
};
|
||||
// Once the full response is available, retain issued authentication or finish
|
||||
// cleanup-only logout before the caller observes cancellation.
|
||||
let response = parse_login_response(response, &self.client, &self.origin, &self.params).await?;
|
||||
self.login_endpoint = response.endpoint;
|
||||
self.login_url = Some(response.url);
|
||||
Ok(response.login)
|
||||
}
|
||||
|
||||
pub(crate) async fn extend_lifetime(&self, cred: &Credential) -> anyhow::Result<GatewayLogin> {
|
||||
let response = receive_gateway_login(&self.origin, &self.client, cred, &self.params, None, None, true).await?;
|
||||
Ok(
|
||||
parse_login_response(response, &self.client, &self.origin, &self.params)
|
||||
.await?
|
||||
.login,
|
||||
)
|
||||
}
|
||||
pub async fn gateway_login_with_context(
|
||||
gateway: &str,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
context: &GatewayLoginContext,
|
||||
) -> anyhow::Result<GatewayLogin> {
|
||||
gateway_login_with_options(gateway, cred, gp_params, Some(context), false).await
|
||||
}
|
||||
|
||||
struct LoginResponse {
|
||||
login: GatewayLogin,
|
||||
endpoint: Option<SocketAddr>,
|
||||
url: reqwest::Url,
|
||||
pub async fn gateway_login_with_extend_lifetime(
|
||||
gateway: &str,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
) -> anyhow::Result<GatewayLogin> {
|
||||
gateway_login_with_options(gateway, cred, gp_params, None, true).await
|
||||
}
|
||||
|
||||
struct ReceivedLogin {
|
||||
body: String,
|
||||
endpoint: Option<SocketAddr>,
|
||||
url: reqwest::Url,
|
||||
}
|
||||
|
||||
fn detect_local_ipv4(host: &str) -> Option<String> {
|
||||
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
|
||||
socket.connect((host, 443)).ok()?;
|
||||
let ip = socket.local_addr().ok()?.ip();
|
||||
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
|
||||
}
|
||||
|
||||
async fn receive_gateway_login(
|
||||
origin: &reqwest::Url,
|
||||
client: &Client,
|
||||
async fn gateway_login_with_options(
|
||||
gateway: &str,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
context: Option<&GatewayLoginContext>,
|
||||
client_ip: Option<&str>,
|
||||
extend_lifetime: bool,
|
||||
) -> anyhow::Result<ReceivedLogin> {
|
||||
let gateway = remove_url_scheme(origin.as_str().trim_end_matches('/'));
|
||||
let login_url = format!("{}/ssl-vpn/login.esp", origin.as_str().trim_end_matches('/'));
|
||||
) -> anyhow::Result<GatewayLogin> {
|
||||
let url = normalize_server(gateway)?;
|
||||
let gateway = remove_url_scheme(&url);
|
||||
|
||||
let login_url = format!("{}/ssl-vpn/login.esp", url);
|
||||
let client = Client::try_from(gp_params)?;
|
||||
|
||||
let client_ip = context.and_then(|context| {
|
||||
context
|
||||
.client_ip()
|
||||
.map(|ip| ip.to_string())
|
||||
.or_else(|| detect_local_ipv4(context.host()))
|
||||
});
|
||||
let request_params = gateway_login::build(&GatewayLoginInput {
|
||||
gp_params,
|
||||
cred,
|
||||
gateway_host: &gateway,
|
||||
context,
|
||||
client_ip,
|
||||
client_ip: client_ip.as_deref(),
|
||||
extend_lifetime,
|
||||
});
|
||||
|
||||
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
|
||||
log_gateway_login_context(context, client_ip, gp_params);
|
||||
log_gateway_login_context(context, client_ip.as_deref(), gp_params);
|
||||
|
||||
let res = client
|
||||
.post(login_url)
|
||||
.post(&login_url)
|
||||
.form(&request_params.body)
|
||||
.send()
|
||||
.await
|
||||
@@ -257,32 +82,11 @@ async fn receive_gateway_login(
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
})?;
|
||||
|
||||
let endpoint = res.remote_addr();
|
||||
let url = res.url().clone();
|
||||
let res = parse_gp_response(res).await.map_err(|err| {
|
||||
warn!("Gateway login response failed: {}", err.reason);
|
||||
warn!("{err}");
|
||||
anyhow::anyhow!("Gateway login error: {}", err.reason)
|
||||
})?;
|
||||
|
||||
Ok(ReceivedLogin {
|
||||
body: res,
|
||||
endpoint,
|
||||
url,
|
||||
})
|
||||
}
|
||||
|
||||
async fn parse_login_response(
|
||||
response: ReceivedLogin,
|
||||
client: &Client,
|
||||
origin: &reqwest::Url,
|
||||
gp_params: &GpParams,
|
||||
) -> anyhow::Result<LoginResponse> {
|
||||
let ReceivedLogin {
|
||||
body: res,
|
||||
endpoint,
|
||||
url,
|
||||
} = response;
|
||||
|
||||
// It's possible to get an empty response, log the response headers for debugging
|
||||
if res.trim().is_empty() {
|
||||
info!("Empty gateway login response headers: {:?}", res);
|
||||
@@ -292,47 +96,27 @@ async fn parse_login_response(
|
||||
// MFA detected
|
||||
if res.contains("Challenge") {
|
||||
let Some((message, input_str)) = parse_mfa(&res) else {
|
||||
bail!("Failed to parse MFA challenge");
|
||||
bail!("Failed to parse MFA challenge: {res}");
|
||||
};
|
||||
|
||||
return Ok(LoginResponse {
|
||||
login: GatewayLogin::Mfa(message, input_str),
|
||||
endpoint,
|
||||
url,
|
||||
});
|
||||
return Ok(GatewayLogin::Mfa(message, input_str));
|
||||
}
|
||||
|
||||
let lower = res.to_ascii_lowercase();
|
||||
if lower.contains("<!doctype") || lower.contains("<!entity") {
|
||||
return Err(GatewayLoginProtocolError.into());
|
||||
}
|
||||
let root = Element::parse(res.as_bytes()).map_err(|_| GatewayLoginProtocolError)?;
|
||||
let (cookie, connection_type) =
|
||||
parse_issued_authentication(&root, gp_params.computer()).map_err(|_| GatewayLoginProtocolError)?;
|
||||
let cookie = Zeroizing::new(cookie);
|
||||
let authentication = connection_type.and_then(|mode| GatewayAuthentication::new(cookie.to_string(), mode));
|
||||
let authentication = match authentication {
|
||||
Ok(authentication) => authentication,
|
||||
Err(_) => {
|
||||
match tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
crate::session::transport::logout_cookie(client, origin, &cookie, gp_params.os_profile()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => warn!("Cleanup-only gateway logout failed: {error}"),
|
||||
Err(_) => warn!("Cleanup-only gateway logout timed out"),
|
||||
}
|
||||
return Err(GatewayLoginProtocolError.into());
|
||||
}
|
||||
};
|
||||
debug!("Gateway login succeeded, mode: {:?}", authentication.mode());
|
||||
Ok(LoginResponse {
|
||||
login: GatewayLogin::Authenticated(authentication),
|
||||
endpoint,
|
||||
url,
|
||||
})
|
||||
debug!("Gateway login response: {}", res);
|
||||
|
||||
let root = Element::parse(res.as_bytes())?;
|
||||
|
||||
let cookie = build_gateway_token(&root, gp_params.computer())?;
|
||||
|
||||
Ok(GatewayLogin::Cookie(cookie))
|
||||
}
|
||||
|
||||
fn detect_local_ipv4(host: &str) -> Option<String> {
|
||||
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
|
||||
socket.connect((host, 443)).ok()?;
|
||||
let ip = socket.local_addr().ok()?.ip();
|
||||
|
||||
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
|
||||
}
|
||||
|
||||
fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>, gp_params: &GpParams) {
|
||||
@@ -352,33 +136,13 @@ fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: O
|
||||
);
|
||||
}
|
||||
|
||||
fn parse_issued_authentication(element: &Element, computer: &str) -> anyhow::Result<(String, anyhow::Result<String>)> {
|
||||
anyhow::ensure!(element.name == "jnlp", "Gateway login response is not JNLP");
|
||||
anyhow::ensure!(
|
||||
element.attr("status").is_none_or(|status| status == "success"),
|
||||
"Gateway login response rejected authentication"
|
||||
);
|
||||
let application = element
|
||||
.child("application-desc")
|
||||
.ok_or_else(|| anyhow::anyhow!("Gateway login response has no application description"))?;
|
||||
let args = application
|
||||
.children("argument")
|
||||
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
|
||||
let args = element
|
||||
.descendants("argument")
|
||||
.iter()
|
||||
.map(|e| e.get_text().unwrap_or_default())
|
||||
.collect::<Vec<_>>();
|
||||
let cookie = build_gateway_token(&args, computer)?;
|
||||
let connection_type = read_arg_value(&args, 12)
|
||||
.and_then(|mode| mode.ok_or_else(|| anyhow::anyhow!("Gateway login response has no connection type")));
|
||||
Ok((cookie, connection_type))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn parse_gateway_authentication(element: &Element, computer: &str) -> anyhow::Result<GatewayAuthentication> {
|
||||
let (cookie, mode) = parse_issued_authentication(element, computer)?;
|
||||
GatewayAuthentication::new(cookie, mode?)
|
||||
}
|
||||
|
||||
fn build_gateway_token(args: &[Cow<'_, str>], computer: &str) -> anyhow::Result<String> {
|
||||
let mut params = vec![
|
||||
read_required_arg(&args, 1, "authcookie")?,
|
||||
read_optional_arg(&args, 2, "persistent-cookie")?,
|
||||
@@ -434,15 +198,11 @@ fn read_arg_value(args: &[Cow<'_, str>], index: usize) -> anyhow::Result<Option<
|
||||
}
|
||||
|
||||
fn normalize_arg_value(value: &str) -> anyhow::Result<Option<String>> {
|
||||
let value = decode(value)?;
|
||||
if value.is_empty() || value == "(null)" || value == "-1" {
|
||||
return Ok(None);
|
||||
}
|
||||
anyhow::ensure!(
|
||||
!value.chars().any(char::is_control),
|
||||
"Gateway argument contains control characters"
|
||||
);
|
||||
Ok(Some(value.into_owned()))
|
||||
|
||||
Ok(Some(decode(value)?.into_owned()))
|
||||
}
|
||||
|
||||
fn parse_mfa(res: &str) -> Option<(String, String)> {
|
||||
@@ -463,268 +223,6 @@ fn parse_mfa(res: &str) -> Option<(String, String)> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tunnel_response() -> String {
|
||||
let root = login_response(Some("tunnel"), "issued-cookie");
|
||||
let mut xml = Vec::new();
|
||||
root.write(&mut xml).unwrap();
|
||||
crate::session::transport::tests::response(std::str::from_utf8(&xml).unwrap())
|
||||
}
|
||||
|
||||
fn test_params() -> GpParams {
|
||||
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_login_cancels_stalled_headers_and_body() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
for partial_response in ["", "HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n<jnlp>"] {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let (ready, received) = tokio::sync::oneshot::channel();
|
||||
let (release, released) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut buffer = [0; 4096];
|
||||
assert!(socket.read(&mut buffer).await.unwrap() > 0);
|
||||
socket.write_all(partial_response.as_bytes()).await.unwrap();
|
||||
ready.send(()).unwrap();
|
||||
released.await.unwrap();
|
||||
});
|
||||
let cancellation = CancellationToken::new();
|
||||
let token = cancellation.clone();
|
||||
let login = tokio::spawn(async move {
|
||||
let mut client = GatewayLoginClient::new(&origin, test_params()).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
client.login(&credential, None, &token).await
|
||||
});
|
||||
received.await.unwrap();
|
||||
cancellation.cancel();
|
||||
let result = tokio::time::timeout(std::time::Duration::from_secs(1), login)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(result.err().unwrap().is::<crate::auth::AuthenticationCancelled>());
|
||||
release.send(()).unwrap();
|
||||
server.await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_during_cleanup_only_logout_awaits_cleanup() {
|
||||
use crate::session::transport::tests::response;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let mut xml = Vec::new();
|
||||
login_response(None, "issued-cookie").write(&mut xml).unwrap();
|
||||
let login_response = response(std::str::from_utf8(&xml).unwrap());
|
||||
let (ready, received) = tokio::sync::oneshot::channel();
|
||||
let (release, released) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut buffer = [0; 4096];
|
||||
assert!(socket.read(&mut buffer).await.unwrap() > 0);
|
||||
socket.write_all(login_response.as_bytes()).await.unwrap();
|
||||
drop(socket);
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let read = socket.read(&mut buffer).await.unwrap();
|
||||
assert!(
|
||||
std::str::from_utf8(&buffer[..read])
|
||||
.unwrap()
|
||||
.contains("/ssl-vpn/logout.esp")
|
||||
);
|
||||
ready.send(()).unwrap();
|
||||
released.await.unwrap();
|
||||
socket
|
||||
.write_all(response("<response status='success'/>").as_bytes())
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
let cancellation = CancellationToken::new();
|
||||
let token = cancellation.clone();
|
||||
let mut login = tokio::spawn(async move {
|
||||
let mut client = GatewayLoginClient::new(&origin, test_params()).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
client.login(&credential, None, &token).await
|
||||
});
|
||||
received.await.unwrap();
|
||||
cancellation.cancel();
|
||||
assert!(
|
||||
tokio::time::timeout(std::time::Duration::from_millis(20), &mut login)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
release.send(()).unwrap();
|
||||
assert!(login.await.unwrap().err().unwrap().is::<GatewayLoginProtocolError>());
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_tunnel_login_follows_redirects_without_physical_binding() {
|
||||
let (_, origin, server) = crate::session::transport::tests::login_gateway(vec![
|
||||
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected-login\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
tunnel_response(),
|
||||
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected-login\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
tunnel_response(),
|
||||
]).await;
|
||||
let mut client = GatewayLoginClient::new(origin.as_str(), test_params()).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
assert!(
|
||||
matches!(client.login(&credential, None, &CancellationToken::new()).await.unwrap(), GatewayLogin::Authenticated(authentication) if authentication.mode() == crate::session::SessionMode::Tunnel)
|
||||
);
|
||||
assert!(client.binding().is_none());
|
||||
assert!(matches!(
|
||||
client.extend_lifetime(&credential).await.unwrap(),
|
||||
GatewayLogin::Authenticated(_)
|
||||
));
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(requests[0].0, "/ssl-vpn/login.esp");
|
||||
assert_eq!(requests[1].0, "/redirected-login");
|
||||
assert_eq!(requests[3].0, "/redirected-login");
|
||||
assert!(requests[3].1.contains("extend-lifetime=true"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_login_keeps_reqwest_address_fallback() {
|
||||
let (_, origin, server) = crate::session::transport::tests::login_gateway(vec![tunnel_response()]).await;
|
||||
let port = origin.port().unwrap();
|
||||
let params = test_params();
|
||||
let mut client = GatewayLoginClient::new(&format!("http://gateway.invalid:{port}"), params.clone()).unwrap();
|
||||
// Supply deterministic DNS candidates; all other client behavior is the
|
||||
// ordinary request path. The first address refuses, the second is reachable.
|
||||
client.client = params
|
||||
.client_builder()
|
||||
.unwrap()
|
||||
.no_proxy()
|
||||
.resolve_to_addrs(
|
||||
"gateway.invalid",
|
||||
&[
|
||||
SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, port)),
|
||||
SocketAddr::from(([127, 0, 0, 1], port)),
|
||||
],
|
||||
)
|
||||
.build()
|
||||
.unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
assert!(matches!(
|
||||
client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap(),
|
||||
GatewayLogin::Authenticated(_)
|
||||
));
|
||||
assert!(client.binding().is_none());
|
||||
assert_eq!(server.await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_tunnel_login_can_use_a_proxy_without_local_gateway_resolution() {
|
||||
let (_, proxy, server) = crate::session::transport::tests::login_gateway(vec![tunnel_response()]).await;
|
||||
let params = test_params();
|
||||
let mut client = GatewayLoginClient::new("http://unresolvable.invalid", params.clone()).unwrap();
|
||||
client.client = params
|
||||
.client_builder()
|
||||
.unwrap()
|
||||
.proxy(reqwest::Proxy::all(proxy.as_str()).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
assert!(matches!(
|
||||
client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap(),
|
||||
GatewayLogin::Authenticated(_)
|
||||
));
|
||||
assert!(client.binding().is_none());
|
||||
assert_eq!(
|
||||
server.await.unwrap()[0].0,
|
||||
"http://unresolvable.invalid/ssl-vpn/login.esp"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_mode_logs_out_issued_cookie_before_returning_protocol_error() {
|
||||
use crate::session::transport::tests::{login_gateway, response};
|
||||
let root = login_response(None, "issued-cookie");
|
||||
let mut xml = Vec::new();
|
||||
root.write(&mut xml).unwrap();
|
||||
let (client, origin, server) = login_gateway(vec![
|
||||
response(std::str::from_utf8(&xml).unwrap()),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let params =
|
||||
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
let mut client = GatewayLoginClient {
|
||||
client,
|
||||
..GatewayLoginClient::new(origin.as_str(), params).unwrap()
|
||||
};
|
||||
let error = client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.is::<GatewayLoginProtocolError>());
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_eq!(requests[0].0, "/ssl-vpn/login.esp");
|
||||
assert_eq!(requests[1].0, "/ssl-vpn/logout.esp");
|
||||
let form: std::collections::HashMap<String, String> = serde_urlencoded::from_str(&requests[1].1).unwrap();
|
||||
assert_eq!(form.get("authcookie").map(String::as_str), Some("issued-cookie"));
|
||||
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_only_parsing_does_not_salvage_server_error_authentication() {
|
||||
let mut root = login_response(None, "issued-cookie");
|
||||
root.attributes.insert("status".into(), "error".into());
|
||||
assert!(parse_issued_authentication(&root, "computer").is_err());
|
||||
for encoded in ["%28null%29", "%2D1", "%00"] {
|
||||
assert!(parse_issued_authentication(&login_response(Some("tunnel"), encoded), "computer").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn login_response(mode: Option<&str>, cookie: &str) -> Element {
|
||||
let mut args = vec![""; 19];
|
||||
args[1] = cookie;
|
||||
args[4] = "alice";
|
||||
if let Some(mode) = mode {
|
||||
args[12] = mode;
|
||||
}
|
||||
let arguments = args
|
||||
.iter()
|
||||
.map(|value| format!("<argument>{value}</argument>"))
|
||||
.collect::<String>();
|
||||
Element::parse(format!("<jnlp><application-desc>{arguments}</application-desc></jnlp>").as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_mode_is_independent_of_network_location() {
|
||||
for (value, mode) in [
|
||||
("tunnel", crate::session::SessionMode::Tunnel),
|
||||
("non-tunnel", crate::session::SessionMode::NonTunnel),
|
||||
("internal", crate::session::SessionMode::NonTunnel),
|
||||
] {
|
||||
let authentication =
|
||||
parse_gateway_authentication(&login_response(Some(value), "test-cookie"), "computer").unwrap();
|
||||
assert_eq!(authentication.mode(), mode);
|
||||
assert_eq!(authentication.connection_type(), value);
|
||||
assert!(!format!("{authentication:?}").contains("test-cookie"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_rejects_missing_mode_or_cookie() {
|
||||
for mode in [None, Some(""), Some("(null)"), Some("-1"), Some(" ")] {
|
||||
assert!(parse_gateway_authentication(&login_response(mode, "test-cookie"), "computer").is_err());
|
||||
}
|
||||
assert!(parse_gateway_authentication(&login_response(Some("tunnel"), ""), "computer").is_err());
|
||||
let response = Element::parse(b"<response status='error'/>".as_slice()).unwrap();
|
||||
assert!(parse_gateway_authentication(&response, "computer").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mfa() {
|
||||
let res = r#"var respStatus = "Challenge";
|
||||
@@ -765,9 +263,7 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
|
||||
"#;
|
||||
|
||||
let root = Element::parse(res.as_bytes()).unwrap();
|
||||
let authentication = parse_gateway_authentication(&root, "metalklesk").unwrap();
|
||||
let token = authentication.cookie();
|
||||
assert_eq!(authentication.mode(), crate::session::SessionMode::Tunnel);
|
||||
let token = build_gateway_token(&root, "metalklesk").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
token,
|
||||
@@ -804,8 +300,7 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
|
||||
"#;
|
||||
|
||||
let root = Element::parse(res.as_bytes()).unwrap();
|
||||
let authentication = parse_gateway_authentication(&root, "metalklesk").unwrap();
|
||||
let token = authentication.cookie();
|
||||
let token = build_gateway_token(&root, "metalklesk").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
token,
|
||||
|
||||
@@ -118,7 +118,7 @@ impl GatewayLoginContext {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> GatewayKind {
|
||||
pub(crate) fn kind(&self) -> GatewayKind {
|
||||
self.kind
|
||||
}
|
||||
|
||||
|
||||
@@ -5,13 +5,15 @@ use std::{
|
||||
|
||||
use anyhow::bail;
|
||||
use log::{info, warn};
|
||||
use reqwest::Client;
|
||||
use xmltree::Element;
|
||||
|
||||
use crate::{
|
||||
credential::Credential,
|
||||
gateway::login::{GatewayLogin, GatewayLoginClient},
|
||||
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
|
||||
gp_params::GpParams,
|
||||
session::SessionRequestArgs,
|
||||
utils::{parse_gp_response, xml::ElementExt},
|
||||
utils::{normalize_server, parse_gp_response, request::create_identity, xml::ElementExt},
|
||||
};
|
||||
|
||||
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
|
||||
@@ -20,18 +22,12 @@ const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
|
||||
#[derive(Clone)]
|
||||
pub struct SessionExtensionAuth {
|
||||
credential: Credential,
|
||||
client: GatewayLoginClient,
|
||||
gp_params: GpParams,
|
||||
}
|
||||
|
||||
impl SessionExtensionAuth {
|
||||
pub fn new(credential: Credential, client: GatewayLoginClient) -> Self {
|
||||
Self { credential, client }
|
||||
}
|
||||
pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> {
|
||||
self.client.client_identity()
|
||||
}
|
||||
pub fn binding(&self) -> Option<&crate::session::network::GatewayBinding> {
|
||||
self.client.binding()
|
||||
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
|
||||
Self { credential, gp_params }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +35,7 @@ impl std::fmt::Debug for SessionExtensionAuth {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("SessionExtensionAuth")
|
||||
.field("username", &self.credential.username())
|
||||
.field("client", &"<redacted>")
|
||||
.field("gp_params", &"<redacted>")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
@@ -87,15 +83,10 @@ impl SessionContext {
|
||||
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
|
||||
extend_session_lifetime(ctx).await?;
|
||||
|
||||
let auth = ctx
|
||||
.extension_auth()
|
||||
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
|
||||
let client = auth.client.request_client();
|
||||
let url = format!(
|
||||
"{}/ssl-vpn/agentmessage.esp",
|
||||
auth.client.origin().as_str().trim_end_matches('/')
|
||||
);
|
||||
let base_url = normalize_server(ctx.server())?;
|
||||
let client = build_session_client(ctx.session_args())?;
|
||||
let form = build_extend_session_form(ctx)?;
|
||||
let url = format!("{base_url}/ssl-vpn/agentmessage.esp");
|
||||
|
||||
info!("Sending extend-session request");
|
||||
|
||||
@@ -117,17 +108,33 @@ async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
|
||||
.extension_auth()
|
||||
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
|
||||
|
||||
let login = auth.client.extend_lifetime(&auth.credential).await?;
|
||||
let login = gateway_login_with_extend_lifetime(ctx.server(), &auth.credential, &auth.gp_params).await?;
|
||||
validate_extension_login(login)
|
||||
}
|
||||
|
||||
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
|
||||
match login {
|
||||
GatewayLogin::Authenticated(_) => Ok(()),
|
||||
GatewayLogin::Cookie(_) => Ok(()),
|
||||
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
|
||||
let mut builder = Client::builder();
|
||||
|
||||
if let Some(user_agent) = args.user_agent() {
|
||||
builder = builder.user_agent(user_agent);
|
||||
}
|
||||
|
||||
if let Some(cert) = args.certificate() {
|
||||
info!("Using client certificate authentication...");
|
||||
let identity = create_identity(&cert, args.sslkey().as_deref(), args.key_password().as_deref())?;
|
||||
builder = builder.identity(identity);
|
||||
}
|
||||
|
||||
Ok(builder.build()?)
|
||||
}
|
||||
|
||||
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
|
||||
Ok(serde_urlencoded::from_str(args.cookie())?)
|
||||
}
|
||||
|
||||
+14
-109
@@ -1,12 +1,11 @@
|
||||
use log::info;
|
||||
use reqwest::{Client, ClientBuilder};
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::{
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile},
|
||||
utils::request::{ClientIdentity, create_identity},
|
||||
utils::request::create_identity,
|
||||
};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
|
||||
@@ -44,7 +43,6 @@ pub struct GpParams {
|
||||
certificate: Option<String>,
|
||||
sslkey: Option<String>,
|
||||
key_password: Option<String>,
|
||||
prepared_identity: Option<ClientIdentity>,
|
||||
// Feature
|
||||
csc_mode: CscMode,
|
||||
// Per-request state
|
||||
@@ -137,49 +135,9 @@ impl GpParams {
|
||||
pub(crate) fn otp(&self) -> Option<&str> {
|
||||
self.otp.as_deref()
|
||||
}
|
||||
|
||||
pub fn prepare_client_identity(&mut self) -> anyhow::Result<()> {
|
||||
if self.prepared_identity.is_none() {
|
||||
if let Some(certificate) = self.certificate.as_deref() {
|
||||
self.prepared_identity = Some(ClientIdentity::load(
|
||||
certificate,
|
||||
self.sslkey.as_deref(),
|
||||
self.key_password.as_deref(),
|
||||
)?);
|
||||
}
|
||||
}
|
||||
self.certificate = None;
|
||||
self.sslkey = None;
|
||||
if let Some(mut passphrase) = self.key_password.take() {
|
||||
passphrase.zeroize();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn client_identity(&self) -> Option<&ClientIdentity> {
|
||||
self.prepared_identity.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
|
||||
let mut builder = Client::builder()
|
||||
.danger_accept_invalid_certs(self.ignore_tls_errors)
|
||||
.user_agent(self.user_agent());
|
||||
if let Some(identity) = &self.prepared_identity {
|
||||
builder = builder.identity(identity.request_identity());
|
||||
} else if let Some(cert) = self.certificate.as_deref() {
|
||||
info!("Using client certificate authentication...");
|
||||
builder = builder.identity(create_identity(
|
||||
cert,
|
||||
self.sslkey.as_deref(),
|
||||
self.key_password.as_deref(),
|
||||
)?);
|
||||
}
|
||||
Ok(builder)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GpParamsBuilder {
|
||||
prepared_identity: Option<ClientIdentity>,
|
||||
is_gateway: bool,
|
||||
os_profile: OsProfile,
|
||||
csc_mode: CscMode,
|
||||
@@ -192,7 +150,6 @@ pub struct GpParamsBuilder {
|
||||
impl GpParamsBuilder {
|
||||
pub fn new(os_profile: OsProfile) -> Self {
|
||||
Self {
|
||||
prepared_identity: None,
|
||||
is_gateway: false,
|
||||
os_profile,
|
||||
csc_mode: Default::default(),
|
||||
@@ -219,34 +176,22 @@ impl GpParamsBuilder {
|
||||
}
|
||||
|
||||
pub fn certificate<T: Into<Option<String>>>(&mut self, certificate: T) -> &mut Self {
|
||||
self.prepared_identity = None;
|
||||
self.certificate = certificate.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn sslkey<T: Into<Option<String>>>(&mut self, sslkey: T) -> &mut Self {
|
||||
self.prepared_identity = None;
|
||||
self.sslkey = sslkey.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn key_password<T: Into<Option<String>>>(&mut self, password: T) -> &mut Self {
|
||||
self.prepared_identity = None;
|
||||
self.key_password = password.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn client_identity(&mut self, identity: Option<ClientIdentity>) -> &mut Self {
|
||||
self.prepared_identity = identity;
|
||||
self.certificate = None;
|
||||
self.sslkey = None;
|
||||
self.key_password = None;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build(&self) -> GpParams {
|
||||
GpParams {
|
||||
prepared_identity: self.prepared_identity.clone(),
|
||||
os_profile: self.os_profile.clone(),
|
||||
ignore_tls_errors: self.ignore_tls_errors,
|
||||
certificate: self.certificate.clone(),
|
||||
@@ -264,64 +209,24 @@ impl TryFrom<&GpParams> for Client {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(value: &GpParams) -> Result<Self, Self::Error> {
|
||||
Ok(value.client_builder()?.build()?)
|
||||
let mut builder = Client::builder()
|
||||
.danger_accept_invalid_certs(value.ignore_tls_errors)
|
||||
.user_agent(value.user_agent());
|
||||
|
||||
if let Some(cert) = value.certificate.as_deref() {
|
||||
info!("Using client certificate authentication...");
|
||||
let identity = create_identity(cert, value.sslkey.as_deref(), value.key_password.as_deref())?;
|
||||
builder = builder.identity(identity);
|
||||
}
|
||||
|
||||
let client = builder.build()?;
|
||||
Ok(client)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn path_identity_settings_replace_a_prepared_snapshot() {
|
||||
let identity = ClientIdentity::load("tests/files/badssl.com-client.pem", None, Some("badssl.com")).unwrap();
|
||||
let setters: [fn(&mut GpParamsBuilder); 3] = [
|
||||
|builder| {
|
||||
builder.certificate(Some("missing-replacement-certificate.pem".into()));
|
||||
},
|
||||
|builder| {
|
||||
builder.sslkey(Some("replacement-key.pem".into()));
|
||||
},
|
||||
|builder| {
|
||||
builder.key_password(Some("replacement-password".into()));
|
||||
},
|
||||
];
|
||||
for setter in setters {
|
||||
let mut builder = GpParams::builder(profile(ClientOs::Linux));
|
||||
builder.client_identity(Some(identity.clone()));
|
||||
setter(&mut builder);
|
||||
let params = builder.build();
|
||||
assert!(
|
||||
params.client_identity().is_none(),
|
||||
"Path settings must not silently use the previous identity"
|
||||
);
|
||||
if params.certificate.is_some() {
|
||||
assert!(
|
||||
Client::try_from(¶ms).is_err(),
|
||||
"The replacement certificate path must actually be loaded"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepared_identity_replaces_paths_and_can_be_explicitly_disabled() {
|
||||
let identity = ClientIdentity::load("tests/files/badssl.com-client.pem", None, Some("badssl.com")).unwrap();
|
||||
let mut builder = GpParams::builder(profile(ClientOs::Linux));
|
||||
builder
|
||||
.certificate(Some("missing-certificate.pem".into()))
|
||||
.sslkey(Some("missing-key.pem".into()))
|
||||
.key_password(Some("unused-password".into()))
|
||||
.client_identity(Some(identity));
|
||||
let params = builder.build();
|
||||
assert!(params.client_identity().is_some());
|
||||
assert!(params.certificate.is_none() && params.sslkey.is_none() && params.key_password.is_none());
|
||||
assert!(Client::try_from(¶ms).is_ok());
|
||||
builder.certificate(None);
|
||||
let params = builder.build();
|
||||
assert!(params.client_identity().is_none());
|
||||
assert!(params.certificate.is_none());
|
||||
}
|
||||
use crate::os_profile::runtime_client_os;
|
||||
|
||||
fn profile(client_os: ClientOs) -> OsProfile {
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// The GUI's choice of HIP report source. gpservice resolves execution details.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, Type, PartialEq, Eq)]
|
||||
#[serde(tag = "source", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum HipSource {
|
||||
#[default]
|
||||
Disabled,
|
||||
Generated,
|
||||
Edited {
|
||||
report_id: String,
|
||||
},
|
||||
UserScript {
|
||||
path: String,
|
||||
},
|
||||
ApprovedRootScript {
|
||||
approval_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Type, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum HipApprovalStatus {
|
||||
Valid,
|
||||
Revoked,
|
||||
Corrupt,
|
||||
OtherUser,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn source_round_trips_without_execution_uid_or_wrapper() {
|
||||
let source = HipSource::ApprovedRootScript {
|
||||
approval_id: "approved-1".into(),
|
||||
};
|
||||
let json = serde_json::to_value(&source).unwrap();
|
||||
assert_eq!(
|
||||
json,
|
||||
serde_json::json!({ "source": "approvedRootScript", "approvalId": "approved-1" })
|
||||
);
|
||||
assert_eq!(serde_json::from_value::<HipSource>(json).unwrap(), source);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,9 @@
|
||||
pub mod auth;
|
||||
pub mod cookie_store;
|
||||
pub mod credential;
|
||||
pub mod device_anchor;
|
||||
pub mod error;
|
||||
pub mod gateway;
|
||||
pub mod gp_params;
|
||||
pub mod hip;
|
||||
pub mod log_format;
|
||||
pub mod os_profile;
|
||||
pub mod params;
|
||||
pub mod portal;
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
//! Machine-readable log output.
|
||||
//!
|
||||
//! The default human format is fine at a terminal, but tools that drive
|
||||
//! gpclient headless have to parse it — and end up matching on prose, including
|
||||
//! text that comes from dependencies rather than from this project. JSON lines
|
||||
//! give those callers fields instead.
|
||||
//!
|
||||
//! This module deliberately depends only on `log` and `serde_json`, so every
|
||||
//! binary can use it without pulling in a logging backend, and so the rendering
|
||||
//! can be tested without installing a global logger.
|
||||
|
||||
use std::io::{self, Write};
|
||||
|
||||
use chrono::{SecondsFormat, Utc};
|
||||
use serde_json::json;
|
||||
|
||||
/// How log records are rendered.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
|
||||
pub enum LogFormat {
|
||||
/// The human-readable default.
|
||||
#[default]
|
||||
Text,
|
||||
/// One JSON object per line.
|
||||
Json,
|
||||
}
|
||||
|
||||
impl LogFormat {
|
||||
/// The name this format is known by on a command line.
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Text => "text",
|
||||
Self::Json => "json",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a [`log::Record`] to `w` as one JSON line, newline included.
|
||||
///
|
||||
/// This is the form a logging backend needs, and it writes into the buffer the
|
||||
/// backend already handed us rather than allocating a line to be copied. It
|
||||
/// takes a `Record` and a `Write` rather than any backend's own types, so `log`
|
||||
/// stays the only logging dependency here — with `env_logger`, this function
|
||||
/// *is* the format callback:
|
||||
///
|
||||
/// ```ignore
|
||||
/// // Not compiled as a doctest: env_logger is an optional dependency of this
|
||||
/// // crate, so it is not linked when the docs are built.
|
||||
/// env_logger::builder().format(write_json_record).init();
|
||||
/// ```
|
||||
pub fn write_json_record<W: Write>(w: &mut W, record: &log::Record) -> io::Result<()> {
|
||||
writeln!(
|
||||
w,
|
||||
"{}",
|
||||
json!({
|
||||
"timestamp": Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true),
|
||||
"level": record.level().as_str(),
|
||||
"target": record.target(),
|
||||
"message": record.args().to_string(),
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::{DateTime, SubsecRound};
|
||||
use log::Level;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn parse(line: &str) -> serde_json::Value {
|
||||
serde_json::from_str(line).expect("each line must be valid JSON")
|
||||
}
|
||||
|
||||
fn write_record(record: &log::Record) -> String {
|
||||
let mut buf = Vec::new();
|
||||
write_json_record(&mut buf, record).expect("writing to a Vec cannot fail");
|
||||
String::from_utf8(buf).expect("output should be UTF-8")
|
||||
}
|
||||
|
||||
/// The fields a consumer is promised, taken off a `Record` as a backend
|
||||
/// hands it over.
|
||||
#[test]
|
||||
fn record_renders_the_expected_fields() {
|
||||
// Built inline: `format_args!` borrows its arguments for the statement it
|
||||
// appears in, so a `Record` held in a `let` would outlive them.
|
||||
let v = parse(&write_record(
|
||||
&log::Record::builder()
|
||||
.level(Level::Error)
|
||||
.target("gpclient::connect")
|
||||
.args(format_args!("portal {} unreachable", "vpn.example.com"))
|
||||
.build(),
|
||||
));
|
||||
|
||||
assert_eq!(v["level"], "ERROR");
|
||||
assert_eq!(v["target"], "gpclient::connect");
|
||||
assert_eq!(v["message"], "portal vpn.example.com unreachable");
|
||||
}
|
||||
|
||||
/// Without a timestamp the JSON output would be strictly less informative
|
||||
/// than the text format it replaces, and a consumer could not order or
|
||||
/// correlate events.
|
||||
#[test]
|
||||
fn records_carry_a_utc_timestamp() {
|
||||
let before = Utc::now();
|
||||
let v = parse(&write_record(
|
||||
&log::Record::builder()
|
||||
.level(Level::Info)
|
||||
.target("t")
|
||||
.args(format_args!("connected"))
|
||||
.build(),
|
||||
));
|
||||
let after = Utc::now();
|
||||
|
||||
let ts = v["timestamp"].as_str().expect("timestamp must be a string");
|
||||
let parsed = DateTime::parse_from_rfc3339(ts)
|
||||
.unwrap_or_else(|e| panic!("timestamp must be RFC 3339: {ts:?} ({e})"))
|
||||
.with_timezone(&Utc);
|
||||
|
||||
assert!(ts.ends_with('Z'), "timestamp must be UTC, got {ts:?}");
|
||||
assert!(
|
||||
parsed >= before.trunc_subsecs(3) && parsed <= after,
|
||||
"timestamp {parsed} should be between {before} and {after}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The backend appends records to one stream, so each has to terminate its
|
||||
/// own line — exactly one, or the next record joins this one. A message
|
||||
/// containing a newline must be escaped into the JSON string rather than
|
||||
/// splitting the record in two.
|
||||
#[test]
|
||||
fn record_ends_with_a_single_newline() {
|
||||
let out = write_record(
|
||||
&log::Record::builder()
|
||||
.level(Level::Info)
|
||||
.target("t")
|
||||
.args(format_args!("first\nsecond"))
|
||||
.build(),
|
||||
);
|
||||
|
||||
assert!(out.ends_with('\n'), "record must terminate its line: {out:?}");
|
||||
assert_eq!(out.matches('\n').count(), 1, "record must be one line: {out:?}");
|
||||
assert_eq!(parse(&out)["message"], "first\nsecond", "the newline must survive");
|
||||
}
|
||||
|
||||
/// `as_str` is what gets passed to a child process on the command line, and
|
||||
/// clap parses that with the names from its own `ValueEnum` derive. If the
|
||||
/// two ever disagree, gpclient hands gpauth a value gpauth rejects.
|
||||
#[cfg(feature = "clap")]
|
||||
#[test]
|
||||
fn as_str_agrees_with_the_names_clap_parses() {
|
||||
use clap::ValueEnum;
|
||||
|
||||
for format in [LogFormat::Text, LogFormat::Json] {
|
||||
let clap_name = format
|
||||
.to_possible_value()
|
||||
.expect("every variant is selectable")
|
||||
.get_name()
|
||||
.to_owned();
|
||||
|
||||
assert_eq!(format.as_str(), clap_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,17 +4,15 @@ use anyhow::bail;
|
||||
use log::{Level, Log, warn};
|
||||
use log_reload::{ReloadHandle, ReloadLog};
|
||||
|
||||
use crate::log_format::{LogFormat, write_json_record};
|
||||
|
||||
pub const LOG_BACKEND_ENV: &str = "GP_LOG_BACKEND";
|
||||
pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified";
|
||||
|
||||
type BoxedLogger = Box<dyn Log + Send + Sync>;
|
||||
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = OnceLock::new();
|
||||
|
||||
pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat) {
|
||||
pub fn init(level: Level, subsystem: &str, category: &str) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if log_format == LogFormat::Text && macos_unified_log_enabled() {
|
||||
if macos_unified_log_enabled() {
|
||||
init_with_logger(level, MacosLogger::new(subsystem, category));
|
||||
return;
|
||||
}
|
||||
@@ -22,19 +20,10 @@ pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = (subsystem, category);
|
||||
|
||||
init_with_logger(level, build_env_logger(log_format).build());
|
||||
}
|
||||
|
||||
fn build_env_logger(log_format: LogFormat) -> env_logger::Builder {
|
||||
let mut builder = env_logger::builder();
|
||||
// The outer reloadable logger owns filtering.
|
||||
builder.filter_level(log::LevelFilter::Trace);
|
||||
|
||||
if log_format == LogFormat::Json {
|
||||
builder.format(write_json_record);
|
||||
}
|
||||
|
||||
builder
|
||||
// Initialize the env_logger and global max level to trace, the logs will be
|
||||
// filtered by the outer logger
|
||||
let logger = env_logger::builder().filter_level(log::LevelFilter::Trace).build();
|
||||
init_with_logger(level, logger);
|
||||
}
|
||||
|
||||
pub fn init_with_logger(level: Level, logger: impl Log + Send + Sync + 'static) {
|
||||
@@ -114,51 +103,11 @@ fn macos_log_level(level: Level) -> oslog::Level {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, target_os = "macos"))]
|
||||
mod tests {
|
||||
use std::{
|
||||
io::Write,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Captured(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl Write for Captured {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_format_configures_the_env_logger() {
|
||||
let captured = Captured::default();
|
||||
let logger = build_env_logger(LogFormat::Json)
|
||||
.target(env_logger::Target::Pipe(Box::new(captured.clone())))
|
||||
.build();
|
||||
|
||||
logger.log(
|
||||
&log::Record::builder()
|
||||
.level(Level::Info)
|
||||
.target("gpauth")
|
||||
.args(format_args!("authenticating"))
|
||||
.build(),
|
||||
);
|
||||
|
||||
let output = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
|
||||
assert_eq!(value["message"], "authenticating");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn info_logs_use_the_persistent_macos_level() {
|
||||
assert_eq!(macos_log_level(Level::Info) as u8, oslog::Level::Default as u8);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use crate::process::collection::{CollectionBudget, CollectionControl};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
@@ -23,39 +20,8 @@ impl HostIdentity {
|
||||
Self::collect_with_host_id(None)
|
||||
}
|
||||
|
||||
pub fn collect_with_control(control: &dyn CollectionControl) -> io::Result<Self> {
|
||||
Self::collect_with_host_id_and_control(None, control)
|
||||
}
|
||||
|
||||
pub(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self {
|
||||
match Self::collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) {
|
||||
Ok(identity) => identity,
|
||||
Err(error) => {
|
||||
log::warn!("Host identity collection was unavailable: {error}");
|
||||
Self::default_with_host_id(host_id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort convenience callers retain the established derived identity
|
||||
/// when native collection is unavailable. Controlled HIP callers get errors.
|
||||
pub(crate) fn default_with_host_id(host_id: Option<&str>) -> Self {
|
||||
Self::from_parts(
|
||||
fallback_hostname(),
|
||||
resolve_host_id(host_id, fallback_host_id),
|
||||
String::new(),
|
||||
primary_mac_colon().unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn collect_with_host_id_and_control(
|
||||
host_id: Option<&str>,
|
||||
control: &dyn CollectionControl,
|
||||
) -> io::Result<Self> {
|
||||
control.check()?;
|
||||
let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity();
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
RuntimeNativeHostIdentity::collect(host_id).into_host_identity()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -63,8 +29,7 @@ impl HostIdentity {
|
||||
Self::from_parts(computer, host_id, serialno, mac_addr)
|
||||
}
|
||||
|
||||
/// Construct a host identity from an already collected or negotiated snapshot.
|
||||
pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
|
||||
pub(crate) fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
|
||||
let host_id = non_empty(host_id, fallback_host_id());
|
||||
let computer = non_empty(computer, fallback_hostname());
|
||||
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
|
||||
@@ -198,12 +163,12 @@ fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod platform {
|
||||
use std::process::Command;
|
||||
|
||||
use super::{
|
||||
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon,
|
||||
primary_mac_colon, resolve_host_id,
|
||||
};
|
||||
use crate::process::collection::{CollectionControl, CollectorCommands};
|
||||
use std::io;
|
||||
|
||||
pub(super) struct RuntimeNativeHostIdentity;
|
||||
|
||||
@@ -212,80 +177,74 @@ mod platform {
|
||||
ClientOs::Mac
|
||||
}
|
||||
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn CollectionControl,
|
||||
) -> io::Result<NativeHostIdentitySnapshot> {
|
||||
let commands = CollectorCommands::new(control);
|
||||
let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon);
|
||||
control.check()?;
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
let native_mac = macos_builtin_mac().or_else(primary_mac_colon);
|
||||
let host_id = resolve_host_id(host_id_override, || {
|
||||
native_mac
|
||||
.clone()
|
||||
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
|
||||
});
|
||||
let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname);
|
||||
let serial_number = collect_macos_serial_number(&commands)?;
|
||||
control.check()?;
|
||||
Ok(NativeHostIdentitySnapshot {
|
||||
NativeHostIdentitySnapshot {
|
||||
host_id,
|
||||
computer,
|
||||
serial_number,
|
||||
computer: macos_computer_name().unwrap_or_else(fallback_hostname),
|
||||
serial_number: collect_macos_serial_number(),
|
||||
mac_address: native_mac,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<Option<String>> {
|
||||
Ok(
|
||||
commands
|
||||
.run(program, args)?
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok()),
|
||||
)
|
||||
}
|
||||
fn macos_computer_name() -> Option<String> {
|
||||
["ComputerName", "LocalHostName"].into_iter().find_map(|name| {
|
||||
let output = Command::new("scutil").args(["--get", name]).output().ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
for name in ["ComputerName", "LocalHostName"] {
|
||||
if let Some(value) = output(commands, "scutil", &["--get", name])?
|
||||
String::from_utf8(output.stdout)
|
||||
.ok()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
return Ok(Some(value));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
})
|
||||
}
|
||||
|
||||
fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? {
|
||||
for name in ["Wi-Fi", "AirPort"] {
|
||||
if let Some(mac) = parse_hardware_port_mac(&stdout, name) {
|
||||
return Ok(Some(mac));
|
||||
}
|
||||
}
|
||||
}
|
||||
macos_system_profiler_wifi_mac(commands)
|
||||
fn macos_builtin_mac() -> Option<String> {
|
||||
macos_networksetup_mac("Wi-Fi")
|
||||
.or_else(|| macos_networksetup_mac("AirPort"))
|
||||
.or_else(macos_system_profiler_wifi_mac)
|
||||
}
|
||||
|
||||
fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option<String> {
|
||||
fn macos_networksetup_mac(port_name: &str) -> Option<String> {
|
||||
let output = Command::new("networksetup")
|
||||
.arg("-listallhardwareports")
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
let mut in_port = false;
|
||||
for line in stdout.lines() {
|
||||
if let Some(port) = line.strip_prefix("Hardware Port: ") {
|
||||
in_port = port == name;
|
||||
in_port = port == port_name;
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
|
||||
return normalize_mac_colon(mac);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
fn macos_system_profiler_wifi_mac() -> Option<String> {
|
||||
let output = Command::new("system_profiler").arg("SPNetworkDataType").output().ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
let mut in_wifi = false;
|
||||
for line in stdout.lines() {
|
||||
let trimmed = line.trim();
|
||||
@@ -293,24 +252,29 @@ mod platform {
|
||||
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
|
||||
return Ok(normalize_mac_colon(mac));
|
||||
return normalize_mac_colon(mac);
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(stdout.lines().find_map(|line| {
|
||||
fn collect_macos_serial_number() -> Option<String> {
|
||||
let output = Command::new("ioreg")
|
||||
.args(["-rd1", "-c", "IOPlatformExpertDevice"])
|
||||
.output()
|
||||
.ok()?;
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
|
||||
stdout.lines().find_map(|line| {
|
||||
line
|
||||
.split_once("IOPlatformSerialNumber")
|
||||
.and_then(|(_, value)| value.split_once('='))
|
||||
.map(|(_, value)| value.trim().trim_matches('"').to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -327,17 +291,7 @@ mod platform {
|
||||
ClientOs::Windows
|
||||
}
|
||||
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn super::CollectionControl,
|
||||
) -> super::io::Result<NativeHostIdentitySnapshot> {
|
||||
control.check()?;
|
||||
let identity = Self::collect(host_id_override);
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
let host_id = resolve_host_id(host_id_override, Self::host_id);
|
||||
NativeHostIdentitySnapshot {
|
||||
host_id,
|
||||
@@ -419,17 +373,7 @@ mod platform {
|
||||
ClientOs::Linux
|
||||
}
|
||||
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn super::CollectionControl,
|
||||
) -> super::io::Result<NativeHostIdentitySnapshot> {
|
||||
control.check()?;
|
||||
let identity = Self::collect(host_id_override);
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
|
||||
debug!("Runtime host-id source: explicit override ({})", host_id);
|
||||
}
|
||||
@@ -532,15 +476,6 @@ mod platform {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn controlled_identity_collection_propagates_cancellation() {
|
||||
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = HostIdentity::collect_with_control(&control).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
let error = HostIdentity::collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_produces_non_empty_identity() {
|
||||
let identity = HostIdentity::collect();
|
||||
@@ -593,8 +528,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn native_snapshot_uses_host_id_as_derivation_seed() {
|
||||
let native =
|
||||
RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap();
|
||||
let native = RuntimeNativeHostIdentity::collect(None);
|
||||
|
||||
assert!(!native.host_id.is_empty());
|
||||
}
|
||||
|
||||
@@ -3,9 +3,6 @@ mod serial_number;
|
||||
|
||||
pub use host_identity::HostIdentity;
|
||||
|
||||
use crate::process::collection::{CollectionBudget, CollectionControl};
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use common::constants::{GP_CLIENT_VERSION_LINUX, GP_CLIENT_VERSION_MACOS, GP_CLIENT_VERSION_WINDOWS, GP_USER_AGENT};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -369,7 +366,6 @@ impl OsProfile {
|
||||
pub struct OsProfileBuilder {
|
||||
client_os: ClientOs,
|
||||
client_version: Option<String>,
|
||||
os_version_override: Option<String>,
|
||||
computer_name_override: Option<String>,
|
||||
host_id_override: Option<String>,
|
||||
host_identity: Option<HostIdentity>,
|
||||
@@ -381,7 +377,6 @@ impl OsProfileBuilder {
|
||||
Self {
|
||||
client_os,
|
||||
client_version: None,
|
||||
os_version_override: None,
|
||||
computer_name_override: None,
|
||||
host_id_override: None,
|
||||
host_identity: None,
|
||||
@@ -399,13 +394,6 @@ impl OsProfileBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Preserve an explicitly negotiated operating system version.
|
||||
pub fn os_version(mut self, version: impl Into<String>) -> Self {
|
||||
let version = version.into();
|
||||
self.os_version_override = if version.trim().is_empty() { None } else { Some(version) };
|
||||
self
|
||||
}
|
||||
|
||||
pub fn host_identity(mut self, identity: HostIdentity) -> Self {
|
||||
self.host_identity = Some(identity);
|
||||
self
|
||||
@@ -423,67 +411,31 @@ impl OsProfileBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Build a best-effort profile with a bounded native collection budget.
|
||||
/// Use `build_with_control` when interruption or timeout must be reported.
|
||||
pub fn build(self) -> OsProfile {
|
||||
match self
|
||||
.clone()
|
||||
.build_with_control(&CollectionBudget::new(Duration::from_secs(60)))
|
||||
{
|
||||
Ok(profile) => profile,
|
||||
Err(error) => {
|
||||
log::warn!("OS profile collection was unavailable: {error}");
|
||||
let identity = self
|
||||
.host_identity
|
||||
.clone()
|
||||
.unwrap_or_else(|| HostIdentity::default_with_host_id(self.host_id_override.as_deref()));
|
||||
let (os_version, software_version) = match self.client_os {
|
||||
ClientOs::Mac => (
|
||||
format!("Apple Mac OS X {DEFAULT_MACOS_VERSION}"),
|
||||
DEFAULT_MACOS_VERSION.into(),
|
||||
),
|
||||
os => (target::os_version(os), target::software_version(os)),
|
||||
};
|
||||
self.finish(identity, os_version, software_version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_with_control(self, control: &dyn CollectionControl) -> io::Result<OsProfile> {
|
||||
control.check()?;
|
||||
let host_identity = match (&self.host_identity, &self.host_id_override) {
|
||||
(Some(identity), _) => identity.clone(),
|
||||
(None, host_id) => HostIdentity::collect_with_host_id_and_control(host_id.as_deref(), control)?,
|
||||
};
|
||||
let (os_version, software_version) = if self.client_os == ClientOs::Mac {
|
||||
let version = macos_version_with_control(control)?;
|
||||
(format!("Apple Mac OS X {version}"), version)
|
||||
} else {
|
||||
(
|
||||
target::os_version(self.client_os),
|
||||
target::software_version(self.client_os),
|
||||
)
|
||||
};
|
||||
control.check()?;
|
||||
Ok(self.finish(host_identity, os_version, software_version))
|
||||
}
|
||||
|
||||
fn finish(self, host_identity: HostIdentity, default_os_version: String, software_version: String) -> OsProfile {
|
||||
let client_version = self
|
||||
.client_version
|
||||
.filter(|version| !version.trim().is_empty())
|
||||
.unwrap_or_else(|| self.client_os.default_client_version().into());
|
||||
.filter(|v| !v.trim().is_empty())
|
||||
.unwrap_or_else(|| self.client_os.default_client_version().to_string());
|
||||
|
||||
let host_identity = match (self.host_identity, self.host_id_override) {
|
||||
(Some(identity), _) => identity,
|
||||
(None, host_id) => HostIdentity::collect_with_host_id(host_id.as_deref()),
|
||||
};
|
||||
let profile_identity =
|
||||
ProfileHostIdentity::for_client_os(self.client_os, &host_identity, self.computer_name_override);
|
||||
let os_version = self.os_version_override.unwrap_or(default_os_version);
|
||||
let os_version = target::os_version(self.client_os);
|
||||
let software_version = target::software_version(self.client_os);
|
||||
let os_vendor = target::os_vendor(self.client_os);
|
||||
|
||||
let user_agent = self
|
||||
.user_agent
|
||||
.unwrap_or_else(|| format!("{GP_USER_AGENT}/{client_version} ({os_version})"));
|
||||
.unwrap_or_else(|| format!("{}/{} ({})", GP_USER_AGENT, client_version, os_version));
|
||||
|
||||
OsProfile {
|
||||
client_os: self.client_os,
|
||||
os_version,
|
||||
software_version,
|
||||
os_vendor: target::os_vendor(self.client_os),
|
||||
os_vendor,
|
||||
client_version,
|
||||
host_identity,
|
||||
profile_identity,
|
||||
@@ -548,28 +500,14 @@ fn runtime_distro_or(fallback: &str) -> String {
|
||||
}
|
||||
|
||||
fn macos_version() -> String {
|
||||
macos_version_with_control(&CollectionBudget::new(Duration::from_secs(60))).unwrap_or_else(|error| {
|
||||
log::warn!("Operating system version collection was unavailable: {error}");
|
||||
DEFAULT_MACOS_VERSION.into()
|
||||
})
|
||||
}
|
||||
|
||||
fn macos_version_with_control(control: &dyn CollectionControl) -> io::Result<String> {
|
||||
control.check()?;
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let commands = crate::process::collection::CollectorCommands::new(control);
|
||||
let version = commands
|
||||
.run("sw_vers", &["-productVersion"])?
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok())
|
||||
.map(|version| version.trim().to_string())
|
||||
.filter(|version| !version.is_empty());
|
||||
control.check()?;
|
||||
Ok(version.unwrap_or_else(|| DEFAULT_MACOS_VERSION.into()))
|
||||
if runtime_client_os() == ClientOs::Mac {
|
||||
match os_info::get().version() {
|
||||
os_info::Version::Unknown => DEFAULT_MACOS_VERSION.to_string(),
|
||||
v => v.to_string(),
|
||||
}
|
||||
} else {
|
||||
DEFAULT_MACOS_VERSION.to_string()
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
Ok(DEFAULT_MACOS_VERSION.into())
|
||||
}
|
||||
|
||||
fn macos_os_string() -> String {
|
||||
@@ -753,37 +691,6 @@ mod target_identity {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn controlled_profile_collection_propagates_cancellation_and_deadline() {
|
||||
let cancelled = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = OsProfileBuilder::new(ClientOs::Mac)
|
||||
.build_with_control(&cancelled)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
let expired = CollectionBudget::new(Duration::ZERO);
|
||||
let error = OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build_with_control(&expired)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negotiated_os_version_is_used_in_profile_and_user_agent() {
|
||||
let identity = HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"host".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let profile = OsProfileBuilder::new(ClientOs::Mac)
|
||||
.host_identity(identity)
|
||||
.client_version("6.3.3")
|
||||
.os_version("negotiated-system-version")
|
||||
.build();
|
||||
assert_eq!(profile.os_version(), "negotiated-system-version");
|
||||
assert!(profile.user_agent().contains("negotiated-system-version"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csc_support_defaults_match_official_profiles() {
|
||||
assert!(!ClientOs::Linux.default_csc_support());
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::bail;
|
||||
use dns_lookup::lookup_addr;
|
||||
use log::{debug, info, warn};
|
||||
use reqwest::{Client, StatusCode};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use xmltree::Element;
|
||||
|
||||
use crate::{
|
||||
@@ -14,7 +14,6 @@ use crate::{
|
||||
gateway::{Gateway, parse_gateways},
|
||||
gp_params::GpParams,
|
||||
params,
|
||||
session::{InternalSessionPolicy, network::InternalHostDetection},
|
||||
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
|
||||
};
|
||||
|
||||
@@ -36,7 +35,6 @@ pub struct PortalConfig {
|
||||
* - Some(true): Internal host detection is supported and the user is connected to the internal network
|
||||
*/
|
||||
internal_host_detection: Option<bool>,
|
||||
internal_detection: Option<InternalHostDetection>,
|
||||
/**
|
||||
* The version returned by the portal config, if any
|
||||
*/
|
||||
@@ -49,7 +47,6 @@ pub struct PortalConfig {
|
||||
* Whether the portal policy enables default-browser authentication.
|
||||
*/
|
||||
default_browser: Option<bool>,
|
||||
internal_session_policy: Option<InternalSessionPolicy>,
|
||||
}
|
||||
|
||||
impl PortalConfig {
|
||||
@@ -73,10 +70,6 @@ impl PortalConfig {
|
||||
self.internal_host_detection
|
||||
}
|
||||
|
||||
pub fn internal_detection(&self) -> Option<&InternalHostDetection> {
|
||||
self.internal_detection.as_ref()
|
||||
}
|
||||
|
||||
pub fn connect_method(&self) -> Option<&str> {
|
||||
self.connect_method.as_deref()
|
||||
}
|
||||
@@ -93,10 +86,6 @@ impl PortalConfig {
|
||||
self.default_browser
|
||||
}
|
||||
|
||||
pub fn internal_session_policy(&self) -> Option<InternalSessionPolicy> {
|
||||
self.internal_session_policy
|
||||
}
|
||||
|
||||
/// In-place sort the gateways by region
|
||||
pub fn sort_gateways(&mut self, region: &str) {
|
||||
let preferred_gateway = self.find_preferred_gateway(region);
|
||||
@@ -140,14 +129,7 @@ impl PortalConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancellation is handled inside the request so a running native detection
|
||||
/// helper is always cancelled and joined. Do not drop this future on disconnect.
|
||||
pub async fn retrieve_config(
|
||||
portal: &str,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<PortalConfig> {
|
||||
pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<PortalConfig> {
|
||||
let portal = normalize_server(portal)?;
|
||||
let server = remove_url_scheme(&portal);
|
||||
|
||||
@@ -164,35 +146,29 @@ pub async fn retrieve_config(
|
||||
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
|
||||
info!("Portal config request params: {}", redact_form_params(&body_pairs));
|
||||
|
||||
let res_xml = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
|
||||
result = async {
|
||||
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
})?;
|
||||
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
})?;
|
||||
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
|
||||
}
|
||||
let res_xml = parse_gp_response(res).await.or_else(|err| {
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
|
||||
}
|
||||
|
||||
if err.is_status_error() {
|
||||
warn!("{err}");
|
||||
bail!("Portal config error: {}", err.reason);
|
||||
}
|
||||
if err.is_status_error() {
|
||||
warn!("{err}");
|
||||
bail!("Portal config error: {}", err.reason);
|
||||
}
|
||||
|
||||
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
|
||||
})
|
||||
} => result?,
|
||||
};
|
||||
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
|
||||
})?;
|
||||
|
||||
if res_xml.is_empty() {
|
||||
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
|
||||
}
|
||||
|
||||
debug!("Portal config response received: {} bytes", res_xml.len());
|
||||
debug!("Portal config response: {}", res_xml);
|
||||
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||
|
||||
if csc::is_config_criteria(&root) {
|
||||
@@ -202,18 +178,14 @@ pub async fn retrieve_config(
|
||||
"Portal returned CSC criteria but CSC support is disabled".to_string()
|
||||
));
|
||||
}
|
||||
let csc_xml = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
|
||||
result = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params) => result?,
|
||||
};
|
||||
debug!("Portal CSC config response received: {} bytes", csc_xml.len());
|
||||
let csc_xml = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params).await?;
|
||||
debug!("Portal CSC config response: {}", csc_xml);
|
||||
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||
return parse_portal_config(&server, cred, root, cancellation).await;
|
||||
return parse_portal_config(&server, cred, root);
|
||||
}
|
||||
|
||||
info!("Portal did not return CSC criteria");
|
||||
parse_portal_config(&server, cred, root, cancellation).await
|
||||
parse_portal_config(&server, cred, root)
|
||||
}
|
||||
|
||||
async fn retrieve_csc_config(
|
||||
@@ -273,31 +245,12 @@ fn present(value: Option<&str>) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
async fn parse_portal_config(
|
||||
server: &str,
|
||||
cred: &Credential,
|
||||
root: Element,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<PortalConfig> {
|
||||
let internal_detection = root
|
||||
.descendant("internal-host-detection")
|
||||
.map(parse_internal_detection)
|
||||
.transpose()
|
||||
.unwrap_or_else(|error| {
|
||||
warn!("Internal host detection policy is unavailable: {error}");
|
||||
None
|
||||
})
|
||||
.flatten();
|
||||
let prefer_internal = match &internal_detection {
|
||||
Some(detection) => detection.detect(cancellation).await.unwrap_or_else(|error| {
|
||||
warn!("Internal host detection failed: {error}");
|
||||
false
|
||||
}),
|
||||
None => false,
|
||||
};
|
||||
|
||||
if cancellation.is_cancelled() {
|
||||
bail!("Portal configuration cancelled");
|
||||
fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow::Result<PortalConfig> {
|
||||
let mut ihd_enabled = false;
|
||||
let mut prefer_internal = false;
|
||||
if let Some(ihd_node) = root.descendant("internal-host-detection") {
|
||||
ihd_enabled = true;
|
||||
prefer_internal = internal_host_detect(ihd_node)
|
||||
}
|
||||
|
||||
let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| {
|
||||
@@ -322,7 +275,6 @@ async fn parse_portal_config(
|
||||
info!("Detected portal version: {:?}", version);
|
||||
let allow_extend_session = parse_allow_extend_session(&root);
|
||||
let default_browser = parse_default_browser(&root);
|
||||
let internal_session_policy = parse_internal_session_policy(&root).ok();
|
||||
|
||||
Ok(PortalConfig {
|
||||
portal: server.to_string(),
|
||||
@@ -331,42 +283,13 @@ async fn parse_portal_config(
|
||||
gateways,
|
||||
connect_method,
|
||||
config_digest: config_digest.map(|s| s.to_string()),
|
||||
internal_host_detection: internal_detection.as_ref().map(|_| prefer_internal),
|
||||
internal_detection,
|
||||
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
|
||||
version,
|
||||
allow_extend_session,
|
||||
default_browser,
|
||||
internal_session_policy,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_internal_session_policy(root: &Element) -> anyhow::Result<InternalSessionPolicy> {
|
||||
let hip = root.descendant("hip-collection");
|
||||
let interval = hip
|
||||
.and_then(|hip| hip.child("hip-report-interval"))
|
||||
.map(|element| element.get_text().unwrap_or_default().into_owned());
|
||||
let collect = hip
|
||||
.and_then(|hip| hip.child("collect-hip-data"))
|
||||
.map(|element| element.get_text().unwrap_or_default().into_owned());
|
||||
let interval = parse_policy_number(interval, 3600, "hip-report-interval")?;
|
||||
let collect = match collect.as_deref().map(str::trim) {
|
||||
None | Some("yes") => true,
|
||||
Some("no") => false,
|
||||
Some(_) => bail!("Invalid portal collect-hip-data policy"),
|
||||
};
|
||||
InternalSessionPolicy::new(interval, collect)
|
||||
}
|
||||
|
||||
fn parse_policy_number(value: Option<String>, default: u32, field: &str) -> anyhow::Result<u32> {
|
||||
match value {
|
||||
Some(value) => value
|
||||
.trim()
|
||||
.parse()
|
||||
.map_err(|_| anyhow::anyhow!("Invalid portal {field} policy")),
|
||||
None => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_default_browser(root: &Element) -> Option<bool> {
|
||||
match root.descendant_text("default-browser")?.trim() {
|
||||
"yes" => Some(true),
|
||||
@@ -390,94 +313,49 @@ fn parse_connect_method(root: &Element) -> Option<String> {
|
||||
.map(|s| s.to_string())
|
||||
}
|
||||
|
||||
fn parse_internal_detection(element: &Element) -> anyhow::Result<Option<InternalHostDetection>> {
|
||||
// Perform DNS lookup and compare the result with the expected hostname
|
||||
fn internal_host_detect(element: &Element) -> bool {
|
||||
let ip_info = [
|
||||
(element.child_text("ip-address"), element.child_text("host")),
|
||||
(element.child_text("ipv6-address"), element.child_text("ipv6-host")),
|
||||
];
|
||||
|
||||
let mut targets = Vec::new();
|
||||
info!("Found internal-host-detection, performing DNS lookup");
|
||||
|
||||
for (ip_address, host) in ip_info.iter() {
|
||||
let address = ip_address.as_deref().filter(|value| !value.is_empty());
|
||||
let host = host.as_deref().filter(|value| !value.is_empty());
|
||||
match (address, host) {
|
||||
(None, None) => {}
|
||||
(Some(address), Some(host)) => targets.push((address.parse()?, host.to_owned())),
|
||||
_ => bail!("Incomplete internal host detection policy"),
|
||||
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref())
|
||||
&& !ip_address.is_empty()
|
||||
&& !host.is_empty()
|
||||
{
|
||||
match ip_address.parse::<std::net::IpAddr>() {
|
||||
Ok(ip) => match lookup_addr(&ip) {
|
||||
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
|
||||
return true;
|
||||
}
|
||||
Ok(host_lookup) => {
|
||||
info!(
|
||||
"rDNS lookup for {} returned {}, expected {}",
|
||||
ip_address, host_lookup, host
|
||||
);
|
||||
}
|
||||
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
|
||||
},
|
||||
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
|
||||
}
|
||||
}
|
||||
}
|
||||
if targets.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(InternalHostDetection::new(targets)?))
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_non_tunnel_policy_does_not_reject_tunnel_candidates() {
|
||||
let root = parse_xml(
|
||||
"<policy><hip-collection><hip-report-interval>invalid</hip-report-interval></hip-collection><internal-host-detection><ip-address>invalid</ip-address><host>internal.example</host></internal-host-detection><gateways><external><list><entry name='vpn.example'/></list></external></gateways></policy>",
|
||||
);
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
let config = parse_portal_config("portal.example", &credential, root, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(config.internal_session_policy().is_none());
|
||||
assert_eq!(config.gateways()[0].server(), "vpn.example");
|
||||
assert_eq!(config.gateways()[0].kind(), crate::gateway::GatewayKind::External);
|
||||
}
|
||||
|
||||
fn parse_xml(xml: &str) -> Element {
|
||||
Element::parse(xml.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_internal_maintenance_policy_with_explicit_units() {
|
||||
let root = parse_xml(
|
||||
"<policy><hip-collection><hip-report-interval>60</hip-report-interval><collect-hip-data>no</collect-hip-data></hip-collection><max-internal-gateway-connection-attempts>3</max-internal-gateway-connection-attempts></policy>",
|
||||
);
|
||||
let policy = parse_internal_session_policy(&root).unwrap();
|
||||
assert_eq!(policy.hip_interval(), std::time::Duration::from_secs(60));
|
||||
assert!(!policy.collect_hip_data());
|
||||
assert_eq!(
|
||||
parse_internal_session_policy(&parse_xml("<policy/>")).unwrap(),
|
||||
InternalSessionPolicy::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_supplied_internal_policy() {
|
||||
for interval in ["0", "-1", "", "4294967295", "not-a-number"] {
|
||||
let root = parse_xml(&format!(
|
||||
"<policy><hip-collection><hip-report-interval>{interval}</hip-report-interval></hip-collection></policy>"
|
||||
));
|
||||
assert!(parse_internal_session_policy(&root).is_err());
|
||||
}
|
||||
let root = parse_xml("<policy><hip-collection><collect-hip-data>true</collect-hip-data></hip-collection></policy>");
|
||||
assert!(parse_internal_session_policy(&root).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepts_existing_full_portal_fixture() {
|
||||
let root = parse_xml(include_str!("../../tests/files/portal_config.xml"));
|
||||
let cred = Credential::from(crate::credential::PasswordCredential::new(
|
||||
"fixture-user",
|
||||
"fixture-password",
|
||||
));
|
||||
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
config.internal_session_policy().unwrap().hip_interval(),
|
||||
std::time::Duration::from_secs(3600)
|
||||
);
|
||||
assert!(!config.gateways().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_allow_extend_session_yes() {
|
||||
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
|
||||
@@ -534,8 +412,8 @@ mod tests {
|
||||
assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn parses_csc_policy_response_as_portal_config() {
|
||||
#[test]
|
||||
fn parses_csc_policy_response_as_portal_config() {
|
||||
let root = parse_xml(
|
||||
r#"<policy>
|
||||
<portal-userauthcookie>user-cookie</portal-userauthcookie>
|
||||
@@ -553,9 +431,7 @@ mod tests {
|
||||
);
|
||||
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
|
||||
|
||||
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
let config = parse_portal_config("vpn.example.com", &cred, root).unwrap();
|
||||
|
||||
assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie");
|
||||
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
|
||||
|
||||
@@ -1,23 +1,16 @@
|
||||
use std::{
|
||||
net::IpAddr,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use std::{path::PathBuf, process::Stdio};
|
||||
|
||||
use anyhow::bail;
|
||||
use common::binary_paths;
|
||||
use tokio::process::Command;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use crate::auth::AuthWindowTheme;
|
||||
use crate::{auth::SamlAuthResult, credential::Credential, log_format::LogFormat, os_profile::OsProfile};
|
||||
use crate::{auth::SamlAuthResult, credential::Credential, os_profile::OsProfile};
|
||||
|
||||
use super::{command_runner::run_controlled, command_traits::CommandExt};
|
||||
|
||||
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
|
||||
use super::command_traits::CommandExt;
|
||||
|
||||
pub struct SamlAuthLauncher<'a> {
|
||||
cancellation: CancellationToken,
|
||||
server: &'a str,
|
||||
auth_executable: Option<&'a str>,
|
||||
gateway: bool,
|
||||
@@ -41,15 +34,12 @@ pub struct SamlAuthLauncher<'a> {
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_theme: Option<AuthWindowTheme>,
|
||||
browser: Option<&'a str>,
|
||||
browser_listen: Option<IpAddr>,
|
||||
verbose: Option<&'a str>,
|
||||
log_format: LogFormat,
|
||||
}
|
||||
|
||||
impl<'a> SamlAuthLauncher<'a> {
|
||||
pub fn new(server: &'a str) -> Self {
|
||||
Self {
|
||||
cancellation: CancellationToken::new(),
|
||||
server,
|
||||
auth_executable: None,
|
||||
gateway: false,
|
||||
@@ -73,9 +63,7 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_theme: None,
|
||||
browser: None,
|
||||
browser_listen: None,
|
||||
verbose: None,
|
||||
log_format: LogFormat::Text,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,37 +149,18 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn browser_listen(mut self, browser_listen: Option<IpAddr>) -> Self {
|
||||
self.browser_listen = browser_listen;
|
||||
self
|
||||
}
|
||||
|
||||
/// Render the child's logs the same way as ours.
|
||||
///
|
||||
/// gpauth inherits this process's stderr, so both processes must use the same
|
||||
/// format to keep the stream consistent.
|
||||
pub fn log_format(mut self, log_format: LogFormat) -> Self {
|
||||
self.log_format = log_format;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
|
||||
self.verbose = verbose;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn cancellation(mut self, cancellation: &CancellationToken) -> Self {
|
||||
self.cancellation = cancellation.clone();
|
||||
self
|
||||
}
|
||||
|
||||
/// The command line this launcher will run.
|
||||
///
|
||||
/// Split out from `launch` so a test can observe the argv the child actually
|
||||
/// receives: asserting on the builder's own fields would not catch an
|
||||
/// argument that never gets appended.
|
||||
fn build_command(&self, program: &Path) -> Command {
|
||||
let mut auth_cmd = Command::new(program);
|
||||
/// Launch the authenticator binary as the current user or SUDO_USER if available.
|
||||
pub async fn launch(self) -> anyhow::Result<Credential> {
|
||||
let program = self
|
||||
.auth_executable
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(binary_paths::gpauth);
|
||||
let mut auth_cmd = Command::new(&program);
|
||||
auth_cmd.arg(self.server);
|
||||
|
||||
if self.gateway {
|
||||
@@ -261,51 +230,22 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
auth_cmd.arg("--browser").arg(browser);
|
||||
}
|
||||
|
||||
if let Some(browser_listen) = self.browser_listen {
|
||||
auth_cmd.arg("--browser-listen").arg(browser_listen.to_string());
|
||||
}
|
||||
|
||||
auth_cmd.arg("--log-format").arg(self.log_format.as_str());
|
||||
|
||||
if let Some(verbose) = self.verbose {
|
||||
auth_cmd.arg(verbose);
|
||||
}
|
||||
|
||||
auth_cmd
|
||||
}
|
||||
let mut non_root_cmd = auth_cmd.into_non_root()?;
|
||||
let child = non_root_cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
|
||||
|
||||
/// Launch the authenticator binary as the current user or SUDO_USER if available.
|
||||
pub async fn launch(self) -> anyhow::Result<Credential> {
|
||||
let program = self
|
||||
.auth_executable
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(binary_paths::gpauth);
|
||||
let auth_cmd = self.build_command(&program);
|
||||
|
||||
let command = auth_cmd.into_non_root()?.into_std();
|
||||
let cancellation = self.cancellation;
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Authentication cancelled",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
run_controlled(command, &check, MAX_AUTH_RESULT_BYTES)
|
||||
})
|
||||
.await?;
|
||||
let output = match output {
|
||||
Ok(output) => output,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
let child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => {
|
||||
bail!("Failed to spawn {}: {}", program.display(), err);
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
|
||||
let output = child.wait_with_output().await?;
|
||||
|
||||
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
|
||||
bail!("Failed to parse auth data")
|
||||
};
|
||||
@@ -346,45 +286,6 @@ mod tests {
|
||||
assert_eq!(launcher.client_version, Some("6.0.0"));
|
||||
}
|
||||
|
||||
fn child_args(launcher: SamlAuthLauncher) -> Vec<String> {
|
||||
launcher
|
||||
.build_command(Path::new("gpauth"))
|
||||
.as_std()
|
||||
.get_args()
|
||||
.map(|arg| arg.to_string_lossy().into_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// gpauth writes to the same stderr as its parent, so a caller reading the
|
||||
/// parent's JSON would hit gpauth's text records mid-stream unless the format
|
||||
/// is passed down.
|
||||
#[test]
|
||||
fn json_is_forwarded_to_the_child() {
|
||||
let args = child_args(SamlAuthLauncher::new("portal.example.com").log_format(LogFormat::Json));
|
||||
|
||||
assert!(
|
||||
args.windows(2).any(|pair| pair == ["--log-format", "json"]),
|
||||
"expected --log-format json in {args:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The launcher always passes the selected format so the parent and child
|
||||
/// cannot silently drift onto different output formats.
|
||||
#[test]
|
||||
fn text_is_forwarded_to_the_child() {
|
||||
for launcher in [
|
||||
SamlAuthLauncher::new("portal.example.com").log_format(LogFormat::Text),
|
||||
SamlAuthLauncher::new("portal.example.com"),
|
||||
] {
|
||||
let args = child_args(launcher);
|
||||
|
||||
assert!(
|
||||
args.windows(2).any(|pair| pair == ["--log-format", "text"]),
|
||||
"expected --log-format text in {args:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_certificate_options_are_stored() {
|
||||
let launcher = SamlAuthLauncher::new("portal.example.com")
|
||||
@@ -396,12 +297,4 @@ mod tests {
|
||||
assert_eq!(launcher.sslkey, Some("/tmp/client.key"));
|
||||
assert_eq!(launcher.key_password, Some("secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_listen_address_is_stored() {
|
||||
let listen_ip = "192.168.107.15".parse().unwrap();
|
||||
let launcher = SamlAuthLauncher::new("portal.example.com").browser_listen(Some(listen_ip));
|
||||
|
||||
assert_eq!(launcher.browser_listen, Some(listen_ip));
|
||||
}
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
use std::{
|
||||
fs, io,
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Output, Stdio},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use super::command_runner::run_controlled;
|
||||
|
||||
/// Invocation control borrowed by collection; interruption must never be treated
|
||||
/// as an unavailable optional product.
|
||||
pub trait CollectionControl {
|
||||
fn check(&self) -> io::Result<()>;
|
||||
}
|
||||
|
||||
impl<F: Fn() -> io::Result<()>> CollectionControl for F {
|
||||
fn check(&self) -> io::Result<()> {
|
||||
self()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CollectionBudget {
|
||||
deadline: Instant,
|
||||
}
|
||||
|
||||
impl CollectionBudget {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
Self {
|
||||
deadline: Instant::now() + timeout,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CollectionControl for CollectionBudget {
|
||||
fn check(&self) -> io::Result<()> {
|
||||
if Instant::now() >= self.deadline {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"Device information collection timed out",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const COMMAND_OUTPUT_LIMIT: usize = 256 * 1024;
|
||||
const TOOL_DIRECTORIES: &[&str] = &[
|
||||
"/usr/bin",
|
||||
"/usr/sbin",
|
||||
"/bin",
|
||||
"/sbin",
|
||||
"/usr/local/bin",
|
||||
"/usr/local/sbin",
|
||||
#[cfg(target_os = "linux")]
|
||||
"/run/current-system/sw/bin",
|
||||
];
|
||||
|
||||
fn tool_directories() -> Vec<PathBuf> {
|
||||
let configured = std::env::var_os("GP_COMMAND_PATH").unwrap_or_default();
|
||||
let mut directories: Vec<_> = std::env::split_paths(&configured)
|
||||
.filter(|path| path.is_absolute())
|
||||
.collect();
|
||||
directories.extend(TOOL_DIRECTORIES.iter().map(PathBuf::from));
|
||||
directories
|
||||
}
|
||||
|
||||
pub struct CollectorCommands<'a> {
|
||||
control: &'a dyn CollectionControl,
|
||||
}
|
||||
|
||||
impl<'a> CollectorCommands<'a> {
|
||||
pub fn new(control: &'a dyn CollectionControl) -> Self {
|
||||
Self { control }
|
||||
}
|
||||
|
||||
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
|
||||
resolve_in_directories(name, &tool_directories(), uzers::get_effective_uid() == 0)
|
||||
}
|
||||
|
||||
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let Some(path) = self.resolve(name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.run_path(&path, args)
|
||||
}
|
||||
|
||||
/// Run an installed helper with the same trust checks as system collectors.
|
||||
/// Root only executes helpers protected from unprivileged modification.
|
||||
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let Some(path) = resolve_executable(path, uzers::get_effective_uid() == 0) else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.run_path(&path, args)
|
||||
}
|
||||
|
||||
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let home = if uzers::get_effective_uid() == 0 {
|
||||
if cfg!(target_os = "macos") {
|
||||
"/var/root"
|
||||
} else {
|
||||
"/root"
|
||||
}
|
||||
} else {
|
||||
"/"
|
||||
};
|
||||
let mut command = Command::new(path);
|
||||
command
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.env("PATH", command_path(uzers::get_effective_uid() == 0)?)
|
||||
.env("LC_ALL", "C")
|
||||
.env("HOME", home)
|
||||
.current_dir("/")
|
||||
.stderr(Stdio::null());
|
||||
match run_controlled(command, self.control, COMMAND_OUTPUT_LIMIT) {
|
||||
Ok(output) => Ok(Some(output)),
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_in_directories(name: &str, directories: &[PathBuf], require_root: bool) -> Option<PathBuf> {
|
||||
directories.iter().find_map(|directory| {
|
||||
let directory = fs::canonicalize(directory).ok()?;
|
||||
if require_root && !root_owned_path(&directory) {
|
||||
return None;
|
||||
}
|
||||
resolve_executable(&directory.join(name), require_root)
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_executable(path: &Path, require_root: bool) -> Option<PathBuf> {
|
||||
let resolved = fs::canonicalize(path).ok()?;
|
||||
let metadata = fs::metadata(&resolved).ok()?;
|
||||
if metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 && (!require_root || root_owned_path(&resolved)) {
|
||||
Some(resolved)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Known command directories, canonicalized and restricted to trusted root
|
||||
/// ownership when used for privileged execution.
|
||||
pub fn command_path(require_root: bool) -> io::Result<std::ffi::OsString> {
|
||||
let configured = tool_directories();
|
||||
let directories = configured.iter().filter_map(|directory| {
|
||||
let resolved = fs::canonicalize(directory).ok()?;
|
||||
if resolved.is_dir() && (!require_root || root_owned_path(&resolved)) {
|
||||
Some(resolved)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
std::env::join_paths(directories).map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))
|
||||
}
|
||||
|
||||
fn root_owned_path(path: &Path) -> bool {
|
||||
path.ancestors().all(|part| {
|
||||
fs::symlink_metadata(part).is_ok_and(|metadata| {
|
||||
let mode = metadata.permissions().mode();
|
||||
let writable = mode & 0o022 != 0;
|
||||
// A root-owned sticky directory protects each root-owned descendant
|
||||
// from replacement, including entries in the Nix store.
|
||||
let protected_ancestor = part != path && metadata.is_dir() && mode & 0o1000 != 0;
|
||||
metadata.uid() == 0 && (!writable || protected_ancestor) && !metadata.file_type().is_symlink()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn root_owned_sticky_directories_protect_collectors_without_trusting_writable_files() {
|
||||
// CI runs Rust tests as root; an unprivileged process cannot create these fixtures.
|
||||
if uzers::get_effective_uid() != 0 {
|
||||
return;
|
||||
}
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let tool = directory.path().join("collector");
|
||||
fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o1775)).unwrap();
|
||||
assert_eq!(resolve_executable(&tool, true), Some(fs::canonicalize(&tool).unwrap()));
|
||||
// A PATH directory must itself reject unprivileged additions, even with the sticky bit.
|
||||
assert!(!root_owned_path(directory.path()));
|
||||
assert!(resolve_in_directories("collector", &[directory.path().to_owned()], true).is_none());
|
||||
let bin = directory.path().join("bin");
|
||||
fs::create_dir(&bin).unwrap();
|
||||
fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::copy(&tool, bin.join("collector")).unwrap();
|
||||
assert!(resolve_in_directories("collector", &[bin], true).is_some());
|
||||
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o775)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o1777)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_some());
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o1775)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::os::unix::fs::chown(&tool, Some(1), None).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
std::os::unix::fs::chown(&tool, Some(0), None).unwrap();
|
||||
std::os::unix::fs::chown(directory.path(), Some(1), None).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_directories_resolve_tools_without_using_the_process_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let tool = dir.path().join("configured-tool");
|
||||
fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(
|
||||
resolve_in_directories("configured-tool", &[dir.path().to_owned()], false),
|
||||
Some(fs::canonicalize(&tool).unwrap())
|
||||
);
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o777)).unwrap();
|
||||
assert!(resolve_in_directories("configured-tool", &[dir.path().to_owned()], true).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_command_path_contains_only_trusted_canonical_directories() {
|
||||
let path = command_path(true).unwrap();
|
||||
let directories: Vec<_> = std::env::split_paths(&path).collect();
|
||||
assert!(!directories.is_empty());
|
||||
for directory in directories {
|
||||
assert!(directory.is_dir());
|
||||
assert!(root_owned_path(&directory));
|
||||
assert_eq!(directory, fs::canonicalize(&directory).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_resolution_returns_target_not_mutable_symlink() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let link = dir.path().join("tool");
|
||||
std::os::unix::fs::symlink("/bin/sh", &link).unwrap();
|
||||
let resolved = resolve_executable(&link, false).unwrap();
|
||||
fs::remove_file(&link).unwrap();
|
||||
std::os::unix::fs::symlink("/bin/echo", &link).unwrap();
|
||||
assert_eq!(resolved, fs::canonicalize("/bin/sh").unwrap());
|
||||
assert_ne!(resolved, fs::canonicalize(&link).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_stops_running_collector() {
|
||||
let started = Instant::now();
|
||||
let control = || {
|
||||
if started.elapsed() >= Duration::from_millis(100) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let error = CollectorCommands::new(&control)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30 & wait"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_has_private_environment_and_cwd() {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(2));
|
||||
let output = CollectorCommands::new(&budget)
|
||||
.run_path(
|
||||
Path::new("/bin/sh"),
|
||||
&[
|
||||
"-c",
|
||||
"printf '%s|%s|%s' \"$LC_ALL\" \"$PWD\" \"${SENTINEL_OUTPUT_JSON-unset}\"",
|
||||
],
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
assert_eq!(String::from_utf8(output.stdout).unwrap(), "C|/|unset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deadline_stops_collector_instead_of_hanging() {
|
||||
let budget = CollectionBudget::new(Duration::from_millis(100));
|
||||
let started = Instant::now();
|
||||
let error = CollectorCommands::new(&budget)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_output_is_bounded() {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(2));
|
||||
let error = CollectorCommands::new(&budget)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "yes x"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_is_not_an_optional_missing_product() {
|
||||
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = CollectorCommands::new(&control).run("not-installed", &[]).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
use std::{
|
||||
io::{self, Read},
|
||||
os::unix::process::CommandExt,
|
||||
process::{Child, Command, Output, Stdio},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, OFlag, fcntl},
|
||||
sys::signal::{Signal, killpg},
|
||||
unistd::Pid,
|
||||
};
|
||||
|
||||
use super::collection::CollectionControl;
|
||||
|
||||
/// Execute an already configured command. Environment, identity and executable
|
||||
/// trust belong to its caller. This worker owns the process group until reaped;
|
||||
/// its asynchronous caller must cancel and await it instead of dropping it.
|
||||
pub(crate) fn run_controlled(
|
||||
mut command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: usize,
|
||||
) -> io::Result<Output> {
|
||||
control.check()?;
|
||||
let child = command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.process_group(0)
|
||||
.spawn()?;
|
||||
let mut child = ControlledChild(child);
|
||||
let mut stdout = child.0.stdout.take().expect("controlled stdout was piped");
|
||||
let flags = fcntl(&stdout, FcntlArg::F_GETFL).map_err(io::Error::from)?;
|
||||
fcntl(
|
||||
&stdout,
|
||||
FcntlArg::F_SETFL(OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK),
|
||||
)
|
||||
.map_err(io::Error::from)?;
|
||||
let mut output = Vec::new();
|
||||
let mut buffer = [0u8; 8192];
|
||||
let mut eof = false;
|
||||
let mut status = None;
|
||||
loop {
|
||||
control.check()?;
|
||||
if !eof {
|
||||
match stdout.read(&mut buffer) {
|
||||
Ok(0) => eof = true,
|
||||
Ok(length) => {
|
||||
if length > output_limit.saturating_sub(output.len()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Command output exceeds its limit",
|
||||
));
|
||||
}
|
||||
output.extend_from_slice(&buffer[..length]);
|
||||
continue;
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
if status.is_none() {
|
||||
status = child.0.try_wait()?;
|
||||
}
|
||||
if eof && let Some(status) = status {
|
||||
return Ok(Output {
|
||||
status,
|
||||
stdout: output,
|
||||
stderr: Vec::new(),
|
||||
});
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
struct ControlledChild(Child);
|
||||
|
||||
impl Drop for ControlledChild {
|
||||
fn drop(&mut self) {
|
||||
// Reap the direct child and stop helpers retaining stdout after it exits.
|
||||
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{File, OpenOptions},
|
||||
path::Path,
|
||||
process::{ExitStatus, Stdio},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use common::binary_paths;
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
|
||||
process::Command,
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{CommandExt, gui_launcher::GuiLauncher};
|
||||
use crate::service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential};
|
||||
|
||||
/// Owns the desktop GUI and its privileged service without leaving the desktop session.
|
||||
pub struct DesktopLauncher<'a> {
|
||||
version: &'a str,
|
||||
minimized: bool,
|
||||
log_file: Option<String>,
|
||||
}
|
||||
|
||||
impl<'a> DesktopLauncher<'a> {
|
||||
pub fn new(version: &'a str) -> Self {
|
||||
Self {
|
||||
version,
|
||||
minimized: false,
|
||||
log_file: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn minimized(mut self, minimized: bool) -> Self {
|
||||
self.minimized = minimized;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn log_file(mut self, log_file: &str) -> Self {
|
||||
self.log_file = Some(log_file.to_owned());
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
||||
ensure!(
|
||||
uzers::get_effective_uid() != 0,
|
||||
"The desktop launcher must not run as root"
|
||||
);
|
||||
let mut command = Command::new_pkexec(binary_paths::gpservice());
|
||||
command
|
||||
.arg("--desktop-credentials")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped());
|
||||
if let Some(path) = &self.log_file {
|
||||
command.stderr(Stdio::from(create_log_file(Path::new(path))?));
|
||||
}
|
||||
let mut service = command.spawn().context("Failed to start the privileged service")?;
|
||||
let mut input = service.stdin.take().context("Service input pipe is unavailable")?;
|
||||
let mut output = service
|
||||
.stdout
|
||||
.take()
|
||||
.context("Service credential pipe is unavailable")?;
|
||||
let mut received_credential = false;
|
||||
let mut cancelled = false;
|
||||
let result = tokio::select! {
|
||||
_ = crate::utils::shutdown_signal() => { cancelled = true; Ok(()) },
|
||||
result = async {
|
||||
let mut minimized = self.minimized;
|
||||
loop {
|
||||
let credential = read_credential(&mut output).await?;
|
||||
let Some(credential) = credential else { return Ok(()); };
|
||||
received_credential = true;
|
||||
ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||
let mut envs: HashMap<String, String> = std::env::vars().collect();
|
||||
if let Some(path) = &self.log_file {
|
||||
envs.insert("GP_LOG_FILE".into(), path.clone());
|
||||
}
|
||||
let launcher = GuiLauncher::new(self.version, Arc::new(credential)).envs(envs).minimized(minimized);
|
||||
let mut unexpected = [0];
|
||||
tokio::select! {
|
||||
result = launcher.launch() => { result?; }
|
||||
status = service.wait() => { anyhow::bail!("The privileged service exited while the GUI was running: {}", status?); }
|
||||
result = output.read(&mut unexpected) => {
|
||||
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
|
||||
anyhow::bail!("The privileged service closed its credential channel");
|
||||
}
|
||||
}
|
||||
input.write_all(&[0]).await?;
|
||||
minimized = false;
|
||||
}
|
||||
} => result,
|
||||
};
|
||||
// EOF lets the service revoke the credential and disconnect the VPN gracefully.
|
||||
drop(input);
|
||||
if cancelled && !received_credential {
|
||||
// pkexec is still user-owned during authorization. After elevation, EOF owns shutdown.
|
||||
if let Err(error) = service.start_kill()
|
||||
&& error.kind() != std::io::ErrorKind::PermissionDenied
|
||||
{
|
||||
return Err(error.into());
|
||||
}
|
||||
}
|
||||
let status = service.wait().await?;
|
||||
result?;
|
||||
ensure!(
|
||||
cancelled || status.success(),
|
||||
"The privileged service exited with {status}"
|
||||
);
|
||||
Ok(status)
|
||||
}
|
||||
}
|
||||
|
||||
fn create_log_file(path: &Path) -> std::io::Result<File> {
|
||||
// Start a fresh desktop session, then let both processes append without overwriting each other.
|
||||
File::create(path)?;
|
||||
OpenOptions::new().append(true).open(path)
|
||||
}
|
||||
|
||||
async fn read_credential(reader: &mut (impl AsyncRead + Unpin)) -> anyhow::Result<Option<SessionCredential>> {
|
||||
let mut header = [0; 2];
|
||||
if reader.read(&mut header[..1]).await? == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
reader.read_exact(&mut header[1..]).await?;
|
||||
let length = usize::from(u16::from_be_bytes(header));
|
||||
ensure!(
|
||||
length != 0 && length + 2 <= MAX_CREDENTIAL_FRAME,
|
||||
"Invalid service credential length"
|
||||
);
|
||||
let mut frame = Zeroizing::new(vec![0; length + 2]);
|
||||
frame[..2].copy_from_slice(&header);
|
||||
reader.read_exact(&mut frame[2..]).await?;
|
||||
Ok(Some(SessionCredential::decode_frame(&frame)?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Write;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn desktop_log_starts_fresh_and_service_writes_preserve_gui_logs() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let path = dir.path().join("desktop.log");
|
||||
std::fs::write(&path, "previous session\n").unwrap();
|
||||
let mut service = create_log_file(&path).unwrap();
|
||||
writeln!(service, "[gpservice] started").unwrap();
|
||||
let mut gui = OpenOptions::new().append(true).open(&path).unwrap();
|
||||
writeln!(gui, "[gpgui] initialized").unwrap();
|
||||
writeln!(service, "[gpservice] connected").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&path).unwrap(),
|
||||
"[gpservice] started\n[gpgui] initialized\n[gpservice] connected\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn credential_channel_distinguishes_clean_close_from_truncated_or_oversized_frames() {
|
||||
assert!(read_credential(&mut &[][..]).await.unwrap().is_none());
|
||||
assert!(read_credential(&mut &[0][..]).await.is_err());
|
||||
assert!(read_credential(&mut &[0, 0][..]).await.is_err());
|
||||
assert!(read_credential(&mut &[255, 255][..]).await.is_err());
|
||||
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let decoded = read_credential(&mut frame.as_slice()).await.unwrap().unwrap();
|
||||
assert_eq!(decoded.session_id(), credential.session_id());
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use common::binary_paths;
|
||||
use log::info;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
|
||||
use crate::service::transport::SessionCredential;
|
||||
use crate::{process::command_traits::CommandExt, service::transport::SessionCredential};
|
||||
|
||||
pub struct GuiHelperLauncher<'a> {
|
||||
program: PathBuf,
|
||||
@@ -49,11 +49,8 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
}
|
||||
|
||||
info!("Launching gpgui-helper");
|
||||
anyhow::ensure!(
|
||||
uzers::get_effective_uid() != 0,
|
||||
"The desktop GUI must not be launched by root"
|
||||
);
|
||||
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||
let mut non_root_cmd = cmd.into_non_root()?;
|
||||
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||
let mut child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
|
||||
|
||||
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user