mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 14:06:14 -05:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
baa77a774b | ||
|
|
92857fc1ba | ||
|
|
5ff3760bc0 | ||
|
|
c476dfefb0 |
No files matched your search
@@ -1,2 +0,0 @@
|
||||
# Keep source and build scripts consistent on every platform.
|
||||
* text=auto eol=lf
|
||||
@@ -12,9 +12,6 @@ on:
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
build:
|
||||
required: true
|
||||
type: string
|
||||
builder:
|
||||
required: true
|
||||
type: string
|
||||
@@ -88,7 +85,7 @@ jobs:
|
||||
- name: Build gpgui in Docker
|
||||
env:
|
||||
GPGUI_BUILDER: ${{ inputs.builder }}
|
||||
GPGUI_BUILD_VERSION: ${{ inputs.build }}
|
||||
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
run: |
|
||||
|
||||
@@ -12,9 +12,6 @@ on:
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
build:
|
||||
required: true
|
||||
type: string
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
@@ -38,7 +35,7 @@ jobs:
|
||||
env:
|
||||
CARGO_INCREMENTAL: '0'
|
||||
CARGO_BUILD_JOBS: '2'
|
||||
GPGUI_BUILD_VERSION: ${{ inputs.build }}
|
||||
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
||||
GPGUI_GIT_COMMIT: ${{ inputs.gpgui_ref }}
|
||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
|
||||
@@ -1,213 +0,0 @@
|
||||
name: Build Windows package
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
gp_ref:
|
||||
type: string
|
||||
required: true
|
||||
gpgui_ref:
|
||||
type: string
|
||||
required: true
|
||||
channel:
|
||||
type: choice
|
||||
options: [snapshot, stable]
|
||||
default: snapshot
|
||||
build:
|
||||
type: string
|
||||
required: true
|
||||
architecture:
|
||||
type: choice
|
||||
options: [x64, arm64]
|
||||
required: true
|
||||
workflow_call:
|
||||
inputs:
|
||||
gp_ref:
|
||||
type: string
|
||||
required: true
|
||||
gpgui_ref:
|
||||
type: string
|
||||
required: true
|
||||
channel:
|
||||
type: string
|
||||
required: true
|
||||
build:
|
||||
type: string
|
||||
required: true
|
||||
architecture:
|
||||
type: string
|
||||
required: true
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
WINDOWS_UPDATE_PRIVATE_KEY:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ${{ inputs.architecture == 'arm64' && 'windows-11-arm' || 'windows-2022' }}
|
||||
environment: windows-signing
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
BUILD_ARCHITECTURE: ${{ inputs.architecture }}
|
||||
CARGO_INCREMENTAL: '0'
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/target-windows
|
||||
CARGO_BUILD_JOBS: '2'
|
||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
GPGUI_BUILD_VERSION: ${{ inputs.channel == 'snapshot' && inputs.build || '' }}
|
||||
GPGUI_WINDOWS_UPDATE_PUBLIC_KEY: ${{ vars.WINDOWS_UPDATE_PUBLIC_KEY }}
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ vars.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ vars.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_SIGNING_PROFILE: ${{ vars.AZURE_SIGNING_PROFILE }}
|
||||
WINDOWS_SIGNING_PUBLISHER: ${{ vars.WINDOWS_SIGNING_PUBLISHER }}
|
||||
steps:
|
||||
- name: Select native build tools
|
||||
id: native
|
||||
shell: pwsh
|
||||
run: |
|
||||
if ($env:BUILD_ARCHITECTURE -eq 'arm64') {
|
||||
'msystem=CLANGARM64' >> $env:GITHUB_OUTPUT
|
||||
'subsystem=clangarm64' >> $env:GITHUB_OUTPUT
|
||||
'packages=mingw-w64-clang-aarch64-clang mingw-w64-clang-aarch64-pkgconf mingw-w64-clang-aarch64-gnutls mingw-w64-clang-aarch64-libxml2 mingw-w64-clang-aarch64-lz4' >> $env:GITHUB_OUTPUT
|
||||
} elseif ($env:BUILD_ARCHITECTURE -eq 'x64') {
|
||||
'msystem=UCRT64' >> $env:GITHUB_OUTPUT
|
||||
'subsystem=ucrt64' >> $env:GITHUB_OUTPUT
|
||||
'packages=mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-pkgconf mingw-w64-ucrt-x86_64-gnutls mingw-w64-ucrt-x86_64-libxml2 mingw-w64-ucrt-x86_64-lz4' >> $env:GITHUB_OUTPUT
|
||||
} else { throw 'Unsupported Windows architecture.' }
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
path: .ci
|
||||
persist-credentials: false
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ inputs.gp_ref }}
|
||||
path: source/gp
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
- uses: ./.ci/.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: source/gpgui
|
||||
- uses: dtolnay/[email protected]
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- uses: msys2/setup-msys2@v2
|
||||
id: msys2
|
||||
with:
|
||||
msystem: ${{ steps.native.outputs.msystem }}
|
||||
update: true
|
||||
install: >-
|
||||
base-devel autoconf automake libtool gettext git
|
||||
${{ steps.native.outputs.packages }}
|
||||
- name: Prepare pinned installer and driver inputs
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (!$env:GPGUI_WINDOWS_UPDATE_PUBLIC_KEY -or !$env:GPGUI_LICENSE_SIGNING_KEYS) { throw 'Configure the Windows update and licensing public keys.' }
|
||||
$tools = Join-Path $env:RUNNER_TEMP 'windows-tools'
|
||||
New-Item -ItemType Directory -Force $tools | Out-Null
|
||||
choco install nsis --version=3.12.0 --yes --no-progress
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Installing NSIS 3.12 failed.' }
|
||||
$wintun = Join-Path $tools 'wintun.zip'
|
||||
Invoke-WebRequest 'https://www.wintun.net/builds/wintun-0.14.1.zip' -OutFile $wintun
|
||||
if ((Get-FileHash $wintun).Hash -ne '07C256185D6EE3652E09FA55C0B673E2624B565E02C4B9091C79CA7D2F24EF51') { throw 'Wintun checksum mismatch.' }
|
||||
Expand-Archive $wintun $tools
|
||||
Remove-Item $wintun
|
||||
"WINDOWS_BUILD_TOOLS=$tools" >> $env:GITHUB_ENV
|
||||
- name: Build OpenConnect and test native packet transport
|
||||
shell: pwsh
|
||||
env:
|
||||
MSYS_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$prefix = Join-Path $env:RUNNER_TEMP 'native-windows'
|
||||
& ./source/gp/scripts/build-openconnect-windows.ps1 -MsysRoot $env:MSYS_ROOT -MsysSubsystem ${{ steps.native.outputs.subsystem }} -Prefix $prefix
|
||||
& ./source/gp/scripts/test-openconnect-windows.ps1 -MsysRoot $env:MSYS_ROOT -MsysSubsystem ${{ steps.native.outputs.subsystem }} -Prefix $prefix
|
||||
"OPENCONNECT_WINDOWS_PREFIX=$prefix" >> $env:GITHUB_ENV
|
||||
- name: Build the matching Windows runtime
|
||||
shell: pwsh
|
||||
env:
|
||||
MSYS_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$log = Join-Path $env:RUNNER_TEMP 'windows-package.log'
|
||||
# Compiler diagnostics may contain private GUI source. Keep them on the runner.
|
||||
try {
|
||||
& ./source/gpgui/scripts/build-windows.ps1 -Profile Release -BuildOnly `
|
||||
-NativePrefix $env:OPENCONNECT_WINDOWS_PREFIX -MsysRoot $env:MSYS_ROOT -MsysSubsystem ${{ steps.native.outputs.subsystem }} `
|
||||
-WintunDirectory (Join-Path $env:WINDOWS_BUILD_TOOLS 'wintun') `
|
||||
-MakeNsis (Join-Path ${env:ProgramFiles(x86)} 'NSIS/makensis.exe') `
|
||||
-OutputDirectory "$env:GITHUB_WORKSPACE/artifacts" *> $log
|
||||
} catch {
|
||||
python ./.ci/scripts/private-ci-diagnostics.py compile $log
|
||||
throw 'Windows compilation failed; private diagnostics remain on the runner.'
|
||||
}
|
||||
Write-Host 'Windows compilation passed.'
|
||||
- name: Install Microsoft Artifact Signing tooling
|
||||
shell: pwsh
|
||||
run: Install-Module ArtifactSigning -RequiredVersion 0.1.20 -Repository PSGallery -Force -Scope CurrentUser
|
||||
- name: Log in to Azure with GitHub OIDC
|
||||
uses: azure/login@v3
|
||||
with:
|
||||
client-id: ${{ vars.AZURE_SIGNING_CLIENT_ID }}
|
||||
tenant-id: ${{ vars.AZURE_TENANT_ID }}
|
||||
subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
|
||||
- name: Sign and package the Windows runtime
|
||||
shell: pwsh
|
||||
env:
|
||||
MSYS_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
run: |
|
||||
& ./source/gpgui/scripts/build-windows.ps1 -Profile Release -SkipBuild -Sign `
|
||||
-NativePrefix $env:OPENCONNECT_WINDOWS_PREFIX -MsysRoot $env:MSYS_ROOT -MsysSubsystem ${{ steps.native.outputs.subsystem }} `
|
||||
-WintunDirectory (Join-Path $env:WINDOWS_BUILD_TOOLS 'wintun') `
|
||||
-MakeNsis (Join-Path ${env:ProgramFiles(x86)} 'NSIS/makensis.exe') `
|
||||
-OutputDirectory "$env:GITHUB_WORKSPACE/artifacts"
|
||||
- name: Sign and verify update payload
|
||||
id: sign
|
||||
shell: pwsh
|
||||
env:
|
||||
UPDATE_PRIVATE_KEY: ${{ secrets.WINDOWS_UPDATE_PRIVATE_KEY }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$key = Join-Path $env:RUNNER_TEMP 'windows-update.key'
|
||||
try {
|
||||
[IO.File]::WriteAllText($key, $env:UPDATE_PRIVATE_KEY.Trim())
|
||||
. ./source/gpgui/scripts/windows-updates/Get-WinSparkle.ps1
|
||||
$tools = Get-WinSparkleTools "$env:GITHUB_WORKSPACE/artifacts/tools" -Architecture $env:BUILD_ARCHITECTURE
|
||||
$installer = @(Get-ChildItem artifacts -Filter '*-setup.exe')
|
||||
if ($installer.Count -ne 1) { throw 'Expected exactly one Windows installer.' }
|
||||
$signature = (& $tools.Tool sign -f $key $installer[0].FullName | Out-String).Trim()
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Windows update signing failed.' }
|
||||
& $tools.Tool verify -p $env:GPGUI_WINDOWS_UPDATE_PUBLIC_KEY -s $signature $installer[0].FullName
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Windows update signature verification failed.' }
|
||||
$signature | Set-Content ($installer[0].FullName + '.sig') -Encoding ascii
|
||||
} finally {
|
||||
Remove-Item $key -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item artifacts/tools -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
- name: Test native installer and uninstaller
|
||||
shell: pwsh
|
||||
run: |
|
||||
$installer = @(Get-ChildItem artifacts -Filter '*-setup.exe')
|
||||
if ($installer.Count -ne 1) { throw 'Expected exactly one Windows installer.' }
|
||||
& ./source/gp/scripts/test-windows-installer.ps1 -Installer $installer[0].FullName -Architecture $env:BUILD_ARCHITECTURE -Build $env:GPGUI_BUILD_VERSION
|
||||
- uses: actions/upload-artifact@v7
|
||||
if: ${{ !cancelled() && steps.sign.outcome == 'success' }}
|
||||
with:
|
||||
name: artifact-gpgui-windows-${{ inputs.architecture }}
|
||||
path: |
|
||||
artifacts/*.exe
|
||||
artifacts/*.exe.sig
|
||||
artifacts/*.exe.sha256
|
||||
overwrite: true
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
+11
-101
@@ -42,11 +42,6 @@ on:
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
build_windows:
|
||||
description: 'Build Windows x64 and ARM64 NSH installers'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
push:
|
||||
paths-ignore:
|
||||
- LICENSE
|
||||
@@ -69,10 +64,8 @@ jobs:
|
||||
actions: read
|
||||
contents: read
|
||||
outputs:
|
||||
gp_sha: ${{ steps.identity.outputs.gp_sha }}
|
||||
gpgui_sha: ${{ steps.identity.outputs.gpgui_sha }}
|
||||
version: ${{ steps.identity.outputs.version }}
|
||||
build_version: ${{ steps.identity.outputs.build_version }}
|
||||
gp_sha: ${{ steps.sources.outputs.gp_sha }}
|
||||
gpgui_sha: ${{ steps.sources.outputs.gpgui_sha }}
|
||||
steps:
|
||||
- name: Validate stable refs
|
||||
env:
|
||||
@@ -121,12 +114,11 @@ jobs:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
||||
path: selected/gpgui
|
||||
- name: Record selected sources and versions
|
||||
id: identity
|
||||
- name: Record selected sources
|
||||
id: sources
|
||||
run: |
|
||||
python3 scripts/record-build-sources.py selected-sources/sources.json \
|
||||
--gp selected/gp --gpgui selected/gpgui \
|
||||
--build-version "${{ github.run_number }}.${{ github.run_attempt }}"
|
||||
--gp selected/gp --gpgui selected/gpgui
|
||||
- name: Retain selected sources for retries
|
||||
if: steps.restored.outputs.cached != 'true'
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -163,7 +155,7 @@ jobs:
|
||||
# Tauri generates schemas in the source tree. Keep the host checkout read-only.
|
||||
cp -R /workspace /tmp/gp-test-workspace
|
||||
cd /tmp/gp-test-workspace
|
||||
cargo test --workspace --locked --features gpapi/openssl-tests
|
||||
cargo test --workspace --locked
|
||||
|
||||
# Exercise only the paths that require an actual root process.
|
||||
sudo -E env PATH="$PATH" PKEXEC_UID="$(id -u)" cargo test --locked -p gpapi \
|
||||
@@ -445,7 +437,6 @@ jobs:
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
builder: gpgui-builder-tauri2
|
||||
verify_desktop_assets: true
|
||||
secrets:
|
||||
@@ -459,7 +450,6 @@ jobs:
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
builder: gpgui-alpine-builder-tauri2
|
||||
artifact_suffix: -musl
|
||||
secrets:
|
||||
@@ -472,31 +462,9 @@ jobs:
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
secrets:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
|
||||
build-windows:
|
||||
needs: validate-inputs
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
if: ${{ (github.event_name == 'workflow_dispatch' && inputs.build_windows) || (startsWith(github.ref, 'refs/tags/') && vars.BUILD_WINDOWS_ON_TAG == 'true') }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
architecture: [x64, arm64]
|
||||
uses: ./.github/workflows/build-windows.yaml
|
||||
with:
|
||||
architecture: ${{ matrix.architecture }}
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
secrets:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
WINDOWS_UPDATE_PRIVATE_KEY: ${{ secrets.WINDOWS_UPDATE_PRIVATE_KEY }}
|
||||
|
||||
nix-source:
|
||||
needs: [validate-inputs, build-gpgui-glibc]
|
||||
strategy:
|
||||
@@ -691,7 +659,7 @@ jobs:
|
||||
FEED_URL: ${{ vars.SPARKLE_FEED_URL }}
|
||||
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
|
||||
RELEASE_TAG: ${{ (github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name) }}
|
||||
BUILD_VERSION: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
BUILD_VERSION: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -859,7 +827,7 @@ jobs:
|
||||
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
|
||||
RELEASE_TAG: ${{ (github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name) }}
|
||||
REQUEST_ID: ${{ format('{0}.{1}.macos', github.run_id, github.run_attempt) }}
|
||||
BUILD_VERSION: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
BUILD_VERSION: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
|
||||
WORKFLOW_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -1058,6 +1026,7 @@ jobs:
|
||||
nettle \
|
||||
gmp \
|
||||
gnome-keyring \
|
||||
libayatana-appindicator \
|
||||
polkit \
|
||||
webkit2-gtk_41
|
||||
pkgconf --exists libxml-2.0 liblz4 gnutls p11-kit-1 hogweed nettle gmp
|
||||
@@ -1066,7 +1035,7 @@ jobs:
|
||||
exec 3>&1
|
||||
(
|
||||
set -eu
|
||||
export GPGUI_BUILD_VERSION=${{ needs.validate-inputs.outputs.build_version }}
|
||||
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
|
||||
@@ -1150,7 +1119,7 @@ jobs:
|
||||
set -eu
|
||||
export AUTOCONF_VERSION=2.72
|
||||
export AUTOMAKE_VERSION=1.17
|
||||
export GPGUI_BUILD_VERSION=${{ needs.validate-inputs.outputs.build_version }}
|
||||
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
|
||||
@@ -1222,7 +1191,6 @@ jobs:
|
||||
- build-gpgui-glibc
|
||||
- build-gpgui-musl
|
||||
- build-gpgui-nsh
|
||||
- build-windows
|
||||
- setup-bsd-matrix
|
||||
- build-gpgui-frontend
|
||||
- build-bsd
|
||||
@@ -1233,7 +1201,6 @@ jobs:
|
||||
NEEDS_JSON: ${{ toJson(needs) }}
|
||||
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
|
||||
IS_STABLE: ${{ (startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
|
||||
BUILD_WINDOWS: ${{ (github.event_name == 'workflow_dispatch' && inputs.build_windows) || (startsWith(github.ref, 'refs/tags/') && vars.BUILD_WINDOWS_ON_TAG == 'true') }}
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
@@ -1253,8 +1220,6 @@ jobs:
|
||||
continue
|
||||
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
|
||||
continue
|
||||
elif name == "build-windows" and result == "skipped" and os.environ["BUILD_WINDOWS"] != "true":
|
||||
continue
|
||||
elif result == "skipped":
|
||||
failed.append(f"{name}: {result}")
|
||||
|
||||
@@ -1321,61 +1286,6 @@ jobs:
|
||||
run: |
|
||||
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
|
||||
|
||||
publish-macos-assets:
|
||||
needs: [build-macos, gh-release]
|
||||
if: >-
|
||||
${{ !cancelled() &&
|
||||
needs.build-macos.result == 'success' && needs.gh-release.result == 'success' }}
|
||||
permissions:
|
||||
actions: read
|
||||
contents: write
|
||||
uses: ./.github/workflows/publish-macos-assets.yaml
|
||||
with:
|
||||
build_run_id: ${{ github.run_id }}
|
||||
release_tag: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
expected_gui: ${{ github.event_name == 'workflow_dispatch' && inputs.macos_gui || 'nsh' }}
|
||||
secrets: inherit
|
||||
|
||||
publish-windows-snapshot-feed:
|
||||
needs: [validate-inputs, gh-release, publish-macos-assets]
|
||||
if: >-
|
||||
${{ !cancelled() && github.event_name == 'workflow_dispatch' &&
|
||||
inputs.channel == 'snapshot' && !inputs.build_only && inputs.build_windows &&
|
||||
needs.gh-release.result == 'success' &&
|
||||
(!inputs.build_macos || needs.publish-macos-assets.result == 'success') }}
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/publish-windows-update-feed.yaml
|
||||
with:
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
release_tag: snapshot
|
||||
version: ${{ needs.validate-inputs.outputs.version }}
|
||||
channel: snapshot
|
||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
highlights: Development snapshot.
|
||||
secrets: inherit
|
||||
|
||||
publish-macos-unix-snapshot-feeds:
|
||||
needs: [validate-inputs, gh-release, publish-macos-assets, publish-windows-snapshot-feed]
|
||||
if: >-
|
||||
${{ !cancelled() && github.event_name == 'workflow_dispatch' &&
|
||||
inputs.channel == 'snapshot' && !inputs.build_only && inputs.build_macos &&
|
||||
needs.gh-release.result == 'success' && needs.publish-macos-assets.result == 'success' &&
|
||||
(!inputs.build_windows || needs.publish-windows-snapshot-feed.result == 'success') }}
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/publish-update-feeds.yaml
|
||||
with:
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
channel: snapshot
|
||||
release_tag: snapshot
|
||||
archive_name: ${{ format('GPConnect_{0}-snapshot.{1}_arm64.zip', needs.validate-inputs.outputs.version, needs.validate-inputs.outputs.build_version) }}
|
||||
expected_gui: ${{ inputs.macos_gui }}
|
||||
unix_platforms: ${{ (inputs.build_bsd || inputs.build_bsd_arm64) && 'linux,freebsd,openbsd' || 'linux' }}
|
||||
highlights: Development snapshot.
|
||||
secrets: inherit
|
||||
|
||||
publish-docker-image:
|
||||
needs:
|
||||
- validate-inputs
|
||||
|
||||
@@ -54,6 +54,7 @@ jobs:
|
||||
gettext \
|
||||
gmp \
|
||||
gnutls \
|
||||
libappindicator-gtk3 \
|
||||
libp11-kit \
|
||||
libsecret \
|
||||
libtool \
|
||||
|
||||
@@ -1,21 +1,6 @@
|
||||
name: Publish macOS assets
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
build_run_id:
|
||||
required: true
|
||||
type: string
|
||||
release_tag:
|
||||
required: true
|
||||
type: string
|
||||
expected_gui:
|
||||
required: false
|
||||
default: nsh
|
||||
type: string
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: false
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build_run_id:
|
||||
|
||||
@@ -34,10 +34,6 @@ on:
|
||||
highlights:
|
||||
required: false
|
||||
type: string
|
||||
unix_snapshot_build:
|
||||
description: Verified Unix snapshot build when it differs from the macOS retry
|
||||
required: false
|
||||
type: string
|
||||
unix_platforms:
|
||||
required: false
|
||||
default: linux,freebsd,openbsd
|
||||
@@ -79,10 +75,6 @@ on:
|
||||
description: Stable release highlights, one per line
|
||||
required: false
|
||||
type: string
|
||||
unix_snapshot_build:
|
||||
description: Verified Unix snapshot build; omit when it matches the macOS build
|
||||
required: false
|
||||
type: string
|
||||
unix_platforms:
|
||||
description: Comma-separated Unix platforms with published assets (linux,freebsd,openbsd)
|
||||
required: true
|
||||
@@ -95,8 +87,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
# Feed verification runs host tools, so it can use Intel runner capacity.
|
||||
runs-on: macos-26-intel
|
||||
runs-on: ${{ vars.MACOS_RUNNER || 'macos-15' }}
|
||||
environment: macos-release
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -112,7 +103,6 @@ jobs:
|
||||
SPARKLE_VERSION: 2.9.2
|
||||
UPDATE_HIGHLIGHTS: ${{ inputs.highlights }}
|
||||
UNIX_PLATFORMS: ${{ inputs.unix_platforms }}
|
||||
UNIX_SNAPSHOT_BUILD: ${{ inputs.unix_snapshot_build }}
|
||||
SPARKLE_ARCHIVE_SHA256: b83e37436774556ed055e0244b297ef2c790e0737393bf65bf495fcbba6eed65
|
||||
steps:
|
||||
- name: Validate inputs
|
||||
@@ -135,12 +125,6 @@ jobs:
|
||||
echo "unix_platforms must list published Unix targets separated by commas" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -n "$UNIX_SNAPSHOT_BUILD" ]]; then
|
||||
if [[ "$CHANNEL" != "snapshot" || ! "$UNIX_SNAPSHOT_BUILD" =~ ^(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*)){0,2}$ ]]; then
|
||||
echo "unix_snapshot_build requires a snapshot channel and one to three numeric components" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
if [[ "$CHANNEL" == "snapshot" && "$RELEASE_TAG" != "snapshot" ]]; then
|
||||
echo "The snapshot channel must publish to the snapshot release" >&2
|
||||
exit 1
|
||||
@@ -359,7 +343,6 @@ jobs:
|
||||
echo "short_version=$short_version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Prepare Unix update manifest
|
||||
id: unix_manifest
|
||||
env:
|
||||
RELEASED_AT: ${{ steps.release.outputs.released_at }}
|
||||
run: |
|
||||
@@ -400,8 +383,7 @@ jobs:
|
||||
else
|
||||
printf 'Development snapshot after %s.\n' \
|
||||
"${{ steps.bundle.outputs.short_version }}" > "$highlights"
|
||||
unix_build="${UNIX_SNAPSHOT_BUILD:-${{ steps.bundle.outputs.version }}}"
|
||||
generate_args+=(--build "$unix_build")
|
||||
generate_args+=(--build "${{ steps.bundle.outputs.version }}")
|
||||
released_at="$(date -u +%F)"
|
||||
fi
|
||||
|
||||
@@ -410,9 +392,6 @@ jobs:
|
||||
--released-at "$released_at" \
|
||||
--highlights-file "$highlights" \
|
||||
--output "$manifest"
|
||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
||||
echo "build=$unix_build" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Fetch current appcast
|
||||
id: current-appcast
|
||||
@@ -548,13 +527,6 @@ jobs:
|
||||
--channel "$CHANNEL" \
|
||||
--archive-url "https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/$ARCHIVE_NAME"
|
||||
|
||||
- name: Preserve other platform feeds
|
||||
run: |
|
||||
python3 scripts/preserve-update-feeds.py \
|
||||
--base-url "${FEED_URL%/appcast.xml}" \
|
||||
--directory gpgui/apps/update-feed-worker/public \
|
||||
--exclude appcast.xml --exclude latest.json
|
||||
|
||||
- name: Deploy update feed worker
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
@@ -608,7 +580,7 @@ jobs:
|
||||
--version "${{ steps.bundle.outputs.short_version }}"
|
||||
)
|
||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
||||
expected+=(--build "${{ steps.unix_manifest.outputs.build }}")
|
||||
expected+=(--build "${{ steps.bundle.outputs.version }}")
|
||||
fi
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if curl --fail --location --silent --show-error \
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
name: Publish Windows update feed
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
gpgui_ref:
|
||||
required: true
|
||||
type: string
|
||||
release_tag:
|
||||
required: true
|
||||
type: string
|
||||
version:
|
||||
required: true
|
||||
type: string
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
build:
|
||||
required: true
|
||||
type: string
|
||||
highlights:
|
||||
required: true
|
||||
type: string
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
CLOUDFLARE_ACCOUNT_ID:
|
||||
required: false
|
||||
CLOUDFLARE_API_TOKEN:
|
||||
required: false
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
gpgui_ref:
|
||||
description: gpgui ref containing the update Worker and pinned WinSparkle tools
|
||||
required: true
|
||||
default: main
|
||||
type: string
|
||||
release_tag:
|
||||
description: GitHub release containing both tested native installers and signatures
|
||||
required: true
|
||||
type: string
|
||||
version:
|
||||
description: Base product version (x.y.z)
|
||||
required: true
|
||||
type: string
|
||||
channel:
|
||||
description: Update channel
|
||||
required: true
|
||||
type: choice
|
||||
options: [stable, snapshot]
|
||||
build:
|
||||
description: Numeric snapshot build; empty for stable
|
||||
type: string
|
||||
highlights:
|
||||
description: Release highlights, one per line
|
||||
required: true
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
group: update-feeds
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: windows-latest
|
||||
environment: macos-release
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
REPOSITORY: yuezk/GlobalProtect-openconnect
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
PRODUCT_VERSION: ${{ inputs.version }}
|
||||
UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
BUILD_VERSION: ${{ inputs.build }}
|
||||
UPDATE_HIGHLIGHTS: ${{ inputs.highlights }}
|
||||
WINDOWS_UPDATE_PUBLIC_KEY: ${{ vars.WINDOWS_UPDATE_PUBLIC_KEY }}
|
||||
WINDOWS_SIGNING_PUBLISHER: ${{ vars.WINDOWS_SIGNING_PUBLISHER }}
|
||||
UPDATES_WORKER_NAME: ${{ vars.UPDATES_WORKER_NAME || 'gp-updates' }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Checkout update Worker and build helpers
|
||||
uses: ./.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: gpgui
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: 9.15.1
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
- name: Verify both tested native installers
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($env:PRODUCT_VERSION -notmatch '^\d+\.\d+\.\d+$') { throw 'Invalid product version.' }
|
||||
if ($env:UPDATE_CHANNEL -eq 'stable') {
|
||||
if ($env:RELEASE_TAG -ne "v$env:PRODUCT_VERSION" -or $env:BUILD_VERSION) { throw 'Stable release identity does not match.' }
|
||||
} elseif ($env:RELEASE_TAG -ne 'snapshot' -or $env:BUILD_VERSION -notmatch '^\d+(\.\d+){0,2}$') { throw 'Snapshot release identity does not match.' }
|
||||
$displayVersion = $env:PRODUCT_VERSION
|
||||
if ($env:UPDATE_CHANNEL -eq 'snapshot') { $displayVersion += "-snapshot.$env:BUILD_VERSION" }
|
||||
if (!$env:WINDOWS_UPDATE_PUBLIC_KEY) { throw 'Configure the Windows public update key before promotion.' }
|
||||
$downloads = Join-Path $env:RUNNER_TEMP 'windows-update'
|
||||
New-Item -ItemType Directory -Force $downloads | Out-Null
|
||||
. ./gpgui/scripts/windows-updates/Get-WinSparkle.ps1
|
||||
$tools = Get-WinSparkleTools (Join-Path $env:RUNNER_TEMP 'signing-tools')
|
||||
foreach ($architecture in @('x64','arm64')) {
|
||||
$name = "GPConnect_${displayVersion}_windows-$architecture-setup.exe"
|
||||
foreach ($asset in @($name, "$name.sig", "$name.sha256")) {
|
||||
gh release download $env:RELEASE_TAG --repo $env:REPOSITORY --pattern $asset --dir $downloads
|
||||
if ($LASTEXITCODE -ne 0) { throw "Missing release asset: $asset" }
|
||||
}
|
||||
$installer = Join-Path $downloads $name
|
||||
$sum = (Get-Content "$installer.sha256" -Raw).Trim()
|
||||
if ($sum -notmatch '^([a-fA-F0-9]{64}) (.+)$' -or $Matches[2] -ne $name) { throw 'Invalid installer checksum file.' }
|
||||
if ((Get-FileHash $installer).Hash -ne $Matches[1]) { throw 'Installer checksum mismatch.' }
|
||||
if ($env:WINDOWS_SIGNING_PUBLISHER) {
|
||||
$authenticode = Get-AuthenticodeSignature $installer
|
||||
if ($authenticode.Status -ne 'Valid' -or $authenticode.SignerCertificate.GetNameInfo([Security.Cryptography.X509Certificates.X509NameType]::SimpleName, $false) -ne $env:WINDOWS_SIGNING_PUBLISHER) { throw 'Installer publisher signature is invalid.' }
|
||||
}
|
||||
if ([Diagnostics.FileVersionInfo]::GetVersionInfo($installer).ProductVersion -ne $displayVersion) { throw 'Installer product version/build mismatch.' }
|
||||
$signature = (Get-Content "$installer.sig" -Raw).Trim()
|
||||
& $tools.Tool verify -p $env:WINDOWS_UPDATE_PUBLIC_KEY -s $signature $installer
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Installer update signature is invalid.' }
|
||||
}
|
||||
"WINDOWS_DISPLAY_VERSION=$displayVersion" >> $env:GITHUB_ENV
|
||||
- name: Preserve other feeds and generate Windows metadata
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$public = 'gpgui/apps/update-feed-worker/public'
|
||||
python scripts/preserve-update-feeds.py --base-url https://updates.gpgui.com --directory $public
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Could not preserve published feeds.' }
|
||||
$notes = Join-Path $env:RUNNER_TEMP 'windows-highlights.txt'
|
||||
$env:UPDATE_HIGHLIGHTS | Set-Content $notes -Encoding utf8NoBOM
|
||||
$output = Join-Path $public 'windows'
|
||||
$previous = Join-Path $output 'latest.json'
|
||||
$arguments = @('scripts/windows-update-feed.py', '--version', $env:PRODUCT_VERSION,
|
||||
'--channel', $env:UPDATE_CHANNEL, '--released-at', [DateTime]::UtcNow.ToString('yyyy-MM-dd'),
|
||||
'--highlights-file', $notes, '--output', $output)
|
||||
foreach ($architecture in @('x64','arm64')) {
|
||||
$name = "GPConnect_$($env:WINDOWS_DISPLAY_VERSION)_windows-$architecture-setup.exe"
|
||||
$installer = Join-Path (Join-Path $env:RUNNER_TEMP 'windows-update') $name
|
||||
$arguments += @('--payload', $architecture, $installer,
|
||||
"https://github.com/$env:REPOSITORY/releases/download/$env:RELEASE_TAG/$name", "$installer.sig")
|
||||
}
|
||||
if (Test-Path $previous) { $arguments += @('--input', $previous) }
|
||||
if ($env:BUILD_VERSION) { $arguments += @('--build', $env:BUILD_VERSION) }
|
||||
python @arguments
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Invalid Windows metadata.' }
|
||||
- name: Deploy complete feed set
|
||||
shell: pwsh
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
pnpm --dir gpgui/apps/update-feed-worker install --frozen-lockfile --ignore-scripts
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Worker dependency installation failed.' }
|
||||
pnpm --dir gpgui/apps/update-feed-worker exec wrangler deploy --config wrangler.jsonc --name $env:UPDATES_WORKER_NAME
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Feed deployment failed.' }
|
||||
- name: Verify published Windows metadata
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$windows = 'gpgui/apps/update-feed-worker/public/windows'
|
||||
$feeds = @('latest.json', 'stable/appcast.xml', 'snapshot/appcast.xml') | Where-Object { Test-Path (Join-Path $windows $_) }
|
||||
foreach ($relative in $feeds) {
|
||||
$expected = [IO.File]::ReadAllBytes((Join-Path 'gpgui/apps/update-feed-worker/public/windows' $relative))
|
||||
$downloaded = Join-Path $env:RUNNER_TEMP ('published-' + ($relative -replace '/', '-'))
|
||||
$matched = $false
|
||||
foreach ($attempt in 1..10) {
|
||||
try {
|
||||
Invoke-WebRequest "https://updates.gpgui.com/windows/$relative" -UserAgent 'GPConnectReleasePublisher/1.0' -OutFile $downloaded
|
||||
$actual = [IO.File]::ReadAllBytes($downloaded)
|
||||
$matched = [Convert]::ToBase64String($expected) -eq [Convert]::ToBase64String($actual)
|
||||
} catch {
|
||||
Write-Host "Waiting for published feed: $relative ($attempt/10)"
|
||||
}
|
||||
if ($matched) { break }
|
||||
if ($attempt -lt 10) { Start-Sleep -Seconds 3 }
|
||||
}
|
||||
if (!$matched) { throw "Published feed does not match: $relative" }
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
name: Verify public Windows release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: Published snapshot or stable release tag
|
||||
required: true
|
||||
type: string
|
||||
version:
|
||||
description: Base product version
|
||||
required: true
|
||||
type: string
|
||||
build:
|
||||
description: Numeric snapshot build; empty for stable
|
||||
type: string
|
||||
gpgui_ref:
|
||||
description: Matching GUI source ref containing the pinned update tools
|
||||
required: true
|
||||
default: release/next
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
architecture: [x64, arm64]
|
||||
runs-on: ${{ matrix.architecture == 'arm64' && 'windows-11-arm' || 'windows-2022' }}
|
||||
timeout-minutes: 20
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
PRODUCT_VERSION: ${{ inputs.version }}
|
||||
BUILD_VERSION: ${{ inputs.build }}
|
||||
ARCHITECTURE: ${{ matrix.architecture }}
|
||||
WINDOWS_UPDATE_PUBLIC_KEY: ${{ vars.WINDOWS_UPDATE_PUBLIC_KEY }}
|
||||
WINDOWS_SIGNING_PUBLISHER: ${{ vars.WINDOWS_SIGNING_PUBLISHER }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ inputs.release_tag == 'snapshot' && 'release/next' || inputs.release_tag }}
|
||||
persist-credentials: false
|
||||
- uses: ./.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: gpgui
|
||||
- name: Download, verify, install and uninstall the public installer
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($env:PRODUCT_VERSION -notmatch '^\d+\.\d+\.\d+$') { throw 'Invalid product version.' }
|
||||
if (!$env:WINDOWS_UPDATE_PUBLIC_KEY -or !$env:WINDOWS_SIGNING_PUBLISHER) { throw 'Configure the update key and signing publisher.' }
|
||||
$displayVersion = $env:PRODUCT_VERSION
|
||||
if ($env:RELEASE_TAG -eq 'snapshot') {
|
||||
if ($env:BUILD_VERSION -notmatch '^\d+(\.\d+){0,2}$') { throw 'Invalid snapshot build.' }
|
||||
$displayVersion += "-snapshot.$env:BUILD_VERSION"
|
||||
} elseif ($env:RELEASE_TAG -ne "v$env:PRODUCT_VERSION" -or $env:BUILD_VERSION) { throw 'Stable release identity does not match.' }
|
||||
$name = "GPConnect_${displayVersion}_windows-$env:ARCHITECTURE-setup.exe"
|
||||
$downloads = Join-Path $env:RUNNER_TEMP 'public-windows-release'
|
||||
New-Item -ItemType Directory $downloads | Out-Null
|
||||
foreach ($asset in @($name, "$name.sha256", "$name.sig")) {
|
||||
gh release download $env:RELEASE_TAG --repo $env:GITHUB_REPOSITORY --pattern $asset --dir $downloads
|
||||
if ($LASTEXITCODE -ne 0) { throw "Could not download $asset" }
|
||||
}
|
||||
$installer = Join-Path $downloads $name
|
||||
$sum = (Get-Content "$installer.sha256" -Raw).Trim()
|
||||
if ($sum -notmatch '^([a-fA-F0-9]{64}) (.+)$' -or $Matches[2] -ne $name) { throw 'Invalid checksum file.' }
|
||||
$hash = (Get-FileHash $installer).Hash
|
||||
if ($hash -ne $Matches[1]) { throw 'Installer checksum mismatch.' }
|
||||
if ([Diagnostics.FileVersionInfo]::GetVersionInfo($installer).ProductVersion -ne $displayVersion) { throw 'Installer version mismatch.' }
|
||||
& ./scripts/test-windows-signature.ps1 -Files $installer -Publisher $env:WINDOWS_SIGNING_PUBLISHER
|
||||
. ./gpgui/scripts/windows-updates/Get-WinSparkle.ps1
|
||||
$tools = Get-WinSparkleTools (Join-Path $env:RUNNER_TEMP 'winsparkle-tools') -Architecture $env:ARCHITECTURE
|
||||
$signature = (Get-Content "$installer.sig" -Raw).Trim()
|
||||
& $tools.Tool verify -p $env:WINDOWS_UPDATE_PUBLIC_KEY -s $signature $installer
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Installer update signature is invalid.' }
|
||||
& ./scripts/test-windows-installer.ps1 -Installer $installer -Architecture $env:ARCHITECTURE -Build $env:BUILD_VERSION
|
||||
@{ release = $env:RELEASE_TAG; version = $displayVersion; architecture = $env:ARCHITECTURE;
|
||||
sha256 = $hash.ToLowerInvariant(); publisher = $env:WINDOWS_SIGNING_PUBLISHER;
|
||||
authenticode = 'Valid'; timestamped = $true; update_signature = 'Valid';
|
||||
installed_signatures = 'Valid'; install_uninstall = 'Passed'
|
||||
} | ConvertTo-Json | Set-Content verification.json -Encoding utf8
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: windows-release-verification-${{ matrix.architecture }}
|
||||
path: verification.json
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
Generated
+23
-96
@@ -292,13 +292,11 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "auth"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"block2",
|
||||
"browser-launcher",
|
||||
"common",
|
||||
"dunce",
|
||||
"gpapi",
|
||||
"gtk",
|
||||
"html-escape",
|
||||
@@ -309,7 +307,6 @@ dependencies = [
|
||||
"objc2-security",
|
||||
"objc2-web-kit",
|
||||
"regex",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"tempfile",
|
||||
"tiny_http",
|
||||
@@ -319,10 +316,6 @@ dependencies = [
|
||||
"uuid",
|
||||
"uzers",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows",
|
||||
"windows-sys 0.61.2",
|
||||
"winreg 0.55.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -554,14 +547,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "browser-launcher"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"log",
|
||||
"open",
|
||||
"webbrowser",
|
||||
"which",
|
||||
"winreg 0.55.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -919,7 +911,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "common"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
@@ -1559,7 +1551,7 @@ dependencies = [
|
||||
"rustc_version",
|
||||
"toml 1.1.8+spec-1.1.0",
|
||||
"vswhom",
|
||||
"winreg 0.56.0",
|
||||
"winreg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1663,16 +1655,6 @@ dependencies = [
|
||||
"rustc_version",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "file-rotate"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e8e2fa049328a1f3295991407a88585805d126dfaadf74b9fe8c194c730aafc"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"flate2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "filedescriptor"
|
||||
version = "0.8.3"
|
||||
@@ -2131,17 +2113,9 @@ dependencies = [
|
||||
"system-deps",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gp-xml"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"url",
|
||||
"xmltree",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gpapi"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.23.1",
|
||||
@@ -2155,9 +2129,7 @@ dependencies = [
|
||||
"directories",
|
||||
"dns-lookup",
|
||||
"env_logger",
|
||||
"file-rotate",
|
||||
"getrandom 0.4.3",
|
||||
"gp-xml",
|
||||
"gtk",
|
||||
"humantime",
|
||||
"libloading 0.9.0",
|
||||
@@ -2197,7 +2169,6 @@ dependencies = [
|
||||
"uuid",
|
||||
"uzers",
|
||||
"whoami",
|
||||
"windows-sys 0.61.2",
|
||||
"x509-cert",
|
||||
"xmltree",
|
||||
"zeroize",
|
||||
@@ -2205,7 +2176,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpauth"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"auth",
|
||||
@@ -2213,6 +2184,7 @@ dependencies = [
|
||||
"common",
|
||||
"compile-time",
|
||||
"gpapi",
|
||||
"home",
|
||||
"log",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
@@ -2223,7 +2195,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpclient"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -2254,7 +2226,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpgui-helper"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -2275,26 +2247,24 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gphip"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
"chrono",
|
||||
"gpapi",
|
||||
"log",
|
||||
"netdev",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
"uuid",
|
||||
"uzers",
|
||||
"windows",
|
||||
"xmltree",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gpservice"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -2303,7 +2273,6 @@ dependencies = [
|
||||
"common",
|
||||
"compile-time",
|
||||
"env_logger",
|
||||
"file-rotate",
|
||||
"futures",
|
||||
"getrandom 0.4.3",
|
||||
"gpapi",
|
||||
@@ -2324,15 +2293,13 @@ dependencies = [
|
||||
"tokio-tungstenite 0.30.0",
|
||||
"tokio-util",
|
||||
"uuid",
|
||||
"windows-service",
|
||||
"windows-sys 0.61.2",
|
||||
"xz2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gptunnel"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"gpapi",
|
||||
"log",
|
||||
@@ -2344,17 +2311,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpvpnc"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"ipnet",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"winreg 0.56.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2472,6 +2431,15 @@ dependencies = [
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "home"
|
||||
version = "0.5.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "html-escape"
|
||||
version = "0.3.0"
|
||||
@@ -2847,9 +2815,6 @@ name = "ipnet"
|
||||
version = "2.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is-docker"
|
||||
@@ -3860,18 +3825,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openconnect"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
dependencies = [
|
||||
"autotools",
|
||||
"cc",
|
||||
"fs_extra",
|
||||
"gp-xml",
|
||||
"is_executable",
|
||||
"libc",
|
||||
"log",
|
||||
"pkg-config",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6767,12 +6730,6 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "widestring"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
@@ -6923,17 +6880,6 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-service"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "857224b3b211c6f3616921f081ee54721ee3ad2ace2fac6a6337e032f7b4dcf2"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"widestring",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
@@ -6961,15 +6907,6 @@ dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
|
||||
dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
@@ -7136,16 +7073,6 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winreg"
|
||||
version = "0.55.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winreg"
|
||||
version = "0.56.0"
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ members = [
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.91"
|
||||
version = "3.5.0"
|
||||
version = "3.3.1"
|
||||
authors = ["Kevin Yue <[email protected]>"]
|
||||
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
edition = "2024"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# GlobalProtect-openconnect
|
||||
|
||||
A GlobalProtect VPN client built on OpenConnect. GP Connect runs on Windows, macOS, Linux, FreeBSD, and OpenBSD. Command-line tools (`gpclient`) are available on macOS, Linux, and BSD.
|
||||
A GlobalProtect VPN client built on OpenConnect. It provides command-line tools (`gpclient`) and the GP Connect desktop application for macOS, Linux, FreeBSD, and OpenBSD.
|
||||
|
||||
> **Disclaimer**: GP Connect is an independent third-party client for GlobalProtect VPN networks. It is not affiliated with or endorsed by Palo Alto Networks, Inc.
|
||||
|
||||
@@ -21,7 +21,6 @@ A GlobalProtect VPN client built on OpenConnect. GP Connect runs on Windows, mac
|
||||
- [Command-Line Interface](#command-line-interface)
|
||||
- [Graphical User Interface](#graphical-user-interface)
|
||||
- [Installation](#installation)
|
||||
- [Windows](#windows)
|
||||
- [macOS](#macos)
|
||||
- [Debian / Ubuntu](#debian--ubuntu)
|
||||
- [Arch Linux / Manjaro](#arch-linux--manjaro)
|
||||
@@ -41,8 +40,8 @@ A GlobalProtect VPN client built on OpenConnect. GP Connect runs on Windows, mac
|
||||
|
||||
## Features
|
||||
|
||||
- **Multi-Platform** – Windows (x64 and ARM64), macOS (Apple silicon), Linux, FreeBSD, and OpenBSD
|
||||
- **Dual Interfaces** – Desktop GUI (**GP Connect**) and terminal CLI (`gpclient`, on macOS, Linux, and BSD)
|
||||
- **Multi-Platform** – macOS (Apple silicon), Linux, FreeBSD, and OpenBSD
|
||||
- **Dual Interfaces** – Fast terminal CLI (`gpclient`) and desktop GUI (**GP Connect**)
|
||||
- **Native Shell on Linux** – Ultra-low-memory native desktop GUI alongside the webview interface
|
||||
- **Flexible Routing** – Full System VPN tunnel or local SOCKS5 proxy mode
|
||||
- **Modern Authentication** – SAML / SSO, MFA, FIDO2 (YubiKey), client certificates, and external browser login
|
||||
@@ -54,7 +53,7 @@ A GlobalProtect VPN client built on OpenConnect. GP Connect runs on Windows, mac
|
||||
|
||||
### Command-Line Interface
|
||||
|
||||
On macOS, Linux, and BSD, the open-source `gpclient` CLI handles authentication, connection lifecycle, and HIP generation:
|
||||
The open-source `gpclient` CLI handles authentication, connection lifecycle, and HIP generation:
|
||||
|
||||
```bash
|
||||
# Connect to a portal server
|
||||
@@ -80,7 +79,6 @@ Run `gpclient --help` or `gpclient <command> --help` to view all available comma
|
||||
|
||||
### Graphical User Interface
|
||||
|
||||
- **Windows**: Open **GP Connect** from the Start menu.
|
||||
- **macOS**: Open **GP Connect** from Applications.
|
||||
- **Linux / BSD**: Launch GP Connect from your application menu or run:
|
||||
```bash
|
||||
@@ -92,19 +90,6 @@ Run `gpclient --help` or `gpclient <command> --help` to view all available comma
|
||||
|
||||
## Installation
|
||||
|
||||
### Windows
|
||||
|
||||
Download the matching EXE installer from [GitHub Releases](https://github.com/yuezk/GlobalProtect-openconnect/releases/latest):
|
||||
|
||||
- **x64**: Windows 10 version 2004 (build 19041) or later.
|
||||
- **ARM64**: Windows 11.
|
||||
|
||||
Run the installer and confirm installation. It installs GP Connect and its background VPN service for all users; administrator access is required. Open GP Connect from the Start menu as your normal user.
|
||||
|
||||
The installer and application executables are signed by **Tangramly, LLC**. Embedded sign-in uses Microsoft Edge WebView2 Runtime. You can also use your system browser from Settings.
|
||||
|
||||
GP Connect checks for updates in the app. Uninstall it from Windows Settings; your app settings are kept. The Windows package contains the desktop app and service, without the `gpclient` command-line tool.
|
||||
|
||||
### macOS
|
||||
|
||||
Requires Apple silicon and macOS 13+. Includes both GP Connect and the `gpclient` CLI.
|
||||
|
||||
@@ -23,6 +23,8 @@ serde_json.workspace = true
|
||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||
compile-time.workspace = true
|
||||
|
||||
home = "0.5.12"
|
||||
|
||||
# webview auth dependencies
|
||||
tauri = { workspace = true, optional = true }
|
||||
|
||||
|
||||
@@ -16,9 +16,6 @@ fn main() {
|
||||
resolve_commit(&repo_root, &source_commit)
|
||||
);
|
||||
|
||||
#[cfg(all(windows, feature = "webview-auth"))]
|
||||
println!("cargo:rerun-if-changed=icons/windows/icon.ico");
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
tauri_build::build()
|
||||
}
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 47 KiB |
@@ -1,8 +1,8 @@
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use auth::forward_auth_callback;
|
||||
use auth::{BrowserAuthenticator, auth_prelogin};
|
||||
use clap::Parser;
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use clap::Subcommand;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use gpapi::auth::AuthWindowTheme;
|
||||
@@ -49,7 +49,7 @@ See 'gpauth -h' for more information.
|
||||
"
|
||||
)]
|
||||
struct Cli {
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[command(subcommand)]
|
||||
command: Option<CliCommand>,
|
||||
|
||||
@@ -134,7 +134,7 @@ struct Cli {
|
||||
verbose: InfoLevelVerbosity,
|
||||
}
|
||||
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[derive(Subcommand)]
|
||||
enum CliCommand {
|
||||
#[command(hide = true)]
|
||||
@@ -272,7 +272,7 @@ fn init_logger(cli: &Cli) {
|
||||
pub async fn run() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[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}");
|
||||
@@ -382,7 +382,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn callback_arguments_parse_separately() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpauth",
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"bundle": {
|
||||
"icon": ["icons/windows/icon.ico"]
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
#![cfg(windows)]
|
||||
|
||||
use auth::AuthCallbackReceiver;
|
||||
use std::{process::Stdio, time::Duration};
|
||||
|
||||
#[tokio::test]
|
||||
async fn callback_command_forwards_between_processes() {
|
||||
let receiver = AuthCallbackReceiver::bind().unwrap();
|
||||
let child = tokio::process::Command::new(env!("CARGO_BIN_EXE_gpauth"))
|
||||
.args([
|
||||
"auth-callback",
|
||||
"globalprotectcallback:cas-as=1&un=windows-fixture&token=callback-command-test",
|
||||
])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let (data, output) = tokio::time::timeout(Duration::from_secs(10), async {
|
||||
tokio::join!(receiver.receive(), child.wait_with_output())
|
||||
})
|
||||
.await
|
||||
.expect("callback executable did not complete");
|
||||
let output = output.unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
let data = data.unwrap();
|
||||
assert_eq!(data.username(), "windows-fixture");
|
||||
assert_eq!(data.token(), Some("callback-command-test"));
|
||||
}
|
||||
@@ -36,27 +36,6 @@ fn login_response() -> String {
|
||||
)
|
||||
}
|
||||
|
||||
async fn read_request(stream: &mut tokio::net::TcpStream) -> String {
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0; 4096];
|
||||
let count = stream.read(&mut buf).await.unwrap();
|
||||
assert_ne!(count, 0, "Request ended before its body");
|
||||
request.extend_from_slice(&buf[..count]);
|
||||
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||
.unwrap_or(0);
|
||||
if request.len() >= end + 4 + length {
|
||||
return String::from_utf8(request).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
@@ -65,7 +44,25 @@ async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task
|
||||
let mut requests = Vec::new();
|
||||
for (status, body) in responses {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
requests.push(read_request(&mut stream).await);
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0; 4096];
|
||||
let count = stream.read(&mut buf).await.unwrap();
|
||||
assert_ne!(count, 0, "Request ended before its body");
|
||||
request.extend_from_slice(&buf[..count]);
|
||||
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||
.unwrap_or(0);
|
||||
if request.len() >= end + 4 + length {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
requests.push(String::from_utf8(request).unwrap());
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
@@ -129,154 +126,6 @@ async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unreachable_gateway_keeps_cached_cookie() {
|
||||
// Nothing listens here: the cached gateway login gets no answer at all.
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let gateway = format!("http://{}", listener.local_addr().unwrap());
|
||||
drop(listener);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let cache = directory.path().join("cookie.json");
|
||||
let args = TestArgs::parse_from([
|
||||
"test",
|
||||
"http://unavailable-portal.invalid",
|
||||
"--cookie-only",
|
||||
"--cookie-cache",
|
||||
cache.to_str().unwrap(),
|
||||
])
|
||||
.connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
cookie_store::save(
|
||||
&cache,
|
||||
&StoredCookie::new(
|
||||
args.server.clone(),
|
||||
"alice".into(),
|
||||
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||
gateway,
|
||||
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(handler.handle_impl().await.is_err());
|
||||
assert!(
|
||||
cache.exists(),
|
||||
"a login that got no answer must not delete the cookie cache"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_closing_without_response_keeps_cached_cookie() {
|
||||
closed_connection_keeps_cached_cookie(false, false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn portal_closing_without_response_keeps_cached_cookie() {
|
||||
closed_connection_keeps_cached_cookie(true, false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn partial_responses_keep_cached_cookie() {
|
||||
closed_connection_keeps_cached_cookie(false, true).await;
|
||||
closed_connection_keeps_cached_cookie(true, true).await;
|
||||
}
|
||||
|
||||
async fn closed_connection_keeps_cached_cookie(portal_discovery: bool, partial_body: bool) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let worker = tokio::spawn(async move {
|
||||
tokio::time::timeout(Duration::from_secs(5), async move {
|
||||
if portal_discovery {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
assert!(read_request(&mut stream).await.contains("/global-protect/prelogin.esp"));
|
||||
let body = "<prelogin-response><status>Success</status></prelogin-response>";
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let request = read_request(&mut stream).await;
|
||||
if partial_body {
|
||||
stream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n<response>")
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
request
|
||||
})
|
||||
.await
|
||||
.expect("Connection-closing fixture timed out")
|
||||
});
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let cache = directory.path().join("cookie.json");
|
||||
let args = TestArgs::parse_from([
|
||||
"test",
|
||||
&origin,
|
||||
"--cookie-only",
|
||||
"--cookie-cache",
|
||||
cache.to_str().unwrap(),
|
||||
])
|
||||
.connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
cookie_store::save(
|
||||
&cache,
|
||||
&StoredCookie::new(
|
||||
args.server.clone(),
|
||||
"alice".into(),
|
||||
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||
origin.clone(),
|
||||
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let result = if portal_discovery {
|
||||
handler.connect_portal_with_prelogin(&origin).await
|
||||
} else {
|
||||
handler.handle_impl().await
|
||||
};
|
||||
let error = result.unwrap_err();
|
||||
let Some(gpapi::error::PortalError::NetworkError(network)) = error.downcast_ref() else {
|
||||
panic!("Expected a network error, got {error:?}");
|
||||
};
|
||||
if partial_body {
|
||||
assert!(network.is_body() || network.is_decode());
|
||||
} else {
|
||||
assert!(network.is_request());
|
||||
}
|
||||
assert!(!network.is_connect());
|
||||
assert!(!network.is_timeout());
|
||||
assert!(cache.exists(), "an unanswered request must not delete the cookie cache");
|
||||
let request = worker.await.unwrap();
|
||||
assert!(request.contains("portal-cookie"));
|
||||
if portal_discovery {
|
||||
assert!(request.starts_with("POST /global-protect/getconfig.esp "));
|
||||
} else {
|
||||
assert!(request.starts_with("POST /ssl-vpn/login.esp "));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
|
||||
let (origin, worker) = gateway(vec![
|
||||
|
||||
@@ -101,11 +101,6 @@ impl ConnectHandler<'_> {
|
||||
{
|
||||
return Some(Err(error));
|
||||
}
|
||||
// A failed request does not establish that the cookie was rejected.
|
||||
if is_network_error(&error) {
|
||||
warn!("Cached gateway authentication request failed: {error}");
|
||||
return Some(Err(error));
|
||||
}
|
||||
cookie_store::clear(&path);
|
||||
warn!("Cached gateway authentication failed: {error}");
|
||||
return None;
|
||||
@@ -835,11 +830,3 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A failed request says nothing about whether a cached cookie is still valid.
|
||||
pub(super) fn is_network_error(error: &anyhow::Error) -> bool {
|
||||
matches!(
|
||||
error.downcast_ref::<gpapi::error::PortalError>(),
|
||||
Some(gpapi::error::PortalError::NetworkError(_))
|
||||
)
|
||||
}
|
||||
@@ -128,18 +128,15 @@ impl ConnectHandler<'_> {
|
||||
produce_report: Arc::new(move |request, control| {
|
||||
control.check()?;
|
||||
if matches!(source.as_ref(), openconnect::HipSource::Disabled) {
|
||||
return gphip::generate_identity_report(
|
||||
&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context: gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
},
|
||||
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context: gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
},
|
||||
control,
|
||||
)
|
||||
})
|
||||
.map_err(std::io::Error::other);
|
||||
}
|
||||
source.collect(
|
||||
|
||||
@@ -292,11 +292,6 @@ impl<'a> ConnectHandler<'a> {
|
||||
Ok(config) => Some((cred, config)),
|
||||
Err(error) => {
|
||||
self.check_cancelled()?;
|
||||
// A failed request does not establish that the cookie was rejected.
|
||||
if gateway::is_network_error(&error) {
|
||||
warn!("Cached portal authentication request failed: {error}");
|
||||
return Err(error);
|
||||
}
|
||||
warn!("Cached portal authentication failed: {error}");
|
||||
self.clear_cookie_cache();
|
||||
None
|
||||
|
||||
@@ -30,24 +30,14 @@ uuid = { workspace = true, features = ["v4"] }
|
||||
zeroize.workspace = true
|
||||
tempfile.workspace = true
|
||||
getrandom = "0.4"
|
||||
mac_address = "1.2.1"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "socket", "user"] }
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
|
||||
mac_address = "1.2.1"
|
||||
|
||||
[target.'cfg(unix)'.dev-dependencies]
|
||||
mac_address = "1.2.1"
|
||||
|
||||
[dev-dependencies]
|
||||
openssl.workspace = true
|
||||
tokio-tungstenite.workspace = true
|
||||
|
||||
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
gpvpnc = { path = "../../crates/gpvpnc" }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
file-rotate = "0.8.0"
|
||||
windows-service = "0.8.1"
|
||||
windows-sys = { version = "0.61", features = ["Win32_System_Pipes"] }
|
||||
@@ -6,7 +6,7 @@ use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use clap::Parser;
|
||||
use common::paths::service_lock_file;
|
||||
use common::constants::GP_SERVICE_LOCK_FILE;
|
||||
use gpapi::clap::InfoLevelVerbosity;
|
||||
use gpapi::logger;
|
||||
#[cfg(debug_assertions)]
|
||||
@@ -25,7 +25,14 @@ use crate::{
|
||||
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
|
||||
};
|
||||
|
||||
use crate::VERSION;
|
||||
const VERSION: &str = concat!(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
" (",
|
||||
env!("GPSERVICE_GIT_COMMIT"),
|
||||
" ",
|
||||
compile_time::date_str!(),
|
||||
")"
|
||||
);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
struct RedactingMacosLogger {
|
||||
@@ -264,7 +271,7 @@ impl Cli {
|
||||
return Ok(dev_service_lock_file_path(socket));
|
||||
}
|
||||
|
||||
Ok(service_lock_file())
|
||||
Ok(PathBuf::from(GP_SERVICE_LOCK_FILE))
|
||||
}
|
||||
|
||||
fn init_logger(&self) -> Arc<Redaction> {
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
use clap::Parser;
|
||||
use gpapi::clap::InfoLevelVerbosity;
|
||||
#[derive(Parser)]
|
||||
#[command(version = crate::VERSION)]
|
||||
struct Cli {
|
||||
#[command(flatten)]
|
||||
verbose: InfoLevelVerbosity,
|
||||
}
|
||||
pub fn run() -> anyhow::Result<()> {
|
||||
let cli = Cli::parse();
|
||||
crate::windows_service::dispatch(cli.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info))
|
||||
}
|
||||
@@ -75,7 +75,7 @@ impl DesktopClient {
|
||||
loop {
|
||||
match self.read_control().await? {
|
||||
Some(DESKTOP_GUI_INSTALLER) => {
|
||||
self.write_all(&[u8::from(crate::gui_installation::installer().is_some())]).await?;
|
||||
self.write_all(&[u8::from(crate::request_dispatcher::gui_installer().is_some())]).await?;
|
||||
}
|
||||
Some(DESKTOP_SWITCH_BEGIN) => {
|
||||
ensure!(pending.is_none(), "A GUI switch is already pending");
|
||||
@@ -299,7 +299,10 @@ mod tests {
|
||||
let mut reader = reader;
|
||||
let mut capability = [0];
|
||||
reader.read_exact(&mut capability).unwrap();
|
||||
assert_eq!(capability[0], u8::from(crate::gui_installation::installer().is_some()));
|
||||
assert_eq!(
|
||||
capability[0],
|
||||
u8::from(crate::request_dispatcher::gui_installer().is_some())
|
||||
);
|
||||
reader
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -366,7 +366,7 @@ mod tests {
|
||||
r#"{"version":1,"anchor":{"hardware_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","source":1}}"#
|
||||
);
|
||||
|
||||
for source in [0, u8::MAX] {
|
||||
for source in [0, 4] {
|
||||
let json = serde_json::json!({
|
||||
"version": 1,
|
||||
"anchor": {
|
||||
|
||||
@@ -1,359 +0,0 @@
|
||||
use gpapi::utils::checksum::verify_checksum;
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions, Permissions},
|
||||
io::{BufReader, Read, Write},
|
||||
os::unix::fs::{OpenOptionsExt, PermissionsExt},
|
||||
path::Path,
|
||||
};
|
||||
use tar::Archive;
|
||||
use tempfile::NamedTempFile;
|
||||
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;
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum InstallError {
|
||||
Checksum(anyhow::Error),
|
||||
Install(anyhow::Error),
|
||||
}
|
||||
|
||||
pub(crate) fn installer() -> Option<std::path::PathBuf> {
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|executable| {
|
||||
executable
|
||||
.parent()?
|
||||
.parent()
|
||||
.map(|prefix| prefix.join("libexec/gpclient/gp-gui-installer"))
|
||||
})
|
||||
.filter(|path| path.is_file())
|
||||
}
|
||||
|
||||
pub(crate) fn install(src: &Path, checksum: &str, target: &Path) -> Result<(), InstallError> {
|
||||
let installer = installer();
|
||||
install_gui_with_installer(src, checksum, target, installer.as_deref())
|
||||
}
|
||||
|
||||
fn install_gui_with_installer(
|
||||
src: &Path,
|
||||
checksum: &str,
|
||||
target: &Path,
|
||||
installer: Option<&Path>,
|
||||
) -> Result<(), InstallError> {
|
||||
let Some(dir) = target.parent() else {
|
||||
return Err(InstallError::Install(anyhow::anyhow!(
|
||||
"Failed to get parent directory of GUI binary"
|
||||
)));
|
||||
};
|
||||
fs::create_dir_all(dir).map_err(|err| InstallError::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(InstallError::Checksum)?;
|
||||
|
||||
// A package may need to prepare downloaded executables for its runtime.
|
||||
// Resolve this helper beside the running service, never from the request or PATH.
|
||||
if let Some(installer) = installer {
|
||||
let status = std::process::Command::new(installer)
|
||||
.arg(staged_archive.path())
|
||||
.arg(checksum)
|
||||
.arg(target)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.status()
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
return if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(InstallError::Install(anyhow::anyhow!(
|
||||
"GUI package installation failed: {status}"
|
||||
)))
|
||||
};
|
||||
}
|
||||
|
||||
let tar = XzDecoder::new(BufReader::new(
|
||||
staged_archive
|
||||
.reopen()
|
||||
.map_err(|err| InstallError::Install(err.into()))?,
|
||||
))
|
||||
.take(MAX_GUI_ARCHIVE_CONTENT_SIZE);
|
||||
let mut archive = Archive::new(tar);
|
||||
let binary_name = target.file_name().and_then(|name| name.to_str()).unwrap_or("gpgui");
|
||||
let file = extract_gui_binary(&mut archive, dir, binary_name)?;
|
||||
file
|
||||
.as_file()
|
||||
.set_permissions(Permissions::from_mode(0o755))
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
file
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
file.persist(&target).map_err(|err| InstallError::Install(err.into()))?;
|
||||
File::open(dir)
|
||||
.and_then(|directory| directory.sync_all())
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stage_gui_archive(src: &Path, dir: &Path) -> Result<NamedTempFile, InstallError> {
|
||||
let mut source = OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(nix::libc::O_NONBLOCK | nix::libc::O_NOFOLLOW)
|
||||
.open(src)
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
let metadata = source.metadata().map_err(|err| InstallError::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(InstallError::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| InstallError::Install(err.into()))?;
|
||||
let copied = std::io::copy(&mut (&mut source).take(MAX_GUI_ARCHIVE_SIZE + 1), &mut staged)
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
if copied != source_size {
|
||||
return Err(InstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive changed while it was being read"
|
||||
)));
|
||||
}
|
||||
staged.flush().map_err(|err| InstallError::Install(err.into()))?;
|
||||
staged
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
fn extract_gui_binary<R: Read>(
|
||||
archive: &mut Archive<R>,
|
||||
dir: &Path,
|
||||
binary_name: &str,
|
||||
) -> Result<NamedTempFile, InstallError> {
|
||||
for entry in archive.entries().map_err(|err| InstallError::Install(err.into()))? {
|
||||
let mut entry = entry.map_err(|err| InstallError::Install(err.into()))?;
|
||||
let is_gui = entry
|
||||
.path()
|
||||
.map_err(|err| InstallError::Install(err.into()))?
|
||||
.file_name()
|
||||
.is_some_and(|name| name == binary_name);
|
||||
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(InstallError::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| InstallError::Install(err.into()))?;
|
||||
let copied = std::io::copy(&mut entry, &mut file).map_err(|err| InstallError::Install(err.into()))?;
|
||||
if copied != declared_size {
|
||||
return Err(InstallError::Install(anyhow::anyhow!(
|
||||
"GUI binary size does not match its archive header"
|
||||
)));
|
||||
}
|
||||
file.flush().map_err(|err| InstallError::Install(err.into()))?;
|
||||
return Ok(file);
|
||||
}
|
||||
}
|
||||
Err(InstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive does not contain a non-empty regular {binary_name} file"
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{io::Cursor, os::unix::fs::PermissionsExt};
|
||||
|
||||
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(), "gpgui").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(), "gpgui").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(), "gpgui").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_gui_at_the_supplied_target() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpclient/gpgui");
|
||||
|
||||
install(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 installs_nsh_beside_tauri_without_replacing_it() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let tauri = output.path().join("gpgui");
|
||||
std::fs::write(&tauri, b"tauri").unwrap();
|
||||
let mut encoder = XzEncoder::new(Vec::new(), 1);
|
||||
{
|
||||
let mut archive = Builder::new(&mut encoder);
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_size(3);
|
||||
header.set_mode(0o755);
|
||||
header.set_cksum();
|
||||
archive
|
||||
.append_data(&mut header, "gpgui-nsh_3.2.0/gpgui-nsh", &b"nsh"[..])
|
||||
.unwrap();
|
||||
archive.finish().unwrap();
|
||||
}
|
||||
let mut archive = NamedTempFile::new().unwrap();
|
||||
archive.write_all(&encoder.finish().unwrap()).unwrap();
|
||||
archive.flush().unwrap();
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let nsh = output.path().join("gpgui-nsh");
|
||||
install(archive.path(), &checksum, &nsh).unwrap();
|
||||
assert_eq!(std::fs::read(nsh).unwrap(), b"nsh");
|
||||
assert_eq!(std::fs::read(tauri).unwrap(), b"tauri");
|
||||
}
|
||||
|
||||
#[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(archive.path(), "invalid", &target).is_err());
|
||||
assert_eq!(std::fs::read(target).unwrap(), b"existing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_installer_receives_a_verified_staged_archive() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpgui-nsh");
|
||||
let installer = output.path().join("installer");
|
||||
std::fs::write(
|
||||
&installer,
|
||||
"#!/bin/sh\nset -eu\ntest -f \"$1\"\nprintf '%s' \"$2\" > \"$3\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert!(install_gui_with_installer(archive.path(), "invalid", &target, Some(&installer)).is_err());
|
||||
assert!(!target.exists());
|
||||
install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(target).unwrap(), checksum);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_installation_failure_preserves_the_existing_gui() {
|
||||
let archive = compressed_gui_archive(b"replacement");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpgui");
|
||||
std::fs::write(&target, b"existing").unwrap();
|
||||
let installer = output.path().join("installer");
|
||||
std::fs::write(&installer, "#!/bin/sh\nexit 1\n").unwrap();
|
||||
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert!(install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).is_err());
|
||||
assert_eq!(std::fs::read(target).unwrap(), b"existing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires GP_TEST_GUI_BINARY pointing to a built gpgui"]
|
||||
fn installs_single_gui_binary_for_fresh_and_upgrade_downloads() {
|
||||
let binary = std::fs::read(std::env::var("GP_TEST_GUI_BINARY").expect("GP_TEST_GUI_BINARY")).unwrap();
|
||||
let archive = compressed_gui_archive(&binary);
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let output = std::env::var_os("GP_TEST_GUI_INSTALL_DIR")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| temporary.path().to_owned());
|
||||
std::fs::create_dir_all(&output).unwrap();
|
||||
std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let target = output.join("gpclient/gpgui");
|
||||
for upgrade in [false, true] {
|
||||
if upgrade {
|
||||
std::fs::write(&target, b"old GUI").unwrap();
|
||||
}
|
||||
install(archive.path(), &checksum, &target).unwrap();
|
||||
assert_eq!(std::fs::read_dir(target.parent().unwrap()).unwrap().count(), 1);
|
||||
assert_eq!(std::fs::read(&target).unwrap(), binary);
|
||||
let result = std::process::Command::new(&target).arg("--version").output().unwrap();
|
||||
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
|
||||
assert!(String::from_utf8_lossy(&result.stdout).contains(env!("CARGO_PKG_VERSION")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ impl HipPreviews {
|
||||
})
|
||||
.await;
|
||||
let result = match generated {
|
||||
Ok(Ok(report)) => preview_result(®istry, session_id, report),
|
||||
Ok(Ok(xml)) => preview_result(®istry, session_id, xml),
|
||||
Ok(Err(error)) => {
|
||||
log::warn!("HIP preview failed: {error:#}");
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
|
||||
@@ -132,20 +132,17 @@ impl HipPreviews {
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_result(registry: &SessionRegistry, session_id: Uuid, report: gpapi::hip::HipReport) -> ServiceResult {
|
||||
let result = registry
|
||||
.store_hip_preview(session_id, report.xml)
|
||||
.and_then(|preview_id| {
|
||||
registry
|
||||
.hip_preview_chunk(session_id, preview_id, 0)
|
||||
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
windows_updates: report.windows_updates,
|
||||
})
|
||||
});
|
||||
fn preview_result(registry: &SessionRegistry, session_id: Uuid, xml: String) -> ServiceResult {
|
||||
let result = registry.store_hip_preview(session_id, xml).and_then(|preview_id| {
|
||||
registry
|
||||
.hip_preview_chunk(session_id, preview_id, 0)
|
||||
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
})
|
||||
});
|
||||
result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"))
|
||||
}
|
||||
|
||||
@@ -155,7 +152,7 @@ fn generate(
|
||||
desktop_uid: Option<u32>,
|
||||
identity: HostIdentity,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<gpapi::hip::HipReport> {
|
||||
) -> 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),
|
||||
@@ -191,15 +188,7 @@ fn generate(
|
||||
};
|
||||
let xml = match &request.source {
|
||||
HipSource::Disabled => bail!("HIP is disabled"),
|
||||
HipSource::Generated => {
|
||||
return gphip::generate_report_details(
|
||||
&gphip::ReportInput {
|
||||
profile,
|
||||
context: gphip::ReportContext::Preview,
|
||||
},
|
||||
&check,
|
||||
);
|
||||
}
|
||||
HipSource::Generated => crate::hip_source::generate(&profile, None, &input, &check, true)?,
|
||||
HipSource::Edited { .. } => {
|
||||
let xml = edited_report.context("Edited HIP report is unavailable")?;
|
||||
crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)?
|
||||
@@ -215,10 +204,7 @@ fn generate(
|
||||
}
|
||||
};
|
||||
check()?;
|
||||
Ok(gpapi::hip::HipReport {
|
||||
xml,
|
||||
windows_updates: None,
|
||||
})
|
||||
Ok(xml)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{io, sync::Arc};
|
||||
use std::{fs, io, os::unix::fs::PermissionsExt, path::PathBuf, sync::Arc};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
@@ -6,17 +6,7 @@ use gpapi::{
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder},
|
||||
};
|
||||
use gphip::{ReportContext, ReportInput};
|
||||
use openconnect::HipRequest;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use openconnect::HipScript;
|
||||
#[cfg(unix)]
|
||||
#[path = "hip_source/unix.rs"]
|
||||
mod scripts;
|
||||
#[cfg(windows)]
|
||||
#[path = "hip_source/windows.rs"]
|
||||
mod scripts;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use scripts::script_environment;
|
||||
use openconnect::{HipRequest, HipScript, HipScriptEnvironment};
|
||||
|
||||
pub(crate) struct HipExecution {
|
||||
pub source: openconnect::HipSource,
|
||||
@@ -46,7 +36,7 @@ impl HipApproval {
|
||||
pub(crate) fn resolve(
|
||||
source: &HipSource,
|
||||
desktop_uid: Option<u32>,
|
||||
restricted_desktop: bool,
|
||||
brokered_macos: bool,
|
||||
edited_report: Option<Arc<str>>,
|
||||
profile: Option<OsProfile>,
|
||||
) -> anyhow::Result<HipExecution> {
|
||||
@@ -73,11 +63,22 @@ pub(crate) fn resolve(
|
||||
}
|
||||
HipSource::UserScript { path } => {
|
||||
approval = None;
|
||||
ensure_custom_available(restricted_desktop)?;
|
||||
scripts::user_script(path, desktop_uid)?
|
||||
ensure_custom_available(brokered_macos)?;
|
||||
let uid = desktop_uid.context("HIP custom scripts require a verified desktop user")?;
|
||||
ensure!(uid != 0, "HIP custom scripts require a non-root desktop user");
|
||||
let path = PathBuf::from(path);
|
||||
ensure!(path.is_absolute(), "HIP custom script path must be absolute");
|
||||
let metadata = fs::symlink_metadata(&path).context("Failed to inspect the HIP script")?;
|
||||
ensure!(
|
||||
metadata.is_file() && !metadata.file_type().is_symlink() && metadata.permissions().mode() & 0o111 != 0,
|
||||
"HIP custom script must be an executable regular file"
|
||||
);
|
||||
let script =
|
||||
HipScript::new(path.to_string_lossy().into_owned(), Some(uid))?.with_environment(script_environment(uid)?)?;
|
||||
openconnect::HipSource::Script(script)
|
||||
}
|
||||
HipSource::ApprovedRootScript { approval_id } => {
|
||||
ensure_custom_available(restricted_desktop)?;
|
||||
ensure_custom_available(brokered_macos)?;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
let owner_uid = desktop_uid.context("Root HIP scripts require a verified desktop user")?;
|
||||
@@ -112,10 +113,10 @@ pub(crate) fn resolve(
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_custom_available(restricted_desktop: bool) -> anyhow::Result<()> {
|
||||
fn ensure_custom_available(brokered_macos: bool) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
!cfg!(target_os = "macos") && !restricted_desktop,
|
||||
"Custom HIP scripts are unavailable on this platform"
|
||||
!cfg!(target_os = "macos") && !brokered_macos,
|
||||
"Custom HIP scripts are unavailable on macOS"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -148,6 +149,27 @@ pub(crate) fn generate(
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn script_environment(uid: u32) -> anyhow::Result<HipScriptEnvironment> {
|
||||
let user =
|
||||
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.context("HIP execution user is unavailable")?;
|
||||
let home = user.dir.to_string_lossy().into_owned();
|
||||
Ok(HipScriptEnvironment {
|
||||
variables: vec![
|
||||
(
|
||||
"PATH".into(),
|
||||
gpapi::process::collection::command_path(uid == 0)?
|
||||
.into_string()
|
||||
.map_err(|_| anyhow::anyhow!("HIP command path is not valid UTF-8"))?,
|
||||
),
|
||||
("LC_ALL".into(), "C".into()),
|
||||
("HOME".into(), home.clone()),
|
||||
("USER".into(), user.name.clone()),
|
||||
("LOGNAME".into(), user.name),
|
||||
],
|
||||
cwd: home,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn profile(
|
||||
identity: &HostIdentity,
|
||||
os: ClientOs,
|
||||
@@ -158,22 +180,19 @@ pub(crate) fn profile(
|
||||
control: &dyn gpapi::collection::CollectionControl,
|
||||
) -> io::Result<OsProfile> {
|
||||
let identity = gpapi::os_profile::desktop::identity_from_parts(
|
||||
hostname.as_deref().unwrap_or(identity.computer()).into(),
|
||||
host_id.as_deref().unwrap_or(identity.host_id()).into(),
|
||||
hostname.unwrap_or_else(|| identity.computer().into()),
|
||||
host_id.unwrap_or_else(|| identity.host_id().into()),
|
||||
identity.serialno().into(),
|
||||
identity.mac_addr().into(),
|
||||
);
|
||||
let mut builder = OsProfileBuilder::new(os).host_identity(identity);
|
||||
if let Some(hostname) = hostname {
|
||||
builder = builder.computer_name_override(hostname);
|
||||
}
|
||||
if let Some(version) = version {
|
||||
builder = builder.client_version(version);
|
||||
}
|
||||
if let Some(os_version) = os_version {
|
||||
builder = builder.os_version(os_version);
|
||||
}
|
||||
gpapi::os_profile::desktop::collect_profile_with_control(builder, host_id.as_deref(), control)
|
||||
gpapi::os_profile::desktop::collect_profile_with_control(builder, None, control)
|
||||
}
|
||||
|
||||
fn generation_error(error: anyhow::Error) -> io::Error {
|
||||
@@ -238,29 +257,6 @@ mod tests {
|
||||
assert_eq!(profile.host_identity().serialno(), "serial");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn native_windows_profile_retains_negotiated_host_id() {
|
||||
let identity = gpapi::os_profile::HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"hardware-seed".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let profile = profile(
|
||||
&identity,
|
||||
ClientOs::Windows,
|
||||
None,
|
||||
None,
|
||||
Some("negotiated-host".into()),
|
||||
None,
|
||||
&gpapi::collection::CollectionBudget::new(std::time::Duration::from_secs(60)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(profile.host_id(), "negotiated-host");
|
||||
assert_eq!(profile.host_identity().host_id(), "negotiated-host");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_errors_preserve_cancellation() {
|
||||
let error = generation_error(io::Error::new(io::ErrorKind::Interrupted, "cancelled").into());
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
use anyhow::{Context, ensure};
|
||||
use openconnect::{HipScript, HipScriptEnvironment};
|
||||
use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf};
|
||||
pub(super) fn user_script(path: &str, desktop_uid: Option<u32>) -> anyhow::Result<openconnect::HipSource> {
|
||||
let uid = desktop_uid.context("HIP custom scripts require a verified desktop user")?;
|
||||
ensure!(uid != 0, "HIP custom scripts require a non-root desktop user");
|
||||
let path = PathBuf::from(path);
|
||||
ensure!(path.is_absolute(), "HIP custom script path must be absolute");
|
||||
let metadata = fs::symlink_metadata(&path).context("Failed to inspect the HIP script")?;
|
||||
ensure!(
|
||||
metadata.is_file() && !metadata.file_type().is_symlink() && metadata.permissions().mode() & 0o111 != 0,
|
||||
"HIP custom script must be an executable regular file"
|
||||
);
|
||||
let script =
|
||||
HipScript::new(path.to_string_lossy().into_owned(), Some(uid))?.with_environment(script_environment(uid)?)?;
|
||||
Ok(openconnect::HipSource::Script(script))
|
||||
}
|
||||
pub(crate) fn script_environment(uid: u32) -> anyhow::Result<HipScriptEnvironment> {
|
||||
let user =
|
||||
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.context("HIP execution user is unavailable")?;
|
||||
let home = user.dir.to_string_lossy().into_owned();
|
||||
Ok(HipScriptEnvironment {
|
||||
variables: vec![
|
||||
(
|
||||
"PATH".into(),
|
||||
gpapi::process::collection::command_path(uid == 0)?
|
||||
.into_string()
|
||||
.map_err(|_| anyhow::anyhow!("HIP command path is not valid UTF-8"))?,
|
||||
),
|
||||
("LC_ALL".into(), "C".into()),
|
||||
("HOME".into(), home.clone()),
|
||||
("USER".into(), user.name.clone()),
|
||||
("LOGNAME".into(), user.name),
|
||||
],
|
||||
cwd: home,
|
||||
})
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
pub(super) fn user_script(_path: &str, _desktop_uid: Option<u32>) -> anyhow::Result<openconnect::HipSource> {
|
||||
anyhow::bail!("Custom HIP scripts are unavailable on Windows")
|
||||
}
|
||||
@@ -1,15 +1,11 @@
|
||||
#[cfg_attr(windows, path = "cli/windows.rs")]
|
||||
mod cli;
|
||||
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
|
||||
mod credential_lease;
|
||||
#[cfg(unix)]
|
||||
mod desktop_client;
|
||||
#[cfg(all(debug_assertions, unix))]
|
||||
#[cfg(debug_assertions)]
|
||||
mod dev_bootstrap;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))]
|
||||
mod device_anchor;
|
||||
#[cfg(unix)]
|
||||
mod gui_installation;
|
||||
mod handlers;
|
||||
mod hip_preview;
|
||||
mod hip_source;
|
||||
@@ -17,41 +13,14 @@ mod hip_source;
|
||||
mod macos_broker;
|
||||
mod request_dispatcher;
|
||||
mod routes;
|
||||
#[cfg(unix)]
|
||||
mod runtime_user;
|
||||
mod session_registry;
|
||||
mod vpn_script;
|
||||
mod vpn_task;
|
||||
#[cfg(windows)]
|
||||
mod windows_patches;
|
||||
mod ws_connection;
|
||||
mod ws_server;
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows_service;
|
||||
|
||||
const VERSION: &str = concat!(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
" (",
|
||||
env!("GPSERVICE_GIT_COMMIT"),
|
||||
" ",
|
||||
compile_time::date_str!(),
|
||||
")"
|
||||
);
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
cli::run().await;
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn main() -> std::process::ExitCode {
|
||||
match cli::run() {
|
||||
Ok(()) => std::process::ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
eprintln!("{error:#}");
|
||||
std::process::ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,27 @@
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions, Permissions},
|
||||
io::{BufReader, Read, Write},
|
||||
os::unix::fs::{OpenOptionsExt, PermissionsExt},
|
||||
path::Path,
|
||||
sync::{Arc, atomic::AtomicBool},
|
||||
};
|
||||
|
||||
use gpapi::{
|
||||
service::{
|
||||
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
utils::redact::Redaction,
|
||||
utils::{checksum::verify_checksum, redact::Redaction},
|
||||
};
|
||||
use log::{info, warn};
|
||||
#[cfg(unix)]
|
||||
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(crate) struct SessionAuthority {
|
||||
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
@@ -63,17 +75,12 @@ pub struct RequestDispatcher {
|
||||
lifecycle: crate::vpn_task::LifecycleHandle,
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
redaction: Arc<Redaction>,
|
||||
#[cfg(unix)]
|
||||
install_lock: Mutex<()>,
|
||||
gui_management_enabled: bool,
|
||||
restricted_desktop: bool,
|
||||
externally_brokered: bool,
|
||||
}
|
||||
|
||||
impl RequestDispatcher {
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn patch_checks(&self) -> Arc<crate::windows_patches::PatchChecks> {
|
||||
self.lifecycle.patch_checks.clone()
|
||||
}
|
||||
pub fn subscribe_tunnel(&self) -> tokio::sync::watch::Receiver<crate::vpn_task::TunnelBinding> {
|
||||
self.lifecycle.subscribe_tunnel()
|
||||
}
|
||||
@@ -82,16 +89,15 @@ impl RequestDispatcher {
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
redaction: Arc<Redaction>,
|
||||
gui_management_enabled: bool,
|
||||
restricted_desktop: bool,
|
||||
externally_brokered: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
lifecycle,
|
||||
gui_restart_requested,
|
||||
redaction,
|
||||
#[cfg(unix)]
|
||||
install_lock: Mutex::new(()),
|
||||
gui_management_enabled,
|
||||
restricted_desktop,
|
||||
externally_brokered,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,7 +202,7 @@ impl RequestDispatcher {
|
||||
edited_report,
|
||||
} => {
|
||||
let prepared =
|
||||
crate::vpn_task::prepare_connection(*request, self.restricted_desktop, preparation.cancellation()).await;
|
||||
crate::vpn_task::prepare_connection(*request, self.externally_brokered, preparation.cancellation()).await;
|
||||
return match prepared {
|
||||
Ok(connection) => preparation.commit(connection, desktop_uid, edited_report),
|
||||
Err(error) => {
|
||||
@@ -266,34 +272,31 @@ impl RequestDispatcher {
|
||||
| WsRequest::GetHipApprovalStatus { .. }
|
||||
| WsRequest::ReadHipPreviewChunk(_)
|
||||
| WsRequest::GetLastSubmittedHipReport
|
||||
| WsRequest::SetTunnelStatisticsEnabled { .. }
|
||||
| WsRequest::SetWindowsPatchInterest { .. }
|
||||
| WsRequest::RefreshWindowsPatches { .. } => {
|
||||
| WsRequest::SetTunnelStatisticsEnabled { .. } => {
|
||||
unreachable!("session-bound request was already dispatched")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_connect_request(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
|
||||
if !self.restricted_desktop {
|
||||
if !self.externally_brokered {
|
||||
return Ok(());
|
||||
}
|
||||
if request.args().vpnc_script().is_some() {
|
||||
return Err("Custom VPN scripts are unavailable on this platform");
|
||||
return Err("macOS does not support custom VPN scripts");
|
||||
}
|
||||
if matches!(
|
||||
request.args().hip_source(),
|
||||
gpapi::hip::HipSource::UserScript { .. } | gpapi::hip::HipSource::ApprovedRootScript { .. }
|
||||
) {
|
||||
return Err("Custom HIP scripts are unavailable on this platform");
|
||||
return Err("macOS does not support custom HIP scripts");
|
||||
}
|
||||
if request.args().certificate().is_some() || request.args().sslkey().is_some() {
|
||||
return Err("Client identity must be provided as certificate data");
|
||||
return Err("macOS client identity must be provided as protected data, not root-readable paths");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult {
|
||||
if request.variant == gpapi::gui::GuiVariant::Nsh && !cfg!(target_os = "linux") {
|
||||
return ServiceResult::rejected(
|
||||
@@ -305,17 +308,14 @@ impl RequestDispatcher {
|
||||
let path = request.path;
|
||||
let checksum = request.checksum;
|
||||
let target = request.variant.update_target();
|
||||
let installed = tokio::task::spawn_blocking(move || {
|
||||
crate::gui_installation::install(std::path::Path::new(&path), &checksum, &target)
|
||||
})
|
||||
.await;
|
||||
let installed = tokio::task::spawn_blocking(move || install_gui_at(Path::new(&path), &checksum, &target)).await;
|
||||
match installed {
|
||||
Ok(Ok(())) => ServiceResult::Accepted,
|
||||
Ok(Err(crate::gui_installation::InstallError::Checksum(err))) => {
|
||||
Ok(Err(GuiInstallError::Checksum(err))) => {
|
||||
warn!("Failed to verify GUI update checksum: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::ChecksumFailed, "GUI update checksum failed")
|
||||
}
|
||||
Ok(Err(crate::gui_installation::InstallError::Install(err))) => {
|
||||
Ok(Err(GuiInstallError::Install(err))) => {
|
||||
warn!("Failed to install GUI update: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed")
|
||||
}
|
||||
@@ -325,20 +325,335 @@ impl RequestDispatcher {
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
async fn update_gui(&self, _request: UpdateGuiRequest) -> ServiceResult {
|
||||
ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"Use the Windows installer to update GP Connect",
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum GuiInstallError {
|
||||
Checksum(anyhow::Error),
|
||||
Install(anyhow::Error),
|
||||
}
|
||||
|
||||
pub(crate) fn gui_installer() -> Option<std::path::PathBuf> {
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|executable| {
|
||||
executable
|
||||
.parent()?
|
||||
.parent()
|
||||
.map(|prefix| prefix.join("libexec/gpclient/gp-gui-installer"))
|
||||
})
|
||||
.filter(|path| path.is_file())
|
||||
}
|
||||
|
||||
fn install_gui_at(src: &Path, checksum: &str, target: &Path) -> Result<(), GuiInstallError> {
|
||||
let installer = gui_installer();
|
||||
install_gui_with_installer(src, checksum, target, installer.as_deref())
|
||||
}
|
||||
|
||||
fn install_gui_with_installer(
|
||||
src: &Path,
|
||||
checksum: &str,
|
||||
target: &Path,
|
||||
installer: Option<&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)?;
|
||||
|
||||
// A package may need to prepare downloaded executables for its runtime.
|
||||
// Resolve this helper beside the running service, never from the request or PATH.
|
||||
if let Some(installer) = installer {
|
||||
let status = std::process::Command::new(installer)
|
||||
.arg(staged_archive.path())
|
||||
.arg(checksum)
|
||||
.arg(target)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.status()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
return if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI package installation failed: {status}"
|
||||
)))
|
||||
};
|
||||
}
|
||||
|
||||
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 binary_name = target.file_name().and_then(|name| name.to_str()).unwrap_or("gpgui");
|
||||
let file = extract_gui_binary(&mut archive, dir, binary_name)?;
|
||||
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,
|
||||
binary_name: &str,
|
||||
) -> 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 == binary_name);
|
||||
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 {binary_name} file"
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::vpn_task::test_connect_request as test_request;
|
||||
use gpapi::gateway::Gateway;
|
||||
use std::{io::Cursor, os::unix::fs::PermissionsExt};
|
||||
|
||||
use gpapi::{
|
||||
gateway::Gateway,
|
||||
service::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(), "gpgui").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(), "gpgui").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(), "gpgui").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_gui_at_the_supplied_target() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let 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 installs_nsh_beside_tauri_without_replacing_it() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let tauri = output.path().join("gpgui");
|
||||
std::fs::write(&tauri, b"tauri").unwrap();
|
||||
let mut encoder = XzEncoder::new(Vec::new(), 1);
|
||||
{
|
||||
let mut archive = Builder::new(&mut encoder);
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_size(3);
|
||||
header.set_mode(0o755);
|
||||
header.set_cksum();
|
||||
archive
|
||||
.append_data(&mut header, "gpgui-nsh_3.2.0/gpgui-nsh", &b"nsh"[..])
|
||||
.unwrap();
|
||||
archive.finish().unwrap();
|
||||
}
|
||||
let mut archive = NamedTempFile::new().unwrap();
|
||||
archive.write_all(&encoder.finish().unwrap()).unwrap();
|
||||
archive.flush().unwrap();
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let nsh = output.path().join("gpgui-nsh");
|
||||
install_gui_at(archive.path(), &checksum, &nsh).unwrap();
|
||||
assert_eq!(std::fs::read(nsh).unwrap(), b"nsh");
|
||||
assert_eq!(std::fs::read(tauri).unwrap(), b"tauri");
|
||||
}
|
||||
|
||||
#[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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_installer_receives_a_verified_staged_archive() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpgui-nsh");
|
||||
let installer = output.path().join("installer");
|
||||
std::fs::write(
|
||||
&installer,
|
||||
"#!/bin/sh\nset -eu\ntest -f \"$1\"\nprintf '%s' \"$2\" > \"$3\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert!(install_gui_with_installer(archive.path(), "invalid", &target, Some(&installer)).is_err());
|
||||
assert!(!target.exists());
|
||||
install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(target).unwrap(), checksum);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_installation_failure_preserves_the_existing_gui() {
|
||||
let archive = compressed_gui_archive(b"replacement");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpgui");
|
||||
std::fs::write(&target, b"existing").unwrap();
|
||||
let installer = output.path().join("installer");
|
||||
std::fs::write(&installer, "#!/bin/sh\nexit 1\n").unwrap();
|
||||
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert!(install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).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(
|
||||
@@ -385,7 +700,7 @@ mod tests {
|
||||
let custom = test_request(info.clone()).with_vpnc_script(Some(script.to_string()));
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_request(&custom),
|
||||
Err("Custom VPN scripts are unavailable on this platform")
|
||||
Err("macOS does not support custom VPN scripts")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -394,7 +709,32 @@ mod tests {
|
||||
});
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_request(&custom),
|
||||
Err("Custom HIP scripts are unavailable on this platform")
|
||||
Err("macOS does not support custom HIP scripts")
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires GP_TEST_GUI_BINARY pointing to a built gpgui"]
|
||||
fn installs_single_gui_binary_for_fresh_and_upgrade_downloads() {
|
||||
let binary = std::fs::read(std::env::var("GP_TEST_GUI_BINARY").expect("GP_TEST_GUI_BINARY")).unwrap();
|
||||
let archive = compressed_gui_archive(&binary);
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let output = std::env::var_os("GP_TEST_GUI_INSTALL_DIR")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| temporary.path().to_owned());
|
||||
std::fs::create_dir_all(&output).unwrap();
|
||||
std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let target = output.join("gpclient/gpgui");
|
||||
for upgrade in [false, true] {
|
||||
if upgrade {
|
||||
std::fs::write(&target, b"old GUI").unwrap();
|
||||
}
|
||||
install_gui_at(archive.path(), &checksum, &target).unwrap();
|
||||
assert_eq!(std::fs::read_dir(target.parent().unwrap()).unwrap().count(), 1);
|
||||
assert_eq!(std::fs::read(&target).unwrap(), binary);
|
||||
let result = std::process::Command::new(&target).arg("--version").output().unwrap();
|
||||
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
|
||||
assert!(String::from_utf8_lossy(&result.stdout).contains(env!("CARGO_PKG_VERSION")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,8 +62,6 @@ enum SessionStatus {
|
||||
}
|
||||
|
||||
struct SessionRecord {
|
||||
#[cfg(windows)]
|
||||
windows_identity: Option<Arc<gpapi::windows::PipeClientIdentity>>,
|
||||
non_tunnel: Option<AttachmentAttempt>,
|
||||
closed_attachment: Option<Uuid>,
|
||||
secret: Zeroizing<[u8; 32]>,
|
||||
@@ -257,8 +255,6 @@ impl SessionRegistry {
|
||||
sessions.insert(
|
||||
credential.session_id(),
|
||||
SessionRecord {
|
||||
#[cfg(windows)]
|
||||
windows_identity: None,
|
||||
non_tunnel: None,
|
||||
closed_attachment: None,
|
||||
secret: Zeroizing::new(*credential.secret()),
|
||||
@@ -277,38 +273,6 @@ impl SessionRegistry {
|
||||
Ok(credential)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn issue_windows(
|
||||
&self,
|
||||
product_version: &str,
|
||||
identity: Arc<gpapi::windows::PipeClientIdentity>,
|
||||
) -> Result<Arc<SessionCredential>, SessionError> {
|
||||
let credential = self.issue(product_version, None)?;
|
||||
// The credential is not published until its Windows owner is retained.
|
||||
self
|
||||
.sessions
|
||||
.lock()
|
||||
.map_err(|_| SessionError::Unavailable)?
|
||||
.get_mut(&credential.session_id())
|
||||
.ok_or(SessionError::Unauthorized)?
|
||||
.windows_identity = Some(identity);
|
||||
Ok(credential)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn windows_identity(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
) -> Result<Arc<gpapi::windows::PipeClientIdentity>, SessionError> {
|
||||
self
|
||||
.sessions
|
||||
.lock()
|
||||
.map_err(|_| SessionError::Unavailable)?
|
||||
.get(&session_id)
|
||||
.and_then(|record| record.windows_identity.clone())
|
||||
.ok_or(SessionError::Unauthorized)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
let Ok(mut sessions) = self.sessions.lock() else {
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[path = "privileged_unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows.rs"]
|
||||
mod platform;
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "macos.rs"]
|
||||
mod platform;
|
||||
@@ -11,8 +8,7 @@ mod platform;
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "macos",
|
||||
windows
|
||||
target_os = "macos"
|
||||
)))]
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
@@ -20,5 +16,3 @@ mod platform;
|
||||
mod selection;
|
||||
|
||||
pub(crate) use platform::builder;
|
||||
#[cfg(windows)]
|
||||
pub(crate) use platform::recover_network;
|
||||
@@ -1,24 +0,0 @@
|
||||
use gpapi::service::request::ConnectArgs;
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
use std::sync::Mutex;
|
||||
const RECOVERY_KEY: &str = r"SOFTWARE\GP Connect\NetworkRecovery";
|
||||
|
||||
pub(crate) fn recover_network() -> std::io::Result<()> {
|
||||
gpvpnc::windows::recover(RECOVERY_KEY)
|
||||
}
|
||||
|
||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result<VpnBuilder> {
|
||||
anyhow::ensure!(
|
||||
args.vpnc_script().is_none(),
|
||||
"Windows does not support custom VPN scripts"
|
||||
);
|
||||
let network = Mutex::new(gpvpnc::windows::NetworkConfigurator::new(RECOVERY_KEY)?);
|
||||
Ok(
|
||||
Vpn::builder(server, cookie).network_configuration_handler(move |configuration| {
|
||||
network
|
||||
.lock()
|
||||
.map_err(|_| std::io::Error::other("Windows network state is unavailable"))?
|
||||
.configure(&configuration.reason, &configuration.environment)
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -31,8 +31,6 @@ mod script_tun;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LifecycleHandle {
|
||||
#[cfg(windows)]
|
||||
pub(crate) patch_checks: Arc<crate::windows_patches::PatchChecks>,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
admissions: Arc<Mutex<Admissions>>,
|
||||
tunnel: watch::Sender<TunnelBinding>,
|
||||
@@ -128,7 +126,6 @@ impl LifecycleHandle {
|
||||
ServiceResult::Accepted
|
||||
}
|
||||
|
||||
#[cfg(any(unix, test))]
|
||||
pub async fn disconnect_and_wait(&self) -> bool {
|
||||
let completion = {
|
||||
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
|
||||
@@ -450,7 +447,7 @@ pub(crate) struct VpnTask {
|
||||
events: mpsc::Receiver<LifecycleEvent>,
|
||||
lifecycle: LifecycleHandle,
|
||||
vpn_state_tx: watch::Sender<VpnState>,
|
||||
restricted_desktop: bool,
|
||||
brokered_macos: bool,
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
active: Option<ActiveAttempt>,
|
||||
cancel_token: CancellationToken,
|
||||
@@ -459,13 +456,11 @@ pub(crate) struct VpnTask {
|
||||
impl VpnTask {
|
||||
pub fn new(
|
||||
vpn_state_tx: watch::Sender<VpnState>,
|
||||
restricted_desktop: bool,
|
||||
brokered_macos: bool,
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
) -> (Self, LifecycleHandle) {
|
||||
let (events_tx, events) = mpsc::channel(4);
|
||||
let lifecycle = LifecycleHandle {
|
||||
#[cfg(windows)]
|
||||
patch_checks: crate::windows_patches::PatchChecks::new(),
|
||||
events: events_tx,
|
||||
admissions: Arc::new(Mutex::new(Admissions::default())),
|
||||
tunnel: watch::channel(TunnelBinding::default()).0,
|
||||
@@ -475,7 +470,7 @@ impl VpnTask {
|
||||
events,
|
||||
lifecycle: lifecycle.clone(),
|
||||
vpn_state_tx,
|
||||
restricted_desktop,
|
||||
brokered_macos,
|
||||
registry,
|
||||
active: None,
|
||||
cancel_token: CancellationToken::new(),
|
||||
@@ -622,7 +617,7 @@ impl VpnTask {
|
||||
desktop_uid,
|
||||
edited_report,
|
||||
session_id,
|
||||
restricted_desktop: self.restricted_desktop,
|
||||
brokered_macos: self.brokered_macos,
|
||||
registry: self.registry.clone(),
|
||||
lifecycle: self.lifecycle.clone(),
|
||||
},
|
||||
|
||||
@@ -66,13 +66,10 @@ pub(super) async fn run(
|
||||
md5: request.md5.clone(),
|
||||
};
|
||||
if !posture_enabled {
|
||||
return gphip::generate_identity_report(
|
||||
&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context,
|
||||
},
|
||||
control,
|
||||
)
|
||||
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context,
|
||||
})
|
||||
.map_err(std::io::Error::other);
|
||||
}
|
||||
source.collect(
|
||||
|
||||
@@ -30,7 +30,7 @@ pub(super) struct ConnectionResources {
|
||||
/// the complete ledger and its retained identity resources to the service.
|
||||
pub(crate) async fn prepare_connection(
|
||||
request: ConnectRequest,
|
||||
restricted_desktop: bool,
|
||||
brokered_macos: bool,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<PreparedConnection> {
|
||||
let mode = request.args().packet_delivery().clone();
|
||||
@@ -77,16 +77,11 @@ pub(crate) async fn prepare_connection(
|
||||
};
|
||||
check()?;
|
||||
let args = setup_request.args();
|
||||
let identity = super::prepare_identity(args, restricted_desktop || non_tunnel)?;
|
||||
#[cfg(target_os = "macos")]
|
||||
let directory = restricted_desktop.then(|| std::path::PathBuf::from("/var/run/com.yuezk.gpgui"));
|
||||
#[cfg(windows)]
|
||||
let directory = Some(common::paths::service_private_dir());
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let directory: Option<std::path::PathBuf> = None;
|
||||
let identity = super::prepare_identity(args, brokered_macos || non_tunnel)?;
|
||||
let directory = brokered_macos.then(|| std::path::Path::new("/var/run/com.yuezk.gpgui"));
|
||||
let identity_files = identity
|
||||
.as_ref()
|
||||
.map(|identity| identity.write_files(directory.as_deref()))
|
||||
.map(|identity| identity.write_files(directory))
|
||||
.transpose()?;
|
||||
let host = args.host_identity().context("Authenticated host identity is missing")?;
|
||||
let profile = crate::hip_source::profile(
|
||||
@@ -186,8 +181,8 @@ mod tests {
|
||||
use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo};
|
||||
|
||||
#[tokio::test]
|
||||
async fn restricted_desktop_and_non_tunnel_identity_reject_path_handoff() {
|
||||
for (restricted_desktop, non_tunnel) in [(true, false), (false, true), (true, true)] {
|
||||
async fn brokered_macos_and_non_tunnel_identity_reject_path_handoff() {
|
||||
for (brokered_macos, non_tunnel) in [(true, false), (false, true), (true, true)] {
|
||||
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
|
||||
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||
.with_certificate(Some("/identity.pem".into()));
|
||||
@@ -197,7 +192,7 @@ mod tests {
|
||||
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
||||
}
|
||||
let request = serde_json::from_value(wire).unwrap();
|
||||
let error = prepare_connection(request, restricted_desktop, CancellationToken::new())
|
||||
let error = prepare_connection(request, brokered_macos, CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
|
||||
@@ -20,7 +20,7 @@ pub(super) struct AttemptInput {
|
||||
pub desktop_uid: Option<u32>,
|
||||
pub edited_report: Option<Arc<str>>,
|
||||
pub session_id: Option<Uuid>,
|
||||
pub restricted_desktop: bool,
|
||||
pub brokered_macos: bool,
|
||||
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
pub lifecycle: LifecycleHandle,
|
||||
}
|
||||
@@ -31,7 +31,6 @@ struct TunnelInput {
|
||||
source: Arc<openconnect::HipSource>,
|
||||
session_id: Option<Uuid>,
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
#[cfg(unix)]
|
||||
desktop_uid: Option<u32>,
|
||||
}
|
||||
|
||||
@@ -50,30 +49,13 @@ pub(super) fn spawn(
|
||||
) -> JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
let attempt = input.attempt;
|
||||
#[cfg(windows)]
|
||||
let _patch_interest = {
|
||||
let args = input.connection.request.args();
|
||||
let profile = &input.connection.resources.profile;
|
||||
(matches!(args.hip_source(), gpapi::hip::HipSource::Generated)
|
||||
&& profile.is_native()
|
||||
&& profile.client_os() == gpapi::os_profile::ClientOs::Windows
|
||||
&& (input.connection.request.plan().policy().collect_hip_data()
|
||||
|| input
|
||||
.connection
|
||||
.request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.any(|member| member.authentication.mode() == SessionMode::Tunnel)))
|
||||
.then(|| input.lifecycle.patch_checks.consumer())
|
||||
};
|
||||
let mut failure = None;
|
||||
let mut approval = None;
|
||||
if !cancellation.is_cancelled() {
|
||||
let request = input.connection.request.clone();
|
||||
let resources = input.connection.resources.clone();
|
||||
let desktop_uid = input.desktop_uid;
|
||||
let brokered = input.restricted_desktop;
|
||||
let brokered = input.brokered_macos;
|
||||
let edited = input.edited_report.clone();
|
||||
let setup_cancel = cancellation.clone();
|
||||
let execution = tokio::task::spawn_blocking(move || {
|
||||
@@ -123,7 +105,6 @@ pub(super) fn spawn(
|
||||
source,
|
||||
session_id: input.session_id,
|
||||
registry: input.registry.clone(),
|
||||
#[cfg(unix)]
|
||||
desktop_uid: input.desktop_uid,
|
||||
};
|
||||
input.connection.request.release_script_tun_bootstrap();
|
||||
@@ -272,14 +253,12 @@ fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyho
|
||||
),
|
||||
gpapi::script_tun::PacketDelivery::ScriptTun(request) => {
|
||||
ensure!(input.session_id.is_some(), "Script-tun requires a desktop session");
|
||||
#[cfg(unix)]
|
||||
let owner = input.desktop_uid.context("Desktop identity is unavailable")?;
|
||||
#[cfg(windows)]
|
||||
let owner = input
|
||||
.registry
|
||||
.windows_identity(input.session_id.context("Desktop session is unavailable")?)?;
|
||||
let (builder, script_tun) =
|
||||
super::script_tun::builder(member.gateway.server(), member.authentication.cookie(), request, owner)?;
|
||||
let (builder, script_tun) = super::script_tun::builder(
|
||||
member.gateway.server(),
|
||||
member.authentication.cookie(),
|
||||
request,
|
||||
input.desktop_uid.context("Desktop identity is unavailable")?,
|
||||
)?;
|
||||
(builder, Some(script_tun))
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,19 +1,40 @@
|
||||
//! Supervision of an unprivileged script-tun consumer; payload semantics belong to the caller.
|
||||
use super::{LifecycleEvent, LifecycleHandle};
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use gpapi::script_tun::{Bootstrap, Identity, Message, receive, send as send_message};
|
||||
use openconnect::{Vpn, tunnel::Event};
|
||||
use gpapi::script_tun::{Bootstrap, Identity, Message, ScriptTunRequest, receive, send as send_message};
|
||||
use openconnect::{Vpn, VpnBuilder, tunnel::Event};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use tokio::{sync::mpsc, time::Instant};
|
||||
use tokio::{net::UnixStream, sync::mpsc, time::Instant};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[path = "script_tun/unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(windows)]
|
||||
#[path = "script_tun/windows.rs"]
|
||||
mod platform;
|
||||
pub(super) use platform::{PreparedScriptTun, builder};
|
||||
pub(super) struct PreparedScriptTun {
|
||||
pub control: std::os::unix::net::UnixStream,
|
||||
pub bootstrap: Bootstrap,
|
||||
}
|
||||
|
||||
pub(super) fn builder(
|
||||
server: &str,
|
||||
cookie: &str,
|
||||
request: &ScriptTunRequest,
|
||||
uid: u32,
|
||||
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
|
||||
request.validate()?;
|
||||
ensure!(uid != 0, "Script-tun worker requires a desktop user");
|
||||
let (control, child) = std::os::unix::net::UnixStream::pair()?;
|
||||
let builder = Vpn::builder(server, cookie).script_tun_program(
|
||||
request.program.to_str().context("Program is not UTF-8")?,
|
||||
&request.args,
|
||||
uid,
|
||||
child.into(),
|
||||
)?;
|
||||
Ok((
|
||||
builder,
|
||||
PreparedScriptTun {
|
||||
control,
|
||||
bootstrap: request.bootstrap.clone(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct NetworkChanged;
|
||||
@@ -32,7 +53,7 @@ enum Native {
|
||||
pub(super) async fn run(
|
||||
identity: Identity,
|
||||
vpn: Arc<Vpn>,
|
||||
mut prepared: PreparedScriptTun,
|
||||
prepared: PreparedScriptTun,
|
||||
approval: &crate::hip_source::HipApproval,
|
||||
lifecycle: &LifecycleHandle,
|
||||
cancellation: CancellationToken,
|
||||
@@ -41,8 +62,6 @@ pub(super) async fn run(
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
sessions: &mut gpapi::session::desktop::GatewaySessions,
|
||||
) -> anyhow::Result<()> {
|
||||
let channel = prepared.connect().await?;
|
||||
let mut control = ConsumerControl::new(channel);
|
||||
let attempt = identity.attempt;
|
||||
let (native_tx, native) = mpsc::channel(64);
|
||||
let observed = native_tx.clone();
|
||||
@@ -58,7 +77,7 @@ pub(super) async fn run(
|
||||
monitor: monitor.clone(),
|
||||
})
|
||||
.await;
|
||||
if event_result.is_err() || cancellation.is_cancelled() {
|
||||
if event_result.is_err() {
|
||||
monitor.stop().await;
|
||||
return Ok(());
|
||||
}
|
||||
@@ -72,50 +91,31 @@ pub(super) async fn run(
|
||||
tokio::pin!(worker);
|
||||
let mut worker_done = false;
|
||||
let stop = cancellation.child_token();
|
||||
let result = {
|
||||
let supervisor = supervise(
|
||||
identity,
|
||||
&mut control,
|
||||
std::mem::take(&mut prepared.bootstrap),
|
||||
native,
|
||||
stop.clone(),
|
||||
events,
|
||||
);
|
||||
tokio::pin!(supervisor);
|
||||
let mut supervisor_done = false;
|
||||
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut supervisor => { supervisor_done = true; break result; }
|
||||
result = &mut worker => { worker_done = true; break Err(anyhow::anyhow!("VPN worker ended: {:?}", result)); }
|
||||
_ = approval_poll.tick() => {
|
||||
if !approval.approval_is_valid() || !registry.has_session(session_id) {
|
||||
super::runtime::stop_for_revoked_approval(lifecycle, &cancellation);
|
||||
}
|
||||
let supervisor = supervise(identity, prepared, native, stop.clone(), events);
|
||||
tokio::pin!(supervisor);
|
||||
let mut supervisor_done = false;
|
||||
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut supervisor => { supervisor_done = true; break result; }
|
||||
result = &mut worker => { worker_done = true; break Err(anyhow::anyhow!("VPN worker ended: {:?}", result)); }
|
||||
_ = approval_poll.tick() => {
|
||||
if !approval.approval_is_valid() || !registry.has_session(session_id) {
|
||||
super::runtime::stop_for_revoked_approval(lifecycle, &cancellation);
|
||||
}
|
||||
}
|
||||
};
|
||||
stop.cancel();
|
||||
// Keep the consumer's control and packet endpoints alive until OpenConnect
|
||||
// consumes cancellation and logs out. Early EOF would interrupt that logout.
|
||||
vpn.disconnect();
|
||||
if !worker_done {
|
||||
let _ = worker.await;
|
||||
}
|
||||
if !supervisor_done {
|
||||
let _ = supervisor.await;
|
||||
}
|
||||
result
|
||||
};
|
||||
control.stop().await;
|
||||
let cleanup = prepared.stop_worker();
|
||||
monitor.stop().await;
|
||||
if result.is_ok() {
|
||||
cleanup?;
|
||||
} else if let Err(error) = cleanup {
|
||||
log::warn!("Could not stop packet worker: {error:#}");
|
||||
stop.cancel();
|
||||
if !supervisor_done {
|
||||
let _ = supervisor.await;
|
||||
}
|
||||
vpn.disconnect();
|
||||
if !worker_done {
|
||||
let _ = worker.await;
|
||||
}
|
||||
monitor.stop().await;
|
||||
result
|
||||
}
|
||||
|
||||
@@ -128,113 +128,93 @@ enum WorkerState {
|
||||
Suspending,
|
||||
}
|
||||
|
||||
// Own the channel independently of its supervision future so run() can drain
|
||||
// the native VPN before telling the consumer to stop or closing its endpoints.
|
||||
struct ConsumerControl {
|
||||
output: tokio::io::WriteHalf<platform::ControlStream>,
|
||||
messages: mpsc::Receiver<std::io::Result<Message>>,
|
||||
reader: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl ConsumerControl {
|
||||
fn new(channel: platform::ControlStream) -> Self {
|
||||
let (mut input, output) = tokio::io::split(channel);
|
||||
let (messages_tx, messages) = mpsc::channel(8);
|
||||
let reader = tokio::spawn(async move {
|
||||
loop {
|
||||
let message = receive(&mut input).await;
|
||||
let failed = message.is_err();
|
||||
if messages_tx.send(message).await.is_err() || failed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
Self {
|
||||
output,
|
||||
messages,
|
||||
reader,
|
||||
}
|
||||
}
|
||||
async fn stop(&mut self) {
|
||||
let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut self.output, &Message::Stop)).await;
|
||||
self.reader.abort();
|
||||
let _ = (&mut self.reader).await;
|
||||
}
|
||||
}
|
||||
impl Drop for ConsumerControl {
|
||||
fn drop(&mut self) {
|
||||
self.reader.abort();
|
||||
}
|
||||
}
|
||||
|
||||
// Production and generic-consumer tests exercise this same state machine.
|
||||
// The same control loop runs against native observations in production and a
|
||||
// generic socket consumer in tests; VPN ownership stays in run().
|
||||
async fn supervise(
|
||||
identity: Identity,
|
||||
control: &mut ConsumerControl,
|
||||
mut bootstrap: Bootstrap,
|
||||
mut prepared: PreparedScriptTun,
|
||||
mut native: mpsc::Receiver<Native>,
|
||||
cancellation: CancellationToken,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
) -> anyhow::Result<()> {
|
||||
let attempt = identity.attempt;
|
||||
let ConsumerControl { output, messages, .. } = control;
|
||||
prepared.control.set_nonblocking(true)?;
|
||||
let control = UnixStream::from_std(prepared.control)?;
|
||||
let (mut input, mut output) = control.into_split();
|
||||
let (messages_tx, mut messages) = mpsc::channel(8);
|
||||
let reader = tokio::spawn(async move {
|
||||
loop {
|
||||
let message = receive(&mut input).await;
|
||||
let failed = message.is_err();
|
||||
if messages_tx.send(message).await.is_err() || failed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut network = None;
|
||||
let mut session = None;
|
||||
let mut worker = WorkerState::Preparing;
|
||||
let mut online = false;
|
||||
let mut was_connected = false;
|
||||
let mut deadline: Option<Instant> = None;
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => break,
|
||||
_ = async { if let Some(at) = deadline { tokio::time::sleep_until(at).await } else { std::future::pending().await } } => bail!("Script-tun worker activation timed out"),
|
||||
message = messages.recv() => match message.context("Script-tun control reader stopped")?? {
|
||||
Message::Ready if worker == WorkerState::Preparing && network.is_some() => {
|
||||
worker = WorkerState::Ready;
|
||||
}
|
||||
Message::Activated if worker == WorkerState::Activating => {
|
||||
ensure!(online, "Script-tun activation completed while VPN was offline");
|
||||
ensure!(!cancellation.is_cancelled(), "Script-tun startup cancelled");
|
||||
events.send(LifecycleEvent::Established { attempt, session: session.clone().context("Native session is missing")? }).await?;
|
||||
worker = WorkerState::Active; was_connected = true; deadline = None;
|
||||
}
|
||||
Message::Suspended if worker == WorkerState::Suspending => { worker = WorkerState::Ready; deadline = None; }
|
||||
Message::Error { message } => bail!("Script-tun worker: {message}"),
|
||||
_ => bail!("Unexpected script-tun consumer message"),
|
||||
},
|
||||
event = native.recv() => match event.context("Native event stream ended")? {
|
||||
Native::Established(value) => { session = Some(value); online = true; deadline.get_or_insert(Instant::now() + Duration::from_secs(10)); }
|
||||
Native::Event(Event::Configuration(config)) => {
|
||||
let observed = config.context("VPN configuration is absent").and_then(observed_network);
|
||||
if was_connected && (observed.is_err() || network.as_ref().is_some_and(|old| observed.as_ref().is_ok_and(|new| old != new))) { return Err(NetworkChanged.into()); }
|
||||
let observed = observed?;
|
||||
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
|
||||
else {
|
||||
send(output, &Message::Configure { identity, bootstrap: std::mem::take(&mut bootstrap), network: observed.clone() }).await?;
|
||||
network = Some(observed);
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
let result = async {
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => break,
|
||||
_ = async { if let Some(at) = deadline { tokio::time::sleep_until(at).await } else { std::future::pending().await } } => bail!("Script-tun worker activation timed out"),
|
||||
message = messages.recv() => match message.context("Script-tun control reader stopped")?? {
|
||||
Message::Ready if worker == WorkerState::Preparing && network.is_some() => {
|
||||
worker = WorkerState::Ready;
|
||||
}
|
||||
}
|
||||
Native::Event(Event::Reconnecting) => {
|
||||
ensure!(worker != WorkerState::Activating, "VPN connection interrupted during script-tun activation; reconnect the VPN");
|
||||
online = false;
|
||||
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
|
||||
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
|
||||
send(output, &Message::Suspend).await?; worker = WorkerState::Suspending;
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
Message::Activated if worker == WorkerState::Activating => {
|
||||
ensure!(online, "Script-tun activation completed while VPN was offline");
|
||||
ensure!(!cancellation.is_cancelled(), "Script-tun startup cancelled");
|
||||
events.send(LifecycleEvent::Established { attempt, session: session.clone().context("Native session is missing")? }).await?;
|
||||
worker = WorkerState::Active; was_connected = true; deadline = None;
|
||||
}
|
||||
Message::Suspended if worker == WorkerState::Suspending => { worker = WorkerState::Ready; deadline = None; }
|
||||
Message::Error { message } => bail!("Script-tun worker: {message}"),
|
||||
_ => bail!("Unexpected script-tun consumer message"),
|
||||
},
|
||||
event = native.recv() => match event.context("Native event stream ended")? {
|
||||
Native::Established(value) => { session = Some(value); online = true; deadline.get_or_insert(Instant::now() + Duration::from_secs(10)); }
|
||||
Native::Event(Event::Configuration(config)) => {
|
||||
let observed = config.context("VPN configuration is absent").and_then(observed_network);
|
||||
if was_connected && (observed.is_err() || network.as_ref().is_some_and(|old| observed.as_ref().is_ok_and(|new| old != new))) { return Err(NetworkChanged.into()); }
|
||||
let observed = observed?;
|
||||
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
|
||||
else {
|
||||
send(&mut output, &Message::Configure { identity, bootstrap: std::mem::take(&mut prepared.bootstrap), network: observed.clone() }).await?;
|
||||
network = Some(observed);
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
Native::Event(Event::Reconnecting) => {
|
||||
ensure!(worker != WorkerState::Activating, "VPN connection interrupted during script-tun activation; reconnect the VPN");
|
||||
online = false;
|
||||
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
|
||||
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
|
||||
send(&mut output, &Message::Suspend).await?; worker = WorkerState::Suspending;
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
Native::Event(Event::Reconnected) => online = true,
|
||||
Native::Event(_) => {},
|
||||
}
|
||||
Native::Event(Event::Reconnected) => online = true,
|
||||
Native::Event(_) => {},
|
||||
}
|
||||
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
|
||||
send(&mut output, &Message::Activate).await?; worker = WorkerState::Activating;
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
|
||||
send(output, &Message::Activate).await?;
|
||||
worker = WorkerState::Activating;
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(())
|
||||
}.await;
|
||||
let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut output, &Message::Stop)).await;
|
||||
drop(output);
|
||||
reader.abort();
|
||||
let _ = reader.await;
|
||||
result
|
||||
}
|
||||
|
||||
fn observed_network(
|
||||
@@ -263,5 +243,5 @@ async fn send(writer: &mut (impl tokio::io::AsyncWrite + Unpin), message: &Messa
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,8 +1,6 @@
|
||||
use super::*;
|
||||
use gpapi::script_tun::{Bootstrap, ScriptTunRequest};
|
||||
use openconnect::{VpnSessionInfo, tunnel::Configuration};
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
// A generic consumer, with no proxy settings or private worker protocol.
|
||||
struct Consumer {
|
||||
@@ -25,26 +23,16 @@ impl Consumer {
|
||||
launch_id: uuid::Uuid::new_v4(),
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
let stopped = cancel.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
let mut prepared = PreparedScriptTun {
|
||||
control: Some(control),
|
||||
let task = tokio::spawn(supervise(
|
||||
identity,
|
||||
PreparedScriptTun {
|
||||
control,
|
||||
bootstrap: Bootstrap::new(b"consumer bootstrap").unwrap(),
|
||||
};
|
||||
let channel = prepared.connect().await?;
|
||||
let mut control = ConsumerControl::new(channel);
|
||||
let result = supervise(
|
||||
identity,
|
||||
&mut control,
|
||||
prepared.bootstrap,
|
||||
observations,
|
||||
stopped,
|
||||
events,
|
||||
)
|
||||
.await;
|
||||
control.stop().await;
|
||||
result
|
||||
});
|
||||
},
|
||||
observations,
|
||||
cancel.clone(),
|
||||
events,
|
||||
));
|
||||
Self {
|
||||
control: UnixStream::from_std(child).unwrap(),
|
||||
native,
|
||||
@@ -303,36 +291,3 @@ async fn reconnect_during_activation_returns_clear_error_without_connected() {
|
||||
);
|
||||
assert!(consumer.events.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn supervision_completion_keeps_consumer_alive_until_owner_stops_it() {
|
||||
let (channel, mut peer) = UnixStream::pair().unwrap();
|
||||
let mut control = ConsumerControl::new(channel);
|
||||
let (_native, observations) = mpsc::channel(1);
|
||||
let (events, _notifications) = mpsc::channel(1);
|
||||
let cancellation = CancellationToken::new();
|
||||
cancellation.cancel();
|
||||
supervise(
|
||||
Identity {
|
||||
service_instance: uuid::Uuid::new_v4(),
|
||||
attempt: 1,
|
||||
launch_id: uuid::Uuid::new_v4(),
|
||||
},
|
||||
&mut control,
|
||||
Bootstrap::default(),
|
||||
observations,
|
||||
cancellation,
|
||||
events,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(30), receive(&mut peer))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
control.stop().await;
|
||||
assert!(matches!(receive(&mut peer).await.unwrap(), Message::Stop));
|
||||
drop(control);
|
||||
assert!(receive(&mut peer).await.is_err());
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::script_tun::{Bootstrap, ScriptTunRequest};
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
pub(super) type ControlStream = tokio::net::UnixStream;
|
||||
pub(crate) struct PreparedScriptTun {
|
||||
pub(super) control: Option<std::os::unix::net::UnixStream>,
|
||||
pub bootstrap: Bootstrap,
|
||||
}
|
||||
|
||||
pub(crate) fn builder(
|
||||
server: &str,
|
||||
cookie: &str,
|
||||
request: &ScriptTunRequest,
|
||||
uid: u32,
|
||||
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
|
||||
request.validate()?;
|
||||
ensure!(uid != 0, "Script-tun worker requires a desktop user");
|
||||
let (control, child) = std::os::unix::net::UnixStream::pair()?;
|
||||
let builder = Vpn::builder(server, cookie).script_tun_program(
|
||||
request.program.to_str().context("Program is not UTF-8")?,
|
||||
&request.args,
|
||||
uid,
|
||||
child.into(),
|
||||
)?;
|
||||
Ok((
|
||||
builder,
|
||||
PreparedScriptTun {
|
||||
control: Some(control),
|
||||
bootstrap: request.bootstrap.clone(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
impl PreparedScriptTun {
|
||||
pub(super) async fn connect(&mut self) -> anyhow::Result<ControlStream> {
|
||||
let control = self.control.take().context("Worker control pipe is unavailable")?;
|
||||
control.set_nonblocking(true)?;
|
||||
Ok(tokio::net::UnixStream::from_std(control)?)
|
||||
}
|
||||
// The native OpenConnect Unix launcher owns/reaps its child on disconnect.
|
||||
pub(super) fn stop_worker(&mut self) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
process::user_process::UserProcess,
|
||||
script_tun::{Bootstrap, ScriptTunRequest},
|
||||
windows::PipeClientIdentity,
|
||||
};
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
use std::{os::windows::io::AsRawHandle, sync::Arc, time::Duration};
|
||||
use tokio::net::windows::named_pipe::NamedPipeServer;
|
||||
use windows_sys::Win32::System::Pipes::GetNamedPipeClientProcessId;
|
||||
pub(super) type ControlStream = NamedPipeServer;
|
||||
|
||||
pub(crate) struct PreparedScriptTun {
|
||||
control: Option<NamedPipeServer>,
|
||||
worker: UserProcess,
|
||||
pub(super) bootstrap: Bootstrap,
|
||||
}
|
||||
pub(crate) fn builder(
|
||||
server: &str,
|
||||
cookie: &str,
|
||||
request: &ScriptTunRequest,
|
||||
owner: Arc<PipeClientIdentity>,
|
||||
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
|
||||
request.validate()?;
|
||||
let attempt = uuid::Uuid::new_v4();
|
||||
let control_name = format!(r"\\.\pipe\GPConnect.ScriptTun.{attempt}.Control");
|
||||
let packet_name = format!(r"\\.\pipe\GPConnect.ScriptTun.{attempt}.Packets");
|
||||
let control = owner.create_control_pipe(&control_name)?;
|
||||
let mut packets = owner.create_packet_pipe(&packet_name)?;
|
||||
let worker = UserProcess::launch(
|
||||
owner.primary_token(),
|
||||
&request.program,
|
||||
&request.args,
|
||||
&[
|
||||
("OPENCONNECT_SCRIPT_TUN_CONTROL_PIPE", &control_name),
|
||||
("VPN_PIPE", &packet_name),
|
||||
],
|
||||
)
|
||||
.context("Could not launch the user-session packet worker")?;
|
||||
packets.connect(worker.id(), Duration::from_secs(10))?;
|
||||
// PacketPipe creates only raw overlapped Win32 I/O and never registers IOCP.
|
||||
let builder = unsafe { Vpn::builder(server, cookie).script_tun_pipe(packets.into_handle()) };
|
||||
Ok((
|
||||
builder,
|
||||
PreparedScriptTun {
|
||||
control: Some(control),
|
||||
worker,
|
||||
bootstrap: request.bootstrap.clone(),
|
||||
},
|
||||
))
|
||||
}
|
||||
impl PreparedScriptTun {
|
||||
pub(super) async fn connect(&mut self) -> anyhow::Result<ControlStream> {
|
||||
ensure!(!self.worker.has_exited()?, "The packet worker exited during startup");
|
||||
let control = self.control.take().context("Worker control pipe is unavailable")?;
|
||||
tokio::time::timeout(Duration::from_secs(10), control.connect())
|
||||
.await
|
||||
.context("Packet control connection timed out")??;
|
||||
let mut pid = 0;
|
||||
if unsafe { GetNamedPipeClientProcessId(control.as_raw_handle(), &mut pid) } == 0 {
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
ensure!(pid == self.worker.id(), "Unexpected packet control client");
|
||||
Ok(control)
|
||||
}
|
||||
pub(super) fn stop_worker(&mut self) -> anyhow::Result<()> {
|
||||
Ok(self.worker.stop()?)
|
||||
}
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
//! One service-owned local patch search, independent of report generation.
|
||||
use gpapi::{
|
||||
collection::{CollectionBudget, CollectionControl},
|
||||
process::collection::CollectorCommands,
|
||||
};
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
const INTERVAL: Duration = Duration::from_secs(15 * 60);
|
||||
const SEARCH_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
enum Command {
|
||||
Interest(Uuid, bool),
|
||||
CheckIfDue,
|
||||
Refresh(Option<u64>, oneshot::Sender<bool>),
|
||||
}
|
||||
|
||||
pub(crate) struct PatchChecks {
|
||||
tx: mpsc::UnboundedSender<Command>,
|
||||
rx: Mutex<Option<mpsc::UnboundedReceiver<Command>>>,
|
||||
}
|
||||
|
||||
pub(crate) struct Consumer {
|
||||
checks: Arc<PatchChecks>,
|
||||
id: Uuid,
|
||||
}
|
||||
impl Drop for Consumer {
|
||||
fn drop(&mut self) {
|
||||
self.checks.set_interest(self.id, false);
|
||||
}
|
||||
}
|
||||
|
||||
impl PatchChecks {
|
||||
pub(crate) fn new() -> Arc<Self> {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
Arc::new(Self {
|
||||
tx,
|
||||
rx: Mutex::new(Some(rx)),
|
||||
})
|
||||
}
|
||||
pub(crate) fn set_interest(&self, id: Uuid, enabled: bool) {
|
||||
let _ = self.tx.send(Command::Interest(id, enabled));
|
||||
}
|
||||
pub(crate) fn check_if_due(&self) {
|
||||
let _ = self.tx.send(Command::CheckIfDue);
|
||||
}
|
||||
pub(crate) fn consumer(self: &Arc<Self>) -> Consumer {
|
||||
let id = Uuid::new_v4();
|
||||
self.set_interest(id, true);
|
||||
Consumer {
|
||||
checks: self.clone(),
|
||||
id,
|
||||
}
|
||||
}
|
||||
pub(crate) async fn refresh(&self, after: Option<u64>) -> bool {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if self.tx.send(Command::Refresh(after, tx)).is_err() {
|
||||
return false;
|
||||
}
|
||||
rx.await.unwrap_or(false)
|
||||
}
|
||||
pub(crate) async fn run(&self, stop: CancellationToken) {
|
||||
let Some(mut commands) = self.rx.lock().unwrap().take() else {
|
||||
return;
|
||||
};
|
||||
let mut consumers = HashSet::new();
|
||||
let mut waiters = Vec::<oneshot::Sender<bool>>::new();
|
||||
let mut worker = None;
|
||||
// Reading status never searches Windows Update. Missing/unreadable data is due immediately.
|
||||
let status = tokio::task::spawn_blocking({
|
||||
let stop = stop.clone();
|
||||
move || helper("--patch-status", None, stop)
|
||||
})
|
||||
.await;
|
||||
let mut next = match status {
|
||||
Ok(Ok(Some(checked))) => checked.saturating_add(INTERVAL.as_secs()),
|
||||
_ => 0,
|
||||
};
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = stop.cancelled() => break,
|
||||
command = commands.recv() => {
|
||||
match command {
|
||||
Some(Command::Interest(id, enabled)) => {
|
||||
if enabled { consumers.insert(id); } else { consumers.remove(&id); }
|
||||
}
|
||||
Some(Command::CheckIfDue) => {
|
||||
if worker.is_none() && now() >= next { worker = Some(start(None, stop.clone())); }
|
||||
}
|
||||
Some(Command::Refresh(after, reply)) => {
|
||||
waiters.push(reply);
|
||||
if worker.is_none() { worker = Some(start(after, stop.clone())); }
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
result = async { match &mut worker { Some(task) => task.await, None => std::future::pending().await } } => {
|
||||
worker = None;
|
||||
let success = matches!(&result, Ok(Ok(Some(_))));
|
||||
if !success { log::warn!("Local Windows patch check failed: {result:?}"); }
|
||||
for reply in waiters.drain(..) { let _ = reply.send(success); }
|
||||
next = match result {
|
||||
Ok(Ok(Some(checked))) => checked.saturating_add(INTERVAL.as_secs()),
|
||||
_ => now().saturating_add(INTERVAL.as_secs()),
|
||||
};
|
||||
}
|
||||
_ = tokio::time::sleep(Duration::from_secs(next.saturating_sub(now()).min(30))),
|
||||
if worker.is_none() && !consumers.is_empty() => {
|
||||
if now() >= next { worker = Some(start(None, stop.clone())); }
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(task) = worker {
|
||||
let _ = task.await;
|
||||
}
|
||||
for reply in waiters {
|
||||
let _ = reply.send(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
}
|
||||
fn start(after: Option<u64>, stop: CancellationToken) -> tokio::task::JoinHandle<anyhow::Result<Option<u64>>> {
|
||||
tokio::task::spawn_blocking(move || helper("--refresh-patches", after, stop))
|
||||
}
|
||||
fn helper(command: &str, after: Option<u64>, stop: CancellationToken) -> anyhow::Result<Option<u64>> {
|
||||
let budget = CollectionBudget::new(SEARCH_TIMEOUT);
|
||||
let check = || {
|
||||
if stop.is_cancelled() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Patch check cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
let path = std::env::current_exe()?.with_file_name("gp-posture.exe");
|
||||
let after = after.map(|after| after.to_string());
|
||||
let mut args = vec![command];
|
||||
if let Some(after) = &after {
|
||||
args.push(after);
|
||||
}
|
||||
let output = CollectorCommands::new(&check)
|
||||
.run_executable(&path, &args)?
|
||||
.ok_or_else(|| anyhow::anyhow!("Windows posture helper is unavailable"))?;
|
||||
anyhow::ensure!(output.status.success(), "Windows posture helper failed");
|
||||
Ok(serde_json::from_slice(&output.stdout)?)
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
//! A credential lease binds the existing desktop session to its Windows token.
|
||||
use crate::session_registry::SessionRegistry;
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
service::transport::WINDOWS_ADMISSION_REQUEST,
|
||||
windows::{PipeClientIdentity, create_service_admission_pipe},
|
||||
};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::windows::named_pipe::NamedPipeServer,
|
||||
task::JoinSet,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(super) struct Admission {
|
||||
listener: NamedPipeServer,
|
||||
registry: Arc<SessionRegistry>,
|
||||
}
|
||||
struct Lease {
|
||||
registry: Arc<SessionRegistry>,
|
||||
session: uuid::Uuid,
|
||||
}
|
||||
impl Drop for Lease {
|
||||
fn drop(&mut self) {
|
||||
self.registry.revoke(self.session);
|
||||
}
|
||||
}
|
||||
impl Admission {
|
||||
pub fn new(registry: Arc<SessionRegistry>) -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
listener: create_service_admission_pipe(true)?,
|
||||
registry,
|
||||
})
|
||||
}
|
||||
pub async fn run(mut self, cancel: CancellationToken) -> anyhow::Result<()> {
|
||||
let mut clients = JoinSet::new();
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => break Ok(()),
|
||||
result = self.listener.connect() => {
|
||||
if let Err(error) = result { break Err(error.into()); }
|
||||
let next = match create_service_admission_pipe(false) { Ok(next) => next, Err(error) => break Err(error.into()) };
|
||||
let pipe = std::mem::replace(&mut self.listener, next);
|
||||
let registry = self.registry.clone();
|
||||
let cancel = cancel.clone();
|
||||
clients.spawn(async move {
|
||||
if let Err(error) = serve(pipe, registry, cancel).await { log::warn!("Desktop credential lease ended: {error:#}"); }
|
||||
});
|
||||
}
|
||||
_ = clients.join_next(), if !clients.is_empty() => {},
|
||||
}
|
||||
};
|
||||
// Drop each lease before the shared registry and service runtime disappear.
|
||||
clients.abort_all();
|
||||
while clients.join_next().await.is_some() {}
|
||||
result
|
||||
}
|
||||
}
|
||||
async fn serve(
|
||||
mut pipe: NamedPipeServer,
|
||||
registry: Arc<SessionRegistry>,
|
||||
cancel: CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut request = [0; WINDOWS_ADMISSION_REQUEST.len()];
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return Ok(()),
|
||||
result = tokio::time::timeout(Duration::from_secs(10), pipe.read_exact(&mut request)) => { result.context("Desktop admission timed out")??; }
|
||||
}
|
||||
ensure!(
|
||||
request == WINDOWS_ADMISSION_REQUEST,
|
||||
"Invalid desktop admission request"
|
||||
);
|
||||
// This synchronous call impersonates, duplicates and reverts before any await.
|
||||
let identity = Arc::new(PipeClientIdentity::from_pipe(&pipe)?);
|
||||
let credential = registry.issue_windows(env!("CARGO_PKG_VERSION"), identity)?;
|
||||
let _lease = Lease {
|
||||
registry,
|
||||
session: credential.session_id(),
|
||||
};
|
||||
let frame = credential.encode_frame()?;
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return Ok(()),
|
||||
result = tokio::time::timeout(Duration::from_secs(10), pipe.write_all(&frame)) => { result.context("Desktop credential delivery timed out")??; }
|
||||
}
|
||||
let mut byte = [0];
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => {},
|
||||
result = pipe.read(&mut byte) => { ensure!(result? == 0, "Unexpected desktop lease message"); }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
use std::{fs::OpenOptions, io, path::Path};
|
||||
|
||||
use file_rotate::{ContentLimit, FileRotate, compression::Compression, suffix::AppendCount};
|
||||
|
||||
const ROTATE_BYTES: usize = 5 * 1024 * 1024;
|
||||
const ARCHIVE_COUNT: usize = 3;
|
||||
|
||||
pub(super) fn writer(path: &Path) -> io::Result<FileRotate<AppendCount>> {
|
||||
// Keep startup failure explicit: FileRotate's constructor suppresses open errors.
|
||||
OpenOptions::new().create(true).read(true).append(true).open(path)?;
|
||||
Ok(FileRotate::new(
|
||||
path,
|
||||
AppendCount::new(ARCHIVE_COUNT),
|
||||
ContentLimit::BytesSurpassed(ROTATE_BYTES),
|
||||
Compression::None,
|
||||
None,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::{fs, io::Write};
|
||||
|
||||
#[test]
|
||||
fn keeps_the_latest_three_archives_and_complete_current_entry() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("gpservice.log");
|
||||
fs::write(dir.path().join("unrelated.log"), "keep").unwrap();
|
||||
let mut log = writer(&path).unwrap();
|
||||
for marker in b'0'..=b'5' {
|
||||
log.write_all(&vec![marker; ROTATE_BYTES + 1]).unwrap();
|
||||
}
|
||||
log.flush().unwrap();
|
||||
drop(log);
|
||||
|
||||
assert_eq!(fs::read(&path).unwrap(), vec![b'5'; ROTATE_BYTES + 1]);
|
||||
for (suffix, marker) in [(1, b'4'), (2, b'3'), (3, b'2')] {
|
||||
let archive = dir.path().join(format!("gpservice.log.{suffix}"));
|
||||
assert_eq!(fs::read(archive).unwrap(), vec![marker; ROTATE_BYTES + 1]);
|
||||
}
|
||||
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 5);
|
||||
assert_eq!(fs::read_to_string(dir.path().join("unrelated.log")).unwrap(), "keep");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_appends_and_accounts_for_existing_file_size() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("gpservice.log");
|
||||
fs::write(&path, "before restart\n").unwrap();
|
||||
{
|
||||
let mut log = writer(&path).unwrap();
|
||||
log.write_all(b"after restart\n").unwrap();
|
||||
}
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "before restart\nafter restart\n");
|
||||
|
||||
let entry = vec![b'x'; ROTATE_BYTES + 1];
|
||||
fs::write(&path, &entry).unwrap();
|
||||
{
|
||||
let mut log = writer(&path).unwrap();
|
||||
log.write_all(b"new entry\n").unwrap();
|
||||
}
|
||||
assert_eq!(fs::read(&path).unwrap(), b"new entry\n");
|
||||
assert_eq!(fs::read(dir.path().join("gpservice.log.1")).unwrap(), entry);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_log_path_remains_a_startup_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert!(writer(dir.path()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
//! Service Control Manager hosting; the GUI remains in the user's desktop session.
|
||||
mod admission;
|
||||
mod logging;
|
||||
use crate::{
|
||||
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
|
||||
};
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
service::vpn_state::VpnState,
|
||||
utils::{lock_file::LockFile, redact::Redaction},
|
||||
};
|
||||
use std::{
|
||||
ffi::OsString,
|
||||
io::Write,
|
||||
sync::{Arc, OnceLock, atomic::AtomicBool},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use windows_service::{
|
||||
define_windows_service,
|
||||
service::{ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType},
|
||||
service_control_handler::{self, ServiceControlHandlerResult, ServiceStatusHandle},
|
||||
service_dispatcher,
|
||||
};
|
||||
const NAME: &str = common::paths::SERVICE_NAME;
|
||||
static LOG_LEVEL: OnceLock<log::Level> = OnceLock::new();
|
||||
define_windows_service!(ffi_service_main, service_main);
|
||||
|
||||
pub(crate) fn dispatch(level: log::Level) -> anyhow::Result<()> {
|
||||
let _ = LOG_LEVEL.set(level);
|
||||
service_dispatcher::start(NAME, ffi_service_main).context("Start GP Connect through the Windows service manager")?;
|
||||
Ok(())
|
||||
}
|
||||
fn status(handle: &ServiceStatusHandle, state: ServiceState, failure: bool) -> windows_service::Result<()> {
|
||||
let running = state == ServiceState::Running;
|
||||
let pending = matches!(state, ServiceState::StartPending | ServiceState::StopPending);
|
||||
handle.set_service_status(ServiceStatus {
|
||||
service_type: ServiceType::OWN_PROCESS,
|
||||
current_state: state,
|
||||
controls_accepted: if running {
|
||||
ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN
|
||||
} else {
|
||||
ServiceControlAccept::empty()
|
||||
},
|
||||
exit_code: if failure {
|
||||
ServiceExitCode::ServiceSpecific(1)
|
||||
} else {
|
||||
ServiceExitCode::Win32(0)
|
||||
},
|
||||
checkpoint: u32::from(pending),
|
||||
wait_hint: if pending {
|
||||
Duration::from_secs(30)
|
||||
} else {
|
||||
Duration::ZERO
|
||||
},
|
||||
process_id: None,
|
||||
})
|
||||
}
|
||||
fn service_main(_arguments: Vec<OsString>) {
|
||||
let stop = CancellationToken::new();
|
||||
let requested = stop.clone();
|
||||
let handle = match service_control_handler::register(NAME, move |control| match control {
|
||||
ServiceControl::Stop | ServiceControl::Shutdown => {
|
||||
requested.cancel();
|
||||
ServiceControlHandlerResult::NoError
|
||||
}
|
||||
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
|
||||
_ => ServiceControlHandlerResult::NotImplemented,
|
||||
}) {
|
||||
Ok(handle) => handle,
|
||||
Err(_) => return,
|
||||
};
|
||||
let result = (|| -> anyhow::Result<()> {
|
||||
status(&handle, ServiceState::StartPending, false)?;
|
||||
ensure!(
|
||||
gpapi::windows::current_user_sid()? == "S-1-5-18",
|
||||
"GP Connect must run as LocalSystem"
|
||||
);
|
||||
let redaction = initialize_logger()?;
|
||||
log::info!("gpservice started: {}", crate::VERSION);
|
||||
crate::vpn_script::recover_network()?;
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build()?;
|
||||
runtime.block_on(run(&handle, stop, redaction))
|
||||
})();
|
||||
if let Err(error) = &result {
|
||||
log::error!("Windows service stopped: {error:#}");
|
||||
}
|
||||
let _ = status(&handle, ServiceState::Stopped, result.is_err());
|
||||
}
|
||||
fn initialize_logger() -> anyhow::Result<Arc<Redaction>> {
|
||||
let state = common::paths::service_lock_file();
|
||||
let directory = state.parent().context("Service state directory is unavailable")?;
|
||||
// The installer provisions these directories and their machine-wide ACLs.
|
||||
// Starting the daemon must not create a user-writable fallback location.
|
||||
ensure!(
|
||||
directory.is_dir() && common::paths::service_private_dir().is_dir(),
|
||||
"Install the GP Connect Windows service before starting it"
|
||||
);
|
||||
let writer = logging::writer(&directory.join("gpservice.log"))?;
|
||||
let redaction = Arc::new(Redaction::new());
|
||||
let filter = redaction.clone();
|
||||
let logger = env_logger::builder()
|
||||
.filter_level(log::LevelFilter::Trace)
|
||||
.target(env_logger::Target::Pipe(Box::new(writer)))
|
||||
.format(move |buffer, record| {
|
||||
writeln!(
|
||||
buffer,
|
||||
"[{} {:<5} {}] {}",
|
||||
buffer.timestamp(),
|
||||
record.level(),
|
||||
record.module_path().unwrap_or_default(),
|
||||
filter.redact_str(&record.args().to_string())
|
||||
)
|
||||
})
|
||||
.build();
|
||||
gpapi::logger::init_with_logger(*LOG_LEVEL.get().unwrap_or(&log::Level::Info), logger);
|
||||
Ok(redaction)
|
||||
}
|
||||
async fn run(handle: &ServiceStatusHandle, stop: CancellationToken, redaction: Arc<Redaction>) -> anyhow::Result<()> {
|
||||
let lock = Arc::new(LockFile::new(common::paths::service_lock_file(), std::process::id()));
|
||||
let registry = Arc::new(SessionRegistry::new(uuid::Uuid::new_v4()));
|
||||
let admission = admission::Admission::new(registry.clone())?;
|
||||
let (state, observed) = watch::channel(VpnState::Disconnected);
|
||||
let (mut vpn, lifecycle) = VpnTask::new(state, true, registry.clone());
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
lifecycle,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
redaction,
|
||||
false,
|
||||
true,
|
||||
));
|
||||
let websocket = WsServer::new(env!("CARGO_PKG_VERSION"), registry, dispatcher, observed, lock.clone());
|
||||
let service_cancel = websocket.cancel_token();
|
||||
let vpn_cancel = vpn.cancel_token();
|
||||
let (shutdown_tx, mut shutdown_rx) = mpsc::channel(4);
|
||||
let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
|
||||
let vpn_stop = service_cancel.clone();
|
||||
let vpn_handle = tokio::spawn(async move { vpn.start(vpn_stop).await });
|
||||
let websocket_shutdown = shutdown_tx.clone();
|
||||
let websocket_handle = tokio::spawn(async move { websocket.start(websocket_shutdown, ready_tx).await });
|
||||
ready_rx.await.context("Desktop protocol listener failed to start")?;
|
||||
let lease_cancel = service_cancel.clone();
|
||||
let admission_handle = tokio::spawn(async move {
|
||||
if let Err(error) = admission.run(lease_cancel).await {
|
||||
log::error!("Desktop admission stopped: {error:#}");
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
}
|
||||
});
|
||||
status(handle, ServiceState::Running, false)?;
|
||||
tokio::select! { _ = stop.cancelled() => {}, _ = shutdown_rx.recv() => {} }
|
||||
let _ = status(handle, ServiceState::StopPending, false);
|
||||
vpn_cancel.cancel();
|
||||
service_cancel.cancel();
|
||||
let _ = tokio::join!(vpn_handle, websocket_handle, admission_handle);
|
||||
lock.unlock()?;
|
||||
log::info!("gpservice stopped");
|
||||
Ok(())
|
||||
}
|
||||
@@ -410,48 +410,6 @@ async fn handle_client_message(
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::SetWindowsPatchInterest { enabled } = &request {
|
||||
#[cfg(windows)]
|
||||
ctx.patch_checks.set_interest(control.connection_id(), *enabled);
|
||||
#[cfg(not(windows))]
|
||||
let _ = enabled;
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::Accepted,
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
if let WsRequest::RefreshWindowsPatches { after } = &request {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let checks = ctx.patch_checks.clone();
|
||||
let control = control.clone();
|
||||
let after = Some(after.unwrap_or(0));
|
||||
tokio::spawn(async move {
|
||||
let success = checks.refresh(after).await;
|
||||
let result = if success {
|
||||
ServiceResult::Accepted
|
||||
} else {
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "Couldn’t check local updates.")
|
||||
};
|
||||
let _ = control.send(ConnectionCommand::Reply { id, result });
|
||||
});
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = after;
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Windows patch checks are unavailable"),
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::StoreEditedHipReportChunk(report) = request {
|
||||
let upload_id = report.upload_id.as_deref().and_then(|id| Uuid::parse_str(id).ok());
|
||||
let result = if report.upload_id.is_some() && upload_id.is_none() {
|
||||
@@ -493,7 +451,6 @@ async fn handle_client_message(
|
||||
offset: chunk.offset,
|
||||
xml,
|
||||
complete,
|
||||
windows_updates: None,
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP preview is unavailable"));
|
||||
@@ -510,7 +467,6 @@ async fn handle_client_message(
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
windows_updates: None,
|
||||
},
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"),
|
||||
},
|
||||
@@ -545,10 +501,6 @@ async fn handle_client_message(
|
||||
}
|
||||
|
||||
if let WsRequest::PreviewHipReport(preview) = request {
|
||||
#[cfg(windows)]
|
||||
if preview.client_os == gpapi::os_profile::ClientOs::Windows && matches!(preview.source, HipSource::Generated) {
|
||||
ctx.patch_checks.check_if_due();
|
||||
}
|
||||
let edited_report = if let HipSource::Edited { report_id } = &preview.source {
|
||||
let report_id = match Uuid::parse_str(report_id) {
|
||||
Ok(id) => id,
|
||||
|
||||
@@ -63,8 +63,6 @@ pub(crate) struct WsServerContext {
|
||||
state: Mutex<ServiceState>,
|
||||
handshake_slots: Arc<Semaphore>,
|
||||
pub(crate) hip_previews: crate::hip_preview::HipPreviews,
|
||||
#[cfg(windows)]
|
||||
pub(crate) patch_checks: Arc<crate::windows_patches::PatchChecks>,
|
||||
}
|
||||
|
||||
impl WsServerContext {
|
||||
@@ -77,8 +75,6 @@ impl WsServerContext {
|
||||
Self {
|
||||
product_version,
|
||||
registry,
|
||||
#[cfg(windows)]
|
||||
patch_checks: dispatcher.patch_checks(),
|
||||
dispatcher,
|
||||
state: Mutex::new(ServiceState {
|
||||
revision: 0,
|
||||
@@ -187,8 +183,6 @@ impl WsServerContext {
|
||||
|
||||
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
||||
self.registry.disconnect_if_current(session_id, generation);
|
||||
#[cfg(windows)]
|
||||
self.patch_checks.set_interest(connection_id, false);
|
||||
let mut state = self.state.lock().await;
|
||||
state.connections.remove(&connection_id);
|
||||
state.refresh_demand();
|
||||
@@ -350,7 +344,6 @@ impl WsServer {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub fn context(&self) -> Arc<WsServerContext> {
|
||||
Arc::clone(&self.ctx)
|
||||
}
|
||||
@@ -370,12 +363,6 @@ impl WsServer {
|
||||
};
|
||||
let _ = ready_tx.send(());
|
||||
|
||||
#[cfg(windows)]
|
||||
let patch_task = {
|
||||
let checks = self.ctx.patch_checks.clone();
|
||||
let stop = self.cancel_token.clone();
|
||||
tokio::spawn(async move { checks.run(stop).await })
|
||||
};
|
||||
tokio::select! {
|
||||
_ = watch_vpn_state(self.vpn_state_rx.clone(), Arc::clone(&self.ctx)) => {
|
||||
info!("VPN state watch task completed");
|
||||
@@ -390,9 +377,6 @@ impl WsServer {
|
||||
info!("WS server cancelled");
|
||||
}
|
||||
}
|
||||
self.cancel_token.cancel();
|
||||
#[cfg(windows)]
|
||||
let _ = patch_task.await;
|
||||
self.ctx.hip_previews.shutdown().await;
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
}
|
||||
|
||||
@@ -1,45 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## 3.5.0
|
||||
|
||||
### Added
|
||||
|
||||
- Added Windows x64 and ARM64 support, with signed installers, built-in browser sign-in, desktop notifications, and in-app updates.
|
||||
- Added a Windows system tray flyout, native HIP reports, and background Windows Update checks.
|
||||
- Added a Compatibility Graphics option on Linux for display problems.
|
||||
|
||||
### Improved
|
||||
|
||||
- Refined Windows settings, controls, icons, and window behavior.
|
||||
- Made HIP Preview faster on Windows and polished connection details across platforms.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed Windows keyboard activation, menu dismissal, dropdown feedback, and scrollbars.
|
||||
- Restored focus to GP Connect after browser sign-in on Windows.
|
||||
- Improved recovery from temporary sign-in and license verification failures.
|
||||
- Corrected native HIP host information on Windows, macOS, Linux, and BSD.
|
||||
- Kept sensitive authentication and tunnel data out of debug logs.
|
||||
- Removed unnecessary Linux and FreeBSD package dependencies.
|
||||
|
||||
## 3.4.0
|
||||
|
||||
### Added
|
||||
|
||||
- Added gateway selection and switching directly from the system tray or macOS menu bar.
|
||||
|
||||
### Improved
|
||||
|
||||
- Added a Retry Activation action to recover from temporary license activation failures without re-entering the key.
|
||||
- Made sign-in prompts and connection errors visible when connecting or switching gateways from the tray.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed a Native Shell crash after license activation.
|
||||
- Fixed the macOS Tauri interface opening unexpectedly after signing in from the tray while the main window was hidden.
|
||||
- Fixed the Native Shell update button text becoming unreadable when pressed.
|
||||
- Fixed Linux Nix builds using unavailable WebKitGTK dependencies.
|
||||
|
||||
## 3.3.1
|
||||
|
||||
### Improved
|
||||
|
||||
+1
-17
@@ -20,6 +20,7 @@ browser-launcher = { path = "../browser-launcher", default-features = false, fea
|
||||
tiny_http = { version = "0.12", optional = true }
|
||||
tempfile = { workspace = true, optional = true }
|
||||
uuid = { version = "1", optional = true, features = ["v4"] }
|
||||
uzers = { workspace = true, optional = true }
|
||||
|
||||
# Webview auth dependencies
|
||||
tauri = { workspace = true, optional = true }
|
||||
@@ -27,7 +28,6 @@ regex = { workspace = true, optional = true }
|
||||
tokio-util = { workspace = true, optional = true }
|
||||
html-escape = { version = "0.3", optional = true }
|
||||
url = { workspace = true, optional = true }
|
||||
serde_json = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
|
||||
webkit2gtk = { version = "2", optional = true }
|
||||
@@ -60,9 +60,6 @@ webview-auth = [
|
||||
"dep:tokio-util",
|
||||
"dep:html-escape",
|
||||
"dep:url",
|
||||
"dep:serde_json",
|
||||
"dep:webview2-com",
|
||||
"dep:windows",
|
||||
"dep:gtk",
|
||||
"dep:webkit2gtk",
|
||||
"dep:block2",
|
||||
@@ -97,16 +94,3 @@ release-devtools = ["webview-auth", "tauri/devtools"]
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
uzers = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Pipes", "Win32_UI_WindowsAndMessaging"] }
|
||||
# Child webviews let the Windows host own layout beside native controls.
|
||||
tauri = { workspace = true, optional = true, features = ["unstable"] }
|
||||
webview2-com = { version = "0.39", optional = true }
|
||||
windows = { version = "0.62", optional = true, features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_Com", "Win32_UI_Controls", "Win32_UI_HiDpi", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }
|
||||
dunce = "1"
|
||||
winreg = "0.55"
|
||||
common = { path = "../common" }
|
||||
@@ -3,6 +3,7 @@ use std::{
|
||||
io::ErrorKind,
|
||||
os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
@@ -13,9 +14,16 @@ use tokio::{
|
||||
time::timeout,
|
||||
};
|
||||
|
||||
mod protocol;
|
||||
pub use protocol::validate_auth_callback;
|
||||
use protocol::*;
|
||||
const CALLBACK_SCHEME: &str = "globalprotectcallback";
|
||||
const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC";
|
||||
const PROTOCOL_VERSION: u8 = 1;
|
||||
const MAX_CALLBACK_SIZE: usize = 1024 * 1024;
|
||||
const IO_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
// Acceptance acknowledges delivery, including an authentication failure.
|
||||
const STATUS_ACCEPTED: u8 = 0;
|
||||
const STATUS_INVALID_CALLBACK: u8 = 1;
|
||||
const STATUS_UNSUPPORTED_VERSION: u8 = 2;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
@@ -224,9 +232,62 @@ fn remove_stale_socket(socket_path: &Path) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
if callback.len() > MAX_CALLBACK_SIZE {
|
||||
bail!("Authentication callback exceeds the maximum supported size");
|
||||
}
|
||||
|
||||
let Some((scheme, data)) = callback.split_once(':') else {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
};
|
||||
if scheme != CALLBACK_SCHEME || data.is_empty() {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
enum CallbackReadError {
|
||||
UnsupportedVersion,
|
||||
Invalid,
|
||||
Io,
|
||||
}
|
||||
|
||||
async fn read_callback(stream: &mut UnixStream) -> Result<String, CallbackReadError> {
|
||||
let mut magic = [0_u8; 4];
|
||||
stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?;
|
||||
if &magic != PROTOCOL_MAGIC {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?;
|
||||
if version != PROTOCOL_VERSION {
|
||||
return Err(CallbackReadError::UnsupportedVersion);
|
||||
}
|
||||
|
||||
let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize;
|
||||
if length == 0 || length > MAX_CALLBACK_SIZE {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let mut payload = vec![0; length];
|
||||
stream
|
||||
.read_exact(&mut payload)
|
||||
.await
|
||||
.map_err(|_| CallbackReadError::Io)?;
|
||||
let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?;
|
||||
validate_auth_callback(&callback).map_err(|_| CallbackReadError::Invalid)?;
|
||||
Ok(callback)
|
||||
}
|
||||
|
||||
async fn write_response(stream: &mut UnixStream, status: u8) -> anyhow::Result<()> {
|
||||
stream.write_u8(PROTOCOL_VERSION).await?;
|
||||
stream.write_u8(status).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
use tempfile::tempdir;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
//! Bounded authentication callback wire format, shared by local transports.
|
||||
use anyhow::bail;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
pub(super) const CALLBACK_SCHEME: &str = "globalprotectcallback";
|
||||
pub(super) const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC";
|
||||
pub(super) const PROTOCOL_VERSION: u8 = 1;
|
||||
pub(super) const MAX_CALLBACK_SIZE: usize = 1024 * 1024;
|
||||
pub(super) const IO_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
// Acceptance acknowledges delivery, including an authentication failure.
|
||||
pub(super) const STATUS_ACCEPTED: u8 = 0;
|
||||
pub(super) const STATUS_INVALID_CALLBACK: u8 = 1;
|
||||
pub(super) const STATUS_UNSUPPORTED_VERSION: u8 = 2;
|
||||
|
||||
pub fn validate_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
if callback.len() > MAX_CALLBACK_SIZE {
|
||||
bail!("Authentication callback exceeds the maximum supported size");
|
||||
}
|
||||
|
||||
let Some((scheme, data)) = callback.split_once(':') else {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
};
|
||||
if scheme != CALLBACK_SCHEME || data.is_empty() {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) enum CallbackReadError {
|
||||
UnsupportedVersion,
|
||||
Invalid,
|
||||
Io,
|
||||
}
|
||||
|
||||
pub(super) async fn read_callback(
|
||||
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
|
||||
) -> Result<String, CallbackReadError> {
|
||||
let mut magic = [0_u8; 4];
|
||||
stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?;
|
||||
if &magic != PROTOCOL_MAGIC {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?;
|
||||
if version != PROTOCOL_VERSION {
|
||||
return Err(CallbackReadError::UnsupportedVersion);
|
||||
}
|
||||
|
||||
let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize;
|
||||
if length == 0 || length > MAX_CALLBACK_SIZE {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let mut payload = vec![0; length];
|
||||
stream
|
||||
.read_exact(&mut payload)
|
||||
.await
|
||||
.map_err(|_| CallbackReadError::Io)?;
|
||||
let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?;
|
||||
validate_auth_callback(&callback).map_err(|_| CallbackReadError::Invalid)?;
|
||||
Ok(callback)
|
||||
}
|
||||
|
||||
pub(super) async fn write_response(
|
||||
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
|
||||
status: u8,
|
||||
) -> anyhow::Result<()> {
|
||||
stream.write_u8(PROTOCOL_VERSION).await?;
|
||||
stream.write_u8(status).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
//! Per-user Windows named pipe for browser authentication callbacks.
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
|
||||
use std::{io, os::windows::io::AsRawHandle};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer},
|
||||
time::timeout,
|
||||
};
|
||||
#[path = "protocol.rs"]
|
||||
mod protocol;
|
||||
pub use protocol::validate_auth_callback;
|
||||
use protocol::*;
|
||||
use windows_sys::Win32::{
|
||||
System::Pipes::GetNamedPipeServerProcessId, UI::WindowsAndMessaging::AllowSetForegroundWindow,
|
||||
};
|
||||
|
||||
pub struct AuthCallbackReceiver {
|
||||
listener: NamedPipeServer,
|
||||
}
|
||||
impl AuthCallbackReceiver {
|
||||
pub fn bind() -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
listener: gpapi::windows::create_user_pipe(&pipe_name()?, true)
|
||||
.context("Another browser authentication is already waiting")?,
|
||||
})
|
||||
}
|
||||
pub async fn receive(mut self) -> anyhow::Result<SamlAuthData> {
|
||||
loop {
|
||||
self.listener.connect().await?;
|
||||
let mut stream = &mut self.listener;
|
||||
let callback = timeout(IO_TIMEOUT, read_callback(&mut stream)).await;
|
||||
let result = match callback {
|
||||
Ok(Ok(callback)) => match SamlAuthData::from_gpcallback(&callback) {
|
||||
Ok(data) => {
|
||||
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
|
||||
Some(Ok(data))
|
||||
}
|
||||
Err(error @ AuthDataParseError::AuthenticationFailed(_)) => {
|
||||
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
|
||||
Some(Err(error.into()))
|
||||
}
|
||||
Err(_) => {
|
||||
let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await;
|
||||
None
|
||||
}
|
||||
},
|
||||
Ok(Err(CallbackReadError::UnsupportedVersion)) => {
|
||||
let _ = write_response(&mut stream, STATUS_UNSUPPORTED_VERSION).await;
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// DisconnectNamedPipe discards unread response bytes. Wait for the client
|
||||
// to confirm it consumed the response before disconnecting this instance.
|
||||
let _ = timeout(IO_TIMEOUT, stream.read_u8()).await;
|
||||
self.listener.disconnect()?;
|
||||
if let Some(result) = result {
|
||||
if let Err(error) = delegate_foreground_to_parent() {
|
||||
log::debug!("Could not delegate authentication foreground permission to the parent: {error}");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn pipe_name() -> anyhow::Result<String> {
|
||||
Ok(format!(
|
||||
r"\\.\pipe\GPConnect.Auth.{}",
|
||||
gpapi::windows::current_user_sid()?
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
validate_auth_callback(callback)?;
|
||||
timeout(IO_TIMEOUT, async {
|
||||
let mut stream = ClientOptions::new()
|
||||
.open(pipe_name()?)
|
||||
.context("No external-browser authentication is waiting for a callback")?;
|
||||
stream.write_all(PROTOCOL_MAGIC).await?;
|
||||
stream.write_u8(PROTOCOL_VERSION).await?;
|
||||
stream.write_u32(callback.len() as u32).await?;
|
||||
stream.write_all(callback.as_bytes()).await?;
|
||||
let version = stream.read_u8().await?;
|
||||
let status = stream.read_u8().await?;
|
||||
// The receiver waits for our acknowledgement before returning to its caller.
|
||||
if version == PROTOCOL_VERSION && status == STATUS_ACCEPTED {
|
||||
if let Err(error) = delegate_foreground_to_receiver(&stream) {
|
||||
log::debug!("Could not delegate browser foreground permission to the authenticator: {error}");
|
||||
}
|
||||
}
|
||||
stream.write_u8(status).await?;
|
||||
anyhow::ensure!(
|
||||
version == PROTOCOL_VERSION,
|
||||
"Authentication callback protocol version mismatch"
|
||||
);
|
||||
match status {
|
||||
STATUS_ACCEPTED => Ok(()),
|
||||
STATUS_INVALID_CALLBACK => bail!("Authentication callback was rejected"),
|
||||
_ => bail!("Authentication callback protocol is unsupported"),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("Timed out forwarding the authentication callback")?
|
||||
}
|
||||
|
||||
fn delegate_foreground_to_receiver(stream: &NamedPipeClient) -> io::Result<()> {
|
||||
let mut process_id = 0;
|
||||
unsafe {
|
||||
if GetNamedPipeServerProcessId(stream.as_raw_handle(), &mut process_id) == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
}
|
||||
allow_foreground(process_id)
|
||||
}
|
||||
|
||||
fn delegate_foreground_to_parent() -> anyhow::Result<()> {
|
||||
let Some(process_id) = std::env::var_os(gpapi::process::auth_launcher::AUTH_PARENT_PROCESS_ID_ENV) else {
|
||||
return Ok(());
|
||||
};
|
||||
let process_id = process_id.to_string_lossy().parse::<u32>()?;
|
||||
allow_foreground(process_id)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn allow_foreground(process_id: u32) -> io::Result<()> {
|
||||
if unsafe { AllowSetForegroundWindow(process_id) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
|
||||
use winreg::{RegKey, enums::HKEY_CURRENT_USER};
|
||||
let executable = common::binary_paths::gpauth();
|
||||
anyhow::ensure!(executable.is_file(), "The authentication helper is missing");
|
||||
let root = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let (scheme, _) = root.create_subkey(r"Software\Classes\globalprotectcallback")?;
|
||||
scheme.set_value("", &"URL:GlobalProtect authentication callback")?;
|
||||
scheme.set_value("URL Protocol", &"")?;
|
||||
let (application, _) = scheme.create_subkey("Application")?;
|
||||
application.set_value("ApplicationName", &"GP Connect Login")?;
|
||||
let (command, _) = scheme.create_subkey(r"shell\open\command")?;
|
||||
// URL association activation requires a shell path, not Rust's verbatim
|
||||
// canonical path (\\?\C:\...), even though CreateProcess accepts both.
|
||||
let executable = dunce::simplified(&executable);
|
||||
command.set_value("", &format!("\"{}\" auth-callback \"%1\"", executable.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn forwards_browser_callback_over_private_windows_pipe() {
|
||||
let receiver = AuthCallbackReceiver::bind().unwrap();
|
||||
// The first-instance flag preserves one pending browser authentication per user.
|
||||
assert!(AuthCallbackReceiver::bind().is_err());
|
||||
let sender = tokio::spawn(async {
|
||||
forward_auth_callback("globalprotectcallback:cas-as=1&[email protected]&token=test-token").await
|
||||
});
|
||||
let data = timeout(std::time::Duration::from_secs(5), receiver.receive())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
sender.await.unwrap().unwrap();
|
||||
assert_eq!(data.username(), "[email protected]");
|
||||
assert_eq!(data.token(), Some("test-token"));
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ use gpapi::{
|
||||
mod browser;
|
||||
|
||||
#[cfg(feature = "browser-auth")]
|
||||
#[cfg_attr(windows, path = "callback/windows.rs")]
|
||||
mod callback;
|
||||
|
||||
#[cfg(feature = "browser-auth")]
|
||||
|
||||
@@ -12,17 +12,12 @@ mod platform_impl;
|
||||
#[path = "webview/macos.rs"]
|
||||
mod platform_impl;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[path = "webview/windows.rs"]
|
||||
mod platform_impl;
|
||||
|
||||
#[cfg(not(any(
|
||||
windows,
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
compile_error!("webview-auth is only supported on Windows, macOS and GTK/WebKitGTK Unix targets");
|
||||
compile_error!("webview-auth is only supported on macOS and GTK/WebKitGTK Unix targets");
|
||||
|
||||
pub use webview_auth::{WebviewAuthenticator, apply_auth_theme};
|
||||
@@ -9,7 +9,7 @@ use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum AuthDataLocation {
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
Headers,
|
||||
Body,
|
||||
}
|
||||
@@ -155,7 +155,7 @@ impl AuthMessenger {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader, generation: u64) {
|
||||
use log::warn;
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ impl RecoveryStatus {
|
||||
Self::Hidden => "",
|
||||
Self::Restarting => "Restarting sign-in…",
|
||||
Self::Loading => "Loading sign-in…",
|
||||
Self::Failed => "Couldn’t load sign-in.",
|
||||
Self::Failed => "Couldn’t restart sign-in.",
|
||||
Self::Rejected => "Sign-in wasn’t completed.",
|
||||
Self::Tls {
|
||||
reason: TlsFailureReason::Handshake,
|
||||
@@ -55,7 +55,6 @@ impl RecoveryStatus {
|
||||
matches!(self, Self::Hidden | Self::Loading | Self::CertificateBypassed)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn is_busy(self) -> bool {
|
||||
matches!(self, Self::Restarting | Self::Loading)
|
||||
}
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum TlsFailureReason {
|
||||
Expired,
|
||||
#[cfg(not(windows))]
|
||||
NotYetValid,
|
||||
#[cfg(not(windows))]
|
||||
Untrusted,
|
||||
HostnameMismatch,
|
||||
InvalidCertificate,
|
||||
@@ -19,9 +17,7 @@ impl TlsFailureReason {
|
||||
pub fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::Expired => "The certificate has expired.",
|
||||
#[cfg(not(windows))]
|
||||
Self::NotYetValid => "The certificate is not valid yet.",
|
||||
#[cfg(not(windows))]
|
||||
Self::Untrusted => "The certificate was issued by an untrusted authority.",
|
||||
Self::HostnameMismatch => "The certificate does not match this server’s hostname.",
|
||||
Self::InvalidCertificate => "The server’s certificate could not be verified.",
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::bail;
|
||||
#[cfg(not(windows))]
|
||||
use gpapi::utils::window::get_title_bar_height;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use gpapi::utils::window::{WindowTypeHint, set_window_type_hint};
|
||||
use gpapi::{
|
||||
@@ -10,51 +8,24 @@ use gpapi::{
|
||||
error::ServerTlsError,
|
||||
gp_params::GpParams,
|
||||
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
|
||||
utils::redact::redact_uri,
|
||||
utils::{redact::redact_uri, window::get_title_bar_height},
|
||||
};
|
||||
use log::{info, warn};
|
||||
#[cfg(target_os = "macos")]
|
||||
use tauri::Manager;
|
||||
#[cfg(not(windows))]
|
||||
use tauri::WebviewUrl;
|
||||
use tauri::{AppHandle, WindowEvent};
|
||||
use tauri::{AppHandle, WebviewUrl, WebviewWindow, WindowEvent};
|
||||
use tokio::{sync::oneshot, time};
|
||||
|
||||
use crate::auth_prelogin;
|
||||
|
||||
#[cfg(not(windows))]
|
||||
use super::address_bar::TOOLBAR_HEIGHT;
|
||||
use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
|
||||
use super::recovery::{Recovery, RecoveryStatus, RetryPlan, RetrySource, RetryTiming};
|
||||
|
||||
#[cfg(not(windows))]
|
||||
type AuthWindow = tauri::WebviewWindow;
|
||||
#[cfg(windows)]
|
||||
use super::platform_impl::{AuthWindow, create_auth_window};
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn create_auth_window(app: &AppHandle, title: &str, theme: Option<tauri::Theme>) -> anyhow::Result<AuthWindow> {
|
||||
let builder = AuthWindow::builder(app, "auth_window", WebviewUrl::default())
|
||||
.title(title)
|
||||
.theme(theme)
|
||||
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
let builder = builder.on_navigation(super::platform_impl::open_okta_verify);
|
||||
Ok(
|
||||
builder
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height() + TOOLBAR_HEIGHT)
|
||||
.min_inner_size(400.0, 300.0)
|
||||
.focused(true)
|
||||
.visible(false)
|
||||
.center()
|
||||
.build()?,
|
||||
)
|
||||
}
|
||||
|
||||
const RESTART_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
pub(super) trait PlatformWebviewExt {
|
||||
fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
|
||||
pub trait PlatformWebviewExt {
|
||||
fn install_auth_controls(&self, window: &WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()>;
|
||||
|
||||
@@ -83,7 +54,7 @@ pub(super) trait PlatformWebviewExt {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub trait GetHeader {
|
||||
fn get_header(&self, key: &str) -> Option<String>;
|
||||
}
|
||||
@@ -154,7 +125,19 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
|
||||
let auth_messenger = Arc::new(AuthMessenger::new());
|
||||
let auth_window = create_auth_window(app_handle, self.window_title, native_theme(self.window_theme))?;
|
||||
let auth_window_builder = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
|
||||
.title(self.window_title)
|
||||
.theme(native_theme(self.window_theme))
|
||||
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
let auth_window_builder = auth_window_builder.on_navigation(super::platform_impl::open_okta_verify);
|
||||
let auth_window = auth_window_builder
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height() + TOOLBAR_HEIGHT)
|
||||
.min_inner_size(400.0, 300.0)
|
||||
.focused(true)
|
||||
.visible(false)
|
||||
.center()
|
||||
.build()?;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?;
|
||||
@@ -187,7 +170,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
async fn wait_for_auth(
|
||||
&self,
|
||||
auth_window: &AuthWindow,
|
||||
auth_window: &WebviewWindow,
|
||||
auth_messenger: Arc<AuthMessenger>,
|
||||
) -> anyhow::Result<SamlAuthData> {
|
||||
let mut recovery = Recovery::default();
|
||||
@@ -327,16 +310,13 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
async fn setup_auth_window(
|
||||
&self,
|
||||
auth_window: &AuthWindow,
|
||||
auth_window: &WebviewWindow,
|
||||
auth_messenger: Arc<AuthMessenger>,
|
||||
) -> anyhow::Result<()> {
|
||||
info!("Setting up auth window...");
|
||||
|
||||
if self.clean {
|
||||
info!("Clearing all browsing data...");
|
||||
#[cfg(windows)]
|
||||
super::platform_impl::clear_browsing_data(auth_window).await?;
|
||||
#[cfg(not(windows))]
|
||||
auth_window.clear_all_browsing_data()?;
|
||||
}
|
||||
|
||||
@@ -381,7 +361,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_not_found(&self, auth_window: &AuthWindow, auth_messenger: &Arc<AuthMessenger>) {
|
||||
fn handle_not_found(&self, auth_window: &WebviewWindow, auth_messenger: &Arc<AuthMessenger>) {
|
||||
let visible = auth_window.is_visible().unwrap_or(false);
|
||||
if visible {
|
||||
return;
|
||||
@@ -390,7 +370,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
auth_messenger.schedule_raise_window(2);
|
||||
}
|
||||
|
||||
fn update_recovery(&self, auth_window: &AuthWindow, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
fn update_recovery(&self, auth_window: &WebviewWindow, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
if status != RecoveryStatus::Hidden {
|
||||
self.raise_window(auth_window);
|
||||
}
|
||||
@@ -417,7 +397,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
fn load_restarted_sign_in(
|
||||
&self,
|
||||
auth_window: &AuthWindow,
|
||||
auth_window: &WebviewWindow,
|
||||
messenger: &Arc<AuthMessenger>,
|
||||
auth_request: String,
|
||||
) -> anyhow::Result<()> {
|
||||
@@ -435,7 +415,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn raise_window(&self, auth_window: &AuthWindow) {
|
||||
fn raise_window(&self, auth_window: &WebviewWindow) {
|
||||
let visible = auth_window.is_visible().unwrap_or(false);
|
||||
if visible {
|
||||
return;
|
||||
|
||||
@@ -1,380 +0,0 @@
|
||||
//! WebView2 authentication. All COM objects and native controls stay on the UI thread.
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::HashMap,
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use super::{
|
||||
auth_messenger::{AuthDataLocation, AuthError, AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
webview_auth::{GetHeader, PlatformWebviewExt},
|
||||
};
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::auth::SamlAuthData;
|
||||
use tauri::{
|
||||
AppHandle, LogicalPosition, Webview, WebviewBuilder, WebviewUrl, Window, WindowBuilder, webview::PlatformWebview,
|
||||
};
|
||||
use webview2_com::{
|
||||
ClearBrowsingDataCompletedHandler, CoTaskMemPWSTR, DOMContentLoadedEventHandler, ExecuteScriptCompletedHandler,
|
||||
Microsoft::Web::WebView2::Win32::*, NavigationCompletedEventHandler, NavigationStartingEventHandler,
|
||||
SourceChangedEventHandler, WebResourceResponseReceivedEventHandler,
|
||||
};
|
||||
use windows::core::{BOOL, HSTRING, Interface, PWSTR};
|
||||
|
||||
#[path = "windows/controls.rs"]
|
||||
mod controls;
|
||||
#[path = "windows/tls.rs"]
|
||||
mod tls;
|
||||
|
||||
/// Windows hosts native chrome and a manually sized child webview in one window.
|
||||
/// Host-owned child bounds keep the page surface below the native controls
|
||||
/// throughout live resizing.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct AuthWindow {
|
||||
window: Window,
|
||||
webview: Webview,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for AuthWindow {
|
||||
type Target = Window;
|
||||
fn deref(&self) -> &Window {
|
||||
&self.window
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthWindow {
|
||||
pub(super) fn with_webview(&self, callback: impl FnOnce(PlatformWebview) + Send + 'static) -> tauri::Result<()> {
|
||||
self.webview.with_webview(callback)
|
||||
}
|
||||
}
|
||||
|
||||
impl gpapi::utils::window::WindowExt for AuthWindow {
|
||||
fn raise(&self) -> anyhow::Result<()> {
|
||||
self.window.show()?;
|
||||
self.window.set_focus()?;
|
||||
self.webview.set_focus()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn create_auth_window(
|
||||
app: &AppHandle,
|
||||
title: &str,
|
||||
theme: Option<tauri::Theme>,
|
||||
) -> anyhow::Result<AuthWindow> {
|
||||
let window = WindowBuilder::new(app, "auth_window")
|
||||
.title(title)
|
||||
.theme(theme)
|
||||
.inner_size(900.0, 650.0 + super::address_bar::TOOLBAR_HEIGHT)
|
||||
.min_inner_size(400.0, 300.0)
|
||||
.focused(true)
|
||||
.visible(false)
|
||||
.center()
|
||||
.build()?;
|
||||
let webview = window.add_child(
|
||||
WebviewBuilder::new("auth_webview", WebviewUrl::default())
|
||||
.devtools(cfg!(any(debug_assertions, feature = "release-devtools"))),
|
||||
LogicalPosition::new(0.0, 0.0),
|
||||
window.inner_size()?,
|
||||
)?;
|
||||
Ok(AuthWindow { window, webview })
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static STATES: RefCell<HashMap<usize, Rc<State>>> = RefCell::default();
|
||||
}
|
||||
|
||||
struct State {
|
||||
core: ICoreWebView2,
|
||||
controller: ICoreWebView2Controller,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
controls: controls::Controls,
|
||||
pending: Cell<Option<u64>>,
|
||||
navigations: RefCell<HashMap<u64, u64>>,
|
||||
document: RefCell<(String, u64)>,
|
||||
tls: RefCell<tls::Policy>,
|
||||
}
|
||||
|
||||
fn text(get: impl FnOnce(*mut PWSTR) -> windows::core::Result<()>) -> windows::core::Result<String> {
|
||||
let mut value = PWSTR::null();
|
||||
let result = get(&mut value);
|
||||
let value = CoTaskMemPWSTR::from(value);
|
||||
result?;
|
||||
Ok(value.to_string())
|
||||
}
|
||||
|
||||
fn state(webview: &PlatformWebview) -> anyhow::Result<Rc<State>> {
|
||||
let core = unsafe { webview.controller().CoreWebView2()? };
|
||||
STATES
|
||||
.with_borrow(|states| states.get(&(core.as_raw() as usize)).cloned())
|
||||
.context("Authentication controls are unavailable")
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn read_html(&self, generation: u64) -> windows::core::Result<()> {
|
||||
if generation != self.messenger.generation() {
|
||||
return Ok(());
|
||||
}
|
||||
let messenger = Arc::clone(&self.messenger);
|
||||
unsafe {
|
||||
self.core.ExecuteScript(
|
||||
&HSTRING::from("document.documentElement.outerHTML"),
|
||||
&ExecuteScriptCompletedHandler::create(Box::new(move |result, json| {
|
||||
result?;
|
||||
if let Ok(html) = serde_json::from_str::<String>(&json) {
|
||||
messenger.read_from_html(&html, generation);
|
||||
}
|
||||
Ok(())
|
||||
})),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn listen(self: &Rc<Self>) -> windows::core::Result<()> {
|
||||
let mut token = 0;
|
||||
let weak = Rc::downgrade(self);
|
||||
let starting = NavigationStartingEventHandler::create(Box::new(move |_, args| {
|
||||
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
|
||||
return Ok(());
|
||||
};
|
||||
unsafe {
|
||||
let mut id = 0;
|
||||
args.NavigationId(&mut id)?;
|
||||
let generation = *state
|
||||
.navigations
|
||||
.borrow_mut()
|
||||
.entry(id)
|
||||
.or_insert_with(|| state.pending.take().unwrap_or_else(|| state.messenger.generation()));
|
||||
let uri = text(|p| args.Uri(p))?;
|
||||
if uri.starts_with("globalprotectcallback:") {
|
||||
args.SetCancel(true)?;
|
||||
match SamlAuthData::from_gpcallback(&uri) {
|
||||
Ok(data) => state
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::Data(generation, data, AuthDataLocation::Body)),
|
||||
Err(error) => state
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::Error(generation, AuthError::invalid_from_body(error.into()))),
|
||||
}
|
||||
} else if generation == state.messenger.generation() {
|
||||
*state.document.borrow_mut() = (uri, generation);
|
||||
state.messenger.cancel_raise_window();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
unsafe {
|
||||
self.core.add_NavigationStarting(&starting, &mut token)?;
|
||||
}
|
||||
|
||||
let weak = Rc::downgrade(self);
|
||||
let loaded = DOMContentLoadedEventHandler::create(Box::new(move |_, args| {
|
||||
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut id = 0;
|
||||
unsafe {
|
||||
args.NavigationId(&mut id)?;
|
||||
}
|
||||
let generation = state.navigations.borrow().get(&id).copied();
|
||||
if let Some(generation) = generation {
|
||||
state.read_html(generation)?;
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
unsafe {
|
||||
self
|
||||
.core
|
||||
.cast::<ICoreWebView2_2>()?
|
||||
.add_DOMContentLoaded(&loaded, &mut token)?;
|
||||
}
|
||||
|
||||
let weak = Rc::downgrade(self);
|
||||
let completed = NavigationCompletedEventHandler::create(Box::new(move |_, args| {
|
||||
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
|
||||
return Ok(());
|
||||
};
|
||||
unsafe {
|
||||
let mut id = 0;
|
||||
args.NavigationId(&mut id)?;
|
||||
let Some(generation) = state.navigations.borrow_mut().remove(&id) else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut success = BOOL(0);
|
||||
args.IsSuccess(&mut success)?;
|
||||
if success.as_bool() {
|
||||
state.read_html(generation)?;
|
||||
state.messenger.send_auth_event(AuthEvent::PageLoaded(generation));
|
||||
} else {
|
||||
let mut error = COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN;
|
||||
args.WebErrorStatus(&mut error)?;
|
||||
if error != COREWEBVIEW2_WEB_ERROR_STATUS_OPERATION_CANCELED {
|
||||
state.messenger.send_auth_event(AuthEvent::Error(
|
||||
generation,
|
||||
AuthError::LoadFailed(anyhow::anyhow!("WebView2 navigation failed ({})", error.0)),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
unsafe {
|
||||
self.core.add_NavigationCompleted(&completed, &mut token)?;
|
||||
}
|
||||
|
||||
let weak = Rc::downgrade(self);
|
||||
let source = SourceChangedEventHandler::create(Box::new(move |_, _| {
|
||||
if let Some(state) = weak.upgrade() {
|
||||
let uri = unsafe { text(|p| state.core.Source(p))? };
|
||||
state.controls.set_address(&uri)?;
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
unsafe {
|
||||
self.core.add_SourceChanged(&source, &mut token)?;
|
||||
}
|
||||
|
||||
let weak = Rc::downgrade(self);
|
||||
let response = WebResourceResponseReceivedEventHandler::create(Box::new(move |_, args| {
|
||||
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
|
||||
return Ok(());
|
||||
};
|
||||
unsafe {
|
||||
let uri = text(|p| args.Request()?.Uri(p))?;
|
||||
let (document, generation) = state.document.borrow().clone();
|
||||
// Subresources must not supply authentication credentials for the page.
|
||||
if uri == document && generation == state.messenger.generation() {
|
||||
state
|
||||
.messenger
|
||||
.read_from_response(&Headers(args.Response()?.Headers()?), generation);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
unsafe {
|
||||
self
|
||||
.core
|
||||
.cast::<ICoreWebView2_2>()?
|
||||
.add_WebResourceResponseReceived(&response, &mut token)?;
|
||||
}
|
||||
tls::install(self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Headers(ICoreWebView2HttpResponseHeaders);
|
||||
impl GetHeader for Headers {
|
||||
fn get_header(&self, key: &str) -> Option<String> {
|
||||
unsafe { text(|p| self.0.GetHeader(&HSTRING::from(key), p)).ok() }
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformWebviewExt for PlatformWebview {
|
||||
fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let controller = self.controller();
|
||||
let core = unsafe { controller.CoreWebView2()? };
|
||||
let key = core.as_raw() as usize;
|
||||
let controls = controls::Controls::new(window, &controller, key)?;
|
||||
let state = Rc::new(State {
|
||||
core,
|
||||
controller,
|
||||
messenger,
|
||||
controls,
|
||||
pending: Cell::new(None),
|
||||
navigations: RefCell::default(),
|
||||
document: RefCell::new((String::new(), 0)),
|
||||
tls: RefCell::default(),
|
||||
});
|
||||
STATES.with_borrow_mut(|states| states.insert(key, Rc::clone(&state)));
|
||||
state.listen()?;
|
||||
state.controls.layout(&state)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
let state = state(self)?;
|
||||
state.controls.update(&state, status)?;
|
||||
Ok(())
|
||||
}
|
||||
fn stop_loading(&self) {
|
||||
let _ = unsafe { self.controller().CoreWebView2().and_then(|wv| wv.Stop()) };
|
||||
}
|
||||
fn confirm_tls_exception(&self) -> anyhow::Result<()> {
|
||||
tls::confirm(state(self)?.as_ref())
|
||||
}
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
|
||||
state(self)?.tls.borrow_mut().ignore_errors = true;
|
||||
Ok(())
|
||||
}
|
||||
fn user_agent(&self) -> anyhow::Result<String> {
|
||||
unsafe {
|
||||
Ok(text(|p| {
|
||||
self
|
||||
.controller()
|
||||
.CoreWebView2()?
|
||||
.Settings()?
|
||||
.cast::<ICoreWebView2Settings2>()?
|
||||
.UserAgent(p)
|
||||
})?)
|
||||
}
|
||||
}
|
||||
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> {
|
||||
unsafe {
|
||||
self
|
||||
.controller()
|
||||
.CoreWebView2()?
|
||||
.Settings()?
|
||||
.cast::<ICoreWebView2Settings2>()?
|
||||
.SetUserAgent(&HSTRING::from(user_agent))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn load_url(&self, url: &str) -> anyhow::Result<()> {
|
||||
let state = state(self)?;
|
||||
state.pending.set(Some(state.messenger.generation()));
|
||||
unsafe {
|
||||
state.core.Navigate(&HSTRING::from(url))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn load_html(&self, html: &str) -> anyhow::Result<()> {
|
||||
let state = state(self)?;
|
||||
state.pending.set(Some(state.messenger.generation()));
|
||||
unsafe {
|
||||
state.core.NavigateToString(&HSTRING::from(html))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// WebView2 clears profiles asynchronously; do not navigate until cookies are gone.
|
||||
pub(super) async fn clear_browsing_data(window: &AuthWindow) -> anyhow::Result<()> {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
window.with_webview(move |wv| {
|
||||
let tx = Rc::new(RefCell::new(Some(tx)));
|
||||
let complete = Rc::clone(&tx);
|
||||
let callback = ClearBrowsingDataCompletedHandler::create(Box::new(move |result| {
|
||||
if let Some(tx) = complete.borrow_mut().take() {
|
||||
let _ = tx.send(result);
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
let result = (|| unsafe {
|
||||
wv.controller()
|
||||
.CoreWebView2()?
|
||||
.cast::<ICoreWebView2_13>()?
|
||||
.Profile()?
|
||||
.cast::<ICoreWebView2Profile2>()?
|
||||
.ClearBrowsingDataAll(&callback)
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
if let Some(tx) = tx.borrow_mut().take() {
|
||||
let _ = tx.send(Err(error));
|
||||
}
|
||||
}
|
||||
})?;
|
||||
rx.await.context("Could not clear sign-in data")??;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,391 +0,0 @@
|
||||
//! Native controls remain outside the identity provider's document.
|
||||
use super::*;
|
||||
use windows::{
|
||||
Win32::{
|
||||
Foundation::{COLORREF, HWND, LPARAM, LRESULT, RECT, WPARAM},
|
||||
Graphics::Gdi::*,
|
||||
UI::{
|
||||
Controls::EM_SETRECT,
|
||||
HiDpi::{GetDpiForWindow, SystemParametersInfoForDpi},
|
||||
Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass},
|
||||
WindowsAndMessaging::*,
|
||||
},
|
||||
},
|
||||
core::{PCWSTR, w},
|
||||
};
|
||||
|
||||
const SUBCLASS: usize = 0x47504155;
|
||||
const ADDRESS_SUBCLASS: usize = 0x47504156;
|
||||
const ADDRESS_HEIGHT: i32 = 24;
|
||||
const TOOLBAR_HEIGHT: i32 = 34;
|
||||
const RECOVERY_PADDING: i32 = 4;
|
||||
const RETRY: usize = 101;
|
||||
const PROCEED: usize = 102;
|
||||
const CANCEL: usize = 103;
|
||||
|
||||
pub(super) struct Controls {
|
||||
pub(super) parent: HWND,
|
||||
webview_host: HWND,
|
||||
address: HWND,
|
||||
message: HWND,
|
||||
retry: HWND,
|
||||
proceed: HWND,
|
||||
cancel: HWND,
|
||||
status: Cell<RecoveryStatus>,
|
||||
recovery_bounds: Cell<RECT>,
|
||||
font: Cell<Option<(u32, HFONT)>>,
|
||||
}
|
||||
|
||||
impl Controls {
|
||||
pub(super) fn new(window: &AuthWindow, controller: &ICoreWebView2Controller, key: usize) -> anyhow::Result<Self> {
|
||||
// The host owns both the toolbar and the child webview's remaining area.
|
||||
let parent = HWND(window.hwnd()?.0);
|
||||
let mut webview_host = HWND::default();
|
||||
unsafe {
|
||||
controller.ParentWindow(&mut webview_host)?;
|
||||
}
|
||||
let child = |class: PCWSTR, title: &str, style: WINDOW_STYLE, id: usize| -> windows::core::Result<HWND> {
|
||||
unsafe {
|
||||
let hwnd = CreateWindowExW(
|
||||
WINDOW_EX_STYLE::default(),
|
||||
class,
|
||||
&HSTRING::from(title),
|
||||
WS_CHILD | style,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
Some(parent),
|
||||
Some(HMENU(id as *mut _)),
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
Ok(hwnd)
|
||||
}
|
||||
};
|
||||
let controls = Self {
|
||||
parent,
|
||||
webview_host,
|
||||
address: child(
|
||||
w!("EDIT"),
|
||||
super::super::address_bar::LOADING_ADDRESS,
|
||||
WS_VISIBLE | WS_BORDER | WINDOW_STYLE(ES_READONLY as u32 | ES_MULTILINE as u32 | ES_AUTOHSCROLL as u32),
|
||||
0,
|
||||
)?,
|
||||
message: child(w!("STATIC"), "", WINDOW_STYLE::default(), 0)?,
|
||||
retry: child(w!("BUTTON"), "Try Again", WS_TABSTOP, RETRY)?,
|
||||
proceed: child(w!("BUTTON"), "Continue Anyway…", WS_TABSTOP, PROCEED)?,
|
||||
cancel: child(w!("BUTTON"), "Cancel", WS_TABSTOP, CANCEL)?,
|
||||
status: Cell::new(RecoveryStatus::Hidden),
|
||||
recovery_bounds: Cell::new(RECT::default()),
|
||||
font: Cell::new(None),
|
||||
};
|
||||
unsafe {
|
||||
anyhow::ensure!(
|
||||
SetWindowSubclass(controls.address, Some(address_proc), ADDRESS_SUBCLASS, 0).as_bool(),
|
||||
"Could not style the sign-in address"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
SetWindowSubclass(parent, Some(window_proc), SUBCLASS, key).as_bool(),
|
||||
"Could not install sign-in controls"
|
||||
);
|
||||
}
|
||||
Ok(controls)
|
||||
}
|
||||
|
||||
pub(super) fn set_address(&self, uri: &str) -> windows::core::Result<()> {
|
||||
unsafe {
|
||||
SetWindowTextW(
|
||||
self.address,
|
||||
&HSTRING::from(super::super::address_bar::display_address(Some(uri))),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn update(&self, state: &State, status: RecoveryStatus) -> windows::core::Result<()> {
|
||||
self.status.set(status);
|
||||
let message = if status.detail().is_empty() {
|
||||
status.message().to_owned()
|
||||
} else {
|
||||
format!("{}\r\n{}", status.message(), status.detail())
|
||||
};
|
||||
unsafe {
|
||||
SetWindowTextW(self.message, &HSTRING::from(message))?;
|
||||
for (hwnd, visible) in [
|
||||
(self.message, status != RecoveryStatus::Hidden),
|
||||
(self.retry, status.can_retry()),
|
||||
(self.proceed, status.can_continue()),
|
||||
(self.cancel, status.blocks_page()),
|
||||
] {
|
||||
let _ = ShowWindow(hwnd, if visible { SW_SHOW } else { SW_HIDE });
|
||||
}
|
||||
state.controller.SetIsVisible(!status.blocks_page())?;
|
||||
}
|
||||
self.layout(state)
|
||||
}
|
||||
|
||||
pub(super) fn layout(&self, state: &State) -> windows::core::Result<()> {
|
||||
unsafe {
|
||||
let dpi = GetDpiForWindow(self.parent);
|
||||
let scale = dpi as f64 / 96.0;
|
||||
let px = |value: i32| (value as f64 * scale).round() as i32;
|
||||
let mut bounds = RECT::default();
|
||||
GetClientRect(self.parent, &mut bounds)?;
|
||||
let width = bounds.right;
|
||||
if self.font.get().is_none_or(|(current_dpi, _)| current_dpi != dpi) {
|
||||
let mut metrics = NONCLIENTMETRICSW {
|
||||
cbSize: std::mem::size_of::<NONCLIENTMETRICSW>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
SystemParametersInfoForDpi(
|
||||
SPI_GETNONCLIENTMETRICS.0,
|
||||
metrics.cbSize,
|
||||
Some(&mut metrics as *mut _ as *mut _),
|
||||
0,
|
||||
dpi,
|
||||
)?;
|
||||
metrics.lfMessageFont.lfHeight = -px(13);
|
||||
let font = CreateFontIndirectW(&metrics.lfMessageFont);
|
||||
if font.is_invalid() {
|
||||
return Err(windows::core::Error::from_thread());
|
||||
}
|
||||
for control in [self.address, self.message, self.retry, self.proceed, self.cancel] {
|
||||
SendMessageW(control, WM_SETFONT, Some(WPARAM(font.0 as usize)), Some(LPARAM(1)));
|
||||
}
|
||||
if let Some((_, old)) = self.font.replace(Some((dpi, font))) {
|
||||
let _ = DeleteObject(old.into());
|
||||
}
|
||||
}
|
||||
MoveWindow(
|
||||
self.address,
|
||||
px(8),
|
||||
px(5),
|
||||
(width - px(16)).max(0),
|
||||
px(ADDRESS_HEIGHT),
|
||||
true,
|
||||
)?;
|
||||
// A one-line formatting rectangle centers the native read-only edit text.
|
||||
// ES_AUTOHSCROLL keeps long URLs on one line and lets users select/copy them.
|
||||
let mut client = RECT::default();
|
||||
GetClientRect(self.address, &mut client)?;
|
||||
let dc = GetDC(Some(self.address));
|
||||
let previous = SelectObject(dc, self.font.get().expect("font initialized").1.into());
|
||||
let mut text_metrics = TEXTMETRICW::default();
|
||||
let measured = GetTextMetricsW(dc, &mut text_metrics);
|
||||
SelectObject(dc, previous);
|
||||
ReleaseDC(Some(self.address), dc);
|
||||
measured.ok()?;
|
||||
let top = ((client.bottom - text_metrics.tmHeight) / 2).max(0);
|
||||
let text = RECT {
|
||||
left: px(6),
|
||||
top,
|
||||
right: client.right - px(6),
|
||||
bottom: top + text_metrics.tmHeight,
|
||||
};
|
||||
SendMessageW(
|
||||
self.address,
|
||||
EM_SETRECT,
|
||||
Some(WPARAM(0)),
|
||||
Some(LPARAM(&text as *const _ as isize)),
|
||||
);
|
||||
let status = self.status.get();
|
||||
let buttons = [
|
||||
(self.cancel, status.blocks_page(), 70),
|
||||
(self.proceed, status.can_continue(), 136),
|
||||
(self.retry, status.can_retry(), 84),
|
||||
];
|
||||
let button_width: i32 = buttons
|
||||
.iter()
|
||||
.filter(|(_, visible, _)| *visible)
|
||||
.map(|(_, _, size)| size + 6)
|
||||
.sum();
|
||||
let stacked = width < px(700) && button_width > 0;
|
||||
let message_height = if status.detail().is_empty() { 20 } else { 40 };
|
||||
let row_height = message_height.max(28);
|
||||
let recovery_content_height = if stacked { message_height + 8 + 28 } else { row_height };
|
||||
// Equal padding surrounds the controls; the divider occupies one physical pixel.
|
||||
let recovery_height = px(recovery_content_height + 2 * RECOVERY_PADDING) + 1;
|
||||
let header_height = if status == RecoveryStatus::Hidden {
|
||||
px(TOOLBAR_HEIGHT)
|
||||
} else {
|
||||
px(TOOLBAR_HEIGHT) + recovery_height
|
||||
};
|
||||
self.recovery_bounds.set(RECT {
|
||||
left: 0,
|
||||
top: px(TOOLBAR_HEIGHT),
|
||||
right: width,
|
||||
bottom: header_height,
|
||||
});
|
||||
let message_width = if stacked {
|
||||
width - px(24)
|
||||
} else {
|
||||
width - px(24 + button_width)
|
||||
};
|
||||
MoveWindow(
|
||||
self.message,
|
||||
px(12),
|
||||
px(TOOLBAR_HEIGHT + RECOVERY_PADDING + if stacked { 0 } else { (row_height - message_height) / 2 }),
|
||||
message_width.max(0),
|
||||
px(message_height),
|
||||
true,
|
||||
)?;
|
||||
let button_top = TOOLBAR_HEIGHT
|
||||
+ RECOVERY_PADDING
|
||||
+ if stacked {
|
||||
message_height + 8
|
||||
} else {
|
||||
(row_height - 28) / 2
|
||||
};
|
||||
let mut right = width - px(8);
|
||||
for (hwnd, visible, size) in buttons {
|
||||
if visible {
|
||||
right -= px(size);
|
||||
MoveWindow(hwnd, right, px(button_top), px(size), px(28), true)?;
|
||||
right -= px(6);
|
||||
}
|
||||
}
|
||||
let content_height = (bounds.bottom - header_height).max(0);
|
||||
MoveWindow(self.webview_host, 0, header_height, width, content_height, true)?;
|
||||
state.controller.SetBounds(RECT {
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: width,
|
||||
bottom: content_height,
|
||||
})?;
|
||||
let _ = InvalidateRect(Some(self.parent), None, true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Controls {
|
||||
fn drop(&mut self) {
|
||||
if let Some((_, font)) = self.font.get() {
|
||||
unsafe {
|
||||
let _ = DeleteObject(font.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the native edit's selection and accessibility, with a quiet, flat frame.
|
||||
unsafe extern "system" fn address_proc(
|
||||
hwnd: HWND,
|
||||
msg: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
id: usize,
|
||||
_: usize,
|
||||
) -> LRESULT {
|
||||
if msg == WM_NCDESTROY {
|
||||
unsafe {
|
||||
let _ = RemoveWindowSubclass(hwnd, Some(address_proc), id);
|
||||
}
|
||||
}
|
||||
let result = unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) };
|
||||
// EDIT also repaints its frame during WM_PAINT, so style it after native drawing.
|
||||
if matches!(msg, WM_NCPAINT | WM_PAINT) {
|
||||
unsafe {
|
||||
let dc = GetWindowDC(Some(hwnd));
|
||||
let mut bounds = RECT::default();
|
||||
if !dc.is_invalid() && GetWindowRect(hwnd, &mut bounds).is_ok() {
|
||||
let background = GetSysColor(COLOR_3DFACE);
|
||||
let foreground = GetSysColor(COLOR_WINDOWTEXT);
|
||||
let mut border = 0;
|
||||
for shift in [0, 8, 16] {
|
||||
let channel = (((background >> shift) & 255) * 82 + ((foreground >> shift) & 255) * 18) / 100;
|
||||
border |= channel << shift;
|
||||
}
|
||||
let brush = CreateSolidBrush(COLORREF(border));
|
||||
FrameRect(
|
||||
dc,
|
||||
&RECT {
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: bounds.right - bounds.left,
|
||||
bottom: bounds.bottom - bounds.top,
|
||||
},
|
||||
brush,
|
||||
);
|
||||
let _ = DeleteObject(brush.into());
|
||||
}
|
||||
ReleaseDC(Some(hwnd), dc);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
unsafe extern "system" fn window_proc(
|
||||
hwnd: HWND,
|
||||
msg: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
id: usize,
|
||||
key: usize,
|
||||
) -> LRESULT {
|
||||
let state = STATES.with_borrow(|states| states.get(&key).cloned());
|
||||
if msg == WM_CTLCOLORSTATIC {
|
||||
unsafe {
|
||||
let dc = HDC(wparam.0 as *mut _);
|
||||
let is_message = state
|
||||
.as_ref()
|
||||
.is_some_and(|state| state.controls.message.0 as isize == lparam.0);
|
||||
let background = if is_message { COLOR_3DFACE } else { COLOR_WINDOW };
|
||||
SetTextColor(dc, COLORREF(GetSysColor(COLOR_WINDOWTEXT)));
|
||||
SetBkColor(dc, COLORREF(GetSysColor(background)));
|
||||
return LRESULT(GetSysColorBrush(background).0 as isize);
|
||||
}
|
||||
}
|
||||
// Paint the native toolbar and recovery surface outside the child webview.
|
||||
if msg == WM_ERASEBKGND {
|
||||
unsafe {
|
||||
let mut bounds = RECT::default();
|
||||
if GetClientRect(hwnd, &mut bounds).is_ok() {
|
||||
let dc = HDC(wparam.0 as *mut _);
|
||||
FillRect(dc, &bounds, GetSysColorBrush(COLOR_WINDOW));
|
||||
if let Some(state) = &state {
|
||||
let row = state.controls.recovery_bounds.get();
|
||||
if row.bottom > row.top {
|
||||
FillRect(dc, &row, GetSysColorBrush(COLOR_3DFACE));
|
||||
let divider = RECT {
|
||||
top: row.bottom - 1,
|
||||
..row
|
||||
};
|
||||
FillRect(dc, ÷r, GetSysColorBrush(COLOR_3DLIGHT));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return LRESULT(1);
|
||||
}
|
||||
if let Some(state) = &state {
|
||||
if msg == WM_COMMAND && (wparam.0 >> 16) == BN_CLICKED as usize {
|
||||
let event = match wparam.0 & 0xffff {
|
||||
RETRY => Some(AuthEvent::Retry),
|
||||
PROCEED => Some(AuthEvent::RequestTlsException),
|
||||
CANCEL => Some(AuthEvent::Close),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(event) = event {
|
||||
state.messenger.send_auth_event(event);
|
||||
return LRESULT(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) };
|
||||
if msg == WM_SIZE || msg == WM_DPICHANGED {
|
||||
if let Some(state) = &state {
|
||||
let _ = state.controls.layout(state);
|
||||
}
|
||||
}
|
||||
if msg == WM_NCDESTROY {
|
||||
unsafe {
|
||||
let _ = RemoveWindowSubclass(hwnd, Some(window_proc), id);
|
||||
}
|
||||
STATES.with_borrow_mut(|states| states.remove(&key));
|
||||
if let Some(state) = state {
|
||||
super::tls::clear_exceptions(&state.core);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
use super::super::tls::{TlsFailure, TlsFailureReason};
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
use webview2_com::{ClearServerCertificateErrorActionsCompletedHandler, ServerCertificateErrorDetectedEventHandler};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{IDYES, MB_DEFBUTTON2, MB_ICONWARNING, MB_YESNO, MessageBoxW};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Policy {
|
||||
pub ignore_errors: bool,
|
||||
approved: HashSet<(String, String)>,
|
||||
pending: Option<Failure>,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Failure {
|
||||
identity: (String, String),
|
||||
failure: TlsFailure,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
fn reason(error: COREWEBVIEW2_WEB_ERROR_STATUS) -> TlsFailureReason {
|
||||
match error {
|
||||
COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_COMMON_NAME_IS_INCORRECT => TlsFailureReason::HostnameMismatch,
|
||||
COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_EXPIRED => TlsFailureReason::Expired,
|
||||
_ => TlsFailureReason::InvalidCertificate,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn install(state: &Rc<State>) -> windows::core::Result<()> {
|
||||
let weak = Rc::downgrade(state);
|
||||
let handler = ServerCertificateErrorDetectedEventHandler::create(Box::new(move |_, args| {
|
||||
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
|
||||
return Ok(());
|
||||
};
|
||||
unsafe {
|
||||
let uri = text(|p| args.RequestUri(p))?;
|
||||
let host = url::Url::parse(&uri)
|
||||
.ok()
|
||||
.and_then(|url| url.host_str().map(str::to_owned))
|
||||
.unwrap_or_default();
|
||||
let pem = text(|p| args.ServerCertificate()?.ToPemEncoding(p))?;
|
||||
let mut error = COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN;
|
||||
args.ErrorStatus(&mut error)?;
|
||||
let identity = (host.clone(), pem);
|
||||
let mut policy = state.tls.borrow_mut();
|
||||
if policy.ignore_errors || policy.approved.contains(&identity) {
|
||||
args.SetAction(COREWEBVIEW2_SERVER_CERTIFICATE_ERROR_ACTION_ALWAYS_ALLOW)?;
|
||||
} else {
|
||||
args.SetAction(COREWEBVIEW2_SERVER_CERTIFICATE_ERROR_ACTION_CANCEL)?;
|
||||
let generation = state.document.borrow().1;
|
||||
let failure = TlsFailure {
|
||||
host,
|
||||
reason: reason(error),
|
||||
can_continue: error != COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_REVOKED,
|
||||
};
|
||||
state
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::Error(generation, AuthError::Tls(failure.clone())));
|
||||
policy.pending = Some(Failure {
|
||||
identity,
|
||||
failure,
|
||||
generation,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
let mut token = 0;
|
||||
unsafe {
|
||||
state
|
||||
.core
|
||||
.cast::<ICoreWebView2_14>()?
|
||||
.add_ServerCertificateErrorDetected(&handler, &mut token)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn confirm(state: &State) -> anyhow::Result<()> {
|
||||
let pending = state
|
||||
.tls
|
||||
.borrow()
|
||||
.pending
|
||||
.clone()
|
||||
.context("No certificate error to confirm")?;
|
||||
if !pending.failure.can_continue || pending.generation != state.messenger.generation() {
|
||||
bail!("This certificate exception is no longer available");
|
||||
}
|
||||
let answer = unsafe {
|
||||
MessageBoxW(
|
||||
Some(state.controls.parent),
|
||||
&HSTRING::from(pending.failure.confirmation_message()),
|
||||
&HSTRING::from(pending.failure.confirmation_title()),
|
||||
MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
|
||||
)
|
||||
};
|
||||
if answer == IDYES {
|
||||
let identity = pending.identity.clone();
|
||||
let generation = pending.generation;
|
||||
state.tls.borrow_mut().approved.insert(identity);
|
||||
state.messenger.send_auth_event(AuthEvent::TlsAccepted(generation));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// WebView2 caches approvals in the session. Do not leave them for another sign-in window.
|
||||
pub(super) fn clear_exceptions(core: &ICoreWebView2) {
|
||||
if let Ok(core) = core.cast::<ICoreWebView2_14>() {
|
||||
let _ = unsafe {
|
||||
core.ClearServerCertificateErrorActions(&ClearServerCertificateErrorActionsCompletedHandler::create(Box::new(
|
||||
|_| Ok(()),
|
||||
)))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn maps_certificate_failure_reasons() {
|
||||
assert_eq!(
|
||||
reason(COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_COMMON_NAME_IS_INCORRECT),
|
||||
TlsFailureReason::HostnameMismatch
|
||||
);
|
||||
assert_eq!(
|
||||
reason(COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_EXPIRED),
|
||||
TlsFailureReason::Expired
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,17 +10,10 @@ license = "MIT"
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
open = { version = "5", optional = true }
|
||||
webbrowser = { version = "1", optional = true }
|
||||
which = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
launcher = ["dep:open", "dep:webbrowser", "dep:which", "dep:winreg"]
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = { version = "0.55", optional = true }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
open = { version = "5", optional = true }
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
which = { workspace = true, optional = true }
|
||||
launcher = ["dep:open", "dep:webbrowser", "dep:which"]
|
||||
@@ -1,11 +1,8 @@
|
||||
#[cfg(all(feature = "launcher", windows))]
|
||||
#[path = "platform/windows.rs"]
|
||||
mod platform;
|
||||
#[cfg(all(feature = "launcher", target_os = "macos"))]
|
||||
#[path = "platform/macos.rs"]
|
||||
mod platform;
|
||||
|
||||
#[cfg(all(feature = "launcher", unix, not(target_os = "macos")))]
|
||||
#[cfg(all(feature = "launcher", not(target_os = "macos")))]
|
||||
#[path = "platform/generic.rs"]
|
||||
mod platform;
|
||||
|
||||
@@ -41,7 +38,7 @@ impl<'a> Browser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "launcher", unix, not(target_os = "macos")))]
|
||||
#[cfg(all(feature = "launcher", not(target_os = "macos")))]
|
||||
pub(crate) fn as_str(&self) -> &str {
|
||||
match self {
|
||||
Browser::Auto => "auto",
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
//! Windows browsers are resolved through their registered App Paths.
|
||||
use crate::Browser;
|
||||
use anyhow::{Context, bail};
|
||||
use std::path::PathBuf;
|
||||
use winreg::{
|
||||
RegKey,
|
||||
enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE},
|
||||
};
|
||||
|
||||
pub(super) fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> {
|
||||
let executable = match browser {
|
||||
Browser::Auto | Browser::Default => return webbrowser::open(url).context("Could not open the browser"),
|
||||
Browser::Chrome => registered_browser("chrome.exe").context("Chrome is not installed")?,
|
||||
Browser::Edge => registered_browser("msedge.exe").context("Edge is not installed")?,
|
||||
Browser::Firefox => registered_browser("firefox.exe").context("Firefox is not installed")?,
|
||||
Browser::Safari => bail!("Safari is not available on Windows"),
|
||||
Browser::Other(program) => PathBuf::from(program),
|
||||
};
|
||||
std::process::Command::new(executable)
|
||||
.arg(url)
|
||||
.spawn()
|
||||
.context("Could not open the configured browser")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn registered_browser(name: &str) -> Option<PathBuf> {
|
||||
[HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE].into_iter().find_map(|hive| {
|
||||
let key = RegKey::predef(hive)
|
||||
.open_subkey(format!(r"Software\Microsoft\Windows\CurrentVersion\App Paths\{name}"))
|
||||
.ok()?;
|
||||
let path: String = key.get_value("").ok()?;
|
||||
let path = PathBuf::from(path.trim_matches('"'));
|
||||
path.is_file().then_some(path)
|
||||
})
|
||||
}
|
||||
+5
-10
@@ -5,16 +5,11 @@ fn main() {
|
||||
let workspace_dir = Path::new(manifest_dir).ancestors().nth(2).unwrap();
|
||||
let gpgui_dir = workspace_dir.parent().unwrap().join("gpgui");
|
||||
|
||||
let suffix = if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||
".exe"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let gp_service_binary = workspace_dir.join(format!("target/debug/gpservice{suffix}"));
|
||||
let gp_client_binary = workspace_dir.join(format!("target/debug/gpclient{suffix}"));
|
||||
let gp_auth_binary = workspace_dir.join(format!("target/debug/gpauth{suffix}"));
|
||||
let gp_gui_helper_binary = workspace_dir.join(format!("target/debug/gpgui-helper{suffix}"));
|
||||
let gp_gui_binary = gpgui_dir.join(format!("target/debug/gpgui{suffix}"));
|
||||
let gp_service_binary = workspace_dir.join("target/debug/gpservice");
|
||||
let gp_client_binary = workspace_dir.join("target/debug/gpclient");
|
||||
let gp_auth_binary = workspace_dir.join("target/debug/gpauth");
|
||||
let gp_gui_helper_binary = workspace_dir.join("target/debug/gpgui-helper");
|
||||
let gp_gui_binary = gpgui_dir.join("target/debug/gpgui");
|
||||
|
||||
println!("cargo:rustc-env=GP_SERVICE_BINARY={}", gp_service_binary.display());
|
||||
println!("cargo:rustc-env=GP_CLIENT_BINARY={}", gp_client_binary.display());
|
||||
|
||||
@@ -89,7 +89,7 @@ fn sibling_binary(binary_name: &str) -> Option<PathBuf> {
|
||||
fn sibling_binary_for_executable(executable: &Path, binary_name: &str) -> Option<PathBuf> {
|
||||
let executable = executable.canonicalize().ok()?;
|
||||
let bin_dir = executable.parent()?;
|
||||
let binary = bin_dir.join(format!("{binary_name}{}", std::env::consts::EXE_SUFFIX));
|
||||
let binary = bin_dir.join(binary_name);
|
||||
if is_file(&binary) {
|
||||
return Some(binary);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ pub const GP_USER_AGENT: &str = "PAN GlobalProtect";
|
||||
pub const GP_CLIENT_VERSION_LINUX: &str = "6.3.3-619";
|
||||
pub const GP_CLIENT_VERSION_WINDOWS: &str = "6.3.3-650";
|
||||
pub const GP_CLIENT_VERSION_MACOS: &str = "6.3.3-915";
|
||||
pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer";
|
||||
#[cfg(target_os = "linux")]
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
pub mod binary_paths;
|
||||
pub mod constants;
|
||||
pub mod paths;
|
||||
@@ -1,32 +0,0 @@
|
||||
//! Machine-wide service state shared by the daemon and desktop clients.
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn service_lock_file() -> PathBuf {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
PathBuf::from("/var/run/gpservice.lock")
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
std::env::var_os("ProgramData")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"))
|
||||
.join("GP Connect")
|
||||
.join("gpservice.lock")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub const SERVICE_PIPE: &str = r"\\.\pipe\GPConnect.Service";
|
||||
|
||||
#[cfg(windows)]
|
||||
pub const SERVICE_NAME: &str = "GPConnect";
|
||||
|
||||
/// Installer-owned SYSTEM/Administrators-only state, including temporary keys.
|
||||
#[cfg(windows)]
|
||||
pub fn service_private_dir() -> PathBuf {
|
||||
service_lock_file()
|
||||
.parent()
|
||||
.expect("service state directory")
|
||||
.join("Private")
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
[package]
|
||||
name = "gp-xml"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
version.workspace = true
|
||||
license = "MIT"
|
||||
description = "GlobalProtect response XML redaction for diagnostics"
|
||||
|
||||
[dependencies]
|
||||
url.workspace = true
|
||||
xmltree.workspace = true
|
||||
@@ -1,172 +0,0 @@
|
||||
//! Redact GlobalProtect response bodies before writing diagnostics.
|
||||
use xmltree::{Element, EmitterConfig, XMLNode};
|
||||
|
||||
const REDACTED: &str = "[redacted]";
|
||||
const MAX_XML_BYTES: usize = 1024 * 1024;
|
||||
|
||||
pub fn redact_xml(body: &[u8]) -> String {
|
||||
if body.len() > MAX_XML_BYTES {
|
||||
return "[XML omitted: exceeds 1 MiB]".into();
|
||||
}
|
||||
let Ok(text) = std::str::from_utf8(body) else {
|
||||
return "[XML omitted: invalid UTF-8]".into();
|
||||
};
|
||||
if text.to_ascii_lowercase().contains("<!doctype") {
|
||||
return "[XML omitted: DTD]".into();
|
||||
}
|
||||
let Ok(nodes) = Element::parse_all(body) else {
|
||||
return "[XML omitted: malformed or non-XML response]".into();
|
||||
};
|
||||
let mut roots = nodes.into_iter().filter_map(|node| match node {
|
||||
XMLNode::Element(element) => Some(element),
|
||||
_ => None,
|
||||
});
|
||||
let Some(mut root) = roots.next() else {
|
||||
return "[XML omitted: no document element]".into();
|
||||
};
|
||||
if roots.next().is_some() || root.name.eq_ignore_ascii_case("html") {
|
||||
return "[XML omitted: unsupported response document]".into();
|
||||
}
|
||||
redact_element(&mut root);
|
||||
let mut output = Vec::new();
|
||||
if root
|
||||
.write_with_config(
|
||||
&mut output,
|
||||
EmitterConfig::new()
|
||||
.perform_indent(true)
|
||||
.write_document_declaration(false),
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
return "[XML omitted: serialization failed]".into();
|
||||
}
|
||||
String::from_utf8(output).unwrap_or_else(|_| "[XML omitted: serialization failed]".into())
|
||||
}
|
||||
|
||||
fn sensitive_name(name: &str) -> bool {
|
||||
let name: String = name
|
||||
.chars()
|
||||
.filter(char::is_ascii_alphanumeric)
|
||||
.map(|c| c.to_ascii_lowercase())
|
||||
.collect();
|
||||
if name.ends_with("label") {
|
||||
return false;
|
||||
}
|
||||
name.contains("cookie")
|
||||
|| name.contains("token")
|
||||
|| name.contains("password")
|
||||
|| name.contains("passphrase")
|
||||
|| name.contains("secret")
|
||||
|| name.starts_with("ekey")
|
||||
|| name.starts_with("akey")
|
||||
|| matches!(
|
||||
name.as_str(),
|
||||
"argument"
|
||||
| "samlrequest"
|
||||
| "samlresponse"
|
||||
| "samlrequestid"
|
||||
| "assertion"
|
||||
| "encryptedassertion"
|
||||
| "authnrequest"
|
||||
| "challenge"
|
||||
| "privatekey"
|
||||
| "encryptionkey"
|
||||
| "enckey"
|
||||
| "hskey"
|
||||
| "enchskey"
|
||||
| "tunnelopaque"
|
||||
| "nonce"
|
||||
| "user"
|
||||
| "username"
|
||||
| "ccusername"
|
||||
| "credential"
|
||||
)
|
||||
}
|
||||
|
||||
fn redact_element(element: &mut Element) {
|
||||
let named_secret = matches!(element.name.as_str(), "field" | "param" | "property" | "setting")
|
||||
&& ["name", "key"]
|
||||
.iter()
|
||||
.any(|name| element.attributes.get(*name).is_some_and(|value| sensitive_name(value)));
|
||||
let secret = sensitive_name(&element.name) || named_secret;
|
||||
for (name, value) in &mut element.attributes {
|
||||
if sensitive_name(name) || (secret && !(named_secret && matches!(name.as_str(), "name" | "key"))) {
|
||||
*value = REDACTED.into();
|
||||
} else {
|
||||
*value = redact_url(value);
|
||||
}
|
||||
}
|
||||
if secret {
|
||||
element.children = vec![XMLNode::Text(REDACTED.into())];
|
||||
return;
|
||||
}
|
||||
element
|
||||
.children
|
||||
.retain(|node| matches!(node, XMLNode::Element(_) | XMLNode::Text(_) | XMLNode::CData(_)));
|
||||
for node in &mut element.children {
|
||||
match node {
|
||||
XMLNode::Element(child) => redact_element(child),
|
||||
XMLNode::Text(value) | XMLNode::CData(value) => *value = redact_url(value),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn redact_url(value: &str) -> String {
|
||||
let Ok(mut url) = url::Url::parse(value) else {
|
||||
return value.into();
|
||||
};
|
||||
if !matches!(url.scheme(), "http" | "https") {
|
||||
return value.into();
|
||||
}
|
||||
if !url.username().is_empty() {
|
||||
let _ = url.set_username(REDACTED);
|
||||
}
|
||||
if url.password().is_some() {
|
||||
let _ = url.set_password(Some(REDACTED));
|
||||
}
|
||||
if url.query().is_some() {
|
||||
let pairs: Vec<_> = url
|
||||
.query_pairs()
|
||||
.map(|(name, _)| (name.into_owned(), REDACTED))
|
||||
.collect();
|
||||
url.query_pairs_mut().clear().extend_pairs(pairs);
|
||||
}
|
||||
if url.fragment().is_some() {
|
||||
url.set_fragment(Some(REDACTED));
|
||||
}
|
||||
url.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn redacts_positional_login_arguments_and_session_keys() {
|
||||
let xml = redact_xml(br#"<response><jnlp><application-desc><argument>fixture-auth-cookie</argument><argument>fixture-user</argument></application-desc></jnlp><ipsec><ekey-c2s><bits>256</bits><val>fixture-key-c2s</val></ekey-c2s><ekey-s2c>fixture-key-s2c</ekey-s2c><akey-c2s><val>fixture-auth-c2s</val></akey-c2s><akey-s2c>fixture-auth-s2c</akey-s2c></ipsec><enc-hs-key>fixture-hs-key</enc-hs-key><PrivateKey>fixture-private-key</PrivateKey><SAMLResponse>fixture-saml-response</SAMLResponse><tunnel-opaque><val>fixture-opaque</val></tunnel-opaque><mtu>1400</mtu></response>"#);
|
||||
assert!(!xml.contains("fixture-"));
|
||||
assert!(xml.contains("<mtu>1400</mtu>"));
|
||||
Element::parse(xml.as_bytes()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omits_unparseable_html_dtd_and_oversized_bodies_without_echoing_them() {
|
||||
for body in [
|
||||
b"not XML fixture-secret".as_slice(),
|
||||
b"<response><cookie>fixture-secret",
|
||||
b"<html><body>fixture-secret</body></html>",
|
||||
b"<!DOCTYPE response [<!ENTITY secret 'fixture-secret'>]><response>&secret;</response>",
|
||||
b"<response/>fixture-secret",
|
||||
b"\xfffixture-secret",
|
||||
] {
|
||||
let xml = redact_xml(body);
|
||||
assert!(xml.starts_with("[XML omitted:"));
|
||||
assert!(!xml.contains("fixture-secret"));
|
||||
}
|
||||
assert_eq!(
|
||||
redact_xml(&vec![b'x'; MAX_XML_BYTES + 1]),
|
||||
"[XML omitted: exceeds 1 MiB]"
|
||||
);
|
||||
}
|
||||
}
|
||||
+5
-36
@@ -6,7 +6,7 @@ edition.workspace = true
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
gp-xml = { path = "../gp-xml" }
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
|
||||
common = { path = "../common" }
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
@@ -35,6 +35,7 @@ thiserror.workspace = true
|
||||
chacha20poly1305 = { version = "0.11", features = ["zeroize"] }
|
||||
url.workspace = true
|
||||
regex.workspace = true
|
||||
uzers = { workspace = true, optional = true }
|
||||
serde_urlencoded.workspace = true
|
||||
md5.workspace = true
|
||||
sha2.workspace = true
|
||||
@@ -47,9 +48,6 @@ snow.workspace = true
|
||||
zeroize = { workspace = true, features = ["serde"] }
|
||||
getrandom = "0.4"
|
||||
|
||||
# Used only by the opt-in certificate interoperability tests.
|
||||
openssl = { workspace = true, optional = true }
|
||||
|
||||
# Optional dependencies for features
|
||||
tauri = { workspace = true, optional = true }
|
||||
clap = { workspace = true, optional = true }
|
||||
@@ -65,10 +63,8 @@ oslog = { version = "0.2", default-features = false, optional = true }
|
||||
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
|
||||
gtk = { version = "0.18", optional = true }
|
||||
|
||||
[target.'cfg(any(target_os="linux", target_os="freebsd", target_os="openbsd"))'.dependencies]
|
||||
directories = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(target_os="linux")'.dependencies]
|
||||
directories = { workspace = true, optional = true }
|
||||
libloading = { version = "0.9", optional = true }
|
||||
|
||||
[target.'cfg(target_os="macos")'.dependencies]
|
||||
@@ -82,6 +78,7 @@ cc = "1"
|
||||
pkg-config = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
openssl.workspace = true
|
||||
libloading = "0.9"
|
||||
proptest.workspace = true
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -92,32 +89,4 @@ desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:u
|
||||
tauri = ["desktop", "dep:tauri", "dep:gtk", "dep:os_info"]
|
||||
clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"]
|
||||
webview-auth = []
|
||||
openssl-tests = ["dep:openssl"]
|
||||
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog", "dep:file-rotate"]
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
|
||||
uzers = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
file-rotate = { version = "0.8.0", optional = true }
|
||||
windows-sys = { version = "0.61", features = ["Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Pipes", "Win32_System_Threading", "Win32_System_Services", "Win32_Globalization", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_IO", "Win32_System_Registry", "Win32_System_SystemInformation"] }
|
||||
|
||||
[target.'cfg(windows)'.dev-dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_UI_Shell"] }
|
||||
|
||||
[[test]]
|
||||
name = "certificate_compatibility"
|
||||
required-features = ["openssl-tests"]
|
||||
|
||||
[[test]]
|
||||
name = "client_certificate_chain"
|
||||
required-features = ["openssl-tests"]
|
||||
|
||||
[[test]]
|
||||
name = "client_certificate_extensions"
|
||||
required-features = ["openssl-tests"]
|
||||
|
||||
[[test]]
|
||||
name = "client_certificate_tls12_hash"
|
||||
required-features = ["openssl-tests"]
|
||||
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"]
|
||||
@@ -1,16 +0,0 @@
|
||||
# gpapi tests
|
||||
|
||||
Ordinary tests do not require OpenSSL. To run the Windows logger regression test:
|
||||
|
||||
```sh
|
||||
cargo test -p gpapi --features logger --lib logger::windows::tests
|
||||
```
|
||||
|
||||
The certificate interoperability suite uses OpenSSL as an independent TLS and
|
||||
signature implementation. Full CI enables it explicitly:
|
||||
|
||||
```sh
|
||||
cargo test -p gpapi --features logger,openssl-tests
|
||||
```
|
||||
|
||||
This optional suite requires OpenSSL development headers and libraries.
|
||||
@@ -10,7 +10,6 @@ pub enum AnchorSource {
|
||||
UnixMac,
|
||||
UnixRandom,
|
||||
MacosIokit,
|
||||
WindowsSmbios,
|
||||
}
|
||||
|
||||
impl From<AnchorSource> for u8 {
|
||||
@@ -19,7 +18,6 @@ impl From<AnchorSource> for u8 {
|
||||
AnchorSource::UnixMac => 1,
|
||||
AnchorSource::UnixRandom => 2,
|
||||
AnchorSource::MacosIokit => 3,
|
||||
AnchorSource::WindowsSmbios => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,7 +41,6 @@ impl TryFrom<u8> for AnchorSource {
|
||||
1 => Ok(Self::UnixMac),
|
||||
2 => Ok(Self::UnixRandom),
|
||||
3 => Ok(Self::MacosIokit),
|
||||
4 => Ok(Self::WindowsSmbios),
|
||||
value => Err(InvalidAnchorSource(value)),
|
||||
}
|
||||
}
|
||||
@@ -68,7 +65,6 @@ impl DeviceAnchor {
|
||||
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
|
||||
AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".as_slice(),
|
||||
AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(),
|
||||
AnchorSource::WindowsSmbios => b"gp-device-anchor:v1:windows-smbios-uuid:".as_slice(),
|
||||
};
|
||||
let mut input = domain.to_vec();
|
||||
input.extend_from_slice(seed.as_ref());
|
||||
@@ -85,7 +81,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn preserves_existing_hardware_ids_for_all_sources() {
|
||||
let cases: [(AnchorSource, &[u8], &str); 4] = [
|
||||
let cases: [(AnchorSource, &[u8], &str); 3] = [
|
||||
(
|
||||
AnchorSource::UnixMac,
|
||||
&[0, 17, 34, 51, 68, 85],
|
||||
@@ -101,11 +97,6 @@ mod tests {
|
||||
b"12345678-1234-5678-9abc-def012345678",
|
||||
"K1KMtAwiOiXKQvQuRmTDKPA6-ZPF5QKUWZzmvRzeP34",
|
||||
),
|
||||
(
|
||||
AnchorSource::WindowsSmbios,
|
||||
b"12345678-1234-5678-9abc-def012345678",
|
||||
"C843jG-lDX91Tab02VelrMJl_OmOji_pCtNWilwzW5s",
|
||||
),
|
||||
];
|
||||
for (source, seed, expected) in cases {
|
||||
let anchor = DeviceAnchor::derive(source, seed);
|
||||
@@ -133,17 +124,12 @@ mod tests {
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::UnixMac).unwrap(), "1");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::UnixRandom).unwrap(), "2");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::MacosIokit).unwrap(), "3");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::WindowsSmbios).unwrap(), "4");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<AnchorSource>("4").unwrap(),
|
||||
AnchorSource::WindowsSmbios
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<AnchorSource>("1").unwrap(),
|
||||
AnchorSource::UnixMac
|
||||
);
|
||||
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>("5").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>("4").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -109,7 +109,6 @@ fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bo
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
hash::MessageDigest,
|
||||
@@ -181,12 +180,10 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
|
||||
server_with_client_auth(tls, SslVerifyMode::NONE)
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
fn server_with_client_auth(tls: bool, verify: SslVerifyMode) -> (String, thread::JoinHandle<()>) {
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
@@ -236,7 +233,6 @@ mod tests {
|
||||
(address, worker)
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn prelogin_returns_typed_certificate_failure_with_only_the_server_origin() {
|
||||
use crate::{
|
||||
@@ -258,7 +254,6 @@ mod tests {
|
||||
assert_eq!(tls.server, address);
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn certificate_bypass_allows_prelogin() {
|
||||
use crate::{
|
||||
@@ -275,7 +270,6 @@ mod tests {
|
||||
assert!(matches!(result.unwrap(), crate::portal::Prelogin::Saml(_)));
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() {
|
||||
let (address, worker) = server(false);
|
||||
@@ -309,7 +303,7 @@ mod tests {
|
||||
assert_eq!(classify(&error), None);
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "desktop", unix))]
|
||||
#[cfg(feature = "desktop")]
|
||||
#[test]
|
||||
fn rendering_recovery_retains_client_certificate_requirement() {
|
||||
use crate::process::rendering_recovery::{RecoveryState, RenderingCrash};
|
||||
@@ -336,7 +330,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn required_client_certificate_is_not_bypassed_by_ignoring_server_trust() {
|
||||
use crate::{
|
||||
@@ -378,7 +371,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn prelogin_explains_peer_rejection_of_an_already_configured_identity() {
|
||||
use crate::{
|
||||
@@ -411,7 +403,6 @@ mod tests {
|
||||
assert!(!error.to_string().contains("passphrase"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
|
||||
use crate::{
|
||||
@@ -444,7 +435,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn imported_identity_formats_complete_mutual_tls_prelogin() {
|
||||
use crate::{
|
||||
|
||||
@@ -202,7 +202,7 @@ async fn receive_gateway_login(
|
||||
let url = res.url().clone();
|
||||
let http_version = res.version();
|
||||
let content_type = res.headers().get(reqwest::header::CONTENT_TYPE).cloned();
|
||||
let res = parse_gp_response(res).await.map_err(|mut err| {
|
||||
let res = parse_gp_response(res).await.map_err(|err| {
|
||||
// Redirect paths and query strings can contain authentication tokens. Log
|
||||
// only the redacted origin and whether the response is from the login path.
|
||||
warn!(
|
||||
@@ -221,9 +221,6 @@ async fn receive_gateway_login(
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err, gp_params.has_client_identity()) {
|
||||
return tls;
|
||||
}
|
||||
if let Some(error) = err.take_body_read_error() {
|
||||
return PortalError::NetworkError(error).into();
|
||||
}
|
||||
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
|
||||
return anyhow::anyhow!(crate::error::AuthenticationRejected);
|
||||
}
|
||||
|
||||
@@ -111,7 +111,7 @@ pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
|
||||
let response = client.post(&url).form(&form).send().await?;
|
||||
let response = parse_gp_response(response).await?;
|
||||
let root = Element::parse(response.as_bytes())?;
|
||||
let status = parse_extend_session_status(&root)?;
|
||||
let status = parse_extend_session_status(&root, &response)?;
|
||||
|
||||
info!("Extend-session gateway response status: {}", status);
|
||||
|
||||
@@ -151,11 +151,11 @@ fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result<HashMap<Str
|
||||
Ok(form)
|
||||
}
|
||||
|
||||
fn parse_extend_session_status(root: &Element) -> anyhow::Result<String> {
|
||||
fn parse_extend_session_status(root: &Element, response: &str) -> anyhow::Result<String> {
|
||||
match root.attr("status") {
|
||||
Some(status) => Ok(status.to_string()),
|
||||
None => {
|
||||
warn!("Extend-session response is missing status");
|
||||
warn!("Malformed extend-session response body: {}", response.trim());
|
||||
bail!("Malformed extend session response")
|
||||
}
|
||||
}
|
||||
@@ -231,7 +231,10 @@ mod tests {
|
||||
fn parses_extend_session_status_attribute() {
|
||||
let root = Element::parse(r#"<response status="success"></response>"#.as_bytes()).unwrap();
|
||||
|
||||
assert_eq!(parse_extend_session_status(&root).unwrap(), "success");
|
||||
assert_eq!(
|
||||
parse_extend_session_status(&root, r#"<response status="success"></response>"#).unwrap(),
|
||||
"success"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -239,7 +242,9 @@ mod tests {
|
||||
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
parse_extend_session_status(&root).unwrap_err().to_string(),
|
||||
parse_extend_session_status(&root, "<response><result>ok</result></response>")
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"Malformed extend session response"
|
||||
);
|
||||
}
|
||||
|
||||
+6
-40
@@ -70,17 +70,17 @@ impl GuiVariant {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn preference_path(name: &str) -> anyhow::Result<PathBuf> {
|
||||
#[cfg(target_os = "linux")]
|
||||
fn preference_path() -> anyhow::Result<PathBuf> {
|
||||
let dirs = directories::ProjectDirs::from("com.yuezk", "GlobalProtect-openconnect", "gpclient")
|
||||
.ok_or_else(|| anyhow::anyhow!("Failed to locate GUI preference directory"))?;
|
||||
Ok(dirs.config_dir().join(name))
|
||||
Ok(dirs.config_dir().join("gui"))
|
||||
}
|
||||
|
||||
pub fn preferred() -> anyhow::Result<GuiVariant> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
match std::fs::read_to_string(preference_path("gui")?) {
|
||||
match std::fs::read_to_string(preference_path()?) {
|
||||
Ok(value) => match value.trim() {
|
||||
"gpgui" => Ok(GuiVariant::Tauri),
|
||||
"gpgui-nsh" => Ok(GuiVariant::Nsh),
|
||||
@@ -96,46 +96,12 @@ pub fn preferred() -> anyhow::Result<GuiVariant> {
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn save_preference(variant: GuiVariant) -> anyhow::Result<()> {
|
||||
save_launch_preference("gui", variant.binary_name())
|
||||
}
|
||||
|
||||
pub const COMPATIBILITY_GRAPHICS_SUPPORTED: bool =
|
||||
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"));
|
||||
|
||||
pub const FORCE_SHARED_MEMORY: &str = "WEBKIT_DMABUF_RENDERER_FORCE_SHM";
|
||||
|
||||
const COMPATIBILITY_GRAPHICS: &str = "compatibility-graphics";
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
fn preference_path(_: &str) -> anyhow::Result<PathBuf> {
|
||||
anyhow::bail!("Compatibility graphics is unavailable")
|
||||
}
|
||||
|
||||
pub fn compatibility_graphics_enabled() -> bool {
|
||||
COMPATIBILITY_GRAPHICS_SUPPORTED && preference_path(COMPATIBILITY_GRAPHICS).is_ok_and(|path| path.is_file())
|
||||
}
|
||||
|
||||
pub fn set_compatibility_graphics(enabled: bool) -> anyhow::Result<()> {
|
||||
anyhow::ensure!(
|
||||
COMPATIBILITY_GRAPHICS_SUPPORTED,
|
||||
"Compatibility graphics is unavailable"
|
||||
);
|
||||
if enabled {
|
||||
return save_launch_preference(COMPATIBILITY_GRAPHICS, "enabled");
|
||||
}
|
||||
match std::fs::remove_file(preference_path(COMPATIBILITY_GRAPHICS)?) {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
result => result.map_err(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
fn save_launch_preference(name: &str, value: &str) -> anyhow::Result<()> {
|
||||
use std::io::Write;
|
||||
let path = preference_path(name)?;
|
||||
let path = preference_path()?;
|
||||
let directory = path.parent().unwrap();
|
||||
std::fs::create_dir_all(directory)?;
|
||||
let mut file = tempfile::NamedTempFile::new_in(directory)?;
|
||||
writeln!(file, "{value}")?;
|
||||
writeln!(file, "{}", variant.binary_name())?;
|
||||
file.persist(path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -45,27 +45,3 @@ mod tests {
|
||||
assert_eq!(serde_json::from_value::<HipSource>(json).unwrap(), source);
|
||||
}
|
||||
}
|
||||
|
||||
/// Collection metadata for the exact XML returned by a generated preview.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HipReport {
|
||||
pub xml: String,
|
||||
pub windows_updates: Option<WindowsUpdateStatus>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WindowsUpdateStatus {
|
||||
/// Present only when this report includes a completed local patch observation.
|
||||
pub checked_at: Option<u64>,
|
||||
/// Time of the observed snapshot when its patch details were too large to include.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub omitted_snapshot_at: Option<u64>,
|
||||
}
|
||||
|
||||
impl WindowsUpdateStatus {
|
||||
pub fn refresh_cursor(&self) -> Option<u64> {
|
||||
self.checked_at.or(self.omitted_snapshot_at)
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,3 @@ pub mod clap;
|
||||
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod script_tun;
|
||||
|
||||
#[cfg(all(feature = "desktop", windows))]
|
||||
pub mod windows;
|
||||
@@ -12,20 +12,6 @@ pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified";
|
||||
type BoxedLogger = Box<dyn Log + Send + Sync>;
|
||||
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = OnceLock::new();
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
#[cfg(windows)]
|
||||
pub use windows::init_file;
|
||||
|
||||
/// Keep helper diagnostics with the application's records when a file logger owns them.
|
||||
pub fn diagnostic_writer() -> Box<dyn std::io::Write + Send> {
|
||||
#[cfg(windows)]
|
||||
if let Some(writer) = windows::diagnostic_writer() {
|
||||
return writer;
|
||||
}
|
||||
Box::new(std::io::stderr())
|
||||
}
|
||||
|
||||
pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if log_format == LogFormat::Text && macos_unified_log_enabled() {
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
use file_rotate::{ContentLimit, FileRotate, compression::Compression, suffix::AppendCount};
|
||||
use std::{
|
||||
fs::{self, OpenOptions},
|
||||
io::{self, Write},
|
||||
path::Path,
|
||||
sync::{Arc, Mutex, OnceLock},
|
||||
};
|
||||
|
||||
const ROTATE_BYTES: usize = 5 * 1024 * 1024;
|
||||
const ARCHIVE_COUNT: usize = 3;
|
||||
static DIAGNOSTICS: OnceLock<DiagnosticWriter> = OnceLock::new();
|
||||
|
||||
#[derive(Clone)]
|
||||
struct DiagnosticWriter(Arc<Mutex<FileRotate<AppendCount>>>);
|
||||
|
||||
impl DiagnosticWriter {
|
||||
fn open(path: &Path) -> io::Result<Self> {
|
||||
if let Some(parent) = path.parent().filter(|parent| !parent.as_os_str().is_empty()) {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
// FileRotate's constructor suppresses open errors, so check the destination first.
|
||||
OpenOptions::new().create(true).append(true).open(path)?;
|
||||
Ok(Self(Arc::new(Mutex::new(FileRotate::new(
|
||||
path,
|
||||
AppendCount::new(ARCHIVE_COUNT),
|
||||
ContentLimit::BytesSurpassed(ROTATE_BYTES),
|
||||
Compression::None,
|
||||
None,
|
||||
)))))
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for DiagnosticWriter {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
self
|
||||
.0
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("Log writer lock is poisoned"))?
|
||||
.write(bytes)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self
|
||||
.0
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("Log writer lock is poisoned"))?
|
||||
.flush()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_file(path: &Path, level: log::Level) -> io::Result<()> {
|
||||
let writer = DiagnosticWriter::open(path)?;
|
||||
let logger = super::build_env_logger(crate::log_format::LogFormat::Text)
|
||||
.target(env_logger::Target::Pipe(Box::new(writer.clone())))
|
||||
.build();
|
||||
DIAGNOSTICS
|
||||
.set(writer)
|
||||
.map_err(|_| io::Error::other("File logging is already initialized"))?;
|
||||
super::init_with_logger(level, logger);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn diagnostic_writer() -> Option<Box<dyn Write + Send>> {
|
||||
DIAGNOSTICS
|
||||
.get()
|
||||
.map(|writer| Box::new(writer.clone()) as Box<dyn Write + Send>)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn gui_and_helper_writers_share_rotation_and_keep_only_three_archives() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("logs/gui.log");
|
||||
let mut gui = DiagnosticWriter::open(&path).unwrap();
|
||||
let mut helper = gui.clone();
|
||||
for marker in b'0'..=b'5' {
|
||||
let writer = if marker % 2 == 0 { &mut gui } else { &mut helper };
|
||||
writer.write_all(&vec![marker; ROTATE_BYTES + 1]).unwrap();
|
||||
}
|
||||
helper.flush().unwrap();
|
||||
drop((gui, helper));
|
||||
assert_eq!(fs::read(&path).unwrap(), vec![b'5'; ROTATE_BYTES + 1]);
|
||||
for (suffix, marker) in [(1, b'4'), (2, b'3'), (3, b'2')] {
|
||||
assert_eq!(
|
||||
fs::read(path.with_extension(format!("log.{suffix}"))).unwrap(),
|
||||
vec![marker; ROTATE_BYTES + 1]
|
||||
);
|
||||
}
|
||||
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 4);
|
||||
let mut reopened = DiagnosticWriter::open(&path).unwrap();
|
||||
reopened.write_all(b"after restart\n").unwrap();
|
||||
reopened.flush().unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"after restart\n");
|
||||
}
|
||||
}
|
||||
@@ -173,12 +173,6 @@ pub fn collect_profile_with_control(
|
||||
Some(identity) => identity.clone(),
|
||||
None => collect_with_host_id_and_control(host_id_override, control)?,
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let identity = if builder.client_os == ClientOs::Windows {
|
||||
windows::native_profile_identity(identity, host_id_override)?
|
||||
} else {
|
||||
identity
|
||||
};
|
||||
let runtime_os = runtime_client_os();
|
||||
// Preserve the old behavior: only probe the native version when reporting it.
|
||||
let (os_version, software_version) = if builder.client_os == runtime_os {
|
||||
@@ -187,8 +181,7 @@ pub fn collect_profile_with_control(
|
||||
(defaults::os_version(runtime_os), defaults::software_version(runtime_os))
|
||||
};
|
||||
control.check()?;
|
||||
// The builder may carry cached hardware identity; use the resolved profile identity.
|
||||
Ok(builder.host_identity(identity.clone()).build(HostSnapshot {
|
||||
Ok(builder.build(HostSnapshot {
|
||||
runtime_os,
|
||||
identity,
|
||||
os_version,
|
||||
|
||||
@@ -137,24 +137,14 @@ fn assert_mac(value: &str, separator: char) {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builder_preserves_supplied_hardware_fields() {
|
||||
fn builder_delegates_default_identity_to_host_identity() {
|
||||
let expected = collect_identity();
|
||||
let profile = collect_profile(
|
||||
OsProfileBuilder::new(runtime_client_os()).host_identity(expected.clone()),
|
||||
None,
|
||||
);
|
||||
|
||||
assert!(
|
||||
profile
|
||||
.host_identity()
|
||||
.computer()
|
||||
.eq_ignore_ascii_case(expected.computer())
|
||||
);
|
||||
assert_eq!(profile.host_identity().serialno(), expected.serialno());
|
||||
assert_eq!(profile.host_identity().mac_addr(), expected.mac_addr());
|
||||
if runtime_client_os() != ClientOs::Windows {
|
||||
assert_eq!(profile.host_identity().host_id(), expected.host_id());
|
||||
}
|
||||
assert_eq!(profile.host_identity(), &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -188,76 +178,3 @@ fn controlled_profile_collection_propagates_cancellation_and_deadline() {
|
||||
let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Linux), None, &expired).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn native_windows_profile_uses_installation_id_and_emulation_keeps_its_seed() {
|
||||
let identity = HostIdentity::from_parts(
|
||||
"test-host".into(),
|
||||
"hardware-seed".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let control = CollectionBudget::new(Duration::from_secs(60));
|
||||
let native = collect_profile_with_control(
|
||||
OsProfile::builder(ClientOs::Windows).host_identity(identity.clone()),
|
||||
None,
|
||||
&control,
|
||||
)
|
||||
.unwrap();
|
||||
// Read independently through the registry CLI to check the native API's source and view.
|
||||
let output = std::process::Command::new("reg")
|
||||
.args([
|
||||
"query",
|
||||
r"HKLM\SOFTWARE\Microsoft\Cryptography",
|
||||
"/v",
|
||||
"MachineGuid",
|
||||
"/reg:64",
|
||||
])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
let text = String::from_utf8(output.stdout).unwrap();
|
||||
let expected = text
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let mut parts = line.split_whitespace();
|
||||
(parts.next()? == "MachineGuid").then(|| parts.last().unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(native.host_id(), expected);
|
||||
assert_eq!(native.host_identity().host_id(), expected);
|
||||
assert!(native.computer().eq_ignore_ascii_case(&fallback_hostname()));
|
||||
let with_host_id = collect_profile_with_control(
|
||||
OsProfile::builder(ClientOs::Windows).host_identity(identity.clone()),
|
||||
Some("explicit-host-id"),
|
||||
&control,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(with_host_id.host_id(), "explicit-host-id");
|
||||
assert_eq!(with_host_id.computer(), native.computer());
|
||||
let overridden = collect_profile_with_control(
|
||||
OsProfile::builder(ClientOs::Windows)
|
||||
.host_identity(identity.clone())
|
||||
.computer_name_override("Custom-Host"),
|
||||
None,
|
||||
&control,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(overridden.computer(), "Custom-Host");
|
||||
|
||||
for client_os in [ClientOs::Mac, ClientOs::Linux] {
|
||||
let builder = OsProfile::builder(client_os).host_identity(identity.clone());
|
||||
let expected = builder.clone().build(HostSnapshot {
|
||||
runtime_os: ClientOs::Windows,
|
||||
identity: identity.clone(),
|
||||
os_version: String::new(),
|
||||
software_version: String::new(),
|
||||
});
|
||||
let actual = collect_profile_with_control(builder, None, &control).unwrap();
|
||||
assert_eq!(actual.host_identity(), &identity);
|
||||
assert_eq!(actual.host_id(), expected.host_id());
|
||||
assert_eq!(actual.serialno(), expected.serialno());
|
||||
assert_eq!(actual.mac_addr(), expected.mac_addr());
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
use std::{io, os::windows::process::CommandExt, process::Command};
|
||||
use windows_sys::Win32::System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ, RRF_SUBKEY_WOW6464KEY, RegGetValueW};
|
||||
use windows_sys::Win32::System::SystemInformation::{ComputerNamePhysicalNetBIOS, GetComputerNameExW};
|
||||
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
|
||||
use std::process::Command;
|
||||
|
||||
use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id};
|
||||
|
||||
@@ -39,7 +36,6 @@ impl RuntimeNativeHostIdentity {
|
||||
|
||||
fn collect_windows_serial_number() -> Option<String> {
|
||||
let output = Command::new("wmic")
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.args(["bios", "get", "serialnumber"])
|
||||
.output()
|
||||
.ok()?;
|
||||
@@ -54,15 +50,11 @@ fn collect_windows_serial_number() -> Option<String> {
|
||||
}
|
||||
|
||||
fn windows_machine_seed() -> Option<String> {
|
||||
collect_windows_csproduct_uuid().or_else(|| collect_windows_machine_guid().ok())
|
||||
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
|
||||
}
|
||||
|
||||
fn collect_windows_csproduct_uuid() -> Option<String> {
|
||||
let output = Command::new("wmic")
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.args(["csproduct", "get", "uuid"])
|
||||
.output()
|
||||
.ok()?;
|
||||
let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?;
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
|
||||
stdout
|
||||
@@ -73,63 +65,24 @@ fn collect_windows_csproduct_uuid() -> Option<String> {
|
||||
.next()
|
||||
}
|
||||
|
||||
// Native Windows uses the OS installation ID and physical NetBIOS name.
|
||||
// Keep the hardware identity used to seed other OS profiles unchanged.
|
||||
pub(super) fn native_profile_identity(
|
||||
identity: super::HostIdentity,
|
||||
host_id_override: Option<&str>,
|
||||
) -> io::Result<super::HostIdentity> {
|
||||
let host_id = match host_id_override.filter(|id| !id.trim().is_empty()) {
|
||||
Some(id) => id.to_owned(),
|
||||
None => collect_windows_machine_guid()?,
|
||||
};
|
||||
Ok(super::HostIdentity::from_parts(
|
||||
collect_windows_computer_name()?,
|
||||
host_id,
|
||||
identity.serialno().into(),
|
||||
identity.mac_addr().into(),
|
||||
))
|
||||
}
|
||||
fn collect_windows_machine_guid() -> Option<String> {
|
||||
let output = Command::new("reg")
|
||||
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
|
||||
fn collect_windows_computer_name() -> io::Result<String> {
|
||||
let mut name = [0u16; 256];
|
||||
let mut size = name.len() as u32;
|
||||
// SAFETY: the buffer and character count describe writable UTF-16 storage.
|
||||
if unsafe { GetComputerNameExW(ComputerNamePhysicalNetBIOS, name.as_mut_ptr(), &mut size) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
String::from_utf16(&name[..size as usize]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
|
||||
}
|
||||
stdout.lines().find_map(|line| {
|
||||
let mut parts = line.split_whitespace();
|
||||
if parts.next()? != "MachineGuid" {
|
||||
return None;
|
||||
}
|
||||
|
||||
fn collect_windows_machine_guid() -> io::Result<String> {
|
||||
let key: Vec<u16> = "SOFTWARE\\Microsoft\\Cryptography\0".encode_utf16().collect();
|
||||
let value: Vec<u16> = "MachineGuid\0".encode_utf16().collect();
|
||||
let mut buffer = [0u16; 128];
|
||||
let mut size = std::mem::size_of_val(&buffer) as u32;
|
||||
// SAFETY: both names are NUL-terminated; buffer and byte length describe writable storage.
|
||||
let status = unsafe {
|
||||
RegGetValueW(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
key.as_ptr(),
|
||||
value.as_ptr(),
|
||||
RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY,
|
||||
std::ptr::null_mut(),
|
||||
buffer.as_mut_ptr().cast(),
|
||||
&mut size,
|
||||
)
|
||||
};
|
||||
if status != 0 {
|
||||
return Err(io::Error::from_raw_os_error(status as i32));
|
||||
}
|
||||
let end = buffer.iter().position(|value| *value == 0).unwrap_or(buffer.len());
|
||||
let guid = String::from_utf16(&buffer[..end]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
|
||||
if guid.trim().is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Windows MachineGuid is empty",
|
||||
));
|
||||
}
|
||||
Ok(guid)
|
||||
parts.last().map(str::to_string)
|
||||
})
|
||||
}
|
||||
|
||||
impl RuntimeNativeHostIdentity {
|
||||
|
||||
@@ -124,7 +124,8 @@ impl OsProfile {
|
||||
self.runtime_os == self.client_os
|
||||
}
|
||||
|
||||
/// Software version for the target OS profile.
|
||||
/// Default software version string for the target OS, matching the
|
||||
/// official client values.
|
||||
pub fn software_version(&self) -> &str {
|
||||
&self.software_version
|
||||
}
|
||||
|
||||
@@ -18,14 +18,14 @@ fn negotiated_os_version_is_used_in_profile_and_user_agent() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csc_support_defaults_match_platform_profiles() {
|
||||
fn csc_support_defaults_match_official_profiles() {
|
||||
assert!(!ClientOs::Linux.default_csc_support());
|
||||
assert!(ClientOs::Mac.default_csc_support());
|
||||
assert!(ClientOs::Windows.default_csc_support());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prelogin_param_location_matches_platform_profiles() {
|
||||
fn prelogin_param_location_matches_official_profiles() {
|
||||
assert_eq!(
|
||||
OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build(test_snapshot())
|
||||
@@ -91,7 +91,7 @@ fn embedded_gateway_default_browser_is_zero_for_all() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_default_browser_values_match_platform_profiles() {
|
||||
fn external_default_browser_values_match_official_profiles() {
|
||||
assert_eq!(
|
||||
OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build(test_snapshot())
|
||||
@@ -132,7 +132,7 @@ fn external_default_browser_values_match_platform_profiles() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saml_password_matches_platform_profiles() {
|
||||
fn saml_password_matches_official_profiles() {
|
||||
assert_eq!(
|
||||
OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build(test_snapshot())
|
||||
@@ -173,7 +173,7 @@ fn gateway_server_uses_resolved_ipv4_for_all() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kerberos_support_in_query_matches_platform_profiles() {
|
||||
fn kerberos_support_in_query_matches_official_profiles() {
|
||||
assert!(
|
||||
!OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build(test_snapshot())
|
||||
@@ -192,7 +192,7 @@ fn kerberos_support_in_query_matches_platform_profiles() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_vendor_matches_platform_profiles() {
|
||||
fn os_vendor_matches_official_profiles() {
|
||||
assert_eq!(
|
||||
OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build(test_snapshot())
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::bail;
|
||||
use log::{info, warn};
|
||||
use log::{debug, info, warn};
|
||||
use reqwest::{Client, StatusCode};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
@@ -207,13 +207,10 @@ pub async fn retrieve_config(
|
||||
}
|
||||
})?;
|
||||
|
||||
parse_gp_response(res).await.or_else(|mut err| {
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
|
||||
return Err(tls);
|
||||
}
|
||||
if let Some(error) = err.take_body_read_error() {
|
||||
return Err(PortalError::NetworkError(error).into());
|
||||
}
|
||||
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
|
||||
return Err(anyhow::anyhow!(crate::error::AuthenticationRejected));
|
||||
}
|
||||
@@ -235,6 +232,7 @@ pub async fn retrieve_config(
|
||||
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
|
||||
}
|
||||
|
||||
debug!("Portal config response received: {} bytes", res_xml.len());
|
||||
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||
|
||||
if csc::is_config_criteria(&root) {
|
||||
@@ -249,6 +247,7 @@ pub async fn retrieve_config(
|
||||
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
|
||||
result = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params) => result?,
|
||||
};
|
||||
debug!("Portal CSC config response received: {} bytes", csc_xml.len());
|
||||
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||
return parse_portal_policy(&server, cred, root, cancellation).await;
|
||||
}
|
||||
@@ -281,13 +280,10 @@ async fn retrieve_csc_config(
|
||||
}
|
||||
})?;
|
||||
|
||||
parse_gp_response(res).await.or_else(|mut err| {
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
|
||||
return Err(tls);
|
||||
}
|
||||
if let Some(error) = err.take_body_read_error() {
|
||||
return Err(PortalError::NetworkError(error).into());
|
||||
}
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use anyhow::{anyhow, bail};
|
||||
use log::{info, warn};
|
||||
use log::{debug, info, warn};
|
||||
use reqwest::{Client, StatusCode};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
@@ -174,8 +174,10 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
|
||||
Err(anyhow!(PortalError::PreloginError(err.reason)))
|
||||
})?;
|
||||
|
||||
debug!("Prelogin response XML: {}", res_xml);
|
||||
|
||||
let prelogin = parse_prelogin_response(&res_xml, is_gateway).map_err(|err| {
|
||||
warn!("Failed to parse prelogin response: {err}");
|
||||
warn!("Parse response error, response: {}", res_xml);
|
||||
PortalError::PreloginError(err.to_string())
|
||||
})?;
|
||||
|
||||
|
||||
@@ -17,17 +17,10 @@ use super::{
|
||||
command_traits::CommandExt,
|
||||
};
|
||||
|
||||
use super::rendering_recovery::{
|
||||
AUTH_STDERR_PREFIX, GbmBufferFailure, RenderingCrash, StderrDiagnostic, allows_shared_memory_override, eligible,
|
||||
is_crash_exit, is_gbm_diagnostic,
|
||||
};
|
||||
use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_crash_exit};
|
||||
|
||||
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
|
||||
|
||||
#[cfg(windows)]
|
||||
/// The caller that receives foreground permission after browser authentication.
|
||||
pub const AUTH_PARENT_PROCESS_ID_ENV: &str = "GPAUTH_PARENT_PROCESS_ID";
|
||||
|
||||
pub struct SamlAuthLauncher<'a> {
|
||||
cancellation: CancellationToken,
|
||||
server: &'a str,
|
||||
@@ -56,7 +49,6 @@ pub struct SamlAuthLauncher<'a> {
|
||||
verbose: Option<&'a str>,
|
||||
log_format: LogFormat,
|
||||
dmabuf_disabled: bool,
|
||||
desktop_compatibility_graphics: bool,
|
||||
}
|
||||
|
||||
impl<'a> SamlAuthLauncher<'a> {
|
||||
@@ -89,15 +81,9 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
verbose: None,
|
||||
log_format: LogFormat::Text,
|
||||
dmabuf_disabled: false,
|
||||
desktop_compatibility_graphics: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn desktop_compatibility_graphics(mut self) -> Self {
|
||||
self.desktop_compatibility_graphics = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn dmabuf_disabled(mut self, disabled: bool) -> Self {
|
||||
self.dmabuf_disabled = disabled;
|
||||
self
|
||||
@@ -211,8 +197,6 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
/// argument that never gets appended.
|
||||
fn build_command(&self, program: &Path) -> Command {
|
||||
let mut auth_cmd = Command::new(program);
|
||||
#[cfg(windows)]
|
||||
auth_cmd.env(AUTH_PARENT_PROCESS_ID_ENV, std::process::id().to_string());
|
||||
auth_cmd.arg(self.server);
|
||||
|
||||
if self.gateway {
|
||||
@@ -252,7 +236,7 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
if self.browser.is_none() {
|
||||
{
|
||||
if self.hidpi {
|
||||
auth_cmd.arg("--hidpi");
|
||||
}
|
||||
@@ -308,34 +292,15 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
if embedded && bundled && self.dmabuf_disabled {
|
||||
command.env("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
|
||||
}
|
||||
let desktop_webview = embedded && bundled && self.desktop_compatibility_graphics;
|
||||
let can_use_shared_memory = desktop_webview && allows_shared_memory_override(&command, true);
|
||||
let use_shared_memory = can_use_shared_memory && crate::gui::compatibility_graphics_enabled();
|
||||
if use_shared_memory {
|
||||
command.env(crate::gui::FORCE_SHARED_MEMORY, "1");
|
||||
}
|
||||
let detect_gbm_failure = can_use_shared_memory && !use_shared_memory;
|
||||
let stdin = auth_stdin(self.browser);
|
||||
let cancellation = self.cancellation.clone();
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
#[cfg(feature = "logger")]
|
||||
let stderr = crate::logger::diagnostic_writer();
|
||||
#[cfg(not(feature = "logger"))]
|
||||
let stderr: Box<dyn std::io::Write + Send> = Box::new(std::io::stderr());
|
||||
let mut stderr = if desktop_webview {
|
||||
Box::new(std::io::LineWriter::new(AuthStderr(stderr)))
|
||||
} else {
|
||||
stderr
|
||||
};
|
||||
let gbm_failed = std::cell::Cell::new(false);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Authentication cancelled",
|
||||
))
|
||||
} else if gbm_failed.get() {
|
||||
Err(std::io::Error::other(GbmBufferFailure))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
@@ -345,31 +310,19 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
command,
|
||||
&check,
|
||||
Some(MAX_AUTH_RESULT_BYTES),
|
||||
&mut |bytes| {
|
||||
diagnostic.push(bytes);
|
||||
gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(can_recover));
|
||||
},
|
||||
&mut stderr,
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut std::io::stderr(),
|
||||
stdin,
|
||||
);
|
||||
std::io::Write::flush(&mut stderr)?;
|
||||
if gbm_failed.get() && !cancellation.is_cancelled() {
|
||||
return Err(GbmBufferFailure.into());
|
||||
}
|
||||
let output = output?;
|
||||
Ok::<_, anyhow::Error>((output.output, diagnostic.matched()))
|
||||
)?;
|
||||
Ok::<_, std::io::Error>((output.output, diagnostic.matched()))
|
||||
})
|
||||
.await?;
|
||||
let (output, rendering_diagnostic) = match output {
|
||||
Ok(output) => output,
|
||||
Err(error)
|
||||
if error
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.is_some_and(|error| error.kind() == std::io::ErrorKind::Interrupted) =>
|
||||
{
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
|
||||
if self.cancellation.is_cancelled() {
|
||||
@@ -379,26 +332,6 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
// Attribute GBM failures to gpauth before forwarding them to the desktop supervisor.
|
||||
struct AuthStderr(Box<dyn std::io::Write + Send>);
|
||||
|
||||
impl std::io::Write for AuthStderr {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
for line in bytes.split_inclusive(|&byte| byte == b'\n') {
|
||||
if is_gbm_diagnostic(line) {
|
||||
self.0.write_all(&[AUTH_STDERR_PREFIX, line].concat())?;
|
||||
} else {
|
||||
self.0.write_all(line)?;
|
||||
}
|
||||
}
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.0.flush()
|
||||
}
|
||||
}
|
||||
|
||||
/// `gpauth --browser manual` reads the pasted `globalprotectcallback:` data from the user's terminal.
|
||||
fn auth_stdin(browser: Option<&str>) -> ChildInput<'static> {
|
||||
match browser {
|
||||
@@ -433,14 +366,11 @@ fn decode_auth_output(output: std::process::Output, rendering_failure: bool) ->
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::os_profile::{ClientOs, OsProfileBuilder};
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::process::ExitStatusExt;
|
||||
|
||||
#[test]
|
||||
fn server_tls_result_survives_process_decoding_as_a_typed_error() {
|
||||
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let output = std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com:8443","kind":"certificate"}}"#.to_vec(),
|
||||
@@ -459,6 +389,7 @@ mod tests {
|
||||
#[test]
|
||||
fn client_certificate_required_result_survives_process_decoding() {
|
||||
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let output = std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com","kind":"clientCertificateRequired"}}"#.to_vec(),
|
||||
@@ -478,42 +409,6 @@ mod tests {
|
||||
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[test]
|
||||
fn external_browser_receives_no_embedded_window_arguments() {
|
||||
let args = child_args(
|
||||
SamlAuthLauncher::new("vpn.example.com")
|
||||
.browser(Some("edge"))
|
||||
.clean(true)
|
||||
.hidpi(true)
|
||||
.window_title("GP Connect Login")
|
||||
.window_theme(AuthWindowTheme::Dark),
|
||||
);
|
||||
assert!(args.windows(2).any(|pair| pair == ["--browser", "edge"]));
|
||||
for option in ["--clean", "--hidpi", "--window-title", "--window-theme"] {
|
||||
assert!(!args.iter().any(|arg| arg == option), "unexpected {option} in {args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[test]
|
||||
fn embedded_window_receives_auth_preferences() {
|
||||
let args = child_args(
|
||||
SamlAuthLauncher::new("vpn.example.com")
|
||||
.clean(true)
|
||||
.window_title("GP Connect Login")
|
||||
.window_theme(AuthWindowTheme::Dark),
|
||||
);
|
||||
assert!(args.iter().any(|arg| arg == "--clean"));
|
||||
assert!(
|
||||
args
|
||||
.windows(2)
|
||||
.any(|pair| pair == ["--window-title", "GP Connect Login"])
|
||||
);
|
||||
assert!(args.windows(2).any(|pair| pair == ["--window-theme", "dark"]));
|
||||
assert!(!args.iter().any(|arg| arg == "--browser"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_profile_sets_os_from_profile() {
|
||||
let profile = OsProfileBuilder::new(ClientOs::Linux)
|
||||
@@ -556,19 +451,6 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn auth_child_receives_its_foreground_parent() {
|
||||
let command = SamlAuthLauncher::new("portal.example.com").build_command(Path::new("gpauth"));
|
||||
let parent = command
|
||||
.as_std()
|
||||
.get_envs()
|
||||
.find(|(name, _)| *name == AUTH_PARENT_PROCESS_ID_ENV)
|
||||
.and_then(|(_, value)| value)
|
||||
.expect("the authenticator must know its foreground recipient");
|
||||
assert_eq!(parent, std::process::id().to_string().as_str());
|
||||
}
|
||||
|
||||
/// gpauth writes to the same stderr as its parent, so a caller reading the
|
||||
/// parent's JSON would hit gpauth's text records mid-stream unless the format
|
||||
/// is passed down.
|
||||
@@ -631,14 +513,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() {
|
||||
#[cfg(unix)]
|
||||
let status = std::process::ExitStatus::from_raw(71 << 8);
|
||||
#[cfg(windows)]
|
||||
let status = std::process::ExitStatus::from_raw(0xC0000005);
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
for stdout in [b"{partial".to_vec(), br#"{"cancelled":null}"#.to_vec()] {
|
||||
let error = decode_auth_output(
|
||||
std::process::Output {
|
||||
status,
|
||||
status: std::process::ExitStatus::from_raw(71 << 8),
|
||||
stdout,
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
@@ -651,6 +530,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn successful_malformed_auth_output_is_not_a_rendering_crash() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let error = decode_auth_output(
|
||||
std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
@@ -664,7 +544,6 @@ mod tests {
|
||||
assert_eq!(error.to_string(), "Failed to parse auth data");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn custom_authenticator_crash_does_not_request_recovery() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
@@ -700,11 +579,8 @@ mod tests {
|
||||
std::fs::write(&custom, "custom").unwrap();
|
||||
assert!(is_bundled_authenticator(&bundled, &bundled));
|
||||
assert!(!is_bundled_authenticator(&custom, &bundled));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let alias = directory.path().join("auth-alias");
|
||||
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
|
||||
assert!(is_bundled_authenticator(&alias, &bundled));
|
||||
}
|
||||
let alias = directory.path().join("auth-alias");
|
||||
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
|
||||
assert!(is_bundled_authenticator(&alias, &bundled));
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,10 @@
|
||||
use super::{
|
||||
command_runner::{ChildInput, run_observed},
|
||||
rendering_recovery::{
|
||||
GbmBufferFailure, RenderingCrash, StderrDiagnostic, allows_shared_memory_override, eligible_with_inheritance,
|
||||
is_crash_exit,
|
||||
},
|
||||
rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible_with_inheritance, is_crash_exit},
|
||||
};
|
||||
use crate::service::transport::SessionCredential;
|
||||
use anyhow::Context;
|
||||
use std::{
|
||||
cell::Cell,
|
||||
collections::HashMap,
|
||||
fs::OpenOptions,
|
||||
path::PathBuf,
|
||||
@@ -23,10 +19,8 @@ pub(super) async fn launch_desktop_child(
|
||||
envs: Option<&HashMap<String, String>>,
|
||||
credential: &SessionCredential,
|
||||
cancellation: &CancellationToken,
|
||||
detect_gbm_failure: bool,
|
||||
) -> anyhow::Result<ExitStatus> {
|
||||
let retry_eligible = eligible_with_inheritance(&command, envs.is_none());
|
||||
let detect_gbm_failure = detect_gbm_failure && allows_shared_memory_override(&command, envs.is_none());
|
||||
let log_file = match envs {
|
||||
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
|
||||
None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from),
|
||||
@@ -44,15 +38,12 @@ pub(super) async fn launch_desktop_child(
|
||||
let cancellation = cancellation.clone();
|
||||
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let gbm_failed = Cell::new(false);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Desktop child launch cancelled",
|
||||
))
|
||||
} else if gbm_failed.get() {
|
||||
Err(std::io::Error::other(GbmBufferFailure))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
@@ -62,17 +53,10 @@ pub(super) async fn launch_desktop_child(
|
||||
command,
|
||||
&check,
|
||||
None,
|
||||
&mut |bytes| {
|
||||
diagnostic.push(bytes);
|
||||
gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(retry_eligible));
|
||||
},
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut sink,
|
||||
ChildInput::Frame(&frame),
|
||||
);
|
||||
if gbm_failed.get() && !cancellation.is_cancelled() {
|
||||
return Err(GbmBufferFailure.into());
|
||||
}
|
||||
let observed = observed?;
|
||||
)?;
|
||||
let output = observed.output;
|
||||
if is_crash_exit(output.status) && retry_eligible && diagnostic.matched() {
|
||||
return Err(RenderingCrash { status: output.status }.into());
|
||||
|
||||
@@ -170,11 +170,7 @@ impl<'a> DesktopLauncher<'a> {
|
||||
}
|
||||
match outcome {
|
||||
Err(error) if recovery.recover(&error) => {
|
||||
if recovery.shared_memory() {
|
||||
warn!("{error}; restarting the desktop launch with compatibility graphics");
|
||||
} else {
|
||||
warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows");
|
||||
}
|
||||
warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows");
|
||||
expecting_renewal = true;
|
||||
input.write_all(&[DESKTOP_RENDERING_RETRY]).await?;
|
||||
}
|
||||
|
||||
@@ -79,7 +79,6 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
self.envs,
|
||||
self.credential,
|
||||
cancellation,
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
|
||||
@@ -101,12 +101,6 @@ impl<'a> GuiLauncher<'a> {
|
||||
if let Some(envs) = &self.envs {
|
||||
cmd.env_clear().envs(envs);
|
||||
}
|
||||
if self.variant == crate::gui::GuiVariant::Tauri
|
||||
&& crate::gui::compatibility_graphics_enabled()
|
||||
&& super::rendering_recovery::allows_shared_memory_override(cmd.as_std(), self.envs.is_none())
|
||||
{
|
||||
cmd.env(crate::gui::FORCE_SHARED_MEMORY, "1");
|
||||
}
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
if self.minimized {
|
||||
cmd.arg("--minimized");
|
||||
@@ -118,7 +112,6 @@ impl<'a> GuiLauncher<'a> {
|
||||
self.envs.as_ref(),
|
||||
&self.credential,
|
||||
cancellation,
|
||||
self.variant == crate::gui::GuiVariant::Tauri,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -214,45 +207,32 @@ impl<'a> GuiLauncher<'a> {
|
||||
gui_switch::reply(&mut socket, Ok(GuiSwitchOutcome::DownloadRequired)).await?;
|
||||
return Ok(None);
|
||||
}
|
||||
use super::rendering_recovery::{GbmBufferFailure, RecoveryState};
|
||||
let mut recovery = RecoveryState::default();
|
||||
let mut program = program;
|
||||
let (mut child, start_result) = loop {
|
||||
service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?;
|
||||
pending = true;
|
||||
let credential = super::desktop_launcher::read_credential(service_output).await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?;
|
||||
anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||
let ready = gui_switch::SwitchListener::new()?;
|
||||
let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect());
|
||||
envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned());
|
||||
let launcher = Self::new(self.version, Arc::new(credential), variant)
|
||||
.envs(envs)
|
||||
.minimized(false);
|
||||
let executable = match &program {
|
||||
Some(program) => program.clone(),
|
||||
None => launcher.resolve_program(cancellation, command.theme).await?,
|
||||
};
|
||||
let mut child = launcher.start_owned(executable.clone(), cancellation.child_token());
|
||||
let start_result = tokio::select! {
|
||||
result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => {
|
||||
result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result)
|
||||
},
|
||||
outcome = &mut child.task => {
|
||||
match outcome? {
|
||||
Ok(status) => return Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")),
|
||||
Err(error) if error.is::<GbmBufferFailure>() && recovery.recover(&error) => {
|
||||
log::warn!("{error}; restarting the selected GUI with compatibility graphics");
|
||||
service_input.write_all(&[DESKTOP_SWITCH_CANCEL]).await?;
|
||||
pending = false;
|
||||
program = Some(executable);
|
||||
continue;
|
||||
}
|
||||
Err(error) => return Err(recovery.terminal(error)),
|
||||
}
|
||||
}
|
||||
};
|
||||
break (child, start_result);
|
||||
service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?;
|
||||
pending = true;
|
||||
let credential = super::desktop_launcher::read_credential(service_output).await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?;
|
||||
anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||
let ready = gui_switch::SwitchListener::new()?;
|
||||
let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect());
|
||||
envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned());
|
||||
let launcher = Self::new(self.version, Arc::new(credential), variant)
|
||||
.envs(envs)
|
||||
.minimized(false);
|
||||
let program = match program {
|
||||
Some(program) => program,
|
||||
None => launcher.resolve_program(cancellation, command.theme).await?,
|
||||
};
|
||||
let mut child = launcher.start_owned(program, cancellation.child_token());
|
||||
let start_result = tokio::select! {
|
||||
result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => {
|
||||
result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result)
|
||||
},
|
||||
outcome = &mut child.task => {
|
||||
return match outcome? {
|
||||
Ok(status) => Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
}
|
||||
};
|
||||
if let Err(error) = start_result.and_then(|()| crate::gui::save_preference(variant)) {
|
||||
child.cancel.cancel();
|
||||
|
||||
@@ -1,41 +1,20 @@
|
||||
#[cfg(unix)]
|
||||
mod command_runner;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/command_runner.rs"]
|
||||
mod command_runner;
|
||||
#[cfg(unix)]
|
||||
mod command_traits;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/command_traits.rs"]
|
||||
mod command_traits;
|
||||
#[cfg(unix)]
|
||||
mod desktop_child;
|
||||
#[cfg(unix)]
|
||||
mod desktop_session_env;
|
||||
#[cfg(unix)]
|
||||
pub(crate) mod gui_helper_launcher;
|
||||
|
||||
pub use command_traits::CommandExt;
|
||||
|
||||
pub mod auth_launcher;
|
||||
#[cfg(unix)]
|
||||
pub mod desktop_launcher;
|
||||
#[cfg(unix)]
|
||||
pub mod gui_launcher;
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
pub mod gui_switch;
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod nsh_runtime;
|
||||
#[cfg(unix)]
|
||||
pub mod users;
|
||||
|
||||
#[cfg(unix)]
|
||||
pub mod collection;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/collection.rs"]
|
||||
pub mod collection;
|
||||
|
||||
pub mod rendering_recovery;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/user_process.rs"]
|
||||
pub mod user_process;
|
||||
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user