feat: build and publish Windows NSH packages with verified updates

This commit is contained in:
Kevin Yue committed 2026-11-14 23:10:21 +08:00
1 parent 2c9d227f02
commit 560d2b2de7
113 files changed
+7264 -801

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
# Requires MSYS2 base-devel/autoconf/automake/libtool and the MINGW64 gcc,
# pkgconf, gnutls, libxml2 and lz4 packages, plus Visual Studio C++ Build Tools.
[CmdletBinding()]
param(
[string]$MsysRoot = 'C:\msys64',
[string]$Prefix,
[int]$Jobs = 4
)
$ErrorActionPreference = 'Stop'
$repo = Split-Path $PSScriptRoot -Parent
if (!$Prefix) { $Prefix = Join-Path $repo 'target\native-windows' }
$Prefix = [System.IO.Path]::GetFullPath($Prefix)
$bash = Join-Path $MsysRoot 'usr\bin\bash.exe'
if (!(Test-Path $bash)) { throw 'MSYS2 is required to build OpenConnect.' }
$ErrorActionPreference = 'Continue'
& $bash "$PSScriptRoot/build-openconnect-windows.sh" $repo $Prefix $Jobs
$nativeExit = $LASTEXITCODE
$ErrorActionPreference = 'Stop'
if ($nativeExit -ne 0) { throw 'OpenConnect compilation failed.' }
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$vs = & $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
if (!$vs) { throw 'Visual Studio C++ Build Tools are required.' }
$tools = (Get-ChildItem "$vs\VC\Tools\MSVC\*\bin\Hostx64\x64\lib.exe" |
Sort-Object FullName | Select-Object -Last 1).DirectoryName
$dll = Join-Path $Prefix 'bin\libopenconnect-5.dll'
$exports = & "$tools\dumpbin.exe" /nologo /exports $dll
if ($LASTEXITCODE -ne 0) { throw 'Could not inspect OpenConnect exports.' }
$names = @($exports | ForEach-Object {
if ($_ -match '^\s+\d+\s+[0-9A-Fa-f]+\s+[0-9A-Fa-f]+\s+(\S+)') { $Matches[1] }
})
foreach ($symbol in @('openconnect_setup_cmd_pipe', 'openconnect_setup_tun_pipe', 'openconnect_set_configure_tun_handler', 'openconnect_set_tunnel_handler')) {
if ($names -notcontains $symbol) { throw "OpenConnect is missing $symbol." }
}
$definition = Join-Path $Prefix 'lib\openconnect.def'
[System.IO.File]::WriteAllLines($definition, @('LIBRARY libopenconnect-5.dll', 'EXPORTS') + $names)
& "$tools\lib.exe" /nologo /machine:x64 "/def:$definition" "/out:$Prefix\lib\openconnect.lib"
if ($LASTEXITCODE -ne 0) { throw 'Could not generate the MSVC import library.' }
# Copy only the native DLL's transitive MinGW runtime dependencies.
$pending = [System.Collections.Generic.Queue[string]]::new()
$visited = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
$pending.Enqueue($dll)
while ($pending.Count) {
$current = $pending.Dequeue()
if (!$visited.Add([System.IO.Path]::GetFileName($current))) { continue }
$dependencies = & "$tools\dumpbin.exe" /nologo /dependents $current
if ($LASTEXITCODE -ne 0) { throw "Could not inspect dependencies of $current." }
foreach ($line in $dependencies) {
if ($line -notmatch '^\s+(\S+\.dll)\s*$') { continue }
$name = $Matches[1]
$source = Join-Path "$MsysRoot\mingw64\bin" $name
if (Test-Path $source) {
$target = Join-Path "$Prefix\bin" $name
Copy-Item $source $target -Force
$pending.Enqueue($target)
} elseif (!(Test-Path "$env:SystemRoot\System32\$name") -and $name -notmatch '^(api|ext)-ms-win-') {
throw "Missing runtime dependency: $name"
}
}
}
Write-Host "OpenConnect native files: $Prefix"
Write-Host "Set OPENCONNECT_WINDOWS_PREFIX to this directory before building gpservice."
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Build the bundled protocol library with MSYS2's native Windows compiler.
set -euo pipefail
export PATH="/mingw64/bin:/usr/bin:$PATH"
repo=$(cygpath -u "$1")
prefix=$(cygpath -u "$2")
jobs=$3
export ACLOCAL_PATH=/mingw64/share/aclocal
source_dir="$repo/crates/openconnect/deps/openconnect"
build_dir="$repo/target/openconnect-windows"
cd "$source_dir"
autoreconf -fi
mkdir -p "$build_dir"
cd "$build_dir"
"$source_dir/configure" --host=x86_64-w64-mingw32 --prefix="$prefix" \
--enable-shared --disable-static --disable-nls --disable-docs --disable-dsa-tests \
--without-libproxy --without-stoken --without-libpcsclite --without-libpskc \
--without-gssapi --with-gnutls --without-openssl --with-gnutls-tss2=no \
--with-vpnc-script=unused
grep -q '^#define OPENCONNECT_GNUTLS 1$' config.h
make -j"$jobs" libopenconnect.la
make install-libLTLIBRARIES
install -Dm644 "$source_dir/openconnect.h" "$prefix/include/openconnect.h"
@@ -0,0 +1,33 @@
# Regenerate the NSIS sidebar from the shared Windows application icon.
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName PresentationCore
$root = Split-Path $PSScriptRoot -Parent
$iconPath = Join-Path $root 'apps\gpauth\icons\windows\icon.ico'
$outputPath = Join-Path $root 'packaging\windows\sidebar.bmp'
# WPF decodes PNG-compressed ICO frames correctly; GDI+ Icon.ToBitmap does not.
$decoder = [Windows.Media.Imaging.BitmapDecoder]::Create(
[Uri]$iconPath,
[Windows.Media.Imaging.BitmapCreateOptions]::PreservePixelFormat,
[Windows.Media.Imaging.BitmapCacheOption]::OnLoad
)
$frame = $decoder.Frames | Sort-Object PixelWidth -Descending | Select-Object -First 1
$encoder = New-Object Windows.Media.Imaging.PngBitmapEncoder
$encoder.Frames.Add($frame)
$stream = New-Object IO.MemoryStream
$encoder.Save($stream)
$stream.Position = 0
$image = [Drawing.Image]::FromStream($stream)
$canvas = New-Object Drawing.Bitmap(164, 314, ([Drawing.Imaging.PixelFormat]::Format24bppRgb))
$graphics = [Drawing.Graphics]::FromImage($canvas)
try {
$graphics.Clear([Drawing.Color]::White)
$graphics.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$graphics.DrawImage($image, 34, 54, 96, 96)
$canvas.Save($outputPath, [Drawing.Imaging.ImageFormat]::Bmp)
} finally {
$graphics.Dispose()
$canvas.Dispose()
$image.Dispose()
$stream.Dispose()
}
+1 -1
View File
@@ -175,7 +175,7 @@ release_snapshot() {
# The appcast publisher removes expired macOS snapshots after the new feed
# is live. Removing them here would temporarily break the current feed.
if [[ "$asset" == GPConnect_*_arm64.* ]]; then
if [[ "$asset" == GPConnect_*_arm64.* || "$asset" == GPConnect_*_windows-x64-setup.exe* ]]; then
continue
fi
if ! delete_release_asset "$asset"; then
+6
View File
@@ -0,0 +1,6 @@
#Requires -RunAsAdministrator
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$SourceDirectory)
$ErrorActionPreference = 'Stop'
$source = (Resolve-Path -LiteralPath $SourceDirectory).Path
& (Join-Path $source 'installer\machine-install.ps1') -Action Install -SourceDirectory $source
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Retain other platform/channel feeds before replacing a static Worker deployment."""
import argparse
import json
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlparse
from urllib.request import urlopen
import xml.etree.ElementTree as ET
FEEDS = ("appcast.xml", "latest.json", "windows/latest.json", "windows/stable/appcast.xml", "windows/snapshot/appcast.xml")
def preserve(base_url: str, directory: Path, exclude: list[str]) -> None:
if urlparse(base_url).scheme != "https":
raise ValueError("feed host must use HTTPS")
for relative in FEEDS:
if relative in exclude:
continue
try:
with urlopen(base_url.rstrip("/") + "/" + relative, timeout=30) as response:
data = response.read(1024 * 1024 + 1)
except HTTPError as error:
if error.code == 404:
continue
raise
if len(data) > 1024 * 1024:
raise ValueError(f"published feed is too large: {relative}")
if relative.endswith(".json"):
json.loads(data)
else:
ET.fromstring(data)
target = directory / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", required=True)
parser.add_argument("--directory", type=Path, required=True)
parser.add_argument("--exclude", action="append", default=[], choices=FEEDS)
args = parser.parse_args()
preserve(args.base_url, args.directory, args.exclude)
+6
View File
@@ -0,0 +1,6 @@
[CmdletBinding()]
param([string]$MsysRoot = 'C:\msys64', [string]$Prefix = $env:OPENCONNECT_WINDOWS_PREFIX)
$repo = Split-Path $PSScriptRoot -Parent
if (!$Prefix) { $Prefix = Join-Path $repo 'target\native-windows' }
& "$MsysRoot\usr\bin\bash.exe" "$PSScriptRoot/test-openconnect-windows.sh" $repo $Prefix
if ($LASTEXITCODE -ne 0) { throw 'Native OpenConnect packet-pipe tests failed.' }
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Run the native packet-pipe regression against the bundled Windows DLL.
set -euo pipefail
export PATH="/mingw64/bin:/usr/bin:$PATH"
repo=$(cygpath -u "$1")
prefix=$(cygpath -u "$2")
build_dir="$repo/target/openconnect-windows"
source_dir="$repo/crates/openconnect/deps/openconnect"
export PATH="$prefix/bin:$PATH"
gcc -Wall -Wextra -I"$build_dir" -I"$source_dir" -I"$source_dir/json" \
$(pkg-config --cflags gnutls libxml-2.0) \
"$repo/crates/openconnect/tests/windows_packet_pipe.c" \
-L"$prefix/lib" -lopenconnect -lws2_32 -o "$build_dir/test-windows-packet-pipe.exe"
"$build_dir/test-windows-packet-pipe.exe"
+164
View File
@@ -0,0 +1,164 @@
import argparse
import base64
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from urllib.error import HTTPError
import xml.etree.ElementTree as ET
def load(name, filename):
spec = importlib.util.spec_from_file_location(name, Path(__file__).parents[1] / filename)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
feed = load("windows_update_feed", "windows-update-feed.py")
preserver = load("preserve_update_feeds", "preserve-update-feeds.py")
class WindowsFeedTests(unittest.TestCase):
def args(self, root, channel="stable", version="3.4.0", build=None):
name = feed.installer_name(version, channel, build)
installer = root / name
installer.write_bytes(b"test installer")
signature = root / "installer.sig"
signature.write_text(base64.b64encode(bytes(64)).decode())
highlights = root / "highlights.txt"
highlights.write_text("Update & improve <Windows>.\n")
tag = f"v{version}" if channel == "stable" else "snapshot"
return argparse.Namespace(installer=installer, signature_file=signature,
installer_url=f"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{tag}/{name}",
repository="yuezk/GlobalProtect-openconnect", channel=channel,
version=version, build=build, released_at="2026-11-14",
highlights_file=highlights, input=None, output=root / "windows", allow_localhost=False)
def test_catalog_and_appcast_keep_the_same_version_and_payload(self):
with tempfile.TemporaryDirectory() as directory:
args = self.args(Path(directory))
feed.generate(args)
catalog = json.loads((args.output / "latest.json").read_text())
self.assertEqual(catalog["stable"]["platforms"], ["windows"])
item = ET.parse(args.output / "stable/appcast.xml").find("channel/item")
self.assertEqual(item.findtext("description"), "Update & improve <Windows>.")
enclosure = item.find("enclosure")
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}version"), catalog["stable"]["version"])
self.assertEqual(int(enclosure.get("length")), args.installer.stat().st_size)
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}os"), "windows-x64")
def test_snapshot_promotion_retains_stable_and_rejects_downgrade(self):
with tempfile.TemporaryDirectory() as directory:
args = self.args(Path(directory))
feed.generate(args)
args.input = args.output / "latest.json"
args.channel, args.build = "snapshot", "2026.1114.2"
args.installer = args.installer.rename(args.installer.parent / feed.installer_name(args.version, args.channel, args.build))
args.installer_url = f"https://github.com/{args.repository}/releases/download/snapshot/{args.installer.name}"
feed.generate(args)
catalog = json.loads(args.input.read_text())
self.assertEqual(catalog["stable"]["version"], "3.4.0")
self.assertEqual(catalog["snapshot"]["build"], "2026.1114.2")
enclosure = ET.parse(args.output / "snapshot/appcast.xml").find("channel/item/enclosure")
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}version"), "3.4.0-snapshot.2026.1114.2")
args.build = "2026.1114.1"
args.installer = args.installer.rename(args.installer.parent / feed.installer_name(args.version, args.channel, args.build))
args.installer_url = f"https://github.com/{args.repository}/releases/download/snapshot/{args.installer.name}"
with self.assertRaisesRegex(ValueError, "older"):
feed.generate(args)
def test_snapshot_filename_cannot_advertise_another_build(self):
with tempfile.TemporaryDirectory() as directory:
args = self.args(Path(directory), "snapshot", build="2026.1114.1")
args.build = "2026.1114.2"
with self.assertRaisesRegex(ValueError, "filename does not match"):
feed.generate(args)
def test_newer_stable_updates_both_native_feeds_and_retains_snapshot_history(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
snapshot = self.args(root, "snapshot", build="2026.1114.2")
feed.generate(snapshot)
stable = self.args(root, version="3.5.0")
stable.input = stable.output / "latest.json"
feed.generate(stable)
catalog = json.loads(stable.input.read_text())
self.assertEqual(catalog["snapshot"]["baseVersion"], "3.4.0")
self.assertEqual(catalog["snapshot"]["build"], "2026.1114.2")
for channel in ("stable", "snapshot"):
enclosure = ET.parse(stable.output / channel / "appcast.xml").find("channel/item/enclosure")
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}version"), "3.5.0")
self.assertEqual(enclosure.get("url"), stable.installer_url)
def test_stable_without_snapshot_initializes_both_native_feeds(self):
with tempfile.TemporaryDirectory() as directory:
args = self.args(Path(directory))
feed.generate(args)
self.assertEqual((args.output / "stable/appcast.xml").read_bytes(),
(args.output / "snapshot/appcast.xml").read_bytes())
self.assertIsNone(json.loads((args.output / "latest.json").read_text())["snapshot"])
def test_stable_does_not_replace_same_or_newer_base_snapshot_feed(self):
for snapshot_version in ("3.4.0", "3.5.0"):
with self.subTest(snapshot_version=snapshot_version), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
snapshot = self.args(root, "snapshot", version=snapshot_version, build="2026.1114.2")
feed.generate(snapshot)
before = (snapshot.output / "snapshot/appcast.xml").read_bytes()
stable = self.args(root)
stable.input = stable.output / "latest.json"
feed.generate(stable)
self.assertEqual((stable.output / "snapshot/appcast.xml").read_bytes(), before)
def test_snapshot_older_than_stable_is_rejected_without_changing_published_files(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
stable = self.args(root, version="3.5.0")
feed.generate(stable)
published = {relative: (stable.output / relative).read_bytes()
for relative in ("latest.json", "stable/appcast.xml", "snapshot/appcast.xml")}
snapshot = self.args(root, "snapshot", version="3.4.0", build="2026.1114.3")
snapshot.input = stable.output / "latest.json"
with self.assertRaisesRegex(ValueError, "snapshot base version is older"):
feed.generate(snapshot)
for relative, content in published.items():
self.assertEqual((stable.output / relative).read_bytes(), content)
def test_private_loopback_download_requires_explicit_opt_in(self):
with tempfile.TemporaryDirectory() as directory:
args = self.args(Path(directory))
args.installer_url = "http://127.0.0.1:18770/setup.exe"
with self.assertRaisesRegex(ValueError, "matching GitHub"):
feed.generate(args)
args.allow_localhost = True
feed.generate(args)
def test_missing_or_malformed_signature_is_rejected(self):
with tempfile.TemporaryDirectory() as directory:
args = self.args(Path(directory))
args.signature_file.write_text("not a signature")
with self.assertRaises(ValueError):
feed.generate(args)
def test_preservation_keeps_other_feeds_and_does_not_hide_server_errors(self):
class Response:
def __enter__(self): return self
def __exit__(self, *unused): pass
def read(self, length): return b'{"schemaVersion": 1}'
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
with patch.object(preserver, "urlopen", return_value=Response()) as request:
preserver.preserve("https://updates.gpgui.com", root,
["appcast.xml", "latest.json", "windows/stable/appcast.xml", "windows/snapshot/appcast.xml"])
self.assertTrue((root / "windows/latest.json").exists())
self.assertEqual(request.call_count, 1)
with patch.object(preserver, "urlopen", side_effect=HTTPError("url", 500, "failure", {}, None)):
with self.assertRaises(HTTPError):
preserver.preserve("https://updates.gpgui.com", root, [])
if __name__ == "__main__":
unittest.main()
+91
View File
@@ -0,0 +1,91 @@
# Run in an unlocked Windows desktop; drives only its own isolated fixture.
param([Parameter(Mandatory)][string]$Binary)
$ErrorActionPreference='Stop'
Add-Type -AssemblyName UIAutomationClient
Add-Type -AssemblyName UIAutomationTypes
Add-Type -AssemblyName System.Drawing
Add-Type @'
using System;
using System.Runtime.InteropServices;
public class GPAuthLiveResize {
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X,Y; }
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left,Top,Right,Bottom; }
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr value);
[DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr h,uint flags);
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h,out RECT r);
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
[DllImport("user32.dll")] public static extern bool SetCursorPos(int x,int y);
[DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
[DllImport("user32.dll")] public static extern void mouse_event(uint flags,uint x,uint y,uint data,UIntPtr extra);
[DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
}
'@
[GPAuthLiveResize]::SetThreadDpiAwarenessContext([IntPtr](-4)) | Out-Null
$work=Join-Path $env:TEMP ('gp-resize-test-'+[Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory $work | Out-Null
$previous=$env:WEBVIEW2_USER_DATA_FOLDER
$env:WEBVIEW2_USER_DATA_FOLDER=Join-Path $work 'profile'
$old=New-Object GPAuthLiveResize+POINT
[GPAuthLiveResize]::GetCursorPos([ref]$old) | Out-Null
$p=$null
try {
$p=Start-Process $Binary -ArgumentList @('https://preview.invalid','--saml-request','"<html><body><h1>Resize fixture</h1></body></html>"','--window-title','"GP Auth Resize Test"') -PassThru -RedirectStandardOutput "$work\result.json" -RedirectStandardError "$work\stderr.log"
$deadline=[DateTime]::UtcNow.AddSeconds(12)
$condition=New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ProcessIdProperty,[int]$p.Id)
$root=$null
do {
$roots=[Windows.Automation.AutomationElement]::RootElement.FindAll([Windows.Automation.TreeScope]::Children,$condition)
$root=@($roots | Where-Object {$_.Current.Name -eq 'GP Auth Resize Test' -and !$_.Current.IsOffscreen})[0]
if ($root) {break}
Start-Sleep -Milliseconds 100
} while([DateTime]::UtcNow -lt $deadline)
if (!$root) {throw 'Resize fixture did not open'}
$hwnd=[GPAuthLiveResize]::GetAncestor([IntPtr]$root.Current.NativeWindowHandle,2)
[GPAuthLiveResize]::SetForegroundWindow($hwnd) | Out-Null
Start-Sleep -Milliseconds 300
$name=New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ClassNameProperty,'Edit')
$address=$root.FindFirst([Windows.Automation.TreeScope]::Descendants,$name)
$bounds=$address.Current.BoundingRectangle
$sample=New-Object GPAuthLiveResize+POINT
$sample.X=[int]($bounds.Left+300);$sample.Y=[int]($bounds.Top+$bounds.Height/2)
$pixel=New-Object Drawing.Bitmap(1,1)
$graphics=[Drawing.Graphics]::FromImage($pixel)
function Pixel {
$graphics.CopyFromScreen($sample.X,$sample.Y,0,0,$pixel.Size)
$pixel.GetPixel(0,0).ToArgb()
}
$baseline=Pixel
$frame=New-Object GPAuthLiveResize+RECT
[GPAuthLiveResize]::GetWindowRect($hwnd,[ref]$frame) | Out-Null
$startX=$frame.Right-2;$startY=[int](($frame.Top+$frame.Bottom)/2)
$edge=New-Object GPAuthLiveResize+POINT
$edge.X=$startX;$edge.Y=$startY
if ([GPAuthLiveResize]::GetAncestor([GPAuthLiveResize]::WindowFromPoint($edge),2) -ne $hwnd) {throw 'Resize edge is covered'}
[GPAuthLiveResize]::SetCursorPos($startX,$startY) | Out-Null
[GPAuthLiveResize]::mouse_event(2,0,0,0,[UIntPtr]::Zero)
$bad=0;$total=0
try {
foreach($direction in @(1,-1,1,-1,1,-1)) {
for($i=1;$i -le 40;$i++) {
$offset=6*$i
if ($direction -lt 0) {$offset=6*(40-$i)}
[GPAuthLiveResize]::SetCursorPos($startX+$offset,$startY) | Out-Null
Start-Sleep -Milliseconds 8
$value=Pixel
$total++
if ($value -ne $baseline) {$bad++}
}
}
} finally {[GPAuthLiveResize]::mouse_event(4,0,0,0,[UIntPtr]::Zero)}
"Address samples while dragging: $bad hidden of $total; baseline $baseline"
if ($bad -gt 0) {throw 'Address bar disappears during live resizing'}
'PASS: address bar remains visible throughout live resize'
} finally {
[GPAuthLiveResize]::mouse_event(4,0,0,0,[UIntPtr]::Zero)
[GPAuthLiveResize]::SetCursorPos($old.X,$old.Y) | Out-Null
if ($graphics) {$graphics.Dispose();$pixel.Dispose()}
if ($p -and !$p.HasExited) {Stop-Process -Id $p.Id}
$env:WEBVIEW2_USER_DATA_FOLDER=$previous
Start-Sleep -Milliseconds 500
Remove-Item $work -Recurse -Force -ErrorAction SilentlyContinue
}
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Loopback-only SAML/WebView2 fixture. All returned credentials are synthetic."""
import argparse
import base64
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import ssl
import threading
BODY = '<html><saml-auth-status>1</saml-auth-status><saml-username>webview-fixture</saml-username><prelogin-cookie>synthetic-webview-cookie</prelogin-cookie></html>'
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_POST(self):
self.rfile.read(int(self.headers.get('Content-Length', '0')))
request = base64.b64encode(f'http://127.0.0.1:{args.http_port}/body'.encode()).decode()
self.respond(f'<prelogin-response><status>Success</status><saml-auth-method>POST</saml-auth-method><saml-request>{request}</saml-request><saml-default-browser>no</saml-default-browser></prelogin-response>')
def respond(self, body, headers=(), status=200):
data = body.encode()
self.send_response(status)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Content-Length', str(len(data)))
for name, value in headers:
self.send_header(name, value)
self.end_headers()
self.wfile.write(data)
def do_GET(self):
path = self.path.split('?')[0]
if path == '/redirect':
self.respond('', [('Location', '/body')], 302)
elif path == '/headers':
self.respond('<html>Header response</html>', [('saml-auth-status', '1'), ('saml-username', 'webview-fixture'), ('prelogin-cookie', 'synthetic-header-cookie')])
elif path == '/callback':
self.respond('<html><script>location.href="globalprotectcallback:cas-as=1&un=webview-fixture&token=synthetic-webview-token"</script></html>')
elif path == '/cookie-set':
self.respond(BODY, [('Set-Cookie', 'webview_fixture=present; Max-Age=3600; Path=/; HttpOnly')])
elif path in ['/cookie-present', '/cookie-clean']:
present = 'webview_fixture=present' in self.headers.get('Cookie', '')
success = present if path == '/cookie-present' else not present
self.respond(BODY if success else '<saml-auth-status>0</saml-auth-status>')
elif path == '/user-agent':
agent = self.headers.get('User-Agent', '')
self.respond(BODY if agent.startswith('PAN GlobalProtect/') and 'Mozilla/' in agent else '<saml-auth-status>0</saml-auth-status>')
elif path == '/temporary':
self.respond('<html>Temporarily Unavailable</html>')
elif path == '/signin':
self.respond('<html><title>Fixture sign-in</title><h1>Sign in</h1><a href="/body">Complete fixture sign-in</a></html>')
elif path == '/rejected':
self.respond('<saml-auth-status>0</saml-auth-status>')
elif path == '/cross-host':
self.respond('', [('Location', f'https://127.0.0.1:{args.https_port}/body')], 302)
elif path == '/body':
self.respond(BODY)
else:
self.send_error(404)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--http-port', type=int, default=18769)
parser.add_argument('--https-port', type=int, default=18770)
parser.add_argument('--cert', required=True)
parser.add_argument('--key', required=True)
args = parser.parse_args()
http = ThreadingHTTPServer(('127.0.0.1', args.http_port), Handler)
https = ThreadingHTTPServer(('127.0.0.1', args.https_port), Handler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(args.cert, args.key)
https.socket = context.wrap_socket(https.socket, server_side=True)
threading.Thread(target=https.serve_forever, daemon=True).start()
print('Webview fixture ready', flush=True)
http.serve_forever()
+160
View File
@@ -0,0 +1,160 @@
# Run in an unlocked Windows desktop. Start windows-webview-server.py first.
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Binary,
[string]$FixtureUrl = 'http://127.0.0.1:18769',
[string]$TlsUrl = 'https://localhost:18770'
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName UIAutomationClient
Add-Type -AssemblyName UIAutomationTypes
Add-Type @'
using System;
using System.Runtime.InteropServices;
public class GPWebviewFixture {
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr h, uint m, IntPtr w, IntPtr l);
[DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int w, int height, uint flags);
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
}
'@
$work = Join-Path $env:TEMP ('gp-webview-test-' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory $work | Out-Null
$previousProfile = $env:WEBVIEW2_USER_DATA_FOLDER
# Microsoft's override isolates cookie tests from the user's real sign-in profile.
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $work 'profile'
$script:current = $null
$script:index = 0
function Start-Auth([string]$Request, [string[]]$Extra = @()) {
$script:index++
$script:stdout = Join-Path $work "$script:index.json"
$script:stderr = Join-Path $work "$script:index.log"
$arguments = @($FixtureUrl, '--saml-request', ('"' + $Request + '"'), '--window-title', '"GP Auth Fixture"', '--os', 'Windows') + $Extra
$script:current = Start-Process -FilePath $Binary -ArgumentList $arguments -PassThru -RedirectStandardOutput $script:stdout -RedirectStandardError $script:stderr
$null = $script:current.Handle
}
function Finish-Auth([bool]$Success) {
if (!$script:current.WaitForExit(20000)) { throw "Authentication timed out in case $script:index" }
if ($script:current.ExitCode -ne 0) { throw "Authenticator exited with $($script:current.ExitCode): $(Get-Content $script:stderr -Tail 8 | Out-String)" }
$result = Get-Content $script:stdout -Raw | ConvertFrom-Json
if ($Success) {
if ($result.success.username -ne 'webview-fixture') { throw "Expected successful fixture authentication in case $script:index" }
} elseif ($result -ne 'cancelled') { throw "Expected cancellation in case $script:index" }
$script:current = $null
}
function Find-Control([string]$Name) {
$processCondition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ProcessIdProperty, [int]$script:current.Id)
$windows = [Windows.Automation.AutomationElement]::RootElement.FindAll([Windows.Automation.TreeScope]::Children, $processCondition)
$condition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::NameProperty, $Name)
foreach ($window in $windows) {
$node = $window.FindFirst([Windows.Automation.TreeScope]::Descendants, $condition)
if ($node) { return $node }
}
}
function Wait-Control([string]$Name) {
$deadline = [DateTime]::UtcNow.AddSeconds(15)
do {
$node = Find-Control $Name
if ($node -and !$node.Current.IsOffscreen) { return $node }
Start-Sleep -Milliseconds 100
} while ([DateTime]::UtcNow -lt $deadline -and !$script:current.HasExited)
throw "Missing '$Name' in authentication case $script:index"
}
function Invoke-Control([string]$Name) {
(Wait-Control $Name).GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke()
}
function Close-Auth {
$processCondition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ProcessIdProperty, [int]$script:current.Id)
$deadline = [DateTime]::UtcNow.AddSeconds(15)
do {
$windows = [Windows.Automation.AutomationElement]::RootElement.FindAll([Windows.Automation.TreeScope]::Children, $processCondition)
foreach ($window in $windows) {
if ($window.Current.Name -eq 'GP Auth Fixture' -and !$window.Current.IsOffscreen) {
[GPWebviewFixture]::PostMessage([IntPtr]$window.Current.NativeWindowHandle, 0x10, [IntPtr]::Zero, [IntPtr]::Zero) | Out-Null
return
}
}
Start-Sleep -Milliseconds 100
} while ([DateTime]::UtcNow -lt $deadline)
throw 'Sign-in window did not become visible'
}
try {
foreach ($path in @('/body', '/headers', '/redirect', '/callback', '/user-agent')) {
Start-Auth ($FixtureUrl + $path)
Finish-Auth $true
"PASS: $path"
}
Start-Auth '<html><saml-auth-status>1</saml-auth-status><saml-username>webview-fixture</saml-username><prelogin-cookie>synthetic-html-cookie</prelogin-cookie></html>'
Finish-Auth $true
'PASS: supplied HTML'
Start-Auth ($FixtureUrl + '/cookie-set')
Finish-Auth $true
Start-Auth ($FixtureUrl + '/cookie-present')
Finish-Auth $true
Start-Auth ($FixtureUrl + '/cookie-clean') @('--clean')
Finish-Auth $true
'PASS: cookie persistence and clean sign-in'
Start-Auth ($FixtureUrl + '/signin')
$link = Wait-Control 'Complete fixture sign-in'
$condition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ProcessIdProperty, [int]$script:current.Id)
$roots = [Windows.Automation.AutomationElement]::RootElement.FindAll([Windows.Automation.TreeScope]::Children, $condition)
$root = @($roots | Where-Object { $_.Current.Name -eq 'GP Auth Fixture' })[0]
if (!$root) { throw 'Missing sign-in window' }
$editCondition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ClassNameProperty, 'Edit')
$address = $root.FindFirst([Windows.Automation.TreeScope]::Descendants, $editCondition)
if (!$address) { throw 'Missing native address bar' }
$bounds = $address.Current.BoundingRectangle
if ($link.Current.BoundingRectangle.Top -lt $bounds.Bottom) { throw 'Webview overlaps the address bar' }
[GPWebviewFixture]::SetForegroundWindow([IntPtr]$root.Current.NativeWindowHandle) | Out-Null
Start-Sleep -Milliseconds 200
$point = New-Object GPWebviewFixture+POINT
$point.X = [int]($bounds.Left + $bounds.Width / 2); $point.Y = [int]($bounds.Top + $bounds.Height / 2)
if ([GPWebviewFixture]::WindowFromPoint($point) -ne [IntPtr]$address.Current.NativeWindowHandle) { throw 'Native address bar is covered' }
$frame = $root.Current.BoundingRectangle
[GPWebviewFixture]::SetWindowPos([IntPtr]$root.Current.NativeWindowHandle, [IntPtr]::Zero, 0, 0, [int]$frame.Width - 40, [int]$frame.Height - 40, 6) | Out-Null
Start-Sleep -Milliseconds 300
$bounds = $address.Current.BoundingRectangle
$point.X = [int]($bounds.Left + $bounds.Width / 2); $point.Y = [int]($bounds.Top + $bounds.Height / 2)
if ($link.Current.BoundingRectangle.Top -lt $bounds.Bottom -or [GPWebviewFixture]::WindowFromPoint($point) -ne [IntPtr]$address.Current.NativeWindowHandle) { throw 'Resizing broke the native address bar layout' }
$link.GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke()
Finish-Auth $true
'PASS: interactive embedded sign-in'
Start-Auth ($FixtureUrl + '/signin')
Close-Auth
Finish-Auth $false
'PASS: window cancellation'
Start-Auth ($FixtureUrl + '/rejected')
Invoke-Control 'Cancel'
Finish-Auth $false
'PASS: rejected sign-in recovery'
Start-Auth ($FixtureUrl + '/temporary')
Finish-Auth $true
'PASS: automatic fresh-prelogin recovery'
Start-Auth ($TlsUrl + '/body') @('--ignore-tls-errors')
Finish-Auth $true
'PASS: explicit ignore-TLS option'
Start-Auth ($TlsUrl + '/body')
Invoke-Control ('Continue Anyway' + [char]0x2026)
Invoke-Control 'Yes'
Finish-Auth $true
'PASS: certificate warning and confirmed exception'
Start-Auth ($TlsUrl + '/body')
Invoke-Control 'Cancel'
Finish-Auth $false
'PASS: certificate exception does not survive the sign-in window'
Start-Auth ($TlsUrl + '/cross-host')
Invoke-Control ('Continue Anyway' + [char]0x2026)
Invoke-Control 'Yes'
Invoke-Control 'Cancel'
Finish-Auth $false
'PASS: certificate exception is scoped to the approved host'
} finally {
if ($script:current -and !$script:current.HasExited) { Stop-Process -Id $script:current.Id; $script:current.WaitForExit() }
$env:WEBVIEW2_USER_DATA_FOLDER = $previousProfile
# WebView2's browser process releases its profile shortly after the window closes.
for ($attempt = 0; $attempt -lt 10; $attempt++) {
try { Remove-Item $work -Recurse -Force; break } catch { Start-Sleep -Milliseconds 500 }
}
if (Test-Path $work) { Write-Warning "Fixture profile remains at $work" }
}
+5
View File
@@ -0,0 +1,5 @@
#Requires -RunAsAdministrator
[CmdletBinding()]
param()
$ErrorActionPreference = 'Stop'
& (Join-Path $PSScriptRoot 'installer\machine-install.ps1') -Action Uninstall
+2 -2
View File
@@ -10,7 +10,7 @@ import unicodedata
from pathlib import Path
from urllib.parse import urlparse
ALLOWED_PLATFORMS = {"linux", "freebsd", "openbsd"}
ALLOWED_PLATFORMS = {"linux", "freebsd", "openbsd", "windows"}
SEMVER = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")
BUILD = re.compile(r"^(0|[1-9][0-9]*)(?:\.(0|[1-9][0-9]*)){0,2}$")
EXPECTED_TOP_LEVEL_KEYS = {"schemaVersion", "stable", "snapshot"}
@@ -192,7 +192,7 @@ def main() -> None:
generate_parser.add_argument("--channel", choices=("stable", "snapshot"), required=True)
generate_parser.add_argument("--version", required=True)
generate_parser.add_argument("--platform", action="append", choices=sorted(ALLOWED_PLATFORMS),
help="Published Unix target; repeat for multiple targets (default: all)")
help="Published target; repeat for multiple targets (default: Unix targets)")
generate_parser.add_argument("--build")
generate_parser.add_argument("--released-at", required=True)
generate_parser.add_argument("--highlights-file", required=True, type=Path)
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Build the Windows catalog and WinSparkle appcast from one verified installer."""
from __future__ import annotations
import argparse
import base64
import hashlib
import importlib.util
import json
from pathlib import Path
from urllib.parse import urlparse
import xml.etree.ElementTree as ET
SPARKLE = "http://www.andymatuschak.org/xml-namespaces/sparkle"
ET.register_namespace("sparkle", SPARKLE)
spec = importlib.util.spec_from_file_location("update_manifest", Path(__file__).with_name("validate-update-manifest.py"))
manifest = importlib.util.module_from_spec(spec)
spec.loader.exec_module(manifest)
def release_version(version: str, channel: str, build: str | None) -> str:
if channel == "snapshot":
return f"{version}-snapshot.{build}"
return version
def installer_name(version: str, channel: str, build: str | None) -> str:
return f"GPConnect_{release_version(version, channel, build)}_windows-x64-setup.exe"
def generate(args: argparse.Namespace) -> None:
manifest.version_tuple(args.version)
if args.channel == "snapshot":
if args.build is None:
raise ValueError("snapshot releases require --build")
manifest.build_tuple(args.build)
elif args.build is not None:
raise ValueError("stable releases must not specify --build")
expected_name = installer_name(args.version, args.channel, args.build)
if not args.allow_localhost and args.installer.name != expected_name:
raise ValueError("installer filename does not match the version, channel and build")
parsed = urlparse(args.installer_url)
tag = f"v{args.version}" if args.channel == "stable" else "snapshot"
expected = f"https://github.com/{args.repository}/releases/download/{tag}/"
local = args.allow_localhost and parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}
if not local and not args.installer_url.startswith(expected):
raise ValueError("installer URL must identify the matching GitHub release asset")
if parsed.query or parsed.fragment or not parsed.path.endswith(".exe"):
raise ValueError("installer URL must name an EXE without query or fragment")
if not local and parsed.path.rsplit("/", 1)[-1] != expected_name:
raise ValueError("installer download filename does not match the version, channel and build")
signature = args.signature_file.read_text(encoding="ascii").strip()
if len(base64.b64decode(signature, validate=True)) != 64:
raise ValueError("EdDSA signature must contain 64 bytes")
length = args.installer.stat().st_size
if length == 0:
raise ValueError("installer is empty")
if args.channel == "snapshot" and args.input is not None:
previous = manifest.validate_manifest(json.loads(args.input.read_text(encoding="utf-8")), args.repository)
stable = previous["stable"]
if stable is not None and manifest.version_tuple(args.version) < manifest.version_tuple(stable["version"]):
raise ValueError("snapshot base version is older than the published stable release")
output = args.output
output.mkdir(parents=True, exist_ok=True)
catalog = output / "latest.json"
manifest.generate(argparse.Namespace(
repository=args.repository, channel=args.channel, version=args.version,
platform=["windows"], build=args.build, released_at=args.released_at,
highlights_file=args.highlights_file, input=args.input, output=catalog,
))
data = json.loads(catalog.read_text(encoding="utf-8"))
if any(release and release["platforms"] != ["windows"] for release in [data["stable"], data["snapshot"]]):
raise ValueError("Windows catalog may contain only the Windows target")
release = data[args.channel]
display_version = release_version(args.version, args.channel, args.build)
rss = ET.Element("rss", {"version": "2.0"})
channel = ET.SubElement(rss, "channel")
ET.SubElement(channel, "title").text = "GP Connect for Windows"
item = ET.SubElement(channel, "item")
ET.SubElement(item, "title").text = f"GP Connect {display_version}"
ET.SubElement(item, "description").text = "\n".join(release["highlights"])
ET.SubElement(item, f"{{{SPARKLE}}}minimumSystemVersion").text = "10.0.19041"
ET.SubElement(item, "enclosure", {
"url": args.installer_url, "length": str(length), "type": "application/octet-stream",
f"{{{SPARKLE}}}version": display_version,
f"{{{SPARKLE}}}shortVersionString": display_version,
f"{{{SPARKLE}}}os": "windows-x64", f"{{{SPARKLE}}}edSignature": signature,
})
ET.indent(rss)
channels = [args.channel]
snapshot = data["snapshot"]
if args.channel == "stable" and (
snapshot is None or manifest.version_tuple(args.version) > manifest.version_tuple(snapshot["baseVersion"])
):
# Core offers a newer stable release to snapshot installations too.
# Keep the snapshot catalog history, but route its native install feed
# to the same newer stable candidate until a new snapshot is promoted.
channels.append("snapshot")
for target_channel in channels:
channel_directory = output / target_channel
channel_directory.mkdir(exist_ok=True)
ET.ElementTree(rss).write(channel_directory / "appcast.xml", encoding="utf-8", xml_declaration=True)
with args.installer.open("rb") as installer:
digest = hashlib.file_digest(installer, "sha256").hexdigest()
(output / (args.installer.name + ".sha256")).write_text(f"{digest} {args.installer.name}\n", encoding="ascii")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--installer", type=Path, required=True)
parser.add_argument("--installer-url", required=True)
parser.add_argument("--signature-file", type=Path, required=True)
parser.add_argument("--repository", default="yuezk/GlobalProtect-openconnect")
parser.add_argument("--channel", choices=("stable", "snapshot"), required=True)
parser.add_argument("--version", required=True)
parser.add_argument("--build")
parser.add_argument("--released-at", required=True)
parser.add_argument("--highlights-file", type=Path, required=True)
parser.add_argument("--input", type=Path)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--allow-localhost", action="store_true", help="Permit an isolated loopback test download")
args = parser.parse_args()
try:
generate(args)
except (OSError, ValueError) as error:
parser.error(str(error))
if __name__ == "__main__":
main()