Skip to main content

tilo_process_services/
action_authority.rs

1//! Bounded read-only action policy transport. Consumers validate the typed
2//! binding and policy; this service never interprets a caller's owner claim.
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5
6pub type AuthoritySource = Arc<dyn Fn() -> Result<Option<Vec<u8>>, String> + Send + Sync>;
7
8/// Read the namespace the trusted process selected. Native I/O stays in
9/// the process service; the portable toolkit consumes only bounded bytes. A
10/// policy the process no longer holds (it exited, or could not replace it) is
11/// read as absent: its admission ends with the process, without a lifetime.
12pub fn source(path: PathBuf, max_bytes: usize) -> AuthoritySource {
13    #[cfg(feature = "native")]
14    {
15        Arc::new(move || read_held(&path, max_bytes))
16    }
17    #[cfg(not(feature = "native"))]
18    {
19        let _ = (path, max_bytes);
20        Arc::new(|| Ok(None))
21    }
22}
23
24/// A watch on what a [`source`] reads; dropping it ends the calls.
25pub type AuthorityWatch = Box<dyn std::any::Any + Send>;
26
27/// Call `changed` whenever what [`source`] reads at `path` may have changed:
28/// the process published another policy over it, removed it, or let go of it.
29/// Letting go needs no help from the process: when its hold (the writable
30/// descriptor the file was published through) closes, on exit or a crash
31/// as much as on a withdrawal, the kernel reports that close.
32pub fn watch(path: &Path, changed: impl Fn() + Send + 'static) -> Result<AuthorityWatch, String> {
33    #[cfg(feature = "native")]
34    {
35        let directory = path.parent().ok_or("action policy has no directory")?;
36        let name = path.to_owned();
37        // A watch that hears the hold end as well as each publication over it: the
38        // policy is current only while the process holds the file, and that ends when its
39        // descriptor closes, which leaves the name and its bytes as they were.
40        tilo_files::native::Watcher::entries(directory)
41            .released()
42            .on_change(move |entry| entry == name, changed)
43            .map(|watch| Box::new(watch) as AuthorityWatch)
44            .map_err(|error| format!("action policy cannot be watched: {error}"))
45    }
46    #[cfg(not(feature = "native"))]
47    {
48        let _ = (path, changed);
49        Ok(Box::new(()))
50    }
51}
52
53#[cfg(feature = "native")]
54fn read_held(path: &std::path::Path, max_bytes: usize) -> Result<Option<Vec<u8>>, String> {
55    tilo_files::native::held::read(path, max_bytes).map_err(|error| match error.kind() {
56        std::io::ErrorKind::FileTooLarge => "action policy exceeds its byte bound".into(),
57        std::io::ErrorKind::InvalidInput => "action policy bound is invalid".into(),
58        _ => "action policy is unavailable".into(),
59    })
60}
61
62#[cfg(all(test, feature = "native"))]
63mod tests {
64    #[test]
65    fn a_policy_is_read_only_while_the_host_holds_it() {
66        let unique = tilo_clock::try_unix_now_ns().unwrap();
67        let root = std::env::temp_dir().join(format!(
68            "tilo-process-authority-{}-{unique}",
69            std::process::id()
70        ));
71        std::fs::create_dir(&root).unwrap();
72        let path = root.join("current.json");
73        let source = super::source(path.clone(), 64);
74        assert_eq!(source().unwrap(), None);
75        let held = tilo_files::native::held::publish(&path, b"policy", 0o600).unwrap();
76        assert_eq!(source().unwrap().as_deref(), Some(&b"policy"[..]));
77        // Nothing renews it: it stays current until the process lets go.
78        assert_eq!(source().unwrap().as_deref(), Some(&b"policy"[..]));
79        drop(held);
80        assert_eq!(
81            source().unwrap(),
82            None,
83            "a process that let go vouches for nothing"
84        );
85        std::fs::remove_dir_all(&root).unwrap();
86    }
87
88    #[test]
89    fn a_watch_hears_each_publication_and_the_host_letting_go() {
90        use std::sync::mpsc;
91        use std::time::Duration;
92        let unique = tilo_clock::try_unix_now_ns().unwrap();
93        let root = std::env::temp_dir().join(format!(
94            "tilo-process-authority-watch-{}-{unique}",
95            std::process::id()
96        ));
97        std::fs::create_dir(&root).unwrap();
98        let path = root.join("current.json");
99        let (told, heard) = mpsc::channel();
100        let _watch = super::watch(&path, move || {
101            let _ = told.send(());
102        })
103        .unwrap();
104        let source = super::source(path.clone(), 64);
105        // A loaded test machine may take this long to report a change.
106        let report = Duration::from_secs(10);
107        let settle = |heard: &mpsc::Receiver<()>| {
108            heard.recv_timeout(report).expect("the change was reported");
109            while heard.recv_timeout(Duration::from_millis(100)).is_ok() {}
110        };
111        let first = tilo_files::native::held::publish(&path, b"first", 0o600).unwrap();
112        settle(&heard);
113        let second = tilo_files::native::held::publish(&path, b"second", 0o600).unwrap();
114        drop(first);
115        settle(&heard);
116        assert_eq!(source().unwrap().as_deref(), Some(&b"second"[..]));
117        // Reading the policy is no change.
118        assert!(heard.recv_timeout(Duration::from_millis(300)).is_err());
119        drop(second);
120        settle(&heard);
121        assert_eq!(source().unwrap(), None);
122        std::fs::remove_dir_all(&root).unwrap();
123    }
124}