fix(desktop): keep GUI in the user authorization session

This commit is contained in:
Kevin Yue committed 2026-10-07 14:07:17 +08:00
1 parent 94bc0f0472
commit 8d45b66660
11 files changed
+438 -281

No files matched your search

@@ -0,0 +1,146 @@
use std::{
collections::HashMap,
fs::File,
process::{ExitStatus, Stdio},
sync::Arc,
};
use anyhow::{Context, ensure};
use common::binary_paths;
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
process::Command,
};
use zeroize::Zeroizing;
use super::{CommandExt, gui_launcher::GuiLauncher};
use crate::service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential};
/// Owns the desktop GUI and its privileged service without leaving the desktop session.
pub struct DesktopLauncher<'a> {
version: &'a str,
minimized: bool,
log_file: Option<String>,
}
impl<'a> DesktopLauncher<'a> {
pub fn new(version: &'a str) -> Self {
Self {
version,
minimized: false,
log_file: None,
}
}
pub fn minimized(mut self, minimized: bool) -> Self {
self.minimized = minimized;
self
}
pub fn log_file(mut self, log_file: &str) -> Self {
self.log_file = Some(log_file.to_owned());
self
}
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
ensure!(
uzers::get_effective_uid() != 0,
"The desktop launcher must not run as root"
);
let mut command = Command::new_pkexec(binary_paths::gpservice());
command
.arg("--desktop-credentials")
.stdin(Stdio::piped())
.stdout(Stdio::piped());
if let Some(path) = &self.log_file {
command.stderr(Stdio::from(File::create(path)?));
}
let mut service = command.spawn().context("Failed to start the privileged service")?;
let mut input = service.stdin.take().context("Service input pipe is unavailable")?;
let mut output = service
.stdout
.take()
.context("Service credential pipe is unavailable")?;
let mut received_credential = false;
let mut cancelled = false;
let result = tokio::select! {
_ = crate::utils::shutdown_signal() => { cancelled = true; Ok(()) },
result = async {
let mut minimized = self.minimized;
loop {
let credential = read_credential(&mut output).await?;
let Some(credential) = credential else { return Ok(()); };
received_credential = true;
ensure!(credential.product_version() == self.version, "Service product version mismatch");
let mut envs: HashMap<String, String> = std::env::vars().collect();
if let Some(path) = &self.log_file {
envs.insert("GP_LOG_FILE".into(), path.clone());
}
let launcher = GuiLauncher::new(self.version, Arc::new(credential)).envs(envs).minimized(minimized);
let mut unexpected = [0];
tokio::select! {
result = launcher.launch() => { result?; }
status = service.wait() => { anyhow::bail!("The privileged service exited while the GUI was running: {}", status?); }
result = output.read(&mut unexpected) => {
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
anyhow::bail!("The privileged service closed its credential channel");
}
}
input.write_all(&[0]).await?;
minimized = false;
}
} => result,
};
// EOF lets the service revoke the credential and disconnect the VPN gracefully.
drop(input);
if cancelled && !received_credential {
// pkexec is still user-owned during authorization. After elevation, EOF owns shutdown.
if let Err(error) = service.start_kill()
&& error.kind() != std::io::ErrorKind::PermissionDenied
{
return Err(error.into());
}
}
let status = service.wait().await?;
result?;
ensure!(
cancelled || status.success(),
"The privileged service exited with {status}"
);
Ok(status)
}
}
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);
}
reader.read_exact(&mut header[1..]).await?;
let length = usize::from(u16::from_be_bytes(header));
ensure!(
length != 0 && length + 2 <= MAX_CREDENTIAL_FRAME,
"Invalid service credential length"
);
let mut frame = Zeroizing::new(vec![0; length + 2]);
frame[..2].copy_from_slice(&header);
reader.read_exact(&mut frame[2..]).await?;
Ok(Some(SessionCredential::decode_frame(&frame)?))
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn credential_channel_distinguishes_clean_close_from_truncated_or_oversized_frames() {
assert!(read_credential(&mut &[][..]).await.unwrap().is_none());
assert!(read_credential(&mut &[0][..]).await.is_err());
assert!(read_credential(&mut &[0, 0][..]).await.is_err());
assert!(read_credential(&mut &[255, 255][..]).await.is_err());
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
let frame = credential.encode_frame().unwrap();
let decoded = read_credential(&mut frame.as_slice()).await.unwrap().unwrap();
assert_eq!(decoded.session_id(), credential.session_id());
}
}
@@ -5,7 +5,7 @@ use common::binary_paths;
use log::info;
use tokio::{io::AsyncWriteExt, process::Command};
use crate::{process::command_traits::CommandExt, service::transport::SessionCredential};
use crate::service::transport::SessionCredential;
pub struct GuiHelperLauncher<'a> {
program: PathBuf,
@@ -49,8 +49,11 @@ impl<'a> GuiHelperLauncher<'a> {
}
info!("Launching gpgui-helper");
let mut non_root_cmd = cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
anyhow::ensure!(
uzers::get_effective_uid() != 0,
"The desktop GUI must not be launched by root"
);
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
+6 -5
View File
@@ -12,8 +12,6 @@ use tokio::{io::AsyncWriteExt, process::Command};
use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport::SessionCredential};
use super::command_traits::CommandExt;
pub struct GuiLauncher<'a> {
version: &'a str,
programs: Vec<PathBuf>,
@@ -52,6 +50,10 @@ impl<'a> GuiLauncher<'a> {
}
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
anyhow::ensure!(
uzers::get_effective_uid() != 0,
"The desktop GUI must not be launched by root"
);
if let Some(program) = self.find_compatible_program().await {
return self.launch_program(&program).await;
}
@@ -92,8 +94,7 @@ impl<'a> GuiLauncher<'a> {
}
info!("Launching gpgui");
let mut non_root_cmd = cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", program.display(), err),
@@ -119,7 +120,7 @@ impl<'a> GuiLauncher<'a> {
cmd.envs(envs);
}
cmd.arg("--version");
let output = cmd.into_non_root()?.output().await?;
let output = cmd.output().await?;
if !output.status.success() {
bail!("Version command exited with {}", output.status);
}
+1 -1
View File
@@ -6,8 +6,8 @@ pub(crate) mod gui_helper_launcher;
pub use command_traits::CommandExt;
pub mod auth_launcher;
pub mod desktop_launcher;
pub mod gui_launcher;
pub mod service_launcher;
pub mod users;
pub mod collection;
@@ -1,82 +0,0 @@
use std::{
fs::File,
path::PathBuf,
process::{ExitStatus, Stdio},
};
use common::binary_paths;
use tokio::process::Command;
use super::command_traits::CommandExt;
pub struct ServiceLauncher<'a> {
program: PathBuf,
minimized: bool,
env_file: Option<String>,
log_file: Option<String>,
verbose: Option<&'a str>,
}
impl Default for ServiceLauncher<'_> {
fn default() -> Self {
Self::new()
}
}
impl<'a> ServiceLauncher<'a> {
pub fn new() -> Self {
Self {
program: binary_paths::gpservice(),
minimized: false,
env_file: None,
log_file: None,
verbose: None,
}
}
pub fn minimized(mut self, minimized: bool) -> Self {
self.minimized = minimized;
self
}
pub fn env_file(mut self, env_file: &str) -> Self {
self.env_file = Some(env_file.to_string());
self
}
pub fn log_file(mut self, log_file: &str) -> Self {
self.log_file = Some(log_file.to_string());
self
}
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
self.verbose = verbose;
self
}
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
let mut cmd = Command::new_pkexec(&self.program);
if self.minimized {
cmd.arg("--minimized");
}
if let Some(env_file) = &self.env_file {
cmd.arg("--env-file").arg(env_file);
}
if let Some(verbose) = self.verbose {
cmd.arg(verbose);
}
if let Some(log_file) = &self.log_file {
let log_file = File::create(log_file)?;
let stdio = Stdio::from(log_file);
cmd.stderr(stdio);
}
let exit_status = cmd.kill_on_drop(true).spawn()?.wait().await?;
Ok(exit_status)
}
}