feat: build and publish Windows NSH packages with verified updates

This commit is contained in:
Kevin Yue committed 2026-11-18 13:55:52 +08:00
1 parent 754b220a9d
commit b4c1dc1647
105 files changed
+6606 -798

No files matched your search

+12 -7
View File
@@ -30,7 +30,7 @@ pub(super) struct ConnectionResources {
/// the complete ledger and its retained identity resources to the service.
pub(crate) async fn prepare_connection(
request: ConnectRequest,
brokered_macos: bool,
restricted_desktop: bool,
cancellation: CancellationToken,
) -> anyhow::Result<PreparedConnection> {
let mode = request.args().packet_delivery().clone();
@@ -77,11 +77,16 @@ pub(crate) async fn prepare_connection(
};
check()?;
let args = setup_request.args();
let identity = super::prepare_identity(args, brokered_macos || non_tunnel)?;
let directory = brokered_macos.then(|| std::path::Path::new("/var/run/com.yuezk.gpgui"));
let identity = super::prepare_identity(args, restricted_desktop || non_tunnel)?;
#[cfg(target_os = "macos")]
let directory = restricted_desktop.then(|| std::path::PathBuf::from("/var/run/com.yuezk.gpgui"));
#[cfg(windows)]
let directory = Some(common::paths::service_private_dir());
#[cfg(all(unix, not(target_os = "macos")))]
let directory: Option<std::path::PathBuf> = None;
let identity_files = identity
.as_ref()
.map(|identity| identity.write_files(directory))
.map(|identity| identity.write_files(directory.as_deref()))
.transpose()?;
let host = args.host_identity().context("Authenticated host identity is missing")?;
let profile = crate::hip_source::profile(
@@ -181,8 +186,8 @@ mod tests {
use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo};
#[tokio::test]
async fn brokered_macos_and_non_tunnel_identity_reject_path_handoff() {
for (brokered_macos, non_tunnel) in [(true, false), (false, true), (true, true)] {
async fn restricted_desktop_and_non_tunnel_identity_reject_path_handoff() {
for (restricted_desktop, non_tunnel) in [(true, false), (false, true), (true, true)] {
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
.with_certificate(Some("/identity.pem".into()));
@@ -192,7 +197,7 @@ mod tests {
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
}
let request = serde_json::from_value(wire).unwrap();
let error = prepare_connection(request, brokered_macos, CancellationToken::new())
let error = prepare_connection(request, restricted_desktop, CancellationToken::new())
.await
.err()
.unwrap();
+12 -8
View File
@@ -20,7 +20,7 @@ pub(super) struct AttemptInput {
pub desktop_uid: Option<u32>,
pub edited_report: Option<Arc<str>>,
pub session_id: Option<Uuid>,
pub brokered_macos: bool,
pub restricted_desktop: bool,
pub registry: Arc<crate::session_registry::SessionRegistry>,
pub lifecycle: LifecycleHandle,
}
@@ -31,6 +31,7 @@ struct TunnelInput {
source: Arc<openconnect::HipSource>,
session_id: Option<Uuid>,
registry: Arc<crate::session_registry::SessionRegistry>,
#[cfg(unix)]
desktop_uid: Option<u32>,
}
@@ -55,7 +56,7 @@ pub(super) fn spawn(
let request = input.connection.request.clone();
let resources = input.connection.resources.clone();
let desktop_uid = input.desktop_uid;
let brokered = input.brokered_macos;
let brokered = input.restricted_desktop;
let edited = input.edited_report.clone();
let setup_cancel = cancellation.clone();
let execution = tokio::task::spawn_blocking(move || {
@@ -105,6 +106,7 @@ pub(super) fn spawn(
source,
session_id: input.session_id,
registry: input.registry.clone(),
#[cfg(unix)]
desktop_uid: input.desktop_uid,
};
input.connection.request.release_script_tun_bootstrap();
@@ -253,12 +255,14 @@ fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyho
),
gpapi::script_tun::PacketDelivery::ScriptTun(request) => {
ensure!(input.session_id.is_some(), "Script-tun requires a desktop session");
let (builder, script_tun) = super::script_tun::builder(
member.gateway.server(),
member.authentication.cookie(),
request,
input.desktop_uid.context("Desktop identity is unavailable")?,
)?;
#[cfg(unix)]
let owner = input.desktop_uid.context("Desktop identity is unavailable")?;
#[cfg(windows)]
let owner = input
.registry
.windows_identity(input.session_id.context("Desktop session is unavailable")?)?;
let (builder, script_tun) =
super::script_tun::builder(member.gateway.server(), member.authentication.cookie(), request, owner)?;
(builder, Some(script_tun))
}
};
+145 -125
View File
@@ -1,40 +1,19 @@
//! Supervision of an unprivileged script-tun consumer; payload semantics belong to the caller.
use super::{LifecycleEvent, LifecycleHandle};
use anyhow::{Context, bail, ensure};
use gpapi::script_tun::{Bootstrap, Identity, Message, ScriptTunRequest, receive, send as send_message};
use openconnect::{Vpn, VpnBuilder, tunnel::Event};
use gpapi::script_tun::{Bootstrap, Identity, Message, receive, send as send_message};
use openconnect::{Vpn, tunnel::Event};
use std::{sync::Arc, time::Duration};
use tokio::{net::UnixStream, sync::mpsc, time::Instant};
use tokio::{sync::mpsc, time::Instant};
use tokio_util::sync::CancellationToken;
pub(super) struct PreparedScriptTun {
pub control: std::os::unix::net::UnixStream,
pub bootstrap: Bootstrap,
}
pub(super) fn builder(
server: &str,
cookie: &str,
request: &ScriptTunRequest,
uid: u32,
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
request.validate()?;
ensure!(uid != 0, "Script-tun worker requires a desktop user");
let (control, child) = std::os::unix::net::UnixStream::pair()?;
let builder = Vpn::builder(server, cookie).script_tun_program(
request.program.to_str().context("Program is not UTF-8")?,
&request.args,
uid,
child.into(),
)?;
Ok((
builder,
PreparedScriptTun {
control,
bootstrap: request.bootstrap.clone(),
},
))
}
#[cfg(unix)]
#[path = "script_tun/unix.rs"]
mod platform;
#[cfg(windows)]
#[path = "script_tun/windows.rs"]
mod platform;
pub(super) use platform::{PreparedScriptTun, builder};
#[derive(Debug)]
pub(super) struct NetworkChanged;
@@ -53,7 +32,7 @@ enum Native {
pub(super) async fn run(
identity: Identity,
vpn: Arc<Vpn>,
prepared: PreparedScriptTun,
mut prepared: PreparedScriptTun,
approval: &crate::hip_source::HipApproval,
lifecycle: &LifecycleHandle,
cancellation: CancellationToken,
@@ -62,6 +41,8 @@ pub(super) async fn run(
registry: Arc<crate::session_registry::SessionRegistry>,
sessions: &mut gpapi::session::desktop::GatewaySessions,
) -> anyhow::Result<()> {
let channel = prepared.connect().await?;
let mut control = ConsumerControl::new(channel);
let attempt = identity.attempt;
let (native_tx, native) = mpsc::channel(64);
let observed = native_tx.clone();
@@ -77,7 +58,7 @@ pub(super) async fn run(
monitor: monitor.clone(),
})
.await;
if event_result.is_err() {
if event_result.is_err() || cancellation.is_cancelled() {
monitor.stop().await;
return Ok(());
}
@@ -91,31 +72,50 @@ pub(super) async fn run(
tokio::pin!(worker);
let mut worker_done = false;
let stop = cancellation.child_token();
let supervisor = supervise(identity, prepared, native, stop.clone(), events);
tokio::pin!(supervisor);
let mut supervisor_done = false;
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
let result = loop {
tokio::select! {
biased;
result = &mut supervisor => { supervisor_done = true; break result; }
result = &mut worker => { worker_done = true; break Err(anyhow::anyhow!("VPN worker ended: {:?}", result)); }
_ = approval_poll.tick() => {
if !approval.approval_is_valid() || !registry.has_session(session_id) {
super::runtime::stop_for_revoked_approval(lifecycle, &cancellation);
let result = {
let supervisor = supervise(
identity,
&mut control,
std::mem::take(&mut prepared.bootstrap),
native,
stop.clone(),
events,
);
tokio::pin!(supervisor);
let mut supervisor_done = false;
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
let result = loop {
tokio::select! {
biased;
result = &mut supervisor => { supervisor_done = true; break result; }
result = &mut worker => { worker_done = true; break Err(anyhow::anyhow!("VPN worker ended: {:?}", result)); }
_ = approval_poll.tick() => {
if !approval.approval_is_valid() || !registry.has_session(session_id) {
super::runtime::stop_for_revoked_approval(lifecycle, &cancellation);
}
}
}
};
stop.cancel();
// Keep the consumer's control and packet endpoints alive until OpenConnect
// consumes cancellation and logs out. Early EOF would interrupt that logout.
vpn.disconnect();
if !worker_done {
let _ = worker.await;
}
if !supervisor_done {
let _ = supervisor.await;
}
result
};
stop.cancel();
if !supervisor_done {
let _ = supervisor.await;
}
vpn.disconnect();
if !worker_done {
let _ = worker.await;
}
control.stop().await;
let cleanup = prepared.stop_worker();
monitor.stop().await;
if result.is_ok() {
cleanup?;
} else if let Err(error) = cleanup {
log::warn!("Could not stop packet worker: {error:#}");
}
result
}
@@ -128,93 +128,113 @@ enum WorkerState {
Suspending,
}
// The same control loop runs against native observations in production and a
// generic socket consumer in tests; VPN ownership stays in run().
// Own the channel independently of its supervision future so run() can drain
// the native VPN before telling the consumer to stop or closing its endpoints.
struct ConsumerControl {
output: tokio::io::WriteHalf<platform::ControlStream>,
messages: mpsc::Receiver<std::io::Result<Message>>,
reader: tokio::task::JoinHandle<()>,
}
impl ConsumerControl {
fn new(channel: platform::ControlStream) -> Self {
let (mut input, output) = tokio::io::split(channel);
let (messages_tx, messages) = mpsc::channel(8);
let reader = tokio::spawn(async move {
loop {
let message = receive(&mut input).await;
let failed = message.is_err();
if messages_tx.send(message).await.is_err() || failed {
break;
}
}
});
Self {
output,
messages,
reader,
}
}
async fn stop(&mut self) {
let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut self.output, &Message::Stop)).await;
self.reader.abort();
let _ = (&mut self.reader).await;
}
}
impl Drop for ConsumerControl {
fn drop(&mut self) {
self.reader.abort();
}
}
// Production and generic-consumer tests exercise this same state machine.
async fn supervise(
identity: Identity,
mut prepared: PreparedScriptTun,
control: &mut ConsumerControl,
mut bootstrap: Bootstrap,
mut native: mpsc::Receiver<Native>,
cancellation: CancellationToken,
events: mpsc::Sender<LifecycleEvent>,
) -> anyhow::Result<()> {
let attempt = identity.attempt;
prepared.control.set_nonblocking(true)?;
let control = UnixStream::from_std(prepared.control)?;
let (mut input, mut output) = control.into_split();
let (messages_tx, mut messages) = mpsc::channel(8);
let reader = tokio::spawn(async move {
loop {
let message = receive(&mut input).await;
let failed = message.is_err();
if messages_tx.send(message).await.is_err() || failed {
break;
}
}
});
let ConsumerControl { output, messages, .. } = control;
let mut network = None;
let mut session = None;
let mut worker = WorkerState::Preparing;
let mut online = false;
let mut was_connected = false;
let mut deadline: Option<Instant> = None;
let result = async {
loop {
tokio::select! {
biased;
_ = cancellation.cancelled() => break,
_ = async { if let Some(at) = deadline { tokio::time::sleep_until(at).await } else { std::future::pending().await } } => bail!("Script-tun worker activation timed out"),
message = messages.recv() => match message.context("Script-tun control reader stopped")?? {
Message::Ready if worker == WorkerState::Preparing && network.is_some() => {
worker = WorkerState::Ready;
}
Message::Activated if worker == WorkerState::Activating => {
ensure!(online, "Script-tun activation completed while VPN was offline");
ensure!(!cancellation.is_cancelled(), "Script-tun startup cancelled");
events.send(LifecycleEvent::Established { attempt, session: session.clone().context("Native session is missing")? }).await?;
worker = WorkerState::Active; was_connected = true; deadline = None;
}
Message::Suspended if worker == WorkerState::Suspending => { worker = WorkerState::Ready; deadline = None; }
Message::Error { message } => bail!("Script-tun worker: {message}"),
_ => bail!("Unexpected script-tun consumer message"),
},
event = native.recv() => match event.context("Native event stream ended")? {
Native::Established(value) => { session = Some(value); online = true; deadline.get_or_insert(Instant::now() + Duration::from_secs(10)); }
Native::Event(Event::Configuration(config)) => {
let observed = config.context("VPN configuration is absent").and_then(observed_network);
if was_connected && (observed.is_err() || network.as_ref().is_some_and(|old| observed.as_ref().is_ok_and(|new| old != new))) { return Err(NetworkChanged.into()); }
let observed = observed?;
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
else {
send(&mut output, &Message::Configure { identity, bootstrap: std::mem::take(&mut prepared.bootstrap), network: observed.clone() }).await?;
network = Some(observed);
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Native::Event(Event::Reconnecting) => {
ensure!(worker != WorkerState::Activating, "VPN connection interrupted during script-tun activation; reconnect the VPN");
online = false;
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
send(&mut output, &Message::Suspend).await?; worker = WorkerState::Suspending;
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Native::Event(Event::Reconnected) => online = true,
Native::Event(_) => {},
loop {
tokio::select! {
biased;
_ = cancellation.cancelled() => break,
_ = async { if let Some(at) = deadline { tokio::time::sleep_until(at).await } else { std::future::pending().await } } => bail!("Script-tun worker activation timed out"),
message = messages.recv() => match message.context("Script-tun control reader stopped")?? {
Message::Ready if worker == WorkerState::Preparing && network.is_some() => {
worker = WorkerState::Ready;
}
}
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
send(&mut output, &Message::Activate).await?; worker = WorkerState::Activating;
deadline = Some(Instant::now() + Duration::from_secs(10));
Message::Activated if worker == WorkerState::Activating => {
ensure!(online, "Script-tun activation completed while VPN was offline");
ensure!(!cancellation.is_cancelled(), "Script-tun startup cancelled");
events.send(LifecycleEvent::Established { attempt, session: session.clone().context("Native session is missing")? }).await?;
worker = WorkerState::Active; was_connected = true; deadline = None;
}
Message::Suspended if worker == WorkerState::Suspending => { worker = WorkerState::Ready; deadline = None; }
Message::Error { message } => bail!("Script-tun worker: {message}"),
_ => bail!("Unexpected script-tun consumer message"),
},
event = native.recv() => match event.context("Native event stream ended")? {
Native::Established(value) => { session = Some(value); online = true; deadline.get_or_insert(Instant::now() + Duration::from_secs(10)); }
Native::Event(Event::Configuration(config)) => {
let observed = config.context("VPN configuration is absent").and_then(observed_network);
if was_connected && (observed.is_err() || network.as_ref().is_some_and(|old| observed.as_ref().is_ok_and(|new| old != new))) { return Err(NetworkChanged.into()); }
let observed = observed?;
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
else {
send(output, &Message::Configure { identity, bootstrap: std::mem::take(&mut bootstrap), network: observed.clone() }).await?;
network = Some(observed);
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Native::Event(Event::Reconnecting) => {
ensure!(worker != WorkerState::Activating, "VPN connection interrupted during script-tun activation; reconnect the VPN");
online = false;
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
send(output, &Message::Suspend).await?; worker = WorkerState::Suspending;
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Native::Event(Event::Reconnected) => online = true,
Native::Event(_) => {},
}
}
Ok(())
}.await;
let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut output, &Message::Stop)).await;
drop(output);
reader.abort();
let _ = reader.await;
result
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
send(output, &Message::Activate).await?;
worker = WorkerState::Activating;
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Ok(())
}
fn observed_network(
@@ -243,5 +263,5 @@ async fn send(writer: &mut (impl tokio::io::AsyncWrite + Unpin), message: &Messa
Ok(())
}
#[cfg(test)]
#[cfg(all(test, unix))]
mod tests;
@@ -1,6 +1,8 @@
use super::*;
use gpapi::script_tun::{Bootstrap, ScriptTunRequest};
use openconnect::{VpnSessionInfo, tunnel::Configuration};
use tokio::io::AsyncWriteExt;
use tokio::net::UnixStream;
// A generic consumer, with no proxy settings or private worker protocol.
struct Consumer {
@@ -23,16 +25,26 @@ impl Consumer {
launch_id: uuid::Uuid::new_v4(),
};
let cancel = CancellationToken::new();
let task = tokio::spawn(supervise(
identity,
PreparedScriptTun {
control,
let stopped = cancel.clone();
let task = tokio::spawn(async move {
let mut prepared = PreparedScriptTun {
control: Some(control),
bootstrap: Bootstrap::new(b"consumer bootstrap").unwrap(),
},
observations,
cancel.clone(),
events,
));
};
let channel = prepared.connect().await?;
let mut control = ConsumerControl::new(channel);
let result = supervise(
identity,
&mut control,
prepared.bootstrap,
observations,
stopped,
events,
)
.await;
control.stop().await;
result
});
Self {
control: UnixStream::from_std(child).unwrap(),
native,
@@ -291,3 +303,36 @@ async fn reconnect_during_activation_returns_clear_error_without_connected() {
);
assert!(consumer.events.try_recv().is_err());
}
#[tokio::test]
async fn supervision_completion_keeps_consumer_alive_until_owner_stops_it() {
let (channel, mut peer) = UnixStream::pair().unwrap();
let mut control = ConsumerControl::new(channel);
let (_native, observations) = mpsc::channel(1);
let (events, _notifications) = mpsc::channel(1);
let cancellation = CancellationToken::new();
cancellation.cancel();
supervise(
Identity {
service_instance: uuid::Uuid::new_v4(),
attempt: 1,
launch_id: uuid::Uuid::new_v4(),
},
&mut control,
Bootstrap::default(),
observations,
cancellation,
events,
)
.await
.unwrap();
assert!(
tokio::time::timeout(Duration::from_millis(30), receive(&mut peer))
.await
.is_err()
);
control.stop().await;
assert!(matches!(receive(&mut peer).await.unwrap(), Message::Stop));
drop(control);
assert!(receive(&mut peer).await.is_err());
}
@@ -0,0 +1,44 @@
use anyhow::{Context, ensure};
use gpapi::script_tun::{Bootstrap, ScriptTunRequest};
use openconnect::{Vpn, VpnBuilder};
pub(super) type ControlStream = tokio::net::UnixStream;
pub(crate) struct PreparedScriptTun {
pub(super) control: Option<std::os::unix::net::UnixStream>,
pub bootstrap: Bootstrap,
}
pub(crate) fn builder(
server: &str,
cookie: &str,
request: &ScriptTunRequest,
uid: u32,
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
request.validate()?;
ensure!(uid != 0, "Script-tun worker requires a desktop user");
let (control, child) = std::os::unix::net::UnixStream::pair()?;
let builder = Vpn::builder(server, cookie).script_tun_program(
request.program.to_str().context("Program is not UTF-8")?,
&request.args,
uid,
child.into(),
)?;
Ok((
builder,
PreparedScriptTun {
control: Some(control),
bootstrap: request.bootstrap.clone(),
},
))
}
impl PreparedScriptTun {
pub(super) async fn connect(&mut self) -> anyhow::Result<ControlStream> {
let control = self.control.take().context("Worker control pipe is unavailable")?;
control.set_nonblocking(true)?;
Ok(tokio::net::UnixStream::from_std(control)?)
}
// The native OpenConnect Unix launcher owns/reaps its child on disconnect.
pub(super) fn stop_worker(&mut self) -> anyhow::Result<()> {
Ok(())
}
}
@@ -0,0 +1,69 @@
use anyhow::{Context, ensure};
use gpapi::{
process::user_process::UserProcess,
script_tun::{Bootstrap, ScriptTunRequest},
windows::PipeClientIdentity,
};
use openconnect::{Vpn, VpnBuilder};
use std::{os::windows::io::AsRawHandle, sync::Arc, time::Duration};
use tokio::net::windows::named_pipe::NamedPipeServer;
use windows_sys::Win32::System::Pipes::GetNamedPipeClientProcessId;
pub(super) type ControlStream = NamedPipeServer;
pub(crate) struct PreparedScriptTun {
control: Option<NamedPipeServer>,
worker: UserProcess,
pub(super) bootstrap: Bootstrap,
}
pub(crate) fn builder(
server: &str,
cookie: &str,
request: &ScriptTunRequest,
owner: Arc<PipeClientIdentity>,
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
request.validate()?;
let attempt = uuid::Uuid::new_v4();
let control_name = format!(r"\\.\pipe\GPConnect.ScriptTun.{attempt}.Control");
let packet_name = format!(r"\\.\pipe\GPConnect.ScriptTun.{attempt}.Packets");
let control = owner.create_control_pipe(&control_name)?;
let mut packets = owner.create_packet_pipe(&packet_name)?;
let worker = UserProcess::launch(
owner.primary_token(),
&request.program,
&request.args,
&[
("OPENCONNECT_SCRIPT_TUN_CONTROL_PIPE", &control_name),
("VPN_PIPE", &packet_name),
],
)
.context("Could not launch the user-session packet worker")?;
packets.connect(worker.id(), Duration::from_secs(10))?;
// PacketPipe creates only raw overlapped Win32 I/O and never registers IOCP.
let builder = unsafe { Vpn::builder(server, cookie).script_tun_pipe(packets.into_handle()) };
Ok((
builder,
PreparedScriptTun {
control: Some(control),
worker,
bootstrap: request.bootstrap.clone(),
},
))
}
impl PreparedScriptTun {
pub(super) async fn connect(&mut self) -> anyhow::Result<ControlStream> {
ensure!(!self.worker.has_exited()?, "The packet worker exited during startup");
let control = self.control.take().context("Worker control pipe is unavailable")?;
tokio::time::timeout(Duration::from_secs(10), control.connect())
.await
.context("Packet control connection timed out")??;
let mut pid = 0;
if unsafe { GetNamedPipeClientProcessId(control.as_raw_handle(), &mut pid) } == 0 {
return Err(std::io::Error::last_os_error().into());
}
ensure!(pid == self.worker.id(), "Unexpected packet control client");
Ok(control)
}
pub(super) fn stop_worker(&mut self) -> anyhow::Result<()> {
Ok(self.worker.stop()?)
}
}