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

difftreelog

feat functional polkit prompt

pvnwrxrnYaroslav Bolyukin2024-08-06parent: #2499daa.patch.diff
in: trunk

7 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -883,6 +883,7 @@
 name = "polkit-shared"
 version = "0.1.0"
 dependencies = [
+ "nix",
  "serde",
  "zbus",
 ]
modifiedcmds/polkit-backend/src/main.rsdiffbeforeafterboth
--- a/cmds/polkit-backend/src/main.rs
+++ b/cmds/polkit-backend/src/main.rs
@@ -45,7 +45,7 @@
             .prompt_text(
                 echo,
                 &prompt.to_string_lossy(),
-                "Polkit prompt request",
+                "PAM prompt request",
                 &[],
             )
             .map_err(|e| {
@@ -81,7 +81,7 @@
         let prompt = prompt.to_string_lossy();
         let result = self
             .0
-            .prompt_radio(&prompt, "Polkit prompt request", &[])
+            .prompt_radio(&prompt, "PAM prompt request", &[])
             .map_err(|_| ErrorCode::CONV_ERR)?;
         Ok(result)
     }
modifiedcmds/remowt-agent/src/main.rsdiffbeforeafterboth
--- a/cmds/remowt-agent/src/main.rs
+++ b/cmds/remowt-agent/src/main.rs
@@ -1,19 +1,20 @@
-use std::collections::HashMap;
+use std::borrow::Cow;
+use std::collections::{BTreeMap, HashMap};
 use std::io::{stdout, Write};
 use std::marker::PhantomData;
 use std::sync::{Mutex, RwLock};
 use std::{future, process};
 
 use clap::Parser;
-use polkit_shared::{BackendRequest, Identity};
+use polkit_shared::{emphasize, BackendRequest, Identity, PidDisplay};
 use tokio::runtime::Handle;
 use tokio::task::{AbortHandle, JoinHandle, LocalSet};
 use tracing::trace;
 use ui_prompt::dbus::DbusPrompterInterface;
 use ui_prompt::rofi::RofiPrompter;
-use ui_prompt::Prompter;
+use ui_prompt::{PrependSourcePrompter, Prompter, Source};
 use zbus::zvariant::{OwnedValue, Str};
-use zbus::ObjectServer;
+use zbus::{fdo, ObjectServer};
 use zbus::{interface, proxy, Connection};
 use zbus_polkit::policykit1::Subject;
 
@@ -81,10 +82,11 @@
         action_id: String,
         message: String,
         icon_name: String,
-        details: HashMap<String, String>,
+        mut details: BTreeMap<String, String>,
         cookie: String,
         identities: Vec<Identity>,
     ) -> zbus::fdo::Result<()> {
+        use std::fmt::Write;
         trace!("begin auth");
         let task = {
             let connection = self.connection.clone();
@@ -92,7 +94,61 @@
             let cookie = cookie.clone();
             tokio::task::spawn(async move {
                 trace!("conversation task");
-                let prompter = TemporaryPrompterInterface::new(connection, RofiPrompter).await;
+                let mut description = format!("{message}\n\n<b>Action id:</b> {action_id}",);
+                if let Some(subject) = details.remove("polkit.caller-pid") {
+                    let _ = write!(description, "\n<b>Caller:</b> ");
+                    if let Ok(pid) = subject.parse::<u32>() {
+                        let _ = write!(description, "{}", PidDisplay(pid));
+                    } else {
+                        let _ = write!(description, "{}", emphasize("invalid pid"));
+                    }
+                }
+                if let Some(subject) = details.remove("polkit.subject-pid") {
+                    let _ = write!(description, "\n<b>Subject:</b> ");
+                    if let Ok(pid) = subject.parse::<u32>() {
+                        let _ = write!(description, "{}", PidDisplay(pid));
+                    } else {
+                        let _ = write!(description, "{}", emphasize("invalid pid"));
+                    }
+                }
+                let mut prompter = PrependSourcePrompter {
+                    source: vec![Source(Cow::Borrowed("polkit agent"))],
+                    description: description.clone(),
+                    prompter: RofiPrompter,
+                };
+
+                let identity_displays: Vec<String> =
+                    identities.iter().map(|v| v.to_string()).collect();
+                let identity_displays: Vec<&str> =
+                    identity_displays.iter().map(|v| v.as_str()).collect();
+                let choosen_identity = match identity_displays.len() {
+                    0 => {
+                        return Err(fdo::Error::AuthFailed(
+                            "no identity to authenticate as".to_owned(),
+                        ))
+                    }
+                    1 => 0,
+                    _ => {
+                        prompter
+                            .prompt_enum(
+                                "Identity",
+                                "Select identity to use for polkit authorization",
+                                &identity_displays,
+                                &[],
+                            )
+                            .await?
+                    }
+                };
+
+                let _ = write!(
+                    description,
+                    "\n<b>Identity:</b> {}",
+                    identities[choosen_identity as usize]
+                );
+                prompter.description = description;
+
+                prompter.source.push(Source(Cow::Borrowed("polkit daemon")));
+                let prompter = TemporaryPrompterInterface::new(connection, prompter).await;
                 helper
                     .init_conversation(
                         BackendRequest {
@@ -100,7 +156,7 @@
                             environment: HashMap::new(),
                             prompter_path: prompter.path.clone(),
                             // TODO: Let user choose
-                            identity: identities.get(0).expect("first always exists").clone(),
+                            identity: identities[choosen_identity as usize].clone(),
                         }, // cookie.to_owned(), HashMap::new(), prompter.path.clone()
                     )
                     .await?;
@@ -135,7 +191,7 @@
     }
 }
 
-const OBJ_PATH: &str = "/0lach/polkitAgent";
+const OBJ_PATH: &str = "/org/freedesktop/PolicyKit1/AuthenticationAgent";
 
 #[proxy(
     interface = "lach.PolkitHelper",
modifiedcrates/polkit-shared/Cargo.tomldiffbeforeafterboth
--- a/crates/polkit-shared/Cargo.toml
+++ b/crates/polkit-shared/Cargo.toml
@@ -4,5 +4,6 @@
 edition = "2021"
 
 [dependencies]
+nix = "0.29.0"
 serde = { version = "1.0.204", features = ["derive"] }
 zbus = "4.4.0"
modifiedcrates/polkit-shared/src/lib.rsdiffbeforeafterboth
--- a/crates/polkit-shared/src/lib.rs
+++ b/crates/polkit-shared/src/lib.rs
@@ -1,14 +1,83 @@
 use std::collections::HashMap;
+use std::{fmt, fs};
 
+use nix::unistd::{Uid, User};
 use serde::{Deserialize, Serialize};
-use zbus::zvariant::{OwnedValue, Type};
+use zbus::zvariant::{OwnedValue, Type, Value};
+
+pub fn emphasize(s: impl AsRef<str>) -> String {
+    format!("<span style=\"italic\">&lt;{}&gt;</span>", escape(s),)
+}
+fn command(s: impl AsRef<str>) -> String {
+    format!("<u><tt>{}</tt></u>", s.as_ref())
+}
+fn escape(s: impl AsRef<str>) -> String {
+    s.as_ref()
+        .replace("&", "&quot;")
+        .replace("<", "&lt;")
+        .replace(">", "&gt;")
+}
 
+pub struct PidDisplay(pub u32);
+impl fmt::Display for PidDisplay {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        if self.0 == 1 {
+            emphasize("init").fmt(f)
+        } else if let Ok(proc) = fs::read_to_string(format!("/proc/{}/cmdline", self.0)) {
+            write!(
+                f,
+                "<sub>command</sub>{}",
+                command(
+                    proc.replace("\0", " ")
+                        .strip_suffix(" ")
+                        .expect("cmdline should end with NUL")
+                )
+            )
+        } else if let Ok(proc) = fs::read_to_string(format!("/proc/{}/comm", self.0)) {
+            write!(f, "<sub>process</sub>{}", command(proc.replace("\0", " ")))
+        } else {
+            emphasize("unknown process").fmt(f)
+        }
+    }
+}
+
 #[derive(Serialize, Deserialize, Type, PartialEq, Debug)]
 pub struct Identity {
     pub kind: String,
     pub details: HashMap<String, OwnedValue>,
 }
 
+impl fmt::Display for Identity {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self.kind.as_str() {
+            "unix-user" => match self.details.get("uid").map(|v| &**v) {
+                Some(Value::U32(uid)) => match User::from_uid(Uid::from_raw(*uid)) {
+                    Ok(Some(u)) => write!(
+                        f,
+                        "<sub>user</sub>{}<sup>{}</sup>{}",
+                        u.name,
+                        u.uid,
+                        if u.gecos.is_empty() {
+                            "".to_owned()
+                        } else {
+                            format!(": {}", escape(u.gecos.to_string_lossy()))
+                        }
+                    ),
+                    Ok(None) => emphasize("not found").fmt(f),
+                    Err(e) => {
+                        let user = format!("could not get user: {e}");
+                        emphasize(&user).fmt(f)?;
+                        Ok(())
+                    }
+                },
+
+                _ => emphasize("unknown uid").fmt(f),
+            },
+            _ => emphasize(format!("identity of unknown kind: {}", self.kind)).fmt(f),
+        }
+    }
+}
+
 impl Clone for Identity {
     fn clone(&self) -> Self {
         Self {
modifiedcrates/ui-prompt/src/lib.rsdiffbeforeafterboth
before · crates/ui-prompt/src/lib.rs
1use core::fmt;2use std::borrow::Cow;3use std::future::Future;4use std::result;56pub mod dbus;7pub mod rofi;89#[derive(thiserror::Error, Debug)]10pub enum Error {11    #[error("user has cancelled input")]12    Cancel,13    #[error("input error: {0}")]14    InputError(String),15}1617pub type Result<T, E = Error> = result::Result<T, E>;1819#[cfg_attr(feature = "dbus", derive(zbus::zvariant::Type))]20#[derive(serde::Serialize, serde::Deserialize, Clone)]21pub struct Source(Cow<'static, str>);22impl fmt::Display for Source {23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {24        write!(f, "<u>{}</u>", self.0)25    }26}2728pub trait Prompter {29    fn prompt_radio(30        &self,31        prompt: &str,32        description: &str,33        source: &[Source],34    ) -> impl Future<Output = Result<bool>> + Send {35        let fut = self.prompt_enum(prompt, description, &["No", "Yes"], source);36        async { fut.await.map(|v| v == 1) }37    }38    fn prompt_enum(39        &self,40        prompt: &str,41        description: &str,42        variants: &[&str],43        source: &[Source],44    ) -> impl Future<Output = Result<u32>> + Send;45    fn prompt_text(46        &self,47        echo: bool,48        prompt: &str,49        description: &str,50        source: &[Source],51    ) -> impl Future<Output = Result<String>> + Send;52    fn display_text(53        &self,54        error: bool,55        description: &str,56        source: &[Source],57    ) -> impl Future<Output = Result<()>> + Send;58}59pub trait BlockingPrompter {60    fn prompt_radio(&self, prompt: &str, description: &str, source: &[Source]) -> Result<bool> {61        self.prompt_enum(prompt, description, &["No", "Yes"], source)62            .map(|v| v == 1)63    }64    fn prompt_enum(65        &self,66        prompt: &str,67        description: &str,68        variants: &[&str],69        source: &[Source],70    ) -> Result<u32>;71    fn prompt_text(72        &self,73        echo: bool,74        prompt: &str,75        description: &str,76        source: &[Source],77    ) -> Result<String>;78    fn display_text(&self, error: bool, description: &str, source: &[Source]) -> Result<()>;79}8081pub struct PrependSourcePrompter<P> {82    prompter: P,83    source: Vec<Source>,84}85impl<P> PrependSourcePrompter<P> {86    fn source(&self, input: &[Source]) -> Vec<Source> {87        let mut out = self.source.clone();88        out.extend(input.iter().cloned());89        out90    }91}92impl<P> Prompter for PrependSourcePrompter<P>93where94    P: Prompter + Sync,95{96    async fn prompt_enum(97        &self,98        prompt: &str,99        description: &str,100        variants: &[&str],101        source: &[Source],102    ) -> Result<u32> {103        self.prompter104            .prompt_enum(prompt, description, variants, &self.source(source))105            .await106    }107108    async fn prompt_text(109        &self,110        echo: bool,111        prompt: &str,112        description: &str,113        source: &[Source],114    ) -> Result<String> {115        self.prompter116            .prompt_text(echo, prompt, description, &self.source(source))117            .await118    }119120    async fn display_text(&self, error: bool, description: &str, source: &[Source]) -> Result<()> {121        self.prompter122            .display_text(error, description, &self.source(source))123            .await124    }125}
modifiedcrates/ui-prompt/src/rofi.rsdiffbeforeafterboth
--- a/crates/ui-prompt/src/rofi.rs
+++ b/crates/ui-prompt/src/rofi.rs
@@ -27,7 +27,10 @@
             description.to_owned()
         } else {
             let mut out = format!("{description}\n\n<b>Requested on ",);
-            for s in source.iter() {
+            for (i, s) in source.iter().enumerate() {
+                if i != 0 {
+                    out.push_str(" -> ");
+                }
                 out.push_str(&s.to_string());
             }
             out.push_str("</b>");
@@ -43,6 +46,7 @@
             fixup_prompt(prompt),
             "-format",
             "i",
+            "-markup-rows",
         ]);
         cmd.stdin(Stdio::piped());
         cmd.stdout(Stdio::piped());
@@ -100,7 +104,10 @@
             description.to_owned()
         } else {
             let mut out = format!("{description}\n\n<b>Requested on ",);
-            for s in source.iter() {
+            for (i, s) in source.iter().enumerate() {
+                if i != 0 {
+                    out.push_str(" -> ");
+                }
                 out.push_str(&s.to_string());
             }
             out.push_str("</b>");