difftreelog
feat functional polkit prompt
in: trunk
7 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -883,6 +883,7 @@
name = "polkit-shared"
version = "0.1.0"
dependencies = [
+ "nix",
"serde",
"zbus",
]
cmds/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)
}
cmds/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",
crates/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"
crates/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\"><{}></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("&", """)
+ .replace("<", "<")
+ .replace(">", ">")
+}
+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 {
crates/ui-prompt/src/lib.rsdiffbeforeafterboth--- a/crates/ui-prompt/src/lib.rs
+++ b/crates/ui-prompt/src/lib.rs
@@ -18,7 +18,7 @@
#[cfg_attr(feature = "dbus", derive(zbus::zvariant::Type))]
#[derive(serde::Serialize, serde::Deserialize, Clone)]
-pub struct Source(Cow<'static, str>);
+pub struct Source(pub Cow<'static, str>);
impl fmt::Display for Source {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "<u>{}</u>", self.0)
@@ -79,8 +79,9 @@
}
pub struct PrependSourcePrompter<P> {
- prompter: P,
- source: Vec<Source>,
+ pub prompter: P,
+ pub source: Vec<Source>,
+ pub description: String,
}
impl<P> PrependSourcePrompter<P> {
fn source(&self, input: &[Source]) -> Vec<Source> {
@@ -88,11 +89,31 @@
out.extend(input.iter().cloned());
out
}
+ fn description(&self, input: &str) -> String {
+ if self.description.is_empty() {
+ input.to_owned()
+ } else if input.is_empty() {
+ self.description.to_owned()
+ } else {
+ format!("{input}\n\n{}", self.description)
+ }
+ }
}
impl<P> Prompter for PrependSourcePrompter<P>
where
P: Prompter + Sync,
{
+ async fn prompt_radio(
+ &self,
+ prompt: &str,
+ description: &str,
+ source: &[Source],
+ ) -> Result<bool> {
+ self.prompter
+ .prompt_radio(prompt, &self.description(description), &self.source(source))
+ .await
+ }
+
async fn prompt_enum(
&self,
prompt: &str,
@@ -101,7 +122,12 @@
source: &[Source],
) -> Result<u32> {
self.prompter
- .prompt_enum(prompt, description, variants, &self.source(source))
+ .prompt_enum(
+ prompt,
+ dbg!(&self.description(description)),
+ variants,
+ &self.source(source),
+ )
.await
}
@@ -113,13 +139,18 @@
source: &[Source],
) -> Result<String> {
self.prompter
- .prompt_text(echo, prompt, description, &self.source(source))
+ .prompt_text(
+ echo,
+ prompt,
+ &self.description(description),
+ &self.source(source),
+ )
.await
}
async fn display_text(&self, error: bool, description: &str, source: &[Source]) -> Result<()> {
self.prompter
- .display_text(error, description, &self.source(source))
+ .display_text(error, &self.description(description), &self.source(source))
.await
}
}
crates/ui-prompt/src/rofi.rsdiffbeforeafterboth1use std::process::Stdio;23use tokio::io::AsyncWriteExt;4use tokio::process::Command;5use tracing::trace;67use crate::{Error, Prompter, Result, Source};89pub struct RofiPrompter;1011fn fixup_prompt(prompt: &str) -> &str {12 // Rofi always appends such suffix13 prompt.strip_suffix(": ").unwrap_or(prompt)14}1516impl Prompter for RofiPrompter {17 async fn prompt_enum(18 &self,19 prompt: &str,20 description: &str,21 variants: &[&str],22 source: &[Source],23 ) -> Result<u32> {24 trace!("rofi radio");25 let mut cmd = Command::new("rofi");26 let mesg = if source.is_empty() {27 description.to_owned()28 } else {29 let mut out = format!("{description}\n\n<b>Requested on ",);30 for s in source.iter() {31 out.push_str(&s.to_string());32 }33 out.push_str("</b>");34 out35 };36 cmd.args([37 "-dmenu",38 "-mesg",39 &mesg,40 "-sync",41 "-only-match",42 "-p",43 fixup_prompt(prompt),44 "-format",45 "i",46 ]);47 cmd.stdin(Stdio::piped());48 cmd.stdout(Stdio::piped());49 cmd.kill_on_drop(true);50 let mut child = cmd51 .spawn()52 .map_err(|e| Error::InputError(format!("failed to spawn rofi: {e}")))?;5354 let mut stdin = child.stdin.take().expect("stdin is piped");55 for var in variants {56 stdin57 .write_all(var.replace('\n', " ").as_bytes())58 .await59 .map_err(|e| Error::InputError(format!("failed to write rofi variants: {e}")))?;60 stdin61 .write_all(b"\n")62 .await63 .map_err(|e| Error::InputError(format!("failed to write rofi variants: {e}")))?;64 }65 // write_all already flushes, just to be sure.66 let _ = stdin.flush().await;67 drop(stdin);6869 let out = child70 .wait_with_output()71 .await72 .map_err(|e| Error::InputError(format!("failed to wait for rofi: {e}")))?;73 let stdout = out74 .stdout75 .strip_suffix(b"\n")76 .unwrap_or(&out.stdout)77 .to_owned();7879 let id: u32 = String::from_utf8(stdout)80 .map_err(|e| Error::InputError(format!("rofi produced invalid output: {e}")))?81 .parse()82 .map_err(|e| Error::InputError(format!("rofi produced invalid output: {e}")))?;83 if id as usize >= variants.len() {84 return Err(Error::InputError("invalid rofi response".to_owned()));85 }8687 Ok(id)88 }8990 async fn prompt_text(91 &self,92 echo: bool,93 prompt: &str,94 description: &str,95 source: &[Source],96 ) -> Result<String> {97 trace!("rofi text");98 let mut cmd = Command::new("rofi");99 let mesg = if source.is_empty() {100 description.to_owned()101 } else {102 let mut out = format!("{description}\n\n<b>Requested on ",);103 for s in source.iter() {104 out.push_str(&s.to_string());105 }106 out.push_str("</b>");107 out108 };109 cmd.args(["-dmenu", "-mesg", &mesg, "-p", fixup_prompt(prompt)]);110 if !echo {111 cmd.arg("-password");112 }113 cmd.stdin(Stdio::null());114 cmd.stdout(Stdio::piped());115 cmd.kill_on_drop(true);116 let child = cmd117 .spawn()118 .map_err(|e| Error::InputError(format!("failed to spawn rofi: {e}")))?;119120 let out = child121 .wait_with_output()122 .await123 .map_err(|e| Error::InputError(format!("failed to wait for rofi: {e}")))?;124 let stdout = out125 .stdout126 .strip_suffix(b"\n")127 .unwrap_or(&out.stdout)128 .to_owned();129130 Ok(String::from_utf8_lossy(&stdout).to_string())131 }132133 async fn display_text(&self, error: bool, description: &str, source: &[Source]) -> Result<()> {134 trace!("rofi display");135 let mut cmd = Command::new("rofi");136 let mut mesg = if source.is_empty() {137 description.to_owned()138 } else {139 let mut out = format!("{description}\n\n<b>Coming from ",);140 for s in source.iter() {141 out.push_str(&s.to_string());142 }143 out.push_str("</b>");144 out145 };146 if error {147 mesg.insert_str(0, "<span color=\"red\">");148 mesg.push_str("</span>");149 }150 cmd.args(["-e", &mesg, "-markup"]);151 cmd.stdin(Stdio::null());152 cmd.stdout(Stdio::null());153 cmd.kill_on_drop(true);154 let mut child = cmd155 .spawn()156 .map_err(|e| Error::InputError(format!("failed to spawn rofi: {e}")))?;157158 child159 .wait()160 .await161 .map_err(|e| Error::InputError(format!("failed to wait for rofi: {e}")))?;162163 Ok(())164 }165}166167#[cfg(test)]168mod tests {169 use std::borrow::Cow;170171 use crate::rofi::RofiPrompter;172 use crate::{PrependSourcePrompter, Prompter as _, Source};173174 #[tokio::test]175 async fn test() {176 let prompter = PrependSourcePrompter {177 prompter: RofiPrompter,178 source: vec![Source(Cow::Borrowed("ssh"))],179 };180 prompter181 .prompt_radio("Enable", "Polkit needs access", &[])182 .await183 .expect("rofi");184 prompter185 .prompt_text(false, "Password", "Polkit needs access", &[])186 .await187 .expect("rofi");188 prompter189 .display_text(true, "Polkit needs access", &[])190 .await191 .expect("rofi");192 }193}