Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fba127e503 | ||
|
|
f41303c797 | ||
|
|
352a2efb35 | ||
|
|
96e25eb408 | ||
|
|
1c777313dc |
No files matched your search
@@ -10,11 +10,6 @@ on:
|
|||||||
description: 'gpgui branch to use for the snapshot release'
|
description: 'gpgui branch to use for the snapshot release'
|
||||||
required: true
|
required: true
|
||||||
default: dev
|
default: dev
|
||||||
build_macos:
|
|
||||||
description: 'Build Apple Silicon artifacts for the snapshot release'
|
|
||||||
required: true
|
|
||||||
default: false
|
|
||||||
type: boolean
|
|
||||||
build_bsd:
|
build_bsd:
|
||||||
description: 'Build FreeBSD/OpenBSD packages for the snapshot release'
|
description: 'Build FreeBSD/OpenBSD packages for the snapshot release'
|
||||||
required: true
|
required: true
|
||||||
@@ -40,32 +35,10 @@ on:
|
|||||||
- v*.*.*
|
- v*.*.*
|
||||||
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && 'release' || github.ref }}
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
cancel-in-progress: ${{ github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/') }}
|
cancel-in-progress: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test-gp:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout GlobalProtect-openconnect
|
|
||||||
uses: actions/checkout@v6
|
|
||||||
with:
|
|
||||||
token: ${{ secrets.GH_PAT }}
|
|
||||||
repository: yuezk/GlobalProtect-openconnect
|
|
||||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
|
|
||||||
submodules: recursive
|
|
||||||
- name: Run Rust tests in Docker
|
|
||||||
run: |
|
|
||||||
docker run --rm \
|
|
||||||
--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 \
|
|
||||||
cargo test --workspace
|
|
||||||
|
|
||||||
tarball:
|
tarball:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -305,22 +278,14 @@ jobs:
|
|||||||
repository: yuezk/gpgui
|
repository: yuezk/gpgui
|
||||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
||||||
path: gpgui-source/gpgui
|
path: gpgui-source/gpgui
|
||||||
- name: Verify Linux desktop assets
|
|
||||||
if: matrix.os.arch == 'amd64' && matrix.libc.name == 'glibc'
|
|
||||||
run: gpgui-source/gp/scripts/verify-linux-desktop-assets.sh gpgui-source/gpgui
|
|
||||||
- name: Tarball
|
- name: Tarball
|
||||||
run: |
|
run: |
|
||||||
cd gpgui-source
|
cd gpgui-source
|
||||||
tar -czf gpgui.tar.gz gpgui gp
|
tar -czf gpgui.tar.gz gpgui gp
|
||||||
- name: Build gpgui in Docker
|
- name: Build gpgui in Docker
|
||||||
env:
|
|
||||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
|
||||||
run: |
|
run: |
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
-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 }}
|
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:${{ matrix.libc.builder }}
|
||||||
- name: Install gpgui in Docker
|
- name: Install gpgui in Docker
|
||||||
run: |
|
run: |
|
||||||
@@ -339,93 +304,6 @@ jobs:
|
|||||||
gpgui-source/*.bin.tar.xz
|
gpgui-source/*.bin.tar.xz
|
||||||
gpgui-source/*.bin.tar.xz.sha256
|
gpgui-source/*.bin.tar.xz.sha256
|
||||||
|
|
||||||
trigger-gpgui-macos:
|
|
||||||
if: ${{ startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.build_macos) }}
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
name: trigger private macOS release
|
|
||||||
outputs:
|
|
||||||
run_id: ${{ steps.dispatch.outputs.run_id }}
|
|
||||||
run_url: ${{ steps.dispatch.outputs.run_url }}
|
|
||||||
steps:
|
|
||||||
- name: Dispatch private macOS release
|
|
||||||
id: dispatch
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
|
|
||||||
PUBLIC_GH_TOKEN: ${{ github.token }}
|
|
||||||
CHANNEL: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
|
|
||||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
|
|
||||||
GP_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref_name }}
|
|
||||||
GPGUI_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
|
||||||
BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
|
||||||
REQUEST_ID: ${{ github.run_id }}.${{ github.run_attempt }}.macos
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
if [[ -z "${GH_TOKEN:-}" ]]; then
|
|
||||||
echo "GPGUI_ACTIONS_TOKEN is not configured" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
gp_ref_path="$(jq -rn --arg ref "$GP_REF" '$ref | @uri')"
|
|
||||||
gpgui_ref_path="$(jq -rn --arg ref "$GPGUI_REF" '$ref | @uri')"
|
|
||||||
gp_sha="$(GH_TOKEN="$PUBLIC_GH_TOKEN" gh api \
|
|
||||||
"repos/yuezk/GlobalProtect-openconnect/commits/$gp_ref_path" --jq .sha)"
|
|
||||||
gpgui_sha="$(gh api "repos/yuezk/gpgui/commits/$gpgui_ref_path" --jq .sha)"
|
|
||||||
if [[ -z "$gp_sha" || -z "$gpgui_sha" ]]; then
|
|
||||||
echo "Could not resolve release source refs" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
expected_title="macOS $CHANNEL $RELEASE_TAG ($REQUEST_ID)"
|
|
||||||
jq -n \
|
|
||||||
--arg workflow_ref "$GPGUI_REF" \
|
|
||||||
--arg request_id "$REQUEST_ID" \
|
|
||||||
--arg build_version "$BUILD_VERSION" \
|
|
||||||
--arg channel "$CHANNEL" \
|
|
||||||
--arg release_tag "$RELEASE_TAG" \
|
|
||||||
--arg gp_ref "$gp_sha" \
|
|
||||||
--arg gpgui_ref "$gpgui_sha" \
|
|
||||||
'{
|
|
||||||
ref: $workflow_ref,
|
|
||||||
inputs: {
|
|
||||||
request_id: $request_id,
|
|
||||||
build_version: $build_version,
|
|
||||||
channel: $channel,
|
|
||||||
release_tag: $release_tag,
|
|
||||||
gp_ref: $gp_ref,
|
|
||||||
gpgui_ref: $gpgui_ref
|
|
||||||
}
|
|
||||||
}' | gh api --method POST \
|
|
||||||
repos/yuezk/gpgui/actions/workflows/release-macos.yaml/dispatches \
|
|
||||||
--input -
|
|
||||||
|
|
||||||
run_id=""
|
|
||||||
run_url=""
|
|
||||||
for _ in {1..40}; do
|
|
||||||
runs="$(gh api \
|
|
||||||
'repos/yuezk/gpgui/actions/workflows/release-macos.yaml/runs?event=workflow_dispatch&per_page=50')"
|
|
||||||
run_id="$(jq -r --arg title "$expected_title" \
|
|
||||||
'[.workflow_runs[] | select(.display_title == $title)] | first | .id // empty' \
|
|
||||||
<<<"$runs")"
|
|
||||||
run_url="$(jq -r --arg title "$expected_title" \
|
|
||||||
'[.workflow_runs[] | select(.display_title == $title)] | first | .html_url // empty' \
|
|
||||||
<<<"$runs")"
|
|
||||||
if [[ -n "$run_id" ]]; then
|
|
||||||
{
|
|
||||||
echo "run_id=$run_id"
|
|
||||||
echo "run_url=$run_url"
|
|
||||||
} >> "$GITHUB_OUTPUT"
|
|
||||||
echo "Triggered private workflow: $run_url"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
sleep 3
|
|
||||||
done
|
|
||||||
|
|
||||||
echo "Could not locate the dispatched private workflow run" >&2
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
setup-bsd-matrix:
|
setup-bsd-matrix:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
outputs:
|
outputs:
|
||||||
@@ -496,7 +374,7 @@ jobs:
|
|||||||
path: gpgui-frontend/gpgui
|
path: gpgui-frontend/gpgui
|
||||||
- name: Build gpgui frontend
|
- name: Build gpgui frontend
|
||||||
run: |
|
run: |
|
||||||
cd gpgui-frontend/gpgui/apps/desktop
|
cd gpgui-frontend/gpgui/app
|
||||||
pnpm install --frozen-lockfile
|
pnpm install --frozen-lockfile
|
||||||
pnpm build
|
pnpm build
|
||||||
- name: Upload gpgui frontend
|
- name: Upload gpgui frontend
|
||||||
@@ -504,7 +382,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
name: bsd-gpgui-frontend
|
name: bsd-gpgui-frontend
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
path: gpgui-frontend/gpgui/apps/desktop/dist/**
|
path: gpgui-frontend/gpgui/app/dist/**
|
||||||
|
|
||||||
build-bsd:
|
build-bsd:
|
||||||
needs:
|
needs:
|
||||||
@@ -538,12 +416,12 @@ jobs:
|
|||||||
uses: actions/download-artifact@v8
|
uses: actions/download-artifact@v8
|
||||||
with:
|
with:
|
||||||
name: bsd-gpgui-frontend
|
name: bsd-gpgui-frontend
|
||||||
path: ${{ matrix.workspace }}/gpgui/apps/desktop/dist
|
path: ${{ matrix.workspace }}/gpgui/app/dist
|
||||||
- name: Build on FreeBSD
|
- name: Build on FreeBSD
|
||||||
if: ${{ matrix.os == 'freebsd' }}
|
if: ${{ matrix.os == 'freebsd' }}
|
||||||
uses: vmactions/freebsd-vm@v1
|
uses: vmactions/freebsd-vm@v1
|
||||||
with:
|
with:
|
||||||
release: "14.4"
|
release: "14.3"
|
||||||
arch: ${{ matrix.arch }}
|
arch: ${{ matrix.arch }}
|
||||||
usesh: true
|
usesh: true
|
||||||
prepare: |
|
prepare: |
|
||||||
@@ -569,17 +447,14 @@ jobs:
|
|||||||
webkit2-gtk_41
|
webkit2-gtk_41
|
||||||
run: |
|
run: |
|
||||||
set -eu
|
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"
|
cd "${{ matrix.workspace }}/gp"
|
||||||
cargo build --release --workspace
|
cargo build --release --workspace
|
||||||
|
|
||||||
cd ../gpgui/apps/desktop/src-tauri
|
cd ../gpgui/app/src-tauri
|
||||||
cargo build --release --workspace
|
cargo build --release --workspace
|
||||||
|
|
||||||
cd ../../../../gp
|
cd ../../../gp
|
||||||
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
|
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
|
||||||
pkg install -y ".build/${{ matrix.artifact_dir }}"/artifacts/*.pkg
|
pkg install -y ".build/${{ matrix.artifact_dir }}"/artifacts/*.pkg
|
||||||
gpclient --version
|
gpclient --version
|
||||||
@@ -595,27 +470,25 @@ jobs:
|
|||||||
arch: ${{ matrix.arch }}
|
arch: ${{ matrix.arch }}
|
||||||
usesh: true
|
usesh: true
|
||||||
prepare: |
|
prepare: |
|
||||||
set -eu
|
pkg_add -z \
|
||||||
pkg_add -u -I
|
|
||||||
pkg_add -I \
|
|
||||||
git \
|
git \
|
||||||
rust \
|
rust \
|
||||||
libiconv \
|
libiconv \
|
||||||
gettext-tools \
|
gettext-tools \
|
||||||
autoconf%2.72 \
|
autoconf-2.72 \
|
||||||
automake%1.17 \
|
automake-1.17 \
|
||||||
libtool \
|
libtool \
|
||||||
|
patch \
|
||||||
gmake \
|
gmake \
|
||||||
|
pkgconf \
|
||||||
libxml \
|
libxml \
|
||||||
gnutls \
|
gnutls \
|
||||||
p11-kit \
|
p11-kit \
|
||||||
|
nettle \
|
||||||
gmp \
|
gmp \
|
||||||
lz4 \
|
|
||||||
dbus \
|
|
||||||
gnome-keyring \
|
gnome-keyring \
|
||||||
polkit \
|
polkit \
|
||||||
webkitgtk41 \
|
webkitgtk41
|
||||||
xdg-utils
|
|
||||||
ln -sf /usr/local/bin/autoreconf-2.72 /usr/local/bin/autoreconf
|
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/autoconf-2.72 /usr/local/bin/autoconf
|
||||||
ln -sf /usr/local/bin/autoheader-2.72 /usr/local/bin/autoheader
|
ln -sf /usr/local/bin/autoheader-2.72 /usr/local/bin/autoheader
|
||||||
@@ -626,17 +499,14 @@ jobs:
|
|||||||
set -eu
|
set -eu
|
||||||
export AUTOCONF_VERSION=2.72
|
export AUTOCONF_VERSION=2.72
|
||||||
export AUTOMAKE_VERSION=1.17
|
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"
|
cd "${{ matrix.workspace }}/gp"
|
||||||
cargo build --release --workspace
|
cargo build --release --workspace
|
||||||
|
|
||||||
cd ../gpgui/apps/desktop/src-tauri
|
cd ../gpgui/app/src-tauri
|
||||||
cargo build --release --workspace
|
cargo build --release --workspace
|
||||||
|
|
||||||
cd ../../../../gp
|
cd ../../../gp
|
||||||
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
|
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
|
||||||
pkg_add -D unsigned ".build/${{ matrix.artifact_dir }}"/artifacts/*.tgz
|
pkg_add -D unsigned ".build/${{ matrix.artifact_dir }}"/artifacts/*.tgz
|
||||||
gpclient --version
|
gpclient --version
|
||||||
@@ -762,54 +632,6 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
|
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
|
||||||
|
|
||||||
wait-gpgui-macos:
|
|
||||||
if: ${{ always() && needs.trigger-gpgui-macos.result != 'skipped' }}
|
|
||||||
needs:
|
|
||||||
- gh-release
|
|
||||||
- trigger-gpgui-macos
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
timeout-minutes: 130
|
|
||||||
steps:
|
|
||||||
- name: Wait for private macOS release
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
|
|
||||||
PUBLIC_RELEASE_RESULT: ${{ needs.gh-release.result }}
|
|
||||||
PRIVATE_RUN_ID: ${{ needs.trigger-gpgui-macos.outputs.run_id }}
|
|
||||||
PRIVATE_RUN_URL: ${{ needs.trigger-gpgui-macos.outputs.run_url }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
if [[ -z "$PRIVATE_RUN_ID" ]]; then
|
|
||||||
echo "The private macOS workflow was not started" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
if [[ "$PUBLIC_RELEASE_RESULT" != "success" ]]; then
|
|
||||||
gh api --method POST \
|
|
||||||
"repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID/cancel" >/dev/null || true
|
|
||||||
echo "The public release failed; cancelled $PRIVATE_RUN_URL" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
for _ in $(seq 1 480); do
|
|
||||||
run="$(gh api "repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID")"
|
|
||||||
status="$(jq -r '.status' <<<"$run")"
|
|
||||||
conclusion="$(jq -r '.conclusion // ""' <<<"$run")"
|
|
||||||
if [[ "$status" == "completed" ]]; then
|
|
||||||
echo "Private macOS workflow completed: $PRIVATE_RUN_URL"
|
|
||||||
if [[ "$conclusion" != "success" ]]; then
|
|
||||||
echo "Private macOS workflow concluded with: $conclusion" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
sleep 15
|
|
||||||
done
|
|
||||||
|
|
||||||
gh api --method POST \
|
|
||||||
"repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID/cancel" >/dev/null || true
|
|
||||||
echo "Private macOS workflow timed out: $PRIVATE_RUN_URL" >&2
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
publish-docker-image:
|
publish-docker-image:
|
||||||
needs:
|
needs:
|
||||||
- build-docker-image
|
- build-docker-image
|
||||||
|
|||||||
@@ -1,118 +0,0 @@
|
|||||||
name: Nix
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request:
|
|
||||||
paths:
|
|
||||||
- "flake.nix"
|
|
||||||
- "flake.lock"
|
|
||||||
- "nix/**"
|
|
||||||
- ".github/workflows/nix.yaml"
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
paths:
|
|
||||||
- "flake.nix"
|
|
||||||
- "flake.lock"
|
|
||||||
- "nix/**"
|
|
||||||
- ".github/workflows/nix.yaml"
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
standalone-package:
|
|
||||||
name: standalone-package (${{ matrix.platform.system }})
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
platform:
|
|
||||||
- runner: ubuntu-latest
|
|
||||||
system: x86_64-linux
|
|
||||||
- runner: ubuntu-24.04-arm
|
|
||||||
system: aarch64-linux
|
|
||||||
runs-on: ${{ matrix.platform.runner }}
|
|
||||||
steps:
|
|
||||||
- name: Checkout GlobalProtect-openconnect
|
|
||||||
uses: actions/checkout@v6
|
|
||||||
|
|
||||||
- name: Install Nix
|
|
||||||
uses: cachix/install-nix-action@v31
|
|
||||||
|
|
||||||
- name: Build standalone prebuilt package
|
|
||||||
run: |
|
|
||||||
nix build .#prebuilt \
|
|
||||||
--extra-experimental-features "nix-command flakes" \
|
|
||||||
--print-build-logs
|
|
||||||
|
|
||||||
- name: Inspect prebuilt package
|
|
||||||
run: |
|
|
||||||
test -x result/bin/gpclient
|
|
||||||
test -x result/bin/gpauth
|
|
||||||
test -x result/bin/gpservice
|
|
||||||
test -x result/bin/gpgui-helper
|
|
||||||
test -x result/bin/gpgui
|
|
||||||
|
|
||||||
nixos-module:
|
|
||||||
name: nixos-module (${{ matrix.platform.system }}, ${{ matrix.nixpkgs }})
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
platform:
|
|
||||||
- runner: ubuntu-latest
|
|
||||||
system: x86_64-linux
|
|
||||||
- runner: ubuntu-24.04-arm
|
|
||||||
system: aarch64-linux
|
|
||||||
nixpkgs:
|
|
||||||
- nixos-25.11
|
|
||||||
- nixos-26.05
|
|
||||||
- nixpkgs-unstable
|
|
||||||
runs-on: ${{ matrix.platform.runner }}
|
|
||||||
steps:
|
|
||||||
- name: Checkout GlobalProtect-openconnect
|
|
||||||
uses: actions/checkout@v6
|
|
||||||
|
|
||||||
- name: Install Nix
|
|
||||||
uses: cachix/install-nix-action@v31
|
|
||||||
|
|
||||||
- name: Build package through host NixOS module
|
|
||||||
env:
|
|
||||||
NIXPKGS_URL: github:NixOS/nixpkgs/${{ matrix.nixpkgs }}
|
|
||||||
NIX_SYSTEM: ${{ matrix.platform.system }}
|
|
||||||
run: |
|
|
||||||
nix build \
|
|
||||||
--impure \
|
|
||||||
--extra-experimental-features "nix-command flakes" \
|
|
||||||
--print-build-logs \
|
|
||||||
--expr '
|
|
||||||
let
|
|
||||||
gp = builtins.getFlake (toString ./.);
|
|
||||||
hostNixpkgs =
|
|
||||||
builtins.getFlake (builtins.getEnv "NIXPKGS_URL");
|
|
||||||
|
|
||||||
hostSystem = hostNixpkgs.lib.nixosSystem {
|
|
||||||
system = builtins.getEnv "NIX_SYSTEM";
|
|
||||||
modules = [
|
|
||||||
gp.nixosModules.default
|
|
||||||
{
|
|
||||||
programs.globalprotect-openconnect.enable = true;
|
|
||||||
system.stateVersion = "25.11";
|
|
||||||
}
|
|
||||||
];
|
|
||||||
};
|
|
||||||
|
|
||||||
package =
|
|
||||||
hostSystem.config.programs.globalprotect-openconnect.package;
|
|
||||||
in
|
|
||||||
assert builtins.elem package
|
|
||||||
hostSystem.config.environment.systemPackages;
|
|
||||||
assert hostSystem.config.services.ayatana-indicators.enable;
|
|
||||||
package
|
|
||||||
'
|
|
||||||
|
|
||||||
- name: Inspect module package
|
|
||||||
run: |
|
|
||||||
test -x result/bin/gpclient
|
|
||||||
test -x result/bin/gpauth
|
|
||||||
test -x result/bin/gpservice
|
|
||||||
test -x result/bin/gpgui-helper
|
|
||||||
test -x result/bin/gpgui
|
|
||||||
@@ -24,8 +24,7 @@ permissions:
|
|||||||
contents: read
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
validate:
|
aur:
|
||||||
name: Validate AUR package
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container: archlinux:base-devel
|
container: archlinux:base-devel
|
||||||
defaults:
|
defaults:
|
||||||
@@ -33,6 +32,7 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
env:
|
env:
|
||||||
AUR_PACKAGE_DIR: packaging/aur/globalprotect-openconnect-git
|
AUR_PACKAGE_DIR: packaging/aur/globalprotect-openconnect-git
|
||||||
|
AUR_REPO: ssh://[email protected]/globalprotect-openconnect-git.git
|
||||||
steps:
|
steps:
|
||||||
- name: Install checkout tools
|
- name: Install checkout tools
|
||||||
run: pacman -Syu --noconfirm --needed git openssh
|
run: pacman -Syu --noconfirm --needed git openssh
|
||||||
@@ -102,42 +102,8 @@ jobs:
|
|||||||
cd "$AUR_PACKAGE_DIR"
|
cd "$AUR_PACKAGE_DIR"
|
||||||
runuser -u builder -- makepkg --noconfirm --clean --cleanbuild
|
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
|
- name: Configure SSH
|
||||||
|
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
|
||||||
env:
|
env:
|
||||||
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||||
run: |
|
run: |
|
||||||
@@ -152,6 +118,7 @@ jobs:
|
|||||||
ssh-keyscan -t rsa,ecdsa,ed25519 aur.archlinux.org > ~/.ssh/known_hosts
|
ssh-keyscan -t rsa,ecdsa,ed25519 aur.archlinux.org > ~/.ssh/known_hosts
|
||||||
|
|
||||||
- name: Publish to AUR
|
- name: Publish to AUR
|
||||||
|
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
|
||||||
env:
|
env:
|
||||||
GIT_SSH_COMMAND: ssh -i /github/home/.ssh/aur -o UserKnownHostsFile=/github/home/.ssh/known_hosts -o StrictHostKeyChecking=yes
|
GIT_SSH_COMMAND: ssh -i /github/home/.ssh/aur -o UserKnownHostsFile=/github/home/.ssh/known_hosts -o StrictHostKeyChecking=yes
|
||||||
run: |
|
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'
|
description: 'Rust version to use'
|
||||||
type: "string"
|
type: "string"
|
||||||
required: true
|
required: true
|
||||||
default: "1.91"
|
default: "1.89"
|
||||||
jobs:
|
jobs:
|
||||||
check:
|
check:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|||||||
@@ -272,6 +272,13 @@ jobs:
|
|||||||
uses: actions/download-artifact@v8
|
uses: actions/download-artifact@v8
|
||||||
with:
|
with:
|
||||||
path: gh-release
|
path: gh-release
|
||||||
|
- name: Generate release notes
|
||||||
|
id: release-notes
|
||||||
|
run: |
|
||||||
|
cd gh-release/gp
|
||||||
|
mkdir -p .build
|
||||||
|
scripts/release-notes.sh "${{ inputs.tag }}" > .build/release-notes.md
|
||||||
|
echo "path=$GITHUB_WORKSPACE/gh-release/gp/.build/release-notes.md" >> "$GITHUB_OUTPUT"
|
||||||
- name: Rename APK artifacts
|
- name: Rename APK artifacts
|
||||||
run: |
|
run: |
|
||||||
shopt -s nullglob
|
shopt -s nullglob
|
||||||
@@ -283,6 +290,7 @@ jobs:
|
|||||||
mv "$file" "${file%.apk}-aarch64.apk"
|
mv "$file" "${file%.apk}-aarch64.apk"
|
||||||
done
|
done
|
||||||
- name: Generate release asset checksums
|
- name: Generate release asset checksums
|
||||||
|
id: release-assets
|
||||||
run: |
|
run: |
|
||||||
cd gh-release/gp
|
cd gh-release/gp
|
||||||
mkdir -p .build
|
mkdir -p .build
|
||||||
@@ -295,20 +303,21 @@ jobs:
|
|||||||
digest=$(sha256sum "$file" | cut -d ' ' -f 1)
|
digest=$(sha256sum "$file" | cut -d ' ' -f 1)
|
||||||
printf '%s %s\n' "$digest" "$(basename "$file")"
|
printf '%s %s\n' "$digest" "$(basename "$file")"
|
||||||
done < .build/release-assets.txt > .build/release-assets.sha256
|
done < .build/release-assets.txt > .build/release-assets.sha256
|
||||||
|
{
|
||||||
|
echo 'files<<EOF'
|
||||||
|
cat .build/release-assets.txt
|
||||||
|
echo EOF
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
- name: Attest release assets
|
- name: Attest release assets
|
||||||
uses: actions/attest-build-provenance@v4
|
uses: actions/attest-build-provenance@v4
|
||||||
with:
|
with:
|
||||||
subject-checksums: gh-release/gp/.build/release-assets.sha256
|
subject-checksums: gh-release/gp/.build/release-assets.sha256
|
||||||
- name: Upload release assets
|
- name: Update release
|
||||||
env:
|
uses: softprops/action-gh-release@v1
|
||||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
with:
|
||||||
run: |
|
token: ${{ secrets.GH_PAT }}
|
||||||
mapfile -t files < gh-release/gp/.build/release-assets.txt
|
prerelease: ${{ contains(github.ref, 'snapshot') }}
|
||||||
if [[ "${{ inputs.tag }}" == "snapshot" ]]; then
|
fail_on_unmatched_files: true
|
||||||
for file in "${files[@]}"; do
|
tag_name: ${{ inputs.tag }}
|
||||||
gh release upload snapshot "$file" --clobber \
|
body_path: ${{ steps.release-notes.outputs.path }}
|
||||||
--repo yuezk/GlobalProtect-openconnect
|
files: ${{ steps.release-assets.outputs.files }}
|
||||||
done
|
|
||||||
else
|
|
||||||
gh-release/gp/scripts/upload-release-assets.sh "${{ inputs.tag }}" "${files[@]}"
|
|
||||||
fi
|
|
||||||
@@ -24,11 +24,6 @@ jobs:
|
|||||||
- name: Install Nix
|
- name: Install Nix
|
||||||
uses: cachix/install-nix-action@v31
|
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
|
- name: Update flake hashes
|
||||||
env:
|
env:
|
||||||
RELEASE_VERSION: ${{ inputs.version }}
|
RELEASE_VERSION: ${{ inputs.version }}
|
||||||
@@ -44,9 +39,7 @@ jobs:
|
|||||||
uses: actions/upload-artifact@v7
|
uses: actions/upload-artifact@v7
|
||||||
with:
|
with:
|
||||||
name: updated-flake
|
name: updated-flake
|
||||||
path: |
|
path: flake.nix
|
||||||
flake.nix
|
|
||||||
flake.lock
|
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
|
|
||||||
validate-nix-prebuilt:
|
validate-nix-prebuilt:
|
||||||
@@ -55,22 +48,22 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
runner:
|
include:
|
||||||
- ubuntu-latest
|
- runner: ubuntu-latest
|
||||||
- ubuntu-24.04-arm
|
nixpkgs: nixos-25.11
|
||||||
nixpkgs:
|
- runner: ubuntu-latest
|
||||||
- locked
|
nixpkgs: nixos-26.05
|
||||||
- nixos-25.11
|
|
||||||
- nixos-26.05
|
|
||||||
- nixpkgs-unstable
|
|
||||||
exclude:
|
|
||||||
- runner: ubuntu-24.04-arm
|
- 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 }})
|
name: validate-nix-prebuilt (${{ matrix.nixpkgs }}, ${{ matrix.runner }})
|
||||||
runs-on: ${{ matrix.runner }}
|
runs-on: ${{ matrix.runner }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout GlobalProtect-openconnect
|
- name: Checkout GlobalProtect-openconnect
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
- name: Download updated flake
|
- name: Download updated flake
|
||||||
uses: actions/download-artifact@v8
|
uses: actions/download-artifact@v8
|
||||||
@@ -82,19 +75,11 @@ jobs:
|
|||||||
uses: cachix/install-nix-action@v31
|
uses: cachix/install-nix-action@v31
|
||||||
|
|
||||||
- name: Build prebuilt Nix package
|
- name: Build prebuilt Nix package
|
||||||
env:
|
|
||||||
NIXPKGS: ${{ matrix.nixpkgs }}
|
|
||||||
run: |
|
run: |
|
||||||
if [[ "$NIXPKGS" == "locked" ]]; then
|
|
||||||
nix build .#prebuilt \
|
nix build .#prebuilt \
|
||||||
|
--override-input nixpkgs "github:NixOS/nixpkgs/${{ matrix.nixpkgs }}" \
|
||||||
--extra-experimental-features "nix-command flakes" \
|
--extra-experimental-features "nix-command flakes" \
|
||||||
--print-build-logs
|
--print-build-logs
|
||||||
else
|
|
||||||
nix build .#prebuilt \
|
|
||||||
--override-input nixpkgs "github:NixOS/nixpkgs/$NIXPKGS" \
|
|
||||||
--extra-experimental-features "nix-command flakes" \
|
|
||||||
--print-build-logs
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Inspect prebuilt Nix package
|
- name: Inspect prebuilt Nix package
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
.idea
|
.idea
|
||||||
.DS_Store
|
|
||||||
/target
|
/target
|
||||||
.pnpm-store
|
.pnpm-store
|
||||||
.env
|
.env
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
[submodule "crates/openconnect/deps/openconnect"]
|
[submodule "crates/openconnect/deps/openconnect"]
|
||||||
path = crates/openconnect/deps/openconnect
|
path = crates/openconnect/deps/openconnect
|
||||||
url = https://github.com/yuezk/openconnect.git
|
url = https://gitlab.com/openconnect/openconnect.git
|
||||||
branch = globalprotect
|
|
||||||
[submodule "crates/openconnect/deps/libxml2"]
|
[submodule "crates/openconnect/deps/libxml2"]
|
||||||
path = crates/openconnect/deps/libxml2
|
path = crates/openconnect/deps/libxml2
|
||||||
url = https://github.com/GNOME/libxml2.git
|
url = https://gitlab.gnome.org/GNOME/libxml2.git
|
||||||
@@ -10,8 +10,8 @@ members = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
rust-version = "1.91"
|
rust-version = "1.89"
|
||||||
version = "2.6.5"
|
version = "2.6.2"
|
||||||
authors = ["Kevin Yue <[email protected]>"]
|
authors = ["Kevin Yue <[email protected]>"]
|
||||||
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
@@ -31,7 +31,7 @@ env_logger = "0.11"
|
|||||||
is_executable = "1.0"
|
is_executable = "1.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
regex = "1"
|
regex = "1"
|
||||||
reqwest = { version = "0.13", default-features = false, features = ["native-tls", "charset", "http2", "system-proxy", "json", "form", "query"] }
|
reqwest = { version = "0.13", features = ["native-tls", "json", "form", "query"] }
|
||||||
openssl = "0.10"
|
openssl = "0.10"
|
||||||
pem = "3"
|
pem = "3"
|
||||||
xmltree = { version = "0.12", features = ["attribute-order"] }
|
xmltree = { version = "0.12", features = ["attribute-order"] }
|
||||||
@@ -59,20 +59,12 @@ which = "8"
|
|||||||
uuid = "1"
|
uuid = "1"
|
||||||
netdev = "0.40"
|
netdev = "0.40"
|
||||||
humantime = "2"
|
humantime = "2"
|
||||||
snow = { version = "0.10", default-features = false, features = ["std", "use-getrandom", "use-curve25519", "use-chacha20poly1305", "use-sha2"] }
|
|
||||||
zeroize = "1"
|
|
||||||
|
|
||||||
# Tauri dependencies
|
# Tauri dependencies
|
||||||
tauri = { version = "2" }
|
tauri = { version = "2" }
|
||||||
specta = "=2.0.0-rc.20"
|
specta = "=2.0.0-rc.20"
|
||||||
proptest = "1"
|
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]
|
[profile.release]
|
||||||
opt-level = 'z' # Optimize for size
|
opt-level = 'z' # Optimize for size
|
||||||
lto = true # Enable link-time optimization
|
lto = true # Enable link-time optimization
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ SHELL := /bin/sh
|
|||||||
INCLUDE_GUI ?= 0
|
INCLUDE_GUI ?= 0
|
||||||
CARGO ?= cargo
|
CARGO ?= cargo
|
||||||
DISABLE_RUST_TOOLCHAIN ?= 0
|
DISABLE_RUST_TOOLCHAIN ?= 0
|
||||||
RUST_VERSION ?= 1.91
|
RUST_VERSION ?= 1.89
|
||||||
IGNORE_RUST_VERSION ?= 0
|
IGNORE_RUST_VERSION ?= 0
|
||||||
|
|
||||||
VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')
|
VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')
|
||||||
@@ -64,9 +64,6 @@ endif
|
|||||||
|
|
||||||
default: build
|
default: build
|
||||||
|
|
||||||
dev-service:
|
|
||||||
./scripts/dev-service.sh
|
|
||||||
|
|
||||||
version:
|
version:
|
||||||
@echo $(VERSION)
|
@echo $(VERSION)
|
||||||
|
|
||||||
@@ -145,9 +142,6 @@ install:
|
|||||||
install -Dm755 target/release/gpclient $(DESTDIR)/usr/bin/gpclient
|
install -Dm755 target/release/gpclient $(DESTDIR)/usr/bin/gpclient
|
||||||
install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth
|
install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth
|
||||||
install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice
|
install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice
|
||||||
install -Dm755 target/release/gp-hip-runner $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner
|
|
||||||
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
|
# Install the GUI components if BUILD_GUI_HELPER is set to 1
|
||||||
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
|
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
|
||||||
@@ -169,14 +163,7 @@ install:
|
|||||||
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/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/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/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/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 -Dm644 packaging/files/usr/share/polkit-1/actions/com.yuezk.gpgui.policy $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
|
||||||
|
|
||||||
install-bsd:
|
install-bsd:
|
||||||
@@ -196,9 +183,6 @@ install-bsd:
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
install -d $(DESTDIR)$(PREFIX)/libexec/gpclient
|
install -d $(DESTDIR)$(PREFIX)/libexec/gpclient
|
||||||
install -m 755 target/release/gp-hip-runner $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-hip-runner
|
|
||||||
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/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 -m 755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)$(PREFIX)/libexec/gpclient/hipreport.sh
|
||||||
|
|
||||||
@@ -207,20 +191,11 @@ install-bsd:
|
|||||||
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps
|
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps
|
||||||
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps
|
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps
|
||||||
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps
|
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps
|
||||||
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256/apps
|
|
||||||
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256@2/apps
|
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/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/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/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/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/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 -d $(DESTDIR)$(PREFIX)/share/polkit-1/actions
|
||||||
install -m 644 packaging/bsd/com.yuezk.gpgui.policy $(DESTDIR)$(PREFIX)/share/polkit-1/actions/com.yuezk.gpgui.policy
|
install -m 644 packaging/bsd/com.yuezk.gpgui.policy $(DESTDIR)$(PREFIX)/share/polkit-1/actions/com.yuezk.gpgui.policy
|
||||||
|
|
||||||
@@ -241,7 +216,7 @@ bsd-gpgui-tarball:
|
|||||||
package-freebsd: BSD_FLAVOR=freebsd
|
package-freebsd: BSD_FLAVOR=freebsd
|
||||||
package-freebsd: clean-bsd-package
|
package-freebsd: clean-bsd-package
|
||||||
test -x "$(GPGUI_BINARY)"
|
test -x "$(GPGUI_BINARY)"
|
||||||
mkdir -p .build/freebsd/pkgroot .build/freebsd/artifacts .build/freebsd/metadata
|
mkdir -p .build/freebsd/pkgroot .build/freebsd/artifacts
|
||||||
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/freebsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
|
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/freebsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
|
||||||
find .build/freebsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/freebsd/pkgroot$(PREFIX)/||' | sort > .build/freebsd/PLIST
|
find .build/freebsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/freebsd/pkgroot$(PREFIX)/||' | sort > .build/freebsd/PLIST
|
||||||
freebsd_major=$$(freebsd-version -u | sed 's/\..*//'); \
|
freebsd_major=$$(freebsd-version -u | sed 's/\..*//'); \
|
||||||
@@ -252,9 +227,8 @@ package-freebsd: clean-bsd-package
|
|||||||
-e "s/@ABI@/FreeBSD:$$freebsd_major:$$freebsd_arch/g" \
|
-e "s/@ABI@/FreeBSD:$$freebsd_major:$$freebsd_arch/g" \
|
||||||
-e "s/@ARCH@/freebsd:$$freebsd_major:$$freebsd_arch/g" \
|
-e "s/@ARCH@/freebsd:$$freebsd_major:$$freebsd_arch/g" \
|
||||||
-e 's|@PREFIX@|$(PREFIX)|g' \
|
-e 's|@PREFIX@|$(PREFIX)|g' \
|
||||||
packaging/bsd/freebsd/MANIFEST.in > .build/freebsd/metadata/+MANIFEST
|
packaging/bsd/freebsd/MANIFEST.in > .build/freebsd/+MANIFEST
|
||||||
cp packaging/bsd/freebsd/POST_DEINSTALL .build/freebsd/metadata/+POST_DEINSTALL
|
pkg create -r .build/freebsd/pkgroot -M .build/freebsd/+MANIFEST -p .build/freebsd/PLIST -o .build/freebsd/artifacts
|
||||||
pkg create -r .build/freebsd/pkgroot -M .build/freebsd/metadata -p .build/freebsd/PLIST -o .build/freebsd/artifacts
|
|
||||||
freebsd_arch=$$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm64/aarch64/'); \
|
freebsd_arch=$$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm64/aarch64/'); \
|
||||||
mv .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION).pkg .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION)-freebsd-$$freebsd_arch.pkg
|
mv .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION).pkg .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION)-freebsd-$$freebsd_arch.pkg
|
||||||
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=freebsd GPGUI_BINARY="$(GPGUI_BINARY)"
|
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=freebsd GPGUI_BINARY="$(GPGUI_BINARY)"
|
||||||
@@ -266,20 +240,12 @@ package-openbsd: clean-bsd-package
|
|||||||
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/openbsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
|
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/openbsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
|
||||||
cp packaging/bsd/openbsd/COMMENT .build/openbsd/+COMMENT
|
cp packaging/bsd/openbsd/COMMENT .build/openbsd/+COMMENT
|
||||||
cp packaging/bsd/openbsd/DESC .build/openbsd/+DESC
|
cp packaging/bsd/openbsd/DESC .build/openbsd/+DESC
|
||||||
{ \
|
find .build/openbsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/openbsd/pkgroot$(PREFIX)/||' | sort > .build/openbsd/PLIST
|
||||||
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/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); \
|
comment=$$(cat .build/openbsd/+COMMENT); \
|
||||||
openbsd_arch=$$(uname -m | sed 's/x86_64/amd64/'); \
|
openbsd_arch=$$(uname -m | sed 's/x86_64/amd64/'); \
|
||||||
gnome_keyring_pkg=$$(pkg_info -e 'gnome-keyring-*' | sed 's/^inst://' | head -n 1); \
|
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); \
|
polkit_pkg=$$(pkg_info -e 'polkit-*' | sed 's/^inst://' | head -n 1); \
|
||||||
webkitgtk_pkg=$$(pkg_info -e 'webkitgtk41-*' | 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 \
|
pkg_create \
|
||||||
-B .build/openbsd/pkgroot \
|
-B .build/openbsd/pkgroot \
|
||||||
-D COMMENT="$$comment" \
|
-D COMMENT="$$comment" \
|
||||||
@@ -287,10 +253,8 @@ package-openbsd: clean-bsd-package
|
|||||||
-f .build/openbsd/PLIST \
|
-f .build/openbsd/PLIST \
|
||||||
-p $(PREFIX) \
|
-p $(PREFIX) \
|
||||||
-P x11/gnome/keyring:gnome-keyring-*:$$gnome_keyring_pkg \
|
-P x11/gnome/keyring:gnome-keyring-*:$$gnome_keyring_pkg \
|
||||||
-P x11/dbus:dbus-*:$$dbus_pkg \
|
|
||||||
-P sysutils/polkit:polkit-*:$$polkit_pkg \
|
-P sysutils/polkit:polkit-*:$$polkit_pkg \
|
||||||
-P www/webkitgtk4,webkitgtk41:webkitgtk41-*:$$webkitgtk_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
|
.build/openbsd/artifacts/$(PKG_NAME)-$(VERSION)-openbsd-$$openbsd_arch.tgz
|
||||||
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)"
|
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)"
|
||||||
|
|
||||||
@@ -300,14 +264,11 @@ uninstall:
|
|||||||
rm -f $(DESTDIR)/usr/bin/gpclient
|
rm -f $(DESTDIR)/usr/bin/gpclient
|
||||||
rm -f $(DESTDIR)/usr/bin/gpauth
|
rm -f $(DESTDIR)/usr/bin/gpauth
|
||||||
rm -f $(DESTDIR)/usr/bin/gpservice
|
rm -f $(DESTDIR)/usr/bin/gpservice
|
||||||
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner
|
|
||||||
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer
|
|
||||||
rm -f $(DESTDIR)/usr/bin/gpgui-helper
|
rm -f $(DESTDIR)/usr/bin/gpgui-helper
|
||||||
rm -f $(DESTDIR)/usr/bin/gpgui
|
rm -f $(DESTDIR)/usr/bin/gpgui
|
||||||
|
|
||||||
rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script
|
rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script
|
||||||
rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
|
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/pre-down.d/gpclient.down
|
||||||
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
|
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
|
||||||
@@ -316,23 +277,9 @@ uninstall:
|
|||||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
|
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/32x32/apps/gpgui.png
|
||||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/128x128/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/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)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
|
||||||
|
|
||||||
rm -f $(DESTDIR)/var/lib/gpclient/gpgui \
|
|
||||||
$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script \
|
|
||||||
$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script.metadata || \
|
|
||||||
echo "Warning: failed to remove gpclient runtime files" >&2
|
|
||||||
rmdir $(DESTDIR)/var/lib/gpclient/scripts 2>/dev/null || true
|
|
||||||
rmdir $(DESTDIR)/var/lib/gpclient 2>/dev/null || true
|
|
||||||
|
|
||||||
clean-debian:
|
clean-debian:
|
||||||
rm -rf .build/deb
|
rm -rf .build/deb
|
||||||
|
|
||||||
@@ -351,19 +298,18 @@ init-debian: clean-debian tarball
|
|||||||
|
|
||||||
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/control
|
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/control
|
||||||
|
|
||||||
# Remove the GUI dependencies if neither GUI component is included
|
# Remove the GUI dependencies if BUILD_GUI_HELPER is set to 0
|
||||||
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ]; then \
|
if [ $(BUILD_GUI_HELPER) -eq 0 ]; then \
|
||||||
sed -i "/libsecret-1-0/d" .build/deb/$(PKG)/debian/control; \
|
sed -i "/libsecret-1-0/d" .build/deb/$(PKG)/debian/control; \
|
||||||
sed -i "/libayatana-appindicator3-1/d" .build/deb/$(PKG)/debian/control; \
|
sed -i "/libayatana-appindicator3-1/d" .build/deb/$(PKG)/debian/control; \
|
||||||
sed -i "/gnome-keyring/d" .build/deb/$(PKG)/debian/control; \
|
sed -i "/gnome-keyring/d" .build/deb/$(PKG)/debian/control; \
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Remove WebKitGTK only if no included component needs it
|
# Remove the WebKitGTK build dependency only if neither gpauth webview auth nor gpgui-helper needs it
|
||||||
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ] && [ $(BUILD_WEBVIEW_AUTH) -eq 0 ]; then \
|
if [ $(BUILD_GUI_HELPER) -eq 0 ] && [ $(BUILD_WEBVIEW_AUTH) -eq 0 ]; then \
|
||||||
sed -i "/libwebkit2gtk-4.1-dev/d" .build/deb/$(PKG)/debian/control; \
|
sed -i "/libwebkit2gtk-4.1-dev/d" .build/deb/$(PKG)/debian/control; \
|
||||||
fi
|
fi
|
||||||
|
|
||||||
sed -i "s/@INCLUDE_GUI@/$(INCLUDE_GUI)/g" .build/deb/$(PKG)/debian/rules
|
|
||||||
sed -i "s/@BUILD_GUI_HELPER@/$(BUILD_GUI_HELPER)/g" .build/deb/$(PKG)/debian/rules
|
sed -i "s/@BUILD_GUI_HELPER@/$(BUILD_GUI_HELPER)/g" .build/deb/$(PKG)/debian/rules
|
||||||
sed -i "s/@BUILD_WEBVIEW_AUTH@/$(BUILD_WEBVIEW_AUTH)/g" .build/deb/$(PKG)/debian/rules
|
sed -i "s/@BUILD_WEBVIEW_AUTH@/$(BUILD_WEBVIEW_AUTH)/g" .build/deb/$(PKG)/debian/rules
|
||||||
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/rules
|
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/rules
|
||||||
@@ -440,7 +386,6 @@ init-pkgbuild: clean-pkgbuild tarball
|
|||||||
|
|
||||||
cp .build/tarball/${PKG}.tar.gz .build/pkgbuild
|
cp .build/tarball/${PKG}.tar.gz .build/pkgbuild
|
||||||
cp packaging/pkgbuild/PKGBUILD.in .build/pkgbuild/PKGBUILD
|
cp packaging/pkgbuild/PKGBUILD.in .build/pkgbuild/PKGBUILD
|
||||||
cp packaging/pkgbuild/gp.install .build/pkgbuild/gp.install
|
|
||||||
|
|
||||||
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/pkgbuild/PKGBUILD
|
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/pkgbuild/PKGBUILD
|
||||||
sed -i "s/@VERSION@/$(VERSION)/g" .build/pkgbuild/PKGBUILD
|
sed -i "s/@VERSION@/$(VERSION)/g" .build/pkgbuild/PKGBUILD
|
||||||
@@ -457,7 +402,6 @@ init-apk: clean-apk tarball
|
|||||||
|
|
||||||
cp .build/tarball/${PKG}.tar.gz .build/apk
|
cp .build/tarball/${PKG}.tar.gz .build/apk
|
||||||
cp packaging/apk/APKBUILD.in .build/apk/APKBUILD
|
cp packaging/apk/APKBUILD.in .build/apk/APKBUILD
|
||||||
cp packaging/apk/post-deinstall .build/apk/$(PKG_NAME).post-deinstall
|
|
||||||
|
|
||||||
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/apk/APKBUILD
|
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/apk/APKBUILD
|
||||||
sed -i "s/@VERSION@/$(VERSION)/g" .build/apk/APKBUILD
|
sed -i "s/@VERSION@/$(VERSION)/g" .build/apk/APKBUILD
|
||||||
@@ -465,17 +409,6 @@ init-apk: clean-apk tarball
|
|||||||
checksum=$$(sha512sum .build/apk/${PKG}.tar.gz | cut -d' ' -f1); \
|
checksum=$$(sha512sum .build/apk/${PKG}.tar.gz | cut -d' ' -f1); \
|
||||||
sed -i "s/@SHA512@/$$checksum/g" .build/apk/APKBUILD
|
sed -i "s/@SHA512@/$$checksum/g" .build/apk/APKBUILD
|
||||||
|
|
||||||
# Remove the GUI dependencies if neither GUI component is included
|
|
||||||
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ]; then \
|
|
||||||
sed -i "/^\tlibayatana-appindicator$$/d" .build/apk/APKBUILD; \
|
|
||||||
sed -i "/^\tlibsecret$$/d" .build/apk/APKBUILD; \
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Remove WebKitGTK only if no included component needs it
|
|
||||||
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ] && [ $(BUILD_WEBVIEW_AUTH) -eq 0 ]; then \
|
|
||||||
sed -i "/^\twebkit2gtk-4.1$$/d" .build/apk/APKBUILD; \
|
|
||||||
fi
|
|
||||||
|
|
||||||
apk: init-apk
|
apk: init-apk
|
||||||
cd .build/apk && abuild -r -P "$(CURDIR)/.build/apk/packages"
|
cd .build/apk && abuild -r -P "$(CURDIR)/.build/apk/packages"
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ A modern GlobalProtect VPN client for Linux, built on OpenConnect with full supp
|
|||||||
- [Other Distributions](#other-distributions)
|
- [Other Distributions](#other-distributions)
|
||||||
- [Building from Source](#building-from-source)
|
- [Building from Source](#building-from-source)
|
||||||
- [Frequently Asked Questions](#frequently-asked-questions)
|
- [Frequently Asked Questions](#frequently-asked-questions)
|
||||||
- [NetworkManager Integration](#networkmanager-integration)
|
|
||||||
- [License](#license)
|
- [License](#license)
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
@@ -56,16 +55,12 @@ Commands:
|
|||||||
connect Connect to a portal server
|
connect Connect to a portal server
|
||||||
disconnect Disconnect from the server
|
disconnect Disconnect from the server
|
||||||
launch-gui Launch the GUI
|
launch-gui Launch the GUI
|
||||||
hip Generate HIP report
|
|
||||||
help Print this message or the help of the given subcommand(s)
|
help Print this message or the help of the given subcommand(s)
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
--fix-openssl Uses extended compatibility mode for OpenSSL operations to support a broader range of systems and formats.
|
--fix-openssl Get around the OpenSSL 'unsafe legacy renegotiation' error
|
||||||
--ignore-tls-errors Ignore the TLS errors
|
--ignore-tls-errors Ignore TLS errors
|
||||||
--log-format <LOG_FORMAT> Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text. [default: text] [possible values: text, json]
|
-h, --help Print help
|
||||||
-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
|
-V, --version Print version
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -77,7 +72,7 @@ For browser-based authentication with the CLI:
|
|||||||
|
|
||||||
**Method 1:** Using sudo with environment preservation:
|
**Method 1:** Using sudo with environment preservation:
|
||||||
```bash
|
```bash
|
||||||
sudo gpclient connect --browser <portal>
|
sudo -E gpclient connect --browser <portal>
|
||||||
```
|
```
|
||||||
|
|
||||||
**Method 2:** Using authentication piping:
|
**Method 2:** Using authentication piping:
|
||||||
@@ -205,26 +200,6 @@ sudo apk add --allow-untrusted globalprotect-openconnect-*.apk
|
|||||||
|
|
||||||
The package uses Alpine's native musl build. Make sure the `community` repository is enabled so GUI dependencies such as `webkit2gtk-4.1`, `libsecret`, and `libayatana-appindicator` can be resolved. GUI-launched connections use polkit, and VPN tunnel creation requires `/dev/net/tun`.
|
The package uses Alpine's native musl build. Make sure the `community` repository is enabled so GUI dependencies such as `webkit2gtk-4.1`, `libsecret`, and `libayatana-appindicator` can be resolved. GUI-launched connections use polkit, and VPN tunnel creation requires `/dev/net/tun`.
|
||||||
|
|
||||||
### FreeBSD
|
|
||||||
|
|
||||||
Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo pkg install ./globalprotect-openconnect-*-freebsd-*.pkg
|
|
||||||
```
|
|
||||||
|
|
||||||
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
|
||||||
|
|
||||||
### OpenBSD
|
|
||||||
|
|
||||||
Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
doas pkg_add -D unsigned ./globalprotect-openconnect-*-openbsd-*.tgz
|
|
||||||
```
|
|
||||||
|
|
||||||
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
|
||||||
|
|
||||||
### Gentoo
|
### Gentoo
|
||||||
|
|
||||||
Available via the `guru` and `lamdness` overlays:
|
Available via the `guru` and `lamdness` overlays:
|
||||||
@@ -241,10 +216,7 @@ This repository includes a flake for NixOS integration.
|
|||||||
|
|
||||||
#### Installation Steps
|
#### Installation Steps
|
||||||
|
|
||||||
Add the flake input and NixOS module to your `flake.nix`:
|
Add the flake input and package 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.
|
|
||||||
|
|
||||||
```nix
|
```nix
|
||||||
{
|
{
|
||||||
@@ -263,11 +235,11 @@ GlobalProtect GUI and the system use the same Nixpkgs dependency versions.
|
|||||||
|
|
||||||
modules = [
|
modules = [
|
||||||
./configuration.nix
|
./configuration.nix
|
||||||
globalprotect-openconnect.nixosModules.default
|
|
||||||
{
|
{
|
||||||
programs.globalprotect-openconnect.enable = true;
|
services.ayatana-indicators.enable = true;
|
||||||
|
|
||||||
environment.systemPackages = [
|
environment.systemPackages = [
|
||||||
|
globalprotect-openconnect.packages.${system}.default
|
||||||
nixpkgs.legacyPackages.${system}.gnomeExtensions.appindicator
|
nixpkgs.legacyPackages.${system}.gnomeExtensions.appindicator
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -290,13 +262,9 @@ After logging back in to GNOME, enable AppIndicator support if needed:
|
|||||||
gnome-extensions enable [email protected]
|
gnome-extensions enable [email protected]
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Official Docker Image
|
### Official Docker Image
|
||||||
|
|
||||||
The [official Docker image](https://hub.docker.com/r/yuezk/globalprotect-openconnect) provides the CLI tools on Alpine Linux:
|
The official Docker image provides the CLI tools on Alpine Linux:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker pull yuezk/globalprotect-openconnect:<version>
|
docker pull yuezk/globalprotect-openconnect:<version>
|
||||||
@@ -320,12 +288,6 @@ docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
|||||||
connect <portal> --browser remote
|
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:
|
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -427,7 +389,7 @@ This project includes a DevContainer configuration that provides a consistent, r
|
|||||||
|
|
||||||
#### Prerequisites
|
#### 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/)
|
- [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
|
- 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)
|
- `pkexec` and `gnome-keyring` (or `pam_kwallet` on KDE)
|
||||||
@@ -486,11 +448,6 @@ sudo -E gpclient connect <portal>
|
|||||||
|
|
||||||
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||||
|
|
||||||
## 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
|
|
||||||
- [jdpipe/networkmanager-gpclient](https://github.com/jdpipe/networkmanager-gpclient) – NetworkManager VPN plugin that uses `gpclient`
|
|
||||||
|
|
||||||
## Licensing
|
## Licensing
|
||||||
|
|
||||||
### Trial and Pricing
|
### Trial and Pricing
|
||||||
@@ -505,10 +462,8 @@ This project consists of multiple components, each with its own license:
|
|||||||
| Component | Type | License |
|
| Component | Type | License |
|
||||||
|-----------|------|---------|
|
|-----------|------|---------|
|
||||||
| [gpapi](./crates/gpapi) | Crate | [MIT](./crates/gpapi/LICENSE) |
|
| [gpapi](./crates/gpapi) | Crate | [MIT](./crates/gpapi/LICENSE) |
|
||||||
| [openconnect](./crates/openconnect) | Rust wrapper crate | [MIT](./crates/openconnect/LICENSE) |
|
| [openconnect](./crates/openconnect) | Crate | [GPL-3.0](./crates/openconnect/LICENSE) |
|
||||||
| [upstream OpenConnect](./crates/openconnect/deps/openconnect) | C library | [LGPL-2.1](./crates/openconnect/deps/openconnect/COPYING.LGPL) |
|
| [common](./crates/common) | Crate | [GPL-3.0](./crates/common/LICENSE) |
|
||||||
| [common](./crates/common) | Crate | [MIT](./crates/common/LICENSE) |
|
|
||||||
| [browser-launcher](./crates/browser-launcher) | Crate | [MIT](./crates/browser-launcher/LICENSE) |
|
|
||||||
| [auth](./crates/auth) | Crate | [GPL-3.0](./crates/auth/LICENSE) |
|
| [auth](./crates/auth) | Crate | [GPL-3.0](./crates/auth/LICENSE) |
|
||||||
| [gpservice](./apps/gpservice) | Application | [GPL-3.0](./apps/gpservice/LICENSE) |
|
| [gpservice](./apps/gpservice) | Application | [GPL-3.0](./apps/gpservice/LICENSE) |
|
||||||
| [gpclient](./apps/gpclient) | Application | [GPL-3.0](./apps/gpclient/LICENSE) |
|
| [gpclient](./apps/gpclient) | Application | [GPL-3.0](./apps/gpclient/LICENSE) |
|
||||||
|
|||||||
@@ -11,13 +11,14 @@ tauri-build = { version = "2", features = [], optional = true }
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
common = { path = "../../crates/common" }
|
common = { path = "../../crates/common" }
|
||||||
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
|
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
|
||||||
|
|
||||||
auth = { path = "../../crates/auth", features = ["browser-auth"] }
|
auth = { path = "../../crates/auth", features = ["browser-auth"] }
|
||||||
|
|
||||||
# Shared dependencies
|
# Shared dependencies
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
clap.workspace = true
|
clap.workspace = true
|
||||||
|
env_logger.workspace = true
|
||||||
log.workspace = true
|
log.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||||
@@ -33,4 +34,3 @@ tauri = { workspace = true, optional = true }
|
|||||||
[features]
|
[features]
|
||||||
default = ["webview-auth"]
|
default = ["webview-auth"]
|
||||||
webview-auth = ["auth/webview-auth", "dep:tauri", "dep:tauri-build"]
|
webview-auth = ["auth/webview-auth", "dep:tauri", "dep:tauri-build"]
|
||||||
release-devtools = ["auth/release-devtools"]
|
|
||||||
@@ -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>
|
|
||||||
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 27 KiB After Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 2.5 KiB |
|
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 57 KiB After Width: | Height: | Size: 83 KiB |
@@ -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(())
|
|
||||||
}
|
|
||||||
@@ -1,22 +1,14 @@
|
|||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
use auth::forward_auth_callback;
|
|
||||||
use auth::{BrowserAuthenticator, auth_prelogin};
|
use auth::{BrowserAuthenticator, auth_prelogin};
|
||||||
use clap::Parser;
|
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::{
|
use gpapi::{
|
||||||
auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult},
|
auth::{SamlAuthData, SamlAuthResult},
|
||||||
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
|
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
|
||||||
gp_params::GpParams,
|
gp_params::GpParams,
|
||||||
log_format::LogFormat,
|
|
||||||
os_profile::{ClientOs, OsProfile},
|
os_profile::{ClientOs, OsProfile},
|
||||||
utils::{normalize_server, openssl},
|
utils::{normalize_server, openssl},
|
||||||
};
|
};
|
||||||
use log::info;
|
use log::info;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::net::IpAddr;
|
|
||||||
use tempfile::NamedTempFile;
|
use tempfile::NamedTempFile;
|
||||||
|
|
||||||
const VERSION: &str = concat!(
|
const VERSION: &str = concat!(
|
||||||
@@ -33,8 +25,6 @@ const VERSION: &str = concat!(
|
|||||||
version = VERSION,
|
version = VERSION,
|
||||||
author,
|
author,
|
||||||
about = "The authentication component for the GlobalProtect VPN client, supports the SSO authentication method.",
|
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 = "\
|
help_template = "\
|
||||||
{before-help}{name} {version}
|
{before-help}{name} {version}
|
||||||
{author}
|
{author}
|
||||||
@@ -49,12 +39,8 @@ See 'gpauth -h' for more information.
|
|||||||
"
|
"
|
||||||
)]
|
)]
|
||||||
struct Cli {
|
struct Cli {
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
#[arg(help = "The portal server to authenticate")]
|
||||||
#[command(subcommand)]
|
server: String,
|
||||||
command: Option<CliCommand>,
|
|
||||||
|
|
||||||
#[arg(required = true, help = "The portal server to authenticate")]
|
|
||||||
server: Option<String>,
|
|
||||||
|
|
||||||
#[arg(long, help = "Treating the server as a gateway")]
|
#[arg(long, help = "Treating the server as a gateway")]
|
||||||
gateway: bool,
|
gateway: bool,
|
||||||
@@ -90,29 +76,18 @@ struct Cli {
|
|||||||
#[arg(long, help = "Ignore TLS errors")]
|
#[arg(long, help = "Ignore TLS errors")]
|
||||||
ignore_tls_errors: bool,
|
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")]
|
#[cfg(feature = "webview-auth")]
|
||||||
#[arg(long, help = "Use the default browser for authentication")]
|
#[arg(long, help = "Use the default browser for authentication")]
|
||||||
default_browser: bool,
|
default_browser: bool,
|
||||||
|
|
||||||
#[arg(
|
#[arg(
|
||||||
long,
|
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",
|
default_missing_value = "auto",
|
||||||
num_args=0..=1
|
num_args=0..=1
|
||||||
)]
|
)]
|
||||||
browser: Option<String>,
|
browser: Option<String>,
|
||||||
|
|
||||||
#[arg(long, help = "Listen on this IP address when using '--browser remote'")]
|
|
||||||
browser_listen: Option<IpAddr>,
|
|
||||||
|
|
||||||
#[cfg(feature = "webview-auth")]
|
#[cfg(feature = "webview-auth")]
|
||||||
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
|
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
|
||||||
hidpi: bool,
|
hidpi: bool,
|
||||||
@@ -121,28 +96,10 @@ struct Cli {
|
|||||||
#[arg(long, help = "Clean the cache of the embedded browser")]
|
#[arg(long, help = "Clean the cache of the embedded browser")]
|
||||||
pub clean: bool,
|
pub clean: bool,
|
||||||
|
|
||||||
#[cfg(feature = "webview-auth")]
|
|
||||||
#[arg(long, help = "Set the embedded authentication window title")]
|
|
||||||
window_title: Option<String>,
|
|
||||||
|
|
||||||
#[cfg(feature = "webview-auth")]
|
|
||||||
#[arg(long, value_enum, default_value_t = AuthWindowTheme::default(), help = "Set the embedded authentication window appearance")]
|
|
||||||
window_theme: AuthWindowTheme,
|
|
||||||
|
|
||||||
#[command(flatten)]
|
#[command(flatten)]
|
||||||
verbose: InfoLevelVerbosity,
|
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 {
|
impl Args for Cli {
|
||||||
fn fix_openssl(&self) -> bool {
|
fn fix_openssl(&self) -> bool {
|
||||||
self.fix_openssl
|
self.fix_openssl
|
||||||
@@ -151,10 +108,6 @@ impl Args for Cli {
|
|||||||
fn ignore_tls_errors(&self) -> bool {
|
fn ignore_tls_errors(&self) -> bool {
|
||||||
self.ignore_tls_errors
|
self.ignore_tls_errors
|
||||||
}
|
}
|
||||||
|
|
||||||
fn log_format(&self) -> LogFormat {
|
|
||||||
self.log_format
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Cli {
|
impl Cli {
|
||||||
@@ -173,19 +126,13 @@ impl Cli {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn run(&self) -> anyhow::Result<()> {
|
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 {
|
if self.ignore_tls_errors {
|
||||||
info!("TLS errors will be ignored");
|
info!("TLS errors will be ignored");
|
||||||
}
|
}
|
||||||
|
|
||||||
let openssl_conf = self.prepare_env()?;
|
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();
|
let gp_params = self.build_gp_params();
|
||||||
info!(
|
info!(
|
||||||
"gpauth auth host-id: {}",
|
"gpauth auth host-id: {}",
|
||||||
@@ -208,7 +155,7 @@ impl Cli {
|
|||||||
|
|
||||||
if let Some(browser) = browser {
|
if let Some(browser) = browser {
|
||||||
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
|
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;
|
let auth_result = authenticator.authenticate().await;
|
||||||
|
|
||||||
print_auth_result(auth_result, Some(&auth_host_id));
|
print_auth_result(auth_result, Some(&auth_host_id));
|
||||||
@@ -219,16 +166,7 @@ impl Cli {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "webview-auth")]
|
#[cfg(feature = "webview-auth")]
|
||||||
crate::webview_auth::authenticate(
|
crate::webview_auth::authenticate(server, gp_params, auth_request, self.clean, openssl_conf).await?;
|
||||||
server,
|
|
||||||
gp_params,
|
|
||||||
auth_request,
|
|
||||||
self.clean,
|
|
||||||
self.window_title.clone(),
|
|
||||||
self.window_theme,
|
|
||||||
openssl_conf,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -268,26 +206,14 @@ impl Cli {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn init_logger(cli: &Cli) {
|
fn init_logger(cli: &Cli) {
|
||||||
let Some(level) = cli.verbose.log_level_filter().to_level() else {
|
env_logger::builder()
|
||||||
log::set_max_level(log::LevelFilter::Off);
|
.filter_level(cli.verbose.log_level_filter())
|
||||||
return;
|
.init();
|
||||||
};
|
|
||||||
|
|
||||||
gpapi::logger::init(level, "com.yuezk.gpgui", "gpauth", cli.log_format);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn run() {
|
pub async fn run() {
|
||||||
let cli = Cli::parse();
|
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);
|
init_logger(&cli);
|
||||||
info!("gpauth started: {}", VERSION);
|
info!("gpauth started: {}", VERSION);
|
||||||
|
|
||||||
@@ -306,7 +232,6 @@ pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Opt
|
|||||||
};
|
};
|
||||||
SamlAuthResult::Success(auth_data)
|
SamlAuthResult::Success(auth_data)
|
||||||
}
|
}
|
||||||
Err(err) if err.downcast_ref::<AuthenticationCancelled>().is_some() => SamlAuthResult::Cancelled,
|
|
||||||
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
|
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -317,24 +242,6 @@ pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Opt
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn os_defaults_to_runtime_os() {
|
fn os_defaults_to_runtime_os() {
|
||||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com"]).expect("gpauth args should parse");
|
let cli = Cli::try_parse_from(["gpauth", "portal.example.com"]).expect("gpauth args should parse");
|
||||||
@@ -342,23 +249,6 @@ mod tests {
|
|||||||
assert_eq!(cli.os, Os::default());
|
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]
|
#[test]
|
||||||
fn host_id_arg_sets_profile_host_id_seed() {
|
fn host_id_arg_sets_profile_host_id_seed() {
|
||||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--host-id", "host-seed"])
|
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--host-id", "host-seed"])
|
||||||
@@ -393,21 +283,6 @@ mod tests {
|
|||||||
assert!(cli.external_browser_requested());
|
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]
|
#[test]
|
||||||
fn client_version_arg_sets_profile_client_version() {
|
fn client_version_arg_sets_profile_client_version() {
|
||||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--client-version", "legacy-client"])
|
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--client-version", "legacy-client"])
|
||||||
@@ -436,21 +311,4 @@ mod tests {
|
|||||||
assert_eq!(cli.sslkey.as_deref(), Some("/tmp/client.key"));
|
assert_eq!(cli.sslkey.as_deref(), Some("/tmp/client.key"));
|
||||||
assert_eq!(cli.key_password.as_deref(), Some("secret"));
|
assert_eq!(cli.key_password.as_deref(), Some("secret"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "webview-auth")]
|
|
||||||
#[test]
|
|
||||||
fn auth_window_options_parse() {
|
|
||||||
let cli = Cli::try_parse_from([
|
|
||||||
"gpauth",
|
|
||||||
"portal.example.com",
|
|
||||||
"--window-title",
|
|
||||||
"GP Connect Login",
|
|
||||||
"--window-theme",
|
|
||||||
"dark",
|
|
||||||
])
|
|
||||||
.expect("gpauth window options should parse");
|
|
||||||
|
|
||||||
assert_eq!(cli.window_title.as_deref(), Some("GP Connect Login"));
|
|
||||||
assert_eq!(cli.window_theme, AuthWindowTheme::Dark);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -2,34 +2,10 @@
|
|||||||
|
|
||||||
mod cli;
|
mod cli;
|
||||||
|
|
||||||
#[cfg(all(target_os = "macos", feature = "webview-auth"))]
|
|
||||||
mod callback_app;
|
|
||||||
|
|
||||||
#[cfg(feature = "webview-auth")]
|
|
||||||
mod tauri_context;
|
|
||||||
|
|
||||||
#[cfg(feature = "webview-auth")]
|
#[cfg(feature = "webview-auth")]
|
||||||
mod webview_auth;
|
mod webview_auth;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn 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;
|
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!()
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
use auth::{WebviewAuthenticator, apply_auth_theme};
|
use auth::WebviewAuthenticator;
|
||||||
use gpapi::{auth::AuthWindowTheme, gp_params::GpParams};
|
use gpapi::gp_params::GpParams;
|
||||||
use log::info;
|
use log::info;
|
||||||
use tauri::RunEvent;
|
use tauri::RunEvent;
|
||||||
use tempfile::NamedTempFile;
|
use tempfile::NamedTempFile;
|
||||||
@@ -11,27 +11,19 @@ pub async fn authenticate(
|
|||||||
gp_params: GpParams,
|
gp_params: GpParams,
|
||||||
auth_request: String,
|
auth_request: String,
|
||||||
clean: bool,
|
clean: bool,
|
||||||
window_title: Option<String>,
|
|
||||||
window_theme: AuthWindowTheme,
|
|
||||||
mut openssl_conf: Option<NamedTempFile>,
|
mut openssl_conf: Option<NamedTempFile>,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
|
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
|
||||||
|
|
||||||
tauri::Builder::default()
|
tauri::Builder::default()
|
||||||
.setup(move |app| {
|
.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();
|
let app_handle = app.handle().clone();
|
||||||
|
|
||||||
tauri::async_runtime::spawn(async move {
|
tauri::async_runtime::spawn(async move {
|
||||||
let authenticator = WebviewAuthenticator::new(&server, &gp_params)
|
let authenticator = WebviewAuthenticator::new(&server, &gp_params)
|
||||||
.with_auth_request(&auth_request)
|
.with_auth_request(&auth_request)
|
||||||
.with_webview_user_agent(gp_params.os_profile().webview_user_agent())
|
.with_webview_user_agent(gp_params.os_profile().webview_user_agent())
|
||||||
.with_clean(clean)
|
.with_clean(clean);
|
||||||
.with_window_title(window_title.as_deref().unwrap_or("GlobalProtect Login"))
|
|
||||||
.with_window_theme(window_theme);
|
|
||||||
|
|
||||||
let auth_result = authenticator.authenticate(&app_handle).await;
|
let auth_result = authenticator.authenticate(&app_handle).await;
|
||||||
print_auth_result(auth_result, Some(&auth_host_id));
|
print_auth_result(auth_result, Some(&auth_host_id));
|
||||||
@@ -42,7 +34,7 @@ pub async fn authenticate(
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.build(crate::tauri_context::get())?
|
.build(tauri::generate_context!())?
|
||||||
.run(move |_app_handle, event| {
|
.run(move |_app_handle, event| {
|
||||||
if let RunEvent::Exit = event {
|
if let RunEvent::Exit = event {
|
||||||
if let Some(file) = openssl_conf.take() {
|
if let Some(file) = openssl_conf.take() {
|
||||||
|
|||||||
@@ -6,14 +6,11 @@
|
|||||||
"beforeBuildCommand": ""
|
"beforeBuildCommand": ""
|
||||||
},
|
},
|
||||||
"identifier": "com.yuezk.gpauth",
|
"identifier": "com.yuezk.gpauth",
|
||||||
"productName": "GP Connect Login",
|
"productName": "gpauth",
|
||||||
"app": {
|
"app": {
|
||||||
"withGlobalTauri": false,
|
"withGlobalTauri": false,
|
||||||
"security": {
|
"security": {
|
||||||
"csp": null
|
"csp": null
|
||||||
}
|
}
|
||||||
},
|
|
||||||
"bundle": {
|
|
||||||
"icon": ["icons/icon.png"]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,10 +9,11 @@ license.workspace = true
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
common = { path = "../../crates/common" }
|
common = { path = "../../crates/common" }
|
||||||
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
|
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
|
||||||
gphip = { path = "../../crates/gphip" }
|
|
||||||
openconnect = { path = "../../crates/openconnect" }
|
openconnect = { path = "../../crates/openconnect" }
|
||||||
|
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
|
askama.workspace = true
|
||||||
|
chrono.workspace = true
|
||||||
clap.workspace = true
|
clap.workspace = true
|
||||||
env_logger.workspace = true
|
env_logger.workspace = true
|
||||||
inquire = "0.9"
|
inquire = "0.9"
|
||||||
@@ -21,12 +22,15 @@ tokio = { workspace = true, features = ["rt-multi-thread"] }
|
|||||||
sysinfo.workspace = true
|
sysinfo.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
|
serde_urlencoded.workspace = true
|
||||||
whoami.workspace = true
|
whoami.workspace = true
|
||||||
tempfile.workspace = true
|
tempfile.workspace = true
|
||||||
reqwest.workspace = true
|
reqwest.workspace = true
|
||||||
directories.workspace = true
|
directories.workspace = true
|
||||||
compile-time.workspace = true
|
compile-time.workspace = true
|
||||||
uzers.workspace = true
|
netdev.workspace = true
|
||||||
|
xmltree.workspace = true
|
||||||
|
uuid = { workspace = true, features = ["v5"] }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["webview-auth"]
|
default = ["webview-auth"]
|
||||||
|
|||||||
@@ -1,13 +1,9 @@
|
|||||||
use std::{
|
use std::{env::temp_dir, fs::File, str::FromStr};
|
||||||
path::{Path, PathBuf},
|
|
||||||
str::FromStr,
|
|
||||||
};
|
|
||||||
|
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
clap::{Args, InfoLevelVerbosity, handle_error},
|
clap::{Args, InfoLevelVerbosity, handle_error},
|
||||||
log_format::{LogFormat, write_json_record},
|
|
||||||
utils::openssl,
|
utils::openssl,
|
||||||
};
|
};
|
||||||
use log::info;
|
use log::info;
|
||||||
@@ -35,9 +31,7 @@ const VERSION: &str = concat!(
|
|||||||
pub(crate) struct SharedArgs<'a> {
|
pub(crate) struct SharedArgs<'a> {
|
||||||
pub(crate) fix_openssl: bool,
|
pub(crate) fix_openssl: bool,
|
||||||
pub(crate) ignore_tls_errors: bool,
|
pub(crate) ignore_tls_errors: bool,
|
||||||
pub(crate) lock_file: &'a Path,
|
|
||||||
pub(crate) verbose: &'a InfoLevelVerbosity,
|
pub(crate) verbose: &'a InfoLevelVerbosity,
|
||||||
pub(crate) log_format: LogFormat,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
@@ -81,21 +75,6 @@ struct Cli {
|
|||||||
fix_openssl: bool,
|
fix_openssl: bool,
|
||||||
#[arg(long, help = "Ignore the TLS errors")]
|
#[arg(long, help = "Ignore the TLS errors")]
|
||||||
ignore_tls_errors: bool,
|
ignore_tls_errors: bool,
|
||||||
#[arg(
|
|
||||||
long,
|
|
||||||
global = true,
|
|
||||||
default_value = GP_CLIENT_LOCK_FILE,
|
|
||||||
help = "Path to the gpclient PID lock file"
|
|
||||||
)]
|
|
||||||
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)]
|
#[command(flatten)]
|
||||||
verbose: InfoLevelVerbosity,
|
verbose: InfoLevelVerbosity,
|
||||||
@@ -109,24 +88,11 @@ impl Args for Cli {
|
|||||||
fn ignore_tls_errors(&self) -> bool {
|
fn ignore_tls_errors(&self) -> bool {
|
||||||
self.ignore_tls_errors
|
self.ignore_tls_errors
|
||||||
}
|
}
|
||||||
|
|
||||||
fn log_format(&self) -> LogFormat {
|
|
||||||
self.log_format
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Cli {
|
impl Cli {
|
||||||
fn can_run_alongside_client(&self) -> bool {
|
|
||||||
match &self.command {
|
|
||||||
CliCommand::Disconnect(_) => true,
|
|
||||||
CliCommand::Hip(_) => true,
|
|
||||||
CliCommand::LaunchGui(args) => args.is_auth_callback(),
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_running(&self) -> bool {
|
async fn is_running(&self) -> bool {
|
||||||
let Ok(c) = fs::read_to_string(&self.lock_file).await else {
|
let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE).await else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -155,7 +121,7 @@ impl Cli {
|
|||||||
|
|
||||||
async fn run(&self) -> anyhow::Result<()> {
|
async fn run(&self) -> anyhow::Result<()> {
|
||||||
// check if an instance is running
|
// 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");
|
bail!("Another instance of the client is already running");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,9 +131,7 @@ impl Cli {
|
|||||||
let shared_args = SharedArgs {
|
let shared_args = SharedArgs {
|
||||||
fix_openssl: self.fix_openssl,
|
fix_openssl: self.fix_openssl,
|
||||||
ignore_tls_errors: self.ignore_tls_errors,
|
ignore_tls_errors: self.ignore_tls_errors,
|
||||||
lock_file: &self.lock_file,
|
|
||||||
verbose: &self.verbose,
|
verbose: &self.verbose,
|
||||||
log_format: self.log_format,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if self.ignore_tls_errors {
|
if self.ignore_tls_errors {
|
||||||
@@ -176,30 +140,35 @@ impl Cli {
|
|||||||
|
|
||||||
match &self.command {
|
match &self.command {
|
||||||
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await,
|
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await,
|
||||||
CliCommand::Disconnect(args) => DisconnectHandler::new(args, shared_args.lock_file).handle().await,
|
CliCommand::Disconnect(args) => DisconnectHandler::new(args).handle().await,
|
||||||
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
|
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
|
||||||
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
|
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_logger(cli: &Cli) -> env_logger::Builder {
|
fn init_logger(cli: &Cli) {
|
||||||
let mut builder = env_logger::builder();
|
let mut builder = env_logger::builder();
|
||||||
builder.filter_level(cli.verbose.log_level_filter());
|
builder.filter_level(cli.verbose.log_level_filter());
|
||||||
|
|
||||||
// Text is env_logger's own format, so leave it untouched rather than
|
// Output the log messages to a file if the command is the auth callback
|
||||||
// reimplementing it.
|
if let CliCommand::LaunchGui(args) = &cli.command {
|
||||||
if cli.log_format == LogFormat::Json {
|
let auth_data = args.auth_data.as_deref().unwrap_or_default();
|
||||||
builder.format(write_json_record);
|
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() {
|
pub(crate) async fn run() {
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
|
|
||||||
build_logger(&cli).init();
|
init_logger(&cli);
|
||||||
|
|
||||||
info!("gpclient started: {}", VERSION);
|
info!("gpclient started: {}", VERSION);
|
||||||
|
|
||||||
@@ -208,185 +177,3 @@ pub(crate) async fn run() {
|
|||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use std::{
|
|
||||||
io::Write,
|
|
||||||
sync::{Arc, Mutex},
|
|
||||||
};
|
|
||||||
|
|
||||||
use log::Log;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn lock_file_defaults_to_standard_path() {
|
|
||||||
let cli = Cli::try_parse_from(["gpclient", "connect", "portal.example.com"]).expect("cli should parse");
|
|
||||||
|
|
||||||
assert_eq!(cli.lock_file, PathBuf::from(GP_CLIENT_LOCK_FILE));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn lock_file_can_be_overridden_after_subcommand() {
|
|
||||||
let cli = Cli::try_parse_from([
|
|
||||||
"gpclient",
|
|
||||||
"connect",
|
|
||||||
"portal.example.com",
|
|
||||||
"--lock-file",
|
|
||||||
"/tmp/gpclient-portal.lock",
|
|
||||||
])
|
|
||||||
.expect("global lock file option should parse after subcommand");
|
|
||||||
|
|
||||||
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},
|
os_profile::{ClientOs, OsProfile},
|
||||||
};
|
};
|
||||||
use log::warn;
|
use log::warn;
|
||||||
use std::{net::IpAddr, path::PathBuf};
|
use std::path::PathBuf;
|
||||||
|
|
||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
pub(crate) struct ConnectArgs {
|
pub(crate) struct ConnectArgs {
|
||||||
@@ -146,17 +146,6 @@ pub(crate) struct ConnectArgs {
|
|||||||
num_args=0..=1
|
num_args=0..=1
|
||||||
)]
|
)]
|
||||||
pub(super) browser: Option<String>,
|
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 {
|
pub(super) fn build_os_profile(args: &ConnectArgs) -> OsProfile {
|
||||||
@@ -274,23 +263,6 @@ mod tests {
|
|||||||
assert_eq!(cli.args.browser.as_deref(), Some("default"));
|
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]
|
#[test]
|
||||||
fn os_defaults_to_runtime_os() {
|
fn os_defaults_to_runtime_os() {
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
@@ -426,23 +398,4 @@ mod tests {
|
|||||||
};
|
};
|
||||||
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
|
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())
|
.sslkey(self.args.sslkey.as_deref())
|
||||||
.key_password(key_password.as_deref())
|
.key_password(key_password.as_deref())
|
||||||
.browser(browser)
|
.browser(browser)
|
||||||
.browser_listen(self.args.browser_listen)
|
|
||||||
.log_format(self.shared_args.log_format)
|
|
||||||
.verbose(verbose);
|
.verbose(verbose);
|
||||||
|
|
||||||
#[cfg(feature = "webview-auth")]
|
#[cfg(feature = "webview-auth")]
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
use std::{
|
use std::{
|
||||||
fs,
|
fs,
|
||||||
path::Path,
|
|
||||||
sync::{
|
sync::{
|
||||||
Arc, Mutex,
|
Arc, Mutex,
|
||||||
atomic::{AtomicBool, Ordering},
|
atomic::{AtomicBool, Ordering},
|
||||||
@@ -8,23 +7,23 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
clap::report,
|
|
||||||
cookie_store,
|
cookie_store,
|
||||||
credential::{AuthCookieCredential, Credential},
|
credential::{AuthCookieCredential, Credential},
|
||||||
gateway::{GatewayLogin, GatewayLoginContext, SessionExtensionAuth, gateway_login, gateway_login_with_context},
|
gateway::{GatewayLogin, GatewayLoginContext, SessionExtensionAuth, gateway_login, gateway_login_with_context},
|
||||||
gp_params::GpParams,
|
gp_params::GpParams,
|
||||||
os_profile::OsProfile,
|
os_profile::OsProfile,
|
||||||
portal::prelogin,
|
portal::prelogin,
|
||||||
process::users::get_user_by_name,
|
process::users::{get_non_root_user, get_user_by_name},
|
||||||
utils::shutdown_signal,
|
utils::shutdown_signal,
|
||||||
};
|
};
|
||||||
use inquire::Text;
|
use inquire::Text;
|
||||||
use log::{Level, info, warn};
|
use log::{info, warn};
|
||||||
use openconnect::{Vpn, VpnBuilder};
|
use openconnect::{Vpn, VpnBuilder};
|
||||||
use tokio::{runtime::Handle, task::JoinHandle};
|
use tokio::{runtime::Handle, task::JoinHandle};
|
||||||
|
|
||||||
use crate::session::{
|
use crate::{
|
||||||
SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info,
|
GP_CLIENT_LOCK_FILE,
|
||||||
|
session::{SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info},
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::{ConnectHandler, args::cookie_cache_path};
|
use super::{ConnectHandler, args::cookie_cache_path};
|
||||||
@@ -282,22 +281,9 @@ impl ConnectHandler<'_> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let format = self.shared_args.log_format;
|
eprintln!("\nNOTE: Gateway authentication failed after portal login.");
|
||||||
report(
|
eprintln!("NOTE: If this server also accepts direct gateway login, try:");
|
||||||
format,
|
eprintln!("NOTE: {}", direct_gateway_command(gateway));
|
||||||
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)),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn login_gateway(
|
async fn login_gateway(
|
||||||
@@ -341,16 +327,6 @@ impl ConnectHandler<'_> {
|
|||||||
allow_extend_session: bool,
|
allow_extend_session: bool,
|
||||||
extension_auth: SessionExtensionAuth,
|
extension_auth: SessionExtensionAuth,
|
||||||
) -> Result<(), GatewayConnectError> {
|
) -> Result<(), GatewayConnectError> {
|
||||||
// --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(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let mtu = self.args.mtu.unwrap_or(0);
|
let mtu = self.args.mtu.unwrap_or(0);
|
||||||
let (hip, csd_wrapper) = self.determine_hip_script();
|
let (hip, csd_wrapper) = self.determine_hip_script();
|
||||||
let hip_user = self.determine_hip_user();
|
let hip_user = self.determine_hip_user();
|
||||||
@@ -408,12 +384,9 @@ impl ConnectHandler<'_> {
|
|||||||
vpn_clone.disconnect();
|
vpn_clone.disconnect();
|
||||||
});
|
});
|
||||||
|
|
||||||
let lock_file = self.shared_args.lock_file.to_path_buf();
|
|
||||||
let lock_file_on_connect = lock_file.clone();
|
|
||||||
let log_format = self.shared_args.log_format;
|
|
||||||
let connect_result = vpn.connect(move |vpn_session_info| {
|
let connect_result = vpn.connect(move |vpn_session_info| {
|
||||||
tunnel_established_on_connect.store(true, Ordering::SeqCst);
|
tunnel_established_on_connect.store(true, Ordering::SeqCst);
|
||||||
write_pid_file(&lock_file_on_connect);
|
write_pid_file();
|
||||||
|
|
||||||
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
|
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
|
||||||
return;
|
return;
|
||||||
@@ -421,7 +394,7 @@ impl ConnectHandler<'_> {
|
|||||||
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
|
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
|
||||||
info!("VPN session info: {}", session_info.log_summary());
|
info!("VPN session info: {}", session_info.log_summary());
|
||||||
|
|
||||||
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info, log_format);
|
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info);
|
||||||
session_task_on_connect.lock().unwrap().replace(task);
|
session_task_on_connect.lock().unwrap().replace(task);
|
||||||
});
|
});
|
||||||
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
|
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
|
||||||
@@ -430,9 +403,9 @@ impl ConnectHandler<'_> {
|
|||||||
task.abort();
|
task.abort();
|
||||||
}
|
}
|
||||||
|
|
||||||
if fs::metadata(&lock_file).is_ok() {
|
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
|
||||||
info!("Removing PID file");
|
info!("Removing PID file");
|
||||||
fs::remove_file(&lock_file).map_err(|err| GatewayConnectError::after_tunnel(err.into()))?;
|
fs::remove_file(GP_CLIENT_LOCK_FILE).map_err(|err| GatewayConnectError::after_tunnel(err.into()))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
|
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
|
||||||
@@ -485,13 +458,13 @@ fn direct_gateway_command(gateway: &str) -> String {
|
|||||||
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
|
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_pid_file(lock_file: &Path) {
|
fn write_pid_file() {
|
||||||
let pid = std::process::id();
|
let pid = std::process::id();
|
||||||
|
|
||||||
if let Err(err) = fs::write(lock_file, pid.to_string()) {
|
if let Err(err) = fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()) {
|
||||||
warn!("Failed to write PID file: {}", err);
|
warn!("Failed to write PID file: {}", err);
|
||||||
} else {
|
} else {
|
||||||
info!("Wrote PID {} to {}", pid, lock_file.display());
|
info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -499,7 +472,7 @@ fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
|
|||||||
if let Some(user) = user {
|
if let Some(user) = user {
|
||||||
get_user_by_name(user).map(|user| user.uid())
|
get_user_by_name(user).map(|user| user.uid())
|
||||||
} else {
|
} else {
|
||||||
Ok(uzers::get_effective_uid())
|
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -516,23 +489,6 @@ fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hip_script_defaults_to_process_effective_uid() {
|
|
||||||
assert_eq!(get_uid(&None).unwrap(), uzers::get_effective_uid());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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(), current.uid());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn openconnect_success_is_not_a_gateway_failure() {
|
fn openconnect_success_is_not_a_gateway_failure() {
|
||||||
assert!(classify_openconnect_result(0, false, false).is_ok());
|
assert!(classify_openconnect_result(0, false, false).is_ok());
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ use std::cell::RefCell;
|
|||||||
|
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
clap::report,
|
|
||||||
error::PortalError,
|
error::PortalError,
|
||||||
gateway::{GatewayLoginContext, GatewaySelection},
|
gateway::{GatewayLoginContext, GatewaySelection},
|
||||||
gp_params::GpParams,
|
gp_params::GpParams,
|
||||||
@@ -15,7 +14,7 @@ use gpapi::{
|
|||||||
utils::request::RequestIdentityError,
|
utils::request::RequestIdentityError,
|
||||||
};
|
};
|
||||||
use inquire::{Password, PasswordDisplayMode, Select};
|
use inquire::{Password, PasswordDisplayMode, Select};
|
||||||
use log::{Level, info, warn};
|
use log::{info, warn};
|
||||||
|
|
||||||
use crate::cli::SharedArgs;
|
use crate::cli::SharedArgs;
|
||||||
|
|
||||||
@@ -93,12 +92,6 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
pub(crate) async fn handle(&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")]
|
#[cfg(feature = "webview-auth")]
|
||||||
if self.args.default_browser && self.args.browser.is_some() {
|
if self.args.default_browser && self.args.browser.is_some() {
|
||||||
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
|
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
|
||||||
@@ -117,17 +110,8 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
|
|
||||||
match root_cause {
|
match root_cause {
|
||||||
RequestIdentityError::NoKey => {
|
RequestIdentityError::NoKey => {
|
||||||
let format = self.shared_args.log_format;
|
eprintln!("ERROR: No private key found in the certificate file");
|
||||||
report(
|
eprintln!("ERROR: Please provide the private key file using the `-k` option");
|
||||||
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",
|
|
||||||
);
|
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
|
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
|
||||||
@@ -169,17 +153,8 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
info!("Trying the gateway authentication workflow...");
|
info!("Trying the gateway authentication workflow...");
|
||||||
self.connect_gateway_with_prelogin(server, server, false, None).await?;
|
self.connect_gateway_with_prelogin(server, server, false, None).await?;
|
||||||
|
|
||||||
let format = self.shared_args.log_format;
|
eprintln!("\nNOTE: the server may be a gateway, not a portal.");
|
||||||
report(
|
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
|
||||||
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.",
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
|
use crate::GP_CLIENT_LOCK_FILE;
|
||||||
use clap::Args;
|
use clap::Args;
|
||||||
use gpapi::utils::lock_file::gpservice_lock_info;
|
use gpapi::utils::lock_file::gpservice_lock_info;
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
use std::{fs, path::Path, str::FromStr, thread, time::Duration};
|
use std::{fs, str::FromStr, thread, time::Duration};
|
||||||
use sysinfo::{Pid, Signal, System};
|
use sysinfo::{Pid, Signal, System};
|
||||||
|
|
||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
@@ -16,17 +17,16 @@ pub struct DisconnectArgs {
|
|||||||
|
|
||||||
pub struct DisconnectHandler<'a> {
|
pub struct DisconnectHandler<'a> {
|
||||||
args: &'a DisconnectArgs,
|
args: &'a DisconnectArgs,
|
||||||
lock_file: &'a Path,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> DisconnectHandler<'a> {
|
impl<'a> DisconnectHandler<'a> {
|
||||||
pub fn new(args: &'a DisconnectArgs, lock_file: &'a Path) -> Self {
|
pub fn new(args: &'a DisconnectArgs) -> Self {
|
||||||
Self { args, lock_file }
|
Self { args }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn handle(&self) -> anyhow::Result<()> {
|
pub async fn handle(&self) -> anyhow::Result<()> {
|
||||||
// Try to disconnect the CLI client
|
// Try to disconnect the CLI client
|
||||||
if let Ok(c) = fs::read_to_string(self.lock_file) {
|
if let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE) {
|
||||||
send_signal(c.trim(), Signal::Interrupt).unwrap_or_else(|err| {
|
send_signal(c.trim(), Signal::Interrupt).unwrap_or_else(|err| {
|
||||||
warn!("Failed to send signal to client: {}", err);
|
warn!("Failed to send signal to client: {}", err);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,9 +1,122 @@
|
|||||||
|
use askama::Template;
|
||||||
use clap::Args;
|
use clap::Args;
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
clap::args::Os,
|
clap::args::Os,
|
||||||
os_profile::{ClientOs, OsProfileBuilder},
|
os_profile::{ClientOs, OsProfile, OsProfileBuilder},
|
||||||
};
|
};
|
||||||
use gphip::{ReportContext, ReportInput, generate_report};
|
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)]
|
#[derive(Args)]
|
||||||
pub(crate) struct HipArgs {
|
pub(crate) struct HipArgs {
|
||||||
@@ -34,29 +147,434 @@ pub(crate) struct HipArgs {
|
|||||||
|
|
||||||
pub(crate) struct HipHandler<'a> {
|
pub(crate) struct HipHandler<'a> {
|
||||||
args: &'a HipArgs,
|
args: &'a HipArgs,
|
||||||
|
profile: OsProfile,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> HipHandler<'a> {
|
impl<'a> HipHandler<'a> {
|
||||||
pub(crate) fn new(args: &'a HipArgs) -> Self {
|
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<()> {
|
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
||||||
let client_os = ClientOs::from(self.args.client_os);
|
let cookie_params = self.parse_cookie();
|
||||||
let mut builder = OsProfileBuilder::new(client_os).client_version(self.args.client_version.clone());
|
let report = self.generate_hip_report(&cookie_params)?;
|
||||||
if let Some(host_id) = self.args.host_id.as_deref() {
|
|
||||||
builder = builder.host_id_override(host_id);
|
debug!("Generated HIP report:\n{}", report);
|
||||||
}
|
println!("{}", report);
|
||||||
let input = ReportInput {
|
|
||||||
profile: builder.build(),
|
|
||||||
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(&input)?);
|
|
||||||
Ok(())
|
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,48 +1,26 @@
|
|||||||
use std::{collections::HashMap, 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;
|
use clap::Args;
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
use common::constants::GP_CALLBACK_PORT_FILENAME;
|
||||||
use common::binary_paths;
|
|
||||||
use directories::ProjectDirs;
|
use directories::ProjectDirs;
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
process::service_launcher::ServiceLauncher,
|
process::service_launcher::ServiceLauncher,
|
||||||
utils::{endpoint::http_endpoint, env_utils, shutdown_signal},
|
utils::{endpoint::http_endpoint, env_utils, shutdown_signal},
|
||||||
};
|
};
|
||||||
use log::info;
|
use log::info;
|
||||||
|
use tokio::io::AsyncWriteExt;
|
||||||
|
|
||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
pub(crate) struct LaunchGuiArgs {
|
pub(crate) struct LaunchGuiArgs {
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
#[arg(
|
#[arg(
|
||||||
required = false,
|
required = false,
|
||||||
conflicts_with = "minimized",
|
help = "The authentication data, used for the default browser authentication"
|
||||||
value_parser = parse_auth_callback,
|
|
||||||
help = "The external-browser authentication callback URL"
|
|
||||||
)]
|
)]
|
||||||
callback: Option<String>,
|
pub auth_data: Option<String>,
|
||||||
#[arg(long, help = "Launch the GUI minimized")]
|
#[arg(long, help = "Launch the GUI minimized")]
|
||||||
minimized: bool,
|
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> {
|
pub(crate) struct LaunchGuiHandler<'a> {
|
||||||
args: &'a LaunchGuiArgs,
|
args: &'a LaunchGuiArgs,
|
||||||
}
|
}
|
||||||
@@ -59,9 +37,11 @@ impl<'a> LaunchGuiHandler<'a> {
|
|||||||
anyhow::bail!("`launch-gui` cannot be run as root");
|
anyhow::bail!("`launch-gui` cannot be run as root");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
let auth_data = self.args.auth_data.as_deref().unwrap_or_default();
|
||||||
if let Some(callback) = &self.args.callback {
|
if !auth_data.is_empty() {
|
||||||
return forward_auth_callback(callback);
|
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() {
|
if try_active_gui().await.is_ok() {
|
||||||
@@ -100,36 +80,24 @@ impl<'a> LaunchGuiHandler<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
async fn feed_auth_data(auth_data: &str) -> anyhow::Result<()> {
|
||||||
fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
|
if let Err(err) = feed_auth_data_cli(auth_data).await {
|
||||||
let status = auth_callback_command(callback)
|
info!("Failed to feed auth data to the CLI: {}", err);
|
||||||
.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}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
async fn feed_auth_data_cli(auth_data: &str) -> anyhow::Result<()> {
|
||||||
fn parse_auth_callback(callback: &str) -> Result<String, String> {
|
info!("Feeding auth data to the CLI");
|
||||||
callback
|
|
||||||
.starts_with("globalprotectcallback:")
|
let port_file = temp_dir().join(GP_CALLBACK_PORT_FILENAME);
|
||||||
.then(|| callback.to_owned())
|
let port = tokio::fs::read_to_string(port_file).await?;
|
||||||
.ok_or_else(|| "callback URL must use the globalprotectcallback scheme".to_owned())
|
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<()> {
|
async fn try_active_gui() -> anyhow::Result<()> {
|
||||||
@@ -152,34 +120,3 @@ fn get_log_file() -> anyhow::Result<PathBuf> {
|
|||||||
|
|
||||||
Ok(dirs.data_dir().join("gpclient.log"))
|
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 std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
clap::report,
|
|
||||||
gateway::{SessionContext, SessionExtensionAuth, extend_session},
|
gateway::{SessionContext, SessionExtensionAuth, extend_session},
|
||||||
log_format::LogFormat,
|
|
||||||
os_profile::OsProfile,
|
os_profile::OsProfile,
|
||||||
session::{SessionInfo, SessionRequestArgs, SessionWarning},
|
session::{SessionInfo, SessionRequestArgs, SessionWarning},
|
||||||
};
|
};
|
||||||
use log::{Level, info, warn};
|
use log::{info, warn};
|
||||||
use openconnect::VpnSessionInfo;
|
use openconnect::VpnSessionInfo;
|
||||||
use tokio::{runtime::Handle, task::JoinHandle};
|
use tokio::{runtime::Handle, task::JoinHandle};
|
||||||
|
|
||||||
@@ -61,12 +59,11 @@ pub(crate) fn spawn_session_runtime_with_info(
|
|||||||
handle: &Handle,
|
handle: &Handle,
|
||||||
session_ctx: SessionContext,
|
session_ctx: SessionContext,
|
||||||
session_info: SessionInfo,
|
session_info: SessionInfo,
|
||||||
log_format: LogFormat,
|
|
||||||
) -> JoinHandle<()> {
|
) -> 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 {
|
loop {
|
||||||
let Some(schedule) = build_session_warning_schedule(&session_info) else {
|
let Some(schedule) = build_session_warning_schedule(&session_info) else {
|
||||||
info!("No session warning schedule provided by the gateway");
|
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;
|
tokio::time::sleep(schedule.delay).await;
|
||||||
|
|
||||||
report(log_format, Level::Warn, &format!("\nWARNING: {}", schedule.message));
|
eprintln!("\nWARNING: {}", schedule.message);
|
||||||
|
|
||||||
if !schedule.should_auto_extend {
|
if !schedule.should_auto_extend {
|
||||||
info!("Session extension is not allowed by the gateway");
|
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;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
report(log_format, Level::Info, "Session extended.");
|
eprintln!("Session extended.");
|
||||||
session_info = next_session_info;
|
session_info = next_session_info;
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
warn!("Failed to extend session: {}", err);
|
warn!("Failed to extend session: {}", err);
|
||||||
report(
|
eprintln!("WARNING: Failed to extend session: {}", err);
|
||||||
log_format,
|
|
||||||
Level::Warn,
|
|
||||||
&format!("WARNING: Failed to extend session: {}", err),
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -220,7 +213,6 @@ mod tests {
|
|||||||
prior_secs: 1_800,
|
prior_secs: 1_800,
|
||||||
message: "Session expires soon".to_string(),
|
message: "Session expires soon".to_string(),
|
||||||
}),
|
}),
|
||||||
..Default::default()
|
|
||||||
},
|
},
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
@@ -241,7 +233,6 @@ mod tests {
|
|||||||
prior_secs: 1_800,
|
prior_secs: 1_800,
|
||||||
message: "Session expires soon".to_string(),
|
message: "Session expires soon".to_string(),
|
||||||
}),
|
}),
|
||||||
..Default::default()
|
|
||||||
},
|
},
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -139,15 +139,6 @@
|
|||||||
{% elif host_info.os_vendor == "Apple" -%}
|
{% elif host_info.os_vendor == "Apple" -%}
|
||||||
<entry name="anti-malware">
|
<entry name="anti-malware">
|
||||||
<list>
|
<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>
|
<entry>
|
||||||
<ProductInfo>
|
<ProductInfo>
|
||||||
<Prod vendor="Apple Inc." name="Xprotect" version="2167" defver="235000000000000" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
|
<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>
|
||||||
<entry name="firewall">
|
<entry name="firewall">
|
||||||
<list>
|
<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>
|
<entry>
|
||||||
<ProductInfo>
|
<ProductInfo>
|
||||||
<Prod vendor="Apple Inc." name="Mac OS X Builtin Firewall" version="{{ host_info.software_version }}"/>
|
<Prod vendor="Apple Inc." name="Mac OS X Builtin Firewall" version="{{ host_info.software_version }}"/>
|
||||||
@@ -237,17 +218,8 @@
|
|||||||
</entry>
|
</entry>
|
||||||
{% elif host_info.os_vendor == "Linux" -%}
|
{% elif host_info.os_vendor == "Linux" -%}
|
||||||
<entry name="anti-malware">
|
<entry name="anti-malware">
|
||||||
|
{% if let Some(defender) = &host_info.defender -%}
|
||||||
<list>
|
<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>
|
<entry>
|
||||||
<ProductInfo>
|
<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 }}">
|
<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>
|
<last-full-scan-time>n/a</last-full-scan-time>
|
||||||
</ProductInfo>
|
</ProductInfo>
|
||||||
</entry>
|
</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>
|
</list>
|
||||||
|
{% else -%}
|
||||||
|
<list/>
|
||||||
|
{% endif -%}
|
||||||
</entry>
|
</entry>
|
||||||
<entry name="disk-backup">
|
<entry name="disk-backup">
|
||||||
<list/>
|
<list/>
|
||||||
@@ -289,14 +254,6 @@
|
|||||||
</entry>
|
</entry>
|
||||||
<entry name="firewall">
|
<entry name="firewall">
|
||||||
<list>
|
<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>
|
<entry>
|
||||||
<ProductInfo>
|
<ProductInfo>
|
||||||
<Prod name="IPTables" version="1.8.4" vendor="IPTables">
|
<Prod name="IPTables" version="1.8.4" vendor="IPTables">
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||||
|
|
||||||
|
<svg
|
||||||
|
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||||
|
xmlns:cc="http://creativecommons.org/ns#"
|
||||||
|
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||||
|
xmlns:svg="http://www.w3.org/2000/svg"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||||
|
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||||
|
version="1.1"
|
||||||
|
id="Layer_1"
|
||||||
|
x="0px"
|
||||||
|
y="0px"
|
||||||
|
viewBox="0 0 96 96"
|
||||||
|
style="enable-background:new 0 0 96 96;"
|
||||||
|
xml:space="preserve"
|
||||||
|
sodipodi:docname="com.yuezk.qt.gpclient.svg"
|
||||||
|
inkscape:version="0.92.4 5da689c313, 2019-01-14"><metadata
|
||||||
|
id="metadata14"><rdf:RDF><cc:Work
|
||||||
|
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
|
||||||
|
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
|
||||||
|
id="defs12" /><sodipodi:namedview
|
||||||
|
pagecolor="#ffffff"
|
||||||
|
bordercolor="#666666"
|
||||||
|
borderopacity="1"
|
||||||
|
objecttolerance="10"
|
||||||
|
gridtolerance="10"
|
||||||
|
guidetolerance="10"
|
||||||
|
inkscape:pageopacity="0"
|
||||||
|
inkscape:pageshadow="2"
|
||||||
|
inkscape:window-width="1920"
|
||||||
|
inkscape:window-height="1006"
|
||||||
|
id="namedview10"
|
||||||
|
showgrid="false"
|
||||||
|
inkscape:zoom="6.9532168"
|
||||||
|
inkscape:cx="7.9545315"
|
||||||
|
inkscape:cy="59.062386"
|
||||||
|
inkscape:window-x="0"
|
||||||
|
inkscape:window-y="0"
|
||||||
|
inkscape:window-maximized="1"
|
||||||
|
inkscape:current-layer="g8499" />
|
||||||
|
<style
|
||||||
|
type="text/css"
|
||||||
|
id="style2">
|
||||||
|
.st0{fill:#2980B9;}
|
||||||
|
.st1{fill:#3498DB;}
|
||||||
|
.st2{fill:#2ECC71;}
|
||||||
|
.st3{fill:#27AE60;}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<g
|
||||||
|
id="g8499"
|
||||||
|
transform="matrix(1.3407388,0,0,1.3407388,-16.409202,-16.355463)"><g
|
||||||
|
id="XMLID_1_">
|
||||||
|
<circle
|
||||||
|
r="32.5"
|
||||||
|
cy="48"
|
||||||
|
cx="48"
|
||||||
|
class="st0"
|
||||||
|
id="XMLID_3_"
|
||||||
|
style="fill:#2980b9" />
|
||||||
|
<path
|
||||||
|
d="m 48,15.5 v 65 C 65.9,80.5 80.5,65.7 80.5,48 80.5,30 65.9,15.5 48,15.5 Z"
|
||||||
|
class="st1"
|
||||||
|
id="XMLID_4_"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
style="fill:#3498db" />
|
||||||
|
<path
|
||||||
|
d="m 48,15.5 v 0.6 l 1.2,-0.3 c 0.3,-0.3 0.4,-0.3 0.6,-0.3 h -1.1 z m 7.3,0.9 c -0.1,0 0.4,0.9 1.1,1.8 0.8,1.5 1.1,2.1 1.3,2.1 0.3,-0.3 1.9,-1.2 3,-2.1 -1.7,-0.9 -3.5,-1.5 -5.4,-1.8 z m 10.3,6.2 c -0.1,0 -0.4,0 -0.9,0.6 l -0.8,0.9 0.6,0.6 c 0.3,0.6 0.8,0.9 1,1.2 0.5,0.6 0.6,0.6 0.1,1.5 -0.2,0.6 -0.3,0.9 -0.3,0.9 0.1,0.3 0.3,0.3 1.4,0.3 h 1.6 c 0.1,0 0.3,-0.6 0.4,-1.2 l 0.1,-0.9 -1.1,-0.9 c -1,-0.9 -1,-0.9 -1.4,-1.8 -0.3,-0.6 -0.6,-1.2 -0.7,-1.2 z m -3,2.4 c -0.2,0 -1.3,2.1 -1.3,2.4 0,0 0.3,0.6 0.7,0.9 0.4,0.3 0.7,0.6 0.7,0.6 0.1,0 1.2,-1.2 1.4,-1.5 C 64.2,27.1 64,26.8 63.5,26.2 63.1,25.5 62.7,25 62.6,25 Z m 9.5,1.1 0.2,0.3 c 0,0.3 -0.7,0.9 -1.4,1.5 -1.2,0.9 -1.4,1.2 -2,1.2 -0.6,0 -0.9,0.3 -1.8,0.9 -0.6,0.6 -1.2,0.9 -1.2,1.2 0,0 0.2,0.3 0.6,0.9 0.7,0.6 0.7,0.9 0.2,1.8 l -0.4,0.3 h -1.1 c -0.6,0 -1.5,0 -1.8,-0.3 -0.9,0 -0.8,0 -0.1,2.1 1,3 1.1,3.2 1.3,3.2 0.1,0 1.3,-1.2 2.8,-2.4 1.5,-1.2 2.7,-2.4 2.8,-2.4 l 0.6,0.3 c 0.4,0.3 0.5,0 1.3,-0.6 l 0.8,-0.6 0.8,0.6 c 1.9,1.2 2.2,1.5 2.3,2.4 0.2,1.5 0.3,1.8 0.5,1.8 0.1,0 1.3,-1.5 1.6,-1.8 0.1,-0.3 -0.1,-0.6 -1.1,-2.1 -0.7,-0.9 -1.1,-1.8 -1.1,-2.1 0,0 0.1,0 0.3,-0.3 0.2,0 0.4,0.3 1,0.9 -1.6,-2.3 -3.2,-4.7 -5.1,-6.8 z m 2.8,10.7 c -0.2,0 -0.9,0.9 -0.8,1.2 l 0.5,0.3 H 75 c 0.2,0 0.3,0 0.2,-0.3 C 75.1,37.4 75,36.8 74.9,36.8 Z M 72.3,38 h -2.4 l -2.4,0.3 -4.5,3.5 -4.4,3.8 v 3.5 c 0,2.1 0,3.8 0.1,3.8 0.1,0 0.7,0.9 1.5,1.5 0.8,0.9 1.5,1.5 1.8,1.8 0.4,0.3 0.5,0.3 4,0.6 l 3.4,0.3 1.6,0.9 c 0.8,0.6 1.5,1.2 1.6,1.2 0.1,0 -0.3,0.3 -0.6,0.6 l -0.6,0.6 1,1.2 c 0.5,0.6 1.3,1.5 1.7,1.8 l 0.6,0.9 v 1.7 0.9 c 3.7,-5 5.9,-11.5 6.1,-18.3 0.1,-2.7 -0.3,-5.3 -0.8,-8 l -0.6,-0.3 c -0.1,0 -0.5,0.3 -1,0.6 -0.5,0.3 -1,0.9 -1.1,0.9 -0.1,0 -0.8,-0.3 -1.8,-0.6 l -1.8,-0.6 v -0.9 c 0,-0.6 0,-0.9 -0.6,-1.5 z M 48,63.7 V 64 h 0.2 z"
|
||||||
|
class="st2"
|
||||||
|
id="XMLID_13_"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
style="fill:#2ecc71" />
|
||||||
|
<path
|
||||||
|
d="m 48,15.5 c -3.1,0 -6.2,0.5 -9,1.3 0.3,0.4 0.3,0.4 0.6,0.9 1.5,2.5 1.7,2.8 2.1,2.9 0.3,0 0.9,0.1 1.6,0.1 h 1.2 l 0.9,-2 0.8,-1.9 1.8,-0.6 z m -16.9,4.7 c -2.8,1.7 -5.4,3.9 -7.6,6.4 -3.8,4.3 -6.3,9.6 -7.4,15.4 0.5,0 0.9,-0.1 1.8,-0.1 2.8,0.1 2.5,0 3.4,1.4 0.5,0.8 0.6,0.8 1.4,0.8 1,0.1 0.9,0 0.5,-1.6 -0.2,-0.6 -0.3,-1.2 -0.3,-1.4 0,-0.2 0.5,-0.7 1.7,-1.6 1.9,-1.5 1.8,-1.3 1.5,-2.9 -0.1,-0.3 0.1,-0.6 0.6,-1.2 0.7,-0.7 0.7,-0.6 1.4,-0.6 h 0.7 l 0.1,-1.2 c 0.1,-0.7 0.1,-1.3 0.2,-1.3 0,0 1.9,-1.1 4.1,-2.3 2.2,-1.2 4.1,-2.2 4.2,-2.3 0.2,-0.2 -0.3,-0.8 -2.7,-3.8 -1.5,-1.9 -2.8,-3.6 -2.9,-3.7 z m -5.8,23 c -0.1,0 -0.1,0.3 -0.1,0.6 0,0.6 0,0.7 0.6,1 0.8,0.4 0.9,0.5 0.8,0.2 -0.1,-0.4 -1.2,-1.9 -1.3,-1.8 z m -3.4,2.1 -0.5,1.8 c 0.1,0.1 0.9,0.3 1.8,0.5 1,0.2 1.6,0.4 1.8,0.3 l 0.5,-1.3 z m -3.8,1 -1.1,0.6 c -0.6,0.3 -1.2,0.6 -1.4,0.6 h -0.1 c 0,1.4 0.1,2.8 0.3,4.2 l 0.6,0.4 1,-0.1 h 1 l 0.6,1.4 c 0.3,0.7 0.7,1.4 0.8,1.5 0.1,0.1 1,0.1 1.8,0.1 h 1.5 L 23,56.2 c 0,1.2 0,1.3 -0.6,2.2 -0.4,0.5 -0.6,1.2 -0.6,1.4 0,0.2 0.7,2.1 1.6,4.3 l 1.5,4 1.6,0.8 c 1.2,0.6 1.5,0.8 1.5,1 0,0.1 -0.4,2.1 -0.6,3.1 3,2.5 6.4,4.5 10.2,5.8 3.5,-3.6 6.8,-7.1 7.3,-7.6 l 0.7,-0.7 0.2,-1.9 c 0.2,-1.1 0.4,-2.1 0.4,-2.2 0,-0.1 0.5,-0.6 1,-1.2 0.5,-0.5 0.8,-1 0.8,-1.1 v -0.2 c -0.1,-0.1 -1.4,-1.1 -3,-2.2 l -3.1,-2.1 -1.1,-0.1 c -0.8,0 -1.2,0 -1.3,-0.2 C 39.4,59.2 39.2,58.5 39.1,57.7 39,56.9 38.9,56.2 38.8,56.1 38.8,56 38,56 37.1,56 36.2,56 35.4,55.9 35.3,55.8 35.2,55.7 35.2,55.1 35.1,54.3 35,53.6 34.9,53 34.8,52.9 34.7,52.8 33.7,52.7 32.5,52.6 30.5,52.5 30.1,52.5 29.1,52 l -1.2,-0.6 -1.6,0.7 -1.7,0.9 -1.8,-0.1 c -2,0 -1.9,0.2 -2.1,-1.6 C 20.6,50.7 20.6,50.1 20.5,50.1 20.4,50 20,50 19.6,49.9 L 18.9,49.7 19,49.2 c 0,-0.3 0,-1 0.1,-1.4 L 19.2,47 18.7,46.5 Z m 9.1,1.1 C 27.1,47.5 27.1,47.8 27,48 l -0.1,0.5 2.9,1.2 c 2.9,1.1 3.4,1.2 3.9,0.7 0.2,-0.2 0.1,-0.2 -0.3,-0.4 -0.3,-0.1 -1.7,-0.9 -3.2,-1.6 -1.7,-0.7 -2.9,-1.1 -3,-1 z"
|
||||||
|
class="st3"
|
||||||
|
id="XMLID_20_"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
style="fill:#27ae60" />
|
||||||
|
</g><g
|
||||||
|
transform="matrix(1.458069,0,0,1.458069,-22.631538,-19.615144)"
|
||||||
|
id="g7664"><path
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
id="XMLID_6_"
|
||||||
|
class="st3"
|
||||||
|
d="m 38.8,56.1 c 0,1.2 1,2.2 2.2,2.2 h 15.2 c 1.2,0 2.2,-1 2.2,-2.2 V 45.3 c 0,-1.2 -1,-2.2 -2.2,-2.2 H 40.9 c -1.2,0 -2.2,1 -2.2,2.2 v 10.8 z"
|
||||||
|
style="fill:#f1aa27;fill-opacity:1" /><path
|
||||||
|
style="fill:#e6e6e6"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
id="XMLID_7_"
|
||||||
|
class="st4"
|
||||||
|
d="m 55.5,43.1 h -3.3 v -3.7 c 0,-2.1 -1.7,-3.8 -3.8,-3.8 -2.1,0 -3.8,1.7 -3.8,3.8 v 3.8 h -3.1 v -3.8 c 0,-3.9 3.2,-7 7,-7 3.9,0 7,3.2 7,7 z" /><path
|
||||||
|
style="fill:#e6e6e6;fill-opacity:1"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
id="XMLID_8_"
|
||||||
|
class="st5"
|
||||||
|
d="m 50.35,48.2 c 0,-1 -0.8,-1.8 -1.8,-1.8 -1,0 -1.8,0.8 -1.8,1.8 0,0.7 0.4,1.3 1,1.6 l -1,5.2 h 3.6 l -1,-5.2 c 0.6,-0.3 1,-0.9 1,-1.6 z" /></g></g></svg>
|
||||||
|
After Width: | Height: | Size: 6.7 KiB |
@@ -1,43 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
|
||||||
<defs>
|
|
||||||
<linearGradient id="ocean" x1="245" y1="170" x2="770" y2="770" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop stop-color="#579bc1"/>
|
|
||||||
<stop offset=".52" stop-color="#438fbd"/>
|
|
||||||
<stop offset="1" stop-color="#2f719e"/>
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="land" x1="260" y1="190" x2="750" y2="735" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop stop-color="#56c78a"/>
|
|
||||||
<stop offset=".55" stop-color="#3bbf78"/>
|
|
||||||
<stop offset="1" stop-color="#279b5d"/>
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="lock" x1="385" y1="400" x2="650" y2="700" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop stop-color="#f3b84c"/>
|
|
||||||
<stop offset=".55" stop-color="#e8a12f"/>
|
|
||||||
<stop offset="1" stop-color="#d4871e"/>
|
|
||||||
</linearGradient>
|
|
||||||
<clipPath id="globe-clip">
|
|
||||||
<circle cx="512" cy="455" r="315"/>
|
|
||||||
</clipPath>
|
|
||||||
</defs>
|
|
||||||
|
|
||||||
<g transform="translate(512 512) scale(1.3) translate(-512 -455)">
|
|
||||||
<circle cx="512" cy="455" r="315" fill="url(#ocean)"/>
|
|
||||||
<g clip-path="url(#globe-clip)" fill="url(#land)">
|
|
||||||
<path d="M177 326c74-121 177-185 302-190-13 51-49 84-105 98-4 45-32 79-86 101-37 17-75 14-111-9Z"/>
|
|
||||||
<path d="M564 135c129 18 229 103 273 220-69-3-121 15-157 54-51-14-83-50-95-107-38-36-45-92-21-167Z"/>
|
|
||||||
<path d="M189 467c63-39 125-34 187 16 57 25 73 73 48 144-45 90-108 146-189 166-58-88-73-197-46-326Z"/>
|
|
||||||
<path d="M612 572c78-38 157-18 238 59-45 89-122 144-231 164-20-67-22-122-7-165-22-17-22-36 0-58Z"/>
|
|
||||||
</g>
|
|
||||||
<circle cx="512" cy="455" r="308" fill="none" stroke="#9ccde2" stroke-width="11" stroke-opacity=".4"/>
|
|
||||||
|
|
||||||
<g transform="translate(512 490) scale(.82) translate(-512 -490)">
|
|
||||||
<path d="M405 429v-75c0-142 214-142 214 0v75" fill="none" stroke="#eef1f2" stroke-width="58" stroke-linecap="round"/>
|
|
||||||
<rect x="340" y="403" width="344" height="278" rx="62" fill="url(#lock)"/>
|
|
||||||
<rect x="346" y="409" width="332" height="266" rx="56" fill="none" stroke="#f7cb75" stroke-width="10" stroke-opacity=".45"/>
|
|
||||||
<g fill="#85500f" opacity=".85">
|
|
||||||
<path d="M501 538h22l16 69h-54Z"/>
|
|
||||||
<circle cx="512" cy="521" r="27"/>
|
|
||||||
</g>
|
|
||||||
</g>
|
|
||||||
</g>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 2.2 KiB |
@@ -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}
|
||||||
@@ -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),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.context`)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,t.error.light,.6)),B(t.Alert,`infoColor`,r(F,t.info.light,.6)),B(t.Alert,`successColor`,r(F,t.success.light,.6)),B(t.Alert,`warningColor`,r(F,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,t.error.light,.9)),B(t.Alert,`infoStandardBg`,r(I,t.info.light,.9)),B(t.Alert,`successStandardBg`,r(I,t.success.light,.9)),B(t.Alert,`warningStandardBg`,r(I,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,t.primary.main,.62)),B(t.LinearProgress,`secondaryBg`,r(I,t.secondary.main,.62)),B(t.LinearProgress,`errorBg`,r(I,t.error.main,.62)),B(t.LinearProgress,`infoBg`,r(I,t.info.main,.62)),B(t.LinearProgress,`successBg`,r(I,t.success.main,.62)),B(t.LinearProgress,`warningBg`,r(I,t.warning.main,.62)),B(t.Skeleton,`bg`,b?r(xi,t.text.primary,.11):`rgba(${n(`palette-text-primaryChannel`)} / 0.11)`),B(t.Slider,`primaryTrack`,r(I,t.primary.main,.62)),B(t.Slider,`secondaryTrack`,r(I,t.secondary.main,.62)),B(t.Slider,`errorTrack`,r(I,t.error.main,.62)),B(t.Slider,`infoTrack`,r(I,t.info.main,.62)),B(t.Slider,`successTrack`,r(I,t.success.main,.62)),B(t.Slider,`warningTrack`,r(I,t.warning.main,.62));let e=b?r(F,t.background.default,.6825):Ti(t.background.default,.8);B(t.SnackbarContent,`bg`,e),B(t.SnackbarContent,`color`,La(()=>b?Ki.text.primary:t.getContrastText(e))),B(t.SpeedDialAction,`fabHoverBg`,Ti(t.background.paper,.15)),B(t.StepConnector,`border`,n(`palette-grey-400`)),B(t.StepContent,`border`,n(`palette-grey-400`)),B(t.Switch,`defaultColor`,n(`palette-common-white`)),B(t.Switch,`defaultDisabledColor`,n(`palette-grey-100`)),B(t.Switch,`primaryDisabledColor`,r(I,t.primarLine 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 s&&s!==`button`&&!(e.tagName===`A`&&e.href)},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&&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:ve,onKeyUp:ye,onMouseDown:ue
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
|
||||||
@@ -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}
|
|
||||||
@@ -2,11 +2,11 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/assets/icon-small-BO4dlTNl.svg" />
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<title>GPGUI Downloader</title>
|
<title>GP Connect Helper</title>
|
||||||
<script type="module" crossorigin src="/assets/main-B7u6_mhO.js"></script>
|
<script type="module" crossorigin src="/assets/main-CyyZK63u.js"></script>
|
||||||
<link rel="stylesheet" crossorigin href="/assets/main-DiWGniCh.css">
|
<link rel="stylesheet" crossorigin href="/assets/main-C5muOSVO.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<script>
|
<script>
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
|
||||||
|
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
|
||||||
|
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
|
||||||
|
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -2,9 +2,9 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/src/assets/icon-small.svg" />
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<title>GPGUI Downloader</title>
|
<title>GP Connect Helper</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<script>
|
<script>
|
||||||
|
|||||||
@@ -9,25 +9,29 @@
|
|||||||
"tauri": "tauri"
|
"tauri": "tauri"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tauri-apps/api": "^2.12.0",
|
"@emotion/react": "^11.14.0",
|
||||||
"react": "^19.3.0",
|
"@emotion/styled": "^11.14.1",
|
||||||
"react-dom": "^19.3.0"
|
"@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": {
|
"devDependencies": {
|
||||||
"@tauri-apps/cli": "^2.12.0",
|
"@tauri-apps/cli": "^2.11.2",
|
||||||
"@types/node": "^26.6.3",
|
"@types/node": "^25.9.4",
|
||||||
"@types/react": "^19.3.0",
|
"@types/react": "^19.2.17",
|
||||||
"@types/react-dom": "^19.3.0",
|
"@types/react-dom": "^19.2.3",
|
||||||
"@typescript-eslint/eslint-plugin": "^8.71.0",
|
"@typescript-eslint/eslint-plugin": "^8.61.1",
|
||||||
"@typescript-eslint/parser": "^8.71.0",
|
"@typescript-eslint/parser": "^8.61.1",
|
||||||
"@vitejs/plugin-react": "^6.1.1",
|
"@vitejs/plugin-react": "^6.0.2",
|
||||||
"eslint": "^9.39.5",
|
"eslint": "^9.39.4",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-plugin-react": "^7.37.5",
|
"eslint-plugin-react": "^7.37.5",
|
||||||
"eslint-plugin-react-hooks": "^7.1.1",
|
"eslint-plugin-react-hooks": "^7.1.1",
|
||||||
"prettier": "3.9.9",
|
"prettier": "3.8.3",
|
||||||
"typescript": "^6.0.3",
|
"typescript": "^6.0.3",
|
||||||
"vite": "^8.3.1"
|
"vite": "^8.0.16"
|
||||||
},
|
},
|
||||||
"packageManager": "[email protected]"
|
"packageManager": "[email protected]"
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
|
||||||
|
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
|
||||||
|
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
|
||||||
|
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -20,9 +20,6 @@ clap.workspace = true
|
|||||||
compile-time.workspace = true
|
compile-time.workspace = true
|
||||||
env_logger.workspace = true
|
env_logger.workspace = true
|
||||||
futures-util.workspace = true
|
futures-util.workspace = true
|
||||||
uuid.workspace = true
|
|
||||||
zeroize.workspace = true
|
|
||||||
tokio-tungstenite = "0.30"
|
|
||||||
tempfile.workspace = true
|
tempfile.workspace = true
|
||||||
reqwest = { workspace = true, features = ["stream"] }
|
reqwest = { workspace = true, features = ["stream"] }
|
||||||
|
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 27 KiB After Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 2.5 KiB |
|
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 57 KiB After Width: | Height: | Size: 83 KiB |
@@ -1,51 +1,99 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
<defs>
|
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||||
<linearGradient id="ocean" x1="245" y1="170" x2="770" y2="770" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop stop-color="#579bc1"/>
|
|
||||||
<stop offset=".52" stop-color="#438fbd"/>
|
|
||||||
<stop offset="1" stop-color="#2f719e"/>
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="land" x1="260" y1="190" x2="750" y2="735" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop stop-color="#56c78a"/>
|
|
||||||
<stop offset=".55" stop-color="#3bbf78"/>
|
|
||||||
<stop offset="1" stop-color="#279b5d"/>
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="lock" x1="385" y1="400" x2="650" y2="700" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop stop-color="#f3b84c"/>
|
|
||||||
<stop offset=".55" stop-color="#e8a12f"/>
|
|
||||||
<stop offset="1" stop-color="#d4871e"/>
|
|
||||||
</linearGradient>
|
|
||||||
<clipPath id="globe-clip">
|
|
||||||
<circle cx="512" cy="455" r="315"/>
|
|
||||||
</clipPath>
|
|
||||||
<filter id="globe-shadow" x="150" y="90" width="730" height="760" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
|
|
||||||
<feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#174d6f" flood-opacity=".14"/>
|
|
||||||
</filter>
|
|
||||||
<filter id="lock-shadow" x="280" y="210" width="470" height="540" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
|
|
||||||
<feDropShadow dx="0" dy="18" stdDeviation="18" flood-color="#70430c" flood-opacity=".2"/>
|
|
||||||
</filter>
|
|
||||||
</defs>
|
|
||||||
|
|
||||||
<g transform="translate(512 512) scale(1.3) translate(-512 -455)">
|
<svg
|
||||||
<g filter="url(#globe-shadow)">
|
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||||
<circle cx="512" cy="455" r="315" fill="url(#ocean)"/>
|
xmlns:cc="http://creativecommons.org/ns#"
|
||||||
<g clip-path="url(#globe-clip)" fill="url(#land)">
|
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||||
<path d="M177 326c74-121 177-185 302-190-13 51-49 84-105 98-4 45-32 79-86 101-37 17-75 14-111-9Z"/>
|
xmlns:svg="http://www.w3.org/2000/svg"
|
||||||
<path d="M564 135c129 18 229 103 273 220-69-3-121 15-157 54-51-14-83-50-95-107-38-36-45-92-21-167Z"/>
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
<path d="M189 467c63-39 125-34 187 16 57 25 73 73 48 144-45 90-108 146-189 166-58-88-73-197-46-326Z"/>
|
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||||
<path d="M612 572c78-38 157-18 238 59-45 89-122 144-231 164-20-67-22-122-7-165-22-17-22-36 0-58Z"/>
|
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||||
</g>
|
version="1.1"
|
||||||
<circle cx="512" cy="455" r="308" fill="none" stroke="#9ccde2" stroke-width="11" stroke-opacity=".24"/>
|
id="Layer_1"
|
||||||
</g>
|
x="0px"
|
||||||
|
y="0px"
|
||||||
|
viewBox="0 0 96 96"
|
||||||
|
style="enable-background:new 0 0 96 96;"
|
||||||
|
xml:space="preserve"
|
||||||
|
sodipodi:docname="com.yuezk.qt.gpclient.svg"
|
||||||
|
inkscape:version="0.92.4 5da689c313, 2019-01-14"><metadata
|
||||||
|
id="metadata14"><rdf:RDF><cc:Work
|
||||||
|
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
|
||||||
|
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
|
||||||
|
id="defs12" /><sodipodi:namedview
|
||||||
|
pagecolor="#ffffff"
|
||||||
|
bordercolor="#666666"
|
||||||
|
borderopacity="1"
|
||||||
|
objecttolerance="10"
|
||||||
|
gridtolerance="10"
|
||||||
|
guidetolerance="10"
|
||||||
|
inkscape:pageopacity="0"
|
||||||
|
inkscape:pageshadow="2"
|
||||||
|
inkscape:window-width="1920"
|
||||||
|
inkscape:window-height="1006"
|
||||||
|
id="namedview10"
|
||||||
|
showgrid="false"
|
||||||
|
inkscape:zoom="6.9532168"
|
||||||
|
inkscape:cx="7.9545315"
|
||||||
|
inkscape:cy="59.062386"
|
||||||
|
inkscape:window-x="0"
|
||||||
|
inkscape:window-y="0"
|
||||||
|
inkscape:window-maximized="1"
|
||||||
|
inkscape:current-layer="g8499" />
|
||||||
|
<style
|
||||||
|
type="text/css"
|
||||||
|
id="style2">
|
||||||
|
.st0{fill:#2980B9;}
|
||||||
|
.st1{fill:#3498DB;}
|
||||||
|
.st2{fill:#2ECC71;}
|
||||||
|
.st3{fill:#27AE60;}
|
||||||
|
</style>
|
||||||
|
|
||||||
<g transform="translate(512 490) scale(.82) translate(-512 -490)" filter="url(#lock-shadow)">
|
<g
|
||||||
<path d="M405 429v-75c0-142 214-142 214 0v75" fill="none" stroke="#eef1f2" stroke-width="58" stroke-linecap="round"/>
|
id="g8499"
|
||||||
<rect x="340" y="403" width="344" height="278" rx="62" fill="url(#lock)"/>
|
transform="matrix(1.3407388,0,0,1.3407388,-16.409202,-16.355463)"><g
|
||||||
<rect x="346" y="409" width="332" height="266" rx="56" fill="none" stroke="#f7cb75" stroke-width="10" stroke-opacity=".3"/>
|
id="XMLID_1_">
|
||||||
<g fill="#85500f" opacity=".78">
|
<circle
|
||||||
<path d="M501 538h22l16 69h-54Z"/>
|
r="32.5"
|
||||||
<circle cx="512" cy="521" r="27"/>
|
cy="48"
|
||||||
</g>
|
cx="48"
|
||||||
</g>
|
class="st0"
|
||||||
</g>
|
id="XMLID_3_"
|
||||||
</svg>
|
style="fill:#2980b9" />
|
||||||
|
<path
|
||||||
|
d="m 48,15.5 v 65 C 65.9,80.5 80.5,65.7 80.5,48 80.5,30 65.9,15.5 48,15.5 Z"
|
||||||
|
class="st1"
|
||||||
|
id="XMLID_4_"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
style="fill:#3498db" />
|
||||||
|
<path
|
||||||
|
d="m 48,15.5 v 0.6 l 1.2,-0.3 c 0.3,-0.3 0.4,-0.3 0.6,-0.3 h -1.1 z m 7.3,0.9 c -0.1,0 0.4,0.9 1.1,1.8 0.8,1.5 1.1,2.1 1.3,2.1 0.3,-0.3 1.9,-1.2 3,-2.1 -1.7,-0.9 -3.5,-1.5 -5.4,-1.8 z m 10.3,6.2 c -0.1,0 -0.4,0 -0.9,0.6 l -0.8,0.9 0.6,0.6 c 0.3,0.6 0.8,0.9 1,1.2 0.5,0.6 0.6,0.6 0.1,1.5 -0.2,0.6 -0.3,0.9 -0.3,0.9 0.1,0.3 0.3,0.3 1.4,0.3 h 1.6 c 0.1,0 0.3,-0.6 0.4,-1.2 l 0.1,-0.9 -1.1,-0.9 c -1,-0.9 -1,-0.9 -1.4,-1.8 -0.3,-0.6 -0.6,-1.2 -0.7,-1.2 z m -3,2.4 c -0.2,0 -1.3,2.1 -1.3,2.4 0,0 0.3,0.6 0.7,0.9 0.4,0.3 0.7,0.6 0.7,0.6 0.1,0 1.2,-1.2 1.4,-1.5 C 64.2,27.1 64,26.8 63.5,26.2 63.1,25.5 62.7,25 62.6,25 Z m 9.5,1.1 0.2,0.3 c 0,0.3 -0.7,0.9 -1.4,1.5 -1.2,0.9 -1.4,1.2 -2,1.2 -0.6,0 -0.9,0.3 -1.8,0.9 -0.6,0.6 -1.2,0.9 -1.2,1.2 0,0 0.2,0.3 0.6,0.9 0.7,0.6 0.7,0.9 0.2,1.8 l -0.4,0.3 h -1.1 c -0.6,0 -1.5,0 -1.8,-0.3 -0.9,0 -0.8,0 -0.1,2.1 1,3 1.1,3.2 1.3,3.2 0.1,0 1.3,-1.2 2.8,-2.4 1.5,-1.2 2.7,-2.4 2.8,-2.4 l 0.6,0.3 c 0.4,0.3 0.5,0 1.3,-0.6 l 0.8,-0.6 0.8,0.6 c 1.9,1.2 2.2,1.5 2.3,2.4 0.2,1.5 0.3,1.8 0.5,1.8 0.1,0 1.3,-1.5 1.6,-1.8 0.1,-0.3 -0.1,-0.6 -1.1,-2.1 -0.7,-0.9 -1.1,-1.8 -1.1,-2.1 0,0 0.1,0 0.3,-0.3 0.2,0 0.4,0.3 1,0.9 -1.6,-2.3 -3.2,-4.7 -5.1,-6.8 z m 2.8,10.7 c -0.2,0 -0.9,0.9 -0.8,1.2 l 0.5,0.3 H 75 c 0.2,0 0.3,0 0.2,-0.3 C 75.1,37.4 75,36.8 74.9,36.8 Z M 72.3,38 h -2.4 l -2.4,0.3 -4.5,3.5 -4.4,3.8 v 3.5 c 0,2.1 0,3.8 0.1,3.8 0.1,0 0.7,0.9 1.5,1.5 0.8,0.9 1.5,1.5 1.8,1.8 0.4,0.3 0.5,0.3 4,0.6 l 3.4,0.3 1.6,0.9 c 0.8,0.6 1.5,1.2 1.6,1.2 0.1,0 -0.3,0.3 -0.6,0.6 l -0.6,0.6 1,1.2 c 0.5,0.6 1.3,1.5 1.7,1.8 l 0.6,0.9 v 1.7 0.9 c 3.7,-5 5.9,-11.5 6.1,-18.3 0.1,-2.7 -0.3,-5.3 -0.8,-8 l -0.6,-0.3 c -0.1,0 -0.5,0.3 -1,0.6 -0.5,0.3 -1,0.9 -1.1,0.9 -0.1,0 -0.8,-0.3 -1.8,-0.6 l -1.8,-0.6 v -0.9 c 0,-0.6 0,-0.9 -0.6,-1.5 z M 48,63.7 V 64 h 0.2 z"
|
||||||
|
class="st2"
|
||||||
|
id="XMLID_13_"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
style="fill:#2ecc71" />
|
||||||
|
<path
|
||||||
|
d="m 48,15.5 c -3.1,0 -6.2,0.5 -9,1.3 0.3,0.4 0.3,0.4 0.6,0.9 1.5,2.5 1.7,2.8 2.1,2.9 0.3,0 0.9,0.1 1.6,0.1 h 1.2 l 0.9,-2 0.8,-1.9 1.8,-0.6 z m -16.9,4.7 c -2.8,1.7 -5.4,3.9 -7.6,6.4 -3.8,4.3 -6.3,9.6 -7.4,15.4 0.5,0 0.9,-0.1 1.8,-0.1 2.8,0.1 2.5,0 3.4,1.4 0.5,0.8 0.6,0.8 1.4,0.8 1,0.1 0.9,0 0.5,-1.6 -0.2,-0.6 -0.3,-1.2 -0.3,-1.4 0,-0.2 0.5,-0.7 1.7,-1.6 1.9,-1.5 1.8,-1.3 1.5,-2.9 -0.1,-0.3 0.1,-0.6 0.6,-1.2 0.7,-0.7 0.7,-0.6 1.4,-0.6 h 0.7 l 0.1,-1.2 c 0.1,-0.7 0.1,-1.3 0.2,-1.3 0,0 1.9,-1.1 4.1,-2.3 2.2,-1.2 4.1,-2.2 4.2,-2.3 0.2,-0.2 -0.3,-0.8 -2.7,-3.8 -1.5,-1.9 -2.8,-3.6 -2.9,-3.7 z m -5.8,23 c -0.1,0 -0.1,0.3 -0.1,0.6 0,0.6 0,0.7 0.6,1 0.8,0.4 0.9,0.5 0.8,0.2 -0.1,-0.4 -1.2,-1.9 -1.3,-1.8 z m -3.4,2.1 -0.5,1.8 c 0.1,0.1 0.9,0.3 1.8,0.5 1,0.2 1.6,0.4 1.8,0.3 l 0.5,-1.3 z m -3.8,1 -1.1,0.6 c -0.6,0.3 -1.2,0.6 -1.4,0.6 h -0.1 c 0,1.4 0.1,2.8 0.3,4.2 l 0.6,0.4 1,-0.1 h 1 l 0.6,1.4 c 0.3,0.7 0.7,1.4 0.8,1.5 0.1,0.1 1,0.1 1.8,0.1 h 1.5 L 23,56.2 c 0,1.2 0,1.3 -0.6,2.2 -0.4,0.5 -0.6,1.2 -0.6,1.4 0,0.2 0.7,2.1 1.6,4.3 l 1.5,4 1.6,0.8 c 1.2,0.6 1.5,0.8 1.5,1 0,0.1 -0.4,2.1 -0.6,3.1 3,2.5 6.4,4.5 10.2,5.8 3.5,-3.6 6.8,-7.1 7.3,-7.6 l 0.7,-0.7 0.2,-1.9 c 0.2,-1.1 0.4,-2.1 0.4,-2.2 0,-0.1 0.5,-0.6 1,-1.2 0.5,-0.5 0.8,-1 0.8,-1.1 v -0.2 c -0.1,-0.1 -1.4,-1.1 -3,-2.2 l -3.1,-2.1 -1.1,-0.1 c -0.8,0 -1.2,0 -1.3,-0.2 C 39.4,59.2 39.2,58.5 39.1,57.7 39,56.9 38.9,56.2 38.8,56.1 38.8,56 38,56 37.1,56 36.2,56 35.4,55.9 35.3,55.8 35.2,55.7 35.2,55.1 35.1,54.3 35,53.6 34.9,53 34.8,52.9 34.7,52.8 33.7,52.7 32.5,52.6 30.5,52.5 30.1,52.5 29.1,52 l -1.2,-0.6 -1.6,0.7 -1.7,0.9 -1.8,-0.1 c -2,0 -1.9,0.2 -2.1,-1.6 C 20.6,50.7 20.6,50.1 20.5,50.1 20.4,50 20,50 19.6,49.9 L 18.9,49.7 19,49.2 c 0,-0.3 0,-1 0.1,-1.4 L 19.2,47 18.7,46.5 Z m 9.1,1.1 C 27.1,47.5 27.1,47.8 27,48 l -0.1,0.5 2.9,1.2 c 2.9,1.1 3.4,1.2 3.9,0.7 0.2,-0.2 0.1,-0.2 -0.3,-0.4 -0.3,-0.1 -1.7,-0.9 -3.2,-1.6 -1.7,-0.7 -2.9,-1.1 -3,-1 z"
|
||||||
|
class="st3"
|
||||||
|
id="XMLID_20_"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
style="fill:#27ae60" />
|
||||||
|
</g><g
|
||||||
|
transform="matrix(1.458069,0,0,1.458069,-22.631538,-19.615144)"
|
||||||
|
id="g7664"><path
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
id="XMLID_6_"
|
||||||
|
class="st3"
|
||||||
|
d="m 38.8,56.1 c 0,1.2 1,2.2 2.2,2.2 h 15.2 c 1.2,0 2.2,-1 2.2,-2.2 V 45.3 c 0,-1.2 -1,-2.2 -2.2,-2.2 H 40.9 c -1.2,0 -2.2,1 -2.2,2.2 v 10.8 z"
|
||||||
|
style="fill:#f1aa27;fill-opacity:1" /><path
|
||||||
|
style="fill:#e6e6e6"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
id="XMLID_7_"
|
||||||
|
class="st4"
|
||||||
|
d="m 55.5,43.1 h -3.3 v -3.7 c 0,-2.1 -1.7,-3.8 -3.8,-3.8 -2.1,0 -3.8,1.7 -3.8,3.8 v 3.8 h -3.1 v -3.8 c 0,-3.9 3.2,-7 7,-7 3.9,0 7,3.2 7,7 z" /><path
|
||||||
|
style="fill:#e6e6e6;fill-opacity:1"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
id="XMLID_8_"
|
||||||
|
class="st5"
|
||||||
|
d="m 50.35,48.2 c 0,-1 -0.8,-1.8 -1.8,-1.8 -1,0 -1.8,0.8 -1.8,1.8 0,0.7 0.4,1.3 1,1.6 l -1,5.2 h 3.6 l -1,-5.2 c 0.6,-0.3 1,-0.9 1,-1.6 z" /></g></g></svg>
|
||||||
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 6.7 KiB |
@@ -1,31 +1,26 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use gpapi::service::transport::SessionCredential;
|
|
||||||
use log::info;
|
use log::info;
|
||||||
use tauri::{Listener, Manager};
|
use tauri::{Listener, Manager};
|
||||||
use tokio::sync::watch;
|
|
||||||
|
|
||||||
use crate::updater::{GuiUpdater, Installer, ProgressNotifier};
|
use crate::updater::{GuiUpdater, Installer, ProgressNotifier};
|
||||||
|
|
||||||
pub struct App {
|
pub struct App {
|
||||||
credential: Arc<SessionCredential>,
|
api_key: Vec<u8>,
|
||||||
credential_lease: watch::Receiver<bool>,
|
|
||||||
gui_version: String,
|
gui_version: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
pub fn new(credential: Arc<SessionCredential>, credential_lease: watch::Receiver<bool>, gui_version: &str) -> Self {
|
pub fn new(api_key: Vec<u8>, gui_version: &str) -> Self {
|
||||||
Self {
|
Self {
|
||||||
credential,
|
api_key,
|
||||||
credential_lease,
|
|
||||||
gui_version: gui_version.to_string(),
|
gui_version: gui_version.to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn run(&self) -> anyhow::Result<()> {
|
pub fn run(&self) -> anyhow::Result<()> {
|
||||||
let gui_version = self.gui_version.clone();
|
let gui_version = self.gui_version.clone();
|
||||||
let credential = Arc::clone(&self.credential);
|
let api_key = self.api_key.clone();
|
||||||
let credential_lease = self.credential_lease.clone();
|
|
||||||
|
|
||||||
tauri::Builder::default()
|
tauri::Builder::default()
|
||||||
.setup(move |app| {
|
.setup(move |app| {
|
||||||
@@ -33,21 +28,9 @@ impl App {
|
|||||||
let _ = win.hide_menu();
|
let _ = win.hide_menu();
|
||||||
|
|
||||||
let notifier = ProgressNotifier::new(win.clone());
|
let notifier = ProgressNotifier::new(win.clone());
|
||||||
let installer = Installer::new(credential, credential_lease.clone());
|
let installer = Installer::new(api_key);
|
||||||
let updater = Arc::new(GuiUpdater::new(gui_version, notifier, installer));
|
let updater = Arc::new(GuiUpdater::new(gui_version, notifier, installer));
|
||||||
|
|
||||||
let app_handle = app.handle().clone();
|
|
||||||
let mut app_credential_lease = credential_lease;
|
|
||||||
tokio::spawn(async move {
|
|
||||||
while *app_credential_lease.borrow() {
|
|
||||||
if app_credential_lease.changed().await.is_err() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
info!("Service credential lease ended");
|
|
||||||
app_handle.exit(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
let win_clone = win.clone();
|
let win_clone = win.clone();
|
||||||
app.listen_any("app://update-done", move |_event| {
|
app.listen_any("app://update-done", move |_event| {
|
||||||
info!("Update done");
|
info!("Update done");
|
||||||
|
|||||||
@@ -1,15 +1,9 @@
|
|||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use std::{io::Read, sync::Arc};
|
|
||||||
|
|
||||||
use anyhow::{Context, bail};
|
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
clap::InfoLevelVerbosity,
|
clap::InfoLevelVerbosity,
|
||||||
service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential},
|
utils::{base64, env_utils},
|
||||||
utils::env_utils,
|
|
||||||
};
|
};
|
||||||
use log::info;
|
use log::info;
|
||||||
use tokio::sync::watch;
|
|
||||||
use zeroize::Zeroizing;
|
|
||||||
|
|
||||||
use crate::app::App;
|
use crate::app::App;
|
||||||
|
|
||||||
@@ -21,11 +15,13 @@ const VERSION: &str = concat!(
|
|||||||
compile_time::date_str!(),
|
compile_time::date_str!(),
|
||||||
")"
|
")"
|
||||||
);
|
);
|
||||||
|
const GP_API_KEY: &[u8; 32] = &[0; 32];
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[command(version = VERSION)]
|
#[command(version = VERSION)]
|
||||||
struct Cli {
|
struct Cli {
|
||||||
#[arg(long, help = "Read the service credential from stdin")]
|
#[arg(long, help = "Read the API key from stdin")]
|
||||||
service_credential_on_stdin: bool,
|
api_key_on_stdin: bool,
|
||||||
|
|
||||||
#[arg(long, default_value = env!("CARGO_PKG_VERSION"), help = "The version of the GUI")]
|
#[arg(long, default_value = env!("CARGO_PKG_VERSION"), help = "The version of the GUI")]
|
||||||
gui_version: String,
|
gui_version: String,
|
||||||
@@ -36,54 +32,26 @@ struct Cli {
|
|||||||
|
|
||||||
impl Cli {
|
impl Cli {
|
||||||
fn run(&self) -> anyhow::Result<()> {
|
fn run(&self) -> anyhow::Result<()> {
|
||||||
let credential = self.read_credential()?;
|
let api_key = self.read_api_key()?;
|
||||||
let credential_lease = monitor_credential_lease().context("Failed to monitor service credential lifetime")?;
|
let app = App::new(api_key, &self.gui_version);
|
||||||
let app = App::new(Arc::new(credential), credential_lease, &self.gui_version);
|
|
||||||
|
|
||||||
env_utils::patch_gui_runtime_env(false);
|
env_utils::patch_gui_runtime_env(false);
|
||||||
|
|
||||||
app.run()
|
app.run()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_credential(&self) -> anyhow::Result<SessionCredential> {
|
fn read_api_key(&self) -> anyhow::Result<Vec<u8>> {
|
||||||
if !self.service_credential_on_stdin {
|
if self.api_key_on_stdin {
|
||||||
bail!("Service credential must be provided via --service-credential-on-stdin");
|
let mut api_key = String::new();
|
||||||
}
|
std::io::stdin().read_line(&mut api_key)?;
|
||||||
let stdin = std::io::stdin();
|
|
||||||
let mut input = stdin.lock();
|
|
||||||
let mut header = [0_u8; 2];
|
|
||||||
input
|
|
||||||
.read_exact(&mut header)
|
|
||||||
.context("Failed to read service credential header")?;
|
|
||||||
let payload_len = u16::from_be_bytes(header) as usize;
|
|
||||||
if payload_len == 0 || payload_len + header.len() > MAX_CREDENTIAL_FRAME {
|
|
||||||
bail!("Invalid service credential length");
|
|
||||||
}
|
|
||||||
let mut frame = Zeroizing::new(Vec::with_capacity(payload_len + header.len()));
|
|
||||||
frame.extend_from_slice(&header);
|
|
||||||
frame.resize(payload_len + header.len(), 0);
|
|
||||||
input
|
|
||||||
.read_exact(&mut frame[header.len()..])
|
|
||||||
.context("Failed to read service credential")?;
|
|
||||||
SessionCredential::decode_frame(&frame).context("Invalid service credential")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn monitor_credential_lease() -> std::io::Result<watch::Receiver<bool>> {
|
let api_key = base64::decode_to_vec(api_key.trim())?;
|
||||||
let (lease_tx, lease_rx) = watch::channel(true);
|
|
||||||
std::thread::Builder::new()
|
|
||||||
.name("credential-lease".to_owned())
|
|
||||||
.spawn(move || {
|
|
||||||
let stdin = std::io::stdin();
|
|
||||||
close_credential_lease_at_eof(stdin.lock(), lease_tx);
|
|
||||||
})?;
|
|
||||||
Ok(lease_rx)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn close_credential_lease_at_eof(mut input: impl Read, lease_tx: watch::Sender<bool>) {
|
Ok(api_key)
|
||||||
let mut buffer = [0_u8; 256];
|
} else {
|
||||||
while matches!(input.read(&mut buffer), Ok(len) if len > 0) {}
|
Ok(GP_API_KEY.to_vec())
|
||||||
let _ = lease_tx.send(false);
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn init_logger(cli: &Cli) {
|
fn init_logger(cli: &Cli) {
|
||||||
@@ -103,17 +71,3 @@ pub fn run() {
|
|||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use std::io::Cursor;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn credential_lease_closes_at_eof() {
|
|
||||||
let (lease_tx, lease_rx) = watch::channel(true);
|
|
||||||
close_credential_lease_at_eof(Cursor::new(b"ignored lease bytes"), lease_tx);
|
|
||||||
assert!(!*lease_rx.borrow());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +1,11 @@
|
|||||||
use std::{
|
use std::sync::{Arc, RwLock};
|
||||||
error::Error,
|
|
||||||
fmt::{self, Display, Formatter},
|
|
||||||
sync::{Arc, RwLock},
|
|
||||||
time::Duration,
|
|
||||||
};
|
|
||||||
|
|
||||||
use anyhow::{Context, bail};
|
|
||||||
use futures_util::{SinkExt, StreamExt};
|
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
service::{
|
service::request::UpdateGuiRequest,
|
||||||
request::{UpdateGuiRequest, WsRequest},
|
utils::{checksum::verify_checksum, crypto::Crypto, endpoint::http_endpoint},
|
||||||
transport::{
|
|
||||||
ClientMessage, ClientPrelude, MAX_WS_MESSAGE, NoiseInitiator, NoiseTransport, ServerMessage, ServerPrelude,
|
|
||||||
ServiceResult, SessionCredential,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
utils::{checksum::verify_checksum, endpoint::ws_endpoint},
|
|
||||||
};
|
};
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
use tauri::{Emitter, WebviewWindow};
|
use tauri::{Emitter, WebviewWindow};
|
||||||
use tokio::net::TcpStream;
|
|
||||||
use tokio::sync::{mpsc, oneshot, watch};
|
|
||||||
use tokio_tungstenite::{
|
|
||||||
MaybeTlsStream, WebSocketStream, connect_async_with_config,
|
|
||||||
tungstenite::{Message, protocol::WebSocketConfig},
|
|
||||||
};
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::downloader::{ChecksumFetcher, FileDownloader};
|
use crate::downloader::{ChecksumFetcher, FileDownloader};
|
||||||
|
|
||||||
@@ -41,22 +21,6 @@ const GUI_LIBC_SUFFIX: &str = "-musl";
|
|||||||
#[cfg(not(target_env = "musl"))]
|
#[cfg(not(target_env = "musl"))]
|
||||||
const GUI_LIBC_SUFFIX: &str = "";
|
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 {
|
pub struct ProgressNotifier {
|
||||||
win: WebviewWindow,
|
win: WebviewWindow,
|
||||||
}
|
}
|
||||||
@@ -80,284 +44,33 @@ impl ProgressNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct Installer {
|
pub struct Installer {
|
||||||
command_tx: mpsc::Sender<InstallCommand>,
|
crypto: Crypto,
|
||||||
}
|
|
||||||
|
|
||||||
struct InstallCommand {
|
|
||||||
request: UpdateGuiRequest,
|
|
||||||
reply: oneshot::Sender<anyhow::Result<()>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Installer {
|
impl Installer {
|
||||||
pub fn new(credential: Arc<SessionCredential>, credential_lease: watch::Receiver<bool>) -> Self {
|
pub fn new(api_key: Vec<u8>) -> Self {
|
||||||
let (command_tx, command_rx) = mpsc::channel(1);
|
Self {
|
||||||
tokio::spawn(async move {
|
crypto: Crypto::new(api_key),
|
||||||
run_installer(credential, credential_lease, command_rx).await;
|
}
|
||||||
});
|
|
||||||
Self { command_tx }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn install(&self, path: &str, checksum: &str) -> anyhow::Result<()> {
|
async fn install(&self, path: &str, checksum: &str) -> anyhow::Result<()> {
|
||||||
|
let service_endpoint = http_endpoint().await?;
|
||||||
|
|
||||||
let request = UpdateGuiRequest {
|
let request = UpdateGuiRequest {
|
||||||
path: path.to_string(),
|
path: path.to_string(),
|
||||||
checksum: checksum.to_string(),
|
checksum: checksum.to_string(),
|
||||||
};
|
};
|
||||||
let (reply, result) = oneshot::channel();
|
let payload = self.crypto.encrypt(&request)?;
|
||||||
self
|
|
||||||
.command_tx
|
|
||||||
.send(InstallCommand { request, reply })
|
|
||||||
.await
|
|
||||||
.context("Authenticated GUI installer is unavailable")?;
|
|
||||||
tokio::time::timeout(Duration::from_secs(60), result)
|
|
||||||
.await
|
|
||||||
.context("Service update request timed out")?
|
|
||||||
.context("Authenticated GUI installer stopped before replying")?
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
|
reqwest::Client::default()
|
||||||
|
.post(format!("{}/update-gui", service_endpoint))
|
||||||
|
.body(payload)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.error_for_status()?;
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct TerminalConnectError(String);
|
|
||||||
|
|
||||||
impl Display for TerminalConnectError {
|
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
|
||||||
formatter.write_str(&self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Error for TerminalConnectError {}
|
|
||||||
|
|
||||||
async fn run_installer(
|
|
||||||
credential: Arc<SessionCredential>,
|
|
||||||
mut credential_lease: watch::Receiver<bool>,
|
|
||||||
mut commands: mpsc::Receiver<InstallCommand>,
|
|
||||||
) {
|
|
||||||
let mut pending = None;
|
|
||||||
|
|
||||||
loop {
|
|
||||||
if !*credential_lease.borrow() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let connection = tokio::select! {
|
|
||||||
changed = credential_lease.changed() => {
|
|
||||||
if changed.is_err() || !*credential_lease.borrow() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
result = tokio::time::timeout(Duration::from_secs(5), connect_installer(&credential)) => {
|
|
||||||
match result {
|
|
||||||
Ok(result) => result,
|
|
||||||
Err(_) => Err(anyhow::anyhow!("Authenticated GUI installer handshake timed out")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
match connection {
|
|
||||||
Ok((mut socket, mut noise)) => {
|
|
||||||
info!("Authenticated GUI installer connected");
|
|
||||||
match run_installer_connection(
|
|
||||||
&mut socket,
|
|
||||||
&mut noise,
|
|
||||||
&mut credential_lease,
|
|
||||||
&mut commands,
|
|
||||||
&mut pending,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(ConnectionEnd::CredentialLeaseEnded | ConnectionEnd::CommandsClosed) => return,
|
|
||||||
Err(err) => warn!("Authenticated GUI installer connection lost: {err}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) if err.is::<TerminalConnectError>() => {
|
|
||||||
warn!("Authenticated GUI installer stopped: {err}");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Err(err) => warn!("Authenticated GUI installer connection failed: {err}"),
|
|
||||||
}
|
|
||||||
|
|
||||||
tokio::select! {
|
|
||||||
changed = credential_lease.changed() => {
|
|
||||||
if changed.is_err() || !*credential_lease.borrow() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ = tokio::time::sleep(Duration::from_millis(100)) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
enum ConnectionEnd {
|
|
||||||
CredentialLeaseEnded,
|
|
||||||
CommandsClosed,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn run_installer_connection(
|
|
||||||
socket: &mut Socket,
|
|
||||||
noise: &mut NoiseTransport,
|
|
||||||
credential_lease: &mut watch::Receiver<bool>,
|
|
||||||
commands: &mut mpsc::Receiver<InstallCommand>,
|
|
||||||
pending: &mut Option<InstallCommand>,
|
|
||||||
) -> anyhow::Result<ConnectionEnd> {
|
|
||||||
if pending.as_ref().is_some_and(|command| command.reply.is_closed()) {
|
|
||||||
pending.take();
|
|
||||||
}
|
|
||||||
let mut pending_id = match pending.as_ref() {
|
|
||||||
Some(command) => Some(send_install_command(socket, noise, command).await?),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
loop {
|
|
||||||
tokio::select! {
|
|
||||||
changed = credential_lease.changed() => {
|
|
||||||
if changed.is_err() || !*credential_lease.borrow() {
|
|
||||||
return Ok(ConnectionEnd::CredentialLeaseEnded);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
command = commands.recv() => {
|
|
||||||
let Some(command) = command else { return Ok(ConnectionEnd::CommandsClosed) };
|
|
||||||
if command.reply.is_closed() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if pending.is_some() {
|
|
||||||
let _ = command.reply.send(Err(anyhow::anyhow!("GUI installation is already pending")));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
*pending = Some(command);
|
|
||||||
pending_id = Some(send_install_command(socket, noise, pending.as_ref().unwrap()).await?);
|
|
||||||
}
|
|
||||||
frame = socket.next() => {
|
|
||||||
match frame.context("Service closed the authenticated GUI installer")?? {
|
|
||||||
Message::Binary(data) => match noise.decrypt::<ServerMessage>(&data)? {
|
|
||||||
ServerMessage::Reply { id, result } => {
|
|
||||||
if pending_id != Some(id) {
|
|
||||||
bail!("Service sent a mismatched GUI installation reply");
|
|
||||||
}
|
|
||||||
let Some(command) = pending.take() else {
|
|
||||||
bail!("Service sent an unexpected GUI installation reply");
|
|
||||||
};
|
|
||||||
pending_id = None;
|
|
||||||
let result = match result {
|
|
||||||
ServiceResult::Accepted => Ok(()),
|
|
||||||
ServiceResult::Rejected(rejection) => Err(anyhow::anyhow!(
|
|
||||||
"Service rejected GUI installation ({:?}): {}",
|
|
||||||
rejection.code(),
|
|
||||||
rejection.message()
|
|
||||||
)),
|
|
||||||
_ => Err(anyhow::anyhow!("Service sent an unexpected GUI installation reply")),
|
|
||||||
};
|
|
||||||
let _ = command.reply.send(result);
|
|
||||||
}
|
|
||||||
ServerMessage::Event { .. } | ServerMessage::Snapshot { .. } => {}
|
|
||||||
ServerMessage::Attached { .. } => bail!("Service sent a duplicate attach response"),
|
|
||||||
},
|
|
||||||
Message::Ping(data) => socket.send(Message::Pong(data)).await?,
|
|
||||||
Message::Pong(_) => {}
|
|
||||||
Message::Close(_) => bail!("Service closed the authenticated GUI installer"),
|
|
||||||
_ => bail!("Service sent an unexpected WebSocket frame"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn send_install_command(
|
|
||||||
socket: &mut Socket,
|
|
||||||
noise: &mut NoiseTransport,
|
|
||||||
command: &InstallCommand,
|
|
||||||
) -> anyhow::Result<Uuid> {
|
|
||||||
let id = Uuid::new_v4();
|
|
||||||
send_client_message(
|
|
||||||
socket,
|
|
||||||
noise,
|
|
||||||
&ClientMessage::Request {
|
|
||||||
id,
|
|
||||||
request: WsRequest::UpdateGui(command.request.clone()),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
Ok(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn connect_installer(credential: &SessionCredential) -> anyhow::Result<(Socket, NoiseTransport)> {
|
|
||||||
let endpoint = ws_endpoint().await?;
|
|
||||||
connect_installer_at(credential, &endpoint).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn connect_installer_at(
|
|
||||||
credential: &SessionCredential,
|
|
||||||
endpoint: &str,
|
|
||||||
) -> anyhow::Result<(Socket, NoiseTransport)> {
|
|
||||||
if credential.product_version() != env!("CARGO_PKG_VERSION") {
|
|
||||||
return Err(TerminalConnectError("Service credential version does not match gpgui-helper".to_owned()).into());
|
|
||||||
}
|
|
||||||
let config = WebSocketConfig::default()
|
|
||||||
.max_message_size(Some(MAX_WS_MESSAGE))
|
|
||||||
.max_frame_size(Some(MAX_WS_MESSAGE));
|
|
||||||
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(),
|
|
||||||
};
|
|
||||||
socket.send(Message::Binary(prelude.encode()?.into())).await?;
|
|
||||||
let server_prelude = ServerPrelude::decode(&receive_binary(&mut socket).await?)
|
|
||||||
.map_err(|err| TerminalConnectError(format!("Service sent an invalid update-session response: {err}")))?;
|
|
||||||
match server_prelude {
|
|
||||||
ServerPrelude::Ready => {}
|
|
||||||
ServerPrelude::Rejected(reason) => {
|
|
||||||
return Err(TerminalConnectError(format!("Service rejected the update session: {reason:?}")).into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut initiator = NoiseInitiator::new(
|
|
||||||
credential.product_version(),
|
|
||||||
credential.service_instance_id(),
|
|
||||||
credential.session_id(),
|
|
||||||
credential.secret(),
|
|
||||||
)?;
|
|
||||||
socket.send(Message::Binary(initiator.write_first()?.into())).await?;
|
|
||||||
let mut noise = initiator.read_response(&receive_binary(&mut socket).await?)?;
|
|
||||||
send_client_message(
|
|
||||||
&mut socket,
|
|
||||||
&mut noise,
|
|
||||||
&ClientMessage::Attach {
|
|
||||||
last_event_revision: None,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
if !matches!(
|
|
||||||
receive_server_message(&mut socket, &mut noise).await?,
|
|
||||||
ServerMessage::Attached { .. }
|
|
||||||
) {
|
|
||||||
bail!("Service did not attach the update session");
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok((socket, noise))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn send_client_message(
|
|
||||||
socket: &mut Socket,
|
|
||||||
noise: &mut NoiseTransport,
|
|
||||||
message: &ClientMessage,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
socket.send(Message::Binary(noise.encrypt(message)?.into())).await?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
|
||||||
|
|
||||||
async fn receive_server_message(socket: &mut Socket, noise: &mut NoiseTransport) -> anyhow::Result<ServerMessage> {
|
|
||||||
Ok(noise.decrypt(&receive_binary(socket).await?)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn receive_binary(socket: &mut Socket) -> anyhow::Result<Vec<u8>> {
|
|
||||||
match socket.next().await {
|
|
||||||
Some(Ok(Message::Binary(data))) => Ok(data.to_vec()),
|
|
||||||
Some(Ok(_)) => bail!("Service sent an unexpected handshake frame"),
|
|
||||||
Some(Err(err)) => Err(err.into()),
|
|
||||||
None => bail!("Service closed during handshake"),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -381,10 +94,10 @@ impl GuiUpdater {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn update(&self) {
|
pub async fn update(&self) {
|
||||||
let Some(asset_name) = gui_asset_name() else {
|
if !cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) {
|
||||||
info!("GUI updates are not supported on this platform.");
|
info!("GUI version is not supported on this architecture.");
|
||||||
return;
|
return;
|
||||||
};
|
}
|
||||||
info!("Update GUI, version: {}", self.version);
|
info!("Update GUI, version: {}", self.version);
|
||||||
|
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
@@ -396,8 +109,16 @@ impl GuiUpdater {
|
|||||||
format!("v{}", self.version)
|
format!("v{}", self.version)
|
||||||
};
|
};
|
||||||
|
|
||||||
let file_url =
|
let arch = if cfg!(target_arch = "x86_64") {
|
||||||
format!("https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{release_tag}/{asset_name}");
|
"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);
|
let checksum_url = format!("{}.sha256", file_url);
|
||||||
|
|
||||||
info!("Downloading file: {}", file_url);
|
info!("Downloading file: {}", file_url);
|
||||||
@@ -485,188 +206,3 @@ impl GuiUpdater {
|
|||||||
self.notifier.notify(progress);
|
self.notifier.notify(progress);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use gpapi::{
|
|
||||||
os_profile::HostIdentity,
|
|
||||||
service::{
|
|
||||||
transport::{ClientPrelude, NoiseResponder},
|
|
||||||
vpn_env::{HostInfo, VpnEnv},
|
|
||||||
vpn_state::VpnState,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
use tokio::net::TcpListener;
|
|
||||||
use tokio_tungstenite::accept_async;
|
|
||||||
|
|
||||||
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());
|
|
||||||
let (command_tx, mut commands) = mpsc::channel(1);
|
|
||||||
let (reply_tx, reply_rx) = oneshot::channel();
|
|
||||||
command_tx
|
|
||||||
.send(InstallCommand {
|
|
||||||
request: UpdateGuiRequest {
|
|
||||||
path: "/tmp/gpgui-update".to_owned(),
|
|
||||||
checksum: "checksum".to_owned(),
|
|
||||||
},
|
|
||||||
reply: reply_tx,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let (_lease_tx, mut credential_lease) = watch::channel(true);
|
|
||||||
let mut pending = None;
|
|
||||||
|
|
||||||
let (first_endpoint, first_service) = spawn_test_service(Arc::clone(&credential), false).await;
|
|
||||||
let (mut socket, mut noise) = connect_installer_at(&credential, &first_endpoint).await.unwrap();
|
|
||||||
assert!(
|
|
||||||
run_installer_connection(
|
|
||||||
&mut socket,
|
|
||||||
&mut noise,
|
|
||||||
&mut credential_lease,
|
|
||||||
&mut commands,
|
|
||||||
&mut pending,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
first_service.await.unwrap();
|
|
||||||
assert!(pending.is_some());
|
|
||||||
|
|
||||||
let (second_endpoint, second_service) = spawn_test_service(Arc::clone(&credential), true).await;
|
|
||||||
let (mut socket, mut noise) = connect_installer_at(&credential, &second_endpoint).await.unwrap();
|
|
||||||
assert!(
|
|
||||||
run_installer_connection(
|
|
||||||
&mut socket,
|
|
||||||
&mut noise,
|
|
||||||
&mut credential_lease,
|
|
||||||
&mut commands,
|
|
||||||
&mut pending,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
second_service.await.unwrap();
|
|
||||||
assert!(pending.is_none());
|
|
||||||
assert!(reply_rx.await.unwrap().is_ok());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn credential_version_mismatch_is_terminal() {
|
|
||||||
let credential = SessionCredential::generate(Uuid::new_v4(), "different-version").unwrap();
|
|
||||||
let Err(err) = connect_installer_at(&credential, "ws://127.0.0.1:1/ws").await else {
|
|
||||||
panic!("version mismatch should fail before connecting");
|
|
||||||
};
|
|
||||||
assert!(err.is::<TerminalConnectError>());
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn spawn_test_service(
|
|
||||||
credential: Arc<SessionCredential>,
|
|
||||||
reply: bool,
|
|
||||||
) -> (String, tokio::task::JoinHandle<()>) {
|
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
||||||
let endpoint = format!("ws://{}/ws", listener.local_addr().unwrap());
|
|
||||||
let service = tokio::spawn(async move {
|
|
||||||
let (stream, _) = listener.accept().await.unwrap();
|
|
||||||
let mut socket = accept_async(stream).await.unwrap();
|
|
||||||
let prelude = match socket.next().await.unwrap().unwrap() {
|
|
||||||
Message::Binary(data) => ClientPrelude::decode(&data).unwrap(),
|
|
||||||
frame => panic!("unexpected prelude frame: {frame:?}"),
|
|
||||||
};
|
|
||||||
assert_eq!(prelude.service_instance_id, credential.service_instance_id());
|
|
||||||
assert_eq!(prelude.session_id, credential.session_id());
|
|
||||||
socket
|
|
||||||
.send(Message::Binary(ServerPrelude::Ready.encode().unwrap().into()))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let mut responder = NoiseResponder::new(
|
|
||||||
credential.product_version(),
|
|
||||||
credential.service_instance_id(),
|
|
||||||
credential.session_id(),
|
|
||||||
credential.secret(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let first = match socket.next().await.unwrap().unwrap() {
|
|
||||||
Message::Binary(data) => data,
|
|
||||||
frame => panic!("unexpected handshake frame: {frame:?}"),
|
|
||||||
};
|
|
||||||
responder.read_first(&first).unwrap();
|
|
||||||
let (response, mut noise) = responder.write_response().unwrap();
|
|
||||||
socket.send(Message::Binary(response.into())).await.unwrap();
|
|
||||||
|
|
||||||
let attach = match socket.next().await.unwrap().unwrap() {
|
|
||||||
Message::Binary(data) => data,
|
|
||||||
frame => panic!("unexpected attach frame: {frame:?}"),
|
|
||||||
};
|
|
||||||
assert!(matches!(
|
|
||||||
noise.decrypt::<ClientMessage>(&attach).unwrap(),
|
|
||||||
ClientMessage::Attach { .. }
|
|
||||||
));
|
|
||||||
let attached = ServerMessage::Attached {
|
|
||||||
connection_id: Uuid::new_v4(),
|
|
||||||
current_revision: 0,
|
|
||||||
snapshot: VpnEnv {
|
|
||||||
vpn_state: VpnState::Disconnected,
|
|
||||||
vpnc_script: None,
|
|
||||||
auth_executable: String::new(),
|
|
||||||
host_info: HostInfo {
|
|
||||||
host_identity: HostIdentity::collect(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
socket
|
|
||||||
.send(Message::Binary(noise.encrypt(&attached).unwrap().into()))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let request = match socket.next().await.unwrap().unwrap() {
|
|
||||||
Message::Binary(data) => noise.decrypt::<ClientMessage>(&data).unwrap(),
|
|
||||||
frame => panic!("unexpected request frame: {frame:?}"),
|
|
||||||
};
|
|
||||||
let ClientMessage::Request {
|
|
||||||
id,
|
|
||||||
request: WsRequest::UpdateGui(update),
|
|
||||||
} = request
|
|
||||||
else {
|
|
||||||
panic!("unexpected installer request");
|
|
||||||
};
|
|
||||||
assert_eq!(update.path, "/tmp/gpgui-update");
|
|
||||||
if reply {
|
|
||||||
let message = ServerMessage::Reply {
|
|
||||||
id,
|
|
||||||
result: ServiceResult::Accepted,
|
|
||||||
};
|
|
||||||
socket
|
|
||||||
.send(Message::Binary(noise.encrypt(&message).unwrap().into()))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
socket.close(None).await.unwrap();
|
|
||||||
});
|
|
||||||
(endpoint, service)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -15,15 +15,15 @@
|
|||||||
},
|
},
|
||||||
"windows": [
|
"windows": [
|
||||||
{
|
{
|
||||||
"title": "GPGUI Downloader",
|
"title": "GP Connect Helper",
|
||||||
"center": true,
|
"center": true,
|
||||||
"resizable": true,
|
"resizable": true,
|
||||||
"width": 460,
|
"width": 500,
|
||||||
"height": 104,
|
"height": 100,
|
||||||
"minWidth": 460,
|
"minWidth": 500,
|
||||||
"minHeight": 104,
|
"minHeight": 100,
|
||||||
"maxWidth": 460,
|
"maxWidth": 500,
|
||||||
"maxHeight": 104,
|
"maxHeight": 100,
|
||||||
"label": "main",
|
"label": "main",
|
||||||
"decorations": false
|
"decorations": false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
|
||||||
<defs>
|
|
||||||
<linearGradient id="ocean" x1="245" y1="170" x2="770" y2="770" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop stop-color="#579bc1"/>
|
|
||||||
<stop offset=".52" stop-color="#438fbd"/>
|
|
||||||
<stop offset="1" stop-color="#2f719e"/>
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="land" x1="260" y1="190" x2="750" y2="735" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop stop-color="#56c78a"/>
|
|
||||||
<stop offset=".55" stop-color="#3bbf78"/>
|
|
||||||
<stop offset="1" stop-color="#279b5d"/>
|
|
||||||
</linearGradient>
|
|
||||||
<linearGradient id="lock" x1="385" y1="400" x2="650" y2="700" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop stop-color="#f3b84c"/>
|
|
||||||
<stop offset=".55" stop-color="#e8a12f"/>
|
|
||||||
<stop offset="1" stop-color="#d4871e"/>
|
|
||||||
</linearGradient>
|
|
||||||
<clipPath id="globe-clip">
|
|
||||||
<circle cx="512" cy="455" r="315"/>
|
|
||||||
</clipPath>
|
|
||||||
</defs>
|
|
||||||
|
|
||||||
<g transform="translate(512 512) scale(1.3) translate(-512 -455)">
|
|
||||||
<circle cx="512" cy="455" r="315" fill="url(#ocean)"/>
|
|
||||||
<g clip-path="url(#globe-clip)" fill="url(#land)">
|
|
||||||
<path d="M177 326c74-121 177-185 302-190-13 51-49 84-105 98-4 45-32 79-86 101-37 17-75 14-111-9Z"/>
|
|
||||||
<path d="M564 135c129 18 229 103 273 220-69-3-121 15-157 54-51-14-83-50-95-107-38-36-45-92-21-167Z"/>
|
|
||||||
<path d="M189 467c63-39 125-34 187 16 57 25 73 73 48 144-45 90-108 146-189 166-58-88-73-197-46-326Z"/>
|
|
||||||
<path d="M612 572c78-38 157-18 238 59-45 89-122 144-231 164-20-67-22-122-7-165-22-17-22-36 0-58Z"/>
|
|
||||||
</g>
|
|
||||||
<circle cx="512" cy="455" r="308" fill="none" stroke="#9ccde2" stroke-width="11" stroke-opacity=".4"/>
|
|
||||||
|
|
||||||
<g transform="translate(512 490) scale(.82) translate(-512 -490)">
|
|
||||||
<path d="M405 429v-75c0-142 214-142 214 0v75" fill="none" stroke="#eef1f2" stroke-width="58" stroke-linecap="round"/>
|
|
||||||
<rect x="340" y="403" width="344" height="278" rx="62" fill="url(#lock)"/>
|
|
||||||
<rect x="346" y="409" width="332" height="266" rx="56" fill="none" stroke="#f7cb75" stroke-width="10" stroke-opacity=".45"/>
|
|
||||||
<g fill="#85500f" opacity=".85">
|
|
||||||
<path d="M501 538h22l16 69h-54Z"/>
|
|
||||||
<circle cx="512" cy="521" r="27"/>
|
|
||||||
</g>
|
|
||||||
</g>
|
|
||||||
</g>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 2.2 KiB |
@@ -0,0 +1,99 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||||
|
|
||||||
|
<svg
|
||||||
|
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||||
|
xmlns:cc="http://creativecommons.org/ns#"
|
||||||
|
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||||
|
xmlns:svg="http://www.w3.org/2000/svg"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||||
|
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||||
|
version="1.1"
|
||||||
|
id="Layer_1"
|
||||||
|
x="0px"
|
||||||
|
y="0px"
|
||||||
|
viewBox="0 0 96 96"
|
||||||
|
style="enable-background:new 0 0 96 96;"
|
||||||
|
xml:space="preserve"
|
||||||
|
sodipodi:docname="com.yuezk.qt.gpclient.svg"
|
||||||
|
inkscape:version="0.92.4 5da689c313, 2019-01-14"><metadata
|
||||||
|
id="metadata14"><rdf:RDF><cc:Work
|
||||||
|
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
|
||||||
|
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
|
||||||
|
id="defs12" /><sodipodi:namedview
|
||||||
|
pagecolor="#ffffff"
|
||||||
|
bordercolor="#666666"
|
||||||
|
borderopacity="1"
|
||||||
|
objecttolerance="10"
|
||||||
|
gridtolerance="10"
|
||||||
|
guidetolerance="10"
|
||||||
|
inkscape:pageopacity="0"
|
||||||
|
inkscape:pageshadow="2"
|
||||||
|
inkscape:window-width="1920"
|
||||||
|
inkscape:window-height="1006"
|
||||||
|
id="namedview10"
|
||||||
|
showgrid="false"
|
||||||
|
inkscape:zoom="6.9532168"
|
||||||
|
inkscape:cx="7.9545315"
|
||||||
|
inkscape:cy="59.062386"
|
||||||
|
inkscape:window-x="0"
|
||||||
|
inkscape:window-y="0"
|
||||||
|
inkscape:window-maximized="1"
|
||||||
|
inkscape:current-layer="g8499" />
|
||||||
|
<style
|
||||||
|
type="text/css"
|
||||||
|
id="style2">
|
||||||
|
.st0{fill:#2980B9;}
|
||||||
|
.st1{fill:#3498DB;}
|
||||||
|
.st2{fill:#2ECC71;}
|
||||||
|
.st3{fill:#27AE60;}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<g
|
||||||
|
id="g8499"
|
||||||
|
transform="matrix(1.3407388,0,0,1.3407388,-16.409202,-16.355463)"><g
|
||||||
|
id="XMLID_1_">
|
||||||
|
<circle
|
||||||
|
r="32.5"
|
||||||
|
cy="48"
|
||||||
|
cx="48"
|
||||||
|
class="st0"
|
||||||
|
id="XMLID_3_"
|
||||||
|
style="fill:#2980b9" />
|
||||||
|
<path
|
||||||
|
d="m 48,15.5 v 65 C 65.9,80.5 80.5,65.7 80.5,48 80.5,30 65.9,15.5 48,15.5 Z"
|
||||||
|
class="st1"
|
||||||
|
id="XMLID_4_"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
style="fill:#3498db" />
|
||||||
|
<path
|
||||||
|
d="m 48,15.5 v 0.6 l 1.2,-0.3 c 0.3,-0.3 0.4,-0.3 0.6,-0.3 h -1.1 z m 7.3,0.9 c -0.1,0 0.4,0.9 1.1,1.8 0.8,1.5 1.1,2.1 1.3,2.1 0.3,-0.3 1.9,-1.2 3,-2.1 -1.7,-0.9 -3.5,-1.5 -5.4,-1.8 z m 10.3,6.2 c -0.1,0 -0.4,0 -0.9,0.6 l -0.8,0.9 0.6,0.6 c 0.3,0.6 0.8,0.9 1,1.2 0.5,0.6 0.6,0.6 0.1,1.5 -0.2,0.6 -0.3,0.9 -0.3,0.9 0.1,0.3 0.3,0.3 1.4,0.3 h 1.6 c 0.1,0 0.3,-0.6 0.4,-1.2 l 0.1,-0.9 -1.1,-0.9 c -1,-0.9 -1,-0.9 -1.4,-1.8 -0.3,-0.6 -0.6,-1.2 -0.7,-1.2 z m -3,2.4 c -0.2,0 -1.3,2.1 -1.3,2.4 0,0 0.3,0.6 0.7,0.9 0.4,0.3 0.7,0.6 0.7,0.6 0.1,0 1.2,-1.2 1.4,-1.5 C 64.2,27.1 64,26.8 63.5,26.2 63.1,25.5 62.7,25 62.6,25 Z m 9.5,1.1 0.2,0.3 c 0,0.3 -0.7,0.9 -1.4,1.5 -1.2,0.9 -1.4,1.2 -2,1.2 -0.6,0 -0.9,0.3 -1.8,0.9 -0.6,0.6 -1.2,0.9 -1.2,1.2 0,0 0.2,0.3 0.6,0.9 0.7,0.6 0.7,0.9 0.2,1.8 l -0.4,0.3 h -1.1 c -0.6,0 -1.5,0 -1.8,-0.3 -0.9,0 -0.8,0 -0.1,2.1 1,3 1.1,3.2 1.3,3.2 0.1,0 1.3,-1.2 2.8,-2.4 1.5,-1.2 2.7,-2.4 2.8,-2.4 l 0.6,0.3 c 0.4,0.3 0.5,0 1.3,-0.6 l 0.8,-0.6 0.8,0.6 c 1.9,1.2 2.2,1.5 2.3,2.4 0.2,1.5 0.3,1.8 0.5,1.8 0.1,0 1.3,-1.5 1.6,-1.8 0.1,-0.3 -0.1,-0.6 -1.1,-2.1 -0.7,-0.9 -1.1,-1.8 -1.1,-2.1 0,0 0.1,0 0.3,-0.3 0.2,0 0.4,0.3 1,0.9 -1.6,-2.3 -3.2,-4.7 -5.1,-6.8 z m 2.8,10.7 c -0.2,0 -0.9,0.9 -0.8,1.2 l 0.5,0.3 H 75 c 0.2,0 0.3,0 0.2,-0.3 C 75.1,37.4 75,36.8 74.9,36.8 Z M 72.3,38 h -2.4 l -2.4,0.3 -4.5,3.5 -4.4,3.8 v 3.5 c 0,2.1 0,3.8 0.1,3.8 0.1,0 0.7,0.9 1.5,1.5 0.8,0.9 1.5,1.5 1.8,1.8 0.4,0.3 0.5,0.3 4,0.6 l 3.4,0.3 1.6,0.9 c 0.8,0.6 1.5,1.2 1.6,1.2 0.1,0 -0.3,0.3 -0.6,0.6 l -0.6,0.6 1,1.2 c 0.5,0.6 1.3,1.5 1.7,1.8 l 0.6,0.9 v 1.7 0.9 c 3.7,-5 5.9,-11.5 6.1,-18.3 0.1,-2.7 -0.3,-5.3 -0.8,-8 l -0.6,-0.3 c -0.1,0 -0.5,0.3 -1,0.6 -0.5,0.3 -1,0.9 -1.1,0.9 -0.1,0 -0.8,-0.3 -1.8,-0.6 l -1.8,-0.6 v -0.9 c 0,-0.6 0,-0.9 -0.6,-1.5 z M 48,63.7 V 64 h 0.2 z"
|
||||||
|
class="st2"
|
||||||
|
id="XMLID_13_"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
style="fill:#2ecc71" />
|
||||||
|
<path
|
||||||
|
d="m 48,15.5 c -3.1,0 -6.2,0.5 -9,1.3 0.3,0.4 0.3,0.4 0.6,0.9 1.5,2.5 1.7,2.8 2.1,2.9 0.3,0 0.9,0.1 1.6,0.1 h 1.2 l 0.9,-2 0.8,-1.9 1.8,-0.6 z m -16.9,4.7 c -2.8,1.7 -5.4,3.9 -7.6,6.4 -3.8,4.3 -6.3,9.6 -7.4,15.4 0.5,0 0.9,-0.1 1.8,-0.1 2.8,0.1 2.5,0 3.4,1.4 0.5,0.8 0.6,0.8 1.4,0.8 1,0.1 0.9,0 0.5,-1.6 -0.2,-0.6 -0.3,-1.2 -0.3,-1.4 0,-0.2 0.5,-0.7 1.7,-1.6 1.9,-1.5 1.8,-1.3 1.5,-2.9 -0.1,-0.3 0.1,-0.6 0.6,-1.2 0.7,-0.7 0.7,-0.6 1.4,-0.6 h 0.7 l 0.1,-1.2 c 0.1,-0.7 0.1,-1.3 0.2,-1.3 0,0 1.9,-1.1 4.1,-2.3 2.2,-1.2 4.1,-2.2 4.2,-2.3 0.2,-0.2 -0.3,-0.8 -2.7,-3.8 -1.5,-1.9 -2.8,-3.6 -2.9,-3.7 z m -5.8,23 c -0.1,0 -0.1,0.3 -0.1,0.6 0,0.6 0,0.7 0.6,1 0.8,0.4 0.9,0.5 0.8,0.2 -0.1,-0.4 -1.2,-1.9 -1.3,-1.8 z m -3.4,2.1 -0.5,1.8 c 0.1,0.1 0.9,0.3 1.8,0.5 1,0.2 1.6,0.4 1.8,0.3 l 0.5,-1.3 z m -3.8,1 -1.1,0.6 c -0.6,0.3 -1.2,0.6 -1.4,0.6 h -0.1 c 0,1.4 0.1,2.8 0.3,4.2 l 0.6,0.4 1,-0.1 h 1 l 0.6,1.4 c 0.3,0.7 0.7,1.4 0.8,1.5 0.1,0.1 1,0.1 1.8,0.1 h 1.5 L 23,56.2 c 0,1.2 0,1.3 -0.6,2.2 -0.4,0.5 -0.6,1.2 -0.6,1.4 0,0.2 0.7,2.1 1.6,4.3 l 1.5,4 1.6,0.8 c 1.2,0.6 1.5,0.8 1.5,1 0,0.1 -0.4,2.1 -0.6,3.1 3,2.5 6.4,4.5 10.2,5.8 3.5,-3.6 6.8,-7.1 7.3,-7.6 l 0.7,-0.7 0.2,-1.9 c 0.2,-1.1 0.4,-2.1 0.4,-2.2 0,-0.1 0.5,-0.6 1,-1.2 0.5,-0.5 0.8,-1 0.8,-1.1 v -0.2 c -0.1,-0.1 -1.4,-1.1 -3,-2.2 l -3.1,-2.1 -1.1,-0.1 c -0.8,0 -1.2,0 -1.3,-0.2 C 39.4,59.2 39.2,58.5 39.1,57.7 39,56.9 38.9,56.2 38.8,56.1 38.8,56 38,56 37.1,56 36.2,56 35.4,55.9 35.3,55.8 35.2,55.7 35.2,55.1 35.1,54.3 35,53.6 34.9,53 34.8,52.9 34.7,52.8 33.7,52.7 32.5,52.6 30.5,52.5 30.1,52.5 29.1,52 l -1.2,-0.6 -1.6,0.7 -1.7,0.9 -1.8,-0.1 c -2,0 -1.9,0.2 -2.1,-1.6 C 20.6,50.7 20.6,50.1 20.5,50.1 20.4,50 20,50 19.6,49.9 L 18.9,49.7 19,49.2 c 0,-0.3 0,-1 0.1,-1.4 L 19.2,47 18.7,46.5 Z m 9.1,1.1 C 27.1,47.5 27.1,47.8 27,48 l -0.1,0.5 2.9,1.2 c 2.9,1.1 3.4,1.2 3.9,0.7 0.2,-0.2 0.1,-0.2 -0.3,-0.4 -0.3,-0.1 -1.7,-0.9 -3.2,-1.6 -1.7,-0.7 -2.9,-1.1 -3,-1 z"
|
||||||
|
class="st3"
|
||||||
|
id="XMLID_20_"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
style="fill:#27ae60" />
|
||||||
|
</g><g
|
||||||
|
transform="matrix(1.458069,0,0,1.458069,-22.631538,-19.615144)"
|
||||||
|
id="g7664"><path
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
id="XMLID_6_"
|
||||||
|
class="st3"
|
||||||
|
d="m 38.8,56.1 c 0,1.2 1,2.2 2.2,2.2 h 15.2 c 1.2,0 2.2,-1 2.2,-2.2 V 45.3 c 0,-1.2 -1,-2.2 -2.2,-2.2 H 40.9 c -1.2,0 -2.2,1 -2.2,2.2 v 10.8 z"
|
||||||
|
style="fill:#f1aa27;fill-opacity:1" /><path
|
||||||
|
style="fill:#e6e6e6"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
id="XMLID_7_"
|
||||||
|
class="st4"
|
||||||
|
d="m 55.5,43.1 h -3.3 v -3.7 c 0,-2.1 -1.7,-3.8 -3.8,-3.8 -2.1,0 -3.8,1.7 -3.8,3.8 v 3.8 h -3.1 v -3.8 c 0,-3.9 3.2,-7 7,-7 3.9,0 7,3.2 7,7 z" /><path
|
||||||
|
style="fill:#e6e6e6;fill-opacity:1"
|
||||||
|
inkscape:connector-curvature="0"
|
||||||
|
id="XMLID_8_"
|
||||||
|
class="st5"
|
||||||
|
d="m 50.35,48.2 c 0,-1 -0.8,-1.8 -1.8,-1.8 -1,0 -1.8,0.8 -1.8,1.8 0,0.7 0.4,1.3 1,1.6 l -1,5.2 h 3.6 l -1,-5.2 c 0.6,-0.3 1,-0.9 1,-1.6 z" /></g></g></svg>
|
||||||
|
After Width: | Height: | Size: 6.7 KiB |
@@ -1,117 +1,135 @@
|
|||||||
|
import { Box, Button, CssBaseline, LinearProgress, Typography } from "@mui/material";
|
||||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||||
import logo from "../../assets/icon-small.svg";
|
import logo from "../../assets/icon.svg";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
import "./styles.css";
|
import "./styles.css";
|
||||||
|
|
||||||
const appWindow = getCurrentWindow();
|
const appWindow = getCurrentWindow();
|
||||||
|
|
||||||
export default function App() {
|
function useUpdateProgress() {
|
||||||
const [error, setError] = useState(false);
|
|
||||||
const [progress, setProgress] = useState<number | null>(null);
|
const [progress, setProgress] = useState<number | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const unlisteners: Array<() => void> = [];
|
const unlisten = appWindow.listen("app://update-progress", (event) => {
|
||||||
let disposed = false;
|
|
||||||
|
|
||||||
const startUpdate = async () => {
|
|
||||||
const progressUnlisten = await appWindow.listen("app://update-progress", (event) => {
|
|
||||||
setProgress(event.payload as number);
|
setProgress(event.payload as number);
|
||||||
});
|
});
|
||||||
const errorUnlisten = await appWindow.listen("app://update-error", () => {
|
|
||||||
|
return () => {
|
||||||
|
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);
|
setError(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (disposed) {
|
|
||||||
progressUnlisten();
|
|
||||||
errorUnlisten();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
unlisteners.push(progressUnlisten, errorUnlisten);
|
|
||||||
await appWindow.emit("app://update");
|
|
||||||
};
|
|
||||||
|
|
||||||
void startUpdate();
|
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
disposed = true;
|
unlisten.then((unlisten) => unlisten());
|
||||||
unlisteners.forEach((unlisten) => unlisten());
|
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleRetry = () => {
|
const handleRetry = () => {
|
||||||
setError(false);
|
setError(false);
|
||||||
setProgress(null);
|
|
||||||
appWindow.emit("app://update");
|
appWindow.emit("app://update");
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="update-window" data-tauri-drag-region>
|
<>
|
||||||
<img src={logo} alt="" className="update-logo" data-tauri-drag-region />
|
<CssBaseline />
|
||||||
<div className="update-content" data-tauri-drag-region>
|
<Box
|
||||||
{error ? (
|
sx={{ position: "absolute", inset: 0 }}
|
||||||
<DownloadFailed onRetry={handleRetry} />
|
display="flex"
|
||||||
) : (
|
alignItems="center"
|
||||||
<DownloadIndicator progress={progress} />
|
px={2}
|
||||||
)}
|
data-tauri-drag-region
|
||||||
</div>
|
>
|
||||||
</div>
|
<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 (
|
return (
|
||||||
<div className="update-status" data-tauri-drag-region>
|
<>
|
||||||
<h1 className="update-title" data-tauri-drag-region>
|
<Typography variant="h1" fontSize="1rem" data-tauri-drag-region>
|
||||||
Getting GP Connect ready
|
Updating the GUI components...
|
||||||
</h1>
|
</Typography>
|
||||||
<DownloadProgress value={progress} />
|
<Box mt={1}>
|
||||||
</div>
|
<LinearProgressWithLabel value={progress} />
|
||||||
|
</Box>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DownloadFailed({ onRetry }: { onRetry: () => void }) {
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="progress-summary" data-tauri-drag-region>
|
<Typography variant="h1" fontSize="1rem" data-tauri-drag-region>
|
||||||
<p className="update-description" data-tauri-drag-region>
|
Failed to update the GUI components.
|
||||||
This should only take a moment.
|
</Typography>
|
||||||
</p>
|
<Box mt={1} data-tauri-drag-region>
|
||||||
<span className="progress-label" aria-hidden="true">
|
<Button
|
||||||
{isDeterminate ? `${Math.round(value)}%` : "In progress"}
|
variant="contained"
|
||||||
</span>
|
color="primary"
|
||||||
</div>
|
size="small"
|
||||||
<div
|
onClick={onRetry}
|
||||||
className={`progress-bar${isDeterminate ? "" : " progress-bar-indeterminate"}`}
|
sx={{
|
||||||
role="progressbar"
|
textTransform: "none",
|
||||||
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} />
|
Retry
|
||||||
</div>
|
</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,
|
html,
|
||||||
body,
|
body,
|
||||||
#root {
|
#root {
|
||||||
box-sizing: border-box;
|
|
||||||
height: 100%;
|
height: 100%;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
overflow: hidden;
|
|
||||||
-webkit-user-select: none;
|
-webkit-user-select: none;
|
||||||
user-select: none;
|
user-select: none;
|
||||||
cursor: default;
|
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: {
|
build: {
|
||||||
rolldownOptions: {
|
rolldownOptions: {
|
||||||
input: {
|
input: {
|
||||||
main: resolve(import.meta.dirname, "index.html"),
|
main: resolve(__dirname, "index.html"),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -7,9 +7,6 @@ license.workspace = true
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
common = { path = "../../crates/common" }
|
common = { path = "../../crates/common" }
|
||||||
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
|
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
|
||||||
gphip = { path = "../../crates/gphip" }
|
|
||||||
base64.workspace = true
|
|
||||||
sha256.workspace = true
|
|
||||||
openconnect = { path = "../../crates/openconnect" }
|
openconnect = { path = "../../crates/openconnect" }
|
||||||
clap.workspace = true
|
clap.workspace = true
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
@@ -24,15 +21,3 @@ log.workspace = true
|
|||||||
compile-time.workspace = true
|
compile-time.workspace = true
|
||||||
xz2 = "0.1"
|
xz2 = "0.1"
|
||||||
tar = "0.4"
|
tar = "0.4"
|
||||||
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]
|
|
||||||
tokio-tungstenite = "0.29"
|
|
||||||
@@ -1,137 +0,0 @@
|
|||||||
use std::{
|
|
||||||
env, fs,
|
|
||||||
io::{self, Write},
|
|
||||||
};
|
|
||||||
|
|
||||||
use anyhow::{Context, ensure};
|
|
||||||
use clap::Parser;
|
|
||||||
use gpapi::{
|
|
||||||
clap::args::Os,
|
|
||||||
os_profile::{ClientOs, OsProfileBuilder},
|
|
||||||
};
|
|
||||||
use gphip::{ReportContext, ReportInput, generate_report, refresh_edited_report};
|
|
||||||
use gpservice::hip_runner_state::{MAX_STATE_BYTES, RunnerReport, STATE_NAME, validate_root_owned_path};
|
|
||||||
|
|
||||||
#[derive(Parser)]
|
|
||||||
struct Args {
|
|
||||||
#[arg(long)]
|
|
||||||
client_version: String,
|
|
||||||
#[arg(long, value_enum)]
|
|
||||||
client_os: Os,
|
|
||||||
#[arg(long)]
|
|
||||||
os_version: Option<String>,
|
|
||||||
#[arg(long)]
|
|
||||||
host_id: Option<String>,
|
|
||||||
#[arg(long)]
|
|
||||||
cookie: Option<String>,
|
|
||||||
#[arg(long)]
|
|
||||||
client_ip: Option<String>,
|
|
||||||
#[arg(long)]
|
|
||||||
client_ipv6: Option<String>,
|
|
||||||
#[arg(long)]
|
|
||||||
md5: Option<String>,
|
|
||||||
#[arg(long)]
|
|
||||||
preview: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
if let Err(err) = run() {
|
|
||||||
eprintln!("HIP report generation failed: {err:#}");
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run() -> anyhow::Result<()> {
|
|
||||||
let args = Args::parse();
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
let original_args: Vec<_> = env::args_os().skip(1).collect();
|
|
||||||
let executable = env::current_exe().context("Cannot locate HIP runner")?;
|
|
||||||
validate_root_owned_path(&executable, true)?;
|
|
||||||
let state = executable
|
|
||||||
.parent()
|
|
||||||
.context("HIP runner has no parent")?
|
|
||||||
.join(STATE_NAME);
|
|
||||||
let metadata = fs::symlink_metadata(&state).context("Cannot inspect HIP report state")?;
|
|
||||||
ensure!(
|
|
||||||
metadata.is_file() && !metadata.file_type().is_symlink(),
|
|
||||||
"Invalid HIP report state"
|
|
||||||
);
|
|
||||||
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
|
||||||
ensure!(
|
|
||||||
metadata.uid() == 0 && metadata.permissions().mode() & 0o077 == 0,
|
|
||||||
"HIP report state is not private"
|
|
||||||
);
|
|
||||||
ensure!(
|
|
||||||
metadata.len() <= MAX_STATE_BYTES as u64,
|
|
||||||
"HIP report state is too large"
|
|
||||||
);
|
|
||||||
let bytes = fs::read(&state).context("Cannot read HIP report state")?;
|
|
||||||
ensure!(bytes.len() <= MAX_STATE_BYTES, "HIP report state is too large");
|
|
||||||
let report: RunnerReport = serde_json::from_slice(&bytes).context("Invalid HIP report state")?;
|
|
||||||
|
|
||||||
// This binary is single-threaded. Clear the VPN and desktop environment
|
|
||||||
// before host collectors invoke any external system utilities.
|
|
||||||
for (key, _) in env::vars_os() {
|
|
||||||
unsafe { env::remove_var(key) };
|
|
||||||
}
|
|
||||||
unsafe {
|
|
||||||
env::set_var("PATH", "/usr/bin:/bin:/usr/sbin:/sbin");
|
|
||||||
env::set_var("LC_ALL", "C");
|
|
||||||
env::set_var(
|
|
||||||
"HOME",
|
|
||||||
if cfg!(target_os = "macos") {
|
|
||||||
"/var/root"
|
|
||||||
} else {
|
|
||||||
"/root"
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let report = match report {
|
|
||||||
RunnerReport::ApprovedRootScript { approval_id, owner_uid } => {
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
{
|
|
||||||
let approved = gpservice::hip_approval::resolve(&approval_id, owner_uid)?;
|
|
||||||
let script_args = original_args.into_iter().filter(|arg| arg != "--preview");
|
|
||||||
let status = std::process::Command::new(approved.path)
|
|
||||||
.args(script_args)
|
|
||||||
.status()
|
|
||||||
.context("Approved HIP script did not start")?;
|
|
||||||
ensure!(status.success(), "Approved HIP script failed");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
|
||||||
{
|
|
||||||
let _ = (approval_id, owner_uid);
|
|
||||||
anyhow::bail!("Root HIP script approvals are unavailable on this platform");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
report => report,
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut builder = OsProfileBuilder::new(ClientOs::from(args.client_os)).client_version(args.client_version);
|
|
||||||
if let Some(host_id) = args.host_id {
|
|
||||||
builder = builder.host_id_override(host_id);
|
|
||||||
}
|
|
||||||
let context = if args.preview {
|
|
||||||
ReportContext::Preview
|
|
||||||
} else {
|
|
||||||
ReportContext::Connected {
|
|
||||||
cookie: args.cookie.context("Missing HIP cookie")?,
|
|
||||||
client_ip: args.client_ip,
|
|
||||||
client_ipv6: args.client_ipv6,
|
|
||||||
md5: args.md5.context("Missing HIP digest")?,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let input = ReportInput {
|
|
||||||
profile: builder.build(),
|
|
||||||
context,
|
|
||||||
};
|
|
||||||
let xml = match report {
|
|
||||||
RunnerReport::Generated => generate_report(&input)?,
|
|
||||||
RunnerReport::Edited { xml } => refresh_edited_report(&xml, &input)?,
|
|
||||||
RunnerReport::ApprovedRootScript { .. } => unreachable!("approved script returned before report generation"),
|
|
||||||
};
|
|
||||||
io::stdout().write_all(xml.as_bytes())?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
#[path = "privileged_unix.rs"]
|
|
||||||
mod platform;
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
|
||||||
#[path = "unsupported.rs"]
|
|
||||||
mod platform;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
platform::run();
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
use std::io::Read;
|
|
||||||
|
|
||||||
use anyhow::{Context, ensure};
|
|
||||||
use clap::{Parser, Subcommand};
|
|
||||||
use gpservice::hip_approval::{self, InstallRequest};
|
|
||||||
use nix::unistd::Uid;
|
|
||||||
|
|
||||||
const MAX_INSTALL_REQUEST_SIZE: u64 = 2 * 1024 * 1024;
|
|
||||||
|
|
||||||
#[derive(Parser)]
|
|
||||||
struct Cli {
|
|
||||||
#[command(subcommand)]
|
|
||||||
command: Command,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Subcommand)]
|
|
||||||
enum Command {
|
|
||||||
Install,
|
|
||||||
Revoke { approval_id: String },
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_run() -> anyhow::Result<()> {
|
|
||||||
ensure!(Uid::effective().is_root(), "HIP script installer must run as root");
|
|
||||||
let approving_uid = std::env::var("PKEXEC_UID")
|
|
||||||
.context("HIP script installer requires pkexec authorization")?
|
|
||||||
.parse::<u32>()
|
|
||||||
.context("Invalid pkexec user identity")?;
|
|
||||||
ensure!(approving_uid != 0, "HIP script installer requires a desktop user");
|
|
||||||
|
|
||||||
match Cli::parse().command {
|
|
||||||
Command::Install => {
|
|
||||||
let mut input = Vec::new();
|
|
||||||
std::io::stdin()
|
|
||||||
.lock()
|
|
||||||
.take(MAX_INSTALL_REQUEST_SIZE + 1)
|
|
||||||
.read_to_end(&mut input)?;
|
|
||||||
ensure!(
|
|
||||||
input.len() as u64 <= MAX_INSTALL_REQUEST_SIZE,
|
|
||||||
"HIP install request is too large"
|
|
||||||
);
|
|
||||||
let request: InstallRequest = serde_json::from_slice(&input).context("Invalid HIP install request")?;
|
|
||||||
let info = hip_approval::install(request, approving_uid)?;
|
|
||||||
serde_json::to_writer(std::io::stdout().lock(), &info)?;
|
|
||||||
println!();
|
|
||||||
}
|
|
||||||
Command::Revoke { approval_id } => hip_approval::revoke(&approval_id, approving_uid)?,
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn run() {
|
|
||||||
if let Err(err) = try_run() {
|
|
||||||
eprintln!("HIP approval failed: {err:#}");
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
pub(super) fn run() {
|
|
||||||
eprintln!("Root HIP script approvals are unavailable on this platform");
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
@@ -1,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,42 +0,0 @@
|
|||||||
use std::io::Read;
|
|
||||||
|
|
||||||
use anyhow::bail;
|
|
||||||
use clap::{Parser, Subcommand};
|
|
||||||
use gpapi::service::vpnc_script::InstallVpncScriptRequest;
|
|
||||||
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,
|
|
||||||
Remove,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_run() -> anyhow::Result<()> {
|
|
||||||
if !Uid::effective().is_root() {
|
|
||||||
bail!("The VPNC script installer must run as root");
|
|
||||||
}
|
|
||||||
|
|
||||||
match Cli::parse().command {
|
|
||||||
Command::Install => {
|
|
||||||
let input = std::io::stdin().lock().take(MAX_INSTALL_REQUEST_SIZE);
|
|
||||||
let request = serde_json::from_reader::<_, InstallVpncScriptRequest>(input)?;
|
|
||||||
gpservice::vpnc_script::install(request)
|
|
||||||
}
|
|
||||||
Command::Remove => gpservice::vpnc_script::remove(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn run() {
|
|
||||||
if let Err(err) = try_run() {
|
|
||||||
eprintln!("Error: {err:#}");
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
pub(super) fn run() {
|
|
||||||
eprintln!("The VPNC script installer is only available on Linux, FreeBSD, and OpenBSD");
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
@@ -1,33 +1,20 @@
|
|||||||
use std::path::PathBuf;
|
use std::sync::Arc;
|
||||||
use std::sync::{
|
|
||||||
Arc,
|
|
||||||
atomic::{AtomicBool, Ordering},
|
|
||||||
};
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
use std::time::Duration;
|
|
||||||
use std::{collections::HashMap, io::Write};
|
use std::{collections::HashMap, io::Write};
|
||||||
|
|
||||||
use anyhow::{Context, bail};
|
use anyhow::bail;
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use common::constants::GP_SERVICE_LOCK_FILE;
|
use common::constants::GP_SERVICE_LOCK_FILE;
|
||||||
use gpapi::clap::InfoLevelVerbosity;
|
use gpapi::clap::InfoLevelVerbosity;
|
||||||
use gpapi::logger;
|
use gpapi::logger;
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
use gpapi::utils::lock_file::dev_service_lock_file_path;
|
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
process::gui_launcher::GuiLauncher,
|
process::gui_launcher::GuiLauncher,
|
||||||
service::vpn_state::VpnState,
|
service::{request::WsRequest, vpn_state::VpnState},
|
||||||
utils::{env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
|
utils::{crypto::generate_key, env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
|
||||||
};
|
};
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
use log::{Log, Metadata, Record};
|
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
use tokio::sync::{mpsc, watch};
|
use tokio::sync::{mpsc, watch};
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{vpn_task::VpnTask, ws_server::WsServer};
|
||||||
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
|
|
||||||
};
|
|
||||||
|
|
||||||
const VERSION: &str = concat!(
|
const VERSION: &str = concat!(
|
||||||
env!("CARGO_PKG_VERSION"),
|
env!("CARGO_PKG_VERSION"),
|
||||||
@@ -38,28 +25,6 @@ const VERSION: &str = concat!(
|
|||||||
")"
|
")"
|
||||||
);
|
);
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
struct RedactingMacosLogger {
|
|
||||||
logger: logger::MacosLogger,
|
|
||||||
redaction: Arc<Redaction>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
impl Log for RedactingMacosLogger {
|
|
||||||
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
|
|
||||||
self.logger.enabled(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn log(&self, record: &Record<'_>) {
|
|
||||||
if self.enabled(record.metadata()) {
|
|
||||||
let message = self.redaction.redact_str(&record.args().to_string());
|
|
||||||
self.logger.write(record.level(), record.target(), &message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn flush(&self) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[command(version = VERSION)]
|
#[command(version = VERSION)]
|
||||||
struct Cli {
|
struct Cli {
|
||||||
@@ -68,17 +33,9 @@ struct Cli {
|
|||||||
#[clap(long)]
|
#[clap(long)]
|
||||||
env_file: Option<String>,
|
env_file: Option<String>,
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
#[clap(long, requires_all = ["dev_uid", "dev_bootstrap_socket"])]
|
#[clap(long)]
|
||||||
dev_standalone: bool,
|
no_gui: bool,
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
#[clap(long, requires = "dev_standalone")]
|
|
||||||
dev_uid: Option<u32>,
|
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
#[clap(long, requires = "dev_standalone")]
|
|
||||||
dev_bootstrap_socket: Option<PathBuf>,
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
#[clap(long, conflicts_with = "dev_standalone")]
|
|
||||||
macos_brokered: bool,
|
|
||||||
#[command(flatten)]
|
#[command(flatten)]
|
||||||
verbose: InfoLevelVerbosity,
|
verbose: InfoLevelVerbosity,
|
||||||
}
|
}
|
||||||
@@ -89,118 +46,55 @@ impl Cli {
|
|||||||
info!("gpservice started: {}", VERSION);
|
info!("gpservice started: {}", VERSION);
|
||||||
|
|
||||||
let pid = std::process::id();
|
let pid = std::process::id();
|
||||||
let lock_file = Arc::new(LockFile::new(self.service_lock_file_path()?, pid));
|
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE, pid));
|
||||||
|
|
||||||
if lock_file.check_health().await {
|
if lock_file.check_health().await {
|
||||||
bail!("Another instance of the service is already running");
|
bail!("Another instance of the service is already running");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Channel for receiving VPN state from the lifecycle actor
|
let api_key = self.prepare_api_key();
|
||||||
|
|
||||||
|
// 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 (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 mut vpn_task = VpnTask::new(ws_req_rx, vpn_state_tx);
|
||||||
let externally_brokered = self.externally_brokered();
|
let ws_server = WsServer::new(api_key.clone(), ws_req_tx, vpn_state_rx, lock_file.clone(), redaction);
|
||||||
let desktop_uid = crate::runtime_user::desktop_uid();
|
|
||||||
let brokered_scripts_dir = if externally_brokered {
|
|
||||||
let executable = std::env::current_exe().context("Failed to locate the gpservice executable")?;
|
|
||||||
let contents_dir = executable
|
|
||||||
.parent()
|
|
||||||
.and_then(std::path::Path::parent)
|
|
||||||
.context("gpservice is not inside a macOS application bundle")?;
|
|
||||||
Some(contents_dir.join("Resources/Scripts"))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
let (mut vpn_task, lifecycle) = VpnTask::new(vpn_state_tx, externally_brokered, Arc::clone(®istry));
|
|
||||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
|
||||||
lifecycle.clone(),
|
|
||||||
Arc::clone(&gui_restart_requested),
|
|
||||||
Arc::clone(&redaction),
|
|
||||||
!externally_brokered,
|
|
||||||
brokered_scripts_dir,
|
|
||||||
));
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
let idle_vpn_state_rx = vpn_state_rx.clone();
|
|
||||||
let ws_server = WsServer::new(
|
|
||||||
env!("CARGO_PKG_VERSION"),
|
|
||||||
Arc::clone(®istry),
|
|
||||||
dispatcher,
|
|
||||||
vpn_state_rx,
|
|
||||||
lock_file.clone(),
|
|
||||||
);
|
|
||||||
|
|
||||||
let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(4);
|
let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(4);
|
||||||
let shutdown_tx_clone = shutdown_tx.clone();
|
let shutdown_tx_clone = shutdown_tx.clone();
|
||||||
let vpn_task_cancel_token = vpn_task.cancel_token();
|
let vpn_task_cancel_token = vpn_task.cancel_token();
|
||||||
let server_token = ws_server.cancel_token();
|
let server_token = ws_server.cancel_token();
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
if externally_brokered {
|
|
||||||
let credential_server = crate::macos_broker::CredentialServer::new(Arc::clone(®istry));
|
|
||||||
let credential_token = server_token.clone();
|
|
||||||
let credential_shutdown = shutdown_tx.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
if let Err(err) = credential_server.start(credential_token).await {
|
|
||||||
warn!("Broker credential server stopped: {err}");
|
|
||||||
let _ = credential_shutdown.send(()).await;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let idle_registry = Arc::clone(®istry);
|
|
||||||
let idle_shutdown = shutdown_tx.clone();
|
|
||||||
let idle_token = server_token.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
wait_for_brokered_idle(idle_vpn_state_rx, idle_registry, idle_token).await;
|
|
||||||
let _ = idle_shutdown.send(()).await;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
if self.dev_standalone {
|
|
||||||
let Some(dev_bootstrap_socket) = self.dev_bootstrap_socket.clone() else {
|
|
||||||
bail!("--dev-bootstrap-socket is required with --dev-standalone");
|
|
||||||
};
|
|
||||||
let Some(dev_uid) = self.dev_uid else {
|
|
||||||
bail!("--dev-uid is required with --dev-standalone");
|
|
||||||
};
|
|
||||||
let bootstrap = crate::dev_bootstrap::DevBootstrap::new(dev_bootstrap_socket, dev_uid, Arc::clone(®istry));
|
|
||||||
let bootstrap_token = server_token.clone();
|
|
||||||
let bootstrap_shutdown = shutdown_tx.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
if let Err(err) = bootstrap.start(bootstrap_token).await {
|
|
||||||
warn!("Debug bootstrap stopped: {err}");
|
|
||||||
let _ = bootstrap_shutdown.send(()).await;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
{
|
||||||
let lifecycle = lifecycle.clone();
|
let vpn_ctx = vpn_task.context();
|
||||||
let ws_ctx = ws_server.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 vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).await });
|
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).await });
|
||||||
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone, ws_ready_tx).await });
|
|
||||||
|
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
let launch_managed_gui = !self.dev_standalone && !externally_brokered;
|
let no_gui = self.no_gui;
|
||||||
#[cfg(not(debug_assertions))]
|
|
||||||
let launch_managed_gui = !externally_brokered;
|
|
||||||
|
|
||||||
if launch_managed_gui {
|
#[cfg(not(debug_assertions))]
|
||||||
ws_ready_rx.await.context("WebSocket server failed to start")?;
|
let no_gui = false;
|
||||||
|
|
||||||
|
if no_gui {
|
||||||
|
info!("GUI is disabled");
|
||||||
|
} else {
|
||||||
let envs = self.env_file.as_ref().map(env_utils::load_env_vars).transpose()?;
|
let envs = self.env_file.as_ref().map(env_utils::load_env_vars).transpose()?;
|
||||||
|
|
||||||
let minimized = self.minimized;
|
let minimized = self.minimized;
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
launch_gui(envs, registry, desktop_uid, minimized, gui_restart_requested).await;
|
launch_gui(envs, api_key, minimized).await;
|
||||||
let _ = shutdown_tx.send(()).await;
|
let _ = shutdown_tx.send(()).await;
|
||||||
});
|
});
|
||||||
} else {
|
|
||||||
info!("Running with a separately started debug GUI");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
@@ -222,43 +116,8 @@ impl Cli {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn externally_brokered(&self) -> bool {
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
return self.macos_brokered;
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "macos"))]
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
fn service_lock_file_path(&self) -> anyhow::Result<PathBuf> {
|
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
if self.dev_standalone {
|
|
||||||
let socket = self
|
|
||||||
.dev_bootstrap_socket
|
|
||||||
.as_ref()
|
|
||||||
.context("--dev-bootstrap-socket is required with --dev-standalone")?;
|
|
||||||
return Ok(dev_service_lock_file_path(socket));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(PathBuf::from(GP_SERVICE_LOCK_FILE))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn init_logger(&self) -> Arc<Redaction> {
|
fn init_logger(&self) -> Arc<Redaction> {
|
||||||
let redaction = Arc::new(Redaction::new());
|
let redaction = Arc::new(Redaction::new());
|
||||||
let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info);
|
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
if logger::macos_unified_log_enabled() {
|
|
||||||
logger::init_with_logger(
|
|
||||||
level,
|
|
||||||
RedactingMacosLogger {
|
|
||||||
logger: logger::MacosLogger::new("com.yuezk.gpgui", "gpservice"),
|
|
||||||
redaction: Arc::clone(&redaction),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
return redaction;
|
|
||||||
}
|
|
||||||
|
|
||||||
let redaction_clone = Arc::clone(&redaction);
|
let redaction_clone = Arc::clone(&redaction);
|
||||||
|
|
||||||
let inner_logger = env_logger::builder()
|
let inner_logger = env_logger::builder()
|
||||||
@@ -277,41 +136,20 @@ impl Cli {
|
|||||||
})
|
})
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info);
|
||||||
|
|
||||||
logger::init_with_logger(level, inner_logger);
|
logger::init_with_logger(level, inner_logger);
|
||||||
|
|
||||||
redaction
|
redaction
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
fn prepare_api_key(&self) -> Vec<u8> {
|
||||||
async fn wait_for_brokered_idle(
|
#[cfg(debug_assertions)]
|
||||||
mut vpn_state_rx: watch::Receiver<VpnState>,
|
if self.no_gui {
|
||||||
registry: Arc<SessionRegistry>,
|
return gpapi::GP_API_KEY.to_vec();
|
||||||
cancel: tokio_util::sync::CancellationToken,
|
|
||||||
) {
|
|
||||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(60);
|
|
||||||
const CHECK_INTERVAL: Duration = Duration::from_secs(1);
|
|
||||||
|
|
||||||
let mut idle_since = None;
|
|
||||||
let mut interval = tokio::time::interval(CHECK_INTERVAL);
|
|
||||||
loop {
|
|
||||||
tokio::select! {
|
|
||||||
_ = cancel.cancelled() => return,
|
|
||||||
_ = vpn_state_rx.changed() => {},
|
|
||||||
_ = interval.tick() => {},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let idle = matches!(*vpn_state_rx.borrow(), VpnState::Disconnected) && registry.is_empty();
|
generate_key().to_vec()
|
||||||
if !idle {
|
|
||||||
idle_since = None;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let started = idle_since.get_or_insert_with(tokio::time::Instant::now);
|
|
||||||
if started.elapsed() >= IDLE_TIMEOUT {
|
|
||||||
info!("Brokered service idle timeout reached");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -321,12 +159,12 @@ mod signals {
|
|||||||
|
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
|
|
||||||
use crate::vpn_task::LifecycleHandle;
|
use crate::vpn_task::VpnTaskContext;
|
||||||
use crate::ws_server::WsServerContext;
|
use crate::ws_server::WsServerContext;
|
||||||
|
|
||||||
const DISCONNECTED_PID_FILE: &str = "/tmp/gpservice_disconnected.pid";
|
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 gpapi::service::event::WsEvent;
|
||||||
use tokio::signal::unix::{Signal, SignalKind, signal};
|
use tokio::signal::unix::{Signal, SignalKind, signal};
|
||||||
|
|
||||||
@@ -346,7 +184,7 @@ mod signals {
|
|||||||
tokio::select! {
|
tokio::select! {
|
||||||
_ = user_sig1.recv() => {
|
_ = user_sig1.recv() => {
|
||||||
info!("Received SIGUSR1 signal");
|
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
|
// Write the PID to a dedicated file to indicate that the VPN task is disconnected via SIGUSR1
|
||||||
let pid = std::process::id();
|
let pid = std::process::id();
|
||||||
if let Err(err) = tokio::fs::write(DISCONNECTED_PID_FILE, pid.to_string()).await {
|
if let Err(err) = tokio::fs::write(DISCONNECTED_PID_FILE, pid.to_string()).await {
|
||||||
@@ -363,40 +201,24 @@ mod signals {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn launch_gui(
|
async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut minimized: bool) {
|
||||||
envs: Option<HashMap<String, String>>,
|
|
||||||
registry: Arc<SessionRegistry>,
|
|
||||||
desktop_uid: Option<u32>,
|
|
||||||
mut minimized: bool,
|
|
||||||
restart_requested: Arc<AtomicBool>,
|
|
||||||
) {
|
|
||||||
loop {
|
loop {
|
||||||
let credential = match registry.issue(env!("CARGO_PKG_VERSION"), desktop_uid) {
|
let gui_launcher = GuiLauncher::new(env!("CARGO_PKG_VERSION"), &api_key)
|
||||||
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())
|
.envs(envs.clone())
|
||||||
.minimized(minimized);
|
.minimized(minimized);
|
||||||
|
|
||||||
match gui_launcher.launch().await {
|
match gui_launcher.launch().await {
|
||||||
Ok(exit_status) => {
|
Ok(exit_status) => {
|
||||||
registry.revoke(session_id);
|
// Exit code 99 means that the GUI needs to be restarted
|
||||||
let should_restart = restart_requested.swap(false, Ordering::SeqCst);
|
if exit_status.code() != Some(99) {
|
||||||
if !should_restart {
|
|
||||||
info!("GUI exited with code {:?}", exit_status.code());
|
info!("GUI exited with code {:?}", exit_status.code());
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("GUI restart requested, restarting");
|
info!("GUI exited with code 99, restarting");
|
||||||
minimized = false;
|
minimized = false;
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
registry.revoke(session_id);
|
|
||||||
warn!("Failed to launch GUI: {}", err);
|
warn!("Failed to launch GUI: {}", err);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use tokio::{
|
|
||||||
io::{AsyncReadExt, AsyncWriteExt},
|
|
||||||
net::UnixStream,
|
|
||||||
};
|
|
||||||
|
|
||||||
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)?;
|
|
||||||
let session_id = credential.session_id();
|
|
||||||
let result = async {
|
|
||||||
stream.write_all(&credential.encode_frame()?).await?;
|
|
||||||
|
|
||||||
let mut buffer = [0_u8; 1];
|
|
||||||
loop {
|
|
||||||
match stream.read(&mut buffer).await {
|
|
||||||
Ok(0) => break,
|
|
||||||
Ok(_) => continue,
|
|
||||||
Err(err) => return Err(err.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
.await;
|
|
||||||
registry.revoke(session_id);
|
|
||||||
result
|
|
||||||
}
|
|
||||||
@@ -1,219 +0,0 @@
|
|||||||
use std::{
|
|
||||||
os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt},
|
|
||||||
path::{Path, PathBuf},
|
|
||||||
sync::Arc,
|
|
||||||
};
|
|
||||||
|
|
||||||
use anyhow::{Context, bail};
|
|
||||||
use log::{info, warn};
|
|
||||||
use nix::unistd::{Uid, chown};
|
|
||||||
use tokio::net::{UnixListener, UnixStream};
|
|
||||||
use tokio_util::sync::CancellationToken;
|
|
||||||
|
|
||||||
use crate::{credential_lease, session_registry::SessionRegistry};
|
|
||||||
|
|
||||||
pub struct DevBootstrap {
|
|
||||||
path: PathBuf,
|
|
||||||
allowed_uid: u32,
|
|
||||||
registry: Arc<SessionRegistry>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DevBootstrap {
|
|
||||||
pub fn new(path: PathBuf, allowed_uid: u32, registry: Arc<SessionRegistry>) -> Self {
|
|
||||||
Self {
|
|
||||||
path,
|
|
||||||
allowed_uid,
|
|
||||||
registry,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn start(self, cancel: CancellationToken) -> anyhow::Result<()> {
|
|
||||||
create_default_parent(&self.path, self.allowed_uid)?;
|
|
||||||
let path = prepare_socket_path(&self.path, self.allowed_uid)?;
|
|
||||||
let listener = UnixListener::bind(&path)
|
|
||||||
.with_context(|| format!("Failed to bind debug bootstrap socket at {}", path.display()))?;
|
|
||||||
chown(&path, Some(Uid::from_raw(self.allowed_uid)), None)?;
|
|
||||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
|
|
||||||
info!("Debug credential bootstrap listening at {}", path.display());
|
|
||||||
|
|
||||||
loop {
|
|
||||||
tokio::select! {
|
|
||||||
_ = cancel.cancelled() => break,
|
|
||||||
accepted = listener.accept() => {
|
|
||||||
let (stream, _) = accepted?;
|
|
||||||
let peer_uid = match peer_uid(&stream) {
|
|
||||||
Ok(uid) => uid,
|
|
||||||
Err(err) => {
|
|
||||||
warn!("Could not verify debug credential client UID: {err}");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if peer_uid != self.allowed_uid {
|
|
||||||
warn!("Rejected debug credential client with unexpected UID");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let registry = Arc::clone(&self.registry);
|
|
||||||
tokio::spawn(async move {
|
|
||||||
if let Err(err) = credential_lease::serve(stream, registry, Some(self.allowed_uid)).await {
|
|
||||||
warn!("Debug credential client ended: {err}");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if path.exists() {
|
|
||||||
std::fs::remove_file(&path)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn create_default_parent(path: &Path, allowed_uid: u32) -> anyhow::Result<()> {
|
|
||||||
let default = default_socket_path(allowed_uid);
|
|
||||||
if path != default {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let parent = path
|
|
||||||
.parent()
|
|
||||||
.context("Debug bootstrap socket has no parent directory")?;
|
|
||||||
std::fs::create_dir_all(parent)?;
|
|
||||||
std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o711))?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_socket_path(allowed_uid: u32) -> PathBuf {
|
|
||||||
PathBuf::from(format!("/var/run/gpservice-dev-{allowed_uid}/dev-bootstrap.sock"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare_socket_path(path: &Path, allowed_uid: u32) -> anyhow::Result<PathBuf> {
|
|
||||||
let parent = path
|
|
||||||
.parent()
|
|
||||||
.context("Debug bootstrap socket has no parent directory")?;
|
|
||||||
let parent = std::fs::canonicalize(parent)
|
|
||||||
.with_context(|| format!("Debug bootstrap directory does not exist: {}", parent.display()))?;
|
|
||||||
let metadata = std::fs::symlink_metadata(&parent)?;
|
|
||||||
if metadata.file_type().is_symlink() || !metadata.is_dir() {
|
|
||||||
bail!("Debug bootstrap parent must be a real directory");
|
|
||||||
}
|
|
||||||
if metadata.uid() != 0 || metadata.permissions().mode() & 0o777 != 0o711 {
|
|
||||||
bail!("Debug bootstrap parent must be owned by root with mode 0711");
|
|
||||||
}
|
|
||||||
|
|
||||||
let file_name = path.file_name().context("Debug bootstrap socket has no file name")?;
|
|
||||||
let path = parent.join(file_name);
|
|
||||||
|
|
||||||
match std::fs::symlink_metadata(&path) {
|
|
||||||
Ok(metadata) => {
|
|
||||||
if metadata.file_type().is_symlink()
|
|
||||||
|| !metadata.file_type().is_socket()
|
|
||||||
|| metadata.uid() != allowed_uid
|
|
||||||
|| metadata.permissions().mode() & 0o777 != 0o600
|
|
||||||
{
|
|
||||||
bail!("Refusing unsafe existing debug bootstrap path");
|
|
||||||
}
|
|
||||||
std::fs::remove_file(&path)?;
|
|
||||||
}
|
|
||||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
|
||||||
Err(err) => return Err(err.into()),
|
|
||||||
}
|
|
||||||
Ok(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
fn peer_uid(stream: &UnixStream) -> anyhow::Result<u32> {
|
|
||||||
use nix::sys::socket::{getsockopt, sockopt};
|
|
||||||
|
|
||||||
let credentials = getsockopt(stream, sockopt::PeerCredentials)?;
|
|
||||||
Ok(credentials.uid())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
fn peer_uid(stream: &UnixStream) -> anyhow::Result<u32> {
|
|
||||||
let (uid, _) = nix::unistd::getpeereid(stream)?;
|
|
||||||
Ok(uid.as_raw())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
|
||||||
|
|
||||||
use gpapi::service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential};
|
|
||||||
use tokio::io::AsyncReadExt;
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_developer_owned_parent() {
|
|
||||||
let temp = tempfile::tempdir().unwrap();
|
|
||||||
std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
|
|
||||||
let socket = temp.path().join("bootstrap.sock");
|
|
||||||
|
|
||||||
assert!(prepare_socket_path(&socket, Uid::current().as_raw()).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_symlink_socket_path() {
|
|
||||||
let temp = tempfile::tempdir().unwrap();
|
|
||||||
std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
|
|
||||||
let target = temp.path().join("target");
|
|
||||||
std::fs::write(&target, "not a socket").unwrap();
|
|
||||||
let socket = temp.path().join("bootstrap.sock");
|
|
||||||
symlink(target, &socket).unwrap();
|
|
||||||
|
|
||||||
assert!(prepare_socket_path(&socket, Uid::current().as_raw()).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn custom_parent_is_not_created_by_the_service() {
|
|
||||||
let temp = tempfile::tempdir().unwrap();
|
|
||||||
let parent = temp.path().join("missing");
|
|
||||||
let socket = parent.join("bootstrap.sock");
|
|
||||||
|
|
||||||
create_default_parent(&socket, Uid::current().as_raw()).unwrap();
|
|
||||||
|
|
||||||
assert!(!parent.exists());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn default_socket_path_is_stable() {
|
|
||||||
assert_eq!(
|
|
||||||
default_socket_path(1234),
|
|
||||||
PathBuf::from("/var/run/gpservice-dev-1234/dev-bootstrap.sock")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
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 mut header = [0_u8; 2];
|
|
||||||
client.read_exact(&mut header).await.unwrap();
|
|
||||||
let payload_len = u16::from_be_bytes(header) as usize;
|
|
||||||
assert!(payload_len + 2 <= MAX_CREDENTIAL_FRAME);
|
|
||||||
let mut frame = vec![0_u8; payload_len + 2];
|
|
||||||
frame[..2].copy_from_slice(&header);
|
|
||||||
client.read_exact(&mut frame[2..]).await.unwrap();
|
|
||||||
let credential = SessionCredential::decode_frame(&frame).unwrap();
|
|
||||||
drop(client);
|
|
||||||
task.await.unwrap().unwrap();
|
|
||||||
|
|
||||||
assert!(matches!(
|
|
||||||
registry.begin_handshake(
|
|
||||||
credential.service_instance_id(),
|
|
||||||
credential.session_id(),
|
|
||||||
credential.product_version()
|
|
||||||
),
|
|
||||||
Err(crate::session_registry::SessionError::Unauthorized)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn peer_uid_matches_current_process() {
|
|
||||||
let (stream, _peer) = UnixStream::pair().unwrap();
|
|
||||||
assert_eq!(peer_uid(&stream).unwrap(), Uid::current().as_raw());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,12 +1,33 @@
|
|||||||
use std::sync::Arc;
|
use std::{
|
||||||
|
fs::{File, Permissions},
|
||||||
|
io::BufReader,
|
||||||
|
ops::ControlFlow,
|
||||||
|
os::unix::fs::PermissionsExt,
|
||||||
|
sync::Arc,
|
||||||
|
};
|
||||||
|
|
||||||
|
use anyhow::bail;
|
||||||
use axum::{
|
use axum::{
|
||||||
extract::{State, WebSocketUpgrade},
|
body::Bytes,
|
||||||
|
extract::{
|
||||||
|
State, WebSocketUpgrade,
|
||||||
|
ws::{self, CloseFrame, Message, Utf8Bytes, WebSocket},
|
||||||
|
},
|
||||||
|
http::StatusCode,
|
||||||
response::IntoResponse,
|
response::IntoResponse,
|
||||||
};
|
};
|
||||||
use gpapi::service::{event::WsEvent, transport::MAX_WS_MESSAGE};
|
use common::binary_paths;
|
||||||
|
use futures::{SinkExt, StreamExt};
|
||||||
|
use gpapi::{
|
||||||
|
service::{event::WsEvent, request::UpdateGuiRequest},
|
||||||
|
utils::checksum::verify_checksum,
|
||||||
|
};
|
||||||
|
use log::{info, warn};
|
||||||
|
use tar::Archive;
|
||||||
|
use tokio::fs;
|
||||||
|
use xz2::read::XzDecoder;
|
||||||
|
|
||||||
use crate::{ws_connection::WsConnection, ws_server::WsServerContext};
|
use crate::ws_server::WsServerContext;
|
||||||
|
|
||||||
pub(crate) async fn health() -> impl IntoResponse {
|
pub(crate) async fn health() -> impl IntoResponse {
|
||||||
"OK"
|
"OK"
|
||||||
@@ -16,8 +37,133 @@ pub(crate) async fn active_gui(State(ctx): State<Arc<WsServerContext>>) -> impl
|
|||||||
ctx.send_event(WsEvent::ActiveGui).await;
|
ctx.send_event(WsEvent::ActiveGui).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn update_gui(State(ctx): State<Arc<WsServerContext>>, body: Bytes) -> Result<(), StatusCode> {
|
||||||
|
let payload = match ctx.decrypt::<UpdateGuiRequest>(body.to_vec()) {
|
||||||
|
Ok(payload) => payload,
|
||||||
|
Err(err) => {
|
||||||
|
warn!("Failed to decrypt update payload: {}", err);
|
||||||
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
info!("Update GUI: {:?}", payload);
|
||||||
|
let UpdateGuiRequest { path, checksum } = payload;
|
||||||
|
|
||||||
|
info!("Verifying checksum");
|
||||||
|
verify_checksum(&path, &checksum).map_err(|err| {
|
||||||
|
warn!("Failed to verify checksum: {}", err);
|
||||||
|
StatusCode::BAD_REQUEST
|
||||||
|
})?;
|
||||||
|
|
||||||
|
info!("Installing GUI");
|
||||||
|
install_gui(&path).await.map_err(|err| {
|
||||||
|
warn!("Failed to install GUI: {}", err);
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unpack GPGUI archive, gpgui_2.0.0_{arch}.bin.tar.xz and install it
|
||||||
|
async fn install_gui(src: &str) -> anyhow::Result<()> {
|
||||||
|
let target = binary_paths::gpgui();
|
||||||
|
let Some(dir) = target.parent() else {
|
||||||
|
bail!("Failed to get parent directory of GUI binary");
|
||||||
|
};
|
||||||
|
|
||||||
|
fs::create_dir_all(dir).await?;
|
||||||
|
|
||||||
|
// Unpack the archive
|
||||||
|
info!("Unpacking GUI archive");
|
||||||
|
let tar = XzDecoder::new(BufReader::new(File::open(src)?));
|
||||||
|
let mut ar = Archive::new(tar);
|
||||||
|
|
||||||
|
for entry in ar.entries()? {
|
||||||
|
let mut entry = entry?;
|
||||||
|
let entry_path = entry.path()?;
|
||||||
|
|
||||||
|
if let Some(name) = entry_path.file_name() {
|
||||||
|
let name = name.to_string_lossy();
|
||||||
|
|
||||||
|
if name == "gpgui" {
|
||||||
|
let mut file = File::create(&target)?;
|
||||||
|
std::io::copy(&mut entry, &mut file)?;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make the binary executable
|
||||||
|
fs::set_permissions(target, Permissions::from_mode(0o755)).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) async fn ws_handler(ws: WebSocketUpgrade, State(ctx): State<Arc<WsServerContext>>) -> impl IntoResponse {
|
pub(crate) async fn ws_handler(ws: WebSocketUpgrade, State(ctx): State<Arc<WsServerContext>>) -> impl IntoResponse {
|
||||||
ws.max_message_size(MAX_WS_MESSAGE)
|
ws.on_upgrade(move |socket| handle_socket(socket, ctx))
|
||||||
.max_frame_size(MAX_WS_MESSAGE)
|
}
|
||||||
.on_upgrade(move |socket| WsConnection::accept(socket, ctx))
|
|
||||||
|
async fn handle_socket(mut socket: WebSocket, ctx: Arc<WsServerContext>) {
|
||||||
|
// Send ping message
|
||||||
|
if let Err(err) = socket.send(Message::Ping("Hi".into())).await {
|
||||||
|
warn!("Failed to send ping: {}", err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for pong message
|
||||||
|
if socket.recv().await.is_none() {
|
||||||
|
warn!("Failed to receive pong");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
info!("New client connected");
|
||||||
|
|
||||||
|
let (mut sender, mut receiver) = socket.split();
|
||||||
|
let (connection, mut msg_rx) = ctx.add_connection().await;
|
||||||
|
|
||||||
|
let send_task = tokio::spawn(async move {
|
||||||
|
while let Some(msg) = msg_rx.recv().await {
|
||||||
|
if let Err(err) = sender.send(msg).await {
|
||||||
|
info!("Failed to send message: {}", err);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let close_msg = Message::Close(Some(CloseFrame {
|
||||||
|
code: ws::close_code::NORMAL,
|
||||||
|
reason: Utf8Bytes::from("Goodbye"),
|
||||||
|
}));
|
||||||
|
|
||||||
|
if let Err(err) = sender.send(close_msg).await {
|
||||||
|
warn!("Failed to close socket: {}", err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let conn = Arc::clone(&connection);
|
||||||
|
let ctx_clone = Arc::clone(&ctx);
|
||||||
|
let recv_task = tokio::spawn(async move {
|
||||||
|
while let Some(Ok(msg)) = receiver.next().await {
|
||||||
|
let ControlFlow::Continue(ws_req) = conn.recv_msg(msg) else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(err) = ctx_clone.forward_req(ws_req).await {
|
||||||
|
info!("Failed to forward request: {}", err);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
tokio::select! {
|
||||||
|
_ = send_task => {
|
||||||
|
info!("WS server send task completed");
|
||||||
|
},
|
||||||
|
_ = recv_task => {
|
||||||
|
info!("WS server recv task completed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
info!("Client disconnected");
|
||||||
|
|
||||||
|
ctx.remove_connection(connection).await;
|
||||||
}
|
}
|
||||||
@@ -1,406 +0,0 @@
|
|||||||
use std::{
|
|
||||||
fs::{self, File, OpenOptions},
|
|
||||||
io::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;
|
|
||||||
|
|
||||||
use crate::hip_runner_state::validate_root_owned_path;
|
|
||||||
|
|
||||||
#[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_root_owned_path(base, false)?;
|
|
||||||
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> {
|
|
||||||
ensure!(desktop_uid != 0, "Root is not a desktop HIP approval owner");
|
|
||||||
let base = Path::new(APPROVAL_DIRECTORY);
|
|
||||||
validate_root_owned_path(base, false)?;
|
|
||||||
resolve_at(base, approval_id, desktop_uid, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
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_root_owned_path(base, false)?;
|
|
||||||
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_root_owned_path(base, false).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 info = read_metadata_at(base, approval_id, desktop_uid, file_owner)?;
|
|
||||||
let script = base.join(approval_id).join(SCRIPT_NAME);
|
|
||||||
validate_file(&script, file_owner, 0o500, MAX_SCRIPT_SIZE as u64)?;
|
|
||||||
let contents = fs::read(&script)?;
|
|
||||||
ensure!(!contents.is_empty(), "Approved HIP script is empty");
|
|
||||||
ensure!(
|
|
||||||
sha256::digest(&contents) == info.sha256,
|
|
||||||
"Approved HIP script digest mismatch"
|
|
||||||
);
|
|
||||||
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(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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,275 +0,0 @@
|
|||||||
use std::{os::unix::process::CommandExt, process::Stdio, sync::Arc, time::Duration};
|
|
||||||
|
|
||||||
use anyhow::{Context, bail, ensure};
|
|
||||||
use gpapi::{hip::HipSource, service::request::PreviewHipReportRequest};
|
|
||||||
use tokio::{io::AsyncReadExt, process::Command};
|
|
||||||
|
|
||||||
const MAX_PREVIEW_BYTES: u64 = 1024 * 1024;
|
|
||||||
const PREVIEW_TIMEOUT: Duration = Duration::from_secs(60);
|
|
||||||
const PREVIEW_COOKIE: &str = "user=preview&domain=preview&computer=preview";
|
|
||||||
const PREVIEW_IP: &str = "192.0.2.1";
|
|
||||||
const PREVIEW_MD5: &str = "00000000000000000000000000000000";
|
|
||||||
|
|
||||||
pub(crate) async fn generate(
|
|
||||||
request: PreviewHipReportRequest,
|
|
||||||
edited_report: Option<Arc<str>>,
|
|
||||||
desktop_uid: Option<u32>,
|
|
||||||
) -> 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 source = &request.source;
|
|
||||||
let execution = match source {
|
|
||||||
HipSource::Disabled => bail!("HIP is disabled"),
|
|
||||||
HipSource::Generated | HipSource::Edited { .. } => crate::hip_source::preview_runner(edited_report)?,
|
|
||||||
HipSource::UserScript { .. } | HipSource::ApprovedRootScript { .. } => {
|
|
||||||
crate::hip_source::resolve(source, desktop_uid, false, None)?
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let script = execution
|
|
||||||
.wrapper
|
|
||||||
.as_deref()
|
|
||||||
.context("HIP preview script is unavailable")?;
|
|
||||||
let is_runner = !matches!(source, HipSource::UserScript { .. });
|
|
||||||
let mut command = Command::new(script);
|
|
||||||
command
|
|
||||||
.arg("--client-version")
|
|
||||||
.arg(&request.client_version)
|
|
||||||
.arg("--client-os")
|
|
||||||
.arg(request.client_os.as_str())
|
|
||||||
.arg("--os-version")
|
|
||||||
.arg(request.client_os.default_os_version());
|
|
||||||
if let Some(host_id) = request.host_id {
|
|
||||||
command.arg("--host-id").arg(host_id);
|
|
||||||
}
|
|
||||||
if is_runner {
|
|
||||||
command.arg("--preview");
|
|
||||||
}
|
|
||||||
command
|
|
||||||
.arg("--cookie")
|
|
||||||
.arg(PREVIEW_COOKIE)
|
|
||||||
.arg("--client-ip")
|
|
||||||
.arg(PREVIEW_IP)
|
|
||||||
.arg("--md5")
|
|
||||||
.arg(PREVIEW_MD5)
|
|
||||||
.stdin(Stdio::null())
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.stderr(Stdio::null());
|
|
||||||
command.as_std_mut().process_group(0);
|
|
||||||
configure_identity(&mut command, execution.uid, &request.client_version)?;
|
|
||||||
command.kill_on_drop(true);
|
|
||||||
|
|
||||||
let mut child = command.spawn().context("Failed to launch HIP preview")?;
|
|
||||||
let mut process_group = ProcessGroupGuard::new(child.id());
|
|
||||||
let mut stdout = child
|
|
||||||
.stdout
|
|
||||||
.take()
|
|
||||||
.context("HIP preview has no output stream")?
|
|
||||||
.take(MAX_PREVIEW_BYTES + 1);
|
|
||||||
let output = tokio::time::timeout(PREVIEW_TIMEOUT, async {
|
|
||||||
let mut bytes = Vec::new();
|
|
||||||
stdout.read_to_end(&mut bytes).await?;
|
|
||||||
ensure!(bytes.len() as u64 <= MAX_PREVIEW_BYTES, "HIP preview exceeds 1 MiB");
|
|
||||||
let status = child.wait().await?;
|
|
||||||
process_group.disarm();
|
|
||||||
ensure!(status.success(), "HIP preview generator failed");
|
|
||||||
Ok::<_, anyhow::Error>(String::from_utf8(bytes)?)
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
match output {
|
|
||||||
Ok(Ok(xml)) => {
|
|
||||||
if matches!(
|
|
||||||
source,
|
|
||||||
HipSource::UserScript { .. } | HipSource::ApprovedRootScript { .. }
|
|
||||||
) {
|
|
||||||
gphip::validate_edited_report(&xml).context("Custom HIP script did not emit a valid HIP report")?;
|
|
||||||
}
|
|
||||||
Ok(xml)
|
|
||||||
}
|
|
||||||
Ok(Err(error)) => {
|
|
||||||
terminate_group(&mut child, &mut process_group).await;
|
|
||||||
Err(error)
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
terminate_group(&mut child, &mut process_group).await;
|
|
||||||
anyhow::bail!("HIP preview timed out")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_identity(command: &mut Command, uid: u32, app_version: &str) -> anyhow::Result<()> {
|
|
||||||
command
|
|
||||||
.as_std_mut()
|
|
||||||
.env_clear()
|
|
||||||
.env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
|
|
||||||
.env("LC_ALL", "C")
|
|
||||||
.env("APP_VERSION", app_version);
|
|
||||||
if uid == 0 {
|
|
||||||
command.as_std_mut().env("HOME", "/root");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
{
|
|
||||||
use nix::unistd::{Uid, User};
|
|
||||||
let user = User::from_uid(Uid::from_raw(uid))?.context("Desktop user is unavailable")?;
|
|
||||||
command
|
|
||||||
.as_std_mut()
|
|
||||||
.env("HOME", &user.dir)
|
|
||||||
.env("USER", &user.name)
|
|
||||||
.env("LOGNAME", &user.name)
|
|
||||||
.current_dir(&user.dir);
|
|
||||||
if Uid::effective().as_raw() == uid {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
// Match OpenConnect's CSD child: a single primary group, then the desktop UID.
|
|
||||||
unsafe {
|
|
||||||
command.as_std_mut().pre_exec(move || {
|
|
||||||
nix::unistd::setgid(user.gid).map_err(std::io::Error::from)?;
|
|
||||||
nix::unistd::setgroups(&[user.gid]).map_err(std::io::Error::from)?;
|
|
||||||
nix::unistd::setuid(Uid::from_raw(uid)).map_err(std::io::Error::from)?;
|
|
||||||
Ok(())
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
|
||||||
{
|
|
||||||
bail!("Custom HIP previews are unavailable on this platform")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct ProcessGroupGuard(Option<u32>);
|
|
||||||
|
|
||||||
impl ProcessGroupGuard {
|
|
||||||
fn new(pid: Option<u32>) -> Self {
|
|
||||||
Self(pid)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn kill(&mut self) {
|
|
||||||
if let Some(pid) = self.0.take() {
|
|
||||||
unsafe { nix::libc::kill(-(pid as i32), nix::libc::SIGKILL) };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn disarm(&mut self) {
|
|
||||||
self.0 = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for ProcessGroupGuard {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
self.kill();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn terminate_group(child: &mut tokio::process::Child, process_group: &mut ProcessGroupGuard) {
|
|
||||||
process_group.kill();
|
|
||||||
let _ = child.start_kill();
|
|
||||||
let _ = child.wait().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(all(test, any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use gpapi::os_profile::ClientOs;
|
|
||||||
use std::{fs, os::unix::fs::PermissionsExt};
|
|
||||||
|
|
||||||
fn request(path: &std::path::Path) -> PreviewHipReportRequest {
|
|
||||||
PreviewHipReportRequest {
|
|
||||||
source: HipSource::UserScript {
|
|
||||||
path: path.to_string_lossy().into_owned(),
|
|
||||||
},
|
|
||||||
client_os: ClientOs::Linux,
|
|
||||||
client_version: "6.3.3".into(),
|
|
||||||
host_id: Some("host-test".into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn script(path: &std::path::Path, body: &str) {
|
|
||||||
fs::write(path, format!("#!/bin/sh\n{body}\n")).unwrap();
|
|
||||||
fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn user_script_preview_receives_placeholders_and_validates_output() {
|
|
||||||
let uid = nix::unistd::Uid::effective().as_raw();
|
|
||||||
if uid == 0 {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let path = dir.path().join("hip.sh");
|
|
||||||
script(
|
|
||||||
&path,
|
|
||||||
r#"
|
|
||||||
test "$1" = --client-version && test "$2" = 6.3.3 || exit 2
|
|
||||||
test "$3" = --client-os && test "$4" = Linux || exit 2
|
|
||||||
test "$5" = --os-version || exit 2
|
|
||||||
test "$7" = --host-id && test "$8" = host-test || exit 2
|
|
||||||
test "$9" = --cookie && test "${10}" = 'user=preview&domain=preview&computer=preview' || exit 2
|
|
||||||
test "${11}" = --client-ip && test "${12}" = 192.0.2.1 || exit 2
|
|
||||||
test "${13}" = --md5 && test "${14}" = 00000000000000000000000000000000 || exit 2
|
|
||||||
test "$#" = 14 || exit 2
|
|
||||||
test "$APP_VERSION" = 6.3.3 || exit 2
|
|
||||||
printf '%s' '<hip-report><md5-sum/><user-name/><domain/><host-name/><host-id/><ip-address/><ipv6-address/><generate-time/><hip-report-version/><categories><entry name="host-info"><client-version/><os/><os-vendor/><domain/><host-name/><host-id/></entry></categories></hip-report>'
|
|
||||||
"#,
|
|
||||||
);
|
|
||||||
let xml = generate(request(&path), None, Some(uid)).await.unwrap();
|
|
||||||
assert!(xml.starts_with("<hip-report>"));
|
|
||||||
|
|
||||||
script(&path, "printf '%s' '<not-hip/>'");
|
|
||||||
assert!(generate(request(&path), None, Some(uid)).await.is_err());
|
|
||||||
|
|
||||||
script(&path, "head -c 1048577 /dev/zero");
|
|
||||||
let err = generate(request(&path), None, Some(uid)).await.unwrap_err();
|
|
||||||
assert!(err.to_string().contains("exceeds 1 MiB"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
#[tokio::test]
|
|
||||||
async fn cancelling_preview_stops_its_process_group() {
|
|
||||||
let uid = nix::unistd::Uid::effective().as_raw();
|
|
||||||
if uid == 0 {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let path = dir.path().join("hip.sh");
|
|
||||||
let pid_file = dir.path().join("pids");
|
|
||||||
script(
|
|
||||||
&path,
|
|
||||||
&format!(
|
|
||||||
"sleep 30 & child=$!; echo \"$$ $child\" > \"{}\"; wait",
|
|
||||||
pid_file.display()
|
|
||||||
),
|
|
||||||
);
|
|
||||||
let preview = tokio::spawn(generate(request(&path), None, Some(uid)));
|
|
||||||
let pids = tokio::time::timeout(Duration::from_secs(3), async {
|
|
||||||
loop {
|
|
||||||
if let Ok(pids) = fs::read_to_string(&pid_file) {
|
|
||||||
break pids;
|
|
||||||
}
|
|
||||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let child_pid = pids.split_whitespace().nth(1).unwrap().parse::<u32>().unwrap();
|
|
||||||
preview.abort();
|
|
||||||
assert!(preview.await.unwrap_err().is_cancelled());
|
|
||||||
tokio::time::timeout(Duration::from_secs(3), async {
|
|
||||||
loop {
|
|
||||||
let state = fs::read_to_string(format!("/proc/{child_pid}/stat"))
|
|
||||||
.ok()
|
|
||||||
.and_then(|stat| stat.rsplit_once(") ").and_then(|(_, fields)| fields.chars().next()));
|
|
||||||
if state.is_none_or(|state| state == 'Z') {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
use std::{
|
|
||||||
fs,
|
|
||||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
|
||||||
path::Path,
|
|
||||||
};
|
|
||||||
|
|
||||||
use anyhow::{Context, ensure};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
pub const RUNNER_NAME: &str = "gp-hip-runner";
|
|
||||||
pub const STATE_NAME: &str = "report.json";
|
|
||||||
pub const MAX_STATE_BYTES: usize = 512 * 1024;
|
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize)]
|
|
||||||
#[serde(tag = "source", rename_all = "camelCase")]
|
|
||||||
pub enum RunnerReport {
|
|
||||||
Generated,
|
|
||||||
Edited { xml: String },
|
|
||||||
ApprovedRootScript { approval_id: String, owner_uid: u32 },
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check every component because a trusted file below a writable parent can
|
|
||||||
/// be replaced before a later HIP refresh.
|
|
||||||
pub fn validate_root_owned_path(path: &Path, file: bool) -> anyhow::Result<()> {
|
|
||||||
ensure!(path.is_absolute(), "HIP runner 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 runner path contains a symlink");
|
|
||||||
ensure!(metadata.uid() == 0, "HIP runner path is not root-owned");
|
|
||||||
ensure!(
|
|
||||||
metadata.permissions().mode() & 0o022 == 0,
|
|
||||||
"HIP runner path is writable by another user"
|
|
||||||
);
|
|
||||||
if component == path && file {
|
|
||||||
ensure!(metadata.is_file(), "HIP runner is not a regular file");
|
|
||||||
ensure!(
|
|
||||||
metadata.permissions().mode() & 0o111 != 0,
|
|
||||||
"HIP runner is not executable"
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
ensure!(metadata.is_dir(), "HIP runner parent is not a directory");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_user_owned_runner_directory() {
|
|
||||||
let temp = tempfile::tempdir().unwrap();
|
|
||||||
if unsafe { nix::libc::geteuid() } != 0 {
|
|
||||||
assert!(validate_root_owned_path(temp.path(), false).is_err());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,291 +0,0 @@
|
|||||||
use std::{
|
|
||||||
fs::{self, OpenOptions},
|
|
||||||
io::Write,
|
|
||||||
os::unix::fs::{OpenOptionsExt, PermissionsExt},
|
|
||||||
path::{Path, PathBuf},
|
|
||||||
sync::Arc,
|
|
||||||
};
|
|
||||||
|
|
||||||
use anyhow::{Context, bail, ensure};
|
|
||||||
use gpapi::hip::HipSource;
|
|
||||||
use gpservice::hip_runner_state::{MAX_STATE_BYTES, RUNNER_NAME, RunnerReport, STATE_NAME, validate_root_owned_path};
|
|
||||||
use tempfile::{Builder, TempDir};
|
|
||||||
|
|
||||||
pub(crate) struct HipExecution {
|
|
||||||
pub enabled: bool,
|
|
||||||
pub uid: u32,
|
|
||||||
pub wrapper: Option<String>,
|
|
||||||
_state_dir: Option<TempDir>,
|
|
||||||
approval: Option<(String, u32)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HipExecution {
|
|
||||||
fn disabled() -> Self {
|
|
||||||
Self {
|
|
||||||
enabled: false,
|
|
||||||
uid: 0,
|
|
||||||
wrapper: None,
|
|
||||||
_state_dir: None,
|
|
||||||
approval: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn script(uid: u32, wrapper: PathBuf, state_dir: Option<TempDir>) -> Self {
|
|
||||||
Self {
|
|
||||||
enabled: true,
|
|
||||||
uid,
|
|
||||||
wrapper: Some(wrapper.to_string_lossy().into_owned()),
|
|
||||||
_state_dir: state_dir,
|
|
||||||
approval: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn approval_id(&self) -> Option<&str> {
|
|
||||||
self.approval.as_ref().map(|(id, _)| id.as_str())
|
|
||||||
}
|
|
||||||
|
|
||||||
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.approval {
|
|
||||||
return gpservice::hip_approval::resolve(id, *uid).is_ok();
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn resolve(
|
|
||||||
source: &HipSource,
|
|
||||||
desktop_uid: Option<u32>,
|
|
||||||
brokered_macos: bool,
|
|
||||||
edited_report: Option<Arc<str>>,
|
|
||||||
) -> anyhow::Result<HipExecution> {
|
|
||||||
match source {
|
|
||||||
HipSource::Disabled => Ok(HipExecution::disabled()),
|
|
||||||
HipSource::Generated => stage_runner(RunnerReport::Generated),
|
|
||||||
HipSource::Edited { .. } => {
|
|
||||||
let xml = edited_report.context("Edited HIP report was not uploaded for this connection")?;
|
|
||||||
gphip::validate_edited_report(&xml)?;
|
|
||||||
stage_runner(RunnerReport::Edited { xml: xml.to_string() })
|
|
||||||
}
|
|
||||||
HipSource::UserScript { path } => {
|
|
||||||
if cfg!(target_os = "macos") || brokered_macos {
|
|
||||||
bail!("Custom HIP scripts are unavailable on 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);
|
|
||||||
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"
|
|
||||||
);
|
|
||||||
Ok(HipExecution::script(uid, path, None))
|
|
||||||
}
|
|
||||||
HipSource::ApprovedRootScript { approval_id } => {
|
|
||||||
if cfg!(target_os = "macos") || brokered_macos {
|
|
||||||
bail!("Custom HIP scripts are unavailable on 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")?;
|
|
||||||
gpservice::hip_approval::resolve(approval_id, owner_uid)?;
|
|
||||||
let mut execution = stage_runner(RunnerReport::ApprovedRootScript {
|
|
||||||
approval_id: approval_id.clone(),
|
|
||||||
owner_uid,
|
|
||||||
})?;
|
|
||||||
execution.approval = Some((approval_id.clone(), owner_uid));
|
|
||||||
Ok(execution)
|
|
||||||
}
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
|
||||||
{
|
|
||||||
let _ = (approval_id, desktop_uid);
|
|
||||||
bail!("Root HIP script approvals are unavailable on this platform")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn preview_runner(edited_report: Option<Arc<str>>) -> anyhow::Result<HipExecution> {
|
|
||||||
let report = if let Some(xml) = edited_report {
|
|
||||||
gphip::validate_edited_report(&xml)?;
|
|
||||||
RunnerReport::Edited { xml: xml.to_string() }
|
|
||||||
} else {
|
|
||||||
RunnerReport::Generated
|
|
||||||
};
|
|
||||||
stage_runner(report)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stage_runner(report: RunnerReport) -> anyhow::Result<HipExecution> {
|
|
||||||
let source = packaged_runner()?;
|
|
||||||
let base = runner_state_base();
|
|
||||||
fs::create_dir_all(base).context("Cannot create HIP runtime directory")?;
|
|
||||||
validate_root_owned_path(base, false)?;
|
|
||||||
fs::set_permissions(base, fs::Permissions::from_mode(0o700))?;
|
|
||||||
let state_dir = Builder::new().prefix("session-").tempdir_in(base)?;
|
|
||||||
fs::set_permissions(state_dir.path(), fs::Permissions::from_mode(0o700))?;
|
|
||||||
validate_root_owned_path(state_dir.path(), false)?;
|
|
||||||
|
|
||||||
let runner = state_dir.path().join(RUNNER_NAME);
|
|
||||||
fs::copy(&source, &runner).context("Cannot stage HIP runner")?;
|
|
||||||
fs::set_permissions(&runner, fs::Permissions::from_mode(0o500))?;
|
|
||||||
validate_root_owned_path(&runner, true)?;
|
|
||||||
verify_staged_runner(&runner)?;
|
|
||||||
|
|
||||||
let encoded_state = serde_json::to_vec(&report)?;
|
|
||||||
ensure!(
|
|
||||||
encoded_state.len() <= MAX_STATE_BYTES,
|
|
||||||
"HIP runner state exceeds its size limit"
|
|
||||||
);
|
|
||||||
let state = state_dir.path().join(STATE_NAME);
|
|
||||||
let mut state_file = OpenOptions::new()
|
|
||||||
.write(true)
|
|
||||||
.create_new(true)
|
|
||||||
.mode(0o600)
|
|
||||||
.open(&state)?;
|
|
||||||
state_file.write_all(&encoded_state)?;
|
|
||||||
state_file.flush()?;
|
|
||||||
Ok(HipExecution::script(0, runner, Some(state_dir)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn runner_state_base() -> &'static Path {
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
{
|
|
||||||
Path::new("/private/var/db/gpclient/hip")
|
|
||||||
}
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
{
|
|
||||||
Path::new("/var/lib/gpclient/hip")
|
|
||||||
}
|
|
||||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
{
|
|
||||||
Path::new("/var/db/gpclient/hip")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn packaged_runner() -> anyhow::Result<PathBuf> {
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
let path = std::env::current_exe()
|
|
||||||
.context("Cannot locate HIP runner")?
|
|
||||||
.with_file_name(RUNNER_NAME);
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
let path = PathBuf::from("/usr/libexec/gpclient/gp-hip-runner");
|
|
||||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
let path = PathBuf::from("/usr/local/libexec/gpclient/gp-hip-runner");
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "macos"))]
|
|
||||||
validate_root_owned_path(&path, true)?;
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
verify_packaged_macos_runner(&path)?;
|
|
||||||
ensure!(path.is_file(), "Bundled HIP runner is missing");
|
|
||||||
Ok(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
fn verify_packaged_macos_runner(path: &Path) -> anyhow::Result<()> {
|
|
||||||
use std::process::Command;
|
|
||||||
let service = std::env::current_exe()?;
|
|
||||||
let app = service
|
|
||||||
.parent()
|
|
||||||
.and_then(Path::parent)
|
|
||||||
.and_then(Path::parent)
|
|
||||||
.context("gpservice is not in an app bundle")?;
|
|
||||||
ensure!(
|
|
||||||
path.parent() == service.parent(),
|
|
||||||
"HIP runner is outside the app Helpers directory"
|
|
||||||
);
|
|
||||||
let status = Command::new("/usr/bin/codesign")
|
|
||||||
.args(["--verify", "--deep", "--strict"])
|
|
||||||
.arg(app)
|
|
||||||
.status()?;
|
|
||||||
ensure!(status.success(), "HIP application bundle signature is invalid");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
fn verify_staged_runner(path: &Path) -> anyhow::Result<()> {
|
|
||||||
use std::process::Command;
|
|
||||||
let status = Command::new("/usr/bin/codesign")
|
|
||||||
.args(["--verify", "--strict"])
|
|
||||||
.arg(path)
|
|
||||||
.status()?;
|
|
||||||
ensure!(status.success(), "Staged HIP runner signature is invalid");
|
|
||||||
let service = std::env::current_exe()?;
|
|
||||||
ensure!(
|
|
||||||
signing_team(path)? == signing_team(&service)?,
|
|
||||||
"HIP runner and service have different signing teams"
|
|
||||||
);
|
|
||||||
|
|
||||||
// The staged runner has no app Frameworks directory. Reject any library
|
|
||||||
// reference that could resolve through a writable bundle or search path.
|
|
||||||
let output = Command::new("/usr/bin/otool").arg("-L").arg(path).output()?;
|
|
||||||
ensure!(output.status.success(), "Cannot inspect HIP runner libraries");
|
|
||||||
for library in String::from_utf8(output.stdout)?
|
|
||||||
.lines()
|
|
||||||
.skip(1)
|
|
||||||
.filter_map(|line| line.trim().split_whitespace().next())
|
|
||||||
{
|
|
||||||
ensure!(
|
|
||||||
library.starts_with("/usr/lib/") || library.starts_with("/System/Library/"),
|
|
||||||
"HIP runner loads a library outside the trusted system paths"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
fn signing_team(path: &Path) -> anyhow::Result<String> {
|
|
||||||
let output = std::process::Command::new("/usr/bin/codesign")
|
|
||||||
.args(["-d", "--verbose=4"])
|
|
||||||
.arg(path)
|
|
||||||
.output()?;
|
|
||||||
ensure!(output.status.success(), "Cannot inspect code signature");
|
|
||||||
let details = String::from_utf8(output.stderr)?;
|
|
||||||
details
|
|
||||||
.lines()
|
|
||||||
.find_map(|line| line.strip_prefix("TeamIdentifier="))
|
|
||||||
.filter(|team| !team.is_empty() && *team != "not set")
|
|
||||||
.map(str::to_owned)
|
|
||||||
.context("Signed HIP binary has no team identifier")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "macos"))]
|
|
||||||
fn verify_staged_runner(_path: &Path) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn disabled_has_no_script_on_both_gui_platforms() {
|
|
||||||
for brokered_macos in [false, true] {
|
|
||||||
let execution = resolve(&HipSource::Disabled, None, brokered_macos, None).unwrap();
|
|
||||||
assert!(!execution.enabled);
|
|
||||||
assert!(execution.wrapper.is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn custom_source_cannot_choose_root_or_run_on_macos() {
|
|
||||||
let source = HipSource::UserScript {
|
|
||||||
path: "/tmp/hip.sh".into(),
|
|
||||||
};
|
|
||||||
assert!(resolve(&source, None, false, None).is_err());
|
|
||||||
assert!(resolve(&source, Some(0), false, None).is_err());
|
|
||||||
assert!(resolve(&source, Some(1000), true, None).is_err());
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
assert!(resolve(&source, Some(1000), false, None).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
#[test]
|
|
||||||
fn root_source_requires_a_bound_user_and_installed_approval() {
|
|
||||||
let source = HipSource::ApprovedRootScript {
|
|
||||||
approval_id: "00000000-0000-4000-8000-000000000000".into(),
|
|
||||||
};
|
|
||||||
assert!(resolve(&source, None, false, None).is_err());
|
|
||||||
assert!(resolve(&source, Some(0), false, None).is_err());
|
|
||||||
assert!(resolve(&source, Some(1000), false, None).is_err());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
pub mod hip_approval;
|
|
||||||
pub mod hip_runner_state;
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
pub mod vpnc_script;
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
use std::{
|
|
||||||
os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt},
|
|
||||||
path::{Path, PathBuf},
|
|
||||||
sync::Arc,
|
|
||||||
};
|
|
||||||
|
|
||||||
use anyhow::{Context, bail};
|
|
||||||
use log::{info, warn};
|
|
||||||
use nix::unistd::Uid;
|
|
||||||
use tokio::net::{UnixListener, UnixStream};
|
|
||||||
use tokio_util::sync::CancellationToken;
|
|
||||||
|
|
||||||
use crate::{credential_lease, session_registry::SessionRegistry};
|
|
||||||
|
|
||||||
pub(crate) const CREDENTIAL_SOCKET: &str = "/var/run/com.yuezk.gpgui/credential.sock";
|
|
||||||
|
|
||||||
pub(crate) struct CredentialServer {
|
|
||||||
registry: Arc<SessionRegistry>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CredentialServer {
|
|
||||||
pub(crate) fn new(registry: Arc<SessionRegistry>) -> Self {
|
|
||||||
Self { registry }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn start(self, cancel: CancellationToken) -> anyhow::Result<()> {
|
|
||||||
if !Uid::effective().is_root() {
|
|
||||||
bail!("macOS brokered mode requires root privileges");
|
|
||||||
}
|
|
||||||
|
|
||||||
let path = prepare_socket(Path::new(CREDENTIAL_SOCKET), 0)?;
|
|
||||||
let listener = UnixListener::bind(&path)
|
|
||||||
.with_context(|| format!("Failed to bind broker credential socket at {}", path.display()))?;
|
|
||||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
|
|
||||||
info!("Broker credential socket listening at {}", path.display());
|
|
||||||
|
|
||||||
loop {
|
|
||||||
tokio::select! {
|
|
||||||
_ = cancel.cancelled() => break,
|
|
||||||
accepted = listener.accept() => {
|
|
||||||
let (stream, _) = accepted?;
|
|
||||||
if peer_uid(&stream)? != 0 {
|
|
||||||
warn!("Rejected non-root broker credential client");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let registry = Arc::clone(&self.registry);
|
|
||||||
tokio::spawn(async move {
|
|
||||||
if let Err(err) = credential_lease::serve(stream, registry, None).await {
|
|
||||||
warn!("Broker credential lease ended: {err}");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
drop(listener);
|
|
||||||
remove_socket(&path, 0)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare_socket(path: &Path, owner_uid: u32) -> anyhow::Result<PathBuf> {
|
|
||||||
let parent = path
|
|
||||||
.parent()
|
|
||||||
.context("Broker credential socket has no parent directory")?;
|
|
||||||
if !parent.exists() {
|
|
||||||
std::fs::create_dir_all(parent)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let metadata = std::fs::symlink_metadata(parent)?;
|
|
||||||
if metadata.file_type().is_symlink() || !metadata.is_dir() || metadata.uid() != owner_uid {
|
|
||||||
bail!("Broker credential directory must be a real root-owned directory");
|
|
||||||
}
|
|
||||||
if metadata.permissions().mode() & 0o077 != 0 {
|
|
||||||
std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
remove_socket(path, owner_uid)?;
|
|
||||||
Ok(path.to_path_buf())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn remove_socket(path: &Path, owner_uid: u32) -> anyhow::Result<()> {
|
|
||||||
match std::fs::symlink_metadata(path) {
|
|
||||||
Ok(metadata) if metadata.file_type().is_socket() && metadata.uid() == owner_uid => {
|
|
||||||
std::fs::remove_file(path)?;
|
|
||||||
}
|
|
||||||
Ok(_) => bail!("Refusing to replace an unsafe broker credential path"),
|
|
||||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
|
||||||
Err(err) => return Err(err.into()),
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn peer_uid(stream: &UnixStream) -> anyhow::Result<u32> {
|
|
||||||
let (uid, _) = nix::unistd::getpeereid(stream)?;
|
|
||||||
Ok(uid.as_raw())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn prepares_private_owner_directory_and_removes_owned_socket_only() {
|
|
||||||
let temp = tempfile::tempdir().unwrap();
|
|
||||||
let owner = Uid::current().as_raw();
|
|
||||||
let parent = temp.path().join("runtime");
|
|
||||||
let socket = parent.join("credential.sock");
|
|
||||||
|
|
||||||
assert_eq!(prepare_socket(&socket, owner).unwrap(), socket);
|
|
||||||
assert_eq!(std::fs::metadata(&parent).unwrap().permissions().mode() & 0o777, 0o700);
|
|
||||||
|
|
||||||
std::fs::write(&socket, "not a socket").unwrap();
|
|
||||||
assert!(prepare_socket(&socket, owner).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn peer_uid_matches_current_process() {
|
|
||||||
let (stream, _peer) = UnixStream::pair().unwrap();
|
|
||||||
assert_eq!(peer_uid(&stream).unwrap(), Uid::current().as_raw());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +1,6 @@
|
|||||||
mod cli;
|
mod cli;
|
||||||
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
|
|
||||||
mod credential_lease;
|
|
||||||
#[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 handlers;
|
||||||
mod hip_preview;
|
|
||||||
mod hip_source;
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
mod macos_broker;
|
|
||||||
mod request_dispatcher;
|
|
||||||
mod routes;
|
mod routes;
|
||||||
mod runtime_user;
|
|
||||||
mod session_registry;
|
|
||||||
mod vpn_script;
|
|
||||||
mod vpn_task;
|
mod vpn_task;
|
||||||
mod ws_connection;
|
mod ws_connection;
|
||||||
mod ws_server;
|
mod ws_server;
|
||||||
|
|||||||
@@ -1,470 +0,0 @@
|
|||||||
use std::{
|
|
||||||
fs::{self, File, OpenOptions, Permissions},
|
|
||||||
io::{BufReader, Read, Write},
|
|
||||||
os::unix::fs::{OpenOptionsExt, PermissionsExt},
|
|
||||||
path::Path,
|
|
||||||
sync::{Arc, atomic::AtomicBool},
|
|
||||||
};
|
|
||||||
|
|
||||||
use common::binary_paths;
|
|
||||||
use gpapi::{
|
|
||||||
service::{
|
|
||||||
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
|
|
||||||
transport::{ServiceErrorCode, ServiceResult},
|
|
||||||
},
|
|
||||||
utils::{checksum::verify_checksum, redact::Redaction},
|
|
||||||
};
|
|
||||||
use log::{info, warn};
|
|
||||||
use tar::Archive;
|
|
||||||
use tempfile::NamedTempFile;
|
|
||||||
use tokio::sync::Mutex;
|
|
||||||
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 struct RequestDispatcher {
|
|
||||||
lifecycle: crate::vpn_task::LifecycleHandle,
|
|
||||||
gui_restart_requested: Arc<AtomicBool>,
|
|
||||||
redaction: Arc<Redaction>,
|
|
||||||
install_lock: Mutex<()>,
|
|
||||||
gui_management_enabled: bool,
|
|
||||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RequestDispatcher {
|
|
||||||
pub fn new(
|
|
||||||
lifecycle: crate::vpn_task::LifecycleHandle,
|
|
||||||
gui_restart_requested: Arc<AtomicBool>,
|
|
||||||
redaction: Arc<Redaction>,
|
|
||||||
gui_management_enabled: bool,
|
|
||||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
lifecycle,
|
|
||||||
gui_restart_requested,
|
|
||||||
redaction,
|
|
||||||
install_lock: Mutex::new(()),
|
|
||||||
gui_management_enabled,
|
|
||||||
brokered_scripts_dir,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn dispatch_lifecycle(
|
|
||||||
&self,
|
|
||||||
request: WsRequest,
|
|
||||||
desktop_uid: Option<u32>,
|
|
||||||
edited_report: Option<Arc<str>>,
|
|
||||||
session_id: Option<uuid::Uuid>,
|
|
||||||
) -> Result<WsRequest, ServiceResult> {
|
|
||||||
match request {
|
|
||||||
WsRequest::Connect(request) => {
|
|
||||||
if let Err(message) = self.validate_connect_paths(&request) {
|
|
||||||
return Err(ServiceResult::rejected(ServiceErrorCode::InvalidRequest, message));
|
|
||||||
}
|
|
||||||
if let Err(err) = self
|
|
||||||
.redaction
|
|
||||||
.add_values(&[request.gateway().server(), request.args().cookie()])
|
|
||||||
{
|
|
||||||
warn!("Failed to update log redaction: {err}");
|
|
||||||
return Err(ServiceResult::rejected(
|
|
||||||
ServiceErrorCode::Internal,
|
|
||||||
"Request could not be accepted",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Err(
|
|
||||||
self
|
|
||||||
.lifecycle
|
|
||||||
.submit_connect(*request, desktop_uid, edited_report, session_id),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
WsRequest::Disconnect(_) => Err(self.lifecycle.request_disconnect()),
|
|
||||||
request => Ok(request),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn dispatch(&self, request: WsRequest) -> ServiceResult {
|
|
||||||
let request = match self.dispatch_lifecycle(request, None, None, None) {
|
|
||||||
Ok(request) => request,
|
|
||||||
Err(result) => return result,
|
|
||||||
};
|
|
||||||
|
|
||||||
match request {
|
|
||||||
WsRequest::RestartGui => {
|
|
||||||
if !self.gui_management_enabled {
|
|
||||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "GUI restart is unavailable on macOS");
|
|
||||||
}
|
|
||||||
info!("GUI restart requested");
|
|
||||||
self
|
|
||||||
.gui_restart_requested
|
|
||||||
.store(true, std::sync::atomic::Ordering::SeqCst);
|
|
||||||
ServiceResult::Accepted
|
|
||||||
}
|
|
||||||
WsRequest::UpdateGui(request) => {
|
|
||||||
if !self.gui_management_enabled {
|
|
||||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "GUI update is unavailable on macOS");
|
|
||||||
}
|
|
||||||
self.update_gui(request).await
|
|
||||||
}
|
|
||||||
WsRequest::GetVpncScriptMetadata => {
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
{
|
|
||||||
match gpservice::vpnc_script::metadata() {
|
|
||||||
Ok(metadata) => ServiceResult::VpncScriptMetadata(metadata),
|
|
||||||
Err(err) => {
|
|
||||||
warn!("Failed to read VPNC script metadata: {err}");
|
|
||||||
ServiceResult::rejected(ServiceErrorCode::Internal, "Failed to read VPNC script metadata")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
|
||||||
{
|
|
||||||
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}");
|
|
||||||
}
|
|
||||||
ServiceResult::Accepted
|
|
||||||
}
|
|
||||||
WsRequest::Connect(_)
|
|
||||||
| WsRequest::Disconnect(_)
|
|
||||||
| WsRequest::StoreEditedHipReportChunk(_)
|
|
||||||
| WsRequest::PreviewHipReport(_)
|
|
||||||
| WsRequest::GetHipApprovalStatus { .. }
|
|
||||||
| WsRequest::ReadHipPreviewChunk(_)
|
|
||||||
| WsRequest::GetLastSubmittedHipReport => {
|
|
||||||
unreachable!("session-bound request was already dispatched")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validate_connect_paths(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
|
|
||||||
let Some(scripts) = &self.brokered_scripts_dir else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
let expected_script = scripts.join("vpnc-script").to_string_lossy().into_owned();
|
|
||||||
if request.args().vpnc_script().as_deref() != Some(expected_script.as_str()) {
|
|
||||||
return Err("macOS VPN script must be the bundled script");
|
|
||||||
}
|
|
||||||
if 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().certificate().is_some() || request.args().sslkey().is_some() {
|
|
||||||
return Err("macOS client identity must be provided as protected data, not root-readable paths");
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult {
|
|
||||||
let _install = self.install_lock.lock().await;
|
|
||||||
let path = request.path;
|
|
||||||
let checksum = request.checksum;
|
|
||||||
let installed = tokio::task::spawn_blocking(move || install_gui(&path, &checksum)).await;
|
|
||||||
match installed {
|
|
||||||
Ok(Ok(())) => ServiceResult::Accepted,
|
|
||||||
Ok(Err(GuiInstallError::Checksum(err))) => {
|
|
||||||
warn!("Failed to verify GUI update checksum: {err}");
|
|
||||||
ServiceResult::rejected(ServiceErrorCode::ChecksumFailed, "GUI update checksum failed")
|
|
||||||
}
|
|
||||||
Ok(Err(GuiInstallError::Install(err))) => {
|
|
||||||
warn!("Failed to install GUI update: {err}");
|
|
||||||
ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed")
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
warn!("GUI update task failed: {err}");
|
|
||||||
ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
enum GuiInstallError {
|
|
||||||
Checksum(anyhow::Error),
|
|
||||||
Install(anyhow::Error),
|
|
||||||
}
|
|
||||||
|
|
||||||
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 Some(dir) = target.parent() else {
|
|
||||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
|
||||||
"Failed to get parent directory of GUI binary"
|
|
||||||
)));
|
|
||||||
};
|
|
||||||
fs::create_dir_all(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
|
|
||||||
let staged_archive = stage_gui_archive(src, dir)?;
|
|
||||||
let archive_path = staged_archive.path().to_string_lossy();
|
|
||||||
verify_checksum(&archive_path, checksum).map_err(GuiInstallError::Checksum)?;
|
|
||||||
|
|
||||||
let tar = XzDecoder::new(BufReader::new(
|
|
||||||
staged_archive
|
|
||||||
.reopen()
|
|
||||||
.map_err(|err| GuiInstallError::Install(err.into()))?,
|
|
||||||
))
|
|
||||||
.take(MAX_GUI_ARCHIVE_CONTENT_SIZE);
|
|
||||||
let mut archive = Archive::new(tar);
|
|
||||||
let file = extract_gui_binary(&mut archive, dir)?;
|
|
||||||
file
|
|
||||||
.as_file()
|
|
||||||
.set_permissions(Permissions::from_mode(0o755))
|
|
||||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
file
|
|
||||||
.as_file()
|
|
||||||
.sync_all()
|
|
||||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
file
|
|
||||||
.persist(&target)
|
|
||||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
File::open(dir)
|
|
||||||
.and_then(|directory| directory.sync_all())
|
|
||||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stage_gui_archive(src: &Path, dir: &Path) -> Result<NamedTempFile, GuiInstallError> {
|
|
||||||
let mut source = OpenOptions::new()
|
|
||||||
.read(true)
|
|
||||||
.custom_flags(nix::libc::O_NONBLOCK | nix::libc::O_NOFOLLOW)
|
|
||||||
.open(src)
|
|
||||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
let metadata = source.metadata().map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
let source_size = metadata.len();
|
|
||||||
if !metadata.file_type().is_file() || source_size == 0 || source_size > MAX_GUI_ARCHIVE_SIZE {
|
|
||||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
|
||||||
"GUI update archive must be a non-empty regular file no larger than {MAX_GUI_ARCHIVE_SIZE} bytes"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut staged = NamedTempFile::new_in(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
let copied = std::io::copy(&mut (&mut source).take(MAX_GUI_ARCHIVE_SIZE + 1), &mut staged)
|
|
||||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
if copied != source_size {
|
|
||||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
|
||||||
"GUI update archive changed while it was being read"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
staged.flush().map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
staged
|
|
||||||
.as_file()
|
|
||||||
.sync_all()
|
|
||||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
Ok(staged)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn extract_gui_binary<R: Read>(archive: &mut Archive<R>, dir: &Path) -> Result<NamedTempFile, GuiInstallError> {
|
|
||||||
for entry in archive.entries().map_err(|err| GuiInstallError::Install(err.into()))? {
|
|
||||||
let mut entry = entry.map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
let is_gui = entry
|
|
||||||
.path()
|
|
||||||
.map_err(|err| GuiInstallError::Install(err.into()))?
|
|
||||||
.file_name()
|
|
||||||
.is_some_and(|name| name == "gpgui");
|
|
||||||
if is_gui && entry.header().entry_type().is_file() {
|
|
||||||
let declared_size = entry.size();
|
|
||||||
if declared_size == 0 || declared_size > MAX_GUI_BINARY_SIZE {
|
|
||||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
|
||||||
"GUI binary must be non-empty and no larger than {MAX_GUI_BINARY_SIZE} bytes"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
let mut file = NamedTempFile::new_in(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
let copied = std::io::copy(&mut entry, &mut file).map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
if copied != declared_size {
|
|
||||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
|
||||||
"GUI binary size does not match its archive header"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
file.flush().map_err(|err| GuiInstallError::Install(err.into()))?;
|
|
||||||
return Ok(file);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(GuiInstallError::Install(anyhow::anyhow!(
|
|
||||||
"GUI update archive does not contain a non-empty regular gpgui file"
|
|
||||||
)))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use std::{io::Cursor, os::unix::fs::PermissionsExt};
|
|
||||||
|
|
||||||
use gpapi::{
|
|
||||||
gateway::Gateway,
|
|
||||||
service::{
|
|
||||||
request::ConnectRequest,
|
|
||||||
transport::{ServiceErrorCode, ServiceResult},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
use tar::{Builder, EntryType, Header};
|
|
||||||
use xz2::write::XzEncoder;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn archive_with_entry(entry_type: EntryType, contents: &[u8]) -> Vec<u8> {
|
|
||||||
let mut data = Vec::new();
|
|
||||||
{
|
|
||||||
let mut builder = Builder::new(&mut data);
|
|
||||||
let mut header = Header::new_gnu();
|
|
||||||
header.set_entry_type(entry_type);
|
|
||||||
header.set_size(contents.len() as u64);
|
|
||||||
header.set_mode(0o755);
|
|
||||||
header.set_cksum();
|
|
||||||
builder.append_data(&mut header, "gpgui", contents).unwrap();
|
|
||||||
builder.finish().unwrap();
|
|
||||||
}
|
|
||||||
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();
|
|
||||||
for (entry_type, contents) in [(EntryType::Directory, &[][..]), (EntryType::Regular, &[][..])] {
|
|
||||||
let data = archive_with_entry(entry_type, contents);
|
|
||||||
let mut archive = Archive::new(Cursor::new(data));
|
|
||||||
assert!(extract_gui_binary(&mut archive, output.path()).is_err());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extracts_non_empty_regular_gui_entry() {
|
|
||||||
let output = tempfile::tempdir().unwrap();
|
|
||||||
let data = archive_with_entry(EntryType::Regular, b"gui binary");
|
|
||||||
let mut archive = Archive::new(Cursor::new(data));
|
|
||||||
let extracted = extract_gui_binary(&mut archive, output.path()).unwrap();
|
|
||||||
let contents = std::fs::read(extracted.path()).unwrap();
|
|
||||||
assert_eq!(contents, b"gui binary");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_invalid_archive_sources() {
|
|
||||||
let output = tempfile::tempdir().unwrap();
|
|
||||||
assert!(stage_gui_archive(output.path(), output.path()).is_err());
|
|
||||||
|
|
||||||
let oversized = output.path().join("oversized.tar.xz");
|
|
||||||
File::create(&oversized)
|
|
||||||
.unwrap()
|
|
||||||
.set_len(MAX_GUI_ARCHIVE_SIZE + 1)
|
|
||||||
.unwrap();
|
|
||||||
assert!(stage_gui_archive(&oversized, output.path()).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_oversized_gui_entry() {
|
|
||||||
let output = tempfile::tempdir().unwrap();
|
|
||||||
let mut header = Header::new_gnu();
|
|
||||||
header.set_entry_type(EntryType::Regular);
|
|
||||||
header.set_size(MAX_GUI_BINARY_SIZE + 1);
|
|
||||||
header.set_mode(0o755);
|
|
||||||
header.set_path("gpgui").unwrap();
|
|
||||||
header.set_cksum();
|
|
||||||
let mut data = header.as_bytes().to_vec();
|
|
||||||
data.resize(512 * 3, 0);
|
|
||||||
|
|
||||||
let mut archive = Archive::new(Cursor::new(data));
|
|
||||||
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 dispatcher = RequestDispatcher::new(
|
|
||||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
|
||||||
Arc::new(AtomicBool::new(false)),
|
|
||||||
Arc::new(Redaction::new()),
|
|
||||||
false,
|
|
||||||
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
|
|
||||||
);
|
|
||||||
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::RestartGui).await else {
|
|
||||||
panic!("brokered mode accepted GUI restart");
|
|
||||||
};
|
|
||||||
assert_eq!(rejection.code(), ServiceErrorCode::InvalidRequest);
|
|
||||||
|
|
||||||
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 = ConnectRequest::new(info, "cookie".into())
|
|
||||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".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");
|
|
||||||
};
|
|
||||||
assert_eq!(rejection.code(), ServiceErrorCode::InvalidRequest);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn brokered_mode_accepts_only_resource_script_paths() {
|
|
||||||
let dispatcher = RequestDispatcher::new(
|
|
||||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
|
||||||
Arc::new(AtomicBool::new(false)),
|
|
||||||
Arc::new(Redaction::new()),
|
|
||||||
false,
|
|
||||||
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
|
|
||||||
);
|
|
||||||
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 = ConnectRequest::new(info.clone(), "cookie".into())
|
|
||||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()));
|
|
||||||
assert_eq!(dispatcher.validate_connect_paths(&bundled), Ok(()));
|
|
||||||
|
|
||||||
let old_layout = ConnectRequest::new(info.clone(), "cookie".into())
|
|
||||||
.with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()));
|
|
||||||
assert_eq!(
|
|
||||||
dispatcher.validate_connect_paths(&old_layout),
|
|
||||||
Err("macOS VPN script must be the bundled script")
|
|
||||||
);
|
|
||||||
|
|
||||||
let custom = ConnectRequest::new(info, "cookie".into())
|
|
||||||
.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")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -11,6 +11,7 @@ pub(crate) fn routes(ctx: Arc<WsServerContext>) -> Router {
|
|||||||
Router::new()
|
Router::new()
|
||||||
.route("/health", get(handlers::health))
|
.route("/health", get(handlers::health))
|
||||||
.route("/active-gui", post(handlers::active_gui))
|
.route("/active-gui", post(handlers::active_gui))
|
||||||
|
.route("/update-gui", post(handlers::update_gui))
|
||||||
.route("/ws", get(handlers::ws_handler))
|
.route("/ws", get(handlers::ws_handler))
|
||||||
.with_state(ctx)
|
.with_state(ctx)
|
||||||
}
|
}
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
pub(crate) fn desktop_uid() -> Option<u32> {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
@@ -1,8 +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 = "default.rs"]
|
|
||||||
mod platform;
|
|
||||||
|
|
||||||
pub(crate) use platform::desktop_uid;
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,660 +0,0 @@
|
|||||||
use std::{
|
|
||||||
collections::HashMap,
|
|
||||||
sync::{Arc, Mutex, Weak},
|
|
||||||
time::{Duration, Instant},
|
|
||||||
};
|
|
||||||
|
|
||||||
use gpapi::service::transport::SessionCredential;
|
|
||||||
use thiserror::Error;
|
|
||||||
use uuid::Uuid;
|
|
||||||
use zeroize::Zeroizing;
|
|
||||||
|
|
||||||
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,
|
|
||||||
registry: Weak<SessionRegistry>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct PreparedAttach {
|
|
||||||
pub generation: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
|
||||||
pub enum SessionError {
|
|
||||||
#[error("credential belongs to another service instance")]
|
|
||||||
ServiceRestarted { service_instance_id: Uuid },
|
|
||||||
#[error("session is unauthorized")]
|
|
||||||
Unauthorized,
|
|
||||||
#[error("too many pending sessions")]
|
|
||||||
TooManyPending,
|
|
||||||
#[error("another reconnect completed first")]
|
|
||||||
ReconnectSuperseded,
|
|
||||||
#[error("session registry is unavailable")]
|
|
||||||
Unavailable,
|
|
||||||
#[error("invalid HIP report upload")]
|
|
||||||
InvalidHipUpload,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub enum HipUploadResult {
|
|
||||||
Progress(Uuid),
|
|
||||||
Stored(Uuid),
|
|
||||||
}
|
|
||||||
|
|
||||||
enum SessionStatus {
|
|
||||||
Pending {
|
|
||||||
activation_deadline: Instant,
|
|
||||||
handshake_token: Option<Uuid>,
|
|
||||||
},
|
|
||||||
Active {
|
|
||||||
generation: u64,
|
|
||||||
connection: Option<ConnectionControl>,
|
|
||||||
reconnect_token: Option<Uuid>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
struct SessionRecord {
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct SessionRegistry {
|
|
||||||
service_instance_id: Uuid,
|
|
||||||
sessions: Mutex<HashMap<Uuid, SessionRecord>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SessionRegistry {
|
|
||||||
pub fn new(service_instance_id: Uuid) -> Self {
|
|
||||||
Self {
|
|
||||||
service_instance_id,
|
|
||||||
sessions: Mutex::new(HashMap::new()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn issue(&self, product_version: &str, desktop_uid: Option<u32>) -> Result<Arc<SessionCredential>, SessionError> {
|
|
||||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
|
||||||
let now = Instant::now();
|
|
||||||
sessions.retain(|_, record| {
|
|
||||||
!matches!(
|
|
||||||
record.status,
|
|
||||||
SessionStatus::Pending {
|
|
||||||
activation_deadline, ..
|
|
||||||
} if now > activation_deadline
|
|
||||||
)
|
|
||||||
});
|
|
||||||
let pending = sessions
|
|
||||||
.values()
|
|
||||||
.filter(|record| matches!(record.status, SessionStatus::Pending { .. }))
|
|
||||||
.count();
|
|
||||||
if pending >= MAX_PENDING_SESSIONS {
|
|
||||||
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);
|
|
||||||
sessions.insert(
|
|
||||||
credential.session_id(),
|
|
||||||
SessionRecord {
|
|
||||||
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,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
Ok(credential)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
pub fn is_empty(&self) -> bool {
|
|
||||||
let Ok(mut sessions) = self.sessions.lock() else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
let now = Instant::now();
|
|
||||||
sessions.retain(|_, record| {
|
|
||||||
!matches!(
|
|
||||||
record.status,
|
|
||||||
SessionStatus::Pending {
|
|
||||||
activation_deadline, ..
|
|
||||||
} if now > activation_deadline
|
|
||||||
)
|
|
||||||
});
|
|
||||||
sessions.is_empty()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn begin_handshake(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
service_instance_id: Uuid,
|
|
||||||
session_id: Uuid,
|
|
||||||
product_version: &str,
|
|
||||||
) -> Result<HandshakePermit, SessionError> {
|
|
||||||
if service_instance_id != self.service_instance_id {
|
|
||||||
return Err(SessionError::ServiceRestarted {
|
|
||||||
service_instance_id: self.service_instance_id,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
|
||||||
let Some(record) = sessions.get_mut(&session_id) else {
|
|
||||||
return Err(SessionError::Unauthorized);
|
|
||||||
};
|
|
||||||
if record.product_version != product_version {
|
|
||||||
return Err(SessionError::Unauthorized);
|
|
||||||
}
|
|
||||||
|
|
||||||
let token = Uuid::new_v4();
|
|
||||||
let observed_generation = match &mut record.status {
|
|
||||||
SessionStatus::Pending {
|
|
||||||
activation_deadline,
|
|
||||||
handshake_token,
|
|
||||||
} => {
|
|
||||||
if Instant::now() > *activation_deadline {
|
|
||||||
sessions.remove(&session_id);
|
|
||||||
return Err(SessionError::Unauthorized);
|
|
||||||
}
|
|
||||||
if handshake_token.is_some() {
|
|
||||||
return Err(SessionError::ReconnectSuperseded);
|
|
||||||
}
|
|
||||||
*handshake_token = Some(token);
|
|
||||||
0
|
|
||||||
}
|
|
||||||
SessionStatus::Active {
|
|
||||||
generation,
|
|
||||||
reconnect_token,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
if reconnect_token.is_some() {
|
|
||||||
return Err(SessionError::ReconnectSuperseded);
|
|
||||||
}
|
|
||||||
*reconnect_token = Some(token);
|
|
||||||
*generation
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
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,
|
|
||||||
registry: Arc::downgrade(self),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn prepare_attach(&self, permit: &HandshakePermit) -> Result<PreparedAttach, SessionError> {
|
|
||||||
let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
|
||||||
let record = sessions.get(&permit.session_id).ok_or(SessionError::Unauthorized)?;
|
|
||||||
let generation = match &record.status {
|
|
||||||
SessionStatus::Pending { handshake_token, .. }
|
|
||||||
if permit.observed_generation == 0 && *handshake_token == Some(permit.token) =>
|
|
||||||
{
|
|
||||||
1
|
|
||||||
}
|
|
||||||
SessionStatus::Active {
|
|
||||||
generation,
|
|
||||||
reconnect_token,
|
|
||||||
..
|
|
||||||
} if *generation == permit.observed_generation && *reconnect_token == Some(permit.token) => {
|
|
||||||
generation.checked_add(1).ok_or(SessionError::Unavailable)?
|
|
||||||
}
|
|
||||||
_ => return Err(SessionError::ReconnectSuperseded),
|
|
||||||
};
|
|
||||||
Ok(PreparedAttach { generation })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn commit_attach(
|
|
||||||
&self,
|
|
||||||
permit: &HandshakePermit,
|
|
||||||
connection: ConnectionControl,
|
|
||||||
) -> Result<Option<ConnectionControl>, SessionError> {
|
|
||||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
|
||||||
let record = sessions.get_mut(&permit.session_id).ok_or(SessionError::Unauthorized)?;
|
|
||||||
|
|
||||||
match &mut record.status {
|
|
||||||
SessionStatus::Pending { handshake_token, .. }
|
|
||||||
if permit.observed_generation == 0 && *handshake_token == Some(permit.token) =>
|
|
||||||
{
|
|
||||||
record.status = SessionStatus::Active {
|
|
||||||
generation: 1,
|
|
||||||
connection: Some(connection),
|
|
||||||
reconnect_token: None,
|
|
||||||
};
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
SessionStatus::Active {
|
|
||||||
generation,
|
|
||||||
connection: current,
|
|
||||||
reconnect_token,
|
|
||||||
} if *generation == permit.observed_generation && *reconnect_token == Some(permit.token) => {
|
|
||||||
*generation = generation.checked_add(1).ok_or(SessionError::Unavailable)?;
|
|
||||||
*reconnect_token = None;
|
|
||||||
Ok(current.replace(connection))
|
|
||||||
}
|
|
||||||
_ => Err(SessionError::ReconnectSuperseded),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn cancel_handshake(&self, session_id: Uuid, observed_generation: u64, token: Uuid) {
|
|
||||||
let Ok(mut sessions) = self.sessions.lock() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let Some(record) = sessions.get_mut(&session_id) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
match &mut record.status {
|
|
||||||
SessionStatus::Pending { handshake_token, .. } if observed_generation == 0 && *handshake_token == Some(token) => {
|
|
||||||
sessions.remove(&session_id);
|
|
||||||
}
|
|
||||||
SessionStatus::Active {
|
|
||||||
generation,
|
|
||||||
reconnect_token,
|
|
||||||
..
|
|
||||||
} if *generation == observed_generation && *reconnect_token == Some(token) => {
|
|
||||||
*reconnect_token = None;
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn is_current(&self, session_id: Uuid, generation: u64) -> bool {
|
|
||||||
let Ok(sessions) = self.sessions.lock() else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
matches!(
|
|
||||||
sessions.get(&session_id).map(|record| &record.status),
|
|
||||||
Some(SessionStatus::Active { generation: current, .. }) if *current == generation
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
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(SessionRecord {
|
|
||||||
status: SessionStatus::Active {
|
|
||||||
generation: current,
|
|
||||||
connection,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
}) = sessions.get_mut(&session_id)
|
|
||||||
&& *current == generation
|
|
||||||
{
|
|
||||||
connection.take();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn revoke(&self, session_id: Uuid) {
|
|
||||||
let connection = self
|
|
||||||
.sessions
|
|
||||||
.lock()
|
|
||||||
.ok()
|
|
||||||
.and_then(|mut sessions| sessions.remove(&session_id))
|
|
||||||
.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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for HandshakePermit {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if let Some(registry) = self.registry.upgrade() {
|
|
||||||
registry.cancel_handshake(self.session_id, self.observed_generation, self.token);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use tokio::sync::mpsc;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::ws_connection::ConnectionCommand;
|
|
||||||
|
|
||||||
fn control() -> ConnectionControl {
|
|
||||||
let (tx, _rx) = mpsc::channel::<ConnectionCommand>(1);
|
|
||||||
ConnectionControl::new(Uuid::new_v4(), tx).0
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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 first = registry
|
|
||||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(registry.prepare_attach(&first).unwrap().generation, 1);
|
|
||||||
registry.commit_attach(&first, control()).unwrap();
|
|
||||||
|
|
||||||
let candidate_a = registry
|
|
||||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
|
||||||
.unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
registry.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4"),
|
|
||||||
Err(SessionError::ReconnectSuperseded)
|
|
||||||
));
|
|
||||||
assert_eq!(registry.prepare_attach(&candidate_a).unwrap().generation, 2);
|
|
||||||
registry.commit_attach(&candidate_a, control()).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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 first = registry
|
|
||||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
|
||||||
.unwrap();
|
|
||||||
drop(first);
|
|
||||||
assert!(matches!(
|
|
||||||
registry.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4"),
|
|
||||||
Err(SessionError::Unauthorized)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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 first = registry
|
|
||||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
|
||||||
.unwrap();
|
|
||||||
registry.commit_attach(&first, control()).unwrap();
|
|
||||||
|
|
||||||
let reconnect = registry
|
|
||||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
|
||||||
.unwrap();
|
|
||||||
drop(reconnect);
|
|
||||||
assert!(registry.is_current(credential.session_id(), 1));
|
|
||||||
assert!(
|
|
||||||
registry
|
|
||||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
|
||||||
.is_ok()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
use gpapi::service::request::ConnectArgs;
|
|
||||||
use openconnect::{Vpn, VpnBuilder};
|
|
||||||
|
|
||||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result<VpnBuilder> {
|
|
||||||
Ok(Vpn::builder(server, cookie).script_path(args.vpnc_script()))
|
|
||||||
}
|
|
||||||
@@ -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 = "default.rs"]
|
|
||||||
mod platform;
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
|
||||||
mod selection;
|
|
||||||
|
|
||||||
pub(crate) use platform::builder;
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
use gpapi::service::request::ConnectArgs;
|
|
||||||
use openconnect::{Vpn, VpnBuilder};
|
|
||||||
|
|
||||||
use super::selection::{ScriptSource, select};
|
|
||||||
|
|
||||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result<VpnBuilder> {
|
|
||||||
let installed = gpservice::vpnc_script::installed_script()?;
|
|
||||||
let legacy = args.vpnc_script();
|
|
||||||
match select(installed.as_deref(), legacy.as_deref()) {
|
|
||||||
ScriptSource::Installed(path) => {
|
|
||||||
Ok(Vpn::builder(server, cookie).script_path(Some(path.to_string_lossy().into_owned())))
|
|
||||||
}
|
|
||||||
ScriptSource::Legacy(script) => Ok(Vpn::builder(server, cookie).script(Some(script.to_owned()))),
|
|
||||||
ScriptSource::Default => Ok(Vpn::builder(server, cookie).script_path(None)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
use std::path::Path;
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
|
||||||
pub(super) enum ScriptSource<'a> {
|
|
||||||
Installed(&'a Path),
|
|
||||||
Legacy(&'a str),
|
|
||||||
Default,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn select<'a>(installed: Option<&'a Path>, legacy: Option<&'a str>) -> ScriptSource<'a> {
|
|
||||||
if let Some(path) = installed {
|
|
||||||
return ScriptSource::Installed(path);
|
|
||||||
}
|
|
||||||
if let Some(script) = legacy {
|
|
||||||
return ScriptSource::Legacy(script);
|
|
||||||
}
|
|
||||||
ScriptSource::Default
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn installed_script_takes_precedence_over_legacy() {
|
|
||||||
let installed = Path::new("/var/lib/gpclient/scripts/vpnc-script");
|
|
||||||
assert_eq!(
|
|
||||||
select(Some(installed), Some("legacy-command")),
|
|
||||||
ScriptSource::Installed(installed)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn legacy_script_is_used_before_default() {
|
|
||||||
assert_eq!(
|
|
||||||
select(None, Some("legacy-command")),
|
|
||||||
ScriptSource::Legacy("legacy-command")
|
|
||||||
);
|
|
||||||
assert_eq!(select(None, None), ScriptSource::Default);
|
|
||||||
}
|
|
||||||
}
|
|
||||||