Tunal/crates/tunal-elevate/tests/helper.rs
astar76 35715817aa S032: tests for core, ops, trash, dirmeta and the elevation protocol
Fixes: file over folder with Overwrite, CRLF .directory files, stray blank line
after removing an added group.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-19 01:00:47 -06:00

343 lines
11 KiB
Rust

//! The root helper driven as the normal user (no pkexec): the `helper_smoke` example doubles
//! as the helper binary (`<exe> --elevated-helper`).
use std::io::{Read, Write};
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
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};
/// `target/<profile>/examples/helper_smoke`, built by `cargo test` before the tests run.
fn helper_exe() -> PathBuf {
let mut dir = std::env::current_exe().unwrap();
dir.pop();
if dir.ends_with("deps") {
dir.pop();
}
let exe = dir.join("examples/helper_smoke");
assert!(
exe.exists(),
"{} is missing: run through `cargo test`",
exe.display()
);
exe
}
fn at(dir: &Path, name: &str) -> Uri {
Uri::from_path(&dir.join(name))
}
fn start() -> ElevatedLocal {
ElevatedLocal::spawn_unelevated(&helper_exe()).expect("launch helper")
}
struct Raw {
child: std::process::Child,
input: Option<std::process::ChildStdin>,
output: std::process::ChildStdout,
}
impl Raw {
fn new() -> Self {
let mut child = Command::new(helper_exe())
.arg(HELPER_ARG)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
Self {
input: child.stdin.take(),
output: child.stdout.take().unwrap(),
child,
}
}
fn call(&mut self, request: &Request) -> Reply {
protocol::send(self.input.as_mut().unwrap(), request).unwrap();
protocol::recv::<Reply>(&mut self.output)
.unwrap()
.expect("reply")
}
fn hello(&mut self) {
let reply = self.call(&Request::Hello {
version: protocol::VERSION,
});
assert!(matches!(reply, Reply::Hello { version } if version == protocol::VERSION));
}
/// Closes stdin and waits for the helper to exit.
fn finish(mut self) -> std::process::ExitStatus {
drop(self.input.take());
self.child.wait().unwrap()
}
}
#[test]
fn file_operations_through_the_helper() {
let dir = tempfile::tempdir().unwrap();
let d = dir.path();
let helper = start();
helper.mkdir(&at(d, "sub")).unwrap();
assert_eq!(helper.mkdir(&at(d, "sub")), Err(Error::Exists));
let data: Vec<u8> = (0..700_000u32).map(|i| (i % 251) as u8).collect();
let mut w = helper
.open_write(&at(d, "sub/a.bin"), WriteMode::CreateNew)
.unwrap();
w.write_all(&data).unwrap();
drop(w);
assert_eq!(std::fs::read(d.join("sub/a.bin")).unwrap(), data);
assert!(matches!(
helper.open_write(&at(d, "sub/a.bin"), WriteMode::CreateNew),
Err(Error::Exists)
));
let mut back = Vec::new();
helper
.open_read(&at(d, "sub/a.bin"))
.unwrap()
.read_to_end(&mut back)
.unwrap();
assert_eq!(back, data);
let mut steps = 0;
helper
.copy_file(
&at(d, "sub/a.bin"),
&at(d, "sub/b.bin"),
WriteMode::CreateNew,
|_| steps += 1,
)
.unwrap();
assert_eq!(std::fs::read(d.join("sub/b.bin")).unwrap(), data);
assert_eq!(
helper.copy_file(
&at(d, "sub/a.bin"),
&at(d, "sub/b.bin"),
WriteMode::CreateNew,
|_| ()
),
Err(Error::Exists)
);
helper
.copy_file(
&at(d, "sub/a.bin"),
&at(d, "sub/b.bin"),
WriteMode::Overwrite,
|_| (),
)
.unwrap();
helper
.rename(&at(d, "sub/b.bin"), &at(d, "sub/c.bin"))
.unwrap();
helper.symlink(&at(d, "sub/link"), b"c.bin").unwrap();
assert_eq!(
std::fs::read_link(d.join("sub/link")).unwrap(),
Path::new("c.bin")
);
let mut listed = Vec::new();
helper
.list(&at(d, "sub"), &mut |chunk| {
listed.extend(chunk.into_iter().map(|e| (e.display_name, e.size)));
ControlFlow::Continue(())
})
.unwrap();
listed.sort();
assert_eq!(
listed,
[
("a.bin".to_string(), 700_000),
("c.bin".to_string(), 700_000),
("link".to_string(), 5)
]
);
assert_eq!(helper.stat(&at(d, "sub/a.bin")).unwrap().size, 700_000);
for name in ["sub/a.bin", "sub/c.bin", "sub/link", "sub"] {
helper.delete(&at(d, name)).unwrap();
}
assert_eq!(helper.stat(&at(d, "sub")), Err(Error::NotFound));
assert_eq!(helper.delete(&at(d, "sub")), Err(Error::NotFound));
assert!(std::fs::read_dir(d).unwrap().next().is_none());
}
#[test]
fn errors_cross_the_pipe_as_the_same_kind() {
let dir = tempfile::tempdir().unwrap();
let helper = start();
let missing = at(dir.path(), "nope/deeper");
assert_eq!(helper.stat(&missing), Err(Error::NotFound));
assert!(matches!(helper.open_read(&missing), Err(Error::NotFound)));
assert_eq!(helper.mkdir(&missing), Err(Error::NotFound));
let mut seen = 0;
let result = helper.list(&missing, &mut |_| {
seen += 1;
ControlFlow::Continue(())
});
assert_eq!((result, seen), (Err(Error::NotFound), 0));
std::fs::create_dir_all(dir.path().join("full/x")).unwrap();
assert_eq!(helper.delete(&at(dir.path(), "full")), Err(Error::NotEmpty));
}
#[test]
fn the_helper_lists_big_folders_in_chunks() {
let dir = tempfile::tempdir().unwrap();
for i in 0..1000 {
std::fs::File::create(dir.path().join(format!("f{i}"))).unwrap();
}
let helper = start();
let (mut total, mut chunks) = (0, 0);
helper
.list(&Uri::from_path(dir.path()), &mut |chunk| {
total += chunk.len();
chunks += 1;
ControlFlow::Continue(())
})
.unwrap();
assert_eq!(total, 1000);
assert!(chunks >= 1);
}
#[test]
fn handshake_and_relative_paths() {
let mut raw = Raw::new();
raw.hello();
let reply = raw.call(&Request::Mkdir {
path: b"relative".to_vec(),
});
assert!(matches!(reply, Reply::Error(_)), "{reply:?}");
for bad in [b"/with\0nul".to_vec(), b"".to_vec()] {
let reply = raw.call(&Request::Stat { path: bad });
assert!(matches!(reply, Reply::Error(_)));
}
// Unknown handles are refused, not panics.
assert!(matches!(
raw.call(&Request::Close { handle: 99 }),
Reply::Error(_)
));
assert!(raw.finish().success());
}
#[test]
fn a_different_protocol_version_is_refused() {
let mut raw = Raw::new();
let reply = raw.call(&Request::Hello { version: 99 });
assert!(matches!(reply, Reply::Error(_)), "{reply:?}");
// The helper stops after refusing.
assert!(raw.finish().success());
}
#[test]
fn eof_before_the_handshake_ends_quietly() {
assert!(Raw::new().finish().success());
}
#[test]
fn helper_exits_when_the_client_is_dropped() {
let dir = tempfile::tempdir().unwrap();
let helper = start();
helper.mkdir(&at(dir.path(), "x")).unwrap();
// Dropping closes stdin; the Drop impl waits for the helper, so this must return.
drop(helper);
assert!(dir.path().join("x").is_dir());
}
#[test]
fn elevation_switches_only_the_elevated_thread() {
let dir = tempfile::tempdir().unwrap();
let d = dir.path().to_path_buf();
let exe = helper_exe();
let launches = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counted = launches.clone();
let elevation = Arc::new(Elevation::with_launcher(move || {
counted.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
ElevatedLocal::spawn_unelevated(&exe)
}));
let me = std::thread::current().id();
// Not elevated: local, no helper started.
elevation.mkdir(&at(&d, "plain")).unwrap();
assert_eq!(launches.load(std::sync::atomic::Ordering::Relaxed), 0);
elevation.elevate(me);
elevation.mkdir(&at(&d, "via-helper")).unwrap();
elevation.mkdir(&at(&d, "via-helper-2")).unwrap();
assert_eq!(
launches.load(std::sync::atomic::Ordering::Relaxed),
1,
"one shared helper"
);
let other = elevation.clone();
let target = at(&d, "other-thread");
std::thread::spawn(move || other.mkdir(&target).unwrap())
.join()
.unwrap();
assert_eq!(launches.load(std::sync::atomic::Ordering::Relaxed), 1);
elevation
.write_file(
&at(&d, "via-helper/.directory"),
b"[Desktop Entry]\nIcon=folder\n",
)
.unwrap();
assert_eq!(
std::fs::read_to_string(d.join("via-helper/.directory")).unwrap(),
"[Desktop Entry]\nIcon=folder\n"
);
// Released: the helper stops and the next call is local again.
elevation.release(me);
elevation.mkdir(&at(&d, "after")).unwrap();
assert_eq!(launches.load(std::sync::atomic::Ordering::Relaxed), 1);
for n in ["plain", "via-helper-2", "other-thread", "after"] {
assert!(d.join(n).is_dir(), "{n}");
}
}
#[test]
fn write_file_without_elevated_threads_starts_and_stops_a_helper() {
let dir = tempfile::tempdir().unwrap();
let exe = helper_exe();
let elevation = Elevation::with_launcher(move || ElevatedLocal::spawn_unelevated(&exe));
elevation.write_file(&at(dir.path(), "f"), b"data").unwrap();
assert_eq!(std::fs::read(dir.path().join("f")).unwrap(), b"data");
elevation.write_file(&at(dir.path(), "f"), b"new").unwrap();
assert_eq!(std::fs::read(dir.path().join("f")).unwrap(), b"new");
}
#[test]
fn a_cancelled_prompt_drops_the_elevation_so_the_next_try_asks_again() {
let dir = tempfile::tempdir().unwrap();
let exe = helper_exe();
let fail = Arc::new(std::sync::atomic::AtomicBool::new(true));
let flag = fail.clone();
let elevation = Elevation::with_launcher(move || {
if flag.load(std::sync::atomic::Ordering::Relaxed) {
Err(Error::Remote("password prompt cancelled".into()))
} else {
ElevatedLocal::spawn_unelevated(&exe)
}
});
elevation.elevate(std::thread::current().id());
assert_eq!(
elevation.mkdir(&at(dir.path(), "a")),
Err(Error::Remote("password prompt cancelled".into()))
);
// The thread is local again: this call must not need the helper at all.
elevation.mkdir(&at(dir.path(), "b")).unwrap();
assert!(dir.path().join("b").is_dir() && !dir.path().join("a").exists());
fail.store(false, std::sync::atomic::Ordering::Relaxed);
elevation.elevate(std::thread::current().id());
elevation.mkdir(&at(dir.path(), "c")).unwrap();
}
#[test]
fn a_missing_helper_program_is_a_clear_error() {
let result = ElevatedLocal::spawn_unelevated(Path::new("/nonexistent/tunal-helper"));
assert!(matches!(result, Err(Error::Remote(_))));
}