From ed0dde2110a9e243fca6b83aa7aa4ee91244a229 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20L=C3=B6nnhager?= Date: Wed, 21 Aug 2024 19:53:40 +0200 Subject: [PATCH] fixup --- test/test-runner/src/util.rs | 65 +++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 23 deletions(-) diff --git a/test/test-runner/src/util.rs b/test/test-runner/src/util.rs index 2314f6c792ae..30b59b05fac8 100644 --- a/test/test-runner/src/util.rs +++ b/test/test-runner/src/util.rs @@ -22,19 +22,40 @@ impl OnDrop { } } -#[cfg(target_os = "windows")] -pub fn as_unprivileged(unpriv_user: &str, func: impl FnOnce() -> T) -> Result { - // NOTE: no-op - let _ = unpriv_user; - Ok(func()) +#[derive(thiserror::Error, Debug)] +#[error(transparent)] +pub struct Error { + inner: InnerError, } +#[cfg(unix)] #[derive(thiserror::Error, Debug)] -pub enum Error { +enum InnerError { #[error("Failed to get the specified user")] GetUser(#[source] nix::Error), #[error("The specified user was not found")] MissingUser, + #[error("Failed to set uid")] + SetUid(#[source] nix::Error), + #[error("Failed to set gid")] + SetGid(#[source] nix::Error), +} + +#[cfg(target_os = "windows")] +#[derive(thiserror::Error, Debug)] +enum InnerError {} + +impl From for Error { + fn from(inner: InnerError) -> Self { + Self { inner } + } +} + +#[cfg(target_os = "windows")] +pub fn as_unprivileged(unpriv_user: &str, func: impl FnOnce() -> T) -> Result { + // NOTE: no-op + let _ = unpriv_user; + Ok(func()) } #[cfg(unix)] @@ -43,26 +64,24 @@ pub fn as_unprivileged(unpriv_user: &str, func: impl FnOnce() -> T) -> Result let original_gid = nix::unistd::getgid(); let user = nix::unistd::User::from_name(unpriv_user) - .map_err(Error::GetUser)? - .ok_or(Error::MissingUser)?; + .map_err(InnerError::GetUser)? + .ok_or(InnerError::MissingUser)?; let uid = user.uid; let gid = user.gid; - if let Err(error) = nix::unistd::setegid(gid) { - log::error!("Failed to set gid: {error}"); - } - if let Err(error) = nix::unistd::seteuid(uid) { - log::error!("Failed to set uid: {error}"); - } - - let func_result = func(); + nix::unistd::setegid(gid).map_err(InnerError::SetGid)?; + OnDrop::new(|| { + if let Err(error) = nix::unistd::setegid(original_gid) { + log::error!("Failed to restore gid: {error}"); + } + }); - if let Err(error) = nix::unistd::seteuid(original_uid) { - log::error!("Failed to restore uid: {error}"); - } - if let Err(error) = nix::unistd::setegid(original_gid) { - log::error!("Failed to restore gid: {error}"); - } + nix::unistd::seteuid(uid).map_err(InnerError::SetUid)?; + OnDrop::new(|| { + if let Err(error) = nix::unistd::seteuid(original_uid) { + log::error!("Failed to restore uid: {error}"); + } + }); - Ok(func_result) + Ok(func()) }