Tunal/crates/tunal-elevate/examples/helper_smoke.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

134 lines
4.6 KiB
Rust

//! Drives the helper as the normal user (no pkexec): `cargo run -p tunal-elevate --example
//! helper_smoke -- <scratch dir>`. The example re-runs itself as the helper.
use std::io::{Read, Write};
use std::ops::ControlFlow;
use std::path::PathBuf;
use std::sync::Arc;
use tunal_core::{Error, Location, Uri, WriteMode};
use tunal_elevate::protocol::{self, Reply, Request};
use tunal_elevate::{ElevatedLocal, Elevation, HELPER_ARG};
fn main() {
let arg = std::env::args().nth(1).expect("usage: helper_smoke <dir>");
if arg == HELPER_ARG {
tunal_elevate::serve().expect("serve");
return;
}
let dir = std::fs::canonicalize(PathBuf::from(arg)).expect("dir");
let exe = std::env::current_exe().expect("exe");
let at = |name: &str| Uri::from_path(&dir.join(name));
let helper = ElevatedLocal::spawn_unelevated(&exe).expect("launch");
helper.mkdir(&at("sub")).expect("mkdir");
let data: Vec<u8> = (0..700_000u32).map(|i| (i % 251) as u8).collect();
let mut w = helper
.open_write(&at("sub/a.bin"), WriteMode::CreateNew)
.expect("open_write");
w.write_all(&data).expect("write");
drop(w);
let mut back = Vec::new();
helper
.open_read(&at("sub/a.bin"))
.expect("open_read")
.read_to_end(&mut back)
.expect("read");
assert_eq!(back, data, "read back");
let mut steps = 0;
helper
.copy_file(
&at("sub/a.bin"),
&at("sub/b.bin"),
WriteMode::CreateNew,
|_| steps += 1,
)
.expect("copy");
assert_eq!(std::fs::read(dir.join("sub/b.bin")).expect("copied"), data);
assert_eq!(
helper.copy_file(
&at("sub/a.bin"),
&at("sub/b.bin"),
WriteMode::CreateNew,
|_| ()
),
Err(Error::Exists)
);
helper
.rename(&at("sub/b.bin"), &at("sub/c.bin"))
.expect("rename");
helper.symlink(&at("sub/link"), b"c.bin").expect("symlink");
let mut names = Vec::new();
helper
.list(&at("sub"), &mut |chunk| {
names.extend(chunk.into_iter().map(|e| (e.display_name, e.mime, e.size)));
ControlFlow::Continue(())
})
.expect("list");
names.sort();
println!("listed: {names:?}");
assert_eq!(names.len(), 3);
for name in ["sub/a.bin", "sub/c.bin", "sub/link", "sub"] {
helper.delete(&at(name)).expect("delete");
}
assert_eq!(helper.stat(&at("sub")), Err(Error::NotFound));
println!("copy, rename, link, list, delete ok ({steps} progress replies)");
// Relative paths are refused by the helper itself (raw request: `Uri` is always absolute).
let mut raw = std::process::Command::new(&exe)
.arg(HELPER_ARG)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.expect("raw helper");
let (mut input, mut output) = (raw.stdin.take().unwrap(), raw.stdout.take().unwrap());
protocol::send(
&mut input,
&Request::Hello {
version: protocol::VERSION,
},
)
.unwrap();
let hello: Option<Reply> = protocol::recv(&mut output).unwrap();
protocol::send(
&mut input,
&Request::Mkdir {
path: b"relative".to_vec(),
},
)
.unwrap();
let reply: Option<Reply> = protocol::recv(&mut output).unwrap();
println!("handshake: {hello:?}; relative mkdir: {reply:?}");
drop(input);
println!("raw helper after EOF: {}", raw.wait().unwrap());
// Elevation switches only the elevated thread to the helper.
let elevation = Arc::new(Elevation::with_launcher(move || {
ElevatedLocal::spawn_unelevated(&exe)
}));
elevation.elevate(std::thread::current().id());
elevation.mkdir(&at("via-switch")).expect("switch mkdir");
let other = elevation.clone();
let dir2 = at("from-other-thread");
std::thread::spawn(move || other.mkdir(&dir2).expect("local mkdir"))
.join()
.unwrap();
elevation
.write_file(
&at("via-switch/.directory"),
b"[Desktop Entry]\nIcon=folder\n",
)
.expect("write_file");
elevation.release(std::thread::current().id());
std::fs::remove_file(dir.join("via-switch/.directory")).expect("written");
std::fs::remove_dir(dir.join("via-switch")).expect("rm");
std::fs::remove_dir(dir.join("from-other-thread")).expect("rm");
// Dropping the backend closes stdin; the helper exits on EOF and is reaped.
drop(helper);
drop(elevation);
println!(
"helper exited on EOF; scratch dir empty: {}",
std::fs::read_dir(&dir).unwrap().next().is_none()
);
}