mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
feat: prepare 3.0.0 release
This commit is contained in:
252 files changed
+26210
-7457
No files matched your search
@@ -1,14 +1,23 @@
|
||||
use std::{path::PathBuf, process::Stdio};
|
||||
use std::{
|
||||
net::IpAddr,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use common::binary_paths;
|
||||
use tokio::process::Command;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{auth::SamlAuthResult, credential::Credential, os_profile::OsProfile};
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use crate::auth::AuthWindowTheme;
|
||||
use crate::{auth::SamlAuthResult, credential::Credential, log_format::LogFormat, os_profile::OsProfile};
|
||||
|
||||
use super::command_traits::CommandExt;
|
||||
use super::{command_runner::run_controlled, command_traits::CommandExt};
|
||||
|
||||
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
|
||||
|
||||
pub struct SamlAuthLauncher<'a> {
|
||||
cancellation: CancellationToken,
|
||||
server: &'a str,
|
||||
auth_executable: Option<&'a str>,
|
||||
gateway: bool,
|
||||
@@ -27,13 +36,20 @@ pub struct SamlAuthLauncher<'a> {
|
||||
clean: bool,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
default_browser: bool,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_title: Option<&'a str>,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_theme: Option<AuthWindowTheme>,
|
||||
browser: Option<&'a str>,
|
||||
browser_listen: Option<IpAddr>,
|
||||
verbose: Option<&'a str>,
|
||||
log_format: LogFormat,
|
||||
}
|
||||
|
||||
impl<'a> SamlAuthLauncher<'a> {
|
||||
pub fn new(server: &'a str) -> Self {
|
||||
Self {
|
||||
cancellation: CancellationToken::new(),
|
||||
server,
|
||||
auth_executable: None,
|
||||
gateway: false,
|
||||
@@ -52,8 +68,14 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
clean: false,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
default_browser: false,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_title: None,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_theme: None,
|
||||
browser: None,
|
||||
browser_listen: None,
|
||||
verbose: None,
|
||||
log_format: LogFormat::Text,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,23 +144,54 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
pub fn window_title(mut self, window_title: &'a str) -> Self {
|
||||
self.window_title = Some(window_title);
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
pub fn window_theme(mut self, window_theme: AuthWindowTheme) -> Self {
|
||||
self.window_theme = Some(window_theme);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn browser(mut self, browser: Option<&'a str>) -> Self {
|
||||
self.browser = browser;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn browser_listen(mut self, browser_listen: Option<IpAddr>) -> Self {
|
||||
self.browser_listen = browser_listen;
|
||||
self
|
||||
}
|
||||
|
||||
/// Render the child's logs the same way as ours.
|
||||
///
|
||||
/// gpauth inherits this process's stderr, so both processes must use the same
|
||||
/// format to keep the stream consistent.
|
||||
pub fn log_format(mut self, log_format: LogFormat) -> Self {
|
||||
self.log_format = log_format;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
|
||||
self.verbose = verbose;
|
||||
self
|
||||
}
|
||||
|
||||
/// Launch the authenticator binary as the current user or SUDO_USER if available.
|
||||
pub async fn launch(self) -> anyhow::Result<Credential> {
|
||||
let program = self
|
||||
.auth_executable
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(binary_paths::gpauth);
|
||||
let mut auth_cmd = Command::new(&program);
|
||||
pub fn cancellation(mut self, cancellation: &CancellationToken) -> Self {
|
||||
self.cancellation = cancellation.clone();
|
||||
self
|
||||
}
|
||||
|
||||
/// The command line this launcher will run.
|
||||
///
|
||||
/// Split out from `launch` so a test can observe the argv the child actually
|
||||
/// receives: asserting on the builder's own fields would not catch an
|
||||
/// argument that never gets appended.
|
||||
fn build_command(&self, program: &Path) -> Command {
|
||||
let mut auth_cmd = Command::new(program);
|
||||
auth_cmd.arg(self.server);
|
||||
|
||||
if self.gateway {
|
||||
@@ -194,28 +247,65 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
if self.default_browser {
|
||||
auth_cmd.arg("--default-browser");
|
||||
}
|
||||
|
||||
if let Some(window_title) = self.window_title {
|
||||
auth_cmd.arg("--window-title").arg(window_title);
|
||||
}
|
||||
|
||||
if let Some(window_theme) = self.window_theme {
|
||||
auth_cmd.arg("--window-theme").arg(window_theme.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(browser) = self.browser {
|
||||
auth_cmd.arg("--browser").arg(browser);
|
||||
}
|
||||
|
||||
if let Some(browser_listen) = self.browser_listen {
|
||||
auth_cmd.arg("--browser-listen").arg(browser_listen.to_string());
|
||||
}
|
||||
|
||||
auth_cmd.arg("--log-format").arg(self.log_format.as_str());
|
||||
|
||||
if let Some(verbose) = self.verbose {
|
||||
auth_cmd.arg(verbose);
|
||||
}
|
||||
|
||||
let mut non_root_cmd = auth_cmd.into_non_root()?;
|
||||
let child = non_root_cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
|
||||
auth_cmd
|
||||
}
|
||||
|
||||
let child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => {
|
||||
bail!("Failed to spawn {}: {}", program.display(), err);
|
||||
/// Launch the authenticator binary as the current user or SUDO_USER if available.
|
||||
pub async fn launch(self) -> anyhow::Result<Credential> {
|
||||
let program = self
|
||||
.auth_executable
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(binary_paths::gpauth);
|
||||
let auth_cmd = self.build_command(&program);
|
||||
|
||||
let command = auth_cmd.into_non_root()?.into_std();
|
||||
let cancellation = self.cancellation;
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Authentication cancelled",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
run_controlled(command, &check, MAX_AUTH_RESULT_BYTES)
|
||||
})
|
||||
.await?;
|
||||
let output = match output {
|
||||
Ok(output) => output,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
|
||||
let output = child.wait_with_output().await?;
|
||||
|
||||
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
|
||||
bail!("Failed to parse auth data")
|
||||
};
|
||||
@@ -256,6 +346,45 @@ mod tests {
|
||||
assert_eq!(launcher.client_version, Some("6.0.0"));
|
||||
}
|
||||
|
||||
fn child_args(launcher: SamlAuthLauncher) -> Vec<String> {
|
||||
launcher
|
||||
.build_command(Path::new("gpauth"))
|
||||
.as_std()
|
||||
.get_args()
|
||||
.map(|arg| arg.to_string_lossy().into_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// gpauth writes to the same stderr as its parent, so a caller reading the
|
||||
/// parent's JSON would hit gpauth's text records mid-stream unless the format
|
||||
/// is passed down.
|
||||
#[test]
|
||||
fn json_is_forwarded_to_the_child() {
|
||||
let args = child_args(SamlAuthLauncher::new("portal.example.com").log_format(LogFormat::Json));
|
||||
|
||||
assert!(
|
||||
args.windows(2).any(|pair| pair == ["--log-format", "json"]),
|
||||
"expected --log-format json in {args:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The launcher always passes the selected format so the parent and child
|
||||
/// cannot silently drift onto different output formats.
|
||||
#[test]
|
||||
fn text_is_forwarded_to_the_child() {
|
||||
for launcher in [
|
||||
SamlAuthLauncher::new("portal.example.com").log_format(LogFormat::Text),
|
||||
SamlAuthLauncher::new("portal.example.com"),
|
||||
] {
|
||||
let args = child_args(launcher);
|
||||
|
||||
assert!(
|
||||
args.windows(2).any(|pair| pair == ["--log-format", "text"]),
|
||||
"expected --log-format text in {args:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_certificate_options_are_stored() {
|
||||
let launcher = SamlAuthLauncher::new("portal.example.com")
|
||||
@@ -267,4 +396,12 @@ mod tests {
|
||||
assert_eq!(launcher.sslkey, Some("/tmp/client.key"));
|
||||
assert_eq!(launcher.key_password, Some("secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_listen_address_is_stored() {
|
||||
let listen_ip = "192.168.107.15".parse().unwrap();
|
||||
let launcher = SamlAuthLauncher::new("portal.example.com").browser_listen(Some(listen_ip));
|
||||
|
||||
assert_eq!(launcher.browser_listen, Some(listen_ip));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
use std::{
|
||||
fs, io,
|
||||
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(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const COMMAND_OUTPUT_LIMIT: usize = 256 * 1024;
|
||||
const TOOL_DIRECTORIES: &[&str] = &[
|
||||
"/usr/bin",
|
||||
"/usr/sbin",
|
||||
"/bin",
|
||||
"/sbin",
|
||||
"/usr/local/bin",
|
||||
"/usr/local/sbin",
|
||||
#[cfg(target_os = "linux")]
|
||||
"/run/current-system/sw/bin",
|
||||
];
|
||||
|
||||
fn tool_directories() -> Vec<PathBuf> {
|
||||
let configured = std::env::var_os("GP_COMMAND_PATH").unwrap_or_default();
|
||||
let mut directories: Vec<_> = std::env::split_paths(&configured)
|
||||
.filter(|path| path.is_absolute())
|
||||
.collect();
|
||||
directories.extend(TOOL_DIRECTORIES.iter().map(PathBuf::from));
|
||||
directories
|
||||
}
|
||||
|
||||
pub struct CollectorCommands<'a> {
|
||||
control: &'a dyn CollectionControl,
|
||||
}
|
||||
|
||||
impl<'a> CollectorCommands<'a> {
|
||||
pub fn new(control: &'a dyn CollectionControl) -> Self {
|
||||
Self { control }
|
||||
}
|
||||
|
||||
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
|
||||
resolve_in_directories(name, &tool_directories(), uzers::get_effective_uid() == 0)
|
||||
}
|
||||
|
||||
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let Some(path) = self.resolve(name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.run_path(&path, args)
|
||||
}
|
||||
|
||||
/// Run an installed helper with the same trust checks as system collectors.
|
||||
/// Root only executes helpers protected from unprivileged modification.
|
||||
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let Some(path) = resolve_executable(path, uzers::get_effective_uid() == 0) else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.run_path(&path, args)
|
||||
}
|
||||
|
||||
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let home = if uzers::get_effective_uid() == 0 {
|
||||
if cfg!(target_os = "macos") {
|
||||
"/var/root"
|
||||
} else {
|
||||
"/root"
|
||||
}
|
||||
} else {
|
||||
"/"
|
||||
};
|
||||
let mut command = Command::new(path);
|
||||
command
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.env("PATH", command_path(uzers::get_effective_uid() == 0)?)
|
||||
.env("LC_ALL", "C")
|
||||
.env("HOME", home)
|
||||
.current_dir("/")
|
||||
.stderr(Stdio::null());
|
||||
match run_controlled(command, self.control, COMMAND_OUTPUT_LIMIT) {
|
||||
Ok(output) => Ok(Some(output)),
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_in_directories(name: &str, directories: &[PathBuf], require_root: bool) -> Option<PathBuf> {
|
||||
directories.iter().find_map(|directory| {
|
||||
let directory = fs::canonicalize(directory).ok()?;
|
||||
if require_root && !root_owned_path(&directory) {
|
||||
return None;
|
||||
}
|
||||
resolve_executable(&directory.join(name), require_root)
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_executable(path: &Path, require_root: bool) -> Option<PathBuf> {
|
||||
let resolved = fs::canonicalize(path).ok()?;
|
||||
let metadata = fs::metadata(&resolved).ok()?;
|
||||
if metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 && (!require_root || root_owned_path(&resolved)) {
|
||||
Some(resolved)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Known command directories, canonicalized and restricted to trusted root
|
||||
/// ownership when used for privileged execution.
|
||||
pub fn command_path(require_root: bool) -> io::Result<std::ffi::OsString> {
|
||||
let configured = tool_directories();
|
||||
let directories = configured.iter().filter_map(|directory| {
|
||||
let resolved = fs::canonicalize(directory).ok()?;
|
||||
if resolved.is_dir() && (!require_root || root_owned_path(&resolved)) {
|
||||
Some(resolved)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
std::env::join_paths(directories).map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))
|
||||
}
|
||||
|
||||
fn root_owned_path(path: &Path) -> bool {
|
||||
path.ancestors().all(|part| {
|
||||
fs::symlink_metadata(part).is_ok_and(|metadata| {
|
||||
let mode = metadata.permissions().mode();
|
||||
let writable = mode & 0o022 != 0;
|
||||
// A root-owned sticky directory protects each root-owned descendant
|
||||
// from replacement, including entries in the Nix store.
|
||||
let protected_ancestor = part != path && metadata.is_dir() && mode & 0o1000 != 0;
|
||||
metadata.uid() == 0 && (!writable || protected_ancestor) && !metadata.file_type().is_symlink()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn root_owned_sticky_directories_protect_collectors_without_trusting_writable_files() {
|
||||
// CI runs Rust tests as root; an unprivileged process cannot create these fixtures.
|
||||
if uzers::get_effective_uid() != 0 {
|
||||
return;
|
||||
}
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let tool = directory.path().join("collector");
|
||||
fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o1775)).unwrap();
|
||||
assert_eq!(resolve_executable(&tool, true), Some(fs::canonicalize(&tool).unwrap()));
|
||||
// A PATH directory must itself reject unprivileged additions, even with the sticky bit.
|
||||
assert!(!root_owned_path(directory.path()));
|
||||
assert!(resolve_in_directories("collector", &[directory.path().to_owned()], true).is_none());
|
||||
let bin = directory.path().join("bin");
|
||||
fs::create_dir(&bin).unwrap();
|
||||
fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::copy(&tool, bin.join("collector")).unwrap();
|
||||
assert!(resolve_in_directories("collector", &[bin], true).is_some());
|
||||
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o775)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o1777)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_some());
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o1775)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::os::unix::fs::chown(&tool, Some(1), None).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
std::os::unix::fs::chown(&tool, Some(0), None).unwrap();
|
||||
std::os::unix::fs::chown(directory.path(), Some(1), None).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_directories_resolve_tools_without_using_the_process_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let tool = dir.path().join("configured-tool");
|
||||
fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(
|
||||
resolve_in_directories("configured-tool", &[dir.path().to_owned()], false),
|
||||
Some(fs::canonicalize(&tool).unwrap())
|
||||
);
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o777)).unwrap();
|
||||
assert!(resolve_in_directories("configured-tool", &[dir.path().to_owned()], true).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_command_path_contains_only_trusted_canonical_directories() {
|
||||
let path = command_path(true).unwrap();
|
||||
let directories: Vec<_> = std::env::split_paths(&path).collect();
|
||||
assert!(!directories.is_empty());
|
||||
for directory in directories {
|
||||
assert!(directory.is_dir());
|
||||
assert!(root_owned_path(&directory));
|
||||
assert_eq!(directory, fs::canonicalize(&directory).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_resolution_returns_target_not_mutable_symlink() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let link = dir.path().join("tool");
|
||||
std::os::unix::fs::symlink("/bin/sh", &link).unwrap();
|
||||
let resolved = resolve_executable(&link, false).unwrap();
|
||||
fs::remove_file(&link).unwrap();
|
||||
std::os::unix::fs::symlink("/bin/echo", &link).unwrap();
|
||||
assert_eq!(resolved, fs::canonicalize("/bin/sh").unwrap());
|
||||
assert_ne!(resolved, fs::canonicalize(&link).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_stops_running_collector() {
|
||||
let started = Instant::now();
|
||||
let control = || {
|
||||
if started.elapsed() >= Duration::from_millis(100) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let error = CollectorCommands::new(&control)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30 & wait"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_has_private_environment_and_cwd() {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(2));
|
||||
let output = CollectorCommands::new(&budget)
|
||||
.run_path(
|
||||
Path::new("/bin/sh"),
|
||||
&[
|
||||
"-c",
|
||||
"printf '%s|%s|%s' \"$LC_ALL\" \"$PWD\" \"${SENTINEL_OUTPUT_JSON-unset}\"",
|
||||
],
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
assert_eq!(String::from_utf8(output.stdout).unwrap(), "C|/|unset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deadline_stops_collector_instead_of_hanging() {
|
||||
let budget = CollectionBudget::new(Duration::from_millis(100));
|
||||
let started = Instant::now();
|
||||
let error = CollectorCommands::new(&budget)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_output_is_bounded() {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(2));
|
||||
let error = CollectorCommands::new(&budget)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "yes x"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_is_not_an_optional_missing_product() {
|
||||
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = CollectorCommands::new(&control).run("not-installed", &[]).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
use std::{
|
||||
io::{self, Read},
|
||||
os::unix::process::CommandExt,
|
||||
process::{Child, Command, Output, Stdio},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, OFlag, fcntl},
|
||||
sys::signal::{Signal, killpg},
|
||||
unistd::Pid,
|
||||
};
|
||||
|
||||
use super::collection::CollectionControl;
|
||||
|
||||
/// Execute an already configured command. Environment, identity and executable
|
||||
/// trust belong to its caller. This worker owns the process group until reaped;
|
||||
/// its asynchronous caller must cancel and await it instead of dropping it.
|
||||
pub(crate) fn run_controlled(
|
||||
mut command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: usize,
|
||||
) -> io::Result<Output> {
|
||||
control.check()?;
|
||||
let child = command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.process_group(0)
|
||||
.spawn()?;
|
||||
let mut child = ControlledChild(child);
|
||||
let mut stdout = child.0.stdout.take().expect("controlled stdout was piped");
|
||||
let flags = fcntl(&stdout, FcntlArg::F_GETFL).map_err(io::Error::from)?;
|
||||
fcntl(
|
||||
&stdout,
|
||||
FcntlArg::F_SETFL(OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK),
|
||||
)
|
||||
.map_err(io::Error::from)?;
|
||||
let mut output = Vec::new();
|
||||
let mut buffer = [0u8; 8192];
|
||||
let mut eof = false;
|
||||
let mut status = None;
|
||||
loop {
|
||||
control.check()?;
|
||||
if !eof {
|
||||
match stdout.read(&mut buffer) {
|
||||
Ok(0) => eof = true,
|
||||
Ok(length) => {
|
||||
if length > output_limit.saturating_sub(output.len()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Command output exceeds its limit",
|
||||
));
|
||||
}
|
||||
output.extend_from_slice(&buffer[..length]);
|
||||
continue;
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
if status.is_none() {
|
||||
status = child.0.try_wait()?;
|
||||
}
|
||||
if eof && let Some(status) = status {
|
||||
return Ok(Output {
|
||||
status,
|
||||
stdout: output,
|
||||
stderr: Vec::new(),
|
||||
});
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
struct ControlledChild(Child);
|
||||
|
||||
impl Drop for ControlledChild {
|
||||
fn drop(&mut self) {
|
||||
// Reap the direct child and stop helpers retaining stdout after it exits.
|
||||
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{File, OpenOptions},
|
||||
path::Path,
|
||||
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(create_log_file(Path::new(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)
|
||||
}
|
||||
}
|
||||
|
||||
fn create_log_file(path: &Path) -> std::io::Result<File> {
|
||||
// Start a fresh desktop session, then let both processes append without overwriting each other.
|
||||
File::create(path)?;
|
||||
OpenOptions::new().append(true).open(path)
|
||||
}
|
||||
|
||||
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 std::io::Write;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn desktop_log_starts_fresh_and_service_writes_preserve_gui_logs() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let path = dir.path().join("desktop.log");
|
||||
std::fs::write(&path, "previous session\n").unwrap();
|
||||
let mut service = create_log_file(&path).unwrap();
|
||||
writeln!(service, "[gpservice] started").unwrap();
|
||||
let mut gui = OpenOptions::new().append(true).open(&path).unwrap();
|
||||
writeln!(gui, "[gpgui] initialized").unwrap();
|
||||
writeln!(service, "[gpservice] connected").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&path).unwrap(),
|
||||
"[gpservice] started\n[gpgui] initialized\n[gpservice] connected\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[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,21 +5,21 @@ use common::binary_paths;
|
||||
use log::info;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
|
||||
use crate::{process::command_traits::CommandExt, utils};
|
||||
use crate::service::transport::SessionCredential;
|
||||
|
||||
pub struct GuiHelperLauncher<'a> {
|
||||
program: PathBuf,
|
||||
envs: Option<&'a HashMap<String, String>>,
|
||||
api_key: &'a [u8],
|
||||
credential: &'a SessionCredential,
|
||||
gui_version: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> GuiHelperLauncher<'a> {
|
||||
pub fn new(api_key: &'a [u8]) -> Self {
|
||||
pub fn new(credential: &'a SessionCredential) -> Self {
|
||||
Self {
|
||||
program: binary_paths::gpgui_helper(),
|
||||
envs: None,
|
||||
api_key,
|
||||
credential,
|
||||
gui_version: None,
|
||||
}
|
||||
}
|
||||
@@ -42,15 +42,18 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
cmd.envs(envs);
|
||||
}
|
||||
|
||||
cmd.arg("--api-key-on-stdin");
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
|
||||
if let Some(gui_version) = self.gui_version {
|
||||
cmd.arg("--gui-version").arg(gui_version);
|
||||
}
|
||||
|
||||
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),
|
||||
@@ -60,13 +63,11 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
bail!("Failed to open stdin");
|
||||
};
|
||||
|
||||
let api_key = utils::base64::encode(self.api_key);
|
||||
tokio::spawn(async move {
|
||||
stdin.write_all(api_key.as_bytes()).await.unwrap();
|
||||
drop(stdin);
|
||||
});
|
||||
let frame = self.credential.encode_frame()?;
|
||||
stdin.write_all(&frame).await?;
|
||||
|
||||
let exit_status = child.wait().await?;
|
||||
drop(stdin);
|
||||
info!("gpgui-helper exited with: {}", exit_status);
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,32 +1,40 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::PathBuf,
|
||||
fs::OpenOptions,
|
||||
path::{Path, PathBuf},
|
||||
process::{ExitStatus, Stdio},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use anyhow::{Context, bail};
|
||||
use common::binary_paths;
|
||||
use log::info;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
|
||||
use crate::{process::gui_helper_launcher::GuiHelperLauncher, utils::base64};
|
||||
|
||||
use super::command_traits::CommandExt;
|
||||
use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport::SessionCredential};
|
||||
|
||||
pub struct GuiLauncher<'a> {
|
||||
version: &'a str,
|
||||
program: PathBuf,
|
||||
api_key: &'a [u8],
|
||||
programs: Vec<PathBuf>,
|
||||
credential: Arc<SessionCredential>,
|
||||
minimized: bool,
|
||||
envs: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
impl<'a> GuiLauncher<'a> {
|
||||
pub fn new(version: &'a str, api_key: &'a [u8]) -> Self {
|
||||
pub fn new(version: &'a str, credential: Arc<SessionCredential>) -> Self {
|
||||
let primary = binary_paths::gpgui();
|
||||
let update_target = binary_paths::gpgui_update_target();
|
||||
let programs = if primary == update_target {
|
||||
vec![primary]
|
||||
} else {
|
||||
vec![primary, update_target]
|
||||
};
|
||||
|
||||
Self {
|
||||
version,
|
||||
program: binary_paths::gpgui(),
|
||||
api_key,
|
||||
programs,
|
||||
credential,
|
||||
minimized: false,
|
||||
envs: None,
|
||||
}
|
||||
@@ -43,56 +51,93 @@ impl<'a> GuiLauncher<'a> {
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
||||
// Check if the program's version
|
||||
if let Err(err) = self.check_version().await {
|
||||
info!("Check version failed: {}", err);
|
||||
// Download the program and replace the current one
|
||||
self.download_program().await?;
|
||||
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;
|
||||
}
|
||||
|
||||
self.launch_program().await
|
||||
self.download_program().await?;
|
||||
|
||||
let program = binary_paths::gpgui_update_target();
|
||||
self.check_version(&program).await?;
|
||||
self.launch_program(&program).await
|
||||
}
|
||||
|
||||
async fn launch_program(&self) -> anyhow::Result<ExitStatus> {
|
||||
let mut cmd = Command::new(&self.program);
|
||||
async fn find_compatible_program(&self) -> Option<PathBuf> {
|
||||
for program in &self.programs {
|
||||
match self.check_version(program).await {
|
||||
Ok(()) => return Some(program.clone()),
|
||||
Err(err) => info!(
|
||||
"GUI candidate {} is unavailable or incompatible: {err}",
|
||||
program.display()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
async fn launch_program(&self, program: &Path) -> anyhow::Result<ExitStatus> {
|
||||
let mut cmd = Command::new(program);
|
||||
|
||||
if let Some(envs) = &self.envs {
|
||||
cmd.env_clear();
|
||||
cmd.envs(envs);
|
||||
}
|
||||
|
||||
cmd.arg("--api-key-on-stdin");
|
||||
let log_file = match &self.envs {
|
||||
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
|
||||
None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from),
|
||||
};
|
||||
if let Some(path) = log_file {
|
||||
let file = OpenOptions::new()
|
||||
.append(true)
|
||||
.open(&path)
|
||||
.with_context(|| format!("Failed to open GUI log file: {}", path.display()))?;
|
||||
cmd.stderr(Stdio::from(file));
|
||||
}
|
||||
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
|
||||
if self.minimized {
|
||||
cmd.arg("--minimized");
|
||||
}
|
||||
|
||||
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 {}: {}", self.program.display(), err),
|
||||
Err(err) => bail!("Failed to spawn {}: {}", program.display(), err),
|
||||
};
|
||||
|
||||
let Some(mut stdin) = child.stdin.take() else {
|
||||
bail!("Failed to open stdin");
|
||||
};
|
||||
|
||||
let api_key = base64::encode(self.api_key);
|
||||
tokio::spawn(async move {
|
||||
stdin.write_all(api_key.as_bytes()).await.unwrap();
|
||||
drop(stdin);
|
||||
});
|
||||
let frame = self.credential.encode_frame()?;
|
||||
stdin.write_all(&frame).await?;
|
||||
|
||||
let exit_status = child.wait().await?;
|
||||
drop(stdin);
|
||||
|
||||
Ok(exit_status)
|
||||
}
|
||||
|
||||
async fn check_version(&self) -> anyhow::Result<()> {
|
||||
let cmd = Command::new(&self.program).arg("--version").output().await?;
|
||||
let output = String::from_utf8_lossy(&cmd.stdout);
|
||||
async fn check_version(&self, program: &Path) -> anyhow::Result<()> {
|
||||
let mut cmd = Command::new(program);
|
||||
if let Some(envs) = &self.envs {
|
||||
cmd.env_clear();
|
||||
cmd.envs(envs);
|
||||
}
|
||||
cmd.arg("--version");
|
||||
let output = cmd.output().await?;
|
||||
if !output.status.success() {
|
||||
bail!("Version command exited with {}", output.status);
|
||||
}
|
||||
let output = String::from_utf8_lossy(&output.stdout);
|
||||
|
||||
// Version string: "gpgui 2.0.0 (2024-02-05)"
|
||||
let Some(version) = output.split_whitespace().nth(1) else {
|
||||
@@ -109,17 +154,96 @@ impl<'a> GuiLauncher<'a> {
|
||||
}
|
||||
|
||||
async fn download_program(&self) -> anyhow::Result<()> {
|
||||
let gui_helper = GuiHelperLauncher::new(self.api_key);
|
||||
let gui_helper = GuiHelperLauncher::new(&self.credential);
|
||||
|
||||
gui_helper
|
||||
.envs(self.envs.as_ref())
|
||||
.gui_version(Some(self.version))
|
||||
.launch()
|
||||
.await?;
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
// Check the version again
|
||||
self.check_version().await?;
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{fs, os::unix::fs::PermissionsExt};
|
||||
|
||||
Ok(())
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
|
||||
const VERSION: &str = "test-version";
|
||||
|
||||
fn executable(dir: &TempDir, name: &str, output: &str, exit_code: i32) -> PathBuf {
|
||||
fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let path = dir.path().join(name);
|
||||
fs::write(
|
||||
&path,
|
||||
format!("#!/bin/sh\nprintf '%s\\n' '{output}'\nexit {exit_code}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn launcher(version: &'static str, programs: Vec<PathBuf>) -> GuiLauncher<'static> {
|
||||
GuiLauncher {
|
||||
version,
|
||||
programs,
|
||||
credential: Arc::new(SessionCredential::generate(Uuid::new_v4(), version).unwrap()),
|
||||
minimized: false,
|
||||
envs: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn captures_gui_logs_in_the_desktop_log_file_across_restarts() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let log_file = dir.path().join("desktop.log");
|
||||
fs::write(&log_file, "[gpservice] started\n").unwrap();
|
||||
let program = dir.path().join("gui");
|
||||
fs::write(&program, "#!/bin/sh\nprintf '[gpgui] initialized\\n' >&2\n").unwrap();
|
||||
fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let launcher = launcher(VERSION, vec![]).envs(HashMap::from([(
|
||||
"GP_LOG_FILE".to_owned(),
|
||||
log_file.to_str().unwrap().to_owned(),
|
||||
)]));
|
||||
|
||||
assert!(launcher.launch_program(&program).await.unwrap().success());
|
||||
assert!(launcher.launch_program(&program).await.unwrap().success());
|
||||
assert_eq!(
|
||||
fs::read_to_string(log_file).unwrap(),
|
||||
"[gpservice] started\n[gpgui] initialized\n[gpgui] initialized\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prefers_the_first_compatible_program() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let packaged = executable(&dir, "packaged", "gpgui test-version", 0);
|
||||
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));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn falls_back_when_the_first_program_is_incompatible() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let packaged = executable(&dir, "packaged", "gpgui other-version", 0);
|
||||
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));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_an_unsuccessful_version_command() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let program = executable(&dir, "broken", "gpgui test-version", 1);
|
||||
let launcher = launcher(VERSION, vec![program]);
|
||||
|
||||
assert_eq!(launcher.find_compatible_program().await, None);
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
use std::process::Stdio;
|
||||
|
||||
use anyhow::bail;
|
||||
use tokio::process::Command;
|
||||
|
||||
pub struct HipLauncher<'a> {
|
||||
program: &'a str,
|
||||
cookie: Option<&'a str>,
|
||||
client_ip: Option<&'a str>,
|
||||
md5: Option<&'a str>,
|
||||
client_os: Option<&'a str>,
|
||||
client_version: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> HipLauncher<'a> {
|
||||
pub fn new(program: &'a str) -> Self {
|
||||
Self {
|
||||
program,
|
||||
cookie: None,
|
||||
client_ip: None,
|
||||
md5: None,
|
||||
client_os: None,
|
||||
client_version: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cookie(mut self, cookie: &'a str) -> Self {
|
||||
self.cookie = Some(cookie);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn client_ip(mut self, client_ip: &'a str) -> Self {
|
||||
self.client_ip = Some(client_ip);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn md5(mut self, md5: &'a str) -> Self {
|
||||
self.md5 = Some(md5);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn client_os(mut self, client_os: &'a str) -> Self {
|
||||
self.client_os = Some(client_os);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn client_version(mut self, client_version: Option<&'a str>) -> Self {
|
||||
self.client_version = client_version;
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<String> {
|
||||
let mut cmd = Command::new(self.program);
|
||||
|
||||
if let Some(cookie) = self.cookie {
|
||||
cmd.arg("--cookie").arg(cookie);
|
||||
}
|
||||
|
||||
if let Some(client_ip) = self.client_ip {
|
||||
cmd.arg("--client-ip").arg(client_ip);
|
||||
}
|
||||
|
||||
if let Some(md5) = self.md5 {
|
||||
cmd.arg("--md5").arg(md5);
|
||||
}
|
||||
|
||||
if let Some(client_os) = self.client_os {
|
||||
cmd.arg("--client-os").arg(client_os);
|
||||
}
|
||||
|
||||
if let Some(client_version) = self.client_version {
|
||||
cmd.env("APP_VERSION", client_version);
|
||||
}
|
||||
|
||||
let child = cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
|
||||
|
||||
let child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => bail!("Failed to spawn {}: {}", self.program, err),
|
||||
};
|
||||
|
||||
let output = child.wait_with_output().await?;
|
||||
|
||||
if let Some(exit_status) = output.status.code() {
|
||||
if exit_status != 0 {
|
||||
bail!("HIP report generation failed with exit code {}", exit_status);
|
||||
}
|
||||
|
||||
let report = String::from_utf8(output.stdout)?;
|
||||
|
||||
Ok(report)
|
||||
} else {
|
||||
bail!("HIP report generation failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
pub(crate) mod command_traits;
|
||||
mod command_runner;
|
||||
mod command_traits;
|
||||
mod desktop_session_env;
|
||||
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 hip_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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user