feat: release GP Connect 3.3.0 with Native Shell support

This commit is contained in:
Kevin Yue committed 2026-11-05 23:05:14 +08:00
1 parent d12d677208
commit fd08cdbe66
226 files changed
+7700 -5225

No files matched your search

+10 -24
View File
@@ -33,8 +33,6 @@ pub struct SamlAuthLauncher<'a> {
certificate: Option<&'a str>,
sslkey: Option<&'a str>,
key_password: Option<&'a str>,
#[cfg(not(target_os = "macos"))]
fix_openssl: bool,
ignore_tls_errors: bool,
#[cfg(feature = "webview-auth")]
hidpi: bool,
@@ -67,8 +65,6 @@ impl<'a> SamlAuthLauncher<'a> {
certificate: None,
sslkey: None,
key_password: None,
#[cfg(not(target_os = "macos"))]
fix_openssl: false,
ignore_tls_errors: false,
#[cfg(feature = "webview-auth")]
hidpi: false,
@@ -115,12 +111,6 @@ impl<'a> SamlAuthLauncher<'a> {
self
}
#[cfg(not(target_os = "macos"))]
pub fn fix_openssl(mut self, fix_openssl: bool) -> Self {
self.fix_openssl = fix_openssl;
self
}
pub fn ignore_tls_errors(mut self, ignore_tls_errors: bool) -> Self {
self.ignore_tls_errors = ignore_tls_errors;
self
@@ -229,11 +219,6 @@ impl<'a> SamlAuthLauncher<'a> {
auth_cmd.arg("--client-version").arg(client_version);
}
#[cfg(not(target_os = "macos"))]
if self.fix_openssl {
auth_cmd.arg("--fix-openssl");
}
if self.ignore_tls_errors {
auth_cmd.arg("--ignore-tls-errors");
}
@@ -419,19 +404,16 @@ mod tests {
#[test]
fn launches_with_platform_tls_options() {
let launcher = SamlAuthLauncher::new("vpn.example.com").ignore_tls_errors(true);
#[cfg(not(target_os = "macos"))]
let launcher = launcher.fix_openssl(true);
let args = child_args(launcher);
assert_eq!(
args.iter().any(|arg| arg == "--fix-openssl"),
!cfg!(target_os = "macos")
);
assert!(!args.iter().any(|arg| arg == "--fix-openssl"));
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors"));
}
#[test]
fn os_profile_sets_os_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.build(crate::os_profile::test_snapshot());
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
@@ -440,7 +422,9 @@ mod tests {
#[test]
fn os_profile_sets_host_id_from_profile_runtime_identity() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.build(crate::os_profile::test_snapshot());
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
@@ -449,7 +433,9 @@ mod tests {
#[test]
fn os_profile_sets_client_version_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.build(crate::os_profile::test_snapshot());
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
+5 -38
View File
@@ -3,48 +3,15 @@ use std::{
os::unix::fs::{MetadataExt, PermissionsExt},
path::{Path, PathBuf},
process::{Command, Output, Stdio},
time::{Duration, Instant},
};
use super::command_runner::run_controlled;
/// Invocation control borrowed by collection; interruption must never be treated
/// as an unavailable optional product.
pub trait CollectionControl {
fn check(&self) -> io::Result<()>;
}
impl<F: Fn() -> io::Result<()>> CollectionControl for F {
fn check(&self) -> io::Result<()> {
self()
}
}
pub struct CollectionBudget {
deadline: Instant,
}
impl CollectionBudget {
pub fn new(timeout: Duration) -> Self {
Self {
deadline: Instant::now() + timeout,
}
}
}
impl CollectionControl for CollectionBudget {
fn check(&self) -> io::Result<()> {
if Instant::now() >= self.deadline {
Err(io::Error::new(
io::ErrorKind::TimedOut,
"Device information collection timed out",
))
} else {
Ok(())
}
}
}
#[cfg(test)]
use crate::collection::CollectionBudget;
use crate::collection::CollectionControl;
#[cfg(test)]
use std::time::{Duration, Instant};
const COMMAND_OUTPUT_LIMIT: usize = 256 * 1024;
const TOOL_DIRECTORIES: &[&str] = &[
"/usr/bin",
+1 -1
View File
@@ -12,7 +12,7 @@ use nix::{
unistd::Pid,
};
use super::collection::CollectionControl;
use crate::collection::CollectionControl;
/// What the child reads on stdin.
pub(crate) enum ChildInput<'a> {
+61 -22
View File
@@ -29,6 +29,18 @@ pub struct DesktopLauncher<'a> {
}
impl<'a> DesktopLauncher<'a> {
/// Bring an already-running GUI to the foreground through its service.
pub async fn activate_existing() -> anyhow::Result<()> {
let endpoint = crate::utils::endpoint::http_endpoint().await?;
crate::utils::request::client_builder()
.build()?
.post(format!("{endpoint}/active-gui"))
.send()
.await?
.error_for_status()?;
Ok(())
}
pub fn new(version: &'a str) -> Self {
Self {
version,
@@ -70,11 +82,12 @@ impl<'a> DesktopLauncher<'a> {
let mut cancelled = false;
let cancellation = CancellationToken::new();
let mut recovery = RecoveryState::default();
#[cfg(target_os = "linux")]
let switch_listener = super::gui_switch::SwitchListener::new()?;
let result = {
let operation = async {
let mut minimized = self.minimized;
let mut expecting_renewal = false;
let mut program = None;
loop {
let credential = tokio::select! {
biased;
@@ -95,37 +108,61 @@ impl<'a> DesktopLauncher<'a> {
"Service product version mismatch"
);
let mut envs: HashMap<String, String> = std::env::vars().collect();
#[cfg(target_os = "linux")]
envs.insert(
super::gui_switch::SOCKET_ENV.into(),
switch_listener.path().to_string_lossy().into_owned(),
);
if recovery.dmabuf_disabled() {
envs.insert("WEBKIT_DISABLE_DMABUF_RENDERER".into(), "1".into());
}
if let Some(path) = &self.log_file {
envs.insert("GP_LOG_FILE".into(), path.clone());
}
let launcher = GuiLauncher::new(self.version, Arc::new(credential))
let launcher = GuiLauncher::new(self.version, Arc::new(credential), crate::gui::preferred()?)
.envs(envs)
.minimized(minimized);
#[cfg(not(target_os = "linux"))]
let mut unexpected = [0];
// Program resolution may launch the WebKit download helper. Keep it under
// the same cancellation, service ownership and recovery budget as gpgui.
let attempt = async {
if program.is_none() {
program = Some(launcher.resolve_program(&cancellation).await?);
}
launcher.launch_program(program.as_ref().unwrap(), &cancellation).await
};
tokio::pin!(attempt);
let outcome = tokio::select! {
biased;
_ = cancellation.cancelled() => { let _ = attempt.await; return Ok(()); }
result = &mut attempt => result,
status = service.wait() => {
cancellation.cancel(); let _ = attempt.await;
anyhow::bail!("The privileged service exited while the GUI was running: {}", status?);
}
result = output.read(&mut unexpected) => {
cancellation.cancel(); let _ = attempt.await;
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
anyhow::bail!("The privileged service closed its credential channel");
let outcome = {
let attempt = async {
let program = launcher
.resolve_program(&cancellation, crate::gui::GuiTheme::System)
.await?;
#[cfg(target_os = "linux")]
return launcher
.launch_with_switches(
&program,
&cancellation,
&switch_listener.listener,
&mut input,
&mut output,
)
.await;
#[cfg(not(target_os = "linux"))]
launcher.launch_program(&program, &cancellation).await
};
tokio::pin!(attempt);
tokio::select! {
biased;
_ = cancellation.cancelled() => { let _ = attempt.await; return Ok(()); }
result = &mut attempt => result,
status = service.wait() => {
cancellation.cancel(); let _ = attempt.await;
anyhow::bail!("The privileged service exited while the GUI was running: {}", status?);
}
result = async {
#[cfg(not(target_os = "linux"))]
return output.read(&mut unexpected).await;
#[cfg(target_os = "linux")]
std::future::pending::<std::io::Result<usize>>().await
} => {
cancellation.cancel(); let _ = attempt.await;
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
anyhow::bail!("The privileged service closed its credential channel");
}
}
};
if cancellation.is_cancelled() {
@@ -184,7 +221,9 @@ fn create_log_file(path: &Path) -> std::io::Result<File> {
OpenOptions::new().append(true).open(path)
}
async fn read_credential(reader: &mut (impl AsyncRead + Unpin)) -> anyhow::Result<Option<SessionCredential>> {
pub(super) async fn read_credential(
reader: &mut (impl AsyncRead + Unpin),
) -> anyhow::Result<Option<SessionCredential>> {
let mut header = [0; 2];
if reader.read(&mut header[..1]).await? == 0 {
return Ok(None);
@@ -12,6 +12,8 @@ pub struct GuiHelperLauncher<'a> {
envs: Option<&'a HashMap<String, String>>,
credential: &'a SessionCredential,
gui_version: Option<&'a str>,
variant: crate::gui::GuiVariant,
theme: crate::gui::GuiTheme,
}
impl<'a> GuiHelperLauncher<'a> {
@@ -21,6 +23,8 @@ impl<'a> GuiHelperLauncher<'a> {
envs: None,
credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
}
}
@@ -34,6 +38,16 @@ impl<'a> GuiHelperLauncher<'a> {
self
}
pub fn variant(mut self, variant: crate::gui::GuiVariant) -> Self {
self.variant = variant;
self
}
pub fn theme(mut self, theme: crate::gui::GuiTheme) -> Self {
self.theme = theme;
self
}
pub async fn launch(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
let mut cmd = Command::new(&self.program);
@@ -43,10 +57,16 @@ impl<'a> GuiHelperLauncher<'a> {
}
cmd.arg("--service-credential-on-stdin");
if self.variant == crate::gui::GuiVariant::Nsh {
cmd.arg("--gui-variant").arg("nsh");
}
if let Some(gui_version) = self.gui_version {
cmd.arg("--gui-version").arg(gui_version);
}
if self.theme != crate::gui::GuiTheme::System {
cmd.arg("--theme").arg(self.theme.as_str());
}
info!("Launching gpgui-helper");
anyhow::ensure!(
@@ -83,6 +103,40 @@ mod tests {
path
}
#[tokio::test]
async fn forwards_explicit_themes_and_leaves_initial_downloads_on_system() {
use crate::gui::{GuiTheme, GuiVariant};
let dir = tempfile::TempDir::new().unwrap();
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
let captured = dir.path().join("arguments");
for variant in [GuiVariant::Tauri, GuiVariant::Nsh] {
for theme in [GuiTheme::System, GuiTheme::Light, GuiTheme::Dark] {
let mut launcher = GuiHelperLauncher::new(&credential)
.variant(variant)
.gui_version(Some("test"))
.theme(theme);
launcher.program = fixture(
&dir,
&credential,
&format!("printf '%s\\n' \"$@\" > '{}'", captured.display()),
);
launcher.launch(&CancellationToken::new()).await.unwrap();
let mut expected = vec!["--service-credential-on-stdin"];
if variant == GuiVariant::Nsh {
expected.extend(["--gui-variant", "nsh"]);
}
expected.extend(["--gui-version", "test"]);
if theme != GuiTheme::System {
expected.extend(["--theme", theme.as_str()]);
}
assert_eq!(
std::fs::read_to_string(&captured).unwrap().lines().collect::<Vec<_>>(),
expected
);
}
}
}
#[tokio::test]
async fn propagates_helper_failure_and_preserves_stderr_in_desktop_log() {
let dir = tempfile::TempDir::new().unwrap();
@@ -96,6 +150,8 @@ mod tests {
envs: Some(&envs),
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
};
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
assert!(error.to_string().contains("gpgui-helper exited with"), "{error:#}");
@@ -122,6 +178,8 @@ mod tests {
envs: Some(&envs),
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
};
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
let eligible =
@@ -143,6 +201,8 @@ mod tests {
envs: Some(&envs),
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
};
let cancellation = CancellationToken::new();
let attempt = launcher.launch(&cancellation);
+518 -22
View File
@@ -6,7 +6,6 @@ use std::{
};
use anyhow::bail;
use common::binary_paths;
use log::info;
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
@@ -15,6 +14,7 @@ use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport:
pub struct GuiLauncher<'a> {
version: &'a str,
variant: crate::gui::GuiVariant,
programs: Vec<PathBuf>,
credential: Arc<SessionCredential>,
minimized: bool,
@@ -22,9 +22,9 @@ pub struct GuiLauncher<'a> {
}
impl<'a> GuiLauncher<'a> {
pub fn new(version: &'a str, credential: Arc<SessionCredential>) -> Self {
let primary = binary_paths::gpgui();
let update_target = binary_paths::gpgui_update_target();
pub fn new(version: &'a str, credential: Arc<SessionCredential>, variant: crate::gui::GuiVariant) -> Self {
let primary = variant.primary();
let update_target = variant.update_target();
let programs = if primary == update_target {
vec![primary]
} else {
@@ -33,6 +33,7 @@ impl<'a> GuiLauncher<'a> {
Self {
version,
variant,
programs,
credential,
minimized: false,
@@ -50,20 +51,20 @@ impl<'a> GuiLauncher<'a> {
self
}
pub(crate) async fn resolve_program(&self, cancellation: &CancellationToken) -> anyhow::Result<PathBuf> {
pub(crate) async fn resolve_program(
&self,
cancellation: &CancellationToken,
helper_theme: crate::gui::GuiTheme,
) -> anyhow::Result<PathBuf> {
anyhow::ensure!(
uzers::get_effective_uid() != 0,
"The desktop GUI must not be launched by root"
);
if let Some(program) = tokio::select! {
biased;
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
result = self.find_compatible_program() => result,
} {
if let Some(program) = self.find_compatible_program(cancellation).await? {
return Ok(program);
}
self.download_program(cancellation).await?;
let program = binary_paths::gpgui_update_target();
self.download_program(cancellation, helper_theme).await?;
let program = self.variant.update_target();
tokio::select! {
biased;
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
@@ -72,10 +73,15 @@ impl<'a> GuiLauncher<'a> {
Ok(program)
}
async fn find_compatible_program(&self) -> Option<PathBuf> {
async fn find_compatible_program(&self, cancellation: &CancellationToken) -> anyhow::Result<Option<PathBuf>> {
for program in &self.programs {
match self.check_version(program).await {
Ok(()) => return Some(program.clone()),
let result = tokio::select! {
biased;
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
result = self.check_version(program) => result,
};
match result {
Ok(()) => return Ok(Some(program.clone())),
Err(err) => info!(
"GUI candidate {} is unavailable or incompatible: {err}",
program.display()
@@ -83,7 +89,7 @@ impl<'a> GuiLauncher<'a> {
}
}
None
Ok(None)
}
pub(crate) async fn launch_program(
@@ -99,7 +105,7 @@ impl<'a> GuiLauncher<'a> {
if self.minimized {
cmd.arg("--minimized");
}
info!("Launching gpgui");
info!("Launching {}", program.display());
super::desktop_child::launch_desktop_child(
"gpgui",
cmd.into_std(),
@@ -137,15 +143,172 @@ impl<'a> GuiLauncher<'a> {
Ok(())
}
async fn download_program(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
async fn download_program(
&self,
cancellation: &CancellationToken,
theme: crate::gui::GuiTheme,
) -> anyhow::Result<()> {
let gui_helper = GuiHelperLauncher::new(&self.credential);
gui_helper
.envs(self.envs.as_ref())
.gui_version(Some(self.version))
.variant(self.variant)
.theme(theme)
.launch(cancellation)
.await
}
#[cfg(target_os = "linux")]
pub(crate) async fn launch_with_switches(
&self,
program: &Path,
cancellation: &CancellationToken,
listener: &tokio::net::UnixListener,
service_input: &mut (impl tokio::io::AsyncWrite + Unpin),
service_output: &mut (impl tokio::io::AsyncRead + Unpin),
) -> anyhow::Result<ExitStatus> {
use super::gui_switch;
use crate::gui::GuiSwitchOutcome;
use crate::service::transport::{DESKTOP_SWITCH_BEGIN, DESKTOP_SWITCH_CANCEL, DESKTOP_SWITCH_COMMIT};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let mut current = Some(self.start_owned(program.to_owned(), cancellation.child_token()));
let mut retired = Vec::new();
let mut unexpected = [0];
let result = async { loop {
tokio::select! {
biased;
outcome = &mut current.as_mut().unwrap().task => {
current.take();
break outcome?;
}
accepted = listener.accept() => {
let (mut socket, _) = accepted?;
let mut pending = false;
let replacement = async {
let command = gui_switch::receive(&mut socket).await?;
let selection = command.selection;
let variant = selection.variant;
let candidate = Self::new(self.version, self.credential.clone(), variant).envs(self.envs.clone());
let program = candidate.find_compatible_program(cancellation).await?;
if program.is_none() && variant == crate::gui::GuiVariant::Nsh {
use crate::service::transport::DESKTOP_GUI_INSTALLER;
service_input.write_all(&[DESKTOP_GUI_INSTALLER]).await?;
let supplies_runtime = match service_output.read_u8().await? {
0 => false,
1 => true,
_ => anyhow::bail!("Invalid GUI installer capability response"),
};
if !supplies_runtime {
super::nsh_runtime::check()?;
}
}
if program.is_none() && !selection.allow_download {
gui_switch::reply(&mut socket, Ok(GuiSwitchOutcome::DownloadRequired)).await?;
return Ok(None);
}
service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?;
pending = true;
let credential = super::desktop_launcher::read_credential(service_output).await?
.ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?;
anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch");
let ready = gui_switch::SwitchListener::new()?;
let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect());
envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned());
let launcher = Self::new(self.version, Arc::new(credential), variant)
.envs(envs)
.minimized(false);
let program = match program {
Some(program) => program,
None => launcher.resolve_program(cancellation, command.theme).await?,
};
let mut child = launcher.start_owned(program, cancellation.child_token());
let start_result = tokio::select! {
result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => {
result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result)
},
outcome = &mut child.task => {
return match outcome? {
Ok(status) => Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")),
Err(error) => Err(error),
};
}
};
if let Err(error) = start_result.and_then(|()| crate::gui::save_preference(variant)) {
child.cancel.cancel();
let _ = child.task.await;
return Err(error);
}
if let Err(error) = gui_switch::reply(&mut socket, Ok(GuiSwitchOutcome::Switched)).await {
child.cancel.cancel();
let _ = child.task.await;
return Err(error);
}
if let Err(error) = service_input.write_all(&[DESKTOP_SWITCH_COMMIT]).await {
child.cancel.cancel();
let _ = child.task.await;
return Err(error.into());
}
pending = false;
Ok(Some(child))
}.await;
match replacement {
Ok(Some(child)) => retired.push(current.replace(child).unwrap()),
Ok(None) => {},
Err(error) => {
if pending {
service_input.write_all(&[DESKTOP_SWITCH_CANCEL]).await?;
}
let _ = gui_switch::reply(&mut socket, Err(format!("{error:#}"))).await;
}
}
}
result = service_output.read(&mut unexpected) => {
break match result {
Ok(0) => Err(anyhow::anyhow!("The privileged service closed its credential channel")),
Ok(_) => Err(anyhow::anyhow!("Unexpected service credential data while the GUI is running")),
Err(error) => Err(error.into()),
};
}
}
}}.await;
// Every GUI remains owned by this supervisor until it is reaped. The retiring
// GUI exits after the successful switch reply; cancellation also joins it.
if let Some(child) = current {
retired.push(child);
}
for child in &retired {
child.cancel.cancel();
}
for child in retired {
let _ = child.task.await;
}
result
}
#[cfg(target_os = "linux")]
fn start_owned(&self, program: PathBuf, cancel: CancellationToken) -> RunningGui {
let version = self.version.to_owned();
let variant = self.variant;
let credential = self.credential.clone();
let envs = self.envs.clone();
let minimized = self.minimized;
let task_cancel = cancel.clone();
let task = tokio::spawn(async move {
GuiLauncher::new(&version, credential, variant)
.envs(envs)
.minimized(minimized)
.launch_program(&program, &task_cancel)
.await
});
RunningGui { task, cancel }
}
}
#[cfg(target_os = "linux")]
struct RunningGui {
task: tokio::task::JoinHandle<anyhow::Result<ExitStatus>>,
cancel: CancellationToken,
}
#[cfg(test)]
@@ -174,6 +337,7 @@ mod tests {
fn launcher(version: &'static str, programs: Vec<PathBuf>) -> GuiLauncher<'static> {
GuiLauncher {
version,
variant: crate::gui::GuiVariant::Tauri,
programs,
credential: Arc::new(SessionCredential::generate(Uuid::new_v4(), version).unwrap()),
minimized: false,
@@ -247,7 +411,7 @@ mod tests {
}
let launcher = launcher(VERSION, vec![first, second]);
let cancellation = CancellationToken::new();
let attempt = launcher.resolve_program(&cancellation);
let attempt = launcher.resolve_program(&cancellation, crate::gui::GuiTheme::System);
tokio::pin!(attempt);
tokio::select! {
result = &mut attempt => panic!("version probe exited early: {result:?}"),
@@ -277,7 +441,13 @@ mod tests {
let downloaded = executable(&dir, "downloaded", "gpgui test-version", 0);
let launcher = launcher(VERSION, vec![packaged.clone(), downloaded]);
assert_eq!(launcher.find_compatible_program().await, Some(packaged));
assert_eq!(
launcher
.find_compatible_program(&CancellationToken::new())
.await
.unwrap(),
Some(packaged)
);
}
#[tokio::test]
@@ -287,7 +457,13 @@ mod tests {
let downloaded = executable(&dir, "downloaded", "gpgui test-version", 0);
let launcher = launcher(VERSION, vec![packaged, downloaded.clone()]);
assert_eq!(launcher.find_compatible_program().await, Some(downloaded));
assert_eq!(
launcher
.find_compatible_program(&CancellationToken::new())
.await
.unwrap(),
Some(downloaded)
);
}
#[tokio::test]
@@ -296,6 +472,326 @@ mod tests {
let program = executable(&dir, "broken", "gpgui test-version", 1);
let launcher = launcher(VERSION, vec![program]);
assert_eq!(launcher.find_compatible_program().await, None);
assert_eq!(
launcher
.find_compatible_program(&CancellationToken::new())
.await
.unwrap(),
None
);
}
#[tokio::test]
async fn nsh_version_mismatch_cannot_select_a_compatible_tauri_binary() {
let dir = TempDir::new().unwrap();
let _tauri = executable(&dir, "gpgui", "gpgui test-version", 0);
let nsh = executable(&dir, "gpgui-nsh", "gpgui-nsh old-version", 0);
let mut selected = launcher(VERSION, vec![nsh.clone()]);
selected.variant = crate::gui::GuiVariant::Nsh;
assert!(
selected
.find_compatible_program(&CancellationToken::new())
.await
.unwrap()
.is_none()
);
executable(&dir, "gpgui-nsh", "gpgui-nsh test-version", 0);
assert_eq!(
selected
.find_compatible_program(&CancellationToken::new())
.await
.unwrap(),
Some(nsh)
);
}
#[test]
#[cfg(target_os = "linux")]
fn supervisor_switch_success_and_failure_preserve_child_ownership() {
for scenario in [
"success",
"failure",
"missing",
"incompatible",
"runtime-too-old",
"runtime-too-old-confirmed",
] {
let directory = TempDir::new().unwrap();
let executable = std::env::current_exe().unwrap();
// An old host GTK must block generic downloads, but not package-managed downloads.
let gtk = super::super::nsh_runtime::tests::gtk_fixture(directory.path(), 12);
fs::rename(gtk, directory.path().join("libgtk-4.so.1")).unwrap();
for name in ["gpgui", "gpgui-nsh"] {
if (scenario == "missing" || scenario.starts_with("runtime-too-old")) && name == "gpgui-nsh" {
continue;
}
let version = if scenario == "incompatible" && name == "gpgui-nsh" {
"old-version"
} else {
VERSION
};
let path = directory.path().join(name);
fs::write(&path, format!(
"#!/bin/sh\nif [ \"$1\" = --version ]; then echo '{name} {version}'; exit 0; fi\nGP_SWITCH_GUI_VARIANT={name} exec '{}' --exact process::gui_launcher::tests::gui_process_fixture --ignored --nocapture\n",
executable.display()
)).unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
}
let output = std::process::Command::new(&executable)
.args([
"--exact",
"process::gui_launcher::tests::supervisor_fixture",
"--ignored",
"--nocapture",
])
.env("GP_SWITCH_SCENARIO", scenario)
.env("GP_SWITCH_DIRECTORY", directory.path())
.env("GP_GUI_BINARY", directory.path().join("gpgui"))
.env("LD_LIBRARY_PATH", directory.path())
.env("XDG_CONFIG_HOME", directory.path().join("config"))
.output()
.unwrap();
assert!(
output.status.success(),
"{scenario}: {} {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
}
#[test]
#[cfg(target_os = "linux")]
fn selected_nsh_upgrade_downloads_nsh_without_probing_tauri() {
let directory = TempDir::new().unwrap();
let test_executable = std::env::current_exe().unwrap();
let tauri_marker = directory.path().join("tauri-probed");
let tauri = executable(&directory, "gpgui", "gpgui test-version", 0);
fs::write(
&tauri,
format!(
"#!/bin/sh\ntouch '{}'; echo 'gpgui {VERSION}'\n",
tauri_marker.display()
),
)
.unwrap();
executable(&directory, "gpgui-nsh", "gpgui-nsh old-version", 0);
let helper = directory.path().join("gpgui-helper");
fs::write(&helper, format!(
"#!/bin/sh\n[ \"$2\" = --gui-variant ] && [ \"$3\" = nsh ] || exit 21\nexec '{}' --exact process::gui_launcher::tests::upgrade_helper_fixture --ignored --nocapture\n",
test_executable.display()
)).unwrap();
fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap();
let result = std::process::Command::new(test_executable)
.args([
"--exact",
"process::gui_launcher::tests::upgrade_fixture",
"--ignored",
"--nocapture",
])
.env("GP_SWITCH_DIRECTORY", directory.path())
.env("GP_GUI_BINARY", &tauri)
.env("GP_GUI_HELPER_BINARY", helper)
.env("XDG_CONFIG_HOME", directory.path().join("config"))
.output()
.unwrap();
assert!(
result.status.success(),
"{} {}",
String::from_utf8_lossy(&result.stdout),
String::from_utf8_lossy(&result.stderr)
);
assert!(!tauri_marker.exists());
assert!(directory.path().join("nsh-updated").exists());
}
#[tokio::test]
#[ignore = "subprocess upgrade resolver fixture"]
#[cfg(target_os = "linux")]
async fn upgrade_fixture() {
crate::gui::save_preference(crate::gui::GuiVariant::Nsh).unwrap();
let credential = Arc::new(SessionCredential::generate(Uuid::new_v4(), VERSION).unwrap());
let selected = GuiLauncher::new(VERSION, credential, crate::gui::preferred().unwrap());
let program = selected
.resolve_program(&CancellationToken::new(), crate::gui::GuiTheme::System)
.await
.unwrap();
assert_eq!(program.file_name().unwrap(), "gpgui-nsh");
}
#[test]
#[ignore = "subprocess download helper fixture"]
#[cfg(target_os = "linux")]
fn upgrade_helper_fixture() {
use std::io::Read;
let mut input = std::io::stdin().lock();
let mut header = [0; 2];
input.read_exact(&mut header).unwrap();
let mut frame = zeroize::Zeroizing::new(vec![0; usize::from(u16::from_be_bytes(header))]);
input.read_exact(&mut frame).unwrap();
let directory = PathBuf::from(std::env::var_os("GP_SWITCH_DIRECTORY").unwrap());
fs::write(
directory.join("gpgui-nsh"),
format!("#!/bin/sh\necho 'gpgui-nsh {VERSION}'\n"),
)
.unwrap();
fs::write(directory.join("nsh-updated"), "").unwrap();
}
#[test]
#[ignore = "subprocess GUI fixture"]
#[cfg(target_os = "linux")]
fn gui_process_fixture() {
use std::io::Read;
let mut input = std::io::stdin().lock();
let mut header = [0; 2];
input.read_exact(&mut header).unwrap();
let mut frame = zeroize::Zeroizing::new(vec![0; usize::from(u16::from_be_bytes(header))]);
input.read_exact(&mut frame).unwrap();
let directory = PathBuf::from(std::env::var_os("GP_SWITCH_DIRECTORY").unwrap());
let variant = std::env::var("GP_SWITCH_GUI_VARIANT").unwrap();
if variant == "gpgui-nsh" && std::env::var("GP_SWITCH_SCENARIO").unwrap() == "failure" {
panic!("fixture: native host failed to initialize");
}
super::super::gui_switch::notify_ready().unwrap();
fs::write(directory.join(format!("{variant}-started")), "").unwrap();
while !directory.join(format!("stop-{variant}")).exists() {
std::thread::sleep(std::time::Duration::from_millis(10));
}
fs::write(directory.join(format!("{variant}-exited")), "").unwrap();
}
#[tokio::test]
#[ignore = "subprocess supervisor fixture with isolated GUI paths and preferences"]
#[cfg(target_os = "linux")]
async fn supervisor_fixture() {
use crate::service::transport::{
DESKTOP_GUI_INSTALLER, DESKTOP_SWITCH_BEGIN, DESKTOP_SWITCH_CANCEL, DESKTOP_SWITCH_COMMIT,
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let directory = PathBuf::from(std::env::var_os("GP_SWITCH_DIRECTORY").unwrap());
let scenario = std::env::var("GP_SWITCH_SCENARIO").unwrap();
let success = scenario == "success";
let download_required = matches!(scenario.as_str(), "missing" | "incompatible");
let runtime_too_old = scenario.starts_with("runtime-too-old");
let listener = super::super::gui_switch::SwitchListener::new().unwrap();
let (mut service_input, mut control) = tokio::io::duplex(64);
let (mut service_output, mut credentials) = tokio::io::duplex(2048);
let service_marker = directory.join("service-switch-started");
let service = tokio::spawn(async move {
loop {
let message = control.read_u8().await.unwrap();
match message {
DESKTOP_GUI_INSTALLER => {
credentials.write_all(&[u8::from(!runtime_too_old)]).await.unwrap();
}
DESKTOP_SWITCH_BEGIN => {
fs::write(&service_marker, "").unwrap();
let credential = SessionCredential::generate(Uuid::new_v4(), VERSION).unwrap();
credentials
.write_all(&credential.encode_frame().unwrap())
.await
.unwrap();
}
DESKTOP_SWITCH_COMMIT | DESKTOP_SWITCH_CANCEL => {}
_ => panic!("unexpected fixture desktop control"),
}
}
});
let envs = std::env::vars().collect::<HashMap<_, _>>();
let launcher = launcher(VERSION, vec![]).envs(envs);
let cancel = CancellationToken::new();
let program = directory.join("gpgui");
let run = launcher.launch_with_switches(
&program,
&cancel,
&listener.listener,
&mut service_input,
&mut service_output,
);
tokio::pin!(run);
let checkpoint = async {
while !directory.join("gpgui-started").exists() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
let result = super::super::gui_switch::request_at(
&listener.path(),
crate::gui::GuiSwitchRequest {
variant: crate::gui::GuiVariant::Nsh,
allow_download: scenario == "runtime-too-old-confirmed",
},
crate::gui::GuiTheme::System,
)
.await;
if runtime_too_old {
let error = result.unwrap_err().to_string();
anyhow::ensure!(
error.contains("4.14") && error.contains("4.12.1"),
"Unexpected runtime error: {error}"
);
} else if download_required {
anyhow::ensure!(
result? == crate::gui::GuiSwitchOutcome::DownloadRequired,
"Missing download confirmation"
);
} else {
anyhow::ensure!(result.is_ok() == success, "Unexpected switch result: {result:?}");
if success {
anyhow::ensure!(
result? == crate::gui::GuiSwitchOutcome::Switched,
"Compatible GUI did not switch directly"
);
}
}
if download_required || runtime_too_old {
anyhow::ensure!(
!directory.join("service-switch-started").exists(),
"Download check changed the service session"
);
anyhow::ensure!(
!directory.join("gpgui-nsh-started").exists(),
"Download check launched the replacement"
);
}
anyhow::ensure!(
!directory.join("gpgui-exited").exists(),
"Current GUI exited before acknowledgement"
);
if success {
anyhow::ensure!(
crate::gui::preferred()? == crate::gui::GuiVariant::Nsh,
"Successful switch did not save preference"
);
fs::write(directory.join("stop-gpgui"), "")?;
while !directory.join("gpgui-exited").exists() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
} else {
anyhow::ensure!(
crate::gui::preferred()? == crate::gui::GuiVariant::Tauri,
"Failed switch changed preference"
);
}
Ok::<_, anyhow::Error>(())
};
let checkpoint_result = tokio::select! {
result = &mut run => panic!("supervisor exited before the owned GUI: {result:?}"),
result = tokio::time::timeout(std::time::Duration::from_secs(10), checkpoint) => result.map_err(anyhow::Error::from).and_then(|result| result),
};
if let Err(error) = checkpoint_result {
cancel.cancel();
let _ = run.await;
panic!("{error:#}");
}
let stop = if success { "stop-gpgui-nsh" } else { "stop-gpgui" };
fs::write(directory.join(stop), "").unwrap();
assert!(
tokio::time::timeout(std::time::Duration::from_secs(5), run)
.await
.unwrap()
.unwrap()
.success()
);
service.abort();
}
}
+139
View File
@@ -0,0 +1,139 @@
//! Linux GUI switching through the user-owned desktop supervisor.
use anyhow::Context;
use std::os::unix::fs::PermissionsExt;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{UnixListener, UnixStream},
};
use crate::gui::{GuiSwitchOutcome, GuiSwitchRequest, GuiTheme};
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) struct SwitchCommand {
#[serde(flatten)]
pub selection: GuiSwitchRequest,
#[serde(default)]
pub theme: GuiTheme,
}
pub(crate) const SOCKET_ENV: &str = "GP_DESKTOP_CONTROL_SOCKET";
pub(crate) const READY_ENV: &str = "GP_DESKTOP_READY_SOCKET";
/// Called after the replacement has initialized its native host.
pub fn notify_ready() -> anyhow::Result<()> {
use std::io::Write;
let Some(path) = std::env::var_os(READY_ENV) else {
return Ok(());
};
let mut socket = std::os::unix::net::UnixStream::connect(path).context("Could not notify the desktop supervisor")?;
socket.write_all(&[1])?;
Ok(())
}
pub async fn request(selection: GuiSwitchRequest, theme: GuiTheme) -> anyhow::Result<GuiSwitchOutcome> {
let path = std::env::var_os(SOCKET_ENV).context("GUI switching requires a desktop supervisor")?;
request_at(std::path::Path::new(&path), selection, theme).await
}
pub(super) async fn request_at(
path: &std::path::Path,
selection: GuiSwitchRequest,
theme: GuiTheme,
) -> anyhow::Result<GuiSwitchOutcome> {
let mut socket = UnixStream::connect(path)
.await
.context("Could not contact the desktop supervisor")?;
socket
.write_all(&serde_json::to_vec(&SwitchCommand { selection, theme })?)
.await?;
socket.shutdown().await?;
let mut reply = Vec::new();
socket.take(4096).read_to_end(&mut reply).await?;
let result: Result<GuiSwitchOutcome, String> =
serde_json::from_slice(&reply).context("Invalid desktop supervisor response")?;
result.map_err(anyhow::Error::msg)
}
pub(crate) struct SwitchListener {
pub listener: UnixListener,
directory: tempfile::TempDir,
}
impl SwitchListener {
pub fn new() -> anyhow::Result<Self> {
let directory = tempfile::Builder::new().prefix("gp-desktop-").tempdir()?;
let path = directory.path().join("control");
let listener = UnixListener::bind(&path)?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
Ok(Self { listener, directory })
}
pub fn path(&self) -> std::path::PathBuf {
self.directory.path().join("control")
}
#[cfg(target_os = "linux")]
pub async fn ready(&self) -> anyhow::Result<()> {
let (mut socket, _) = self.listener.accept().await?;
anyhow::ensure!(
socket.peer_cred()?.uid() == uzers::get_effective_uid(),
"Desktop supervisor user mismatch"
);
let mut byte = [0];
socket.read_exact(&mut byte).await?;
anyhow::ensure!(byte == [1], "Invalid GUI startup notification");
Ok(())
}
}
pub(crate) async fn receive(socket: &mut UnixStream) -> anyhow::Result<SwitchCommand> {
anyhow::ensure!(
socket.peer_cred()?.uid() == uzers::get_effective_uid(),
"Desktop supervisor user mismatch"
);
let mut request = Vec::new();
tokio::time::timeout(
std::time::Duration::from_secs(5),
socket.take(128).read_to_end(&mut request),
)
.await??;
serde_json::from_slice(&request).context("Invalid GUI selection")
}
pub(crate) async fn reply(socket: &mut UnixStream, result: Result<GuiSwitchOutcome, String>) -> anyhow::Result<()> {
socket.write_all(&serde_json::to_vec(&result)?).await?;
socket.shutdown().await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn private_switch_socket_preserves_selection_and_reports_failure() {
let selection = GuiSwitchRequest {
variant: crate::gui::GuiVariant::Nsh,
allow_download: false,
};
let control = SwitchListener::new().unwrap();
let path = control.path();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let client = tokio::spawn(async move { request_at(&path, selection, GuiTheme::Dark).await });
let (mut socket, _) = control.listener.accept().await.unwrap();
assert_eq!(
receive(&mut socket).await.unwrap(),
SwitchCommand {
selection,
theme: GuiTheme::Dark
}
);
reply(&mut socket, Err("Selected GUI could not start".into()))
.await
.unwrap();
assert_eq!(
client.await.unwrap().unwrap_err().to_string(),
"Selected GUI could not start"
);
}
}
+4
View File
@@ -9,6 +9,10 @@ pub use command_traits::CommandExt;
pub mod auth_launcher;
pub mod desktop_launcher;
pub mod gui_launcher;
#[cfg(any(target_os = "linux", test))]
pub mod gui_switch;
#[cfg(any(target_os = "linux", test))]
mod nsh_runtime;
pub mod users;
pub mod collection;
+105
View File
@@ -0,0 +1,105 @@
//! Checks the generic Linux NSH runtime before offering a download.
//! Runs in the desktop supervisor, which does not load either GUI's GTK runtime.
use std::{ffi::OsStr, os::raw::c_uint};
use anyhow::{Context, ensure};
use libloading::{
Library,
os::unix::{RTLD_LOCAL, RTLD_NOW},
};
// Match nsh-platform-linux's gtk4/v4_14 feature when changing the NSH build.
const MIN_GTK_MINOR: u32 = 14;
#[cfg(target_os = "linux")]
pub(super) fn check() -> anyhow::Result<()> {
check_gtk(OsStr::new("libgtk-4.so.1"))?;
load_library(OsStr::new("libgnutls.so.30"), "GnuTLS 3")?;
load_library(OsStr::new("libdbus-1.so.3"), "D-Bus")?;
Ok(())
}
fn load_library(path: &OsStr, name: &str) -> anyhow::Result<Library> {
// Resolve symbols now as well as transitive dependencies, without initializing GTK.
let library = unsafe { libloading::os::unix::Library::open(Some(path), RTLD_LOCAL | RTLD_NOW) };
library.map(Into::into).map_err(|error| {
log::warn!("Native Shell runtime check failed for {name}: {error}");
anyhow::anyhow!("Native Shell could not load {name}. Install its runtime libraries and try again.")
})
}
fn check_gtk(path: &OsStr) -> anyhow::Result<()> {
let library = load_library(path, "GTK 4.14 or later")?;
type Version = unsafe extern "C" fn() -> c_uint;
// These public GTK getters take no arguments and do not initialize a display.
let (major, minor, micro) = unsafe {
let major = library.get::<Version>(b"gtk_get_major_version\0");
let minor = library.get::<Version>(b"gtk_get_minor_version\0");
let micro = library.get::<Version>(b"gtk_get_micro_version\0");
let message = "Native Shell requires GTK 4.14 or later. Update GTK 4 and try again.";
(
major.context(message)?(),
minor.context(message)?(),
micro.context(message)?(),
)
};
ensure!(
major == 4 && minor >= MIN_GTK_MINOR,
"Native Shell requires GTK 4.14 or later. This system has GTK {major}.{minor}.{micro}."
);
Ok(())
}
#[cfg(test)]
pub(super) mod tests {
use super::*;
use std::{fs, process::Command};
pub(in crate::process) fn gtk_fixture(directory: &std::path::Path, minor: u32) -> std::path::PathBuf {
let source = directory.join(format!("gtk-{minor}.c"));
let library = directory.join(format!("gtk-{minor}.so"));
fs::write(
&source,
format!(
"unsigned gtk_get_major_version(void) {{ return 4; }}\n\
unsigned gtk_get_minor_version(void) {{ return {minor}; }}\n\
unsigned gtk_get_micro_version(void) {{ return 1; }}\n"
),
)
.unwrap();
assert!(
Command::new("cc")
.args(["-shared", "-fPIC"])
.arg(source)
.arg("-o")
.arg(&library)
.status()
.unwrap()
.success()
);
library
}
#[test]
fn loads_runtime_version_without_development_metadata_or_a_display() {
let directory = tempfile::tempdir().unwrap();
let old = gtk_fixture(directory.path(), 12);
let supported = gtk_fixture(directory.path(), 14);
let newer = gtk_fixture(directory.path(), 20);
let error = check_gtk(old.as_os_str()).unwrap_err().to_string();
assert!(error.contains("4.14"), "{error}");
assert!(error.contains("4.12.1"), "{error}");
check_gtk(supported.as_os_str()).unwrap();
check_gtk(newer.as_os_str()).unwrap();
}
#[test]
fn missing_runtime_reports_an_actionable_error() {
let directory = tempfile::tempdir().unwrap();
let error = check_gtk(directory.path().join("missing.so").as_os_str())
.unwrap_err()
.to_string();
assert!(error.contains("GTK 4.14 or later"), "{error}");
assert!(error.contains("Install"), "{error}");
}
}