difftreelog
feat auto prompter
in: trunk
9 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -308,9 +308,9 @@
[[package]]
name = "bifrostlink"
-version = "0.2.3"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "704657867d2107831c57edd363726440c86675464b5fc113702854e17062cafc"
+checksum = "ad2d0e30a2aa432b78f41f9676572f88201d4dc73bc2b7bc90704d2e02b7d062"
dependencies = [
"async-trait",
"async_fn_traits",
@@ -327,9 +327,9 @@
[[package]]
name = "bifrostlink-macros"
-version = "0.2.3"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "158308eb569b467c0116680f79d0ecc389f4d540f6d5a0c9279bfe79b1cd5bdb"
+checksum = "e2121559c45cbe89c4f8d1d741360d5b028577254f6beca053dc02332da85b43"
dependencies = [
"proc-macro2",
"quote",
@@ -338,9 +338,9 @@
[[package]]
name = "bifrostlink-ports"
-version = "0.2.3"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7612993f0bd8bc6a71867461266567212a35a716b2a5aef5f9967ab08c891782"
+checksum = "e9395c4ccca497b0c50583e6de57aca921c046ae0c10f56030cd2c5a20db05f8"
dependencies = [
"bifrostlink",
"bytes",
@@ -1835,7 +1835,7 @@
[[package]]
name = "polkit-backend"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
"anyhow",
"clap",
@@ -2055,7 +2055,7 @@
[[package]]
name = "remowt-agent"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
"anyhow",
"bifrostlink",
@@ -2083,7 +2083,7 @@
[[package]]
name = "remowt-client"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
"anyhow",
"bifrostlink",
@@ -2106,7 +2106,7 @@
[[package]]
name = "remowt-endpoints"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
"anyhow",
"bifrostlink",
@@ -2124,7 +2124,7 @@
[[package]]
name = "remowt-link-shared"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
"bifrostlink",
"bytes",
@@ -2138,7 +2138,7 @@
[[package]]
name = "remowt-plugin"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
"anyhow",
"bifrostlink",
@@ -2152,7 +2152,7 @@
[[package]]
name = "remowt-polkit-shared"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
"nix",
"serde",
@@ -2161,7 +2161,7 @@
[[package]]
name = "remowt-ssh"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
"anyhow",
"async-trait",
@@ -2189,8 +2189,9 @@
[[package]]
name = "remowt-ui-prompt"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
+ "anyhow",
"bifrostlink",
"bifrostlink-macros",
"serde",
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@
resolver = "2"
[workspace.package]
-version = "0.1.3"
+version = "0.1.4"
license = "MIT"
edition = "2021"
repository = "https://git.delta.rocks/r/remowt"
@@ -52,7 +52,6 @@
thiserror = "2.0.18"
[profile.release]
-strip = true
panic = "abort"
opt-level = "z"
lto = true
cmds/remowt-agent/src/askpass.rsdiffbeforeafterboth--- a/cmds/remowt-agent/src/askpass.rs
+++ b/cmds/remowt-agent/src/askpass.rs
@@ -2,24 +2,25 @@
use std::io::Write as _;
use anyhow::Context as _;
-use remowt_ui_prompt::bifrost::PromptEndpointsClient;
-use remowt_ui_prompt::dbus::{DbusPrompterInterface, DbusPrompterProxy};
-use remowt_ui_prompt::Source;
+use remowt_ui_prompt::dbus::{DbusPrompterInterface, DbusPrompterProxy, BUS_NAME, PROMPTER_PATH};
+use remowt_ui_prompt::{Prompter, Source};
+use tracing::debug;
use zbus::Connection;
-
-use remowt_link_shared::BifConfig;
-
-const BUS_NAME: &str = "lach.RemowtAskpass";
-const PROMPTER_PATH: &str = "/lach/Askpass";
-pub async fn serve(
- conn: &Connection,
- prompter: PromptEndpointsClient<BifConfig>,
-) -> anyhow::Result<()> {
+pub async fn serve<P>(conn: &Connection, prompter: P) -> anyhow::Result<()>
+where
+ P: Prompter + 'static,
+{
conn.object_server()
.at(PROMPTER_PATH, DbusPrompterInterface(prompter))
.await?;
- conn.request_name(BUS_NAME).await?;
+ match conn.request_name(BUS_NAME).await {
+ Ok(()) => {}
+ Err(zbus::Error::NameTaken) => {
+ debug!("{BUS_NAME} already owned, chaining to upstream");
+ }
+ Err(e) => return Err(e.into()),
+ }
Ok(())
}
cmds/remowt-agent/src/main.rsdiffbeforeafterboth1use 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}cmds/remowt-ssh/src/main.rsdiffbeforeafterboth--- a/cmds/remowt-ssh/src/main.rs
+++ b/cmds/remowt-ssh/src/main.rs
@@ -13,8 +13,8 @@
use remowt_client::editor::SshEditor;
use remowt_client::{AgentBundle, Remowt};
use remowt_link_shared::editor::serve_editor;
+use remowt_ui_prompt::auto::AutoPrompter;
use remowt_ui_prompt::bifrost::serve_prompts;
-use remowt_ui_prompt::rofi::RofiPrompter;
use remowt_ui_prompt::{PrependSourcePrompter, Source};
use tokio::io::unix::AsyncFd;
use tokio::io::{AsyncRead, ReadBuf};
@@ -61,7 +61,7 @@
serve_prompts(
&mut rpc,
PrependSourcePrompter {
- prompter: RofiPrompter,
+ prompter: AutoPrompter::new().await,
source: match opts {
Opts::Ssh { host, .. } => vec![Source(Cow::Owned(format!("ssh host: {}", host)))],
Opts::Local { .. } => vec![],
crates/remowt-ui-prompt/Cargo.tomldiffbeforeafterboth--- a/crates/remowt-ui-prompt/Cargo.toml
+++ b/crates/remowt-ui-prompt/Cargo.toml
@@ -6,6 +6,7 @@
license.workspace = true
[dependencies]
+anyhow.workspace = true
bifrostlink.workspace = true
bifrostlink-macros.workspace = true
serde.workspace = true
crates/remowt-ui-prompt/src/auto.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/remowt-ui-prompt/src/auto.rs
@@ -0,0 +1,83 @@
+use anyhow::bail;
+use tracing::debug;
+use zbus::fdo::DBusProxy;
+use zbus::names::BusName;
+
+use crate::dbus::{DbusPrompterProxy, BUS_NAME, PROMPTER_PATH};
+use crate::rofi::RofiPrompter;
+use crate::{Prompter, Result, Source};
+
+pub struct AutoPrompter {
+ dbus: Option<DbusPrompterProxy<'static>>,
+ fallback: RofiPrompter,
+}
+
+impl AutoPrompter {
+ pub async fn new() -> Self {
+ let dbus = match Self::try_dbus().await {
+ Ok(p) => Some(p),
+ Err(e) => {
+ debug!("dbus prompter unavailable, falling back to rofi: {e}");
+ None
+ }
+ };
+ Self {
+ dbus,
+ fallback: RofiPrompter,
+ }
+ }
+
+ async fn try_dbus() -> anyhow::Result<DbusPrompterProxy<'static>> {
+ let conn = zbus::Connection::session().await?;
+ let dbus = DBusProxy::new(&conn).await?;
+ let name = BusName::try_from(BUS_NAME)?;
+ if !dbus.name_has_owner(name).await? {
+ bail!("{BUS_NAME} not registered on session bus");
+ }
+ let proxy = DbusPrompterProxy::builder(&conn)
+ .destination(BUS_NAME)?
+ .path(PROMPTER_PATH)?
+ .build()
+ .await?;
+ Ok(proxy)
+ }
+}
+
+impl Prompter for AutoPrompter {
+ async fn prompt_enum(
+ &self,
+ prompt: &str,
+ description: &str,
+ variants: &[&str],
+ source: &[Source],
+ ) -> Result<u32> {
+ if let Some(dbus) = &self.dbus {
+ return Prompter::prompt_enum(dbus, prompt, description, variants, source).await;
+ }
+ self.fallback
+ .prompt_enum(prompt, description, variants, source)
+ .await
+ }
+
+ async fn prompt_text(
+ &self,
+ echo: bool,
+ prompt: &str,
+ description: &str,
+ source: &[Source],
+ ) -> Result<String> {
+ if let Some(dbus) = &self.dbus {
+ return Prompter::prompt_text(dbus, echo, prompt, description, source).await;
+ }
+ self.fallback
+ .prompt_text(echo, prompt, description, source)
+ .await
+ }
+
+ async fn display_text(&self, error: bool, description: &str, source: &[Source]) -> Result<()> {
+ if let Some(dbus) = &self.dbus {
+ return Prompter::display_text(dbus, error, description, source).await;
+ }
+ self.fallback.display_text(error, description, source).await
+ }
+}
crates/remowt-ui-prompt/src/dbus.rsdiffbeforeafterboth--- a/crates/remowt-ui-prompt/src/dbus.rs
+++ b/crates/remowt-ui-prompt/src/dbus.rs
@@ -5,17 +5,25 @@
use crate::{BlockingPrompter, Result};
use crate::{Error, Prompter};
+pub const BUS_NAME: &str = "lach.RemowtAskpass";
+pub const PROMPTER_PATH: &str = "/lach/Askpass";
+
pub struct DbusPrompterInterface<P>(pub P);
#[interface(name = "lach.PolkitInputHandler")]
impl<P: Prompter + Send + Sync + 'static> DbusPrompterInterface<P> {
- async fn prompt_radio(
+ async fn prompt_enum(
&self,
prompt: &str,
description: &str,
+ variants: Vec<String>,
source: Vec<Source>,
- ) -> fdo::Result<bool> {
- Ok(self.0.prompt_radio(prompt, description, &source).await?)
+ ) -> fdo::Result<u32> {
+ let variants: Vec<&str> = variants.iter().map(|v| v.as_str()).collect();
+ Ok(self
+ .0
+ .prompt_enum(prompt, description, &variants, &source)
+ .await?)
}
async fn prompt_text(
&self,
crates/remowt-ui-prompt/src/lib.rsdiffbeforeafterboth--- a/crates/remowt-ui-prompt/src/lib.rs
+++ b/crates/remowt-ui-prompt/src/lib.rs
@@ -3,6 +3,7 @@
use std::future::Future;
use std::result;
+pub mod auto;
pub mod bifrost;
pub mod dbus;
pub mod rofi;