Tunal/crates/tunal-elevate/src/lib.rs
astar76 4920193095 S016: root operations through a pkexec helper
Helper mode tunal --elevated-helper over a framed stdin/stdout protocol,
pkexec launcher, ElevatedLocal backend, per-job-thread Elevation for the
job engine, Retry as administrator in the error dialog, polkit policy and
a helper smoke example.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 20:29:25 -06:00

158 lines
4.7 KiB
Rust

//! Root operations behind a password prompt: polkit's agent asks for the password
//! (Tunal never sees it) and `pkexec tunal --elevated-helper` runs the operations.
mod elevated;
mod helper;
pub mod protocol;
use std::collections::HashSet;
use std::io::{Read, Write};
use std::sync::{Arc, Mutex};
use std::thread::ThreadId;
use tunal_core::{
Capabilities, Entry, Error, FILE, ListSink, LocalLocation, Location, Result, Uri, Watch,
WatchCallback, WriteMode,
};
pub use elevated::{ElevatedLocal, HELPER_ARG};
pub use helper::serve;
/// Polkit action of the helper (`assets/polkit/<id>.policy`).
pub const POLICY_ID: &str = "org.tunal.Tunal.elevated-helper";
type Launcher = dyn Fn() -> Result<ElevatedLocal> + Send + Sync;
/// `file://` backend for the job engine: local, except on threads that were elevated,
/// whose calls go through one shared root helper (started on first use).
/// A job runs on one thread, so elevating its thread reruns the rest of that job as root.
pub struct Elevation {
threads: Mutex<HashSet<ThreadId>>,
helper: Mutex<Option<Arc<ElevatedLocal>>>,
launch: Box<Launcher>,
}
impl Default for Elevation {
fn default() -> Self {
Self::with_launcher(ElevatedLocal::start)
}
}
impl Elevation {
pub fn new() -> Self {
Self::default()
}
pub fn with_launcher(
launch: impl Fn() -> Result<ElevatedLocal> + Send + Sync + 'static,
) -> Self {
Self {
threads: Mutex::default(),
helper: Mutex::default(),
launch: Box::new(launch),
}
}
/// Later calls from `thread` run as root.
pub fn elevate(&self, thread: ThreadId) {
self.threads.lock().unwrap().insert(thread);
}
/// `thread` is back to local calls; the helper stops when no thread is elevated.
pub fn release(&self, thread: ThreadId) {
let mut threads = self.threads.lock().unwrap();
if threads.remove(&thread) && threads.is_empty() {
self.helper.lock().unwrap().take();
}
}
/// Writes a whole file as root (e.g. a `.directory` in a folder the user can't write).
/// Blocks while the password prompt is open.
pub fn write_file(&self, uri: &Uri, data: &[u8]) -> Result<()> {
let helper = self.helper()?;
let result = helper
.open_write(uri, WriteMode::Overwrite)
.and_then(|mut w| w.write_all(data).map_err(Error::from));
if self.threads.lock().unwrap().is_empty() {
self.helper.lock().unwrap().take();
}
result
}
fn helper(&self) -> Result<Arc<ElevatedLocal>> {
let mut helper = self.helper.lock().unwrap();
if let Some(h) = helper.as_ref() {
return Ok(h.clone());
}
let started = Arc::new((self.launch)()?);
*helper = Some(started.clone());
Ok(started)
}
/// Runs `op` on the helper when this thread is elevated, else locally. A failed
/// launch (prompt cancelled) drops the elevation so the next retry asks again.
fn on<T>(&self, op: impl FnOnce(&dyn Location) -> Result<T>) -> Result<T> {
let me = std::thread::current().id();
if !self.threads.lock().unwrap().contains(&me) {
return op(&LocalLocation);
}
match self.helper() {
Ok(helper) => op(&*helper),
Err(e) => {
self.release(me);
Err(e)
}
}
}
}
impl Location for Elevation {
fn scheme(&self) -> &str {
FILE
}
fn capabilities(&self) -> Capabilities {
LocalLocation.capabilities()
}
fn list(&self, dir: &Uri, sink: &mut ListSink<'_>) -> Result<()> {
self.on(|b| b.list(dir, sink))
}
fn stat(&self, uri: &Uri) -> Result<Entry> {
self.on(|b| b.stat(uri))
}
fn open_read(&self, uri: &Uri) -> Result<Box<dyn Read + Send>> {
self.on(|b| b.open_read(uri))
}
fn open_write(&self, uri: &Uri, mode: WriteMode) -> Result<Box<dyn Write + Send>> {
self.on(|b| b.open_write(uri, mode))
}
fn mkdir(&self, uri: &Uri) -> Result<()> {
self.on(|b| b.mkdir(uri))
}
fn rename(&self, from: &Uri, to: &Uri) -> Result<()> {
self.on(|b| b.rename(from, to))
}
fn delete(&self, uri: &Uri) -> Result<()> {
self.on(|b| b.delete(uri))
}
/// Unsupported when elevated: root would trash into its own home.
fn trash(&self, uri: &Uri) -> Result<()> {
self.on(|b| b.trash(uri))
}
fn symlink(&self, link: &Uri, target: &[u8]) -> Result<()> {
self.on(|b| b.symlink(link, target))
}
fn watch(&self, dir: &Uri, callback: WatchCallback) -> Result<Watch> {
LocalLocation.watch(dir, callback)
}
}