mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 14:06:14 -05:00
Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c783e5bf50 | ||
|
|
d41fba2019 | ||
|
|
4dcc6ddb26 | ||
|
|
6ffb1e8709 | ||
|
|
1bdaf4e8be | ||
|
|
127961cab7 | ||
|
|
756b8b8957 | ||
|
|
d9df8eb34b | ||
|
|
1da96d9459 | ||
|
|
693a619659 | ||
|
|
aa5b6e4163 | ||
|
|
afd5ec3f09 | ||
|
|
9a43880c4d | ||
|
|
65fce7bcf0 | ||
|
|
ab3908b809 | ||
|
|
8bb061d53f | ||
|
|
5e7e343def | ||
|
|
bde11186f8 | ||
|
|
f2ca674b88 | ||
|
|
6197c658d3 | ||
|
|
f7fdc53be9 | ||
|
|
731101b4bc | ||
|
|
b4ceb90bb5 | ||
|
|
c772693745 | ||
|
|
19f40dcf8d | ||
|
|
225b57eeb4 | ||
|
|
ccd5850a70 | ||
|
|
81e8d06b5b | ||
|
|
22d724c394 | ||
|
|
345ac209fd | ||
|
|
b4c1dc1647 | ||
|
|
8b0d1af648 | ||
|
|
2251afab00 | ||
|
|
754b220a9d | ||
|
|
ce6c97a2f7 | ||
|
|
67b30ac7ca | ||
|
|
b06d7e7672 | ||
|
|
387d4cfa7a | ||
|
|
b1cc0feca7 | ||
|
|
59b8110084 | ||
|
|
1072a35817 | ||
|
|
a43785792a | ||
|
|
76310f1494 | ||
|
|
029f292a6d | ||
|
|
dedd06366e | ||
|
|
5031d4dcfb | ||
|
|
1ac01081e0 | ||
|
|
594ab0ea32 | ||
|
|
e2e762dd35 | ||
|
|
9432f0c3e5 | ||
|
|
fdbe3bcbba |
No files matched your search
@@ -12,6 +12,9 @@ on:
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
build:
|
||||
required: true
|
||||
type: string
|
||||
builder:
|
||||
required: true
|
||||
type: string
|
||||
@@ -85,7 +88,7 @@ jobs:
|
||||
- name: Build gpgui in Docker
|
||||
env:
|
||||
GPGUI_BUILDER: ${{ inputs.builder }}
|
||||
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
||||
GPGUI_BUILD_VERSION: ${{ inputs.build }}
|
||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
run: |
|
||||
|
||||
@@ -12,6 +12,9 @@ on:
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
build:
|
||||
required: true
|
||||
type: string
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
@@ -35,7 +38,7 @@ jobs:
|
||||
env:
|
||||
CARGO_INCREMENTAL: '0'
|
||||
CARGO_BUILD_JOBS: '2'
|
||||
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
||||
GPGUI_BUILD_VERSION: ${{ inputs.build }}
|
||||
GPGUI_GIT_COMMIT: ${{ inputs.gpgui_ref }}
|
||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
|
||||
@@ -49,6 +49,10 @@ permissions:
|
||||
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 }}
|
||||
@@ -59,6 +63,10 @@ jobs:
|
||||
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
|
||||
@@ -125,7 +133,7 @@ jobs:
|
||||
& ./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 and package the matching Windows runtime
|
||||
- name: Build the matching Windows runtime
|
||||
shell: pwsh
|
||||
env:
|
||||
MSYS_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
@@ -134,16 +142,35 @@ jobs:
|
||||
$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 `
|
||||
& ./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 or packaging failed; private diagnostics remain on the runner.'
|
||||
throw 'Windows compilation failed; private diagnostics remain on the runner.'
|
||||
}
|
||||
Write-Host 'Windows compilation and packaging passed.'
|
||||
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
|
||||
|
||||
@@ -69,8 +69,10 @@ jobs:
|
||||
actions: read
|
||||
contents: read
|
||||
outputs:
|
||||
gp_sha: ${{ steps.sources.outputs.gp_sha }}
|
||||
gpgui_sha: ${{ steps.sources.outputs.gpgui_sha }}
|
||||
gp_sha: ${{ steps.identity.outputs.gp_sha }}
|
||||
gpgui_sha: ${{ steps.identity.outputs.gpgui_sha }}
|
||||
version: ${{ steps.identity.outputs.version }}
|
||||
build_version: ${{ steps.identity.outputs.build_version }}
|
||||
steps:
|
||||
- name: Validate stable refs
|
||||
env:
|
||||
@@ -119,11 +121,12 @@ jobs:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
||||
path: selected/gpgui
|
||||
- name: Record selected sources
|
||||
id: sources
|
||||
- name: Record selected sources and versions
|
||||
id: identity
|
||||
run: |
|
||||
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
|
||||
if: steps.restored.outputs.cached != 'true'
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -160,7 +163,7 @@ jobs:
|
||||
# Tauri generates schemas in the source tree. Keep the host checkout read-only.
|
||||
cp -R /workspace /tmp/gp-test-workspace
|
||||
cd /tmp/gp-test-workspace
|
||||
cargo test --workspace --locked
|
||||
cargo test --workspace --locked --features gpapi/openssl-tests
|
||||
|
||||
# Exercise only the paths that require an actual root process.
|
||||
sudo -E env PATH="$PATH" PKEXEC_UID="$(id -u)" cargo test --locked -p gpapi \
|
||||
@@ -442,6 +445,7 @@ jobs:
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
builder: gpgui-builder-tauri2
|
||||
verify_desktop_assets: true
|
||||
secrets:
|
||||
@@ -455,6 +459,7 @@ jobs:
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
builder: gpgui-alpine-builder-tauri2
|
||||
artifact_suffix: -musl
|
||||
secrets:
|
||||
@@ -467,11 +472,15 @@ jobs:
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
secrets:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
|
||||
build-windows:
|
||||
needs: validate-inputs
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
if: ${{ (github.event_name == 'workflow_dispatch' && inputs.build_windows) || (startsWith(github.ref, 'refs/tags/') && vars.BUILD_WINDOWS_ON_TAG == 'true') }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -483,7 +492,7 @@ jobs:
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
build: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
|
||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
secrets:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
WINDOWS_UPDATE_PRIVATE_KEY: ${{ secrets.WINDOWS_UPDATE_PRIVATE_KEY }}
|
||||
@@ -682,7 +691,7 @@ jobs:
|
||||
FEED_URL: ${{ vars.SPARKLE_FEED_URL }}
|
||||
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
|
||||
RELEASE_TAG: ${{ (github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name) }}
|
||||
BUILD_VERSION: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
|
||||
BUILD_VERSION: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -850,7 +859,7 @@ jobs:
|
||||
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
|
||||
RELEASE_TAG: ${{ (github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name) }}
|
||||
REQUEST_ID: ${{ format('{0}.{1}.macos', github.run_id, github.run_attempt) }}
|
||||
BUILD_VERSION: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
|
||||
BUILD_VERSION: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
WORKFLOW_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -1049,7 +1058,6 @@ jobs:
|
||||
nettle \
|
||||
gmp \
|
||||
gnome-keyring \
|
||||
libayatana-appindicator \
|
||||
polkit \
|
||||
webkit2-gtk_41
|
||||
pkgconf --exists libxml-2.0 liblz4 gnutls p11-kit-1 hogweed nettle gmp
|
||||
@@ -1058,7 +1066,7 @@ jobs:
|
||||
exec 3>&1
|
||||
(
|
||||
set -eu
|
||||
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
|
||||
export GPGUI_BUILD_VERSION=${{ needs.validate-inputs.outputs.build_version }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
|
||||
@@ -1142,7 +1150,7 @@ jobs:
|
||||
set -eu
|
||||
export AUTOCONF_VERSION=2.72
|
||||
export AUTOMAKE_VERSION=1.17
|
||||
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
|
||||
export GPGUI_BUILD_VERSION=${{ needs.validate-inputs.outputs.build_version }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
|
||||
@@ -1313,6 +1321,61 @@ jobs:
|
||||
run: |
|
||||
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
|
||||
|
||||
publish-macos-assets:
|
||||
needs: [build-macos, gh-release]
|
||||
if: >-
|
||||
${{ !cancelled() &&
|
||||
needs.build-macos.result == 'success' && needs.gh-release.result == 'success' }}
|
||||
permissions:
|
||||
actions: read
|
||||
contents: write
|
||||
uses: ./.github/workflows/publish-macos-assets.yaml
|
||||
with:
|
||||
build_run_id: ${{ github.run_id }}
|
||||
release_tag: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
expected_gui: ${{ github.event_name == 'workflow_dispatch' && inputs.macos_gui || 'nsh' }}
|
||||
secrets: inherit
|
||||
|
||||
publish-windows-snapshot-feed:
|
||||
needs: [validate-inputs, gh-release, publish-macos-assets]
|
||||
if: >-
|
||||
${{ !cancelled() && github.event_name == 'workflow_dispatch' &&
|
||||
inputs.channel == 'snapshot' && !inputs.build_only && inputs.build_windows &&
|
||||
needs.gh-release.result == 'success' &&
|
||||
(!inputs.build_macos || needs.publish-macos-assets.result == 'success') }}
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/publish-windows-update-feed.yaml
|
||||
with:
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
release_tag: snapshot
|
||||
version: ${{ needs.validate-inputs.outputs.version }}
|
||||
channel: snapshot
|
||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
highlights: Development snapshot.
|
||||
secrets: inherit
|
||||
|
||||
publish-macos-unix-snapshot-feeds:
|
||||
needs: [validate-inputs, gh-release, publish-macos-assets, publish-windows-snapshot-feed]
|
||||
if: >-
|
||||
${{ !cancelled() && github.event_name == 'workflow_dispatch' &&
|
||||
inputs.channel == 'snapshot' && !inputs.build_only && inputs.build_macos &&
|
||||
needs.gh-release.result == 'success' && needs.publish-macos-assets.result == 'success' &&
|
||||
(!inputs.build_windows || needs.publish-windows-snapshot-feed.result == 'success') }}
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/publish-update-feeds.yaml
|
||||
with:
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
channel: snapshot
|
||||
release_tag: snapshot
|
||||
archive_name: ${{ format('GPConnect_{0}-snapshot.{1}_arm64.zip', needs.validate-inputs.outputs.version, needs.validate-inputs.outputs.build_version) }}
|
||||
expected_gui: ${{ inputs.macos_gui }}
|
||||
unix_platforms: ${{ (inputs.build_bsd || inputs.build_bsd_arm64) && 'linux,freebsd,openbsd' || 'linux' }}
|
||||
highlights: Development snapshot.
|
||||
secrets: inherit
|
||||
|
||||
publish-docker-image:
|
||||
needs:
|
||||
- validate-inputs
|
||||
|
||||
@@ -54,7 +54,6 @@ jobs:
|
||||
gettext \
|
||||
gmp \
|
||||
gnutls \
|
||||
libappindicator-gtk3 \
|
||||
libp11-kit \
|
||||
libsecret \
|
||||
libtool \
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
name: Publish macOS assets
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
build_run_id:
|
||||
required: true
|
||||
type: string
|
||||
release_tag:
|
||||
required: true
|
||||
type: string
|
||||
expected_gui:
|
||||
required: false
|
||||
default: nsh
|
||||
type: string
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: false
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build_run_id:
|
||||
|
||||
@@ -1,6 +1,33 @@
|
||||
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:
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
name: Verify public Windows release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: Published snapshot or stable release tag
|
||||
required: true
|
||||
type: string
|
||||
version:
|
||||
description: Base product version
|
||||
required: true
|
||||
type: string
|
||||
build:
|
||||
description: Numeric snapshot build; empty for stable
|
||||
type: string
|
||||
gpgui_ref:
|
||||
description: Matching GUI source ref containing the pinned update tools
|
||||
required: true
|
||||
default: release/next
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
architecture: [x64, arm64]
|
||||
runs-on: ${{ matrix.architecture == 'arm64' && 'windows-11-arm' || 'windows-2022' }}
|
||||
timeout-minutes: 20
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
PRODUCT_VERSION: ${{ inputs.version }}
|
||||
BUILD_VERSION: ${{ inputs.build }}
|
||||
ARCHITECTURE: ${{ matrix.architecture }}
|
||||
WINDOWS_UPDATE_PUBLIC_KEY: ${{ vars.WINDOWS_UPDATE_PUBLIC_KEY }}
|
||||
WINDOWS_SIGNING_PUBLISHER: ${{ vars.WINDOWS_SIGNING_PUBLISHER }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ inputs.release_tag == 'snapshot' && 'release/next' || inputs.release_tag }}
|
||||
persist-credentials: false
|
||||
- uses: ./.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: gpgui
|
||||
- name: Download, verify, install and uninstall the public installer
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($env:PRODUCT_VERSION -notmatch '^\d+\.\d+\.\d+$') { throw 'Invalid product version.' }
|
||||
if (!$env:WINDOWS_UPDATE_PUBLIC_KEY -or !$env:WINDOWS_SIGNING_PUBLISHER) { throw 'Configure the update key and signing publisher.' }
|
||||
$displayVersion = $env:PRODUCT_VERSION
|
||||
if ($env:RELEASE_TAG -eq 'snapshot') {
|
||||
if ($env:BUILD_VERSION -notmatch '^\d+(\.\d+){0,2}$') { throw 'Invalid snapshot build.' }
|
||||
$displayVersion += "-snapshot.$env:BUILD_VERSION"
|
||||
} elseif ($env:RELEASE_TAG -ne "v$env:PRODUCT_VERSION" -or $env:BUILD_VERSION) { throw 'Stable release identity does not match.' }
|
||||
$name = "GPConnect_${displayVersion}_windows-$env:ARCHITECTURE-setup.exe"
|
||||
$downloads = Join-Path $env:RUNNER_TEMP 'public-windows-release'
|
||||
New-Item -ItemType Directory $downloads | Out-Null
|
||||
foreach ($asset in @($name, "$name.sha256", "$name.sig")) {
|
||||
gh release download $env:RELEASE_TAG --repo $env:GITHUB_REPOSITORY --pattern $asset --dir $downloads
|
||||
if ($LASTEXITCODE -ne 0) { throw "Could not download $asset" }
|
||||
}
|
||||
$installer = Join-Path $downloads $name
|
||||
$sum = (Get-Content "$installer.sha256" -Raw).Trim()
|
||||
if ($sum -notmatch '^([a-fA-F0-9]{64}) (.+)$' -or $Matches[2] -ne $name) { throw 'Invalid checksum file.' }
|
||||
$hash = (Get-FileHash $installer).Hash
|
||||
if ($hash -ne $Matches[1]) { throw 'Installer checksum mismatch.' }
|
||||
if ([Diagnostics.FileVersionInfo]::GetVersionInfo($installer).ProductVersion -ne $displayVersion) { throw 'Installer version mismatch.' }
|
||||
& ./scripts/test-windows-signature.ps1 -Files $installer -Publisher $env:WINDOWS_SIGNING_PUBLISHER
|
||||
. ./gpgui/scripts/windows-updates/Get-WinSparkle.ps1
|
||||
$tools = Get-WinSparkleTools (Join-Path $env:RUNNER_TEMP 'winsparkle-tools') -Architecture $env:ARCHITECTURE
|
||||
$signature = (Get-Content "$installer.sig" -Raw).Trim()
|
||||
& $tools.Tool verify -p $env:WINDOWS_UPDATE_PUBLIC_KEY -s $signature $installer
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Installer update signature is invalid.' }
|
||||
& ./scripts/test-windows-installer.ps1 -Installer $installer -Architecture $env:ARCHITECTURE -Build $env:BUILD_VERSION
|
||||
@{ release = $env:RELEASE_TAG; version = $displayVersion; architecture = $env:ARCHITECTURE;
|
||||
sha256 = $hash.ToLowerInvariant(); publisher = $env:WINDOWS_SIGNING_PUBLISHER;
|
||||
authenticode = 'Valid'; timestamped = $true; update_signature = 'Valid';
|
||||
installed_signatures = 'Valid'; install_uninstall = 'Passed'
|
||||
} | ConvertTo-Json | Set-Content verification.json -Encoding utf8
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: windows-release-verification-${{ matrix.architecture }}
|
||||
path: verification.json
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
Generated
+26
-22
@@ -292,7 +292,7 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "auth"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"block2",
|
||||
@@ -321,6 +321,7 @@ dependencies = [
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows",
|
||||
"windows-sys 0.61.2",
|
||||
"winreg 0.55.0",
|
||||
]
|
||||
|
||||
@@ -553,7 +554,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "browser-launcher"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"log",
|
||||
@@ -918,7 +919,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "common"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
@@ -2130,9 +2131,17 @@ dependencies = [
|
||||
"system-deps",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gp-xml"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"url",
|
||||
"xmltree",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gpapi"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.23.1",
|
||||
@@ -2146,7 +2155,9 @@ dependencies = [
|
||||
"directories",
|
||||
"dns-lookup",
|
||||
"env_logger",
|
||||
"file-rotate",
|
||||
"getrandom 0.4.3",
|
||||
"gp-xml",
|
||||
"gtk",
|
||||
"humantime",
|
||||
"libloading 0.9.0",
|
||||
@@ -2194,7 +2205,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpauth"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"auth",
|
||||
@@ -2202,7 +2213,6 @@ dependencies = [
|
||||
"common",
|
||||
"compile-time",
|
||||
"gpapi",
|
||||
"home",
|
||||
"log",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
@@ -2213,7 +2223,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpclient"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -2244,7 +2254,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpgui-helper"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -2265,24 +2275,26 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gphip"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
"chrono",
|
||||
"gpapi",
|
||||
"log",
|
||||
"netdev",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
"uuid",
|
||||
"uzers",
|
||||
"windows",
|
||||
"xmltree",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gpservice"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -2320,7 +2332,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gptunnel"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"gpapi",
|
||||
"log",
|
||||
@@ -2332,7 +2344,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpvpnc"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"ipnet",
|
||||
@@ -2460,15 +2472,6 @@ dependencies = [
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "home"
|
||||
version = "0.5.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "html-escape"
|
||||
version = "0.3.0"
|
||||
@@ -3857,11 +3860,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openconnect"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
dependencies = [
|
||||
"autotools",
|
||||
"cc",
|
||||
"fs_extra",
|
||||
"gp-xml",
|
||||
"is_executable",
|
||||
"libc",
|
||||
"log",
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ members = [
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.91"
|
||||
version = "3.4.0"
|
||||
version = "3.5.0"
|
||||
authors = ["Kevin Yue <[email protected]>"]
|
||||
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
edition = "2024"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# GlobalProtect-openconnect
|
||||
|
||||
A GlobalProtect VPN client built on OpenConnect. It provides command-line tools (`gpclient`) and the GP Connect desktop application for macOS, Linux, FreeBSD, and OpenBSD.
|
||||
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.
|
||||
|
||||
> **Disclaimer**: GP Connect is an independent third-party client for GlobalProtect VPN networks. It is not affiliated with or endorsed by Palo Alto Networks, Inc.
|
||||
|
||||
@@ -21,6 +21,7 @@ A GlobalProtect VPN client built on OpenConnect. It provides command-line tools
|
||||
- [Command-Line Interface](#command-line-interface)
|
||||
- [Graphical User Interface](#graphical-user-interface)
|
||||
- [Installation](#installation)
|
||||
- [Windows](#windows)
|
||||
- [macOS](#macos)
|
||||
- [Debian / Ubuntu](#debian--ubuntu)
|
||||
- [Arch Linux / Manjaro](#arch-linux--manjaro)
|
||||
@@ -40,8 +41,8 @@ A GlobalProtect VPN client built on OpenConnect. It provides command-line tools
|
||||
|
||||
## Features
|
||||
|
||||
- **Multi-Platform** – macOS (Apple silicon), Linux, FreeBSD, and OpenBSD
|
||||
- **Dual Interfaces** – Fast terminal CLI (`gpclient`) and desktop GUI (**GP Connect**)
|
||||
- **Multi-Platform** – Windows (x64 and ARM64), macOS (Apple silicon), Linux, FreeBSD, and OpenBSD
|
||||
- **Dual Interfaces** – Desktop GUI (**GP Connect**) and terminal CLI (`gpclient`, on macOS, Linux, and BSD)
|
||||
- **Native Shell on Linux** – Ultra-low-memory native desktop GUI alongside the webview interface
|
||||
- **Flexible Routing** – Full System VPN tunnel or local SOCKS5 proxy mode
|
||||
- **Modern Authentication** – SAML / SSO, MFA, FIDO2 (YubiKey), client certificates, and external browser login
|
||||
@@ -53,7 +54,7 @@ A GlobalProtect VPN client built on OpenConnect. It provides command-line tools
|
||||
|
||||
### Command-Line Interface
|
||||
|
||||
The open-source `gpclient` CLI handles authentication, connection lifecycle, and HIP generation:
|
||||
On macOS, Linux, and BSD, the open-source `gpclient` CLI handles authentication, connection lifecycle, and HIP generation:
|
||||
|
||||
```bash
|
||||
# Connect to a portal server
|
||||
@@ -79,6 +80,7 @@ Run `gpclient --help` or `gpclient <command> --help` to view all available comma
|
||||
|
||||
### Graphical User Interface
|
||||
|
||||
- **Windows**: Open **GP Connect** from the Start menu.
|
||||
- **macOS**: Open **GP Connect** from Applications.
|
||||
- **Linux / BSD**: Launch GP Connect from your application menu or run:
|
||||
```bash
|
||||
@@ -90,6 +92,19 @@ Run `gpclient --help` or `gpclient <command> --help` to view all available comma
|
||||
|
||||
## Installation
|
||||
|
||||
### Windows
|
||||
|
||||
Download the matching EXE installer from [GitHub Releases](https://github.com/yuezk/GlobalProtect-openconnect/releases/latest):
|
||||
|
||||
- **x64**: Windows 10 version 2004 (build 19041) or later.
|
||||
- **ARM64**: Windows 11.
|
||||
|
||||
Run the installer and confirm installation. It installs GP Connect and its background VPN service for all users; administrator access is required. Open GP Connect from the Start menu as your normal user.
|
||||
|
||||
The installer and application executables are signed by **Tangramly, LLC**. Embedded sign-in uses Microsoft Edge WebView2 Runtime. You can also use your system browser from Settings.
|
||||
|
||||
GP Connect checks for updates in the app. Uninstall it from Windows Settings; your app settings are kept. The Windows package contains the desktop app and service, without the `gpclient` command-line tool.
|
||||
|
||||
### macOS
|
||||
|
||||
Requires Apple silicon and macOS 13+. Includes both GP Connect and the `gpclient` CLI.
|
||||
|
||||
@@ -23,8 +23,6 @@ serde_json.workspace = true
|
||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||
compile-time.workspace = true
|
||||
|
||||
home = "0.5.12"
|
||||
|
||||
# webview auth dependencies
|
||||
tauri = { workspace = true, optional = true }
|
||||
|
||||
|
||||
@@ -36,6 +36,27 @@ fn login_response() -> String {
|
||||
)
|
||||
}
|
||||
|
||||
async fn read_request(stream: &mut tokio::net::TcpStream) -> String {
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0; 4096];
|
||||
let count = stream.read(&mut buf).await.unwrap();
|
||||
assert_ne!(count, 0, "Request ended before its body");
|
||||
request.extend_from_slice(&buf[..count]);
|
||||
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||
.unwrap_or(0);
|
||||
if request.len() >= end + 4 + length {
|
||||
return String::from_utf8(request).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
@@ -44,25 +65,7 @@ async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task
|
||||
let mut requests = Vec::new();
|
||||
for (status, body) in responses {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0; 4096];
|
||||
let count = stream.read(&mut buf).await.unwrap();
|
||||
assert_ne!(count, 0, "Request ended before its body");
|
||||
request.extend_from_slice(&buf[..count]);
|
||||
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||
.unwrap_or(0);
|
||||
if request.len() >= end + 4 + length {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
requests.push(String::from_utf8(request).unwrap());
|
||||
requests.push(read_request(&mut stream).await);
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
@@ -126,6 +129,154 @@ async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unreachable_gateway_keeps_cached_cookie() {
|
||||
// Nothing listens here: the cached gateway login gets no answer at all.
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let gateway = format!("http://{}", listener.local_addr().unwrap());
|
||||
drop(listener);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let cache = directory.path().join("cookie.json");
|
||||
let args = TestArgs::parse_from([
|
||||
"test",
|
||||
"http://unavailable-portal.invalid",
|
||||
"--cookie-only",
|
||||
"--cookie-cache",
|
||||
cache.to_str().unwrap(),
|
||||
])
|
||||
.connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
cookie_store::save(
|
||||
&cache,
|
||||
&StoredCookie::new(
|
||||
args.server.clone(),
|
||||
"alice".into(),
|
||||
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||
gateway,
|
||||
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(handler.handle_impl().await.is_err());
|
||||
assert!(
|
||||
cache.exists(),
|
||||
"a login that got no answer must not delete the cookie cache"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_closing_without_response_keeps_cached_cookie() {
|
||||
closed_connection_keeps_cached_cookie(false, false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn portal_closing_without_response_keeps_cached_cookie() {
|
||||
closed_connection_keeps_cached_cookie(true, false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn partial_responses_keep_cached_cookie() {
|
||||
closed_connection_keeps_cached_cookie(false, true).await;
|
||||
closed_connection_keeps_cached_cookie(true, true).await;
|
||||
}
|
||||
|
||||
async fn closed_connection_keeps_cached_cookie(portal_discovery: bool, partial_body: bool) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let worker = tokio::spawn(async move {
|
||||
tokio::time::timeout(Duration::from_secs(5), async move {
|
||||
if portal_discovery {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
assert!(read_request(&mut stream).await.contains("/global-protect/prelogin.esp"));
|
||||
let body = "<prelogin-response><status>Success</status></prelogin-response>";
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let request = read_request(&mut stream).await;
|
||||
if partial_body {
|
||||
stream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n<response>")
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
request
|
||||
})
|
||||
.await
|
||||
.expect("Connection-closing fixture timed out")
|
||||
});
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let cache = directory.path().join("cookie.json");
|
||||
let args = TestArgs::parse_from([
|
||||
"test",
|
||||
&origin,
|
||||
"--cookie-only",
|
||||
"--cookie-cache",
|
||||
cache.to_str().unwrap(),
|
||||
])
|
||||
.connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
cookie_store::save(
|
||||
&cache,
|
||||
&StoredCookie::new(
|
||||
args.server.clone(),
|
||||
"alice".into(),
|
||||
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||
origin.clone(),
|
||||
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let result = if portal_discovery {
|
||||
handler.connect_portal_with_prelogin(&origin).await
|
||||
} else {
|
||||
handler.handle_impl().await
|
||||
};
|
||||
let error = result.unwrap_err();
|
||||
let Some(gpapi::error::PortalError::NetworkError(network)) = error.downcast_ref() else {
|
||||
panic!("Expected a network error, got {error:?}");
|
||||
};
|
||||
if partial_body {
|
||||
assert!(network.is_body() || network.is_decode());
|
||||
} else {
|
||||
assert!(network.is_request());
|
||||
}
|
||||
assert!(!network.is_connect());
|
||||
assert!(!network.is_timeout());
|
||||
assert!(cache.exists(), "an unanswered request must not delete the cookie cache");
|
||||
let request = worker.await.unwrap();
|
||||
assert!(request.contains("portal-cookie"));
|
||||
if portal_discovery {
|
||||
assert!(request.starts_with("POST /global-protect/getconfig.esp "));
|
||||
} else {
|
||||
assert!(request.starts_with("POST /ssl-vpn/login.esp "));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
|
||||
let (origin, worker) = gateway(vec![
|
||||
|
||||
@@ -101,6 +101,11 @@ impl ConnectHandler<'_> {
|
||||
{
|
||||
return Some(Err(error));
|
||||
}
|
||||
// A failed request does not establish that the cookie was rejected.
|
||||
if is_network_error(&error) {
|
||||
warn!("Cached gateway authentication request failed: {error}");
|
||||
return Some(Err(error));
|
||||
}
|
||||
cookie_store::clear(&path);
|
||||
warn!("Cached gateway authentication failed: {error}");
|
||||
return None;
|
||||
@@ -830,3 +835,11 @@ 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,15 +128,18 @@ impl ConnectHandler<'_> {
|
||||
produce_report: Arc::new(move |request, control| {
|
||||
control.check()?;
|
||||
if matches!(source.as_ref(), openconnect::HipSource::Disabled) {
|
||||
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context: gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
return gphip::generate_identity_report(
|
||||
&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context: gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
},
|
||||
},
|
||||
})
|
||||
control,
|
||||
)
|
||||
.map_err(std::io::Error::other);
|
||||
}
|
||||
source.collect(
|
||||
|
||||
@@ -292,6 +292,11 @@ impl<'a> ConnectHandler<'a> {
|
||||
Ok(config) => Some((cred, config)),
|
||||
Err(error) => {
|
||||
self.check_cancelled()?;
|
||||
// A failed request does not establish that the cookie was rejected.
|
||||
if gateway::is_network_error(&error) {
|
||||
warn!("Cached portal authentication request failed: {error}");
|
||||
return Err(error);
|
||||
}
|
||||
warn!("Cached portal authentication failed: {error}");
|
||||
self.clear_cookie_cache();
|
||||
None
|
||||
|
||||
@@ -85,7 +85,7 @@ impl HipPreviews {
|
||||
})
|
||||
.await;
|
||||
let result = match generated {
|
||||
Ok(Ok(xml)) => preview_result(®istry, session_id, xml),
|
||||
Ok(Ok(report)) => preview_result(®istry, session_id, report),
|
||||
Ok(Err(error)) => {
|
||||
log::warn!("HIP preview failed: {error:#}");
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
|
||||
@@ -132,17 +132,20 @@ impl HipPreviews {
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_result(registry: &SessionRegistry, session_id: Uuid, xml: String) -> ServiceResult {
|
||||
let result = registry.store_hip_preview(session_id, xml).and_then(|preview_id| {
|
||||
registry
|
||||
.hip_preview_chunk(session_id, preview_id, 0)
|
||||
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
})
|
||||
});
|
||||
fn preview_result(registry: &SessionRegistry, session_id: Uuid, report: gpapi::hip::HipReport) -> ServiceResult {
|
||||
let result = registry
|
||||
.store_hip_preview(session_id, report.xml)
|
||||
.and_then(|preview_id| {
|
||||
registry
|
||||
.hip_preview_chunk(session_id, preview_id, 0)
|
||||
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
windows_updates: report.windows_updates,
|
||||
})
|
||||
});
|
||||
result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"))
|
||||
}
|
||||
|
||||
@@ -152,7 +155,7 @@ fn generate(
|
||||
desktop_uid: Option<u32>,
|
||||
identity: HostIdentity,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<String> {
|
||||
) -> anyhow::Result<gpapi::hip::HipReport> {
|
||||
ensure!(request.client_version.len() <= 64, "Invalid HIP client version");
|
||||
ensure!(
|
||||
request.host_id.as_ref().is_none_or(|id| id.len() <= 256),
|
||||
@@ -188,7 +191,15 @@ fn generate(
|
||||
};
|
||||
let xml = match &request.source {
|
||||
HipSource::Disabled => bail!("HIP is disabled"),
|
||||
HipSource::Generated => crate::hip_source::generate(&profile, None, &input, &check, true)?,
|
||||
HipSource::Generated => {
|
||||
return gphip::generate_report_details(
|
||||
&gphip::ReportInput {
|
||||
profile,
|
||||
context: gphip::ReportContext::Preview,
|
||||
},
|
||||
&check,
|
||||
);
|
||||
}
|
||||
HipSource::Edited { .. } => {
|
||||
let xml = edited_report.context("Edited HIP report is unavailable")?;
|
||||
crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)?
|
||||
@@ -204,7 +215,10 @@ fn generate(
|
||||
}
|
||||
};
|
||||
check()?;
|
||||
Ok(xml)
|
||||
Ok(gpapi::hip::HipReport {
|
||||
xml,
|
||||
windows_updates: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -158,19 +158,22 @@ pub(crate) fn profile(
|
||||
control: &dyn gpapi::collection::CollectionControl,
|
||||
) -> io::Result<OsProfile> {
|
||||
let identity = gpapi::os_profile::desktop::identity_from_parts(
|
||||
hostname.unwrap_or_else(|| identity.computer().into()),
|
||||
host_id.unwrap_or_else(|| identity.host_id().into()),
|
||||
hostname.as_deref().unwrap_or(identity.computer()).into(),
|
||||
host_id.as_deref().unwrap_or(identity.host_id()).into(),
|
||||
identity.serialno().into(),
|
||||
identity.mac_addr().into(),
|
||||
);
|
||||
let mut builder = OsProfileBuilder::new(os).host_identity(identity);
|
||||
if let Some(hostname) = hostname {
|
||||
builder = builder.computer_name_override(hostname);
|
||||
}
|
||||
if let Some(version) = version {
|
||||
builder = builder.client_version(version);
|
||||
}
|
||||
if let Some(os_version) = os_version {
|
||||
builder = builder.os_version(os_version);
|
||||
}
|
||||
gpapi::os_profile::desktop::collect_profile_with_control(builder, None, control)
|
||||
gpapi::os_profile::desktop::collect_profile_with_control(builder, host_id.as_deref(), control)
|
||||
}
|
||||
|
||||
fn generation_error(error: anyhow::Error) -> io::Error {
|
||||
@@ -235,6 +238,29 @@ mod tests {
|
||||
assert_eq!(profile.host_identity().serialno(), "serial");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn native_windows_profile_retains_negotiated_host_id() {
|
||||
let identity = gpapi::os_profile::HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"hardware-seed".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let profile = profile(
|
||||
&identity,
|
||||
ClientOs::Windows,
|
||||
None,
|
||||
None,
|
||||
Some("negotiated-host".into()),
|
||||
None,
|
||||
&gpapi::collection::CollectionBudget::new(std::time::Duration::from_secs(60)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(profile.host_id(), "negotiated-host");
|
||||
assert_eq!(profile.host_identity().host_id(), "negotiated-host");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_errors_preserve_cancellation() {
|
||||
let error = generation_error(io::Error::new(io::ErrorKind::Interrupted, "cancelled").into());
|
||||
|
||||
@@ -22,6 +22,8 @@ mod runtime_user;
|
||||
mod session_registry;
|
||||
mod vpn_script;
|
||||
mod vpn_task;
|
||||
#[cfg(windows)]
|
||||
mod windows_patches;
|
||||
mod ws_connection;
|
||||
mod ws_server;
|
||||
|
||||
|
||||
@@ -70,6 +70,10 @@ pub struct 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> {
|
||||
self.lifecycle.subscribe_tunnel()
|
||||
}
|
||||
@@ -262,7 +266,9 @@ impl RequestDispatcher {
|
||||
| WsRequest::GetHipApprovalStatus { .. }
|
||||
| WsRequest::ReadHipPreviewChunk(_)
|
||||
| WsRequest::GetLastSubmittedHipReport
|
||||
| WsRequest::SetTunnelStatisticsEnabled { .. } => {
|
||||
| WsRequest::SetTunnelStatisticsEnabled { .. }
|
||||
| WsRequest::SetWindowsPatchInterest { .. }
|
||||
| WsRequest::RefreshWindowsPatches { .. } => {
|
||||
unreachable!("session-bound request was already dispatched")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ mod script_tun;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LifecycleHandle {
|
||||
#[cfg(windows)]
|
||||
pub(crate) patch_checks: Arc<crate::windows_patches::PatchChecks>,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
admissions: Arc<Mutex<Admissions>>,
|
||||
tunnel: watch::Sender<TunnelBinding>,
|
||||
@@ -462,6 +464,8 @@ impl VpnTask {
|
||||
) -> (Self, LifecycleHandle) {
|
||||
let (events_tx, events) = mpsc::channel(4);
|
||||
let lifecycle = LifecycleHandle {
|
||||
#[cfg(windows)]
|
||||
patch_checks: crate::windows_patches::PatchChecks::new(),
|
||||
events: events_tx,
|
||||
admissions: Arc::new(Mutex::new(Admissions::default())),
|
||||
tunnel: watch::channel(TunnelBinding::default()).0,
|
||||
|
||||
@@ -66,10 +66,13 @@ pub(super) async fn run(
|
||||
md5: request.md5.clone(),
|
||||
};
|
||||
if !posture_enabled {
|
||||
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context,
|
||||
})
|
||||
return gphip::generate_identity_report(
|
||||
&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context,
|
||||
},
|
||||
control,
|
||||
)
|
||||
.map_err(std::io::Error::other);
|
||||
}
|
||||
source.collect(
|
||||
|
||||
@@ -50,6 +50,23 @@ pub(super) fn spawn(
|
||||
) -> JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
let attempt = input.attempt;
|
||||
#[cfg(windows)]
|
||||
let _patch_interest = {
|
||||
let args = input.connection.request.args();
|
||||
let profile = &input.connection.resources.profile;
|
||||
(matches!(args.hip_source(), gpapi::hip::HipSource::Generated)
|
||||
&& profile.is_native()
|
||||
&& profile.client_os() == gpapi::os_profile::ClientOs::Windows
|
||||
&& (input.connection.request.plan().policy().collect_hip_data()
|
||||
|| input
|
||||
.connection
|
||||
.request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.any(|member| member.authentication.mode() == SessionMode::Tunnel)))
|
||||
.then(|| input.lifecycle.patch_checks.consumer())
|
||||
};
|
||||
let mut failure = None;
|
||||
let mut approval = None;
|
||||
if !cancellation.is_cancelled() {
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! 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)?)
|
||||
}
|
||||
@@ -410,6 +410,48 @@ async fn handle_client_message(
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::SetWindowsPatchInterest { enabled } = &request {
|
||||
#[cfg(windows)]
|
||||
ctx.patch_checks.set_interest(control.connection_id(), *enabled);
|
||||
#[cfg(not(windows))]
|
||||
let _ = enabled;
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::Accepted,
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
if let WsRequest::RefreshWindowsPatches { after } = &request {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let checks = ctx.patch_checks.clone();
|
||||
let control = control.clone();
|
||||
let after = Some(after.unwrap_or(0));
|
||||
tokio::spawn(async move {
|
||||
let success = checks.refresh(after).await;
|
||||
let result = if success {
|
||||
ServiceResult::Accepted
|
||||
} else {
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "Couldn’t check local updates.")
|
||||
};
|
||||
let _ = control.send(ConnectionCommand::Reply { id, result });
|
||||
});
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = after;
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Windows patch checks are unavailable"),
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::StoreEditedHipReportChunk(report) = request {
|
||||
let upload_id = report.upload_id.as_deref().and_then(|id| Uuid::parse_str(id).ok());
|
||||
let result = if report.upload_id.is_some() && upload_id.is_none() {
|
||||
@@ -451,6 +493,7 @@ async fn handle_client_message(
|
||||
offset: chunk.offset,
|
||||
xml,
|
||||
complete,
|
||||
windows_updates: None,
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP preview is unavailable"));
|
||||
@@ -467,6 +510,7 @@ async fn handle_client_message(
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
windows_updates: None,
|
||||
},
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"),
|
||||
},
|
||||
@@ -501,6 +545,10 @@ async fn handle_client_message(
|
||||
}
|
||||
|
||||
if let WsRequest::PreviewHipReport(preview) = request {
|
||||
#[cfg(windows)]
|
||||
if preview.client_os == gpapi::os_profile::ClientOs::Windows && matches!(preview.source, HipSource::Generated) {
|
||||
ctx.patch_checks.check_if_due();
|
||||
}
|
||||
let edited_report = if let HipSource::Edited { report_id } = &preview.source {
|
||||
let report_id = match Uuid::parse_str(report_id) {
|
||||
Ok(id) => id,
|
||||
|
||||
@@ -63,6 +63,8 @@ pub(crate) struct WsServerContext {
|
||||
state: Mutex<ServiceState>,
|
||||
handshake_slots: Arc<Semaphore>,
|
||||
pub(crate) hip_previews: crate::hip_preview::HipPreviews,
|
||||
#[cfg(windows)]
|
||||
pub(crate) patch_checks: Arc<crate::windows_patches::PatchChecks>,
|
||||
}
|
||||
|
||||
impl WsServerContext {
|
||||
@@ -75,6 +77,8 @@ impl WsServerContext {
|
||||
Self {
|
||||
product_version,
|
||||
registry,
|
||||
#[cfg(windows)]
|
||||
patch_checks: dispatcher.patch_checks(),
|
||||
dispatcher,
|
||||
state: Mutex::new(ServiceState {
|
||||
revision: 0,
|
||||
@@ -183,6 +187,8 @@ impl WsServerContext {
|
||||
|
||||
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
||||
self.registry.disconnect_if_current(session_id, generation);
|
||||
#[cfg(windows)]
|
||||
self.patch_checks.set_interest(connection_id, false);
|
||||
let mut state = self.state.lock().await;
|
||||
state.connections.remove(&connection_id);
|
||||
state.refresh_demand();
|
||||
@@ -364,6 +370,12 @@ impl WsServer {
|
||||
};
|
||||
let _ = ready_tx.send(());
|
||||
|
||||
#[cfg(windows)]
|
||||
let patch_task = {
|
||||
let checks = self.ctx.patch_checks.clone();
|
||||
let stop = self.cancel_token.clone();
|
||||
tokio::spawn(async move { checks.run(stop).await })
|
||||
};
|
||||
tokio::select! {
|
||||
_ = watch_vpn_state(self.vpn_state_rx.clone(), Arc::clone(&self.ctx)) => {
|
||||
info!("VPN state watch task completed");
|
||||
@@ -378,6 +390,9 @@ impl WsServer {
|
||||
info!("WS server cancelled");
|
||||
}
|
||||
}
|
||||
self.cancel_token.cancel();
|
||||
#[cfg(windows)]
|
||||
let _ = patch_task.await;
|
||||
self.ctx.hip_previews.shutdown().await;
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,27 @@
|
||||
# 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
|
||||
|
||||
@@ -102,6 +102,7 @@ tempfile.workspace = true
|
||||
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 }
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
//! 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, NamedPipeServer},
|
||||
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,
|
||||
@@ -52,6 +56,9 @@ impl AuthCallbackReceiver {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -76,6 +83,12 @@ pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
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,
|
||||
@@ -91,6 +104,32 @@ pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
.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();
|
||||
@@ -99,6 +138,8 @@ pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
|
||||
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.
|
||||
|
||||
@@ -22,7 +22,7 @@ impl RecoveryStatus {
|
||||
Self::Hidden => "",
|
||||
Self::Restarting => "Restarting sign-in…",
|
||||
Self::Loading => "Loading sign-in…",
|
||||
Self::Failed => "Couldn’t restart sign-in.",
|
||||
Self::Failed => "Couldn’t load sign-in.",
|
||||
Self::Rejected => "Sign-in wasn’t completed.",
|
||||
Self::Tls {
|
||||
reason: TlsFailureReason::Handshake,
|
||||
@@ -55,6 +55,7 @@ impl RecoveryStatus {
|
||||
matches!(self, Self::Hidden | Self::Loading | Self::CertificateBypassed)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn is_busy(self) -> bool {
|
||||
matches!(self, Self::Restarting | Self::Loading)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum TlsFailureReason {
|
||||
Expired,
|
||||
#[cfg(not(windows))]
|
||||
NotYetValid,
|
||||
#[cfg(not(windows))]
|
||||
Untrusted,
|
||||
HostnameMismatch,
|
||||
InvalidCertificate,
|
||||
@@ -17,7 +19,9 @@ impl TlsFailureReason {
|
||||
pub fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::Expired => "The certificate has expired.",
|
||||
#[cfg(not(windows))]
|
||||
Self::NotYetValid => "The certificate is not valid yet.",
|
||||
#[cfg(not(windows))]
|
||||
Self::Untrusted => "The certificate was issued by an untrusted authority.",
|
||||
Self::HostnameMismatch => "The certificate does not match this server’s hostname.",
|
||||
Self::InvalidCertificate => "The server’s certificate could not be verified.",
|
||||
|
||||
@@ -18,6 +18,7 @@ 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;
|
||||
@@ -31,6 +32,7 @@ pub(super) struct Controls {
|
||||
proceed: HWND,
|
||||
cancel: HWND,
|
||||
status: Cell<RecoveryStatus>,
|
||||
recovery_bounds: Cell<RECT>,
|
||||
font: Cell<Option<(u32, HFONT)>>,
|
||||
}
|
||||
|
||||
@@ -75,6 +77,7 @@ impl Controls {
|
||||
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 {
|
||||
@@ -186,33 +189,63 @@ impl Controls {
|
||||
Some(LPARAM(&text as *const _ as isize)),
|
||||
);
|
||||
let status = self.status.get();
|
||||
let header = if status == RecoveryStatus::Hidden {
|
||||
TOOLBAR_HEIGHT
|
||||
} else {
|
||||
TOOLBAR_HEIGHT + 68
|
||||
};
|
||||
MoveWindow(
|
||||
self.message,
|
||||
px(8),
|
||||
px(TOOLBAR_HEIGHT + 2),
|
||||
(width - px(16)).max(0),
|
||||
px(38),
|
||||
true,
|
||||
)?;
|
||||
let mut right = width - px(8);
|
||||
for (hwnd, visible, size) in [
|
||||
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(TOOLBAR_HEIGHT + 38), px(size), px(28), true)?;
|
||||
MoveWindow(hwnd, right, px(button_top), px(size), px(28), true)?;
|
||||
right -= px(6);
|
||||
}
|
||||
}
|
||||
let content_height = (bounds.bottom - px(header)).max(0);
|
||||
MoveWindow(self.webview_host, 0, px(header), width, content_height, true)?;
|
||||
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,
|
||||
@@ -291,12 +324,36 @@ unsafe extern "system" fn window_proc(
|
||||
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() {
|
||||
FillRect(HDC(wparam.0 as *mut _), &bounds, GetSysColorBrush(COLOR_WINDOW));
|
||||
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);
|
||||
|
||||
@@ -10,9 +10,7 @@ license = "MIT"
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
open = { version = "5", optional = true }
|
||||
webbrowser = { version = "1", optional = true }
|
||||
which = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
@@ -20,3 +18,9 @@ launcher = ["dep:open", "dep:webbrowser", "dep:which", "dep:winreg"]
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = { version = "0.55", optional = true }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
open = { version = "5", optional = true }
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
which = { workspace = true, optional = true }
|
||||
@@ -0,0 +1,11 @@
|
||||
[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
|
||||
@@ -0,0 +1,172 @@
|
||||
//! 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]"
|
||||
);
|
||||
}
|
||||
}
|
||||
+27
-4
@@ -6,6 +6,7 @@ edition.workspace = true
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
gp-xml = { path = "../gp-xml" }
|
||||
common = { path = "../common" }
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
@@ -46,6 +47,9 @@ snow.workspace = true
|
||||
zeroize = { workspace = true, features = ["serde"] }
|
||||
getrandom = "0.4"
|
||||
|
||||
# Used only by the opt-in certificate interoperability tests.
|
||||
openssl = { workspace = true, optional = true }
|
||||
|
||||
# Optional dependencies for features
|
||||
tauri = { workspace = true, optional = true }
|
||||
clap = { workspace = true, optional = true }
|
||||
@@ -61,8 +65,10 @@ oslog = { version = "0.2", default-features = false, optional = true }
|
||||
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
|
||||
gtk = { version = "0.18", optional = true }
|
||||
|
||||
[target.'cfg(target_os="linux")'.dependencies]
|
||||
[target.'cfg(any(target_os="linux", target_os="freebsd", target_os="openbsd"))'.dependencies]
|
||||
directories = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(target_os="linux")'.dependencies]
|
||||
libloading = { version = "0.9", optional = true }
|
||||
|
||||
[target.'cfg(target_os="macos")'.dependencies]
|
||||
@@ -76,7 +82,6 @@ cc = "1"
|
||||
pkg-config = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
openssl.workspace = true
|
||||
libloading = "0.9"
|
||||
proptest.workspace = true
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -87,14 +92,32 @@ desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:u
|
||||
tauri = ["desktop", "dep:tauri", "dep:gtk", "dep:os_info"]
|
||||
clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"]
|
||||
webview-auth = []
|
||||
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"]
|
||||
openssl-tests = ["dep:openssl"]
|
||||
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog", "dep:file-rotate"]
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
|
||||
uzers = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
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"] }
|
||||
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"]
|
||||
@@ -0,0 +1,16 @@
|
||||
# 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.
|
||||
@@ -109,6 +109,7 @@ fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bo
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
hash::MessageDigest,
|
||||
@@ -180,10 +181,12 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
|
||||
server_with_client_auth(tls, SslVerifyMode::NONE)
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
fn server_with_client_auth(tls: bool, verify: SslVerifyMode) -> (String, thread::JoinHandle<()>) {
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
@@ -233,6 +236,7 @@ mod tests {
|
||||
(address, worker)
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn prelogin_returns_typed_certificate_failure_with_only_the_server_origin() {
|
||||
use crate::{
|
||||
@@ -254,6 +258,7 @@ mod tests {
|
||||
assert_eq!(tls.server, address);
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn certificate_bypass_allows_prelogin() {
|
||||
use crate::{
|
||||
@@ -270,6 +275,7 @@ mod tests {
|
||||
assert!(matches!(result.unwrap(), crate::portal::Prelogin::Saml(_)));
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() {
|
||||
let (address, worker) = server(false);
|
||||
@@ -303,7 +309,7 @@ mod tests {
|
||||
assert_eq!(classify(&error), None);
|
||||
}
|
||||
|
||||
#[cfg(feature = "desktop")]
|
||||
#[cfg(all(feature = "desktop", unix))]
|
||||
#[test]
|
||||
fn rendering_recovery_retains_client_certificate_requirement() {
|
||||
use crate::process::rendering_recovery::{RecoveryState, RenderingCrash};
|
||||
@@ -330,6 +336,7 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn required_client_certificate_is_not_bypassed_by_ignoring_server_trust() {
|
||||
use crate::{
|
||||
@@ -371,6 +378,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn prelogin_explains_peer_rejection_of_an_already_configured_identity() {
|
||||
use crate::{
|
||||
@@ -403,6 +411,7 @@ mod tests {
|
||||
assert!(!error.to_string().contains("passphrase"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
|
||||
use crate::{
|
||||
@@ -435,6 +444,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[tokio::test]
|
||||
async fn imported_identity_formats_complete_mutual_tls_prelogin() {
|
||||
use crate::{
|
||||
|
||||
@@ -202,7 +202,7 @@ async fn receive_gateway_login(
|
||||
let url = res.url().clone();
|
||||
let http_version = res.version();
|
||||
let content_type = res.headers().get(reqwest::header::CONTENT_TYPE).cloned();
|
||||
let res = parse_gp_response(res).await.map_err(|err| {
|
||||
let res = parse_gp_response(res).await.map_err(|mut err| {
|
||||
// Redirect paths and query strings can contain authentication tokens. Log
|
||||
// only the redacted origin and whether the response is from the login path.
|
||||
warn!(
|
||||
@@ -221,6 +221,9 @@ async fn receive_gateway_login(
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err, gp_params.has_client_identity()) {
|
||||
return tls;
|
||||
}
|
||||
if let Some(error) = err.take_body_read_error() {
|
||||
return PortalError::NetworkError(error).into();
|
||||
}
|
||||
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
|
||||
return anyhow::anyhow!(crate::error::AuthenticationRejected);
|
||||
}
|
||||
|
||||
@@ -111,7 +111,7 @@ pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
|
||||
let response = client.post(&url).form(&form).send().await?;
|
||||
let response = parse_gp_response(response).await?;
|
||||
let root = Element::parse(response.as_bytes())?;
|
||||
let status = parse_extend_session_status(&root, &response)?;
|
||||
let status = parse_extend_session_status(&root)?;
|
||||
|
||||
info!("Extend-session gateway response status: {}", status);
|
||||
|
||||
@@ -151,11 +151,11 @@ fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result<HashMap<Str
|
||||
Ok(form)
|
||||
}
|
||||
|
||||
fn parse_extend_session_status(root: &Element, response: &str) -> anyhow::Result<String> {
|
||||
fn parse_extend_session_status(root: &Element) -> anyhow::Result<String> {
|
||||
match root.attr("status") {
|
||||
Some(status) => Ok(status.to_string()),
|
||||
None => {
|
||||
warn!("Malformed extend-session response body: {}", response.trim());
|
||||
warn!("Extend-session response is missing status");
|
||||
bail!("Malformed extend session response")
|
||||
}
|
||||
}
|
||||
@@ -231,10 +231,7 @@ mod tests {
|
||||
fn parses_extend_session_status_attribute() {
|
||||
let root = Element::parse(r#"<response status="success"></response>"#.as_bytes()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
parse_extend_session_status(&root, r#"<response status="success"></response>"#).unwrap(),
|
||||
"success"
|
||||
);
|
||||
assert_eq!(parse_extend_session_status(&root).unwrap(), "success");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -242,9 +239,7 @@ mod tests {
|
||||
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
parse_extend_session_status(&root, "<response><result>ok</result></response>")
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
parse_extend_session_status(&root).unwrap_err().to_string(),
|
||||
"Malformed extend session response"
|
||||
);
|
||||
}
|
||||
|
||||
+40
-6
@@ -70,17 +70,17 @@ impl GuiVariant {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn preference_path() -> anyhow::Result<PathBuf> {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn preference_path(name: &str) -> anyhow::Result<PathBuf> {
|
||||
let dirs = directories::ProjectDirs::from("com.yuezk", "GlobalProtect-openconnect", "gpclient")
|
||||
.ok_or_else(|| anyhow::anyhow!("Failed to locate GUI preference directory"))?;
|
||||
Ok(dirs.config_dir().join("gui"))
|
||||
Ok(dirs.config_dir().join(name))
|
||||
}
|
||||
|
||||
pub fn preferred() -> anyhow::Result<GuiVariant> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
match std::fs::read_to_string(preference_path()?) {
|
||||
match std::fs::read_to_string(preference_path("gui")?) {
|
||||
Ok(value) => match value.trim() {
|
||||
"gpgui" => Ok(GuiVariant::Tauri),
|
||||
"gpgui-nsh" => Ok(GuiVariant::Nsh),
|
||||
@@ -96,12 +96,46 @@ pub fn preferred() -> anyhow::Result<GuiVariant> {
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn save_preference(variant: GuiVariant) -> anyhow::Result<()> {
|
||||
save_launch_preference("gui", variant.binary_name())
|
||||
}
|
||||
|
||||
pub const COMPATIBILITY_GRAPHICS_SUPPORTED: bool =
|
||||
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"));
|
||||
|
||||
pub const FORCE_SHARED_MEMORY: &str = "WEBKIT_DMABUF_RENDERER_FORCE_SHM";
|
||||
|
||||
const COMPATIBILITY_GRAPHICS: &str = "compatibility-graphics";
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
fn preference_path(_: &str) -> anyhow::Result<PathBuf> {
|
||||
anyhow::bail!("Compatibility graphics is unavailable")
|
||||
}
|
||||
|
||||
pub fn compatibility_graphics_enabled() -> bool {
|
||||
COMPATIBILITY_GRAPHICS_SUPPORTED && preference_path(COMPATIBILITY_GRAPHICS).is_ok_and(|path| path.is_file())
|
||||
}
|
||||
|
||||
pub fn set_compatibility_graphics(enabled: bool) -> anyhow::Result<()> {
|
||||
anyhow::ensure!(
|
||||
COMPATIBILITY_GRAPHICS_SUPPORTED,
|
||||
"Compatibility graphics is unavailable"
|
||||
);
|
||||
if enabled {
|
||||
return save_launch_preference(COMPATIBILITY_GRAPHICS, "enabled");
|
||||
}
|
||||
match std::fs::remove_file(preference_path(COMPATIBILITY_GRAPHICS)?) {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
result => result.map_err(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
fn save_launch_preference(name: &str, value: &str) -> anyhow::Result<()> {
|
||||
use std::io::Write;
|
||||
let path = preference_path()?;
|
||||
let path = preference_path(name)?;
|
||||
let directory = path.parent().unwrap();
|
||||
std::fs::create_dir_all(directory)?;
|
||||
let mut file = tempfile::NamedTempFile::new_in(directory)?;
|
||||
writeln!(file, "{}", variant.binary_name())?;
|
||||
writeln!(file, "{value}")?;
|
||||
file.persist(path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -45,3 +45,27 @@ mod tests {
|
||||
assert_eq!(serde_json::from_value::<HipSource>(json).unwrap(), source);
|
||||
}
|
||||
}
|
||||
|
||||
/// Collection metadata for the exact XML returned by a generated preview.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HipReport {
|
||||
pub xml: String,
|
||||
pub windows_updates: Option<WindowsUpdateStatus>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WindowsUpdateStatus {
|
||||
/// Present only when this report includes a completed local patch observation.
|
||||
pub checked_at: Option<u64>,
|
||||
/// Time of the observed snapshot when its patch details were too large to include.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub omitted_snapshot_at: Option<u64>,
|
||||
}
|
||||
|
||||
impl WindowsUpdateStatus {
|
||||
pub fn refresh_cursor(&self) -> Option<u64> {
|
||||
self.checked_at.or(self.omitted_snapshot_at)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,20 @@ pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified";
|
||||
type BoxedLogger = Box<dyn Log + Send + Sync>;
|
||||
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = OnceLock::new();
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
#[cfg(windows)]
|
||||
pub use windows::init_file;
|
||||
|
||||
/// Keep helper diagnostics with the application's records when a file logger owns them.
|
||||
pub fn diagnostic_writer() -> Box<dyn std::io::Write + Send> {
|
||||
#[cfg(windows)]
|
||||
if let Some(writer) = windows::diagnostic_writer() {
|
||||
return writer;
|
||||
}
|
||||
Box::new(std::io::stderr())
|
||||
}
|
||||
|
||||
pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if log_format == LogFormat::Text && macos_unified_log_enabled() {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
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,6 +173,12 @@ pub fn collect_profile_with_control(
|
||||
Some(identity) => identity.clone(),
|
||||
None => collect_with_host_id_and_control(host_id_override, control)?,
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let identity = if builder.client_os == ClientOs::Windows {
|
||||
windows::native_profile_identity(identity, host_id_override)?
|
||||
} else {
|
||||
identity
|
||||
};
|
||||
let runtime_os = runtime_client_os();
|
||||
// Preserve the old behavior: only probe the native version when reporting it.
|
||||
let (os_version, software_version) = if builder.client_os == runtime_os {
|
||||
@@ -181,7 +187,8 @@ pub fn collect_profile_with_control(
|
||||
(defaults::os_version(runtime_os), defaults::software_version(runtime_os))
|
||||
};
|
||||
control.check()?;
|
||||
Ok(builder.build(HostSnapshot {
|
||||
// The builder may carry cached hardware identity; use the resolved profile identity.
|
||||
Ok(builder.host_identity(identity.clone()).build(HostSnapshot {
|
||||
runtime_os,
|
||||
identity,
|
||||
os_version,
|
||||
|
||||
@@ -137,14 +137,24 @@ fn assert_mac(value: &str, separator: char) {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builder_delegates_default_identity_to_host_identity() {
|
||||
fn builder_preserves_supplied_hardware_fields() {
|
||||
let expected = collect_identity();
|
||||
let profile = collect_profile(
|
||||
OsProfileBuilder::new(runtime_client_os()).host_identity(expected.clone()),
|
||||
None,
|
||||
);
|
||||
|
||||
assert_eq!(profile.host_identity(), &expected);
|
||||
assert!(
|
||||
profile
|
||||
.host_identity()
|
||||
.computer()
|
||||
.eq_ignore_ascii_case(expected.computer())
|
||||
);
|
||||
assert_eq!(profile.host_identity().serialno(), expected.serialno());
|
||||
assert_eq!(profile.host_identity().mac_addr(), expected.mac_addr());
|
||||
if runtime_client_os() != ClientOs::Windows {
|
||||
assert_eq!(profile.host_identity().host_id(), expected.host_id());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -178,3 +188,76 @@ fn controlled_profile_collection_propagates_cancellation_and_deadline() {
|
||||
let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Linux), None, &expired).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn native_windows_profile_uses_installation_id_and_emulation_keeps_its_seed() {
|
||||
let identity = HostIdentity::from_parts(
|
||||
"test-host".into(),
|
||||
"hardware-seed".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let control = CollectionBudget::new(Duration::from_secs(60));
|
||||
let native = collect_profile_with_control(
|
||||
OsProfile::builder(ClientOs::Windows).host_identity(identity.clone()),
|
||||
None,
|
||||
&control,
|
||||
)
|
||||
.unwrap();
|
||||
// Read independently through the registry CLI to check the native API's source and view.
|
||||
let output = std::process::Command::new("reg")
|
||||
.args([
|
||||
"query",
|
||||
r"HKLM\SOFTWARE\Microsoft\Cryptography",
|
||||
"/v",
|
||||
"MachineGuid",
|
||||
"/reg:64",
|
||||
])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
let text = String::from_utf8(output.stdout).unwrap();
|
||||
let expected = text
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let mut parts = line.split_whitespace();
|
||||
(parts.next()? == "MachineGuid").then(|| parts.last().unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(native.host_id(), expected);
|
||||
assert_eq!(native.host_identity().host_id(), expected);
|
||||
assert!(native.computer().eq_ignore_ascii_case(&fallback_hostname()));
|
||||
let with_host_id = collect_profile_with_control(
|
||||
OsProfile::builder(ClientOs::Windows).host_identity(identity.clone()),
|
||||
Some("explicit-host-id"),
|
||||
&control,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(with_host_id.host_id(), "explicit-host-id");
|
||||
assert_eq!(with_host_id.computer(), native.computer());
|
||||
let overridden = collect_profile_with_control(
|
||||
OsProfile::builder(ClientOs::Windows)
|
||||
.host_identity(identity.clone())
|
||||
.computer_name_override("Custom-Host"),
|
||||
None,
|
||||
&control,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(overridden.computer(), "Custom-Host");
|
||||
|
||||
for client_os in [ClientOs::Mac, ClientOs::Linux] {
|
||||
let builder = OsProfile::builder(client_os).host_identity(identity.clone());
|
||||
let expected = builder.clone().build(HostSnapshot {
|
||||
runtime_os: ClientOs::Windows,
|
||||
identity: identity.clone(),
|
||||
os_version: String::new(),
|
||||
software_version: String::new(),
|
||||
});
|
||||
let actual = collect_profile_with_control(builder, None, &control).unwrap();
|
||||
assert_eq!(actual.host_identity(), &identity);
|
||||
assert_eq!(actual.host_id(), expected.host_id());
|
||||
assert_eq!(actual.serialno(), expected.serialno());
|
||||
assert_eq!(actual.mac_addr(), expected.mac_addr());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
use std::process::Command;
|
||||
use std::{io, os::windows::process::CommandExt, process::Command};
|
||||
use windows_sys::Win32::System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ, RRF_SUBKEY_WOW6464KEY, RegGetValueW};
|
||||
use windows_sys::Win32::System::SystemInformation::{ComputerNamePhysicalNetBIOS, GetComputerNameExW};
|
||||
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
|
||||
|
||||
use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id};
|
||||
|
||||
@@ -36,6 +39,7 @@ impl RuntimeNativeHostIdentity {
|
||||
|
||||
fn collect_windows_serial_number() -> Option<String> {
|
||||
let output = Command::new("wmic")
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.args(["bios", "get", "serialnumber"])
|
||||
.output()
|
||||
.ok()?;
|
||||
@@ -50,11 +54,15 @@ fn collect_windows_serial_number() -> Option<String> {
|
||||
}
|
||||
|
||||
fn windows_machine_seed() -> Option<String> {
|
||||
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
|
||||
collect_windows_csproduct_uuid().or_else(|| collect_windows_machine_guid().ok())
|
||||
}
|
||||
|
||||
fn collect_windows_csproduct_uuid() -> Option<String> {
|
||||
let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?;
|
||||
let output = Command::new("wmic")
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.args(["csproduct", "get", "uuid"])
|
||||
.output()
|
||||
.ok()?;
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
|
||||
stdout
|
||||
@@ -65,24 +73,63 @@ fn collect_windows_csproduct_uuid() -> Option<String> {
|
||||
.next()
|
||||
}
|
||||
|
||||
fn collect_windows_machine_guid() -> Option<String> {
|
||||
let output = Command::new("reg")
|
||||
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
// Native Windows uses the OS installation ID and physical NetBIOS name.
|
||||
// Keep the hardware identity used to seed other OS profiles unchanged.
|
||||
pub(super) fn native_profile_identity(
|
||||
identity: super::HostIdentity,
|
||||
host_id_override: Option<&str>,
|
||||
) -> io::Result<super::HostIdentity> {
|
||||
let host_id = match host_id_override.filter(|id| !id.trim().is_empty()) {
|
||||
Some(id) => id.to_owned(),
|
||||
None => collect_windows_machine_guid()?,
|
||||
};
|
||||
Ok(super::HostIdentity::from_parts(
|
||||
collect_windows_computer_name()?,
|
||||
host_id,
|
||||
identity.serialno().into(),
|
||||
identity.mac_addr().into(),
|
||||
))
|
||||
}
|
||||
|
||||
fn collect_windows_computer_name() -> io::Result<String> {
|
||||
let mut name = [0u16; 256];
|
||||
let mut size = name.len() as u32;
|
||||
// SAFETY: the buffer and character count describe writable UTF-16 storage.
|
||||
if unsafe { GetComputerNameExW(ComputerNamePhysicalNetBIOS, name.as_mut_ptr(), &mut size) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
String::from_utf16(&name[..size as usize]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
|
||||
}
|
||||
|
||||
stdout.lines().find_map(|line| {
|
||||
let mut parts = line.split_whitespace();
|
||||
if parts.next()? != "MachineGuid" {
|
||||
return None;
|
||||
}
|
||||
|
||||
parts.last().map(str::to_string)
|
||||
})
|
||||
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 {
|
||||
|
||||
@@ -124,8 +124,7 @@ impl OsProfile {
|
||||
self.runtime_os == self.client_os
|
||||
}
|
||||
|
||||
/// Default software version string for the target OS, matching the
|
||||
/// official client values.
|
||||
/// Software version for the target OS profile.
|
||||
pub fn software_version(&self) -> &str {
|
||||
&self.software_version
|
||||
}
|
||||
|
||||
@@ -18,14 +18,14 @@ fn negotiated_os_version_is_used_in_profile_and_user_agent() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csc_support_defaults_match_official_profiles() {
|
||||
fn csc_support_defaults_match_platform_profiles() {
|
||||
assert!(!ClientOs::Linux.default_csc_support());
|
||||
assert!(ClientOs::Mac.default_csc_support());
|
||||
assert!(ClientOs::Windows.default_csc_support());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prelogin_param_location_matches_official_profiles() {
|
||||
fn prelogin_param_location_matches_platform_profiles() {
|
||||
assert_eq!(
|
||||
OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build(test_snapshot())
|
||||
@@ -91,7 +91,7 @@ fn embedded_gateway_default_browser_is_zero_for_all() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_default_browser_values_match_official_profiles() {
|
||||
fn external_default_browser_values_match_platform_profiles() {
|
||||
assert_eq!(
|
||||
OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build(test_snapshot())
|
||||
@@ -132,7 +132,7 @@ fn external_default_browser_values_match_official_profiles() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saml_password_matches_official_profiles() {
|
||||
fn saml_password_matches_platform_profiles() {
|
||||
assert_eq!(
|
||||
OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build(test_snapshot())
|
||||
@@ -173,7 +173,7 @@ fn gateway_server_uses_resolved_ipv4_for_all() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kerberos_support_in_query_matches_official_profiles() {
|
||||
fn kerberos_support_in_query_matches_platform_profiles() {
|
||||
assert!(
|
||||
!OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build(test_snapshot())
|
||||
@@ -192,7 +192,7 @@ fn kerberos_support_in_query_matches_official_profiles() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_vendor_matches_official_profiles() {
|
||||
fn os_vendor_matches_platform_profiles() {
|
||||
assert_eq!(
|
||||
OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build(test_snapshot())
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::bail;
|
||||
use log::{debug, info, warn};
|
||||
use log::{info, warn};
|
||||
use reqwest::{Client, StatusCode};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
@@ -207,10 +207,13 @@ pub async fn retrieve_config(
|
||||
}
|
||||
})?;
|
||||
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
parse_gp_response(res).await.or_else(|mut err| {
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
|
||||
return Err(tls);
|
||||
}
|
||||
if let Some(error) = err.take_body_read_error() {
|
||||
return Err(PortalError::NetworkError(error).into());
|
||||
}
|
||||
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
|
||||
return Err(anyhow::anyhow!(crate::error::AuthenticationRejected));
|
||||
}
|
||||
@@ -232,7 +235,6 @@ pub async fn retrieve_config(
|
||||
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
|
||||
}
|
||||
|
||||
debug!("Portal config response received: {} bytes", res_xml.len());
|
||||
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||
|
||||
if csc::is_config_criteria(&root) {
|
||||
@@ -247,7 +249,6 @@ pub async fn retrieve_config(
|
||||
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
|
||||
result = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params) => result?,
|
||||
};
|
||||
debug!("Portal CSC config response received: {} bytes", csc_xml.len());
|
||||
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||
return parse_portal_policy(&server, cred, root, cancellation).await;
|
||||
}
|
||||
@@ -280,10 +281,13 @@ async fn retrieve_csc_config(
|
||||
}
|
||||
})?;
|
||||
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
parse_gp_response(res).await.or_else(|mut err| {
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
|
||||
return Err(tls);
|
||||
}
|
||||
if let Some(error) = err.take_body_read_error() {
|
||||
return Err(PortalError::NetworkError(error).into());
|
||||
}
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use anyhow::{anyhow, bail};
|
||||
use log::{debug, info, warn};
|
||||
use log::{info, warn};
|
||||
use reqwest::{Client, StatusCode};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
@@ -174,10 +174,8 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
|
||||
Err(anyhow!(PortalError::PreloginError(err.reason)))
|
||||
})?;
|
||||
|
||||
debug!("Prelogin response XML: {}", res_xml);
|
||||
|
||||
let prelogin = parse_prelogin_response(&res_xml, is_gateway).map_err(|err| {
|
||||
warn!("Parse response error, response: {}", res_xml);
|
||||
warn!("Failed to parse prelogin response: {err}");
|
||||
PortalError::PreloginError(err.to_string())
|
||||
})?;
|
||||
|
||||
|
||||
@@ -17,10 +17,17 @@ use super::{
|
||||
command_traits::CommandExt,
|
||||
};
|
||||
|
||||
use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_crash_exit};
|
||||
use super::rendering_recovery::{
|
||||
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;
|
||||
|
||||
#[cfg(windows)]
|
||||
/// The caller that receives foreground permission after browser authentication.
|
||||
pub const AUTH_PARENT_PROCESS_ID_ENV: &str = "GPAUTH_PARENT_PROCESS_ID";
|
||||
|
||||
pub struct SamlAuthLauncher<'a> {
|
||||
cancellation: CancellationToken,
|
||||
server: &'a str,
|
||||
@@ -49,6 +56,7 @@ pub struct SamlAuthLauncher<'a> {
|
||||
verbose: Option<&'a str>,
|
||||
log_format: LogFormat,
|
||||
dmabuf_disabled: bool,
|
||||
desktop_compatibility_graphics: bool,
|
||||
}
|
||||
|
||||
impl<'a> SamlAuthLauncher<'a> {
|
||||
@@ -81,9 +89,15 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
verbose: None,
|
||||
log_format: LogFormat::Text,
|
||||
dmabuf_disabled: false,
|
||||
desktop_compatibility_graphics: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn desktop_compatibility_graphics(mut self) -> Self {
|
||||
self.desktop_compatibility_graphics = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn dmabuf_disabled(mut self, disabled: bool) -> Self {
|
||||
self.dmabuf_disabled = disabled;
|
||||
self
|
||||
@@ -197,6 +211,8 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
/// argument that never gets appended.
|
||||
fn build_command(&self, program: &Path) -> Command {
|
||||
let mut auth_cmd = Command::new(program);
|
||||
#[cfg(windows)]
|
||||
auth_cmd.env(AUTH_PARENT_PROCESS_ID_ENV, std::process::id().to_string());
|
||||
auth_cmd.arg(self.server);
|
||||
|
||||
if self.gateway {
|
||||
@@ -292,15 +308,34 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
if embedded && bundled && self.dmabuf_disabled {
|
||||
command.env("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
|
||||
}
|
||||
let desktop_webview = embedded && bundled && self.desktop_compatibility_graphics;
|
||||
let can_use_shared_memory = desktop_webview && allows_shared_memory_override(&command, true);
|
||||
let use_shared_memory = can_use_shared_memory && crate::gui::compatibility_graphics_enabled();
|
||||
if use_shared_memory {
|
||||
command.env(crate::gui::FORCE_SHARED_MEMORY, "1");
|
||||
}
|
||||
let detect_gbm_failure = can_use_shared_memory && !use_shared_memory;
|
||||
let stdin = auth_stdin(self.browser);
|
||||
let cancellation = self.cancellation.clone();
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
#[cfg(feature = "logger")]
|
||||
let stderr = crate::logger::diagnostic_writer();
|
||||
#[cfg(not(feature = "logger"))]
|
||||
let stderr: Box<dyn std::io::Write + Send> = Box::new(std::io::stderr());
|
||||
let mut stderr = if desktop_webview {
|
||||
Box::new(std::io::LineWriter::new(AuthStderr(stderr)))
|
||||
} else {
|
||||
stderr
|
||||
};
|
||||
let gbm_failed = std::cell::Cell::new(false);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Authentication cancelled",
|
||||
))
|
||||
} else if gbm_failed.get() {
|
||||
Err(std::io::Error::other(GbmBufferFailure))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
@@ -310,19 +345,31 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
command,
|
||||
&check,
|
||||
Some(MAX_AUTH_RESULT_BYTES),
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut std::io::stderr(),
|
||||
&mut |bytes| {
|
||||
diagnostic.push(bytes);
|
||||
gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(can_recover));
|
||||
},
|
||||
&mut stderr,
|
||||
stdin,
|
||||
)?;
|
||||
Ok::<_, std::io::Error>((output.output, diagnostic.matched()))
|
||||
);
|
||||
std::io::Write::flush(&mut stderr)?;
|
||||
if gbm_failed.get() && !cancellation.is_cancelled() {
|
||||
return Err(GbmBufferFailure.into());
|
||||
}
|
||||
let output = output?;
|
||||
Ok::<_, anyhow::Error>((output.output, diagnostic.matched()))
|
||||
})
|
||||
.await?;
|
||||
let (output, rendering_diagnostic) = match output {
|
||||
Ok(output) => output,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
|
||||
Err(error)
|
||||
if error
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.is_some_and(|error| error.kind() == std::io::ErrorKind::Interrupted) =>
|
||||
{
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
|
||||
if self.cancellation.is_cancelled() {
|
||||
@@ -332,6 +379,26 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
// Attribute GBM failures to gpauth before forwarding them to the desktop supervisor.
|
||||
struct AuthStderr(Box<dyn std::io::Write + Send>);
|
||||
|
||||
impl std::io::Write for AuthStderr {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
for line in bytes.split_inclusive(|&byte| byte == b'\n') {
|
||||
if is_gbm_diagnostic(line) {
|
||||
self.0.write_all(&[AUTH_STDERR_PREFIX, line].concat())?;
|
||||
} else {
|
||||
self.0.write_all(line)?;
|
||||
}
|
||||
}
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.0.flush()
|
||||
}
|
||||
}
|
||||
|
||||
/// `gpauth --browser manual` reads the pasted `globalprotectcallback:` data from the user's terminal.
|
||||
fn auth_stdin(browser: Option<&str>) -> ChildInput<'static> {
|
||||
match browser {
|
||||
@@ -366,11 +433,14 @@ fn decode_auth_output(output: std::process::Output, rendering_failure: bool) ->
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::os_profile::{ClientOs, OsProfileBuilder};
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::process::ExitStatusExt;
|
||||
|
||||
#[test]
|
||||
fn server_tls_result_survives_process_decoding_as_a_typed_error() {
|
||||
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let output = std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com:8443","kind":"certificate"}}"#.to_vec(),
|
||||
@@ -389,7 +459,6 @@ mod tests {
|
||||
#[test]
|
||||
fn client_certificate_required_result_survives_process_decoding() {
|
||||
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let output = std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com","kind":"clientCertificateRequired"}}"#.to_vec(),
|
||||
@@ -487,6 +556,19 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn auth_child_receives_its_foreground_parent() {
|
||||
let command = SamlAuthLauncher::new("portal.example.com").build_command(Path::new("gpauth"));
|
||||
let parent = command
|
||||
.as_std()
|
||||
.get_envs()
|
||||
.find(|(name, _)| *name == AUTH_PARENT_PROCESS_ID_ENV)
|
||||
.and_then(|(_, value)| value)
|
||||
.expect("the authenticator must know its foreground recipient");
|
||||
assert_eq!(parent, std::process::id().to_string().as_str());
|
||||
}
|
||||
|
||||
/// gpauth writes to the same stderr as its parent, so a caller reading the
|
||||
/// parent's JSON would hit gpauth's text records mid-stream unless the format
|
||||
/// is passed down.
|
||||
@@ -549,11 +631,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
#[cfg(unix)]
|
||||
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()] {
|
||||
let error = decode_auth_output(
|
||||
std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(71 << 8),
|
||||
status,
|
||||
stdout,
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
@@ -566,7 +651,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn successful_malformed_auth_output_is_not_a_rendering_crash() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let error = decode_auth_output(
|
||||
std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
@@ -580,6 +664,7 @@ mod tests {
|
||||
assert_eq!(error.to_string(), "Failed to parse auth data");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn custom_authenticator_crash_does_not_request_recovery() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
@@ -615,8 +700,11 @@ mod tests {
|
||||
std::fs::write(&custom, "custom").unwrap();
|
||||
assert!(is_bundled_authenticator(&bundled, &bundled));
|
||||
assert!(!is_bundled_authenticator(&custom, &bundled));
|
||||
let alias = directory.path().join("auth-alias");
|
||||
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
|
||||
assert!(is_bundled_authenticator(&alias, &bundled));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let alias = directory.path().join("auth-alias");
|
||||
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
|
||||
assert!(is_bundled_authenticator(&alias, &bundled));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
use super::{
|
||||
command_runner::{ChildInput, run_observed},
|
||||
rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible_with_inheritance, is_crash_exit},
|
||||
rendering_recovery::{
|
||||
GbmBufferFailure, RenderingCrash, StderrDiagnostic, allows_shared_memory_override, eligible_with_inheritance,
|
||||
is_crash_exit,
|
||||
},
|
||||
};
|
||||
use crate::service::transport::SessionCredential;
|
||||
use anyhow::Context;
|
||||
use std::{
|
||||
cell::Cell,
|
||||
collections::HashMap,
|
||||
fs::OpenOptions,
|
||||
path::PathBuf,
|
||||
@@ -19,8 +23,10 @@ pub(super) async fn launch_desktop_child(
|
||||
envs: Option<&HashMap<String, String>>,
|
||||
credential: &SessionCredential,
|
||||
cancellation: &CancellationToken,
|
||||
detect_gbm_failure: bool,
|
||||
) -> anyhow::Result<ExitStatus> {
|
||||
let retry_eligible = eligible_with_inheritance(&command, envs.is_none());
|
||||
let detect_gbm_failure = detect_gbm_failure && allows_shared_memory_override(&command, envs.is_none());
|
||||
let log_file = match envs {
|
||||
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
|
||||
None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from),
|
||||
@@ -38,12 +44,15 @@ pub(super) async fn launch_desktop_child(
|
||||
let cancellation = cancellation.clone();
|
||||
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let gbm_failed = Cell::new(false);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Desktop child launch cancelled",
|
||||
))
|
||||
} else if gbm_failed.get() {
|
||||
Err(std::io::Error::other(GbmBufferFailure))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
@@ -53,10 +62,17 @@ pub(super) async fn launch_desktop_child(
|
||||
command,
|
||||
&check,
|
||||
None,
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut |bytes| {
|
||||
diagnostic.push(bytes);
|
||||
gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(retry_eligible));
|
||||
},
|
||||
&mut sink,
|
||||
ChildInput::Frame(&frame),
|
||||
)?;
|
||||
);
|
||||
if gbm_failed.get() && !cancellation.is_cancelled() {
|
||||
return Err(GbmBufferFailure.into());
|
||||
}
|
||||
let observed = observed?;
|
||||
let output = observed.output;
|
||||
if is_crash_exit(output.status) && retry_eligible && diagnostic.matched() {
|
||||
return Err(RenderingCrash { status: output.status }.into());
|
||||
|
||||
@@ -170,7 +170,11 @@ impl<'a> DesktopLauncher<'a> {
|
||||
}
|
||||
match outcome {
|
||||
Err(error) if recovery.recover(&error) => {
|
||||
warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows");
|
||||
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");
|
||||
}
|
||||
expecting_renewal = true;
|
||||
input.write_all(&[DESKTOP_RENDERING_RETRY]).await?;
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
self.envs,
|
||||
self.credential,
|
||||
cancellation,
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
|
||||
@@ -101,6 +101,12 @@ impl<'a> GuiLauncher<'a> {
|
||||
if let Some(envs) = &self.envs {
|
||||
cmd.env_clear().envs(envs);
|
||||
}
|
||||
if self.variant == crate::gui::GuiVariant::Tauri
|
||||
&& crate::gui::compatibility_graphics_enabled()
|
||||
&& super::rendering_recovery::allows_shared_memory_override(cmd.as_std(), self.envs.is_none())
|
||||
{
|
||||
cmd.env(crate::gui::FORCE_SHARED_MEMORY, "1");
|
||||
}
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
if self.minimized {
|
||||
cmd.arg("--minimized");
|
||||
@@ -112,6 +118,7 @@ impl<'a> GuiLauncher<'a> {
|
||||
self.envs.as_ref(),
|
||||
&self.credential,
|
||||
cancellation,
|
||||
self.variant == crate::gui::GuiVariant::Tauri,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -207,32 +214,45 @@ impl<'a> GuiLauncher<'a> {
|
||||
gui_switch::reply(&mut socket, Ok(GuiSwitchOutcome::DownloadRequired)).await?;
|
||||
return Ok(None);
|
||||
}
|
||||
service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?;
|
||||
pending = true;
|
||||
let credential = super::desktop_launcher::read_credential(service_output).await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?;
|
||||
anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||
let ready = gui_switch::SwitchListener::new()?;
|
||||
let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect());
|
||||
envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned());
|
||||
let launcher = Self::new(self.version, Arc::new(credential), variant)
|
||||
.envs(envs)
|
||||
.minimized(false);
|
||||
let program = match program {
|
||||
Some(program) => program,
|
||||
None => launcher.resolve_program(cancellation, command.theme).await?,
|
||||
};
|
||||
let mut child = launcher.start_owned(program, cancellation.child_token());
|
||||
let start_result = tokio::select! {
|
||||
result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => {
|
||||
result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result)
|
||||
},
|
||||
outcome = &mut child.task => {
|
||||
return match outcome? {
|
||||
Ok(status) => Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
}
|
||||
use super::rendering_recovery::{GbmBufferFailure, RecoveryState};
|
||||
let mut recovery = RecoveryState::default();
|
||||
let mut program = program;
|
||||
let (mut child, start_result) = loop {
|
||||
service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?;
|
||||
pending = true;
|
||||
let credential = super::desktop_launcher::read_credential(service_output).await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?;
|
||||
anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||
let ready = gui_switch::SwitchListener::new()?;
|
||||
let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect());
|
||||
envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned());
|
||||
let launcher = Self::new(self.version, Arc::new(credential), variant)
|
||||
.envs(envs)
|
||||
.minimized(false);
|
||||
let executable = match &program {
|
||||
Some(program) => program.clone(),
|
||||
None => launcher.resolve_program(cancellation, command.theme).await?,
|
||||
};
|
||||
let mut child = launcher.start_owned(executable.clone(), cancellation.child_token());
|
||||
let start_result = tokio::select! {
|
||||
result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => {
|
||||
result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result)
|
||||
},
|
||||
outcome = &mut child.task => {
|
||||
match outcome? {
|
||||
Ok(status) => return Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")),
|
||||
Err(error) if error.is::<GbmBufferFailure>() && recovery.recover(&error) => {
|
||||
log::warn!("{error}; restarting the selected GUI with compatibility graphics");
|
||||
service_input.write_all(&[DESKTOP_SWITCH_CANCEL]).await?;
|
||||
pending = false;
|
||||
program = Some(executable);
|
||||
continue;
|
||||
}
|
||||
Err(error) => return Err(recovery.terminal(error)),
|
||||
}
|
||||
}
|
||||
};
|
||||
break (child, start_result);
|
||||
};
|
||||
if let Err(error) = start_result.and_then(|()| crate::gui::save_preference(variant)) {
|
||||
child.cancel.cancel();
|
||||
|
||||
@@ -22,9 +22,9 @@ pub mod auth_launcher;
|
||||
pub mod desktop_launcher;
|
||||
#[cfg(unix)]
|
||||
pub mod gui_launcher;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
pub mod gui_switch;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
mod nsh_runtime;
|
||||
#[cfg(unix)]
|
||||
pub mod users;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
use std::process::{Command, ExitStatus};
|
||||
|
||||
const DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";
|
||||
pub const MAIN_WEBVIEW_INITIALIZED: &str = "GP Connect main webview initialized";
|
||||
const GBM_DIAGNOSTIC: &[u8] = b"Failed to create GBM buffer";
|
||||
pub(crate) const AUTH_STDERR_PREFIX: &[u8] = b"gpauth stderr: ";
|
||||
const DIAGNOSTIC: &[u8] = b"Error 71 (Protocol error) dispatching to Wayland display";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -16,20 +19,33 @@ pub struct RecoveryFailed(#[source] anyhow::Error);
|
||||
#[derive(Default)]
|
||||
pub struct RecoveryState {
|
||||
first_failure: Option<String>,
|
||||
shared_memory: bool,
|
||||
}
|
||||
|
||||
impl RecoveryState {
|
||||
pub fn dmabuf_disabled(&self) -> bool {
|
||||
self.first_failure.is_some()
|
||||
self.first_failure.is_some() && !self.shared_memory
|
||||
}
|
||||
|
||||
pub fn shared_memory(&self) -> bool {
|
||||
self.shared_memory
|
||||
}
|
||||
|
||||
pub fn recover(&mut self, error: &anyhow::Error) -> bool {
|
||||
if self.first_failure.is_none() && error.downcast_ref::<RenderingCrash>().is_some() {
|
||||
self.first_failure = Some(error.to_string());
|
||||
true
|
||||
} else {
|
||||
false
|
||||
if self.first_failure.is_some() {
|
||||
return false;
|
||||
}
|
||||
let gbm_failure = error.downcast_ref::<GbmBufferFailure>().is_some();
|
||||
if !gbm_failure && error.downcast_ref::<RenderingCrash>().is_none() {
|
||||
return false;
|
||||
}
|
||||
if gbm_failure && let Err(error) = crate::gui::set_compatibility_graphics(true) {
|
||||
log::warn!("Could not save compatibility graphics setting: {error:#}");
|
||||
return false;
|
||||
}
|
||||
self.first_failure = Some(error.to_string());
|
||||
self.shared_memory = gbm_failure;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn terminal(&self, error: anyhow::Error) -> anyhow::Error {
|
||||
@@ -70,6 +86,16 @@ pub(crate) fn eligible_with_inheritance(command: &Command, inherits: bool) -> bo
|
||||
&& effective_env(command, DMABUF, inherits).is_none()
|
||||
}
|
||||
|
||||
pub(crate) fn allows_shared_memory_override(command: &Command, inherits: bool) -> bool {
|
||||
crate::gui::COMPATIBILITY_GRAPHICS_SUPPORTED
|
||||
&& effective_env(command, DMABUF, inherits).is_none()
|
||||
&& effective_env(command, crate::gui::FORCE_SHARED_MEMORY, inherits).is_none()
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("WebKit failed to create a GBM buffer")]
|
||||
pub(crate) struct GbmBufferFailure;
|
||||
|
||||
fn effective_env(command: &Command, key: &str, inherits: bool) -> Option<std::ffi::OsString> {
|
||||
for (name, value) in command.get_envs() {
|
||||
if name == key {
|
||||
@@ -79,12 +105,21 @@ fn effective_env(command: &Command, key: &str, inherits: bool) -> Option<std::ff
|
||||
inherits.then(|| std::env::var_os(key)).flatten()
|
||||
}
|
||||
|
||||
pub(crate) fn is_gbm_diagnostic(line: &[u8]) -> bool {
|
||||
!line.starts_with(AUTH_STDERR_PREFIX)
|
||||
&& line
|
||||
.windows(GBM_DIAGNOSTIC.len())
|
||||
.any(|message| message == GBM_DIAGNOSTIC)
|
||||
}
|
||||
|
||||
/// Observes diagnostic lines without retaining arbitrary application output.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct StderrDiagnostic {
|
||||
line: Vec<u8>,
|
||||
overflow: bool,
|
||||
matched: bool,
|
||||
gbm_failed: bool,
|
||||
main_webview_initialized: bool,
|
||||
}
|
||||
|
||||
impl StderrDiagnostic {
|
||||
@@ -104,6 +139,14 @@ impl StderrDiagnostic {
|
||||
|
||||
fn check_line(&mut self) {
|
||||
let line = self.line.trim_ascii_end();
|
||||
if !self.overflow {
|
||||
if line == MAIN_WEBVIEW_INITIALIZED.as_bytes() {
|
||||
self.main_webview_initialized = true;
|
||||
}
|
||||
if !self.main_webview_initialized && is_gbm_diagnostic(line) {
|
||||
self.gbm_failed = true;
|
||||
}
|
||||
}
|
||||
let message = line.strip_suffix(b".").unwrap_or(line);
|
||||
if !self.overflow
|
||||
&& (line.starts_with(b"Gdk-Message:")
|
||||
@@ -117,6 +160,10 @@ impl StderrDiagnostic {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn should_retry_gbm(&self, can_retry_wayland: bool) -> bool {
|
||||
self.gbm_failed && !(can_retry_wayland && self.matched)
|
||||
}
|
||||
|
||||
pub(crate) fn matched(&mut self) -> bool {
|
||||
self.check_line();
|
||||
self.matched
|
||||
@@ -127,6 +174,43 @@ impl StderrDiagnostic {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detects_gbm_failure_before_main_webview_initializes() {
|
||||
for line in [
|
||||
b"Failed to create GBM buffer of size 280x404: Invalid argument\n".as_slice(),
|
||||
b"(WebKitWebProcess:42): Warning: Failed to create GBM buffer\n",
|
||||
b"gpauth: Failed to create GBM buffer\n",
|
||||
] {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
for bytes in line.chunks(7) {
|
||||
observer.push(bytes);
|
||||
}
|
||||
assert!(observer.gbm_failed);
|
||||
assert!(!observer.matched());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_gbm_failure_after_startup_and_from_auth_stderr() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
observer
|
||||
.push(b"gpauth stderr: (WebKitWebProcess:42): Failed to create GBM buffer of size 900x648: Invalid argument\n");
|
||||
assert!(!observer.gbm_failed);
|
||||
observer.push(format!("{MAIN_WEBVIEW_INITIALIZED}\n").as_bytes());
|
||||
observer.push(b"Failed to create GBM buffer of size 840x640: Invalid argument\n");
|
||||
assert!(!observer.gbm_failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_wayland_retry_when_both_diagnostics_are_observed() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
observer.push(b"Failed to create GBM buffer of size 280x404: Invalid argument\n");
|
||||
observer.push(b"Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display.\n");
|
||||
assert!(observer.matched());
|
||||
assert!(!observer.should_retry_gbm(true));
|
||||
assert!(observer.should_retry_gbm(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognizes_split_diagnostic_without_matching_quoted_warning() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
@@ -198,6 +282,7 @@ mod tests {
|
||||
assert!(!eligible_with_inheritance(&command, false));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_is_once_and_preserves_cancellation_and_both_failures() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
@@ -219,6 +304,7 @@ mod tests {
|
||||
assert!(error.to_string().contains("71"));
|
||||
assert!(error.to_string().contains("second exit 72"));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn explicit_termination_is_not_a_rendering_crash() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
@@ -424,6 +424,8 @@ pub struct UpdateLogLevelRequest(pub String);
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub enum WsRequest {
|
||||
SetTunnelStatisticsEnabled { enabled: bool },
|
||||
SetWindowsPatchInterest { enabled: bool },
|
||||
RefreshWindowsPatches { after: Option<u64> },
|
||||
Connect(Box<ConnectRequest>),
|
||||
Disconnect(DisconnectRequest),
|
||||
StopNonTunnelAttachment { connection_id: uuid::Uuid },
|
||||
|
||||
@@ -55,6 +55,8 @@ pub enum ServiceResult {
|
||||
offset: usize,
|
||||
xml: String,
|
||||
complete: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
windows_updates: Option<crate::hip::WindowsUpdateStatus>,
|
||||
},
|
||||
HipApprovalStatus(HipApprovalStatus),
|
||||
NoSubmittedHipReport,
|
||||
|
||||
@@ -172,6 +172,7 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn cancellation_kills_and_joins_the_running_resolver_process() {
|
||||
let file = tempfile::NamedTempFile::new().unwrap();
|
||||
|
||||
@@ -164,6 +164,7 @@ async fn post(
|
||||
crate::utils::request::ResponseBodyError::Transport(error) => GatewayRequestError::Transport(error),
|
||||
crate::utils::request::ResponseBodyError::TooLarge => GatewayRequestError::ResponseTooLarge,
|
||||
})?;
|
||||
crate::utils::log_response_xml(&format!("/ssl-vpn/{endpoint}"), status, &body);
|
||||
parse_response(&body)
|
||||
}
|
||||
|
||||
|
||||
@@ -204,6 +204,7 @@ impl Signer for ClientSigner {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
use openssl::{
|
||||
hash::MessageDigest,
|
||||
pkey::PKey,
|
||||
@@ -220,6 +221,7 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
fn native_key(bytes: &[u8]) -> ClientKey {
|
||||
let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes))
|
||||
.unwrap()
|
||||
@@ -227,6 +229,7 @@ mod tests {
|
||||
ClientKey::load(&key).unwrap()
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[test]
|
||||
fn rsa_signatures_use_the_offered_scheme_and_tls_pss_salt_length() {
|
||||
let bytes = fixture("rsa-pkcs8.pem");
|
||||
@@ -255,6 +258,7 @@ mod tests {
|
||||
assert!(key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).is_none());
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[test]
|
||||
fn p256_signatures_verify_with_an_independent_backend() {
|
||||
let bytes = fixture("ec-pkcs8.pem");
|
||||
@@ -281,6 +285,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "openssl-tests")]
|
||||
#[test]
|
||||
fn a_key_remains_usable_when_shared_clients_sign_concurrently() {
|
||||
let key = native_key(&fixture("rsa-pkcs8.pem"));
|
||||
|
||||
@@ -13,6 +13,8 @@ mod identity_encoding;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod lock_file;
|
||||
pub mod redact;
|
||||
mod response_log;
|
||||
pub(crate) use response_log::log_response_xml;
|
||||
pub mod request;
|
||||
#[cfg(feature = "tauri")]
|
||||
pub mod window;
|
||||
@@ -53,16 +55,23 @@ pub fn remove_url_scheme(s: &str) -> String {
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
#[error("GP response error: reason={reason}, status={status}, body={body}")]
|
||||
#[error("GP response error: reason={reason}, status={status}")]
|
||||
pub struct GpError {
|
||||
pub status: StatusCode,
|
||||
pub reason: String,
|
||||
body: String,
|
||||
#[source]
|
||||
source: Option<reqwest::Error>,
|
||||
}
|
||||
|
||||
impl GpError {
|
||||
pub(crate) fn take_body_read_error(&mut self) -> Option<reqwest::Error> {
|
||||
if self.is_status_error() {
|
||||
None
|
||||
} else {
|
||||
self.source.take()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_status_error(&self) -> bool {
|
||||
self.status.is_client_error() || self.status.is_server_error()
|
||||
}
|
||||
@@ -79,16 +88,20 @@ pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError>
|
||||
return Err(parse_gp_error(res).await);
|
||||
}
|
||||
|
||||
res.text().await.map_err(|err| {
|
||||
let path = log::log_enabled!(log::Level::Debug).then(|| res.url().path().to_owned());
|
||||
let body = res.text().await.map_err(|err| {
|
||||
warn!("Failed to read response: {}", err);
|
||||
|
||||
GpError {
|
||||
status,
|
||||
reason: "failed to read response".to_string(),
|
||||
body: "<failed to read response>".to_string(),
|
||||
source: Some(err),
|
||||
}
|
||||
})
|
||||
})?;
|
||||
if let Some(path) = path {
|
||||
log_response_xml(&path, status, body.as_bytes());
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
async fn parse_gp_error(res: Response) -> GpError {
|
||||
@@ -99,15 +112,16 @@ async fn parse_gp_error(res: Response) -> GpError {
|
||||
.map_or_else(|| "<none>", |v| v.to_str().unwrap_or("<invalid header>"))
|
||||
.to_string();
|
||||
|
||||
let (body, source) = match res.text().await {
|
||||
Ok(body) => (if body.is_empty() { "<empty>".to_string() } else { body }, None),
|
||||
Err(error) => ("<failed to read response>".to_string(), Some(error)),
|
||||
let path = log::log_enabled!(log::Level::Debug).then(|| res.url().path().to_owned());
|
||||
let source = match res.text().await {
|
||||
Ok(body) => {
|
||||
if let Some(path) = path {
|
||||
log_response_xml(&path, status, body.as_bytes());
|
||||
}
|
||||
None
|
||||
}
|
||||
Err(error) => Some(error),
|
||||
};
|
||||
|
||||
GpError {
|
||||
status,
|
||||
reason,
|
||||
body,
|
||||
source,
|
||||
}
|
||||
GpError { status, reason, source }
|
||||
}
|
||||
@@ -266,6 +266,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn unencrypted_key_ignores_unused_password_and_archive_owned_file_is_private() {
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let identity = ClientIdentity::from_data(
|
||||
Zeroizing::new(CERTIFICATE.to_vec()),
|
||||
@@ -280,6 +281,7 @@ mod tests {
|
||||
let path = files.certificate().to_owned();
|
||||
assert!(path.ends_with(".p12"));
|
||||
assert!(files.key().is_none());
|
||||
#[cfg(unix)]
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
drop(files);
|
||||
assert!(!Path::new(&path).exists());
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
use gp_xml::redact_xml;
|
||||
use reqwest::StatusCode;
|
||||
|
||||
pub(crate) fn log_response_xml(path: &str, status: StatusCode, body: &[u8]) {
|
||||
if !log::log_enabled!(log::Level::Debug) {
|
||||
return;
|
||||
}
|
||||
// Redirect paths can themselves contain authentication tokens.
|
||||
let endpoint = match path {
|
||||
"/global-protect/prelogin.esp"
|
||||
| "/ssl-vpn/prelogin.esp"
|
||||
| "/global-protect/getconfig.esp"
|
||||
| "/global-protect/getconfig_csc.esp"
|
||||
| "/ssl-vpn/login.esp"
|
||||
| "/ssl-vpn/getconfig.esp"
|
||||
| "/ssl-vpn/agentmessage.esp"
|
||||
| "/ssl-vpn/hipreportcheck.esp"
|
||||
| "/ssl-vpn/hipreport.esp"
|
||||
| "/ssl-vpn/logout.esp" => path,
|
||||
_ => "[response endpoint]",
|
||||
};
|
||||
// Individual XML lines remain readable in macOS unified logs with limited record sizes.
|
||||
for line in redact_xml(body).lines() {
|
||||
log::debug!("{endpoint} response XML (HTTP {}): {line}", status.as_u16());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use xmltree::Element;
|
||||
|
||||
#[test]
|
||||
fn preserves_policy_checks_and_redacts_authentication_material() {
|
||||
let input = include_str!("../../tests/fixtures/portal-response.xml");
|
||||
let xml = redact_xml(input.as_bytes());
|
||||
let root = Element::parse(xml.as_bytes()).unwrap();
|
||||
assert!(xml.contains("custom-checks") && xml.contains("HipID") && xml.contains("NV Domain"));
|
||||
assert!(xml.contains("Corp.Example.test"));
|
||||
assert!(xml.contains("com.1password.1password") && xml.contains("Version"));
|
||||
for secret in [
|
||||
"fixture-user-cookie",
|
||||
"fixture-prelogon-cookie",
|
||||
"fixture-csc-cookie",
|
||||
"fixture-username",
|
||||
"fixture-saml",
|
||||
"fixture-attribute-token",
|
||||
"fixture-property-password",
|
||||
"fixture-cookie-name",
|
||||
"fixture-query-token",
|
||||
"fixture-url-password",
|
||||
"fixture-comment",
|
||||
"fixture-pi",
|
||||
] {
|
||||
assert!(!xml.contains(secret), "secret retained: {secret}");
|
||||
}
|
||||
assert_eq!(root.name, "policy");
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0"?>
|
||||
<?fixture fixture-pi?>
|
||||
<policy>
|
||||
<!--fixture-comment-->
|
||||
<portal-userauthcookie>fixture-user-cookie</portal-userauthcookie>
|
||||
<portal-prelogonuserauthcookie><![CDATA[fixture-prelogon-cookie]]></portal-prelogonuserauthcookie>
|
||||
<portal-csc-auth-cookie>fixture-csc-cookie</portal-csc-auth-cookie>
|
||||
<username>fixture-username</username>
|
||||
<saml-request>fixture-saml</saml-request>
|
||||
<property name="password" value="fixture-property-password"/>
|
||||
<cookie name="fixture-cookie-name"/>
|
||||
<settings auth_token="fixture-attribute-token"/>
|
||||
<download href="https://user:[email protected]/client?auth=fixture-query-token"/>
|
||||
<hip-collection>
|
||||
<hip-report-interval>3600</hip-report-interval>
|
||||
<collect-hip-data>yes</collect-hip-data>
|
||||
<custom-checks>
|
||||
<mac-os><plist><entry name="com.paloaltonetworks.GlobalProtect.settings"><key><member>HipID</member></key></entry><entry name="com.1password.1password"><key><member>Version</member></key></entry></plist></mac-os>
|
||||
<windows><registry-key><entry name="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"><registry-value><member>Domain</member><member>NV Domain</member></registry-value></entry></registry-key></windows>
|
||||
</custom-checks>
|
||||
</hip-collection>
|
||||
<domain>Corp.Example.test</domain>
|
||||
</policy>
|
||||
@@ -93,12 +93,19 @@ fn traditional_encrypted_pem_preserves_password_errors() {
|
||||
let result = load(&certificate, &key, password);
|
||||
if password == Some(PASSWORD) {
|
||||
let identity = result.unwrap_or_else(|error| panic!("{key:?}: {error}"));
|
||||
let actual = openssl::pkey::PKey::private_key_from_pem(identity.key_data().unwrap()).unwrap();
|
||||
let expected = openssl::pkey::PKey::private_key_from_pem(&bytes(&format!("{algorithm}-pkcs8.pem"))).unwrap();
|
||||
assert!(
|
||||
actual.public_eq(&expected),
|
||||
"{key:?}: imported key differs from the fixture"
|
||||
);
|
||||
let public_key = |pem: &[u8]| {
|
||||
let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(pem))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
rustls::crypto::ring::sign::any_supported_type(&key)
|
||||
.unwrap()
|
||||
.public_key()
|
||||
.unwrap()
|
||||
.into_owned()
|
||||
};
|
||||
let actual = public_key(identity.key_data().unwrap());
|
||||
let expected = public_key(&bytes(&format!("{algorithm}-pkcs8.pem")));
|
||||
assert!(actual == expected, "{key:?}: imported key differs from the fixture");
|
||||
assert!(identity.key_password().is_none());
|
||||
} else {
|
||||
let error = result.unwrap_err();
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
use std::sync::Mutex;
|
||||
|
||||
use gpapi::utils::parse_gp_response;
|
||||
use log::{LevelFilter, Log, Metadata, Record};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpListener,
|
||||
};
|
||||
|
||||
struct Capture(Mutex<Vec<String>>);
|
||||
static LOGS: Capture = Capture(Mutex::new(Vec::new()));
|
||||
impl Log for Capture {
|
||||
fn enabled(&self, _: &Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
fn log(&self, record: &Record<'_>) {
|
||||
if record.target() == "gpapi::utils::response_log" {
|
||||
self.0.lock().unwrap().push(record.args().to_string());
|
||||
}
|
||||
}
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
async fn response(path: &str, status: &str, body: &str) -> reqwest::Response {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let data = format!(
|
||||
"HTTP/1.1 {status}\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut request = [0; 4096];
|
||||
socket.read(&mut request).await.unwrap();
|
||||
socket.write_all(data.as_bytes()).await.unwrap();
|
||||
});
|
||||
reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(format!("http://{address}{path}"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn logs_redacted_xml_at_debug_without_changing_responses_or_exposing_error_bodies() {
|
||||
rustls::crypto::ring::default_provider().install_default().unwrap();
|
||||
log::set_logger(&LOGS).unwrap();
|
||||
log::set_max_level(LevelFilter::Debug);
|
||||
let portal = include_str!("fixtures/portal-response.xml");
|
||||
for path in [
|
||||
"/global-protect/getconfig.esp",
|
||||
"/global-protect/getconfig_csc.esp",
|
||||
"/global-protect/prelogin.esp",
|
||||
"/ssl-vpn/login.esp",
|
||||
] {
|
||||
let result = parse_gp_response(response(path, "200 OK", portal).await).await.unwrap();
|
||||
assert_eq!(result, portal);
|
||||
}
|
||||
let logs = LOGS.0.lock().unwrap().join("\n");
|
||||
assert!(logs.contains("getconfig.esp response XML"));
|
||||
assert!(logs.contains("getconfig_csc.esp response XML"));
|
||||
assert!(logs.contains("prelogin.esp response XML"));
|
||||
assert!(logs.contains("login.esp response XML"));
|
||||
assert!(logs.contains("custom-checks") && logs.contains("HipID"));
|
||||
for secret in [
|
||||
"fixture-user-cookie",
|
||||
"fixture-prelogon-cookie",
|
||||
"fixture-csc-cookie",
|
||||
"fixture-username",
|
||||
"fixture-saml",
|
||||
"fixture-attribute-token",
|
||||
"fixture-property-password",
|
||||
"fixture-cookie-name",
|
||||
"fixture-query-token",
|
||||
"fixture-url-password",
|
||||
"fixture-comment",
|
||||
"fixture-pi",
|
||||
] {
|
||||
assert!(!logs.contains(secret), "logged secret: {secret}");
|
||||
}
|
||||
|
||||
let error = parse_gp_response(response("/global-protect/getconfig.esp", "403 Forbidden", portal).await)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.status, reqwest::StatusCode::FORBIDDEN);
|
||||
assert!(!format!("{error:?} {error}").contains("fixture-"));
|
||||
assert!(LOGS.0.lock().unwrap().iter().any(|line| line.contains("HTTP 403")));
|
||||
|
||||
let error = parse_gp_response(
|
||||
response(
|
||||
"/global-protect/getconfig.esp",
|
||||
"500 Internal Server Error",
|
||||
"<html><body>fixture-error-secret</body></html>",
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(!format!("{error:?} {error}").contains("fixture-error-secret"));
|
||||
assert!(!LOGS.0.lock().unwrap().join("\n").contains("fixture-error-secret"));
|
||||
|
||||
LOGS.0.lock().unwrap().clear();
|
||||
let body = "<jnlp><application-desc><argument>fixture-login-cookie</argument></application-desc></jnlp>";
|
||||
parse_gp_response(response("/redirect/fixture-path-token?token=fixture-query-token", "200 OK", body).await)
|
||||
.await
|
||||
.unwrap();
|
||||
let logs = LOGS.0.lock().unwrap().join("\n");
|
||||
assert!(logs.contains("[response endpoint]"));
|
||||
assert!(!logs.contains("fixture-"));
|
||||
|
||||
LOGS.0.lock().unwrap().clear();
|
||||
log::set_max_level(LevelFilter::Info);
|
||||
assert_eq!(
|
||||
parse_gp_response(response("/global-protect/getconfig.esp", "200 OK", portal).await)
|
||||
.await
|
||||
.unwrap(),
|
||||
portal
|
||||
);
|
||||
assert!(LOGS.0.lock().unwrap().is_empty());
|
||||
}
|
||||
@@ -19,3 +19,7 @@ xmltree.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
uzers.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.62", features = ["Win32_Networking_ActiveDirectory", "Win32_System_SystemInformation"] }
|
||||
log.workspace = true
|
||||
@@ -0,0 +1,12 @@
|
||||
//! Generate native Windows posture on Windows, or a Windows emulation preview elsewhere.
|
||||
use gpapi::os_profile::{ClientOs, OsProfile};
|
||||
use gphip::{ReportContext, ReportInput};
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let input = ReportInput {
|
||||
profile: gpapi::os_profile::desktop::collect_profile(OsProfile::builder(ClientOs::Windows), None),
|
||||
context: ReportContext::Preview,
|
||||
};
|
||||
println!("{}", gphip::generate_report(&input)?);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Native macOS Active Directory domain collection.
|
||||
use gpapi::process::collection::CollectorCommands;
|
||||
use std::{io, path::Path};
|
||||
|
||||
pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result<String> {
|
||||
let Some(output) = commands.run_executable(Path::new("/usr/sbin/dsconfigad"), &["-show"])? else {
|
||||
return Ok(String::new());
|
||||
};
|
||||
let text = String::from_utf8(output.stdout).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
|
||||
// A nonzero exit status does not invalidate a reported domain.
|
||||
Ok(parse_domain(&text))
|
||||
}
|
||||
|
||||
fn parse_domain(output: &str) -> String {
|
||||
output
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let (label, value) = line.split_once('=')?;
|
||||
(label.trim() == "Active Directory Domain").then(|| value.trim().to_owned())
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_ad_domain_without_using_other_domain_fields() {
|
||||
assert_eq!(
|
||||
parse_domain(
|
||||
"Forest = forest.test\nActive Directory Domain = Corp.Example.test \t\r\nComputer Account = HOST$\n"
|
||||
),
|
||||
"Corp.Example.test"
|
||||
);
|
||||
assert_eq!(
|
||||
parse_domain("Active Directory Domain = first.test\nActive Directory Domain = second.test\n"),
|
||||
"first.test"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbound_or_empty_domain_stays_empty() {
|
||||
for output in [
|
||||
"",
|
||||
"Not bound to Active Directory\n",
|
||||
"Forest = forest.test\n",
|
||||
"Active Directory Domain = \t\n",
|
||||
] {
|
||||
assert_eq!(parse_domain(output), "");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Native Linux and BSD computer-domain collection.
|
||||
use std::io;
|
||||
|
||||
#[cfg(unix)]
|
||||
use gpapi::process::collection::CollectorCommands;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result<String> {
|
||||
linux_domain(|program, args| read(commands, program, args))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "freebsd")]
|
||||
pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result<String> {
|
||||
read(commands, "hostname", &["-d"])
|
||||
}
|
||||
|
||||
#[cfg(target_os = "openbsd")]
|
||||
pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result<String> {
|
||||
read(commands, "hostname", &[]).map(|hostname| hostname_domain(&hostname))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn read(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<String> {
|
||||
let Some(output) = commands.run(program, args)? else {
|
||||
return Ok(String::new());
|
||||
};
|
||||
let text = String::from_utf8(output.stdout).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
|
||||
// A nonzero exit status does not invalidate a reported domain.
|
||||
Ok(first_line(&text))
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
fn linux_domain(mut read: impl FnMut(&str, &[&str]) -> io::Result<String>) -> io::Result<String> {
|
||||
let realm = read("realm", &["list", "--name-only"])?;
|
||||
if !realm.is_empty() {
|
||||
return Ok(realm);
|
||||
}
|
||||
read("dnsdomainname", &[])
|
||||
}
|
||||
|
||||
fn first_line(output: &str) -> String {
|
||||
output.lines().next().unwrap_or_default().trim().to_owned()
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "openbsd", test))]
|
||||
fn hostname_domain(hostname: &str) -> String {
|
||||
hostname
|
||||
.split_once('.')
|
||||
.map(|(_, domain)| domain)
|
||||
.unwrap_or_default()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn uses_first_stdout_line_even_with_nonzero_exit() {
|
||||
let budget = gpapi::collection::CollectionBudget::new(std::time::Duration::from_secs(5));
|
||||
let commands = CollectorCommands::new(&budget);
|
||||
let domain = read(
|
||||
&commands,
|
||||
"sh",
|
||||
&["-c", "printf ' Corp.Example.test \\nsecond.test\\n'; exit 7"],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(domain, "Corp.Example.test");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_prefers_realm_and_only_queries_dns_when_empty() {
|
||||
let realm = linux_domain(|program, args| {
|
||||
assert_eq!(program, "realm");
|
||||
assert_eq!(args, ["list", "--name-only"]);
|
||||
Ok("Corp.Example.test".into())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(realm, "Corp.Example.test");
|
||||
|
||||
let mut calls = Vec::new();
|
||||
let dns = linux_domain(|program, _| {
|
||||
calls.push(program.to_string());
|
||||
if program == "realm" {
|
||||
Ok(String::new())
|
||||
} else {
|
||||
Ok("dns.example.test".into())
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(calls, ["realm", "dnsdomainname"]);
|
||||
assert_eq!(dns, "dns.example.test");
|
||||
assert_eq!(linux_domain(|_, _| Ok(String::new())).unwrap(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interrupted_collection_does_not_continue_to_dns() {
|
||||
let result = linux_domain(|program, _| {
|
||||
assert_eq!(program, "realm");
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
});
|
||||
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_only_first_line_and_preserves_domain_case() {
|
||||
assert_eq!(first_line(" Corp.Example.test \r\nsecond.test\n"), "Corp.Example.test");
|
||||
assert_eq!(first_line("\nsecond.test\n"), "");
|
||||
assert_eq!(first_line(""), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openbsd_uses_hostname_suffix_without_inventing_a_domain() {
|
||||
assert_eq!(hostname_domain("host.Corp.Example.test"), "Corp.Example.test");
|
||||
assert_eq!(hostname_domain("host"), "");
|
||||
assert_eq!(hostname_domain("host."), "");
|
||||
assert_eq!(hostname_domain(""), "");
|
||||
}
|
||||
}
|
||||
+337
-44
@@ -9,11 +9,20 @@ use gpapi::collection::{CollectionBudget, CollectionControl};
|
||||
use gpapi::process::collection::CollectorCommands;
|
||||
use xmltree::Element;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod domain_macos;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
mod domain_unix;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod sentinel_macos;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
mod sentinel_unix;
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
#[cfg(any(windows, test))]
|
||||
mod windows_report;
|
||||
|
||||
pub const MAX_EDITED_REPORT_BYTES: usize = 48 * 1024;
|
||||
|
||||
/// Validate an edited report before it is stored or used as a submission body.
|
||||
@@ -98,9 +107,9 @@ pub fn refresh_edited_report_with_control(
|
||||
control.check()?;
|
||||
let mut edited = validate_edited_report(edited_xml)?;
|
||||
let cookie_params = cookie_params(input);
|
||||
let identity = HostInfoCollector::new(&input.profile, input, &cookie_params).collect_identity();
|
||||
let identity = HostInfoCollector::new(&input.profile, input, &cookie_params).collect_identity(control)?;
|
||||
control.check()?;
|
||||
let domain = format!("{}.internal", identity.domain);
|
||||
let domain = &identity.domain;
|
||||
let generate_time = get_current_time_components().0;
|
||||
for (name, value) in [
|
||||
("md5-sum", input.context.md5()),
|
||||
@@ -201,6 +210,27 @@ impl ReportContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a computer domain only for native profiles with a platform-specific source.
|
||||
fn native_domain(profile: &OsProfile, control: &dyn CollectionControl) -> io::Result<Option<String>> {
|
||||
control.check()?;
|
||||
if !profile.is_native() {
|
||||
return Ok(None);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if profile.client_os() == ClientOs::Windows {
|
||||
return windows::domain().map(Some);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
if profile.client_os() == ClientOs::Mac {
|
||||
return domain_macos::collect(&CollectorCommands::new(control)).map(Some);
|
||||
}
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
if profile.client_os() == ClientOs::Linux {
|
||||
return domain_unix::collect(&CollectorCommands::new(control)).map(Some);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Inputs collected by the caller for one HIP report.
|
||||
pub struct ReportInput {
|
||||
pub profile: OsProfile,
|
||||
@@ -214,14 +244,17 @@ pub fn generate_report(input: &ReportInput) -> anyhow::Result<String> {
|
||||
}
|
||||
|
||||
/// Identity-only maintenance report. This deliberately does not enumerate the
|
||||
/// machine or execute posture collectors; addresses come from the session owner.
|
||||
pub fn generate_identity_report(input: &ReportInput) -> anyhow::Result<String> {
|
||||
/// interfaces or execute posture collectors; addresses come from the session owner.
|
||||
/// Native profiles read the computer domain, consistent with generated and refreshed reports.
|
||||
pub fn generate_identity_report(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result<String> {
|
||||
let params = cookie_params(input);
|
||||
let domain =
|
||||
native_domain(&input.profile, control)?.unwrap_or_else(|| params.get("domain").cloned().unwrap_or_default());
|
||||
let mut report = Element::new("hip-report");
|
||||
for (name, value) in [
|
||||
("md5-sum", input.context.md5()),
|
||||
("user-name", report_user_name(input, ¶ms)),
|
||||
("domain", params.get("domain").map(String::as_str).unwrap_or_default()),
|
||||
("domain", domain.as_str()),
|
||||
("host-name", input.profile.computer()),
|
||||
("host-id", input.profile.host_id()),
|
||||
("ip-address", input.context.client_ip().unwrap_or_default()),
|
||||
@@ -241,10 +274,18 @@ pub fn generate_identity_report(input: &ReportInput) -> anyhow::Result<String> {
|
||||
}
|
||||
|
||||
pub fn generate_report_with_control(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result<String> {
|
||||
Ok(generate_report_details(input, control)?.xml)
|
||||
}
|
||||
|
||||
pub fn generate_report_details(
|
||||
input: &ReportInput,
|
||||
control: &dyn CollectionControl,
|
||||
) -> anyhow::Result<gpapi::hip::HipReport> {
|
||||
control.check()?;
|
||||
let cookie_params = cookie_params(input);
|
||||
let (generate_time, day, month, year) = get_current_time_components();
|
||||
let host_info = HostInfoCollector::new(&input.profile, input, &cookie_params).collect(control)?;
|
||||
let windows_updates = host_info.windows_updates.clone();
|
||||
let template = HipReportTemplate {
|
||||
client_version: input.profile.client_version(),
|
||||
generate_time,
|
||||
@@ -255,9 +296,9 @@ pub fn generate_report_with_control(input: &ReportInput, control: &dyn Collectio
|
||||
host_info,
|
||||
md5: input.context.md5(),
|
||||
};
|
||||
let report = format_xml(&template.render()?)?;
|
||||
let xml = format_xml(&template.render()?)?;
|
||||
control.check()?;
|
||||
Ok(report)
|
||||
Ok(gpapi::hip::HipReport { xml, windows_updates })
|
||||
}
|
||||
|
||||
fn cookie_params(input: &ReportInput) -> HashMap<String, String> {
|
||||
@@ -338,6 +379,8 @@ struct HostInfo {
|
||||
clamav: Option<ClamAvInfo>,
|
||||
sentinel: Option<SentinelInfo>,
|
||||
ufw: Option<UfwInfo>,
|
||||
windows_categories: Option<String>,
|
||||
windows_updates: Option<gpapi::hip::WindowsUpdateStatus>,
|
||||
}
|
||||
|
||||
impl HostInfo {
|
||||
@@ -425,16 +468,6 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Domain belongs to the runtime user/session, not the simulated OS, so
|
||||
/// it is sourced from the auth cookie when available.
|
||||
fn get_domain(&self) -> String {
|
||||
self
|
||||
.cookie_params
|
||||
.get("domain")
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Collect network interface information with fallback
|
||||
fn collect_network_interface(&self) -> NetworkInterface {
|
||||
match netdev::get_default_interface() {
|
||||
@@ -452,28 +485,28 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Single entry point for collecting host info — dispatches per-OS
|
||||
/// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`.
|
||||
fn collect_identity(&self) -> HostInfo {
|
||||
fn collect_identity(&self, control: &dyn CollectionControl) -> io::Result<HostInfo> {
|
||||
let runtime_iface = self.collect_network_interface();
|
||||
let primary = self.adapt_primary_interface(&runtime_iface);
|
||||
|
||||
let mut interfaces = vec![primary.clone()];
|
||||
interfaces.extend(self.extra_interfaces(&primary));
|
||||
|
||||
HostInfo {
|
||||
Ok(HostInfo {
|
||||
os_vendor: self.profile.os_vendor().to_string(),
|
||||
os_version: self.profile.os_version().to_string(),
|
||||
host_id: self.profile.host_id().to_string(),
|
||||
host_name: self.profile.computer().to_string(),
|
||||
software_version: self.profile.software_version().to_string(),
|
||||
domain: self.domain_for_profile(),
|
||||
domain: self.domain_for_profile(control)?,
|
||||
network_interfaces: interfaces,
|
||||
defender: None,
|
||||
clamav: None,
|
||||
sentinel: None,
|
||||
ufw: None,
|
||||
}
|
||||
windows_categories: None,
|
||||
windows_updates: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Build the primary network interface with OS-appropriate naming and
|
||||
@@ -496,9 +529,12 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional interfaces appended after the primary. Only Windows
|
||||
/// emits the software loopback interface in HIP reports.
|
||||
/// Native Windows enumerates loopback adapters; Windows emulation retains its synthetic interface.
|
||||
fn extra_interfaces(&self, primary: &NetworkInterface) -> Vec<NetworkInterface> {
|
||||
#[cfg(windows)]
|
||||
if self.profile.client_os() == ClientOs::Windows && self.profile.is_native() {
|
||||
return windows::loopback_interfaces();
|
||||
}
|
||||
match self.profile.client_os() {
|
||||
ClientOs::Windows => vec![NetworkInterface {
|
||||
name: derive_windows_network_name(self.profile.host_id(), primary),
|
||||
@@ -511,20 +547,31 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linux HIP reports omit the domain field; macOS/Windows include it
|
||||
/// from the auth cookie.
|
||||
fn domain_for_profile(&self) -> String {
|
||||
match self.profile.client_os() {
|
||||
ClientOs::Linux => String::new(),
|
||||
ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => self.get_domain(),
|
||||
fn domain_for_profile(&self, control: &dyn CollectionControl) -> io::Result<String> {
|
||||
if let Some(domain) = native_domain(self.profile, control)? {
|
||||
return Ok(domain);
|
||||
}
|
||||
let domain = match self.profile.client_os() {
|
||||
ClientOs::Linux => "",
|
||||
ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => {
|
||||
self.cookie_params.get("domain").map(String::as_str).unwrap_or_default()
|
||||
}
|
||||
};
|
||||
Ok(format!("{domain}.internal"))
|
||||
}
|
||||
|
||||
fn collect(&self, control: &dyn CollectionControl) -> io::Result<HostInfo> {
|
||||
control.check()?;
|
||||
let mut info = self.collect_identity();
|
||||
let mut info = self.collect_identity(control)?;
|
||||
control.check()?;
|
||||
let commands = CollectorCommands::new(control);
|
||||
#[cfg(windows)]
|
||||
if self.profile.client_os() == ClientOs::Windows && self.profile.is_native() {
|
||||
let report = windows::collect(&commands, control)?;
|
||||
info.windows_updates = Some(report.update_status());
|
||||
info.windows_categories = Some(report.render()?);
|
||||
}
|
||||
|
||||
if self.profile.client_os() == ClientOs::Linux && self.profile.is_native() {
|
||||
info.defender = detect_microsoft_defender(&commands)?;
|
||||
info.clamav = detect_clamav(&commands)?;
|
||||
@@ -671,16 +718,20 @@ fn placeholder_interface_for(profile: &OsProfile, runtime: &NetworkInterface) ->
|
||||
}
|
||||
}
|
||||
|
||||
/// MAC address formatting per target OS. Windows uses hyphen separators;
|
||||
/// Linux and macOS preserve the colon-separated form returned by the
|
||||
/// platform.
|
||||
/// Native Windows uses uppercase hex and hyphens. Windows emulation retains its
|
||||
/// existing casing; other profiles preserve the platform's MAC representation.
|
||||
fn format_mac_for(profile: &OsProfile, mac: Option<String>) -> Option<String> {
|
||||
match profile.client_os() {
|
||||
ClientOs::Windows => mac.map(|m| m.replace(':', "-")),
|
||||
ClientOs::Windows if profile.is_native() => mac.map(format_native_windows_mac),
|
||||
ClientOs::Windows => mac.map(|value| value.replace(':', "-")),
|
||||
ClientOs::Linux | ClientOs::Mac | ClientOs::Ios => mac,
|
||||
}
|
||||
}
|
||||
|
||||
fn format_native_windows_mac(mac: String) -> String {
|
||||
mac.replace(':', "-").to_ascii_uppercase()
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Utility Functions
|
||||
// ============================================================================
|
||||
@@ -759,6 +810,17 @@ mod tests {
|
||||
gpapi::os_profile::desktop::collect_profile(OsProfileBuilder::new(client_os), None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_identity_report_stops_before_domain_collection() {
|
||||
let input = make_input(make_profile(ClientOs::Linux));
|
||||
let cancelled = || Err(io::Error::from(io::ErrorKind::Interrupted));
|
||||
let error = generate_identity_report(&input, &cancelled).unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast_ref::<io::Error>().unwrap().kind(),
|
||||
io::ErrorKind::Interrupted
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_report_contains_session_identity_without_posture() {
|
||||
for os in [ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] {
|
||||
@@ -769,7 +831,7 @@ mod tests {
|
||||
client_ipv6: Some("2001:db8::7".into()),
|
||||
md5: "identity-token".into(),
|
||||
};
|
||||
let xml = generate_identity_report(&input).unwrap();
|
||||
let xml = generate_identity_report(&input, &|| Ok(())).unwrap();
|
||||
let root = Element::parse(xml.as_bytes()).unwrap();
|
||||
assert_eq!(
|
||||
unique_child(&root, "user-name").unwrap().get_text().unwrap(),
|
||||
@@ -796,13 +858,39 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_windows_mac_casing_does_not_change_emulation_or_other_platforms() {
|
||||
for (runtime_os, client_os, expected) in [
|
||||
(ClientOs::Windows, ClientOs::Windows, "AA-BB-CC-DD-EE-FF"),
|
||||
(ClientOs::Mac, ClientOs::Windows, "aa-bb-cc-dd-ee-ff"),
|
||||
(ClientOs::Linux, ClientOs::Windows, "aa-bb-cc-dd-ee-ff"),
|
||||
(ClientOs::Mac, ClientOs::Mac, "aa:bb:cc:dd:ee:ff"),
|
||||
(ClientOs::Linux, ClientOs::Linux, "aa:bb:cc:dd:ee:ff"),
|
||||
] {
|
||||
let profile = OsProfileBuilder::new(client_os).build(gpapi::os_profile::HostSnapshot {
|
||||
runtime_os,
|
||||
identity: gpapi::os_profile::HostIdentity::application("host".into(), "id".into()),
|
||||
os_version: "OS".into(),
|
||||
software_version: "version".into(),
|
||||
});
|
||||
assert_eq!(
|
||||
format_mac_for(&profile, Some("aa:bb:cc:dd:ee:ff".into())).as_deref(),
|
||||
Some(expected)
|
||||
);
|
||||
assert_eq!(format_mac_for(&profile, Some(String::new())).as_deref(), Some(""));
|
||||
assert_eq!(format_mac_for(&profile, None), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_info_os_vendor_is_linux_for_linux_profile() {
|
||||
let input = make_input(make_profile(ClientOs::Linux));
|
||||
let profile = make_profile(ClientOs::Linux);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params)
|
||||
.collect_identity(&CollectionBudget::new(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(info.os_vendor, "Linux");
|
||||
}
|
||||
@@ -813,7 +901,9 @@ mod tests {
|
||||
let profile = make_profile(ClientOs::Mac);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params)
|
||||
.collect_identity(&CollectionBudget::new(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(info.os_vendor, "Apple");
|
||||
}
|
||||
@@ -824,7 +914,9 @@ mod tests {
|
||||
let profile = make_profile(ClientOs::Windows);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params)
|
||||
.collect_identity(&CollectionBudget::new(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(info.os_vendor, "Microsoft");
|
||||
}
|
||||
@@ -835,7 +927,9 @@ mod tests {
|
||||
let profile = make_profile(ClientOs::Linux);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params)
|
||||
.collect_identity(&CollectionBudget::new(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(info.host_id, profile.host_id());
|
||||
}
|
||||
@@ -849,7 +943,9 @@ mod tests {
|
||||
let profile = make_profile(client_os);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params)
|
||||
.collect_identity(&CollectionBudget::new(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(info.host_id, profile.host_id());
|
||||
}
|
||||
@@ -870,11 +966,206 @@ mod tests {
|
||||
validate_edited_report(&report).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emulated_windows_uses_v4_categories_and_preserves_template_posture() {
|
||||
use gpapi::os_profile::HostSnapshot;
|
||||
let identity = gpapi::os_profile::desktop::identity_from_parts(
|
||||
"emulated-device".into(),
|
||||
"emulated-id".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let profile = OsProfileBuilder::new(ClientOs::Windows).build(HostSnapshot {
|
||||
runtime_os: ClientOs::Mac,
|
||||
identity,
|
||||
os_version: "macOS".into(),
|
||||
software_version: "15.0".into(),
|
||||
});
|
||||
assert!(!profile.is_native());
|
||||
let mut input = make_input(profile);
|
||||
input.context = ReportContext::Connected {
|
||||
cookie: "domain=emulated-domain".into(),
|
||||
client_ip: None,
|
||||
client_ipv6: None,
|
||||
md5: "test-digest".into(),
|
||||
};
|
||||
let report = generate_report(&input).unwrap();
|
||||
let root = validate_edited_report(&report).unwrap();
|
||||
assert_eq!(
|
||||
unique_child(&root, "domain").unwrap().get_text().unwrap(),
|
||||
"emulated-domain.internal"
|
||||
);
|
||||
assert!(report.contains("<domain>emulated-domain.internal</domain>"));
|
||||
let identity = Element::parse(generate_identity_report(&input, &|| Ok(())).unwrap().as_bytes()).unwrap();
|
||||
assert_eq!(
|
||||
unique_child(&identity, "domain").unwrap().get_text().unwrap(),
|
||||
"emulated-domain"
|
||||
);
|
||||
let categories = unique_child(&root, "categories").unwrap();
|
||||
let names = categories
|
||||
.children
|
||||
.iter()
|
||||
.filter_map(xmltree::XMLNode::as_element)
|
||||
.filter_map(|entry| entry.attributes.get("name").map(String::as_str))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"host-info",
|
||||
"anti-malware",
|
||||
"disk-backup",
|
||||
"disk-encryption",
|
||||
"firewall",
|
||||
"patch-management",
|
||||
"data-loss-prevention"
|
||||
]
|
||||
);
|
||||
assert!(report.contains("McAfee VirusScan Enterprise"));
|
||||
assert!(report.contains("McAfee ePolicy Orchestrator Agent"));
|
||||
assert_eq!(report.matches("prodType=\"3\"").count(), 2);
|
||||
assert!(report.contains("<drive-name>C:\\</drive-name>"));
|
||||
assert!(report.contains("<enc-state>encrypted</enc-state>"));
|
||||
assert!(report.contains("<missing-patches />"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emulated_unix_domains_keep_existing_cookie_and_suffix_behavior() {
|
||||
for client_os in [ClientOs::Mac, ClientOs::Linux] {
|
||||
let expected_domain = if client_os == ClientOs::Linux {
|
||||
".internal"
|
||||
} else {
|
||||
"emulated-domain.internal"
|
||||
};
|
||||
let profile = OsProfileBuilder::new(client_os).build(gpapi::os_profile::HostSnapshot {
|
||||
runtime_os: ClientOs::Windows,
|
||||
identity: gpapi::os_profile::HostIdentity::from_parts(
|
||||
"host".into(),
|
||||
"id".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
),
|
||||
os_version: "Windows".into(),
|
||||
software_version: "11".into(),
|
||||
});
|
||||
assert!(!profile.is_native());
|
||||
let mut input = make_input(profile);
|
||||
input.context = ReportContext::Connected {
|
||||
cookie: "domain=emulated-domain".into(),
|
||||
client_ip: None,
|
||||
client_ipv6: None,
|
||||
md5: "test-digest".into(),
|
||||
};
|
||||
let xml = generate_report(&input).unwrap();
|
||||
let generated = validate_edited_report(&xml).unwrap();
|
||||
let refreshed = validate_edited_report(&refresh_edited_report(&xml, &input).unwrap()).unwrap();
|
||||
for report in [generated, refreshed] {
|
||||
assert_eq!(
|
||||
unique_child(&report, "domain").unwrap().get_text().unwrap(),
|
||||
expected_domain
|
||||
);
|
||||
assert_eq!(
|
||||
unique_child(host_info(&report).unwrap(), "domain")
|
||||
.unwrap()
|
||||
.get_text()
|
||||
.unwrap(),
|
||||
expected_domain
|
||||
);
|
||||
}
|
||||
let identity = Element::parse(generate_identity_report(&input, &|| Ok(())).unwrap().as_bytes()).unwrap();
|
||||
assert_eq!(
|
||||
unique_child(&identity, "domain").unwrap().get_text().unwrap(),
|
||||
"emulated-domain"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_domain_is_shared_by_generated_edited_and_identity_reports() {
|
||||
let client_os = if cfg!(windows) {
|
||||
ClientOs::Windows
|
||||
} else if cfg!(target_os = "macos") {
|
||||
ClientOs::Mac
|
||||
} else {
|
||||
ClientOs::Linux
|
||||
};
|
||||
let profile = OsProfileBuilder::new(client_os).build(gpapi::os_profile::HostSnapshot {
|
||||
runtime_os: client_os,
|
||||
identity: gpapi::os_profile::HostIdentity::from_parts(
|
||||
"host".into(),
|
||||
"id".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
),
|
||||
os_version: "Windows".into(),
|
||||
software_version: "11".into(),
|
||||
});
|
||||
let mut input = make_input(profile);
|
||||
input.context = ReportContext::Connected {
|
||||
cookie: "domain=auth-cookie-must-not-be-used.invalid".into(),
|
||||
client_ip: None,
|
||||
client_ipv6: None,
|
||||
md5: "test-digest".into(),
|
||||
};
|
||||
let expected = native_domain(&input.profile, &CollectionBudget::new(Duration::from_secs(10)))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let params = cookie_params(&input);
|
||||
let mut host_info = HostInfoCollector::new(&input.profile, &input, ¶ms)
|
||||
.collect_identity(&CollectionBudget::new(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
// Render the identity path without executing the product collectors.
|
||||
if client_os == ClientOs::Windows {
|
||||
host_info.windows_categories = Some(windows_report::WindowsReport::default().render().unwrap());
|
||||
}
|
||||
let (generate_time, day, month, year) = get_current_time_components();
|
||||
let xml = HipReportTemplate {
|
||||
client_version: input.profile.client_version(),
|
||||
generate_time,
|
||||
day,
|
||||
month,
|
||||
year,
|
||||
user_name: "test-user",
|
||||
host_info,
|
||||
md5: "test-digest",
|
||||
}
|
||||
.render()
|
||||
.unwrap();
|
||||
let generated = validate_edited_report(&xml).unwrap();
|
||||
let mut stale = generated.clone();
|
||||
set_field(&mut stale, "domain", "stale.internal").unwrap();
|
||||
set_field(host_info_mut(&mut stale).unwrap(), "domain", "stale.internal").unwrap();
|
||||
let refreshed = refresh_edited_report(&write_xml(&stale).unwrap(), &input).unwrap();
|
||||
let refreshed = validate_edited_report(&refreshed).unwrap();
|
||||
let identity = Element::parse(generate_identity_report(&input, &|| Ok(())).unwrap().as_bytes()).unwrap();
|
||||
for report in [&generated, &refreshed, &identity] {
|
||||
assert_eq!(
|
||||
unique_child(report, "domain")
|
||||
.unwrap()
|
||||
.get_text()
|
||||
.unwrap_or_default()
|
||||
.as_ref(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
for mut report in [generated, refreshed] {
|
||||
assert_eq!(
|
||||
unique_child(host_info_mut(&mut report).unwrap(), "domain")
|
||||
.unwrap()
|
||||
.get_text()
|
||||
.unwrap_or_default()
|
||||
.as_ref(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_report_renders_detected_sentinel_products() {
|
||||
let input = make_input(make_profile(ClientOs::Mac));
|
||||
let cookie_params = HashMap::new();
|
||||
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity();
|
||||
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params)
|
||||
.collect_identity(&CollectionBudget::new(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
host_info.sentinel = Some(SentinelInfo {
|
||||
version: "25.3.4.8365".to_string(),
|
||||
real_time_protection: true,
|
||||
@@ -905,7 +1196,9 @@ mod tests {
|
||||
fn linux_report_renders_detected_sentinel_antimalware() {
|
||||
let input = make_input(make_profile(ClientOs::Linux));
|
||||
let cookie_params = HashMap::new();
|
||||
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity();
|
||||
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params)
|
||||
.collect_identity(&CollectionBudget::new(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
host_info.sentinel = Some(SentinelInfo {
|
||||
version: "25.2.2.14".to_string(),
|
||||
real_time_protection: true,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! Public JSON adapter and native Windows host identity.
|
||||
use super::windows_report::WindowsReport;
|
||||
use gpapi::{collection::CollectionControl, process::collection::CollectorCommands};
|
||||
use std::io;
|
||||
|
||||
pub(super) fn collect(commands: &CollectorCommands<'_>, control: &dyn CollectionControl) -> io::Result<WindowsReport> {
|
||||
let executable = std::env::current_exe()?;
|
||||
let helper = executable
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::other("Application directory is unavailable"))?
|
||||
.join("gp-posture.exe");
|
||||
let output = commands
|
||||
.run_executable(&helper, &[])?
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Windows posture helper is not installed"))?;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other("Windows posture collection failed"));
|
||||
}
|
||||
let report: WindowsReport = serde_json::from_slice(&output.stdout).map_err(io::Error::other)?;
|
||||
for category in &report.unavailable {
|
||||
log::warn!("Windows HIP data unavailable: {category}");
|
||||
}
|
||||
control.check()?;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Windows supplies the loopback adapter's real ID through GetAdaptersAddresses (via netdev).
|
||||
pub(super) fn loopback_interfaces() -> Vec<super::NetworkInterface> {
|
||||
netdev::get_interfaces()
|
||||
.into_iter()
|
||||
.filter(|interface| interface.is_loopback())
|
||||
.map(|interface| {
|
||||
super::NetworkInterface::new(interface.name.clone(), interface.description.unwrap_or(interface.name))
|
||||
.with_mac(Some(
|
||||
interface
|
||||
.mac_addr
|
||||
.map(|mac| super::format_native_windows_mac(mac.address()))
|
||||
.unwrap_or_default(),
|
||||
))
|
||||
.with_ipv4(interface.ipv4.first().map(|ip| ip.addr().to_string()))
|
||||
.with_ipv6(interface.ipv6.first().map(|ip| ip.addr().to_string()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Primary DNS domain, or physical DNS domain if the primary query fails.
|
||||
pub(super) fn domain() -> io::Result<String> {
|
||||
use windows::Win32::{
|
||||
Networking::ActiveDirectory::{
|
||||
DSROLE_PRIMARY_DOMAIN_INFO_BASIC, DsRoleFreeMemory, DsRoleGetPrimaryDomainInformation,
|
||||
DsRolePrimaryDomainInfoBasic,
|
||||
},
|
||||
System::SystemInformation::{ComputerNamePhysicalDnsDomain, GetComputerNameExW},
|
||||
};
|
||||
use windows::core::PWSTR;
|
||||
|
||||
let mut buffer = std::ptr::null_mut();
|
||||
// SAFETY: a null server selects this computer; Windows allocates and owns the returned structure.
|
||||
let status = unsafe { DsRoleGetPrimaryDomainInformation(None, DsRolePrimaryDomainInfoBasic, &mut buffer) };
|
||||
if status == 0 && !buffer.is_null() {
|
||||
// SAFETY: the requested information level returns this structure. Copy the string before freeing its allocation.
|
||||
let result = unsafe { copy_domain_name((*buffer.cast::<DSROLE_PRIMARY_DOMAIN_INFO_BASIC>()).DomainNameDns) };
|
||||
unsafe { DsRoleFreeMemory(buffer.cast()) };
|
||||
return result;
|
||||
}
|
||||
|
||||
let mut name = [0u16; 257];
|
||||
let mut size = name.len() as u32;
|
||||
// SAFETY: the writable UTF-16 buffer and its character count remain valid for the call.
|
||||
unsafe { GetComputerNameExW(ComputerNamePhysicalDnsDomain, Some(PWSTR(name.as_mut_ptr())), &mut size) }
|
||||
.map_err(io::Error::other)?;
|
||||
String::from_utf16(&name[..size as usize]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
|
||||
}
|
||||
|
||||
// SAFETY: a non-null name must point to a live NUL-terminated UTF-16 string.
|
||||
unsafe fn copy_domain_name(name: windows::core::PWSTR) -> io::Result<String> {
|
||||
if name.is_null() {
|
||||
// A successful primary-domain query with no DNS name is an empty domain, including workgroup hosts.
|
||||
return Ok(String::new());
|
||||
}
|
||||
unsafe { name.to_string() }.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use windows::core::PWSTR;
|
||||
#[test]
|
||||
fn primary_domain_preserves_dns_name_and_empty_workgroup_domain() {
|
||||
let mut name: Vec<u16> = "Lab.Example.test\0".encode_utf16().collect();
|
||||
assert_eq!(
|
||||
unsafe { copy_domain_name(PWSTR(name.as_mut_ptr())) }.unwrap(),
|
||||
"Lab.Example.test"
|
||||
);
|
||||
assert_eq!(unsafe { copy_domain_name(PWSTR::null()) }.unwrap(), "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
//! Windows posture facts and their HIP v4 representation.
|
||||
use serde::Deserialize;
|
||||
use xmltree::{Element, XMLNode};
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub(super) struct WindowsReport {
|
||||
pub anti_malware: Vec<AntiMalware>,
|
||||
pub disk_backup: Vec<Backup>,
|
||||
pub disk_encryption: Vec<Encryption>,
|
||||
pub firewall: Vec<ProductState>,
|
||||
pub patch_management: Vec<ProductState>,
|
||||
pub missing_patches: Option<Vec<MissingPatch>>,
|
||||
pub patches_checked_at: Option<u64>,
|
||||
pub unavailable: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub(super) struct Product {
|
||||
pub name: String,
|
||||
pub vendor: String,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub(super) struct AntiMalware {
|
||||
pub product: Product,
|
||||
pub enabled: Option<bool>,
|
||||
pub definition_version: Option<String>,
|
||||
pub engine_version: Option<String>,
|
||||
pub definition_date: Option<String>,
|
||||
pub last_scan: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub(super) struct Backup {
|
||||
pub product: Product,
|
||||
pub last_backup: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub(super) struct Encryption {
|
||||
pub product: Product,
|
||||
pub drives: Vec<Drive>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct Drive {
|
||||
pub name: String,
|
||||
pub conversion_status: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub(super) struct ProductState {
|
||||
pub product: Product,
|
||||
pub enabled: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub(super) struct MissingPatch {
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub kb: String,
|
||||
pub category: String,
|
||||
pub vendor: String,
|
||||
pub msrc_severity: Option<String>,
|
||||
}
|
||||
|
||||
impl MissingPatch {
|
||||
fn severity(&self) -> i32 {
|
||||
match self.msrc_severity.as_deref().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("critical") => 3,
|
||||
Some("important") => 2,
|
||||
Some("moderate") => 1,
|
||||
Some("low") => 0,
|
||||
_ => -1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WindowsReport {
|
||||
pub(super) fn update_status(&self) -> gpapi::hip::WindowsUpdateStatus {
|
||||
let mut status = gpapi::hip::WindowsUpdateStatus::default();
|
||||
if self.missing_patches.is_some() {
|
||||
status.checked_at = self.patches_checked_at;
|
||||
} else {
|
||||
status.omitted_snapshot_at = self.patches_checked_at;
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
pub fn render(&self) -> std::io::Result<String> {
|
||||
let mut categories = Vec::new();
|
||||
categories.push(category(
|
||||
"anti-malware",
|
||||
self.anti_malware.iter().map(|item| {
|
||||
let mut info = product(&item.product);
|
||||
let prod = info.get_mut_child("Prod").unwrap();
|
||||
prod.attributes.insert("prodType".into(), "3".into());
|
||||
prod.attributes.insert("osType".into(), "1".into());
|
||||
for (name, value) in [("defver", &item.definition_version), ("engver", &item.engine_version)] {
|
||||
if let Some(value) = value {
|
||||
prod.attributes.insert(name.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(date) = item
|
||||
.definition_date
|
||||
.as_deref()
|
||||
.and_then(|date| chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok())
|
||||
{
|
||||
use chrono::Datelike;
|
||||
for (name, value) in [
|
||||
("dateyear", date.year().to_string()),
|
||||
("datemon", date.month().to_string()),
|
||||
("dateday", date.day().to_string()),
|
||||
] {
|
||||
prod.attributes.insert(name.into(), value);
|
||||
}
|
||||
}
|
||||
field(&mut info, "real-time-protection", yes_no(item.enabled));
|
||||
field(
|
||||
&mut info,
|
||||
"last-full-scan-time",
|
||||
item.last_scan.as_deref().unwrap_or("n/a"),
|
||||
);
|
||||
info
|
||||
}),
|
||||
));
|
||||
categories.push(category(
|
||||
"disk-backup",
|
||||
self.disk_backup.iter().map(|item| {
|
||||
let mut info = product(&item.product);
|
||||
field(
|
||||
&mut info,
|
||||
"last-backup-time",
|
||||
item.last_backup.as_deref().unwrap_or("n/a"),
|
||||
);
|
||||
info
|
||||
}),
|
||||
));
|
||||
categories.push(category(
|
||||
"disk-encryption",
|
||||
self.disk_encryption.iter().map(|item| {
|
||||
let mut info = product(&item.product);
|
||||
let mut drives = Element::new("drives");
|
||||
for drive in &item.drives {
|
||||
let mut entry = Element::new("entry");
|
||||
field(&mut entry, "drive-name", &drive.name);
|
||||
field(
|
||||
&mut entry,
|
||||
"enc-state",
|
||||
match drive.conversion_status {
|
||||
Some(0) => "unencrypted",
|
||||
Some(1) => "encrypted",
|
||||
_ => "n/a",
|
||||
},
|
||||
);
|
||||
drives.children.push(XMLNode::Element(entry));
|
||||
}
|
||||
info.children.push(XMLNode::Element(drives));
|
||||
info
|
||||
}),
|
||||
));
|
||||
categories.push(category("firewall", self.firewall.iter().map(state)));
|
||||
let mut patches = category("patch-management", self.patch_management.iter().map(state));
|
||||
// A failed search is not evidence that the machine has no missing updates.
|
||||
if let Some(missing) = &self.missing_patches {
|
||||
let mut list = Element::new("missing-patches");
|
||||
for patch in missing {
|
||||
let mut entry = Element::new("entry");
|
||||
field(&mut entry, "title", &patch.title);
|
||||
field(&mut entry, "description", &patch.description);
|
||||
field(&mut entry, "product", "");
|
||||
field(&mut entry, "vendor", &patch.vendor);
|
||||
field(&mut entry, "info-url", "");
|
||||
field(&mut entry, "kb-article-id", &patch.kb);
|
||||
field(&mut entry, "security-bulletin-id", "");
|
||||
field(&mut entry, "severity", &patch.severity().to_string());
|
||||
field(&mut entry, "category", &patch.category);
|
||||
field(&mut entry, "is-installed", "no");
|
||||
list.children.push(XMLNode::Element(entry));
|
||||
}
|
||||
patches.children.push(XMLNode::Element(list));
|
||||
}
|
||||
categories.push(patches);
|
||||
let mut output = Vec::new();
|
||||
for category in categories {
|
||||
category
|
||||
.write_with_config(
|
||||
&mut output,
|
||||
xmltree::EmitterConfig::new().write_document_declaration(false),
|
||||
)
|
||||
.map_err(std::io::Error::other)?;
|
||||
}
|
||||
String::from_utf8(output).map_err(std::io::Error::other)
|
||||
}
|
||||
}
|
||||
|
||||
fn yes_no(enabled: Option<bool>) -> &'static str {
|
||||
match enabled {
|
||||
Some(true) => "yes",
|
||||
Some(false) => "no",
|
||||
None => "n/a",
|
||||
}
|
||||
}
|
||||
|
||||
fn field(parent: &mut Element, name: &str, value: &str) {
|
||||
let mut child = Element::new(name);
|
||||
child.children.push(XMLNode::Text(value.into()));
|
||||
parent.children.push(XMLNode::Element(child));
|
||||
}
|
||||
|
||||
fn product(product: &Product) -> Element {
|
||||
let mut info = Element::new("ProductInfo");
|
||||
let mut prod = Element::new("Prod");
|
||||
for (name, value) in [
|
||||
("name", &product.name),
|
||||
("vendor", &product.vendor),
|
||||
("version", &product.version),
|
||||
] {
|
||||
if !value.is_empty() {
|
||||
prod.attributes.insert(name.into(), value.clone());
|
||||
}
|
||||
}
|
||||
info.children.push(XMLNode::Element(prod));
|
||||
info
|
||||
}
|
||||
|
||||
fn state(item: &ProductState) -> Element {
|
||||
let mut info = product(&item.product);
|
||||
field(&mut info, "is-enabled", yes_no(item.enabled));
|
||||
info
|
||||
}
|
||||
|
||||
fn category(name: &str, products: impl Iterator<Item = Element>) -> Element {
|
||||
let mut category = Element::new("entry");
|
||||
category.attributes.insert("name".into(), name.into());
|
||||
let mut list = Element::new("list");
|
||||
for product in products {
|
||||
let mut entry = Element::new("entry");
|
||||
entry.children.push(XMLNode::Element(product));
|
||||
list.children.push(XMLNode::Element(entry));
|
||||
}
|
||||
category.children.push(XMLNode::Element(list));
|
||||
category
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn omitted_snapshot_can_be_refreshed_without_claiming_patch_details() {
|
||||
let mut report = WindowsReport::default();
|
||||
assert_eq!(report.update_status().refresh_cursor(), None);
|
||||
report.patches_checked_at = Some(123);
|
||||
let status = report.update_status();
|
||||
assert_eq!(status.checked_at, None);
|
||||
assert_eq!(status.refresh_cursor(), Some(123));
|
||||
assert!(!report.render().unwrap().contains("missing-patches"));
|
||||
report.missing_patches = Some(Vec::new());
|
||||
assert_eq!(report.update_status().checked_at, Some(123));
|
||||
assert_eq!(report.update_status().refresh_cursor(), Some(123));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_posture_preserves_unavailable_values_and_escapes_product_text() {
|
||||
let report: WindowsReport = serde_json::from_str(
|
||||
r#"{
|
||||
"anti_malware":[{"product":{"name":"Agent & Endpoint","version":"25.1"},"enabled":true}],
|
||||
"disk_encryption":[{"product":{"name":"BitLocker"},"drives":[{"name":"C:\\","conversion_status":0}]}],
|
||||
"missing_patches":null
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let xml = report.render().unwrap();
|
||||
let root = Element::parse(format!("<categories>{xml}</categories>").as_bytes()).unwrap();
|
||||
assert_eq!(root.children.len(), 5);
|
||||
assert!(xml.contains("Agent & Endpoint"));
|
||||
assert!(xml.contains("<enc-state>unencrypted</enc-state>"));
|
||||
assert!(xml.contains("<last-full-scan-time>n/a</last-full-scan-time>"));
|
||||
assert!(!xml.contains("missing-patches"));
|
||||
assert!(!xml.contains("McAfee"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_patch_severity_is_unknown_without_an_observed_msrc_rating() {
|
||||
for category in ["driver", "update", "security_update", "critical_update"] {
|
||||
let mut patch = MissingPatch {
|
||||
category: category.into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(patch.severity(), -1);
|
||||
patch.msrc_severity = Some("Critical".into());
|
||||
assert_eq!(patch.severity(), 3);
|
||||
patch.msrc_severity = Some("Unrecognized".into());
|
||||
assert_eq!(patch.severity(), -1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_update_search_distinguishes_empty_and_missing_updates() {
|
||||
let mut report = WindowsReport {
|
||||
missing_patches: Some(vec![]),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(report.render().unwrap().contains("<missing-patches />"));
|
||||
report.missing_patches = Some(vec![MissingPatch {
|
||||
title: "Security update".into(),
|
||||
kb: "123".into(),
|
||||
..Default::default()
|
||||
}]);
|
||||
let xml = report.render().unwrap();
|
||||
assert!(xml.contains("<kb-article-id>123</kb-article-id>"));
|
||||
assert!(xml.contains("<is-installed>no</is-installed>"));
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
<hip-report name="hip-report">
|
||||
<md5-sum>{{ md5 }}</md5-sum>
|
||||
<user-name>{{ user_name }}</user-name>
|
||||
<domain>{{ host_info.domain }}.internal</domain>
|
||||
<domain>{{ host_info.domain }}</domain>
|
||||
<host-name>{{ host_info.host_name }}</host-name>
|
||||
<host-id>{{ host_info.host_id }}</host-id>
|
||||
<ip-address>{{ host_info.default_ipv4() }}</ip-address>
|
||||
@@ -14,7 +14,7 @@
|
||||
<client-version>{{ client_version }}</client-version>
|
||||
<os>{{ host_info.os_version }}</os>
|
||||
<os-vendor>{{ host_info.os_vendor }}</os-vendor>
|
||||
<domain>{{ host_info.domain }}.internal</domain>
|
||||
<domain>{{ host_info.domain }}</domain>
|
||||
<host-name>{{ host_info.host_name }}</host-name>
|
||||
<host-id>{{ host_info.host_id }}</host-id>
|
||||
<network-interface>
|
||||
@@ -39,103 +39,11 @@
|
||||
</network-interface>
|
||||
</entry>
|
||||
{% if host_info.os_vendor == "Microsoft" -%}
|
||||
<entry name="antivirus">
|
||||
<list>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="1" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
|
||||
</Prod>
|
||||
<real-time-protection>yes</real-time-protection>
|
||||
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="1" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
|
||||
</Prod>
|
||||
<real-time-protection>no</real-time-protection>
|
||||
<last-full-scan-time>n/a</last-full-scan-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
</list>
|
||||
</entry>
|
||||
<entry name="anti-spyware">
|
||||
<list>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="2" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
|
||||
</Prod>
|
||||
<real-time-protection>yes</real-time-protection>
|
||||
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="2" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
|
||||
</Prod>
|
||||
<real-time-protection>no</real-time-protection>
|
||||
<last-full-scan-time>n/a</last-full-scan-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
</list>
|
||||
</entry>
|
||||
<entry name="disk-backup">
|
||||
<list>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Windows Backup and Restore" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
|
||||
</Prod>
|
||||
<last-backup-time>n/a</last-backup-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
</list>
|
||||
</entry>
|
||||
<entry name="disk-encryption">
|
||||
<list>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Windows Drive Encryption" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
|
||||
</Prod>
|
||||
<drives>
|
||||
<entry>
|
||||
<drive-name>C:\\</drive-name>
|
||||
<enc-state>full</enc-state>
|
||||
</entry>
|
||||
</drives>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
</list>
|
||||
</entry>
|
||||
<entry name="firewall">
|
||||
<list>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Microsoft Windows Firewall" version="10.0.22621.4830" vendor="Microsoft Corp.">
|
||||
</Prod>
|
||||
<is-enabled>yes</is-enabled>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
</list>
|
||||
</entry>
|
||||
<entry name="patch-management">
|
||||
<list>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="McAfee ePolicy Orchestrator Agent" version="5.0.5.658" vendor="McAfee, Inc.">
|
||||
</Prod>
|
||||
<is-enabled>yes</is-enabled>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Microsoft Windows Update Agent" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
|
||||
</Prod>
|
||||
<is-enabled>yes</is-enabled>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
</list>
|
||||
<missing-patches/>
|
||||
</entry>
|
||||
{% if let Some(categories) = &host_info.windows_categories -%}
|
||||
{{ categories|safe }}
|
||||
{% else -%}
|
||||
{% include "windows_emulation.xml" %}
|
||||
{% endif -%}
|
||||
{% elif host_info.os_vendor == "Apple" -%}
|
||||
<entry name="anti-malware">
|
||||
<list>
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
<entry name="anti-malware">
|
||||
<list>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="3" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
|
||||
</Prod>
|
||||
<real-time-protection>yes</real-time-protection>
|
||||
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="3" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
|
||||
</Prod>
|
||||
<real-time-protection>no</real-time-protection>
|
||||
<last-full-scan-time>n/a</last-full-scan-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
</list>
|
||||
</entry>
|
||||
<entry name="disk-backup">
|
||||
<list>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Windows Backup and Restore" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
|
||||
</Prod>
|
||||
<last-backup-time>n/a</last-backup-time>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
</list>
|
||||
</entry>
|
||||
<entry name="disk-encryption">
|
||||
<list>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Windows Drive Encryption" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
|
||||
</Prod>
|
||||
<drives>
|
||||
<entry>
|
||||
<drive-name>C:\</drive-name>
|
||||
<enc-state>encrypted</enc-state>
|
||||
</entry>
|
||||
</drives>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
</list>
|
||||
</entry>
|
||||
<entry name="firewall">
|
||||
<list>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Microsoft Windows Firewall" version="10.0.22621.4830" vendor="Microsoft Corp.">
|
||||
</Prod>
|
||||
<is-enabled>yes</is-enabled>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
</list>
|
||||
</entry>
|
||||
<entry name="patch-management">
|
||||
<list>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="McAfee ePolicy Orchestrator Agent" version="5.0.5.658" vendor="McAfee, Inc.">
|
||||
</Prod>
|
||||
<is-enabled>yes</is-enabled>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
<entry>
|
||||
<ProductInfo>
|
||||
<Prod name="Microsoft Windows Update Agent" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
|
||||
</Prod>
|
||||
<is-enabled>yes</is-enabled>
|
||||
</ProductInfo>
|
||||
</entry>
|
||||
</list>
|
||||
<missing-patches/>
|
||||
</entry>
|
||||
@@ -7,6 +7,7 @@ license = "MIT"
|
||||
links = "openconnect"
|
||||
|
||||
[dependencies]
|
||||
gp-xml = { path = "../gp-xml" }
|
||||
log.workspace = true
|
||||
libc = "0.2"
|
||||
is_executable.workspace = true
|
||||
|
||||
Submodule crates/openconnect/deps/openconnect updated: c312e48d4f...80b4f80926.
@@ -153,6 +153,14 @@ extern "C" fn on_vpn_connected(pipe_fd: CommandHandle, session_info: *const VpnS
|
||||
extern "C" fn vpn_log(level: i32, message: *const c_char) {
|
||||
let message = unsafe { std::ffi::CStr::from_ptr(message) };
|
||||
let message = message.to_str().unwrap_or("Invalid log message");
|
||||
// This dump comes from the native GlobalProtect protocol handler.
|
||||
if let Some(body) = message.strip_prefix("GlobalProtect getconfig.esp response:\n") {
|
||||
debug!(
|
||||
"GlobalProtect getconfig.esp response:\n{}",
|
||||
gp_xml::redact_xml(body.as_bytes())
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Strip the trailing newline
|
||||
let message = message.trim_end_matches('\n');
|
||||
|
||||
@@ -172,3 +180,41 @@ extern "C" fn vpn_log(level: i32, message: *const c_char) {
|
||||
debug!("{}", message);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod log_tests {
|
||||
use super::vpn_log;
|
||||
use std::sync::Mutex;
|
||||
|
||||
struct Capture(Mutex<String>);
|
||||
impl log::Log for Capture {
|
||||
fn enabled(&self, _: &log::Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
fn flush(&self) {}
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
if record.target() == module_path!().trim_end_matches("::log_tests") {
|
||||
self.0.lock().unwrap().push_str(&record.args().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_config_dump_keeps_settings_and_redacts_keys_before_logging() {
|
||||
static CAPTURE: Capture = Capture(Mutex::new(String::new()));
|
||||
log::set_logger(&CAPTURE).unwrap();
|
||||
log::set_max_level(log::LevelFilter::Debug);
|
||||
let message = c"GlobalProtect getconfig.esp response:\n<response><mtu>1400</mtu><akey-c2s><val>fixture-secret</val></akey-c2s><hs-key><bits>128</bits><val>fixture-handshake-key</val></hs-key></response>\n";
|
||||
vpn_log(2, message.as_ptr());
|
||||
vpn_log(
|
||||
2,
|
||||
c"GlobalProtect getconfig.esp response:\n<malformed>fixture-secret".as_ptr(),
|
||||
);
|
||||
let output = CAPTURE.0.lock().unwrap();
|
||||
assert!(output.contains("<mtu>1400</mtu>"));
|
||||
assert!(output.contains("[redacted]"));
|
||||
assert!(output.contains("[XML omitted:"));
|
||||
assert!(!output.contains("fixture-secret"));
|
||||
assert!(!output.contains("fixture-handshake-key"));
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,6 @@
|
||||
|
||||
linuxRuntimeDependencies = with pkgs; [
|
||||
glib-networking
|
||||
libayatana-appindicator
|
||||
xdg-utils
|
||||
];
|
||||
|
||||
@@ -174,7 +173,6 @@
|
||||
webkitgtk_4_1
|
||||
glib-networking
|
||||
libsecret
|
||||
libayatana-appindicator
|
||||
];
|
||||
|
||||
installNixosPolkitRule = ''
|
||||
|
||||
+2
-2
@@ -18,10 +18,10 @@ pkgs.stdenv.mkDerivation {
|
||||
);
|
||||
buildInputs = with pkgs;
|
||||
[ gnutls ] ++ (if nativeShell then [ gtk4 ] else [
|
||||
gtk3 webkitgtk_4_1 libsoup_3 glib-networking libsecret libayatana-appindicator
|
||||
gtk3 webkitgtk_4_1 libsoup_3 glib-networking libsecret
|
||||
]);
|
||||
runtimeDependencies = [ pkgs.libglvnd ] ++ pkgs.lib.optionals (!nativeShell) [
|
||||
pkgs.glib-networking pkgs.libayatana-appindicator
|
||||
pkgs.glib-networking
|
||||
];
|
||||
installPhase = ''
|
||||
runHook preInstall
|
||||
|
||||
@@ -10,7 +10,6 @@ license="GPL-3.0-only"
|
||||
depends="
|
||||
gmp
|
||||
gnutls
|
||||
libayatana-appindicator
|
||||
libsecret
|
||||
libxml2
|
||||
lz4
|
||||
@@ -30,7 +29,6 @@ makedepends="
|
||||
gmp-dev
|
||||
gnutls-dev
|
||||
gtk+3.0-dev
|
||||
libayatana-appindicator-dev
|
||||
libsecret-dev
|
||||
librsvg-dev
|
||||
libtool
|
||||
|
||||
@@ -10,7 +10,7 @@ url="https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
license=('GPL3')
|
||||
|
||||
makedepends=(git pkg-config make autoconf automake gettext libtool patch curl wget file appmenu-gtk-module librsvg cargo)
|
||||
depends=(webkit2gtk-4.1 libappindicator-gtk3 libsecret libxml2 zlib lz4 gnutls libp11-kit nettle libhogweed.so gmp shared-mime-info desktop-file-utils xdg-utils)
|
||||
depends=(webkit2gtk-4.1 libsecret libxml2 zlib lz4 gnutls libp11-kit nettle libhogweed.so gmp shared-mime-info desktop-file-utils xdg-utils)
|
||||
optdepends=('wmctrl: for window management')
|
||||
|
||||
conflicts=('globalprotect-openconnect')
|
||||
|
||||
@@ -23,10 +23,6 @@ deps: {
|
||||
origin: "security/gnutls"
|
||||
version: "*"
|
||||
}
|
||||
"libayatana-appindicator": {
|
||||
origin: "devel/libayatana-appindicator"
|
||||
version: "*"
|
||||
}
|
||||
"liblz4": {
|
||||
origin: "archivers/liblz4"
|
||||
version: "*"
|
||||
|
||||
@@ -19,7 +19,6 @@ Build-Depends: debhelper (>= 9),
|
||||
nettle-dev,
|
||||
libgmp-dev,
|
||||
libsecret-1-0,
|
||||
libayatana-appindicator3-1,
|
||||
gnome-keyring,
|
||||
libwebkit2gtk-4.1-dev,
|
||||
cargo-@RUST_VERSION@,
|
||||
@@ -33,7 +32,6 @@ Depends:
|
||||
${misc:Depends},
|
||||
${shlibs:Depends},
|
||||
libsecret-1-0,
|
||||
libayatana-appindicator3-1,
|
||||
gnome-keyring,
|
||||
xdg-utils,
|
||||
Description: A GUI client for GlobalProtect VPN
|
||||
|
||||
@@ -9,7 +9,7 @@ arch=('x86_64' 'aarch64')
|
||||
url="https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
license=('GPL3')
|
||||
makedepends=('make' 'pkg-config' 'cargo' 'file' 'autoconf' 'automake' 'gettext' 'libtool' 'patch')
|
||||
depends=('webkit2gtk-4.1' 'libappindicator-gtk3' 'librsvg' 'libsecret' 'appmenu-gtk-module'
|
||||
depends=('webkit2gtk-4.1' 'librsvg' 'libsecret' 'appmenu-gtk-module'
|
||||
'gnutls' 'libxml2' 'zlib' 'lz4' 'libp11-kit' 'nettle' 'libhogweed.so' 'gmp' 'xdg-utils')
|
||||
optdepends=('wmctrl: for window management')
|
||||
|
||||
|
||||
@@ -28,15 +28,9 @@ BuildRequires: file
|
||||
BuildRequires: perl
|
||||
|
||||
BuildRequires: pkgconfig(webkit2gtk-4.1)
|
||||
BuildRequires: (pkgconfig(appindicator3-0.1) or pkgconfig(ayatana-appindicator3-0.1))
|
||||
|
||||
BuildRequires: (librsvg2-devel or librsvg-devel)
|
||||
|
||||
%if 0%{?suse_version}
|
||||
Requires: (libappindicator3-1 or libayatana-appindicator3-1)
|
||||
%else
|
||||
Requires: (libappindicator-gtk3 or libayatana-appindicator-gtk3)
|
||||
%endif
|
||||
Requires: xdg-utils
|
||||
Conflicts: globalprotect-openconnect-snapshot
|
||||
|
||||
|
||||
@@ -11,6 +11,11 @@
|
||||
the payload. Each installer accepts only its native Windows architecture. ARM64
|
||||
requires Windows 11; x64 requires Windows 10 build 19041 or newer.
|
||||
|
||||
The native library build accepts `scripts/build-openconnect-windows.ps1 -TunnelType 'GP Connect'`
|
||||
(the default). This passes OpenConnect's `--with-wintun-tunnel-type` build option;
|
||||
OpenConnect itself defaults to `OpenConnect`. Wintun appends ` Tunnel` to the
|
||||
selected type. The gateway-based connection name is unchanged.
|
||||
|
||||
`BUILD_VERSION` must contain four numeric components. `PRODUCT_VERSION` must
|
||||
match the payload's `build-info.json`. `DISPLAY_VERSION` is the full release
|
||||
identity, including the snapshot build when applicable. The payload must contain matching
|
||||
@@ -19,7 +24,7 @@ vendor-signed `wintun.dll`, `licenses`, and `build-info.json`. The NSIS compiler
|
||||
adds the generated uninstaller; it is not a separately built executable.
|
||||
|
||||
The installer, extraction progress and uninstaller use the shared Windows icon
|
||||
from `apps/gpauth/icons/windows/icon.ico`. The Finish page uses `sidebar.bmp`,
|
||||
from `apps/gpauth/icons/windows/icon.ico`. The confirmation and Finish pages use `sidebar.bmp`,
|
||||
derived from that same icon. After regenerating application icons, run
|
||||
`powershell -NoProfile -File scripts/generate-windows-installer-artwork.ps1`
|
||||
on Windows and retain the updated bitmap before building installers.
|
||||
@@ -51,8 +56,36 @@ the current and previous attempt in ProgramData. No updater cache is added.
|
||||
|
||||
The installer never launches the GUI as administrator. Users open GP Connect
|
||||
from the Start menu after completion. User configuration and licensing state
|
||||
are retained during upgrades and uninstall. Authenticode setup is separate;
|
||||
WinSparkle must still verify the installer payload signature before handoff.
|
||||
are retained during upgrades and uninstall. Release builds use Azure Artifact
|
||||
Signing with GitHub OIDC and RFC 3161 timestamps. Application executables,
|
||||
the built OpenConnect DLL, and the generated NSIS uninstaller and installer
|
||||
are signed before checksums and WinSparkle signatures are generated.
|
||||
Vendor DLL signatures are preserved. WinSparkle independently verifies its
|
||||
installer payload signature before handoff.
|
||||
|
||||
The GitHub `windows-signing` environment is trusted by the Entra application
|
||||
`gp-connect-github-signing`. Its only Azure role is Artifact Signing Certificate
|
||||
Profile Signer on `tangramly-signing/certificateProfiles/gp-connect`.
|
||||
Environment deployment policies allow the `release/next` branch and `v*` tags.
|
||||
Repository variables supply `AZURE_SIGNING_CLIENT_ID`, `AZURE_TENANT_ID`,
|
||||
`AZURE_SUBSCRIPTION_ID`, `AZURE_SIGNING_ENDPOINT`, `AZURE_SIGNING_ACCOUNT`,
|
||||
`AZURE_SIGNING_PROFILE`, and `WINDOWS_SIGNING_PUBLISHER`. No Azure client secret
|
||||
or Authenticode private key is stored in GitHub. `build-windows.ps1 -Sign` requires
|
||||
Microsoft's ArtifactSigning PowerShell module 0.1.20 and an Azure CLI login.
|
||||
The build verifies the publisher, certificate trust and timestamp on each signed
|
||||
file. The installer smoke test repeats those checks on the installed runtime
|
||||
and uninstaller before testing removal.
|
||||
|
||||
The Start menu shortcut registers `System.AppUserModel.ID` as `com.yuezk.gpgui`,
|
||||
matching the GUI and native toast sender. Windows uses the shortcut's name and
|
||||
executable icon to identify GP Connect in Notification Center. Its identity is
|
||||
part of the shortcut, so the existing shortcut rollback and uninstall own its cleanup.
|
||||
|
||||
Manual launches show an Install/Cancel confirmation page (Update/Cancel when
|
||||
GP Connect is already installed). The update feed supplies `/UPDATE` through
|
||||
WinSparkle's `sparkle:installerArguments` to skip that page after the user has
|
||||
already confirmed the in-app update. This is not silent mode: elevation,
|
||||
installation progress, errors, and the Finish page remain visible.
|
||||
|
||||
The service log rotates after 5 MiB and retains three numbered archives, keeping
|
||||
each entry whole. The bundle includes `licenses/file-rotate.txt` for the Windows
|
||||
|
||||
@@ -2,6 +2,7 @@ Unicode true
|
||||
RequestExecutionLevel admin
|
||||
!include "MUI2.nsh"
|
||||
!include "x64.nsh"
|
||||
!include "FileFunc.nsh"
|
||||
|
||||
!ifndef PAYLOAD_DIR
|
||||
!error "PAYLOAD_DIR is required"
|
||||
@@ -21,6 +22,10 @@ RequestExecutionLevel admin
|
||||
!ifndef DISPLAY_VERSION
|
||||
!define DISPLAY_VERSION "${PRODUCT_VERSION}"
|
||||
!endif
|
||||
!ifdef SIGN_SCRIPT
|
||||
!uninstfinalize 'pwsh -NoLogo -NoProfile -NonInteractive -File "${SIGN_SCRIPT}" -Files "%1"' = 0
|
||||
!finalize 'pwsh -NoLogo -NoProfile -NonInteractive -File "${SIGN_SCRIPT}" -Files "%1"' = 0
|
||||
!endif
|
||||
|
||||
Name "GP Connect"
|
||||
OutFile "${OUTPUT_FILE}"
|
||||
@@ -33,12 +38,18 @@ VIAddVersionKey "FileVersion" "${BUILD_VERSION}"
|
||||
VIAddVersionKey "LegalCopyright" "GP Connect contributors"
|
||||
ShowInstDetails show
|
||||
ShowUninstDetails show
|
||||
Var InstallAction
|
||||
!define MUI_ICON "${__FILEDIR__}\..\..\apps\gpauth\icons\windows\icon.ico"
|
||||
!define MUI_UNICON "${MUI_ICON}"
|
||||
!define MUI_WELCOMEFINISHPAGE_BITMAP "${__FILEDIR__}\sidebar.bmp"
|
||||
!define MUI_ABORTWARNING
|
||||
!define MUI_FINISHPAGE_TITLE "GP Connect is ready"
|
||||
!define MUI_FINISHPAGE_TEXT "Open GP Connect from the Start menu."
|
||||
!define MUI_WELCOMEPAGE_TITLE "$InstallAction GP Connect"
|
||||
!define MUI_WELCOMEPAGE_TEXT "$InstallAction GP Connect for all users on this computer.$\r$\n$\r$\nClick $InstallAction to continue."
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE ConfirmInstall
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_SHOW ShowInstallAction
|
||||
!insertmacro MUI_PAGE_WELCOME
|
||||
!insertmacro MUI_PAGE_INSTFILES
|
||||
!insertmacro MUI_PAGE_FINISH
|
||||
!insertmacro MUI_UNPAGE_CONFIRM
|
||||
@@ -62,6 +73,25 @@ Function .onInit
|
||||
!error "Unsupported TARGET_ARCH"
|
||||
!endif
|
||||
SetRegView 64
|
||||
StrCpy $InstallAction "Install"
|
||||
ReadRegStr $0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GPConnect" "DisplayVersion"
|
||||
${If} $0 != ""
|
||||
StrCpy $InstallAction "Update"
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
Function ConfirmInstall
|
||||
${GetParameters} $0
|
||||
ClearErrors
|
||||
${GetOptions} $0 "/UPDATE" $1
|
||||
${IfNot} ${Errors}
|
||||
Abort
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
Function ShowInstallAction
|
||||
GetDlgItem $0 $HWNDPARENT 1
|
||||
SendMessage $0 ${WM_SETTEXT} 0 "STR:$InstallAction"
|
||||
FunctionEnd
|
||||
|
||||
Section "Install"
|
||||
|
||||
@@ -144,14 +144,68 @@ function Set-MachineState {
|
||||
} finally { $registry.Dispose() }
|
||||
}
|
||||
|
||||
function Set-ShortcutAppUserModelId([string]$Path, [string]$ApplicationId) {
|
||||
if (-not ('GPConnect.Installer.ShortcutIdentity' -as [type])) {
|
||||
# NSIS also extracts a native System.dll; reference the loaded .NET assembly explicitly.
|
||||
Add-Type -ReferencedAssemblies ([System.Uri].Assembly.Location) -TypeDefinition @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace GPConnect.Installer {
|
||||
public static class ShortcutIdentity {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct PropertyKey { public Guid Format; public uint Id; }
|
||||
|
||||
// PROPVARIANT is 24 bytes in both supported 64-bit architectures.
|
||||
[StructLayout(LayoutKind.Explicit, Size = 24)]
|
||||
private struct PropVariant {
|
||||
[FieldOffset(0)] public ushort Type;
|
||||
[FieldOffset(8)] public IntPtr Value;
|
||||
}
|
||||
|
||||
[ComImport, Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface IPropertyStore {
|
||||
void GetCount(out uint count);
|
||||
void GetAt(uint index, out PropertyKey key);
|
||||
void GetValue(ref PropertyKey key, out PropVariant value);
|
||||
void SetValue(ref PropertyKey key, ref PropVariant value);
|
||||
void Commit();
|
||||
}
|
||||
|
||||
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
|
||||
private static extern void SHGetPropertyStoreFromParsingName(
|
||||
string path, IntPtr context, uint flags, ref Guid iid, out IPropertyStore store);
|
||||
|
||||
public static void Set(string path, string applicationId) {
|
||||
var iid = typeof(IPropertyStore).GUID;
|
||||
IPropertyStore store;
|
||||
SHGetPropertyStoreFromParsingName(path, IntPtr.Zero, 2, ref iid, out store); // GPS_READWRITE
|
||||
var value = new PropVariant { Type = 31, Value = Marshal.StringToCoTaskMemUni(applicationId) }; // VT_LPWSTR
|
||||
try {
|
||||
var key = new PropertyKey { Format = new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), Id = 5 };
|
||||
store.SetValue(ref key, ref value); // PKEY_AppUserModel_ID
|
||||
store.Commit();
|
||||
} finally {
|
||||
Marshal.FreeCoTaskMem(value.Value);
|
||||
Marshal.ReleaseComObject(store);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
[GPConnect.Installer.ShortcutIdentity]::Set($Path, $ApplicationId)
|
||||
}
|
||||
|
||||
function Set-InstallationMetadata([string]$InstalledVersion) {
|
||||
$shell = New-Object -ComObject WScript.Shell
|
||||
$shortcut = $shell.CreateShortcut($shortcutPath)
|
||||
$shortcut.TargetPath = Join-Path $destination 'gpgui.exe'
|
||||
$shortcut.WorkingDirectory = $destination
|
||||
$shortcut.Description = 'GP Connect'
|
||||
$shortcut.Description = 'A GUI client for GlobalProtect VPN'
|
||||
$shortcut.IconLocation = (Join-Path $destination 'gpgui.exe') + ',0'
|
||||
$shortcut.Save()
|
||||
Set-ShortcutAppUserModelId $shortcutPath 'com.yuezk.gpgui'
|
||||
if (Test-Path -LiteralPath (Join-Path $destination 'uninstall.exe')) {
|
||||
New-Item -Path $uninstallKey -Force | Out-Null
|
||||
$values = @{
|
||||
@@ -227,7 +281,7 @@ try {
|
||||
if ($source -eq $destination -or $source.StartsWith($destination + '\', [StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw 'Install from an extracted package outside the application folder.'
|
||||
}
|
||||
foreach ($name in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'libopenconnect-5.dll', 'wintun.dll', 'build-info.json')) {
|
||||
foreach ($name in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'gp-posture.exe', 'libopenconnect-5.dll', 'wintun.dll', 'build-info.json')) {
|
||||
if (!(Test-Path -LiteralPath (Join-Path $source $name) -PathType Leaf)) { throw "Missing Windows package file: $name" }
|
||||
}
|
||||
$info = Get-Content -LiteralPath (Join-Path $source 'build-info.json') -Raw | ConvertFrom-Json
|
||||
@@ -249,7 +303,7 @@ try {
|
||||
$payload = @(Get-ChildItem -LiteralPath $source -Force | Where-Object {
|
||||
($_.PSIsContainer -and $_.Name -eq 'licenses') -or
|
||||
(!$_.PSIsContainer -and ($_.Extension -eq '.dll' -or
|
||||
$_.Name -in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'uninstall.exe', 'build-info.json')))
|
||||
$_.Name -in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'gp-posture.exe', 'uninstall.exe', 'build-info.json')))
|
||||
})
|
||||
foreach ($item in $payload) {
|
||||
$items = @($item)
|
||||
|
||||
@@ -5,7 +5,8 @@ param(
|
||||
[string]$MsysRoot = 'C:\msys64',
|
||||
[ValidateSet('mingw64','ucrt64','clangarm64')][string]$MsysSubsystem = 'mingw64',
|
||||
[string]$Prefix,
|
||||
[int]$Jobs = 4
|
||||
[int]$Jobs = 4,
|
||||
[ValidateNotNullOrEmpty()][string]$TunnelType = 'GP Connect'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = Split-Path $PSScriptRoot -Parent
|
||||
@@ -14,7 +15,7 @@ $Prefix = [System.IO.Path]::GetFullPath($Prefix)
|
||||
$bash = Join-Path $MsysRoot 'usr\bin\bash.exe'
|
||||
if (!(Test-Path $bash)) { throw 'MSYS2 is required to build OpenConnect.' }
|
||||
$ErrorActionPreference = 'Continue'
|
||||
& $bash "$PSScriptRoot/build-openconnect-windows.sh" $repo $Prefix $Jobs $MsysSubsystem
|
||||
& $bash "$PSScriptRoot/build-openconnect-windows.sh" $repo $Prefix $Jobs $MsysSubsystem $TunnelType
|
||||
$nativeExit = $LASTEXITCODE
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($nativeExit -ne 0) { throw 'OpenConnect compilation failed.' }
|
||||
|
||||
@@ -6,6 +6,7 @@ export PATH="/$subsystem/bin:/usr/bin:$PATH"
|
||||
repo=$(cygpath -u "$1")
|
||||
prefix=$(cygpath -u "$2")
|
||||
jobs=$3
|
||||
tunnel_type=$5
|
||||
export ACLOCAL_PATH="/$subsystem/share/aclocal"
|
||||
source_dir="$repo/crates/openconnect/deps/openconnect"
|
||||
build_dir="$repo/target/openconnect-windows"
|
||||
@@ -22,7 +23,7 @@ fi
|
||||
--enable-shared --disable-static --disable-nls --disable-docs --disable-dsa-tests \
|
||||
--without-libproxy --without-stoken --without-libpcsclite --without-libpskc \
|
||||
--without-gssapi --with-gnutls --without-openssl --with-gnutls-tss2=no \
|
||||
--with-vpnc-script=unused
|
||||
--with-vpnc-script=unused --with-wintun-tunnel-type="$tunnel_type"
|
||||
grep -q '^#define OPENCONNECT_GNUTLS 1$' config.h
|
||||
make -j"$jobs" libopenconnect.la
|
||||
make install-libLTLIBRARIES
|
||||
|
||||
@@ -1,33 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Retain one source pair per build run so retries cannot move branch refs."""
|
||||
"""Retain one source and version identity per build run, including retries."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def record(path, gp, gpgui, output):
|
||||
def record(path, gp, gpgui, output, build_version):
|
||||
if path.exists():
|
||||
sources = json.loads(path.read_text())
|
||||
identity = json.loads(path.read_text())
|
||||
else:
|
||||
sources = {
|
||||
identity = {
|
||||
name: subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"],
|
||||
text=True, stderr=subprocess.DEVNULL).strip()
|
||||
for name, root in (("gp_sha", gp), ("gpgui_sha", gpgui))
|
||||
}
|
||||
if set(sources) != {"gp_sha", "gpgui_sha"} or any(
|
||||
cargo_version = runpy.run_path(str(Path(__file__).with_name("validate-release-version.py")))["cargo_version"]
|
||||
version = cargo_version(gp)
|
||||
if cargo_version(gpgui) != version:
|
||||
raise ValueError("public and desktop product versions differ")
|
||||
identity.update(version=version, build_version=build_version)
|
||||
if set(identity) != {"gp_sha", "gpgui_sha", "version", "build_version"} or any(
|
||||
not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{40}", value)
|
||||
for value in sources.values()
|
||||
for name, value in identity.items() if name.endswith("_sha")
|
||||
):
|
||||
raise ValueError("invalid retained build source refs")
|
||||
if not isinstance(identity["version"], str) or not re.fullmatch(r"\d+\.\d+\.\d+", identity["version"]):
|
||||
raise ValueError("invalid retained product version")
|
||||
if not isinstance(identity["build_version"], str) or not re.fullmatch(
|
||||
r"(0|[1-9]\d*)\.(0|[1-9]\d*)", identity["build_version"]
|
||||
):
|
||||
raise ValueError("invalid retained build version")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(sources, indent=2) + "\n")
|
||||
path.write_text(json.dumps(identity, indent=2) + "\n")
|
||||
with output.open("a") as stream:
|
||||
for name, sha in sources.items():
|
||||
stream.write(f"{name}={sha}\n")
|
||||
for name, value in identity.items():
|
||||
stream.write(f"{name}={value}\n")
|
||||
|
||||
|
||||
def main():
|
||||
@@ -35,9 +47,10 @@ def main():
|
||||
parser.add_argument("path", type=Path)
|
||||
parser.add_argument("--gp", type=Path, required=True)
|
||||
parser.add_argument("--gpgui", type=Path, required=True)
|
||||
parser.add_argument("--build-version", required=True)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
record(args.path, args.gp, args.gpgui, Path(os.environ["GITHUB_OUTPUT"]))
|
||||
record(args.path, args.gp, args.gpgui, Path(os.environ["GITHUB_OUTPUT"]), args.build_version)
|
||||
except (OSError, ValueError, subprocess.CalledProcessError):
|
||||
parser.exit(1, "Could not retain the selected build source refs.\n")
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory=$true)][string[]]$Files)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
foreach ($name in @('AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_SIGNING_PROFILE', 'WINDOWS_SIGNING_PUBLISHER')) {
|
||||
if (![Environment]::GetEnvironmentVariable($name)) { throw "Missing signing configuration: $name" }
|
||||
}
|
||||
Import-Module ArtifactSigning -RequiredVersion 0.1.20
|
||||
$credentials = @{
|
||||
ExcludeEnvironmentCredential = $true
|
||||
ExcludeWorkloadIdentityCredential = $true
|
||||
ExcludeManagedIdentityCredential = $true
|
||||
ExcludeSharedTokenCacheCredential = $true
|
||||
ExcludeVisualStudioCredential = $true
|
||||
ExcludeVisualStudioCodeCredential = $true
|
||||
ExcludeAzurePowerShellCredential = $true
|
||||
ExcludeAzureDeveloperCliCredential = $true
|
||||
ExcludeInteractiveBrowserCredential = $true
|
||||
}
|
||||
# Azure CLI holds the short-lived GitHub OIDC login; no client secret is used.
|
||||
Invoke-ArtifactSigning -Endpoint $env:AZURE_SIGNING_ENDPOINT `
|
||||
-CodeSigningAccountName $env:AZURE_SIGNING_ACCOUNT -CertificateProfileName $env:AZURE_SIGNING_PROFILE `
|
||||
-Files ($Files -join ',') -FileDigest SHA256 -TimestampDigest SHA256 `
|
||||
-TimestampRfc3161 'http://timestamp.acs.microsoft.com' -Description 'GP Connect' @credentials
|
||||
& (Join-Path $PSScriptRoot 'test-windows-signature.ps1') -Files $Files -Publisher $env:WINDOWS_SIGNING_PUBLISHER
|
||||
@@ -60,6 +60,6 @@ run_stage 'Frontend tests' 5m \
|
||||
run_stage 'Frontend build' 10m \
|
||||
docker exec --workdir "$workspace" "$container" pnpm --filter gpgui build
|
||||
run_stage 'Compile Rust tests' 30m \
|
||||
docker exec --workdir "$workspace" "$container" cargo test --workspace --locked --no-run
|
||||
docker exec --workdir "$workspace" "$container" cargo test --workspace --locked --features gpapi/openssl-tests --no-run
|
||||
run_stage 'Rust tests' 10m \
|
||||
docker exec --workdir "$workspace" "$container" cargo test --workspace --locked
|
||||
docker exec --workdir "$workspace" "$container" cargo test --workspace --locked --features gpapi/openssl-tests
|
||||
@@ -20,14 +20,34 @@ if ($process.ExitCode -ne 0) {
|
||||
}
|
||||
$info = Get-Content (Join-Path $destination 'build-info.json') -Raw | ConvertFrom-Json
|
||||
if ($info.architecture -ne $Architecture -or [string]$info.build_version -ne $Build) { throw 'The installed package identity does not match.' }
|
||||
if ($env:WINDOWS_SIGNING_PUBLISHER) {
|
||||
$signed = @($Installer)
|
||||
foreach ($name in @('gpgui.exe', 'gpauth.exe', 'gpservice.exe', 'gp-posture.exe', 'libopenconnect-5.dll', 'uninstall.exe')) {
|
||||
$signed += Join-Path $destination $name
|
||||
}
|
||||
& (Join-Path $PSScriptRoot 'test-windows-signature.ps1') -Files $signed -Publisher $env:WINDOWS_SIGNING_PUBLISHER
|
||||
}
|
||||
$service = Get-CimInstance Win32_Service -Filter "Name='GPConnect'"
|
||||
if ($service.State -ne 'Running' -or $service.StartMode -ne 'Auto' -or $service.StartName -ne 'LocalSystem') {
|
||||
throw 'The service did not start automatically as LocalSystem.'
|
||||
}
|
||||
$shortcut = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\GP Connect.lnk'
|
||||
$shell = New-Object -ComObject Shell.Application
|
||||
$link = $shell.Namespace((Split-Path $shortcut)).ParseName((Split-Path $shortcut -Leaf))
|
||||
if (!$link -or $link.ExtendedProperty('System.AppUserModel.ID') -ne 'com.yuezk.gpgui') {
|
||||
throw 'The Start menu shortcut does not register the notification application identity.'
|
||||
}
|
||||
foreach ($name in @('gpgui.exe', 'gpauth.exe')) {
|
||||
$process = Start-Process (Join-Path $destination $name) -ArgumentList '--version' -PassThru -Wait
|
||||
if ($process.ExitCode -ne 0) { throw "The installed $name cannot start." }
|
||||
}
|
||||
$helper = Join-Path $destination 'gp-posture.exe'
|
||||
$output = Join-Path $env:TEMP 'gp-posture-install-test.json'
|
||||
$process = Start-Process $helper -PassThru -Wait -RedirectStandardOutput $output
|
||||
if ($process.ExitCode -ne 0) { throw 'The installed posture helper failed.' }
|
||||
$report = Get-Content $output -Raw | ConvertFrom-Json
|
||||
if ($null -eq $report.anti_malware -or $null -eq $report.firewall) { throw 'Invalid posture helper output.' }
|
||||
Remove-Item $output
|
||||
$state = Join-Path $env:LOCALAPPDATA 'GP Connect\config\protected-state'
|
||||
New-Item -ItemType Directory -Force $state | Out-Null
|
||||
$marker = Join-Path $state 'ci-install-retention'
|
||||
@@ -37,7 +57,6 @@ if ($process.ExitCode -ne 0) { throw 'The uninstaller failed.' }
|
||||
if ((Get-Service GPConnect -ErrorAction SilentlyContinue) -or (Test-Path $destination) -or (Test-Path ($destination + '.previous'))) {
|
||||
throw 'The uninstaller left service registration or runtime files.'
|
||||
}
|
||||
$shortcut = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\GP Connect.lnk'
|
||||
if ((Test-Path $shortcut) -or (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GPConnect')) {
|
||||
throw 'The uninstaller left its shortcut or registration.'
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string[]]$Files,
|
||||
[Parameter(Mandatory=$true)][string]$Publisher
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
foreach ($file in $Files) {
|
||||
$signature = Get-AuthenticodeSignature -LiteralPath $file
|
||||
if ($signature.Status -ne 'Valid') { throw "Invalid Authenticode signature: $file ($($signature.Status))" }
|
||||
$name = $signature.SignerCertificate.GetNameInfo([Security.Cryptography.X509Certificates.X509NameType]::SimpleName, $false)
|
||||
if ($name -ne $Publisher) { throw "Unexpected signing publisher for ${file}: $name" }
|
||||
if (!$signature.TimeStamperCertificate) { throw "Missing signature timestamp: $file" }
|
||||
Write-Host "Verified $file (publisher: $name; timestamped)"
|
||||
}
|
||||
@@ -90,24 +90,43 @@ class ReleaseVersionTests(unittest.TestCase):
|
||||
versions.validate(root, package=package)
|
||||
|
||||
|
||||
class SourceSelectionTests(unittest.TestCase):
|
||||
class BuildIdentityTests(unittest.TestCase):
|
||||
def test_retry_uses_original_sources_after_both_branches_advance(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
paths = [root / 'gp', root / 'gpgui']
|
||||
for repo in paths:
|
||||
initialize(repo)
|
||||
write_version(repo)
|
||||
(repo / 'source').write_text('first')
|
||||
commit(repo, 'first')
|
||||
path, output = root / 'sources.json', root / 'output'
|
||||
sources.record(path, *paths, output)
|
||||
sources.record(path, *paths, output, '42.1')
|
||||
original = json.loads(path.read_text())
|
||||
for repo in paths:
|
||||
write_version(repo, '3.2.0')
|
||||
(repo / 'source').write_text('second')
|
||||
commit(repo, 'second')
|
||||
sources.record(path, *paths, output)
|
||||
sources.record(path, *paths, output, '42.2')
|
||||
self.assertEqual(json.loads(path.read_text()), original)
|
||||
self.assertEqual(output.read_text().count(f"gp_sha={original['gp_sha']}"), 2)
|
||||
self.assertEqual(original['version'], '3.1.0')
|
||||
self.assertEqual(original['build_version'], '42.1')
|
||||
sources.record(path, root / 'missing-gp', root / 'missing-gui', output, '42.3')
|
||||
self.assertEqual(json.loads(path.read_text()), original)
|
||||
|
||||
def test_mismatched_product_versions_are_not_retained(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
paths = [root / 'gp', root / 'gpgui']
|
||||
for repo, version in zip(paths, ['3.1.0', '3.2.0']):
|
||||
initialize(repo)
|
||||
write_version(repo, version)
|
||||
commit(repo, 'source')
|
||||
path = root / 'sources.json'
|
||||
with self.assertRaisesRegex(ValueError, 'versions differ'):
|
||||
sources.record(path, *paths, root / 'output', '42.1')
|
||||
self.assertFalse(path.exists())
|
||||
|
||||
def test_corrupt_retained_sources_do_not_resolve_again(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
@@ -115,7 +134,7 @@ class SourceSelectionTests(unittest.TestCase):
|
||||
path = root / 'sources.json'
|
||||
path.write_text('{"gp_sha":"main","gpgui_sha":"main"}')
|
||||
with self.assertRaises(ValueError):
|
||||
sources.record(path, root, root, root / 'output')
|
||||
sources.record(path, root, root, root / 'output', '42.1')
|
||||
|
||||
|
||||
class PromotionTests(unittest.TestCase):
|
||||
@@ -196,6 +215,65 @@ class SnapshotBranchTests(unittest.TestCase):
|
||||
self.assertEqual(git(origin, 'branch', '--list', 'main'), '')
|
||||
|
||||
|
||||
class PublicationWorkflowTests(unittest.TestCase):
|
||||
def job(self, name):
|
||||
source = (ROOT / '.github/workflows/build.yaml').read_text()
|
||||
return re.search(r'(?ms)^ ' + name + r':\n.*?(?=^ [\w-]+:|\Z)', source).group(0)
|
||||
|
||||
def decisions(self, name, cases):
|
||||
expression = re.search(r'\$\{\{ (.*?) \}\}', self.job(name), re.DOTALL).group(1)
|
||||
expression = re.sub(r'needs\.([\w-]+)\.result', r'needs["\1"].result', expression)
|
||||
script = """
|
||||
const cases = JSON.parse(process.argv[1]);
|
||||
const allows = new Function('needs', 'inputs', 'github', 'cancelled',
|
||||
'return (' + process.argv[2] + ')');
|
||||
console.log(JSON.stringify(cases.map(c => allows(c.needs, c.inputs, c.github, () => c.cancelled))));
|
||||
"""
|
||||
return json.loads(subprocess.check_output(
|
||||
['node', '-e', script, json.dumps(cases), expression], text=True))
|
||||
|
||||
def test_macos_assets_require_both_jobs_and_a_live_run(self):
|
||||
job = self.job('publish-macos-assets')
|
||||
self.assertIn('needs: [build-macos, gh-release]', job)
|
||||
self.assertIn('uses: ./.github/workflows/publish-macos-assets.yaml', job)
|
||||
cases, expected = [], []
|
||||
for macos in ['success', 'failure', 'skipped', 'cancelled']:
|
||||
for release in ['success', 'failure', 'skipped', 'cancelled']:
|
||||
for cancelled in [False, True]:
|
||||
cases.append({'needs': {'build-macos': {'result': macos},
|
||||
'gh-release': {'result': release}},
|
||||
'inputs': {}, 'github': {}, 'cancelled': cancelled})
|
||||
expected.append(not cancelled and macos == release == 'success')
|
||||
self.assertEqual(self.decisions('publish-macos-assets', cases), expected)
|
||||
|
||||
def test_snapshot_feeds_follow_selection_and_publication_results(self):
|
||||
cases, expected_windows, expected_macos = [], [], []
|
||||
for macos in [False, True]:
|
||||
for windows in [False, True]:
|
||||
for override in [{}, {'channel': 'stable'}, {'build_only': True},
|
||||
{'event': 'push'}, {'cancelled': True}, {'release': 'failure'},
|
||||
{'macos_publish': 'failure'}, {'windows_feed': 'failure'}]:
|
||||
inputs = dict(channel='snapshot', build_only=False,
|
||||
build_macos=macos, build_windows=windows)
|
||||
inputs.update({key: value for key, value in override.items() if key in inputs})
|
||||
release = override.get('release', 'success')
|
||||
macos_publish = override.get('macos_publish', 'success') if macos else 'skipped'
|
||||
windows_feed = override.get('windows_feed', 'success') if windows else 'skipped'
|
||||
cancelled = override.get('cancelled', False)
|
||||
event = override.get('event', 'workflow_dispatch')
|
||||
cases.append({'needs': {'gh-release': {'result': release},
|
||||
'publish-macos-assets': {'result': macos_publish},
|
||||
'publish-windows-snapshot-feed': {'result': windows_feed}},
|
||||
'inputs': inputs, 'github': {'event_name': event}, 'cancelled': cancelled})
|
||||
ready = (not cancelled and event == 'workflow_dispatch' and
|
||||
inputs['channel'] == 'snapshot' and not inputs['build_only'] and
|
||||
release == 'success' and (not macos or macos_publish == 'success'))
|
||||
expected_windows.append(ready and windows)
|
||||
expected_macos.append(ready and macos and (not windows or windows_feed == 'success'))
|
||||
self.assertEqual(self.decisions('publish-windows-snapshot-feed', cases), expected_windows)
|
||||
self.assertEqual(self.decisions('publish-macos-unix-snapshot-feeds', cases), expected_macos)
|
||||
|
||||
|
||||
class DockerMatrixTests(unittest.TestCase):
|
||||
def test_workflow_matrix_follows_all_architecture_choices(self):
|
||||
source = (ROOT / '.github/workflows/release.yaml').read_text()
|
||||
|
||||
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user