git.delta.rocks / remowt / refs/commits / eadb0bb3c19e

difftreelog

source

cmds/remowt-agent/src/main.rs10.8 KiBsourcehistory
1use std::borrow::Cow;2use std::collections::{BTreeMap, HashMap};3use std::fs::Permissions;4use std::future::pending;5use std::os::unix::fs::PermissionsExt as _;6use std::path::PathBuf;7use std::sync::{Arc, Mutex, OnceLock};89use bifrostlink::declarative::RemoteEndpoints;10use bifrostlink::Rpc;11use bifrostlink_ports::stdio::from_stdio;12use bifrostlink_ports::unix_socket::from_socket;13use clap::Parser;14use remowt_endpoints::{15	fs::Fs, nix_daemon::NixDaemon, pty::Pty, subprocess::Subprocess, systemd::Systemd,16};17use remowt_link_shared::{editor::EditorEndpointsClient, Address, BifConfig};18use remowt_polkit_shared::{emphasize, BackendRequest, Identity, PidDisplay};19use remowt_ui_prompt::bifrost::PromptEndpointsClient;20use remowt_ui_prompt::rofi::RofiPrompter;21use remowt_ui_prompt::{PrependSourcePrompter, Prompter, Source};22use tokio::fs;23use tokio::net::UnixStream;24use tokio::runtime::Builder;25use tokio::task::AbortHandle;26use tracing::{debug, trace};27use zbus::fdo;28use zbus::zvariant::{OwnedValue, Str};29use zbus::{interface, proxy, Connection};30use zbus_polkit::policykit1::Subject;3132use self::helper::{Helper, SocketHelper, SuidHelper};3334pub mod askpass;35pub mod bus;36pub mod editor;37pub mod helper;3839struct CancelTaskOnDrop {40	tasks: Arc<Mutex<HashMap<String, AbortHandle>>>,41	handle: String,42}43impl Drop for CancelTaskOnDrop {44	fn drop(&mut self) {45		debug!("cancel on drop");46		if let Some(task) = self47			.tasks48			.lock()49			.expect("not poisoned")50			.remove(&self.handle)51		{52			task.abort();53		}54	}55}5657struct Agent<H, P> {58	tasks: Arc<Mutex<HashMap<String, AbortHandle>>>,59	helper: H,60	prompter: P,61}62impl<H, P> Agent<H, P> {63	fn new(helper: H, prompter: P) -> Self {64		Agent {65			tasks: Arc::new(Mutex::new(HashMap::new())),66			helper,67			prompter,68		}69	}70}7172#[interface(name = "org.freedesktop.PolicyKit1.AuthenticationAgent")]73impl<H, P> Agent<H, P>74where75	H: Helper + Clone + Send + Sync + 'static,76	P: Prompter + Clone + Send + Sync + 'static,77{78	/// BeginAuthentication method79	#[allow(clippy::too_many_arguments)]80	async fn begin_authentication(81		&self,82		action_id: String,83		message: String,84		_icon_name: String,85		mut details: BTreeMap<String, String>,86		cookie: String,87		identities: Vec<Identity>,88	) -> zbus::fdo::Result<()> {89		use std::fmt::Write;90		debug!("begin auth");91		let _cancel_guard = Arc::new(OnceLock::new());92		let task = {93			let helper = self.helper.clone();94			let prompter = self.prompter.clone();95			let cookie = cookie.clone();96			let _cancel_guard = _cancel_guard.clone();97			tokio::task::spawn(async move {98				let _cancel_guard = _cancel_guard.clone();99				trace!("conversation task");100				let mut description = format!("{message}\n\n<b>Action id:</b> {action_id}",);101				if let Some(subject) = details.remove("polkit.caller-pid") {102					let _ = write!(description, "\n<b>Caller:</b> ");103					if let Ok(pid) = subject.parse::<u32>() {104						let _ = write!(description, "{}", PidDisplay(pid));105					} else {106						let _ = write!(description, "{}", emphasize("invalid pid"));107					}108				}109				if let Some(subject) = details.remove("polkit.subject-pid") {110					let _ = write!(description, "\n<b>Subject:</b> ");111					if let Ok(pid) = subject.parse::<u32>() {112						let _ = write!(description, "{}", PidDisplay(pid));113					} else {114						let _ = write!(description, "{}", emphasize("invalid pid"));115					}116				}117				let mut prompter = PrependSourcePrompter {118					source: vec![Source(Cow::Borrowed("polkit agent"))],119					description: description.clone(),120					prompter,121				};122123				let identity_displays: Vec<String> =124					identities.iter().map(|v| v.to_string()).collect();125				let identity_displays: Vec<&str> =126					identity_displays.iter().map(|v| v.as_str()).collect();127				debug!("choose identity");128				let choosen_identity = match identity_displays.len() {129					0 => {130						return Err(fdo::Error::AuthFailed(131							"no identity to authenticate as".to_owned(),132						))133					}134					1 => 0,135					_ => {136						prompter137							.prompt_enum(138								"Identity",139								"Select identity to use for polkit authorization",140								&identity_displays,141								&[],142							)143							.await?144					}145				};146				debug!("identity chosen");147148				let _ = write!(149					description,150					"\n<b>Identity:</b> {}",151					identities[choosen_identity as usize]152				);153				prompter.description = description;154155				prompter.source.push(Source(Cow::Borrowed("polkit daemon")));156157				helper158					.help_me(159						&cookie,160						prompter,161						identities[choosen_identity as usize].clone(),162					)163					.await164					.map_err(|e| fdo::Error::Failed(e.to_string()))?;165				// let connection = Connection::system().await?;166				// let helper = PolkitHelperProxy::new(&connection).await?;167168				Ok(())169			})170		};171		self.tasks172			.lock()173			.unwrap()174			.insert(cookie.clone(), task.abort_handle());175		debug!("abort handle stored");176		let _ = _cancel_guard.set(CancelTaskOnDrop {177			tasks: self.tasks.clone(),178			handle: cookie.clone(),179		});180181		let _ = task.await;182183		Ok(())184	}185186	/// CancelAuthentication method187	async fn cancel_authentication(&self, cookie: &str) -> zbus::fdo::Result<()> {188		debug!("auth cancelled");189		if let Some(abort) = self.tasks.lock().unwrap().remove(cookie) {190			debug!("abort handle found");191			abort.abort();192		}193		// debug!("Authentication cancled ! {cookie}");194		Ok(())195	}196}197198const OBJ_PATH: &str = "/org/freedesktop/PolicyKit1/AuthenticationAgent";199200#[proxy(201	interface = "lach.PolkitHelper",202	default_service = "lach.polkit.helper1",203	default_path = "/lach/PolkitHelper"204)]205trait PolkitHelper {206	fn init_conversation(&self, request: BackendRequest) -> zbus::Result<()>;207}208209#[derive(Parser)]210enum Opts {211	AskPass {212		prompt: String,213		description: String,214	},215	Editor {216		/// Argument to nvim217		path: String,218	},219	RealAgent {220		#[arg(long)]221		path: Option<PathBuf>,222		/// Expect own address to be AgentPrivileged, skip installing polkit agent223		#[arg(long)]224		privileged: bool,225		#[arg(long)]226		local: bool,227	},228	LocalAgent,229}230231fn main() -> anyhow::Result<()> {232	tracing_subscriber::fmt()233		.with_writer(std::io::stderr)234		.without_time()235		.init();236	let opts = Opts::parse();237238	let runtime = Builder::new_current_thread().enable_all().build()?;239240	match opts {241		Opts::AskPass {242			prompt,243			description,244		} => runtime.block_on(askpass::ask(&prompt, description)),245		Opts::LocalAgent => runtime.block_on(main_real()),246		Opts::Editor { path } => runtime.block_on(editor::edit(path)),247		Opts::RealAgent {248			path,249			privileged,250			local,251		} => runtime.block_on(main_real_agent(path, privileged, local)),252	}253}254async fn main_real() -> anyhow::Result<()> {255	let system_conn = Connection::system().await?;256	let helper = SocketHelper {257		fallback: SuidHelper,258	};259	register_auth_agent(&system_conn, Agent::new(helper, RofiPrompter)).await?;260261	let session_conn = Connection::session().await?;262	askpass::serve(&session_conn, RofiPrompter).await?;263264	let _keep_alive = (system_conn, session_conn);265	pending().await266}267async fn main_real_agent(268	path: Option<PathBuf>,269	privileged: bool,270	local: bool,271) -> anyhow::Result<()> {272	let address = if privileged {273		Address::AgentPrivileged274	} else {275		Address::Agent276	};277	let mut rpc = Rpc::<BifConfig>::new(address);278279	Fs::new().register_endpoints(&mut rpc);280	Systemd.register_endpoints(&mut rpc);281	Pty::new().register_endpoints(&mut rpc);282	Subprocess::new().register_endpoints(&mut rpc);283	NixDaemon.register_endpoints(&mut rpc);284285	remowt_plugin::host::serve(&mut rpc);286287	let user_prompter = PromptEndpointsClient::wrap(rpc.remote(Address::User));288	let editor_client = EditorEndpointsClient::wrap(rpc.remote(Address::User));289290	let bus = bus::spawn().await?;291	askpass::serve(&bus.conn, user_prompter.clone()).await?;292	editor::serve(&bus.conn, editor_client).await?;293294	let helpers = tempfile::Builder::new().prefix("remowt-path.").tempdir()?;295	let exe = std::env::current_exe()?;296	let askpass_helper = helpers.path().join("remowt-askpass");297	let editor_helper = helpers.path().join("remowt-editor");298	{299		let script = format!(300			"#!/bin/sh\nexec {} ask-pass \"password\" \"$1\"\n",301			sh_quote(&exe.to_string_lossy())302		);303		fs::write(&askpass_helper, script).await?;304		fs::set_permissions(&askpass_helper, Permissions::from_mode(0o755)).await?;305	}306	{307		let script = format!(308			"#!/bin/sh\nexec {} editor \"$1\"\n",309			sh_quote(&exe.to_string_lossy())310		);311		fs::write(&editor_helper, script).await?;312		fs::set_permissions(&editor_helper, Permissions::from_mode(0o755)).await?;313	}314315	// Safety: Hoping tokio own threads won't read any of those...316	unsafe {317		prepend_path(helpers.path());318		std::env::set_var("SUDO_ASKPASS", &askpass_helper);319		std::env::set_var("SSH_ASKPASS", &askpass_helper);320		std::env::set_var("SSH_ASKPASS_REQUIRE", "force");321		std::env::set_var("EDITOR", &editor_helper);322		std::env::set_var("VISUAL", &editor_helper);323		std::env::set_var("DBUS_SESSION_BUS_ADDRESS", &bus.address);324	}325326	let port = match path {327		Some(path) => from_socket(UnixStream::connect(path).await?),328		None => from_stdio(),329	};330	rpc.add_direct(Address::User, port, bifrostlink::Rtt(0));331332	let polkit_conn = if !privileged && !local {333		// The unprivileged agent doubles as a polkit authentication agent so334		// `run0` (e.g. our own elevation) routes its prompt to the User over335		// bifrost instead of failing on a tty-less session.336		let conn = Connection::system().await?;337		let helper = SocketHelper {338			fallback: SuidHelper,339		};340		register_auth_agent(&conn, Agent::new(helper, user_prompter)).await?;341		Some(conn)342	} else {343		None344	};345346	let _keep_alive = (bus, helpers, polkit_conn);347	pending().await348}349350async fn register_auth_agent<H, P>(conn: &Connection, agent: Agent<H, P>) -> anyhow::Result<()>351where352	H: Helper + Clone + Send + Sync + 'static,353	P: Prompter + Clone + Send + Sync + 'static,354{355	let proxy = zbus_polkit::policykit1::AuthorityProxy::new(conn).await?;356	conn.object_server().at(OBJ_PATH, agent).await?;357358	let subject = auth_agent_subject()?;359	proxy360		.register_authentication_agent(&subject, "C", OBJ_PATH)361		.await?;362	debug!(kind = subject.subject_kind, "registered polkit agent");363	Ok(())364}365366fn auth_agent_subject() -> anyhow::Result<Subject> {367	let mut details = HashMap::new();368	if let Ok(session_id) = std::env::var("XDG_SESSION_ID") {369		let val: OwnedValue = Str::from(session_id).into();370		details.insert("session-id".to_string(), val);371		return Ok(Subject {372			subject_kind: "unix-session".to_string(),373			subject_details: details,374		});375	}376377	details.insert("pid".to_string(), OwnedValue::from(std::process::id()));378	Ok(Subject {379		subject_kind: "unix-process".to_string(),380		subject_details: details,381	})382}383384fn sh_quote(s: &str) -> String {385	format!("'{}'", s.replace('\'', "'\\''"))386}387388/// Prepend `dir` to the process `PATH`.389///390/// # SAFETY391///392/// Same as `set_var`393unsafe fn prepend_path(dir: &std::path::Path) {394	let value = match std::env::var_os("PATH") {395		Some(existing) => {396			let mut v = dir.as_os_str().to_owned();397			v.push(":");398			v.push(existing);399			v400		}401		None => dir.as_os_str().to_owned(),402	};403	unsafe {404		std::env::set_var("PATH", value);405	}406}