mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 14:36:15 -05:00
Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6cf639887 | ||
|
|
197cd5748d | ||
|
|
907e161b12 | ||
|
|
b26a416f45 | ||
|
|
0212b7ff91 | ||
|
|
9001b768c1 | ||
|
|
a02dfd10ab | ||
|
|
6ebffad3c8 | ||
|
|
c84bfcc13a | ||
|
|
aa92251d47 | ||
|
|
b15bc2bfa5 | ||
|
|
d825e2b9c8 | ||
|
|
dcc74d805b | ||
|
|
43eda033e5 | ||
|
|
54b4d810d9 | ||
|
|
e108ce50dc | ||
|
|
18ce000640 | ||
|
|
14c4e24e0e | ||
|
|
37c88c7adb | ||
|
|
f2ec8c7770 | ||
|
|
1698397af3 | ||
|
|
eb8f919121 | ||
|
|
b4529398b0 | ||
|
|
c53911e7b8 | ||
|
|
580438e8eb | ||
|
|
92943e0a9d | ||
|
|
6f2f8e1265 | ||
|
|
f643180b59 | ||
|
|
3a643fe6ff | ||
|
|
66b1cf3c47 | ||
|
|
472806ca73 | ||
|
|
d7de2df53b | ||
|
|
6ef2f0497d | ||
|
|
0436a18e42 | ||
|
|
56489a4e90 | ||
|
|
6316f8d68e | ||
|
|
d9e00bc3c9 | ||
|
|
e284840d89 | ||
|
|
0df25fbd28 | ||
|
|
8e3bb8ff11 | ||
|
|
a7c571a2c1 | ||
|
|
2b38de10f6 | ||
|
|
4aa7b66313 | ||
|
|
ce5a19c131 | ||
|
|
e7ddc2ca2a | ||
|
|
4635b1b4b8 | ||
|
|
0cb246b0c5 | ||
|
|
fabc7d4461 | ||
|
|
d2fcf66be8 | ||
|
|
ae504dfbbe | ||
|
|
fca3076b64 | ||
|
|
c29c57639a | ||
|
|
da90bc80e3 |
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:
|
channel:
|
||||||
required: true
|
required: true
|
||||||
type: string
|
type: string
|
||||||
build:
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
builder:
|
builder:
|
||||||
required: true
|
required: true
|
||||||
type: string
|
type: string
|
||||||
@@ -88,7 +85,7 @@ jobs:
|
|||||||
- name: Build gpgui in Docker
|
- name: Build gpgui in Docker
|
||||||
env:
|
env:
|
||||||
GPGUI_BUILDER: ${{ inputs.builder }}
|
GPGUI_BUILDER: ${{ inputs.builder }}
|
||||||
GPGUI_BUILD_VERSION: ${{ inputs.build }}
|
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
||||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -12,9 +12,6 @@ on:
|
|||||||
channel:
|
channel:
|
||||||
required: true
|
required: true
|
||||||
type: string
|
type: string
|
||||||
build:
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
secrets:
|
secrets:
|
||||||
GH_PAT:
|
GH_PAT:
|
||||||
required: true
|
required: true
|
||||||
@@ -38,7 +35,7 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
CARGO_INCREMENTAL: '0'
|
CARGO_INCREMENTAL: '0'
|
||||||
CARGO_BUILD_JOBS: '2'
|
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_GIT_COMMIT: ${{ inputs.gpgui_ref }}
|
||||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
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
|
required: true
|
||||||
default: false
|
default: false
|
||||||
type: boolean
|
type: boolean
|
||||||
build_windows:
|
|
||||||
description: 'Build Windows x64 and ARM64 NSH installers'
|
|
||||||
required: true
|
|
||||||
default: false
|
|
||||||
type: boolean
|
|
||||||
push:
|
push:
|
||||||
paths-ignore:
|
paths-ignore:
|
||||||
- LICENSE
|
- LICENSE
|
||||||
@@ -69,10 +64,8 @@ jobs:
|
|||||||
actions: read
|
actions: read
|
||||||
contents: read
|
contents: read
|
||||||
outputs:
|
outputs:
|
||||||
gp_sha: ${{ steps.identity.outputs.gp_sha }}
|
gp_sha: ${{ steps.sources.outputs.gp_sha }}
|
||||||
gpgui_sha: ${{ steps.identity.outputs.gpgui_sha }}
|
gpgui_sha: ${{ steps.sources.outputs.gpgui_sha }}
|
||||||
version: ${{ steps.identity.outputs.version }}
|
|
||||||
build_version: ${{ steps.identity.outputs.build_version }}
|
|
||||||
steps:
|
steps:
|
||||||
- name: Validate stable refs
|
- name: Validate stable refs
|
||||||
env:
|
env:
|
||||||
@@ -121,12 +114,11 @@ jobs:
|
|||||||
token: ${{ secrets.GH_PAT }}
|
token: ${{ secrets.GH_PAT }}
|
||||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
||||||
path: selected/gpgui
|
path: selected/gpgui
|
||||||
- name: Record selected sources and versions
|
- name: Record selected sources
|
||||||
id: identity
|
id: sources
|
||||||
run: |
|
run: |
|
||||||
python3 scripts/record-build-sources.py selected-sources/sources.json \
|
python3 scripts/record-build-sources.py selected-sources/sources.json \
|
||||||
--gp selected/gp --gpgui selected/gpgui \
|
--gp selected/gp --gpgui selected/gpgui
|
||||||
--build-version "${{ github.run_number }}.${{ github.run_attempt }}"
|
|
||||||
- name: Retain selected sources for retries
|
- name: Retain selected sources for retries
|
||||||
if: steps.restored.outputs.cached != 'true'
|
if: steps.restored.outputs.cached != 'true'
|
||||||
uses: actions/upload-artifact@v7
|
uses: actions/upload-artifact@v7
|
||||||
@@ -163,7 +155,7 @@ jobs:
|
|||||||
# Tauri generates schemas in the source tree. Keep the host checkout read-only.
|
# Tauri generates schemas in the source tree. Keep the host checkout read-only.
|
||||||
cp -R /workspace /tmp/gp-test-workspace
|
cp -R /workspace /tmp/gp-test-workspace
|
||||||
cd /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.
|
# Exercise only the paths that require an actual root process.
|
||||||
sudo -E env PATH="$PATH" PKEXEC_UID="$(id -u)" cargo test --locked -p gpapi \
|
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 }}
|
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
|
||||||
builder: gpgui-builder-tauri2
|
builder: gpgui-builder-tauri2
|
||||||
verify_desktop_assets: true
|
verify_desktop_assets: true
|
||||||
secrets:
|
secrets:
|
||||||
@@ -459,7 +450,6 @@ jobs:
|
|||||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
|
||||||
builder: gpgui-alpine-builder-tauri2
|
builder: gpgui-alpine-builder-tauri2
|
||||||
artifact_suffix: -musl
|
artifact_suffix: -musl
|
||||||
secrets:
|
secrets:
|
||||||
@@ -472,31 +462,9 @@ jobs:
|
|||||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
|
||||||
secrets:
|
secrets:
|
||||||
GH_PAT: ${{ secrets.GH_PAT }}
|
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:
|
nix-source:
|
||||||
needs: [validate-inputs, build-gpgui-glibc]
|
needs: [validate-inputs, build-gpgui-glibc]
|
||||||
strategy:
|
strategy:
|
||||||
@@ -691,7 +659,7 @@ jobs:
|
|||||||
FEED_URL: ${{ vars.SPARKLE_FEED_URL }}
|
FEED_URL: ${{ vars.SPARKLE_FEED_URL }}
|
||||||
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
|
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) }}
|
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: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
@@ -859,7 +827,7 @@ jobs:
|
|||||||
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
|
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) }}
|
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) }}
|
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 }}
|
WORKFLOW_SHA: ${{ github.sha }}
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -1058,6 +1026,7 @@ jobs:
|
|||||||
nettle \
|
nettle \
|
||||||
gmp \
|
gmp \
|
||||||
gnome-keyring \
|
gnome-keyring \
|
||||||
|
libayatana-appindicator \
|
||||||
polkit \
|
polkit \
|
||||||
webkit2-gtk_41
|
webkit2-gtk_41
|
||||||
pkgconf --exists libxml-2.0 liblz4 gnutls p11-kit-1 hogweed nettle gmp
|
pkgconf --exists libxml-2.0 liblz4 gnutls p11-kit-1 hogweed nettle gmp
|
||||||
@@ -1066,7 +1035,7 @@ jobs:
|
|||||||
exec 3>&1
|
exec 3>&1
|
||||||
(
|
(
|
||||||
set -eu
|
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_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||||
|
|
||||||
@@ -1150,7 +1119,7 @@ jobs:
|
|||||||
set -eu
|
set -eu
|
||||||
export AUTOCONF_VERSION=2.72
|
export AUTOCONF_VERSION=2.72
|
||||||
export AUTOMAKE_VERSION=1.17
|
export AUTOMAKE_VERSION=1.17
|
||||||
export GPGUI_BUILD_VERSION=${{ 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_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||||
|
|
||||||
@@ -1222,7 +1191,6 @@ jobs:
|
|||||||
- build-gpgui-glibc
|
- build-gpgui-glibc
|
||||||
- build-gpgui-musl
|
- build-gpgui-musl
|
||||||
- build-gpgui-nsh
|
- build-gpgui-nsh
|
||||||
- build-windows
|
|
||||||
- setup-bsd-matrix
|
- setup-bsd-matrix
|
||||||
- build-gpgui-frontend
|
- build-gpgui-frontend
|
||||||
- build-bsd
|
- build-bsd
|
||||||
@@ -1233,7 +1201,6 @@ jobs:
|
|||||||
NEEDS_JSON: ${{ toJson(needs) }}
|
NEEDS_JSON: ${{ toJson(needs) }}
|
||||||
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
|
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
|
||||||
IS_STABLE: ${{ (startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
|
IS_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: |
|
run: |
|
||||||
python3 - <<'PY'
|
python3 - <<'PY'
|
||||||
import json
|
import json
|
||||||
@@ -1253,8 +1220,6 @@ jobs:
|
|||||||
continue
|
continue
|
||||||
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
|
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
|
||||||
continue
|
continue
|
||||||
elif name == "build-windows" and result == "skipped" and os.environ["BUILD_WINDOWS"] != "true":
|
|
||||||
continue
|
|
||||||
elif result == "skipped":
|
elif result == "skipped":
|
||||||
failed.append(f"{name}: {result}")
|
failed.append(f"{name}: {result}")
|
||||||
|
|
||||||
@@ -1321,61 +1286,6 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
|
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:
|
publish-docker-image:
|
||||||
needs:
|
needs:
|
||||||
- validate-inputs
|
- validate-inputs
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ jobs:
|
|||||||
gettext \
|
gettext \
|
||||||
gmp \
|
gmp \
|
||||||
gnutls \
|
gnutls \
|
||||||
|
libappindicator-gtk3 \
|
||||||
libp11-kit \
|
libp11-kit \
|
||||||
libsecret \
|
libsecret \
|
||||||
libtool \
|
libtool \
|
||||||
|
|||||||
@@ -1,21 +1,6 @@
|
|||||||
name: Publish macOS assets
|
name: Publish macOS assets
|
||||||
|
|
||||||
on:
|
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:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
build_run_id:
|
build_run_id:
|
||||||
|
|||||||
@@ -34,10 +34,6 @@ on:
|
|||||||
highlights:
|
highlights:
|
||||||
required: false
|
required: false
|
||||||
type: string
|
type: string
|
||||||
unix_snapshot_build:
|
|
||||||
description: Verified Unix snapshot build when it differs from the macOS retry
|
|
||||||
required: false
|
|
||||||
type: string
|
|
||||||
unix_platforms:
|
unix_platforms:
|
||||||
required: false
|
required: false
|
||||||
default: linux,freebsd,openbsd
|
default: linux,freebsd,openbsd
|
||||||
@@ -79,10 +75,6 @@ on:
|
|||||||
description: Stable release highlights, one per line
|
description: Stable release highlights, one per line
|
||||||
required: false
|
required: false
|
||||||
type: string
|
type: string
|
||||||
unix_snapshot_build:
|
|
||||||
description: Verified Unix snapshot build; omit when it matches the macOS build
|
|
||||||
required: false
|
|
||||||
type: string
|
|
||||||
unix_platforms:
|
unix_platforms:
|
||||||
description: Comma-separated Unix platforms with published assets (linux,freebsd,openbsd)
|
description: Comma-separated Unix platforms with published assets (linux,freebsd,openbsd)
|
||||||
required: true
|
required: true
|
||||||
@@ -95,8 +87,7 @@ concurrency:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish:
|
publish:
|
||||||
# Feed verification runs host tools, so it can use Intel runner capacity.
|
runs-on: ${{ vars.MACOS_RUNNER || 'macos-15' }}
|
||||||
runs-on: macos-26-intel
|
|
||||||
environment: macos-release
|
environment: macos-release
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -112,7 +103,6 @@ jobs:
|
|||||||
SPARKLE_VERSION: 2.9.2
|
SPARKLE_VERSION: 2.9.2
|
||||||
UPDATE_HIGHLIGHTS: ${{ inputs.highlights }}
|
UPDATE_HIGHLIGHTS: ${{ inputs.highlights }}
|
||||||
UNIX_PLATFORMS: ${{ inputs.unix_platforms }}
|
UNIX_PLATFORMS: ${{ inputs.unix_platforms }}
|
||||||
UNIX_SNAPSHOT_BUILD: ${{ inputs.unix_snapshot_build }}
|
|
||||||
SPARKLE_ARCHIVE_SHA256: b83e37436774556ed055e0244b297ef2c790e0737393bf65bf495fcbba6eed65
|
SPARKLE_ARCHIVE_SHA256: b83e37436774556ed055e0244b297ef2c790e0737393bf65bf495fcbba6eed65
|
||||||
steps:
|
steps:
|
||||||
- name: Validate inputs
|
- name: Validate inputs
|
||||||
@@ -135,12 +125,6 @@ jobs:
|
|||||||
echo "unix_platforms must list published Unix targets separated by commas" >&2
|
echo "unix_platforms must list published Unix targets separated by commas" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
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
|
if [[ "$CHANNEL" == "snapshot" && "$RELEASE_TAG" != "snapshot" ]]; then
|
||||||
echo "The snapshot channel must publish to the snapshot release" >&2
|
echo "The snapshot channel must publish to the snapshot release" >&2
|
||||||
exit 1
|
exit 1
|
||||||
@@ -359,7 +343,6 @@ jobs:
|
|||||||
echo "short_version=$short_version" >> "$GITHUB_OUTPUT"
|
echo "short_version=$short_version" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Prepare Unix update manifest
|
- name: Prepare Unix update manifest
|
||||||
id: unix_manifest
|
|
||||||
env:
|
env:
|
||||||
RELEASED_AT: ${{ steps.release.outputs.released_at }}
|
RELEASED_AT: ${{ steps.release.outputs.released_at }}
|
||||||
run: |
|
run: |
|
||||||
@@ -400,8 +383,7 @@ jobs:
|
|||||||
else
|
else
|
||||||
printf 'Development snapshot after %s.\n' \
|
printf 'Development snapshot after %s.\n' \
|
||||||
"${{ steps.bundle.outputs.short_version }}" > "$highlights"
|
"${{ steps.bundle.outputs.short_version }}" > "$highlights"
|
||||||
unix_build="${UNIX_SNAPSHOT_BUILD:-${{ steps.bundle.outputs.version }}}"
|
generate_args+=(--build "${{ steps.bundle.outputs.version }}")
|
||||||
generate_args+=(--build "$unix_build")
|
|
||||||
released_at="$(date -u +%F)"
|
released_at="$(date -u +%F)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -410,9 +392,6 @@ jobs:
|
|||||||
--released-at "$released_at" \
|
--released-at "$released_at" \
|
||||||
--highlights-file "$highlights" \
|
--highlights-file "$highlights" \
|
||||||
--output "$manifest"
|
--output "$manifest"
|
||||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
|
||||||
echo "build=$unix_build" >> "$GITHUB_OUTPUT"
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Fetch current appcast
|
- name: Fetch current appcast
|
||||||
id: current-appcast
|
id: current-appcast
|
||||||
@@ -548,13 +527,6 @@ jobs:
|
|||||||
--channel "$CHANNEL" \
|
--channel "$CHANNEL" \
|
||||||
--archive-url "https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/$ARCHIVE_NAME"
|
--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
|
- name: Deploy update feed worker
|
||||||
env:
|
env:
|
||||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||||
@@ -608,7 +580,7 @@ jobs:
|
|||||||
--version "${{ steps.bundle.outputs.short_version }}"
|
--version "${{ steps.bundle.outputs.short_version }}"
|
||||||
)
|
)
|
||||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
if [[ "$CHANNEL" == "snapshot" ]]; then
|
||||||
expected+=(--build "${{ steps.unix_manifest.outputs.build }}")
|
expected+=(--build "${{ steps.bundle.outputs.version }}")
|
||||||
fi
|
fi
|
||||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||||
if curl --fail --location --silent --show-error \
|
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
|
|
||||||
@@ -16,6 +16,3 @@ gen
|
|||||||
|
|
||||||
# Nix files
|
# Nix files
|
||||||
result
|
result
|
||||||
|
|
||||||
# Packages & test assets
|
|
||||||
*.ipa
|
|
||||||
Generated
+34
-99
@@ -292,13 +292,11 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "auth"
|
name = "auth"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"block2",
|
"block2",
|
||||||
"browser-launcher",
|
"browser-launcher",
|
||||||
"common",
|
|
||||||
"dunce",
|
|
||||||
"gpapi",
|
"gpapi",
|
||||||
"gtk",
|
"gtk",
|
||||||
"html-escape",
|
"html-escape",
|
||||||
@@ -309,7 +307,6 @@ dependencies = [
|
|||||||
"objc2-security",
|
"objc2-security",
|
||||||
"objc2-web-kit",
|
"objc2-web-kit",
|
||||||
"regex",
|
"regex",
|
||||||
"serde_json",
|
|
||||||
"tauri",
|
"tauri",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"tiny_http",
|
"tiny_http",
|
||||||
@@ -319,10 +316,6 @@ dependencies = [
|
|||||||
"uuid",
|
"uuid",
|
||||||
"uzers",
|
"uzers",
|
||||||
"webkit2gtk",
|
"webkit2gtk",
|
||||||
"webview2-com",
|
|
||||||
"windows",
|
|
||||||
"windows-sys 0.61.2",
|
|
||||||
"winreg 0.55.0",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -554,14 +547,13 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "browser-launcher"
|
name = "browser-launcher"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"log",
|
"log",
|
||||||
"open",
|
"open",
|
||||||
"webbrowser",
|
"webbrowser",
|
||||||
"which",
|
"which",
|
||||||
"winreg 0.55.0",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -919,7 +911,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "common"
|
name = "common"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"tempfile",
|
"tempfile",
|
||||||
]
|
]
|
||||||
@@ -1559,7 +1551,7 @@ dependencies = [
|
|||||||
"rustc_version",
|
"rustc_version",
|
||||||
"toml 1.1.8+spec-1.1.0",
|
"toml 1.1.8+spec-1.1.0",
|
||||||
"vswhom",
|
"vswhom",
|
||||||
"winreg 0.56.0",
|
"winreg",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1663,16 +1655,6 @@ dependencies = [
|
|||||||
"rustc_version",
|
"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]]
|
[[package]]
|
||||||
name = "filedescriptor"
|
name = "filedescriptor"
|
||||||
version = "0.8.3"
|
version = "0.8.3"
|
||||||
@@ -2131,17 +2113,9 @@ dependencies = [
|
|||||||
"system-deps",
|
"system-deps",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "gp-xml"
|
|
||||||
version = "3.5.0"
|
|
||||||
dependencies = [
|
|
||||||
"url",
|
|
||||||
"xmltree",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "gpapi"
|
name = "gpapi"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
@@ -2150,14 +2124,11 @@ dependencies = [
|
|||||||
"chrono",
|
"chrono",
|
||||||
"clap",
|
"clap",
|
||||||
"clap-verbosity-flag",
|
"clap-verbosity-flag",
|
||||||
"cms",
|
|
||||||
"common",
|
"common",
|
||||||
"directories",
|
"directories",
|
||||||
"dns-lookup",
|
"dns-lookup",
|
||||||
"env_logger",
|
"env_logger",
|
||||||
"file-rotate",
|
|
||||||
"getrandom 0.4.3",
|
"getrandom 0.4.3",
|
||||||
"gp-xml",
|
|
||||||
"gtk",
|
"gtk",
|
||||||
"humantime",
|
"humantime",
|
||||||
"libloading 0.9.0",
|
"libloading 0.9.0",
|
||||||
@@ -2171,7 +2142,6 @@ dependencies = [
|
|||||||
"oslog",
|
"oslog",
|
||||||
"p12-keystore",
|
"p12-keystore",
|
||||||
"pem",
|
"pem",
|
||||||
"pkcs12",
|
|
||||||
"pkcs8",
|
"pkcs8",
|
||||||
"pkg-config",
|
"pkg-config",
|
||||||
"proptest",
|
"proptest",
|
||||||
@@ -2179,7 +2149,7 @@ dependencies = [
|
|||||||
"reqwest",
|
"reqwest",
|
||||||
"rustls",
|
"rustls",
|
||||||
"rustls-pemfile",
|
"rustls-pemfile",
|
||||||
"rustls-platform-verifier",
|
"sec1",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_urlencoded",
|
"serde_urlencoded",
|
||||||
@@ -2197,7 +2167,6 @@ dependencies = [
|
|||||||
"uuid",
|
"uuid",
|
||||||
"uzers",
|
"uzers",
|
||||||
"whoami",
|
"whoami",
|
||||||
"windows-sys 0.61.2",
|
|
||||||
"x509-cert",
|
"x509-cert",
|
||||||
"xmltree",
|
"xmltree",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
@@ -2205,7 +2174,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "gpauth"
|
name = "gpauth"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"auth",
|
"auth",
|
||||||
@@ -2213,6 +2182,7 @@ dependencies = [
|
|||||||
"common",
|
"common",
|
||||||
"compile-time",
|
"compile-time",
|
||||||
"gpapi",
|
"gpapi",
|
||||||
|
"home",
|
||||||
"log",
|
"log",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
@@ -2223,7 +2193,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "gpclient"
|
name = "gpclient"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
@@ -2254,7 +2224,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "gpgui-helper"
|
name = "gpgui-helper"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
@@ -2275,26 +2245,24 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "gphip"
|
name = "gphip"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"askama",
|
"askama",
|
||||||
"chrono",
|
"chrono",
|
||||||
"gpapi",
|
"gpapi",
|
||||||
"log",
|
|
||||||
"netdev",
|
"netdev",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_urlencoded",
|
"serde_urlencoded",
|
||||||
"uuid",
|
"uuid",
|
||||||
"uzers",
|
"uzers",
|
||||||
"windows",
|
|
||||||
"xmltree",
|
"xmltree",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "gpservice"
|
name = "gpservice"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"axum",
|
"axum",
|
||||||
@@ -2303,7 +2271,6 @@ dependencies = [
|
|||||||
"common",
|
"common",
|
||||||
"compile-time",
|
"compile-time",
|
||||||
"env_logger",
|
"env_logger",
|
||||||
"file-rotate",
|
|
||||||
"futures",
|
"futures",
|
||||||
"getrandom 0.4.3",
|
"getrandom 0.4.3",
|
||||||
"gpapi",
|
"gpapi",
|
||||||
@@ -2324,15 +2291,13 @@ dependencies = [
|
|||||||
"tokio-tungstenite 0.30.0",
|
"tokio-tungstenite 0.30.0",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
"uuid",
|
"uuid",
|
||||||
"windows-service",
|
|
||||||
"windows-sys 0.61.2",
|
|
||||||
"xz2",
|
"xz2",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "gptunnel"
|
name = "gptunnel"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"gpapi",
|
"gpapi",
|
||||||
"log",
|
"log",
|
||||||
@@ -2344,17 +2309,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "gpvpnc"
|
name = "gpvpnc"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.23.1",
|
|
||||||
"ipnet",
|
|
||||||
"log",
|
"log",
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"tempfile",
|
|
||||||
"uuid",
|
|
||||||
"windows-sys 0.61.2",
|
|
||||||
"winreg 0.56.0",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2472,6 +2429,15 @@ dependencies = [
|
|||||||
"digest 0.11.3",
|
"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]]
|
[[package]]
|
||||||
name = "html-escape"
|
name = "html-escape"
|
||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
@@ -2847,9 +2813,6 @@ name = "ipnet"
|
|||||||
version = "2.12.2"
|
version = "2.12.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
|
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
|
||||||
dependencies = [
|
|
||||||
"serde",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "is-docker"
|
name = "is-docker"
|
||||||
@@ -3860,18 +3823,16 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "openconnect"
|
name = "openconnect"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"autotools",
|
"autotools",
|
||||||
"cc",
|
"cc",
|
||||||
"fs_extra",
|
"fs_extra",
|
||||||
"gp-xml",
|
|
||||||
"is_executable",
|
"is_executable",
|
||||||
"libc",
|
"libc",
|
||||||
"log",
|
"log",
|
||||||
"pkg-config",
|
"pkg-config",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"windows-sys 0.61.2",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4919,6 +4880,16 @@ dependencies = [
|
|||||||
"sha2 0.11.1",
|
"sha2 0.11.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sec1"
|
||||||
|
version = "0.8.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d"
|
||||||
|
dependencies = [
|
||||||
|
"der",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "security-framework"
|
name = "security-framework"
|
||||||
version = "3.7.0"
|
version = "3.7.0"
|
||||||
@@ -6767,12 +6738,6 @@ dependencies = [
|
|||||||
"web-sys",
|
"web-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "widestring"
|
|
||||||
version = "1.2.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winapi"
|
name = "winapi"
|
||||||
version = "0.3.9"
|
version = "0.3.9"
|
||||||
@@ -6923,17 +6888,6 @@ dependencies = [
|
|||||||
"windows-link",
|
"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]]
|
[[package]]
|
||||||
name = "windows-strings"
|
name = "windows-strings"
|
||||||
version = "0.5.1"
|
version = "0.5.1"
|
||||||
@@ -6961,15 +6915,6 @@ dependencies = [
|
|||||||
"windows-targets 0.52.6",
|
"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]]
|
[[package]]
|
||||||
name = "windows-sys"
|
name = "windows-sys"
|
||||||
version = "0.61.2"
|
version = "0.61.2"
|
||||||
@@ -7136,16 +7081,6 @@ dependencies = [
|
|||||||
"memchr",
|
"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]]
|
[[package]]
|
||||||
name = "winreg"
|
name = "winreg"
|
||||||
version = "0.56.0"
|
version = "0.56.0"
|
||||||
|
|||||||
+2
-1
@@ -11,7 +11,7 @@ members = [
|
|||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
rust-version = "1.91"
|
rust-version = "1.91"
|
||||||
version = "3.5.0"
|
version = "3.2.0"
|
||||||
authors = ["Kevin Yue <[email protected]>"]
|
authors = ["Kevin Yue <[email protected]>"]
|
||||||
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
@@ -24,6 +24,7 @@ base64 = { version = "0.23", default-features = false, features = ["std"] }
|
|||||||
chrono = "0.4"
|
chrono = "0.4"
|
||||||
clap = { version = "4", features = ["derive"] }
|
clap = { version = "4", features = ["derive"] }
|
||||||
clap-verbosity-flag = "3"
|
clap-verbosity-flag = "3"
|
||||||
|
ctrlc = "3.4"
|
||||||
directories = "6.0"
|
directories = "6.0"
|
||||||
dns-lookup = "4.0.2"
|
dns-lookup = "4.0.2"
|
||||||
env_logger = "0.11"
|
env_logger = "0.11"
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
# GlobalProtect-openconnect
|
# 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 with support for SSO authentication. It provides command-line tools 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.
|
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<picture>
|
<picture>
|
||||||
@@ -21,107 +19,150 @@ A GlobalProtect VPN client built on OpenConnect. GP Connect runs on Windows, mac
|
|||||||
- [Command-Line Interface](#command-line-interface)
|
- [Command-Line Interface](#command-line-interface)
|
||||||
- [Graphical User Interface](#graphical-user-interface)
|
- [Graphical User Interface](#graphical-user-interface)
|
||||||
- [Installation](#installation)
|
- [Installation](#installation)
|
||||||
- [Windows](#windows)
|
|
||||||
- [macOS](#macos)
|
- [macOS](#macos)
|
||||||
- [Debian / Ubuntu](#debian--ubuntu)
|
- [Debian / Ubuntu](#debian--ubuntu)
|
||||||
- [Arch Linux / Manjaro](#arch-linux--manjaro)
|
- [Arch Linux / Manjaro](#arch-linux--manjaro)
|
||||||
- [Fedora / RHEL](#fedora--rhel)
|
- [Fedora 38+ / Rawhide](#fedora-38--rawhide)
|
||||||
- [openSUSE](#opensuse)
|
- [openSUSE Leap 15.6+ / Tumbleweed](#opensuse-leap-156--tumbleweed)
|
||||||
|
- [Other RPM-based Distributions](#other-rpm-based-distributions)
|
||||||
- [Alpine Linux](#alpine-linux)
|
- [Alpine Linux](#alpine-linux)
|
||||||
- [FreeBSD](#freebsd)
|
- [FreeBSD](#freebsd)
|
||||||
- [OpenBSD](#openbsd)
|
- [OpenBSD](#openbsd)
|
||||||
- [Gentoo](#gentoo)
|
- [Gentoo](#gentoo)
|
||||||
- [NixOS](#nixos)
|
- [NixOS](#nixos)
|
||||||
- [Docker](#docker)
|
- [Official Docker Image](#official-docker-image)
|
||||||
- [Other Distributions](#other-distributions)
|
- [Other Distributions](#other-distributions)
|
||||||
- [Building from Source](#building-from-source)
|
- [Building from Source](#building-from-source)
|
||||||
- [Troubleshooting](#troubleshooting)
|
- [Frequently Asked Questions](#frequently-asked-questions)
|
||||||
- [NetworkManager Integration](#networkmanager-integration)
|
- [NetworkManager Integration](#networkmanager-integration)
|
||||||
- [Licensing](#licensing)
|
- [Licensing](#licensing)
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Multi-Platform** – Windows (x64 and ARM64), macOS (Apple silicon), Linux, FreeBSD, and OpenBSD
|
- **Desktop Platform Support** – macOS, Linux, FreeBSD, and OpenBSD
|
||||||
- **Dual Interfaces** – Desktop GUI (**GP Connect**) and terminal CLI (`gpclient`, on macOS, Linux, and BSD)
|
- **Dual Interface** – Available as both CLI and GUI applications
|
||||||
- **Native Shell on Linux** – Ultra-low-memory native desktop GUI alongside the webview interface
|
- **Flexible Authentication** – Supports SSO, non-SSO, FIDO2 (e.g., YubiKey), and client certificate authentication
|
||||||
- **Flexible Routing** – Full System VPN tunnel or local SOCKS5 proxy mode
|
- **Browser Integration** – Authenticate using your default browser or any specified browser
|
||||||
- **Modern Authentication** – SAML / SSO, MFA, FIDO2 (YubiKey), client certificates, and external browser login
|
- **Multi-Portal Support** – Connect to multiple portals and gateways
|
||||||
- **Automated HIP Reports** – Built-in HIP report generation or custom scripts
|
- **Direct Gateway Connection** – Bypass portal selection when needed
|
||||||
- **Multi-Portal & Direct Gateway** – Manage multiple saved portals or connect directly to a gateway
|
- **Auto-Connect** – Automatically connect on system startup
|
||||||
- **Desktop Integration** – Theme-aware system tray icon, auto-connect on launch, and reconnect on wake
|
- **System Tray Integration** – Convenient system tray icon (requires [gnome-shell-extension-appindicator](https://extensions.gnome.org/extension/615/appindicator-support/) on GNOME)
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
### Command-Line Interface
|
### Command-Line Interface
|
||||||
|
|
||||||
On macOS, Linux, and BSD, the open-source `gpclient` CLI handles authentication, connection lifecycle, and HIP generation:
|
The CLI is free and open source. Use it to authenticate, connect to portals or gateways, and generate HIP reports from the terminal.
|
||||||
|
|
||||||
|
#### Basic Commands
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Connect to a portal server
|
Usage: gpclient [OPTIONS] <COMMAND>
|
||||||
sudo gpclient connect <portal>
|
|
||||||
|
|
||||||
# Connect using browser authentication (SSO / SAML)
|
Commands:
|
||||||
sudo gpclient connect <portal> --browser
|
connect Connect to a portal server
|
||||||
|
disconnect Disconnect from the server
|
||||||
|
launch-gui Launch the GUI
|
||||||
|
hip Generate HIP report
|
||||||
|
help Print this message or the help of the given subcommand(s)
|
||||||
|
|
||||||
# Connect directly to a gateway server
|
Options:
|
||||||
sudo gpclient connect <gateway> --as-gateway
|
--ignore-tls-errors Ignore the TLS errors
|
||||||
|
--lock-file <LOCK_FILE> Path to the gpclient PID lock file
|
||||||
# Connect with automatic HIP report generation
|
--log-format <LOG_FORMAT> Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text. [default: text] [possible values: text, json]
|
||||||
sudo gpclient connect <portal> --hip
|
-v, --verbose... Enable verbose output, -v for debug, -vv for trace
|
||||||
|
-q, --quiet... Decrease logging verbosity, -q for warnings, -qq for errors
|
||||||
# Headless / remote server authentication (prints auth URL to open in any browser)
|
-h, --help Print help (see more with '--help')
|
||||||
sudo gpclient connect <portal> --browser manual
|
-V, --version Print version
|
||||||
|
|
||||||
# Disconnect
|
|
||||||
sudo gpclient disconnect
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Run `gpclient --help` or `gpclient <command> --help` to view all available commands and options.
|
|
||||||
|
> **Tip:** Use `gpclient help <command>` for detailed information on a specific command.
|
||||||
|
|
||||||
|
#### HIP reports
|
||||||
|
|
||||||
|
HIP is disabled in the CLI unless enabled explicitly. Use `--hip` to generate reports inside `gpclient`, including later reports requested by the gateway:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo gpclient connect <portal> --hip
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `--hip=/absolute/path/to/script` for a custom executable. It runs as the `gpclient` process user unless `--hip-user` specifies another user. No installed HIP script is discovered automatically. `--hip-user` applies only to custom executables.
|
||||||
|
|
||||||
|
`gpclient hip` generates a report on demand for inspection; see `gpclient hip --help` for report inputs. The GUI's HIP tab supports generated reports, edited XML, and HIP Off on all desktop platforms. Linux, FreeBSD, and OpenBSD also support desktop-user scripts and explicitly approved root scripts.
|
||||||
|
|
||||||
|
#### External Browser Authentication
|
||||||
|
|
||||||
|
Use `gpclient` directly for browser-based authentication. It opens the browser as your normal desktop user while keeping VPN tunnel setup privileged:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo gpclient connect <portal> --browser
|
||||||
|
```
|
||||||
|
|
||||||
|
For standalone CLI installations, use `--browser manual` (`--browser remote` before v3.0.6): open the printed URL and paste the resulting `globalprotectcallback:…` data into the terminal.
|
||||||
|
|
||||||
|
To reuse a saved portal cookie for later connections, add `--cookie-cache`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo gpclient connect <portal> --browser --cookie-cache
|
||||||
|
```
|
||||||
|
|
||||||
|
Add `--gateway <gateway>` to select a particular gateway. Cookie caching is handled by `gpclient`. Its default cache file is `$HOME/.config/gpclient/cookie.json`, which normally belongs to root when running with `sudo`. To choose a predictable location, specify the path explicitly:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo gpclient connect <portal> --browser --cookie-cache=/absolute/path/to/cookie.json
|
||||||
|
```
|
||||||
|
|
||||||
|
**Browser Options:**
|
||||||
|
|
||||||
|
- Use `--browser` to automatically select an available browser
|
||||||
|
- Use `--browser <browser>` to specify a browser (e.g., `firefox`, `chrome`)
|
||||||
|
- Use `--browser manual` for standalone CLI installations or headless servers
|
||||||
|
|
||||||
### Graphical User Interface
|
### Graphical User Interface
|
||||||
|
|
||||||
- **Windows**: Open **GP Connect** from the Start menu.
|
GP Connect provides a desktop interface for managing VPN connections. On macOS, open GP Connect from Applications. On Linux, FreeBSD, and OpenBSD, launch it from your application menu or via the terminal:
|
||||||
- **macOS**: Open **GP Connect** from Applications.
|
|
||||||
- **Linux / BSD**: Launch GP Connect from your application menu or run:
|
|
||||||
```bash
|
```bash
|
||||||
gpclient launch-gui
|
gpclient launch-gui
|
||||||
```
|
```
|
||||||
|
|
||||||
> [!TIP]
|
> [!TIP]
|
||||||
> **On Linux, try Native Shell for lower memory usage.** Switch between Native Shell and Tauri in **Settings → General → Interface**.
|
> **On Linux, try Native Shell for lower memory usage.** Switch to it in **Settings → General → Interface**.
|
||||||
|
|
||||||
|
> [!Note]
|
||||||
|
>
|
||||||
|
> The GUI version is partially open source. The background service ([gpservice](./apps/gpservice/)) is open source, while the GUI wrapper is proprietary.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
### Windows
|
> [!Note]
|
||||||
|
>
|
||||||
Download the matching EXE installer from [GitHub Releases](https://github.com/yuezk/GlobalProtect-openconnect/releases/latest):
|
> For older Linux distributions, use [v2.3.13](https://github.com/yuezk/GlobalProtect-openconnect/releases/tag/v2.3.13) instead of the latest release. It provides release assets for common distro families, including Debian/Ubuntu (`.deb`), Arch Linux / Manjaro (`.pkg.tar.zst`), RPM-based distros such as Fedora / RHEL / Rocky / AlmaLinux / CentOS (`.rpm`), and generic Linux tarballs (`.bin.tar.xz`).
|
||||||
|
|
||||||
- **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
|
### macOS
|
||||||
|
|
||||||
Requires Apple silicon and macOS 13+. Includes both GP Connect and the `gpclient` CLI.
|
GP Connect requires Apple silicon and macOS 13 or later. The macOS app includes both the desktop application and the free `gpclient` CLI. The CLI does not require a GUI license.
|
||||||
|
|
||||||
#### Option 1: Homebrew (Recommended)
|
#### Option 1: Install with Homebrew
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
brew install --cask yuezk/gp-connect/gp-connect
|
brew install --cask yuezk/gp-connect/gp-connect
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Option 2: DMG Installer
|
Open GP Connect from Applications, or connect from the terminal:
|
||||||
|
|
||||||
Download the `.dmg` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page and drag GP Connect into Applications.
|
```bash
|
||||||
|
sudo gpclient connect <portal> --browser
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Option 2: Install from DMG
|
||||||
|
|
||||||
|
Download the GP Connect `.dmg` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, open it, and drag GP Connect into Applications.
|
||||||
|
|
||||||
### Debian / Ubuntu
|
### Debian / Ubuntu
|
||||||
|
|
||||||
#### Option 1: PPA (Recommended)
|
#### Option 1: Install from PPA (Recommended)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
|
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
|
||||||
@@ -129,152 +170,392 @@ sudo apt-get update
|
|||||||
sudo apt-get install globalprotect-openconnect
|
sudo apt-get install globalprotect-openconnect
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Option 2: DEB Package
|
> [!Note]
|
||||||
|
>
|
||||||
|
> **For Linux Mint users:** If you encounter a GPG key error, import the key manually:
|
||||||
|
> ```bash
|
||||||
|
> sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761
|
||||||
|
> ```
|
||||||
|
|
||||||
Download the latest `.deb` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
#### Option 2: Install from DEB Package
|
||||||
|
|
||||||
|
Download the latest `.deb` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo apt install ./globalprotect-openconnect_*.deb
|
sudo apt install --fix-broken ./globalprotect-openconnect_*.deb
|
||||||
```
|
```
|
||||||
|
|
||||||
### Arch Linux / Manjaro
|
### Arch Linux / Manjaro
|
||||||
|
|
||||||
```bash
|
#### Option 1: Install from AUR
|
||||||
# Official Extra repository
|
|
||||||
sudo pacman -S globalprotect-openconnect
|
|
||||||
|
|
||||||
# AUR (git main)
|
Package: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/)
|
||||||
|
|
||||||
|
You can install it using an AUR helper like [`yay`](https://github.com/Jguer/yay):
|
||||||
|
|
||||||
|
```bash
|
||||||
yay -S globalprotect-openconnect-git
|
yay -S globalprotect-openconnect-git
|
||||||
```
|
```
|
||||||
|
|
||||||
### Fedora / RHEL
|
#### Option 2: Install from the Official Extra Repository
|
||||||
|
|
||||||
Enable the COPR repository:
|
The package is also available in the official Arch Linux Extra repository.
|
||||||
|
|
||||||
|
Package: [globalprotect-openconnect](https://archlinux.org/packages/extra/x86_64/globalprotect-openconnect/)
|
||||||
|
|
||||||
|
> [!Note]
|
||||||
|
>
|
||||||
|
> Since the official package does not include the system tray support dependency, you need to install `libappindicator` manually:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo pacman -S libappindicator globalprotect-openconnect
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Option 3: Install from Package
|
||||||
|
|
||||||
|
Download the latest package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo pacman -U globalprotect-openconnect-*.pkg.tar.zst
|
||||||
|
```
|
||||||
|
|
||||||
|
### Fedora 38+ / Rawhide
|
||||||
|
|
||||||
|
#### Install from COPR
|
||||||
|
|
||||||
|
The package is available on [COPR](https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/) for RPM-based distributions:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo dnf copr enable yuezk/globalprotect-openconnect
|
sudo dnf copr enable yuezk/globalprotect-openconnect
|
||||||
sudo dnf install globalprotect-openconnect
|
sudo dnf install globalprotect-openconnect
|
||||||
```
|
```
|
||||||
|
|
||||||
### openSUSE
|
### openSUSE Leap 15.6+ / Tumbleweed
|
||||||
|
|
||||||
Packages are available on the [openSUSE Build Service](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect). Follow the [OBS instructions](https://software.opensuse.org/download.html?project=home%3Ayuezk&package=globalprotect-openconnect) for your distribution.
|
#### Install from OBS (openSUSE Build Service)
|
||||||
|
|
||||||
|
Packages are available on the [openSUSE Build Service](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect). Follow the [installation instructions](https://software.opensuse.org//download.html?project=home%3Ayuezk&package=globalprotect-openconnect) for your distribution.
|
||||||
|
|
||||||
|
### Other RPM-based Distributions
|
||||||
|
|
||||||
|
#### Install from RPM Package
|
||||||
|
|
||||||
|
Download the latest RPM package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo rpm -i globalprotect-openconnect-*.rpm
|
||||||
|
```
|
||||||
|
|
||||||
### Alpine Linux
|
### Alpine Linux
|
||||||
|
|
||||||
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo apk add --allow-untrusted globalprotect-openconnect-*.apk
|
sudo apk add --allow-untrusted globalprotect-openconnect-*.apk
|
||||||
```
|
```
|
||||||
|
|
||||||
*(Requires `community` repository enabled for WebKitGTK and AppIndicator dependencies).*
|
The package uses Alpine's native musl build. Make sure the `community` repository is enabled so GUI dependencies such as `webkit2gtk-4.1`, `libsecret`, and `libayatana-appindicator` can be resolved. GUI-launched connections use polkit, and VPN tunnel creation requires `/dev/net/tun`.
|
||||||
|
|
||||||
### FreeBSD
|
### FreeBSD
|
||||||
|
|
||||||
Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo pkg install ./globalprotect-openconnect-*-freebsd-*.pkg
|
sudo pkg install ./globalprotect-openconnect-*-freebsd-*.pkg
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
||||||
|
|
||||||
### OpenBSD
|
### OpenBSD
|
||||||
|
|
||||||
Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
doas pkg_add -D unsigned ./globalprotect-openconnect-*-openbsd-*.tgz
|
doas pkg_add -D unsigned ./globalprotect-openconnect-*-openbsd-*.tgz
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
||||||
|
|
||||||
### Gentoo
|
### Gentoo
|
||||||
|
|
||||||
Available via the `guru` repository:
|
Available via the `guru` and `lamdness` overlays:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo eselect repository enable guru
|
sudo eselect repository enable guru
|
||||||
sudo emerge --sync guru
|
sudo emerge --sync guru
|
||||||
sudo emerge --ask net-vpn/GlobalProtect-openconnect
|
sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect
|
||||||
```
|
```
|
||||||
|
|
||||||
### NixOS
|
### NixOS
|
||||||
|
|
||||||
Add the flake to your `flake.nix`:
|
This repository includes a flake for NixOS integration.
|
||||||
|
|
||||||
|
#### Installation Steps
|
||||||
|
|
||||||
|
Add the flake input and NixOS module to your `flake.nix`:
|
||||||
|
|
||||||
|
The module builds the package with your NixOS configuration's `pkgs`, so the
|
||||||
|
GlobalProtect GUI and the system use the same Nixpkgs dependency versions.
|
||||||
|
It also enables Polkit and its setuid `pkexec` wrapper for privileged operations.
|
||||||
|
|
||||||
```nix
|
```nix
|
||||||
{
|
{
|
||||||
inputs.globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
|
inputs = {
|
||||||
|
# ... other inputs
|
||||||
|
globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
|
||||||
|
};
|
||||||
|
|
||||||
|
outputs = { self, nixpkgs, globalprotect-openconnect, ... }:
|
||||||
|
let
|
||||||
|
system = "x86_64-linux"; # or "aarch64-linux" for ARM64
|
||||||
|
hostname = "<your-host>";
|
||||||
|
in {
|
||||||
|
nixosConfigurations.${hostname} = nixpkgs.lib.nixosSystem {
|
||||||
|
inherit system;
|
||||||
|
|
||||||
outputs = { self, nixpkgs, globalprotect-openconnect, ... }: {
|
|
||||||
nixosConfigurations.<hostname> = nixpkgs.lib.nixosSystem {
|
|
||||||
modules = [
|
modules = [
|
||||||
|
./configuration.nix
|
||||||
globalprotect-openconnect.nixosModules.default
|
globalprotect-openconnect.nixosModules.default
|
||||||
{
|
{
|
||||||
programs.globalprotect-openconnect.enable = true;
|
programs.globalprotect-openconnect.enable = true;
|
||||||
|
|
||||||
|
environment.systemPackages = [
|
||||||
|
nixpkgs.legacyPackages.${system}.gnomeExtensions.appindicator
|
||||||
|
];
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Apply changes:
|
Apply:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo nixos-rebuild switch
|
sudo nixos-rebuild switch
|
||||||
|
loginctl terminate-user "$USER"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Docker
|
After logging back in to GNOME, enable AppIndicator support if needed:
|
||||||
|
|
||||||
Run the CLI client in an official Alpine container:
|
```bash
|
||||||
|
gnome-extensions enable [email protected]
|
||||||
|
```
|
||||||
|
|
||||||
|
NixOS does not run an imperative package-uninstall hook when a package is
|
||||||
|
removed from the system configuration. Remove an installed replacement VPN
|
||||||
|
script from the app settings before removing the package.
|
||||||
|
|
||||||
|
The `prebuilt` package and NixOS module use the published release pinned in `flake.nix`. Both `prebuilt` and `fromSource` run natively on the host with packaged dependencies and installer paths. The `fromSource` package builds the current flake checkout, including its Git submodules:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git submodule update --init --recursive
|
||||||
|
nix build "git+file://$PWD?submodules=1#fromSource"
|
||||||
|
```
|
||||||
|
|
||||||
|
Local source builds require initialized Git submodules and a flake URL with `submodules=1`, as shown above. For a remote source flake, use a Git URL with submodules enabled, such as `git+https://github.com/yuezk/GlobalProtect-openconnect?submodules=1#fromSource`. The `prebuilt` package and NixOS module do not require Git submodules. Build output (`target`, `.build`, and `node_modules`) is excluded from the source input. Updating release asset hashes changes the prebuilt package, independently of source builds.
|
||||||
|
|
||||||
|
Source builds also support downloading either desktop interface on NixOS. The
|
||||||
|
downloader packages the verified Tauri or Native Shell archive with Nix, including
|
||||||
|
its runtime libraries. Each installed interface has a garbage-collection root
|
||||||
|
under `/var/lib/gpclient/nix-gui`, so its dependencies remain available after
|
||||||
|
system upgrades. No Rust compilation or NixOS rebuild is needed for GUI downloads.
|
||||||
|
Prebuilt packages gain this support when their release includes the updated
|
||||||
|
service; adding the flake installer alone does not change older service binaries.
|
||||||
|
|
||||||
|
### Official Docker Image
|
||||||
|
|
||||||
|
The [official Docker image](https://hub.docker.com/r/yuezk/globalprotect-openconnect) provides the CLI tools on Alpine Linux:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker pull yuezk/globalprotect-openconnect:<version>
|
||||||
|
```
|
||||||
|
|
||||||
|
Release images are tagged as `vX.Y.Z`, `X.Y.Z`, and `latest`.
|
||||||
|
|
||||||
|
Run it with access to the TUN device:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||||
yuezk/globalprotect-openconnect:latest \
|
yuezk/globalprotect-openconnect:<version> \
|
||||||
|
connect <portal>
|
||||||
|
```
|
||||||
|
|
||||||
|
For browser authentication in a headless environment, use manual browser authentication:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||||
|
yuezk/globalprotect-openconnect:<version> \
|
||||||
connect <portal> --browser manual
|
connect <portal> --browser manual
|
||||||
```
|
```
|
||||||
|
|
||||||
*(Add `--network host` on Linux if VPN routes should apply to the host network).*
|
On a host with multiple network interfaces, use `--browser-listen` to select the IP address reachable from the browser machine:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gpclient connect <portal> --browser manual --browser-listen 192.168.107.15
|
||||||
|
```
|
||||||
|
|
||||||
|
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run --rm -it --network host --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||||
|
yuezk/globalprotect-openconnect:<version> \
|
||||||
|
connect <portal> --browser manual
|
||||||
|
```
|
||||||
|
|
||||||
|
Without `--network host`, the VPN connection stays inside the container's network namespace. Docker Desktop on macOS and Windows does not make the host use the VPN through `--network host`; run `gpclient` on the host or use a container gateway setup for host traffic.
|
||||||
|
|
||||||
|
The image includes `gpclient` and `gpauth` only. It does not include embedded webview authentication, `gpgui-helper`, or `gpgui`.
|
||||||
|
|
||||||
### Other Distributions
|
### Other Distributions
|
||||||
|
|
||||||
Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
#### Manual Installation
|
||||||
|
|
||||||
|
1. **Install dependencies:**
|
||||||
|
- WebKitGTK 4.1 (for example, `libwebkit2gtk-4.1-0` on Debian/Ubuntu)
|
||||||
|
- `libsecret`
|
||||||
|
- `libayatana-appindicator` or `libappindicator-gtk3`
|
||||||
|
- polkit (`pkexec`) for GUI-launched VPN connections
|
||||||
|
|
||||||
|
2. **Download and extract:**
|
||||||
|
Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||||
|
```bash
|
||||||
|
tar -xJf globalprotect-openconnect_${version}_${arch}.bin.tar.xz
|
||||||
|
cd globalprotect-openconnect_${version}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Install:**
|
||||||
```bash
|
```bash
|
||||||
tar -xJf globalprotect-openconnect_*.bin.tar.xz
|
|
||||||
cd globalprotect-openconnect_*
|
|
||||||
sudo make install
|
sudo make install
|
||||||
```
|
```
|
||||||
|
|
||||||
## Building from Source
|
## Building from Source
|
||||||
|
|
||||||
### Prerequisites (Linux)
|
The instructions below build the open-source components on Linux. For FreeBSD and OpenBSD, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
||||||
|
|
||||||
- [Rust](https://www.rust-lang.org/tools/install) 1.91 or later
|
### Method 1: Using DevContainer
|
||||||
- Build tools: `make`, `pkg-config`, `autoconf`, `automake`, `libtool`, `gettext`
|
|
||||||
- Libraries: `gmp`, `gnutls`, `nettle`, `libxml2`, `zlib`, `lz4`, `p11-kit`, `libsecret`, and `webkit2gtk-4.1` (or GTK 4 for Native Shell)
|
|
||||||
- Polkit (`pkexec`) for privileged tunnel setup
|
|
||||||
|
|
||||||
*(For FreeBSD and OpenBSD instructions, see [Building from Source on FreeBSD and OpenBSD](docs/bsd-source-build.md)).*
|
This project includes a DevContainer configuration for Linux development. The repository's `rust-toolchain.toml` selects the Rust toolchain; rustup may need to download it on the first build.
|
||||||
|
|
||||||
### Build Steps
|
#### Prerequisites
|
||||||
|
|
||||||
|
- [Docker](https://docs.docker.com/get-docker/)
|
||||||
|
- [Visual Studio Code](https://code.visualstudio.com/) (optional, for IDE support)
|
||||||
|
- [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) (if using VS Code)
|
||||||
|
|
||||||
|
#### Build Steps
|
||||||
|
|
||||||
|
1. **Clone the repository:**
|
||||||
```bash
|
```bash
|
||||||
git clone --recursive https://github.com/yuezk/GlobalProtect-openconnect.git
|
git clone https://github.com/yuezk/GlobalProtect-openconnect.git
|
||||||
cd GlobalProtect-openconnect
|
cd GlobalProtect-openconnect
|
||||||
|
git submodule update --init --recursive
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Build the DevContainer image:**
|
||||||
|
```bash
|
||||||
|
docker build -t gpoc-devcontainer .devcontainer/
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Build the project:**
|
||||||
|
|
||||||
|
To build the open-source components, including the GUI helper, run:
|
||||||
|
```bash
|
||||||
|
docker run --privileged --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||||
|
--tty -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
|
||||||
|
bash -c "export PATH=/usr/local/cargo/bin:\$PATH && make build"
|
||||||
|
```
|
||||||
|
To build without the GUI helper run the same command as above, but with `BUILD_GUI_HELPER=0` passed as an argument to `make`.
|
||||||
|
|
||||||
|
4. **Locate build artifacts:**
|
||||||
|
|
||||||
|
The compiled binaries will be available in `target/release/`:
|
||||||
|
- `gpclient` – CLI client
|
||||||
|
- `gpservice` – Background service
|
||||||
|
- `gpauth` – Authentication helper
|
||||||
|
- `gpgui-helper` – GUI helper
|
||||||
|
- `gp-hip-script-installer` – Privileged HIP script installer
|
||||||
|
- `gp-vpnc-script-installer` – Privileged VPN script installer
|
||||||
|
|
||||||
|
The proprietary GP Connect desktop application is distributed separately. Use `INCLUDE_GUI=1` with `make build` to download its matching published Linux build for installation.
|
||||||
|
|
||||||
|
#### Alternative: Using VS Code
|
||||||
|
|
||||||
|
1. Open the project in VS Code
|
||||||
|
2. When prompted, click "Reopen in Container" (or run **Dev Containers: Reopen in Container**)
|
||||||
|
3. Once the container is ready, open a terminal and run:
|
||||||
|
```bash
|
||||||
make build
|
make build
|
||||||
|
```
|
||||||
|
|
||||||
|
### Method 2: Local Development Build
|
||||||
|
|
||||||
|
#### Prerequisites
|
||||||
|
|
||||||
|
- [Rust 1.91 or later](https://www.rust-lang.org/tools/install)
|
||||||
|
- [Tauri dependencies](https://tauri.app/start/prerequisites/)
|
||||||
|
- OpenConnect source-build dependencies: `autoconf`, `automake`, `autopoint`/`gettext`, `libtool`, `patch`, `pkg-config`, `libxml2`, `zlib`, `lz4`, `gnutls`, `p11-kit`, `nettle`, and `gmp` development packages
|
||||||
|
- `pkexec` and `gnome-keyring` (or `pam_kwallet` on KDE)
|
||||||
|
- Node.js and pnpm if rebuilding the GUI helper frontend
|
||||||
|
|
||||||
|
#### Build Steps
|
||||||
|
|
||||||
|
1. **Download source code:**
|
||||||
|
|
||||||
|
Download `globalprotect-openconnect-${version}.tar.gz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
|
||||||
|
|
||||||
|
2. **Extract and build:**
|
||||||
|
```bash
|
||||||
|
tar -xzf globalprotect-openconnect-${version}.tar.gz
|
||||||
|
cd globalprotect-openconnect-${version}
|
||||||
|
make build
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Install:**
|
||||||
|
```bash
|
||||||
sudo make install
|
sudo make install
|
||||||
```
|
```
|
||||||
|
|
||||||
**Build Options:**
|
To stage the files for packaging instead of installing them into the system, use `make install DESTDIR=/absolute/path/to/staging`.
|
||||||
|
|
||||||
- `INCLUDE_GUI=1` – Download and install the matching desktop application bundle.
|
### Testing Your Build
|
||||||
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication (uses external browser or manual mode).
|
|
||||||
- `BUILD_GUI_HELPER=0` – Skip building the helper UI.
|
|
||||||
|
|
||||||
## Troubleshooting
|
Verify the CLI client is working correctly:
|
||||||
|
|
||||||
- **Headless / Remote Login**: When running without a desktop display or over SSH, use `--browser manual`. Open the printed URL in any browser and paste the callback URL back into the terminal.
|
```bash
|
||||||
- **Diagnostics**: If you encounter issues, run `gpclient diagnostics` or follow the [diagnostics guide](docs/diagnostics.md) when opening an issue.
|
./target/release/gpclient --help
|
||||||
|
```
|
||||||
|
|
||||||
|
### Build Options
|
||||||
|
|
||||||
|
- `BUILD_GUI_HELPER=0` – Skip building and installing the GUI helper
|
||||||
|
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication; use an external browser or manual authentication
|
||||||
|
- `INCLUDE_GUI=1` – Download the matching published Linux desktop application for installation
|
||||||
|
- `OFFLINE=1` – Build in offline mode using vendored dependencies
|
||||||
|
|
||||||
|
## Frequently Asked Questions
|
||||||
|
|
||||||
|
When reporting a problem, follow the [diagnostics collection instructions](docs/diagnostics.md). A standalone script is available for versions without the diagnostics command; you do not need to upgrade first.
|
||||||
|
|
||||||
|
### Q: How do I resolve the "Secure Storage not ready" error?
|
||||||
|
|
||||||
|
Unlock your desktop keyring and ensure the application can access it. On Linux and BSD, check that a keyring service such as GNOME Keyring is installed and running in your desktop session. On macOS, check Keychain access.
|
||||||
|
|
||||||
|
Linux and BSD can use file storage when secure storage is unavailable during initial setup. An existing configuration that uses the keyring still needs access to that keyring.
|
||||||
|
|
||||||
|
See related issues: [#321](https://github.com/yuezk/GlobalProtect-openconnect/issues/321), [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||||
|
|
||||||
|
### Q: How do I fix the "cannot open display" error when using CLI?
|
||||||
|
|
||||||
|
Run the client from a terminal in your normal desktop session and use an external browser:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo gpclient connect <portal> --browser
|
||||||
|
```
|
||||||
|
|
||||||
|
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||||
|
|
||||||
|
On a headless server, use `--browser manual` and complete authentication from another machine.
|
||||||
|
|
||||||
## NetworkManager Integration
|
## NetworkManager Integration
|
||||||
|
|
||||||
@@ -283,10 +564,14 @@ sudo make install
|
|||||||
|
|
||||||
## Licensing
|
## Licensing
|
||||||
|
|
||||||
- **CLI (`gpclient`)**: Free and open source (GPL-3.0).
|
### Trial and Pricing
|
||||||
- **GUI (GP Connect)**: Commercial desktop application with a free trial.
|
|
||||||
|
|
||||||
### Open Source Components
|
The **CLI version** is completely free and open source.
|
||||||
|
The **GUI version** is a paid application with a **7-day trial**. Start the trial in the app by verifying your email address with a one-time code. Installing the app alone does not start the trial.
|
||||||
|
|
||||||
|
### Open Source Licenses
|
||||||
|
|
||||||
|
This project consists of multiple components, each with its own license:
|
||||||
|
|
||||||
| Component | Type | License |
|
| Component | Type | License |
|
||||||
|-----------|------|---------|
|
|-----------|------|---------|
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ serde_json.workspace = true
|
|||||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||||
compile-time.workspace = true
|
compile-time.workspace = true
|
||||||
|
|
||||||
|
home = "0.5.12"
|
||||||
|
|
||||||
# webview auth dependencies
|
# webview auth dependencies
|
||||||
tauri = { workspace = true, optional = true }
|
tauri = { workspace = true, optional = true }
|
||||||
|
|
||||||
|
|||||||
@@ -16,9 +16,6 @@ fn main() {
|
|||||||
resolve_commit(&repo_root, &source_commit)
|
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")]
|
#[cfg(feature = "webview-auth")]
|
||||||
tauri_build::build()
|
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::forward_auth_callback;
|
||||||
use auth::{BrowserAuthenticator, auth_prelogin};
|
use auth::{BrowserAuthenticator, auth_prelogin};
|
||||||
use clap::Parser;
|
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;
|
use clap::Subcommand;
|
||||||
#[cfg(feature = "webview-auth")]
|
#[cfg(feature = "webview-auth")]
|
||||||
use gpapi::auth::AuthWindowTheme;
|
use gpapi::auth::AuthWindowTheme;
|
||||||
@@ -49,7 +49,7 @@ See 'gpauth -h' for more information.
|
|||||||
"
|
"
|
||||||
)]
|
)]
|
||||||
struct Cli {
|
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(subcommand)]
|
||||||
command: Option<CliCommand>,
|
command: Option<CliCommand>,
|
||||||
|
|
||||||
@@ -134,7 +134,7 @@ struct Cli {
|
|||||||
verbose: InfoLevelVerbosity,
|
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)]
|
#[derive(Subcommand)]
|
||||||
enum CliCommand {
|
enum CliCommand {
|
||||||
#[command(hide = true)]
|
#[command(hide = true)]
|
||||||
@@ -272,7 +272,7 @@ fn init_logger(cli: &Cli) {
|
|||||||
pub async fn run() {
|
pub async fn run() {
|
||||||
let cli = Cli::parse();
|
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 Some(CliCommand::AuthCallback { callback }) = &cli.command {
|
||||||
if let Err(err) = forward_auth_callback(callback).await {
|
if let Err(err) = forward_auth_callback(callback).await {
|
||||||
eprintln!("Failed to forward authentication callback: {err}");
|
eprintln!("Failed to forward authentication callback: {err}");
|
||||||
@@ -382,7 +382,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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() {
|
fn callback_arguments_parse_separately() {
|
||||||
let cli = Cli::try_parse_from([
|
let cli = Cli::try_parse_from([
|
||||||
"gpauth",
|
"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,7 +36,14 @@ fn login_response() -> String {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn read_request(stream: &mut tokio::net::TcpStream) -> String {
|
async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||||
|
let worker = tokio::spawn(async move {
|
||||||
|
tokio::time::timeout(Duration::from_secs(5), async move {
|
||||||
|
let mut requests = Vec::new();
|
||||||
|
for (status, body) in responses {
|
||||||
|
let (mut stream, _) = listener.accept().await.unwrap();
|
||||||
let mut request = Vec::new();
|
let mut request = Vec::new();
|
||||||
loop {
|
loop {
|
||||||
let mut buf = [0; 4096];
|
let mut buf = [0; 4096];
|
||||||
@@ -51,21 +58,11 @@ async fn read_request(stream: &mut tokio::net::TcpStream) -> String {
|
|||||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
if request.len() >= end + 4 + length {
|
if request.len() >= end + 4 + length {
|
||||||
return String::from_utf8(request).unwrap();
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
requests.push(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());
|
|
||||||
let worker = tokio::spawn(async move {
|
|
||||||
tokio::time::timeout(Duration::from_secs(5), async move {
|
|
||||||
let mut requests = Vec::new();
|
|
||||||
for (status, body) in responses {
|
|
||||||
let (mut stream, _) = listener.accept().await.unwrap();
|
|
||||||
requests.push(read_request(&mut stream).await);
|
|
||||||
stream
|
stream
|
||||||
.write_all(
|
.write_all(
|
||||||
format!(
|
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]
|
#[tokio::test]
|
||||||
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
|
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
|
||||||
let (origin, worker) = gateway(vec![
|
let (origin, worker) = gateway(vec![
|
||||||
@@ -662,62 +511,3 @@ printf '%s\n' '{"success":{"username":"alice","preloginCookie":"new-cookie"}}'
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn unsupported_and_malformed_identities_fail_before_password_prompt_or_network_connection() {
|
|
||||||
use gpapi::utils::request::RequestIdentityError;
|
|
||||||
let directory = tempfile::tempdir().unwrap();
|
|
||||||
let malformed = directory.path().join("invalid.p12");
|
|
||||||
std::fs::write(&malformed, b"not a certificate archive").unwrap();
|
|
||||||
let fixtures =
|
|
||||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/gpapi/tests/files/client-identity");
|
|
||||||
|
|
||||||
for (certificate, key, expected) in [
|
|
||||||
(
|
|
||||||
fixtures.join("rsa-pss-cert.pem"),
|
|
||||||
Some(fixtures.join("rsa-pss.pem")),
|
|
||||||
"algorithm",
|
|
||||||
),
|
|
||||||
(fixtures.join("legacy-RC2-128.p12"), None, "encryption"),
|
|
||||||
(malformed, None, "malformed"),
|
|
||||||
] {
|
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
||||||
let server = format!("https://{}", listener.local_addr().unwrap());
|
|
||||||
let mut argv = vec![
|
|
||||||
"test".to_owned(),
|
|
||||||
server,
|
|
||||||
"--as-gateway".to_owned(),
|
|
||||||
"--certificate".to_owned(),
|
|
||||||
certificate.to_string_lossy().into_owned(),
|
|
||||||
];
|
|
||||||
if let Some(key) = key {
|
|
||||||
argv.extend(["--sslkey".to_owned(), key.to_string_lossy().into_owned()]);
|
|
||||||
}
|
|
||||||
let args = TestArgs::parse_from(argv).connect;
|
|
||||||
let lock = directory.path().join("client.pid");
|
|
||||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
|
||||||
let shared = SharedArgs {
|
|
||||||
ignore_tls_errors: false,
|
|
||||||
lock_file: &lock,
|
|
||||||
verbose: &verbose,
|
|
||||||
log_format: LogFormat::Text,
|
|
||||||
};
|
|
||||||
let handler = ConnectHandler::new(&args, &shared);
|
|
||||||
let error = tokio::time::timeout(Duration::from_secs(2), handler.handle_attempt())
|
|
||||||
.await
|
|
||||||
.expect("identity failure must not wait for a password or server")
|
|
||||||
.unwrap_err();
|
|
||||||
match (expected, error.downcast_ref::<RequestIdentityError>()) {
|
|
||||||
("algorithm", Some(RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS"))) => {}
|
|
||||||
("encryption", Some(RequestIdentityError::UnsupportedEncryption)) => {}
|
|
||||||
("malformed", Some(RequestIdentityError::InvalidPkcs12(_) | RequestIdentityError::InvalidCertificate)) => {}
|
|
||||||
_ => panic!("{expected}: unexpected failure {error:#}"),
|
|
||||||
}
|
|
||||||
assert!(
|
|
||||||
tokio::time::timeout(Duration::from_millis(20), listener.accept())
|
|
||||||
.await
|
|
||||||
.is_err(),
|
|
||||||
"{expected}: local identity failure must precede network access"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -101,11 +101,6 @@ impl ConnectHandler<'_> {
|
|||||||
{
|
{
|
||||||
return Some(Err(error));
|
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);
|
cookie_store::clear(&path);
|
||||||
warn!("Cached gateway authentication failed: {error}");
|
warn!("Cached gateway authentication failed: {error}");
|
||||||
return None;
|
return None;
|
||||||
@@ -790,8 +785,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn explicit_hip_user_resolves_to_the_selected_account() {
|
fn explicit_hip_user_resolves_to_the_selected_account() {
|
||||||
// Build sandboxes may use a UID without an entry in the user database.
|
let current = uzers::get_user_by_uid(uzers::get_effective_uid()).unwrap();
|
||||||
assert_eq!(get_uid(&Some("root".to_string())).unwrap(), Some(0));
|
let name = current.name().to_string_lossy().into_owned();
|
||||||
|
assert_eq!(get_uid(&Some(name)).unwrap(), Some(current.uid()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -835,11 +831,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,8 +128,7 @@ impl ConnectHandler<'_> {
|
|||||||
produce_report: Arc::new(move |request, control| {
|
produce_report: Arc::new(move |request, control| {
|
||||||
control.check()?;
|
control.check()?;
|
||||||
if matches!(source.as_ref(), openconnect::HipSource::Disabled) {
|
if matches!(source.as_ref(), openconnect::HipSource::Disabled) {
|
||||||
return gphip::generate_identity_report(
|
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||||
&gphip::ReportInput {
|
|
||||||
profile: profile.clone(),
|
profile: profile.clone(),
|
||||||
context: gphip::ReportContext::Connected {
|
context: gphip::ReportContext::Connected {
|
||||||
cookie: request.cookie.clone(),
|
cookie: request.cookie.clone(),
|
||||||
@@ -137,9 +136,7 @@ impl ConnectHandler<'_> {
|
|||||||
client_ipv6: request.client_ipv6.clone(),
|
client_ipv6: request.client_ipv6.clone(),
|
||||||
md5: request.md5.clone(),
|
md5: request.md5.clone(),
|
||||||
},
|
},
|
||||||
},
|
})
|
||||||
control,
|
|
||||||
)
|
|
||||||
.map_err(std::io::Error::other);
|
.map_err(std::io::Error::other);
|
||||||
}
|
}
|
||||||
source.collect(
|
source.collect(
|
||||||
|
|||||||
@@ -186,8 +186,6 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
match identity_error {
|
match identity_error {
|
||||||
RequestIdentityError::UnsupportedEncryption
|
RequestIdentityError::UnsupportedEncryption
|
||||||
| RequestIdentityError::UnsupportedKeyFormat
|
| RequestIdentityError::UnsupportedKeyFormat
|
||||||
| RequestIdentityError::UnsupportedKeyAlgorithm(_)
|
|
||||||
| RequestIdentityError::KeyMismatch
|
|
||||||
| RequestIdentityError::InvalidKey
|
| RequestIdentityError::InvalidKey
|
||||||
| RequestIdentityError::InvalidCertificate
|
| RequestIdentityError::InvalidCertificate
|
||||||
| RequestIdentityError::IncompletePkcs12
|
| RequestIdentityError::IncompletePkcs12
|
||||||
@@ -208,12 +206,8 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
|
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
|
||||||
let message = if *cert_type == "PKCS#12" {
|
let message = format!("Enter the {} passphrase:", cert_type);
|
||||||
"Enter the certificate file password:"
|
let password = Password::new(&message)
|
||||||
} else {
|
|
||||||
"Enter the private key password:"
|
|
||||||
};
|
|
||||||
let password = Password::new(message)
|
|
||||||
.without_confirmation()
|
.without_confirmation()
|
||||||
.with_display_mode(PasswordDisplayMode::Masked)
|
.with_display_mode(PasswordDisplayMode::Masked)
|
||||||
.prompt()?;
|
.prompt()?;
|
||||||
@@ -292,11 +286,6 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
Ok(config) => Some((cred, config)),
|
Ok(config) => Some((cred, config)),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
self.check_cancelled()?;
|
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}");
|
warn!("Cached portal authentication failed: {error}");
|
||||||
self.clear_cookie_cache();
|
self.clear_cookie_cache();
|
||||||
None
|
None
|
||||||
|
|||||||
@@ -30,24 +30,14 @@ uuid = { workspace = true, features = ["v4"] }
|
|||||||
zeroize.workspace = true
|
zeroize.workspace = true
|
||||||
tempfile.workspace = true
|
tempfile.workspace = true
|
||||||
getrandom = "0.4"
|
getrandom = "0.4"
|
||||||
|
mac_address = "1.2.1"
|
||||||
|
|
||||||
[target.'cfg(unix)'.dependencies]
|
[target.'cfg(unix)'.dependencies]
|
||||||
nix = { version = "0.31", features = ["fs", "socket", "user"] }
|
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]
|
[dev-dependencies]
|
||||||
openssl.workspace = true
|
openssl.workspace = true
|
||||||
tokio-tungstenite.workspace = true
|
tokio-tungstenite.workspace = true
|
||||||
|
|
||||||
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
gpvpnc = { path = "../../crates/gpvpnc" }
|
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 anyhow::{Context, bail};
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use common::paths::service_lock_file;
|
use common::constants::GP_SERVICE_LOCK_FILE;
|
||||||
use gpapi::clap::InfoLevelVerbosity;
|
use gpapi::clap::InfoLevelVerbosity;
|
||||||
use gpapi::logger;
|
use gpapi::logger;
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
@@ -25,7 +25,14 @@ use crate::{
|
|||||||
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
|
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")]
|
#[cfg(target_os = "macos")]
|
||||||
struct RedactingMacosLogger {
|
struct RedactingMacosLogger {
|
||||||
@@ -264,7 +271,7 @@ impl Cli {
|
|||||||
return Ok(dev_service_lock_file_path(socket));
|
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> {
|
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 {
|
loop {
|
||||||
match self.read_control().await? {
|
match self.read_control().await? {
|
||||||
Some(DESKTOP_GUI_INSTALLER) => {
|
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) => {
|
Some(DESKTOP_SWITCH_BEGIN) => {
|
||||||
ensure!(pending.is_none(), "A GUI switch is already pending");
|
ensure!(pending.is_none(), "A GUI switch is already pending");
|
||||||
@@ -299,7 +299,10 @@ mod tests {
|
|||||||
let mut reader = reader;
|
let mut reader = reader;
|
||||||
let mut capability = [0];
|
let mut capability = [0];
|
||||||
reader.read_exact(&mut capability).unwrap();
|
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
|
reader
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -366,7 +366,7 @@ mod tests {
|
|||||||
r#"{"version":1,"anchor":{"hardware_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","source":1}}"#
|
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!({
|
let json = serde_json::json!({
|
||||||
"version": 1,
|
"version": 1,
|
||||||
"anchor": {
|
"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;
|
.await;
|
||||||
let result = match generated {
|
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)) => {
|
Ok(Err(error)) => {
|
||||||
log::warn!("HIP preview failed: {error:#}");
|
log::warn!("HIP preview failed: {error:#}");
|
||||||
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
|
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
|
||||||
@@ -132,10 +132,8 @@ impl HipPreviews {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn preview_result(registry: &SessionRegistry, session_id: Uuid, report: gpapi::hip::HipReport) -> ServiceResult {
|
fn preview_result(registry: &SessionRegistry, session_id: Uuid, xml: String) -> ServiceResult {
|
||||||
let result = registry
|
let result = registry.store_hip_preview(session_id, xml).and_then(|preview_id| {
|
||||||
.store_hip_preview(session_id, report.xml)
|
|
||||||
.and_then(|preview_id| {
|
|
||||||
registry
|
registry
|
||||||
.hip_preview_chunk(session_id, preview_id, 0)
|
.hip_preview_chunk(session_id, preview_id, 0)
|
||||||
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
|
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
|
||||||
@@ -143,7 +141,6 @@ fn preview_result(registry: &SessionRegistry, session_id: Uuid, report: gpapi::h
|
|||||||
offset: 0,
|
offset: 0,
|
||||||
xml,
|
xml,
|
||||||
complete,
|
complete,
|
||||||
windows_updates: report.windows_updates,
|
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"))
|
result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"))
|
||||||
@@ -155,7 +152,7 @@ fn generate(
|
|||||||
desktop_uid: Option<u32>,
|
desktop_uid: Option<u32>,
|
||||||
identity: HostIdentity,
|
identity: HostIdentity,
|
||||||
cancellation: CancellationToken,
|
cancellation: CancellationToken,
|
||||||
) -> anyhow::Result<gpapi::hip::HipReport> {
|
) -> anyhow::Result<String> {
|
||||||
ensure!(request.client_version.len() <= 64, "Invalid HIP client version");
|
ensure!(request.client_version.len() <= 64, "Invalid HIP client version");
|
||||||
ensure!(
|
ensure!(
|
||||||
request.host_id.as_ref().is_none_or(|id| id.len() <= 256),
|
request.host_id.as_ref().is_none_or(|id| id.len() <= 256),
|
||||||
@@ -191,15 +188,7 @@ fn generate(
|
|||||||
};
|
};
|
||||||
let xml = match &request.source {
|
let xml = match &request.source {
|
||||||
HipSource::Disabled => bail!("HIP is disabled"),
|
HipSource::Disabled => bail!("HIP is disabled"),
|
||||||
HipSource::Generated => {
|
HipSource::Generated => crate::hip_source::generate(&profile, None, &input, &check, true)?,
|
||||||
return gphip::generate_report_details(
|
|
||||||
&gphip::ReportInput {
|
|
||||||
profile,
|
|
||||||
context: gphip::ReportContext::Preview,
|
|
||||||
},
|
|
||||||
&check,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
HipSource::Edited { .. } => {
|
HipSource::Edited { .. } => {
|
||||||
let xml = edited_report.context("Edited HIP report is unavailable")?;
|
let xml = edited_report.context("Edited HIP report is unavailable")?;
|
||||||
crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)?
|
crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)?
|
||||||
@@ -215,10 +204,7 @@ fn generate(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
check()?;
|
check()?;
|
||||||
Ok(gpapi::hip::HipReport {
|
Ok(xml)
|
||||||
xml,
|
|
||||||
windows_updates: None,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[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 anyhow::{Context, ensure};
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
@@ -6,17 +6,7 @@ use gpapi::{
|
|||||||
os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder},
|
os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder},
|
||||||
};
|
};
|
||||||
use gphip::{ReportContext, ReportInput};
|
use gphip::{ReportContext, ReportInput};
|
||||||
use openconnect::HipRequest;
|
use openconnect::{HipRequest, HipScript, HipScriptEnvironment};
|
||||||
#[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;
|
|
||||||
|
|
||||||
pub(crate) struct HipExecution {
|
pub(crate) struct HipExecution {
|
||||||
pub source: openconnect::HipSource,
|
pub source: openconnect::HipSource,
|
||||||
@@ -46,7 +36,7 @@ impl HipApproval {
|
|||||||
pub(crate) fn resolve(
|
pub(crate) fn resolve(
|
||||||
source: &HipSource,
|
source: &HipSource,
|
||||||
desktop_uid: Option<u32>,
|
desktop_uid: Option<u32>,
|
||||||
restricted_desktop: bool,
|
brokered_macos: bool,
|
||||||
edited_report: Option<Arc<str>>,
|
edited_report: Option<Arc<str>>,
|
||||||
profile: Option<OsProfile>,
|
profile: Option<OsProfile>,
|
||||||
) -> anyhow::Result<HipExecution> {
|
) -> anyhow::Result<HipExecution> {
|
||||||
@@ -73,11 +63,22 @@ pub(crate) fn resolve(
|
|||||||
}
|
}
|
||||||
HipSource::UserScript { path } => {
|
HipSource::UserScript { path } => {
|
||||||
approval = None;
|
approval = None;
|
||||||
ensure_custom_available(restricted_desktop)?;
|
ensure_custom_available(brokered_macos)?;
|
||||||
scripts::user_script(path, desktop_uid)?
|
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 } => {
|
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"))]
|
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||||
{
|
{
|
||||||
let owner_uid = desktop_uid.context("Root HIP scripts require a verified desktop user")?;
|
let 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!(
|
ensure!(
|
||||||
!cfg!(target_os = "macos") && !restricted_desktop,
|
!cfg!(target_os = "macos") && !brokered_macos,
|
||||||
"Custom HIP scripts are unavailable on this platform"
|
"Custom HIP scripts are unavailable on macOS"
|
||||||
);
|
);
|
||||||
Ok(())
|
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(
|
pub(crate) fn profile(
|
||||||
identity: &HostIdentity,
|
identity: &HostIdentity,
|
||||||
os: ClientOs,
|
os: ClientOs,
|
||||||
@@ -158,22 +180,19 @@ pub(crate) fn profile(
|
|||||||
control: &dyn gpapi::collection::CollectionControl,
|
control: &dyn gpapi::collection::CollectionControl,
|
||||||
) -> io::Result<OsProfile> {
|
) -> io::Result<OsProfile> {
|
||||||
let identity = gpapi::os_profile::desktop::identity_from_parts(
|
let identity = gpapi::os_profile::desktop::identity_from_parts(
|
||||||
hostname.as_deref().unwrap_or(identity.computer()).into(),
|
hostname.unwrap_or_else(|| identity.computer().into()),
|
||||||
host_id.as_deref().unwrap_or(identity.host_id()).into(),
|
host_id.unwrap_or_else(|| identity.host_id().into()),
|
||||||
identity.serialno().into(),
|
identity.serialno().into(),
|
||||||
identity.mac_addr().into(),
|
identity.mac_addr().into(),
|
||||||
);
|
);
|
||||||
let mut builder = OsProfileBuilder::new(os).host_identity(identity);
|
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 {
|
if let Some(version) = version {
|
||||||
builder = builder.client_version(version);
|
builder = builder.client_version(version);
|
||||||
}
|
}
|
||||||
if let Some(os_version) = os_version {
|
if let Some(os_version) = os_version {
|
||||||
builder = builder.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 {
|
fn generation_error(error: anyhow::Error) -> io::Error {
|
||||||
@@ -238,29 +257,6 @@ mod tests {
|
|||||||
assert_eq!(profile.host_identity().serialno(), "serial");
|
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]
|
#[test]
|
||||||
fn callback_errors_preserve_cancellation() {
|
fn callback_errors_preserve_cancellation() {
|
||||||
let error = generation_error(io::Error::new(io::ErrorKind::Interrupted, "cancelled").into());
|
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;
|
mod cli;
|
||||||
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
|
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
|
||||||
mod credential_lease;
|
mod credential_lease;
|
||||||
#[cfg(unix)]
|
|
||||||
mod desktop_client;
|
mod desktop_client;
|
||||||
#[cfg(all(debug_assertions, unix))]
|
#[cfg(debug_assertions)]
|
||||||
mod dev_bootstrap;
|
mod dev_bootstrap;
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))]
|
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))]
|
||||||
mod device_anchor;
|
mod device_anchor;
|
||||||
#[cfg(unix)]
|
|
||||||
mod gui_installation;
|
|
||||||
mod handlers;
|
mod handlers;
|
||||||
mod hip_preview;
|
mod hip_preview;
|
||||||
mod hip_source;
|
mod hip_source;
|
||||||
@@ -17,41 +13,14 @@ mod hip_source;
|
|||||||
mod macos_broker;
|
mod macos_broker;
|
||||||
mod request_dispatcher;
|
mod request_dispatcher;
|
||||||
mod routes;
|
mod routes;
|
||||||
#[cfg(unix)]
|
|
||||||
mod runtime_user;
|
mod runtime_user;
|
||||||
mod session_registry;
|
mod session_registry;
|
||||||
mod vpn_script;
|
mod vpn_script;
|
||||||
mod vpn_task;
|
mod vpn_task;
|
||||||
#[cfg(windows)]
|
|
||||||
mod windows_patches;
|
|
||||||
mod ws_connection;
|
mod ws_connection;
|
||||||
mod ws_server;
|
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]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
cli::run().await;
|
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::{
|
use gpapi::{
|
||||||
service::{
|
service::{
|
||||||
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
|
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
|
||||||
transport::{ServiceErrorCode, ServiceResult},
|
transport::{ServiceErrorCode, ServiceResult},
|
||||||
},
|
},
|
||||||
utils::redact::Redaction,
|
utils::{checksum::verify_checksum, redact::Redaction},
|
||||||
};
|
};
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
#[cfg(unix)]
|
use tar::Archive;
|
||||||
|
use tempfile::NamedTempFile;
|
||||||
use tokio::sync::Mutex;
|
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(crate) struct SessionAuthority {
|
||||||
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||||
@@ -63,17 +75,12 @@ pub struct RequestDispatcher {
|
|||||||
lifecycle: crate::vpn_task::LifecycleHandle,
|
lifecycle: crate::vpn_task::LifecycleHandle,
|
||||||
gui_restart_requested: Arc<AtomicBool>,
|
gui_restart_requested: Arc<AtomicBool>,
|
||||||
redaction: Arc<Redaction>,
|
redaction: Arc<Redaction>,
|
||||||
#[cfg(unix)]
|
|
||||||
install_lock: Mutex<()>,
|
install_lock: Mutex<()>,
|
||||||
gui_management_enabled: bool,
|
gui_management_enabled: bool,
|
||||||
restricted_desktop: bool,
|
externally_brokered: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RequestDispatcher {
|
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> {
|
pub fn subscribe_tunnel(&self) -> tokio::sync::watch::Receiver<crate::vpn_task::TunnelBinding> {
|
||||||
self.lifecycle.subscribe_tunnel()
|
self.lifecycle.subscribe_tunnel()
|
||||||
}
|
}
|
||||||
@@ -82,16 +89,15 @@ impl RequestDispatcher {
|
|||||||
gui_restart_requested: Arc<AtomicBool>,
|
gui_restart_requested: Arc<AtomicBool>,
|
||||||
redaction: Arc<Redaction>,
|
redaction: Arc<Redaction>,
|
||||||
gui_management_enabled: bool,
|
gui_management_enabled: bool,
|
||||||
restricted_desktop: bool,
|
externally_brokered: bool,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
lifecycle,
|
lifecycle,
|
||||||
gui_restart_requested,
|
gui_restart_requested,
|
||||||
redaction,
|
redaction,
|
||||||
#[cfg(unix)]
|
|
||||||
install_lock: Mutex::new(()),
|
install_lock: Mutex::new(()),
|
||||||
gui_management_enabled,
|
gui_management_enabled,
|
||||||
restricted_desktop,
|
externally_brokered,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,7 +202,7 @@ impl RequestDispatcher {
|
|||||||
edited_report,
|
edited_report,
|
||||||
} => {
|
} => {
|
||||||
let prepared =
|
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 {
|
return match prepared {
|
||||||
Ok(connection) => preparation.commit(connection, desktop_uid, edited_report),
|
Ok(connection) => preparation.commit(connection, desktop_uid, edited_report),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
@@ -266,34 +272,31 @@ impl RequestDispatcher {
|
|||||||
| WsRequest::GetHipApprovalStatus { .. }
|
| WsRequest::GetHipApprovalStatus { .. }
|
||||||
| WsRequest::ReadHipPreviewChunk(_)
|
| WsRequest::ReadHipPreviewChunk(_)
|
||||||
| WsRequest::GetLastSubmittedHipReport
|
| WsRequest::GetLastSubmittedHipReport
|
||||||
| WsRequest::SetTunnelStatisticsEnabled { .. }
|
| WsRequest::SetTunnelStatisticsEnabled { .. } => {
|
||||||
| WsRequest::SetWindowsPatchInterest { .. }
|
|
||||||
| WsRequest::RefreshWindowsPatches { .. } => {
|
|
||||||
unreachable!("session-bound request was already dispatched")
|
unreachable!("session-bound request was already dispatched")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn validate_connect_request(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
|
fn validate_connect_request(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
|
||||||
if !self.restricted_desktop {
|
if !self.externally_brokered {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
if request.args().vpnc_script().is_some() {
|
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!(
|
if matches!(
|
||||||
request.args().hip_source(),
|
request.args().hip_source(),
|
||||||
gpapi::hip::HipSource::UserScript { .. } | gpapi::hip::HipSource::ApprovedRootScript { .. }
|
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() {
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult {
|
async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult {
|
||||||
if request.variant == gpapi::gui::GuiVariant::Nsh && !cfg!(target_os = "linux") {
|
if request.variant == gpapi::gui::GuiVariant::Nsh && !cfg!(target_os = "linux") {
|
||||||
return ServiceResult::rejected(
|
return ServiceResult::rejected(
|
||||||
@@ -305,17 +308,14 @@ impl RequestDispatcher {
|
|||||||
let path = request.path;
|
let path = request.path;
|
||||||
let checksum = request.checksum;
|
let checksum = request.checksum;
|
||||||
let target = request.variant.update_target();
|
let target = request.variant.update_target();
|
||||||
let installed = tokio::task::spawn_blocking(move || {
|
let installed = tokio::task::spawn_blocking(move || install_gui_at(Path::new(&path), &checksum, &target)).await;
|
||||||
crate::gui_installation::install(std::path::Path::new(&path), &checksum, &target)
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
match installed {
|
match installed {
|
||||||
Ok(Ok(())) => ServiceResult::Accepted,
|
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}");
|
warn!("Failed to verify GUI update checksum: {err}");
|
||||||
ServiceResult::rejected(ServiceErrorCode::ChecksumFailed, "GUI update checksum failed")
|
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}");
|
warn!("Failed to install GUI update: {err}");
|
||||||
ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed")
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
|
||||||
use crate::vpn_task::test_connect_request as test_request;
|
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]
|
#[tokio::test]
|
||||||
async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() {
|
async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() {
|
||||||
let dispatcher = RequestDispatcher::new(
|
let dispatcher = RequestDispatcher::new(
|
||||||
@@ -385,7 +700,7 @@ mod tests {
|
|||||||
let custom = test_request(info.clone()).with_vpnc_script(Some(script.to_string()));
|
let custom = test_request(info.clone()).with_vpnc_script(Some(script.to_string()));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
dispatcher.validate_connect_request(&custom),
|
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!(
|
assert_eq!(
|
||||||
dispatcher.validate_connect_request(&custom),
|
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 {
|
struct SessionRecord {
|
||||||
#[cfg(windows)]
|
|
||||||
windows_identity: Option<Arc<gpapi::windows::PipeClientIdentity>>,
|
|
||||||
non_tunnel: Option<AttachmentAttempt>,
|
non_tunnel: Option<AttachmentAttempt>,
|
||||||
closed_attachment: Option<Uuid>,
|
closed_attachment: Option<Uuid>,
|
||||||
secret: Zeroizing<[u8; 32]>,
|
secret: Zeroizing<[u8; 32]>,
|
||||||
@@ -257,8 +255,6 @@ impl SessionRegistry {
|
|||||||
sessions.insert(
|
sessions.insert(
|
||||||
credential.session_id(),
|
credential.session_id(),
|
||||||
SessionRecord {
|
SessionRecord {
|
||||||
#[cfg(windows)]
|
|
||||||
windows_identity: None,
|
|
||||||
non_tunnel: None,
|
non_tunnel: None,
|
||||||
closed_attachment: None,
|
closed_attachment: None,
|
||||||
secret: Zeroizing::new(*credential.secret()),
|
secret: Zeroizing::new(*credential.secret()),
|
||||||
@@ -277,38 +273,6 @@ impl SessionRegistry {
|
|||||||
Ok(credential)
|
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")]
|
#[cfg(target_os = "macos")]
|
||||||
pub fn is_empty(&self) -> bool {
|
pub fn is_empty(&self) -> bool {
|
||||||
let Ok(mut sessions) = self.sessions.lock() else {
|
let Ok(mut sessions) = self.sessions.lock() else {
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||||
#[path = "privileged_unix.rs"]
|
#[path = "privileged_unix.rs"]
|
||||||
mod platform;
|
mod platform;
|
||||||
#[cfg(windows)]
|
|
||||||
#[path = "windows.rs"]
|
|
||||||
mod platform;
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
#[path = "macos.rs"]
|
#[path = "macos.rs"]
|
||||||
mod platform;
|
mod platform;
|
||||||
@@ -11,8 +8,7 @@ mod platform;
|
|||||||
target_os = "linux",
|
target_os = "linux",
|
||||||
target_os = "freebsd",
|
target_os = "freebsd",
|
||||||
target_os = "openbsd",
|
target_os = "openbsd",
|
||||||
target_os = "macos",
|
target_os = "macos"
|
||||||
windows
|
|
||||||
)))]
|
)))]
|
||||||
#[path = "default.rs"]
|
#[path = "default.rs"]
|
||||||
mod platform;
|
mod platform;
|
||||||
@@ -20,5 +16,3 @@ mod platform;
|
|||||||
mod selection;
|
mod selection;
|
||||||
|
|
||||||
pub(crate) use platform::builder;
|
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)]
|
#[derive(Clone)]
|
||||||
pub(crate) struct LifecycleHandle {
|
pub(crate) struct LifecycleHandle {
|
||||||
#[cfg(windows)]
|
|
||||||
pub(crate) patch_checks: Arc<crate::windows_patches::PatchChecks>,
|
|
||||||
events: mpsc::Sender<LifecycleEvent>,
|
events: mpsc::Sender<LifecycleEvent>,
|
||||||
admissions: Arc<Mutex<Admissions>>,
|
admissions: Arc<Mutex<Admissions>>,
|
||||||
tunnel: watch::Sender<TunnelBinding>,
|
tunnel: watch::Sender<TunnelBinding>,
|
||||||
@@ -128,7 +126,6 @@ impl LifecycleHandle {
|
|||||||
ServiceResult::Accepted
|
ServiceResult::Accepted
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(unix, test))]
|
|
||||||
pub async fn disconnect_and_wait(&self) -> bool {
|
pub async fn disconnect_and_wait(&self) -> bool {
|
||||||
let completion = {
|
let completion = {
|
||||||
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
|
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
|
||||||
@@ -450,7 +447,7 @@ pub(crate) struct VpnTask {
|
|||||||
events: mpsc::Receiver<LifecycleEvent>,
|
events: mpsc::Receiver<LifecycleEvent>,
|
||||||
lifecycle: LifecycleHandle,
|
lifecycle: LifecycleHandle,
|
||||||
vpn_state_tx: watch::Sender<VpnState>,
|
vpn_state_tx: watch::Sender<VpnState>,
|
||||||
restricted_desktop: bool,
|
brokered_macos: bool,
|
||||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||||
active: Option<ActiveAttempt>,
|
active: Option<ActiveAttempt>,
|
||||||
cancel_token: CancellationToken,
|
cancel_token: CancellationToken,
|
||||||
@@ -459,13 +456,11 @@ pub(crate) struct VpnTask {
|
|||||||
impl VpnTask {
|
impl VpnTask {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
vpn_state_tx: watch::Sender<VpnState>,
|
vpn_state_tx: watch::Sender<VpnState>,
|
||||||
restricted_desktop: bool,
|
brokered_macos: bool,
|
||||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||||
) -> (Self, LifecycleHandle) {
|
) -> (Self, LifecycleHandle) {
|
||||||
let (events_tx, events) = mpsc::channel(4);
|
let (events_tx, events) = mpsc::channel(4);
|
||||||
let lifecycle = LifecycleHandle {
|
let lifecycle = LifecycleHandle {
|
||||||
#[cfg(windows)]
|
|
||||||
patch_checks: crate::windows_patches::PatchChecks::new(),
|
|
||||||
events: events_tx,
|
events: events_tx,
|
||||||
admissions: Arc::new(Mutex::new(Admissions::default())),
|
admissions: Arc::new(Mutex::new(Admissions::default())),
|
||||||
tunnel: watch::channel(TunnelBinding::default()).0,
|
tunnel: watch::channel(TunnelBinding::default()).0,
|
||||||
@@ -475,7 +470,7 @@ impl VpnTask {
|
|||||||
events,
|
events,
|
||||||
lifecycle: lifecycle.clone(),
|
lifecycle: lifecycle.clone(),
|
||||||
vpn_state_tx,
|
vpn_state_tx,
|
||||||
restricted_desktop,
|
brokered_macos,
|
||||||
registry,
|
registry,
|
||||||
active: None,
|
active: None,
|
||||||
cancel_token: CancellationToken::new(),
|
cancel_token: CancellationToken::new(),
|
||||||
@@ -622,7 +617,7 @@ impl VpnTask {
|
|||||||
desktop_uid,
|
desktop_uid,
|
||||||
edited_report,
|
edited_report,
|
||||||
session_id,
|
session_id,
|
||||||
restricted_desktop: self.restricted_desktop,
|
brokered_macos: self.brokered_macos,
|
||||||
registry: self.registry.clone(),
|
registry: self.registry.clone(),
|
||||||
lifecycle: self.lifecycle.clone(),
|
lifecycle: self.lifecycle.clone(),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -66,13 +66,10 @@ pub(super) async fn run(
|
|||||||
md5: request.md5.clone(),
|
md5: request.md5.clone(),
|
||||||
};
|
};
|
||||||
if !posture_enabled {
|
if !posture_enabled {
|
||||||
return gphip::generate_identity_report(
|
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||||
&gphip::ReportInput {
|
|
||||||
profile: profile.clone(),
|
profile: profile.clone(),
|
||||||
context,
|
context,
|
||||||
},
|
})
|
||||||
control,
|
|
||||||
)
|
|
||||||
.map_err(std::io::Error::other);
|
.map_err(std::io::Error::other);
|
||||||
}
|
}
|
||||||
source.collect(
|
source.collect(
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ pub(super) struct ConnectionResources {
|
|||||||
/// the complete ledger and its retained identity resources to the service.
|
/// the complete ledger and its retained identity resources to the service.
|
||||||
pub(crate) async fn prepare_connection(
|
pub(crate) async fn prepare_connection(
|
||||||
request: ConnectRequest,
|
request: ConnectRequest,
|
||||||
restricted_desktop: bool,
|
brokered_macos: bool,
|
||||||
cancellation: CancellationToken,
|
cancellation: CancellationToken,
|
||||||
) -> anyhow::Result<PreparedConnection> {
|
) -> anyhow::Result<PreparedConnection> {
|
||||||
let mode = request.args().packet_delivery().clone();
|
let mode = request.args().packet_delivery().clone();
|
||||||
@@ -77,16 +77,11 @@ pub(crate) async fn prepare_connection(
|
|||||||
};
|
};
|
||||||
check()?;
|
check()?;
|
||||||
let args = setup_request.args();
|
let args = setup_request.args();
|
||||||
let identity = super::prepare_identity(args, restricted_desktop || non_tunnel)?;
|
let identity = super::prepare_identity(args, brokered_macos || non_tunnel)?;
|
||||||
#[cfg(target_os = "macos")]
|
let directory = brokered_macos.then(|| std::path::Path::new("/var/run/com.yuezk.gpgui"));
|
||||||
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_files = identity
|
let identity_files = identity
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|identity| identity.write_files(directory.as_deref()))
|
.map(|identity| identity.write_files(directory))
|
||||||
.transpose()?;
|
.transpose()?;
|
||||||
let host = args.host_identity().context("Authenticated host identity is missing")?;
|
let host = args.host_identity().context("Authenticated host identity is missing")?;
|
||||||
let profile = crate::hip_source::profile(
|
let profile = crate::hip_source::profile(
|
||||||
@@ -186,8 +181,8 @@ mod tests {
|
|||||||
use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo};
|
use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo};
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn restricted_desktop_and_non_tunnel_identity_reject_path_handoff() {
|
async fn brokered_macos_and_non_tunnel_identity_reject_path_handoff() {
|
||||||
for (restricted_desktop, non_tunnel) in [(true, false), (false, true), (true, true)] {
|
for (brokered_macos, non_tunnel) in [(true, false), (false, true), (true, true)] {
|
||||||
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
|
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![]))
|
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||||
.with_certificate(Some("/identity.pem".into()));
|
.with_certificate(Some("/identity.pem".into()));
|
||||||
@@ -197,7 +192,7 @@ mod tests {
|
|||||||
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
||||||
}
|
}
|
||||||
let request = serde_json::from_value(wire).unwrap();
|
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
|
.await
|
||||||
.err()
|
.err()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ pub(super) struct AttemptInput {
|
|||||||
pub desktop_uid: Option<u32>,
|
pub desktop_uid: Option<u32>,
|
||||||
pub edited_report: Option<Arc<str>>,
|
pub edited_report: Option<Arc<str>>,
|
||||||
pub session_id: Option<Uuid>,
|
pub session_id: Option<Uuid>,
|
||||||
pub restricted_desktop: bool,
|
pub brokered_macos: bool,
|
||||||
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||||
pub lifecycle: LifecycleHandle,
|
pub lifecycle: LifecycleHandle,
|
||||||
}
|
}
|
||||||
@@ -31,7 +31,6 @@ struct TunnelInput {
|
|||||||
source: Arc<openconnect::HipSource>,
|
source: Arc<openconnect::HipSource>,
|
||||||
session_id: Option<Uuid>,
|
session_id: Option<Uuid>,
|
||||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||||
#[cfg(unix)]
|
|
||||||
desktop_uid: Option<u32>,
|
desktop_uid: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,30 +49,13 @@ pub(super) fn spawn(
|
|||||||
) -> JoinHandle<()> {
|
) -> JoinHandle<()> {
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let attempt = input.attempt;
|
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 failure = None;
|
||||||
let mut approval = None;
|
let mut approval = None;
|
||||||
if !cancellation.is_cancelled() {
|
if !cancellation.is_cancelled() {
|
||||||
let request = input.connection.request.clone();
|
let request = input.connection.request.clone();
|
||||||
let resources = input.connection.resources.clone();
|
let resources = input.connection.resources.clone();
|
||||||
let desktop_uid = input.desktop_uid;
|
let desktop_uid = input.desktop_uid;
|
||||||
let brokered = input.restricted_desktop;
|
let brokered = input.brokered_macos;
|
||||||
let edited = input.edited_report.clone();
|
let edited = input.edited_report.clone();
|
||||||
let setup_cancel = cancellation.clone();
|
let setup_cancel = cancellation.clone();
|
||||||
let execution = tokio::task::spawn_blocking(move || {
|
let execution = tokio::task::spawn_blocking(move || {
|
||||||
@@ -123,7 +105,6 @@ pub(super) fn spawn(
|
|||||||
source,
|
source,
|
||||||
session_id: input.session_id,
|
session_id: input.session_id,
|
||||||
registry: input.registry.clone(),
|
registry: input.registry.clone(),
|
||||||
#[cfg(unix)]
|
|
||||||
desktop_uid: input.desktop_uid,
|
desktop_uid: input.desktop_uid,
|
||||||
};
|
};
|
||||||
input.connection.request.release_script_tun_bootstrap();
|
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) => {
|
gpapi::script_tun::PacketDelivery::ScriptTun(request) => {
|
||||||
ensure!(input.session_id.is_some(), "Script-tun requires a desktop session");
|
ensure!(input.session_id.is_some(), "Script-tun requires a desktop session");
|
||||||
#[cfg(unix)]
|
let (builder, script_tun) = super::script_tun::builder(
|
||||||
let owner = input.desktop_uid.context("Desktop identity is unavailable")?;
|
member.gateway.server(),
|
||||||
#[cfg(windows)]
|
member.authentication.cookie(),
|
||||||
let owner = input
|
request,
|
||||||
.registry
|
input.desktop_uid.context("Desktop identity is unavailable")?,
|
||||||
.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)?;
|
|
||||||
(builder, Some(script_tun))
|
(builder, Some(script_tun))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,19 +1,40 @@
|
|||||||
//! Supervision of an unprivileged script-tun consumer; payload semantics belong to the caller.
|
//! Supervision of an unprivileged script-tun consumer; payload semantics belong to the caller.
|
||||||
use super::{LifecycleEvent, LifecycleHandle};
|
use super::{LifecycleEvent, LifecycleHandle};
|
||||||
use anyhow::{Context, bail, ensure};
|
use anyhow::{Context, bail, ensure};
|
||||||
use gpapi::script_tun::{Bootstrap, Identity, Message, receive, send as send_message};
|
use gpapi::script_tun::{Bootstrap, Identity, Message, ScriptTunRequest, receive, send as send_message};
|
||||||
use openconnect::{Vpn, tunnel::Event};
|
use openconnect::{Vpn, VpnBuilder, tunnel::Event};
|
||||||
use std::{sync::Arc, time::Duration};
|
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;
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
#[cfg(unix)]
|
pub(super) struct PreparedScriptTun {
|
||||||
#[path = "script_tun/unix.rs"]
|
pub control: std::os::unix::net::UnixStream,
|
||||||
mod platform;
|
pub bootstrap: Bootstrap,
|
||||||
#[cfg(windows)]
|
}
|
||||||
#[path = "script_tun/windows.rs"]
|
|
||||||
mod platform;
|
pub(super) fn builder(
|
||||||
pub(super) use platform::{PreparedScriptTun, 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)]
|
#[derive(Debug)]
|
||||||
pub(super) struct NetworkChanged;
|
pub(super) struct NetworkChanged;
|
||||||
@@ -32,7 +53,7 @@ enum Native {
|
|||||||
pub(super) async fn run(
|
pub(super) async fn run(
|
||||||
identity: Identity,
|
identity: Identity,
|
||||||
vpn: Arc<Vpn>,
|
vpn: Arc<Vpn>,
|
||||||
mut prepared: PreparedScriptTun,
|
prepared: PreparedScriptTun,
|
||||||
approval: &crate::hip_source::HipApproval,
|
approval: &crate::hip_source::HipApproval,
|
||||||
lifecycle: &LifecycleHandle,
|
lifecycle: &LifecycleHandle,
|
||||||
cancellation: CancellationToken,
|
cancellation: CancellationToken,
|
||||||
@@ -41,8 +62,6 @@ pub(super) async fn run(
|
|||||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||||
sessions: &mut gpapi::session::desktop::GatewaySessions,
|
sessions: &mut gpapi::session::desktop::GatewaySessions,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let channel = prepared.connect().await?;
|
|
||||||
let mut control = ConsumerControl::new(channel);
|
|
||||||
let attempt = identity.attempt;
|
let attempt = identity.attempt;
|
||||||
let (native_tx, native) = mpsc::channel(64);
|
let (native_tx, native) = mpsc::channel(64);
|
||||||
let observed = native_tx.clone();
|
let observed = native_tx.clone();
|
||||||
@@ -58,7 +77,7 @@ pub(super) async fn run(
|
|||||||
monitor: monitor.clone(),
|
monitor: monitor.clone(),
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
if event_result.is_err() || cancellation.is_cancelled() {
|
if event_result.is_err() {
|
||||||
monitor.stop().await;
|
monitor.stop().await;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -72,15 +91,7 @@ pub(super) async fn run(
|
|||||||
tokio::pin!(worker);
|
tokio::pin!(worker);
|
||||||
let mut worker_done = false;
|
let mut worker_done = false;
|
||||||
let stop = cancellation.child_token();
|
let stop = cancellation.child_token();
|
||||||
let result = {
|
let supervisor = supervise(identity, prepared, native, stop.clone(), events);
|
||||||
let supervisor = supervise(
|
|
||||||
identity,
|
|
||||||
&mut control,
|
|
||||||
std::mem::take(&mut prepared.bootstrap),
|
|
||||||
native,
|
|
||||||
stop.clone(),
|
|
||||||
events,
|
|
||||||
);
|
|
||||||
tokio::pin!(supervisor);
|
tokio::pin!(supervisor);
|
||||||
let mut supervisor_done = false;
|
let mut supervisor_done = false;
|
||||||
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
|
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
|
||||||
@@ -97,25 +108,14 @@ pub(super) async fn run(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
stop.cancel();
|
stop.cancel();
|
||||||
// Keep the consumer's control and packet endpoints alive until OpenConnect
|
if !supervisor_done {
|
||||||
// consumes cancellation and logs out. Early EOF would interrupt that logout.
|
let _ = supervisor.await;
|
||||||
|
}
|
||||||
vpn.disconnect();
|
vpn.disconnect();
|
||||||
if !worker_done {
|
if !worker_done {
|
||||||
let _ = worker.await;
|
let _ = worker.await;
|
||||||
}
|
}
|
||||||
if !supervisor_done {
|
|
||||||
let _ = supervisor.await;
|
|
||||||
}
|
|
||||||
result
|
|
||||||
};
|
|
||||||
control.stop().await;
|
|
||||||
let cleanup = prepared.stop_worker();
|
|
||||||
monitor.stop().await;
|
monitor.stop().await;
|
||||||
if result.is_ok() {
|
|
||||||
cleanup?;
|
|
||||||
} else if let Err(error) = cleanup {
|
|
||||||
log::warn!("Could not stop packet worker: {error:#}");
|
|
||||||
}
|
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,17 +128,20 @@ enum WorkerState {
|
|||||||
Suspending,
|
Suspending,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Own the channel independently of its supervision future so run() can drain
|
// The same control loop runs against native observations in production and a
|
||||||
// the native VPN before telling the consumer to stop or closing its endpoints.
|
// generic socket consumer in tests; VPN ownership stays in run().
|
||||||
struct ConsumerControl {
|
async fn supervise(
|
||||||
output: tokio::io::WriteHalf<platform::ControlStream>,
|
identity: Identity,
|
||||||
messages: mpsc::Receiver<std::io::Result<Message>>,
|
mut prepared: PreparedScriptTun,
|
||||||
reader: tokio::task::JoinHandle<()>,
|
mut native: mpsc::Receiver<Native>,
|
||||||
}
|
cancellation: CancellationToken,
|
||||||
impl ConsumerControl {
|
events: mpsc::Sender<LifecycleEvent>,
|
||||||
fn new(channel: platform::ControlStream) -> Self {
|
) -> anyhow::Result<()> {
|
||||||
let (mut input, output) = tokio::io::split(channel);
|
let attempt = identity.attempt;
|
||||||
let (messages_tx, messages) = mpsc::channel(8);
|
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 {
|
let reader = tokio::spawn(async move {
|
||||||
loop {
|
loop {
|
||||||
let message = receive(&mut input).await;
|
let message = receive(&mut input).await;
|
||||||
@@ -148,41 +151,13 @@ impl ConsumerControl {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
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.
|
|
||||||
async fn supervise(
|
|
||||||
identity: Identity,
|
|
||||||
control: &mut ConsumerControl,
|
|
||||||
mut bootstrap: Bootstrap,
|
|
||||||
mut native: mpsc::Receiver<Native>,
|
|
||||||
cancellation: CancellationToken,
|
|
||||||
events: mpsc::Sender<LifecycleEvent>,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let attempt = identity.attempt;
|
|
||||||
let ConsumerControl { output, messages, .. } = control;
|
|
||||||
let mut network = None;
|
let mut network = None;
|
||||||
let mut session = None;
|
let mut session = None;
|
||||||
let mut worker = WorkerState::Preparing;
|
let mut worker = WorkerState::Preparing;
|
||||||
let mut online = false;
|
let mut online = false;
|
||||||
let mut was_connected = false;
|
let mut was_connected = false;
|
||||||
let mut deadline: Option<Instant> = None;
|
let mut deadline: Option<Instant> = None;
|
||||||
|
let result = async {
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
biased;
|
biased;
|
||||||
@@ -210,7 +185,7 @@ async fn supervise(
|
|||||||
let observed = observed?;
|
let observed = observed?;
|
||||||
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
|
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
|
||||||
else {
|
else {
|
||||||
send(output, &Message::Configure { identity, bootstrap: std::mem::take(&mut bootstrap), network: observed.clone() }).await?;
|
send(&mut output, &Message::Configure { identity, bootstrap: std::mem::take(&mut prepared.bootstrap), network: observed.clone() }).await?;
|
||||||
network = Some(observed);
|
network = Some(observed);
|
||||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||||
}
|
}
|
||||||
@@ -220,7 +195,7 @@ async fn supervise(
|
|||||||
online = false;
|
online = false;
|
||||||
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
|
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
|
||||||
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
|
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
|
||||||
send(output, &Message::Suspend).await?; worker = WorkerState::Suspending;
|
send(&mut output, &Message::Suspend).await?; worker = WorkerState::Suspending;
|
||||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -229,12 +204,17 @@ async fn supervise(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
|
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
|
||||||
send(output, &Message::Activate).await?;
|
send(&mut output, &Message::Activate).await?; worker = WorkerState::Activating;
|
||||||
worker = WorkerState::Activating;
|
|
||||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
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(
|
fn observed_network(
|
||||||
@@ -263,5 +243,5 @@ async fn send(writer: &mut (impl tokio::io::AsyncWrite + Unpin), message: &Messa
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, unix))]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use gpapi::script_tun::{Bootstrap, ScriptTunRequest};
|
|
||||||
use openconnect::{VpnSessionInfo, tunnel::Configuration};
|
use openconnect::{VpnSessionInfo, tunnel::Configuration};
|
||||||
use tokio::io::AsyncWriteExt;
|
use tokio::io::AsyncWriteExt;
|
||||||
use tokio::net::UnixStream;
|
|
||||||
|
|
||||||
// A generic consumer, with no proxy settings or private worker protocol.
|
// A generic consumer, with no proxy settings or private worker protocol.
|
||||||
struct Consumer {
|
struct Consumer {
|
||||||
@@ -25,26 +23,16 @@ impl Consumer {
|
|||||||
launch_id: uuid::Uuid::new_v4(),
|
launch_id: uuid::Uuid::new_v4(),
|
||||||
};
|
};
|
||||||
let cancel = CancellationToken::new();
|
let cancel = CancellationToken::new();
|
||||||
let stopped = cancel.clone();
|
let task = tokio::spawn(supervise(
|
||||||
let task = tokio::spawn(async move {
|
|
||||||
let mut prepared = PreparedScriptTun {
|
|
||||||
control: Some(control),
|
|
||||||
bootstrap: Bootstrap::new(b"consumer bootstrap").unwrap(),
|
|
||||||
};
|
|
||||||
let channel = prepared.connect().await?;
|
|
||||||
let mut control = ConsumerControl::new(channel);
|
|
||||||
let result = supervise(
|
|
||||||
identity,
|
identity,
|
||||||
&mut control,
|
PreparedScriptTun {
|
||||||
prepared.bootstrap,
|
control,
|
||||||
|
bootstrap: Bootstrap::new(b"consumer bootstrap").unwrap(),
|
||||||
|
},
|
||||||
observations,
|
observations,
|
||||||
stopped,
|
cancel.clone(),
|
||||||
events,
|
events,
|
||||||
)
|
));
|
||||||
.await;
|
|
||||||
control.stop().await;
|
|
||||||
result
|
|
||||||
});
|
|
||||||
Self {
|
Self {
|
||||||
control: UnixStream::from_std(child).unwrap(),
|
control: UnixStream::from_std(child).unwrap(),
|
||||||
native,
|
native,
|
||||||
@@ -303,36 +291,3 @@ async fn reconnect_during_activation_returns_clear_error_without_connected() {
|
|||||||
);
|
);
|
||||||
assert!(consumer.events.try_recv().is_err());
|
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(());
|
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 {
|
if let WsRequest::StoreEditedHipReportChunk(report) = request {
|
||||||
let upload_id = report.upload_id.as_deref().and_then(|id| Uuid::parse_str(id).ok());
|
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() {
|
let result = if report.upload_id.is_some() && upload_id.is_none() {
|
||||||
@@ -493,7 +451,6 @@ async fn handle_client_message(
|
|||||||
offset: chunk.offset,
|
offset: chunk.offset,
|
||||||
xml,
|
xml,
|
||||||
complete,
|
complete,
|
||||||
windows_updates: None,
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.unwrap_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP preview is unavailable"));
|
.unwrap_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP preview is unavailable"));
|
||||||
@@ -510,7 +467,6 @@ async fn handle_client_message(
|
|||||||
offset: 0,
|
offset: 0,
|
||||||
xml,
|
xml,
|
||||||
complete,
|
complete,
|
||||||
windows_updates: None,
|
|
||||||
},
|
},
|
||||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"),
|
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 {
|
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 edited_report = if let HipSource::Edited { report_id } = &preview.source {
|
||||||
let report_id = match Uuid::parse_str(report_id) {
|
let report_id = match Uuid::parse_str(report_id) {
|
||||||
Ok(id) => id,
|
Ok(id) => id,
|
||||||
|
|||||||
@@ -63,8 +63,6 @@ pub(crate) struct WsServerContext {
|
|||||||
state: Mutex<ServiceState>,
|
state: Mutex<ServiceState>,
|
||||||
handshake_slots: Arc<Semaphore>,
|
handshake_slots: Arc<Semaphore>,
|
||||||
pub(crate) hip_previews: crate::hip_preview::HipPreviews,
|
pub(crate) hip_previews: crate::hip_preview::HipPreviews,
|
||||||
#[cfg(windows)]
|
|
||||||
pub(crate) patch_checks: Arc<crate::windows_patches::PatchChecks>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WsServerContext {
|
impl WsServerContext {
|
||||||
@@ -77,8 +75,6 @@ impl WsServerContext {
|
|||||||
Self {
|
Self {
|
||||||
product_version,
|
product_version,
|
||||||
registry,
|
registry,
|
||||||
#[cfg(windows)]
|
|
||||||
patch_checks: dispatcher.patch_checks(),
|
|
||||||
dispatcher,
|
dispatcher,
|
||||||
state: Mutex::new(ServiceState {
|
state: Mutex::new(ServiceState {
|
||||||
revision: 0,
|
revision: 0,
|
||||||
@@ -187,8 +183,6 @@ impl WsServerContext {
|
|||||||
|
|
||||||
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
||||||
self.registry.disconnect_if_current(session_id, generation);
|
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;
|
let mut state = self.state.lock().await;
|
||||||
state.connections.remove(&connection_id);
|
state.connections.remove(&connection_id);
|
||||||
state.refresh_demand();
|
state.refresh_demand();
|
||||||
@@ -350,7 +344,6 @@ impl WsServer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
pub fn context(&self) -> Arc<WsServerContext> {
|
pub fn context(&self) -> Arc<WsServerContext> {
|
||||||
Arc::clone(&self.ctx)
|
Arc::clone(&self.ctx)
|
||||||
}
|
}
|
||||||
@@ -370,12 +363,6 @@ impl WsServer {
|
|||||||
};
|
};
|
||||||
let _ = ready_tx.send(());
|
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! {
|
tokio::select! {
|
||||||
_ = watch_vpn_state(self.vpn_state_rx.clone(), Arc::clone(&self.ctx)) => {
|
_ = watch_vpn_state(self.vpn_state_rx.clone(), Arc::clone(&self.ctx)) => {
|
||||||
info!("VPN state watch task completed");
|
info!("VPN state watch task completed");
|
||||||
@@ -390,9 +377,6 @@ impl WsServer {
|
|||||||
info!("WS server cancelled");
|
info!("WS server cancelled");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.cancel_token.cancel();
|
|
||||||
#[cfg(windows)]
|
|
||||||
let _ = patch_task.await;
|
|
||||||
self.ctx.hip_previews.shutdown().await;
|
self.ctx.hip_previews.shutdown().await;
|
||||||
let _ = shutdown_tx.send(()).await;
|
let _ = shutdown_tx.send(()).await;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,90 +1,5 @@
|
|||||||
# Changelog
|
# 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
|
|
||||||
|
|
||||||
- Made client certificate errors clearer and added more detail to gateway sign-in logs.
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
|
|
||||||
- Restored support for client certificates with private extensions and legacy RC4-encrypted PKCS#12 files.
|
|
||||||
- Fixed certificate chain selection for PKCS#12 files containing multiple possible issuers.
|
|
||||||
- Fixed certificate validation and recovery guidance in both desktop interfaces.
|
|
||||||
- Fixed Native Shell Settings windows failing to activate from the macOS menu or reopening on the wrong page.
|
|
||||||
- Fixed keyboard navigation and Escape handling in the macOS Native Shell interface.
|
|
||||||
- Fixed AUR package builds and dependency metadata.
|
|
||||||
|
|
||||||
## 3.3.0
|
|
||||||
|
|
||||||
### Added
|
|
||||||
|
|
||||||
- Added Native Shell, a new desktop interface for macOS and Linux. macOS builds now use it by default.
|
|
||||||
- Added an Interface setting on Linux to switch between Tauri and Native Shell.
|
|
||||||
- Added tray icon appearance options for light and dark desktop panels on Linux, FreeBSD, and OpenBSD.
|
|
||||||
- Added in-app feature highlights, with a setting to turn them off.
|
|
||||||
|
|
||||||
### Improved
|
|
||||||
|
|
||||||
- Made System VPN and Local Proxy modes selectable directly from the main window.
|
|
||||||
- Refined connection details, saved-server selection, keyboard navigation, and dialog appearance.
|
|
||||||
- Removed the need for OpenSSL compatibility configuration and external OpenSSL conversion tools.
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
|
|
||||||
- Fixed macOS VPN DNS configuration and cleanup, including split-tunnel connections.
|
|
||||||
- Fixed background CLI reconnections failing after the initial connection.
|
|
||||||
- Fixed server addresses losing custom ports when pasted as URLs.
|
|
||||||
- Fixed gateway login address handling for servers with explicit ports.
|
|
||||||
- Fixed browser sign-in registration when desktop-specific settings override the callback handler on Linux, FreeBSD, or OpenBSD.
|
|
||||||
- Fixed Okta FastPass failing to open Okta Verify from the embedded sign-in window on Linux, FreeBSD, and OpenBSD.
|
|
||||||
- Fixed supplied server certificate pins not being enforced during tunnel setup.
|
|
||||||
- Fixed delayed clicks activating a different control after a Native Shell view changed.
|
|
||||||
|
|
||||||
### Command-line notes
|
|
||||||
|
|
||||||
- Deprecated `--fix-openssl` on Linux, FreeBSD, and OpenBSD. Existing commands still accept it, but it has no effect.
|
|
||||||
|
|
||||||
## 3.2.0
|
## 3.2.0
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
+1
-17
@@ -20,6 +20,7 @@ browser-launcher = { path = "../browser-launcher", default-features = false, fea
|
|||||||
tiny_http = { version = "0.12", optional = true }
|
tiny_http = { version = "0.12", optional = true }
|
||||||
tempfile = { workspace = true, optional = true }
|
tempfile = { workspace = true, optional = true }
|
||||||
uuid = { version = "1", optional = true, features = ["v4"] }
|
uuid = { version = "1", optional = true, features = ["v4"] }
|
||||||
|
uzers = { workspace = true, optional = true }
|
||||||
|
|
||||||
# Webview auth dependencies
|
# Webview auth dependencies
|
||||||
tauri = { workspace = true, optional = true }
|
tauri = { workspace = true, optional = true }
|
||||||
@@ -27,7 +28,6 @@ regex = { workspace = true, optional = true }
|
|||||||
tokio-util = { workspace = true, optional = true }
|
tokio-util = { workspace = true, optional = true }
|
||||||
html-escape = { version = "0.3", optional = true }
|
html-escape = { version = "0.3", optional = true }
|
||||||
url = { workspace = true, 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]
|
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
|
||||||
webkit2gtk = { version = "2", optional = true }
|
webkit2gtk = { version = "2", optional = true }
|
||||||
@@ -60,9 +60,6 @@ webview-auth = [
|
|||||||
"dep:tokio-util",
|
"dep:tokio-util",
|
||||||
"dep:html-escape",
|
"dep:html-escape",
|
||||||
"dep:url",
|
"dep:url",
|
||||||
"dep:serde_json",
|
|
||||||
"dep:webview2-com",
|
|
||||||
"dep:windows",
|
|
||||||
"dep:gtk",
|
"dep:gtk",
|
||||||
"dep:webkit2gtk",
|
"dep:webkit2gtk",
|
||||||
"dep:block2",
|
"dep:block2",
|
||||||
@@ -97,16 +94,3 @@ release-devtools = ["webview-auth", "tauri/devtools"]
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile.workspace = true
|
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,
|
io::ErrorKind,
|
||||||
os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
|
os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
|
||||||
use anyhow::{Context, bail};
|
use anyhow::{Context, bail};
|
||||||
@@ -13,9 +14,16 @@ use tokio::{
|
|||||||
time::timeout,
|
time::timeout,
|
||||||
};
|
};
|
||||||
|
|
||||||
mod protocol;
|
const CALLBACK_SCHEME: &str = "globalprotectcallback";
|
||||||
pub use protocol::validate_auth_callback;
|
const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC";
|
||||||
use protocol::*;
|
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")]
|
#[cfg(target_os = "macos")]
|
||||||
mod macos;
|
mod macos;
|
||||||
@@ -224,9 +232,62 @@ fn remove_stale_socket(socket_path: &Path) -> anyhow::Result<()> {
|
|||||||
Ok(())
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::time::Duration;
|
|
||||||
use tempfile::tempdir;
|
use tempfile::tempdir;
|
||||||
|
|
||||||
use super::*;
|
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;
|
mod browser;
|
||||||
|
|
||||||
#[cfg(feature = "browser-auth")]
|
#[cfg(feature = "browser-auth")]
|
||||||
#[cfg_attr(windows, path = "callback/windows.rs")]
|
|
||||||
mod callback;
|
mod callback;
|
||||||
|
|
||||||
#[cfg(feature = "browser-auth")]
|
#[cfg(feature = "browser-auth")]
|
||||||
|
|||||||
@@ -12,17 +12,12 @@ mod platform_impl;
|
|||||||
#[path = "webview/macos.rs"]
|
#[path = "webview/macos.rs"]
|
||||||
mod platform_impl;
|
mod platform_impl;
|
||||||
|
|
||||||
#[cfg(windows)]
|
|
||||||
#[path = "webview/windows.rs"]
|
|
||||||
mod platform_impl;
|
|
||||||
|
|
||||||
#[cfg(not(any(
|
#[cfg(not(any(
|
||||||
windows,
|
|
||||||
target_os = "macos",
|
target_os = "macos",
|
||||||
target_os = "linux",
|
target_os = "linux",
|
||||||
target_os = "freebsd",
|
target_os = "freebsd",
|
||||||
target_os = "openbsd"
|
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};
|
pub use webview_auth::{WebviewAuthenticator, apply_auth_theme};
|
||||||
@@ -9,7 +9,7 @@ use tokio_util::sync::CancellationToken;
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub(crate) enum AuthDataLocation {
|
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,
|
Headers,
|
||||||
Body,
|
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) {
|
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader, generation: u64) {
|
||||||
use log::warn;
|
use log::warn;
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ impl RecoveryStatus {
|
|||||||
Self::Hidden => "",
|
Self::Hidden => "",
|
||||||
Self::Restarting => "Restarting sign-in…",
|
Self::Restarting => "Restarting sign-in…",
|
||||||
Self::Loading => "Loading 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::Rejected => "Sign-in wasn’t completed.",
|
||||||
Self::Tls {
|
Self::Tls {
|
||||||
reason: TlsFailureReason::Handshake,
|
reason: TlsFailureReason::Handshake,
|
||||||
@@ -55,7 +55,6 @@ impl RecoveryStatus {
|
|||||||
matches!(self, Self::Hidden | Self::Loading | Self::CertificateBypassed)
|
matches!(self, Self::Hidden | Self::Loading | Self::CertificateBypassed)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(windows))]
|
|
||||||
pub fn is_busy(self) -> bool {
|
pub fn is_busy(self) -> bool {
|
||||||
matches!(self, Self::Restarting | Self::Loading)
|
matches!(self, Self::Restarting | Self::Loading)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,7 @@
|
|||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub(super) enum TlsFailureReason {
|
pub(super) enum TlsFailureReason {
|
||||||
Expired,
|
Expired,
|
||||||
#[cfg(not(windows))]
|
|
||||||
NotYetValid,
|
NotYetValid,
|
||||||
#[cfg(not(windows))]
|
|
||||||
Untrusted,
|
Untrusted,
|
||||||
HostnameMismatch,
|
HostnameMismatch,
|
||||||
InvalidCertificate,
|
InvalidCertificate,
|
||||||
@@ -19,9 +17,7 @@ impl TlsFailureReason {
|
|||||||
pub fn message(self) -> &'static str {
|
pub fn message(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
Self::Expired => "The certificate has expired.",
|
Self::Expired => "The certificate has expired.",
|
||||||
#[cfg(not(windows))]
|
|
||||||
Self::NotYetValid => "The certificate is not valid yet.",
|
Self::NotYetValid => "The certificate is not valid yet.",
|
||||||
#[cfg(not(windows))]
|
|
||||||
Self::Untrusted => "The certificate was issued by an untrusted authority.",
|
Self::Untrusted => "The certificate was issued by an untrusted authority.",
|
||||||
Self::HostnameMismatch => "The certificate does not match this server’s hostname.",
|
Self::HostnameMismatch => "The certificate does not match this server’s hostname.",
|
||||||
Self::InvalidCertificate => "The server’s certificate could not be verified.",
|
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 std::{future::Future, pin::Pin, sync::Arc, time::Duration};
|
||||||
|
|
||||||
use anyhow::bail;
|
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"))]
|
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||||
use gpapi::utils::window::{WindowTypeHint, set_window_type_hint};
|
use gpapi::utils::window::{WindowTypeHint, set_window_type_hint};
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
@@ -10,51 +8,24 @@ use gpapi::{
|
|||||||
error::ServerTlsError,
|
error::ServerTlsError,
|
||||||
gp_params::GpParams,
|
gp_params::GpParams,
|
||||||
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
|
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
|
||||||
utils::redact::redact_uri,
|
utils::{redact::redact_uri, window::get_title_bar_height},
|
||||||
};
|
};
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
use tauri::Manager;
|
use tauri::Manager;
|
||||||
#[cfg(not(windows))]
|
use tauri::{AppHandle, WebviewUrl, WebviewWindow, WindowEvent};
|
||||||
use tauri::WebviewUrl;
|
|
||||||
use tauri::{AppHandle, WindowEvent};
|
|
||||||
use tokio::{sync::oneshot, time};
|
use tokio::{sync::oneshot, time};
|
||||||
|
|
||||||
use crate::auth_prelogin;
|
use crate::auth_prelogin;
|
||||||
|
|
||||||
#[cfg(not(windows))]
|
|
||||||
use super::address_bar::TOOLBAR_HEIGHT;
|
use super::address_bar::TOOLBAR_HEIGHT;
|
||||||
use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
|
use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
|
||||||
use super::recovery::{Recovery, RecoveryStatus, RetryPlan, RetrySource, RetryTiming};
|
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);
|
const RESTART_TIMEOUT: Duration = Duration::from_secs(30);
|
||||||
|
|
||||||
pub(super) trait PlatformWebviewExt {
|
pub trait PlatformWebviewExt {
|
||||||
fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
|
fn install_auth_controls(&self, window: &WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
|
||||||
|
|
||||||
fn set_recovery_status(&self, status: RecoveryStatus) -> 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 {
|
pub trait GetHeader {
|
||||||
fn get_header(&self, key: &str) -> Option<String>;
|
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> {
|
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
|
||||||
let auth_messenger = Arc::new(AuthMessenger::new());
|
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"))]
|
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||||
set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?;
|
set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?;
|
||||||
@@ -187,7 +170,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
|||||||
|
|
||||||
async fn wait_for_auth(
|
async fn wait_for_auth(
|
||||||
&self,
|
&self,
|
||||||
auth_window: &AuthWindow,
|
auth_window: &WebviewWindow,
|
||||||
auth_messenger: Arc<AuthMessenger>,
|
auth_messenger: Arc<AuthMessenger>,
|
||||||
) -> anyhow::Result<SamlAuthData> {
|
) -> anyhow::Result<SamlAuthData> {
|
||||||
let mut recovery = Recovery::default();
|
let mut recovery = Recovery::default();
|
||||||
@@ -327,16 +310,13 @@ impl<'a> WebviewAuthenticator<'a> {
|
|||||||
|
|
||||||
async fn setup_auth_window(
|
async fn setup_auth_window(
|
||||||
&self,
|
&self,
|
||||||
auth_window: &AuthWindow,
|
auth_window: &WebviewWindow,
|
||||||
auth_messenger: Arc<AuthMessenger>,
|
auth_messenger: Arc<AuthMessenger>,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
info!("Setting up auth window...");
|
info!("Setting up auth window...");
|
||||||
|
|
||||||
if self.clean {
|
if self.clean {
|
||||||
info!("Clearing all browsing data...");
|
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()?;
|
auth_window.clear_all_browsing_data()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -381,7 +361,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
|||||||
Ok(())
|
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);
|
let visible = auth_window.is_visible().unwrap_or(false);
|
||||||
if visible {
|
if visible {
|
||||||
return;
|
return;
|
||||||
@@ -390,7 +370,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
|||||||
auth_messenger.schedule_raise_window(2);
|
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 {
|
if status != RecoveryStatus::Hidden {
|
||||||
self.raise_window(auth_window);
|
self.raise_window(auth_window);
|
||||||
}
|
}
|
||||||
@@ -417,7 +397,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
|||||||
|
|
||||||
fn load_restarted_sign_in(
|
fn load_restarted_sign_in(
|
||||||
&self,
|
&self,
|
||||||
auth_window: &AuthWindow,
|
auth_window: &WebviewWindow,
|
||||||
messenger: &Arc<AuthMessenger>,
|
messenger: &Arc<AuthMessenger>,
|
||||||
auth_request: String,
|
auth_request: String,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
@@ -435,7 +415,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn raise_window(&self, auth_window: &AuthWindow) {
|
fn raise_window(&self, auth_window: &WebviewWindow) {
|
||||||
let visible = auth_window.is_visible().unwrap_or(false);
|
let visible = auth_window.is_visible().unwrap_or(false);
|
||||||
if visible {
|
if visible {
|
||||||
return;
|
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]
|
[dependencies]
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
log.workspace = true
|
log.workspace = true
|
||||||
|
open = { version = "5", optional = true }
|
||||||
webbrowser = { version = "1", optional = true }
|
webbrowser = { version = "1", optional = true }
|
||||||
|
which = { workspace = true, optional = true }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = []
|
default = []
|
||||||
launcher = ["dep:open", "dep:webbrowser", "dep:which", "dep:winreg"]
|
launcher = ["dep:open", "dep:webbrowser", "dep:which"]
|
||||||
|
|
||||||
[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 }
|
|
||||||
@@ -1,11 +1,8 @@
|
|||||||
#[cfg(all(feature = "launcher", windows))]
|
|
||||||
#[path = "platform/windows.rs"]
|
|
||||||
mod platform;
|
|
||||||
#[cfg(all(feature = "launcher", target_os = "macos"))]
|
#[cfg(all(feature = "launcher", target_os = "macos"))]
|
||||||
#[path = "platform/macos.rs"]
|
#[path = "platform/macos.rs"]
|
||||||
mod platform;
|
mod platform;
|
||||||
|
|
||||||
#[cfg(all(feature = "launcher", unix, not(target_os = "macos")))]
|
#[cfg(all(feature = "launcher", not(target_os = "macos")))]
|
||||||
#[path = "platform/generic.rs"]
|
#[path = "platform/generic.rs"]
|
||||||
mod platform;
|
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 {
|
pub(crate) fn as_str(&self) -> &str {
|
||||||
match self {
|
match self {
|
||||||
Browser::Auto => "auto",
|
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 workspace_dir = Path::new(manifest_dir).ancestors().nth(2).unwrap();
|
||||||
let gpgui_dir = workspace_dir.parent().unwrap().join("gpgui");
|
let gpgui_dir = workspace_dir.parent().unwrap().join("gpgui");
|
||||||
|
|
||||||
let suffix = if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
let gp_service_binary = workspace_dir.join("target/debug/gpservice");
|
||||||
".exe"
|
let gp_client_binary = workspace_dir.join("target/debug/gpclient");
|
||||||
} else {
|
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");
|
||||||
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}"));
|
|
||||||
|
|
||||||
println!("cargo:rustc-env=GP_SERVICE_BINARY={}", gp_service_binary.display());
|
println!("cargo:rustc-env=GP_SERVICE_BINARY={}", gp_service_binary.display());
|
||||||
println!("cargo:rustc-env=GP_CLIENT_BINARY={}", gp_client_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> {
|
fn sibling_binary_for_executable(executable: &Path, binary_name: &str) -> Option<PathBuf> {
|
||||||
let executable = executable.canonicalize().ok()?;
|
let executable = executable.canonicalize().ok()?;
|
||||||
let bin_dir = executable.parent()?;
|
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) {
|
if is_file(&binary) {
|
||||||
return Some(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_LINUX: &str = "6.3.3-619";
|
||||||
pub const GP_CLIENT_VERSION_WINDOWS: &str = "6.3.3-650";
|
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_CLIENT_VERSION_MACOS: &str = "6.3.3-915";
|
||||||
|
pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer";
|
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer";
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
|
|||||||
@@ -1,3 +1,2 @@
|
|||||||
pub mod binary_paths;
|
pub mod binary_paths;
|
||||||
pub mod constants;
|
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]"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+9
-47
@@ -6,8 +6,9 @@ edition.workspace = true
|
|||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
gp-xml = { path = "../gp-xml" }
|
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
|
||||||
common = { path = "../common" }
|
common = { path = "../common" }
|
||||||
|
directories = { workspace = true, optional = true }
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
base64.workspace = true
|
base64.workspace = true
|
||||||
dns-lookup = { workspace = true, optional = true }
|
dns-lookup = { workspace = true, optional = true }
|
||||||
@@ -15,10 +16,8 @@ log.workspace = true
|
|||||||
reqwest.workspace = true
|
reqwest.workspace = true
|
||||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||||
rustls-pemfile = "2"
|
rustls-pemfile = "2"
|
||||||
rustls-platform-verifier = "0.7"
|
|
||||||
p12-keystore = "0.4.1"
|
p12-keystore = "0.4.1"
|
||||||
pkcs12 = { version = "=0.2.0-pre.0", default-features = false }
|
sec1 = { version = "0.8.1", default-features = false, features = ["der"] }
|
||||||
cms = { version = "=0.3.0-pre.1", default-features = false }
|
|
||||||
pem.workspace = true
|
pem.workspace = true
|
||||||
pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] }
|
pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] }
|
||||||
x509-cert = { version = "0.3", default-features = false }
|
x509-cert = { version = "0.3", default-features = false }
|
||||||
@@ -35,6 +34,7 @@ thiserror.workspace = true
|
|||||||
chacha20poly1305 = { version = "0.11", features = ["zeroize"] }
|
chacha20poly1305 = { version = "0.11", features = ["zeroize"] }
|
||||||
url.workspace = true
|
url.workspace = true
|
||||||
regex.workspace = true
|
regex.workspace = true
|
||||||
|
uzers = { workspace = true, optional = true }
|
||||||
serde_urlencoded.workspace = true
|
serde_urlencoded.workspace = true
|
||||||
md5.workspace = true
|
md5.workspace = true
|
||||||
sha2.workspace = true
|
sha2.workspace = true
|
||||||
@@ -43,13 +43,11 @@ chrono.workspace = true
|
|||||||
humantime.workspace = true
|
humantime.workspace = true
|
||||||
netdev = { workspace = true, optional = true }
|
netdev = { workspace = true, optional = true }
|
||||||
socket2 = { version = "0.6", features = ["all"], optional = true }
|
socket2 = { version = "0.6", features = ["all"], optional = true }
|
||||||
|
os_info = { version = "3", default-features = false, optional = true }
|
||||||
snow.workspace = true
|
snow.workspace = true
|
||||||
zeroize = { workspace = true, features = ["serde"] }
|
zeroize = { workspace = true, features = ["serde"] }
|
||||||
getrandom = "0.4"
|
getrandom = "0.4"
|
||||||
|
|
||||||
# Used only by the opt-in certificate interoperability tests.
|
|
||||||
openssl = { workspace = true, optional = true }
|
|
||||||
|
|
||||||
# Optional dependencies for features
|
# Optional dependencies for features
|
||||||
tauri = { workspace = true, optional = true }
|
tauri = { workspace = true, optional = true }
|
||||||
clap = { workspace = true, optional = true }
|
clap = { workspace = true, optional = true }
|
||||||
@@ -65,59 +63,23 @@ oslog = { version = "0.2", default-features = false, optional = true }
|
|||||||
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
|
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
|
||||||
gtk = { version = "0.18", optional = true }
|
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]
|
[target.'cfg(target_os="linux")'.dependencies]
|
||||||
libloading = { version = "0.9", optional = true }
|
libloading = { version = "0.9", optional = true }
|
||||||
|
|
||||||
[target.'cfg(target_os="macos")'.dependencies]
|
|
||||||
os_info = { version = "3", default-features = false, optional = true }
|
|
||||||
|
|
||||||
[target.'cfg(target_os="windows")'.dependencies]
|
|
||||||
os_info = { version = "3", default-features = false }
|
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
cc = "1"
|
cc = "1"
|
||||||
pkg-config = "0.3"
|
pkg-config = "0.3"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
openssl.workspace = true
|
||||||
libloading = "0.9"
|
libloading = "0.9"
|
||||||
proptest.workspace = true
|
proptest.workspace = true
|
||||||
tokio = { workspace = true, features = ["test-util"] }
|
tokio = { workspace = true, features = ["test-util"] }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["desktop"]
|
default = ["desktop"]
|
||||||
desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:uzers", "dep:netdev", "dep:whoami", "dep:dns-lookup", "dep:socket2", "dep:libloading"]
|
desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:uzers", "dep:netdev", "dep:os_info", "dep:whoami", "dep:dns-lookup", "dep:socket2", "dep:libloading"]
|
||||||
tauri = ["desktop", "dep:tauri", "dep:gtk", "dep:os_info"]
|
tauri = ["desktop", "dep:tauri", "dep:gtk"]
|
||||||
clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"]
|
clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"]
|
||||||
webview-auth = []
|
webview-auth = []
|
||||||
openssl-tests = ["dep:openssl"]
|
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"]
|
||||||
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"]
|
|
||||||
@@ -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,
|
UnixMac,
|
||||||
UnixRandom,
|
UnixRandom,
|
||||||
MacosIokit,
|
MacosIokit,
|
||||||
WindowsSmbios,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<AnchorSource> for u8 {
|
impl From<AnchorSource> for u8 {
|
||||||
@@ -19,7 +18,6 @@ impl From<AnchorSource> for u8 {
|
|||||||
AnchorSource::UnixMac => 1,
|
AnchorSource::UnixMac => 1,
|
||||||
AnchorSource::UnixRandom => 2,
|
AnchorSource::UnixRandom => 2,
|
||||||
AnchorSource::MacosIokit => 3,
|
AnchorSource::MacosIokit => 3,
|
||||||
AnchorSource::WindowsSmbios => 4,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -43,7 +41,6 @@ impl TryFrom<u8> for AnchorSource {
|
|||||||
1 => Ok(Self::UnixMac),
|
1 => Ok(Self::UnixMac),
|
||||||
2 => Ok(Self::UnixRandom),
|
2 => Ok(Self::UnixRandom),
|
||||||
3 => Ok(Self::MacosIokit),
|
3 => Ok(Self::MacosIokit),
|
||||||
4 => Ok(Self::WindowsSmbios),
|
|
||||||
value => Err(InvalidAnchorSource(value)),
|
value => Err(InvalidAnchorSource(value)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -68,7 +65,6 @@ impl DeviceAnchor {
|
|||||||
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
|
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
|
||||||
AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".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::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();
|
let mut input = domain.to_vec();
|
||||||
input.extend_from_slice(seed.as_ref());
|
input.extend_from_slice(seed.as_ref());
|
||||||
@@ -85,7 +81,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn preserves_existing_hardware_ids_for_all_sources() {
|
fn preserves_existing_hardware_ids_for_all_sources() {
|
||||||
let cases: [(AnchorSource, &[u8], &str); 4] = [
|
let cases: [(AnchorSource, &[u8], &str); 3] = [
|
||||||
(
|
(
|
||||||
AnchorSource::UnixMac,
|
AnchorSource::UnixMac,
|
||||||
&[0, 17, 34, 51, 68, 85],
|
&[0, 17, 34, 51, 68, 85],
|
||||||
@@ -101,11 +97,6 @@ mod tests {
|
|||||||
b"12345678-1234-5678-9abc-def012345678",
|
b"12345678-1234-5678-9abc-def012345678",
|
||||||
"K1KMtAwiOiXKQvQuRmTDKPA6-ZPF5QKUWZzmvRzeP34",
|
"K1KMtAwiOiXKQvQuRmTDKPA6-ZPF5QKUWZzmvRzeP34",
|
||||||
),
|
),
|
||||||
(
|
|
||||||
AnchorSource::WindowsSmbios,
|
|
||||||
b"12345678-1234-5678-9abc-def012345678",
|
|
||||||
"C843jG-lDX91Tab02VelrMJl_OmOji_pCtNWilwzW5s",
|
|
||||||
),
|
|
||||||
];
|
];
|
||||||
for (source, seed, expected) in cases {
|
for (source, seed, expected) in cases {
|
||||||
let anchor = DeviceAnchor::derive(source, seed);
|
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::UnixMac).unwrap(), "1");
|
||||||
assert_eq!(serde_json::to_string(&AnchorSource::UnixRandom).unwrap(), "2");
|
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::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!(
|
assert_eq!(
|
||||||
serde_json::from_str::<AnchorSource>("1").unwrap(),
|
serde_json::from_str::<AnchorSource>("1").unwrap(),
|
||||||
AnchorSource::UnixMac
|
AnchorSource::UnixMac
|
||||||
);
|
);
|
||||||
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
|
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());
|
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -22,23 +22,11 @@ pub enum ServerTlsErrorKind {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ServerTlsError {
|
impl ServerTlsError {
|
||||||
pub(crate) fn from_request(
|
pub(crate) fn from_request(server: &url::Url, error: &(dyn Error + 'static)) -> Option<Self> {
|
||||||
server: &url::Url,
|
Some(Self {
|
||||||
error: &(dyn Error + 'static),
|
|
||||||
has_client_identity: bool,
|
|
||||||
) -> Option<anyhow::Error> {
|
|
||||||
let kind = classify_with_identity(error, has_client_identity)?;
|
|
||||||
let error = anyhow::Error::new(Self {
|
|
||||||
server: server.origin().ascii_serialization(),
|
server: server.origin().ascii_serialization(),
|
||||||
kind,
|
kind: classify(error)?,
|
||||||
});
|
})
|
||||||
if has_client_identity && kind == ServerTlsErrorKind::ClientCertificateRequired {
|
|
||||||
Some(error.context(
|
|
||||||
"The VPN server could not use the configured client certificate. Check it with your VPN administrator",
|
|
||||||
))
|
|
||||||
} else {
|
|
||||||
Some(error)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,10 +60,6 @@ impl ServerTlsErrorKind {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
|
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
|
||||||
classify_with_identity(error, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bool) -> Option<ServerTlsErrorKind> {
|
|
||||||
let mut source = Some(error);
|
let mut source = Some(error);
|
||||||
while let Some(error) = source {
|
while let Some(error) = source {
|
||||||
if let Some(tls) = error.downcast_ref::<ServerTlsError>() {
|
if let Some(tls) = error.downcast_ref::<ServerTlsError>() {
|
||||||
@@ -87,14 +71,6 @@ fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bo
|
|||||||
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => {
|
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => {
|
||||||
ServerTlsErrorKind::ClientCertificateRequired
|
ServerTlsErrorKind::ClientCertificateRequired
|
||||||
}
|
}
|
||||||
rustls::Error::AlertReceived(
|
|
||||||
rustls::AlertDescription::BadCertificate
|
|
||||||
| rustls::AlertDescription::UnsupportedCertificate
|
|
||||||
| rustls::AlertDescription::CertificateRevoked
|
|
||||||
| rustls::AlertDescription::CertificateExpired
|
|
||||||
| rustls::AlertDescription::CertificateUnknown
|
|
||||||
| rustls::AlertDescription::UnknownCA,
|
|
||||||
) if has_client_identity => ServerTlsErrorKind::ClientCertificateRequired,
|
|
||||||
_ => ServerTlsErrorKind::Other,
|
_ => ServerTlsErrorKind::Other,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -109,7 +85,6 @@ fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bo
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
#[cfg(feature = "openssl-tests")]
|
|
||||||
use openssl::{
|
use openssl::{
|
||||||
asn1::Asn1Time,
|
asn1::Asn1Time,
|
||||||
hash::MessageDigest,
|
hash::MessageDigest,
|
||||||
@@ -148,45 +123,10 @@ mod tests {
|
|||||||
assert_eq!(classify(&std::io::Error::other("certificate verify failed")), None);
|
assert_eq!(classify(&std::io::Error::other("certificate verify failed")), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn configured_identity_peer_errors_have_actionable_copy_without_becoming_server_trust_failures() {
|
|
||||||
let server = url::Url::parse("https://vpn.example.com/private/login").unwrap();
|
|
||||||
for alert in [
|
|
||||||
rustls::AlertDescription::CertificateRequired,
|
|
||||||
rustls::AlertDescription::BadCertificate,
|
|
||||||
rustls::AlertDescription::UnknownCA,
|
|
||||||
] {
|
|
||||||
let error = rustls::Error::AlertReceived(alert);
|
|
||||||
let configured = ServerTlsError::from_request(&server, &error, true).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
ServerTlsErrorKind::from_error(&configured),
|
|
||||||
Some(ServerTlsErrorKind::ClientCertificateRequired)
|
|
||||||
);
|
|
||||||
let message = configured.to_string();
|
|
||||||
assert!(
|
|
||||||
message.contains("configured client certificate") && message.contains("VPN administrator"),
|
|
||||||
"{message}"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
!message.contains("password") && !message.contains("passphrase"),
|
|
||||||
"{message}"
|
|
||||||
);
|
|
||||||
assert!(!message.contains("/private/login"));
|
|
||||||
}
|
|
||||||
let trust_error = rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer);
|
|
||||||
let classified = ServerTlsError::from_request(&server, &trust_error, true).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
ServerTlsErrorKind::from_error(&classified),
|
|
||||||
Some(ServerTlsErrorKind::Certificate)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "openssl-tests")]
|
|
||||||
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
|
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
|
||||||
server_with_client_auth(tls, SslVerifyMode::NONE)
|
server_with_client_auth(tls, SslVerifyMode::NONE)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "openssl-tests")]
|
|
||||||
fn server_with_client_auth(tls: bool, verify: SslVerifyMode) -> (String, thread::JoinHandle<()>) {
|
fn server_with_client_auth(tls: bool, verify: SslVerifyMode) -> (String, thread::JoinHandle<()>) {
|
||||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||||
let mut name = X509NameBuilder::new().unwrap();
|
let mut name = X509NameBuilder::new().unwrap();
|
||||||
@@ -236,7 +176,6 @@ mod tests {
|
|||||||
(address, worker)
|
(address, worker)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "openssl-tests")]
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn prelogin_returns_typed_certificate_failure_with_only_the_server_origin() {
|
async fn prelogin_returns_typed_certificate_failure_with_only_the_server_origin() {
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -258,7 +197,6 @@ mod tests {
|
|||||||
assert_eq!(tls.server, address);
|
assert_eq!(tls.server, address);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "openssl-tests")]
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn certificate_bypass_allows_prelogin() {
|
async fn certificate_bypass_allows_prelogin() {
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -275,7 +213,6 @@ mod tests {
|
|||||||
assert!(matches!(result.unwrap(), crate::portal::Prelogin::Saml(_)));
|
assert!(matches!(result.unwrap(), crate::portal::Prelogin::Saml(_)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "openssl-tests")]
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() {
|
async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() {
|
||||||
let (address, worker) = server(false);
|
let (address, worker) = server(false);
|
||||||
@@ -289,8 +226,8 @@ mod tests {
|
|||||||
.await
|
.await
|
||||||
.unwrap_err();
|
.unwrap_err();
|
||||||
worker.join().unwrap();
|
worker.join().unwrap();
|
||||||
let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error, false).unwrap();
|
let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error).unwrap();
|
||||||
assert_eq!(ServerTlsErrorKind::from_error(&tls), Some(ServerTlsErrorKind::Other));
|
assert_eq!(tls.kind, ServerTlsErrorKind::Other);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -309,7 +246,7 @@ mod tests {
|
|||||||
assert_eq!(classify(&error), None);
|
assert_eq!(classify(&error), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(feature = "desktop", unix))]
|
#[cfg(feature = "desktop")]
|
||||||
#[test]
|
#[test]
|
||||||
fn rendering_recovery_retains_client_certificate_requirement() {
|
fn rendering_recovery_retains_client_certificate_requirement() {
|
||||||
use crate::process::rendering_recovery::{RecoveryState, RenderingCrash};
|
use crate::process::rendering_recovery::{RecoveryState, RenderingCrash};
|
||||||
@@ -336,7 +273,6 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "openssl-tests")]
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn required_client_certificate_is_not_bypassed_by_ignoring_server_trust() {
|
async fn required_client_certificate_is_not_bypassed_by_ignoring_server_trust() {
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -378,40 +314,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "openssl-tests")]
|
|
||||||
#[tokio::test]
|
|
||||||
async fn prelogin_explains_peer_rejection_of_an_already_configured_identity() {
|
|
||||||
use crate::{
|
|
||||||
gp_params::GpParams,
|
|
||||||
os_profile::{ClientOs, OsProfile},
|
|
||||||
portal::{PreloginOptions, prelogin},
|
|
||||||
utils::request::ClientIdentity,
|
|
||||||
};
|
|
||||||
let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/files/client-identity");
|
|
||||||
let identity = ClientIdentity::load(
|
|
||||||
fixtures.join("rsa-critical-extension.pem").to_str().unwrap(),
|
|
||||||
Some(fixtures.join("rsa-pkcs8.pem").to_str().unwrap()),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()))
|
|
||||||
.client_identity(Some(identity))
|
|
||||||
.ignore_tls_errors(true)
|
|
||||||
.build();
|
|
||||||
let (address, worker) = server_with_client_auth(true, SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
|
|
||||||
let error = prelogin(&address, ¶ms, PreloginOptions::default())
|
|
||||||
.await
|
|
||||||
.unwrap_err();
|
|
||||||
worker.join().unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
ServerTlsErrorKind::from_error(&error),
|
|
||||||
Some(ServerTlsErrorKind::ClientCertificateRequired)
|
|
||||||
);
|
|
||||||
assert!(error.to_string().contains("configured client certificate"), "{error:#}");
|
|
||||||
assert!(!error.to_string().contains("passphrase"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "openssl-tests")]
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
|
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -444,7 +346,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "openssl-tests")]
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn imported_identity_formats_complete_mutual_tls_prelogin() {
|
async fn imported_identity_formats_complete_mutual_tls_prelogin() {
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -510,10 +411,10 @@ mod tests {
|
|||||||
.await
|
.await
|
||||||
.unwrap_err();
|
.unwrap_err();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
ServerTlsErrorKind::from_error(
|
ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error)
|
||||||
&ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error, false).unwrap()
|
.unwrap()
|
||||||
),
|
.kind,
|
||||||
Some(ServerTlsErrorKind::Certificate)
|
ServerTlsErrorKind::Certificate
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ use crate::{
|
|||||||
gp_params::GpParams,
|
gp_params::GpParams,
|
||||||
params::gateway_login::{self, GatewayLoginInput},
|
params::gateway_login::{self, GatewayLoginInput},
|
||||||
session::GatewayAuthentication,
|
session::GatewayAuthentication,
|
||||||
utils::{normalize_server, parse_gp_response, redact::redact_uri, remove_url_scheme, xml::ElementExt},
|
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub enum GatewayLogin {
|
pub enum GatewayLogin {
|
||||||
@@ -181,14 +181,14 @@ async fn receive_gateway_login(
|
|||||||
log_gateway_login_context(context, client_ip, gp_params);
|
log_gateway_login_context(context, client_ip, gp_params);
|
||||||
|
|
||||||
let res = client
|
let res = client
|
||||||
.post(&login_url)
|
.post(login_url)
|
||||||
.form(&request_params.body)
|
.form(&request_params.body)
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
warn!("Network error: {:?}", e);
|
warn!("Network error: {:?}", e);
|
||||||
match crate::error::ServerTlsError::from_request(origin, &e, gp_params.has_client_identity()) {
|
match crate::error::ServerTlsError::from_request(origin, &e) {
|
||||||
Some(tls) => tls,
|
Some(tls) => anyhow::anyhow!(tls),
|
||||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||||
}
|
}
|
||||||
})?;
|
})?;
|
||||||
@@ -200,33 +200,14 @@ async fn receive_gateway_login(
|
|||||||
.map(<[u8]>::to_vec);
|
.map(<[u8]>::to_vec);
|
||||||
let endpoint = res.remote_addr();
|
let endpoint = res.remote_addr();
|
||||||
let url = res.url().clone();
|
let url = res.url().clone();
|
||||||
let http_version = res.version();
|
let res = parse_gp_response(res).await.map_err(|err| {
|
||||||
let content_type = res.headers().get(reqwest::header::CONTENT_TYPE).cloned();
|
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err) {
|
||||||
let res = parse_gp_response(res).await.map_err(|mut err| {
|
return anyhow::anyhow!(tls);
|
||||||
// Redirect paths and query strings can contain authentication tokens. Log
|
|
||||||
// only the redacted origin and whether the response is from the login path.
|
|
||||||
warn!(
|
|
||||||
"Gateway login response failed: status={}, reason={}, http={:?}, origin={}, port={:?}, redirected={}, login_endpoint={}, content_type={:?}, client_certificate={}, ignore_tls_errors={}",
|
|
||||||
err.status,
|
|
||||||
err.reason,
|
|
||||||
http_version,
|
|
||||||
redact_uri(&url.origin().ascii_serialization()),
|
|
||||||
url.port_or_known_default(),
|
|
||||||
url.as_str() != login_url,
|
|
||||||
url.path() == "/ssl-vpn/login.esp",
|
|
||||||
content_type,
|
|
||||||
gp_params.has_client_identity(),
|
|
||||||
gp_params.ignore_tls_errors(),
|
|
||||||
);
|
|
||||||
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() {
|
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
|
||||||
return anyhow::anyhow!(crate::error::AuthenticationRejected);
|
return anyhow::anyhow!(crate::error::AuthenticationRejected);
|
||||||
}
|
}
|
||||||
|
warn!("Gateway login response failed: {}", err.reason);
|
||||||
anyhow::anyhow!("Gateway login error: {}", err.reason)
|
anyhow::anyhow!("Gateway login error: {}", err.reason)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
@@ -448,85 +429,6 @@ mod tests {
|
|||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn failed_login_logs_http_context_without_credentials_or_redirect_tokens() {
|
|
||||||
use std::cell::RefCell;
|
|
||||||
|
|
||||||
thread_local! {
|
|
||||||
static MESSAGES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
|
|
||||||
}
|
|
||||||
struct Logger;
|
|
||||||
impl log::Log for Logger {
|
|
||||||
fn enabled(&self, _: &log::Metadata<'_>) -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
fn log(&self, record: &log::Record<'_>) {
|
|
||||||
let message = record.args().to_string();
|
|
||||||
if message.starts_with("Gateway login response failed:") {
|
|
||||||
MESSAGES.with_borrow_mut(|messages| messages.push(message));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn flush(&self) {}
|
|
||||||
}
|
|
||||||
log::set_logger(&Logger).unwrap();
|
|
||||||
log::set_max_level(log::LevelFilter::Warn);
|
|
||||||
|
|
||||||
for (status, reason, redirected) in [
|
|
||||||
(403, None, false),
|
|
||||||
(502, None, true),
|
|
||||||
(401, Some("access denied"), false),
|
|
||||||
] {
|
|
||||||
let body = "<html>response-body-secret</html>";
|
|
||||||
let mut responses = Vec::new();
|
|
||||||
if redirected {
|
|
||||||
responses.push(
|
|
||||||
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /path-secret?token=query-secret\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let reason_header = reason
|
|
||||||
.map(|reason| format!("x-private-pan-globalprotect: {reason}\r\n"))
|
|
||||||
.unwrap_or_default();
|
|
||||||
responses.push(format!(
|
|
||||||
"HTTP/1.1 {status} Error\r\nContent-Type: text/html\r\nSet-Cookie: cookie-secret\r\n{reason_header}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
|
||||||
body.len()
|
|
||||||
));
|
|
||||||
let (_, origin, server) = crate::session::transport::tests::login_gateway(responses).await;
|
|
||||||
let mut client = GatewayLoginClient::new(origin.as_str(), test_params()).unwrap();
|
|
||||||
let credential = crate::credential::PasswordCredential::new("username-secret", "password-secret").into();
|
|
||||||
let error = client
|
|
||||||
.login(&credential, None, &CancellationToken::new())
|
|
||||||
.await
|
|
||||||
.err()
|
|
||||||
.unwrap();
|
|
||||||
server.await.unwrap();
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
error.to_string(),
|
|
||||||
format!("Gateway login error: {}", reason.unwrap_or("<none>"))
|
|
||||||
);
|
|
||||||
let messages = MESSAGES.with_borrow_mut(std::mem::take);
|
|
||||||
assert_eq!(messages.len(), 1);
|
|
||||||
let message = &messages[0];
|
|
||||||
for expected in [
|
|
||||||
format!("status={status}"),
|
|
||||||
format!("reason={}", reason.unwrap_or("<none>")),
|
|
||||||
format!("port={:?}", origin.port()),
|
|
||||||
format!("redirected={redirected}"),
|
|
||||||
format!("login_endpoint={}", !redirected),
|
|
||||||
"http=HTTP/1.1".into(),
|
|
||||||
"content_type=Some(\"text/html\")".into(),
|
|
||||||
"client_certificate=false".into(),
|
|
||||||
"ignore_tls_errors=false".into(),
|
|
||||||
] {
|
|
||||||
assert!(message.contains(&expected), "missing {expected}: {message}");
|
|
||||||
}
|
|
||||||
assert!(!message.contains("secret"), "sensitive data in diagnostic: {message}");
|
|
||||||
assert!(!message.contains("127.0.0.1"), "unredacted origin: {message}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn gateway_login_cancels_stalled_headers_and_body() {
|
async fn gateway_login_cancels_stalled_headers_and_body() {
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
|||||||
@@ -111,7 +111,7 @@ pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
|
|||||||
let response = client.post(&url).form(&form).send().await?;
|
let response = client.post(&url).form(&form).send().await?;
|
||||||
let response = parse_gp_response(response).await?;
|
let response = parse_gp_response(response).await?;
|
||||||
let root = Element::parse(response.as_bytes())?;
|
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);
|
info!("Extend-session gateway response status: {}", status);
|
||||||
|
|
||||||
@@ -151,11 +151,11 @@ fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result<HashMap<Str
|
|||||||
Ok(form)
|
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") {
|
match root.attr("status") {
|
||||||
Some(status) => Ok(status.to_string()),
|
Some(status) => Ok(status.to_string()),
|
||||||
None => {
|
None => {
|
||||||
warn!("Extend-session response is missing status");
|
warn!("Malformed extend-session response body: {}", response.trim());
|
||||||
bail!("Malformed extend session response")
|
bail!("Malformed extend session response")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -231,7 +231,10 @@ mod tests {
|
|||||||
fn parses_extend_session_status_attribute() {
|
fn parses_extend_session_status_attribute() {
|
||||||
let root = Element::parse(r#"<response status="success"></response>"#.as_bytes()).unwrap();
|
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]
|
#[test]
|
||||||
@@ -239,7 +242,9 @@ mod tests {
|
|||||||
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
|
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
|
||||||
|
|
||||||
assert_eq!(
|
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"
|
"Malformed extend session response"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use zeroize::Zeroize;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
os_profile::{ClientOs, HostIdentity, OsProfile},
|
os_profile::{ClientOs, HostIdentity, OsProfile},
|
||||||
utils::request::ClientIdentity,
|
utils::request::{ClientIdentity, create_identity},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
|
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
|
||||||
@@ -160,21 +160,21 @@ impl GpParams {
|
|||||||
self.prepared_identity.as_ref()
|
self.prepared_identity.as_ref()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn has_client_identity(&self) -> bool {
|
|
||||||
self.prepared_identity.is_some() || self.certificate.is_some()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
|
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
|
||||||
let builder = if let Some(identity) = &self.prepared_identity {
|
let mut builder = crate::utils::request::client_builder()
|
||||||
identity.client_builder(self.ignore_tls_errors)?
|
.tls_info(true)
|
||||||
|
.danger_accept_invalid_certs(self.ignore_tls_errors)
|
||||||
|
.user_agent(self.user_agent());
|
||||||
|
if let Some(identity) = &self.prepared_identity {
|
||||||
|
builder = builder.identity(identity.request_identity());
|
||||||
} else if let Some(cert) = self.certificate.as_deref() {
|
} else if let Some(cert) = self.certificate.as_deref() {
|
||||||
info!("Using client certificate authentication...");
|
info!("Using client certificate authentication...");
|
||||||
ClientIdentity::load(cert, self.sslkey.as_deref(), self.key_password.as_deref())?
|
builder = builder.identity(create_identity(
|
||||||
.client_builder(self.ignore_tls_errors)?
|
cert,
|
||||||
} else {
|
self.sslkey.as_deref(),
|
||||||
crate::utils::request::client_builder().danger_accept_invalid_certs(self.ignore_tls_errors)
|
self.key_password.as_deref(),
|
||||||
};
|
)?);
|
||||||
let builder = builder.tls_info(true).user_agent(self.user_agent());
|
}
|
||||||
Ok(builder)
|
Ok(builder)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-40
@@ -70,17 +70,17 @@ impl GuiVariant {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
#[cfg(target_os = "linux")]
|
||||||
fn preference_path(name: &str) -> anyhow::Result<PathBuf> {
|
fn preference_path() -> anyhow::Result<PathBuf> {
|
||||||
let dirs = directories::ProjectDirs::from("com.yuezk", "GlobalProtect-openconnect", "gpclient")
|
let dirs = directories::ProjectDirs::from("com.yuezk", "GlobalProtect-openconnect", "gpclient")
|
||||||
.ok_or_else(|| anyhow::anyhow!("Failed to locate GUI preference directory"))?;
|
.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> {
|
pub fn preferred() -> anyhow::Result<GuiVariant> {
|
||||||
#[cfg(target_os = "linux")]
|
#[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() {
|
Ok(value) => match value.trim() {
|
||||||
"gpgui" => Ok(GuiVariant::Tauri),
|
"gpgui" => Ok(GuiVariant::Tauri),
|
||||||
"gpgui-nsh" => Ok(GuiVariant::Nsh),
|
"gpgui-nsh" => Ok(GuiVariant::Nsh),
|
||||||
@@ -96,46 +96,12 @@ pub fn preferred() -> anyhow::Result<GuiVariant> {
|
|||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
pub fn save_preference(variant: GuiVariant) -> anyhow::Result<()> {
|
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;
|
use std::io::Write;
|
||||||
let path = preference_path(name)?;
|
let path = preference_path()?;
|
||||||
let directory = path.parent().unwrap();
|
let directory = path.parent().unwrap();
|
||||||
std::fs::create_dir_all(directory)?;
|
std::fs::create_dir_all(directory)?;
|
||||||
let mut file = tempfile::NamedTempFile::new_in(directory)?;
|
let mut file = tempfile::NamedTempFile::new_in(directory)?;
|
||||||
writeln!(file, "{value}")?;
|
writeln!(file, "{}", variant.binary_name())?;
|
||||||
file.persist(path)?;
|
file.persist(path)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,27 +45,3 @@ mod tests {
|
|||||||
assert_eq!(serde_json::from_value::<HipSource>(json).unwrap(), source);
|
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")]
|
#[cfg(feature = "desktop")]
|
||||||
pub mod script_tun;
|
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>;
|
type BoxedLogger = Box<dyn Log + Send + Sync>;
|
||||||
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = OnceLock::new();
|
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) {
|
pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat) {
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
if log_format == LogFormat::Text && macos_unified_log_enabled() {
|
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(),
|
Some(identity) => identity.clone(),
|
||||||
None => collect_with_host_id_and_control(host_id_override, control)?,
|
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();
|
let runtime_os = runtime_client_os();
|
||||||
// Preserve the old behavior: only probe the native version when reporting it.
|
// Preserve the old behavior: only probe the native version when reporting it.
|
||||||
let (os_version, software_version) = if builder.client_os == runtime_os {
|
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))
|
(defaults::os_version(runtime_os), defaults::software_version(runtime_os))
|
||||||
};
|
};
|
||||||
control.check()?;
|
control.check()?;
|
||||||
// The builder may carry cached hardware identity; use the resolved profile identity.
|
Ok(builder.build(HostSnapshot {
|
||||||
Ok(builder.host_identity(identity.clone()).build(HostSnapshot {
|
|
||||||
runtime_os,
|
runtime_os,
|
||||||
identity,
|
identity,
|
||||||
os_version,
|
os_version,
|
||||||
|
|||||||
@@ -137,24 +137,14 @@ fn assert_mac(value: &str, separator: char) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn builder_preserves_supplied_hardware_fields() {
|
fn builder_delegates_default_identity_to_host_identity() {
|
||||||
let expected = collect_identity();
|
let expected = collect_identity();
|
||||||
let profile = collect_profile(
|
let profile = collect_profile(
|
||||||
OsProfileBuilder::new(runtime_client_os()).host_identity(expected.clone()),
|
OsProfileBuilder::new(runtime_client_os()).host_identity(expected.clone()),
|
||||||
None,
|
None,
|
||||||
);
|
);
|
||||||
|
|
||||||
assert!(
|
assert_eq!(profile.host_identity(), &expected);
|
||||||
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());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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();
|
let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Linux), None, &expired).unwrap_err();
|
||||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
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 std::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 super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id};
|
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> {
|
fn collect_windows_serial_number() -> Option<String> {
|
||||||
let output = Command::new("wmic")
|
let output = Command::new("wmic")
|
||||||
.creation_flags(CREATE_NO_WINDOW)
|
|
||||||
.args(["bios", "get", "serialnumber"])
|
.args(["bios", "get", "serialnumber"])
|
||||||
.output()
|
.output()
|
||||||
.ok()?;
|
.ok()?;
|
||||||
@@ -54,15 +50,11 @@ fn collect_windows_serial_number() -> Option<String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn windows_machine_seed() -> 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> {
|
fn collect_windows_csproduct_uuid() -> Option<String> {
|
||||||
let output = Command::new("wmic")
|
let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?;
|
||||||
.creation_flags(CREATE_NO_WINDOW)
|
|
||||||
.args(["csproduct", "get", "uuid"])
|
|
||||||
.output()
|
|
||||||
.ok()?;
|
|
||||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||||
|
|
||||||
stdout
|
stdout
|
||||||
@@ -73,63 +65,24 @@ fn collect_windows_csproduct_uuid() -> Option<String> {
|
|||||||
.next()
|
.next()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Native Windows uses the OS installation ID and physical NetBIOS name.
|
fn collect_windows_machine_guid() -> Option<String> {
|
||||||
// Keep the hardware identity used to seed other OS profiles unchanged.
|
let output = Command::new("reg")
|
||||||
pub(super) fn native_profile_identity(
|
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
|
||||||
identity: super::HostIdentity,
|
.output()
|
||||||
host_id_override: Option<&str>,
|
.ok()?;
|
||||||
) -> io::Result<super::HostIdentity> {
|
if !output.status.success() {
|
||||||
let host_id = match host_id_override.filter(|id| !id.trim().is_empty()) {
|
return None;
|
||||||
Some(id) => id.to_owned(),
|
}
|
||||||
None => collect_windows_machine_guid()?,
|
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||||
};
|
|
||||||
Ok(super::HostIdentity::from_parts(
|
stdout.lines().find_map(|line| {
|
||||||
collect_windows_computer_name()?,
|
let mut parts = line.split_whitespace();
|
||||||
host_id,
|
if parts.next()? != "MachineGuid" {
|
||||||
identity.serialno().into(),
|
return None;
|
||||||
identity.mac_addr().into(),
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn collect_windows_computer_name() -> io::Result<String> {
|
parts.last().map(str::to_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))
|
|
||||||
}
|
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RuntimeNativeHostIdentity {
|
impl RuntimeNativeHostIdentity {
|
||||||
|
|||||||
@@ -124,7 +124,8 @@ impl OsProfile {
|
|||||||
self.runtime_os == self.client_os
|
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 {
|
pub fn software_version(&self) -> &str {
|
||||||
&self.software_version
|
&self.software_version
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,14 +18,14 @@ fn negotiated_os_version_is_used_in_profile_and_user_agent() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn csc_support_defaults_match_platform_profiles() {
|
fn csc_support_defaults_match_official_profiles() {
|
||||||
assert!(!ClientOs::Linux.default_csc_support());
|
assert!(!ClientOs::Linux.default_csc_support());
|
||||||
assert!(ClientOs::Mac.default_csc_support());
|
assert!(ClientOs::Mac.default_csc_support());
|
||||||
assert!(ClientOs::Windows.default_csc_support());
|
assert!(ClientOs::Windows.default_csc_support());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn prelogin_param_location_matches_platform_profiles() {
|
fn prelogin_param_location_matches_official_profiles() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
OsProfileBuilder::new(ClientOs::Linux)
|
OsProfileBuilder::new(ClientOs::Linux)
|
||||||
.build(test_snapshot())
|
.build(test_snapshot())
|
||||||
@@ -91,7 +91,7 @@ fn embedded_gateway_default_browser_is_zero_for_all() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn external_default_browser_values_match_platform_profiles() {
|
fn external_default_browser_values_match_official_profiles() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
OsProfileBuilder::new(ClientOs::Linux)
|
OsProfileBuilder::new(ClientOs::Linux)
|
||||||
.build(test_snapshot())
|
.build(test_snapshot())
|
||||||
@@ -132,7 +132,7 @@ fn external_default_browser_values_match_platform_profiles() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn saml_password_matches_platform_profiles() {
|
fn saml_password_matches_official_profiles() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
OsProfileBuilder::new(ClientOs::Linux)
|
OsProfileBuilder::new(ClientOs::Linux)
|
||||||
.build(test_snapshot())
|
.build(test_snapshot())
|
||||||
@@ -173,7 +173,7 @@ fn gateway_server_uses_resolved_ipv4_for_all() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn kerberos_support_in_query_matches_platform_profiles() {
|
fn kerberos_support_in_query_matches_official_profiles() {
|
||||||
assert!(
|
assert!(
|
||||||
!OsProfileBuilder::new(ClientOs::Linux)
|
!OsProfileBuilder::new(ClientOs::Linux)
|
||||||
.build(test_snapshot())
|
.build(test_snapshot())
|
||||||
@@ -192,7 +192,7 @@ fn kerberos_support_in_query_matches_platform_profiles() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn os_vendor_matches_platform_profiles() {
|
fn os_vendor_matches_official_profiles() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
OsProfileBuilder::new(ClientOs::Linux)
|
OsProfileBuilder::new(ClientOs::Linux)
|
||||||
.build(test_snapshot())
|
.build(test_snapshot())
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use log::{info, warn};
|
use log::{debug, info, warn};
|
||||||
use reqwest::{Client, StatusCode};
|
use reqwest::{Client, StatusCode};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use specta::Type;
|
use specta::Type;
|
||||||
@@ -201,18 +201,15 @@ pub async fn retrieve_config(
|
|||||||
result = async {
|
result = async {
|
||||||
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
||||||
warn!("Network error: {:?}", e);
|
warn!("Network error: {:?}", e);
|
||||||
match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
|
match ServerTlsError::from_request(&server_url, &e) {
|
||||||
Some(tls) => tls,
|
Some(tls) => anyhow::anyhow!(tls),
|
||||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||||
}
|
}
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
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()) {
|
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) {
|
||||||
return Err(tls);
|
return Err(anyhow::anyhow!(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() {
|
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
|
||||||
return Err(anyhow::anyhow!(crate::error::AuthenticationRejected));
|
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()))
|
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()))?;
|
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||||
|
|
||||||
if csc::is_config_criteria(&root) {
|
if csc::is_config_criteria(&root) {
|
||||||
@@ -249,6 +247,7 @@ pub async fn retrieve_config(
|
|||||||
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
|
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
|
||||||
result = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params) => result?,
|
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()))?;
|
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;
|
return parse_portal_policy(&server, cred, root, cancellation).await;
|
||||||
}
|
}
|
||||||
@@ -275,18 +274,15 @@ async fn retrieve_csc_config(
|
|||||||
|
|
||||||
let res = client.post(&url).form(¶ms).send().await.map_err(|e| {
|
let res = client.post(&url).form(¶ms).send().await.map_err(|e| {
|
||||||
warn!("Network error: {:?}", e);
|
warn!("Network error: {:?}", e);
|
||||||
match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
|
match ServerTlsError::from_request(&server_url, &e) {
|
||||||
Some(tls) => tls,
|
Some(tls) => anyhow::anyhow!(tls),
|
||||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||||
}
|
}
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
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()) {
|
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) {
|
||||||
return Err(tls);
|
return Err(anyhow::anyhow!(tls));
|
||||||
}
|
|
||||||
if let Some(error) = err.take_body_read_error() {
|
|
||||||
return Err(PortalError::NetworkError(error).into());
|
|
||||||
}
|
}
|
||||||
if err.status == StatusCode::NOT_FOUND {
|
if err.status == StatusCode::NOT_FOUND {
|
||||||
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
|
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use anyhow::{anyhow, bail};
|
use anyhow::{anyhow, bail};
|
||||||
use log::{info, warn};
|
use log::{debug, info, warn};
|
||||||
use reqwest::{Client, StatusCode};
|
use reqwest::{Client, StatusCode};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use specta::Type;
|
use specta::Type;
|
||||||
@@ -152,15 +152,15 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
|
|||||||
|
|
||||||
let res = request.send().await.map_err(|e| {
|
let res = request.send().await.map_err(|e| {
|
||||||
warn!("Network error: {:?}", e);
|
warn!("Network error: {:?}", e);
|
||||||
match crate::error::ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
|
match crate::error::ServerTlsError::from_request(&server_url, &e) {
|
||||||
Some(error) => error,
|
Some(error) => anyhow!(error),
|
||||||
None => anyhow!(PortalError::NetworkError(e)),
|
None => anyhow!(PortalError::NetworkError(e)),
|
||||||
}
|
}
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let res_xml = parse_gp_response(res).await.or_else(|err| {
|
let res_xml = parse_gp_response(res).await.or_else(|err| {
|
||||||
if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
|
if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err) {
|
||||||
return Err(tls);
|
return Err(anyhow!(tls));
|
||||||
}
|
}
|
||||||
if err.status == StatusCode::NOT_FOUND {
|
if err.status == StatusCode::NOT_FOUND {
|
||||||
bail!(PortalError::PreloginError("Prelogin endpoint not found".to_string()))
|
bail!(PortalError::PreloginError("Prelogin endpoint not found".to_string()))
|
||||||
@@ -174,8 +174,10 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
|
|||||||
Err(anyhow!(PortalError::PreloginError(err.reason)))
|
Err(anyhow!(PortalError::PreloginError(err.reason)))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
debug!("Prelogin response XML: {}", res_xml);
|
||||||
|
|
||||||
let prelogin = parse_prelogin_response(&res_xml, is_gateway).map_err(|err| {
|
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())
|
PortalError::PreloginError(err.to_string())
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
|||||||
@@ -17,17 +17,10 @@ use super::{
|
|||||||
command_traits::CommandExt,
|
command_traits::CommandExt,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::rendering_recovery::{
|
use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_crash_exit};
|
||||||
AUTH_STDERR_PREFIX, GbmBufferFailure, RenderingCrash, StderrDiagnostic, allows_shared_memory_override, eligible,
|
|
||||||
is_crash_exit, is_gbm_diagnostic,
|
|
||||||
};
|
|
||||||
|
|
||||||
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
|
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> {
|
pub struct SamlAuthLauncher<'a> {
|
||||||
cancellation: CancellationToken,
|
cancellation: CancellationToken,
|
||||||
server: &'a str,
|
server: &'a str,
|
||||||
@@ -56,7 +49,6 @@ pub struct SamlAuthLauncher<'a> {
|
|||||||
verbose: Option<&'a str>,
|
verbose: Option<&'a str>,
|
||||||
log_format: LogFormat,
|
log_format: LogFormat,
|
||||||
dmabuf_disabled: bool,
|
dmabuf_disabled: bool,
|
||||||
desktop_compatibility_graphics: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> SamlAuthLauncher<'a> {
|
impl<'a> SamlAuthLauncher<'a> {
|
||||||
@@ -89,15 +81,9 @@ impl<'a> SamlAuthLauncher<'a> {
|
|||||||
verbose: None,
|
verbose: None,
|
||||||
log_format: LogFormat::Text,
|
log_format: LogFormat::Text,
|
||||||
dmabuf_disabled: false,
|
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 {
|
pub fn dmabuf_disabled(mut self, disabled: bool) -> Self {
|
||||||
self.dmabuf_disabled = disabled;
|
self.dmabuf_disabled = disabled;
|
||||||
self
|
self
|
||||||
@@ -211,8 +197,6 @@ impl<'a> SamlAuthLauncher<'a> {
|
|||||||
/// argument that never gets appended.
|
/// argument that never gets appended.
|
||||||
fn build_command(&self, program: &Path) -> Command {
|
fn build_command(&self, program: &Path) -> Command {
|
||||||
let mut auth_cmd = Command::new(program);
|
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);
|
auth_cmd.arg(self.server);
|
||||||
|
|
||||||
if self.gateway {
|
if self.gateway {
|
||||||
@@ -252,7 +236,7 @@ impl<'a> SamlAuthLauncher<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "webview-auth")]
|
#[cfg(feature = "webview-auth")]
|
||||||
if self.browser.is_none() {
|
{
|
||||||
if self.hidpi {
|
if self.hidpi {
|
||||||
auth_cmd.arg("--hidpi");
|
auth_cmd.arg("--hidpi");
|
||||||
}
|
}
|
||||||
@@ -308,34 +292,15 @@ impl<'a> SamlAuthLauncher<'a> {
|
|||||||
if embedded && bundled && self.dmabuf_disabled {
|
if embedded && bundled && self.dmabuf_disabled {
|
||||||
command.env("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
|
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 stdin = auth_stdin(self.browser);
|
||||||
let cancellation = self.cancellation.clone();
|
let cancellation = self.cancellation.clone();
|
||||||
let output = tokio::task::spawn_blocking(move || {
|
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 = || {
|
let check = || {
|
||||||
if cancellation.is_cancelled() {
|
if cancellation.is_cancelled() {
|
||||||
Err(std::io::Error::new(
|
Err(std::io::Error::new(
|
||||||
std::io::ErrorKind::Interrupted,
|
std::io::ErrorKind::Interrupted,
|
||||||
"Authentication cancelled",
|
"Authentication cancelled",
|
||||||
))
|
))
|
||||||
} else if gbm_failed.get() {
|
|
||||||
Err(std::io::Error::other(GbmBufferFailure))
|
|
||||||
} else {
|
} else {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -345,31 +310,19 @@ impl<'a> SamlAuthLauncher<'a> {
|
|||||||
command,
|
command,
|
||||||
&check,
|
&check,
|
||||||
Some(MAX_AUTH_RESULT_BYTES),
|
Some(MAX_AUTH_RESULT_BYTES),
|
||||||
&mut |bytes| {
|
&mut |bytes| diagnostic.push(bytes),
|
||||||
diagnostic.push(bytes);
|
&mut std::io::stderr(),
|
||||||
gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(can_recover));
|
|
||||||
},
|
|
||||||
&mut stderr,
|
|
||||||
stdin,
|
stdin,
|
||||||
);
|
)?;
|
||||||
std::io::Write::flush(&mut stderr)?;
|
Ok::<_, std::io::Error>((output.output, diagnostic.matched()))
|
||||||
if gbm_failed.get() && !cancellation.is_cancelled() {
|
|
||||||
return Err(GbmBufferFailure.into());
|
|
||||||
}
|
|
||||||
let output = output?;
|
|
||||||
Ok::<_, anyhow::Error>((output.output, diagnostic.matched()))
|
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
let (output, rendering_diagnostic) = match output {
|
let (output, rendering_diagnostic) = match output {
|
||||||
Ok(output) => output,
|
Ok(output) => output,
|
||||||
Err(error)
|
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
|
||||||
if error
|
|
||||||
.downcast_ref::<std::io::Error>()
|
|
||||||
.is_some_and(|error| error.kind() == std::io::ErrorKind::Interrupted) =>
|
|
||||||
{
|
|
||||||
return Err(crate::auth::AuthenticationCancelled.into());
|
return Err(crate::auth::AuthenticationCancelled.into());
|
||||||
}
|
}
|
||||||
Err(error) => return Err(error),
|
Err(error) => return Err(error.into()),
|
||||||
};
|
};
|
||||||
|
|
||||||
if self.cancellation.is_cancelled() {
|
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.
|
/// `gpauth --browser manual` reads the pasted `globalprotectcallback:` data from the user's terminal.
|
||||||
fn auth_stdin(browser: Option<&str>) -> ChildInput<'static> {
|
fn auth_stdin(browser: Option<&str>) -> ChildInput<'static> {
|
||||||
match browser {
|
match browser {
|
||||||
@@ -433,14 +366,11 @@ fn decode_auth_output(output: std::process::Output, rendering_failure: bool) ->
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::os_profile::{ClientOs, OsProfileBuilder};
|
use crate::os_profile::{ClientOs, OsProfileBuilder};
|
||||||
#[cfg(unix)]
|
|
||||||
use std::os::unix::process::ExitStatusExt;
|
|
||||||
#[cfg(windows)]
|
|
||||||
use std::os::windows::process::ExitStatusExt;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn server_tls_result_survives_process_decoding_as_a_typed_error() {
|
fn server_tls_result_survives_process_decoding_as_a_typed_error() {
|
||||||
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
||||||
|
use std::os::unix::process::ExitStatusExt;
|
||||||
let output = std::process::Output {
|
let output = std::process::Output {
|
||||||
status: std::process::ExitStatus::from_raw(0),
|
status: std::process::ExitStatus::from_raw(0),
|
||||||
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com:8443","kind":"certificate"}}"#.to_vec(),
|
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com:8443","kind":"certificate"}}"#.to_vec(),
|
||||||
@@ -459,6 +389,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn client_certificate_required_result_survives_process_decoding() {
|
fn client_certificate_required_result_survives_process_decoding() {
|
||||||
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
||||||
|
use std::os::unix::process::ExitStatusExt;
|
||||||
let output = std::process::Output {
|
let output = std::process::Output {
|
||||||
status: std::process::ExitStatus::from_raw(0),
|
status: std::process::ExitStatus::from_raw(0),
|
||||||
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com","kind":"clientCertificateRequired"}}"#.to_vec(),
|
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"));
|
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]
|
#[test]
|
||||||
fn os_profile_sets_os_from_profile() {
|
fn os_profile_sets_os_from_profile() {
|
||||||
let profile = OsProfileBuilder::new(ClientOs::Linux)
|
let profile = OsProfileBuilder::new(ClientOs::Linux)
|
||||||
@@ -556,19 +451,6 @@ mod tests {
|
|||||||
.collect()
|
.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
|
/// 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
|
/// parent's JSON would hit gpauth's text records mid-stream unless the format
|
||||||
/// is passed down.
|
/// is passed down.
|
||||||
@@ -631,14 +513,11 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() {
|
fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() {
|
||||||
#[cfg(unix)]
|
use std::os::unix::process::ExitStatusExt;
|
||||||
let status = std::process::ExitStatus::from_raw(71 << 8);
|
|
||||||
#[cfg(windows)]
|
|
||||||
let status = std::process::ExitStatus::from_raw(0xC0000005);
|
|
||||||
for stdout in [b"{partial".to_vec(), br#"{"cancelled":null}"#.to_vec()] {
|
for stdout in [b"{partial".to_vec(), br#"{"cancelled":null}"#.to_vec()] {
|
||||||
let error = decode_auth_output(
|
let error = decode_auth_output(
|
||||||
std::process::Output {
|
std::process::Output {
|
||||||
status,
|
status: std::process::ExitStatus::from_raw(71 << 8),
|
||||||
stdout,
|
stdout,
|
||||||
stderr: Vec::new(),
|
stderr: Vec::new(),
|
||||||
},
|
},
|
||||||
@@ -651,6 +530,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn successful_malformed_auth_output_is_not_a_rendering_crash() {
|
fn successful_malformed_auth_output_is_not_a_rendering_crash() {
|
||||||
|
use std::os::unix::process::ExitStatusExt;
|
||||||
let error = decode_auth_output(
|
let error = decode_auth_output(
|
||||||
std::process::Output {
|
std::process::Output {
|
||||||
status: std::process::ExitStatus::from_raw(0),
|
status: std::process::ExitStatus::from_raw(0),
|
||||||
@@ -664,7 +544,6 @@ mod tests {
|
|||||||
assert_eq!(error.to_string(), "Failed to parse auth data");
|
assert_eq!(error.to_string(), "Failed to parse auth data");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn custom_authenticator_crash_does_not_request_recovery() {
|
async fn custom_authenticator_crash_does_not_request_recovery() {
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
@@ -700,11 +579,8 @@ mod tests {
|
|||||||
std::fs::write(&custom, "custom").unwrap();
|
std::fs::write(&custom, "custom").unwrap();
|
||||||
assert!(is_bundled_authenticator(&bundled, &bundled));
|
assert!(is_bundled_authenticator(&bundled, &bundled));
|
||||||
assert!(!is_bundled_authenticator(&custom, &bundled));
|
assert!(!is_bundled_authenticator(&custom, &bundled));
|
||||||
#[cfg(unix)]
|
|
||||||
{
|
|
||||||
let alias = directory.path().join("auth-alias");
|
let alias = directory.path().join("auth-alias");
|
||||||
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
|
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
|
||||||
assert!(is_bundled_authenticator(&alias, &bundled));
|
assert!(is_bundled_authenticator(&alias, &bundled));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
@@ -1,14 +1,10 @@
|
|||||||
use super::{
|
use super::{
|
||||||
command_runner::{ChildInput, run_observed},
|
command_runner::{ChildInput, run_observed},
|
||||||
rendering_recovery::{
|
rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible_with_inheritance, is_crash_exit},
|
||||||
GbmBufferFailure, RenderingCrash, StderrDiagnostic, allows_shared_memory_override, eligible_with_inheritance,
|
|
||||||
is_crash_exit,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
use crate::service::transport::SessionCredential;
|
use crate::service::transport::SessionCredential;
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use std::{
|
use std::{
|
||||||
cell::Cell,
|
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
fs::OpenOptions,
|
fs::OpenOptions,
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
@@ -23,10 +19,8 @@ pub(super) async fn launch_desktop_child(
|
|||||||
envs: Option<&HashMap<String, String>>,
|
envs: Option<&HashMap<String, String>>,
|
||||||
credential: &SessionCredential,
|
credential: &SessionCredential,
|
||||||
cancellation: &CancellationToken,
|
cancellation: &CancellationToken,
|
||||||
detect_gbm_failure: bool,
|
|
||||||
) -> anyhow::Result<ExitStatus> {
|
) -> anyhow::Result<ExitStatus> {
|
||||||
let retry_eligible = eligible_with_inheritance(&command, envs.is_none());
|
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 {
|
let log_file = match envs {
|
||||||
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
|
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
|
||||||
None => std::env::var_os("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();
|
let cancellation = cancellation.clone();
|
||||||
|
|
||||||
tokio::task::spawn_blocking(move || {
|
tokio::task::spawn_blocking(move || {
|
||||||
let gbm_failed = Cell::new(false);
|
|
||||||
let check = || {
|
let check = || {
|
||||||
if cancellation.is_cancelled() {
|
if cancellation.is_cancelled() {
|
||||||
Err(std::io::Error::new(
|
Err(std::io::Error::new(
|
||||||
std::io::ErrorKind::Interrupted,
|
std::io::ErrorKind::Interrupted,
|
||||||
"Desktop child launch cancelled",
|
"Desktop child launch cancelled",
|
||||||
))
|
))
|
||||||
} else if gbm_failed.get() {
|
|
||||||
Err(std::io::Error::other(GbmBufferFailure))
|
|
||||||
} else {
|
} else {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -62,17 +53,10 @@ pub(super) async fn launch_desktop_child(
|
|||||||
command,
|
command,
|
||||||
&check,
|
&check,
|
||||||
None,
|
None,
|
||||||
&mut |bytes| {
|
&mut |bytes| diagnostic.push(bytes),
|
||||||
diagnostic.push(bytes);
|
|
||||||
gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(retry_eligible));
|
|
||||||
},
|
|
||||||
&mut sink,
|
&mut sink,
|
||||||
ChildInput::Frame(&frame),
|
ChildInput::Frame(&frame),
|
||||||
);
|
)?;
|
||||||
if gbm_failed.get() && !cancellation.is_cancelled() {
|
|
||||||
return Err(GbmBufferFailure.into());
|
|
||||||
}
|
|
||||||
let observed = observed?;
|
|
||||||
let output = observed.output;
|
let output = observed.output;
|
||||||
if is_crash_exit(output.status) && retry_eligible && diagnostic.matched() {
|
if is_crash_exit(output.status) && retry_eligible && diagnostic.matched() {
|
||||||
return Err(RenderingCrash { status: output.status }.into());
|
return Err(RenderingCrash { status: output.status }.into());
|
||||||
|
|||||||
@@ -170,11 +170,7 @@ impl<'a> DesktopLauncher<'a> {
|
|||||||
}
|
}
|
||||||
match outcome {
|
match outcome {
|
||||||
Err(error) if recovery.recover(&error) => {
|
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;
|
expecting_renewal = true;
|
||||||
input.write_all(&[DESKTOP_RENDERING_RETRY]).await?;
|
input.write_all(&[DESKTOP_RENDERING_RETRY]).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,7 +79,6 @@ impl<'a> GuiHelperLauncher<'a> {
|
|||||||
self.envs,
|
self.envs,
|
||||||
self.credential,
|
self.credential,
|
||||||
cancellation,
|
cancellation,
|
||||||
false,
|
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
Loaded 100 of 236 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user