git.delta.rocks / remowt / refs/commits / 745d95dba7aa

difftreelog

chore(polkit-dbus-helper) update dependencies

tlqrluwsYaroslav Bolyukin2026-01-25parent: #0fd20a2.patch.diff
in: trunk

2 files changed

modifiedcmds/polkit-dbus-helper/Cargo.tomldiffbeforeafterboth
--- a/cmds/polkit-dbus-helper/Cargo.toml
+++ b/cmds/polkit-dbus-helper/Cargo.toml
@@ -4,14 +4,14 @@
 edition = "2021"
 
 [dependencies]
-anyhow = "1.0.86"
-clap = { version = "4.5.11", features = ["derive"] }
-nix = "0.29.0"
-pam-client = "0.5.0"
-polkit-shared = { version = "0.1.0", path = "../../crates/polkit-shared" }
-tokio = { version = "1.39.2", features = ["macros", "rt", "rt-multi-thread"] }
-tracing = "0.1.40"
-tracing-subscriber = "0.3.18"
-ui-prompt = { version = "0.1.0", path = "../../crates/ui-prompt" }
-zbus = { version = "4.4.0", features = ["tokio"] }
-zbus_polkit = { version = "4.0.0", features = ["tokio"] }
+anyhow.workspace = true
+clap = { workspace = true, features = ["derive"] }
+nix.workspace = true
+pam-client.workspace = true
+polkit-shared.workspace = true
+tokio = { workspace = true, features = ["macros", "rt", "rt-multi-thread"] }
+tracing.workspace = true
+tracing-subscriber.workspace = true
+ui-prompt.workspace = true
+zbus = { workspace = true, features = ["tokio"] }
+zbus_polkit = { workspace = true, features = ["tokio"] }
modifiedcmds/polkit-dbus-helper/src/main.rsdiffbeforeafterboth
before · cmds/polkit-dbus-helper/src/main.rs
1use std::collections::{HashMap, HashSet};2use std::ffi::{CStr, CString};3use std::future::pending;4use std::sync::LazyLock;56use anyhow::Context as _;7use clap::Parser;8use nix::unistd::{setuid, Uid, User};9use pam_client::{Context, ConversationHandler, ErrorCode, Flag};10use polkit_shared::BackendRequest;11use tokio::task::{block_in_place, spawn_blocking};12use tracing::trace;13use ui_prompt::dbus::DbusPrompterProxyBlocking;14use ui_prompt::BlockingPrompter;15use zbus::fdo;16use zbus::message::Header;17use zbus::zvariant::OwnedValue;18use zbus::{blocking, interface, proxy, Connection};1920struct Helper {21    connection: Connection,22    blocking_connection: blocking::Connection,23}2425static ALLOWED_ENVIRONMENT: LazyLock<HashSet<&str>> = LazyLock::new(|| {26    [27        // pam ssh agent auth28        "SSH_AUTH_SOCK",29        // ssh itself provides this when running PAM30        "SSH_AUTH_INFO_0",31        // contains user which ran sudo32        "SUDO_USER",33    ]34    .into_iter()35    .collect()36});3738struct Conversation<P>(P);39impl<P: BlockingPrompter> Conversation<P> {40    fn prompt_inner(&self, echo: bool, prompt: &CStr) -> Result<CString, ErrorCode> {41        trace!("do prompt");42        let out = self43            .044            .prompt_text(echo, &prompt.to_string_lossy(), "PAM prompt request", &[])45            .map_err(|e| {46                trace!("prompt error: {e}");47                ErrorCode::CONV_ERR48            })?;49        CString::new(out).map_err(|_| ErrorCode::CONV_AGAIN)50    }51    fn text_inner(&self, error: bool, msg: &CStr) {52        trace!("do text");53        let msg = msg.to_string_lossy();54        let _ = self.0.display_text(error, &msg, &[]);55    }56}57impl<P: BlockingPrompter> ConversationHandler for Conversation<P> {58    fn prompt_echo_on(&mut self, prompt: &CStr) -> Result<CString, ErrorCode> {59        self.prompt_inner(true, prompt)60    }6162    fn prompt_echo_off(&mut self, prompt: &CStr) -> Result<CString, ErrorCode> {63        self.prompt_inner(false, prompt)64    }6566    fn text_info(&mut self, msg: &CStr) {67        self.text_inner(false, msg)68    }6970    fn error_msg(&mut self, msg: &CStr) {71        self.text_inner(true, msg)72    }7374    fn radio_prompt(&mut self, prompt: &CStr) -> Result<bool, ErrorCode> {75        let prompt = prompt.to_string_lossy();76        let result = self77            .078            .prompt_radio(&prompt, "PAM prompt request", &[])79            .map_err(|_| ErrorCode::CONV_ERR)?;80        Ok(result)81    }82}8384#[proxy(85    default_service = "org.freedesktop.DBus",86    default_path = "/org/freedesktop/DBus"87)]88trait DBus {89    fn get_connection_credentials(&self, body: &str) -> zbus::Result<HashMap<String, OwnedValue>>;90}9192#[interface(name = "lach.PolkitHelper")]93impl Helper {94    async fn init_conversation(95        &self,96        request: BackendRequest,97        #[zbus(header)] hdr: Header<'_>,98    ) -> fdo::Result<()> {99        let Some(sender) = hdr.sender().map(|v| v.to_owned()) else {100            trace!("missing sender");101            return Err(fdo::Error::AuthFailed("missing sender".to_owned()));102        };103104        let dbus = DBusProxy::new(&self.connection).await?;105106        // TOCTOU: sender might be already disconnected, and there might be another107        // user with different user id here, but does it matters?108        let reply = dbus.get_connection_credentials(&sender).await?;109        let connection_uid: u32 = (&reply["UnixUserID"]).try_into().unwrap();110111        let identity = request.identity.clone();112        let blocking_connection = self.blocking_connection.clone();113        let thread_result: fdo::Result<()> = block_in_place(move || {114            trace!("find user");115            let Some(identity_uid) = identity.uid() else {116                return Err(fdo::Error::AuthFailed("can't process identity".to_owned()));117            };118            let user = User::from_uid(identity_uid)119                .map_err(|_| fdo::Error::AuthFailed("error querying user".to_owned()))?120                .ok_or_else(|| fdo::Error::AuthFailed("uid not found".to_owned()))?;121122            let responder = DbusPrompterProxyBlocking::new(123                &blocking_connection,124                sender,125                request.prompter_path,126            )?;127            let conversation = Conversation(responder);128            trace!("run context for {}", &user.name);129            let mut ctx = Context::new(130                // TODO: Should another scope be used?131                "login",132                Some(&user.name),133                conversation,134            )135            .map_err(|_| fdo::Error::Failed("pam context init failed".to_owned()))?;136137            trace!("fill env");138            for (k, v) in request.environment {139                if k.contains('=') || !ALLOWED_ENVIRONMENT.contains(k.as_str()) {140                    continue;141                }142                let _ = ctx.putenv(format!("{k}={v}"));143            }144145            trace!("authenticate");146            ctx.authenticate(Flag::NONE)147                .map_err(|_| fdo::Error::AuthFailed("pam authentication failed".to_owned()))?;148149            trace!("acct mgmt");150            ctx.acct_mgmt(Flag::NONE)151                .map_err(|_| fdo::Error::AuthFailed("pam acct mgmt failed".to_owned()))?;152153            Ok(())154        });155156        thread_result?;157158        trace!("respond");159        let proxy = zbus_polkit::policykit1::AuthorityProxy::new(&self.connection).await?;160161        let identity_details = request162            .identity163            .details164            .iter()165            .map(|(k, v)| (k.as_str(), (**v).try_clone().expect("success")))166            .collect::<HashMap<_, _>>();167        proxy168            .authentication_agent_response2(169                connection_uid,170                &request.cookie,171                &zbus_polkit::policykit1::Identity {172                    identity_kind: &request.identity.kind,173                    identity_details: &identity_details,174                },175            )176            .await?;177        Ok(())178    }179}180181const OBJ_PATH: &str = "/lach/PolkitHelper";182183#[derive(Parser)]184struct Opts {185    /// Not recommended: start as a session connection, then use escalation186    /// to respond to polkit requests.187    #[arg(long)]188    session: bool,189}190191#[tokio::main]192async fn main() -> anyhow::Result<()> {193    tracing_subscriber::fmt::init();194    let opts = Opts::parse();195    let connection = if opts.session {196        Connection::session().await197    } else {198        Connection::system().await199    }200    .context("failed to open connection")?;201202    let session = opts.session;203    let blocking_connection: anyhow::Result<blocking::Connection> = spawn_blocking(move || {204        Ok(if session {205            blocking::Connection::session()?206        } else {207            blocking::Connection::system()?208        })209    })210    .await?;211    let blocking_connection = blocking_connection.context("failed to open blocking connection")?;212213    if opts.session {214        setuid(Uid::from_raw(0))215            .context("polkit-backend needs to be suid if run in session mode")?;216    }217218    connection219        .object_server()220        .at(221            OBJ_PATH,222            Helper {223                connection: connection.clone(),224                blocking_connection,225            },226        )227        .await228        .context("failed listen path")?;229230    connection231        .request_name("lach.polkit.helper1")232        .await233        .context("failed to request name")?;234235    pending().await236}
after · cmds/polkit-dbus-helper/src/main.rs
1use std::collections::{HashMap, HashSet};2use std::ffi::{CStr, CString};3use std::future::pending;4use std::sync::LazyLock;56use anyhow::Context as _;7use clap::Parser;8use nix::unistd::{setuid, Uid, User};9use pam_client::{Context, ConversationHandler, ErrorCode, Flag};10use polkit_shared::BackendRequest;11use tokio::task::{block_in_place, spawn_blocking};12use tracing::trace;13use ui_prompt::dbus::DbusPrompterProxyBlocking;14use ui_prompt::BlockingPrompter;15use zbus::fdo;16use zbus::message::Header;17use zbus::zvariant::OwnedValue;18use zbus::{blocking, interface, proxy, Connection};1920struct Helper {21	connection: Connection,22	blocking_connection: blocking::Connection,23}2425static ALLOWED_ENVIRONMENT: LazyLock<HashSet<&str>> = LazyLock::new(|| {26	[27		// pam ssh agent auth28		"SSH_AUTH_SOCK",29		// ssh itself provides this when running PAM30		"SSH_AUTH_INFO_0",31		// contains user which ran sudo32		"SUDO_USER",33	]34	.into_iter()35	.collect()36});3738struct Conversation<P>(P);39impl<P: BlockingPrompter> Conversation<P> {40	fn prompt_inner(&self, echo: bool, prompt: &CStr) -> Result<CString, ErrorCode> {41		trace!("do prompt");42		let out = self43			.044			.prompt_text(echo, &prompt.to_string_lossy(), "PAM prompt request", &[])45			.map_err(|e| {46				trace!("prompt error: {e}");47				ErrorCode::CONV_ERR48			})?;49		CString::new(out).map_err(|_| ErrorCode::CONV_AGAIN)50	}51	fn text_inner(&self, error: bool, msg: &CStr) {52		trace!("do text");53		let msg = msg.to_string_lossy();54		let _ = self.0.display_text(error, &msg, &[]);55	}56}57impl<P: BlockingPrompter> ConversationHandler for Conversation<P> {58	fn prompt_echo_on(&mut self, prompt: &CStr) -> Result<CString, ErrorCode> {59		self.prompt_inner(true, prompt)60	}6162	fn prompt_echo_off(&mut self, prompt: &CStr) -> Result<CString, ErrorCode> {63		self.prompt_inner(false, prompt)64	}6566	fn text_info(&mut self, msg: &CStr) {67		self.text_inner(false, msg)68	}6970	fn error_msg(&mut self, msg: &CStr) {71		self.text_inner(true, msg)72	}7374	fn radio_prompt(&mut self, prompt: &CStr) -> Result<bool, ErrorCode> {75		let prompt = prompt.to_string_lossy();76		let result = self77			.078			.prompt_radio(&prompt, "PAM prompt request", &[])79			.map_err(|_| ErrorCode::CONV_ERR)?;80		Ok(result)81	}82}8384#[proxy(85	default_service = "org.freedesktop.DBus",86	default_path = "/org/freedesktop/DBus"87)]88trait DBus {89	fn get_connection_credentials(&self, body: &str) -> zbus::Result<HashMap<String, OwnedValue>>;90}9192#[interface(name = "lach.PolkitHelper")]93impl Helper {94	async fn init_conversation(95		&self,96		request: BackendRequest,97		#[zbus(header)] hdr: Header<'_>,98	) -> fdo::Result<()> {99		let Some(sender) = hdr.sender().map(|v| v.to_owned()) else {100			trace!("missing sender");101			return Err(fdo::Error::AuthFailed("missing sender".to_owned()));102		};103104		let dbus = DBusProxy::new(&self.connection).await?;105106		// TOCTOU: sender might be already disconnected, and there might be another107		// user with different user id here, but does it matters?108		let reply = dbus.get_connection_credentials(&sender).await?;109		let connection_uid: u32 = (&reply["UnixUserID"]).try_into().unwrap();110111		let identity = request.identity.clone();112		let blocking_connection = self.blocking_connection.clone();113		let thread_result: fdo::Result<()> = block_in_place(move || {114			trace!("find user");115			let Some(identity_uid) = identity.uid() else {116				return Err(fdo::Error::AuthFailed("can't process identity".to_owned()));117			};118			let user = User::from_uid(identity_uid)119				.map_err(|_| fdo::Error::AuthFailed("error querying user".to_owned()))?120				.ok_or_else(|| fdo::Error::AuthFailed("uid not found".to_owned()))?;121122			let responder = DbusPrompterProxyBlocking::new(123				&blocking_connection,124				sender,125				request.prompter_path,126			)?;127			let conversation = Conversation(responder);128			trace!("run context for {}", &user.name);129			let mut ctx = Context::new(130				// TODO: Should another scope be used?131				"login",132				Some(&user.name),133				conversation,134			)135			.map_err(|_| fdo::Error::Failed("pam context init failed".to_owned()))?;136137			trace!("fill env");138			for (k, v) in request.environment {139				if k.contains('=') || !ALLOWED_ENVIRONMENT.contains(k.as_str()) {140					continue;141				}142				let _ = ctx.putenv(format!("{k}={v}"));143			}144145			trace!("authenticate");146			ctx.authenticate(Flag::NONE)147				.map_err(|_| fdo::Error::AuthFailed("pam authentication failed".to_owned()))?;148149			trace!("acct mgmt");150			ctx.acct_mgmt(Flag::NONE)151				.map_err(|_| fdo::Error::AuthFailed("pam acct mgmt failed".to_owned()))?;152153			Ok(())154		});155156		thread_result?;157158		trace!("respond");159		let proxy = zbus_polkit::policykit1::AuthorityProxy::new(&self.connection).await?;160161		let identity_details = request162			.identity163			.details164			.iter()165			.map(|(k, v)| (k.as_str(), (**v).try_clone().expect("success")))166			.collect::<HashMap<_, _>>();167		proxy168			.authentication_agent_response2(169				connection_uid,170				&request.cookie,171				&zbus_polkit::policykit1::Identity {172					identity_kind: &request.identity.kind,173					identity_details: &identity_details,174				},175			)176			.await?;177		Ok(())178	}179}180181const OBJ_PATH: &str = "/lach/PolkitHelper";182183#[derive(Parser)]184struct Opts {185	/// Not recommended: start as a session connection, then use escalation186	/// to respond to polkit requests.187	#[arg(long)]188	session: bool,189}190191#[tokio::main]192async fn main() -> anyhow::Result<()> {193	tracing_subscriber::fmt::init();194	let opts = Opts::parse();195	let connection = if opts.session {196		Connection::session().await197	} else {198		Connection::system().await199	}200	.context("failed to open connection")?;201202	let session = opts.session;203	let blocking_connection: anyhow::Result<blocking::Connection> = spawn_blocking(move || {204		Ok(if session {205			blocking::Connection::session()?206		} else {207			blocking::Connection::system()?208		})209	})210	.await?;211	let blocking_connection = blocking_connection.context("failed to open blocking connection")?;212213	if opts.session {214		setuid(Uid::from_raw(0))215			.context("polkit-backend needs to be suid if run in session mode")?;216	}217218	connection219		.object_server()220		.at(221			OBJ_PATH,222			Helper {223				connection: connection.clone(),224				blocking_connection,225			},226		)227		.await228		.context("failed listen path")?;229230	connection231		.request_name("lach.polkit.helper1")232		.await233		.context("failed to request name")?;234235	pending().await236}