Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd08cdbe66 | ||
|
|
d12d677208 | ||
|
|
d15ebdfe3a | ||
|
|
4f8f828a0b | ||
|
|
c3188ce1c8 | ||
|
|
e509cbccdb | ||
|
|
1ea9327f18 | ||
|
|
69e4183202 | ||
|
|
4b61c84c37 | ||
|
|
3a8080eb2f | ||
|
|
6040ced26b | ||
|
|
ddd2137143 | ||
|
|
915c130c70 | ||
|
|
9b297b14a6 | ||
|
|
69d67721a6 | ||
|
|
935240f9b5 | ||
|
|
e15422a64f | ||
|
|
dfab3882e1 | ||
|
|
4cf17f6256 | ||
|
|
ac81463a3b | ||
|
|
4faa2ecb0d | ||
|
|
56751a755c | ||
|
|
18ed6bac1a | ||
|
|
10139e0f2c | ||
|
|
ff1ea259d9 | ||
|
|
57322e3cf3 | ||
|
|
9532374805 | ||
|
|
90faa58811 | ||
|
|
93504eaec2 | ||
|
|
d73b712dd3 | ||
|
|
be111a671a | ||
|
|
f9965f8a35 | ||
|
|
f7649898fd | ||
|
|
e6910060df | ||
|
|
f41a429a5e | ||
|
|
888f288c0d | ||
|
|
f0292a9292 | ||
|
|
580b81e7bb | ||
|
|
8724ed3b37 | ||
|
|
01075cb6dc | ||
|
|
b7b708e9cd | ||
|
|
0425ee6ddb | ||
|
|
9e4f45997e | ||
|
|
3882e29b0e | ||
|
|
32bac9b675 | ||
|
|
0e1aedce82 | ||
|
|
8eb4d48887 | ||
|
|
87f91e3c13 | ||
|
|
f9f9dd8abe | ||
|
|
2283d4a076 | ||
|
|
d75e422c1d | ||
|
|
0c2d4830b5 | ||
|
|
3c49eab0c8 | ||
|
|
13ec7dfc37 | ||
|
|
e98fd7894a | ||
|
|
6f860d3dff | ||
|
|
5902bee5ff | ||
|
|
66f48b3ff6 | ||
|
|
0f7d065628 | ||
|
|
494e4a5331 | ||
|
|
b5b71df6e6 | ||
|
|
49f410e63b | ||
|
|
225acf13aa | ||
|
|
61d2b702c0 | ||
|
|
3276ac0f9a | ||
|
|
0b037e158c | ||
|
|
10e94e0b81 | ||
|
|
0f76539075 | ||
|
|
f9b8c55924 | ||
|
|
a708ce0115 | ||
|
|
b3f4ba0a32 | ||
|
|
02cf4a0b26 | ||
|
|
370189cbee | ||
|
|
6746cf64c3 | ||
|
|
40739739b5 | ||
|
|
dc7a200b93 | ||
|
|
f49b6471f3 | ||
|
|
4da922aa3b | ||
|
|
ecc9c9f09c | ||
|
|
b32002710b | ||
|
|
7b6d20a003 | ||
|
|
d27029fad8 | ||
|
|
1b488ba696 | ||
|
|
f78f7c9bc8 | ||
|
|
7e11693ce3 | ||
|
|
c601fa9aa2 | ||
|
|
536a43773f | ||
|
|
ae4cbedd3b | ||
|
|
fe55d11fc4 | ||
|
|
34f1feaf43 | ||
|
|
f640b4d325 | ||
|
|
a35b4a289e | ||
|
|
a7a5d9bf96 | ||
|
|
888dc93643 | ||
|
|
f98e0336dc | ||
|
|
7a571f9b27 | ||
|
|
67de92044f | ||
|
|
7d63836e35 | ||
|
|
3e23fc7d22 | ||
|
|
8bf05d381e | ||
|
|
1ab36a1137 | ||
|
|
18b788e664 | ||
|
|
ebadab8f06 | ||
|
|
81d13deaab | ||
|
|
6f91a79081 | ||
|
|
4d252fa31c | ||
|
|
398475c649 | ||
|
|
13d4aa398c | ||
|
|
9423665fe5 | ||
|
|
5e8dbfa26d | ||
|
|
d96b3f9c0d | ||
|
|
7720942681 | ||
|
|
f129ca7ea1 | ||
|
|
628d0febdd | ||
|
|
add284d3b4 | ||
|
|
a3f2224952 | ||
|
|
966bcc554b | ||
|
|
d6e3a212f2 | ||
|
|
e45b4a4145 | ||
|
|
93a7f4bd10 | ||
|
|
d1401171d8 | ||
|
|
9591ca287e | ||
|
|
46c80ecc93 | ||
|
|
99d2a26d45 | ||
|
|
067037517e | ||
|
|
c04b49fe11 | ||
|
|
a044cb35ad | ||
|
|
ac4b6240ef | ||
|
|
0c3af0d60d | ||
|
|
6289e1539a | ||
|
|
08a77f9d38 | ||
|
|
fb6db0dc12 | ||
|
|
731a0d895c | ||
|
|
ab58dd6cec | ||
|
|
cdcf03ff2f | ||
|
|
1d715f059d | ||
|
|
88951d863b | ||
|
|
0d5d06ead0 | ||
|
|
3171bb9fd1 | ||
|
|
d48b29025e | ||
|
|
d06ce925ac | ||
|
|
5ace087f92 | ||
|
|
a51f034036 | ||
|
|
982562874a | ||
|
|
45fe7165f3 | ||
|
|
d0f6a67be1 | ||
|
|
8461c73bc3 | ||
|
|
238a4ee1e3 | ||
|
|
253f995dc6 | ||
|
|
0972c89ee1 | ||
|
|
13a4b928ed | ||
|
|
c6b47eef6a | ||
|
|
a1afe3f1e3 | ||
|
|
a3672ba764 | ||
|
|
d01ef9d394 | ||
|
|
dad4f13f64 | ||
|
|
4f477901d9 | ||
|
|
d3ffefa897 | ||
|
|
93f786452d | ||
|
|
635fd9f8bf | ||
|
|
e4295a6ce8 | ||
|
|
e4426df6a2 | ||
|
|
65a93041aa | ||
|
|
8287a669fb | ||
|
|
48d96dbb9d | ||
|
|
bd613382bc | ||
|
|
3eda3afba4 | ||
|
|
d7ec1c16a2 | ||
|
|
d241d48f52 | ||
|
|
67954d7c4b | ||
|
|
977725868a | ||
|
|
e2acdd7df2 | ||
|
|
ae50155fbd | ||
|
|
24f9bbbccb | ||
|
|
1b4ea720a6 | ||
|
|
7d87442f73 | ||
|
|
f398ccadb7 | ||
|
|
740c79af9b | ||
|
|
d0096c6cb2 | ||
|
|
e4701c1bd8 | ||
|
|
a08ae655cf | ||
|
|
a917e16e62 | ||
|
|
8ed3304e61 | ||
|
|
c40fd051e5 | ||
|
|
09cd8ecb18 | ||
|
|
a4e1743691 | ||
|
|
801a339525 | ||
|
|
49a7cbfe99 | ||
|
|
603975bfe0 | ||
|
|
49fe7447ff | ||
|
|
7048248268 | ||
|
|
cad5ca3d68 | ||
|
|
9e9ab6fb7d | ||
|
|
8e55698271 | ||
|
|
47338b21a8 | ||
|
|
4c307e05f5 | ||
|
|
b56659b0b4 | ||
|
|
e3c3b6e89e | ||
|
|
f1a8a3c19a | ||
|
|
986b63391a | ||
|
|
9b180ad90c | ||
|
|
6079dc6aee | ||
|
|
2bd7371c7a | ||
|
|
e1eb191def | ||
|
|
a9d2de06b5 | ||
|
|
2aa875a626 | ||
|
|
e4fa429dcc | ||
|
|
5ba7bf2e18 | ||
|
|
11925a372d | ||
|
|
e1eb9e20f1 | ||
|
|
1d3aa889d5 | ||
|
|
c1ab26aef3 | ||
|
|
ea9819d161 | ||
|
|
dc9480fd71 | ||
|
|
fa2849a080 | ||
|
|
c70c7ee5b9 | ||
|
|
fe3d3df662 | ||
|
|
2f90b73683 | ||
|
|
5186e80c6f | ||
|
|
4ff1c1dc1f | ||
|
|
c1427040f6 | ||
|
|
a7ad02acb6 | ||
|
|
b188d61be1 | ||
|
|
ec85e857bc | ||
|
|
d37ccafdc2 | ||
|
|
0c9b8e6c63 | ||
|
|
8f8ad466f4 | ||
|
|
0f67be465b | ||
|
|
ed7c8ca1a1 | ||
|
|
f71e29de5c | ||
|
|
a641453388 | ||
|
|
366b95ce1f | ||
|
|
136c870d1f | ||
|
|
0c411a542f | ||
|
|
1e70dd088f | ||
|
|
2dc7f97ff0 | ||
|
|
6542d677a9 | ||
|
|
222fe26cea | ||
|
|
ed413ee029 | ||
|
|
516d685c9e | ||
|
|
54e2371022 | ||
|
|
511cc5ebd7 |
No files matched your search
@@ -0,0 +1,6 @@
|
||||
BasedOnStyle: LLVM
|
||||
IndentWidth: 8
|
||||
TabWidth: 8
|
||||
UseTab: Always
|
||||
ColumnLimit: 80
|
||||
BreakBeforeBraces: Linux
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM ubuntu:18.04
|
||||
FROM ubuntu:22.04
|
||||
|
||||
ARG USERNAME=vscode
|
||||
ARG USER_UID=1000
|
||||
@@ -7,45 +7,63 @@ ARG USER_GID=$USER_UID
|
||||
ENV RUSTUP_HOME=/usr/local/rustup \
|
||||
CARGO_HOME=/usr/local/cargo \
|
||||
PATH=/usr/local/cargo/bin:$PATH \
|
||||
RUST_VERSION=1.75.0
|
||||
RUST_VERSION=1.89.0 \
|
||||
DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Install all system dependencies in a single layer and clean up apt cache
|
||||
RUN set -eux; \
|
||||
apt-get update; \
|
||||
apt-get install -y --no-install-recommends \
|
||||
# Common utilities
|
||||
dh-autoreconf \
|
||||
sudo \
|
||||
ca-certificates \
|
||||
curl \
|
||||
gnupg \
|
||||
git \
|
||||
less \
|
||||
wget \
|
||||
file \
|
||||
software-properties-common \
|
||||
# libopenconnect-dev to install the related dependencies for building openconnect from source
|
||||
# Otherwise, we have to install them manually one by one
|
||||
libopenconnect-dev \
|
||||
# Tauri dependencies
|
||||
libwebkit2gtk-4.0-dev build-essential wget libssl-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev; \
|
||||
# Install openconnect
|
||||
add-apt-repository ppa:yuezk/globalprotect-openconnect; \
|
||||
apt-get update; \
|
||||
apt-get install -y openconnect libopenconnect-dev; \
|
||||
# Create a non-root user
|
||||
libwebkit2gtk-4.1-dev \
|
||||
build-essential \
|
||||
libxdo-dev \
|
||||
libssl-dev \
|
||||
libayatana-appindicator3-dev \
|
||||
librsvg2-dev; \
|
||||
# Clean up apt cache to reduce image size
|
||||
apt-get clean; \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Create a non-root user
|
||||
RUN set -eux; \
|
||||
groupadd --gid $USER_GID $USERNAME; \
|
||||
useradd --uid $USER_UID --gid $USER_GID -m $USERNAME; \
|
||||
echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME; \
|
||||
chmod 0440 /etc/sudoers.d/$USERNAME; \
|
||||
# Install Node.js
|
||||
mkdir -p /etc/apt/keyrings; \
|
||||
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg; \
|
||||
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_16.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list; \
|
||||
apt-get update; \
|
||||
apt-get install -y nodejs; \
|
||||
corepack enable; \
|
||||
# Install diff-so-fancy
|
||||
npm install -g diff-so-fancy; \
|
||||
# Install Rust
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain $RUST_VERSION; \
|
||||
chmod 0440 /etc/sudoers.d/$USERNAME
|
||||
|
||||
# Install Rust
|
||||
RUN set -eux; \
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain $RUST_VERSION --profile minimal; \
|
||||
chown -R $USERNAME:$USERNAME $RUSTUP_HOME $CARGO_HOME; \
|
||||
rustup --version; \
|
||||
cargo --version; \
|
||||
rustc --version
|
||||
|
||||
# Install Node.js and global npm packages
|
||||
RUN set -eux; \
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -; \
|
||||
apt-get install -y --no-install-recommends nodejs; \
|
||||
corepack enable; \
|
||||
npm install -g diff-so-fancy; \
|
||||
# Clean up apt cache
|
||||
apt-get clean; \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
USER $USERNAME
|
||||
|
||||
# Install Oh My Zsh
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
.build
|
||||
.git
|
||||
.vendor
|
||||
apps/gpgui-helper/node_modules
|
||||
target
|
||||
vendor.tar.xz
|
||||
@@ -8,5 +8,9 @@ end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[{*.c,*.h}]
|
||||
indent_style = tab
|
||||
indent_size = 8
|
||||
|
||||
[{Makefile,Makefile.in}]
|
||||
indent_style = tab
|
||||
@@ -1,30 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Logs**
|
||||
- For the GUI version, you can find the logs at `~/.local/share/gpclient/gpclient.log`
|
||||
- For the CLI version, copy the output of the `gpclient` command.
|
||||
|
||||
**Environment:**
|
||||
- OS: [e.g. Ubuntu 22.04]
|
||||
- Desktop Environment: [e.g. GNOME or KDE]
|
||||
- Output of `ps aux | grep 'gnome-keyring\|kwalletd5' | grep -v grep`: [Required for secure store error]
|
||||
- Is remote SSH? [Yes/No]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,115 @@
|
||||
name: Bug report
|
||||
description: Report a problem with GP Connect or gpclient.
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thank you for reporting a problem. You can report against your installed version; you do not need to upgrade first.
|
||||
|
||||
Review everything before posting. Remove passwords, cookies, tokens, SAML payloads, and private VPN addresses. Do not attach a complete environment dump.
|
||||
- type: dropdown
|
||||
id: component
|
||||
attributes:
|
||||
label: Affected component
|
||||
options:
|
||||
- CLI connection
|
||||
- GP Connect GUI
|
||||
- Login window or browser authentication
|
||||
- Installation or update
|
||||
- Credential storage
|
||||
- Other or unsure
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Application version
|
||||
description: Run gpclient --version, or use the version shown in the GUI's About dialog. Include helper versions if relevant.
|
||||
placeholder: "For example: gpclient 3.0.1"
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: installation
|
||||
attributes:
|
||||
label: Installation method
|
||||
options:
|
||||
- APT
|
||||
- AUR
|
||||
- RPM package or repository
|
||||
- Nix
|
||||
- Homebrew
|
||||
- Downloaded release package
|
||||
- FreeBSD or OpenBSD package
|
||||
- Source build
|
||||
- Other or unknown
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: os
|
||||
attributes:
|
||||
label: Operating system and version
|
||||
description: Include the Linux distribution, macOS version, or FreeBSD/OpenBSD version, and architecture if known.
|
||||
placeholder: "For example: Fedora 43 x86_64, macOS 26 arm64, or FreeBSD 14.4 amd64"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: reproduction
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: Include the exact command and options, or the GUI steps. Replace private portal names with a placeholder and omit credentials.
|
||||
placeholder: |
|
||||
1. Run sudo gpclient connect <portal> --browser
|
||||
2. ...
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: Actual behavior
|
||||
description: Describe the failure and any error message.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: regression
|
||||
attributes:
|
||||
label: Last working version and recent changes
|
||||
description: If this worked before, give the last working app version and any recent OS, desktop, graphics driver, or package updates. It is okay if you do not know.
|
||||
- type: textarea
|
||||
id: diagnostics
|
||||
attributes:
|
||||
label: Diagnostics
|
||||
description: Run gpclient diagnostics as your normal desktop user, without sudo. If the command is unavailable, use the standalone script linked below or provide the relevant information manually. Reports include raw desktop identifiers and are not guaranteed anonymous; review before posting.
|
||||
render: text
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
**Older versions:** download and inspect the [standalone diagnostic script](https://github.com/yuezk/GlobalProtect-openconnect/blob/dev/scripts/collect-diagnostics.sh), then run it with `sh collect-diagnostics.sh`. See [collection instructions](https://github.com/yuezk/GlobalProtect-openconnect/blob/dev/docs/diagnostics.md). Do not pipe a download directly into a shell.
|
||||
|
||||
If you cannot run either collector, provide the relevant details below. You do not need graphics details for unrelated connection problems.
|
||||
- type: textarea
|
||||
id: rendering
|
||||
attributes:
|
||||
label: Window or rendering failures only
|
||||
description: Desktop/compositor and version; Wayland or X11; GPU and driver version; GTK/WebKitGTK version when available; VM or remote session; any rendering environment overrides. Skip for unrelated problems. The diagnostics report may already contain this information.
|
||||
- type: textarea
|
||||
id: authentication
|
||||
attributes:
|
||||
label: Authentication or credential storage failures only
|
||||
description: Embedded login window or external browser (name/version)? At what stage does it stop? For credential storage errors, include the keyring implementation or macOS Keychain error. Omit cookies, tokens, passwords, and SAML data.
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Relevant logs
|
||||
description: For the CLI, paste relevant terminal output. For the GUI, use its built-in option to open or export logs, if available. Review and remove sensitive authentication data before posting; avoid full verbose logs unless requested.
|
||||
render: text
|
||||
- type: textarea
|
||||
id: screenshots
|
||||
attributes:
|
||||
label: Screenshots and additional context
|
||||
description: Attach screenshots if helpful. Hide private portal names, account details, and other sensitive content.
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Checkout private source quietly
|
||||
description: Fetch private source without printing Git diagnostics or retaining credentials.
|
||||
inputs:
|
||||
token:
|
||||
required: true
|
||||
description: Token with read access to the private repository
|
||||
ref:
|
||||
required: true
|
||||
description: Branch, tag, or full commit SHA
|
||||
path:
|
||||
required: true
|
||||
description: Destination within the workspace
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- shell: bash
|
||||
env:
|
||||
PRIVATE_TOKEN: ${{ inputs.token }}
|
||||
PRIVATE_REF: ${{ inputs.ref }}
|
||||
PRIVATE_PATH: ${{ inputs.path }}
|
||||
run: |
|
||||
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private source checkout failed; diagnostics suppressed."; fi' EXIT
|
||||
(
|
||||
set -euo pipefail
|
||||
export GIT_TERMINAL_PROMPT=0
|
||||
export GIT_CONFIG_COUNT=1
|
||||
export GIT_CONFIG_KEY_0=http.https://github.com/.extraheader
|
||||
GIT_CONFIG_VALUE_0="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$PRIVATE_TOKEN" | base64 | tr -d '\n')"
|
||||
export GIT_CONFIG_VALUE_0
|
||||
git init "$PRIVATE_PATH"
|
||||
git -C "$PRIVATE_PATH" remote add origin https://github.com/yuezk/gpgui
|
||||
git -C "$PRIVATE_PATH" fetch --no-tags --depth=1 -- origin "$PRIVATE_REF"
|
||||
git -C "$PRIVATE_PATH" checkout --detach FETCH_HEAD
|
||||
) >/dev/null 2>&1
|
||||
echo "Private source checkout passed."
|
||||
@@ -0,0 +1,64 @@
|
||||
name: Prepare cached macOS native dependencies
|
||||
description: Cache only the completed public native-library prefix, without private source or app outputs.
|
||||
inputs:
|
||||
gpgui-directory:
|
||||
description: Private checkout containing the native dependency builder
|
||||
required: true
|
||||
outputs:
|
||||
prefix:
|
||||
description: Validated native dependency installation prefix
|
||||
value: ${{ steps.identity.outputs.path }}
|
||||
cache-hit:
|
||||
description: Whether the exact dependency cache was restored
|
||||
value: ${{ steps.restore.outputs.cache-hit }}
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Identify native dependency cache
|
||||
id: identity
|
||||
shell: bash
|
||||
env:
|
||||
GPGUI_DIRECTORY: ${{ inputs.gpgui-directory }}
|
||||
GPGUI_MACOS_DEPS_CACHE_DIR: ${{ runner.tool_cache }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Native dependency cache identification failed; diagnostics suppressed."; fi' EXIT
|
||||
metadata="$("$GPGUI_DIRECTORY/scripts/build-macos-native-deps.sh" --cache-info 2>/dev/null)"
|
||||
key="$(printf '%s\n' "$metadata" | sed -n 's/^key=//p')"
|
||||
prefix="$(printf '%s\n' "$metadata" | sed -n 's/^path=//p')"
|
||||
# Emit only an opaque identity and one dependency directory outside the checkout.
|
||||
if [[ "$key" =~ ^[0-9a-f]{64}$ ]] &&
|
||||
[[ "$metadata" == "key=$key"$'\n'"path=$prefix" ]] &&
|
||||
[[ "${prefix%/*}" == "$RUNNER_TOOL_CACHE/gpgui-macos-native-deps" ]] &&
|
||||
[[ "${prefix##*/}" == macos-*-"$key" ]]; then
|
||||
printf 'key=macos-native-deps-%s\npath=%s\n' "$key" "$prefix" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Restore public native libraries
|
||||
id: restore
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: ${{ steps.identity.outputs.path }}
|
||||
key: ${{ steps.identity.outputs.key }}
|
||||
|
||||
- name: Build or validate native libraries
|
||||
shell: bash
|
||||
env:
|
||||
GPGUI_DIRECTORY: ${{ inputs.gpgui-directory }}
|
||||
GPGUI_MACOS_DEPS_CACHE_DIR: ${{ runner.tool_cache }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Native dependency preparation failed; diagnostics suppressed."; fi' EXIT
|
||||
started=$SECONDS
|
||||
"$GPGUI_DIRECTORY/scripts/build-macos-native-deps.sh" >/dev/null 2>&1
|
||||
echo "Native dependency preparation passed in $((SECONDS - started)) seconds."
|
||||
|
||||
# Save before any private application compilation or signing credential import.
|
||||
- name: Save public native libraries
|
||||
if: steps.restore.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: ${{ steps.identity.outputs.path }}
|
||||
key: ${{ steps.identity.outputs.key }}
|
||||
@@ -0,0 +1,127 @@
|
||||
name: Build Linux GUI
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
gp_ref:
|
||||
required: true
|
||||
type: string
|
||||
gpgui_ref:
|
||||
required: true
|
||||
type: string
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
builder:
|
||||
required: true
|
||||
type: string
|
||||
artifact_suffix:
|
||||
default: ""
|
||||
type: string
|
||||
verify_desktop_assets:
|
||||
default: false
|
||||
type: boolean
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os:
|
||||
- runner: ubuntu-latest
|
||||
arch: amd64
|
||||
- runner: ubuntu-24.04-arm
|
||||
arch: ubuntu-24.04-arm
|
||||
runs-on: ${{ matrix.os.runner }}
|
||||
name: build (${{ matrix.os.arch }})
|
||||
steps:
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: 9
|
||||
- name: Prepare workspace
|
||||
run: rm -rf gpgui-source && mkdir gpgui-source
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
repository: yuezk/GlobalProtect-openconnect
|
||||
ref: ${{ inputs.gp_ref }}
|
||||
path: gpgui-source/gp
|
||||
submodules: recursive
|
||||
- name: Checkout CI helpers
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
path: .ci
|
||||
persist-credentials: false
|
||||
- name: Checkout gpgui
|
||||
uses: ./.ci/.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: gpgui-source/gpgui
|
||||
- name: Verify Linux desktop assets
|
||||
if: matrix.os.arch == 'amd64' && inputs.verify_desktop_assets
|
||||
run: |
|
||||
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
|
||||
(
|
||||
set -euo pipefail
|
||||
gpgui-source/gp/scripts/verify-linux-desktop-assets.sh gpgui-source/gpgui
|
||||
) >/dev/null 2>&1
|
||||
echo "Private operation passed."
|
||||
|
||||
- name: Tarball
|
||||
run: |
|
||||
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
|
||||
(
|
||||
set -euo pipefail
|
||||
cd gpgui-source
|
||||
tar -czf gpgui.tar.gz gpgui gp
|
||||
) >/dev/null 2>&1
|
||||
echo "Private operation passed."
|
||||
|
||||
- name: Build gpgui in Docker
|
||||
env:
|
||||
GPGUI_BUILDER: ${{ inputs.builder }}
|
||||
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
run: |
|
||||
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
|
||||
(
|
||||
set -euo pipefail
|
||||
docker run --rm \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-e GPGUI_BUILD_VERSION \
|
||||
-e GPGUI_UPDATE_CHANNEL \
|
||||
-e GPGUI_LICENSE_SIGNING_KEYS \
|
||||
-v "$(pwd)/gpgui-source:/workspace" "yuezk/gpdev:$GPGUI_BUILDER"
|
||||
) >/dev/null 2>&1
|
||||
echo "Private operation passed."
|
||||
|
||||
- name: Install gpgui in Docker
|
||||
env:
|
||||
GPGUI_BUILDER: ${{ inputs.builder }}
|
||||
run: |
|
||||
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
|
||||
(
|
||||
set -euo pipefail
|
||||
cd gpgui-source
|
||||
tar -xJf ./*.bin.tar.xz
|
||||
docker run --rm \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-v "$(pwd):/workspace" "yuezk/gpdev:$GPGUI_BUILDER" \
|
||||
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
|
||||
) >/dev/null 2>&1
|
||||
echo "Private operation passed."
|
||||
|
||||
- name: Upload gpgui
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: artifact-gpgui${{ inputs.artifact_suffix }}-${{ matrix.os.arch }}
|
||||
if-no-files-found: error
|
||||
path: |
|
||||
gpgui-source/*.bin.tar.xz
|
||||
gpgui-source/*.bin.tar.xz.sha256
|
||||
@@ -0,0 +1,109 @@
|
||||
name: Build Linux Native Shell
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
gp_ref:
|
||||
required: true
|
||||
type: string
|
||||
gpgui_ref:
|
||||
required: true
|
||||
type: string
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: ubuntu-24.04
|
||||
arch: x86_64
|
||||
- runner: ubuntu-24.04-arm
|
||||
arch: aarch64
|
||||
runs-on: ${{ matrix.runner }}
|
||||
name: build (${{ matrix.arch }})
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
CARGO_INCREMENTAL: '0'
|
||||
CARGO_BUILD_JOBS: '2'
|
||||
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
||||
GPGUI_GIT_COMMIT: ${{ inputs.gpgui_ref }}
|
||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
steps:
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ inputs.gp_ref }}
|
||||
path: source/gp
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
- name: Checkout CI helpers
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
path: .ci
|
||||
persist-credentials: false
|
||||
- name: Checkout gpgui
|
||||
uses: ./.ci/.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: source/gpgui
|
||||
- name: Install Ubuntu 24.04 dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y autoconf automake gettext libtool pkg-config \
|
||||
clang libclang-dev libgtk-4-dev libxml2-dev \
|
||||
libgnutls28-dev liblz4-dev libwayland-dev libxkbcommon-dev libdbus-1-dev
|
||||
pkg-config --exists gtk4 gnutls dbus-1 wayland-client xkbcommon
|
||||
- name: Install the NSH compiler
|
||||
run: rustup toolchain install 1.97.0 --profile minimal
|
||||
- name: Cache public crate downloads
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/registry/index
|
||||
key: nsh-crates-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('source/gpgui/apps/desktop-nsh/Cargo.lock') }}
|
||||
restore-keys: nsh-crates-${{ runner.os }}-${{ runner.arch }}-
|
||||
- name: Build and package Native Shell
|
||||
run: |
|
||||
trap 'code=$?; if [ "$code" -ne 0 ]; then echo "::error::Native Shell build failed; diagnostics suppressed."; fi' EXIT
|
||||
(
|
||||
set -euo pipefail
|
||||
cd source/gpgui
|
||||
cargo +1.97.0 build --manifest-path apps/desktop-nsh/Cargo.toml --locked \
|
||||
--release --bin gpgui-nsh --target-dir target
|
||||
target/release/gpgui-nsh --version
|
||||
version="$(cargo +1.97.0 metadata --manifest-path apps/desktop-nsh/Cargo.toml --no-deps --format-version 1 \
|
||||
| jq -r '.packages[] | select(.name == "gpgui-nsh") | .version')"
|
||||
directory="gpgui-nsh_$version"
|
||||
archive="gpgui-nsh_$(uname -m).bin.tar.xz"
|
||||
mkdir -p ".build/package/$directory"
|
||||
cp target/release/gpgui-nsh ".build/package/$directory/"
|
||||
cp apps/desktop-nsh/ICU4X-LICENSE.txt ".build/package/$directory/ICU4X-LICENSE.txt"
|
||||
if ldd target/release/gpgui-nsh | grep -q 'libicu'; then
|
||||
echo "The release executable must not depend on ICU4C." >&2
|
||||
exit 1
|
||||
fi
|
||||
tar -cJf ".build/package/$archive" -C .build/package "$directory"
|
||||
sha256sum ".build/package/$archive" | cut -d ' ' -f 1 > ".build/package/$archive.sha256"
|
||||
) >/dev/null 2>&1
|
||||
echo "Native Shell build and version check passed."
|
||||
- name: Upload Native Shell
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: artifact-gpgui-nsh-${{ matrix.arch }}
|
||||
if-no-files-found: error
|
||||
path: |
|
||||
source/gpgui/.build/package/*.bin.tar.xz
|
||||
source/gpgui/.build/package/*.bin.tar.xz.sha256
|
||||
@@ -0,0 +1,67 @@
|
||||
name: Check macOS native dependency cache
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
gpgui_ref:
|
||||
description: Full gpgui commit SHA
|
||||
required: true
|
||||
type: string
|
||||
workflow_call:
|
||||
inputs:
|
||||
gpgui_ref:
|
||||
required: true
|
||||
type: string
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ${{ vars.MACOS_RUNNER || 'macos-15' }}
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Require immutable source ref
|
||||
env:
|
||||
GPGUI_REF: ${{ inputs.gpgui_ref }}
|
||||
run: test "${#GPGUI_REF}" -eq 40 && [[ "$GPGUI_REF" != *[!0-9a-f]* ]]
|
||||
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
path: .ci
|
||||
persist-credentials: false
|
||||
|
||||
- name: Checkout gpgui quietly
|
||||
uses: ./.ci/.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: source/gpgui
|
||||
|
||||
- name: Select release toolchain and install native build tools
|
||||
env:
|
||||
DEVELOPER_DIR: /Applications/Xcode_26.3.app/Contents/Developer
|
||||
run: |
|
||||
test "$(uname -m)" = arm64
|
||||
xcodebuild -version
|
||||
echo "DEVELOPER_DIR=$DEVELOPER_DIR" >> "$GITHUB_ENV"
|
||||
brew install autoconf automake gettext libtool meson ninja pkgconf
|
||||
|
||||
- name: Prepare cached native dependencies
|
||||
id: native
|
||||
uses: ./.ci/.github/actions/macos-native-deps
|
||||
with:
|
||||
gpgui-directory: source/gpgui
|
||||
|
||||
- name: Record cache result
|
||||
env:
|
||||
CACHE_HIT: ${{ steps.native.outputs.cache-hit }}
|
||||
run: |
|
||||
if [[ "$CACHE_HIT" == true ]]; then
|
||||
echo "Validated an exact native dependency cache hit." >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo "Built and validated native dependencies after a cache miss." >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
@@ -0,0 +1,139 @@
|
||||
name: Check NSH
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
gp_ref:
|
||||
description: 'Full GlobalProtect-openconnect commit SHA'
|
||||
required: true
|
||||
type: string
|
||||
gpgui_ref:
|
||||
description: 'Full gpgui commit SHA'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
workflow_call:
|
||||
inputs:
|
||||
gp_ref:
|
||||
required: true
|
||||
type: string
|
||||
gpgui_ref:
|
||||
required: true
|
||||
type: string
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check:
|
||||
name: NSH (${{ matrix.platform }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 90
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: linux
|
||||
runner: ubuntu-24.04
|
||||
- platform: macos
|
||||
runner: ${{ vars.MACOS_RUNNER || 'macos-15' }}
|
||||
env:
|
||||
CARGO_INCREMENTAL: '0'
|
||||
CARGO_BUILD_JOBS: '2'
|
||||
steps:
|
||||
- name: Require immutable source refs
|
||||
env:
|
||||
GP_REF: ${{ inputs.gp_ref }}
|
||||
GPGUI_REF: ${{ inputs.gpgui_ref }}
|
||||
run: |
|
||||
[[ "$GP_REF" =~ ^[0-9a-f]{40}$ && "$GPGUI_REF" =~ ^[0-9a-f]{40}$ ]] || {
|
||||
echo "Both source refs must be full commit SHAs."
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ inputs.gp_ref }}
|
||||
path: source/gp
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
- name: Checkout CI helpers
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
path: .ci
|
||||
persist-credentials: false
|
||||
- name: Checkout gpgui
|
||||
uses: ./.ci/.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: source/gpgui
|
||||
|
||||
- name: Install Linux dependencies
|
||||
if: matrix.platform == 'linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y autoconf automake gettext libtool pkg-config \
|
||||
clang libclang-dev libgtk-4-dev libxml2-dev \
|
||||
libgnutls28-dev liblz4-dev libwayland-dev libxkbcommon-dev libdbus-1-dev
|
||||
pkg-config --exists gtk4 gnutls dbus-1 wayland-client xkbcommon
|
||||
- name: Install macOS dependencies
|
||||
if: matrix.platform == 'macos'
|
||||
env:
|
||||
DEVELOPER_DIR: /Applications/Xcode_26.3.app/Contents/Developer
|
||||
run: |
|
||||
xcodebuild -version
|
||||
echo "DEVELOPER_DIR=$DEVELOPER_DIR" >> "$GITHUB_ENV"
|
||||
brew install autoconf automake gettext libtool pkgconf gnutls libxml2 lz4
|
||||
echo "$(brew --prefix gettext)/bin" >> "$GITHUB_PATH"
|
||||
echo "ACLOCAL_PATH=$(brew --prefix gettext)/share/aclocal" >> "$GITHUB_ENV"
|
||||
echo "PKG_CONFIG_PATH=$(brew --prefix libxml2)/lib/pkgconfig:$(brew --prefix gnutls)/lib/pkgconfig" >> "$GITHUB_ENV"
|
||||
- name: Install the NSH compiler
|
||||
run: rustup toolchain install 1.97.0 --profile minimal
|
||||
- name: Cache public crate downloads
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
# Private source and build outputs stay out of the public cache.
|
||||
path: |
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/registry/index
|
||||
key: nsh-crates-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('source/gpgui/apps/desktop-nsh/Cargo.lock') }}
|
||||
restore-keys: nsh-crates-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Check demo-free NSH production
|
||||
timeout-minutes: 30
|
||||
run: |
|
||||
diagnostics="$(mktemp)"
|
||||
trap 'code=$?; if [ "$code" -ne 0 ]; then echo "::error::NSH production check failed; diagnostics suppressed."; python3 .ci/scripts/private-ci-diagnostics.py compile "$diagnostics" || true; fi; rm -f "$diagnostics"' EXIT
|
||||
(
|
||||
set -euo pipefail
|
||||
cd source/gpgui
|
||||
cargo +1.97.0 check --manifest-path apps/desktop-nsh/Cargo.toml --locked --bin gpgui-nsh
|
||||
) >"$diagnostics" 2>&1
|
||||
echo "NSH production check passed."
|
||||
- name: Compile NSH tests
|
||||
timeout-minutes: 30
|
||||
run: |
|
||||
diagnostics="$(mktemp)"
|
||||
trap 'code=$?; if [ "$code" -ne 0 ]; then echo "::error::NSH test compilation failed; diagnostics suppressed."; python3 .ci/scripts/private-ci-diagnostics.py compile "$diagnostics" || true; fi; rm -f "$diagnostics"' EXIT
|
||||
(
|
||||
set -euo pipefail
|
||||
cd source/gpgui
|
||||
cargo +1.97.0 test --manifest-path apps/desktop-nsh/Cargo.toml --locked --features demo --no-run
|
||||
) >"$diagnostics" 2>&1
|
||||
echo "NSH test compilation passed."
|
||||
- name: Run NSH tests
|
||||
timeout-minutes: 10
|
||||
run: |
|
||||
diagnostics="$(mktemp)"
|
||||
trap 'code=$?; if [ "$code" -ne 0 ]; then echo "::error::NSH tests failed; diagnostics suppressed."; python3 .ci/scripts/private-ci-diagnostics.py tests "$diagnostics" || true; fi; rm -f "$diagnostics"' EXIT
|
||||
(
|
||||
set -euo pipefail
|
||||
cd source/gpgui
|
||||
cargo +1.97.0 test --manifest-path apps/desktop-nsh/Cargo.toml --locked --features demo -- --test-threads=1
|
||||
) >"$diagnostics" 2>&1
|
||||
echo "NSH tests passed."
|
||||
@@ -0,0 +1,34 @@
|
||||
name: Desktop icon compatibility
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/desktop-icons.yaml'
|
||||
- 'scripts/tests/test_desktop_icon.py'
|
||||
- 'packaging/files/usr/share/icons/**'
|
||||
- 'apps/gpgui-helper/src-tauri/icons/**'
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.github/workflows/desktop-icons.yaml'
|
||||
- 'scripts/tests/test_desktop_icon.py'
|
||||
- 'packaging/files/usr/share/icons/**'
|
||||
- 'apps/gpgui-helper/src-tauri/icons/**'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
render:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-22.04, ubuntu-24.04]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Install the distro SVG loader
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y python3-gi gir1.2-gdkpixbuf-2.0 librsvg2-common
|
||||
- name: Render desktop icons
|
||||
run: /usr/bin/python3 -m unittest discover -s scripts/tests -p test_desktop_icon.py
|
||||
@@ -0,0 +1,128 @@
|
||||
name: Nix
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "Cargo.toml"
|
||||
- "scripts/validate-release-version.py"
|
||||
- "flake.nix"
|
||||
- "flake.lock"
|
||||
- "nix/**"
|
||||
- ".github/workflows/nix.yaml"
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "Cargo.toml"
|
||||
- "scripts/validate-release-version.py"
|
||||
- "flake.nix"
|
||||
- "flake.lock"
|
||||
- "nix/**"
|
||||
- ".github/workflows/nix.yaml"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
standalone-package:
|
||||
name: standalone-package (${{ matrix.platform.system }})
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform:
|
||||
- runner: ubuntu-latest
|
||||
system: x86_64-linux
|
||||
- runner: ubuntu-24.04-arm
|
||||
system: aarch64-linux
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
steps:
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
|
||||
- name: Build standalone prebuilt package
|
||||
run: |
|
||||
nix build .#prebuilt \
|
||||
--extra-experimental-features "nix-command flakes" \
|
||||
--print-build-logs
|
||||
|
||||
- name: Check installed release versions
|
||||
run: python3 scripts/validate-release-version.py --package result
|
||||
|
||||
- name: Inspect prebuilt package
|
||||
run: |
|
||||
test -x result/bin/gpclient
|
||||
test -x result/bin/gpauth
|
||||
test -x result/bin/gpservice
|
||||
test -x result/bin/gpgui-helper
|
||||
test -x result/bin/gpgui
|
||||
|
||||
nixos-module:
|
||||
name: nixos-module (${{ matrix.platform.system }}, ${{ matrix.nixpkgs }})
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform:
|
||||
- runner: ubuntu-latest
|
||||
system: x86_64-linux
|
||||
- runner: ubuntu-24.04-arm
|
||||
system: aarch64-linux
|
||||
nixpkgs:
|
||||
- nixos-25.11
|
||||
- nixos-26.05
|
||||
- nixpkgs-unstable
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
steps:
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
|
||||
- name: Build package through host NixOS module
|
||||
env:
|
||||
NIXPKGS_URL: github:NixOS/nixpkgs/${{ matrix.nixpkgs }}
|
||||
NIX_SYSTEM: ${{ matrix.platform.system }}
|
||||
run: |
|
||||
nix build \
|
||||
--impure \
|
||||
--extra-experimental-features "nix-command flakes" \
|
||||
--print-build-logs \
|
||||
--expr '
|
||||
let
|
||||
gp = builtins.getFlake (toString ./.);
|
||||
hostNixpkgs =
|
||||
builtins.getFlake (builtins.getEnv "NIXPKGS_URL");
|
||||
|
||||
hostSystem = hostNixpkgs.lib.nixosSystem {
|
||||
system = builtins.getEnv "NIX_SYSTEM";
|
||||
modules = [
|
||||
gp.nixosModules.default
|
||||
{
|
||||
programs.globalprotect-openconnect.enable = true;
|
||||
system.stateVersion = "25.11";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
package =
|
||||
hostSystem.config.programs.globalprotect-openconnect.package;
|
||||
in
|
||||
assert builtins.elem package
|
||||
hostSystem.config.environment.systemPackages;
|
||||
assert hostSystem.config.services.ayatana-indicators.enable;
|
||||
package
|
||||
'
|
||||
|
||||
- name: Check installed release versions
|
||||
run: python3 scripts/validate-release-version.py --package result
|
||||
|
||||
- name: Inspect module package
|
||||
run: |
|
||||
test -x result/bin/gpclient
|
||||
test -x result/bin/gpauth
|
||||
test -x result/bin/gpservice
|
||||
test -x result/bin/gpgui-helper
|
||||
test -x result/bin/gpgui
|
||||
@@ -0,0 +1,185 @@
|
||||
name: Publish AUR git package
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build-package:
|
||||
type: boolean
|
||||
description: "Build the package before publishing"
|
||||
required: true
|
||||
default: true
|
||||
publish:
|
||||
type: boolean
|
||||
description: "Push PKGBUILD, .SRCINFO, and gp.install to AUR"
|
||||
required: true
|
||||
default: true
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- packaging/aur/globalprotect-openconnect-git/**
|
||||
- .github/workflows/publish-aur-git.yaml
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Validate AUR package
|
||||
runs-on: ubuntu-latest
|
||||
container: archlinux:base-devel
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
AUR_PACKAGE_DIR: packaging/aur/globalprotect-openconnect-git
|
||||
steps:
|
||||
- name: Install checkout tools
|
||||
run: pacman -Syu --noconfirm --needed git openssh
|
||||
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Install build tools
|
||||
run: |
|
||||
pacman -Syu --noconfirm --needed \
|
||||
appmenu-gtk-module \
|
||||
autoconf \
|
||||
automake \
|
||||
cargo \
|
||||
curl \
|
||||
desktop-file-utils \
|
||||
file \
|
||||
git \
|
||||
gettext \
|
||||
gmp \
|
||||
gnutls \
|
||||
libappindicator-gtk3 \
|
||||
libp11-kit \
|
||||
libsecret \
|
||||
libtool \
|
||||
libxml2 \
|
||||
lz4 \
|
||||
make \
|
||||
namcap \
|
||||
nettle \
|
||||
patch \
|
||||
pkgconf \
|
||||
librsvg \
|
||||
shared-mime-info \
|
||||
wget \
|
||||
webkit2gtk-4.1 \
|
||||
xdg-utils \
|
||||
zlib
|
||||
|
||||
- name: Save committed .SRCINFO
|
||||
if: ${{ github.event_name == 'push' }}
|
||||
run: cp "$AUR_PACKAGE_DIR/.SRCINFO" /tmp/committed.SRCINFO
|
||||
|
||||
- name: Prepare build user
|
||||
run: |
|
||||
useradd -m builder
|
||||
chown -R builder:builder "$GITHUB_WORKSPACE"
|
||||
|
||||
- name: Refresh VCS package version
|
||||
if: ${{ github.event_name == 'workflow_dispatch' }}
|
||||
run: |
|
||||
cd "$AUR_PACKAGE_DIR"
|
||||
runuser -u builder -- makepkg --nobuild --noconfirm --cleanbuild
|
||||
|
||||
- name: Regenerate .SRCINFO
|
||||
run: |
|
||||
cd "$AUR_PACKAGE_DIR"
|
||||
runuser -u builder -- makepkg --printsrcinfo > .SRCINFO
|
||||
|
||||
- name: Check committed .SRCINFO
|
||||
if: ${{ github.event_name == 'push' }}
|
||||
run: |
|
||||
cmp -s /tmp/committed.SRCINFO "$AUR_PACKAGE_DIR/.SRCINFO" || {
|
||||
diff -u /tmp/committed.SRCINFO "$AUR_PACKAGE_DIR/.SRCINFO"
|
||||
echo ".SRCINFO is out of date. Regenerate it with makepkg --printsrcinfo." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Run namcap
|
||||
run: |
|
||||
cd "$AUR_PACKAGE_DIR"
|
||||
runuser -u builder -- namcap PKGBUILD
|
||||
|
||||
- name: Build package
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs['build-package'] }}
|
||||
run: |
|
||||
cd "$AUR_PACKAGE_DIR"
|
||||
runuser -u builder -- makepkg --noconfirm --clean --cleanbuild
|
||||
|
||||
- name: Upload AUR package metadata
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: aur-package-metadata
|
||||
path: |
|
||||
${{ env.AUR_PACKAGE_DIR }}/PKGBUILD
|
||||
${{ env.AUR_PACKAGE_DIR }}/.SRCINFO
|
||||
${{ env.AUR_PACKAGE_DIR }}/gp.install
|
||||
if-no-files-found: error
|
||||
include-hidden-files: true
|
||||
overwrite: true
|
||||
|
||||
publish:
|
||||
name: Publish to AUR
|
||||
needs: validate
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
|
||||
runs-on: ubuntu-latest
|
||||
container: archlinux:base-devel
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
AUR_PACKAGE_DIR: /tmp/aur-package
|
||||
AUR_REPO: ssh://[email protected]/globalprotect-openconnect-git.git
|
||||
steps:
|
||||
- name: Install publish tools
|
||||
run: pacman -Syu --noconfirm --needed git openssh
|
||||
|
||||
- name: Download AUR package metadata
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: aur-package-metadata
|
||||
path: ${{ env.AUR_PACKAGE_DIR }}
|
||||
|
||||
- name: Configure SSH
|
||||
env:
|
||||
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||
run: |
|
||||
if [[ -z "$AUR_SSH_PRIVATE_KEY" ]]; then
|
||||
echo "AUR_SSH_PRIVATE_KEY is required to publish to AUR" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
install -d -m 700 ~/.ssh
|
||||
printf '%s\n' "$AUR_SSH_PRIVATE_KEY" > ~/.ssh/aur
|
||||
chmod 600 ~/.ssh/aur
|
||||
ssh-keyscan -t rsa,ecdsa,ed25519 aur.archlinux.org > ~/.ssh/known_hosts
|
||||
|
||||
- name: Publish to AUR
|
||||
env:
|
||||
GIT_SSH_COMMAND: ssh -i /github/home/.ssh/aur -o UserKnownHostsFile=/github/home/.ssh/known_hosts -o StrictHostKeyChecking=yes
|
||||
run: |
|
||||
workdir="$(mktemp -d)"
|
||||
git clone "$AUR_REPO" "$workdir/aur"
|
||||
|
||||
cp "$AUR_PACKAGE_DIR"/PKGBUILD "$workdir/aur/PKGBUILD"
|
||||
cp "$AUR_PACKAGE_DIR"/.SRCINFO "$workdir/aur/.SRCINFO"
|
||||
cp "$AUR_PACKAGE_DIR"/gp.install "$workdir/aur/gp.install"
|
||||
|
||||
cd "$workdir/aur"
|
||||
if git diff --quiet; then
|
||||
echo "AUR package is already up to date"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add PKGBUILD .SRCINFO gp.install
|
||||
git commit -m "Update globalprotect-openconnect-git"
|
||||
git push origin master
|
||||
@@ -0,0 +1,143 @@
|
||||
name: Publish COPR
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Tag to publish'
|
||||
required: true
|
||||
revision:
|
||||
description: 'Package revision'
|
||||
type: string
|
||||
required: true
|
||||
default: "1"
|
||||
build_id:
|
||||
description: 'Existing Copr build ID to verify; leave empty to submit a new build'
|
||||
type: string
|
||||
required: false
|
||||
distros:
|
||||
description: 'Space-separated distro releases, e.g. fedora-44 fedora-45; all configured architectures are included'
|
||||
type: string
|
||||
required: false
|
||||
|
||||
concurrency:
|
||||
group: publish-copr
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish-copr:
|
||||
runs-on: ubuntu-latest
|
||||
container: fedora:latest
|
||||
timeout-minutes: 210
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Install tools
|
||||
run: dnf install -y copr-cli gh python3 zstd
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Check inputs
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null
|
||||
|
||||
- name: Resolve publication distros
|
||||
id: targets
|
||||
env:
|
||||
DISTROS: ${{ inputs.distros }}
|
||||
BUILD_ID: ${{ inputs.build_id }}
|
||||
run: |
|
||||
build_args=()
|
||||
if [[ -n "$BUILD_ID" ]]; then
|
||||
build_args+=(--build-id "$BUILD_ID")
|
||||
fi
|
||||
python3 scripts/select-publication-targets.py copr \
|
||||
--distros "$DISTROS" "${build_args[@]}"
|
||||
|
||||
- name: Download published spec
|
||||
if: ${{ inputs.build_id == '' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
mkdir -p publish-copr
|
||||
|
||||
gh release download "$TAG" \
|
||||
--repo "${{ github.repository }}" \
|
||||
--pattern globalprotect-openconnect.spec \
|
||||
--dir publish-copr
|
||||
|
||||
- name: Set package revision
|
||||
if: ${{ inputs.build_id == '' }}
|
||||
env:
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
spec=publish-copr/globalprotect-openconnect.spec
|
||||
|
||||
if [[ "$(grep -c '^Release:' "$spec")" -ne 1 ]]; then
|
||||
echo "Expected exactly one Release field in $spec" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sed -Ei \
|
||||
"s/^Release:[[:space:]]+.*/Release: ${REVISION}%{?dist}/" \
|
||||
"$spec"
|
||||
|
||||
grep '^Release:' "$spec"
|
||||
|
||||
- name: Configure COPR authentication
|
||||
if: ${{ inputs.build_id == '' }}
|
||||
env:
|
||||
COPR_CONFIG: ${{ secrets.COPR_CONFIG }}
|
||||
run: |
|
||||
install -d -m 700 "$HOME/.config"
|
||||
printf '%s\n' "$COPR_CONFIG" > "$HOME/.config/copr"
|
||||
chmod 600 "$HOME/.config/copr"
|
||||
|
||||
- name: Submit or select Copr build
|
||||
id: build
|
||||
env:
|
||||
EXISTING_BUILD_ID: ${{ inputs.build_id }}
|
||||
CHROOTS: ${{ steps.targets.outputs.targets }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
build_id="$EXISTING_BUILD_ID"
|
||||
if [[ -z "$build_id" ]]; then
|
||||
read -r -a chroots <<< "$CHROOTS"
|
||||
chroot_args=()
|
||||
for chroot in "${chroots[@]}"; do
|
||||
chroot_args+=(--chroot "$chroot")
|
||||
done
|
||||
copr-cli build --nowait yuezk/globalprotect-openconnect \
|
||||
"${chroot_args[@]}" \
|
||||
publish-copr/globalprotect-openconnect.spec | tee copr-submission.log
|
||||
build_id="$(sed -n 's/^Created builds: \([0-9][0-9]*\)$/\1/p' copr-submission.log)"
|
||||
fi
|
||||
[[ "$build_id" =~ ^[0-9]+$ ]]
|
||||
echo "id=$build_id" >> "$GITHUB_OUTPUT"
|
||||
echo "Copr build: https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/build/$build_id/" \
|
||||
>> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Wait for Copr builds and public repositories
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
BUILD_ID: ${{ steps.build.outputs.id }}
|
||||
CHROOTS: ${{ steps.targets.outputs.targets }}
|
||||
run: |
|
||||
read -r -a chroots <<< "$CHROOTS"
|
||||
python3 scripts/wait-for-publication.py copr \
|
||||
--chroots "${chroots[@]}" \
|
||||
--build-id "$BUILD_ID" --version "${TAG#v}" --revision "$REVISION"
|
||||
@@ -0,0 +1,143 @@
|
||||
name: Publish macOS assets
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build_run_id:
|
||||
description: 'Public gp Build run ID with a successful build-macos job'
|
||||
required: true
|
||||
type: string
|
||||
release_tag:
|
||||
description: 'Existing public release tag (vX.Y.Z or snapshot)'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
expected_gui:
|
||||
description: 'Expected macOS shell in the selected build artifact'
|
||||
required: true
|
||||
default: nsh
|
||||
type: choice
|
||||
options: [tauri, nsh]
|
||||
|
||||
concurrency:
|
||||
group: publish-macos-assets
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
environment: macos-release
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Check completed build and public release
|
||||
id: build
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
BUILD_REPOSITORY: yuezk/GlobalProtect-openconnect
|
||||
BUILD_RUN_ID: ${{ inputs.build_run_id }}
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ "$BUILD_RUN_ID" =~ ^[0-9]+$ ]]
|
||||
[[ "$RELEASE_TAG" == snapshot || "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]
|
||||
run="$(gh api "repos/$BUILD_REPOSITORY/actions/runs/$BUILD_RUN_ID")"
|
||||
jq -e '(.event == "workflow_dispatch" or .event == "push") and
|
||||
.path == ".github/workflows/build.yaml"' <<<"$run" >/dev/null
|
||||
attempt="$(jq -r '.run_attempt' <<<"$run")"
|
||||
artifact_name="$(bash scripts/select-macos-artifact.sh "$BUILD_REPOSITORY" "$BUILD_RUN_ID" "$attempt")"
|
||||
{
|
||||
echo "artifact=$artifact_name"
|
||||
echo "workflow_commit=$(jq -r '.head_sha' <<<"$run")"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
gh release view "$RELEASE_TAG" \
|
||||
--repo yuezk/GlobalProtect-openconnect --json isDraft,isPrerelease \
|
||||
--jq 'select(.isDraft == false and .isPrerelease == false)' | jq -e .
|
||||
|
||||
- name: Download completed build artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
repository: yuezk/GlobalProtect-openconnect
|
||||
github-token: ${{ github.token }}
|
||||
run-id: ${{ inputs.build_run_id }}
|
||||
name: ${{ steps.build.outputs.artifact }}
|
||||
path: release-assets
|
||||
|
||||
- name: Validate build identity and checksums
|
||||
id: metadata
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
WORKFLOW_COMMIT: ${{ steps.build.outputs.workflow_commit }}
|
||||
ARTIFACT_NAME: ${{ steps.build.outputs.artifact }}
|
||||
EXPECTED_GUI: ${{ inputs.expected_gui }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
metadata="$(python3 scripts/validate-macos-release.py release-assets \
|
||||
--release-tag "$RELEASE_TAG" --workflow-commit "$WORKFLOW_COMMIT" --gui "$EXPECTED_GUI")"
|
||||
[[ "$ARTIFACT_NAME" == "macos-release-$(jq -r '.request_id' <<<"$metadata")" ]]
|
||||
{
|
||||
echo "gp_ref=$(jq -r '.gp_ref' <<<"$metadata")"
|
||||
echo "gpgui_ref=$(jq -r '.gpgui_ref' <<<"$metadata")"
|
||||
echo "channel=$(jq -r '.channel' <<<"$metadata")"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Checkout public upload helper
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
repository: yuezk/GlobalProtect-openconnect
|
||||
ref: ${{ steps.metadata.outputs.gp_ref }}
|
||||
path: gp-release
|
||||
|
||||
- name: Check stable tags
|
||||
if: ${{ steps.metadata.outputs.channel == 'stable' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
GP_REF: ${{ steps.metadata.outputs.gp_ref }}
|
||||
GPGUI_REF: ${{ steps.metadata.outputs.gpgui_ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git -C gp-release fetch --no-tags origin "refs/tags/$RELEASE_TAG"
|
||||
if [[ "$(git -C gp-release rev-parse 'FETCH_HEAD^{commit}')" != "$GP_REF" ]]; then
|
||||
echo "gp source commit does not match $RELEASE_TAG" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! tagged_gui_commit="$(gh api "repos/yuezk/gpgui/commits/$RELEASE_TAG" --jq .sha 2>/dev/null)"; then
|
||||
echo "Private source tag verification failed; diagnostics suppressed." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$tagged_gui_commit" != "$GPGUI_REF" ]]; then
|
||||
echo "gpgui source commit does not match $RELEASE_TAG" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Publish and verify macOS assets
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_REPOSITORY: yuezk/GlobalProtect-openconnect
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
CHANNEL: ${{ steps.metadata.outputs.channel }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
files=(release-assets/*.dmg release-assets/*.zip release-assets/*.sha256)
|
||||
args=()
|
||||
if [[ "$CHANNEL" == snapshot ]]; then
|
||||
args+=(--clobber)
|
||||
fi
|
||||
gp-release/scripts/upload-release-assets.sh "${args[@]}" "$RELEASE_TAG" "${files[@]}"
|
||||
gh release download "$RELEASE_TAG" --repo yuezk/GlobalProtect-openconnect \
|
||||
--pattern 'GPConnect_*_arm64.*' --dir published-assets
|
||||
python3 - <<'PY'
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
metadata = json.loads(Path("release-assets/release-build.json").read_text())
|
||||
for name, digest in metadata["assets"].items():
|
||||
if hashlib.sha256((Path("published-assets") / name).read_bytes()).hexdigest() != digest:
|
||||
raise SystemExit(f"Published asset checksum mismatch: {name}")
|
||||
PY
|
||||
echo "Published verified macOS assets to $RELEASE_TAG" >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -0,0 +1,112 @@
|
||||
name: Publish OBS
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Tag to publish'
|
||||
required: true
|
||||
revision:
|
||||
description: 'Package revision'
|
||||
type: string
|
||||
required: true
|
||||
default: "1"
|
||||
verify_only:
|
||||
description: 'Verify the existing source and publication without uploading again'
|
||||
type: boolean
|
||||
default: false
|
||||
repositories:
|
||||
description: 'Space-separated distro repositories, e.g. 16.0 openSUSE_Tumbleweed; empty keeps enabled targets'
|
||||
type: string
|
||||
required: false
|
||||
|
||||
concurrency:
|
||||
group: publish-obs
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish-obs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 210
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Install metadata decompressor
|
||||
run: sudo apt-get update && sudo apt-get install -y zstd
|
||||
- name: Check inputs
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null
|
||||
|
||||
- name: Prepare OBS package
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
version="${TAG#v}"
|
||||
archive="globalprotect-openconnect-${version}.offline.tar.gz"
|
||||
source_dir="publish-obs/source/globalprotect-openconnect-${version}"
|
||||
|
||||
mkdir -p publish-obs/files publish-obs/source
|
||||
|
||||
gh release download "$TAG" \
|
||||
--repo "${{ github.repository }}" \
|
||||
--pattern "$archive" \
|
||||
--dir publish-obs
|
||||
|
||||
tar -xzf "publish-obs/$archive" -C publish-obs/source
|
||||
|
||||
make -C "$source_dir" init-rpm \
|
||||
REVISION="$REVISION" \
|
||||
RPM_SOURCE='%{name}.tar.gz'
|
||||
|
||||
mv "publish-obs/$archive" \
|
||||
publish-obs/files/globalprotect-openconnect.tar.gz
|
||||
cp "$source_dir/.build/rpm/globalprotect-openconnect.spec" \
|
||||
"$source_dir/.build/rpm/globalprotect-openconnect.changes" \
|
||||
publish-obs/files/
|
||||
|
||||
- name: Select OBS publication targets
|
||||
env:
|
||||
REPOSITORIES: ${{ inputs.repositories }}
|
||||
VERIFY_ONLY: ${{ inputs.verify_only }}
|
||||
OBS_USERNAME: yuezk
|
||||
OBS_PASSWORD: ${{ secrets.OBS_PASSWORD }}
|
||||
run: |
|
||||
verify_args=()
|
||||
if [[ "$VERIFY_ONLY" == 'true' ]]; then
|
||||
verify_args+=(--verify-only)
|
||||
fi
|
||||
python3 scripts/select-publication-targets.py obs \
|
||||
--repositories "$REPOSITORIES" "${verify_args[@]}" --output publish-obs/targets.json
|
||||
|
||||
- name: Publish OBS package
|
||||
if: ${{ !inputs.verify_only }}
|
||||
uses: yuezk/publish-obs-package@main
|
||||
with:
|
||||
project: home:yuezk
|
||||
package: globalprotect-openconnect
|
||||
username: yuezk
|
||||
password: ${{ secrets.OBS_PASSWORD }}
|
||||
files: ./publish-obs/files/*
|
||||
commit_message: 'Release ${{ inputs.tag }}-${{ inputs.revision }}'
|
||||
|
||||
- name: Wait for OBS builds and public repositories
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
python3 scripts/wait-for-publication.py obs \
|
||||
--targets-file publish-obs/targets.json \
|
||||
--version "${TAG#v}" --revision "$REVISION" --files publish-obs/files
|
||||
@@ -0,0 +1,196 @@
|
||||
name: Publish PPA
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Tag to publish'
|
||||
required: true
|
||||
revision:
|
||||
description: 'Package revision'
|
||||
required: false
|
||||
default: "1"
|
||||
series:
|
||||
description: 'Space-separated Ubuntu series. Leave empty to publish all supported series.'
|
||||
type: "string"
|
||||
required: false
|
||||
default: ""
|
||||
rust:
|
||||
description: 'Rust version to use'
|
||||
type: "string"
|
||||
required: true
|
||||
default: "1.91"
|
||||
verify_only:
|
||||
description: 'Verify an existing upload without building or uploading source again'
|
||||
type: boolean
|
||||
default: false
|
||||
concurrency:
|
||||
group: publish-ppa
|
||||
cancel-in-progress: false
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check tag exists
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null 2>&1; then
|
||||
echo "Tag $TAG does not exist"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
resolve-series:
|
||||
needs: check
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.resolve.outputs.matrix }}
|
||||
steps:
|
||||
- name: Resolve Ubuntu series
|
||||
id: resolve
|
||||
env:
|
||||
INPUT_SERIES: ${{ inputs.series }}
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y distro-info distro-info-data
|
||||
|
||||
if [[ "$INPUT_SERIES" == *","* ]]; then
|
||||
echo "Use space-separated series, for example: jammy noble" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
series=()
|
||||
if [[ -z "${INPUT_SERIES// }" ]]; then
|
||||
while IFS= read -r item; do
|
||||
[[ -n "$item" ]] && series+=("$item")
|
||||
done < <(ubuntu-distro-info --supported)
|
||||
else
|
||||
read -r -a series <<< "$INPUT_SERIES"
|
||||
fi
|
||||
|
||||
if [[ "${#series[@]}" -eq 0 ]]; then
|
||||
echo "No Ubuntu series resolved" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
declare -A seen=()
|
||||
for item in "${series[@]}"; do
|
||||
ubuntu-distro-info --series "$item" >/dev/null
|
||||
if [[ -n "${seen[$item]+present}" ]]; then
|
||||
echo "Duplicate Ubuntu series: $item" >&2
|
||||
exit 1
|
||||
fi
|
||||
seen[$item]=1
|
||||
done
|
||||
|
||||
matrix="$(printf '%s\n' "${series[@]}" | jq -R . | jq -s -c '{series: .}')"
|
||||
echo "Resolved matrix: $matrix"
|
||||
echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
|
||||
|
||||
publish-ppa:
|
||||
needs: [check, resolve-series]
|
||||
name: publish-ppa (${{ matrix.series }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 210
|
||||
container:
|
||||
image: ubuntu:${{ matrix.series }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJSON(needs.resolve-series.outputs.matrix) }}
|
||||
steps:
|
||||
- name: Install container tools
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y ca-certificates curl gpg sudo python3 distro-info distro-info-data
|
||||
mkdir -p /etc/apt/keyrings
|
||||
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
|
||||
| gpg --dearmor -o /etc/apt/keyrings/githubcli-archive-keyring.gpg
|
||||
chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg
|
||||
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
|
||||
> /etc/apt/sources.list.d/github-cli.list
|
||||
apt-get update
|
||||
apt-get install -y gh
|
||||
- uses: actions/checkout@v6
|
||||
- name: Prepare workspace
|
||||
if: ${{ !inputs.verify_only }}
|
||||
run: rm -rf publish-ppa && mkdir publish-ppa
|
||||
- name: Download ${{ inputs.tag }} offline source code
|
||||
if: ${{ !inputs.verify_only }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
run: |
|
||||
gh -R yuezk/GlobalProtect-openconnect \
|
||||
release download ${{ inputs.tag }} \
|
||||
--pattern '*.offline.tar.gz' \
|
||||
--dir publish-ppa
|
||||
- name: Patch the source code
|
||||
if: ${{ !inputs.verify_only }}
|
||||
run: |
|
||||
cd publish-ppa
|
||||
|
||||
# Rename the source tarball without the offline suffix
|
||||
archives=(./*.offline.tar.gz)
|
||||
[[ "${#archives[@]}" -eq 1 && -f "${archives[0]}" ]]
|
||||
archive="${archives[0]%.offline.tar.gz}.tar.gz"
|
||||
mv -v -- "${archives[0]}" "$archive"
|
||||
|
||||
# Extract the source tarball
|
||||
tar -xzf "$archive"
|
||||
|
||||
# Prepare the debian directory with custom files
|
||||
source_dirs=(./globalprotect-openconnect-*/)
|
||||
[[ "${#source_dirs[@]}" -eq 1 && -d "${source_dirs[0]}" ]]
|
||||
cd "${source_dirs[0]}"
|
||||
|
||||
# Prepare the debian directory with custom files
|
||||
mkdir -p .build/debian
|
||||
|
||||
cp -v packaging/deb/control.in .build/debian/control
|
||||
cp -v packaging/deb/rules.in .build/debian/rules
|
||||
cp -v packaging/deb/compat .build/debian/compat
|
||||
cp -v packaging/deb/postrm .build/debian/postrm
|
||||
|
||||
sed -i "s/@BUILD_GUI_HELPER@/1/g" .build/debian/rules
|
||||
sed -i "s/@BUILD_WEBVIEW_AUTH@/1/g" .build/debian/rules
|
||||
|
||||
# Update the control file with the correct Rust version
|
||||
sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/control
|
||||
sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/rules
|
||||
sed -i "s/DISABLE_RUST_TOOLCHAIN = 0/DISABLE_RUST_TOOLCHAIN = 1/g" .build/debian/rules
|
||||
|
||||
- name: Publish to PPA
|
||||
if: ${{ !inputs.verify_only }}
|
||||
uses: yuezk/publish-ppa-package@main
|
||||
with:
|
||||
repository: "yuezk/globalprotect-openconnect"
|
||||
gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }}
|
||||
gpg_passphrase: ${{ secrets.PPA_GPG_PASSPHRASE }}
|
||||
tarball: publish-ppa/globalprotect-openconnect-*.tar.gz
|
||||
debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian
|
||||
deb_email: ${{ vars.DEB_EMAIL }}
|
||||
deb_fullname: ${{ vars.DEB_FULLNAME }}
|
||||
extra_ppa: "yuezk/globalprotect-openconnect"
|
||||
series: ${{ matrix.series }}
|
||||
revision: ${{ inputs.revision }}
|
||||
|
||||
- name: Wait for Launchpad builds and public package indexes
|
||||
if: ${{ inputs.verify_only }}
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
SERIES: ${{ matrix.series }}
|
||||
run: |
|
||||
ubuntu_version="$(ubuntu-distro-info --series "$SERIES" --release | cut -d' ' -f1)"
|
||||
python3 scripts/wait-for-publication.py ppa --series "$SERIES" \
|
||||
--version "${TAG#v}-ppa${REVISION}~ubuntu${ubuntu_version}"
|
||||
@@ -0,0 +1,642 @@
|
||||
name: Publish update feeds
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
CLOUDFLARE_ACCOUNT_ID:
|
||||
required: false
|
||||
CLOUDFLARE_API_TOKEN:
|
||||
required: false
|
||||
SPARKLE_PRIVATE_KEY:
|
||||
required: false
|
||||
inputs:
|
||||
gpgui_ref:
|
||||
required: true
|
||||
type: string
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
release_tag:
|
||||
required: true
|
||||
type: string
|
||||
archive_name:
|
||||
required: false
|
||||
type: string
|
||||
gp_ref:
|
||||
required: true
|
||||
type: string
|
||||
expected_gui:
|
||||
required: false
|
||||
default: nsh
|
||||
type: string
|
||||
highlights:
|
||||
required: false
|
||||
type: string
|
||||
unix_platforms:
|
||||
required: false
|
||||
default: linux,freebsd,openbsd
|
||||
type: string
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
gpgui_ref:
|
||||
description: gpgui ref containing the update feed Worker
|
||||
required: true
|
||||
default: main
|
||||
type: string
|
||||
channel:
|
||||
description: Update channel
|
||||
required: true
|
||||
type: choice
|
||||
options:
|
||||
- stable
|
||||
- snapshot
|
||||
release_tag:
|
||||
description: Release containing the macOS update archive
|
||||
required: true
|
||||
type: string
|
||||
archive_name:
|
||||
description: Exact ZIP asset name; leave empty when the release has one macOS update archive
|
||||
required: false
|
||||
type: string
|
||||
gp_ref:
|
||||
description: GlobalProtect-openconnect ref containing release helpers
|
||||
required: true
|
||||
default: main
|
||||
type: string
|
||||
expected_gui:
|
||||
description: Expected macOS shell in the selected update archive
|
||||
required: true
|
||||
default: nsh
|
||||
type: choice
|
||||
options: [tauri, nsh]
|
||||
highlights:
|
||||
description: Stable release highlights, one per line
|
||||
required: false
|
||||
type: string
|
||||
unix_platforms:
|
||||
description: Comma-separated Unix platforms with published assets (linux,freebsd,openbsd)
|
||||
required: true
|
||||
default: linux,freebsd,openbsd
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
group: update-feeds
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ${{ vars.MACOS_RUNNER || 'macos-15' }}
|
||||
environment: macos-release
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
REPOSITORY: yuezk/GlobalProtect-openconnect
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
CHANNEL: ${{ inputs.channel }}
|
||||
REQUESTED_ARCHIVE: ${{ inputs.archive_name }}
|
||||
FEED_URL: ${{ vars.SPARKLE_FEED_URL }}
|
||||
EXPECTED_TEAM_ID: ${{ vars.MACOS_TEAM_ID }}
|
||||
EXPECTED_GUI: ${{ inputs.expected_gui }}
|
||||
UPDATES_WORKER_NAME: ${{ vars.UPDATES_WORKER_NAME || 'gp-updates' }}
|
||||
SPARKLE_VERSION: 2.9.2
|
||||
UPDATE_HIGHLIGHTS: ${{ inputs.highlights }}
|
||||
UNIX_PLATFORMS: ${{ inputs.unix_platforms }}
|
||||
SPARKLE_ARCHIVE_SHA256: b83e37436774556ed055e0244b297ef2c790e0737393bf65bf495fcbba6eed65
|
||||
steps:
|
||||
- name: Validate inputs
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ "$CHANNEL" != "stable" && "$CHANNEL" != "snapshot" ]]; then
|
||||
echo "channel must be stable or snapshot" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$EXPECTED_GUI" != "tauri" && "$EXPECTED_GUI" != "nsh" ]]; then
|
||||
echo "expected_gui must be tauri or nsh" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! "$UNIX_PLATFORMS" =~ ^(linux|freebsd|openbsd)(,(linux|freebsd|openbsd))*$ ]]; then
|
||||
echo "unix_platforms must list published Unix targets separated by commas" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$CHANNEL" == "snapshot" && "$RELEASE_TAG" != "snapshot" ]]; then
|
||||
echo "The snapshot channel must publish to the snapshot release" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$CHANNEL" == "stable" && "$RELEASE_TAG" == "snapshot" ]]; then
|
||||
echo "The stable channel cannot publish to the snapshot release" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$CHANNEL" == "stable" && -z "${UPDATE_HIGHLIGHTS//[$'\t\r\n ']/}" ]]; then
|
||||
echo "Stable updates require at least one release highlight" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -z "$SPARKLE_PRIVATE_KEY" ]]; then
|
||||
echo "SPARKLE_PRIVATE_KEY is not configured" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -z "$EXPECTED_TEAM_ID" ]]; then
|
||||
echo "MACOS_TEAM_ID is not configured" >&2
|
||||
exit 1
|
||||
fi
|
||||
for variable in CLOUDFLARE_ACCOUNT_ID CLOUDFLARE_API_TOKEN; do
|
||||
if [[ -z "${!variable:-}" ]]; then
|
||||
echo "$variable is not configured" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if [[ "$FEED_URL" != https://*/appcast.xml ]]; then
|
||||
echo "SPARKLE_FEED_URL must be an HTTPS URL ending in /appcast.xml" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Checkout release infrastructure
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Checkout public release helpers
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
repository: yuezk/GlobalProtect-openconnect
|
||||
ref: ${{ inputs.gp_ref }}
|
||||
path: gp-release
|
||||
|
||||
- name: Checkout update feed Worker
|
||||
uses: ./.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: gpgui
|
||||
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: 9.15.1
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Install Worker tooling
|
||||
run: |
|
||||
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
|
||||
(
|
||||
set -euo pipefail
|
||||
pnpm --dir gpgui/apps/update-feed-worker install --frozen-lockfile --ignore-scripts
|
||||
) >/dev/null 2>&1
|
||||
echo "Private operation passed."
|
||||
|
||||
|
||||
- name: Prepare Sparkle tools
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
archive="$RUNNER_TEMP/Sparkle.zip"
|
||||
curl --fail --location --silent --show-error \
|
||||
"https://github.com/sparkle-project/Sparkle/releases/download/$SPARKLE_VERSION/Sparkle-for-Swift-Package-Manager.zip" \
|
||||
--output "$archive"
|
||||
echo "$SPARKLE_ARCHIVE_SHA256 $archive" | shasum -a 256 --check
|
||||
ditto -x -k "$archive" "$RUNNER_TEMP/sparkle"
|
||||
test -x "$RUNNER_TEMP/sparkle/bin/generate_appcast"
|
||||
|
||||
- name: Validate GitHub release
|
||||
id: release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
release="$(gh release view "$RELEASE_TAG" --repo "$REPOSITORY" \
|
||||
--json tagName,isDraft,isPrerelease,publishedAt)"
|
||||
if [[ "$(jq -r '.tagName' <<<"$release")" != "$RELEASE_TAG" ]] || \
|
||||
[[ "$(jq -r '.isDraft' <<<"$release")" != "false" ]]; then
|
||||
echo "Release must be published with the requested tag" >&2
|
||||
exit 1
|
||||
fi
|
||||
is_prerelease="$(jq -r '.isPrerelease' <<<"$release")"
|
||||
if [[ "$is_prerelease" != "false" ]]; then
|
||||
echo "Updates require a non-prerelease GitHub release" >&2
|
||||
exit 1
|
||||
fi
|
||||
published_at="$(jq -r '.publishedAt' <<<"$release")"
|
||||
if [[ ! "$published_at" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T ]]; then
|
||||
echo "Release has no valid publication date" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "released_at=${published_at%%T*}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Download update archive
|
||||
id: archive
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
mkdir -p "$RUNNER_TEMP/updates"
|
||||
archive_name="$REQUESTED_ARCHIVE"
|
||||
if [[ -z "$archive_name" ]]; then
|
||||
archive_name="$(gh release view "$RELEASE_TAG" --repo "$REPOSITORY" --json assets \
|
||||
--jq '[.assets[] | select(.name | test("^GPConnect_[0-9A-Za-z._-]+_arm64\\.zip$"))] | sort_by(.createdAt) | last | .name // ""')"
|
||||
if [[ -z "$archive_name" ]]; then
|
||||
echo "No macOS update archive found on $RELEASE_TAG" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ ! "$archive_name" =~ ^GPConnect_[0-9A-Za-z._-]+_arm64\.zip$ ]]; then
|
||||
echo "Invalid macOS update archive name: $archive_name" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
gh release download "$RELEASE_TAG" --repo "$REPOSITORY" \
|
||||
--pattern "$archive_name" \
|
||||
--pattern "$archive_name.sha256" \
|
||||
--dir "$RUNNER_TEMP/updates"
|
||||
{
|
||||
echo "name=$archive_name"
|
||||
echo "path=$RUNNER_TEMP/updates/$archive_name"
|
||||
echo "checksum_path=$RUNNER_TEMP/updates/$archive_name.sha256"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Verify update archive
|
||||
id: bundle
|
||||
env:
|
||||
ARCHIVE_PATH: ${{ steps.archive.outputs.path }}
|
||||
CHECKSUM_PATH: ${{ steps.archive.outputs.checksum_path }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
expected_digest="$(awk 'NR == 1 { print $1 }' "$CHECKSUM_PATH")"
|
||||
actual_digest="$(shasum -a 256 "$ARCHIVE_PATH" | awk '{ print $1 }')"
|
||||
if [[ -z "$expected_digest" || "$actual_digest" != "$expected_digest" ]]; then
|
||||
echo "Update archive checksum does not match its release checksum" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
extract_dir="$RUNNER_TEMP/extracted"
|
||||
ditto -x -k "$ARCHIVE_PATH" "$extract_dir"
|
||||
app="$extract_dir/GP Connect.app"
|
||||
test -d "$app"
|
||||
codesign --verify --deep --strict --verbose=2 "$app"
|
||||
|
||||
signing_info="$(codesign -d --verbose=4 "$app" 2>&1)"
|
||||
xcrun stapler validate "$app"
|
||||
grep -q '^Authority=Developer ID Application:' <<<"$signing_info"
|
||||
grep -q '^CodeDirectory .*flags=.*runtime' <<<"$signing_info"
|
||||
team_identifier="$(sed -n 's/^TeamIdentifier=//p' <<<"$signing_info")"
|
||||
if [[ "$team_identifier" != "$EXPECTED_TEAM_ID" ]]; then
|
||||
echo "Unexpected Apple Team Identifier: $team_identifier" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
identifier="$(sed -n 's/^Identifier=//p' <<<"$signing_info")"
|
||||
if [[ "$identifier" != "com.yuezk.gpgui" ]]; then
|
||||
echo "Unexpected bundle identifier: $identifier" >&2
|
||||
exit 1
|
||||
fi
|
||||
file "$app/Contents/MacOS/gpgui" | grep -q 'arm64'
|
||||
|
||||
desktop_shell="$(plutil -extract GPDesktopShell raw "$app/Contents/Info.plist")"
|
||||
if [[ "$desktop_shell" != "$EXPECTED_GUI" ]]; then
|
||||
echo "Update archive desktop shell does not match the selected GUI" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
feed_url="$(plutil -extract SUFeedURL raw "$app/Contents/Info.plist")"
|
||||
if [[ "$feed_url" != "$FEED_URL" ]]; then
|
||||
echo "Unexpected Sparkle feed URL: $feed_url" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
update_channel="$(plutil -extract GPUpdateChannel raw "$app/Contents/Info.plist")"
|
||||
if [[ "$update_channel" != "$CHANNEL" ]]; then
|
||||
echo "Unexpected update channel: $update_channel" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
bundle_version="$(plutil -extract CFBundleVersion raw "$app/Contents/Info.plist")"
|
||||
short_version="$(plutil -extract CFBundleShortVersionString raw "$app/Contents/Info.plist")"
|
||||
if [[ ! "$bundle_version" =~ ^[0-9]+(\.[0-9]+){0,2}$ ]]; then
|
||||
echo "Invalid bundle version: $bundle_version" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$CHANNEL" == "stable" ]]; then
|
||||
expected_tag="v$short_version"
|
||||
expected_archive="GPConnect_${short_version}_arm64.zip"
|
||||
else
|
||||
expected_tag="snapshot"
|
||||
expected_archive="GPConnect_${short_version}-snapshot.${bundle_version}_arm64.zip"
|
||||
fi
|
||||
if [[ "$RELEASE_TAG" != "$expected_tag" ]]; then
|
||||
echo "Release tag $RELEASE_TAG does not match $expected_tag" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "${{ steps.archive.outputs.name }}" != "$expected_archive" ]]; then
|
||||
echo "Archive name does not match packaged version: $expected_archive" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "version=$bundle_version" >> "$GITHUB_OUTPUT"
|
||||
echo "short_version=$short_version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Prepare Unix update manifest
|
||||
env:
|
||||
RELEASED_AT: ${{ steps.release.outputs.released_at }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
manifest="$RUNNER_TEMP/updates/latest.json"
|
||||
current_manifest="$RUNNER_TEMP/current-latest.json"
|
||||
latest_url="${FEED_URL%/appcast.xml}/latest.json"
|
||||
status="$(curl --location --silent --show-error \
|
||||
--output "$current_manifest" --write-out '%{http_code}' "$latest_url")"
|
||||
generate_args=(
|
||||
--repository "$REPOSITORY"
|
||||
--channel "$CHANNEL"
|
||||
--version "${{ steps.bundle.outputs.short_version }}"
|
||||
)
|
||||
IFS=',' read -r -a platforms <<<"$UNIX_PLATFORMS"
|
||||
for platform in "${platforms[@]}"; do
|
||||
generate_args+=(--platform "$platform")
|
||||
done
|
||||
case "$status" in
|
||||
200)
|
||||
python3 scripts/validate-update-manifest.py validate "$current_manifest" \
|
||||
--repository "$REPOSITORY"
|
||||
generate_args+=(--input "$current_manifest")
|
||||
;;
|
||||
404)
|
||||
;;
|
||||
*)
|
||||
echo "Could not check the current Unix update manifest: HTTP $status" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
highlights="$RUNNER_TEMP/update-highlights.txt"
|
||||
if [[ "$CHANNEL" == "stable" ]]; then
|
||||
printf '%s\n' "$UPDATE_HIGHLIGHTS" > "$highlights"
|
||||
released_at="$RELEASED_AT"
|
||||
else
|
||||
printf 'Development snapshot after %s.\n' \
|
||||
"${{ steps.bundle.outputs.short_version }}" > "$highlights"
|
||||
generate_args+=(--build "${{ steps.bundle.outputs.version }}")
|
||||
released_at="$(date -u +%F)"
|
||||
fi
|
||||
|
||||
python3 scripts/validate-update-manifest.py generate \
|
||||
"${generate_args[@]}" \
|
||||
--released-at "$released_at" \
|
||||
--highlights-file "$highlights" \
|
||||
--output "$manifest"
|
||||
|
||||
- name: Fetch current appcast
|
||||
id: current-appcast
|
||||
env:
|
||||
ARCHIVE_NAME: ${{ steps.archive.outputs.name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
appcast="$RUNNER_TEMP/updates/appcast.xml"
|
||||
archive_url="https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/$ARCHIVE_NAME"
|
||||
status="$(curl --location --silent --show-error \
|
||||
--output "$appcast" --write-out '%{http_code}' "$FEED_URL")"
|
||||
case "$status" in
|
||||
200)
|
||||
test -s "$appcast"
|
||||
decision="$(python3 scripts/validate-macos-appcast.py status "$appcast" \
|
||||
--repository "$REPOSITORY" \
|
||||
--build-version "${{ steps.bundle.outputs.version }}")"
|
||||
if [[ "$decision" == "older" ]]; then
|
||||
echo "Candidate build is older than the published appcast" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$decision" == "same" ]]; then
|
||||
python3 scripts/validate-macos-appcast.py validate "$appcast" \
|
||||
--repository "$REPOSITORY" \
|
||||
--build-version "${{ steps.bundle.outputs.version }}" \
|
||||
--short-version "${{ steps.bundle.outputs.short_version }}" \
|
||||
--channel "$CHANNEL" \
|
||||
--archive-url "$archive_url"
|
||||
fi
|
||||
echo "decision=$decision" >> "$GITHUB_OUTPUT"
|
||||
;;
|
||||
404)
|
||||
rm -f "$appcast"
|
||||
echo "decision=newer" >> "$GITHUB_OUTPUT"
|
||||
;;
|
||||
*)
|
||||
echo "Could not fetch the current appcast: HTTP $status" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
- name: Generate appcast
|
||||
if: ${{ steps.current-appcast.outputs.decision == 'newer' }}
|
||||
env:
|
||||
ARCHIVE_NAME: ${{ steps.archive.outputs.name }}
|
||||
SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
embedded_public_key="$(plutil -extract SUPublicEDKey raw \
|
||||
"$RUNNER_TEMP/extracted/GP Connect.app/Contents/Info.plist")"
|
||||
derived_public_key="$(swift -e '
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
let encoded = ProcessInfo.processInfo.environment["SPARKLE_PRIVATE_KEY"]!
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let privateKey = try Curve25519.Signing.PrivateKey(
|
||||
rawRepresentation: Data(base64Encoded: encoded)!)
|
||||
print(privateKey.publicKey.rawRepresentation.base64EncodedString())
|
||||
')"
|
||||
if [[ "$derived_public_key" != "$embedded_public_key" ]]; then
|
||||
echo "Sparkle private key does not match the public key embedded in the application" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
download_prefix="https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/"
|
||||
generate_args=(
|
||||
--download-url-prefix "$download_prefix"
|
||||
--full-release-notes-url "https://github.com/$REPOSITORY/releases/tag/$RELEASE_TAG"
|
||||
--maximum-deltas 0
|
||||
--maximum-versions 1
|
||||
--versions "${{ steps.bundle.outputs.version }}"
|
||||
--ed-key-file -
|
||||
)
|
||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
||||
generate_args+=(--channel snapshot)
|
||||
fi
|
||||
printf '%s' "$SPARKLE_PRIVATE_KEY" | \
|
||||
"$RUNNER_TEMP/sparkle/bin/generate_appcast" \
|
||||
"${generate_args[@]}" "$RUNNER_TEMP/updates"
|
||||
|
||||
appcast="$RUNNER_TEMP/updates/appcast.xml"
|
||||
test -s "$appcast"
|
||||
python3 scripts/validate-macos-appcast.py validate "$appcast" \
|
||||
--repository "$REPOSITORY" \
|
||||
--build-version "${{ steps.bundle.outputs.version }}" \
|
||||
--short-version "${{ steps.bundle.outputs.short_version }}" \
|
||||
--channel "$CHANNEL" \
|
||||
--archive-url "$download_prefix$ARCHIVE_NAME"
|
||||
|
||||
- name: Publish appcast
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
appcast="$RUNNER_TEMP/updates/appcast.xml"
|
||||
archive_url="https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/${{ steps.archive.outputs.name }}"
|
||||
if [[ "$CHANNEL" == "stable" ]] && \
|
||||
gh release view "$RELEASE_TAG" --repo "$REPOSITORY" --json assets \
|
||||
--jq '.assets[].name' | grep -Fx appcast.xml >/dev/null; then
|
||||
existing="$RUNNER_TEMP/existing-release-appcast.xml"
|
||||
gh release download "$RELEASE_TAG" --repo "$REPOSITORY" \
|
||||
--pattern appcast.xml --output "$existing"
|
||||
python3 scripts/validate-macos-appcast.py validate "$existing" \
|
||||
--repository "$REPOSITORY" \
|
||||
--build-version "${{ steps.bundle.outputs.version }}" \
|
||||
--short-version "${{ steps.bundle.outputs.short_version }}" \
|
||||
--channel "$CHANNEL" \
|
||||
--archive-url "$archive_url"
|
||||
cp "$existing" "$appcast"
|
||||
else
|
||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
||||
RELEASE_REPOSITORY="$REPOSITORY" \
|
||||
gp-release/scripts/upload-release-assets.sh \
|
||||
--clobber "$RELEASE_TAG" "$appcast"
|
||||
else
|
||||
RELEASE_REPOSITORY="$REPOSITORY" \
|
||||
gp-release/scripts/upload-release-assets.sh "$RELEASE_TAG" "$appcast"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Validate final appcast
|
||||
env:
|
||||
ARCHIVE_NAME: ${{ steps.archive.outputs.name }}
|
||||
run: |
|
||||
python3 scripts/validate-macos-appcast.py validate \
|
||||
"$RUNNER_TEMP/updates/appcast.xml" \
|
||||
--repository "$REPOSITORY" \
|
||||
--build-version "${{ steps.bundle.outputs.version }}" \
|
||||
--short-version "${{ steps.bundle.outputs.short_version }}" \
|
||||
--channel "$CHANNEL" \
|
||||
--archive-url "https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/$ARCHIVE_NAME"
|
||||
|
||||
- name: Deploy update feed worker
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
run: |
|
||||
trap 'status=$?; if [ "$status" -ne 0 ]; then echo "::error::Private operation failed; diagnostics suppressed."; fi' EXIT
|
||||
(
|
||||
set -euo pipefail
|
||||
|
||||
cp "$RUNNER_TEMP/updates/appcast.xml" gpgui/apps/update-feed-worker/public/appcast.xml
|
||||
if [[ -f "$RUNNER_TEMP/updates/latest.json" ]]; then
|
||||
cp "$RUNNER_TEMP/updates/latest.json" gpgui/apps/update-feed-worker/public/latest.json
|
||||
fi
|
||||
pnpm --dir gpgui/apps/update-feed-worker exec wrangler deploy \
|
||||
--config wrangler.jsonc \
|
||||
--name "$UPDATES_WORKER_NAME"
|
||||
) >/dev/null 2>&1
|
||||
echo "Private operation passed."
|
||||
|
||||
- name: Verify published appcast
|
||||
env:
|
||||
ARCHIVE_NAME: ${{ steps.archive.outputs.name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
published_appcast="$RUNNER_TEMP/published-appcast.xml"
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if curl --fail --location --silent --show-error \
|
||||
--output "$published_appcast" "$FEED_URL" && \
|
||||
python3 scripts/validate-macos-appcast.py validate "$published_appcast" \
|
||||
--repository "$REPOSITORY" \
|
||||
--build-version "${{ steps.bundle.outputs.version }}" \
|
||||
--short-version "${{ steps.bundle.outputs.short_version }}" \
|
||||
--channel "$CHANNEL" \
|
||||
--archive-url "https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/$ARCHIVE_NAME"; then
|
||||
exit 0
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
echo "Published appcast did not become available at $FEED_URL" >&2
|
||||
exit 1
|
||||
|
||||
- name: Verify published Unix update manifest
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
latest_url="${FEED_URL%/appcast.xml}/latest.json"
|
||||
published_manifest="$RUNNER_TEMP/published-latest.json"
|
||||
expected=(
|
||||
--channel "$CHANNEL"
|
||||
--version "${{ steps.bundle.outputs.short_version }}"
|
||||
)
|
||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
||||
expected+=(--build "${{ steps.bundle.outputs.version }}")
|
||||
fi
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if curl --fail --location --silent --show-error \
|
||||
--output "$published_manifest" "$latest_url" && \
|
||||
python3 scripts/validate-update-manifest.py validate "$published_manifest" \
|
||||
--repository "$REPOSITORY" "${expected[@]}"; then
|
||||
if ! cmp --silent "$RUNNER_TEMP/updates/latest.json" "$published_manifest"; then
|
||||
sleep 3
|
||||
continue
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
echo "Published Unix update manifest did not become available at $latest_url" >&2
|
||||
exit 1
|
||||
|
||||
- name: Prune expired snapshot assets
|
||||
if: ${{ inputs.channel == 'snapshot' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
assets="$RUNNER_TEMP/snapshot-assets.json"
|
||||
delete_list="$RUNNER_TEMP/delete-snapshot-assets.txt"
|
||||
gh release view snapshot --repo "$REPOSITORY" --json assets > "$assets"
|
||||
ASSETS="$assets" python3 - <<'PY' > "$delete_list"
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
with open(os.environ["ASSETS"], encoding="utf-8") as file:
|
||||
assets = json.load(file)["assets"]
|
||||
|
||||
archive_pattern = re.compile(
|
||||
r"^(GPConnect_.+-snapshot\.(\d+(?:\.\d+){1,2}))_arm64\.zip$"
|
||||
)
|
||||
asset_pattern = re.compile(
|
||||
r"^(GPConnect_.+-snapshot\.\d+(?:\.\d+){1,2})_arm64\.(?:zip|dmg)(?:\.sha256)?$"
|
||||
)
|
||||
builds = []
|
||||
for asset in assets:
|
||||
match = archive_pattern.match(asset["name"])
|
||||
if match:
|
||||
builds.append((tuple(map(int, match.group(2).split("."))), match.group(1)))
|
||||
keep = {stem for _, stem in sorted(builds, reverse=True)[:2]}
|
||||
for asset in assets:
|
||||
match = asset_pattern.match(asset["name"])
|
||||
if match and not any(asset["name"].startswith(stem + "_arm64.") for stem in keep):
|
||||
print(asset["name"])
|
||||
PY
|
||||
|
||||
while IFS= read -r asset; do
|
||||
if [[ -n "$asset" ]] && ! gh release delete-asset snapshot "$asset" \
|
||||
--repo "$REPOSITORY" --yes; then
|
||||
echo "::warning::Could not remove expired snapshot asset: $asset" >&2
|
||||
fi
|
||||
done < "$delete_list"
|
||||
@@ -1,89 +0,0 @@
|
||||
name: Publish Packages
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Tag to publish'
|
||||
required: true
|
||||
revision:
|
||||
description: 'Package revision'
|
||||
required: true
|
||||
default: "1"
|
||||
ppa:
|
||||
description: 'Publish to PPA'
|
||||
type: boolean
|
||||
required: true
|
||||
default: true
|
||||
obs:
|
||||
description: 'Publish to OBS'
|
||||
type: boolean
|
||||
required: true
|
||||
default: true
|
||||
aur:
|
||||
description: 'Publish to AUR'
|
||||
type: boolean
|
||||
required: true
|
||||
default: true
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check tag exists
|
||||
uses: mukunku/[email protected]
|
||||
id: check-tag
|
||||
with:
|
||||
tag: ${{ inputs.tag }}
|
||||
- name: Exit if tag does not exist
|
||||
run: |
|
||||
if [[ "${{ steps.check-tag.outputs.exists }}" == "false" ]]; then
|
||||
echo "Tag ${{ inputs.tag }} does not exist"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
publish-ppa:
|
||||
needs: check
|
||||
if: ${{ inputs.ppa }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 8
|
||||
- name: Prepare workspace
|
||||
run: rm -rf publish-ppa && mkdir publish-ppa
|
||||
- name: Download ${{ inputs.tag }} source code
|
||||
uses: robinraju/[email protected]
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
tag: ${{ inputs.tag }}
|
||||
fileName: globalprotect-openconnect-*.tar.gz
|
||||
tarBall: false
|
||||
zipBall: false
|
||||
out-file-path: publish-ppa
|
||||
- name: Make the offline tarball
|
||||
run: |
|
||||
cd publish-ppa
|
||||
tar -xf globalprotect-openconnect-*.tar.gz
|
||||
cd globalprotect-openconnect-*/
|
||||
|
||||
make tarball OFFLINE=1
|
||||
|
||||
# Prepare the debian directory with custom files
|
||||
mkdir -p .build/debian
|
||||
sed 's/@RUST@/rust-all(>=1.70)/g' packaging/deb/control.in > .build/debian/control
|
||||
sed 's/@OFFLINE@/1/g' packaging/deb/rules.in > .build/debian/rules
|
||||
cp packaging/deb/postrm .build/debian/postrm
|
||||
|
||||
- name: Publish to PPA
|
||||
uses: yuezk/publish-ppa-package@dev
|
||||
with:
|
||||
repository: "yuezk/globalprotect-openconnect"
|
||||
gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }}
|
||||
gpg_passphrase: ${{ secrets.PPA_GPG_PASSPHRASE }}
|
||||
tarball: publish-ppa/globalprotect-openconnect-*/.build/tarball/*.tar.gz
|
||||
debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian
|
||||
deb_email: "[email protected]"
|
||||
deb_fullname: "Kevin Yue"
|
||||
extra_ppa: "liushuyu-011/rust-bpo-1.75"
|
||||
revision: ${{ inputs.revision }}
|
||||
@@ -0,0 +1,77 @@
|
||||
name: Release infrastructure checks
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/**'
|
||||
- '.github/actions/**'
|
||||
- 'scripts/record-build-sources.py'
|
||||
- 'scripts/validate-release-version.py'
|
||||
- 'scripts/publish-flake-test-branch.sh'
|
||||
- 'scripts/prepare-release-promotion.sh'
|
||||
- 'scripts/tests/test_release_flow.py'
|
||||
- 'scripts/select-macos-artifact.sh'
|
||||
- 'scripts/test-private-desktop.sh'
|
||||
- 'scripts/tests/test_private_ci.py'
|
||||
- 'scripts/wait-for-publication.py'
|
||||
- 'scripts/select-publication-targets.py'
|
||||
- 'scripts/verify-docker-publication.sh'
|
||||
- 'scripts/tests/test_*publication.py'
|
||||
- 'scripts/validate-macos-release.py'
|
||||
- 'scripts/validate-macos-appcast.py'
|
||||
- 'scripts/validate-update-manifest.py'
|
||||
- 'scripts/tests/test_validate_*.py'
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.github/workflows/**'
|
||||
- '.github/actions/**'
|
||||
- 'scripts/record-build-sources.py'
|
||||
- 'scripts/validate-release-version.py'
|
||||
- 'scripts/publish-flake-test-branch.sh'
|
||||
- 'scripts/prepare-release-promotion.sh'
|
||||
- 'scripts/tests/test_release_flow.py'
|
||||
- 'scripts/select-macos-artifact.sh'
|
||||
- 'scripts/test-private-desktop.sh'
|
||||
- 'scripts/tests/test_private_ci.py'
|
||||
- 'scripts/wait-for-publication.py'
|
||||
- 'scripts/select-publication-targets.py'
|
||||
- 'scripts/verify-docker-publication.sh'
|
||||
- 'scripts/tests/test_*publication.py'
|
||||
- 'scripts/validate-macos-release.py'
|
||||
- 'scripts/validate-macos-appcast.py'
|
||||
- 'scripts/validate-update-manifest.py'
|
||||
- 'scripts/tests/test_validate_*.py'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
release-checks:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Validate workflow expressions and schema
|
||||
run: |
|
||||
docker run --rm -v "$PWD:/repo" -w /repo \
|
||||
rhysd/actionlint:1.7.12@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667 \
|
||||
-shellcheck='' -pyflakes=''
|
||||
- name: Check Docker publication script
|
||||
run: |
|
||||
bash -n scripts/verify-docker-publication.sh
|
||||
shellcheck scripts/verify-docker-publication.sh
|
||||
- name: Test publication verification
|
||||
run: python3 -m unittest discover -s scripts/tests -p 'test_*publication.py'
|
||||
- name: Test macOS publication and update feed validation
|
||||
run: python3 -m unittest discover -s scripts/tests -p 'test_validate_*.py'
|
||||
- name: Check private CI and macOS artifact selection
|
||||
run: |
|
||||
bash -n scripts/select-macos-artifact.sh
|
||||
shellcheck scripts/select-macos-artifact.sh scripts/test-private-desktop.sh
|
||||
bash -n scripts/test-private-desktop.sh
|
||||
python3 -m unittest discover -s scripts/tests -p 'test_private_ci.py'
|
||||
- name: Test release promotion and source selection
|
||||
run: |
|
||||
bash -n scripts/prepare-release-promotion.sh scripts/publish-flake-test-branch.sh
|
||||
shellcheck scripts/prepare-release-promotion.sh scripts/publish-flake-test-branch.sh
|
||||
python3 -m unittest discover -s scripts/tests -p 'test_release_flow.py'
|
||||
@@ -0,0 +1,23 @@
|
||||
name: Release version consistency
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
release-version:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# The default PR checkout is the candidate merged with the current base.
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Check main release version
|
||||
env:
|
||||
BASE_REF: ${{ github.event.pull_request.base.sha || github.event.before }}
|
||||
run: python3 scripts/validate-release-version.py --base-ref "$BASE_REF"
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Release Packages
|
||||
name: GH Release Packages
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -30,11 +30,21 @@ on:
|
||||
description: 'Build PKG package'
|
||||
required: true
|
||||
default: true
|
||||
release-apk:
|
||||
type: boolean
|
||||
description: 'Build APK package'
|
||||
required: true
|
||||
default: true
|
||||
release-binary:
|
||||
type: boolean
|
||||
description: 'Build binary package'
|
||||
required: true
|
||||
default: true
|
||||
release-docker:
|
||||
type: boolean
|
||||
description: 'Publish Docker image'
|
||||
required: true
|
||||
default: true
|
||||
gh-release:
|
||||
type: boolean
|
||||
description: 'Update GitHub release'
|
||||
@@ -63,6 +73,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.set-matrix.outputs.result }}
|
||||
docker_matrix: ${{ steps.set-matrix.outputs.docker_matrix }}
|
||||
steps:
|
||||
- name: Set up matrix
|
||||
id: set-matrix
|
||||
@@ -73,13 +84,19 @@ jobs:
|
||||
const inputs = ${{ toJson(inputs) }}
|
||||
const { arch } = inputs
|
||||
const osMap = {
|
||||
"all": ["ubuntu-latest", "arm64"],
|
||||
"all": ["ubuntu-latest", "ubuntu-24.04-arm"],
|
||||
"x86_64": ["ubuntu-latest"],
|
||||
"arm64": ["arm64"]
|
||||
"arm64": ["ubuntu-24.04-arm"]
|
||||
}
|
||||
|
||||
const docker = [
|
||||
{ runner: 'ubuntu-latest', platform: 'linux/amd64' },
|
||||
{ runner: 'ubuntu-24.04-arm', platform: 'linux/arm64' },
|
||||
].filter(item => osMap[arch].includes(item.runner))
|
||||
core.setOutput('docker_matrix', JSON.stringify({ include: docker }))
|
||||
|
||||
const package = Object.entries(inputs)
|
||||
.filter(([key, value]) => key.startsWith('release-') && value)
|
||||
.filter(([key, value]) => key.startsWith('release-') && key !== 'release-docker' && value)
|
||||
.map(([key, value]) => key.replace('release-', ''))
|
||||
|
||||
return JSON.stringify({
|
||||
@@ -96,58 +113,243 @@ jobs:
|
||||
steps:
|
||||
- name: Prepare workspace
|
||||
run: rm -rf build-${{ matrix.package }} && mkdir -p build-${{ matrix.package }}
|
||||
|
||||
- name: Download ${{ inputs.tag }} source code
|
||||
uses: robinraju/[email protected]
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
tag: ${{ inputs.tag }}
|
||||
fileName: globalprotect-openconnect-*.tar.gz
|
||||
tarBall: false
|
||||
zipBall: false
|
||||
out-file-path: build-${{ matrix.package }}
|
||||
- name: Docker Login
|
||||
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
run: |
|
||||
gh -R yuezk/GlobalProtect-openconnect \
|
||||
release download ${{ inputs.tag }} \
|
||||
--pattern '*[^offline].tar.gz' \
|
||||
--dir build-${{ matrix.package }}
|
||||
|
||||
- name: Build ${{ matrix.package }} package in Docker
|
||||
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
|
||||
run: |
|
||||
docker run --rm \
|
||||
-v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \
|
||||
-v $(pwd)/build-${{ matrix.package }}:/workspace \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-e LIBXML2_STATIC=1 \
|
||||
-e INCLUDE_GUI=1 \
|
||||
yuezk/gpdev:${{ matrix.package }}-builder
|
||||
yuezk/gpdev:${{ matrix.package }}-builder-tauri2
|
||||
|
||||
- name: Install ${{ matrix.package }} package in Docker
|
||||
run: |
|
||||
docker run --rm \
|
||||
-v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \
|
||||
yuezk/gpdev:${{ matrix.package }}-builder \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-v $(pwd)/build-${{ matrix.package }}:/workspace \
|
||||
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \
|
||||
bash install.sh
|
||||
|
||||
- name: Upload ${{ matrix.package }} package
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: artifact-${{ matrix.os }}-${{ matrix.package }}
|
||||
if-no-files-found: error
|
||||
path: |
|
||||
build-${{ matrix.package }}/artifacts/*
|
||||
|
||||
build-docker-image:
|
||||
needs:
|
||||
- check
|
||||
- setup-matrix
|
||||
if: ${{ inputs.release-docker }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJson(needs.setup-matrix.outputs.docker_matrix) }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- name: Prepare
|
||||
run: |
|
||||
platform=${{ matrix.platform }}
|
||||
echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
|
||||
- name: Prepare workspace
|
||||
run: rm -rf docker-image && mkdir -p docker-image/source
|
||||
|
||||
- name: Download ${{ inputs.tag }} source code
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
run: |
|
||||
gh -R yuezk/GlobalProtect-openconnect \
|
||||
release download ${{ inputs.tag }} \
|
||||
--pattern '*[^offline].tar.gz' \
|
||||
--dir docker-image
|
||||
tar -xzf docker-image/*.tar.gz -C docker-image/source --strip-components=1
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_HUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
- name: Build and push by digest
|
||||
id: build
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: docker-image/source
|
||||
file: docker-image/source/packaging/docker/alpine/Dockerfile
|
||||
platforms: ${{ matrix.platform }}
|
||||
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
|
||||
- name: Verify CLI tools
|
||||
env:
|
||||
IMAGE: yuezk/globalprotect-openconnect
|
||||
DIGEST: ${{ steps.build.outputs.digest }}
|
||||
run: |
|
||||
docker run --rm "$IMAGE@$DIGEST" --help
|
||||
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
|
||||
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
|
||||
- name: Export digest
|
||||
run: |
|
||||
mkdir -p /tmp/digests
|
||||
digest="${{ steps.build.outputs.digest }}"
|
||||
touch "/tmp/digests/${digest#sha256:}"
|
||||
- name: Upload digest
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: digests-${{ env.PLATFORM_PAIR }}
|
||||
path: /tmp/digests/*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
publish-docker-image:
|
||||
needs:
|
||||
- build-docker-image
|
||||
if: ${{ inputs.release-docker }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
path: /tmp/digests
|
||||
pattern: digests-*
|
||||
merge-multiple: true
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_HUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
- name: Publish Docker manifest
|
||||
working-directory: /tmp/digests
|
||||
env:
|
||||
IMAGE: yuezk/globalprotect-openconnect
|
||||
TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
# Reject an incomplete or unexpected selection before writing any tag.
|
||||
shopt -s nullglob
|
||||
digest_files=(*)
|
||||
expected_count=1
|
||||
if [[ "${{ inputs.arch }}" == all ]]; then
|
||||
expected_count=2
|
||||
fi
|
||||
[[ ${#digest_files[@]} -eq $expected_count ]]
|
||||
for digest in "${digest_files[@]}"; do
|
||||
[[ "$digest" =~ ^[0-9a-f]{64}$ ]]
|
||||
done
|
||||
VERSION="${TAG#v}"
|
||||
tags=(-t "$IMAGE:$TAG")
|
||||
|
||||
if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
tags+=(-t "$IMAGE:$VERSION" -t "$IMAGE:latest")
|
||||
fi
|
||||
|
||||
docker buildx imagetools create "${tags[@]}" \
|
||||
$(printf "$IMAGE@sha256:%s " *)
|
||||
|
||||
"$GITHUB_WORKSPACE/scripts/verify-docker-publication.sh" "$IMAGE:$TAG" /tmp/digests "${{ inputs.arch }}"
|
||||
if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
for alias in "$VERSION" latest; do
|
||||
"$GITHUB_WORKSPACE/scripts/verify-docker-publication.sh" "$IMAGE:$alias" /tmp/digests "${{ inputs.arch }}"
|
||||
done
|
||||
fi
|
||||
|
||||
gh-release:
|
||||
needs:
|
||||
- build
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ inputs.gh-release }}
|
||||
outputs:
|
||||
stable_version: ${{ steps.stable-release.outputs.version }}
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
id-token: write
|
||||
attestations: write
|
||||
artifact-metadata: write
|
||||
steps:
|
||||
- name: Prepare workspace
|
||||
run: rm -rf gh-release && mkdir gh-release
|
||||
- name: Download artifact
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
path: gh-release
|
||||
- name: Update release
|
||||
uses: softprops/action-gh-release@v1
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
prerelease: ${{ contains(github.ref, 'snapshot') }}
|
||||
fail_on_unmatched_files: true
|
||||
tag_name: ${{ inputs.tag }}
|
||||
files: |
|
||||
gh-release/artifact-*/*
|
||||
repository: yuezk/GlobalProtect-openconnect
|
||||
ref: ${{ github.ref }}
|
||||
path: gh-release/gp
|
||||
submodules: recursive
|
||||
- name: Download artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
path: gh-release
|
||||
- name: Rename APK artifacts
|
||||
run: |
|
||||
shopt -s nullglob
|
||||
|
||||
for file in gh-release/artifact-ubuntu-latest-apk/*.apk; do
|
||||
mv "$file" "${file%.apk}-x86_64.apk"
|
||||
done
|
||||
for file in gh-release/artifact-ubuntu-24.04-arm-apk/*.apk; do
|
||||
mv "$file" "${file%.apk}-aarch64.apk"
|
||||
done
|
||||
- name: Generate release asset checksums
|
||||
run: |
|
||||
cd gh-release/gp
|
||||
mkdir -p .build
|
||||
scripts/release-assets.sh all "$GITHUB_WORKSPACE/gh-release" > .build/release-assets.txt
|
||||
if [ ! -s .build/release-assets.txt ]; then
|
||||
echo "No release assets found"
|
||||
exit 1
|
||||
fi
|
||||
while IFS= read -r file; do
|
||||
digest=$(sha256sum "$file" | cut -d ' ' -f 1)
|
||||
printf '%s %s\n' "$digest" "$(basename "$file")"
|
||||
done < .build/release-assets.txt > .build/release-assets.sha256
|
||||
- name: Attest release assets
|
||||
uses: actions/attest-build-provenance@v4
|
||||
with:
|
||||
subject-checksums: gh-release/gp/.build/release-assets.sha256
|
||||
- name: Upload release assets
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
run: |
|
||||
mapfile -t files < gh-release/gp/.build/release-assets.txt
|
||||
if [[ "${{ inputs.tag }}" == "snapshot" ]]; then
|
||||
for file in "${files[@]}"; do
|
||||
gh release upload snapshot "$file" --clobber \
|
||||
--repo yuezk/GlobalProtect-openconnect
|
||||
done
|
||||
else
|
||||
gh-release/gp/scripts/upload-release-assets.sh "${{ inputs.tag }}" "${files[@]}"
|
||||
fi
|
||||
|
||||
- name: Resolve stable release version
|
||||
id: stable-release
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
if [[ "$TAG" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
|
||||
echo "version=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
update-flake-hashes:
|
||||
needs: gh-release
|
||||
if: ${{ inputs.release-binary && inputs.arch == 'all' && needs.gh-release.outputs.stable_version != '' }}
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/update-flake-hashes.yaml
|
||||
with:
|
||||
version: ${{ needs.gh-release.outputs.stable_version }}
|
||||
release_tag: ${{ inputs.tag }}
|
||||
@@ -0,0 +1,190 @@
|
||||
name: Update flake hashes
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
version:
|
||||
required: true
|
||||
type: string
|
||||
release_tag:
|
||||
required: true
|
||||
type: string
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Release version. Defaults to Cargo.toml workspace version."
|
||||
required: false
|
||||
release_tag:
|
||||
description: "GitHub release tag to fetch assets from. Defaults to v<version>; use snapshot for snapshot assets."
|
||||
required: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
update-flake-hashes:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.release.outputs.version }}
|
||||
release_tag: ${{ steps.release.outputs.release_tag }}
|
||||
steps:
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
|
||||
- name: Resolve candidate release
|
||||
id: release
|
||||
env:
|
||||
RELEASE_VERSION: ${{ inputs.version }}
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
run: |
|
||||
python3 - <<'PYRELEASE'
|
||||
import json, os, re, runpy, subprocess
|
||||
from pathlib import Path
|
||||
helpers = runpy.run_path('scripts/validate-release-version.py')
|
||||
version = os.environ['RELEASE_VERSION'].removeprefix('v') or helpers['cargo_version'](Path('.'))
|
||||
tag = os.environ['RELEASE_TAG'] or f'v{version}'
|
||||
if not re.fullmatch(r'(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)', version) or tag not in (f'v{version}', 'snapshot'):
|
||||
raise SystemExit('Expected a stable version and its matching release tag, or snapshot')
|
||||
source_slug = re.sub(r'[^A-Za-z0-9._-]', '', re.sub(r'[/\s]+', '-', os.environ['GITHUB_REF_NAME'])).strip('-')
|
||||
test_branch = f'chore/flake-{source_slug}'
|
||||
expected_head = ''
|
||||
if tag == 'snapshot':
|
||||
remote = subprocess.check_output(['git', 'ls-remote', '--heads', 'origin', f'refs/heads/{test_branch}'], text=True)
|
||||
expected_head = remote.split()[0] if remote.strip() else ''
|
||||
with open(os.environ['GITHUB_OUTPUT'], 'a') as output:
|
||||
output.write(f'version={version}\nrelease_tag={tag}\n')
|
||||
Path('release-candidate.json').write_text(json.dumps({
|
||||
'version': version, 'releaseTag': tag, 'sourceSha': os.environ['GITHUB_SHA'],
|
||||
'workflowRunId': os.environ['GITHUB_RUN_ID'],
|
||||
'testBranch': test_branch, 'expectedTestHead': expected_head,
|
||||
}, indent=2) + '\n')
|
||||
PYRELEASE
|
||||
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
|
||||
- name: Update Nixpkgs lock
|
||||
run: |
|
||||
nix flake update nixpkgs \
|
||||
--extra-experimental-features "nix-command flakes"
|
||||
|
||||
- name: Update flake hashes
|
||||
env:
|
||||
RELEASE_VERSION: ${{ steps.release.outputs.version }}
|
||||
RELEASE_TAG: ${{ steps.release.outputs.release_tag }}
|
||||
run: |
|
||||
if [[ -n "$RELEASE_VERSION" ]]; then
|
||||
scripts/update-flake-hashes.sh "$RELEASE_VERSION" "$RELEASE_TAG"
|
||||
else
|
||||
scripts/update-flake-hashes.sh "" "$RELEASE_TAG"
|
||||
fi
|
||||
|
||||
- name: Upload updated flake
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: updated-flake
|
||||
path: |
|
||||
flake.nix
|
||||
flake.lock
|
||||
release-candidate.json
|
||||
if-no-files-found: error
|
||||
|
||||
validate-nix-prebuilt:
|
||||
needs:
|
||||
- update-flake-hashes
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
runner:
|
||||
- ubuntu-latest
|
||||
- ubuntu-24.04-arm
|
||||
nixpkgs:
|
||||
- locked
|
||||
- nixos-25.11
|
||||
- nixos-26.05
|
||||
- nixpkgs-unstable
|
||||
exclude:
|
||||
- runner: ubuntu-24.04-arm
|
||||
nixpkgs: locked
|
||||
name: validate-nix-prebuilt (${{ matrix.nixpkgs }}, ${{ matrix.runner }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
|
||||
- name: Download updated flake
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: updated-flake
|
||||
path: .
|
||||
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
|
||||
- name: Build prebuilt Nix package
|
||||
env:
|
||||
NIXPKGS: ${{ matrix.nixpkgs }}
|
||||
run: |
|
||||
if [[ "$NIXPKGS" == "locked" ]]; then
|
||||
nix build .#prebuilt \
|
||||
--extra-experimental-features "nix-command flakes" \
|
||||
--print-build-logs
|
||||
else
|
||||
nix build .#prebuilt \
|
||||
--override-input nixpkgs "github:NixOS/nixpkgs/$NIXPKGS" \
|
||||
--extra-experimental-features "nix-command flakes" \
|
||||
--print-build-logs
|
||||
fi
|
||||
|
||||
- name: Validate installed release versions
|
||||
run: |
|
||||
python3 scripts/validate-release-version.py \
|
||||
--version '${{ needs.update-flake-hashes.outputs.version }}' \
|
||||
--release-tag '${{ needs.update-flake-hashes.outputs.release_tag }}' --package result
|
||||
|
||||
- name: Inspect prebuilt Nix package
|
||||
run: |
|
||||
test -x result/bin/gpclient
|
||||
test -x result/bin/gpauth
|
||||
test -x result/bin/gpservice
|
||||
test -x result/bin/gpgui-helper
|
||||
test -x result/bin/gpgui
|
||||
test ! -L result/bin/gpservice
|
||||
test -x result/libexec/gpclient/gp-vpnc-script-installer
|
||||
test -x result/libexec/gpclient/gp-hip-script-installer
|
||||
result/bin/gpclient --version
|
||||
result/bin/gpservice --version
|
||||
result/bin/gpauth --version
|
||||
|
||||
if grep -R '/usr/bin/gp' result/share; then
|
||||
echo "Desktop assets contain paths outside the Nix package" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Verify desktop authorization runs on the host
|
||||
run: bash scripts/tests/nix-desktop-authorization.sh result
|
||||
|
||||
publish-test-branch:
|
||||
if: needs.update-flake-hashes.outputs.release_tag == 'snapshot'
|
||||
needs: [update-flake-hashes, validate-nix-prebuilt]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
|
||||
- name: Download updated flake
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: updated-flake
|
||||
path: .
|
||||
|
||||
- name: Publish branch for snapshot testing
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: scripts/publish-flake-test-branch.sh
|
||||
@@ -1,4 +1,5 @@
|
||||
.idea
|
||||
.DS_Store
|
||||
/target
|
||||
.pnpm-store
|
||||
.env
|
||||
@@ -8,3 +9,13 @@
|
||||
.cargo
|
||||
.build
|
||||
SNAPSHOT
|
||||
SOURCE_COMMIT
|
||||
|
||||
# Tauri generated files
|
||||
gen
|
||||
|
||||
# Nix files
|
||||
result
|
||||
|
||||
# Packages & test assets
|
||||
*.ipa
|
||||
@@ -0,0 +1,7 @@
|
||||
[submodule "crates/openconnect/deps/openconnect"]
|
||||
path = crates/openconnect/deps/openconnect
|
||||
url = https://github.com/yuezk/openconnect.git
|
||||
branch = globalprotect
|
||||
[submodule "crates/openconnect/deps/libxml2"]
|
||||
path = crates/openconnect/deps/libxml2
|
||||
url = https://github.com/GNOME/libxml2.git
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Mac",
|
||||
"includePath": ["crates/openconnect/deps/openconnect"],
|
||||
"macFrameworkPath": ["/System/Library/Frameworks", "/Library/Frameworks"],
|
||||
"intelliSenseMode": "macos-clang-x64",
|
||||
"compilerPath": "/usr/bin/clang",
|
||||
"cStandard": "c17",
|
||||
"cppStandard": "c++17"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
@@ -23,8 +23,12 @@
|
||||
"gpgui",
|
||||
"gpservice",
|
||||
"hidpi",
|
||||
"Ivars",
|
||||
"jnlp",
|
||||
"LOGNAME",
|
||||
"NSHTTPURL",
|
||||
"NSURL",
|
||||
"objc",
|
||||
"oneshot",
|
||||
"openconnect",
|
||||
"pkcs",
|
||||
@@ -55,9 +59,16 @@
|
||||
"Vite",
|
||||
"vpnc",
|
||||
"vpninfo",
|
||||
"webbrowser",
|
||||
"wmctrl",
|
||||
"XAUTHORITY",
|
||||
"yuezk"
|
||||
],
|
||||
"rust-analyzer.cargo.features": "all",
|
||||
"files.associations": {
|
||||
"unistd.h": "c",
|
||||
"utsname.h": "c",
|
||||
"vpn.h": "c",
|
||||
"openconnect.h": "c"
|
||||
},
|
||||
}
|
||||
@@ -1,58 +1,78 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
resolver = "3"
|
||||
|
||||
members = ["crates/*", "apps/gpclient", "apps/gpservice", "apps/gpauth", "apps/gpgui-helper/src-tauri"]
|
||||
members = [
|
||||
"crates/*",
|
||||
"apps/gpclient",
|
||||
"apps/gpservice",
|
||||
"apps/gpauth",
|
||||
"apps/gpgui-helper/src-tauri",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.70"
|
||||
version = "2.3.7"
|
||||
rust-version = "1.91"
|
||||
version = "3.3.0"
|
||||
authors = ["Kevin Yue <[email protected]>"]
|
||||
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
edition = "2021"
|
||||
edition = "2024"
|
||||
license = "GPL-3.0"
|
||||
|
||||
[workspace.dependencies]
|
||||
anyhow = "1.0"
|
||||
base64 = "0.21"
|
||||
clap = { version = "4.4.2", features = ["derive"] }
|
||||
askama = { version = "0.16", default-features = false, features = ["std", "derive", "config"] }
|
||||
base64 = { version = "0.23", default-features = false, features = ["std"] }
|
||||
chrono = "0.4"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
clap-verbosity-flag = "3"
|
||||
ctrlc = "3.4"
|
||||
directories = "5.0"
|
||||
dns-lookup = "2.0.4"
|
||||
env_logger = "0.10"
|
||||
directories = "6.0"
|
||||
dns-lookup = "4.0.2"
|
||||
env_logger = "0.11"
|
||||
is_executable = "1.0"
|
||||
log = "0.4"
|
||||
regex = "1"
|
||||
reqwest = { version = "0.11", features = ["native-tls-vendored", "json"] }
|
||||
# RUST_LOG accepts user-supplied Unicode property filters through env_logger.
|
||||
regex = { version = "1", default-features = false, features = ["std", "perf", "unicode"] }
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "charset", "http2", "system-proxy", "json", "form", "query"] }
|
||||
openssl = "0.10"
|
||||
pem = "3"
|
||||
roxmltree = "0.18"
|
||||
pem = "4"
|
||||
xmltree = { version = "0.12", features = ["attribute-order"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
sysinfo = "0.29"
|
||||
# The 0.39 series requires Rust 1.95, above the workspace minimum.
|
||||
sysinfo = { version = "0.38.4", default-features = false, features = ["system"] }
|
||||
tempfile = "3.8"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio = { version = "1" }
|
||||
tokio-util = "0.7"
|
||||
tokio-tungstenite = "0.30"
|
||||
url = "2.4"
|
||||
urlencoding = "2.1.3"
|
||||
axum = "0.7"
|
||||
futures = "0.3"
|
||||
axum = { version = "0.8", default-features = false, features = ["http1", "tokio"] }
|
||||
futures = { version = "0.3", default-features = false, features = ["std"] }
|
||||
futures-util = "0.3"
|
||||
tokio-tungstenite = "0.20.1"
|
||||
uzers = "0.11"
|
||||
whoami = "1"
|
||||
thiserror = "1"
|
||||
redact-engine = "0.1"
|
||||
compile-time = "0.2"
|
||||
uzers = "0.12"
|
||||
whoami = "2"
|
||||
thiserror = "2"
|
||||
compile-time = "0.4"
|
||||
serde_urlencoded = "0.7"
|
||||
md5="0.7"
|
||||
sha256="1"
|
||||
which="6"
|
||||
md5 = "0.8"
|
||||
sha2 = { version = "0.11", default-features = false }
|
||||
which = "8"
|
||||
uuid = "1"
|
||||
netdev = "0.47"
|
||||
humantime = "2"
|
||||
snow = { version = "0.10", default-features = false, features = ["use-getrandom", "use-curve25519", "use-chacha20poly1305", "use-sha2"] }
|
||||
zeroize = "1"
|
||||
|
||||
# Tauri dependencies
|
||||
tauri = { version = "1.5" }
|
||||
specta = "=2.0.0-rc.1"
|
||||
specta-macros = "=2.0.0-rc.1"
|
||||
rspc = { version = "1.0.0-rc.5", features = ["tauri"] }
|
||||
tauri = { version = "2" }
|
||||
specta = "=2.0.0-rc.20"
|
||||
proptest = "1"
|
||||
|
||||
[patch.crates-io]
|
||||
# Restore BSD GTK resize hit testing and apply fixed-size windows before first configure.
|
||||
tao = { git = "https://github.com/yuezk/tao", rev = "bba0f1c4e86d697b173c75280d1651f408b8023c" }
|
||||
# Use one macro source for Tao and Wry so Cargo can vendor the workspace.
|
||||
tao-macros = { git = "https://github.com/yuezk/tao", rev = "bba0f1c4e86d697b173c75280d1651f408b8023c" }
|
||||
|
||||
[profile.release]
|
||||
opt-level = 'z' # Optimize for size
|
||||
|
||||
@@ -1,21 +1,59 @@
|
||||
.SHELLFLAGS += -e
|
||||
SHELL := /bin/sh
|
||||
.SHELLFLAGS := -ec
|
||||
|
||||
OFFLINE ?= 0
|
||||
BUILD_FE ?= 1
|
||||
INCLUDE_GUI ?= 0
|
||||
CARGO ?= cargo
|
||||
CARGO_TARGET_DIR ?= target
|
||||
CARGO_RELEASE_DIR ?= $(CARGO_TARGET_DIR)/$(if $(CARGO_BUILD_TARGET),$(CARGO_BUILD_TARGET)/)release
|
||||
DISABLE_RUST_TOOLCHAIN ?= 0
|
||||
RUST_VERSION ?= 1.91
|
||||
IGNORE_RUST_VERSION ?= 0
|
||||
|
||||
VERSION = $(shell $(CARGO) metadata --no-deps --format-version 1 | jq -r '.packages[0].version')
|
||||
VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')
|
||||
SOURCE_COMMIT_VALUE := $(shell \
|
||||
if [ -n "$$SOURCE_GIT_COMMIT" ]; then \
|
||||
printf '%s' "$$SOURCE_GIT_COMMIT" | cut -c1-9; \
|
||||
elif [ -n "$$GITHUB_SHA" ]; then \
|
||||
printf '%s' "$$GITHUB_SHA" | cut -c1-9; \
|
||||
elif [ -f SOURCE_COMMIT ]; then \
|
||||
head -n1 SOURCE_COMMIT | tr -d '[:space:]' | cut -c1-9; \
|
||||
else \
|
||||
git rev-parse --short=9 HEAD 2>/dev/null || printf unknown; \
|
||||
fi)
|
||||
GUI_LIBC_SUFFIX ?= $(shell ldd --version 2>&1 | grep -qi musl && echo -musl || true)
|
||||
REVISION ?= 1
|
||||
RPM_SOURCE ?= %{name}.tar.gz
|
||||
|
||||
PPA_REVISION ?= 1
|
||||
PKG_NAME = globalprotect-openconnect
|
||||
PKG = $(PKG_NAME)-$(VERSION)
|
||||
SERIES ?= $(shell lsb_release -cs)
|
||||
PUBLISH ?= 0
|
||||
|
||||
# Indicates whether to build the GUI components
|
||||
BUILD_GUI_HELPER ?= 1
|
||||
|
||||
# Indicates whether to build embedded webview auth support into gpauth
|
||||
BUILD_WEBVIEW_AUTH ?= 1
|
||||
ifeq ($(shell uname -s),Linux)
|
||||
PREFIX ?= /usr
|
||||
GPGUI_BINARY ?= $(wildcard .build/gpgui/gpgui_*/gpgui)
|
||||
else ifeq ($(shell uname -s)-$(shell uname -m),Darwin-arm64)
|
||||
PREFIX ?= /opt/homebrew
|
||||
else
|
||||
PREFIX ?= /usr/local
|
||||
endif
|
||||
BSD_FLAVOR ?= $(shell uname -s | tr '[:upper:]' '[:lower:]')
|
||||
GPGUI_BINARY ?= ../gpgui/target/release/gpgui
|
||||
|
||||
export DEBEMAIL = [email protected]
|
||||
export DEBFULLNAME = Kevin Yue
|
||||
export SNAPSHOT = $(shell test -f SNAPSHOT && echo "true" || echo "false")
|
||||
export OFFLINE_BUILD = $(shell test -f OFFLINE_BUILD && echo "1" || echo "0")
|
||||
# If OFFLINE is not set, use OFFLINE_BUILD
|
||||
ifndef OFFLINE
|
||||
OFFLINE = $(OFFLINE_BUILD)
|
||||
endif
|
||||
|
||||
ifeq ($(SNAPSHOT), true)
|
||||
RELEASE_TAG = snapshot
|
||||
@@ -29,8 +67,15 @@ ifeq ($(OFFLINE), 1)
|
||||
CARGO_BUILD_ARGS += --frozen
|
||||
endif
|
||||
|
||||
ifeq ($(IGNORE_RUST_VERSION), 1)
|
||||
CARGO_BUILD_ARGS += --ignore-rust-version
|
||||
endif
|
||||
|
||||
default: build
|
||||
|
||||
dev-service:
|
||||
./scripts/dev-service.sh
|
||||
|
||||
version:
|
||||
@echo $(VERSION)
|
||||
|
||||
@@ -39,24 +84,20 @@ clean-tarball:
|
||||
rm -rf .vendor
|
||||
rm -rf vendor.tar.xz
|
||||
rm -rf .cargo
|
||||
rm -f SOURCE_COMMIT
|
||||
|
||||
# Create a tarball, include the cargo dependencies if OFFLINE is set to 1
|
||||
tarball: clean-tarball
|
||||
if [ $(BUILD_FE) -eq 1 ]; then \
|
||||
echo "Building frontend..."; \
|
||||
cd apps/gpgui-helper && pnpm install && pnpm build; \
|
||||
fi
|
||||
|
||||
# Remove node_modules to reduce the tarball size
|
||||
rm -rf apps/gpgui-helper/node_modules
|
||||
|
||||
mkdir -p .cargo
|
||||
mkdir -p .build/tarball
|
||||
printf '%s\n' "$(SOURCE_COMMIT_VALUE)" > SOURCE_COMMIT
|
||||
|
||||
# If OFFLINE is set to 1, vendor all cargo dependencies
|
||||
# Generate a OFFLINE_BUILD file to indicate offline build
|
||||
if [ $(OFFLINE) -eq 1 ]; then \
|
||||
$(CARGO) vendor .vendor > .cargo/config.toml; \
|
||||
tar -cJf vendor.tar.xz .vendor; \
|
||||
touch OFFLINE_BUILD; \
|
||||
fi
|
||||
|
||||
@echo "Creating tarball..."
|
||||
@@ -68,36 +109,38 @@ download-gui:
|
||||
if [ $(INCLUDE_GUI) -eq 1 ]; then \
|
||||
echo "Downloading GlobalProtect GUI..."; \
|
||||
mkdir -p .build/gpgui; \
|
||||
curl -sSL https://github.com/yuezk/GlobalProtect-openconnect/releases/download/$(RELEASE_TAG)/gpgui_$(shell uname -m).bin.tar.xz \
|
||||
-o .build/gpgui/gpgui_$(shell uname -m).bin.tar.xz; \
|
||||
curl -sSL https://github.com/yuezk/GlobalProtect-openconnect/releases/download/$(RELEASE_TAG)/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz \
|
||||
-o .build/gpgui/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz; \
|
||||
tar -xJf .build/gpgui/*.tar.xz -C .build/gpgui; \
|
||||
else \
|
||||
echo "Skipping GlobalProtect GUI download (INCLUDE_GUI=0)"; \
|
||||
fi
|
||||
|
||||
build: download-gui build-fe build-rs
|
||||
|
||||
# Install and build the frontend
|
||||
# If OFFLINE is set to 1, skip it
|
||||
build-fe:
|
||||
if [ $(OFFLINE) -eq 1 ] || [ $(BUILD_FE) -eq 0 ]; then \
|
||||
echo "Skipping frontend build (OFFLINE=1 or BUILD_FE=0)"; \
|
||||
else \
|
||||
cd apps/gpgui-helper && pnpm install && pnpm build; \
|
||||
fi
|
||||
|
||||
if [ ! -d apps/gpgui-helper/dist ]; then \
|
||||
echo "Error: frontend build failed"; \
|
||||
exit 1; \
|
||||
fi
|
||||
build: download-gui build-rs
|
||||
|
||||
build-rs:
|
||||
if [ $(OFFLINE) -eq 1 ]; then \
|
||||
tar -xJf vendor.tar.xz; \
|
||||
fi
|
||||
|
||||
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth
|
||||
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpgui-helper --features "tauri/custom-protocol"
|
||||
# Remove the rust-toolchain.toml if DISABLE_RUST_TOOLCHAIN is set to 1
|
||||
if [ $(DISABLE_RUST_TOOLCHAIN) -eq 1 ]; then \
|
||||
rm -vf rust-toolchain.toml; \
|
||||
fi
|
||||
|
||||
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice
|
||||
|
||||
# Build gpauth with or without embedded webview auth support
|
||||
if [ $(BUILD_WEBVIEW_AUTH) -eq 1 ]; then \
|
||||
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpauth; \
|
||||
else \
|
||||
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpauth --no-default-features; \
|
||||
fi
|
||||
|
||||
# Only build the GUI components if BUILD_GUI_HELPER is set to 1
|
||||
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
|
||||
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpgui-helper; \
|
||||
fi
|
||||
|
||||
clean:
|
||||
$(CARGO) clean
|
||||
@@ -105,40 +148,198 @@ clean:
|
||||
rm -rf .vendor
|
||||
rm -rf apps/gpgui-helper/node_modules
|
||||
|
||||
install:
|
||||
@echo "Installing $(PKG_NAME)..."
|
||||
ifeq ($(shell uname -s),Darwin)
|
||||
install: install-macos
|
||||
install-gpclient: install-gpclient-macos
|
||||
else ifneq ($(filter FreeBSD OpenBSD,$(shell uname -s)),)
|
||||
install: install-bsd
|
||||
install-gpclient: install-gpclient-unix
|
||||
else
|
||||
install: install-linux
|
||||
install-gpclient: install-gpclient-unix
|
||||
endif
|
||||
|
||||
install -Dm755 target/release/gpclient $(DESTDIR)/usr/bin/gpclient
|
||||
install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth
|
||||
install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice
|
||||
install -Dm755 target/release/gpgui-helper $(DESTDIR)/usr/bin/gpgui-helper
|
||||
install-gpclient-unix:
|
||||
install -d "$(DESTDIR)$(PREFIX)/bin" "$(DESTDIR)$(PREFIX)/libexec/gpclient"
|
||||
install -m 755 "$(CARGO_RELEASE_DIR)/gpclient" "$(DESTDIR)$(PREFIX)/bin/"
|
||||
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script "$(DESTDIR)$(PREFIX)/libexec/gpclient/"
|
||||
|
||||
if [ -f .build/gpgui/gpgui_*/gpgui ]; then \
|
||||
install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \
|
||||
install-gpclient-macos:
|
||||
install -d "$(DESTDIR)$(PREFIX)/bin" "$(DESTDIR)$(PREFIX)/lib/gpclient" "$(DESTDIR)$(PREFIX)/libexec/gpclient"
|
||||
install -m 755 "$(CARGO_RELEASE_DIR)/gpclient" "$(DESTDIR)$(PREFIX)/bin/"
|
||||
set -e; library=$$(sh scripts/macos-openconnect-library.sh "$(CARGO_RELEASE_DIR)/gpclient"); \
|
||||
install -m 755 "$$library" "$(DESTDIR)$(PREFIX)/lib/gpclient/"; \
|
||||
install_name_tool -delete_rpath "$$(dirname "$$library")" "$(DESTDIR)$(PREFIX)/bin/gpclient"; \
|
||||
codesign --force --sign - "$(DESTDIR)$(PREFIX)/bin/gpclient"
|
||||
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script "$(DESTDIR)$(PREFIX)/libexec/gpclient/"
|
||||
|
||||
install-macos: install-gpclient-macos
|
||||
install -m 755 "$(CARGO_RELEASE_DIR)/gpauth" "$(DESTDIR)$(PREFIX)/bin/"
|
||||
|
||||
# Common executable and icon installation uses portable install options on Linux/BSD.
|
||||
install-unix: install-gpclient-unix
|
||||
set -e; for binary in gpauth gpservice; do \
|
||||
install -m 755 "$(CARGO_RELEASE_DIR)/$$binary" "$(DESTDIR)$(PREFIX)/bin/"; \
|
||||
done
|
||||
set -e; for binary in gp-hip-script-installer gp-vpnc-script-installer; do \
|
||||
install -m 755 "$(CARGO_RELEASE_DIR)/$$binary" "$(DESTDIR)$(PREFIX)/libexec/gpclient/"; \
|
||||
done
|
||||
set -e; if [ "$(BUILD_GUI_HELPER)" = "1" ]; then \
|
||||
install -m 755 "$(CARGO_RELEASE_DIR)/gpgui-helper" "$(DESTDIR)$(PREFIX)/bin/"; \
|
||||
fi
|
||||
set -e; if [ -f "$(GPGUI_BINARY)" ]; then \
|
||||
install -m 755 "$(GPGUI_BINARY)" "$(DESTDIR)$(PREFIX)/bin/gpgui"; \
|
||||
fi
|
||||
set -e; for file in packaging/files/usr/share/icons/hicolor/*/apps/gpgui.*; do \
|
||||
destination="$(DESTDIR)$(PREFIX)/$${file#packaging/files/usr/}"; \
|
||||
install -d "$$(dirname "$$destination")"; \
|
||||
install -m 644 "$$file" "$$destination"; \
|
||||
done
|
||||
|
||||
install -Dm644 packaging/files/usr/share/applications/gpgui.desktop $(DESTDIR)/usr/share/applications/gpgui.desktop
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/128x128/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/128x128/apps/gpgui.png
|
||||
install -Dm644 packaging/files/usr/share/icons/hicolor/256x256@2/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/256x256@2/apps/gpgui.png
|
||||
install -Dm644 packaging/files/usr/share/polkit-1/actions/com.yuezk.gpgui.policy $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
|
||||
install-linux: install-unix
|
||||
@echo "Installing Linux integration under $(PREFIX)..."
|
||||
set -e; for file in share/applications/gpgui.desktop \
|
||||
share/applications/gpgui-helper.desktop \
|
||||
share/applications/gpauth.desktop \
|
||||
share/polkit-1/actions/com.yuezk.gpgui.policy \
|
||||
lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down \
|
||||
lib/NetworkManager/dispatcher.d/gpclient-nm-hook; do \
|
||||
mode=644; case "$$file" in lib/*) mode=755 ;; esac; \
|
||||
destination="$(DESTDIR)$(PREFIX)/$$file"; \
|
||||
install -d "$$(dirname "$$destination")"; \
|
||||
install -m "$$mode" "packaging/files/usr/$$file" "$$destination"; \
|
||||
done
|
||||
sh scripts/relocate-install-paths.sh "$(PREFIX)" /usr "$(DESTDIR)$(PREFIX)"
|
||||
|
||||
uninstall:
|
||||
@echo "Uninstalling $(PKG_NAME)..."
|
||||
install-bsd: install-unix
|
||||
@echo "Installing BSD integration under $(PREFIX)..."
|
||||
install -d "$(DESTDIR)$(PREFIX)/share/applications" "$(DESTDIR)$(PREFIX)/share/polkit-1/actions"
|
||||
install -m 644 packaging/bsd/gpgui.desktop packaging/bsd/gpgui-helper.desktop packaging/bsd/gpauth.desktop "$(DESTDIR)$(PREFIX)/share/applications/"
|
||||
install -m 644 packaging/bsd/com.yuezk.gpgui.policy "$(DESTDIR)$(PREFIX)/share/polkit-1/actions/"
|
||||
sh scripts/relocate-install-paths.sh "$(PREFIX)" /usr/local "$(DESTDIR)$(PREFIX)"
|
||||
|
||||
rm -f $(DESTDIR)/usr/bin/gpclient
|
||||
rm -f $(DESTDIR)/usr/bin/gpauth
|
||||
rm -f $(DESTDIR)/usr/bin/gpservice
|
||||
rm -f $(DESTDIR)/usr/bin/gpgui-helper
|
||||
rm -f $(DESTDIR)/usr/bin/gpgui
|
||||
clean-bsd-package:
|
||||
rm -rf .build/$(BSD_FLAVOR)
|
||||
|
||||
rm -f $(DESTDIR)/usr/share/applications/gpgui.desktop
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/128x128/apps/gpgui.png
|
||||
rm -f $(DESTDIR)/usr/share/icons/hicolor/256x256@2/apps/gpgui.png
|
||||
rm -f $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
|
||||
bsd-gpgui-tarball:
|
||||
test -x "$(GPGUI_BINARY)"
|
||||
rm -rf .build/$(BSD_FLAVOR)/gpgui
|
||||
mkdir -p .build/$(BSD_FLAVOR)/artifacts .build/$(BSD_FLAVOR)/gpgui/gpgui_$(VERSION)
|
||||
cp "$(GPGUI_BINARY)" .build/$(BSD_FLAVOR)/gpgui/gpgui_$(VERSION)/
|
||||
tar -cf - -C .build/$(BSD_FLAVOR)/gpgui gpgui_$(VERSION) | xz -c > .build/$(BSD_FLAVOR)/artifacts/gpgui_$(BSD_FLAVOR)_$(shell uname -m).bin.tar.xz
|
||||
file=.build/$(BSD_FLAVOR)/artifacts/gpgui_$(BSD_FLAVOR)_$(shell uname -m).bin.tar.xz; \
|
||||
if command -v sha256sum >/dev/null 2>&1; then sha256sum "$$file" | cut -d ' ' -f 1; \
|
||||
elif command -v sha256 >/dev/null 2>&1; then sha256 -q "$$file"; \
|
||||
else cksum -a sha256 "$$file" | awk '{print $$1}'; fi > "$$file.sha256"
|
||||
|
||||
package-freebsd: BSD_FLAVOR=freebsd
|
||||
package-freebsd: clean-bsd-package
|
||||
test -x "$(GPGUI_BINARY)"
|
||||
mkdir -p .build/freebsd/pkgroot .build/freebsd/artifacts .build/freebsd/metadata
|
||||
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/freebsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
|
||||
find .build/freebsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/freebsd/pkgroot$(PREFIX)/||' | sort > .build/freebsd/PLIST
|
||||
freebsd_major=$$(freebsd-version -u | sed 's/\..*//'); \
|
||||
freebsd_arch=$$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm64/aarch64/'); \
|
||||
sed \
|
||||
-e 's/@PKG_NAME@/$(PKG_NAME)/g' \
|
||||
-e 's/@VERSION@/$(VERSION)/g' \
|
||||
-e "s/@ABI@/FreeBSD:$$freebsd_major:$$freebsd_arch/g" \
|
||||
-e "s/@ARCH@/freebsd:$$freebsd_major:$$freebsd_arch/g" \
|
||||
-e 's|@PREFIX@|$(PREFIX)|g' \
|
||||
packaging/bsd/freebsd/MANIFEST.in > .build/freebsd/metadata/+MANIFEST
|
||||
cp packaging/bsd/freebsd/POST_DEINSTALL .build/freebsd/metadata/+POST_DEINSTALL
|
||||
pkg create -r .build/freebsd/pkgroot -M .build/freebsd/metadata -p .build/freebsd/PLIST -o .build/freebsd/artifacts
|
||||
freebsd_arch=$$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm64/aarch64/'); \
|
||||
mv .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION).pkg .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION)-freebsd-$$freebsd_arch.pkg
|
||||
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=freebsd GPGUI_BINARY="$(GPGUI_BINARY)"
|
||||
|
||||
package-openbsd: BSD_FLAVOR=openbsd
|
||||
package-openbsd: clean-bsd-package
|
||||
test -x "$(GPGUI_BINARY)"
|
||||
mkdir -p .build/openbsd/pkgroot .build/openbsd/artifacts
|
||||
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/openbsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
|
||||
cp packaging/bsd/openbsd/COMMENT .build/openbsd/+COMMENT
|
||||
cp packaging/bsd/openbsd/DESC .build/openbsd/+DESC
|
||||
sh scripts/openbsd-library-dependencies.sh .build/openbsd/pkgroot > .build/openbsd/WANTLIB
|
||||
{ \
|
||||
cat .build/openbsd/WANTLIB; \
|
||||
echo '@unexec-delete /bin/rm -f /usr/local/libexec/gpclient/gpgui /var/db/gpclient/scripts/vpnc-script /var/db/gpclient/scripts/vpnc-script.metadata || echo "Warning: failed to remove gpclient runtime files" >&2'; \
|
||||
echo '@unexec-delete /bin/rmdir /usr/local/libexec/gpclient 2>/dev/null || true'; \
|
||||
echo '@unexec-delete /bin/rmdir /var/db/gpclient/scripts 2>/dev/null || true'; \
|
||||
echo '@unexec-delete /bin/rmdir /var/db/gpclient 2>/dev/null || true'; \
|
||||
find .build/openbsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/openbsd/pkgroot$(PREFIX)/||' | sort; \
|
||||
} > .build/openbsd/PLIST
|
||||
comment=$$(cat .build/openbsd/+COMMENT); \
|
||||
openbsd_arch=$$(uname -m | sed 's/x86_64/amd64/'); \
|
||||
gnome_keyring_pkg=$$(pkg_info -e 'gnome-keyring-*' | sed 's/^inst://' | head -n 1); \
|
||||
dbus_pkg=$$(pkg_info -e 'dbus-*' | sed 's/^inst://' | head -n 1); \
|
||||
polkit_pkg=$$(pkg_info -e 'polkit-*' | sed 's/^inst://' | head -n 1); \
|
||||
webkitgtk_pkg=$$(pkg_info -e 'webkitgtk41-*' | sed 's/^inst://' | head -n 1); \
|
||||
xdg_utils_pkg=$$(pkg_info -e 'xdg-utils-*' | sed 's/^inst://' | head -n 1); \
|
||||
pkg_create \
|
||||
-B .build/openbsd/pkgroot \
|
||||
-D COMMENT="$$comment" \
|
||||
-d .build/openbsd/+DESC \
|
||||
-f .build/openbsd/PLIST \
|
||||
-p $(PREFIX) \
|
||||
-P x11/gnome/keyring:gnome-keyring-*:$$gnome_keyring_pkg \
|
||||
-P x11/dbus:dbus-*:$$dbus_pkg \
|
||||
-P sysutils/polkit:polkit-*:$$polkit_pkg \
|
||||
-P www/webkitgtk4,webkitgtk41:webkitgtk41-*:$$webkitgtk_pkg \
|
||||
-P devel/xdg-utils:xdg-utils-*:$$xdg_utils_pkg \
|
||||
.build/openbsd/artifacts/$(PKG_NAME)-$(VERSION)-openbsd-$$openbsd_arch.tgz
|
||||
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)"
|
||||
|
||||
ifeq ($(shell uname -s),Darwin)
|
||||
uninstall: uninstall-macos
|
||||
else ifneq ($(filter FreeBSD OpenBSD,$(shell uname -s)),)
|
||||
uninstall: uninstall-bsd
|
||||
else
|
||||
uninstall: uninstall-linux
|
||||
endif
|
||||
|
||||
.PHONY: install install-gpclient install-macos install-unix install-linux install-bsd \
|
||||
install-gpclient-macos install-gpclient-unix \
|
||||
uninstall uninstall-macos uninstall-unix uninstall-linux uninstall-bsd
|
||||
|
||||
uninstall-macos:
|
||||
@echo "Uninstalling $(PKG_NAME) for macOS under $(PREFIX)..."
|
||||
rm -f "$(DESTDIR)$(PREFIX)/bin/gpclient" "$(DESTDIR)$(PREFIX)/bin/gpauth" \
|
||||
"$(DESTDIR)$(PREFIX)/libexec/gpclient/vpnc-script" \
|
||||
"$(DESTDIR)$(PREFIX)/lib/gpclient/"libopenconnect.*.dylib
|
||||
rmdir "$(DESTDIR)$(PREFIX)/lib/gpclient" "$(DESTDIR)$(PREFIX)/libexec/gpclient" 2>/dev/null || true
|
||||
|
||||
uninstall-unix:
|
||||
@echo "Uninstalling $(PKG_NAME) under $(PREFIX)..."
|
||||
set -e; for binary in gpclient gpauth gpservice gpgui-helper gpgui; do \
|
||||
rm -f "$(DESTDIR)$(PREFIX)/bin/$$binary"; \
|
||||
done
|
||||
set -e; for file in gp-hip-script-installer gp-vpnc-script-installer vpnc-script; do \
|
||||
rm -f "$(DESTDIR)$(PREFIX)/libexec/gpclient/$$file"; \
|
||||
done
|
||||
set -e; for file in packaging/files/usr/share/icons/hicolor/*/apps/gpgui.*; do \
|
||||
rm -f "$(DESTDIR)$(PREFIX)/$${file#packaging/files/usr/}"; \
|
||||
done
|
||||
rm -f "$(DESTDIR)$(PREFIX)/share/applications/gpgui.desktop" \
|
||||
"$(DESTDIR)$(PREFIX)/share/applications/gpgui-helper.desktop" \
|
||||
"$(DESTDIR)$(PREFIX)/share/applications/gpauth.desktop" \
|
||||
"$(DESTDIR)$(PREFIX)/share/polkit-1/actions/com.yuezk.gpgui.policy"
|
||||
rmdir "$(DESTDIR)$(PREFIX)/libexec/gpclient" 2>/dev/null || true
|
||||
|
||||
uninstall-linux: uninstall-unix
|
||||
rm -f "$(DESTDIR)$(PREFIX)/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down" \
|
||||
"$(DESTDIR)$(PREFIX)/lib/NetworkManager/dispatcher.d/gpclient-nm-hook"
|
||||
rm -f "$(DESTDIR)/var/lib/gpclient/gpgui" \
|
||||
"$(DESTDIR)/var/lib/gpclient/gpgui-nsh" \
|
||||
"$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script" \
|
||||
"$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script.metadata"
|
||||
rmdir "$(DESTDIR)/var/lib/gpclient/scripts" "$(DESTDIR)/var/lib/gpclient" 2>/dev/null || true
|
||||
|
||||
uninstall-bsd: uninstall-unix
|
||||
rm -f "$(DESTDIR)/usr/local/libexec/gpclient/gpgui" \
|
||||
"$(DESTDIR)/var/db/gpclient/scripts/vpnc-script" \
|
||||
"$(DESTDIR)/var/db/gpclient/scripts/vpnc-script.metadata"
|
||||
rmdir "$(DESTDIR)/var/db/gpclient/scripts" "$(DESTDIR)/var/db/gpclient" 2>/dev/null || true
|
||||
|
||||
clean-debian:
|
||||
rm -rf .build/deb
|
||||
@@ -154,18 +355,36 @@ init-debian: clean-debian tarball
|
||||
cp -f packaging/deb/control.in .build/deb/$(PKG)/debian/control
|
||||
cp -f packaging/deb/rules.in .build/deb/$(PKG)/debian/rules
|
||||
cp -f packaging/deb/postrm .build/deb/$(PKG)/debian/postrm
|
||||
cp -f packaging/deb/compat .build/deb/$(PKG)/debian/compat
|
||||
|
||||
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/deb/$(PKG)/debian/rules
|
||||
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/control
|
||||
|
||||
# Remove the GUI dependencies if neither GUI component is included
|
||||
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ]; then \
|
||||
sed -i "/libsecret-1-0/d" .build/deb/$(PKG)/debian/control; \
|
||||
sed -i "/libayatana-appindicator3-1/d" .build/deb/$(PKG)/debian/control; \
|
||||
sed -i "/gnome-keyring/d" .build/deb/$(PKG)/debian/control; \
|
||||
fi
|
||||
|
||||
# Remove WebKitGTK only if no included component needs it
|
||||
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ] && [ $(BUILD_WEBVIEW_AUTH) -eq 0 ]; then \
|
||||
sed -i "/libwebkit2gtk-4.1-dev/d" .build/deb/$(PKG)/debian/control; \
|
||||
fi
|
||||
|
||||
sed -i "s/@INCLUDE_GUI@/$(INCLUDE_GUI)/g" .build/deb/$(PKG)/debian/rules
|
||||
sed -i "s/@BUILD_GUI_HELPER@/$(BUILD_GUI_HELPER)/g" .build/deb/$(PKG)/debian/rules
|
||||
sed -i "s/@BUILD_WEBVIEW_AUTH@/$(BUILD_WEBVIEW_AUTH)/g" .build/deb/$(PKG)/debian/rules
|
||||
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/rules
|
||||
|
||||
rm -f .build/deb/$(PKG)/debian/changelog
|
||||
|
||||
deb: init-debian
|
||||
# Remove the rust build depdency from the control file
|
||||
sed -i "s/@RUST@//g" .build/deb/$(PKG)/debian/control
|
||||
|
||||
cd .build/deb/$(PKG) && dch --create --distribution unstable --package $(PKG_NAME) --newversion $(VERSION)-$(REVISION) "Bugfix and improvements."
|
||||
|
||||
cd .build/deb/$(PKG) && debuild --preserve-env -e PATH -us -uc -b
|
||||
# Install build dependencies
|
||||
cd .build/deb/$(PKG) && sudo mk-build-deps --install --remove debian/control || echo "mk-build-deps failed, continuing"
|
||||
|
||||
cd .build/deb/$(PKG) && debuild --preserve-env -e PATH -us -uc -b -d
|
||||
|
||||
check-ppa:
|
||||
if [ $(OFFLINE) -eq 0 ]; then \
|
||||
@@ -174,8 +393,6 @@ check-ppa:
|
||||
|
||||
# Usage: make ppa SERIES=focal OFFLINE=1 PUBLISH=1
|
||||
ppa: check-ppa init-debian
|
||||
sed -i "s/@RUST@/rust-all(>=1.70)/g" .build/deb/$(PKG)/debian/control
|
||||
|
||||
$(eval SERIES_VER = $(shell distro-info --series $(SERIES) -r | cut -d' ' -f1))
|
||||
@echo "Building for $(SERIES) $(SERIES_VER)"
|
||||
|
||||
@@ -202,7 +419,7 @@ init-rpm: clean-rpm
|
||||
|
||||
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.spec
|
||||
sed -i "s/@REVISION@/$(REVISION)/g" .build/rpm/globalprotect-openconnect.spec
|
||||
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/rpm/globalprotect-openconnect.spec
|
||||
sed -i "s|@SOURCE@|$(RPM_SOURCE)|g" .build/rpm/globalprotect-openconnect.spec
|
||||
sed -i "s/@DATE@/$(shell LC_ALL=en.US date "+%a %b %d %Y")/g" .build/rpm/globalprotect-openconnect.spec
|
||||
|
||||
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.changes
|
||||
@@ -231,15 +448,47 @@ init-pkgbuild: clean-pkgbuild tarball
|
||||
|
||||
cp .build/tarball/${PKG}.tar.gz .build/pkgbuild
|
||||
cp packaging/pkgbuild/PKGBUILD.in .build/pkgbuild/PKGBUILD
|
||||
cp packaging/pkgbuild/gp.install .build/pkgbuild/gp.install
|
||||
|
||||
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/pkgbuild/PKGBUILD
|
||||
sed -i "s/@VERSION@/$(VERSION)/g" .build/pkgbuild/PKGBUILD
|
||||
sed -i "s/@REVISION@/$(REVISION)/g" .build/pkgbuild/PKGBUILD
|
||||
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/pkgbuild/PKGBUILD
|
||||
|
||||
pkgbuild: init-pkgbuild
|
||||
cd .build/pkgbuild && makepkg -s --noconfirm
|
||||
|
||||
clean-apk:
|
||||
rm -rf .build/apk
|
||||
|
||||
init-apk: clean-apk tarball
|
||||
mkdir -p .build/apk
|
||||
|
||||
cp .build/tarball/${PKG}.tar.gz .build/apk
|
||||
cp packaging/apk/APKBUILD.in .build/apk/APKBUILD
|
||||
cp packaging/apk/post-deinstall .build/apk/$(PKG_NAME).post-deinstall
|
||||
|
||||
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/apk/APKBUILD
|
||||
sed -i "s/@VERSION@/$(VERSION)/g" .build/apk/APKBUILD
|
||||
sed -i "s/@REVISION@/$(REVISION)/g" .build/apk/APKBUILD
|
||||
checksum=$$(sha512sum .build/apk/${PKG}.tar.gz | cut -d' ' -f1); \
|
||||
sed -i "s/@SHA512@/$$checksum/g" .build/apk/APKBUILD
|
||||
|
||||
# Remove the GUI dependencies if neither GUI component is included
|
||||
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ]; then \
|
||||
sed -i "/^\tlibayatana-appindicator$$/d" .build/apk/APKBUILD; \
|
||||
sed -i "/^\tlibsecret$$/d" .build/apk/APKBUILD; \
|
||||
fi
|
||||
|
||||
# Remove WebKitGTK only if no included component needs it
|
||||
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ] && [ $(BUILD_WEBVIEW_AUTH) -eq 0 ]; then \
|
||||
sed -i "/^\twebkit2gtk-4.1$$/d" .build/apk/APKBUILD; \
|
||||
fi
|
||||
|
||||
apk: init-apk
|
||||
cd .build/apk && abuild -r -P "$(CURDIR)/.build/apk/packages"
|
||||
|
||||
find .build/apk/packages -type f -name "$(PKG_NAME)-*.apk" -exec cp {} .build/apk \;
|
||||
|
||||
clean-binary:
|
||||
rm -rf .build/binary
|
||||
|
||||
@@ -251,7 +500,7 @@ binary: clean-binary tarball
|
||||
|
||||
mkdir -p .build/binary/$(PKG_NAME)_$(VERSION)/artifacts
|
||||
|
||||
make -C .build/binary/${PKG} build OFFLINE=$(OFFLINE) BUILD_FE=0 INCLUDE_GUI=$(INCLUDE_GUI)
|
||||
make -C .build/binary/${PKG} build INCLUDE_GUI=$(INCLUDE_GUI)
|
||||
make -C .build/binary/${PKG} install DESTDIR=$(PWD)/.build/binary/$(PKG_NAME)_$(VERSION)/artifacts
|
||||
|
||||
cp packaging/binary/Makefile.in .build/binary/$(PKG_NAME)_$(VERSION)/Makefile
|
||||
|
||||
@@ -1,234 +1,287 @@
|
||||
# GlobalProtect-openconnect
|
||||
|
||||
A GUI for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method. Inspired by [gp-saml-gui](https://github.com/dlenski/gp-saml-gui).
|
||||
A GlobalProtect VPN client built on OpenConnect. It provides command-line tools (`gpclient`) and the GP Connect desktop application for macOS, Linux, FreeBSD, and OpenBSD.
|
||||
|
||||
> **Disclaimer**: GP Connect is an independent third-party client for GlobalProtect VPN networks. It is not affiliated with or endorsed by Palo Alto Networks, Inc.
|
||||
|
||||
<p align="center">
|
||||
<img width="300" src="https://github.com/yuezk/GlobalProtect-openconnect/assets/3297602/9242df9c-217d-42ab-8c21-8f9f69cd4eb5">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/images/gp-connect-showcase-dark.png">
|
||||
<source media="(prefers-color-scheme: light)" srcset="docs/images/gp-connect-showcase-light.png">
|
||||
<img alt="GP Connect Desktop" src="docs/images/gp-connect-showcase-light.png" width="640">
|
||||
</picture>
|
||||
</p>
|
||||
|
||||
> **Inspired by** [gp-saml-gui](https://github.com/dlenski/gp-saml-gui)
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Features](#features)
|
||||
- [Usage](#usage)
|
||||
- [Command-Line Interface](#command-line-interface)
|
||||
- [Graphical User Interface](#graphical-user-interface)
|
||||
- [Installation](#installation)
|
||||
- [macOS](#macos)
|
||||
- [Debian / Ubuntu](#debian--ubuntu)
|
||||
- [Arch Linux / Manjaro](#arch-linux--manjaro)
|
||||
- [Fedora / RHEL](#fedora--rhel)
|
||||
- [openSUSE](#opensuse)
|
||||
- [Alpine Linux](#alpine-linux)
|
||||
- [FreeBSD](#freebsd)
|
||||
- [OpenBSD](#openbsd)
|
||||
- [Gentoo](#gentoo)
|
||||
- [NixOS](#nixos)
|
||||
- [Docker](#docker)
|
||||
- [Other Distributions](#other-distributions)
|
||||
- [Building from Source](#building-from-source)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [NetworkManager Integration](#networkmanager-integration)
|
||||
- [Licensing](#licensing)
|
||||
|
||||
## Features
|
||||
|
||||
- [x] Better Linux support
|
||||
- [x] Support both CLI and GUI
|
||||
- [x] Support both SSO and non-SSO authentication
|
||||
- [x] Support the FIDO2 authentication (e.g., YubiKey)
|
||||
- [x] Support authentication using default browser
|
||||
- [x] Support client certificate authentication
|
||||
- [x] Support multiple portals
|
||||
- [x] Support gateway selection
|
||||
- [x] Support connect gateway directly
|
||||
- [x] Support auto-connect on startup
|
||||
- [x] Support system tray icon
|
||||
- **Multi-Platform** – macOS (Apple silicon), Linux, FreeBSD, and OpenBSD
|
||||
- **Dual Interfaces** – Fast terminal CLI (`gpclient`) and desktop GUI (**GP Connect**)
|
||||
- **Native Shell on Linux** – Ultra-low-memory native desktop GUI alongside the webview interface
|
||||
- **Flexible Routing** – Full System VPN tunnel or local SOCKS5 proxy mode
|
||||
- **Modern Authentication** – SAML / SSO, MFA, FIDO2 (YubiKey), client certificates, and external browser login
|
||||
- **Automated HIP Reports** – Built-in HIP report generation or custom scripts
|
||||
- **Multi-Portal & Direct Gateway** – Manage multiple saved portals or connect directly to a gateway
|
||||
- **Desktop Integration** – Theme-aware system tray icon, auto-connect on launch, and reconnect on wake
|
||||
|
||||
## Usage
|
||||
|
||||
### CLI
|
||||
### Command-Line Interface
|
||||
|
||||
The CLI version is always free and open source in this repo. It has almost the same features as the GUI version.
|
||||
|
||||
```
|
||||
Usage: gpclient [OPTIONS] <COMMAND>
|
||||
|
||||
Commands:
|
||||
connect Connect to a portal server
|
||||
disconnect Disconnect from the server
|
||||
launch-gui Launch the GUI
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
|
||||
Options:
|
||||
--fix-openssl Get around the OpenSSL `unsafe legacy renegotiation` error
|
||||
--ignore-tls-errors Ignore the TLS errors
|
||||
-h, --help Print help
|
||||
-V, --version Print version
|
||||
|
||||
See 'gpclient help <command>' for more information on a specific command.
|
||||
```
|
||||
|
||||
To use the external browser for authentication with the CLI version, you need to use the following command:
|
||||
The open-source `gpclient` CLI handles authentication, connection lifecycle, and HIP generation:
|
||||
|
||||
```bash
|
||||
sudo -E gpclient connect --browser default <portal>
|
||||
# Connect to a portal server
|
||||
sudo gpclient connect <portal>
|
||||
|
||||
# Connect using browser authentication (SSO / SAML)
|
||||
sudo gpclient connect <portal> --browser
|
||||
|
||||
# Connect directly to a gateway server
|
||||
sudo gpclient connect <gateway> --as-gateway
|
||||
|
||||
# Connect with automatic HIP report generation
|
||||
sudo gpclient connect <portal> --hip
|
||||
|
||||
# Headless / remote server authentication (prints auth URL to open in any browser)
|
||||
sudo gpclient connect <portal> --browser manual
|
||||
|
||||
# Disconnect
|
||||
sudo gpclient disconnect
|
||||
```
|
||||
|
||||
Or you can try the following command if the above command does not work:
|
||||
Run `gpclient --help` or `gpclient <command> --help` to view all available commands and options.
|
||||
|
||||
```bash
|
||||
gpauth <portal> --browser default 2>/dev/null | sudo gpclient connect <portal> --cookie-on-stdin
|
||||
```
|
||||
### Graphical User Interface
|
||||
|
||||
You can specify the browser with the `--browser <browser>` option, e.g., `--browser firefox`, `--browser chrome`, etc.
|
||||
- **macOS**: Open **GP Connect** from Applications.
|
||||
- **Linux / BSD**: Launch GP Connect from your application menu or run:
|
||||
```bash
|
||||
gpclient launch-gui
|
||||
```
|
||||
|
||||
### GUI
|
||||
|
||||
The GUI version is also available after you installed it. You can launch it from the application menu or run `gpclient launch-gui` in the terminal.
|
||||
|
||||
> [!Note]
|
||||
>
|
||||
> The GUI version is partially open source. Its background service is open sourced in this repo as [gpservice](./apps/gpservice/). The GUI part is a wrapper of the background service, which is not open sourced.
|
||||
> [!TIP]
|
||||
> **On Linux, try Native Shell for lower memory usage.** Switch between Native Shell and Tauri in **Settings → General → Interface**.
|
||||
|
||||
## Installation
|
||||
|
||||
### Debian/Ubuntu based distributions
|
||||
### macOS
|
||||
|
||||
#### Install from PPA (Ubuntu 18.04 and later, except 24.04)
|
||||
Requires Apple silicon and macOS 13+. Includes both GP Connect and the `gpclient` CLI.
|
||||
|
||||
#### Option 1: Homebrew (Recommended)
|
||||
|
||||
```bash
|
||||
brew install --cask yuezk/gp-connect/gp-connect
|
||||
```
|
||||
sudo apt-get install gir1.2-gtk-3.0 gir1.2-webkit2-4.0
|
||||
|
||||
#### Option 2: DMG Installer
|
||||
|
||||
Download the `.dmg` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page and drag GP Connect into Applications.
|
||||
|
||||
### Debian / Ubuntu
|
||||
|
||||
#### Option 1: PPA (Recommended)
|
||||
|
||||
```bash
|
||||
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
|
||||
sudo apt-get update
|
||||
sudo apt-get install globalprotect-openconnect
|
||||
```
|
||||
|
||||
> [!Note]
|
||||
>
|
||||
> For Linux Mint, you might need to import the GPG key with: `sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761` if you encountered an error `gpg: keyserver receive failed: General error`.
|
||||
#### Option 2: DEB Package
|
||||
|
||||
#### **Ubuntu 24.04 and later**
|
||||
|
||||
The `libwebkit2gtk-4.0-37` package was [removed](https://bugs.launchpad.net/ubuntu/+source/webkit2gtk/+bug/2061914) from its repo, before [the issue](https://github.com/yuezk/GlobalProtect-openconnect/issues/351) gets resolved, you need to install them manually:
|
||||
Download the latest `.deb` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
|
||||
```bash
|
||||
wget http://launchpadlibrarian.net/704701349/libwebkit2gtk-4.0-37_2.43.3-1_amd64.deb
|
||||
wget http://launchpadlibrarian.net/704701345/libjavascriptcoregtk-4.0-18_2.43.3-1_amd64.deb
|
||||
|
||||
sudo dpkg --install *.deb
|
||||
```
|
||||
|
||||
And the latest package is not available in the PPA, you can follow the [Install from deb package](#install-from-deb-package) section to install the latest package.
|
||||
|
||||
#### **Ubuntu 18.04**
|
||||
|
||||
The latest package is not available in the PPA either, but you still needs to add the `ppa:yuezk/globalprotect-openconnect` repo beforehand to use the required `openconnect` package. Then you can follow the [Install from deb package](#install-from-deb-package) section to install the latest package.
|
||||
|
||||
#### Install from deb package
|
||||
|
||||
Download the latest deb package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `apt`:
|
||||
|
||||
```bash
|
||||
sudo apt install --fix-broken globalprotect-openconnect_*.deb
|
||||
sudo apt install ./globalprotect-openconnect_*.deb
|
||||
```
|
||||
|
||||
### Arch Linux / Manjaro
|
||||
|
||||
#### Install from AUR
|
||||
```bash
|
||||
# Official Extra repository
|
||||
sudo pacman -S globalprotect-openconnect
|
||||
|
||||
Install from AUR: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/)
|
||||
|
||||
```
|
||||
# AUR (git main)
|
||||
yay -S globalprotect-openconnect-git
|
||||
```
|
||||
|
||||
#### Install from package
|
||||
### Fedora / RHEL
|
||||
|
||||
Download the latest package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `pacman`:
|
||||
Enable the COPR repository:
|
||||
|
||||
```bash
|
||||
sudo pacman -U globalprotect-openconnect-*.pkg.tar.zst
|
||||
```
|
||||
|
||||
### Fedora 38 and later / Fedora Rawhide
|
||||
|
||||
#### Install from COPR
|
||||
|
||||
The package is available on [COPR](https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/) for various RPM-based distributions. You can install it with the following commands:
|
||||
|
||||
```
|
||||
sudo dnf copr enable yuezk/globalprotect-openconnect
|
||||
sudo dnf install globalprotect-openconnect
|
||||
```
|
||||
|
||||
### openSUSE Leap 15.6 / openSUSE Tumbleweed
|
||||
### openSUSE
|
||||
|
||||
#### Install from OBS (openSUSE Build Service)
|
||||
Packages are available on the [openSUSE Build Service](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect). Follow the [OBS instructions](https://software.opensuse.org/download.html?project=home%3Ayuezk&package=globalprotect-openconnect) for your distribution.
|
||||
|
||||
The package is also available on [OBS](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect) for various RPM-based distributions. You can follow the instructions [on this page](https://software.opensuse.org//download.html?project=home%3Ayuezk&package=globalprotect-openconnect) to install it.
|
||||
### Alpine Linux
|
||||
|
||||
### Other RPM-based distributions
|
||||
|
||||
#### Install from RPM package
|
||||
|
||||
Download the latest RPM package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
|
||||
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
|
||||
```bash
|
||||
sudo rpm -i globalprotect-openconnect-*.rpm
|
||||
sudo apk add --allow-untrusted globalprotect-openconnect-*.apk
|
||||
```
|
||||
|
||||
*(Requires `community` repository enabled for WebKitGTK and AppIndicator dependencies).*
|
||||
|
||||
### FreeBSD
|
||||
|
||||
Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
|
||||
```bash
|
||||
sudo pkg install ./globalprotect-openconnect-*-freebsd-*.pkg
|
||||
```
|
||||
|
||||
### OpenBSD
|
||||
|
||||
Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
|
||||
```bash
|
||||
doas pkg_add -D unsigned ./globalprotect-openconnect-*-openbsd-*.tgz
|
||||
```
|
||||
|
||||
### Gentoo
|
||||
|
||||
Install from the ```rios``` or ```slonko``` overlays. Example using rios:
|
||||
Available via the `guru` repository:
|
||||
|
||||
#### 1. Enable the overlay
|
||||
```
|
||||
sudo eselect repository enable rios
|
||||
```bash
|
||||
sudo eselect repository enable guru
|
||||
sudo emerge --sync guru
|
||||
sudo emerge --ask net-vpn/GlobalProtect-openconnect
|
||||
```
|
||||
|
||||
#### 2. Sync with the repository
|
||||
### NixOS
|
||||
|
||||
- If you have eix installed, use it:
|
||||
```
|
||||
sudo eix-sync
|
||||
```
|
||||
- Otherwise, use:
|
||||
```
|
||||
sudo emerge --sync
|
||||
Add the flake to your `flake.nix`:
|
||||
|
||||
```nix
|
||||
{
|
||||
inputs.globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
|
||||
|
||||
outputs = { self, nixpkgs, globalprotect-openconnect, ... }: {
|
||||
nixosConfigurations.<hostname> = nixpkgs.lib.nixosSystem {
|
||||
modules = [
|
||||
globalprotect-openconnect.nixosModules.default
|
||||
{
|
||||
programs.globalprotect-openconnect.enable = true;
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 3. Install
|
||||
Apply changes:
|
||||
|
||||
```sudo emerge globalprotect-openconnect```
|
||||
```bash
|
||||
sudo nixos-rebuild switch
|
||||
```
|
||||
|
||||
### Docker
|
||||
|
||||
### Other distributions
|
||||
Run the CLI client in an official Alpine container:
|
||||
|
||||
- Install `openconnect >= 8.20`, `webkit2gtk`, `libsecret`, `libayatana-appindicator` or `libappindicator-gtk3`.
|
||||
- Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
|
||||
- Extract the tarball with `tar -xJf globalprotect-openconnect_${version}_${arch}.bin.tar.xz`.
|
||||
- Run `sudo make install` to install the client.
|
||||
```bash
|
||||
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:latest \
|
||||
connect <portal> --browser manual
|
||||
```
|
||||
|
||||
## Build from source
|
||||
*(Add `--network host` on Linux if VPN routes should apply to the host network).*
|
||||
|
||||
You can also build the client from source, steps are as follows:
|
||||
### Other Distributions
|
||||
|
||||
### Prerequisites
|
||||
Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
|
||||
- [Install Rust 1.75 or later](https://www.rust-lang.org/tools/install)
|
||||
- Install Tauri dependencies: https://tauri.app/v1/guides/getting-started/prerequisites/#setting-up-linux
|
||||
- Install `perl` and `jq`
|
||||
- Install `openconnect >= 8.20` and `libopenconnect-dev` (or `openconnect-devel` on RPM-based distributions)
|
||||
- Install `pkexec`, `gnome-keyring` (or `pam_kwallet` on KDE)
|
||||
- Install `nodejs` and `pnpm` (optional only if you downloaded the source tarball from the release page and run with the `BUILD_FE=0` flag, see below)
|
||||
```bash
|
||||
tar -xJf globalprotect-openconnect_*.bin.tar.xz
|
||||
cd globalprotect-openconnect_*
|
||||
sudo make install
|
||||
```
|
||||
|
||||
### Build
|
||||
## Building from Source
|
||||
|
||||
1. Download the source code tarball from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Choose `globalprotect-openconnect-${version}.tar.gz`.
|
||||
2. Extract the tarball with `tar -xzf globalprotect-openconnect-${version}.tar.gz`.
|
||||
3. Enter the source directory and run `make build BUILD_FE=0` to build the client.
|
||||
3. Run `sudo make install` to install the client. (Note, `DESTDIR` is not supported)
|
||||
### Prerequisites (Linux)
|
||||
|
||||
## FAQ
|
||||
- [Rust](https://www.rust-lang.org/tools/install) 1.91 or later
|
||||
- Build tools: `make`, `pkg-config`, `autoconf`, `automake`, `libtool`, `gettext`
|
||||
- Libraries: `gmp`, `gnutls`, `nettle`, `libxml2`, `zlib`, `lz4`, `p11-kit`, `libsecret`, and `webkit2gtk-4.1` (or GTK 4 for Native Shell)
|
||||
- Polkit (`pkexec`) for privileged tunnel setup
|
||||
|
||||
1. How to deal with error `Secure Storage not ready`
|
||||
*(For FreeBSD and OpenBSD instructions, see [Building from Source on FreeBSD and OpenBSD](docs/bsd-source-build.md)).*
|
||||
|
||||
Try upgrade the client to `2.2.0` or later, which will use a file-based storage as a fallback.
|
||||
### Build Steps
|
||||
|
||||
You need to install the `gnome-keyring` package, and restart the system (See [#321](https://github.com/yuezk/GlobalProtect-openconnect/issues/321), [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)).
|
||||
```bash
|
||||
git clone --recursive https://github.com/yuezk/GlobalProtect-openconnect.git
|
||||
cd GlobalProtect-openconnect
|
||||
make build
|
||||
sudo make install
|
||||
```
|
||||
|
||||
2. How to deal with error `(gpauth:18869): Gtk-WARNING **: 10:33:37.566: cannot open display:`
|
||||
**Build Options:**
|
||||
|
||||
If you encounter this error when using the CLI version, try to run the command with `sudo -E` (See [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)).
|
||||
- `INCLUDE_GUI=1` – Download and install the matching desktop application bundle.
|
||||
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication (uses external browser or manual mode).
|
||||
- `BUILD_GUI_HELPER=0` – Skip building the helper UI.
|
||||
|
||||
## About Trial
|
||||
## Troubleshooting
|
||||
|
||||
The CLI version is always free, while the GUI version is paid. There are two trial modes for the GUI version:
|
||||
- **Headless / Remote Login**: When running without a desktop display or over SSH, use `--browser manual`. Open the printed URL in any browser and paste the callback URL back into the terminal.
|
||||
- **Diagnostics**: If you encounter issues, run `gpclient diagnostics` or follow the [diagnostics guide](docs/diagnostics.md) when opening an issue.
|
||||
|
||||
1. 10-day trial: You can use the GUI stable release for 10 days after the installation.
|
||||
2. 14-day trial: Each beta release has a fresh trial period (at most 14 days) after released.
|
||||
## NetworkManager Integration
|
||||
|
||||
## License
|
||||
- [WMP/GlobalProtect-SAML-NetworkManager](https://github.com/WMP/GlobalProtect-SAML-NetworkManager) – NetworkManager VPN plugin with SAML/SSO support for GNOME and KDE Plasma
|
||||
- [jdpipe/networkmanager-gpclient](https://github.com/jdpipe/networkmanager-gpclient) – NetworkManager VPN plugin that uses `gpclient`
|
||||
|
||||
- crate [gpapi](./crates/gpapi): [MIT](./crates/gpapi/LICENSE)
|
||||
- crate [openconnect](./crates/openconnect): [GPL-3.0](./crates/openconnect/LICENSE)
|
||||
- crate [common](./crates/common): [GPL-3.0](./crates/common/LICENSE)
|
||||
- app [gpservice](./apps/gpservice): [GPL-3.0](./apps/gpservice/LICENSE)
|
||||
- app [gpclient](./apps/gpclient): [GPL-3.0](./apps/gpclient/LICENSE)
|
||||
- app [gpauth](./apps/gpauth): [GPL-3.0](./apps/gpauth/LICENSE)
|
||||
- app [gpgui-helper](./apps/gpgui-helper): [GPL-3.0](./apps/gpgui-helper/LICENSE)
|
||||
## Licensing
|
||||
|
||||
- **CLI (`gpclient`)**: Free and open source (GPL-3.0).
|
||||
- **GUI (GP Connect)**: Commercial desktop application with a free trial.
|
||||
|
||||
### Open Source Components
|
||||
|
||||
| Component | Type | License |
|
||||
|-----------|------|---------|
|
||||
| [gpapi](./crates/gpapi) | Crate | [MIT](./crates/gpapi/LICENSE) |
|
||||
| [openconnect](./crates/openconnect) | Rust wrapper crate | [MIT](./crates/openconnect/LICENSE) |
|
||||
| [upstream OpenConnect](./crates/openconnect/deps/openconnect) | C library | [LGPL-2.1](./crates/openconnect/deps/openconnect/COPYING.LGPL) |
|
||||
| [common](./crates/common) | Crate | [MIT](./crates/common/LICENSE) |
|
||||
| [browser-launcher](./crates/browser-launcher) | Crate | [MIT](./crates/browser-launcher/LICENSE) |
|
||||
| [auth](./crates/auth) | Crate | [GPL-3.0](./crates/auth/LICENSE) |
|
||||
| [gpservice](./apps/gpservice) | Application | [GPL-3.0](./apps/gpservice/LICENSE) |
|
||||
| [gpclient](./apps/gpclient) | Application | [GPL-3.0](./apps/gpclient/LICENSE) |
|
||||
| [gpauth](./apps/gpauth) | Application | [GPL-3.0](./apps/gpauth/LICENSE) |
|
||||
| [gpgui-helper](./apps/gpgui-helper) | Application | [GPL-3.0](./apps/gpgui-helper/LICENSE) |
|
||||
@@ -1,29 +1,37 @@
|
||||
[package]
|
||||
name = "gpauth"
|
||||
rust-version.workspace = true
|
||||
authors.workspace = true
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "1.5", features = [] }
|
||||
tauri-build = { version = "2", features = [], optional = true }
|
||||
|
||||
[dependencies]
|
||||
gpapi = { path = "../../crates/gpapi", features = [
|
||||
"tauri",
|
||||
"clap",
|
||||
"browser-auth",
|
||||
] }
|
||||
common = { path = "../../crates/common" }
|
||||
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
|
||||
|
||||
auth = { path = "../../crates/auth", features = ["browser-auth"] }
|
||||
|
||||
# Shared dependencies
|
||||
anyhow.workspace = true
|
||||
clap.workspace = true
|
||||
env_logger.workspace = true
|
||||
log.workspace = true
|
||||
regex.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
tokio-util.workspace = true
|
||||
tempfile.workspace = true
|
||||
html-escape = "0.2.13"
|
||||
webkit2gtk = "0.18.2"
|
||||
tauri = { workspace = true, features = ["http-all"] }
|
||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||
compile-time.workspace = true
|
||||
|
||||
home = "0.5.12"
|
||||
|
||||
# webview auth dependencies
|
||||
tauri = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
default = ["webview-auth"]
|
||||
webview-auth = ["auth/webview-auth", "dep:tauri", "dep:tauri-build"]
|
||||
release-devtools = ["auth/release-devtools"]
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>LSUIElement</key>
|
||||
<true/>
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>GlobalProtect authentication callback</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>globalprotectcallback</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,3 +1,63 @@
|
||||
use std::{env, fs, path::PathBuf, process::Command};
|
||||
|
||||
const UNKNOWN_COMMIT: &str = "unknown";
|
||||
const DISPLAY_COMMIT_LEN: usize = 9;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-env-changed=GPAUTH_GIT_COMMIT");
|
||||
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
|
||||
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
|
||||
|
||||
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
|
||||
let source_commit = repo_root.join("SOURCE_COMMIT");
|
||||
println!("cargo:rerun-if-changed={}", source_commit.display());
|
||||
println!(
|
||||
"cargo:rustc-env=GPAUTH_GIT_COMMIT={}",
|
||||
resolve_commit(&repo_root, &source_commit)
|
||||
);
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
tauri_build::build()
|
||||
}
|
||||
|
||||
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
|
||||
env_commit("GPAUTH_GIT_COMMIT")
|
||||
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
|
||||
.or_else(|| env_commit("GITHUB_SHA"))
|
||||
.or_else(|| file_commit(source_commit))
|
||||
.or_else(|| git_commit(repo_root))
|
||||
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
|
||||
}
|
||||
|
||||
fn env_commit(key: &str) -> Option<String> {
|
||||
env::var(key).ok().and_then(|value| normalize_commit(&value))
|
||||
}
|
||||
|
||||
fn file_commit(path: &PathBuf) -> Option<String> {
|
||||
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
|
||||
}
|
||||
|
||||
fn git_commit(repo_root: &PathBuf) -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.args(["rev-parse", "--short=9", "HEAD"])
|
||||
.current_dir(repo_root)
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
String::from_utf8(output.stdout)
|
||||
.ok()
|
||||
.and_then(|value| normalize_commit(&value))
|
||||
}
|
||||
|
||||
fn normalize_commit(value: &str) -> Option<String> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
|
||||
}
|
||||
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 8.0 KiB |
|
Before Width: | Height: | Size: 2.5 KiB After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 83 KiB After Width: | Height: | Size: 58 KiB |
@@ -1,523 +0,0 @@
|
||||
use std::{
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use gpapi::{
|
||||
auth::SamlAuthData,
|
||||
error::AuthDataParseError,
|
||||
gp_params::GpParams,
|
||||
portal::{prelogin, Prelogin},
|
||||
utils::{redact::redact_uri, window::WindowExt},
|
||||
};
|
||||
use log::{info, warn};
|
||||
use regex::Regex;
|
||||
use tauri::{AppHandle, Window, WindowEvent, WindowUrl};
|
||||
use tokio::sync::{mpsc, oneshot, RwLock};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use webkit2gtk::{
|
||||
gio::Cancellable,
|
||||
glib::{GString, TimeSpan},
|
||||
LoadEvent, SettingsExt, TLSErrorsPolicy, URIResponse, URIResponseExt, WebContextExt, WebResource, WebResourceExt,
|
||||
WebView, WebViewExt, WebsiteDataManagerExtManual, WebsiteDataTypes,
|
||||
};
|
||||
|
||||
enum AuthDataError {
|
||||
/// Failed to load page due to TLS error
|
||||
TlsError,
|
||||
/// 1. Found auth data in headers/body but it's invalid
|
||||
/// 2. Loaded an empty page, failed to load page. etc.
|
||||
Invalid,
|
||||
/// No auth data found in headers/body
|
||||
NotFound,
|
||||
}
|
||||
|
||||
type AuthResult = Result<SamlAuthData, AuthDataError>;
|
||||
|
||||
pub(crate) struct AuthWindow<'a> {
|
||||
app_handle: AppHandle,
|
||||
server: &'a str,
|
||||
saml_request: &'a str,
|
||||
user_agent: &'a str,
|
||||
gp_params: Option<GpParams>,
|
||||
clean: bool,
|
||||
}
|
||||
|
||||
impl<'a> AuthWindow<'a> {
|
||||
pub fn new(app_handle: AppHandle) -> Self {
|
||||
Self {
|
||||
app_handle,
|
||||
server: "",
|
||||
saml_request: "",
|
||||
user_agent: "",
|
||||
gp_params: None,
|
||||
clean: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn server(mut self, server: &'a str) -> Self {
|
||||
self.server = server;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn saml_request(mut self, saml_request: &'a str) -> Self {
|
||||
self.saml_request = saml_request;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn user_agent(mut self, user_agent: &'a str) -> Self {
|
||||
self.user_agent = user_agent;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn gp_params(mut self, gp_params: GpParams) -> Self {
|
||||
self.gp_params.replace(gp_params);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn clean(mut self, clean: bool) -> Self {
|
||||
self.clean = clean;
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn open(&self) -> anyhow::Result<SamlAuthData> {
|
||||
info!("Open auth window, user_agent: {}", self.user_agent);
|
||||
|
||||
let window = Window::builder(&self.app_handle, "auth_window", WindowUrl::default())
|
||||
.title("GlobalProtect Login")
|
||||
// .user_agent(self.user_agent)
|
||||
.focused(true)
|
||||
.visible(false)
|
||||
.center()
|
||||
.build()?;
|
||||
|
||||
let window = Arc::new(window);
|
||||
|
||||
let cancel_token = CancellationToken::new();
|
||||
let cancel_token_clone = cancel_token.clone();
|
||||
|
||||
window.on_window_event(move |event| {
|
||||
if let WindowEvent::CloseRequested { .. } = event {
|
||||
cancel_token_clone.cancel();
|
||||
}
|
||||
});
|
||||
|
||||
let window_clone = Arc::clone(&window);
|
||||
let timeout_secs = 15;
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_secs(timeout_secs)).await;
|
||||
let visible = window_clone.is_visible().unwrap_or(false);
|
||||
if !visible {
|
||||
info!("Try to raise auth window after {} seconds", timeout_secs);
|
||||
raise_window(&window_clone);
|
||||
}
|
||||
});
|
||||
|
||||
tokio::select! {
|
||||
_ = cancel_token.cancelled() => {
|
||||
bail!("Auth cancelled");
|
||||
}
|
||||
saml_result = self.auth_loop(&window) => {
|
||||
window.close()?;
|
||||
saml_result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn auth_loop(&self, window: &Arc<Window>) -> anyhow::Result<SamlAuthData> {
|
||||
let saml_request = self.saml_request.to_string();
|
||||
let (auth_result_tx, mut auth_result_rx) = mpsc::unbounded_channel::<AuthResult>();
|
||||
let raise_window_cancel_token: Arc<RwLock<Option<CancellationToken>>> = Default::default();
|
||||
let gp_params = self.gp_params.as_ref().unwrap();
|
||||
let tls_err_policy = if gp_params.ignore_tls_errors() {
|
||||
TLSErrorsPolicy::Ignore
|
||||
} else {
|
||||
TLSErrorsPolicy::Fail
|
||||
};
|
||||
|
||||
if self.clean {
|
||||
clear_webview_cookies(window).await?;
|
||||
}
|
||||
|
||||
let raise_window_cancel_token_clone = Arc::clone(&raise_window_cancel_token);
|
||||
window.with_webview(move |wv| {
|
||||
let wv = wv.inner();
|
||||
|
||||
if let Some(context) = wv.context() {
|
||||
context.set_tls_errors_policy(tls_err_policy);
|
||||
}
|
||||
|
||||
if let Some(settings) = wv.settings() {
|
||||
let ua = settings.user_agent().unwrap_or("".into());
|
||||
info!("Auth window user agent: {}", ua);
|
||||
}
|
||||
|
||||
// Load the initial SAML request
|
||||
load_saml_request(&wv, &saml_request);
|
||||
|
||||
let auth_result_tx_clone = auth_result_tx.clone();
|
||||
wv.connect_load_changed(move |wv, event| {
|
||||
if event == LoadEvent::Started {
|
||||
let Ok(mut cancel_token) = raise_window_cancel_token_clone.try_write() else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Cancel the raise window task
|
||||
if let Some(cancel_token) = cancel_token.take() {
|
||||
cancel_token.cancel();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if event != LoadEvent::Finished {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(main_resource) = wv.main_resource() {
|
||||
let uri = main_resource.uri().unwrap_or("".into());
|
||||
|
||||
if uri.is_empty() {
|
||||
warn!("Loaded an empty uri");
|
||||
send_auth_result(&auth_result_tx_clone, Err(AuthDataError::Invalid));
|
||||
return;
|
||||
}
|
||||
|
||||
info!("Loaded uri: {}", redact_uri(&uri));
|
||||
if uri.starts_with("globalprotectcallback:") {
|
||||
return;
|
||||
}
|
||||
|
||||
read_auth_data(&main_resource, auth_result_tx_clone.clone());
|
||||
}
|
||||
});
|
||||
|
||||
let auth_result_tx_clone = auth_result_tx.clone();
|
||||
wv.connect_load_failed_with_tls_errors(move |_wv, uri, cert, err| {
|
||||
let redacted_uri = redact_uri(uri);
|
||||
warn!(
|
||||
"Failed to load uri: {} with error: {}, cert: {}",
|
||||
redacted_uri, err, cert
|
||||
);
|
||||
|
||||
send_auth_result(&auth_result_tx_clone, Err(AuthDataError::TlsError));
|
||||
true
|
||||
});
|
||||
|
||||
wv.connect_load_failed(move |_wv, _event, uri, err| {
|
||||
let redacted_uri = redact_uri(uri);
|
||||
if !uri.starts_with("globalprotectcallback:") {
|
||||
warn!("Failed to load uri: {} with error: {}", redacted_uri, err);
|
||||
}
|
||||
// NOTE: Don't send error here, since load_changed event will be triggered after this
|
||||
// send_auth_result(&auth_result_tx, Err(AuthDataError::Invalid));
|
||||
// true to stop other handlers from being invoked for the event. false to propagate the event further.
|
||||
true
|
||||
});
|
||||
})?;
|
||||
|
||||
let portal = self.server.to_string();
|
||||
|
||||
loop {
|
||||
if let Some(auth_result) = auth_result_rx.recv().await {
|
||||
match auth_result {
|
||||
Ok(auth_data) => return Ok(auth_data),
|
||||
Err(AuthDataError::TlsError) => bail!("TLS error: certificate verify failed"),
|
||||
Err(AuthDataError::NotFound) => {
|
||||
info!("No auth data found, it may not be the /SAML20/SP/ACS endpoint");
|
||||
|
||||
// The user may need to interact with the auth window, raise it in 3 seconds
|
||||
if !window.is_visible().unwrap_or(false) {
|
||||
let window = Arc::clone(window);
|
||||
let cancel_token = CancellationToken::new();
|
||||
|
||||
raise_window_cancel_token.write().await.replace(cancel_token.clone());
|
||||
|
||||
tokio::spawn(async move {
|
||||
let delay_secs = 1;
|
||||
|
||||
info!("Raise window in {} second(s)", delay_secs);
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(Duration::from_secs(delay_secs)) => {
|
||||
raise_window(&window);
|
||||
}
|
||||
_ = cancel_token.cancelled() => {
|
||||
info!("Raise window cancelled");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(AuthDataError::Invalid) => {
|
||||
info!("Got invalid auth data, retrying...");
|
||||
|
||||
window.with_webview(|wv| {
|
||||
let wv = wv.inner();
|
||||
wv.run_javascript(r#"
|
||||
var loading = document.createElement("div");
|
||||
loading.innerHTML = '<div style="position: absolute; width: 100%; text-align: center; font-size: 20px; font-weight: bold; top: 50%; left: 50%; transform: translate(-50%, -50%);">Got invalid token, retrying...</div>';
|
||||
loading.style = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 99999;";
|
||||
document.body.appendChild(loading);
|
||||
"#,
|
||||
Cancellable::NONE,
|
||||
|_| info!("Injected loading element successfully"),
|
||||
);
|
||||
})?;
|
||||
|
||||
let saml_request = portal_prelogin(&portal, gp_params).await?;
|
||||
window.with_webview(move |wv| {
|
||||
let wv = wv.inner();
|
||||
load_saml_request(&wv, &saml_request);
|
||||
})?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn raise_window(window: &Arc<Window>) {
|
||||
let visible = window.is_visible().unwrap_or(false);
|
||||
if !visible {
|
||||
if let Err(err) = window.raise() {
|
||||
warn!("Failed to raise window: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn portal_prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<String> {
|
||||
match prelogin(portal, gp_params).await? {
|
||||
Prelogin::Saml(prelogin) => Ok(prelogin.saml_request().to_string()),
|
||||
Prelogin::Standard(_) => bail!("Received non-SAML prelogin response"),
|
||||
}
|
||||
}
|
||||
|
||||
fn send_auth_result(auth_result_tx: &mpsc::UnboundedSender<AuthResult>, auth_result: AuthResult) {
|
||||
if let Err(err) = auth_result_tx.send(auth_result) {
|
||||
warn!("Failed to send auth event: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
fn load_saml_request(wv: &Rc<WebView>, saml_request: &str) {
|
||||
if saml_request.starts_with("http") {
|
||||
info!("Load the SAML request as URI...");
|
||||
wv.load_uri(saml_request);
|
||||
} else {
|
||||
info!("Load the SAML request as HTML...");
|
||||
wv.load_html(saml_request, None);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_auth_data_from_headers(response: &URIResponse) -> AuthResult {
|
||||
response.http_headers().map_or_else(
|
||||
|| {
|
||||
info!("No headers found in response");
|
||||
Err(AuthDataError::NotFound)
|
||||
},
|
||||
|mut headers| match headers.get("saml-auth-status") {
|
||||
Some(status) if status == "1" => {
|
||||
let username = headers.get("saml-username").map(GString::into);
|
||||
let prelogin_cookie = headers.get("prelogin-cookie").map(GString::into);
|
||||
let portal_userauthcookie = headers.get("portal-userauthcookie").map(GString::into);
|
||||
|
||||
if SamlAuthData::check(&username, &prelogin_cookie, &portal_userauthcookie) {
|
||||
return Ok(SamlAuthData::new(
|
||||
username.unwrap(),
|
||||
prelogin_cookie,
|
||||
portal_userauthcookie,
|
||||
));
|
||||
}
|
||||
|
||||
info!("Found invalid auth data in headers");
|
||||
Err(AuthDataError::Invalid)
|
||||
}
|
||||
Some(status) => {
|
||||
info!("Found invalid SAML status: {} in headers", status);
|
||||
Err(AuthDataError::Invalid)
|
||||
}
|
||||
None => {
|
||||
info!("No saml-auth-status header found");
|
||||
Err(AuthDataError::NotFound)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn read_auth_data_from_body<F>(main_resource: &WebResource, callback: F)
|
||||
where
|
||||
F: FnOnce(Result<SamlAuthData, AuthDataParseError>) + Send + 'static,
|
||||
{
|
||||
main_resource.data(Cancellable::NONE, |data| match data {
|
||||
Ok(data) => {
|
||||
let html = String::from_utf8_lossy(&data);
|
||||
callback(read_auth_data_from_html(&html));
|
||||
}
|
||||
Err(err) => {
|
||||
info!("Failed to read response body: {}", err);
|
||||
callback(Err(AuthDataParseError::Invalid))
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn read_auth_data_from_html(html: &str) -> Result<SamlAuthData, AuthDataParseError> {
|
||||
if html.contains("Temporarily Unavailable") {
|
||||
info!("Found 'Temporarily Unavailable' in HTML, auth failed");
|
||||
return Err(AuthDataParseError::Invalid);
|
||||
}
|
||||
|
||||
SamlAuthData::from_html(html).or_else(|err| {
|
||||
if let Some(gpcallback) = extract_gpcallback(html) {
|
||||
info!("Found gpcallback from html...");
|
||||
SamlAuthData::from_gpcallback(&gpcallback)
|
||||
} else {
|
||||
Err(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn extract_gpcallback(html: &str) -> Option<String> {
|
||||
let re = Regex::new(r#"globalprotectcallback:[^"]+"#).unwrap();
|
||||
re.captures(html)
|
||||
.and_then(|captures| captures.get(0))
|
||||
.map(|m| html_escape::decode_html_entities(m.as_str()).to_string())
|
||||
}
|
||||
|
||||
fn read_auth_data(main_resource: &WebResource, auth_result_tx: mpsc::UnboundedSender<AuthResult>) {
|
||||
let Some(response) = main_resource.response() else {
|
||||
info!("No response found in main resource");
|
||||
send_auth_result(&auth_result_tx, Err(AuthDataError::Invalid));
|
||||
return;
|
||||
};
|
||||
|
||||
info!("Trying to read auth data from response headers...");
|
||||
|
||||
match read_auth_data_from_headers(&response) {
|
||||
Ok(auth_data) => {
|
||||
info!("Got auth data from headers");
|
||||
send_auth_result(&auth_result_tx, Ok(auth_data));
|
||||
}
|
||||
Err(AuthDataError::Invalid) => {
|
||||
info!("Found invalid auth data in headers, trying to read from body...");
|
||||
read_auth_data_from_body(main_resource, move |auth_result| {
|
||||
// Since we have already found invalid auth data in headers, which means this could be the `/SAML20/SP/ACS` endpoint
|
||||
// any error result from body should be considered as invalid, and trigger a retry
|
||||
let auth_result = auth_result.map_err(|err| {
|
||||
info!("Failed to read auth data from body: {}", err);
|
||||
AuthDataError::Invalid
|
||||
});
|
||||
send_auth_result(&auth_result_tx, auth_result);
|
||||
});
|
||||
}
|
||||
Err(AuthDataError::NotFound) => {
|
||||
info!("No auth data found in headers, trying to read from body...");
|
||||
|
||||
let is_acs_endpoint = main_resource.uri().map_or(false, |uri| uri.contains("/SAML20/SP/ACS"));
|
||||
|
||||
read_auth_data_from_body(main_resource, move |auth_result| {
|
||||
// If the endpoint is `/SAML20/SP/ACS` and no auth data found in body, it should be considered as invalid
|
||||
let auth_result = auth_result.map_err(|err| {
|
||||
info!("Failed to read auth data from body: {}", err);
|
||||
|
||||
if !is_acs_endpoint && matches!(err, AuthDataParseError::NotFound) {
|
||||
AuthDataError::NotFound
|
||||
} else {
|
||||
AuthDataError::Invalid
|
||||
}
|
||||
});
|
||||
|
||||
send_auth_result(&auth_result_tx, auth_result)
|
||||
});
|
||||
}
|
||||
Err(AuthDataError::TlsError) => {
|
||||
// NOTE: This is unreachable
|
||||
info!("TLS error found in headers, trying to read from body...");
|
||||
send_auth_result(&auth_result_tx, Err(AuthDataError::TlsError));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn clear_webview_cookies(window: &Window) -> anyhow::Result<()> {
|
||||
let (tx, rx) = oneshot::channel::<Result<(), String>>();
|
||||
|
||||
window.with_webview(|wv| {
|
||||
let send_result = move |result: Result<(), String>| {
|
||||
if let Err(err) = tx.send(result) {
|
||||
info!("Failed to send result: {:?}", err);
|
||||
}
|
||||
};
|
||||
|
||||
let wv = wv.inner();
|
||||
let context = match wv.context() {
|
||||
Some(context) => context,
|
||||
None => {
|
||||
send_result(Err("No webview context found".into()));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let data_manager = match context.website_data_manager() {
|
||||
Some(manager) => manager,
|
||||
None => {
|
||||
send_result(Err("No data manager found".into()));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let now = Instant::now();
|
||||
data_manager.clear(
|
||||
WebsiteDataTypes::COOKIES,
|
||||
TimeSpan(0),
|
||||
Cancellable::NONE,
|
||||
move |result| match result {
|
||||
Err(err) => {
|
||||
send_result(Err(err.to_string()));
|
||||
}
|
||||
Ok(_) => {
|
||||
info!("Cookies cleared in {} ms", now.elapsed().as_millis());
|
||||
send_result(Ok(()));
|
||||
}
|
||||
},
|
||||
);
|
||||
})?;
|
||||
|
||||
rx.await?.map_err(|err| anyhow::anyhow!(err))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn extract_gpcallback_some() {
|
||||
let html = r#"
|
||||
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
|
||||
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
|
||||
"#;
|
||||
|
||||
assert_eq!(
|
||||
extract_gpcallback(html).as_deref(),
|
||||
Some("globalprotectcallback:PGh0bWw+PCEtLSA8c")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_gpcallback_cas() {
|
||||
let html = r#"
|
||||
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:cas-as=1&[email protected]&token=very_long_string">
|
||||
"#;
|
||||
|
||||
assert_eq!(
|
||||
extract_gpcallback(html).as_deref(),
|
||||
Some("globalprotectcallback:cas-as=1&[email protected]&token=very_long_string")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_gpcallback_none() {
|
||||
let html = r#"
|
||||
<meta http-equiv="refresh" content="0; URL=PGh0bWw+PCEtLSA8c">
|
||||
"#;
|
||||
|
||||
assert_eq!(extract_gpcallback(html), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
use std::{
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use tauri::RunEvent;
|
||||
|
||||
pub fn run() -> anyhow::Result<()> {
|
||||
let handled = Arc::new(AtomicBool::new(false));
|
||||
let timeout_handled = Arc::clone(&handled);
|
||||
let app = tauri::Builder::default()
|
||||
.setup(move |app| {
|
||||
#[cfg(target_os = "macos")]
|
||||
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
|
||||
|
||||
let app_handle = app.handle().clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||
if !timeout_handled.swap(true, Ordering::AcqRel) {
|
||||
app_handle.exit(1);
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
})
|
||||
.build(crate::tauri_context::get())?;
|
||||
|
||||
app.run(move |app_handle, event| {
|
||||
let RunEvent::Opened { urls } = event else {
|
||||
return;
|
||||
};
|
||||
let Some(callback) = urls
|
||||
.into_iter()
|
||||
.find(|url| url.scheme().eq_ignore_ascii_case("globalprotectcallback"))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if handled.swap(true, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
|
||||
let app_handle = app_handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let exit_code = match auth::forward_auth_callback(callback.as_str()).await {
|
||||
Ok(()) => 0,
|
||||
Err(err) => {
|
||||
eprintln!("Failed to forward authentication callback: {err}");
|
||||
1
|
||||
}
|
||||
};
|
||||
app_handle.exit(exit_code);
|
||||
});
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,29 +1,40 @@
|
||||
use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use auth::forward_auth_callback;
|
||||
use auth::{BrowserAuthenticator, auth_prelogin};
|
||||
use clap::Parser;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use clap::Subcommand;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use gpapi::auth::AuthWindowTheme;
|
||||
use gpapi::{
|
||||
auth::{SamlAuthData, SamlAuthResult},
|
||||
clap::args::Os,
|
||||
gp_params::{ClientOs, GpParams},
|
||||
process::browser_authenticator::BrowserAuthenticator,
|
||||
utils::{normalize_server, openssl},
|
||||
GP_USER_AGENT,
|
||||
auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult},
|
||||
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
|
||||
error::ServerTlsError,
|
||||
gp_params::GpParams,
|
||||
log_format::LogFormat,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
utils::normalize_server,
|
||||
};
|
||||
use log::{info, LevelFilter};
|
||||
use log::info;
|
||||
use serde_json::json;
|
||||
use tauri::{App, AppHandle, RunEvent};
|
||||
use tempfile::NamedTempFile;
|
||||
use tokio::{io::AsyncReadExt, net::TcpListener};
|
||||
use std::net::IpAddr;
|
||||
|
||||
use crate::auth_window::{portal_prelogin, AuthWindow};
|
||||
const VERSION: &str = concat!(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
" (",
|
||||
env!("GPAUTH_GIT_COMMIT"),
|
||||
" ",
|
||||
compile_time::date_str!(),
|
||||
")"
|
||||
);
|
||||
|
||||
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
|
||||
|
||||
#[derive(Parser, Clone)]
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
version = VERSION,
|
||||
author,
|
||||
about = "The authentication component for the GlobalProtect VPN client, supports the SSO authentication method.",
|
||||
args_conflicts_with_subcommands = true,
|
||||
subcommand_negates_reqs = true,
|
||||
help_template = "\
|
||||
{before-help}{name} {version}
|
||||
{author}
|
||||
@@ -38,8 +49,12 @@ See 'gpauth -h' for more information.
|
||||
"
|
||||
)]
|
||||
struct Cli {
|
||||
#[arg(help = "The portal server to authenticate")]
|
||||
server: String,
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[command(subcommand)]
|
||||
command: Option<CliCommand>,
|
||||
|
||||
#[arg(required = true, help = "The portal server to authenticate")]
|
||||
server: Option<String>,
|
||||
|
||||
#[arg(long, help = "Treating the server as a gateway")]
|
||||
gateway: bool,
|
||||
@@ -47,212 +62,434 @@ struct Cli {
|
||||
#[arg(long, help = "The SAML authentication request")]
|
||||
saml_request: Option<String>,
|
||||
|
||||
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
|
||||
user_agent: String,
|
||||
|
||||
#[arg(long, default_value = "Linux")]
|
||||
#[arg(long, value_enum, default_value_t = Os::default())]
|
||||
os: Os,
|
||||
|
||||
#[arg(long)]
|
||||
os_version: Option<String>,
|
||||
#[arg(long, help = "Use this runtime host ID when building the OS profile")]
|
||||
host_id: Option<String>,
|
||||
|
||||
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
|
||||
hidpi: bool,
|
||||
#[arg(long, help = "Override the GlobalProtect client version reported to the server")]
|
||||
client_version: Option<String>,
|
||||
|
||||
#[arg(long, help = "Get around the OpenSSL `unsafe legacy renegotiation` error")]
|
||||
#[arg(
|
||||
short,
|
||||
long,
|
||||
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
|
||||
)]
|
||||
certificate: Option<String>,
|
||||
|
||||
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
|
||||
sslkey: Option<String>,
|
||||
|
||||
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
|
||||
key_password: Option<String>,
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[arg(long, hide = true)]
|
||||
fix_openssl: bool,
|
||||
|
||||
#[arg(long, help = "Ignore TLS errors")]
|
||||
ignore_tls_errors: bool,
|
||||
|
||||
#[arg(long, help = "Clean the cache of the embedded browser")]
|
||||
clean: bool,
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
default_value_t = LogFormat::Text,
|
||||
help = "Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text."
|
||||
)]
|
||||
log_format: LogFormat,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, help = "Use the default browser for authentication")]
|
||||
default_browser: bool,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable"
|
||||
help = "Use a browser; omit the value to auto-select. Use `manual` to open the URL and paste the callback.",
|
||||
default_missing_value = "auto",
|
||||
num_args=0..=1
|
||||
)]
|
||||
browser: Option<String>,
|
||||
|
||||
#[arg(long, help = "Listen on this IP address when using '--browser manual'")]
|
||||
browser_listen: Option<IpAddr>,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
|
||||
hidpi: bool,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, help = "Clean the cache of the embedded browser")]
|
||||
pub clean: bool,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, help = "Set the embedded authentication window title")]
|
||||
window_title: Option<String>,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, value_enum, default_value_t = AuthWindowTheme::default(), help = "Set the embedded authentication window appearance")]
|
||||
window_theme: AuthWindowTheme,
|
||||
|
||||
#[command(flatten)]
|
||||
verbose: InfoLevelVerbosity,
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[derive(Subcommand)]
|
||||
enum CliCommand {
|
||||
#[command(hide = true)]
|
||||
AuthCallback {
|
||||
#[arg(help = "The globalprotectcallback URL to forward")]
|
||||
callback: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl Args for Cli {
|
||||
fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
|
||||
fn log_format(&self) -> LogFormat {
|
||||
self.log_format
|
||||
}
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
async fn run(&mut self) -> anyhow::Result<()> {
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if self.fix_openssl {
|
||||
log::warn!("--fix-openssl is deprecated and has no effect. It will be removed in a future release.");
|
||||
}
|
||||
|
||||
if self.browser_listen.is_some()
|
||||
&& !matches!(self.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("manual") || browser.eq_ignore_ascii_case("remote"))
|
||||
{
|
||||
anyhow::bail!("The '--browser-listen' option requires '--browser manual'");
|
||||
}
|
||||
|
||||
if self.ignore_tls_errors {
|
||||
info!("TLS errors will be ignored");
|
||||
}
|
||||
|
||||
let mut openssl_conf = self.prepare_env()?;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
gpapi::utils::env_utils::patch_gui_runtime_env(self.hidpi);
|
||||
|
||||
self.server = normalize_server(&self.server)?;
|
||||
let server = normalize_server(self.server.as_deref().expect("server is required for authentication"))?;
|
||||
let gp_params = self.build_gp_params();
|
||||
info!(
|
||||
"gpauth auth host-id: {}",
|
||||
gp_params.os_profile().host_identity().host_id()
|
||||
);
|
||||
|
||||
// Get the initial SAML request
|
||||
let saml_request = match self.saml_request {
|
||||
Some(ref saml_request) => saml_request.clone(),
|
||||
None => portal_prelogin(&self.server, &gp_params).await?,
|
||||
let auth_request = match self.saml_request.as_deref() {
|
||||
Some(auth_request) => auth_request.to_string(),
|
||||
None => match auth_prelogin(&server, &gp_params, self.external_browser_requested(), self.gateway).await {
|
||||
Ok(request) => request,
|
||||
Err(error) => {
|
||||
let Some(tls) = error.downcast_ref::<ServerTlsError>().cloned() else {
|
||||
return Err(error);
|
||||
};
|
||||
handle_error(error, self);
|
||||
print_auth_result(Err(tls.into()), None);
|
||||
return Ok(());
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let browser_auth = if let Some(browser) = &self.browser {
|
||||
Some(BrowserAuthenticator::new_with_browser(&saml_request, browser))
|
||||
} else if self.default_browser {
|
||||
Some(BrowserAuthenticator::new(&saml_request))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
#[cfg(feature = "webview-auth")]
|
||||
let browser = self
|
||||
.browser
|
||||
.as_deref()
|
||||
.or_else(|| self.default_browser.then(|| "default"));
|
||||
|
||||
if let Some(browser_auth) = browser_auth {
|
||||
browser_auth.authenticate()?;
|
||||
#[cfg(not(feature = "webview-auth"))]
|
||||
let browser = self.browser.as_deref().or(Some("default"));
|
||||
|
||||
info!("Please continue the authentication process in the default browser");
|
||||
if let Some(browser) = browser {
|
||||
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
|
||||
let authenticator = BrowserAuthenticator::new(&auth_request, browser, self.browser_listen);
|
||||
let auth_result = authenticator.authenticate().await;
|
||||
|
||||
let auth_result = match wait_auth_data().await {
|
||||
Ok(auth_data) => SamlAuthResult::Success(auth_data),
|
||||
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
|
||||
};
|
||||
|
||||
info!("Authentication completed");
|
||||
|
||||
println!("{}", json!(auth_result));
|
||||
print_auth_result(auth_result, Some(&auth_host_id));
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.saml_request.replace(saml_request);
|
||||
|
||||
let app = create_app(self.clone())?;
|
||||
|
||||
app.run(move |_app_handle, event| {
|
||||
if let RunEvent::Exit = event {
|
||||
if let Some(file) = openssl_conf.take() {
|
||||
if let Err(err) = file.close() {
|
||||
info!("Error closing OpenSSL config file: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
#[cfg(feature = "webview-auth")]
|
||||
crate::webview_auth::authenticate(
|
||||
server,
|
||||
gp_params,
|
||||
auth_request,
|
||||
self.clean,
|
||||
self.window_title.clone(),
|
||||
self.window_theme,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prepare_env(&self) -> anyhow::Result<Option<NamedTempFile>> {
|
||||
std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1");
|
||||
|
||||
if self.hidpi {
|
||||
info!("Setting GDK_SCALE=2 and GDK_DPI_SCALE=0.5");
|
||||
|
||||
std::env::set_var("GDK_SCALE", "2");
|
||||
std::env::set_var("GDK_DPI_SCALE", "0.5");
|
||||
}
|
||||
|
||||
if self.fix_openssl {
|
||||
info!("Fixing OpenSSL environment");
|
||||
let file = openssl::fix_openssl_env()?;
|
||||
|
||||
return Ok(Some(file));
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn build_gp_params(&self) -> GpParams {
|
||||
let gp_params = GpParams::builder()
|
||||
.user_agent(&self.user_agent)
|
||||
.client_os(ClientOs::from(&self.os))
|
||||
.os_version(self.os_version.clone())
|
||||
GpParams::builder(self.build_os_profile())
|
||||
.ignore_tls_errors(self.ignore_tls_errors)
|
||||
.certificate(self.certificate.clone())
|
||||
.sslkey(self.sslkey.clone())
|
||||
.key_password(self.key_password.clone())
|
||||
.is_gateway(self.gateway)
|
||||
.build();
|
||||
|
||||
gp_params
|
||||
.build()
|
||||
}
|
||||
|
||||
async fn saml_auth(&self, app_handle: AppHandle) -> anyhow::Result<SamlAuthData> {
|
||||
let auth_window = AuthWindow::new(app_handle)
|
||||
.server(&self.server)
|
||||
.user_agent(&self.user_agent)
|
||||
.gp_params(self.build_gp_params())
|
||||
.saml_request(self.saml_request.as_ref().unwrap())
|
||||
.clean(self.clean);
|
||||
fn build_os_profile(&self) -> OsProfile {
|
||||
let mut builder = OsProfile::builder(ClientOs::from(self.os));
|
||||
if let Some(client_version) = self.client_version.as_deref() {
|
||||
builder = builder.client_version(client_version);
|
||||
}
|
||||
gpapi::os_profile::desktop::collect_profile(builder, self.host_id.as_deref())
|
||||
}
|
||||
|
||||
auth_window.open().await
|
||||
fn external_browser_requested(&self) -> bool {
|
||||
#[cfg(feature = "webview-auth")]
|
||||
{
|
||||
self.default_browser || self.browser.is_some()
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "webview-auth"))]
|
||||
{
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_app(cli: Cli) -> anyhow::Result<App> {
|
||||
let app = tauri::Builder::default()
|
||||
.setup(|app| {
|
||||
let app_handle = app.handle();
|
||||
fn init_logger(cli: &Cli) {
|
||||
let Some(level) = cli.verbose.log_level_filter().to_level() else {
|
||||
log::set_max_level(log::LevelFilter::Off);
|
||||
return;
|
||||
};
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let auth_result = match cli.saml_auth(app_handle.clone()).await {
|
||||
Ok(auth_data) => SamlAuthResult::Success(auth_data),
|
||||
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
|
||||
};
|
||||
|
||||
println!("{}", json!(auth_result));
|
||||
});
|
||||
Ok(())
|
||||
})
|
||||
.build(tauri::generate_context!())?;
|
||||
|
||||
Ok(app)
|
||||
}
|
||||
|
||||
fn init_logger() {
|
||||
env_logger::builder().filter_level(LevelFilter::Info).init();
|
||||
gpapi::logger::init(level, "com.yuezk.gpgui", "gpauth", cli.log_format);
|
||||
}
|
||||
|
||||
pub async fn run() {
|
||||
let mut cli = Cli::parse();
|
||||
let cli = Cli::parse();
|
||||
|
||||
init_logger();
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
if let Some(CliCommand::AuthCallback { callback }) = &cli.command {
|
||||
if let Err(err) = forward_auth_callback(callback).await {
|
||||
eprintln!("Failed to forward authentication callback: {err}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
init_logger(&cli);
|
||||
info!("gpauth started: {}", VERSION);
|
||||
|
||||
if let Err(err) = cli.run().await {
|
||||
eprintln!("\nError: {}", err);
|
||||
|
||||
if err.to_string().contains("unsafe legacy renegotiation") && !cli.fix_openssl {
|
||||
eprintln!("\nRe-run it with the `--fix-openssl` option to work around this issue, e.g.:\n");
|
||||
// Print the command
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
eprintln!("{} --fix-openssl {}\n", args[0], args[1..].join(" "));
|
||||
}
|
||||
|
||||
handle_error(err, &cli);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_auth_data() -> anyhow::Result<SamlAuthData> {
|
||||
// Start a local server to receive the browser authentication data
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let port_file = temp_dir().join("gpcallback.port");
|
||||
|
||||
// Write the port to a file
|
||||
fs::write(&port_file, port.to_string())?;
|
||||
fs::set_permissions(&port_file, fs::Permissions::from_mode(0o600))?;
|
||||
|
||||
// Remove the previous log file
|
||||
let callback_log = temp_dir().join("gpcallback.log");
|
||||
let _ = fs::remove_file(&callback_log);
|
||||
|
||||
info!("Listening authentication data on port {}", port);
|
||||
info!(
|
||||
"If it hangs, please check the logs at `{}` for more information",
|
||||
callback_log.display()
|
||||
);
|
||||
let (mut socket, _) = listener.accept().await?;
|
||||
|
||||
info!("Received the browser authentication data from the socket");
|
||||
let mut data = String::new();
|
||||
socket.read_to_string(&mut data).await?;
|
||||
|
||||
// Remove the port file
|
||||
fs::remove_file(&port_file)?;
|
||||
|
||||
let auth_data = SamlAuthData::from_gpcallback(&data)?;
|
||||
Ok(auth_data)
|
||||
pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>) {
|
||||
println!("{}", json!(auth_outcome(auth_result, host_id)));
|
||||
}
|
||||
|
||||
fn auth_outcome(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>) -> SamlAuthResult {
|
||||
match auth_result {
|
||||
Ok(auth_data) => {
|
||||
let auth_data = match host_id {
|
||||
Some(host_id) => auth_data.with_host_id(host_id),
|
||||
None => auth_data,
|
||||
};
|
||||
SamlAuthResult::Success(auth_data)
|
||||
}
|
||||
Err(err) if err.downcast_ref::<AuthenticationCancelled>().is_some() => SamlAuthResult::Cancelled,
|
||||
Err(err) => match err.downcast::<ServerTlsError>() {
|
||||
Ok(tls) => SamlAuthResult::ServerTlsError(tls),
|
||||
Err(err) => SamlAuthResult::Failure(err.to_string()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn deprecated_openssl_option_remains_supported_but_hidden() {
|
||||
let result = Cli::try_parse_from(["gpauth", "portal.example.com", "--fix-openssl"]);
|
||||
assert_eq!(result.is_ok(), !cfg!(target_os = "macos"));
|
||||
for flag in ["-h", "--help"] {
|
||||
let help = Cli::try_parse_from(["gpauth", flag]).err().unwrap().to_string();
|
||||
assert!(!help.contains("--fix-openssl"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn result_keeps_server_tls_kind_and_generic_failure_format() {
|
||||
use gpapi::error::ServerTlsErrorKind;
|
||||
let tls = ServerTlsError {
|
||||
server: "https://vpn.example.com".into(),
|
||||
kind: ServerTlsErrorKind::Certificate,
|
||||
};
|
||||
let outcome = auth_outcome(Err(anyhow::Error::new(tls).context("retry failed")), None);
|
||||
assert_eq!(
|
||||
serde_json::to_value(outcome).unwrap(),
|
||||
json!({"serverTlsError": {"server": "https://vpn.example.com", "kind": "certificate"}})
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(auth_outcome(Err(anyhow::anyhow!("rejected")), None)).unwrap(),
|
||||
json!({"failure": "rejected"})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_result_preserves_client_certificate_requirement() {
|
||||
let error = ServerTlsError {
|
||||
server: "https://vpn.example.com".into(),
|
||||
kind: gpapi::error::ServerTlsErrorKind::ClientCertificateRequired,
|
||||
};
|
||||
let outcome = auth_outcome(Err(anyhow::Error::new(error).context("retry failed")), None);
|
||||
assert_eq!(
|
||||
serde_json::to_value(outcome).unwrap(),
|
||||
json!({"serverTlsError": {"server": "https://vpn.example.com", "kind": "clientCertificateRequired"}})
|
||||
);
|
||||
}
|
||||
|
||||
/// gpauth's own result already goes to stdout as JSON; this makes its *logs*
|
||||
/// readable the same way, so a caller driving it does not have to parse prose
|
||||
/// on stderr to find out why an attempt failed.
|
||||
#[test]
|
||||
fn log_format_defaults_to_text() {
|
||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com"]).expect("gpauth args should parse");
|
||||
|
||||
assert_eq!(cli.log_format, LogFormat::Text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_format_accepts_json() {
|
||||
let cli =
|
||||
Cli::try_parse_from(["gpauth", "portal.example.com", "--log-format", "json"]).expect("gpauth args should parse");
|
||||
|
||||
assert_eq!(cli.log_format, LogFormat::Json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_defaults_to_runtime_os() {
|
||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com"]).expect("gpauth args should parse");
|
||||
|
||||
assert_eq!(cli.os, Os::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn callback_arguments_parse_separately() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpauth",
|
||||
"auth-callback",
|
||||
"globalprotectcallback:cas-as=1&[email protected]&token=token",
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
cli.command,
|
||||
Some(CliCommand::AuthCallback { callback }) if callback.starts_with("globalprotectcallback:")
|
||||
));
|
||||
assert!(cli.server.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_id_arg_sets_profile_host_id_seed() {
|
||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--host-id", "host-seed"])
|
||||
.expect("gpauth args should parse");
|
||||
let profile = cli.build_os_profile();
|
||||
|
||||
assert_eq!(profile.host_identity().host_id(), "host-seed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_arg_requests_external_browser() {
|
||||
let cli =
|
||||
Cli::try_parse_from(["gpauth", "portal.example.com", "--browser", "firefox"]).expect("gpauth args should parse");
|
||||
|
||||
assert!(cli.external_browser_requested());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_without_value_uses_auto_mode() {
|
||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--browser"]).expect("gpauth args should parse");
|
||||
|
||||
assert_eq!(cli.browser.as_deref(), Some("auto"));
|
||||
assert!(cli.external_browser_requested());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_default_keeps_system_default_mode() {
|
||||
let cli =
|
||||
Cli::try_parse_from(["gpauth", "portal.example.com", "--browser", "default"]).expect("gpauth args should parse");
|
||||
|
||||
assert_eq!(cli.browser.as_deref(), Some("default"));
|
||||
assert!(cli.external_browser_requested());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_listen_accepts_ip_address() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpauth",
|
||||
"portal.example.com",
|
||||
"--browser",
|
||||
"manual",
|
||||
"--browser-listen",
|
||||
"192.168.107.15",
|
||||
])
|
||||
.expect("gpauth args should parse");
|
||||
|
||||
assert_eq!(cli.browser_listen, Some("192.168.107.15".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_version_arg_sets_profile_client_version() {
|
||||
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--client-version", "legacy-client"])
|
||||
.expect("gpauth args should parse");
|
||||
let profile = cli.build_os_profile();
|
||||
|
||||
assert_eq!(profile.client_version(), "legacy-client");
|
||||
assert!(profile.user_agent().contains("legacy-client"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_certificate_args_parse() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpauth",
|
||||
"portal.example.com",
|
||||
"--certificate",
|
||||
"/tmp/client.pem",
|
||||
"--sslkey",
|
||||
"/tmp/client.key",
|
||||
"--key-password",
|
||||
"secret",
|
||||
])
|
||||
.expect("gpauth args should parse");
|
||||
|
||||
assert_eq!(cli.certificate.as_deref(), Some("/tmp/client.pem"));
|
||||
assert_eq!(cli.sslkey.as_deref(), Some("/tmp/client.key"));
|
||||
assert_eq!(cli.key_password.as_deref(), Some("secret"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[test]
|
||||
fn auth_window_options_parse() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpauth",
|
||||
"portal.example.com",
|
||||
"--window-title",
|
||||
"GP Connect Login",
|
||||
"--window-theme",
|
||||
"dark",
|
||||
])
|
||||
.expect("gpauth window options should parse");
|
||||
|
||||
assert_eq!(cli.window_title.as_deref(), Some("GP Connect Login"));
|
||||
assert_eq!(cli.window_theme, AuthWindowTheme::Dark);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,35 @@
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
mod auth_window;
|
||||
mod cli;
|
||||
|
||||
#[cfg(all(target_os = "macos", feature = "webview-auth"))]
|
||||
mod callback_app;
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
mod tauri_context;
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
mod webview_auth;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
#[cfg(all(target_os = "macos", feature = "webview-auth"))]
|
||||
if is_callback_app_launch() {
|
||||
if let Err(err) = callback_app::run() {
|
||||
eprintln!("Failed to handle authentication callback: {err}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
cli::run().await;
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "macos", feature = "webview-auth"))]
|
||||
fn is_callback_app_launch() -> bool {
|
||||
std::env::args_os().len() == 1
|
||||
&& std::env::current_exe().is_ok_and(|executable| {
|
||||
executable
|
||||
.ancestors()
|
||||
.any(|path| path.extension().is_some_and(|extension| extension == "app"))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub fn get() -> tauri::Context<tauri::Wry> {
|
||||
tauri::generate_context!()
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use auth::{WebviewAuthenticator, apply_auth_theme};
|
||||
use gpapi::{auth::AuthWindowTheme, gp_params::GpParams};
|
||||
|
||||
use crate::cli::print_auth_result;
|
||||
|
||||
pub async fn authenticate(
|
||||
server: String,
|
||||
gp_params: GpParams,
|
||||
auth_request: String,
|
||||
clean: bool,
|
||||
window_title: Option<String>,
|
||||
window_theme: AuthWindowTheme,
|
||||
) -> anyhow::Result<()> {
|
||||
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
|
||||
|
||||
tauri::Builder::default()
|
||||
.setup(move |app| {
|
||||
#[cfg(target_os = "macos")]
|
||||
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
|
||||
|
||||
apply_auth_theme(app.handle(), window_theme);
|
||||
let app_handle = app.handle().clone();
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let authenticator = WebviewAuthenticator::new(&server, &gp_params)
|
||||
.with_auth_request(&auth_request)
|
||||
.with_webview_user_agent(gp_params.os_profile().webview_user_agent())
|
||||
.with_clean(clean)
|
||||
.with_window_title(window_title.as_deref().unwrap_or("GlobalProtect Login"))
|
||||
.with_window_theme(window_theme);
|
||||
|
||||
let auth_result = authenticator.authenticate(&app_handle).await;
|
||||
print_auth_result(auth_result, Some(&auth_host_id));
|
||||
|
||||
// Ensure the app exits after the authentication process
|
||||
app_handle.exit(0);
|
||||
});
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.build(crate::tauri_context::get())?
|
||||
.run(|_, _| {});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,47 +1,19 @@
|
||||
{
|
||||
"$schema": "https://cdn.jsdelivr.net/gh/tauri-apps/tauri@tauri-v1.5.0/tooling/cli/schema.json",
|
||||
"$schema": "https://cdn.jsdelivr.net/gh/tauri-apps/tauri@tauri-v2.1.1/crates/tauri-cli/config.schema.json",
|
||||
"build": {
|
||||
"distDir": [
|
||||
"index.html"
|
||||
],
|
||||
"devPath": [
|
||||
"index.html"
|
||||
],
|
||||
"frontendDist": ["index.html"],
|
||||
"beforeDevCommand": "",
|
||||
"beforeBuildCommand": "",
|
||||
"withGlobalTauri": false
|
||||
"beforeBuildCommand": ""
|
||||
},
|
||||
"package": {
|
||||
"productName": "gpauth",
|
||||
"version": "0.0.0"
|
||||
},
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
"all": false,
|
||||
"http": {
|
||||
"all": true,
|
||||
"request": true,
|
||||
"scope": [
|
||||
"http://*",
|
||||
"https://*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "deb",
|
||||
"identifier": "com.yuezk.gpauth",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/[email protected]",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
},
|
||||
"identifier": "com.yuezk.gpauth",
|
||||
"productName": "GP Connect Login",
|
||||
"app": {
|
||||
"withGlobalTauri": false,
|
||||
"security": {
|
||||
"csp": null
|
||||
},
|
||||
"windows": []
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"icon": ["icons/icon.png"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#![cfg(not(target_os = "macos"))]
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn deprecated_flag_warns_without_changing_auth_output_or_configuration() {
|
||||
const WARNING: &str = "--fix-openssl is deprecated and has no effect. It will be removed in a future release.";
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let configuration = directory.path().join("openssl.cnf");
|
||||
std::fs::write(&configuration, "existing user configuration").unwrap();
|
||||
for deprecated in [false, true] {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_gpauth"));
|
||||
command.arg("portal.example.com");
|
||||
if deprecated {
|
||||
command.arg("--fix-openssl");
|
||||
}
|
||||
// Reject invalid options before authentication, without making a network request.
|
||||
let output = command
|
||||
.args(["--browser-listen", "127.0.0.1", "--log-format", "json"])
|
||||
.env("OPENSSL_CONF", &configuration)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
let logs = String::from_utf8(output.stderr).unwrap();
|
||||
let records = logs
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
records.iter().filter(|record| record["message"] == WARNING).count(),
|
||||
usize::from(deprecated)
|
||||
);
|
||||
assert!(logs.contains("requires '--browser manual'"));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&configuration).unwrap(),
|
||||
"existing user configuration"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
[package]
|
||||
name = "gpclient"
|
||||
rust-version.workspace = true
|
||||
authors.workspace = true
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
@@ -8,17 +9,35 @@ license.workspace = true
|
||||
[dependencies]
|
||||
common = { path = "../../crates/common" }
|
||||
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
|
||||
gphip = { path = "../../crates/gphip" }
|
||||
openconnect = { path = "../../crates/openconnect" }
|
||||
gptunnel = { path = "../../crates/gptunnel" }
|
||||
|
||||
anyhow.workspace = true
|
||||
clap.workspace = true
|
||||
env_logger.workspace = true
|
||||
inquire = "0.6.2"
|
||||
inquire = "0.9"
|
||||
log.workspace = true
|
||||
tokio.workspace = true
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process", "poll", "term"] }
|
||||
ratatui = { version = "=0.30.2", default-features = false, features = ["crossterm", "unstable-rendered-line-info"] }
|
||||
crossterm = { version = "0.29", features = ["use-dev-tty"] }
|
||||
strip-ansi-escapes = "0.2"
|
||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||
tokio-util.workspace = true
|
||||
sysinfo.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
whoami.workspace = true
|
||||
tempfile.workspace = true
|
||||
reqwest.workspace = true
|
||||
directories = "5.0"
|
||||
directories.workspace = true
|
||||
compile-time.workspace = true
|
||||
uzers.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["webview-auth"]
|
||||
webview-auth = ["gpapi/webview-auth"]
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
gpvpnc = { path = "../../crates/gpvpnc" }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,65 @@
|
||||
use std::{env, fs, path::PathBuf, process::Command};
|
||||
|
||||
const UNKNOWN_COMMIT: &str = "unknown";
|
||||
const DISPLAY_COMMIT_LEN: usize = 9;
|
||||
|
||||
fn main() {
|
||||
// Installed OpenConnect lives in the private ../lib/gpclient directory.
|
||||
// Build executables also locate their exact Cargo library; installers remove that rpath.
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
println!("cargo:rustc-link-arg=-Wl,-rpath,@executable_path/../lib/gpclient");
|
||||
let library_dir = env::var("DEP_OPENCONNECT_LIB_DIR").expect("OpenConnect exports its build library directory");
|
||||
println!("cargo:rustc-link-arg=-Wl,-rpath,{library_dir}");
|
||||
}
|
||||
|
||||
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
|
||||
println!("cargo:rerun-if-env-changed=GPCLIENT_GIT_COMMIT");
|
||||
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
|
||||
|
||||
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
|
||||
let source_commit = repo_root.join("SOURCE_COMMIT");
|
||||
println!("cargo:rerun-if-changed={}", source_commit.display());
|
||||
|
||||
let commit = env_commit("GPCLIENT_GIT_COMMIT")
|
||||
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
|
||||
.or_else(|| env_commit("GITHUB_SHA"))
|
||||
.or_else(|| file_commit(&source_commit))
|
||||
.or_else(|| git_commit(&repo_root))
|
||||
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string());
|
||||
|
||||
println!("cargo:rustc-env=GPCLIENT_GIT_COMMIT={commit}");
|
||||
}
|
||||
|
||||
fn env_commit(key: &str) -> Option<String> {
|
||||
env::var(key).ok().and_then(|value| normalize_commit(&value))
|
||||
}
|
||||
|
||||
fn file_commit(path: &PathBuf) -> Option<String> {
|
||||
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
|
||||
}
|
||||
|
||||
fn git_commit(repo_root: &PathBuf) -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.args(["rev-parse", "--short=12", "HEAD"])
|
||||
.current_dir(repo_root)
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
String::from_utf8(output.stdout)
|
||||
.ok()
|
||||
.and_then(|value| normalize_commit(&value))
|
||||
}
|
||||
|
||||
fn normalize_commit(value: &str) -> Option<String> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
//! Re-exec a worker in the foreground for sign-in, then detach only after tunnel setup.
|
||||
//! No process is forked after authentication or OpenConnect has started its threads.
|
||||
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
ffi::OsString,
|
||||
fs::{File, OpenOptions},
|
||||
io::{self, Write},
|
||||
os::{
|
||||
fd::{AsRawFd, FromRawFd, OwnedFd},
|
||||
unix::{
|
||||
fs::{MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
net::UnixStream,
|
||||
},
|
||||
},
|
||||
path::Path,
|
||||
process::{ExitStatus, Stdio},
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, FdFlag, OFlag, fcntl},
|
||||
sys::signal::{Signal, kill},
|
||||
unistd::{Pid, dup2_stderr, dup2_stdin, dup2_stdout, setsid},
|
||||
};
|
||||
use tokio::{io::AsyncReadExt, process::Command};
|
||||
|
||||
const READY: u8 = 1;
|
||||
|
||||
pub(crate) struct BackgroundWorker {
|
||||
// Consumed after detachment; later tunnels stay in the same background session.
|
||||
ready: RefCell<Option<UnixStream>>,
|
||||
log: File,
|
||||
input: File,
|
||||
}
|
||||
|
||||
// Keep sign-in interactive again if a tunnel attempt fails before detachment.
|
||||
pub(crate) struct BackgroundStdio {
|
||||
saved: Option<[OwnedFd; 3]>,
|
||||
}
|
||||
|
||||
impl Drop for BackgroundStdio {
|
||||
fn drop(&mut self) {
|
||||
if let Some([input, output, error]) = &self.saved {
|
||||
let _ = io::stdout().flush();
|
||||
let _ = io::stderr().flush();
|
||||
let result = dup2_stdin(input)
|
||||
.and_then(|_| dup2_stdout(output))
|
||||
.and_then(|_| dup2_stderr(error));
|
||||
if let Err(error) = result {
|
||||
log::warn!("Cannot restore foreground standard streams: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BackgroundWorker {
|
||||
pub(crate) fn new(fd: i32, log_path: &Path) -> anyhow::Result<Self> {
|
||||
anyhow::ensure!(fd >= 3, "Invalid background readiness descriptor");
|
||||
// Validate the raw descriptor before taking ownership; malformed internal args
|
||||
// must return an error rather than violate OwnedFd's validity requirement.
|
||||
if unsafe { nix::libc::fcntl(fd, nix::libc::F_GETFD) } == -1 {
|
||||
return Err(io::Error::last_os_error().into());
|
||||
}
|
||||
// The launcher passes its own readiness socket across exec, without authentication state.
|
||||
let ready = unsafe { UnixStream::from_raw_fd(fd) };
|
||||
ready.peer_addr().context("Invalid background readiness socket")?;
|
||||
fcntl(&ready, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC))?;
|
||||
let log = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.mode(0o600)
|
||||
.custom_flags(OFlag::O_NOFOLLOW.bits() | OFlag::O_NONBLOCK.bits())
|
||||
.open(log_path)
|
||||
.with_context(|| format!("Cannot open background log {}", log_path.display()))?;
|
||||
let metadata = log.metadata()?;
|
||||
anyhow::ensure!(metadata.is_file(), "Background log must be a regular file");
|
||||
anyhow::ensure!(
|
||||
metadata.uid() == uzers::get_effective_uid(),
|
||||
"Background log must be owned by the user running gpclient"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
metadata.permissions().mode() & 0o077 == 0,
|
||||
"Background log must not be readable or writable by other users"
|
||||
);
|
||||
let input = File::open("/dev/null")?;
|
||||
Ok(Self {
|
||||
ready: RefCell::new(Some(ready)),
|
||||
log,
|
||||
input,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn redirect_stdio(&self) -> anyhow::Result<BackgroundStdio> {
|
||||
if self.ready.borrow().is_none() {
|
||||
return Ok(BackgroundStdio { saved: None });
|
||||
}
|
||||
io::stdout().flush()?;
|
||||
io::stderr().flush()?;
|
||||
let save = |fd| -> anyhow::Result<OwnedFd> {
|
||||
// Duplicate atomically with close-on-exec so helpers never inherit the terminal copies.
|
||||
let saved = unsafe { nix::libc::fcntl(fd, nix::libc::F_DUPFD_CLOEXEC, 3) };
|
||||
if saved == -1 {
|
||||
return Err(io::Error::last_os_error().into());
|
||||
}
|
||||
Ok(unsafe { OwnedFd::from_raw_fd(saved) })
|
||||
};
|
||||
let stdio = BackgroundStdio {
|
||||
saved: Some([save(0)?, save(1)?, save(2)?]),
|
||||
};
|
||||
// Redirect before tunnel setup, which can start a persistent --script-tun helper.
|
||||
dup2_stdin(&self.input)?;
|
||||
dup2_stdout(&self.log)?;
|
||||
dup2_stderr(&self.log)?;
|
||||
Ok(stdio)
|
||||
}
|
||||
|
||||
pub(crate) fn detach(&self, stdio: &mut BackgroundStdio) -> anyhow::Result<()> {
|
||||
let mut ready = self.ready.borrow_mut();
|
||||
let Some(socket) = ready.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
// The worker inherited the launcher's foreground group, so it can prompt normally.
|
||||
// It becomes a session leader only when sign-in and tunnel configuration are done.
|
||||
setsid().context("Cannot detach the VPN session from the terminal")?;
|
||||
socket
|
||||
.write_all(&[READY])
|
||||
.context("Background launcher exited before tunnel setup")?;
|
||||
stdio.saved.take();
|
||||
ready.take();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn start(log_path: &Path, format: gpapi::log_format::LogFormat) -> anyhow::Result<()> {
|
||||
let command = Command::new(std::env::current_exe()?);
|
||||
let arguments = std::env::args_os().skip(1).collect::<Vec<_>>();
|
||||
launch(command, &arguments)
|
||||
.await
|
||||
.with_context(|| format!("Background VPN startup failed; log file: {}", log_path.display()))?;
|
||||
gpapi::clap::report(
|
||||
format,
|
||||
log::Level::Info,
|
||||
&format!("VPN is running in the background. Logs: {}", log_path.display()),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn launch(mut command: Command, arguments: &[OsString]) -> anyhow::Result<()> {
|
||||
let (parent, worker) = UnixStream::pair()?;
|
||||
parent.set_nonblocking(true)?;
|
||||
let mut ready = tokio::net::UnixStream::from_std(parent)?;
|
||||
let fd = worker.as_raw_fd();
|
||||
command.arg("--background-worker-fd").arg(fd.to_string());
|
||||
// Internal options precede user arguments, which can include the `--` terminator.
|
||||
command.args(arguments);
|
||||
command
|
||||
.stdin(Stdio::inherit())
|
||||
.stdout(Stdio::inherit())
|
||||
.stderr(Stdio::inherit());
|
||||
// Only async-signal-safe descriptor setup runs between spawn's fork and exec.
|
||||
unsafe {
|
||||
command.pre_exec(move || {
|
||||
fcntl(&worker, FcntlArg::F_SETFD(FdFlag::empty())).map_err(io::Error::from)?;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let mut child = command.spawn().context("Cannot start background VPN worker")?;
|
||||
// Release our copy of the worker's socket so EOF reports startup failure.
|
||||
drop(command);
|
||||
let pid = Pid::from_raw(child.id().context("Background worker has no PID")? as i32);
|
||||
let outcome = tokio::select! {
|
||||
result = ready.read_u8() => result.map_err(anyhow::Error::from),
|
||||
status = child.wait() => return startup_exit(status?),
|
||||
_ = gpapi::utils::shutdown_signal() => {
|
||||
let _ = kill(pid, Signal::SIGINT);
|
||||
child.wait().await?;
|
||||
bail!("Background connection cancelled");
|
||||
}
|
||||
};
|
||||
match outcome {
|
||||
Ok(READY) => Ok(()),
|
||||
_ => {
|
||||
let _ = kill(pid, Signal::SIGINT);
|
||||
startup_exit(child.wait().await?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn startup_exit(status: ExitStatus) -> anyhow::Result<()> {
|
||||
bail!("Background VPN exited before the tunnel was established ({status})")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use nix::unistd::{getpid, getsid};
|
||||
use std::time::Duration;
|
||||
|
||||
// Re-exec the test binary so the test exercises real process/session/descriptor setup.
|
||||
// The shell consumes launch's internal FD argument instead of giving it to libtest.
|
||||
fn fixture(directory: &Path) -> Command {
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "export GPCLIENT_TEST_FD=\"$2\"; exec \"$GPCLIENT_TEST_EXE\" --exact background::tests::worker_fixture --nocapture", "fixture"])
|
||||
.env("GPCLIENT_TEST_EXE", std::env::current_exe().unwrap())
|
||||
.env("GPCLIENT_TEST_DIR", directory);
|
||||
command
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_failure_is_not_reported_as_a_background_connection() {
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "exit 7"]);
|
||||
let error = tokio::time::timeout(Duration::from_secs(5), launch(command, &[]))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("before the tunnel was established"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detached_worker_reconnects_after_launcher_exits() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(5), launch(fixture(directory.path()), &[]))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
std::fs::write(directory.path().join("reconnect"), "").unwrap();
|
||||
let pid = std::fs::read_to_string(directory.path().join("pid"))
|
||||
.unwrap()
|
||||
.parse::<i32>()
|
||||
.unwrap();
|
||||
let pid = Pid::from_raw(pid);
|
||||
assert_eq!(
|
||||
getsid(Some(pid)).unwrap(),
|
||||
pid,
|
||||
"Worker must own a terminal-independent session"
|
||||
);
|
||||
kill(pid, None).unwrap();
|
||||
let reconnected = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !std::fs::read_to_string(directory.path().join("worker.log"))
|
||||
.unwrap()
|
||||
.contains("reconnected-output")
|
||||
{
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let log = std::fs::read_to_string(directory.path().join("worker.log")).unwrap();
|
||||
assert!(reconnected.is_ok(), "Worker did not reconnect:\n{log}");
|
||||
assert!(log.contains("failed-attempt-output"));
|
||||
assert!(log.contains("helper-output"));
|
||||
assert!(!log.contains("restored-foreground-output"));
|
||||
#[derive(clap::Parser)]
|
||||
struct Disconnect {
|
||||
#[command(flatten)]
|
||||
args: crate::disconnect::DisconnectArgs,
|
||||
}
|
||||
let args = <Disconnect as clap::Parser>::parse_from(["test"]);
|
||||
crate::disconnect::DisconnectHandler::new(&args.args, &directory.path().join("pid"))
|
||||
.handle()
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !directory.path().join("stopped").exists() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsafe_log_path_fails_before_detaching() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
std::os::unix::fs::symlink(directory.path().join("target"), directory.path().join("worker.log")).unwrap();
|
||||
let result = tokio::time::timeout(Duration::from_secs(5), launch(fixture(directory.path()), &[]))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.is_err());
|
||||
assert!(!directory.path().join("target").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn worker_fixture() {
|
||||
let Ok(fd) = std::env::var("GPCLIENT_TEST_FD") else {
|
||||
return;
|
||||
};
|
||||
let directory = std::path::PathBuf::from(std::env::var_os("GPCLIENT_TEST_DIR").unwrap());
|
||||
let worker = match BackgroundWorker::new(fd.parse().unwrap(), &directory.join("worker.log")) {
|
||||
Ok(worker) => worker,
|
||||
Err(error) => {
|
||||
eprintln!("{error:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let mut interrupt = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()).unwrap();
|
||||
std::fs::write(directory.join("pid"), getpid().to_string()).unwrap();
|
||||
// A failed attempt must restore foreground streams before another sign-in.
|
||||
{
|
||||
let _stdio = worker.redirect_stdio().unwrap();
|
||||
println!("failed-attempt-output");
|
||||
}
|
||||
println!("restored-foreground-output");
|
||||
let mut stdio = worker.redirect_stdio().unwrap();
|
||||
// Like OpenConnect's script-tun helper, this child starts before readiness.
|
||||
let mut helper = std::process::Command::new("sh")
|
||||
.args(["-c", "sleep 0.1; echo helper-output"])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
worker.detach(&mut stdio).unwrap();
|
||||
println!("detached-output");
|
||||
io::stdout().flush().unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !directory.join("reconnect").exists() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
helper.wait().unwrap();
|
||||
let mut stdio = worker.redirect_stdio().unwrap();
|
||||
worker.detach(&mut stdio).unwrap();
|
||||
assert_eq!(getsid(None).unwrap(), getpid());
|
||||
println!("reconnected-output");
|
||||
io::stdout().flush().unwrap();
|
||||
interrupt.recv().await;
|
||||
std::fs::write(directory.join("stopped"), "stopped").unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,41 @@
|
||||
use std::{env::temp_dir, fs::File};
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use clap::{Parser, Subcommand};
|
||||
use gpapi::utils::openssl;
|
||||
use log::{info, LevelFilter};
|
||||
use tempfile::NamedTempFile;
|
||||
use gpapi::{
|
||||
clap::{Args, InfoLevelVerbosity, handle_error},
|
||||
log_format::{LogFormat, write_json_record},
|
||||
};
|
||||
use log::info;
|
||||
use sysinfo::{Pid, System};
|
||||
use tokio::fs;
|
||||
|
||||
use crate::{
|
||||
GP_CLIENT_LOCK_FILE,
|
||||
connect::{ConnectArgs, ConnectHandler},
|
||||
disconnect::DisconnectHandler,
|
||||
diagnostics::DiagnosticsArgs,
|
||||
disconnect::{DisconnectArgs, DisconnectHandler},
|
||||
hip::{HipArgs, HipHandler},
|
||||
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
|
||||
};
|
||||
|
||||
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
|
||||
const VERSION: &str = concat!(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
" (",
|
||||
env!("GPCLIENT_GIT_COMMIT"),
|
||||
" ",
|
||||
compile_time::date_str!(),
|
||||
")"
|
||||
);
|
||||
|
||||
pub(crate) struct SharedArgs {
|
||||
pub(crate) fix_openssl: bool,
|
||||
pub(crate) struct SharedArgs<'a> {
|
||||
pub(crate) ignore_tls_errors: bool,
|
||||
pub(crate) lock_file: &'a Path,
|
||||
pub(crate) verbose: &'a InfoLevelVerbosity,
|
||||
pub(crate) log_format: LogFormat,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
@@ -23,9 +43,28 @@ enum CliCommand {
|
||||
#[command(about = "Connect to a portal server")]
|
||||
Connect(Box<ConnectArgs>),
|
||||
#[command(about = "Disconnect from the server")]
|
||||
Disconnect,
|
||||
Disconnect(DisconnectArgs),
|
||||
#[command(about = "Launch the GUI")]
|
||||
LaunchGui(LaunchGuiArgs),
|
||||
#[command(about = "Generate HIP report")]
|
||||
Hip(HipArgs),
|
||||
#[command(about = "Collect system diagnostics for a bug report without connecting to a VPN")]
|
||||
Diagnostics(DiagnosticsArgs),
|
||||
#[command(hide = true)]
|
||||
DetectInternalHost {
|
||||
#[arg(long)]
|
||||
address: std::net::IpAddr,
|
||||
#[arg(long)]
|
||||
hostname: String,
|
||||
},
|
||||
#[command(hide = true)]
|
||||
ResolveGateway {
|
||||
host: String,
|
||||
#[arg(long, default_value_t = 443)]
|
||||
port: u16,
|
||||
#[arg(long)]
|
||||
disable_ipv6: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
@@ -50,29 +89,119 @@ struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: CliCommand,
|
||||
|
||||
#[arg(long, help = "Get around the OpenSSL `unsafe legacy renegotiation` error")]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[arg(long, hide = true)]
|
||||
fix_openssl: bool,
|
||||
#[arg(long, help = "Ignore the TLS errors")]
|
||||
ignore_tls_errors: bool,
|
||||
#[arg(
|
||||
long,
|
||||
global = true,
|
||||
default_value = GP_CLIENT_LOCK_FILE,
|
||||
help = "Path to the gpclient PID lock file"
|
||||
)]
|
||||
lock_file: PathBuf,
|
||||
|
||||
#[arg(long, hide = true, global = true)]
|
||||
background_worker_fd: Option<i32>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
default_value_t = LogFormat::Text,
|
||||
help = "Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text."
|
||||
)]
|
||||
log_format: LogFormat,
|
||||
|
||||
#[command(flatten)]
|
||||
verbose: InfoLevelVerbosity,
|
||||
}
|
||||
|
||||
impl Args for Cli {
|
||||
fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
|
||||
fn log_format(&self) -> LogFormat {
|
||||
self.log_format
|
||||
}
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
fn fix_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
|
||||
if self.fix_openssl {
|
||||
let file = openssl::fix_openssl_env()?;
|
||||
return Ok(Some(file));
|
||||
fn can_run_alongside_client(&self) -> bool {
|
||||
match &self.command {
|
||||
CliCommand::Connect(_) => false,
|
||||
CliCommand::LaunchGui(args) => args.is_auth_callback(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
async fn is_running(&self) -> bool {
|
||||
let Ok(c) = fs::read_to_string(&self.lock_file).await else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let Ok(pid) = Pid::from_str(c.trim()) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let s = System::new_all();
|
||||
let Some(p) = s.process(pid) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
p.exe()
|
||||
.map(|exe| exe.to_string_lossy().contains("gpclient"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
// The temp file will be dropped automatically when the file handle is dropped
|
||||
// So, declare it here to ensure it's not dropped
|
||||
let _file = self.fix_openssl()?;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if self.fix_openssl
|
||||
&& !(matches!(&self.command, CliCommand::Connect(args) if args.background) && self.background_worker_fd.is_none())
|
||||
{
|
||||
log::warn!("--fix-openssl is deprecated and has no effect. It will be removed in a future release.");
|
||||
}
|
||||
|
||||
if let CliCommand::Connect(args) = &self.command {
|
||||
if args.dashboard {
|
||||
crate::dashboard::validate(self.log_format)?;
|
||||
}
|
||||
}
|
||||
if self.background_worker_fd.is_some() && !matches!(&self.command, CliCommand::Connect(args) if args.background) {
|
||||
bail!("Background worker requires connect --background");
|
||||
}
|
||||
if let CliCommand::Diagnostics(args) = &self.command {
|
||||
return args.run(VERSION).await;
|
||||
}
|
||||
|
||||
// check if an instance is running
|
||||
if !self.can_run_alongside_client() && self.is_running().await {
|
||||
bail!("Another instance of the client is already running");
|
||||
}
|
||||
|
||||
let background_worker = if let CliCommand::Connect(args) = &self.command {
|
||||
if args.background {
|
||||
let log_file = args
|
||||
.log_file
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| Path::new("/var/log/gpclient.log"));
|
||||
match self.background_worker_fd {
|
||||
Some(fd) => Some(crate::background::BackgroundWorker::new(fd, log_file)?),
|
||||
None => return crate::background::start(log_file, self.log_format).await,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let shared_args = SharedArgs {
|
||||
fix_openssl: self.fix_openssl,
|
||||
ignore_tls_errors: self.ignore_tls_errors,
|
||||
lock_file: &self.lock_file,
|
||||
verbose: &self.verbose,
|
||||
log_format: self.log_format,
|
||||
};
|
||||
|
||||
if self.ignore_tls_errors {
|
||||
@@ -80,57 +209,387 @@ impl Cli {
|
||||
}
|
||||
|
||||
match &self.command {
|
||||
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await,
|
||||
CliCommand::Disconnect => DisconnectHandler::new().handle(),
|
||||
CliCommand::Connect(args) => {
|
||||
ConnectHandler::new(args, &shared_args)
|
||||
.with_background(background_worker)
|
||||
.handle()
|
||||
.await
|
||||
}
|
||||
CliCommand::Disconnect(args) => DisconnectHandler::new(args, shared_args.lock_file).handle().await,
|
||||
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
|
||||
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
|
||||
CliCommand::Diagnostics(_) => unreachable!("diagnostics is dispatched before VPN setup"),
|
||||
CliCommand::DetectInternalHost { address, hostname } => {
|
||||
let internal = gpapi::session::desktop::network::native::detect_in_helper(*address, hostname)?;
|
||||
println!("{}", serde_json::to_string(&internal)?);
|
||||
Ok(())
|
||||
}
|
||||
CliCommand::ResolveGateway {
|
||||
host,
|
||||
port,
|
||||
disable_ipv6,
|
||||
} => {
|
||||
let addresses = gpapi::session::desktop::network::native::lookup_in_helper(host, *port, *disable_ipv6)?;
|
||||
println!("{}", serde_json::to_string(&addresses)?);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn init_logger(command: &CliCommand) {
|
||||
fn build_logger(cli: &Cli) -> env_logger::Builder {
|
||||
let mut builder = env_logger::builder();
|
||||
builder.filter_level(LevelFilter::Info);
|
||||
builder.filter_level(cli.verbose.log_level_filter());
|
||||
|
||||
// Output the log messages to a file if the command is the auth callback
|
||||
if let CliCommand::LaunchGui(args) = command {
|
||||
let auth_data = args.auth_data.as_deref().unwrap_or_default();
|
||||
if !auth_data.is_empty() {
|
||||
if let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) {
|
||||
let target = Box::new(log_file);
|
||||
builder.target(env_logger::Target::Pipe(target));
|
||||
}
|
||||
}
|
||||
// Text is env_logger's own format, so leave it untouched rather than
|
||||
// reimplementing it.
|
||||
if cli.log_format == LogFormat::Json {
|
||||
builder.format(write_json_record);
|
||||
}
|
||||
|
||||
builder.init();
|
||||
builder
|
||||
}
|
||||
|
||||
pub(crate) async fn run() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
init_logger(&cli.command);
|
||||
if matches!(&cli.command, CliCommand::Connect(args) if args.dashboard) {
|
||||
let logger = build_logger(&cli).build();
|
||||
log::set_max_level(logger.filter());
|
||||
log::set_boxed_logger(Box::new(crate::dashboard::NoticeLogger::new(logger))).expect("failed to initialize logger");
|
||||
} else {
|
||||
build_logger(&cli).init();
|
||||
}
|
||||
|
||||
info!("gpclient started: {}", VERSION);
|
||||
|
||||
if let Err(err) = cli.run().await {
|
||||
eprintln!("\nError: {}", err);
|
||||
|
||||
let err = err.to_string();
|
||||
|
||||
if err.contains("unsafe legacy renegotiation") && !cli.fix_openssl {
|
||||
eprintln!("\nRe-run it with the `--fix-openssl` option to work around this issue, e.g.:\n");
|
||||
// Print the command
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
eprintln!("{} --fix-openssl {}\n", args[0], args[1..].join(" "));
|
||||
}
|
||||
|
||||
if err.contains("certificate verify failed") && !cli.ignore_tls_errors {
|
||||
eprintln!("\nRe-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n");
|
||||
// Print the command
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
eprintln!("{} --ignore-tls-errors {}\n", args[0], args[1..].join(" "));
|
||||
}
|
||||
|
||||
handle_error(err, &cli);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io::Write,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use log::Log;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn background_worker_option_precedes_user_option_terminator() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"--background-worker-fd",
|
||||
"3",
|
||||
"connect",
|
||||
"--background",
|
||||
"--",
|
||||
"portal.example.com",
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(cli.background_worker_fd, Some(3));
|
||||
assert!(matches!(cli.command, CliCommand::Connect(args) if args.background));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_mode_rejects_cookie_only_and_requires_background_for_log_file() {
|
||||
assert!(
|
||||
Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"connect",
|
||||
"portal.example.com",
|
||||
"--background",
|
||||
"--cookie-only"
|
||||
])
|
||||
.is_err()
|
||||
);
|
||||
assert!(Cli::try_parse_from(["gpclient", "connect", "portal.example.com", "--log-file", "/tmp/gp.log"]).is_err());
|
||||
assert!(
|
||||
Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"connect",
|
||||
"portal.example.com",
|
||||
"--background",
|
||||
"--passwd-on-stdin"
|
||||
])
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashboard_is_opt_in_and_conflicts_with_noninteractive_connection_modes() {
|
||||
for option in ["--background", "--cookie-only"] {
|
||||
assert!(Cli::try_parse_from(["gpclient", "connect", "portal.example.com", "--dashboard", option]).is_err());
|
||||
}
|
||||
assert!(Cli::try_parse_from(["gpclient", "connect", "portal.example.com", "--stats"]).is_err());
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"connect",
|
||||
"portal.example.com",
|
||||
"--dashboard",
|
||||
"--cookie-on-stdin",
|
||||
])
|
||||
.unwrap();
|
||||
assert!(matches!(cli.command, CliCommand::Connect(args) if args.dashboard));
|
||||
let cli = Cli::try_parse_from(["gpclient", "connect", "portal.example.com"]).unwrap();
|
||||
assert!(matches!(cli.command, CliCommand::Connect(args) if !args.dashboard));
|
||||
assert!(
|
||||
crate::dashboard::validate(LogFormat::Json)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("--log-format json")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deprecated_openssl_option_remains_supported_but_hidden() {
|
||||
let result = Cli::try_parse_from(["gpclient", "--fix-openssl", "diagnostics"]);
|
||||
assert_eq!(result.is_ok(), !cfg!(target_os = "macos"));
|
||||
for flag in ["-h", "--help"] {
|
||||
let help = Cli::try_parse_from(["gpclient", flag]).err().unwrap().to_string();
|
||||
assert!(!help.contains("--fix-openssl"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostics_accepts_output_options_and_runs_alongside_the_client() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
"--fix-openssl",
|
||||
"diagnostics",
|
||||
"--json",
|
||||
"--output",
|
||||
"report.json",
|
||||
])
|
||||
.unwrap();
|
||||
assert!(matches!(cli.command, CliCommand::Diagnostics(_)));
|
||||
assert!(cli.can_run_alongside_client());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolver_helper_runs_alongside_client_and_is_hidden_from_help() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"resolve-gateway",
|
||||
"localhost",
|
||||
"--port",
|
||||
"444",
|
||||
"--disable-ipv6",
|
||||
])
|
||||
.unwrap();
|
||||
assert!(cli.can_run_alongside_client());
|
||||
use clap::CommandFactory;
|
||||
let help = Cli::command().render_help().to_string();
|
||||
assert!(!help.contains("resolve-gateway"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_file_defaults_to_standard_path() {
|
||||
let cli = Cli::try_parse_from(["gpclient", "connect", "portal.example.com"]).expect("cli should parse");
|
||||
|
||||
assert_eq!(cli.lock_file, PathBuf::from(GP_CLIENT_LOCK_FILE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_file_can_be_overridden_after_subcommand() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"connect",
|
||||
"portal.example.com",
|
||||
"--lock-file",
|
||||
"/tmp/gpclient-portal.lock",
|
||||
])
|
||||
.expect("global lock file option should parse after subcommand");
|
||||
|
||||
assert_eq!(cli.lock_file, PathBuf::from("/tmp/gpclient-portal.lock"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hip_can_run_alongside_connected_client() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"hip",
|
||||
"--client-version",
|
||||
"6.2.4-49",
|
||||
"--client-os",
|
||||
"Mac",
|
||||
"--cookie",
|
||||
"user=alice",
|
||||
"--md5",
|
||||
"test",
|
||||
])
|
||||
.expect("HIP arguments should parse");
|
||||
|
||||
assert!(cli.can_run_alongside_client());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn launch_gui_accepts_auth_callback() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"launch-gui",
|
||||
"globalprotectcallback:cas-as=1&[email protected]&token=token",
|
||||
])
|
||||
.expect("authentication callback should parse");
|
||||
|
||||
assert!(matches!(
|
||||
&cli.command,
|
||||
CliCommand::LaunchGui(args) if args.is_auth_callback()
|
||||
));
|
||||
assert!(cli.can_run_alongside_client());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn launch_gui_rejects_callback_with_minimized() {
|
||||
assert!(Cli::try_parse_from(["gpclient", "launch-gui", "globalprotectcallback:token", "--minimized",]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn launch_gui_rejects_non_callback_positional() {
|
||||
assert!(Cli::try_parse_from(["gpclient", "launch-gui", "https://example.com/callback"]).is_err());
|
||||
}
|
||||
|
||||
fn parse_cli(args: &[&str]) -> Cli {
|
||||
Cli::try_parse_from(args).expect("arguments should parse")
|
||||
}
|
||||
|
||||
/// Text stays the default: a plain `gpclient connect` must keep the output it
|
||||
/// has always had, or every existing user's terminal changes under them.
|
||||
#[test]
|
||||
fn log_format_defaults_to_text() {
|
||||
assert_eq!(parse_cli(&["gpclient", "disconnect"]).log_format, LogFormat::Text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_format_accepts_json() {
|
||||
assert_eq!(
|
||||
parse_cli(&["gpclient", "--log-format", "json", "disconnect"]).log_format,
|
||||
LogFormat::Json
|
||||
);
|
||||
}
|
||||
|
||||
/// An unknown value is a mistake worth reporting rather than silently
|
||||
/// falling back to text, which would leave a caller parsing prose.
|
||||
#[test]
|
||||
fn log_format_rejects_an_unknown_value() {
|
||||
// `.err()` rather than `unwrap_err()`: the Ok side is `Cli`, which is not
|
||||
// `Debug`, and it is not worth deriving it just to print an error we expect.
|
||||
let err = Cli::try_parse_from(["gpclient", "--log-format", "yaml", "disconnect"])
|
||||
.err()
|
||||
.expect("an unknown log format should be rejected");
|
||||
let msg = err.to_string();
|
||||
assert!(msg.contains("yaml"), "error should name the input: {msg}");
|
||||
assert!(msg.contains("json"), "error should list the valid values: {msg}");
|
||||
}
|
||||
|
||||
/// A `Write` that keeps what was written, so the logger can be driven for
|
||||
/// real instead of asserting on how it was configured.
|
||||
#[derive(Clone, Default)]
|
||||
struct Captured(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl Captured {
|
||||
fn contents(&self) -> String {
|
||||
String::from_utf8(self.0.lock().unwrap().clone()).expect("log output should be UTF-8")
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for Captured {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn log_one_record(args: &[&str]) -> String {
|
||||
let captured = Captured::default();
|
||||
let logger = build_logger(&parse_cli(args))
|
||||
.target(env_logger::Target::Pipe(Box::new(captured.clone())))
|
||||
.build();
|
||||
|
||||
// Drive the logger directly: `init()` installs a global that a second test
|
||||
// could not replace.
|
||||
logger.log(
|
||||
&log::Record::builder()
|
||||
.level(log::Level::Info)
|
||||
.target("gpclient")
|
||||
.args(format_args!("connected to {}", "vpn.example.com"))
|
||||
.build(),
|
||||
);
|
||||
logger.flush();
|
||||
|
||||
captured.contents()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_property_log_filters_keep_matching_and_excluding_records() {
|
||||
for (pattern, matching, excluded) in [
|
||||
(r"\p{Greek}", "α", "plain ASCII"),
|
||||
(r"\p{Mark}", "\u{0301}", "plain ASCII"),
|
||||
(r"\p{Alphabetic}", "α", "123"),
|
||||
(r"\p{Grapheme_Extend}", "\u{0301}", "plain ASCII"),
|
||||
] {
|
||||
let captured = Captured::default();
|
||||
let logger = build_logger(&parse_cli(&["gpclient", "disconnect"]))
|
||||
.parse_filters(&format!("info/{pattern}"))
|
||||
.target(env_logger::Target::Pipe(Box::new(captured.clone())))
|
||||
.build();
|
||||
for message in [excluded, matching] {
|
||||
logger.log(
|
||||
&log::Record::builder()
|
||||
.level(log::Level::Info)
|
||||
.target("gpclient")
|
||||
.args(format_args!("{message}"))
|
||||
.build(),
|
||||
);
|
||||
}
|
||||
let output = captured.contents();
|
||||
assert!(
|
||||
output.contains(matching),
|
||||
"filter {pattern} dropped its matching record"
|
||||
);
|
||||
assert!(
|
||||
!output.contains(excluded),
|
||||
"filter {pattern} allowed an excluded record"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The point of the flag: with `json`, a caller gets fields, and gets them one
|
||||
/// record per line so the stream can be read incrementally.
|
||||
#[test]
|
||||
fn json_format_emits_one_json_object_per_record() {
|
||||
let out = log_one_record(&["gpclient", "--log-format", "json", "disconnect"]);
|
||||
|
||||
let lines: Vec<_> = out.lines().collect();
|
||||
assert_eq!(lines.len(), 1, "expected exactly one line, got: {out:?}");
|
||||
|
||||
let v: serde_json::Value = serde_json::from_str(lines[0]).unwrap_or_else(|e| panic!("not JSON: {out:?} ({e})"));
|
||||
assert_eq!(v["level"], "INFO");
|
||||
assert_eq!(v["target"], "gpclient");
|
||||
assert_eq!(v["message"], "connected to vpn.example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_format_is_left_alone() {
|
||||
let out = log_one_record(&["gpclient", "disconnect"]);
|
||||
|
||||
assert!(out.contains("connected to vpn.example.com"), "message missing: {out:?}");
|
||||
assert!(
|
||||
serde_json::from_str::<serde_json::Value>(out.trim()).is_err(),
|
||||
"text output should not be JSON: {out:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,426 +0,0 @@
|
||||
use std::{cell::RefCell, fs, sync::Arc};
|
||||
|
||||
use anyhow::bail;
|
||||
use clap::Args;
|
||||
use common::vpn_utils::find_csd_wrapper;
|
||||
use gpapi::{
|
||||
auth::SamlAuthResult,
|
||||
clap::args::Os,
|
||||
credential::{Credential, PasswordCredential},
|
||||
error::PortalError,
|
||||
gateway::{gateway_login, GatewayLogin},
|
||||
gp_params::{ClientOs, GpParams},
|
||||
portal::{prelogin, retrieve_config, Prelogin},
|
||||
process::{
|
||||
auth_launcher::SamlAuthLauncher,
|
||||
users::{get_non_root_user, get_user_by_name},
|
||||
},
|
||||
utils::{request::RequestIdentityError, shutdown_signal},
|
||||
GP_USER_AGENT,
|
||||
};
|
||||
use inquire::{Password, PasswordDisplayMode, Select, Text};
|
||||
use log::info;
|
||||
use openconnect::Vpn;
|
||||
|
||||
use crate::{cli::SharedArgs, GP_CLIENT_LOCK_FILE};
|
||||
|
||||
#[derive(Args)]
|
||||
pub(crate) struct ConnectArgs {
|
||||
#[arg(help = "The portal server to connect to")]
|
||||
server: String,
|
||||
|
||||
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
|
||||
gateway: Option<String>,
|
||||
|
||||
#[arg(short, long, help = "The username to use, it will prompt if not specified")]
|
||||
user: Option<String>,
|
||||
|
||||
#[arg(long, help = "Read the password from standard input")]
|
||||
passwd_on_stdin: bool,
|
||||
|
||||
#[arg(long, help = "Read the cookie from standard input")]
|
||||
cookie_on_stdin: bool,
|
||||
|
||||
#[arg(long, short, help = "The VPNC script to use")]
|
||||
script: Option<String>,
|
||||
|
||||
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
|
||||
as_gateway: bool,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Use the default CSD wrapper to generate the HIP report and send it to the server"
|
||||
)]
|
||||
hip: bool,
|
||||
|
||||
#[arg(
|
||||
short,
|
||||
long,
|
||||
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
|
||||
)]
|
||||
certificate: Option<String>,
|
||||
|
||||
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
|
||||
sslkey: Option<String>,
|
||||
|
||||
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
|
||||
key_password: Option<String>,
|
||||
|
||||
#[arg(long, help = "Same as the '--csd-user' option in the openconnect command")]
|
||||
csd_user: Option<String>,
|
||||
|
||||
#[arg(long, help = "Same as the '--csd-wrapper' option in the openconnect command")]
|
||||
csd_wrapper: Option<String>,
|
||||
|
||||
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
|
||||
reconnect_timeout: u32,
|
||||
|
||||
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
|
||||
mtu: Option<u32>,
|
||||
|
||||
#[arg(long, help = "Do not ask for IPv6 connectivity")]
|
||||
disable_ipv6: bool,
|
||||
|
||||
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
|
||||
user_agent: String,
|
||||
|
||||
#[arg(long, default_value = "Linux")]
|
||||
os: Os,
|
||||
|
||||
#[arg(long)]
|
||||
os_version: Option<String>,
|
||||
|
||||
#[arg(long, help = "Disable DTLS and ESP")]
|
||||
no_dtls: bool,
|
||||
|
||||
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
|
||||
hidpi: bool,
|
||||
|
||||
#[arg(long, help = "Do not reuse the remembered authentication cookie")]
|
||||
clean: bool,
|
||||
|
||||
#[arg(long, help = "Use the default browser to authenticate")]
|
||||
default_browser: bool,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable"
|
||||
)]
|
||||
browser: Option<String>,
|
||||
}
|
||||
|
||||
impl ConnectArgs {
|
||||
fn os_version(&self) -> String {
|
||||
if let Some(os_version) = &self.os_version {
|
||||
return os_version.to_owned();
|
||||
}
|
||||
|
||||
match self.os {
|
||||
Os::Linux => format!("Linux {}", whoami::distro()),
|
||||
Os::Windows => String::from("Microsoft Windows 11 Pro , 64-bit"),
|
||||
Os::Mac => String::from("Apple Mac OS X 13.4.0"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ConnectHandler<'a> {
|
||||
args: &'a ConnectArgs,
|
||||
shared_args: &'a SharedArgs,
|
||||
latest_key_password: RefCell<Option<String>>,
|
||||
}
|
||||
|
||||
impl<'a> ConnectHandler<'a> {
|
||||
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
|
||||
Self {
|
||||
args,
|
||||
shared_args,
|
||||
latest_key_password: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_gp_params(&self) -> GpParams {
|
||||
GpParams::builder()
|
||||
.user_agent(&self.args.user_agent)
|
||||
.client_os(ClientOs::from(&self.args.os))
|
||||
.os_version(self.args.os_version())
|
||||
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
|
||||
.certificate(self.args.certificate.clone())
|
||||
.sslkey(self.args.sslkey.clone())
|
||||
.key_password(self.latest_key_password.borrow().clone())
|
||||
.build()
|
||||
}
|
||||
|
||||
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
||||
if self.args.default_browser && self.args.browser.is_some() {
|
||||
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
|
||||
}
|
||||
|
||||
self.latest_key_password.replace(self.args.key_password.clone());
|
||||
|
||||
loop {
|
||||
let Err(err) = self.handle_impl().await else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
|
||||
return Err(err);
|
||||
};
|
||||
|
||||
match root_cause {
|
||||
RequestIdentityError::NoKey => {
|
||||
eprintln!("ERROR: No private key found in the certificate file");
|
||||
eprintln!("ERROR: Please provide the private key file using the `-k` option");
|
||||
return Ok(());
|
||||
}
|
||||
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
|
||||
// Decrypt the private key error, ask for the key password
|
||||
let message = format!("Enter the {} passphrase:", cert_type);
|
||||
let password = Password::new(&message)
|
||||
.without_confirmation()
|
||||
.with_display_mode(PasswordDisplayMode::Masked)
|
||||
.prompt()?;
|
||||
|
||||
self.latest_key_password.replace(Some(password));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
|
||||
let server = self.args.server.as_str();
|
||||
let as_gateway = self.args.as_gateway;
|
||||
|
||||
if as_gateway {
|
||||
info!("Treating the server as a gateway");
|
||||
return self.connect_gateway_with_prelogin(server).await;
|
||||
}
|
||||
|
||||
let Err(err) = self.connect_portal_with_prelogin(server).await else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
info!("Failed to connect portal with prelogin: {}", err);
|
||||
if err.root_cause().downcast_ref::<PortalError>().is_some() {
|
||||
info!("Trying the gateway authentication workflow...");
|
||||
self.connect_gateway_with_prelogin(server).await?;
|
||||
|
||||
eprintln!("\nNOTE: the server may be a gateway, not a portal.");
|
||||
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
|
||||
let gp_params = self.build_gp_params();
|
||||
|
||||
let prelogin = prelogin(portal, &gp_params).await?;
|
||||
|
||||
let cred = self.obtain_credential(&prelogin, portal).await?;
|
||||
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
|
||||
|
||||
let selected_gateway = match &self.args.gateway {
|
||||
Some(gateway) => portal_config
|
||||
.find_gateway(gateway)
|
||||
.ok_or_else(|| anyhow::anyhow!("Cannot find gateway specified: {}", gateway))?,
|
||||
None => {
|
||||
portal_config.sort_gateways(prelogin.region());
|
||||
let gateways = portal_config.gateways();
|
||||
|
||||
if gateways.len() > 1 {
|
||||
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
|
||||
.with_vim_mode(true)
|
||||
.prompt()?;
|
||||
info!("Connecting to the selected gateway: {}", gateway);
|
||||
gateway
|
||||
} else {
|
||||
info!("Connecting to the only available gateway: {}", gateways[0]);
|
||||
gateways[0]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let gateway = selected_gateway.server();
|
||||
let cred = portal_config.auth_cookie().into();
|
||||
|
||||
let cookie = match self.login_gateway(gateway, &cred, &gp_params).await {
|
||||
Ok(cookie) => cookie,
|
||||
Err(err) => {
|
||||
info!("Gateway login failed: {}", err);
|
||||
return self.connect_gateway_with_prelogin(gateway).await;
|
||||
}
|
||||
};
|
||||
|
||||
self.connect_gateway(gateway, &cookie).await
|
||||
}
|
||||
|
||||
async fn connect_gateway_with_prelogin(&self, gateway: &str) -> anyhow::Result<()> {
|
||||
info!("Performing the gateway authentication...");
|
||||
|
||||
let mut gp_params = self.build_gp_params();
|
||||
gp_params.set_is_gateway(true);
|
||||
|
||||
let prelogin = prelogin(gateway, &gp_params).await?;
|
||||
let cred = self.obtain_credential(&prelogin, gateway).await?;
|
||||
|
||||
let cookie = self.login_gateway(gateway, &cred, &gp_params).await?;
|
||||
|
||||
self.connect_gateway(gateway, &cookie).await
|
||||
}
|
||||
|
||||
async fn login_gateway(&self, gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<String> {
|
||||
let mut gp_params = gp_params.clone();
|
||||
|
||||
loop {
|
||||
match gateway_login(gateway, cred, &gp_params).await? {
|
||||
GatewayLogin::Cookie(cookie) => return Ok(cookie),
|
||||
GatewayLogin::Mfa(message, input_str) => {
|
||||
let otp = Text::new(&message).prompt()?;
|
||||
gp_params.set_input_str(&input_str);
|
||||
gp_params.set_otp(&otp);
|
||||
|
||||
info!("Retrying gateway login with MFA...");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_gateway(&self, gateway: &str, cookie: &str) -> anyhow::Result<()> {
|
||||
let mtu = self.args.mtu.unwrap_or(0);
|
||||
let csd_uid = get_csd_uid(&self.args.csd_user)?;
|
||||
let csd_wrapper = if self.args.csd_wrapper.is_some() {
|
||||
self.args.csd_wrapper.clone()
|
||||
} else if self.args.hip {
|
||||
find_csd_wrapper()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let os = ClientOs::from(&self.args.os).to_openconnect_os().to_string();
|
||||
let vpn = Vpn::builder(gateway, cookie)
|
||||
.script(self.args.script.clone())
|
||||
.user_agent(self.args.user_agent.clone())
|
||||
.os(Some(os))
|
||||
.certificate(self.args.certificate.clone())
|
||||
.sslkey(self.args.sslkey.clone())
|
||||
.key_password(self.latest_key_password.borrow().clone())
|
||||
.csd_uid(csd_uid)
|
||||
.csd_wrapper(csd_wrapper)
|
||||
.reconnect_timeout(self.args.reconnect_timeout)
|
||||
.mtu(mtu)
|
||||
.disable_ipv6(self.args.disable_ipv6)
|
||||
.no_dtls(self.args.no_dtls)
|
||||
.build()?;
|
||||
|
||||
let vpn = Arc::new(vpn);
|
||||
let vpn_clone = vpn.clone();
|
||||
|
||||
// Listen for the interrupt signal in the background
|
||||
tokio::spawn(async move {
|
||||
shutdown_signal().await;
|
||||
info!("Received the interrupt signal, disconnecting...");
|
||||
vpn_clone.disconnect();
|
||||
});
|
||||
|
||||
vpn.connect(write_pid_file);
|
||||
|
||||
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
|
||||
info!("Removing PID file");
|
||||
fs::remove_file(GP_CLIENT_LOCK_FILE)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn obtain_credential(&self, prelogin: &Prelogin, server: &str) -> anyhow::Result<Credential> {
|
||||
if self.args.cookie_on_stdin {
|
||||
return read_cookie_from_stdin();
|
||||
}
|
||||
|
||||
let is_gateway = prelogin.is_gateway();
|
||||
|
||||
match prelogin {
|
||||
Prelogin::Saml(prelogin) => {
|
||||
let use_default_browser = prelogin.support_default_browser() && self.args.default_browser;
|
||||
let browser = if prelogin.support_default_browser() {
|
||||
self.args.browser.as_deref()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let cred = SamlAuthLauncher::new(&self.args.server)
|
||||
.gateway(is_gateway)
|
||||
.saml_request(prelogin.saml_request())
|
||||
.user_agent(&self.args.user_agent)
|
||||
.os(self.args.os.as_str())
|
||||
.os_version(Some(&self.args.os_version()))
|
||||
.hidpi(self.args.hidpi)
|
||||
.fix_openssl(self.shared_args.fix_openssl)
|
||||
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
|
||||
.clean(self.args.clean)
|
||||
.default_browser(use_default_browser)
|
||||
.browser(browser)
|
||||
.launch()
|
||||
.await?;
|
||||
|
||||
Ok(cred)
|
||||
}
|
||||
|
||||
Prelogin::Standard(prelogin) => {
|
||||
let prefix = if is_gateway { "Gateway" } else { "Portal" };
|
||||
println!("{} ({}: {})", prelogin.auth_message(), prefix, server);
|
||||
|
||||
let user = self.args.user.as_ref().map_or_else(
|
||||
|| Text::new(&format!("{}:", prelogin.label_username())).prompt(),
|
||||
|user| Ok(user.to_owned()),
|
||||
)?;
|
||||
|
||||
let password = if self.args.passwd_on_stdin {
|
||||
info!("Reading password from standard input");
|
||||
let mut input = String::new();
|
||||
std::io::stdin().read_line(&mut input)?;
|
||||
input.trim_end().to_owned()
|
||||
} else {
|
||||
Password::new(&format!("{}:", prelogin.label_password()))
|
||||
.without_confirmation()
|
||||
.with_display_mode(PasswordDisplayMode::Masked)
|
||||
.prompt()?
|
||||
};
|
||||
|
||||
let password_cred = PasswordCredential::new(&user, &password);
|
||||
|
||||
Ok(password_cred.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_cookie_from_stdin() -> anyhow::Result<Credential> {
|
||||
info!("Reading cookie from standard input");
|
||||
|
||||
let mut cookie = String::new();
|
||||
std::io::stdin().read_line(&mut cookie)?;
|
||||
|
||||
let Ok(auth_result) = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()) else {
|
||||
bail!("Failed to parse auth data")
|
||||
};
|
||||
|
||||
Credential::try_from(auth_result)
|
||||
}
|
||||
|
||||
fn write_pid_file() {
|
||||
let pid = std::process::id();
|
||||
|
||||
fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()).unwrap();
|
||||
info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
|
||||
}
|
||||
|
||||
fn get_csd_uid(csd_user: &Option<String>) -> anyhow::Result<u32> {
|
||||
if let Some(csd_user) = csd_user {
|
||||
get_user_by_name(csd_user).map(|user| user.uid())
|
||||
} else {
|
||||
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
use clap::Args;
|
||||
use gpapi::{
|
||||
clap::args::Os,
|
||||
cookie_store,
|
||||
gp_params::CscMode,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
};
|
||||
use log::warn;
|
||||
use std::{net::IpAddr, path::PathBuf};
|
||||
|
||||
#[derive(Args)]
|
||||
pub(crate) struct ConnectArgs {
|
||||
#[arg(help = "The portal server to connect to")]
|
||||
pub(super) server: String,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
conflicts_with = "cookie_only",
|
||||
help = "Complete sign-in, then keep the VPN running after this command exits"
|
||||
)]
|
||||
pub(crate) background: bool,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
conflicts_with_all = ["background", "cookie_only"],
|
||||
help = "Show an interactive connection dashboard after sign-in (requires a foreground terminal)"
|
||||
)]
|
||||
pub(crate) dashboard: bool,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
requires = "background",
|
||||
help = "Background log file (default: /var/log/gpclient.log)"
|
||||
)]
|
||||
pub(crate) log_file: Option<PathBuf>,
|
||||
|
||||
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
|
||||
pub(super) gateway: Option<String>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
conflicts_with = "gateway",
|
||||
help = "Automatically try gateways in priority order until gateway auth/config succeeds, without prompting"
|
||||
)]
|
||||
pub(super) auto_gateway: bool,
|
||||
|
||||
#[arg(short, long, help = "The username to use, it will prompt if not specified")]
|
||||
pub(super) user: Option<String>,
|
||||
|
||||
#[arg(long, help = "Read the password from standard input")]
|
||||
pub(super) passwd_on_stdin: bool,
|
||||
|
||||
#[arg(long, help = "Read the gpauth authentication result from standard input")]
|
||||
pub(super) cookie_on_stdin: bool,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Read and write the portal cookie cache, optionally specify the cache file path",
|
||||
default_missing_value = "",
|
||||
num_args=0..=1
|
||||
)]
|
||||
pub(super) cookie_cache: Option<String>,
|
||||
|
||||
#[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))]
|
||||
pub(super) script: Option<String>,
|
||||
|
||||
#[arg(long, short, help = "The IFNAME for tunnel interface")]
|
||||
pub(super) interface: Option<String>,
|
||||
|
||||
#[arg(long, short = 'S', help = "Pass traffic to '--script' program, not tun")]
|
||||
pub(super) script_tun: bool,
|
||||
|
||||
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
|
||||
pub(super) as_gateway: bool,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Enable HIP (Host Information Profile), optionally specify a custom executable",
|
||||
default_missing_value = "",
|
||||
num_args=0..=1
|
||||
)]
|
||||
pub(super) hip: Option<String>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Run a custom HIP executable as this user; otherwise inherit the process user"
|
||||
)]
|
||||
pub(super) hip_user: Option<String>,
|
||||
|
||||
#[arg(
|
||||
short,
|
||||
long,
|
||||
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
|
||||
)]
|
||||
pub(super) certificate: Option<String>,
|
||||
|
||||
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
|
||||
pub(super) sslkey: Option<String>,
|
||||
|
||||
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
|
||||
pub(super) key_password: Option<String>,
|
||||
|
||||
#[arg(long, hide = true)]
|
||||
pub(super) csd_user: Option<String>,
|
||||
|
||||
#[arg(long, hide = true)]
|
||||
pub(super) csd_wrapper: Option<String>,
|
||||
|
||||
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
|
||||
pub(super) reconnect_timeout: u32,
|
||||
|
||||
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
|
||||
pub(super) mtu: Option<u32>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
default_value = "auto",
|
||||
help = "Choose which IP version to try first when connecting to the gateway"
|
||||
)]
|
||||
pub(super) ip_preference: gpapi::gateway::GatewayIpPreference,
|
||||
|
||||
#[arg(long, help = "Use only IPv4 for traffic inside the VPN tunnel")]
|
||||
pub(super) disable_ipv6: bool,
|
||||
|
||||
#[arg(long = "user-agent", hide = true)]
|
||||
pub(super) deprecated_user_agent: Option<String>,
|
||||
|
||||
#[arg(long = "os-version", hide = true)]
|
||||
pub(super) deprecated_os_version: Option<String>,
|
||||
|
||||
#[arg(long, help = "Override the client version reported to the server, e.g., '6.2.4-49'")]
|
||||
pub(super) client_version: Option<String>,
|
||||
|
||||
#[arg(long, value_enum, default_value_t = Os::default())]
|
||||
pub(super) os: Os,
|
||||
|
||||
#[arg(long, value_enum, default_value_t = CscMode::Auto, help = "CSC support mode: auto, yes, or no")]
|
||||
pub(super) csc: CscMode,
|
||||
|
||||
#[arg(long, help = "Disable DTLS and ESP")]
|
||||
pub(super) no_dtls: bool,
|
||||
|
||||
#[arg(
|
||||
long = "local-hostname",
|
||||
help = "Same as the '--local-hostname' option in the openconnect command"
|
||||
)]
|
||||
pub(super) local_hostname: Option<String>,
|
||||
|
||||
#[arg(
|
||||
long = "force-dpd",
|
||||
help = "Same as the '--force-dpd' option in the openconnect command"
|
||||
)]
|
||||
pub(super) dpd_interval: Option<u32>,
|
||||
|
||||
#[arg(
|
||||
long = "no-xmlpost",
|
||||
help = "Same as the '--no-xmlpost' option in the openconnect command"
|
||||
)]
|
||||
pub(super) no_xmlpost: bool,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
|
||||
pub(super) hidpi: bool,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, help = "Do not reuse the remembered authentication cookie")]
|
||||
pub(super) clean: bool,
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[arg(long, help = "Deprecated: Use the `--browser` option instead")]
|
||||
pub(super) default_browser: bool,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Use a browser; omit the value to auto-select. Use `manual` to open the URL and paste the callback.",
|
||||
default_missing_value = "auto",
|
||||
num_args=0..=1
|
||||
)]
|
||||
pub(super) browser: Option<String>,
|
||||
|
||||
#[arg(long, help = "Listen on this IP address when using '--browser manual'")]
|
||||
pub(super) browser_listen: Option<IpAddr>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Authenticate and print the gateway cookie to stdout, then exit without starting the \
|
||||
VPN tunnel. Outputs two lines: COOKIE='<value>' and HOST='<gateway>'. Combine with \
|
||||
--cookie-cache to avoid re-authenticating when the portal session is still valid."
|
||||
)]
|
||||
pub(super) cookie_only: bool,
|
||||
}
|
||||
|
||||
pub(super) fn build_os_profile(args: &ConnectArgs) -> OsProfile {
|
||||
build_os_profile_with_host_id(args, None)
|
||||
}
|
||||
|
||||
pub(super) fn build_os_profile_with_host_id(args: &ConnectArgs, host_id: Option<&str>) -> OsProfile {
|
||||
let mut builder = OsProfile::builder(ClientOs::from(args.os));
|
||||
if let Some(client_version) = args.client_version.as_deref() {
|
||||
builder = builder.client_version(client_version.to_string());
|
||||
}
|
||||
if let Some(local_hostname) = args.local_hostname.as_deref() {
|
||||
builder = builder.computer_name_override(local_hostname.to_string());
|
||||
}
|
||||
gpapi::os_profile::desktop::collect_profile(builder, host_id)
|
||||
}
|
||||
|
||||
pub(super) fn cookie_cache_path(args: &ConnectArgs) -> Option<PathBuf> {
|
||||
args.cookie_cache.as_deref().map(|path| {
|
||||
let custom = (!path.is_empty()).then_some(path);
|
||||
cookie_store::cookie_path(custom)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn warn_deprecated_connect_args(args: &ConnectArgs) {
|
||||
if args.csd_user.is_some() {
|
||||
warn!("Deprecated option --csd-user will be removed; use --hip-user instead");
|
||||
}
|
||||
|
||||
if args.csd_wrapper.is_some() {
|
||||
warn!("Deprecated option --csd-wrapper will be removed; use --hip instead");
|
||||
}
|
||||
|
||||
if args.deprecated_user_agent.is_some() {
|
||||
warn!("Deprecated option --user-agent is ignored; user agent is derived from --os");
|
||||
}
|
||||
|
||||
if args.deprecated_os_version.is_some() {
|
||||
warn!("Deprecated option --os-version is ignored; OS version is derived from --os");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(clap::Parser)]
|
||||
struct ConnectArgsTestCli {
|
||||
#[command(flatten)]
|
||||
args: ConnectArgs,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_csc_mode_values() {
|
||||
use clap::ValueEnum;
|
||||
|
||||
assert_eq!(CscMode::from_str("auto", false), Ok(CscMode::Auto));
|
||||
assert_eq!(CscMode::from_str("yes", false), Ok(CscMode::Yes));
|
||||
assert_eq!(CscMode::from_str("no", false), Ok(CscMode::No));
|
||||
assert!(CscMode::from_str("maybe", false).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_gateway_flag_parses() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--auto-gateway"])
|
||||
.expect("--auto-gateway alone should parse");
|
||||
|
||||
assert!(cli.args.auto_gateway);
|
||||
assert!(cli.args.gateway.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_gateway_help_describes_auth_config_retry() {
|
||||
use clap::CommandFactory;
|
||||
|
||||
let help = ConnectArgsTestCli::command().render_long_help().to_string();
|
||||
|
||||
assert!(help.contains("--auto-gateway"));
|
||||
assert!(help.contains("Automatically try gateways in priority order until gateway auth/config succeeds"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gateway_flag_alone_parses() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--gateway", "gw1"])
|
||||
.expect("--gateway alone should parse");
|
||||
|
||||
assert!(!cli.args.auto_gateway);
|
||||
assert_eq!(cli.args.gateway.as_deref(), Some("gw1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_without_value_uses_auto_mode() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--browser"])
|
||||
.expect("--browser without value should parse");
|
||||
|
||||
assert_eq!(cli.args.browser.as_deref(), Some("auto"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_default_keeps_system_default_mode() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--browser", "default"])
|
||||
.expect("--browser default should parse");
|
||||
|
||||
assert_eq!(cli.args.browser.as_deref(), Some("default"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_listen_accepts_ip_address() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from([
|
||||
"test",
|
||||
"portal.example.com",
|
||||
"--browser",
|
||||
"manual",
|
||||
"--browser-listen",
|
||||
"192.168.107.15",
|
||||
])
|
||||
.expect("connect args should parse");
|
||||
|
||||
assert_eq!(cli.args.browser_listen, Some("192.168.107.15".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_defaults_to_runtime_os() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
|
||||
|
||||
assert_eq!(cli.args.os, Os::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deprecated_profile_override_flags_still_parse() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from([
|
||||
"test",
|
||||
"portal.example.com",
|
||||
"--user-agent",
|
||||
"legacy-agent",
|
||||
"--os-version",
|
||||
"legacy-os",
|
||||
"--client-version",
|
||||
"legacy-client",
|
||||
])
|
||||
.expect("deprecated profile override flags should remain parse-compatible");
|
||||
|
||||
assert_eq!(cli.args.deprecated_user_agent.as_deref(), Some("legacy-agent"));
|
||||
assert_eq!(cli.args.deprecated_os_version.as_deref(), Some("legacy-os"));
|
||||
assert_eq!(cli.args.client_version.as_deref(), Some("legacy-client"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deprecated_profile_override_flags_do_not_affect_os_profile() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from([
|
||||
"test",
|
||||
"portal.example.com",
|
||||
"--os",
|
||||
"Linux",
|
||||
"--user-agent",
|
||||
"legacy-agent",
|
||||
"--os-version",
|
||||
"legacy-os",
|
||||
"--client-version",
|
||||
"legacy-client",
|
||||
])
|
||||
.expect("deprecated profile override flags should remain parse-compatible");
|
||||
|
||||
let profile = build_os_profile(&cli.args);
|
||||
|
||||
assert_ne!(profile.user_agent(), "legacy-agent");
|
||||
assert_ne!(profile.os_version(), "legacy-os");
|
||||
assert_eq!(profile.client_version(), "legacy-client");
|
||||
assert!(profile.user_agent().contains("legacy-client"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_host_id_sets_profile_runtime_identity_seed() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--os", "Linux"])
|
||||
.expect("connect args should parse");
|
||||
|
||||
let profile = build_os_profile_with_host_id(&cli.args, Some("auth-host-id"));
|
||||
|
||||
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_cache_is_disabled_by_default() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
|
||||
|
||||
assert!(cli.args.cookie_cache.is_none());
|
||||
assert!(cookie_cache_path(&cli.args).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_cache_accepts_default_path_without_value() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-cache"])
|
||||
.expect("--cookie-cache without value should parse");
|
||||
|
||||
assert_eq!(cli.args.cookie_cache.as_deref(), Some(""));
|
||||
assert!(cookie_cache_path(&cli.args).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_cache_accepts_custom_path() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli =
|
||||
ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-cache", "/tmp/gp-cookie.json"])
|
||||
.expect("--cookie-cache with value should parse");
|
||||
|
||||
assert_eq!(
|
||||
cookie_cache_path(&cli.args).as_deref(),
|
||||
Some(std::path::Path::new("/tmp/gp-cookie.json"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deprecated_hip_alias_flags_still_parse() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from([
|
||||
"test",
|
||||
"portal.example.com",
|
||||
"--csd-user",
|
||||
"legacy-user",
|
||||
"--csd-wrapper",
|
||||
"/tmp/legacy-hip.sh",
|
||||
])
|
||||
.expect("deprecated HIP alias flags should remain parse-compatible");
|
||||
|
||||
assert_eq!(cli.args.csd_user.as_deref(), Some("legacy-user"));
|
||||
assert_eq!(cli.args.csd_wrapper.as_deref(), Some("/tmp/legacy-hip.sh"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_gateway_and_gateway_are_mutually_exclusive() {
|
||||
use clap::Parser;
|
||||
use clap::error::ErrorKind;
|
||||
|
||||
let result =
|
||||
ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--gateway", "gw1", "--auto-gateway"]);
|
||||
|
||||
let err = match result {
|
||||
Ok(_) => panic!("--gateway and --auto-gateway must conflict"),
|
||||
Err(err) => err,
|
||||
};
|
||||
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_only_flag_parses() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-only"])
|
||||
.expect("--cookie-only should parse");
|
||||
|
||||
assert!(cli.args.cookie_only);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_only_is_disabled_by_default() {
|
||||
use clap::Parser;
|
||||
|
||||
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
|
||||
|
||||
assert!(!cli.args.cookie_only);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ip_preference_parses_independently_of_tunnel_ipv6() {
|
||||
use clap::Parser;
|
||||
use gpapi::gateway::GatewayIpPreference;
|
||||
let default = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).unwrap();
|
||||
assert_eq!(default.args.ip_preference, GatewayIpPreference::Auto);
|
||||
for (value, expected) in [
|
||||
("auto", GatewayIpPreference::Auto),
|
||||
("ipv4", GatewayIpPreference::Ipv4),
|
||||
("ipv6", GatewayIpPreference::Ipv6),
|
||||
] {
|
||||
let cli =
|
||||
ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--ip-preference", value, "--disable-ipv6"])
|
||||
.unwrap();
|
||||
assert_eq!(cli.args.ip_preference, expected);
|
||||
assert!(cli.args.disable_ipv6);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::{
|
||||
auth::SamlAuthResult,
|
||||
clap::ToVerboseArg,
|
||||
credential::{Credential, PasswordCredential},
|
||||
portal::{Prelogin, StandardPrelogin},
|
||||
process::auth_launcher::SamlAuthLauncher,
|
||||
};
|
||||
use inquire::{Password, PasswordDisplayMode, Text};
|
||||
use log::info;
|
||||
|
||||
use super::ConnectHandler;
|
||||
|
||||
/// Replaces only the child launch boundary in workflow tests.
|
||||
#[cfg(test)]
|
||||
#[derive(Default)]
|
||||
pub(super) struct AuthAttemptFixture {
|
||||
pub(super) outcomes: std::collections::VecDeque<anyhow::Result<Credential>>,
|
||||
pub(super) observed: Vec<(String, bool, bool)>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct CleanAuthState {
|
||||
requested: bool,
|
||||
}
|
||||
|
||||
impl CleanAuthState {
|
||||
pub(super) fn new(requested: bool) -> Self {
|
||||
Self { requested }
|
||||
}
|
||||
|
||||
fn consume_for_webview(&mut self, webview_auth: bool) -> bool {
|
||||
if !webview_auth || !self.requested {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.requested = false;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectHandler<'_> {
|
||||
pub(super) fn prepare_cookie_from_stdin(&self) -> anyhow::Result<()> {
|
||||
if !self.args.cookie_on_stdin || self.cookie_from_stdin.borrow().is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let auth_result = self.read_auth_result_from_stdin()?;
|
||||
log_stdin_host_id(auth_result.host_id());
|
||||
self.apply_stdin_host_id(auth_result.host_id());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn obtain_credential_with_recovery(
|
||||
&self,
|
||||
mut response: Prelogin,
|
||||
server: &str,
|
||||
browser_allowed: bool,
|
||||
) -> anyhow::Result<(Prelogin, Credential)> {
|
||||
loop {
|
||||
self.check_cancelled()?;
|
||||
let result = self.obtain_credential(&response, server, browser_allowed).await;
|
||||
self.check_cancelled()?;
|
||||
match result {
|
||||
Ok(credential) => return Ok((response, credential)),
|
||||
Err(error) => {
|
||||
if !self.auth_recovery.borrow_mut().recover(&error) {
|
||||
return Err(self.auth_recovery.borrow().terminal(error));
|
||||
}
|
||||
log::warn!("Authenticator exited with a Wayland rendering error; retrying with DMABUF disabled");
|
||||
let refreshed = self
|
||||
.refresh_auth_prelogin(server, response.is_gateway(), browser_allowed)
|
||||
.await;
|
||||
response = refreshed.map_err(|error| self.auth_recovery.borrow().terminal(error))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn refresh_auth_prelogin(
|
||||
&self,
|
||||
server: &str,
|
||||
is_gateway: bool,
|
||||
browser_allowed: bool,
|
||||
) -> anyhow::Result<Prelogin> {
|
||||
let mut params = self.build_gp_params();
|
||||
params.set_is_gateway(is_gateway);
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.cancellation.cancelled() => Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||
result = gpapi::portal::prelogin(server, ¶ms, self.prelogin_options(browser_allowed)) => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn obtain_credential(
|
||||
&self,
|
||||
prelogin: &Prelogin,
|
||||
server: &str,
|
||||
gateway_browser_auth_allowed: bool,
|
||||
) -> anyhow::Result<Credential> {
|
||||
if should_read_stdin_credential(self.args.cookie_on_stdin, self.args.as_gateway, prelogin.is_gateway()) {
|
||||
return self.read_cookie_from_stdin();
|
||||
}
|
||||
|
||||
let is_gateway = prelogin.is_gateway();
|
||||
|
||||
match prelogin {
|
||||
Prelogin::Saml(prelogin) => {
|
||||
let external_browser_supported = can_use_external_browser_auth(
|
||||
prelogin.support_default_browser(),
|
||||
is_gateway,
|
||||
gateway_browser_auth_allowed,
|
||||
);
|
||||
let browser = if external_browser_supported {
|
||||
self.args.browser.as_deref()
|
||||
} else if !cfg!(feature = "webview-auth") {
|
||||
bail!(
|
||||
"The server does not support authentication via the default browser and the gpclient is not built with the `webview-auth` feature"
|
||||
);
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let verbose = self.shared_args.verbose.to_verbose_arg();
|
||||
let os_profile = self.os_profile.borrow().clone();
|
||||
let key_password = self.latest_key_password.borrow().clone();
|
||||
let auth_launcher = SamlAuthLauncher::new(server)
|
||||
.dmabuf_disabled(self.auth_recovery.borrow().dmabuf_disabled())
|
||||
.gateway(is_gateway)
|
||||
.saml_request(prelogin.saml_request())
|
||||
.os_profile(&os_profile)
|
||||
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
|
||||
.certificate(self.args.certificate.as_deref())
|
||||
.sslkey(self.args.sslkey.as_deref())
|
||||
.key_password(key_password.as_deref())
|
||||
.browser(browser)
|
||||
.browser_listen(self.args.browser_listen)
|
||||
.log_format(self.shared_args.log_format)
|
||||
.verbose(verbose);
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
let use_default_browser = external_browser_supported && self.args.default_browser;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
let browser_kind = if browser.is_some() || use_default_browser {
|
||||
"external"
|
||||
} else {
|
||||
"embedded"
|
||||
};
|
||||
#[cfg(not(feature = "webview-auth"))]
|
||||
let browser_kind = "external";
|
||||
|
||||
let clean_auth = self
|
||||
.clean_auth_state
|
||||
.borrow_mut()
|
||||
.consume_for_webview(browser_kind == "embedded");
|
||||
|
||||
info!(
|
||||
"SAML auth launch: gateway={}, clean={}, browser={}",
|
||||
is_gateway, clean_auth, browser_kind
|
||||
);
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
let auth_launcher = auth_launcher
|
||||
.hidpi(self.args.hidpi)
|
||||
.clean(clean_auth)
|
||||
.default_browser(use_default_browser);
|
||||
|
||||
#[cfg(test)]
|
||||
{
|
||||
let mut fixture = self.auth_attempt_fixture.borrow_mut();
|
||||
if let Some(outcome) = fixture.outcomes.pop_front() {
|
||||
fixture.observed.push((
|
||||
prelogin.saml_request().to_owned(),
|
||||
self.auth_recovery.borrow().dmabuf_disabled(),
|
||||
clean_auth,
|
||||
));
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
|
||||
let cred = auth_launcher.cancellation(&self.cancellation).launch().await?;
|
||||
self.check_cancelled()?;
|
||||
Ok(cred)
|
||||
}
|
||||
|
||||
Prelogin::Standard(prelogin) => {
|
||||
let prefix = if is_gateway { "Gateway" } else { "Portal" };
|
||||
println!("{} ({}: {})", prelogin.auth_message(), prefix, server);
|
||||
|
||||
let user = self.args.user.as_ref().map_or_else(
|
||||
|| Text::new(&format!("{}:", prelogin.label_username())).prompt(),
|
||||
|user| Ok(user.to_owned()),
|
||||
)?;
|
||||
|
||||
let password = self.obtain_password(prelogin)?;
|
||||
let password_cred = PasswordCredential::new(&user, &password);
|
||||
|
||||
Ok(password_cred.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_cookie_from_stdin(&self) -> anyhow::Result<Credential> {
|
||||
if let Some(cookie) = self.cookie_from_stdin.borrow().as_ref() {
|
||||
info!("Reusing the cookie read from standard input");
|
||||
return Credential::try_from(serde_json::from_str::<SamlAuthResult>(cookie)?);
|
||||
}
|
||||
|
||||
let auth_result = self.read_auth_result_from_stdin()?;
|
||||
log_stdin_host_id(auth_result.host_id());
|
||||
self.apply_stdin_host_id(auth_result.host_id());
|
||||
Credential::try_from(auth_result)
|
||||
}
|
||||
|
||||
fn read_auth_result_from_stdin(&self) -> anyhow::Result<SamlAuthResult> {
|
||||
info!("Reading cookie from standard input");
|
||||
|
||||
let mut cookie = String::new();
|
||||
std::io::stdin().read_line(&mut cookie)?;
|
||||
|
||||
self.cookie_from_stdin.replace(Some(cookie.trim_end().to_owned()));
|
||||
|
||||
let auth_result = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()).context("Failed to parse auth data")?;
|
||||
Ok(auth_result)
|
||||
}
|
||||
|
||||
fn obtain_password(&self, prelogin: &StandardPrelogin) -> anyhow::Result<String> {
|
||||
let password = if self.args.passwd_on_stdin {
|
||||
if let Some(password) = self.password_from_stdin.borrow().as_ref() {
|
||||
info!("Reusing the password read from standard input");
|
||||
return Ok(password.clone());
|
||||
}
|
||||
|
||||
info!("Reading password from standard input");
|
||||
let mut input = String::new();
|
||||
std::io::stdin().read_line(&mut input)?;
|
||||
let password = input.trim_end().to_owned();
|
||||
self.password_from_stdin.replace(Some(password.clone()));
|
||||
|
||||
password
|
||||
} else {
|
||||
Password::new(&format!("{}:", prelogin.label_password()))
|
||||
.without_confirmation()
|
||||
.with_display_mode(PasswordDisplayMode::Masked)
|
||||
.prompt()?
|
||||
};
|
||||
|
||||
Ok(password)
|
||||
}
|
||||
}
|
||||
|
||||
fn should_read_stdin_credential(cookie_on_stdin: bool, as_gateway: bool, prelogin_is_gateway: bool) -> bool {
|
||||
cookie_on_stdin && (!prelogin_is_gateway || as_gateway)
|
||||
}
|
||||
|
||||
fn can_use_external_browser_auth(
|
||||
saml_support_default_browser: bool,
|
||||
is_gateway: bool,
|
||||
gateway_browser_auth_allowed: bool,
|
||||
) -> bool {
|
||||
saml_support_default_browser && (!is_gateway || gateway_browser_auth_allowed)
|
||||
}
|
||||
|
||||
fn log_stdin_host_id(host_id: Option<&str>) {
|
||||
match host_id {
|
||||
Some(host_id) => info!("stdin auth result host-id: {}", host_id),
|
||||
None => info!("stdin auth result host-id: <none>"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn clean_auth_state_is_consumed_once_for_webview() {
|
||||
let mut state = CleanAuthState::new(true);
|
||||
|
||||
assert!(state.consume_for_webview(true));
|
||||
assert!(!state.consume_for_webview(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_auth_state_is_not_consumed_by_external_browser() {
|
||||
let mut state = CleanAuthState::new(true);
|
||||
|
||||
assert!(!state.consume_for_webview(false));
|
||||
assert!(state.consume_for_webview(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_auth_state_remains_false_when_not_requested() {
|
||||
let mut state = CleanAuthState::new(false);
|
||||
|
||||
assert!(!state.consume_for_webview(true));
|
||||
assert!(!state.consume_for_webview(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_credential_is_allowed_for_portal_auth() {
|
||||
assert!(should_read_stdin_credential(true, false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_credential_is_allowed_for_direct_gateway_auth() {
|
||||
assert!(should_read_stdin_credential(true, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_credential_is_not_reused_for_gateway_fallback_auth() {
|
||||
assert!(!should_read_stdin_credential(true, false, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_credential_is_not_used_when_flag_is_disabled() {
|
||||
assert!(!should_read_stdin_credential(false, false, false));
|
||||
assert!(!should_read_stdin_credential(false, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portal_saml_can_use_default_browser_when_supported() {
|
||||
assert!(can_use_external_browser_auth(true, false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gateway_saml_requires_gateway_browser_auth_allowance() {
|
||||
assert!(!can_use_external_browser_auth(true, true, false));
|
||||
assert!(can_use_external_browser_auth(true, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_browser_auth_requires_saml_support() {
|
||||
assert!(!can_use_external_browser_auth(false, false, true));
|
||||
assert!(!can_use_external_browser_auth(false, true, true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,513 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Parser;
|
||||
use gpapi::{
|
||||
cookie_store::{self, StoredCookie},
|
||||
credential::AuthCookieCredential,
|
||||
gateway::{Gateway, GatewayLoginContext, GatewaySelection},
|
||||
log_format::LogFormat,
|
||||
session::SessionMode,
|
||||
};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use super::{ConnectArgs, ConnectHandler};
|
||||
use crate::cli::SharedArgs;
|
||||
|
||||
#[derive(Parser)]
|
||||
struct TestArgs {
|
||||
#[command(flatten)]
|
||||
connect: ConnectArgs,
|
||||
}
|
||||
|
||||
fn login_response() -> String {
|
||||
let mut fields = [""; 20];
|
||||
fields[1] = "issued-cookie";
|
||||
fields[3] = "gateway";
|
||||
fields[4] = "alice";
|
||||
fields[5] = "fixture-auth";
|
||||
fields[6] = "vsys1";
|
||||
fields[12] = "tunnel";
|
||||
format!(
|
||||
"<jnlp><application-desc>{}</application-desc></jnlp>",
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| format!("<argument>{field}</argument>"))
|
||||
.collect::<String>()
|
||||
)
|
||||
}
|
||||
|
||||
async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let worker = tokio::spawn(async move {
|
||||
tokio::time::timeout(Duration::from_secs(5), async move {
|
||||
let mut requests = Vec::new();
|
||||
for (status, body) in responses {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0; 4096];
|
||||
let count = stream.read(&mut buf).await.unwrap();
|
||||
assert_ne!(count, 0, "Request ended before its body");
|
||||
request.extend_from_slice(&buf[..count]);
|
||||
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||
.unwrap_or(0);
|
||||
if request.len() >= end + 4 + length {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
requests.push(String::from_utf8(request).unwrap());
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
requests
|
||||
})
|
||||
.await
|
||||
.expect("Gateway fixture timed out")
|
||||
});
|
||||
(origin, worker)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
|
||||
let (gateway, worker) = gateway(vec![("200 OK", login_response())]).await;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let cache = directory.path().join("cookie.json");
|
||||
let args = TestArgs::parse_from([
|
||||
"test",
|
||||
"http://unavailable-portal.invalid",
|
||||
"--cookie-only",
|
||||
"--cookie-cache",
|
||||
cache.to_str().unwrap(),
|
||||
])
|
||||
.connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
cookie_store::save(
|
||||
&cache,
|
||||
&StoredCookie::new(
|
||||
args.server.clone(),
|
||||
"alice".into(),
|
||||
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||
gateway,
|
||||
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
handler.handle_impl().await.unwrap();
|
||||
let requests = worker.await.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert!(requests[0].starts_with("POST /ssl-vpn/login.esp "));
|
||||
assert!(requests[0].contains("portal-cookie"));
|
||||
assert_eq!(
|
||||
handler.sessions.borrow().members()[0].transport.authentication().mode(),
|
||||
SessionMode::Tunnel
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
|
||||
let (origin, worker) = gateway(vec![
|
||||
(
|
||||
"200 OK",
|
||||
"<prelogin-response><status>Success</status></prelogin-response>".into(),
|
||||
),
|
||||
("403 Forbidden", "<response><error>rejected</error></response>".into()),
|
||||
("200 OK", login_response()),
|
||||
])
|
||||
.await;
|
||||
let args = TestArgs::parse_from(["test", &origin, "--user", "alice", "--passwd-on-stdin"]).connect;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
handler.password_from_stdin.replace(Some("gateway-password".into()));
|
||||
let mut value = serde_json::to_value(Gateway::new("internal".into(), origin.clone())).unwrap();
|
||||
value["kind"] = serde_json::json!("internal");
|
||||
let gateway: Gateway = serde_json::from_value(value).unwrap();
|
||||
let session = handler
|
||||
.authenticate_gateway(
|
||||
&origin,
|
||||
&origin,
|
||||
&AuthCookieCredential::new("alice", "rejected-cookie", ""),
|
||||
false,
|
||||
GatewayLoginContext::new(&gateway, GatewaySelection::Auto),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(session.authentication.mode(), SessionMode::Tunnel);
|
||||
assert!(session.extension_auth.binding().is_none());
|
||||
let requests = worker.await.unwrap();
|
||||
assert_eq!(requests.len(), 3);
|
||||
assert!(requests[1].contains("rejected-cookie"));
|
||||
assert!(requests[2].contains("gateway-password"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rendering_recovery_fetches_new_prelogin_metadata_and_preserves_gateway_mode() {
|
||||
let (origin, worker) = gateway(vec![
|
||||
(
|
||||
"200 OK",
|
||||
"<prelogin-response><status>Success</status><region>old</region></prelogin-response>".into(),
|
||||
),
|
||||
(
|
||||
"200 OK",
|
||||
"<prelogin-response><status>Success</status><region>replacement</region></prelogin-response>".into(),
|
||||
),
|
||||
])
|
||||
.await;
|
||||
let args = TestArgs::parse_from(["test", &origin]).connect;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
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);
|
||||
let original = handler.refresh_auth_prelogin(&origin, true, true).await.unwrap();
|
||||
let replacement = handler
|
||||
.refresh_auth_prelogin(&origin, original.is_gateway(), true)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(original.region(), "old");
|
||||
assert_eq!(replacement.region(), "replacement");
|
||||
assert!(replacement.is_gateway());
|
||||
let requests = worker.await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert!(
|
||||
requests
|
||||
.iter()
|
||||
.all(|request| request.starts_with("POST /ssl-vpn/prelogin.esp"))
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[tokio::test]
|
||||
async fn cancellation_during_recovery_prelogin_stops_request() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let args = TestArgs::parse_from(["test", &origin]).connect;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
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);
|
||||
handler
|
||||
.auth_attempt_fixture
|
||||
.borrow_mut()
|
||||
.outcomes
|
||||
.push_back(Err(rendering_crash()));
|
||||
let (result, ()) = tokio::time::timeout(Duration::from_secs(3), async {
|
||||
tokio::join!(
|
||||
async {
|
||||
let original = handler.refresh_auth_prelogin(&origin, false, false).await?;
|
||||
handler.obtain_credential_with_recovery(original, &origin, false).await
|
||||
},
|
||||
async {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut byte = [0];
|
||||
socket.read_exact(&mut byte).await.unwrap();
|
||||
handler.cancellation.cancel();
|
||||
}
|
||||
)
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.downcast_ref::<gpapi::auth::AuthenticationCancelled>()
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
fn rendering_crash() -> anyhow::Error {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
gpapi::process::rendering_recovery::RenderingCrash {
|
||||
status: std::process::ExitStatus::from_raw(71 << 8),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
fn saml_prelogin_response(region: &str, encoded_request: &str) -> String {
|
||||
format!(
|
||||
"<prelogin-response><status>Success</status><region>{region}</region><saml-auth-method>POST</saml-auth-method><saml-request>{encoded_request}</saml-request></prelogin-response>"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[tokio::test]
|
||||
async fn auth_crash_uses_fresh_saml_and_clean_once_with_shared_budget() {
|
||||
use gpapi::credential::{Credential, PreloginCredential};
|
||||
let (origin, worker) = gateway(vec![
|
||||
("200 OK", saml_prelogin_response("old-region", "b2xk")),
|
||||
("200 OK", saml_prelogin_response("new-region", "bmV3")),
|
||||
("200 OK", saml_prelogin_response("gateway-region", "Z2F0ZXdheQ==")),
|
||||
])
|
||||
.await;
|
||||
let args = TestArgs::parse_from(["test", &origin, "--clean"]).connect;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
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);
|
||||
handler.auth_attempt_fixture.borrow_mut().outcomes.extend([
|
||||
Err(rendering_crash()),
|
||||
Ok(Credential::Prelogin(PreloginCredential::new(
|
||||
"alice",
|
||||
Some("new-cookie"),
|
||||
None,
|
||||
None,
|
||||
))),
|
||||
Err(rendering_crash()),
|
||||
]);
|
||||
let original = handler.refresh_auth_prelogin(&origin, false, false).await.unwrap();
|
||||
let (replacement, credential) = handler
|
||||
.obtain_credential_with_recovery(original, &origin, false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(replacement.region(), "new-region");
|
||||
assert_eq!(credential.username(), "alice");
|
||||
assert!(matches!(credential, Credential::Prelogin(ref value) if value.prelogin_cookie() == Some("new-cookie")));
|
||||
let gateway_prelogin = handler.refresh_auth_prelogin(&origin, true, false).await.unwrap();
|
||||
let error = handler
|
||||
.obtain_credential_with_recovery(gateway_prelogin, &origin, false)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
);
|
||||
assert_eq!(
|
||||
handler.auth_attempt_fixture.borrow().observed,
|
||||
[
|
||||
("old".into(), false, true),
|
||||
("new".into(), true, false),
|
||||
("gateway".into(), true, false),
|
||||
]
|
||||
);
|
||||
assert_eq!(worker.await.unwrap().len(), 3);
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[tokio::test]
|
||||
async fn exhausted_auth_recovery_is_terminal_before_portal_gateway_fallback() {
|
||||
let (origin, worker) = gateway(vec![
|
||||
("200 OK", saml_prelogin_response("old-region", "b2xk")),
|
||||
("200 OK", saml_prelogin_response("new-region", "bmV3")),
|
||||
])
|
||||
.await;
|
||||
let args = TestArgs::parse_from(["test", &origin, "--clean"]).connect;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
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);
|
||||
handler.auth_attempt_fixture.borrow_mut().outcomes.extend([
|
||||
Err(rendering_crash()),
|
||||
Err(anyhow::anyhow!(gpapi::error::PortalError::PreloginError(
|
||||
"second failure".into()
|
||||
))),
|
||||
]);
|
||||
let error = handler.handle_impl().await.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
);
|
||||
assert_eq!(handler.auth_attempt_fixture.borrow().observed.len(), 2);
|
||||
assert_eq!(worker.await.unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
feature = "webview-auth",
|
||||
any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")
|
||||
))]
|
||||
mod gtk_retry {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn real_gtk_crash_retries_bundled_authenticator() {
|
||||
// Environment overrides belong to a separate test process, never the parallel test runner.
|
||||
if let Some(directory) = std::env::var_os("GP_TEST_GTK_AUTH_DIR") {
|
||||
verify_real_authenticator_retry(std::path::Path::new(&directory)).await;
|
||||
} else {
|
||||
run_real_authenticator_retry(false);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
#[ignore = "requires non-interactive sudo authorization and a running Wayland desktop session"]
|
||||
fn sudo_gtk_crash_retries_after_restoring_desktop_environment() {
|
||||
run_real_authenticator_retry(true);
|
||||
}
|
||||
|
||||
fn run_real_authenticator_retry(sudo: bool) {
|
||||
use std::{fs, os::unix::fs::PermissionsExt, process::Command};
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let executable = directory.path().join("gpauth");
|
||||
// Fixtures contain only dummy data and must remain accessible after a root test drops privileges.
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let attempts_path = directory.path().join("attempts");
|
||||
fs::write(&attempts_path, "").unwrap();
|
||||
fs::set_permissions(&attempts_path, fs::Permissions::from_mode(0o666)).unwrap();
|
||||
fs::write(&executable, r#"#!/bin/sh
|
||||
set -eu
|
||||
request=
|
||||
while [ "$#" -gt 0 ]; do
|
||||
if [ "$1" = '--saml-request' ]; then
|
||||
shift
|
||||
request=$1
|
||||
fi
|
||||
shift
|
||||
done
|
||||
printf '%s|%s|%s|%s\n' "$(id -u)" "${WAYLAND_DISPLAY:-}" "${WEBKIT_DISABLE_DMABUF_RENDERER-unset}" "$request" >> "$GP_TEST_GTK_AUTH_DIR/attempts"
|
||||
if [ "$request" = 'old' ]; then
|
||||
printf 'Gdk-Message: 10:49:22.617: Error 71 (Protocol error) dispatching to Wayland display.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
[ "$request" = 'new' ] && [ "${WEBKIT_DISABLE_DMABUF_RENDERER:-}" = '1' ] || exit 2
|
||||
printf '%s\n' '{"success":{"username":"alice","preloginCookie":"new-cookie"}}'
|
||||
"#).unwrap();
|
||||
fs::set_permissions(&executable, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let mut command = if sudo {
|
||||
assert_ne!(
|
||||
uzers::get_effective_uid(),
|
||||
0,
|
||||
"run this test as the Wayland desktop user"
|
||||
);
|
||||
let mut command = Command::new("sudo");
|
||||
command.args([
|
||||
"-n",
|
||||
"env",
|
||||
"-u",
|
||||
"WAYLAND_DISPLAY",
|
||||
"-u",
|
||||
"DISPLAY",
|
||||
"-u",
|
||||
"XDG_SESSION_TYPE",
|
||||
"-u",
|
||||
"WEBKIT_DISABLE_DMABUF_RENDERER",
|
||||
]);
|
||||
command.arg("GP_TEST_EXPECT_ROOT=1");
|
||||
command
|
||||
} else {
|
||||
let mut command = Command::new("env");
|
||||
command.arg("-u").arg("WEBKIT_DISABLE_DMABUF_RENDERER");
|
||||
command.arg("WAYLAND_DISPLAY=wayland-test");
|
||||
command
|
||||
};
|
||||
command.arg(format!("GP_AUTH_BINARY={}", executable.display()));
|
||||
command.arg(format!("GP_TEST_GTK_AUTH_DIR={}", directory.path().display()));
|
||||
command.arg(std::env::current_exe().unwrap()).args([
|
||||
"--exact",
|
||||
"connect::flow_tests::gtk_retry::real_gtk_crash_retries_bundled_authenticator",
|
||||
"--nocapture",
|
||||
]);
|
||||
let output = command.output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"retry subprocess failed: {}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let expected_uid = gpapi::process::users::get_non_root_user().unwrap().uid().to_string();
|
||||
let attempts = fs::read_to_string(attempts_path).unwrap();
|
||||
let attempts: Vec<Vec<&str>> = attempts.lines().map(|line| line.split('|').collect()).collect();
|
||||
assert_eq!(attempts.len(), 2, "expected exactly one retry");
|
||||
for attempt in &attempts {
|
||||
assert_eq!(attempt[0], expected_uid, "authenticator must run as the desktop user");
|
||||
assert!(!attempt[1].is_empty(), "authenticator must receive WAYLAND_DISPLAY");
|
||||
}
|
||||
assert_eq!(&attempts[0][2..], ["unset", "old"]);
|
||||
assert_eq!(&attempts[1][2..], ["1", "new"]);
|
||||
}
|
||||
|
||||
async fn verify_real_authenticator_retry(directory: &std::path::Path) {
|
||||
use gpapi::credential::Credential;
|
||||
|
||||
if std::env::var_os("GP_TEST_EXPECT_ROOT").is_some() {
|
||||
assert_eq!(uzers::get_effective_uid(), 0);
|
||||
assert!(std::env::var_os("SUDO_UID").is_some());
|
||||
assert!(std::env::var_os("WAYLAND_DISPLAY").is_none());
|
||||
}
|
||||
let (origin, worker) = gateway(vec![
|
||||
("200 OK", saml_prelogin_response("old-region", "b2xk")),
|
||||
("200 OK", saml_prelogin_response("new-region", "bmV3")),
|
||||
])
|
||||
.await;
|
||||
let args = TestArgs::parse_from(["test", &origin]).connect;
|
||||
let lock = directory.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);
|
||||
let original = handler.refresh_auth_prelogin(&origin, false, false).await.unwrap();
|
||||
let (replacement, credential) = handler
|
||||
.obtain_credential_with_recovery(original, &origin, false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(replacement.region(), "new-region");
|
||||
assert!(matches!(credential, Credential::Prelogin(ref value) if value.prelogin_cookie() == Some("new-cookie")));
|
||||
assert_eq!(
|
||||
worker.await.unwrap().len(),
|
||||
2,
|
||||
"recovery must fetch fresh prelogin data"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,833 @@
|
||||
use std::{
|
||||
fs,
|
||||
path::Path,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use gpapi::{
|
||||
clap::report,
|
||||
cookie_store,
|
||||
credential::{AuthCookieCredential, Credential},
|
||||
gateway::{Gateway, GatewayLogin, GatewayLoginClient, GatewayLoginContext, GatewaySelection, SessionExtensionAuth},
|
||||
gp_params::GpParams,
|
||||
os_profile::OsProfile,
|
||||
portal::{PortalConfig, prelogin},
|
||||
process::users::get_user_by_name,
|
||||
session::{GatewayAuthentication, SessionMode},
|
||||
};
|
||||
use inquire::Text;
|
||||
use log::{Level, info, warn};
|
||||
use openconnect::{HipScript, HipSource, VpnBuilder};
|
||||
use tokio::{runtime::Handle, task::JoinHandle};
|
||||
|
||||
use crate::session::{
|
||||
SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info,
|
||||
};
|
||||
|
||||
use super::{ConnectHandler, args::cookie_cache_path, vpn_script};
|
||||
|
||||
const OPENCONNECT_INTERRUPTED_EXIT_CODE: i32 = -4;
|
||||
|
||||
pub(super) struct GatewayLoginSession {
|
||||
pub(super) authentication: GatewayAuthentication,
|
||||
pub(super) extension_auth: SessionExtensionAuth,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum GatewayConnectFailureStage {
|
||||
BeforeEstablishment,
|
||||
AfterEstablishment,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct GatewayConnectError {
|
||||
stage: GatewayConnectFailureStage,
|
||||
error: anyhow::Error,
|
||||
}
|
||||
|
||||
impl GatewayConnectError {
|
||||
fn before_establishment(error: anyhow::Error) -> Self {
|
||||
Self {
|
||||
stage: GatewayConnectFailureStage::BeforeEstablishment,
|
||||
error,
|
||||
}
|
||||
}
|
||||
|
||||
fn after_establishment(error: anyhow::Error) -> Self {
|
||||
Self {
|
||||
stage: GatewayConnectFailureStage::AfterEstablishment,
|
||||
error,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn is_before_establishment(&self) -> bool {
|
||||
self.stage == GatewayConnectFailureStage::BeforeEstablishment
|
||||
}
|
||||
|
||||
pub(super) fn as_error(&self) -> &anyhow::Error {
|
||||
&self.error
|
||||
}
|
||||
|
||||
pub(super) fn into_error(self) -> anyhow::Error {
|
||||
self.error
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectHandler<'_> {
|
||||
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<anyhow::Result<()>> {
|
||||
let path = cookie_cache_path(self.args)?;
|
||||
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
|
||||
let stored = cookie_store::load(&path, server, &host_id)?;
|
||||
if !stored.auth_cookie.can_authenticate_gateway() {
|
||||
cookie_store::clear(&path);
|
||||
return None;
|
||||
}
|
||||
let credential = (&stored.auth_cookie).into();
|
||||
let mut params = self.build_gp_params();
|
||||
params.set_is_gateway(true);
|
||||
let session = match self
|
||||
.login_gateway(&stored.last_gateway, &credential, ¶ms, None)
|
||||
.await
|
||||
{
|
||||
Ok(session) => session,
|
||||
Err(error) => {
|
||||
if self.cancellation.is_cancelled()
|
||||
|| error
|
||||
.downcast_ref::<gpapi::gateway::GatewayLoginProtocolError>()
|
||||
.is_some()
|
||||
{
|
||||
return Some(Err(error));
|
||||
}
|
||||
cookie_store::clear(&path);
|
||||
warn!("Cached gateway authentication failed: {error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if session.authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only {
|
||||
self.logout_gateway(&stored.last_gateway).await;
|
||||
info!("Cached non-tunnel login requires fresh portal discovery");
|
||||
return None;
|
||||
}
|
||||
let result = self
|
||||
.connect_gateway(
|
||||
server,
|
||||
&stored.last_gateway,
|
||||
&session.authentication,
|
||||
false,
|
||||
session.extension_auth,
|
||||
)
|
||||
.await;
|
||||
match result {
|
||||
Ok(()) => Some(Ok(())),
|
||||
Err(error) if self.cancellation.is_cancelled() => Some(Err(error.into_error())),
|
||||
Err(error) => {
|
||||
self.logout_gateway(&stored.last_gateway).await;
|
||||
warn!("Cached gateway connection failed: {}", error.as_error());
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cached_portal_credential(&self, server: &str) -> Option<Credential> {
|
||||
if self.args.cookie_on_stdin {
|
||||
return None;
|
||||
}
|
||||
let path = cookie_cache_path(self.args)?;
|
||||
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
|
||||
let stored = cookie_store::load(&path, server, &host_id)?;
|
||||
if !stored.auth_cookie.can_authenticate_gateway() {
|
||||
cookie_store::clear(&path);
|
||||
return None;
|
||||
}
|
||||
info!("Using cached credential for fresh portal discovery");
|
||||
Some((&stored.auth_cookie).into())
|
||||
}
|
||||
|
||||
pub(super) fn clear_cookie_cache(&self) {
|
||||
if let Some(path) = cookie_cache_path(self.args) {
|
||||
cookie_store::clear(&path);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn connect_gateway_with_prelogin(
|
||||
&self,
|
||||
portal: &str,
|
||||
gateway: &str,
|
||||
allow_extend_session: bool,
|
||||
gateway_context: Option<GatewayLoginContext>,
|
||||
) -> anyhow::Result<()> {
|
||||
info!("Performing the gateway authentication...");
|
||||
|
||||
let mut gp_params = self.build_gp_params();
|
||||
gp_params.set_is_gateway(true);
|
||||
|
||||
let gateway_browser_auth_allowed = true;
|
||||
let prelogin = tokio::select! {
|
||||
biased;
|
||||
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||
result = prelogin(gateway, &gp_params, self.direct_gateway_prelogin_options()) => result?,
|
||||
};
|
||||
let (_, cred) = self
|
||||
.obtain_credential_with_recovery(prelogin, gateway, gateway_browser_auth_allowed)
|
||||
.await?;
|
||||
|
||||
let login_session = self
|
||||
.login_gateway(gateway, &cred, &gp_params, gateway_context.as_ref())
|
||||
.await?;
|
||||
|
||||
self
|
||||
.connect_gateway(
|
||||
portal,
|
||||
gateway,
|
||||
&login_session.authentication,
|
||||
allow_extend_session,
|
||||
login_session.extension_auth,
|
||||
)
|
||||
.await
|
||||
.map_err(GatewayConnectError::into_error)
|
||||
}
|
||||
|
||||
pub(super) async fn connect_gateway_with_fallback(
|
||||
&self,
|
||||
portal: &str,
|
||||
gateway: &Gateway,
|
||||
portal_cred: &AuthCookieCredential,
|
||||
config: &PortalConfig,
|
||||
selection: GatewaySelection,
|
||||
remaining: &[&Gateway],
|
||||
) -> Result<(), GatewayConnectError> {
|
||||
let session = self
|
||||
.authenticate_gateway(
|
||||
portal,
|
||||
gateway.server(),
|
||||
portal_cred,
|
||||
config.default_browser().unwrap_or(false),
|
||||
GatewayLoginContext::new(gateway, selection).with_connect_method(config.connect_method()),
|
||||
)
|
||||
.await
|
||||
.map_err(GatewayConnectError::before_establishment)?;
|
||||
if !self.args.cookie_only && session.authentication.mode() == SessionMode::NonTunnel {
|
||||
if gateway.kind() != gpapi::gateway::GatewayKind::Internal {
|
||||
return Err(GatewayConnectError::after_establishment(anyhow::anyhow!(
|
||||
"Non-tunnel authentication requires freshly discovered internal gateways"
|
||||
)));
|
||||
}
|
||||
return self
|
||||
.connect_internal_gateways(portal, config, portal_cred, gateway, session, remaining)
|
||||
.await
|
||||
.map_err(GatewayConnectError::after_establishment);
|
||||
}
|
||||
self
|
||||
.connect_gateway(
|
||||
portal,
|
||||
gateway.server(),
|
||||
&session.authentication,
|
||||
config.allow_extend_session().unwrap_or(false),
|
||||
session.extension_auth,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn authenticate_gateway(
|
||||
&self,
|
||||
portal: &str,
|
||||
gateway: &str,
|
||||
portal_cred: &AuthCookieCredential,
|
||||
portal_config_default_browser: bool,
|
||||
gateway_context: GatewayLoginContext,
|
||||
) -> anyhow::Result<GatewayLoginSession> {
|
||||
self.check_cancelled()?;
|
||||
let mut gp_params = self.build_gp_params();
|
||||
gp_params.set_is_gateway(true);
|
||||
let browser_allowed = self.gateway_browser_auth_allowed(portal_config_default_browser);
|
||||
let gateway_prelogin = tokio::select! {
|
||||
biased;
|
||||
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||
result = prelogin(gateway, &gp_params, self.prelogin_options(browser_allowed)) => result?,
|
||||
};
|
||||
self.check_cancelled()?;
|
||||
|
||||
if portal_cred.can_authenticate_gateway() {
|
||||
let credential: Credential = portal_cred.into();
|
||||
match self
|
||||
.login_gateway(gateway, &credential, &gp_params, Some(&gateway_context))
|
||||
.await
|
||||
{
|
||||
Ok(session) => {
|
||||
self.save_cookie_cache(portal, gateway, portal_cred);
|
||||
return Ok(session);
|
||||
}
|
||||
Err(error) => {
|
||||
self.check_cancelled()?;
|
||||
let error = self.auth_recovery.borrow().terminal(error);
|
||||
if error
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
{
|
||||
return Err(error);
|
||||
}
|
||||
if error
|
||||
.downcast_ref::<gpapi::gateway::GatewayLoginProtocolError>()
|
||||
.is_some()
|
||||
{
|
||||
return Err(error);
|
||||
}
|
||||
info!("Portal cookie login failed; using gateway prelogin authentication: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (_, credential) = self
|
||||
.obtain_credential_with_recovery(gateway_prelogin, gateway, browser_allowed)
|
||||
.await
|
||||
.inspect_err(|_| self.print_direct_gateway_recommendation(gateway))?;
|
||||
self.check_cancelled()?;
|
||||
let result = self
|
||||
.login_gateway(gateway, &credential, &gp_params, Some(&gateway_context))
|
||||
.await;
|
||||
if result.is_err() {
|
||||
self.print_direct_gateway_recommendation(gateway);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn save_cookie_cache(&self, portal: &str, gateway: &str, auth_cookie: &AuthCookieCredential) {
|
||||
let Some(path) = cookie_cache_path(self.args) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if !auth_cookie.can_authenticate_gateway() {
|
||||
return;
|
||||
}
|
||||
|
||||
let stored = cookie_store::StoredCookie::new(
|
||||
portal.to_string(),
|
||||
auth_cookie.username().to_string(),
|
||||
self.os_profile.borrow().host_identity().host_id().to_string(),
|
||||
gateway.to_string(),
|
||||
auth_cookie.clone(),
|
||||
);
|
||||
|
||||
match cookie_store::save(&path, &stored) {
|
||||
Ok(()) => info!("Saved portal cookie cache to {}", path.display()),
|
||||
Err(err) => warn!("Failed to save portal cookie cache to {}: {}", path.display(), err),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_direct_gateway_recommendation(&self, gateway: &str) {
|
||||
if !self.args.cookie_on_stdin {
|
||||
return;
|
||||
}
|
||||
|
||||
let format = self.shared_args.log_format;
|
||||
report(
|
||||
format,
|
||||
Level::Warn,
|
||||
"\nNOTE: Gateway authentication failed after portal login.",
|
||||
);
|
||||
report(
|
||||
format,
|
||||
Level::Warn,
|
||||
"NOTE: If this server also accepts direct gateway login, try:",
|
||||
);
|
||||
report(
|
||||
format,
|
||||
Level::Warn,
|
||||
&format!("NOTE: {}", direct_gateway_command(gateway)),
|
||||
);
|
||||
}
|
||||
|
||||
async fn login_gateway(
|
||||
&self,
|
||||
gateway: &str,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
gateway_context: Option<&GatewayLoginContext>,
|
||||
) -> anyhow::Result<GatewayLoginSession> {
|
||||
let mut gp_params = gp_params.clone();
|
||||
gp_params.prepare_client_identity()?;
|
||||
let cancellation = self.cancellation.clone();
|
||||
let internal = gateway_context.is_some_and(|context| context.kind() == gpapi::gateway::GatewayKind::Internal);
|
||||
let mut client = GatewayLoginClient::new(gateway, gp_params)?;
|
||||
|
||||
loop {
|
||||
self.check_cancelled()?;
|
||||
let login = client.login(cred, gateway_context, &cancellation).await?;
|
||||
|
||||
match login {
|
||||
GatewayLogin::Authenticated(authentication) => {
|
||||
let descriptor = Gateway::new(gateway.to_string(), gateway.to_string());
|
||||
self
|
||||
.sessions
|
||||
.borrow_mut()
|
||||
.register_login(descriptor.clone(), authentication.clone(), &client);
|
||||
self.check_cancelled()?;
|
||||
let binding = if internal && authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only {
|
||||
Some(
|
||||
self
|
||||
.sessions
|
||||
.borrow_mut()
|
||||
.bind_non_tunnel(&descriptor, &client, self.args.disable_ipv6, None, &cancellation)
|
||||
.await
|
||||
.map_err(|error| error.context(gpapi::gateway::GatewayLoginProtocolError))?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
return Ok(GatewayLoginSession {
|
||||
authentication,
|
||||
extension_auth: SessionExtensionAuth::new(cred.clone(), client).with_binding(binding),
|
||||
});
|
||||
}
|
||||
GatewayLogin::Mfa(message, input_str) => {
|
||||
let otp = Text::new(&message).prompt()?;
|
||||
client.respond_mfa(&input_str, &otp);
|
||||
|
||||
info!("Retrying gateway login with MFA...");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn connect_gateway(
|
||||
&self,
|
||||
portal: &str,
|
||||
gateway: &str,
|
||||
authentication: &GatewayAuthentication,
|
||||
allow_extend_session: bool,
|
||||
extension_auth: SessionExtensionAuth,
|
||||
) -> Result<(), GatewayConnectError> {
|
||||
let cookie = authentication.cookie();
|
||||
// --cookie-only: print the gateway cookie and exit without opening a tunnel.
|
||||
// No tun device is allocated, no root is required, and no logout is issued
|
||||
// against the gateway — the cookie remains valid for subsequent use.
|
||||
// Output format matches openconnect --authenticate for easy shell consumption.
|
||||
if self.args.cookie_only {
|
||||
println!("COOKIE='{}'", cookie);
|
||||
println!("HOST='{}'", gateway);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if authentication.mode() != SessionMode::Tunnel {
|
||||
return Err(GatewayConnectError::after_establishment(anyhow::anyhow!(
|
||||
"Non-tunnel authentication requires fresh internal portal discovery"
|
||||
)));
|
||||
}
|
||||
self
|
||||
.check_cancelled()
|
||||
.map_err(GatewayConnectError::after_establishment)?;
|
||||
let identity_files = extension_auth
|
||||
.client_identity()
|
||||
.map(|identity| identity.write_files(None))
|
||||
.transpose()
|
||||
.map_err(GatewayConnectError::before_establishment)?;
|
||||
let certificate = identity_files.as_ref().map(|files| files.certificate().to_owned());
|
||||
let sslkey = identity_files.as_ref().and_then(|files| files.key().map(str::to_owned));
|
||||
let key_password = extension_auth
|
||||
.client_identity()
|
||||
.and_then(|identity| identity.key_password())
|
||||
.map(str::to_owned);
|
||||
let mtu = self.args.mtu.unwrap_or(0);
|
||||
let os_profile = self.os_profile.borrow().clone();
|
||||
let hip_source = self
|
||||
.hip_source(os_profile.clone())
|
||||
.map_err(GatewayConnectError::before_establishment)?;
|
||||
|
||||
let session_ctx = build_session_context(SessionContextInput {
|
||||
portal: portal.to_string(),
|
||||
gateway: gateway.to_string(),
|
||||
cookie: cookie.to_string(),
|
||||
os_profile: os_profile.clone(),
|
||||
certificate: certificate.clone(),
|
||||
sslkey: sslkey.clone(),
|
||||
key_password: key_password.clone(),
|
||||
disable_ipv6: self.args.disable_ipv6,
|
||||
extension_auth: Some(extension_auth),
|
||||
});
|
||||
let vpn_builder = vpn_script::builder(gateway, cookie, self.args)
|
||||
.interface(self.args.interface.clone())
|
||||
.certificate(certificate)
|
||||
.sslkey(sslkey)
|
||||
.key_password(key_password)
|
||||
.hip_source(hip_source)
|
||||
.reconnect_timeout(self.args.reconnect_timeout)
|
||||
.mtu(mtu)
|
||||
.disable_ipv6(self.args.disable_ipv6)
|
||||
.gateway_ip_preference(match self.args.ip_preference {
|
||||
gpapi::gateway::GatewayIpPreference::Auto => openconnect::GatewayIpPreference::Auto,
|
||||
gpapi::gateway::GatewayIpPreference::Ipv4 => openconnect::GatewayIpPreference::Ipv4,
|
||||
gpapi::gateway::GatewayIpPreference::Ipv6 => openconnect::GatewayIpPreference::Ipv6,
|
||||
})
|
||||
.no_dtls(self.args.no_dtls)
|
||||
.local_hostname(self.args.local_hostname.clone())
|
||||
.dpd_interval(self.args.dpd_interval.unwrap_or(0))
|
||||
.no_xmlpost(self.args.no_xmlpost);
|
||||
let vpn = apply_os_profile(vpn_builder, &os_profile)
|
||||
.build()
|
||||
.map_err(|err| GatewayConnectError::before_establishment(err.into()))?;
|
||||
|
||||
let vpn = Arc::new(vpn);
|
||||
let vpn_clone = vpn.clone();
|
||||
let runtime_handle = Handle::current();
|
||||
let session_ctx = Arc::new(Mutex::new(Some(session_ctx)));
|
||||
let session_task: Arc<Mutex<Option<JoinHandle<()>>>> = Arc::new(Mutex::new(None));
|
||||
let session_task_on_connect = Arc::clone(&session_task);
|
||||
let session_ctx_on_connect = Arc::clone(&session_ctx);
|
||||
let tunnel_established = Arc::new(AtomicBool::new(false));
|
||||
let tunnel_established_on_connect = Arc::clone(&tunnel_established);
|
||||
let disconnect_requested = Arc::new(AtomicBool::new(false));
|
||||
let disconnect_requested_on_signal = Arc::clone(&disconnect_requested);
|
||||
let cancellation = self.cancellation.clone();
|
||||
|
||||
let mut background_stdio = self
|
||||
.background
|
||||
.as_ref()
|
||||
.map(|background| background.redirect_stdio())
|
||||
.transpose()
|
||||
.map_err(GatewayConnectError::before_establishment)?;
|
||||
|
||||
let mut dashboard = if self.args.dashboard {
|
||||
Some(
|
||||
crate::dashboard::Dashboard::prepare(gateway.to_owned(), self.cancellation.clone())
|
||||
.map_err(GatewayConnectError::before_establishment)?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let monitor = gptunnel::TunnelMonitor::attach(vpn.clone());
|
||||
|
||||
let disconnect_task = tokio::spawn(async move {
|
||||
cancellation.cancelled().await;
|
||||
info!("Received the interrupt signal, disconnecting...");
|
||||
disconnect_requested_on_signal.store(true, Ordering::SeqCst);
|
||||
vpn_clone.disconnect();
|
||||
});
|
||||
|
||||
let lock_file_on_connect = self.shared_args.lock_file.to_path_buf();
|
||||
let pid_written = self.pid_written.clone();
|
||||
let log_format = self.shared_args.log_format;
|
||||
let session_cancellation = self.cancellation.clone();
|
||||
let (established_tx, established_rx) = tokio::sync::oneshot::channel();
|
||||
self.sessions.borrow_mut().relinquish_gateway(gateway);
|
||||
let mut worker = tokio::task::spawn_blocking(move || {
|
||||
vpn.connect(move |vpn_session_info| {
|
||||
if session_cancellation.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
tunnel_established_on_connect.store(true, Ordering::SeqCst);
|
||||
pid_written.store(write_pid_file(&lock_file_on_connect), Ordering::SeqCst);
|
||||
let _ = established_tx.send(());
|
||||
|
||||
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
|
||||
return;
|
||||
};
|
||||
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
|
||||
info!("VPN session info: {}", session_info.log_summary());
|
||||
|
||||
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info, log_format);
|
||||
session_task_on_connect.lock().unwrap().replace(task);
|
||||
})
|
||||
});
|
||||
let mut output_error = None;
|
||||
let connect_result = tokio::select! {
|
||||
result = &mut worker => result,
|
||||
established = established_rx => {
|
||||
if established.is_ok() {
|
||||
let unused = self.sessions.borrow().members().iter()
|
||||
.filter(|session| session.gateway.server() != gateway)
|
||||
.map(|session| session.gateway.server().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
wait_for_tunnel_exit(&mut worker, async {
|
||||
for server in unused {
|
||||
self.logout_gateway(&server).await;
|
||||
}
|
||||
}, || {
|
||||
if let Some(dashboard) = &mut dashboard {
|
||||
if let Err(error) = dashboard.start_tunnel(monitor.clone()) {
|
||||
self.cancellation.cancel();
|
||||
output_error = Some(error);
|
||||
}
|
||||
}
|
||||
if let (Some(background), Some(stdio)) = (&self.background, &mut background_stdio) {
|
||||
let detach = if self.pid_written.load(Ordering::SeqCst) {
|
||||
background.detach(stdio)
|
||||
} else {
|
||||
Err(anyhow::anyhow!("Cannot detach without a writable PID lock file"))
|
||||
};
|
||||
if let Err(error) = detach {
|
||||
self.cancellation.cancel();
|
||||
output_error = Some(error);
|
||||
}
|
||||
}
|
||||
}).await
|
||||
} else {
|
||||
(&mut worker).await
|
||||
}
|
||||
}
|
||||
};
|
||||
monitor.stop().await;
|
||||
if let Some(dashboard) = &mut dashboard {
|
||||
if let Err(error) = dashboard.finish() {
|
||||
output_error = Some(error);
|
||||
}
|
||||
}
|
||||
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
|
||||
disconnect_task.abort();
|
||||
let _ = disconnect_task.await;
|
||||
|
||||
let session_task = { session_task.lock().unwrap().take() };
|
||||
if let Some(task) = session_task {
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
}
|
||||
|
||||
if let Some(error) = output_error {
|
||||
return Err(GatewayConnectError::after_establishment(error));
|
||||
}
|
||||
|
||||
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
|
||||
let connect_result = connect_result.map_err(|error| GatewayConnectError::after_establishment(error.into()))?;
|
||||
classify_openconnect_result(connect_result, tunnel_established, disconnect_requested)
|
||||
}
|
||||
|
||||
pub(super) fn hip_source(&self, profile: OsProfile) -> anyhow::Result<HipSource> {
|
||||
let user = self.determine_hip_user();
|
||||
let script = self.args.hip.as_ref().or(self.args.csd_wrapper.as_ref());
|
||||
match script {
|
||||
Some(path) if !path.is_empty() => Ok(HipSource::Script(HipScript::new(path.clone(), get_uid(&user)?)?)),
|
||||
Some(_) => {
|
||||
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
|
||||
Ok(HipSource::Generator(Arc::new(move |request, control| {
|
||||
let input = gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context: gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
},
|
||||
};
|
||||
gphip::generate_report_with_control(&input, &|| control.check())
|
||||
.map_err(|error| error.downcast::<std::io::Error>().unwrap_or_else(std::io::Error::other))
|
||||
})))
|
||||
}
|
||||
None => {
|
||||
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
|
||||
Ok(HipSource::Disabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn determine_hip_user(&self) -> Option<String> {
|
||||
if let Some(hip_user) = &self.args.hip_user {
|
||||
return Some(hip_user.clone());
|
||||
}
|
||||
|
||||
self.args.csd_user.clone()
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_tunnel_exit(
|
||||
worker: &mut JoinHandle<i32>,
|
||||
cleanup: impl std::future::Future<Output = ()>,
|
||||
on_ready: impl FnOnce(),
|
||||
) -> Result<i32, tokio::task::JoinError> {
|
||||
tokio::pin!(cleanup);
|
||||
tokio::select! {
|
||||
// A finished tunnel must not publish readiness, including when cleanup is
|
||||
// also ready in the same poll.
|
||||
biased;
|
||||
result = &mut *worker => {
|
||||
// Logout temporarily owns the session registry. Complete it even when
|
||||
// the tunnel exits, so cancelling this future cannot discard sessions.
|
||||
cleanup.await;
|
||||
return result;
|
||||
},
|
||||
_ = &mut cleanup => {},
|
||||
}
|
||||
on_ready();
|
||||
worker.await
|
||||
}
|
||||
|
||||
fn classify_openconnect_result(
|
||||
exit_code: i32,
|
||||
tunnel_established: bool,
|
||||
disconnect_requested: bool,
|
||||
) -> Result<(), GatewayConnectError> {
|
||||
if exit_code == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if disconnect_requested && exit_code == OPENCONNECT_INTERRUPTED_EXIT_CODE {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let error = anyhow::anyhow!("OpenConnect exited with status {}", exit_code);
|
||||
if tunnel_established {
|
||||
Err(GatewayConnectError::after_establishment(error))
|
||||
} else {
|
||||
Err(GatewayConnectError::before_establishment(error))
|
||||
}
|
||||
}
|
||||
|
||||
fn direct_gateway_command(gateway: &str) -> String {
|
||||
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
|
||||
}
|
||||
|
||||
pub(super) fn write_pid_file(lock_file: &Path) -> bool {
|
||||
let pid = std::process::id();
|
||||
|
||||
if let Err(err) = fs::write(lock_file, pid.to_string()) {
|
||||
warn!("Failed to write PID file: {}", err);
|
||||
false
|
||||
} else {
|
||||
info!("Wrote PID {} to {}", pid, lock_file.display());
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn get_uid(user: &Option<String>) -> anyhow::Result<Option<u32>> {
|
||||
user
|
||||
.as_ref()
|
||||
.map(|user| get_user_by_name(user).map(|user| user.uid()))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
|
||||
builder
|
||||
.os(Some(profile.client_os().to_openconnect_os().to_string()))
|
||||
.os_version(Some(profile.os_version().to_string()))
|
||||
.client_version(Some(profile.client_version().to_string()))
|
||||
.host_id(Some(profile.host_identity().host_id().to_string()))
|
||||
.user_agent(Some(profile.user_agent().to_string()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn tunnel_exit_during_startup_cleanup_does_not_publish_readiness() {
|
||||
let (cleanup_started_tx, cleanup_started_rx) = tokio::sync::oneshot::channel();
|
||||
let (worker_exited_tx, worker_exited_rx) = tokio::sync::oneshot::channel();
|
||||
let mut worker = tokio::spawn(async move {
|
||||
cleanup_started_rx.await.unwrap();
|
||||
worker_exited_tx.send(()).unwrap();
|
||||
7
|
||||
});
|
||||
let mut ready = false;
|
||||
let result = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
wait_for_tunnel_exit(
|
||||
&mut worker,
|
||||
async {
|
||||
cleanup_started_tx.send(()).unwrap();
|
||||
worker_exited_rx.await.unwrap();
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
},
|
||||
|| ready = true,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("Tunnel exit must preserve completed cleanup")
|
||||
.unwrap();
|
||||
assert_eq!(result, 7);
|
||||
assert!(!ready, "An exited tunnel must not report background startup success");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn finished_tunnel_takes_priority_over_finished_startup_cleanup() {
|
||||
let mut worker = tokio::spawn(async { 7 });
|
||||
while !worker.is_finished() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
let mut ready = false;
|
||||
let result = wait_for_tunnel_exit(&mut worker, async {}, || ready = true)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result, 7);
|
||||
assert!(!ready, "A ready cleanup must not conceal a finished tunnel");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn running_tunnel_publishes_readiness_after_startup_cleanup() {
|
||||
let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
|
||||
let mut worker = tokio::spawn(async move {
|
||||
ready_rx.await.unwrap();
|
||||
0
|
||||
});
|
||||
let cleanup_complete = AtomicBool::new(false);
|
||||
let result = wait_for_tunnel_exit(
|
||||
&mut worker,
|
||||
async { cleanup_complete.store(true, Ordering::SeqCst) },
|
||||
|| {
|
||||
assert!(cleanup_complete.load(Ordering::SeqCst));
|
||||
ready_tx.send(()).unwrap();
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hip_script_defaults_to_inherited_process_identity() {
|
||||
assert_eq!(get_uid(&None).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_hip_user_must_exist() {
|
||||
assert!(get_uid(&Some("gpclient-nonexistent-hip-user".to_string())).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_hip_user_resolves_to_the_selected_account() {
|
||||
let current = uzers::get_user_by_uid(uzers::get_effective_uid()).unwrap();
|
||||
let name = current.name().to_string_lossy().into_owned();
|
||||
assert_eq!(get_uid(&Some(name)).unwrap(), Some(current.uid()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openconnect_success_is_not_a_gateway_failure() {
|
||||
assert!(classify_openconnect_result(0, false, false).is_ok());
|
||||
assert!(classify_openconnect_result(0, true, false).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openconnect_failure_before_callback_is_retryable_gateway_failure() {
|
||||
let err = classify_openconnect_result(1, false, false).expect_err("nonzero exit should fail");
|
||||
|
||||
assert!(err.is_before_establishment());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openconnect_failure_after_callback_is_terminal_gateway_failure() {
|
||||
let err = classify_openconnect_result(1, true, false).expect_err("nonzero exit should fail");
|
||||
|
||||
assert!(!err.is_before_establishment());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interrupted_exit_after_requested_disconnect_is_success() {
|
||||
assert!(classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, true).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interrupted_exit_without_requested_disconnect_is_failure() {
|
||||
let err = classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, false)
|
||||
.expect_err("unexpected interrupt should fail");
|
||||
|
||||
assert!(!err.is_before_establishment());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_gateway_recommendation_uses_gateway_server() {
|
||||
assert_eq!(
|
||||
direct_gateway_command("gateway.example.test"),
|
||||
"gpauth --gateway gateway.example.test | sudo gpclient connect gateway.example.test --as-gateway --cookie-on-stdin"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use gpapi::{
|
||||
collection::CollectionControl,
|
||||
credential::AuthCookieCredential,
|
||||
gateway::{Gateway, GatewayLoginContext, GatewaySelection},
|
||||
portal::PortalConfig,
|
||||
session::{
|
||||
MaintenanceState, SessionEndReason, SessionMode,
|
||||
desktop::network::PhysicalNetwork,
|
||||
desktop::non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions},
|
||||
},
|
||||
};
|
||||
use log::{info, warn};
|
||||
|
||||
use super::ConnectHandler;
|
||||
|
||||
impl ConnectHandler<'_> {
|
||||
pub(super) async fn connect_internal_gateways(
|
||||
&self,
|
||||
portal: &str,
|
||||
config: &PortalConfig,
|
||||
credential: &AuthCookieCredential,
|
||||
first_gateway: &Gateway,
|
||||
first_session: super::gateway::GatewayLoginSession,
|
||||
remaining: &[&Gateway],
|
||||
) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
self.background.is_none(),
|
||||
"--background requires a VPN tunnel; internal non-tunnel sessions must run in the foreground"
|
||||
);
|
||||
ensure!(remaining.len() < 64, "Too many internal non-tunnel candidates");
|
||||
let mut hosts = std::collections::HashSet::new();
|
||||
for gateway in std::iter::once(first_gateway).chain(remaining.iter().copied()) {
|
||||
ensure!(
|
||||
gateway.kind() == gpapi::gateway::GatewayKind::Internal,
|
||||
"Non-tunnel candidates must be internal"
|
||||
);
|
||||
ensure!(
|
||||
hosts.insert(gpapi::utils::normalize_server(gateway.server())?),
|
||||
"Duplicate internal gateway"
|
||||
);
|
||||
}
|
||||
let mut authenticated = vec![(first_gateway, first_session)];
|
||||
for gateway in remaining.iter().copied() {
|
||||
self.check_cancelled()?;
|
||||
let context =
|
||||
GatewayLoginContext::new(gateway, GatewaySelection::Auto).with_connect_method(config.connect_method());
|
||||
match self
|
||||
.authenticate_gateway(
|
||||
portal,
|
||||
gateway.server(),
|
||||
credential,
|
||||
config.default_browser().unwrap_or(false),
|
||||
context,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(session) => authenticated.push((gateway, session)),
|
||||
Err(error) => {
|
||||
self.logout_gateway(gateway.server()).await;
|
||||
self.check_cancelled()?;
|
||||
if self.auth_recovery.borrow().dmabuf_disabled() {
|
||||
return Err(self.auth_recovery.borrow().terminal(error));
|
||||
}
|
||||
warn!("Internal gateway {gateway} authentication failed: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
self.check_cancelled()?;
|
||||
let modes = authenticated.iter().map(|(_, session)| session.authentication.mode());
|
||||
ensure!(
|
||||
internal_session_mode(modes)? == SessionMode::NonTunnel,
|
||||
"Expected non-tunnel authentication"
|
||||
);
|
||||
self.run_internal_session(config, &authenticated).await
|
||||
}
|
||||
|
||||
async fn run_internal_session(
|
||||
&self,
|
||||
config: &PortalConfig,
|
||||
authenticated: &[(&gpapi::gateway::Gateway, super::gateway::GatewayLoginSession)],
|
||||
) -> anyhow::Result<()> {
|
||||
let cancellation = self.cancellation.clone();
|
||||
let network = Arc::new(PhysicalNetwork::capture_controlled(&cancellation).await?);
|
||||
let detection = config.internal_detection().cloned();
|
||||
let bindings = authenticated
|
||||
.iter()
|
||||
.map(|(_, session)| {
|
||||
session
|
||||
.extension_auth
|
||||
.binding()
|
||||
.cloned()
|
||||
.context("Non-tunnel binding is missing")
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
for binding in &bindings {
|
||||
network
|
||||
.validate_internal_binding(binding, detection.as_ref(), &cancellation)
|
||||
.await?;
|
||||
}
|
||||
let policy = config
|
||||
.internal_session_policy()
|
||||
.context("Invalid internal session policy")?;
|
||||
let profile = self.os_profile.borrow().clone();
|
||||
let source = if policy.collect_hip_data() {
|
||||
self.hip_source(profile.clone())?
|
||||
} else {
|
||||
openconnect::HipSource::Disabled
|
||||
};
|
||||
let source = Arc::new(source);
|
||||
let validate_network = network.clone();
|
||||
let validate_detection = detection.clone();
|
||||
let members = crate::dashboard::InternalMembers::default();
|
||||
let dashboard_members = members.clone();
|
||||
let (established_tx, established_rx) = tokio::sync::oneshot::channel();
|
||||
let established_tx = std::sync::Mutex::new(Some(established_tx));
|
||||
let mut dashboard = if self.args.dashboard {
|
||||
Some(crate::dashboard::Dashboard::prepare(
|
||||
authenticated[0].0.server().to_owned(),
|
||||
cancellation.clone(),
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let callbacks = SessionCallbacks {
|
||||
produce_report: Arc::new(move |request, control| {
|
||||
control.check()?;
|
||||
if matches!(source.as_ref(), openconnect::HipSource::Disabled) {
|
||||
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context: gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
},
|
||||
})
|
||||
.map_err(std::io::Error::other);
|
||||
}
|
||||
source.collect(
|
||||
&openconnect::HipRequest {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
client_version: profile.client_version().into(),
|
||||
client_os: profile.client_os().as_str().into(),
|
||||
os_version: profile.os_version().into(),
|
||||
host_id: Some(profile.host_id().into()),
|
||||
local_hostname: Some(profile.computer().into()),
|
||||
},
|
||||
&|| control.check(),
|
||||
)
|
||||
}),
|
||||
report_submitted: Arc::new(|_, _| {}),
|
||||
status_changed: Arc::new(move |member| {
|
||||
match member.maintenance {
|
||||
MaintenanceState::Healthy => {
|
||||
info!(
|
||||
"Internal network — authenticated: {} (IPv4: {:?}, IPv6: {:?})",
|
||||
member.gateway, member.client_ip, member.client_ipv6
|
||||
);
|
||||
if let Some(established) = established_tx.lock().unwrap().take() {
|
||||
let _ = established.send(());
|
||||
}
|
||||
}
|
||||
state => info!("Internal gateway {}: {state:?}", member.gateway),
|
||||
}
|
||||
members.lock().unwrap().insert(
|
||||
member.gateway.server().to_owned(),
|
||||
format!("{}: {:?}", member.gateway, member.maintenance),
|
||||
);
|
||||
}),
|
||||
validate_network: Arc::new(move |cancellation| {
|
||||
let network = validate_network.clone();
|
||||
let detection = validate_detection.clone();
|
||||
let bindings = bindings.clone();
|
||||
Box::pin(async move {
|
||||
for binding in &bindings {
|
||||
network
|
||||
.validate_internal_binding(binding, detection.as_ref(), &cancellation)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}),
|
||||
};
|
||||
let monitor_cancel = cancellation.child_token();
|
||||
let monitor_token = monitor_cancel.clone();
|
||||
let (network_changed, network_signal) = tokio::sync::oneshot::channel();
|
||||
let monitor = tokio::spawn(async move {
|
||||
match network.wait_for_change(detection, monitor_token).await {
|
||||
Ok(false) => {}
|
||||
Ok(true) | Err(_) => {
|
||||
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// The PID spans maintenance and cleanup, including initialization before the
|
||||
// first successful HIP exchange. The outer handler owns final session logout.
|
||||
self.pid_written.store(
|
||||
super::gateway::write_pid_file(self.shared_args.lock_file),
|
||||
std::sync::atomic::Ordering::SeqCst,
|
||||
);
|
||||
let mut sessions = self.sessions.take();
|
||||
let mut dashboard_error = None;
|
||||
let result = {
|
||||
let maintenance = maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation, async move {
|
||||
network_signal.await.unwrap_or(SessionEndReason::NetworkChanged)
|
||||
});
|
||||
tokio::pin!(maintenance);
|
||||
tokio::select! {
|
||||
result = &mut maintenance => result,
|
||||
established = established_rx => {
|
||||
if established.is_ok() {
|
||||
if let Some(dashboard) = &mut dashboard {
|
||||
if let Err(error) = dashboard.start_internal(dashboard_members) {
|
||||
self.cancellation.cancel();
|
||||
dashboard_error = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
maintenance.await
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(dashboard) = &mut dashboard {
|
||||
if let Err(error) = dashboard.finish() {
|
||||
dashboard_error = Some(error);
|
||||
}
|
||||
}
|
||||
self.sessions.replace(sessions);
|
||||
monitor_cancel.cancel();
|
||||
monitor.await.context("Internal network monitor failed")?;
|
||||
if let Some(error) = dashboard_error {
|
||||
return Err(error);
|
||||
}
|
||||
match result? {
|
||||
SessionExit::Disconnected => Ok(()),
|
||||
SessionExit::Failed(reason) => bail!("Internal session ended: {reason:?}. Connect again to authenticate."),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn logout_gateway(&self, gateway: &str) {
|
||||
let mut sessions = self.sessions.take();
|
||||
sessions.logout_gateway(gateway).await;
|
||||
self.sessions.replace(sessions);
|
||||
}
|
||||
}
|
||||
|
||||
fn internal_session_mode(modes: impl Iterator<Item = SessionMode>) -> anyhow::Result<SessionMode> {
|
||||
let mut modes = modes;
|
||||
let mode = modes.next().context("No internal gateway authenticated successfully")?;
|
||||
ensure!(
|
||||
modes.all(|candidate| candidate == mode),
|
||||
"Mixed tunnel and non-tunnel internal gateways are unsupported; select a gateway explicitly"
|
||||
);
|
||||
Ok(mode)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn internal_modes_reject_mixed_and_empty_sets() {
|
||||
assert!(internal_session_mode([].into_iter()).is_err());
|
||||
assert!(internal_session_mode([SessionMode::Tunnel, SessionMode::NonTunnel].into_iter()).is_err());
|
||||
assert_eq!(
|
||||
internal_session_mode([SessionMode::NonTunnel, SessionMode::NonTunnel].into_iter()).unwrap(),
|
||||
SessionMode::NonTunnel
|
||||
);
|
||||
assert_eq!(
|
||||
internal_session_mode([SessionMode::Tunnel].into_iter()).unwrap(),
|
||||
SessionMode::Tunnel
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
mod args;
|
||||
mod credential;
|
||||
#[cfg(test)]
|
||||
mod flow_tests;
|
||||
mod gateway;
|
||||
mod internal;
|
||||
mod vpn_script;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use gpapi::{
|
||||
clap::report,
|
||||
error::PortalError,
|
||||
gateway::GatewaySelection,
|
||||
gp_params::GpParams,
|
||||
os_profile::OsProfile,
|
||||
portal::{PreloginOptions, discovery::discover, prelogin},
|
||||
session::desktop::GatewaySessions,
|
||||
utils::request::RequestIdentityError,
|
||||
};
|
||||
use inquire::{Password, PasswordDisplayMode, Select};
|
||||
use log::{Level, info, warn};
|
||||
|
||||
use crate::cli::SharedArgs;
|
||||
|
||||
pub(crate) use args::ConnectArgs;
|
||||
use args::{build_os_profile, build_os_profile_with_host_id, warn_deprecated_connect_args};
|
||||
use credential::CleanAuthState;
|
||||
use gateway::GatewayConnectError;
|
||||
|
||||
pub(crate) struct ConnectHandler<'a> {
|
||||
cancellation: tokio_util::sync::CancellationToken,
|
||||
args: &'a ConnectArgs,
|
||||
shared_args: &'a SharedArgs<'a>,
|
||||
os_profile: RefCell<OsProfile>,
|
||||
latest_key_password: RefCell<Option<String>>,
|
||||
password_from_stdin: RefCell<Option<String>>,
|
||||
cookie_from_stdin: RefCell<Option<String>>,
|
||||
clean_auth_state: RefCell<CleanAuthState>,
|
||||
#[cfg(test)]
|
||||
auth_attempt_fixture: RefCell<credential::AuthAttemptFixture>,
|
||||
auth_recovery: RefCell<gpapi::process::rendering_recovery::RecoveryState>,
|
||||
sessions: RefCell<GatewaySessions>,
|
||||
pid_written: Arc<AtomicBool>,
|
||||
background: Option<crate::background::BackgroundWorker>,
|
||||
}
|
||||
|
||||
impl<'a> ConnectHandler<'a> {
|
||||
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
|
||||
warn_deprecated_connect_args(args);
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
let clean_auth = args.clean;
|
||||
#[cfg(not(feature = "webview-auth"))]
|
||||
let clean_auth = false;
|
||||
|
||||
Self {
|
||||
cancellation: tokio_util::sync::CancellationToken::new(),
|
||||
args,
|
||||
shared_args,
|
||||
os_profile: RefCell::new(build_os_profile(args)),
|
||||
latest_key_password: Default::default(),
|
||||
password_from_stdin: Default::default(),
|
||||
cookie_from_stdin: Default::default(),
|
||||
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
|
||||
#[cfg(test)]
|
||||
auth_attempt_fixture: Default::default(),
|
||||
auth_recovery: RefCell::default(),
|
||||
sessions: RefCell::default(),
|
||||
pid_written: Arc::default(),
|
||||
background: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_background(mut self, background: Option<crate::background::BackgroundWorker>) -> Self {
|
||||
self.background = background;
|
||||
self
|
||||
}
|
||||
|
||||
fn build_gp_params(&self) -> GpParams {
|
||||
let mut builder = GpParams::builder(self.os_profile.borrow().clone());
|
||||
builder
|
||||
.csc_mode(self.args.csc)
|
||||
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
|
||||
.certificate(self.args.certificate.clone())
|
||||
.sslkey(self.args.sslkey.clone())
|
||||
.key_password(self.latest_key_password.borrow().clone());
|
||||
|
||||
builder.build()
|
||||
}
|
||||
|
||||
pub(super) fn prelogin_options(&self, gateway_browser_auth_allowed: bool) -> PreloginOptions {
|
||||
PreloginOptions::default()
|
||||
.external_browser_requested(self.external_browser_requested())
|
||||
.gateway_external_browser_allowed(gateway_browser_auth_allowed)
|
||||
}
|
||||
|
||||
pub(super) fn direct_gateway_prelogin_options(&self) -> PreloginOptions {
|
||||
self.prelogin_options(true)
|
||||
}
|
||||
|
||||
pub(super) fn gateway_browser_auth_allowed(&self, portal_config_default_browser: bool) -> bool {
|
||||
gateway_browser_auth_allowed(portal_config_default_browser, self.external_browser_requested())
|
||||
}
|
||||
|
||||
fn external_browser_requested(&self) -> bool {
|
||||
#[cfg(feature = "webview-auth")]
|
||||
{
|
||||
self.args.default_browser || self.args.browser.is_some()
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "webview-auth"))]
|
||||
{
|
||||
self.args.browser.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
||||
let cancellation = self.cancellation.clone();
|
||||
let signal = tokio::spawn(async move {
|
||||
gpapi::utils::shutdown_signal().await;
|
||||
cancellation.cancel();
|
||||
});
|
||||
self.auth_recovery.replace(Default::default());
|
||||
let result = self.handle_attempt().await;
|
||||
let sessions = self.sessions.take();
|
||||
if self.args.cookie_only && result.is_ok() {
|
||||
sessions.relinquish();
|
||||
} else {
|
||||
sessions.logout().await;
|
||||
}
|
||||
if self.pid_written.load(Ordering::SeqCst) {
|
||||
if let Err(error) = std::fs::remove_file(self.shared_args.lock_file) {
|
||||
warn!("Failed to remove PID file: {error}");
|
||||
}
|
||||
}
|
||||
signal.abort();
|
||||
let _ = signal.await;
|
||||
result
|
||||
}
|
||||
|
||||
fn check_cancelled(&self) -> anyhow::Result<()> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
Err(gpapi::auth::AuthenticationCancelled.into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_attempt(&self) -> anyhow::Result<()> {
|
||||
if self.args.browser_listen.is_some()
|
||||
&& !matches!(self.args.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("manual") || browser.eq_ignore_ascii_case("remote"))
|
||||
{
|
||||
bail!("The '--browser-listen' option requires '--browser manual'");
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
if self.args.default_browser && self.args.browser.is_some() {
|
||||
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
|
||||
}
|
||||
|
||||
self.latest_key_password.replace(self.args.key_password.clone());
|
||||
|
||||
loop {
|
||||
self.check_cancelled()?;
|
||||
let result = self.handle_impl().await;
|
||||
let Err(err) = self.auth_recovery.borrow().finish(result) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if err
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
let Some(identity_error) = err.downcast_ref::<RequestIdentityError>() else {
|
||||
return Err(err);
|
||||
};
|
||||
|
||||
match identity_error {
|
||||
RequestIdentityError::UnsupportedEncryption
|
||||
| RequestIdentityError::UnsupportedKeyFormat
|
||||
| RequestIdentityError::InvalidKey
|
||||
| RequestIdentityError::InvalidCertificate
|
||||
| RequestIdentityError::IncompletePkcs12
|
||||
| RequestIdentityError::AmbiguousPkcs12
|
||||
| RequestIdentityError::InvalidPkcs12(_) => return Err(err),
|
||||
RequestIdentityError::NoKey => {
|
||||
let format = self.shared_args.log_format;
|
||||
report(
|
||||
format,
|
||||
Level::Error,
|
||||
"ERROR: No private key found in the certificate file",
|
||||
);
|
||||
report(
|
||||
format,
|
||||
Level::Error,
|
||||
"ERROR: Please provide the private key file using the `-k` option",
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
|
||||
let message = format!("Enter the {} passphrase:", cert_type);
|
||||
let password = Password::new(&message)
|
||||
.without_confirmation()
|
||||
.with_display_mode(PasswordDisplayMode::Masked)
|
||||
.prompt()?;
|
||||
|
||||
self.latest_key_password.replace(Some(password));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
|
||||
self.check_cancelled()?;
|
||||
let server = self.args.server.as_str();
|
||||
let as_gateway = self.args.as_gateway;
|
||||
|
||||
self.prepare_cookie_from_stdin()?;
|
||||
|
||||
if as_gateway {
|
||||
info!("Treating the server as a gateway");
|
||||
return self.connect_gateway_with_prelogin(server, server, false, None).await;
|
||||
}
|
||||
|
||||
if !self.args.cookie_on_stdin {
|
||||
if let Some(result) = self.try_cached_cookie(server).await {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
self.check_cancelled()?;
|
||||
|
||||
let Err(err) = self.connect_portal_with_prelogin(server).await else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let err = self.auth_recovery.borrow().terminal(err);
|
||||
if err
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
warn!("Failed to connect portal with prelogin: {}", err);
|
||||
if err.root_cause().downcast_ref::<PortalError>().is_some() {
|
||||
info!("Trying the gateway authentication workflow...");
|
||||
self.connect_gateway_with_prelogin(server, server, false, None).await?;
|
||||
|
||||
let format = self.shared_args.log_format;
|
||||
report(
|
||||
format,
|
||||
Level::Warn,
|
||||
"\nNOTE: the server may be a gateway, not a portal.",
|
||||
);
|
||||
report(
|
||||
format,
|
||||
Level::Warn,
|
||||
"NOTE: try to use the `--as-gateway` option if you were authenticated twice.",
|
||||
);
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
|
||||
let gp_params = self.build_gp_params();
|
||||
|
||||
let mut prelogin = tokio::select! {
|
||||
biased;
|
||||
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||
result = prelogin(portal, &gp_params, self.prelogin_options(false)) => result?,
|
||||
};
|
||||
|
||||
let cached = self.cached_portal_credential(portal);
|
||||
let cached_config = match cached {
|
||||
Some(cred) => match discover(portal, &cred, &gp_params, &self.cancellation).await {
|
||||
Ok(config) => Some((cred, config)),
|
||||
Err(error) => {
|
||||
self.check_cancelled()?;
|
||||
warn!("Cached portal authentication failed: {error}");
|
||||
self.clear_cookie_cache();
|
||||
None
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let (cred, mut portal_config) = match cached_config {
|
||||
Some(result) => result,
|
||||
None => {
|
||||
let (replacement, cred) = self
|
||||
.obtain_credential_with_recovery(prelogin.clone(), portal, false)
|
||||
.await?;
|
||||
prelogin = replacement;
|
||||
self.check_cancelled()?;
|
||||
let config = discover(portal, &cred, &gp_params, &self.cancellation).await?;
|
||||
(cred, config)
|
||||
}
|
||||
};
|
||||
self.check_cancelled()?;
|
||||
|
||||
portal_config.sort_gateways(prelogin.region());
|
||||
|
||||
let auth_cookie = match cred.password() {
|
||||
Some(password) => portal_config.auth_cookie().clone().with_password(password),
|
||||
None => portal_config.auth_cookie().clone(),
|
||||
};
|
||||
let portal_config_default_browser = portal_config.default_browser().unwrap_or(false);
|
||||
info!("Portal config default-browser: {}", portal_config_default_browser);
|
||||
|
||||
if self.args.auto_gateway {
|
||||
let gateways = portal_config.gateways();
|
||||
if gateways.is_empty() {
|
||||
bail!("No gateways available in portal config for auto-gateway selection");
|
||||
}
|
||||
|
||||
info!(
|
||||
"Auto-gateway mode: trying {} gateway(s) in priority order",
|
||||
gateways.len()
|
||||
);
|
||||
|
||||
let mut last_err: Option<anyhow::Error> = None;
|
||||
for (index, gateway) in gateways.iter().enumerate() {
|
||||
info!("Auto-gateway: attempting gateway {}", gateway);
|
||||
match self
|
||||
.connect_gateway_with_fallback(
|
||||
portal,
|
||||
gateway,
|
||||
&auth_cookie,
|
||||
&portal_config,
|
||||
GatewaySelection::Auto,
|
||||
&gateways[index + 1..],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => return Ok(()),
|
||||
Err(err) => {
|
||||
self.logout_gateway(gateway.server()).await;
|
||||
if self.auth_recovery.borrow().dmabuf_disabled() || !err.is_before_establishment() {
|
||||
return Err(self.auth_recovery.borrow().terminal(err.into_error()));
|
||||
}
|
||||
warn!(
|
||||
"Auto-gateway: gateway {} failed before session establishment: {}",
|
||||
gateway,
|
||||
err.as_error()
|
||||
);
|
||||
last_err = Some(err.into_error());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let detail = last_err
|
||||
.map(|e| e.to_string())
|
||||
.unwrap_or_else(|| "unknown error".to_string());
|
||||
bail!(
|
||||
"Auto-gateway: all {} gateway(s) failed to connect; last error: {}",
|
||||
gateways.len(),
|
||||
detail
|
||||
);
|
||||
}
|
||||
|
||||
let gateway_selection = if self.args.gateway.is_some() {
|
||||
GatewaySelection::Manual
|
||||
} else {
|
||||
GatewaySelection::Auto
|
||||
};
|
||||
let selected_gateway = match &self.args.gateway {
|
||||
Some(gateway) => portal_config
|
||||
.find_gateway(gateway)
|
||||
.ok_or_else(|| anyhow::anyhow!("Cannot find gateway specified: {}", gateway))?,
|
||||
None => {
|
||||
let gateways = portal_config.gateways();
|
||||
|
||||
if gateways.is_empty() {
|
||||
bail!("No gateways available in portal configuration");
|
||||
}
|
||||
if gateways.len() > 1 {
|
||||
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
|
||||
.with_vim_mode(true)
|
||||
.prompt()?;
|
||||
info!("Connecting to the selected gateway: {}", gateway);
|
||||
gateway
|
||||
} else {
|
||||
info!("Connecting to the only available gateway: {}", gateways[0]);
|
||||
gateways[0]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self
|
||||
.connect_gateway_with_fallback(
|
||||
portal,
|
||||
selected_gateway,
|
||||
&auth_cookie,
|
||||
&portal_config,
|
||||
gateway_selection,
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.map_err(GatewayConnectError::into_error)
|
||||
}
|
||||
|
||||
fn apply_stdin_host_id(&self, host_id: Option<&str>) {
|
||||
let Some(host_id) = host_id else {
|
||||
return;
|
||||
};
|
||||
self
|
||||
.os_profile
|
||||
.replace(build_os_profile_with_host_id(self.args, Some(host_id)));
|
||||
info!(
|
||||
"connect profile host-id: {}",
|
||||
self.os_profile.borrow().host_identity().host_id()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn gateway_browser_auth_allowed(portal_config_default_browser: bool, external_browser_requested: bool) -> bool {
|
||||
portal_config_default_browser || external_browser_requested
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::gateway_browser_auth_allowed;
|
||||
|
||||
#[test]
|
||||
fn gateway_browser_auth_is_allowed_by_portal_config() {
|
||||
assert!(gateway_browser_auth_allowed(true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gateway_browser_auth_is_allowed_by_explicit_browser_request() {
|
||||
assert!(gateway_browser_auth_allowed(false, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gateway_browser_auth_is_disabled_without_portal_config_or_user_request() {
|
||||
assert!(!gateway_browser_auth_allowed(false, false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
|
||||
use crate::connect::ConnectArgs;
|
||||
|
||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> VpnBuilder {
|
||||
Vpn::builder(server, cookie)
|
||||
.script(args.script.clone())
|
||||
.script_tun(args.script_tun)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
use std::ffi::OsStr;
|
||||
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
|
||||
use crate::connect::ConnectArgs;
|
||||
|
||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> VpnBuilder {
|
||||
let configured_script = std::env::var_os("GP_VPNC_SCRIPT");
|
||||
configure_builder(server, cookie, args, configured_script.as_deref())
|
||||
}
|
||||
|
||||
fn configure_builder(server: &str, cookie: &str, args: &ConnectArgs, configured_script: Option<&OsStr>) -> VpnBuilder {
|
||||
let builder = Vpn::builder(server, cookie)
|
||||
.script(args.script.clone())
|
||||
.script_tun(args.script_tun);
|
||||
let has_environment_script = configured_script.is_some_and(|value| !value.is_empty());
|
||||
if args.script.is_none() && !args.script_tun && !has_environment_script {
|
||||
builder.network_configuration_handler(|configuration| {
|
||||
gpvpnc::macos::configure_network(&configuration.reason, &configuration.environment)
|
||||
})
|
||||
} else {
|
||||
builder
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use clap::Parser;
|
||||
|
||||
#[derive(Parser)]
|
||||
struct TestCli {
|
||||
#[command(flatten)]
|
||||
args: ConnectArgs,
|
||||
}
|
||||
|
||||
fn args(options: &[&str]) -> ConnectArgs {
|
||||
TestCli::try_parse_from(
|
||||
["connect", "vpn.example.com"]
|
||||
.into_iter()
|
||||
.chain(options.iter().copied()),
|
||||
)
|
||||
.unwrap()
|
||||
.args
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_does_not_require_an_installed_script() {
|
||||
for configured in [None, Some(OsStr::new(""))] {
|
||||
assert!(
|
||||
configure_builder("server", "cookie", &args(&[]), configured)
|
||||
.build()
|
||||
.is_ok()
|
||||
);
|
||||
assert!(
|
||||
configure_builder("server", "cookie", &args(&[]), configured)
|
||||
.script("/bin/sh".to_string())
|
||||
.script_tun(true)
|
||||
.build()
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_commands_and_script_tunnels_remain_supported() {
|
||||
for options in [
|
||||
vec!["--script", "exec /bin/sh"],
|
||||
vec!["--script", "/bin/sh", "--script-tun"],
|
||||
] {
|
||||
assert!(
|
||||
configure_builder("server", "cookie", &args(&options), None)
|
||||
.build()
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environment_override_does_not_install_default_callback() {
|
||||
let builder = configure_builder("server", "cookie", &args(&[]), Some(OsStr::new("/bin/sh")));
|
||||
// Converting the selected builder to an explicit packet script would fail
|
||||
// if the embedded configuration callback had replaced the environment override.
|
||||
assert!(builder.script("/bin/sh".to_string()).script_tun(true).build().is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "macos.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
|
||||
pub(super) use platform::builder;
|
||||
@@ -0,0 +1,627 @@
|
||||
//! Dashboard presentation only; connection ownership and sampling stay outside this module.
|
||||
use crossterm::event::KeyCode;
|
||||
use gpapi::session::desktop::tunnel::{
|
||||
TunnelList, TunnelPhase, TunnelState, TunnelStatisticsSnapshot, TunnelStatisticsState,
|
||||
};
|
||||
use ratatui::{
|
||||
Frame,
|
||||
buffer::Buffer,
|
||||
layout::Rect,
|
||||
style::{Color, Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Paragraph, Widget, Wrap},
|
||||
};
|
||||
|
||||
use super::output::plain_text;
|
||||
|
||||
const MAX_CONTENT_WIDTH: u16 = 120;
|
||||
const LABEL_WIDTH: usize = 12;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct DetailScroll {
|
||||
offset: u16,
|
||||
maximum: u16,
|
||||
page: u16,
|
||||
}
|
||||
|
||||
impl DetailScroll {
|
||||
pub(super) fn handle_key(&mut self, key: KeyCode) {
|
||||
self.offset = match key {
|
||||
KeyCode::Up => self.offset.saturating_sub(1),
|
||||
KeyCode::Down => self.offset.saturating_add(1),
|
||||
KeyCode::PageUp => self.offset.saturating_sub(self.page),
|
||||
KeyCode::PageDown => self.offset.saturating_add(self.page),
|
||||
KeyCode::Home => 0,
|
||||
KeyCode::End => self.maximum,
|
||||
_ => self.offset,
|
||||
}
|
||||
.min(self.maximum);
|
||||
}
|
||||
|
||||
pub(super) fn can_scroll(&self) -> bool {
|
||||
self.maximum > 0
|
||||
}
|
||||
|
||||
fn update(&mut self, content_height: u16, viewport_height: u16) {
|
||||
self.maximum = if viewport_height == 0 {
|
||||
0
|
||||
} else {
|
||||
content_height.saturating_sub(viewport_height)
|
||||
};
|
||||
self.offset = self.offset.min(self.maximum);
|
||||
self.page = viewport_height.saturating_sub(1).max(1);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn phase_label(phase: TunnelPhase) -> &'static str {
|
||||
match phase {
|
||||
TunnelPhase::Establishing => "Establishing",
|
||||
TunnelPhase::Connected => "Connected",
|
||||
TunnelPhase::Reconnecting => "Reconnecting",
|
||||
TunnelPhase::Ended => "Disconnected",
|
||||
}
|
||||
}
|
||||
|
||||
fn uptime(milliseconds: u64) -> String {
|
||||
let seconds = milliseconds / 1000;
|
||||
format!("{:02}:{:02}:{:02}", seconds / 3600, (seconds / 60) % 60, seconds % 60)
|
||||
}
|
||||
|
||||
fn bytes(value: u64) -> String {
|
||||
const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
|
||||
let mut amount = value as f64;
|
||||
let mut unit = 0;
|
||||
while amount >= 1024.0 && unit < UNITS.len() - 1 {
|
||||
amount /= 1024.0;
|
||||
unit += 1;
|
||||
}
|
||||
if unit == 0 {
|
||||
format!("{value} B")
|
||||
} else {
|
||||
format!("{amount:.1} {}", UNITS[unit])
|
||||
}
|
||||
}
|
||||
|
||||
fn muted(text: impl Into<String>) -> Span<'static> {
|
||||
Span::styled(text.into(), Style::default().fg(Color::DarkGray))
|
||||
}
|
||||
|
||||
fn heading(text: impl Into<String>) -> Line<'static> {
|
||||
Line::styled(
|
||||
text.into(),
|
||||
Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn row(label: &str, value: impl Into<String>) -> Line<'static> {
|
||||
Line::from(vec![
|
||||
muted(format!("{label:<LABEL_WIDTH$} ")),
|
||||
Span::raw(plain_text(value.into().as_bytes())),
|
||||
])
|
||||
}
|
||||
|
||||
fn paragraph(lines: Vec<Line<'static>>) -> Paragraph<'static> {
|
||||
Paragraph::new(lines).wrap(Wrap { trim: false })
|
||||
}
|
||||
|
||||
fn summary(server: &str, state: &TunnelState, width: u16) -> Paragraph<'static> {
|
||||
let status = Span::styled(
|
||||
format!("{:<LABEL_WIDTH$} ", phase_label(state.phase)),
|
||||
Style::default().fg(if state.phase == TunnelPhase::Connected {
|
||||
Color::Green
|
||||
} else {
|
||||
Color::Yellow
|
||||
}),
|
||||
);
|
||||
let mut lines = if width >= 64 {
|
||||
vec![Line::from(vec![
|
||||
status,
|
||||
Span::raw(format!(
|
||||
"{} Uptime {}",
|
||||
state.transport.label(),
|
||||
uptime(state.elapsed_ms)
|
||||
)),
|
||||
])]
|
||||
} else {
|
||||
vec![
|
||||
Line::from(status),
|
||||
row("Transport", state.transport.label()),
|
||||
row("Uptime", uptime(state.elapsed_ms)),
|
||||
]
|
||||
};
|
||||
lines.insert(0, row("Server", server));
|
||||
paragraph(lines)
|
||||
}
|
||||
|
||||
fn traffic(statistics: &TunnelStatisticsSnapshot, width: u16) -> Paragraph<'static> {
|
||||
let mut lines = vec![heading("TRAFFIC")];
|
||||
if let Some(view) = statistics.view() {
|
||||
let label = match view.state {
|
||||
TunnelStatisticsState::Disabled => "disabled",
|
||||
TunnelStatisticsState::Waiting => "waiting for sample",
|
||||
TunnelStatisticsState::Fresh => "live",
|
||||
TunnelStatisticsState::Stale => "stale",
|
||||
TunnelStatisticsState::Ended => "ended",
|
||||
};
|
||||
lines[0] = heading(format!("TRAFFIC · {label}"));
|
||||
if let Some(sample) = &view.sample {
|
||||
if width >= 56 {
|
||||
let rows = [
|
||||
("Bytes", bytes(sample.received_bytes), bytes(sample.sent_bytes)),
|
||||
(
|
||||
"Packets",
|
||||
sample.received_packets.to_string(),
|
||||
sample.sent_packets.to_string(),
|
||||
),
|
||||
];
|
||||
// Size to the values, while keeping room for full u64 counters and a
|
||||
// visible gap even when both numeric columns are filled.
|
||||
let numeric_width = rows
|
||||
.iter()
|
||||
.flat_map(|(_, received, sent)| [received.len(), sent.len()])
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
.max(10);
|
||||
lines.push(Line::from(muted(format!(
|
||||
"{:<10}{:>numeric_width$} {:>numeric_width$}",
|
||||
"", "Received", "Sent"
|
||||
))));
|
||||
for (label, received, sent) in rows {
|
||||
lines.push(Line::from(vec![
|
||||
muted(format!("{label:<10}")),
|
||||
Span::raw(format!("{received:>numeric_width$} {sent:>numeric_width$}")),
|
||||
]));
|
||||
}
|
||||
} else {
|
||||
lines.push(row("Received", bytes(sample.received_bytes)));
|
||||
lines.push(row("Sent", bytes(sample.sent_bytes)));
|
||||
lines.push(row("Packets in", sample.received_packets.to_string()));
|
||||
lines.push(row("Packets out", sample.sent_packets.to_string()));
|
||||
}
|
||||
if view.state != TunnelStatisticsState::Fresh {
|
||||
if let Some(age) = view.sample_age_ms {
|
||||
lines.push(row("Sample age", format!("{} seconds", age / 1000)));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
lines.push(row("Statistics", "unavailable"));
|
||||
}
|
||||
paragraph(lines)
|
||||
}
|
||||
|
||||
fn list_rows(lines: &mut Vec<Line<'static>>, label: &str, value: &TunnelList) {
|
||||
if value.items.is_empty() && !value.truncated {
|
||||
lines.push(row(label, "none"));
|
||||
} else {
|
||||
for (index, item) in value.items.iter().enumerate() {
|
||||
lines.push(row(if index == 0 { label } else { "" }, item));
|
||||
}
|
||||
if value.truncated {
|
||||
lines.push(row("", format!("[truncated; {} total]", value.total_count)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn routes(lines: &mut Vec<Line<'static>>, label: &str, list: &TunnelList, width: u16) {
|
||||
lines.push(row(label, list.total_count.to_string()));
|
||||
// Only whole entries move between columns. Long individual entries wrap through
|
||||
// Paragraph rather than disappearing off the edge of a narrow terminal.
|
||||
let entries: Vec<_> = list.items.iter().map(|item| plain_text(item.as_bytes())).collect();
|
||||
let cell_width = entries.iter().map(|item| Line::raw(item).width()).max().unwrap_or(0) + 3;
|
||||
let columns = (width as usize / cell_width).clamp(1, 3);
|
||||
for chunk in entries.chunks(columns) {
|
||||
let mut spans = Vec::new();
|
||||
for (index, entry) in chunk.iter().enumerate() {
|
||||
spans.push(Span::raw(entry.clone()));
|
||||
if index + 1 < chunk.len() {
|
||||
spans.push(Span::raw(" ".repeat(cell_width - Line::raw(entry).width())));
|
||||
}
|
||||
}
|
||||
lines.push(Line::from(spans));
|
||||
}
|
||||
if list.truncated {
|
||||
lines.push(Line::raw(format!(
|
||||
"[truncated; showing {} of {}]",
|
||||
list.items.len(),
|
||||
list.total_count
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
fn details(state: &TunnelState, statistics: &TunnelStatisticsSnapshot, width: u16) -> Buffer {
|
||||
let traffic = traffic(statistics, width);
|
||||
let traffic_height = traffic.line_count(width) as u16;
|
||||
let mut tunnel = vec![heading("TUNNEL")];
|
||||
let mut dns = vec![heading("DNS")];
|
||||
let mut route_lines = vec![heading("ROUTES")];
|
||||
if let Some(config) = &state.configuration {
|
||||
tunnel.extend([
|
||||
row("Interface", config.interface.as_deref().unwrap_or("none")),
|
||||
row(
|
||||
"IPv4",
|
||||
config
|
||||
.ipv4
|
||||
.as_ref()
|
||||
.map(|address| address.display())
|
||||
.unwrap_or_else(|| "none".into()),
|
||||
),
|
||||
row(
|
||||
"IPv6",
|
||||
config
|
||||
.ipv6
|
||||
.as_ref()
|
||||
.map(|address| address.display())
|
||||
.unwrap_or_else(|| "none".into()),
|
||||
),
|
||||
row("Gateway", config.server_ip.as_deref().unwrap_or("none")),
|
||||
row(
|
||||
"MTU",
|
||||
config.mtu.map(|mtu| mtu.to_string()).unwrap_or_else(|| "none".into()),
|
||||
),
|
||||
]);
|
||||
list_rows(&mut dns, "Servers", &config.dns);
|
||||
list_rows(&mut dns, "Domains", &config.search_domains);
|
||||
list_rows(&mut dns, "Split DNS", &config.split_dns);
|
||||
routes(&mut route_lines, "Included", &config.included_routes, width);
|
||||
routes(&mut route_lines, "Excluded", &config.excluded_routes, width);
|
||||
if config.truncated {
|
||||
route_lines.push(row("Configuration", "truncated"));
|
||||
}
|
||||
} else {
|
||||
tunnel.push(row("Configuration", "unavailable"));
|
||||
}
|
||||
let tunnel = paragraph(tunnel);
|
||||
let dns = paragraph(dns);
|
||||
let routes = paragraph(route_lines);
|
||||
let columns = width >= 88;
|
||||
let column_width = if columns { (width - 4) / 2 } else { width };
|
||||
let tunnel_height = tunnel.line_count(column_width) as u16;
|
||||
let dns_height = dns.line_count(column_width) as u16;
|
||||
let network_height = if columns {
|
||||
tunnel_height.max(dns_height)
|
||||
} else {
|
||||
tunnel_height + 1 + dns_height
|
||||
};
|
||||
let network_y = traffic_height + 1;
|
||||
let routes_y = network_y + network_height + 1;
|
||||
let height = routes_y + routes.line_count(width) as u16;
|
||||
let mut buffer = Buffer::empty(Rect::new(0, 0, width, height));
|
||||
traffic.render(Rect::new(0, 0, width, traffic_height), &mut buffer);
|
||||
tunnel.render(Rect::new(0, network_y, column_width, tunnel_height), &mut buffer);
|
||||
let (dns_x, dns_y) = if columns {
|
||||
(column_width + 4, network_y)
|
||||
} else {
|
||||
(0, network_y + tunnel_height + 1)
|
||||
};
|
||||
dns.render(Rect::new(dns_x, dns_y, column_width, dns_height), &mut buffer);
|
||||
routes.render(Rect::new(0, routes_y, width, height - routes_y), &mut buffer);
|
||||
buffer
|
||||
}
|
||||
|
||||
pub(super) fn render_tunnel(
|
||||
frame: &mut Frame,
|
||||
area: Rect,
|
||||
server: &str,
|
||||
state: &TunnelState,
|
||||
statistics: &TunnelStatisticsSnapshot,
|
||||
scroll: &mut DetailScroll,
|
||||
) {
|
||||
if area.is_empty() {
|
||||
return;
|
||||
}
|
||||
let area = Rect {
|
||||
width: area.width.min(MAX_CONTENT_WIDTH),
|
||||
..area
|
||||
};
|
||||
let full_summary = summary(server, state, area.width);
|
||||
let summary = if full_summary.line_count(area.width) + 2 > area.height as usize {
|
||||
Paragraph::new(phase_label(state.phase))
|
||||
} else {
|
||||
full_summary
|
||||
};
|
||||
let summary_height = (summary.line_count(area.width) as u16).min(area.height);
|
||||
frame.render_widget(summary, Rect::new(area.x, area.y, area.width, summary_height));
|
||||
let body_y = summary_height.saturating_add(1).min(area.height);
|
||||
let viewport = Rect::new(area.x, area.y + body_y, area.width, area.height - body_y);
|
||||
let buffer = details(state, statistics, area.width);
|
||||
scroll.update(buffer.area.height, viewport.height);
|
||||
// Render the full detail layout with Ratatui, then expose just the scrolled rows.
|
||||
// This preserves wrapped fields and aligned columns through terminal resizes.
|
||||
for y in 0..viewport.height {
|
||||
if y + scroll.offset >= buffer.area.height {
|
||||
break;
|
||||
}
|
||||
for x in 0..viewport.width {
|
||||
frame.buffer_mut()[(viewport.x + x, viewport.y + y)] = buffer[(x, y + scroll.offset)].clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpapi::session::desktop::tunnel::{TunnelStatistics, TunnelStatisticsView, TunnelTransport};
|
||||
use ratatui::{Terminal, backend::TestBackend};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn state() -> TunnelState {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"tunnelId": "00000000-0000-0000-0000-000000000001",
|
||||
"sequence": "1", "phase": "connected", "configurationRevision": "1",
|
||||
"transport": "ipsecEsp", "elapsedMs": "177000",
|
||||
"configuration": {
|
||||
"interface": "tun0", "serverIp": "220.191.185.154",
|
||||
"ipv4": {"address": "10.197.121.152", "prefixLength": 32, "netmask": null},
|
||||
"ipv6": null, "mtu": 1439, "truncated": false,
|
||||
"dns": {"items": ["10.197.82.140", "10.15.70.11"], "totalCount": 2, "truncated": false},
|
||||
"searchDomains": {"items": ["corp.microstrategy.com"], "totalCount": 1, "truncated": false},
|
||||
"splitDns": {"items": [], "totalCount": 0, "truncated": false},
|
||||
"includedRoutes": {"items": ["10.15.70.11/32", "10.197.82.140/32", "185.199.108.0/22", "2001:db8:1234:5678::/64"], "totalCount": 5, "truncated": true},
|
||||
"excludedRoutes": {"items": ["192.168.0.0/16"], "totalCount": 1, "truncated": false}
|
||||
}
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
fn statistics(state: &TunnelState) -> TunnelStatisticsSnapshot {
|
||||
TunnelStatisticsSnapshot::Available(TunnelStatisticsView {
|
||||
sequence: 1,
|
||||
tunnel_id: state.tunnel_id,
|
||||
state_sequence: 1,
|
||||
phase: state.phase,
|
||||
transport: TunnelTransport::IpsecEsp,
|
||||
state: TunnelStatisticsState::Fresh,
|
||||
elapsed_ms: state.elapsed_ms,
|
||||
sample_age_ms: Some(0),
|
||||
sample: Some(TunnelStatistics {
|
||||
tunnel_id: state.tunnel_id,
|
||||
sequence: 1,
|
||||
state_sequence: 1,
|
||||
configuration_revision: 1,
|
||||
elapsed_ms: state.elapsed_ms,
|
||||
received_bytes: 1_258_291,
|
||||
sent_bytes: 71_578,
|
||||
received_packets: u64::MAX,
|
||||
sent_packets: 702,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
fn text(buffer: &Buffer) -> String {
|
||||
(0..buffer.area.height)
|
||||
.map(|y| {
|
||||
(0..buffer.area.width)
|
||||
.map(|x| buffer[(x, y)].symbol())
|
||||
.collect::<String>()
|
||||
.trim_end()
|
||||
.to_string()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_and_transport_share_a_column_through_status_changes() {
|
||||
let mut state = state();
|
||||
for width in [40, 64, 120] {
|
||||
for phase in [
|
||||
TunnelPhase::Establishing,
|
||||
TunnelPhase::Connected,
|
||||
TunnelPhase::Reconnecting,
|
||||
TunnelPhase::Ended,
|
||||
] {
|
||||
state.phase = phase;
|
||||
let mut buffer = Buffer::empty(Rect::new(0, 0, width, 8));
|
||||
summary("vpn.example.com", &state, width).render(buffer.area, &mut buffer);
|
||||
let rendered = text(&buffer);
|
||||
let server = rendered.lines().find(|line| line.contains("vpn.example.com")).unwrap();
|
||||
let transport = rendered.lines().find(|line| line.contains("IPsec (ESP)")).unwrap();
|
||||
assert_eq!(server.find("vpn.example.com"), Some(14));
|
||||
assert_eq!(
|
||||
transport.find("IPsec (ESP)"),
|
||||
server.find("vpn.example.com"),
|
||||
"{phase:?} at width {width}"
|
||||
);
|
||||
assert!(rendered.lines().any(|line| line.starts_with(phase_label(phase))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_layout_groups_settings_and_keeps_routes_and_counters_intact() {
|
||||
let state = state();
|
||||
let buffer = details(&state, &statistics(&state), 100);
|
||||
let text = text(&buffer);
|
||||
let headings = text.lines().find(|line| line.starts_with("TUNNEL")).unwrap();
|
||||
assert!(headings.contains("DNS"));
|
||||
assert!(text.contains("18446744073709551615"));
|
||||
assert!(text.contains("1.2 MiB"));
|
||||
assert!(text.contains("69.9 KiB"));
|
||||
assert!(text.contains("2001:db8:1234:5678::/64"));
|
||||
assert!(text.contains("[truncated; showing 4 of 5]"));
|
||||
assert!(text.contains("192.168.0.0/16"));
|
||||
let received_column = text
|
||||
.lines()
|
||||
.find(|line| line.contains("Received"))
|
||||
.unwrap()
|
||||
.find("Received")
|
||||
.unwrap()
|
||||
+ "Received".len();
|
||||
let bytes_column = text
|
||||
.lines()
|
||||
.find(|line| line.starts_with("Bytes"))
|
||||
.unwrap()
|
||||
.find("1.2 MiB")
|
||||
.unwrap()
|
||||
+ "1.2 MiB".len();
|
||||
assert_eq!(received_column, bytes_column);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traffic_columns_stay_compact_with_a_visible_gap() {
|
||||
let state = state();
|
||||
let mut stats = statistics(&state);
|
||||
let TunnelStatisticsSnapshot::Available(view) = &mut stats else {
|
||||
unreachable!()
|
||||
};
|
||||
view.sample.as_mut().unwrap().received_packets = 6518;
|
||||
let mut buffer = Buffer::empty(Rect::new(0, 0, 120, 4));
|
||||
traffic(&stats, 120).render(buffer.area, &mut buffer);
|
||||
let rendered = text(&buffer);
|
||||
for line in rendered.lines() {
|
||||
assert!(
|
||||
line.len() <= 40,
|
||||
"traffic row should not expand with the terminal: {line}"
|
||||
);
|
||||
}
|
||||
let TunnelStatisticsSnapshot::Available(view) = &mut stats else {
|
||||
unreachable!()
|
||||
};
|
||||
view.sample.as_mut().unwrap().received_packets = u64::MAX;
|
||||
view.sample.as_mut().unwrap().sent_packets = u64::MAX;
|
||||
let mut buffer = Buffer::empty(Rect::new(0, 0, 56, 4));
|
||||
traffic(&stats, 56).render(buffer.area, &mut buffer);
|
||||
assert!(text(&buffer).contains("18446744073709551615 18446744073709551615"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_terminal_keeps_content_left_aligned_and_within_120_columns() {
|
||||
let state = state();
|
||||
let stats = statistics(&state);
|
||||
let mut terminal = Terminal::new(TestBackend::new(220, 40)).unwrap();
|
||||
let mut scroll = DetailScroll::default();
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &stats, &mut scroll))
|
||||
.unwrap();
|
||||
let wide = terminal.backend().buffer().clone();
|
||||
terminal.backend_mut().resize(120, 40);
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &stats, &mut scroll))
|
||||
.unwrap();
|
||||
for y in 0..40 {
|
||||
for x in 0..220 {
|
||||
if x < 120 {
|
||||
assert_eq!(wide[(x, y)], terminal.backend().buffer()[(x, y)]);
|
||||
} else {
|
||||
assert_eq!(wide[(x, y)].symbol(), " ");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routes_use_at_most_three_columns_and_keep_every_entry() {
|
||||
let list = TunnelList {
|
||||
items: (1..=7).map(|n| format!("10.0.{n}.0/24")).collect(),
|
||||
total_count: 7,
|
||||
truncated: false,
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
routes(&mut lines, "Included", &list, 220);
|
||||
let mut buffer = Buffer::empty(Rect::new(0, 0, 220, 4));
|
||||
paragraph(lines).render(buffer.area, &mut buffer);
|
||||
let rendered = text(&buffer);
|
||||
let route_rows: Vec<_> = rendered.lines().skip(1).collect();
|
||||
assert_eq!(route_rows.len(), 3);
|
||||
for line in route_rows {
|
||||
assert!(line.split_whitespace().count() <= 3);
|
||||
}
|
||||
for entry in &list.items {
|
||||
assert!(rendered.contains(entry));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_layout_stacks_sections_without_losing_routes() {
|
||||
let state = state();
|
||||
for width in [24, 60, 87] {
|
||||
let text = text(&details(&state, &statistics(&state), width));
|
||||
assert!(text.lines().any(|line| line == "TUNNEL"));
|
||||
assert!(text.lines().any(|line| line == "DNS"));
|
||||
assert!(text.contains("2001:db8:1234:5678::/64"));
|
||||
assert!(text.contains("192.168.0.0/16"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrolling_reaches_last_route_and_resize_clamps_offset_with_summary_pinned() {
|
||||
let state = state();
|
||||
let statistics = statistics(&state);
|
||||
let mut terminal = Terminal::new(TestBackend::new(60, 14)).unwrap();
|
||||
let mut scroll = DetailScroll::default();
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &statistics, &mut scroll))
|
||||
.unwrap();
|
||||
assert!(scroll.can_scroll());
|
||||
scroll.handle_key(KeyCode::End);
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &statistics, &mut scroll))
|
||||
.unwrap();
|
||||
let rendered = text(terminal.backend().buffer());
|
||||
assert!(rendered.contains("Connected"));
|
||||
assert!(rendered.contains("vpn.example.com"));
|
||||
assert!(rendered.contains("192.168.0.0/16"));
|
||||
terminal.backend_mut().resize(100, 50);
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &statistics, &mut scroll))
|
||||
.unwrap();
|
||||
assert!(!scroll.can_scroll());
|
||||
assert_eq!(scroll.offset, 0);
|
||||
assert!(text(terminal.backend().buffer()).contains("TRAFFIC · live"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn very_short_body_keeps_status_and_scrollable_details_visible() {
|
||||
let state = state();
|
||||
for (width, height) in [(60, 6), (24, 3)] {
|
||||
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
|
||||
let mut scroll = DetailScroll::default();
|
||||
let stats = statistics(&state);
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &stats, &mut scroll))
|
||||
.unwrap();
|
||||
assert!(text(terminal.backend().buffer()).contains("Connected"));
|
||||
assert!(text(terminal.backend().buffer()).contains("TRAFFIC"));
|
||||
scroll.handle_key(KeyCode::End);
|
||||
terminal
|
||||
.draw(|frame| render_tunnel(frame, frame.area(), "vpn.example.com", &state, &stats, &mut scroll))
|
||||
.unwrap();
|
||||
assert!(text(terminal.backend().buffer()).contains("192.168.0.0/16"));
|
||||
scroll.handle_key(KeyCode::PageUp);
|
||||
let page_up = scroll.offset;
|
||||
assert!(page_up < scroll.maximum);
|
||||
scroll.handle_key(KeyCode::Up);
|
||||
assert!(scroll.offset < page_up);
|
||||
scroll.handle_key(KeyCode::Down);
|
||||
assert_eq!(scroll.offset, page_up);
|
||||
scroll.handle_key(KeyCode::PageDown);
|
||||
assert_eq!(scroll.offset, scroll.maximum);
|
||||
scroll.handle_key(KeyCode::Home);
|
||||
assert_eq!(scroll.offset, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_and_missing_configuration_remain_explicit() {
|
||||
let mut state = state();
|
||||
let mut statistics = statistics(&state);
|
||||
let TunnelStatisticsSnapshot::Available(view) = &mut statistics else {
|
||||
unreachable!()
|
||||
};
|
||||
view.state = TunnelStatisticsState::Stale;
|
||||
view.sample_age_ms = Some(12_000);
|
||||
state.configuration = None;
|
||||
let rendered = text(&details(&state, &statistics, 100));
|
||||
assert!(rendered.contains("TRAFFIC · stale"));
|
||||
assert!(rendered.contains("12 seconds"));
|
||||
assert!(rendered.contains("unavailable"));
|
||||
assert!(rendered.contains("1.2 MiB"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn units_and_long_sessions_are_explicit() {
|
||||
assert_eq!(bytes(1024), "1.0 KiB");
|
||||
assert_eq!(bytes(0), "0 B");
|
||||
assert_eq!(uptime(90_061_000), "25:01:01");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
//! Optional foreground presentation. Connection ownership stays with ConnectHandler.
|
||||
mod layout;
|
||||
mod notice;
|
||||
mod output;
|
||||
mod restoration;
|
||||
mod screen;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
io::IsTerminal,
|
||||
os::fd::AsRawFd,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc,
|
||||
},
|
||||
thread::JoinHandle,
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::log_format::LogFormat;
|
||||
use nix::unistd::{getpgrp, tcgetpgrp};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(crate) use notice::{NoticeLogger, session_notice};
|
||||
use output::OutputRouting;
|
||||
|
||||
pub(crate) type InternalMembers = Arc<Mutex<std::collections::BTreeMap<String, String>>>;
|
||||
|
||||
pub(crate) fn validate(format: LogFormat) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
format == LogFormat::Text,
|
||||
"--dashboard conflicts with --log-format json"
|
||||
);
|
||||
ensure!(
|
||||
std::env::var_os("TERM").is_some_and(|term| term != "dumb"),
|
||||
"--dashboard requires a capable terminal (TERM must not be dumb)"
|
||||
);
|
||||
let tty = terminal()?;
|
||||
ensure!(
|
||||
std::io::stderr().is_terminal(),
|
||||
"--dashboard requires stderr attached to the controlling terminal"
|
||||
);
|
||||
let stderr = output::duplicate(2)?;
|
||||
ensure!(
|
||||
same_terminal(&stderr, &tty),
|
||||
"--dashboard requires stderr attached to the controlling terminal"
|
||||
);
|
||||
ensure!(
|
||||
tcgetpgrp(&tty)? == getpgrp(),
|
||||
"--dashboard requires a foreground terminal"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn terminal() -> anyhow::Result<File> {
|
||||
OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open("/dev/tty")
|
||||
.context("--dashboard requires a controlling terminal")
|
||||
}
|
||||
|
||||
fn same_terminal(first: &File, second: &File) -> bool {
|
||||
// /dev/tty is a multiplexor node, so its st_rdev differs from the underlying
|
||||
// PTY. A session has one controlling terminal; compare terminal session IDs.
|
||||
let first_session = unsafe { nix::libc::tcgetsid(first.as_raw_fd()) };
|
||||
let second_session = unsafe { nix::libc::tcgetsid(second.as_raw_fd()) };
|
||||
first_session >= 0 && first_session == second_session
|
||||
}
|
||||
|
||||
pub(super) enum Content {
|
||||
Tunnel(Arc<gptunnel::TunnelMonitor>),
|
||||
Internal(InternalMembers),
|
||||
}
|
||||
|
||||
pub(super) enum Command {
|
||||
Suspend,
|
||||
Resume,
|
||||
}
|
||||
|
||||
pub(crate) struct Dashboard {
|
||||
routing: OutputRouting,
|
||||
server: String,
|
||||
cancellation: CancellationToken,
|
||||
stop: Arc<AtomicBool>,
|
||||
worker: Option<JoinHandle<()>>,
|
||||
signals: Vec<tokio::task::JoinHandle<()>>,
|
||||
error: Arc<Mutex<Option<String>>>,
|
||||
}
|
||||
|
||||
impl Dashboard {
|
||||
/// Install before native startup so persistent children inherit captured descriptors.
|
||||
pub(crate) fn prepare(server: String, cancellation: CancellationToken) -> anyhow::Result<Self> {
|
||||
let capture_stdout =
|
||||
std::io::stdout().is_terminal() && same_terminal(&output::duplicate(1)?, &output::duplicate(2)?);
|
||||
Ok(Self {
|
||||
routing: OutputRouting::install(capture_stdout, cancellation.clone())?,
|
||||
server,
|
||||
cancellation,
|
||||
stop: Arc::default(),
|
||||
worker: None,
|
||||
signals: Vec::new(),
|
||||
error: Arc::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn start_tunnel(&mut self, monitor: Arc<gptunnel::TunnelMonitor>) -> anyhow::Result<()> {
|
||||
self.start(Content::Tunnel(monitor.clone()))?;
|
||||
monitor.set_statistics_enabled(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn start_internal(&mut self, members: InternalMembers) -> anyhow::Result<()> {
|
||||
self.start(Content::Internal(members))
|
||||
}
|
||||
|
||||
fn start(&mut self, content: Content) -> anyhow::Result<()> {
|
||||
ensure!(self.worker.is_none(), "Dashboard already started");
|
||||
let (commands, receiver) = mpsc::channel();
|
||||
for (kind, command) in [
|
||||
(
|
||||
tokio::signal::unix::SignalKind::from_raw(nix::libc::SIGTSTP),
|
||||
Command::Suspend,
|
||||
),
|
||||
(
|
||||
tokio::signal::unix::SignalKind::from_raw(nix::libc::SIGCONT),
|
||||
Command::Resume,
|
||||
),
|
||||
] {
|
||||
let mut signal = tokio::signal::unix::signal(kind)?;
|
||||
let commands = commands.clone();
|
||||
self.signals.push(tokio::spawn(async move {
|
||||
while signal.recv().await.is_some() {
|
||||
let command = match command {
|
||||
Command::Suspend => Command::Suspend,
|
||||
Command::Resume => Command::Resume,
|
||||
};
|
||||
if commands.send(command).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
let mut hangup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())?;
|
||||
let cancellation = self.cancellation.clone();
|
||||
self.signals.push(tokio::spawn(async move {
|
||||
if hangup.recv().await.is_some() {
|
||||
cancellation.cancel();
|
||||
}
|
||||
}));
|
||||
let (ready, started) = mpsc::sync_channel(1);
|
||||
let context = screen::Context {
|
||||
terminal: terminal()?,
|
||||
output: self.routing.original_error.clone(),
|
||||
saved_stdout: self.routing.saved_output(),
|
||||
saved_stdin_flags: self.routing.saved_input_flags(),
|
||||
history: self.routing.history(),
|
||||
passthrough: self.routing.passthrough(),
|
||||
gate: self.routing.gate(),
|
||||
stop: self.stop.clone(),
|
||||
cancellation: self.cancellation.clone(),
|
||||
notice: notice::slot(),
|
||||
server: self.server.clone(),
|
||||
content,
|
||||
commands: receiver,
|
||||
};
|
||||
let error = self.error.clone();
|
||||
let cancellation = self.cancellation.clone();
|
||||
self.worker = Some(std::thread::Builder::new().name("dashboard".into()).spawn(move || {
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| screen::run(context, ready)));
|
||||
let failure = match result {
|
||||
Ok(Ok(())) => None,
|
||||
Ok(Err(failure)) => Some(format!("{failure:#}")),
|
||||
Err(_) => Some("Dashboard renderer panicked".into()),
|
||||
};
|
||||
if let Some(failure) = failure {
|
||||
*error.lock().unwrap_or_else(|error| error.into_inner()) = Some(failure);
|
||||
cancellation.cancel();
|
||||
}
|
||||
})?);
|
||||
started.recv().context("Dashboard stopped during initialization")??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Called after native shutdown and network cleanup, while capture still drains.
|
||||
pub(crate) fn finish(&mut self) -> anyhow::Result<()> {
|
||||
self.stop.store(true, Ordering::Release);
|
||||
if let Some(worker) = self.worker.take() {
|
||||
let _ = worker.join();
|
||||
}
|
||||
for signal in self.signals.drain(..) {
|
||||
signal.abort();
|
||||
}
|
||||
self.routing.restore();
|
||||
if let Some(error) = self.routing.take_error() {
|
||||
anyhow::bail!("Dashboard failed: {error}");
|
||||
}
|
||||
if let Some(error) = self.error.lock().unwrap_or_else(|error| error.into_inner()).take() {
|
||||
anyhow::bail!("Dashboard failed: {error}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dashboard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.finish();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use log::{Level, Log};
|
||||
|
||||
use super::output::plain_text;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Notice {
|
||||
pub(super) level: Level,
|
||||
pub(super) message: String,
|
||||
}
|
||||
|
||||
pub(super) type NoticeSlot = Arc<Mutex<Option<Notice>>>;
|
||||
static NOTICES: OnceLock<NoticeSlot> = OnceLock::new();
|
||||
|
||||
pub(super) fn slot() -> NoticeSlot {
|
||||
NOTICES.get_or_init(Arc::default).clone()
|
||||
}
|
||||
|
||||
pub(crate) fn session_notice(level: Level, message: &str) {
|
||||
if let Some(slot) = NOTICES.get() {
|
||||
let mut end = message.len().min(8192);
|
||||
while !message.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
*slot.lock().unwrap_or_else(|error| error.into_inner()) = Some(Notice {
|
||||
level,
|
||||
message: plain_text(message[..end].as_bytes()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata goes to the notice slot; descriptor capture owns the sole history entry.
|
||||
pub(crate) struct NoticeLogger {
|
||||
inner: env_logger::Logger,
|
||||
}
|
||||
|
||||
impl NoticeLogger {
|
||||
pub(crate) fn new(inner: env_logger::Logger) -> Self {
|
||||
let _ = slot();
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl Log for NoticeLogger {
|
||||
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
|
||||
self.inner.enabled(metadata)
|
||||
}
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
if self.inner.matches(record) {
|
||||
if record.level() <= Level::Warn {
|
||||
session_notice(record.level(), &record.args().to_string());
|
||||
}
|
||||
self.inner.log(record);
|
||||
}
|
||||
}
|
||||
fn flush(&self) {
|
||||
self.inner.flush();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn notice_tap_honors_message_filters_and_keeps_warning_severity() {
|
||||
let logger = NoticeLogger::new(
|
||||
env_logger::Builder::new()
|
||||
.parse_filters("warn/allowed")
|
||||
.target(env_logger::Target::Pipe(Box::new(std::io::sink())))
|
||||
.build(),
|
||||
);
|
||||
session_notice(Level::Info, "previous event");
|
||||
logger.log(
|
||||
&log::Record::builder()
|
||||
.level(Level::Warn)
|
||||
.args(format_args!("filtered warning"))
|
||||
.build(),
|
||||
);
|
||||
assert_eq!(slot().lock().unwrap().as_ref().unwrap().message, "previous event");
|
||||
logger.log(
|
||||
&log::Record::builder()
|
||||
.level(Level::Warn)
|
||||
.args(format_args!("allowed warning"))
|
||||
.build(),
|
||||
);
|
||||
let current = slot();
|
||||
let notice = current.lock().unwrap();
|
||||
assert_eq!(notice.as_ref().unwrap().level, Level::Warn);
|
||||
assert_eq!(notice.as_ref().unwrap().message, "allowed warning");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
//! Own terminal output while the native worker and its children are running.
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
fs::File,
|
||||
io::{self, Read, Write},
|
||||
os::fd::{AsFd, FromRawFd},
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
thread::{self, JoinHandle},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, FdFlag, OFlag, fcntl},
|
||||
poll::{PollFd, PollFlags, poll},
|
||||
unistd::{dup2_stderr, dup2_stdout},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const MAX_LINES: usize = 2_000;
|
||||
const MAX_BYTES: usize = 1_048_576;
|
||||
const MAX_LINE_BYTES: usize = 8_192;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct History {
|
||||
lines: VecDeque<String>,
|
||||
bytes: usize,
|
||||
discarded: u64,
|
||||
partial: [String; 2],
|
||||
}
|
||||
|
||||
impl History {
|
||||
fn push(&mut self, line: String) {
|
||||
self.bytes += line.len();
|
||||
self.lines.push_back(line);
|
||||
while self.lines.len() > MAX_LINES || self.bytes > MAX_BYTES {
|
||||
if let Some(line) = self.lines.pop_front() {
|
||||
self.bytes -= line.len();
|
||||
self.discarded = self.discarded.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn tail(&self, count: usize) -> Vec<String> {
|
||||
if count == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut lines = Vec::new();
|
||||
if self.discarded > 0 {
|
||||
lines.push(format!("[{} older log lines discarded]", self.discarded));
|
||||
}
|
||||
let partial_count = self.partial.iter().filter(|line| !line.is_empty()).count();
|
||||
let retained_count = count.saturating_sub(lines.len() + partial_count);
|
||||
lines.extend(
|
||||
self
|
||||
.lines
|
||||
.iter()
|
||||
.skip(self.lines.len().saturating_sub(retained_count))
|
||||
.cloned(),
|
||||
);
|
||||
lines.extend(self.partial.iter().filter(|line| !line.is_empty()).cloned());
|
||||
lines.truncate(count);
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn plain_text(bytes: &[u8]) -> String {
|
||||
String::from_utf8_lossy(&strip_ansi_escapes::strip(bytes))
|
||||
.chars()
|
||||
.filter(|ch| !ch.is_control() || *ch == '\t')
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct LineDecoder {
|
||||
bytes: Vec<u8>,
|
||||
truncated: bool,
|
||||
stream: usize,
|
||||
}
|
||||
|
||||
impl LineDecoder {
|
||||
fn new(stream: usize) -> Self {
|
||||
Self {
|
||||
bytes: Vec::new(),
|
||||
truncated: false,
|
||||
stream,
|
||||
}
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
let suffix = if self.truncated { " [line truncated]" } else { "" };
|
||||
format!("{}{suffix}", plain_text(&self.bytes))
|
||||
}
|
||||
|
||||
fn ingest(&mut self, bytes: &[u8], history: &mut History) {
|
||||
for byte in bytes {
|
||||
if *byte == b'\n' {
|
||||
history.push(self.text());
|
||||
self.bytes.clear();
|
||||
self.truncated = false;
|
||||
} else if self.bytes.len() < MAX_LINE_BYTES {
|
||||
self.bytes.push(*byte);
|
||||
} else {
|
||||
self.truncated = true;
|
||||
}
|
||||
}
|
||||
history.partial[self.stream] = if self.bytes.is_empty() && !self.truncated {
|
||||
String::new()
|
||||
} else {
|
||||
self.text()
|
||||
};
|
||||
}
|
||||
|
||||
fn finish(&mut self, history: &mut History) {
|
||||
if !self.bytes.is_empty() || self.truncated {
|
||||
history.push(self.text());
|
||||
}
|
||||
history.partial[self.stream].clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// The duplicate is close-on-exec: helpers inherit the capture pipe, never the renderer.
|
||||
pub(super) fn duplicate(fd: i32) -> io::Result<File> {
|
||||
let duplicate = unsafe { nix::libc::fcntl(fd, nix::libc::F_DUPFD_CLOEXEC, 3) };
|
||||
if duplicate < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(unsafe { File::from_raw_fd(duplicate) })
|
||||
}
|
||||
|
||||
pub(super) struct OutputRouting {
|
||||
pub(super) original_error: Arc<File>,
|
||||
original_input_flags: FdFlag,
|
||||
original_output: Option<Arc<File>>,
|
||||
history: Arc<Mutex<History>>,
|
||||
passthrough: Arc<AtomicBool>,
|
||||
stop: Arc<AtomicBool>,
|
||||
readers: Vec<JoinHandle<()>>,
|
||||
gate: Arc<Mutex<()>>,
|
||||
error: Arc<Mutex<Option<String>>>,
|
||||
restored: bool,
|
||||
}
|
||||
|
||||
impl OutputRouting {
|
||||
pub(super) fn install(capture_stdout: bool, cancellation: CancellationToken) -> anyhow::Result<Self> {
|
||||
io::stdout().flush()?;
|
||||
io::stderr().flush()?;
|
||||
unsafe {
|
||||
nix::libc::fflush(std::ptr::null_mut());
|
||||
}
|
||||
let mut routing = Self {
|
||||
original_error: Arc::new(duplicate(2)?),
|
||||
original_input_flags: FdFlag::from_bits_truncate(fcntl(io::stdin(), FcntlArg::F_GETFD)?),
|
||||
original_output: capture_stdout.then(|| duplicate(1).map(Arc::new)).transpose()?,
|
||||
history: Arc::default(),
|
||||
passthrough: Arc::new(AtomicBool::new(true)),
|
||||
stop: Arc::default(),
|
||||
readers: Vec::new(),
|
||||
gate: Arc::default(),
|
||||
error: Arc::default(),
|
||||
restored: false,
|
||||
};
|
||||
routing.capture(1, routing.original_error.clone(), cancellation.clone())?;
|
||||
if let Some(original) = routing.original_output.clone() {
|
||||
routing.capture(0, original, cancellation)?;
|
||||
}
|
||||
// Authentication may have initialized Crossterm's global reader with fd 0.
|
||||
// Keep that descriptor stable, but do not let executed helpers inherit it.
|
||||
// Script-TUN packet I/O continues through its separate VPNFD socket.
|
||||
fcntl(
|
||||
io::stdin(),
|
||||
FcntlArg::F_SETFD(routing.original_input_flags | FdFlag::FD_CLOEXEC),
|
||||
)?;
|
||||
Ok(routing)
|
||||
}
|
||||
|
||||
fn capture(&mut self, stream: usize, destination: Arc<File>, cancellation: CancellationToken) -> anyhow::Result<()> {
|
||||
let (reader, writer) = io::pipe()?;
|
||||
// Polling plus nonblocking reads lets teardown bound inherited pipe lifetimes.
|
||||
fcntl(&reader, FcntlArg::F_SETFL(OFlag::O_NONBLOCK))?;
|
||||
let history = self.history.clone();
|
||||
let passthrough = self.passthrough.clone();
|
||||
let stop = self.stop.clone();
|
||||
let gate = self.gate.clone();
|
||||
let error = self.error.clone();
|
||||
let thread = thread::Builder::new()
|
||||
.name(format!("dashboard-output-{stream}"))
|
||||
.spawn(move || {
|
||||
let mut reader = reader;
|
||||
let mut decoder = LineDecoder::new(stream);
|
||||
let mut buffer = [0; 4096];
|
||||
let mut deadline = None;
|
||||
loop {
|
||||
if stop.load(Ordering::Acquire) && deadline.is_none() {
|
||||
deadline = Some(Instant::now() + Duration::from_millis(250));
|
||||
}
|
||||
if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
|
||||
break;
|
||||
}
|
||||
let mut descriptors = [PollFd::new(reader.as_fd(), PollFlags::POLLIN)];
|
||||
match poll(&mut descriptors, 50u16) {
|
||||
Ok(0) => {
|
||||
if deadline.is_some() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(nix::errno::Errno::EINTR) => continue,
|
||||
Err(failure) => {
|
||||
*error.lock().unwrap_or_else(|error| error.into_inner()) =
|
||||
Some(format!("Cannot poll dashboard output: {failure}"));
|
||||
cancellation.cancel();
|
||||
break;
|
||||
}
|
||||
}
|
||||
match reader.read(&mut buffer) {
|
||||
Ok(0) => break,
|
||||
Ok(length) => {
|
||||
{
|
||||
let _gate = gate.lock().unwrap_or_else(|error| error.into_inner());
|
||||
if passthrough.load(Ordering::Acquire) {
|
||||
if let Err(failure) = (&*destination).write_all(&buffer[..length]) {
|
||||
*error.lock().unwrap_or_else(|error| error.into_inner()) =
|
||||
Some(format!("Cannot forward dashboard output: {failure}"));
|
||||
cancellation.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
decoder.ingest(
|
||||
&buffer[..length],
|
||||
&mut history.lock().unwrap_or_else(|error| error.into_inner()),
|
||||
);
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => continue,
|
||||
Err(failure) => {
|
||||
*error.lock().unwrap_or_else(|error| error.into_inner()) =
|
||||
Some(format!("Cannot read dashboard output: {failure}"));
|
||||
cancellation.cancel();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
decoder.finish(&mut history.lock().unwrap_or_else(|error| error.into_inner()));
|
||||
})
|
||||
.context("Cannot start dashboard output reader")?;
|
||||
self.readers.push(thread);
|
||||
if stream == 0 {
|
||||
dup2_stdout(&writer)?;
|
||||
} else {
|
||||
dup2_stderr(&writer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn history(&self) -> Arc<Mutex<History>> {
|
||||
self.history.clone()
|
||||
}
|
||||
pub(super) fn passthrough(&self) -> Arc<AtomicBool> {
|
||||
self.passthrough.clone()
|
||||
}
|
||||
pub(super) fn gate(&self) -> Arc<Mutex<()>> {
|
||||
self.gate.clone()
|
||||
}
|
||||
pub(super) fn saved_output(&self) -> Option<Arc<File>> {
|
||||
self.original_output.clone()
|
||||
}
|
||||
pub(super) fn saved_input_flags(&self) -> FdFlag {
|
||||
self.original_input_flags
|
||||
}
|
||||
pub(super) fn take_error(&self) -> Option<String> {
|
||||
self.error.lock().unwrap_or_else(|error| error.into_inner()).take()
|
||||
}
|
||||
|
||||
pub(super) fn restore(&mut self) {
|
||||
if self.restored {
|
||||
return;
|
||||
}
|
||||
let _ = io::stdout().flush();
|
||||
let _ = io::stderr().flush();
|
||||
unsafe {
|
||||
nix::libc::fflush(std::ptr::null_mut());
|
||||
}
|
||||
let _ = dup2_stderr(&*self.original_error);
|
||||
let _ = fcntl(io::stdin(), FcntlArg::F_SETFD(self.original_input_flags));
|
||||
if let Some(output) = &self.original_output {
|
||||
let _ = dup2_stdout(&**output);
|
||||
}
|
||||
self.stop.store(true, Ordering::Release);
|
||||
for reader in self.readers.drain(..) {
|
||||
let _ = reader.join();
|
||||
}
|
||||
self.restored = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OutputRouting {
|
||||
fn drop(&mut self) {
|
||||
self.restore();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn split_utf8_and_unterminated_lines_are_preserved_without_escape_commands() {
|
||||
for stream in [0, 1] {
|
||||
let mut history = History::default();
|
||||
let mut decoder = LineDecoder::new(stream);
|
||||
let bytes = "connected 日本語\x1b[2J\npartial".as_bytes();
|
||||
for byte in bytes {
|
||||
decoder.ingest(&[*byte], &mut history);
|
||||
}
|
||||
assert_eq!(history.tail(10), ["connected 日本語", "partial"]);
|
||||
decoder.finish(&mut history);
|
||||
assert_eq!(history.tail(10), ["connected 日本語", "partial"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_long_lines_and_history_are_bounded() {
|
||||
let mut history = History::default();
|
||||
let mut decoder = LineDecoder::new(0);
|
||||
decoder.ingest(&vec![b'x'; MAX_LINE_BYTES * 3], &mut history);
|
||||
decoder.ingest(b"\n", &mut history);
|
||||
assert!(history.lines[0].ends_with("[line truncated]"));
|
||||
for _ in 0..MAX_LINES + 10 {
|
||||
decoder.ingest(b"line\n", &mut history);
|
||||
}
|
||||
assert!(history.lines.len() <= MAX_LINES);
|
||||
assert!(history.bytes <= MAX_BYTES);
|
||||
assert!(history.tail(10)[0].contains("discarded"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Panic restoration must remain independent of renderer and output-ingestion locks.
|
||||
use std::{
|
||||
fs::File,
|
||||
io,
|
||||
os::fd::AsRawFd,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
pub(super) struct TerminalRestoration {
|
||||
terminal: File,
|
||||
error: Arc<File>,
|
||||
output: Option<Arc<File>>,
|
||||
input_flags: nix::fcntl::FdFlag,
|
||||
termios: nix::libc::termios,
|
||||
active: AtomicBool,
|
||||
}
|
||||
|
||||
impl TerminalRestoration {
|
||||
pub(super) fn install(
|
||||
terminal: File,
|
||||
error: Arc<File>,
|
||||
output: Option<Arc<File>>,
|
||||
input_flags: nix::fcntl::FdFlag,
|
||||
) -> io::Result<Arc<Self>> {
|
||||
let mut termios = std::mem::MaybeUninit::uninit();
|
||||
if unsafe { nix::libc::tcgetattr(terminal.as_raw_fd(), termios.as_mut_ptr()) } != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let restoration = Arc::new(Self {
|
||||
terminal,
|
||||
error,
|
||||
output,
|
||||
input_flags,
|
||||
termios: unsafe { termios.assume_init() },
|
||||
active: AtomicBool::new(false),
|
||||
});
|
||||
let previous = std::panic::take_hook();
|
||||
let panic_restoration = restoration.clone();
|
||||
std::panic::set_hook(Box::new(move |panic| {
|
||||
panic_restoration.restore();
|
||||
previous(panic);
|
||||
}));
|
||||
Ok(restoration)
|
||||
}
|
||||
|
||||
pub(super) fn arm(&self) {
|
||||
self.active.store(true, Ordering::Release);
|
||||
}
|
||||
pub(super) fn disarm(&self) {
|
||||
self.active.store(false, Ordering::Release);
|
||||
}
|
||||
|
||||
pub(super) fn restore(&self) {
|
||||
if !self.active.swap(false, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
unsafe {
|
||||
nix::libc::tcsetattr(self.terminal.as_raw_fd(), nix::libc::TCSANOW, &self.termios);
|
||||
let sequence = b"\x1b[?25h\x1b[?1049l";
|
||||
nix::libc::write(self.error.as_raw_fd(), sequence.as_ptr().cast(), sequence.len());
|
||||
nix::libc::dup2(self.error.as_raw_fd(), 2);
|
||||
nix::libc::fcntl(0, nix::libc::F_SETFD, self.input_flags.bits());
|
||||
if let Some(output) = &self.output {
|
||||
nix::libc::dup2(output.as_raw_fd(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
use std::{
|
||||
fs::File,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc,
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use anyhow::{Context as _, ensure};
|
||||
use crossterm::{
|
||||
cursor::Show,
|
||||
event::{self, Event, KeyCode, KeyEventKind, KeyModifiers},
|
||||
execute,
|
||||
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
|
||||
};
|
||||
use gpapi::session::desktop::tunnel::TunnelPhase;
|
||||
use log::Level;
|
||||
use nix::unistd::{getpgrp, tcgetpgrp};
|
||||
use ratatui::{
|
||||
Terminal,
|
||||
backend::CrosstermBackend,
|
||||
layout::{Constraint, Layout},
|
||||
style::{Color, Modifier, Style},
|
||||
text::Line,
|
||||
widgets::{Block, Borders, Paragraph, Wrap},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{
|
||||
Command, Content,
|
||||
layout::{DetailScroll, phase_label, render_tunnel, row},
|
||||
notice::{Notice, NoticeSlot},
|
||||
output::{History, plain_text},
|
||||
restoration::TerminalRestoration,
|
||||
};
|
||||
|
||||
pub(super) struct Context {
|
||||
pub(super) terminal: File,
|
||||
pub(super) output: Arc<File>,
|
||||
pub(super) saved_stdout: Option<Arc<File>>,
|
||||
pub(super) saved_stdin_flags: nix::fcntl::FdFlag,
|
||||
pub(super) history: Arc<Mutex<History>>,
|
||||
pub(super) passthrough: Arc<AtomicBool>,
|
||||
pub(super) gate: Arc<Mutex<()>>,
|
||||
pub(super) stop: Arc<AtomicBool>,
|
||||
pub(super) cancellation: CancellationToken,
|
||||
pub(super) notice: NoticeSlot,
|
||||
pub(super) server: String,
|
||||
pub(super) content: Content,
|
||||
pub(super) commands: mpsc::Receiver<Command>,
|
||||
}
|
||||
|
||||
struct Screen {
|
||||
terminal: Terminal<CrosstermBackend<File>>,
|
||||
restore: Arc<TerminalRestoration>,
|
||||
controlling_terminal: File,
|
||||
passthrough: Arc<AtomicBool>,
|
||||
gate: Arc<Mutex<()>>,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl Screen {
|
||||
fn new(context: &Context) -> anyhow::Result<Self> {
|
||||
let restore = TerminalRestoration::install(
|
||||
context.terminal.try_clone()?,
|
||||
context.output.clone(),
|
||||
context.saved_stdout.clone(),
|
||||
context.saved_stdin_flags,
|
||||
)?;
|
||||
let terminal = Terminal::new(CrosstermBackend::new(context.output.try_clone()?))?;
|
||||
let mut screen = Self {
|
||||
terminal,
|
||||
restore,
|
||||
controlling_terminal: context.terminal.try_clone()?,
|
||||
passthrough: context.passthrough.clone(),
|
||||
gate: context.gate.clone(),
|
||||
active: false,
|
||||
};
|
||||
screen.enter()?;
|
||||
Ok(screen)
|
||||
}
|
||||
|
||||
fn enter(&mut self) -> anyhow::Result<()> {
|
||||
if self.active {
|
||||
return Ok(());
|
||||
}
|
||||
ensure!(
|
||||
tcgetpgrp(&self.controlling_terminal)? == getpgrp(),
|
||||
"Dashboard is no longer in the foreground"
|
||||
);
|
||||
let _gate = self.gate.lock().unwrap_or_else(|error| error.into_inner());
|
||||
self.passthrough.store(false, Ordering::Release);
|
||||
// Arm before changing termios, including partial initialization failures.
|
||||
self.restore.arm();
|
||||
self.active = true;
|
||||
enable_raw_mode()?;
|
||||
execute!(self.terminal.backend_mut(), EnterAlternateScreen)?;
|
||||
// Terminal::clear queries cursor position through process stdout. Fullscreen
|
||||
// resize clears and resets buffers through our saved terminal backend only.
|
||||
self.terminal.resize(self.terminal.size()?.into())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn leave(&mut self) {
|
||||
if !self.active {
|
||||
return;
|
||||
}
|
||||
let _gate = self.gate.lock().unwrap_or_else(|error| error.into_inner());
|
||||
let _ = disable_raw_mode();
|
||||
let _ = execute!(self.terminal.backend_mut(), Show, LeaveAlternateScreen);
|
||||
self.restore.disarm();
|
||||
self.passthrough.store(true, Ordering::Release);
|
||||
self.active = false;
|
||||
}
|
||||
|
||||
fn suspend(&mut self) {
|
||||
self.leave();
|
||||
// SIGSTOP avoids recursion through our SIGTSTP listener. The shell resumes us.
|
||||
unsafe {
|
||||
nix::libc::raise(nix::libc::SIGSTOP);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Screen {
|
||||
fn drop(&mut self) {
|
||||
self.leave();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run(context: Context, ready: mpsc::SyncSender<anyhow::Result<()>>) -> anyhow::Result<()> {
|
||||
let screen = Screen::new(&context);
|
||||
let mut screen = match screen {
|
||||
Ok(screen) => {
|
||||
let _ = ready.send(Ok(()));
|
||||
screen
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = ready.send(Err(anyhow::anyhow!("{error:#}")));
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let mut logs = false;
|
||||
let mut scroll = DetailScroll::default();
|
||||
let mut next_draw = Instant::now();
|
||||
let mut dirty = true;
|
||||
while !context.stop.load(Ordering::Acquire) {
|
||||
for command in context.commands.try_iter() {
|
||||
match command {
|
||||
Command::Suspend => screen.suspend(),
|
||||
Command::Resume => {}
|
||||
}
|
||||
}
|
||||
if !screen.active {
|
||||
if tcgetpgrp(&context.terminal)? == getpgrp() {
|
||||
screen.enter()?;
|
||||
} else {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if dirty || Instant::now() >= next_draw {
|
||||
draw(&mut screen.terminal, &context, logs, &mut scroll)?;
|
||||
next_draw = Instant::now() + Duration::from_secs(1);
|
||||
dirty = false;
|
||||
}
|
||||
if event::poll(Duration::from_millis(100)).context("Cannot read dashboard input")? {
|
||||
if let Event::Key(key) = event::read()? {
|
||||
if key.kind != KeyEventKind::Press {
|
||||
continue;
|
||||
}
|
||||
match key.code {
|
||||
KeyCode::Tab | KeyCode::BackTab => {
|
||||
logs = !logs;
|
||||
dirty = true;
|
||||
}
|
||||
KeyCode::Up | KeyCode::Down | KeyCode::PageUp | KeyCode::PageDown | KeyCode::Home | KeyCode::End if !logs => {
|
||||
scroll.handle_key(key.code);
|
||||
dirty = true;
|
||||
}
|
||||
KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
context.cancellation.cancel();
|
||||
dirty = true;
|
||||
}
|
||||
KeyCode::Char('z') if key.modifiers.contains(KeyModifiers::CONTROL) => screen.suspend(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn draw(
|
||||
terminal: &mut Terminal<CrosstermBackend<File>>,
|
||||
context: &Context,
|
||||
logs: bool,
|
||||
scroll: &mut DetailScroll,
|
||||
) -> anyhow::Result<()> {
|
||||
terminal.draw(|frame| {
|
||||
let area = frame.area();
|
||||
if area.height < 8 || area.width < 24 {
|
||||
frame.render_widget(
|
||||
Paragraph::new("GP Connect\nCtrl+C Disconnect").wrap(Wrap { trim: false }),
|
||||
area,
|
||||
);
|
||||
return;
|
||||
}
|
||||
let compact = area.height < 18;
|
||||
let footer_height = if area.width < 80 { 2 } else { 1 };
|
||||
let [header, body, notice, footer] = Layout::vertical([
|
||||
Constraint::Length(2),
|
||||
Constraint::Min(1),
|
||||
Constraint::Length(if compact { 1 } else { 3 }),
|
||||
Constraint::Length(footer_height),
|
||||
])
|
||||
.areas(area);
|
||||
let view = if logs { "Live logs" } else { "Dashboard" };
|
||||
frame.render_widget(
|
||||
Paragraph::new(format!(" GP Connect · {view}"))
|
||||
.style(Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD))
|
||||
.block(Block::default().borders(Borders::BOTTOM)),
|
||||
header,
|
||||
);
|
||||
let mut lines = vec![row("Server", context.server.clone()), Line::default()];
|
||||
if logs {
|
||||
let history = context.history.lock().unwrap_or_else(|error| error.into_inner());
|
||||
let tail = history.tail(body.height as usize);
|
||||
lines = tail.into_iter().map(Line::raw).collect();
|
||||
let skip = lines.len().saturating_sub(body.height as usize);
|
||||
lines.drain(..skip);
|
||||
} else {
|
||||
match &context.content {
|
||||
Content::Tunnel(monitor) => {
|
||||
render_tunnel(
|
||||
frame,
|
||||
body,
|
||||
&context.server,
|
||||
&monitor.state(),
|
||||
&monitor.statistics(),
|
||||
scroll,
|
||||
);
|
||||
}
|
||||
Content::Internal(members) => {
|
||||
lines.push(row("Status", "Internal network session"));
|
||||
lines.push(Line::raw("Tunnel statistics unavailable (non-tunnel session)"));
|
||||
lines.push(Line::default());
|
||||
lines.extend(
|
||||
members
|
||||
.lock()
|
||||
.unwrap_or_else(|error| error.into_inner())
|
||||
.values()
|
||||
.map(|member| Line::raw(plain_text(member.as_bytes()))),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if logs || matches!(context.content, Content::Internal(_)) {
|
||||
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), body);
|
||||
}
|
||||
let current = context.notice.lock().unwrap_or_else(|error| error.into_inner()).clone();
|
||||
let current = match &context.content {
|
||||
Content::Tunnel(monitor) => {
|
||||
let state = monitor.state();
|
||||
Some(notice_for_status(current, state.phase, state.transport))
|
||||
}
|
||||
Content::Internal(_) => current,
|
||||
};
|
||||
if let Some(current) = current {
|
||||
let color = if current.level <= Level::Warn {
|
||||
Color::Yellow
|
||||
} else {
|
||||
Color::Gray
|
||||
};
|
||||
let block = if compact {
|
||||
Block::default()
|
||||
} else {
|
||||
Block::default().title("Latest event").borders(Borders::TOP)
|
||||
};
|
||||
frame.render_widget(
|
||||
Paragraph::new(current.message)
|
||||
.style(Style::default().fg(color))
|
||||
.wrap(Wrap { trim: false })
|
||||
.block(block),
|
||||
notice,
|
||||
);
|
||||
}
|
||||
let ending = if context.cancellation.is_cancelled() {
|
||||
"Disconnecting…"
|
||||
} else {
|
||||
"Ctrl+C Disconnect"
|
||||
};
|
||||
frame.render_widget(
|
||||
footer_text(logs, ending, scroll.can_scroll(), area.width).style(Style::default().fg(Color::DarkGray)),
|
||||
footer,
|
||||
);
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn footer_text(logs: bool, ending: &str, scrollable: bool, width: u16) -> Paragraph<'static> {
|
||||
let view = if logs { "Dashboard" } else { "Logs" };
|
||||
let scrolling = scrollable && !logs;
|
||||
let text = if width < 80 {
|
||||
format!("{ending}\nTab {view}{}", if scrolling { " ↑↓ Scroll" } else { "" })
|
||||
} else {
|
||||
format!(
|
||||
"Tab {view} {ending}{}",
|
||||
if scrolling { " ↑↓/PgUp/PgDn Scroll" } else { "" }
|
||||
)
|
||||
};
|
||||
Paragraph::new(text)
|
||||
}
|
||||
|
||||
fn notice_for_status(
|
||||
notice: Option<Notice>,
|
||||
phase: TunnelPhase,
|
||||
transport: gpapi::session::desktop::tunnel::TunnelTransport,
|
||||
) -> Notice {
|
||||
notice.unwrap_or_else(|| Notice {
|
||||
level: Level::Info,
|
||||
message: format!("{} · {}", phase_label(phase), transport.label()),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn narrow_footer_keeps_disconnect_switch_and_scroll_hints_visible() {
|
||||
use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
|
||||
let area = Rect::new(0, 0, 24, 2);
|
||||
let mut buffer = Buffer::empty(area);
|
||||
footer_text(false, "Ctrl+C Disconnect", true, area.width).render(area, &mut buffer);
|
||||
let lines: Vec<String> = (0..2)
|
||||
.map(|y| (0..24).map(|x| buffer[(x, y)].symbol()).collect())
|
||||
.collect();
|
||||
assert!(lines[0].contains("Ctrl+C Disconnect"));
|
||||
assert!(lines[1].contains("Tab Logs"));
|
||||
assert!(lines[1].contains("↑↓ Scroll"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_transitions_cannot_overwrite_an_existing_warning() {
|
||||
use gpapi::session::desktop::tunnel::TunnelTransport;
|
||||
let warning = Notice {
|
||||
level: Level::Warn,
|
||||
message: "ESP unavailable; using SSL".into(),
|
||||
};
|
||||
let first = notice_for_status(Some(warning), TunnelPhase::Connected, TunnelTransport::SslTls);
|
||||
let reconnecting = notice_for_status(Some(first), TunnelPhase::Reconnecting, TunnelTransport::Unavailable);
|
||||
let resumed = notice_for_status(Some(reconnecting), TunnelPhase::Connected, TunnelTransport::IpsecEsp);
|
||||
assert_eq!(resumed.level, Level::Warn);
|
||||
assert_eq!(resumed.message, "ESP unavailable; using SSL");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
//! Terminal integration runs in child test processes so descriptor/signal changes
|
||||
//! cannot capture another test's output or change its controlling terminal.
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{self, Read, Write},
|
||||
os::unix::process::CommandExt,
|
||||
process::{Child, Command, Stdio},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, OFlag, fcntl},
|
||||
pty::{Winsize, openpty},
|
||||
sys::signal::{Signal, kill},
|
||||
unistd::Pid,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
struct Fixture {
|
||||
child: Child,
|
||||
master: File,
|
||||
slave: File,
|
||||
output: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn start(piped: bool) -> Self {
|
||||
Self::start_mode(if piped { "piped" } else { "terminal" }, piped)
|
||||
}
|
||||
|
||||
fn start_mode(mode: &str, piped: bool) -> Self {
|
||||
let mut command = Command::new(std::env::current_exe().unwrap());
|
||||
command
|
||||
.args([
|
||||
"--exact",
|
||||
"dashboard::tests::terminal_fixture",
|
||||
"--ignored",
|
||||
"--nocapture",
|
||||
])
|
||||
.env("GPCLIENT_DASHBOARD_FIXTURE", mode);
|
||||
Self::spawn(command, piped)
|
||||
}
|
||||
|
||||
fn spawn(mut command: Command, piped: bool) -> Self {
|
||||
let pty = openpty(
|
||||
Some(&Winsize {
|
||||
ws_row: 40,
|
||||
ws_col: 100,
|
||||
ws_xpixel: 0,
|
||||
ws_ypixel: 0,
|
||||
}),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let master = File::from(pty.master);
|
||||
let slave = File::from(pty.slave);
|
||||
fcntl(&master, FcntlArg::F_SETFL(OFlag::O_NONBLOCK)).unwrap();
|
||||
command
|
||||
.env("TERM", "xterm-256color")
|
||||
.stdin(if piped {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::from(slave.try_clone().unwrap())
|
||||
})
|
||||
.stdout(if piped {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::from(slave.try_clone().unwrap())
|
||||
})
|
||||
.stderr(Stdio::from(slave.try_clone().unwrap()));
|
||||
unsafe {
|
||||
command.pre_exec(|| {
|
||||
if nix::libc::setsid() < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if nix::libc::ioctl(2, nix::libc::TIOCSCTTY as _, 0) < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let no_core = nix::libc::rlimit {
|
||||
rlim_cur: 0,
|
||||
rlim_max: 0,
|
||||
};
|
||||
nix::libc::setrlimit(nix::libc::RLIMIT_CORE, &no_core);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let mut child = command.spawn().unwrap();
|
||||
if piped {
|
||||
child.stdin.take().unwrap().write_all(b"fixture-cookie\n").unwrap();
|
||||
}
|
||||
Self {
|
||||
child,
|
||||
master,
|
||||
slave,
|
||||
output: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn drain(&mut self) {
|
||||
let mut bytes = [0; 8192];
|
||||
loop {
|
||||
match self.master.read(&mut bytes) {
|
||||
Ok(0) => break,
|
||||
Ok(length) => self.output.extend_from_slice(&bytes[..length]),
|
||||
Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
|
||||
Err(error) if error.raw_os_error() == Some(nix::libc::EIO) => break,
|
||||
Err(error) => panic!("PTY read: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_text(&mut self, text: &str) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
self.drain();
|
||||
let plain = strip_ansi_escapes::strip(&self.output);
|
||||
if String::from_utf8_lossy(&plain).contains(text) {
|
||||
return;
|
||||
}
|
||||
if let Some(status) = self.child.try_wait().unwrap() {
|
||||
panic!(
|
||||
"Fixture exited {status} before {text:?}: {}",
|
||||
String::from_utf8_lossy(&self.output)
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"Missing {text:?}: {}",
|
||||
String::from_utf8_lossy(&self.output)
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&mut self) {
|
||||
self.wait_text("DASHBOARD_RESTORED");
|
||||
let attrs = nix::sys::termios::tcgetattr(&self.slave).unwrap();
|
||||
assert!(attrs.local_flags.contains(nix::sys::termios::LocalFlags::ICANON));
|
||||
assert!(attrs.local_flags.contains(nix::sys::termios::LocalFlags::ECHO));
|
||||
self.master.write_all(b"\n").unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
self.drain();
|
||||
if let Some(status) = self.child.try_wait().unwrap() {
|
||||
assert!(
|
||||
status.success(),
|
||||
"Fixture failed {status}: {}",
|
||||
String::from_utf8_lossy(&self.output)
|
||||
);
|
||||
self.drain();
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "Fixture did not restore/exit");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert!(String::from_utf8_lossy(&self.output).contains("DASHBOARD_RESTORED"));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// A failed assertion must not leave a suspended child or its helper alive.
|
||||
let _ = kill(Pid::from_raw(self.child.id() as i32), Signal::SIGCONT);
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_switches_to_captured_child_logs_and_ctrl_c_restores_terminal() {
|
||||
let mut fixture = Fixture::start(false);
|
||||
fixture.wait_text("Internal");
|
||||
fixture.master.write_all(b"\t").unwrap();
|
||||
fixture.wait_text("Live logs");
|
||||
fixture.wait_text("child-stderr-after-entry");
|
||||
fixture.master.write_all(b"\x03").unwrap();
|
||||
fixture.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warning_before_first_tunnel_frame_remains_visible() {
|
||||
let mut fixture = Fixture::start_mode("tunnel", false);
|
||||
fixture.wait_text("initial-fallback-warning");
|
||||
fixture.master.write_all(b"\x03").unwrap();
|
||||
fixture.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connected_tunnel_samples_statistics_and_accepts_ctrl_c() {
|
||||
let mut fixture = Fixture::start_mode("active-tunnel", false);
|
||||
fixture.wait_text("IPsec");
|
||||
fixture.wait_text("(ESP)");
|
||||
fixture.wait_text("Received");
|
||||
fixture.wait_text("4.0");
|
||||
fixture.master.write_all(b"\x03").unwrap();
|
||||
fixture.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authenticated_terminal_input_remains_usable_after_dashboard_entry() {
|
||||
let mut fixture = Fixture::start_mode("prompted-tunnel", false);
|
||||
fixture.wait_text("Received");
|
||||
fixture.master.write_all(b"\t").unwrap();
|
||||
fixture.wait_text("Live logs");
|
||||
fixture.master.write_all(b"\x03").unwrap();
|
||||
fixture.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn piped_credentials_and_stdout_redirection_preserve_their_streams() {
|
||||
let mut fixture = Fixture::start(true);
|
||||
fixture.wait_text("Internal");
|
||||
fixture.master.write_all(b"\x03").unwrap();
|
||||
fixture.finish();
|
||||
let mut output = String::new();
|
||||
fixture
|
||||
.child
|
||||
.stdout
|
||||
.take()
|
||||
.unwrap()
|
||||
.read_to_string(&mut output)
|
||||
.unwrap();
|
||||
assert!(output.contains("redirected-stdout"));
|
||||
assert!(!output.contains('\x1b'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_termination_and_suspend_resume_restore_terminal() {
|
||||
let mut fixture = Fixture::start(false);
|
||||
fixture.wait_text("Internal");
|
||||
kill(Pid::from_raw(fixture.child.id() as i32), Signal::SIGTSTP).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let attrs = nix::sys::termios::tcgetattr(&fixture.slave).unwrap();
|
||||
if attrs.local_flags.contains(nix::sys::termios::LocalFlags::ICANON) {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "suspend did not restore termios");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
kill(Pid::from_raw(fixture.child.id() as i32), Signal::SIGCONT).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
kill(Pid::from_raw(fixture.child.id() as i32), Signal::SIGTERM).unwrap();
|
||||
fixture.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_panic_hook_restores_terminal_with_panic_abort() {
|
||||
let dependencies = std::env::current_exe().unwrap().parent().unwrap().to_path_buf();
|
||||
let nix = std::fs::read_dir(&dependencies)
|
||||
.unwrap()
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.find(|path| {
|
||||
path.file_name().unwrap().to_string_lossy().starts_with("libnix-")
|
||||
&& path.extension().is_some_and(|ext| ext == "rlib")
|
||||
})
|
||||
.expect("compiled nix rlib");
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let binary = directory.path().join("dashboard-abort");
|
||||
let build = Command::new("rustc")
|
||||
.args(["--edition=2024", "-C", "panic=abort", "-A", "dead_code"])
|
||||
.arg(format!(
|
||||
"{}/tests/fixtures/dashboard_abort.rs",
|
||||
env!("CARGO_MANIFEST_DIR")
|
||||
))
|
||||
.arg("--extern")
|
||||
.arg(format!("nix={}", nix.display()))
|
||||
.arg("-L")
|
||||
.arg(format!("dependency={}", dependencies.display()))
|
||||
.arg("-o")
|
||||
.arg(&binary)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
build.status.success(),
|
||||
"Abort fixture compilation failed: {}",
|
||||
String::from_utf8_lossy(&build.stderr)
|
||||
);
|
||||
let mut fixture = Fixture::spawn(Command::new(binary), false);
|
||||
fixture.wait_text("ABORT_FIXTURE_READY");
|
||||
fixture.master.write_all(b"x").unwrap();
|
||||
fixture.wait_text("ABORT_HOOK_RESTORED");
|
||||
let attrs = nix::sys::termios::tcgetattr(&fixture.slave).unwrap();
|
||||
assert!(attrs.local_flags.contains(nix::sys::termios::LocalFlags::ICANON));
|
||||
assert!(attrs.local_flags.contains(nix::sys::termios::LocalFlags::ECHO));
|
||||
fixture.master.write_all(b"\n").unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
fixture.drain();
|
||||
if let Some(status) = fixture.child.try_wait().unwrap() {
|
||||
assert!(!status.success(), "panic=abort fixture unexpectedly succeeded");
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "abort fixture did not exit");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
fixture.drain();
|
||||
assert!(String::from_utf8_lossy(&fixture.output).contains("intentional abort-hook fixture panic"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "runs in an isolated PTY subprocess"]
|
||||
fn terminal_fixture() {
|
||||
let mode = std::env::var("GPCLIENT_DASHBOARD_FIXTURE").expect("subprocess fixture only");
|
||||
if mode == "active-tunnel" || mode == "prompted-tunnel" {
|
||||
env_logger::builder()
|
||||
.filter_level(log::LevelFilter::Info)
|
||||
.try_init()
|
||||
.unwrap();
|
||||
}
|
||||
if mode == "piped" {
|
||||
let mut credentials = String::new();
|
||||
std::io::stdin().read_to_string(&mut credentials).unwrap();
|
||||
assert_eq!(credentials, "fixture-cookie\n");
|
||||
}
|
||||
validate(LogFormat::Text).unwrap();
|
||||
if mode == "prompted-tunnel" {
|
||||
// Authentication prompts use Crossterm before dashboard output routing.
|
||||
// Exercise its real global reader initialization while stdin is the TTY.
|
||||
let _ = crossterm::event::poll(Duration::from_millis(1)).unwrap();
|
||||
}
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
runtime.block_on(async {
|
||||
let cancellation = CancellationToken::new();
|
||||
let signal_cancel = cancellation.clone();
|
||||
let signals = tokio::spawn(async move {
|
||||
gpapi::utils::shutdown_signal().await;
|
||||
signal_cancel.cancel();
|
||||
});
|
||||
let input_flags = fcntl(std::io::stdin(), FcntlArg::F_GETFD).unwrap();
|
||||
let mut dashboard = Dashboard::prepare("vpn.example.com".into(), cancellation.clone()).unwrap();
|
||||
eprintln!("child-stderr-before-entry");
|
||||
// Native VPN helpers exec /bin/sh without Rust's standard-fd repair.
|
||||
let mut child = Command::new("/bin/sh")
|
||||
.args([
|
||||
"-c",
|
||||
r#"
|
||||
sleep 1
|
||||
if test -t 0; then exit 1; fi
|
||||
if read -r input 2>/dev/null; then exit 1; fi
|
||||
printf '%s\n' child-stderr-after-entry >&2
|
||||
"#,
|
||||
])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let members = InternalMembers::default();
|
||||
members
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert("internal.example.com".into(), "internal.example.com: Healthy".into());
|
||||
let mut native = None;
|
||||
let monitor = if mode == "tunnel" || mode == "active-tunnel" || mode == "prompted-tunnel" {
|
||||
let vpn = Arc::new(
|
||||
openconnect::Vpn::builder("vpn.example.com", "fixture-cookie")
|
||||
.network_configuration_handler(|_| Ok(()))
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
let monitor = gptunnel::TunnelMonitor::attach(vpn.clone());
|
||||
if mode == "active-tunnel" || mode == "prompted-tunnel" {
|
||||
native = Some(active_native_fixture(vpn, cancellation.clone()));
|
||||
}
|
||||
let _ = notice::slot();
|
||||
session_notice(log::Level::Warn, "initial-fallback-warning");
|
||||
dashboard.start_tunnel(monitor.clone()).unwrap();
|
||||
Some(monitor)
|
||||
} else {
|
||||
dashboard.start_internal(members).unwrap();
|
||||
None
|
||||
};
|
||||
println!("redirected-stdout");
|
||||
tokio::time::timeout(Duration::from_secs(15), cancellation.cancelled())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
child.wait().unwrap().success(),
|
||||
"helper must not inherit dashboard input"
|
||||
);
|
||||
if let Some(monitor) = monitor {
|
||||
monitor.stop().await;
|
||||
}
|
||||
if let Some(native) = native {
|
||||
native.join().unwrap();
|
||||
}
|
||||
dashboard.finish().unwrap();
|
||||
assert_eq!(fcntl(std::io::stdin(), FcntlArg::F_GETFD).unwrap(), input_flags);
|
||||
signals.abort();
|
||||
eprintln!("DASHBOARD_RESTORED");
|
||||
let mut acknowledgement = String::new();
|
||||
let mut tty = std::fs::OpenOptions::new().read(true).open("/dev/tty").unwrap();
|
||||
use std::io::BufRead;
|
||||
std::io::BufReader::new(&mut tty)
|
||||
.read_line(&mut acknowledgement)
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
fn active_native_fixture(vpn: Arc<openconnect::Vpn>, cancellation: CancellationToken) -> std::thread::JoinHandle<()> {
|
||||
use std::{
|
||||
ffi::{c_int, c_void},
|
||||
os::fd::AsRawFd,
|
||||
os::unix::net::UnixStream,
|
||||
};
|
||||
#[repr(C)]
|
||||
struct Statistics {
|
||||
tx_pkts: u64,
|
||||
tx_bytes: u64,
|
||||
rx_pkts: u64,
|
||||
rx_bytes: u64,
|
||||
}
|
||||
unsafe extern "C" {
|
||||
fn vpn_attach_command_pipe(vpn: *mut c_void, fd: c_int) -> c_int;
|
||||
fn vpn_detach_command_pipe(vpn: *mut c_void);
|
||||
fn vpn_tunnel_event(vpn: *mut c_void, event: c_int);
|
||||
fn vpn_tunnel_statistics(vpn: *mut c_void, statistics: *const Statistics);
|
||||
}
|
||||
let (sender, mut receiver) = UnixStream::pair().unwrap();
|
||||
receiver.set_nonblocking(true).unwrap();
|
||||
let pointer = Arc::as_ptr(&vpn).cast_mut().cast();
|
||||
// SAFETY: the fixture retains Vpn and both endpoints through detach; event
|
||||
// numbers and statistics layout match the native bridge used in production.
|
||||
unsafe {
|
||||
assert_eq!(vpn_attach_command_pipe(pointer, sender.as_raw_fd()), 0);
|
||||
vpn_tunnel_event(pointer, 1);
|
||||
vpn_tunnel_event(pointer, 5);
|
||||
}
|
||||
std::thread::spawn(move || {
|
||||
let pointer = Arc::as_ptr(&vpn).cast_mut().cast();
|
||||
let mut command = [0];
|
||||
while !cancellation.is_cancelled() {
|
||||
match receiver.read(&mut command) {
|
||||
Ok(1) if command[0] == b's' => unsafe {
|
||||
vpn_tunnel_statistics(
|
||||
pointer,
|
||||
&Statistics {
|
||||
tx_pkts: 2,
|
||||
tx_bytes: 1024,
|
||||
rx_pkts: 4,
|
||||
rx_bytes: 4096,
|
||||
},
|
||||
);
|
||||
},
|
||||
Err(error) if error.kind() == io::ErrorKind::WouldBlock => std::thread::sleep(Duration::from_millis(10)),
|
||||
other => panic!("Unexpected native fixture command: {other:?}"),
|
||||
}
|
||||
}
|
||||
// SAFETY: all native observations finish before the retained Vpn is freed.
|
||||
unsafe {
|
||||
vpn_detach_command_pipe(pointer);
|
||||
vpn_tunnel_event(pointer, 7);
|
||||
}
|
||||
drop(sender);
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
use std::{
|
||||
collections::BTreeMap, fs::OpenOptions, io::Write, os::unix::fs::OpenOptionsExt, path::PathBuf, process::Stdio,
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use clap::Args;
|
||||
use common::binary_paths;
|
||||
use serde::Serialize;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
|
||||
const COLLECTOR: &str = include_str!("../../../scripts/collect-diagnostics.sh");
|
||||
const MAX_REPORT_BYTES: usize = 64 * 1024;
|
||||
const FIELDS: &[&str] = &[
|
||||
"os",
|
||||
"os_version",
|
||||
"kernel",
|
||||
"architecture",
|
||||
"execution_user",
|
||||
"ssh_session",
|
||||
"virtualization",
|
||||
"gpclient_path",
|
||||
"gpclient_version",
|
||||
"gpauth_path",
|
||||
"gpauth_version",
|
||||
"gpgui_path",
|
||||
"gpgui_version",
|
||||
"display_protocol",
|
||||
"graphics",
|
||||
"graphics_packages",
|
||||
"desktop_version",
|
||||
"env.XDG_CURRENT_DESKTOP",
|
||||
"env.XDG_SESSION_DESKTOP",
|
||||
"env.XDG_SESSION_TYPE",
|
||||
"env.DESKTOP_SESSION",
|
||||
"env.WEBKIT_DISABLE_DMABUF_RENDERER",
|
||||
"env.WEBKIT_DISABLE_COMPOSITING_MODE",
|
||||
"env.LIBGL_ALWAYS_SOFTWARE",
|
||||
"env.__NV_DISABLE_EXPLICIT_SYNC",
|
||||
"env.GDK_BACKEND",
|
||||
"env.GDK_GL",
|
||||
];
|
||||
|
||||
#[derive(Args)]
|
||||
pub(crate) struct DiagnosticsArgs {
|
||||
/// Print the report as JSON instead of text
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
/// Save the report to a new file instead of stdout (existing files are preserved)
|
||||
#[arg(long, value_name = "PATH")]
|
||||
output: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum ProbeStatus {
|
||||
Ok,
|
||||
Unset,
|
||||
Unavailable,
|
||||
Failed,
|
||||
TimedOut,
|
||||
NotApplicable,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct DiagnosticField {
|
||||
status: ProbeStatus,
|
||||
value: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct DiagnosticsReport {
|
||||
schema_version: u32,
|
||||
fields: BTreeMap<String, DiagnosticField>,
|
||||
}
|
||||
|
||||
impl DiagnosticsReport {
|
||||
fn parse(bytes: &[u8]) -> anyhow::Result<Self> {
|
||||
ensure!(
|
||||
bytes.len() <= MAX_REPORT_BYTES,
|
||||
"Diagnostics report exceeds its size limit"
|
||||
);
|
||||
let mut fields = BTreeMap::new();
|
||||
let mut schema_version = None;
|
||||
for raw_line in bytes.split(|byte| *byte == b'\n').filter(|line| !line.is_empty()) {
|
||||
let line = String::from_utf8_lossy(raw_line);
|
||||
let (name, rest) = line.split_once(": ").context("Invalid diagnostics record")?;
|
||||
let (status, value) = rest.split_once(": ").context("Invalid diagnostics status")?;
|
||||
let raw_value_length = raw_line
|
||||
.len()
|
||||
.checked_sub(name.len() + status.len() + 4)
|
||||
.context("Invalid diagnostics framing")?;
|
||||
ensure!(raw_value_length <= 512, "Diagnostics field exceeds its size limit");
|
||||
ensure!(
|
||||
!value.chars().any(|c| c.is_ascii_control()),
|
||||
"Invalid diagnostics value"
|
||||
);
|
||||
let status = match status {
|
||||
"ok" => ProbeStatus::Ok,
|
||||
"unset" => ProbeStatus::Unset,
|
||||
"unavailable" => ProbeStatus::Unavailable,
|
||||
"failed" => ProbeStatus::Failed,
|
||||
"timed_out" => ProbeStatus::TimedOut,
|
||||
"not_applicable" => ProbeStatus::NotApplicable,
|
||||
_ => anyhow::bail!("Unknown diagnostics status"),
|
||||
};
|
||||
if name == "schema_version" {
|
||||
ensure!(schema_version.is_none(), "Duplicate diagnostics schema version");
|
||||
ensure!(
|
||||
matches!(status, ProbeStatus::Ok) && value == "1",
|
||||
"Unsupported diagnostics schema"
|
||||
);
|
||||
schema_version = Some(1);
|
||||
continue;
|
||||
}
|
||||
ensure!(FIELDS.contains(&name), "Unknown diagnostics field");
|
||||
let value = if matches!(status, ProbeStatus::Ok) {
|
||||
let mut normalized = String::new();
|
||||
for character in value.chars() {
|
||||
let character = if character.is_control() { ' ' } else { character };
|
||||
if normalized.len() + character.len_utf8() > 512 {
|
||||
break;
|
||||
}
|
||||
normalized.push(character);
|
||||
}
|
||||
Some(normalized)
|
||||
} else {
|
||||
ensure!(value.is_empty(), "Unexpected value for unavailable diagnostics field");
|
||||
None
|
||||
};
|
||||
ensure!(
|
||||
fields
|
||||
.insert(name.to_owned(), DiagnosticField { status, value })
|
||||
.is_none(),
|
||||
"Duplicate diagnostics field"
|
||||
);
|
||||
}
|
||||
ensure!(fields.len() == FIELDS.len(), "Incomplete diagnostics report");
|
||||
Ok(Self {
|
||||
schema_version: schema_version.context("Missing diagnostics schema version")?,
|
||||
fields,
|
||||
})
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
let mut text = format!("schema_version: ok: {}\n", self.schema_version);
|
||||
for name in FIELDS {
|
||||
let field = &self.fields[*name];
|
||||
let status = match field.status {
|
||||
ProbeStatus::Ok => "ok",
|
||||
ProbeStatus::Unset => "unset",
|
||||
ProbeStatus::Unavailable => "unavailable",
|
||||
ProbeStatus::Failed => "failed",
|
||||
ProbeStatus::TimedOut => "timed_out",
|
||||
ProbeStatus::NotApplicable => "not_applicable",
|
||||
};
|
||||
text.push_str(&format!(
|
||||
"{name}: {status}: {}\n",
|
||||
field.value.as_deref().unwrap_or_default()
|
||||
));
|
||||
}
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
impl DiagnosticsArgs {
|
||||
pub(crate) async fn run(&self, version: &str) -> anyhow::Result<()> {
|
||||
let mut child = Command::new("/bin/sh")
|
||||
.args(["-s", "--", "--client-version", version, "--client-path"])
|
||||
.arg(std::env::current_exe().context("Cannot locate gpclient")?)
|
||||
.arg("--auth-path")
|
||||
.arg(binary_paths::gpauth())
|
||||
.arg("--gui-path")
|
||||
.arg(binary_paths::gpgui())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.context("Cannot start diagnostics collector")?;
|
||||
let mut input = child.stdin.take().context("Collector input is unavailable")?;
|
||||
let (_, output) = tokio::try_join!(
|
||||
async move {
|
||||
input.write_all(COLLECTOR.as_bytes()).await?;
|
||||
drop(input);
|
||||
Ok::<_, std::io::Error>(())
|
||||
},
|
||||
child.wait_with_output(),
|
||||
)
|
||||
.context("Diagnostics collection failed")?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"Diagnostics collector exited with {}",
|
||||
output.status
|
||||
);
|
||||
let report = DiagnosticsReport::parse(&output.stdout)?;
|
||||
let content = if self.json {
|
||||
format!("{}\n", serde_json::to_string_pretty(&report)?)
|
||||
} else {
|
||||
report.text()
|
||||
};
|
||||
if let Some(path) = &self.output {
|
||||
save_report(path, &content)?;
|
||||
} else {
|
||||
std::io::stdout().lock().write_all(content.as_bytes())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn save_report(path: &std::path::Path, content: &str) -> anyhow::Result<()> {
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.context("Cannot create diagnostics file; use a new path")?;
|
||||
file
|
||||
.write_all(content.as_bytes())
|
||||
.context("Cannot save diagnostics report")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_report() -> String {
|
||||
let mut text = String::from("schema_version: ok: 1\n");
|
||||
for name in FIELDS {
|
||||
text.push_str(&format!("{name}: unavailable: \n"));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_preserves_collected_values_and_distinguishes_missing_probes() {
|
||||
let text = sample_report().replace("os: unavailable: ", "os: ok: FreeBSD");
|
||||
let report = DiagnosticsReport::parse(text.as_bytes()).unwrap();
|
||||
let json = serde_json::to_value(report).unwrap();
|
||||
assert_eq!(json["schema_version"], 1);
|
||||
assert_eq!(json["fields"]["os"]["value"], "FreeBSD");
|
||||
assert_eq!(json["fields"]["graphics"]["status"], "unavailable");
|
||||
assert!(json["fields"]["graphics"]["value"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_or_injected_records_are_rejected() {
|
||||
let good = sample_report();
|
||||
for bad in [
|
||||
good.replace("os: unavailable: ", "os: mystery: "),
|
||||
good.replace("os: unavailable: ", "os: ok: text\u{1b}[31m"),
|
||||
good.replace("os: unavailable: ", "os: ok: value\nsecret: ok: token"),
|
||||
format!("{good}os: ok: duplicate\n"),
|
||||
good.replace("schema_version: ok: 1", "schema_version: ok: 2"),
|
||||
good.replace("os: unavailable: \n", ""),
|
||||
] {
|
||||
assert!(DiagnosticsReport::parse(bad.as_bytes()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_utf8_and_unicode_controls_produce_a_bounded_readable_value() {
|
||||
let mut bytes = sample_report()
|
||||
.replace("os: unavailable: ", "os: ok: REPLACE")
|
||||
.into_bytes();
|
||||
let start = bytes.windows(7).position(|value| value == b"REPLACE").unwrap();
|
||||
bytes.splice(start..start + 7, [0xff; 500]);
|
||||
let report = DiagnosticsReport::parse(&bytes).unwrap();
|
||||
let value = report.fields["os"].value.as_ref().unwrap();
|
||||
assert!(value.len() <= 512);
|
||||
assert!(value.starts_with('\u{fffd}'));
|
||||
let text = sample_report().replace("os: unavailable: ", "os: ok: Test\u{85}OS");
|
||||
let report = DiagnosticsReport::parse(text.as_bytes()).unwrap();
|
||||
assert_eq!(report.fields["os"].value.as_deref(), Some("Test OS"));
|
||||
assert!(report.text().contains("os: ok: Test OS"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_a_report_does_not_overwrite_existing_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("diagnostics.txt");
|
||||
save_report(&path, "first").unwrap();
|
||||
assert!(save_report(&path, "second").is_err());
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "first");
|
||||
}
|
||||
}
|
||||
@@ -1,31 +1,64 @@
|
||||
use crate::GP_CLIENT_LOCK_FILE;
|
||||
use clap::Args;
|
||||
use gpapi::utils::lock_file::gpservice_lock_info;
|
||||
use log::{info, warn};
|
||||
use std::fs;
|
||||
use sysinfo::{Pid, ProcessExt, Signal, System, SystemExt};
|
||||
use std::{fs, path::Path, str::FromStr, thread, time::Duration};
|
||||
use sysinfo::{Pid, Signal, System};
|
||||
|
||||
pub(crate) struct DisconnectHandler;
|
||||
#[derive(Args)]
|
||||
pub struct DisconnectArgs {
|
||||
#[arg(
|
||||
long,
|
||||
required = false,
|
||||
help = "The time in seconds to wait for the VPN connection to disconnect"
|
||||
)]
|
||||
wait: Option<u64>,
|
||||
}
|
||||
|
||||
impl DisconnectHandler {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self
|
||||
pub struct DisconnectHandler<'a> {
|
||||
args: &'a DisconnectArgs,
|
||||
lock_file: &'a Path,
|
||||
}
|
||||
|
||||
impl<'a> DisconnectHandler<'a> {
|
||||
pub fn new(args: &'a DisconnectArgs, lock_file: &'a Path) -> Self {
|
||||
Self { args, lock_file }
|
||||
}
|
||||
|
||||
pub(crate) fn handle(&self) -> anyhow::Result<()> {
|
||||
if fs::metadata(GP_CLIENT_LOCK_FILE).is_err() {
|
||||
warn!("PID file not found, maybe the client is not running");
|
||||
return Ok(());
|
||||
pub async fn handle(&self) -> anyhow::Result<()> {
|
||||
// Try to disconnect the CLI client
|
||||
let cli_signalled = match fs::read_to_string(self.lock_file) {
|
||||
Ok(c) => send_signal(c.trim(), Signal::Interrupt).unwrap_or_else(|err| {
|
||||
warn!("Failed to send signal to client: {}", err);
|
||||
false
|
||||
}),
|
||||
Err(_) => false,
|
||||
};
|
||||
|
||||
// Try to disconnect the GUI service
|
||||
if !cli_signalled && let Ok(c) = gpservice_lock_info().await {
|
||||
send_signal(&c.pid.to_string(), Signal::User1).unwrap_or_else(|err| {
|
||||
warn!("Failed to send signal to service: {}", err);
|
||||
false
|
||||
});
|
||||
};
|
||||
|
||||
// sleep, to give the client and service time to disconnect
|
||||
if let Some(wait) = self.args.wait {
|
||||
thread::sleep(Duration::from_secs(wait));
|
||||
}
|
||||
|
||||
let pid = fs::read_to_string(GP_CLIENT_LOCK_FILE)?;
|
||||
let pid = pid.trim().parse::<usize>()?;
|
||||
let s = System::new_all();
|
||||
|
||||
if let Some(process) = s.process(Pid::from(pid)) {
|
||||
info!("Found process {}, killing...", pid);
|
||||
if process.kill_with(Signal::Interrupt).is_none() {
|
||||
warn!("Failed to kill process {}", pid);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn send_signal(pid: &str, signal: Signal) -> anyhow::Result<bool> {
|
||||
let s = System::new_all();
|
||||
let pid = Pid::from_str(pid)?;
|
||||
|
||||
if let Some(process) = s.process(pid) {
|
||||
info!("Found process {}, sending signal...", pid);
|
||||
|
||||
return Ok(process.kill_with(signal).unwrap_or(false));
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Args;
|
||||
use gpapi::{
|
||||
clap::args::Os,
|
||||
collection::CollectionBudget,
|
||||
os_profile::{ClientOs, OsProfileBuilder},
|
||||
};
|
||||
use gphip::{ReportContext, ReportInput, generate_report_with_control};
|
||||
|
||||
#[derive(Args)]
|
||||
pub(crate) struct HipArgs {
|
||||
#[arg(long, help = "The GP client version, e.g., 6.2.4-49")]
|
||||
client_version: String,
|
||||
|
||||
#[arg(long, value_enum, help = "The client OS")]
|
||||
client_os: Os,
|
||||
|
||||
#[arg(long, hide = true)]
|
||||
os_version: Option<String>,
|
||||
|
||||
#[arg(long, help = "Use this runtime host ID when building the OS profile")]
|
||||
host_id: Option<String>,
|
||||
|
||||
#[arg(long, help = "The authentication cookie")]
|
||||
cookie: String,
|
||||
|
||||
#[arg(long, help = "The client IPv4 address")]
|
||||
client_ip: Option<String>,
|
||||
|
||||
#[arg(long, help = "The client IPv6 address")]
|
||||
client_ipv6: Option<String>,
|
||||
|
||||
#[arg(long, help = "The MD5 digest to encode into the HIP report")]
|
||||
md5: String,
|
||||
}
|
||||
|
||||
pub(crate) struct HipHandler<'a> {
|
||||
args: &'a HipArgs,
|
||||
}
|
||||
|
||||
impl<'a> HipHandler<'a> {
|
||||
pub(crate) fn new(args: &'a HipArgs) -> Self {
|
||||
Self { args }
|
||||
}
|
||||
|
||||
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let client_os = ClientOs::from(self.args.client_os);
|
||||
let mut builder = OsProfileBuilder::new(client_os).client_version(self.args.client_version.clone());
|
||||
if let Some(os_version) = self.args.os_version.as_deref() {
|
||||
builder = builder.os_version(os_version);
|
||||
}
|
||||
let input = ReportInput {
|
||||
profile: gpapi::os_profile::desktop::collect_profile_with_control(
|
||||
builder,
|
||||
self.args.host_id.as_deref(),
|
||||
&budget,
|
||||
)?,
|
||||
context: ReportContext::Connected {
|
||||
cookie: self.args.cookie.clone(),
|
||||
client_ip: self.args.client_ip.clone(),
|
||||
client_ipv6: self.args.client_ipv6.clone(),
|
||||
md5: self.args.md5.clone(),
|
||||
},
|
||||
};
|
||||
println!("{}", generate_report_with_control(&input, &budget)?);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,45 @@
|
||||
use std::{collections::HashMap, env::temp_dir, fs, path::PathBuf};
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use std::process::{Command, ExitStatus};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use anyhow::Context;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use anyhow::bail;
|
||||
use clap::Args;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use common::binary_paths;
|
||||
use directories::ProjectDirs;
|
||||
use gpapi::{
|
||||
process::service_launcher::ServiceLauncher,
|
||||
utils::{endpoint::http_endpoint, env_file, shutdown_signal},
|
||||
};
|
||||
use gpapi::process::desktop_launcher::DesktopLauncher;
|
||||
use log::info;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
#[derive(Args)]
|
||||
pub(crate) struct LaunchGuiArgs {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[arg(
|
||||
required = false,
|
||||
help = "The authentication data, used for the default browser authentication"
|
||||
conflicts_with = "minimized",
|
||||
value_parser = parse_auth_callback,
|
||||
help = "The external-browser authentication callback URL"
|
||||
)]
|
||||
pub auth_data: Option<String>,
|
||||
callback: Option<String>,
|
||||
#[arg(long, help = "Launch the GUI minimized")]
|
||||
minimized: bool,
|
||||
}
|
||||
|
||||
impl LaunchGuiArgs {
|
||||
pub(crate) fn is_auth_callback(&self) -> bool {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
return self.callback.is_some();
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct LaunchGuiHandler<'a> {
|
||||
args: &'a LaunchGuiArgs,
|
||||
}
|
||||
@@ -31,44 +51,28 @@ impl<'a> LaunchGuiHandler<'a> {
|
||||
|
||||
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
||||
// `launch-gui`cannot be run as root
|
||||
let user = whoami::username();
|
||||
let user = whoami::username().map_err(|err| anyhow::anyhow!("Failed to resolve current user: {err}"))?;
|
||||
if user == "root" {
|
||||
anyhow::bail!("`launch-gui` cannot be run as root");
|
||||
}
|
||||
|
||||
let auth_data = self.args.auth_data.as_deref().unwrap_or_default();
|
||||
if !auth_data.is_empty() {
|
||||
info!("Received auth callback data");
|
||||
// Process the authentication data, its format is `globalprotectcallback:<data>`
|
||||
return feed_auth_data(auth_data).await;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
if let Some(callback) = &self.args.callback {
|
||||
return forward_auth_callback(callback);
|
||||
}
|
||||
|
||||
if try_active_gui().await.is_ok() {
|
||||
if DesktopLauncher::activate_existing().await.is_ok() {
|
||||
info!("The GUI is already running");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
tokio::spawn(async move {
|
||||
shutdown_signal().await;
|
||||
info!("Shutting down...");
|
||||
});
|
||||
|
||||
let log_file = get_log_file()?;
|
||||
let log_file_path = log_file.to_string_lossy().to_string();
|
||||
|
||||
info!("Log file: {}", log_file_path);
|
||||
|
||||
let mut extra_envs = HashMap::<String, String>::new();
|
||||
extra_envs.insert("GP_LOG_FILE".into(), log_file_path.clone());
|
||||
|
||||
// Persist the environment variables to a file
|
||||
let env_file = env_file::persist_env_vars(Some(extra_envs))?;
|
||||
let env_file = env_file.into_temp_path();
|
||||
let env_file_path = env_file.to_string_lossy().to_string();
|
||||
|
||||
let exit_status = ServiceLauncher::new()
|
||||
let exit_status = DesktopLauncher::new(env!("CARGO_PKG_VERSION"))
|
||||
.minimized(self.args.minimized)
|
||||
.env_file(&env_file_path)
|
||||
.log_file(&log_file_path)
|
||||
.launch()
|
||||
.await?;
|
||||
@@ -79,61 +83,36 @@ impl<'a> LaunchGuiHandler<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
async fn feed_auth_data(auth_data: &str) -> anyhow::Result<()> {
|
||||
let (res_gui, res_cli) = tokio::join!(feed_auth_data_gui(auth_data), feed_auth_data_cli(auth_data));
|
||||
if let Err(err) = res_gui {
|
||||
info!("Failed to feed auth data to the GUI: {}", err);
|
||||
}
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
let status = auth_callback_command(callback)
|
||||
.status()
|
||||
.context("Failed to start the authentication callback handler")?;
|
||||
ensure_auth_callback_succeeded(status)
|
||||
}
|
||||
|
||||
if let Err(err) = res_cli {
|
||||
info!("Failed to feed auth data to the CLI: {}", err);
|
||||
}
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn auth_callback_command(callback: &str) -> Command {
|
||||
let mut command = Command::new(binary_paths::gpauth());
|
||||
command.args(["auth-callback", callback]);
|
||||
command
|
||||
}
|
||||
|
||||
// Cleanup the temporary file
|
||||
let html_file = temp_dir().join("gpauth.html");
|
||||
if let Err(err) = std::fs::remove_file(&html_file) {
|
||||
info!("Failed to remove {}: {}", html_file.display(), err);
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn ensure_auth_callback_succeeded(status: ExitStatus) -> anyhow::Result<()> {
|
||||
if !status.success() {
|
||||
bail!("Authentication callback handler exited with {status}");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn feed_auth_data_gui(auth_data: &str) -> anyhow::Result<()> {
|
||||
info!("Feeding auth data to the GUI");
|
||||
let service_endpoint = http_endpoint().await?;
|
||||
|
||||
reqwest::Client::default()
|
||||
.post(format!("{}/auth-data", service_endpoint))
|
||||
.body(auth_data.to_string())
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn feed_auth_data_cli(auth_data: &str) -> anyhow::Result<()> {
|
||||
info!("Feeding auth data to the CLI");
|
||||
|
||||
let port_file = temp_dir().join("gpcallback.port");
|
||||
let port = tokio::fs::read_to_string(port_file).await?;
|
||||
let mut stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{}", port.trim())).await?;
|
||||
|
||||
stream.write_all(auth_data.as_bytes()).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn try_active_gui() -> anyhow::Result<()> {
|
||||
let service_endpoint = http_endpoint().await?;
|
||||
|
||||
reqwest::Client::default()
|
||||
.post(format!("{}/active-gui", service_endpoint))
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
|
||||
Ok(())
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn parse_auth_callback(callback: &str) -> Result<String, String> {
|
||||
callback
|
||||
.starts_with("globalprotectcallback:")
|
||||
.then(|| callback.to_owned())
|
||||
.ok_or_else(|| "callback URL must use the globalprotectcallback scheme".to_owned())
|
||||
}
|
||||
|
||||
fn get_log_file() -> anyhow::Result<PathBuf> {
|
||||
@@ -144,3 +123,34 @@ fn get_log_file() -> anyhow::Result<PathBuf> {
|
||||
|
||||
Ok(dirs.data_dir().join("gpclient.log"))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
use super::*;
|
||||
|
||||
const CALLBACK: &str = "globalprotectcallback:cas-as=1&[email protected]&token=token";
|
||||
|
||||
#[test]
|
||||
fn callback_command_preserves_callback_argument() {
|
||||
let command = auth_callback_command(CALLBACK);
|
||||
let args = command
|
||||
.get_args()
|
||||
.map(|argument| argument.to_str().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(args, ["auth-callback", CALLBACK]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_command_status_is_propagated() {
|
||||
assert!(ensure_auth_callback_succeeded(ExitStatus::from_raw(0)).is_ok());
|
||||
assert!(ensure_auth_callback_succeeded(ExitStatus::from_raw(1 << 8)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_callback_url() {
|
||||
assert!(parse_auth_callback("https://example.com/callback").is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
mod background;
|
||||
mod cli;
|
||||
mod connect;
|
||||
mod dashboard;
|
||||
mod diagnostics;
|
||||
mod disconnect;
|
||||
mod hip;
|
||||
mod launch_gui;
|
||||
mod session;
|
||||
|
||||
pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock";
|
||||
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use gpapi::{
|
||||
clap::report,
|
||||
gateway::{SessionContext, SessionExtensionAuth, extend_session},
|
||||
log_format::LogFormat,
|
||||
os_profile::OsProfile,
|
||||
session::{SessionInfo, SessionRequestArgs, SessionWarning},
|
||||
};
|
||||
use log::{Level, info, warn};
|
||||
use openconnect::VpnSessionInfo;
|
||||
use tokio::{runtime::Handle, task::JoinHandle};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct SessionWarningSchedule {
|
||||
delay: Duration,
|
||||
message: String,
|
||||
should_auto_extend: bool,
|
||||
}
|
||||
|
||||
pub(crate) struct SessionContextInput {
|
||||
pub(crate) portal: String,
|
||||
pub(crate) gateway: String,
|
||||
pub(crate) cookie: String,
|
||||
pub(crate) os_profile: OsProfile,
|
||||
pub(crate) certificate: Option<String>,
|
||||
pub(crate) sslkey: Option<String>,
|
||||
pub(crate) key_password: Option<String>,
|
||||
pub(crate) disable_ipv6: bool,
|
||||
pub(crate) extension_auth: Option<SessionExtensionAuth>,
|
||||
}
|
||||
|
||||
pub(crate) fn build_session_context(input: SessionContextInput) -> SessionContext {
|
||||
let session_args = SessionRequestArgs::new(input.cookie)
|
||||
.with_user_agent(input.os_profile.user_agent().to_string())
|
||||
.with_certificate(input.certificate)
|
||||
.with_sslkey(input.sslkey)
|
||||
.with_key_password(input.key_password)
|
||||
.with_disable_ipv6(input.disable_ipv6);
|
||||
|
||||
let ctx = SessionContext::new(input.gateway, input.portal, session_args);
|
||||
match input.extension_auth {
|
||||
Some(extension_auth) => ctx.with_extension_auth(extension_auth),
|
||||
None => ctx,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn session_info_from_vpn(vpn_session_info: VpnSessionInfo, allow_extend_session: bool) -> SessionInfo {
|
||||
SessionInfo::from_vpn_session_fields(
|
||||
vpn_session_info.lifetime_secs,
|
||||
vpn_session_info.user_expires,
|
||||
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
|
||||
prior_secs: warning.prior_secs,
|
||||
message: warning.message,
|
||||
}),
|
||||
allow_extend_session,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn spawn_session_runtime_with_info(
|
||||
handle: &Handle,
|
||||
session_ctx: SessionContext,
|
||||
session_info: SessionInfo,
|
||||
log_format: LogFormat,
|
||||
) -> JoinHandle<()> {
|
||||
handle.spawn(run_session_runtime(session_ctx, session_info, log_format))
|
||||
}
|
||||
|
||||
async fn run_session_runtime(session_ctx: SessionContext, mut session_info: SessionInfo, log_format: LogFormat) {
|
||||
loop {
|
||||
let Some(schedule) = build_session_warning_schedule(&session_info) else {
|
||||
info!("No session warning schedule provided by the gateway");
|
||||
return;
|
||||
};
|
||||
|
||||
tokio::time::sleep(schedule.delay).await;
|
||||
|
||||
crate::dashboard::session_notice(Level::Warn, &schedule.message);
|
||||
report(log_format, Level::Warn, &format!("\nWARNING: {}", schedule.message));
|
||||
|
||||
if !schedule.should_auto_extend {
|
||||
info!("Session extension is not allowed by the gateway");
|
||||
return;
|
||||
}
|
||||
|
||||
info!("Attempting to extend the session");
|
||||
match extend_session(&session_ctx).await {
|
||||
Ok(()) => {
|
||||
let Some(next_session_info) = session_info.rescheduled_after_extension() else {
|
||||
info!("Session extended, but no lifetime is available to schedule another warning");
|
||||
return;
|
||||
};
|
||||
|
||||
crate::dashboard::session_notice(Level::Info, "Session extended.");
|
||||
report(log_format, Level::Info, "Session extended.");
|
||||
session_info = next_session_info;
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Failed to extend session: {}", err);
|
||||
report(
|
||||
log_format,
|
||||
Level::Warn,
|
||||
&format!("WARNING: Failed to extend session: {}", err),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_session_warning_schedule(session_info: &SessionInfo) -> Option<SessionWarningSchedule> {
|
||||
let warning = session_info.lifetime_warning.as_ref()?;
|
||||
let warning_secs = if let Some(user_expires) = session_info.user_expires {
|
||||
let now = unix_timestamp();
|
||||
user_expires.saturating_sub(warning.prior_secs).saturating_sub(now)
|
||||
} else if let Some(lifetime_secs) = session_info.lifetime_secs {
|
||||
lifetime_secs.saturating_sub(warning.prior_secs)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
|
||||
Some(SessionWarningSchedule {
|
||||
delay: Duration::from_secs(warning_secs as u64),
|
||||
message: warning.message.clone(),
|
||||
should_auto_extend: session_info.allow_extend_session,
|
||||
})
|
||||
}
|
||||
|
||||
fn unix_timestamp() -> u32 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as u32
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_session_info(user_expires: Option<u32>, allow_extend_session: bool) -> SessionInfo {
|
||||
SessionInfo {
|
||||
user_expires,
|
||||
lifetime_warning: Some(SessionWarning {
|
||||
prior_secs: 1800,
|
||||
message: "Session expires soon".to_string(),
|
||||
}),
|
||||
allow_extend_session,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_warning_schedule_for_auto_extend() {
|
||||
let session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
|
||||
|
||||
let schedule = build_session_warning_schedule(&session_info).unwrap();
|
||||
|
||||
assert_eq!(schedule.message, "Session expires soon");
|
||||
assert!(schedule.delay <= Duration::from_secs(30));
|
||||
assert!(schedule.should_auto_extend);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_warning_schedule_without_auto_extend() {
|
||||
let session_info = sample_session_info(Some(unix_timestamp() + 1830), false);
|
||||
|
||||
let schedule = build_session_warning_schedule(&session_info).unwrap();
|
||||
|
||||
assert!(!schedule.should_auto_extend);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schedules_next_warning_after_extension_from_lifetime() {
|
||||
let mut session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
|
||||
session_info.lifetime_secs = Some(7200);
|
||||
|
||||
let next_session_info = session_info.rescheduled_after_extension().unwrap();
|
||||
let schedule = build_session_warning_schedule(&next_session_info).unwrap();
|
||||
|
||||
assert!(schedule.delay <= Duration::from_secs(5400));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_session_context_from_os_profile() {
|
||||
let profile = gpapi::os_profile::desktop::collect_profile(
|
||||
OsProfile::builder(gpapi::os_profile::ClientOs::Mac).client_version("6.3.1-12".to_string()),
|
||||
None,
|
||||
);
|
||||
let expected_user_agent = profile.user_agent().to_string();
|
||||
|
||||
let ctx = build_session_context(SessionContextInput {
|
||||
portal: "portal.example.com".to_string(),
|
||||
gateway: "vpn.example.com".to_string(),
|
||||
cookie: "authcookie=AUTH".to_string(),
|
||||
os_profile: profile,
|
||||
certificate: Some("/tmp/client.pem".to_string()),
|
||||
sslkey: Some("/tmp/client.key".to_string()),
|
||||
key_password: Some("secret".to_string()),
|
||||
disable_ipv6: true,
|
||||
extension_auth: None,
|
||||
});
|
||||
|
||||
assert_eq!(ctx.portal(), "portal.example.com");
|
||||
assert_eq!(ctx.server(), "vpn.example.com");
|
||||
assert_eq!(ctx.session_args().cookie(), "authcookie=AUTH");
|
||||
assert_eq!(
|
||||
ctx.session_args().user_agent().as_deref(),
|
||||
Some(expected_user_agent.as_str())
|
||||
);
|
||||
assert_eq!(ctx.session_args().certificate().as_deref(), Some("/tmp/client.pem"));
|
||||
assert_eq!(ctx.session_args().sslkey().as_deref(), Some("/tmp/client.key"));
|
||||
assert_eq!(ctx.session_args().key_password().as_deref(), Some("secret"));
|
||||
assert!(ctx.session_args().disable_ipv6());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_openconnect_session_metadata_to_runtime_session_info() {
|
||||
let info = session_info_from_vpn(
|
||||
VpnSessionInfo {
|
||||
lifetime_secs: Some(43_200),
|
||||
user_expires: Some(1_776_828_409),
|
||||
lifetime_warning: Some(openconnect::VpnSessionWarning {
|
||||
prior_secs: 1_800,
|
||||
message: "Session expires soon".to_string(),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(info.lifetime_secs, Some(43_200));
|
||||
assert_eq!(info.user_expires, Some(1_776_828_409));
|
||||
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
|
||||
assert!(info.allow_extend_session);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_gateway_session_info_does_not_allow_extension_without_portal_policy() {
|
||||
let info = session_info_from_vpn(
|
||||
VpnSessionInfo {
|
||||
lifetime_secs: Some(43_200),
|
||||
user_expires: Some(1_776_828_409),
|
||||
lifetime_warning: Some(openconnect::VpnSessionWarning {
|
||||
prior_secs: 1_800,
|
||||
message: "Session expires soon".to_string(),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(info.lifetime_secs, Some(43_200));
|
||||
assert_eq!(info.user_expires, Some(1_776_828_409));
|
||||
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
|
||||
assert!(!info.allow_extend_session);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
#![cfg(not(target_os = "macos"))]
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn background_worker_warns_once_for_the_deprecated_flag() {
|
||||
const WARNING: &str = "--fix-openssl is deprecated and has no effect. It will be removed in a future release.";
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
for deprecated in [false, true] {
|
||||
let log = directory.path().join(format!("background-{deprecated}.log"));
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_gpclient"));
|
||||
if deprecated {
|
||||
command.arg("--fix-openssl");
|
||||
}
|
||||
let output = command
|
||||
.arg("--lock-file")
|
||||
.arg(directory.path().join("client.pid"))
|
||||
.args([
|
||||
"--log-format",
|
||||
"json",
|
||||
"connect",
|
||||
"vpn.example.test",
|
||||
"--background",
|
||||
"--certificate",
|
||||
])
|
||||
// Fail identity preparation before authentication or a network connection.
|
||||
.arg(directory.path().join("missing.pem"))
|
||||
.arg("--log-file")
|
||||
.arg(&log)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
let mut records = String::from_utf8(output.stderr).unwrap();
|
||||
records.push_str(&std::fs::read_to_string(log).unwrap());
|
||||
assert!(records.contains("Failed to read client identity"), "{records}");
|
||||
assert_eq!(records.matches(WARNING).count(), usize::from(deprecated), "{records}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use std::{os::unix::fs::PermissionsExt, process::Stdio, time::Duration};
|
||||
|
||||
use tokio::process::Command;
|
||||
|
||||
fn executable(dir: &std::path::Path, name: &str, body: &str) {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn embedded_collector_reports_missing_helpers_without_recursing_or_exposing_private_environment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join("bin");
|
||||
std::fs::create_dir(&bin).unwrap();
|
||||
executable(
|
||||
&bin,
|
||||
"uname",
|
||||
"case \"$1\" in -s) echo Linux ;; -m) echo aarch64 ;; *) echo test-kernel ;; esac",
|
||||
);
|
||||
executable(&bin, "gpclient", "echo unexpected-recursion >&2; exit 99");
|
||||
executable(&bin, "systemd-detect-virt", "echo kvm");
|
||||
executable(
|
||||
&bin,
|
||||
"lspci",
|
||||
"echo '00:02.0 VGA compatible controller: Test GPU'; echo ' Kernel driver in use: test'",
|
||||
);
|
||||
executable(&bin, "pacman", "echo 'gtk3 test-version'");
|
||||
let report_file = dir.path().join("report.json");
|
||||
let output = tokio::time::timeout(
|
||||
Duration::from_secs(30),
|
||||
Command::new(env!("CARGO_BIN_EXE_gpclient"))
|
||||
.args([
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
"--fix-openssl",
|
||||
"diagnostics",
|
||||
"--json",
|
||||
"--output",
|
||||
])
|
||||
.arg(&report_file)
|
||||
.env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
|
||||
.env("GP_AUTH_BINARY", dir.path().join("missing-gpauth"))
|
||||
.env("GP_GUI_BINARY", dir.path().join("missing-gpgui"))
|
||||
.env("GP_DIAGNOSTICS_PRIVATE_TOKEN", "secret-value-must-not-appear")
|
||||
.env("XDG_CURRENT_DESKTOP", "TestDesktop\nInjected: secret")
|
||||
.stdin(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output(),
|
||||
)
|
||||
.await
|
||||
.expect("collector must close stdin and terminate")
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(output.stdout.is_empty());
|
||||
let text = std::fs::read_to_string(&report_file).unwrap();
|
||||
assert!(!text.contains("secret-value-must-not-appear"));
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("unexpected-recursion"));
|
||||
let report: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(report["schema_version"], 1);
|
||||
assert_eq!(report["fields"]["os"]["value"], "Linux");
|
||||
assert_eq!(report["fields"]["gpclient_path"]["status"], "ok");
|
||||
for field in ["gpauth_path", "gpauth_version", "gpgui_path", "gpgui_version"] {
|
||||
assert_eq!(report["fields"][field]["status"], "unavailable");
|
||||
assert!(report["fields"][field]["value"].is_null());
|
||||
}
|
||||
assert!(
|
||||
report["fields"]["gpclient_version"]["value"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with(env!("CARGO_PKG_VERSION"))
|
||||
);
|
||||
assert_eq!(
|
||||
report["fields"]["env.XDG_CURRENT_DESKTOP"]["value"],
|
||||
"TestDesktop Injected: secret"
|
||||
);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
.matches("--fix-openssl is deprecated and has no effect. It will be removed in a future release.")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Compiled by the PTY test with -C panic=abort against the production hook.
|
||||
#[path = "../../src/dashboard/restoration.rs"]
|
||||
mod restoration;
|
||||
|
||||
use std::{fs::{File, OpenOptions}, io::{Read, Write}, os::fd::{AsRawFd, FromRawFd}, sync::Arc};
|
||||
|
||||
fn main() {
|
||||
let tty = OpenOptions::new().read(true).write(true).open("/dev/tty").unwrap();
|
||||
let error = Arc::new(unsafe { File::from_raw_fd(nix::libc::fcntl(2, nix::libc::F_DUPFD_CLOEXEC, 3)) });
|
||||
let input_flags = nix::fcntl::FdFlag::from_bits_truncate(unsafe { nix::libc::fcntl(0, nix::libc::F_GETFD) });
|
||||
let previous = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |panic| {
|
||||
assert_eq!(unsafe { nix::libc::fcntl(0, nix::libc::F_GETFD) }, input_flags.bits());
|
||||
previous(panic);
|
||||
eprintln!("ABORT_HOOK_RESTORED");
|
||||
let mut acknowledgement = String::new();
|
||||
std::io::stdin().read_line(&mut acknowledgement).unwrap();
|
||||
}));
|
||||
let restore = restoration::TerminalRestoration::install(tty.try_clone().unwrap(), error.clone(), None, input_flags).unwrap();
|
||||
restore.arm();
|
||||
unsafe { nix::libc::fcntl(0, nix::libc::F_SETFD, input_flags.bits() | nix::libc::FD_CLOEXEC); }
|
||||
let mut termios = std::mem::MaybeUninit::uninit();
|
||||
unsafe {
|
||||
assert_eq!(nix::libc::tcgetattr(tty.as_raw_fd(), termios.as_mut_ptr()), 0);
|
||||
let mut raw = termios.assume_init();
|
||||
nix::libc::cfmakeraw(&mut raw);
|
||||
assert_eq!(nix::libc::tcsetattr(tty.as_raw_fd(), nix::libc::TCSANOW, &raw), 0);
|
||||
}
|
||||
(&*error).write_all(b"\x1b[?1049hABORT_FIXTURE_READY").unwrap();
|
||||
let mut trigger = [0];
|
||||
(&tty).read_exact(&mut trigger).unwrap();
|
||||
panic!("intentional abort-hook fixture panic");
|
||||
}
|
||||
@@ -8,7 +8,6 @@ pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
|
||||
@@ -1,7 +1,36 @@
|
||||
# Tauri + React + Typescript
|
||||
# GP Connect download helper
|
||||
|
||||
This template should help get you started developing with Tauri, React and Typescript in Vite.
|
||||
The desktop supervisor launches this window when the selected GUI is missing or
|
||||
has an incompatible version. It downloads the selected Tauri or Native Shell
|
||||
interface and requests installation through the service. Launches require the
|
||||
existing service credential and lifetime channel on stdin.
|
||||
|
||||
## Recommended IDE Setup
|
||||
## Appearance
|
||||
|
||||
- [VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)
|
||||
`--theme system|light|dark` controls this window only. The default is `system`,
|
||||
which follows system appearance and changes while the window is open. Explicit
|
||||
`light` and `dark` modes override system appearance for that launch. Nothing is
|
||||
saved by the helper.
|
||||
|
||||
Initial downloads follow the system. During Linux Tauri/Native Shell switches,
|
||||
Desktop Core supplies the running app's saved theme choice to the supervisor,
|
||||
which forwards it to the helper. There is no `--helper-theme` option on
|
||||
`gpclient launch-gui`.
|
||||
|
||||
The native window and web content use the selected appearance before the window
|
||||
is shown. Browser previews follow the system when no native mode is supplied.
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
pnpm build
|
||||
pnpm test
|
||||
```
|
||||
|
||||
The built `dist/` assets are tracked and must be rebuilt after frontend changes.
|
||||
Run Rust checks and helper tests from the `gp` repository:
|
||||
|
||||
```sh
|
||||
cargo check -p gpgui-helper
|
||||
cargo test -p gpgui-helper --lib
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||
<defs>
|
||||
<linearGradient id="ocean" x1="210.49524" y1="190.80952" x2="802.16190" y2="867.00000" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#579bc1"/>
|
||||
<stop offset=".52" stop-color="#438fbd"/>
|
||||
<stop offset="1" stop-color="#2f719e"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="land" x1="227.40000" y1="213.34921" x2="779.62222" y2="827.55556" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#56c78a"/>
|
||||
<stop offset=".55" stop-color="#3bbf78"/>
|
||||
<stop offset="1" stop-color="#279b5d"/>
|
||||
</linearGradient>
|
||||
|
||||
|
||||
|
||||
|
||||
<linearGradient id="shipped-lock" x1="385" y1="400" x2="650" y2="700" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#f3b84c"/>
|
||||
<stop offset=".55" stop-color="#e8a12f"/>
|
||||
<stop offset="1" stop-color="#d4871e"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<g transform="translate(512 512) scale(1.1535211267605634) translate(-511.4 -512)">
|
||||
<g>
|
||||
<circle cx="511.4" cy="512" r="355" fill="url(#ocean)"/>
|
||||
<path d="m341.5 202.8c-83.71 44.8-148.5 123-170.9 210.4 10.88 28.67 32.13 48.77 54.14 63.49 13.18 8.96 18.94 19.84 17.15 31.87-3.84 26.5-46.85 37.89-50.3 71.3-2.688 27.78 17.54 52.74 46.46 67.71 21.76 11.39 35.2 25.73 41.34 44.29 13.44 39.17 32.64 82.56 68.99 105.5 30.08 18.94 46.85 12.67 41.09-1.92-6.144-15.36-26.37-32.13-26.24-53.63 0.128-27.39 26.5-41.98 31.49-62.72v-87.3c-18.69-0.896-30.59-9.216-40.19-19.71-16.51-17.41-37.76-29.44-55.68-36.86-10.37-4.352-12.67-12.8-13.7-22.66-0.896-11.39-6.144-20.74-15.1-28.16-12.8-10.62-19.97-22.53-18.3-34.82 1.92-15.62 17.28-26.5 36.74-29.44 37.25-6.144 70.53-34.69 74.11-63.49 1.792-14.46-5.504-24.32-2.816-33.66 4.864-21.12 34.18-38.14 65.02-51.71 24.83-10.88 45.7-20.61 45.95-39.81 0.256-20.22-20.74-32.9-60.03-33.41-22.53 0.128-46.08 2.56-69.25 4.736z" fill="url(#land)"/>
|
||||
<path d="m663.7 191.5c-50.43 5.376-89.34 38.4-89.34 68.61 0 26.75 27.78 42.88 62.98 46.98 31.36 3.712 48.9 15.36 49.79 34.18 0.896 20.74-17.15 34.18-16.77 51.71 0.512 36.35 51.84 71.04 107.4 71.17 31.74 0.128 62.59-11.39 79.74-28.54-24.32-107.8-99.2-199.3-193.8-244.1z" fill="url(#land)"/>
|
||||
<path d="m866.2 532c-19.46-9.216-42.62-13.7-66.18-13.7-57.47 0-102.1 34.05-102.1 60.8 0 11.9 6.144 19.97 13.06 26.75 11.52 11.52 17.66 25.73 17.66 42.24 0 29.18-22.53 45.06-22.53 73.34 0 26.88 18.69 47.36 39.04 57.73 71.42-61.31 117.6-154.6 121.1-247.2z" fill="url(#land)"/>
|
||||
<circle cx="511.4" cy="512" r="347.111111" fill="none" stroke="#9ccde2" stroke-width="12.396825" stroke-opacity=".4"/>
|
||||
|
||||
</g>
|
||||
</g>
|
||||
<g transform="translate(512 512) scale(1.3) translate(-512 -455)">
|
||||
<g transform="translate(512 490) scale(.82) translate(-512 -490)">
|
||||
<path d="M405 429v-75c0-142 214-142 214 0v75" fill="none" stroke="#eef1f2" stroke-width="58" stroke-linecap="round"/>
|
||||
<rect x="340" y="403" width="344" height="278" rx="62" fill="url(#shipped-lock)"/>
|
||||
<rect x="346" y="409" width="332" height="266" rx="56" fill="none" stroke="#f7cb75" stroke-width="10" stroke-opacity=".3"/>
|
||||
<g fill="#85500f" opacity=".78" transform="translate(512 550.5) scale(1.2) translate(-512 -550.5)">
|
||||
<path d="M501 538h22l16 69h-54Z"/>
|
||||
<circle cx="512" cy="521" r="27"/>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.2 KiB |
@@ -0,0 +1,9 @@
|
||||
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports);(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=e((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function ee(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,x||(x=!0,ie());else{var t=n(l);t!==null&&se(ee,t.startTime-e)}}}var x=!1,te=-1,ne=5,S=-1;function re(){return g?!0:!(e.unstable_now()-S<ne)}function C(){if(g=!1,x){var t=e.unstable_now();S=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(te),te=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&re());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&se(ee,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?ie():x=!1}}}var ie;if(typeof y==`function`)ie=function(){y(C)};else if(typeof MessageChannel<`u`){var ae=new MessageChannel,oe=ae.port2;ae.port1.onmessage=C,ie=function(){oe.postMessage(null)}}else ie=function(){_(C,0)};function se(t,n){te=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):ne=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(te),te=-1):h=!0,se(ee,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,x||(x=!0,ie()))),r},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),n=e(((e,n)=>{n.exports=t()})),r=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};functionLine truncated
|
||||
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
|
||||
`+ze+e+Be}var He=!1;function Ue(e,t){if(!e||He)return``;He=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}n=!1;try{var i=Object.getOwnPropertyDescriptor(e.prototype,`props`);Object.defineProperty(e.prototype,"props",{configurable:!0,set:function(){throw Error()}}),n=!0,new e}finally{n&&(i===void 0?delete e.prototype.props:Object.defineProperty(e.prototype,"props",i))}}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
|
||||
`),l=s.split(`
|
||||
`);for(i=r=0;r<c.length&&!c[r].includes(`DetermineComponentFrameRoot`);)r++;for(;i<l.length&&!l[i].includes(`DetermineComponentFrameRoot`);)i++;if(r===c.length||i===l.length)for(r=c.length-1,i=l.length-1;1<=r&&0<=i&&c[r]!==l[i];)i--;for(;1<=r&&0<=i;r--,i--)if(c[r]!==l[i]){if(r!==1||i!==1)do if(r--,i--,0>i||c[r]!==l[i]){var u=`
|
||||
`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(`<anonymous>`)&&(u=u.replace(`<anonymous>`,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{He=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Ve(n):``}function We(e,t){switch(e.tag){case 26:case 27:case 5:return Ve(e.type);case 16:return Ve(`Lazy`);case 13:return e.child!==t&&t!==null?Ve(`Suspense Fallback`):Ve(`Suspense`);case 19:return Ve(`SuspenseList`);case 0:case 15:return Ue(e.type,!1);case 11:return Ue(e.type.render,!1);case 1:return Ue(e.type,!0);case 31:return Ve(`Activity`);case 30:return Ve(`ViewTransition`);default:return``}}function Ge(e){try{var t=``,n=null;do t+=We(e,n),n=e,e=e.return;while(e);return t}catch(e){return`
|
||||
Error generating stack: `+e.message+`
|
||||
`+e.stack}}var Ke=Object.prototype.hasOwnProperty,qe=t.unstable_scheduleCallback,Je=t.unstable_cancelCallback,Ye=t.unstable_shouldYield,Xe=t.unstable_requestPaint,Ze=t.unstable_now,Qe=t.unstable_getCurrentPriorityLevel,$e=t.unstable_ImmediatePriority,et=t.unstable_UserBlockingPriority,tt=t.unstable_NormalPriority,nt=t.unstable_LowPriority,rt=t.unstable_IdlePriority,it=t.log,at=t.unstable_setDisableYieldValue,ot=null,st=null;function ct(e){if(typeof it==`function`&&at(e),st&&typeof st.setStrictMode==`function`)try{st.setStrictMode(ot,e)}catch{}}var lt=Math.clz32?Math.clz32:ft,ut=Math.log,dt=Math.LN2;function ft(e){return e>>>=0,e===0?32:31-(ut(e)/dt|0)|0}var pt=256,mt=262144,ht=4194304;function gt(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function _t(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=gt(n))):i=gt(o):i=gt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=gt(n))):i=gt(o)):i=gt(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function vt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function yt(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0<n;){var r=31-lt(n),i=1<<r;t|=e[r],n&=~i}return t}function bt(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function xt(){var e=ht;return ht<<=1,!(ht&62914560)&&(ht=4194304),e}function St(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ct(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function wt(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0<n;){var u=31-lt(n),d=1<<u;s[u]=0,c[u]=-1;var f=l[u];if(f!==null)for(l[u]=null,u=0;u<f.length;u++){var p=f[u];p!==null&&(p.lane&=-536870913)}n&=~d}r!==0&&Tt(e,r,0),a!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=a&~(o&~t))}function Tt(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-lt(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function Et(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-lt(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function Dt(e,t){var n=t&-t;return n=n&42?1:Ot(n),(n&(e.suspendedLanes|t))===0?n:0}function Ot(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function kt(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function At(){var e=E.p;return e===0?(e=window.event,e===void 0?32:Ch(e.type)):e}function jt(e,t){var n=E.p;try{return E.p=e,t()}finally{E.p=n}}var Mt=Math.random().toString(36).slice(2),Nt=`__reactFiber$`+Mt,Pt=`__reactProps$`+Mt,Ft=`__reactContainer$`+Mt,It=`__reactEvents$`+Mt,Lt=`__reactListeners$`+Mt,Rt=`__reactHandles$`+Mt,zt=`__reactResources$`+Mt,Bt=`__reactMarker$`+Mt,Vt=`__reactLoad$`+Mt;function Ht(e){delete e[Nt],delete e[Pt],delete e[Lt],delete e[Rt]}function Ut(e){var t;if(t=e[Nt])return t;for(var n=e.parentNode;n;){if(t=n[Ft]||n[Nt]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=fm(e);e!==null;){if(n=e[Nt])return n;e=fm(e)}return t}e=n,n=e.parentNode}return null}function Wt(e){if(e=e[Nt]||e[Ft]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function Gt(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(s(33))}function Kt(e){var t=e[zt];return t||=e[zt]={hoistableStyles:new Map,hoistableScripts:new Map},t}function qt(e){e[Bt]=!0}function Jt(e){e[Vt]=void 0}var Yt=new Set,Xt={};function Zt(e,t){Qt(e,t),Qt(e+`Capture`,t)}function Qt(e,t){for(Xt[e]=t,e=0;e<t.le
Line truncated
|
||||
`).replace(Qf,``)}function ep(e,t){return t=$f(t),$f(e)===t}function $(e,t,n,r,i,a){switch(n){case`children`:if(typeof r==`string`)t===`body`||t===`textarea`&&r===``||xn(e,r);else if(typeof r==`number`||typeof r==`bigint`)t!==`body`&&xn(e,``+r);else return;break;case`className`:on(e,`class`,r);break;case`tabIndex`:on(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:on(e,n,r);break;case`style`:wn(e,r,a);return;case`data`:if(t!==`object`){on(e,`data`,r);break}case`src`:case`href`:if(r===``&&(t!==`a`||n!==`href`)||r==null||typeof r==`function`||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=On(r),e.setAttribute(n,r);break;case`action`:case`formAction`:if(typeof r==`function`){e.setAttribute(n,`javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')`);break}if(typeof a==`function`&&(n===`formAction`?(t!==`input`&&$(e,t,`name`,i.name,i,null),$(e,t,`formEncType`,i.formEncType,i,null),$(e,t,`formMethod`,i.formMethod,i,null),$(e,t,`formTarget`,i.formTarget,i,null)):($(e,t,`encType`,i.encType,i,null),$(e,t,`method`,i.method,i,null),$(e,t,`target`,i.target,i,null))),r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=On(r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=kn);return;case`onScroll`:r!=null&&Q(`scroll`,e);return;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);return;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(s(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(s(60));a?.__html!==n&&(e.innerHTML=n)}}break;case`multiple`:e.multiple=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`muted`:e.muted=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`defaultValue`:case`defaultChecked`:case`innerHTML`:case`ref`:break;case`autoFocus`:break;case`xlinkHref`:if(r==null||typeof r==`function`||typeof r==`boolean`||typeof r==`symbol`){e.removeAttribute(`xlink:href`);break}n=On(r),e.setAttributeNS(`http://www.w3.org/1999/xlink`,`xlink:href`,n);break;case`contentEditable`:case`spellCheck`:case`draggable`:case`value`:case`autoReverse`:case`externalResourcesRequired`:case`focusable`:case`preserveAlpha`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`inert`:case`allowFullScreen`:case`async`:case`autoPlay`:case`controls`:case`credentialless`:case`default`:case`defer`:case`disabled`:case`disablePictureInPicture`:case`disableRemotePlayback`:case`formNoValidate`:case`hidden`:case`loop`:case`noModule`:case`noValidate`:case`open`:case`playsInline`:case`readOnly`:case`required`:case`reversed`:case`scoped`:case`seamless`:case`itemScope`:r&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``):e.removeAttribute(n);break;case`capture`:case`download`:!0===r?e.setAttribute(n,``):!1!==r&&r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`cols`:case`rows`:case`size`:case`span`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case`rowSpan`:case`start`:r==null||typeof r==`function`||typeof r==`symbol`||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case`popover`:Q(`beforetoggle`,e),Q(`toggle`,e),an(e,`popover`,r);break;case`xlinkActuate`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:an(e,`is`,r);break;case`innerText`:case`textContent`:return;default:if(!(2<n.length)||n[0]!==`o`&&n[0]!==`O`||n[1]!==`n`&&n[1]!==`N`)n=En.get(n)||n,an(e,n,r);else return}O=!0}function tp(e,t,n,r,i,a){switch(n){case`style`:wn(e,r,a);return;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(s(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(s(60));a?.__html!==n&&(e.innerHTML=n)}}break;case`children`:if(typeof r==`string`)xn(e,r);else if(typeof r==`number`||typeof r==`bigint`)xn(e,``+r);else return;break;case`onScroll`:r!=null&&Q(`scroll`,e);return;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);return;case`onClick`:r!=null&&(e.onclick=kn);return;case`suppressContent
Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
:root{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--background:#f6f5f4;--foreground:#2e3436;--muted-foreground:#5e5c64;--progress-label:#3d3846;--progress-track:#d5d3d1;--progress-fill:#3584e4;--error:#9c2f2f;--button:#1c71d8;--button-hover:#1a5fb4;--button-active:#174a8b;--focus-ring:#1a5fb4}:root[data-theme=dark]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--background:#242424;--foreground:#fff;--muted-foreground:#c0bfbc;--progress-label:#deddda;--progress-track:#454545;--progress-fill:#78aeed;--error:#ffb4ab;--button:#1c71d8;--button-hover:#3584e4;--button-active:#1a5fb4;--focus-ring:#78aeed}html,body,#root{box-sizing:border-box;-webkit-user-select:none;user-select:none;cursor:default;height:100%;margin:0;padding:0;overflow:hidden}body{background:var(--background);color:var(--foreground);font-family:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}button{font:inherit}.update-window{box-sizing:border-box;background:var(--background);align-items:center;gap:15px;width:100%;height:100%;padding:16px 18px;display:flex}.update-logo{flex:none;width:48px;height:48px}.update-content,.update-status{width:100%;min-width:0}.update-title{color:var(--foreground);letter-spacing:-.01em;margin:0;font-size:16px;font-weight:600;line-height:1.25}.update-description{color:var(--muted-foreground);margin:3px 0 0;font-size:12px;line-height:1.4}.progress-summary{justify-content:space-between;align-items:baseline;gap:12px;margin-top:3px;display:flex}.progress-summary .update-description{margin:0}.progress-bar{background-color:var(--progress-track);border-radius:3px;width:100%;height:6px;margin-top:9px;position:relative;overflow:hidden}.progress-fill{background:var(--progress-fill);border-radius:3px;height:100%;transition:width .18s ease-out}.progress-bar-indeterminate .progress-fill{width:35%;animation:1.4s ease-in-out infinite progress-indeterminate}@keyframes progress-indeterminate{0%{transform:translate(-110%)}to{transform:translate(300%)}}@media (prefers-reduced-motion:reduce){.progress-fill{transition:none}.progress-bar-indeterminate .progress-fill{animation:none;transform:translate(90%)}}.progress-label{color:var(--progress-label);font-variant-numeric:tabular-nums;text-align:right;white-space:nowrap;flex:none;font-size:12px;font-weight:500}.error-status{justify-content:space-between;align-items:center;gap:16px;display:flex}.error-status .update-title{color:var(--error)}.error-copy{min-width:0}.retry-button{background:var(--button);color:#fff;cursor:default;border:0;border-radius:8px;min-width:68px;padding:4px 14px;font-size:12px;font-weight:600;line-height:1.5}.retry-button:hover{background:var(--button-hover)}.retry-button:active{background:var(--button-active)}.retry-button:focus-visible{outline:2px solid var(--focus-ring);outline-offset:2px}
|
||||
@@ -0,0 +1,30 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<script>
|
||||
const theme = window.__GP_HELPER_THEME__ || "system";
|
||||
const systemTheme = matchMedia("(prefers-color-scheme: dark)");
|
||||
const applyTheme = () => {
|
||||
document.documentElement.dataset.theme =
|
||||
theme === "system" ? (systemTheme.matches ? "dark" : "light") : theme;
|
||||
};
|
||||
applyTheme();
|
||||
if (theme === "system") systemTheme.addEventListener("change", applyTheme);
|
||||
</script>
|
||||
<link rel="icon" type="image/svg+xml" href="/assets/icon-small-DFuJkDph.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>GPGUI Downloader</title>
|
||||
<script type="module" crossorigin src="/assets/main-BJvLW_Ih.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/main-CVTp2z3I.css">
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
/* workaround to webview font size auto scaling */
|
||||
var htmlFontSize = getComputedStyle(document.documentElement).fontSize;
|
||||
var ratio = parseInt(htmlFontSize, 10) / 16;
|
||||
document.documentElement.style.fontSize = 16 / ratio + "px";
|
||||
</script>
|
||||
<div id="root" data-tauri-drag-region></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -2,9 +2,19 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<script>
|
||||
const theme = window.__GP_HELPER_THEME__ || "system";
|
||||
const systemTheme = matchMedia("(prefers-color-scheme: dark)");
|
||||
const applyTheme = () => {
|
||||
document.documentElement.dataset.theme =
|
||||
theme === "system" ? (systemTheme.matches ? "dark" : "light") : theme;
|
||||
};
|
||||
applyTheme();
|
||||
if (theme === "system") systemTheme.addEventListener("change", applyTheme);
|
||||
</script>
|
||||
<link rel="icon" type="image/svg+xml" href="/src/assets/icon-small.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>GlobalProtect</title>
|
||||
<title>GPGUI Downloader</title>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
|
||||
@@ -5,33 +5,30 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"test": "node --test tests/*.test.mjs",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.13.0",
|
||||
"@emotion/styled": "^11.13.0",
|
||||
"@mui/icons-material": "^5.16.7",
|
||||
"@mui/material": "^5.16.7",
|
||||
"@tauri-apps/api": "^1.6.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
"@tauri-apps/api": "^2.12.4",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^1.6.0",
|
||||
"@types/node": "^20.14.15",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@typescript-eslint/eslint-plugin": "^6.21.0",
|
||||
"@typescript-eslint/parser": "^6.21.0",
|
||||
"@vitejs/plugin-react": "^4.3.1",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-react": "^7.35.0",
|
||||
"eslint-plugin-react-hooks": "^4.6.2",
|
||||
"prettier": "3.1.0",
|
||||
"typescript": "^5.5.4",
|
||||
"vite": "^4.5.3"
|
||||
"@tauri-apps/cli": "^2.12.4",
|
||||
"@types/node": "^26.6.6",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.72.1",
|
||||
"@typescript-eslint/parser": "^8.72.1",
|
||||
"@vitejs/plugin-react": "^6.1.2",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"prettier": "3.9.10",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^8.3.5"
|
||||
},
|
||||
"packageManager": "pnpm@8.15.7"
|
||||
"packageManager": "pnpm@9.15.1"
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
|
||||
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.5 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
@@ -1,16 +1,18 @@
|
||||
[package]
|
||||
name = "gpgui-helper"
|
||||
rust-version.workspace = true
|
||||
authors.workspace = true
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "1.5", features = [] }
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
gpapi = { path = "../../../crates/gpapi", features = ["tauri"] }
|
||||
tauri = { workspace = true, features = ["window-start-dragging"] }
|
||||
gpapi = { path = "../../../crates/gpapi", features = ["tauri", "clap"] }
|
||||
tauri.workspace = true
|
||||
|
||||
tokio.workspace = true
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
@@ -18,8 +20,11 @@ clap.workspace = true
|
||||
compile-time.workspace = true
|
||||
env_logger.workspace = true
|
||||
futures-util.workspace = true
|
||||
uuid.workspace = true
|
||||
zeroize.workspace = true
|
||||
tokio-tungstenite = "0.30"
|
||||
tempfile.workspace = true
|
||||
reqwest = { workspace = true, features = ["stream"] }
|
||||
|
||||
[features]
|
||||
custom-protocol = ["tauri/custom-protocol"]
|
||||
default = ["tauri/custom-protocol"]
|
||||
@@ -1,3 +1,62 @@
|
||||
use std::{env, fs, path::PathBuf, process::Command};
|
||||
|
||||
const UNKNOWN_COMMIT: &str = "unknown";
|
||||
const DISPLAY_COMMIT_LEN: usize = 9;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-env-changed=GPGUI_HELPER_GIT_COMMIT");
|
||||
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
|
||||
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
|
||||
|
||||
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../../..");
|
||||
let source_commit = repo_root.join("SOURCE_COMMIT");
|
||||
println!("cargo:rerun-if-changed={}", source_commit.display());
|
||||
println!(
|
||||
"cargo:rustc-env=GPGUI_HELPER_GIT_COMMIT={}",
|
||||
resolve_commit(&repo_root, &source_commit)
|
||||
);
|
||||
|
||||
tauri_build::build()
|
||||
}
|
||||
|
||||
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
|
||||
env_commit("GPGUI_HELPER_GIT_COMMIT")
|
||||
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
|
||||
.or_else(|| env_commit("GITHUB_SHA"))
|
||||
.or_else(|| file_commit(source_commit))
|
||||
.or_else(|| git_commit(repo_root))
|
||||
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
|
||||
}
|
||||
|
||||
fn env_commit(key: &str) -> Option<String> {
|
||||
env::var(key).ok().and_then(|value| normalize_commit(&value))
|
||||
}
|
||||
|
||||
fn file_commit(path: &PathBuf) -> Option<String> {
|
||||
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
|
||||
}
|
||||
|
||||
fn git_commit(repo_root: &PathBuf) -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.args(["rev-parse", "--short=9", "HEAD"])
|
||||
.current_dir(repo_root)
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
String::from_utf8(output.stdout)
|
||||
.ok()
|
||||
.and_then(|value| normalize_commit(&value))
|
||||
}
|
||||
|
||||
fn normalize_commit(value: &str) -> Option<String> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:window:allow-start-dragging",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit",
|
||||
"core:event:allow-unlisten"
|
||||
]
|
||||
}
|
||||
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 8.0 KiB |
|
Before Width: | Height: | Size: 2.5 KiB After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 38 KiB |