Skip to main content

troupekit_kit/
laws.rs

1use crate::error::KitError;
2use std::io::Read;
3use std::path::{Component, Path, PathBuf};
4use troupekit_trace::{trace, Trace};
5
6const MAX_LAW_FILE_BYTES: u64 = 1024 * 1024;
7const MAX_INLINE_LAW_BYTES: usize = 64 * 1024;
8const MAX_LAWS: usize = 64;
9
10/// The laws attached to an agent or graph, checked at `build`.
11/// 0.2 stores and validates them; no run proves them yet. `auto` asks
12/// the verifier to also derive laws from the code, and defaults to `true`.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct Laws {
15    paths: Vec<PathBuf>,
16    inline: Vec<String>,
17    auto: bool,
18}
19
20impl Laws {
21    /// Returns the law files, as absolute paths resolved at `build`.
22    /// Each is an existing `.bend` file of at most 1 MiB of UTF-8. Paths
23    /// are trusted host input: symlinks and any directory are allowed.
24    pub fn paths(&self) -> &[PathBuf] {
25        &self.paths
26    }
27
28    /// Returns the inline laws in the order they were added.
29    /// Each is non-blank, at most 64 KiB and free of NUL bytes.
30    /// The text is kept exactly as given.
31    pub fn inline(&self) -> &[String] {
32        &self.inline
33    }
34
35    /// Reports whether laws derived from the code are wanted.
36    /// Set with `.auto_laws(..)`; `true` unless turned off.
37    /// 0.2 records the choice only.
38    pub fn auto(&self) -> bool {
39        self.auto
40    }
41
42    pub(crate) fn check(
43        owner: &str,
44        paths: &[PathBuf],
45        inline: &[String],
46        auto: bool,
47    ) -> Result<Laws, KitError> {
48        let fail = |m: String| KitError::config(owner, m);
49        let total = paths.len() + inline.len();
50        if total > MAX_LAWS {
51            return Err(fail(format!("takes at most {MAX_LAWS} laws, got {total}")));
52        }
53        let mut resolved = Vec::with_capacity(paths.len());
54        for path in paths {
55            resolved.push(
56                read_checked(path, "bend", MAX_LAW_FILE_BYTES)
57                    .map(|(absolute, _)| absolute)
58                    .map_err(|m| fail(format!("law file `{}` {m}", path.display())))?,
59            );
60        }
61        for (i, law) in inline.iter().enumerate() {
62            let n = i + 1;
63            if law.trim().is_empty() {
64                return Err(fail(format!("inline law {n} is blank")));
65            }
66            if law.len() > MAX_INLINE_LAW_BYTES {
67                return Err(fail(format!("inline law {n} is over 64 KiB")));
68            }
69            if law.contains('\0') {
70                return Err(fail(format!("inline law {n} contains a NUL byte")));
71            }
72        }
73        assert_eq!(resolved.len(), paths.len());
74        for path in &resolved {
75            let shown = path.display().to_string();
76            trace!(
77                Trace::Laws,
78                "law.load",
79                owner = owner,
80                source = "file",
81                path = shown,
82                auto = auto,
83            );
84        }
85        for law in inline {
86            trace!(
87                Trace::Laws,
88                "law.load",
89                owner = owner,
90                source = "inline",
91                bytes = law.len(),
92                auto = auto,
93            );
94        }
95        Ok(Laws {
96            paths: resolved,
97            inline: inline.to_vec(),
98            auto,
99        })
100    }
101}
102
103impl Default for Laws {
104    fn default() -> Self {
105        Laws {
106            paths: Vec::new(),
107            inline: Vec::new(),
108            auto: true,
109        }
110    }
111}
112
113/// `O_NONBLOCK` on the BSD family, so opening a FIFO returns at once.
114#[cfg(any(
115    target_os = "macos",
116    target_os = "ios",
117    target_os = "freebsd",
118    target_os = "openbsd",
119    target_os = "netbsd",
120    target_os = "dragonfly"
121))]
122const O_NONBLOCK: i32 = 0x0004;
123/// `O_NONBLOCK` on Linux and Android for every architecture except the
124/// MIPS, SPARC, Alpha and PA-RISC families, which number it differently.
125#[cfg(all(
126    any(target_os = "linux", target_os = "android"),
127    any(
128        target_arch = "x86",
129        target_arch = "x86_64",
130        target_arch = "arm",
131        target_arch = "aarch64",
132        target_arch = "riscv64",
133        target_arch = "powerpc",
134        target_arch = "powerpc64",
135        target_arch = "s390x",
136        target_arch = "loongarch64"
137    )
138))]
139const O_NONBLOCK: i32 = 0o4000;
140/// No known `O_NONBLOCK` value for this target, so open stays blocking;
141/// the opened handle is still checked to be a regular file.
142#[cfg(all(
143    unix,
144    not(any(
145        target_os = "macos",
146        target_os = "ios",
147        target_os = "freebsd",
148        target_os = "openbsd",
149        target_os = "netbsd",
150        target_os = "dragonfly"
151    )),
152    not(all(
153        any(target_os = "linux", target_os = "android"),
154        any(
155            target_arch = "x86",
156            target_arch = "x86_64",
157            target_arch = "arm",
158            target_arch = "aarch64",
159            target_arch = "riscv64",
160            target_arch = "powerpc",
161            target_arch = "powerpc64",
162            target_arch = "s390x",
163            target_arch = "loongarch64"
164        )
165    ))
166))]
167const O_NONBLOCK: i32 = 0;
168
169/// Opens a law file for reading without waiting on a FIFO, as the context
170/// loader does; the caller then checks the handle is a regular file.
171/// Input: the absolute path. Output: the file or the I/O error.
172fn open_nonblocking(path: &Path) -> std::io::Result<std::fs::File> {
173    let mut options = std::fs::OpenOptions::new();
174    options.read(true);
175    #[cfg(unix)]
176    std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, O_NONBLOCK);
177    options.open(path)
178}
179
180/// Checks and reads one user-named file: non-empty path, no `..`, the
181/// given extension, a regular file of at most `max_bytes`, valid UTF-8.
182/// Returns the absolute path and the text, or the reason it was refused.
183/// `max_bytes` must be a whole number of MiB.
184pub(crate) fn read_checked(
185    path: &Path,
186    extension: &str,
187    max_bytes: u64,
188) -> Result<(PathBuf, String), String> {
189    assert!(max_bytes > 0 && max_bytes.is_multiple_of(1024 * 1024));
190    let too_big = || format!("is over {} MiB", max_bytes / (1024 * 1024));
191    if path.as_os_str().is_empty() {
192        return Err("is empty".into());
193    }
194    if path.components().any(|c| c == Component::ParentDir) {
195        return Err("must not contain `..`".into());
196    }
197    if path.extension().is_none_or(|e| e != extension) {
198        return Err(format!("must be a .{extension} file"));
199    }
200    let absolute = std::path::absolute(path).map_err(|e| format!("cannot be resolved: {e}"))?;
201    assert!(absolute.is_absolute(), "std::path::absolute returns an absolute path");
202    let file = match open_nonblocking(&absolute) {
203        Ok(file) => file,
204        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err("does not exist".into()),
205        Err(e) => return Err(format!("cannot be read: {e}")),
206    };
207    let meta = file.metadata().map_err(|e| format!("cannot be read: {e}"))?;
208    if !meta.is_file() {
209        return Err("is not a regular file".into());
210    }
211    if meta.len() > max_bytes {
212        return Err(too_big());
213    }
214    let bytes = read_bounded(file, max_bytes).map_err(|e| e.unwrap_or_else(too_big))?;
215    let text = String::from_utf8(bytes).map_err(|_| "is not valid UTF-8".to_string())?;
216    Ok((absolute, text))
217}
218
219/// Reads at most `max_bytes` plus one byte, so a file that grew after its
220/// size check is refused without reading it all. Input: the opened file
221/// and the cap. Output: the bytes, `Err(None)` past the cap, or the I/O
222/// failure as text.
223fn read_bounded(file: impl Read, max_bytes: u64) -> Result<Vec<u8>, Option<String>> {
224    let mut bytes = Vec::new();
225    file.take(max_bytes + 1)
226        .read_to_end(&mut bytes)
227        .map_err(|e| Some(format!("cannot be read: {e}")))?;
228    if bytes.len() as u64 > max_bytes {
229        return Err(None);
230    }
231    Ok(bytes)
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    #[test]
239    fn read_stops_one_byte_past_the_cap() {
240        assert_eq!(read_bounded(std::io::repeat(b'a'), MAX_LAW_FILE_BYTES).unwrap_err(), None);
241        let exact = vec![b'a'; MAX_LAW_FILE_BYTES as usize];
242        assert_eq!(read_bounded(exact.as_slice(), MAX_LAW_FILE_BYTES).unwrap().len(), exact.len());
243    }
244
245    #[cfg(any(
246        target_os = "macos",
247        target_os = "ios",
248        target_os = "freebsd",
249        target_os = "openbsd",
250        target_os = "netbsd",
251        target_os = "dragonfly",
252        all(
253            any(target_os = "linux", target_os = "android"),
254            any(
255                target_arch = "x86",
256                target_arch = "x86_64",
257                target_arch = "arm",
258                target_arch = "aarch64",
259                target_arch = "riscv64",
260                target_arch = "powerpc",
261                target_arch = "powerpc64",
262                target_arch = "s390x",
263                target_arch = "loongarch64"
264            )
265        )
266    ))]
267    #[test]
268    fn a_named_pipe_law_file_is_refused_without_blocking() {
269        let dir = tempfile::tempdir().unwrap();
270        let fifo = dir.path().join("rules.bend");
271        let made = std::process::Command::new("mkfifo").arg(&fifo).status().unwrap();
272        assert!(made.success());
273        let (tx, rx) = std::sync::mpsc::channel();
274        std::thread::spawn(move || tx.send(read_checked(&fifo, "bend", MAX_LAW_FILE_BYTES).map(|(p, _)| p)).unwrap());
275        let result = rx
276            .recv_timeout(std::time::Duration::from_secs(10))
277            .expect("read_checked blocked on a named pipe");
278        assert_eq!(result, Err("is not a regular file".to_string()));
279    }
280
281    #[cfg(windows)]
282    #[test]
283    fn drive_relative_path_resolves_to_an_absolute_one() {
284        let dir = tempfile::tempdir().unwrap();
285        std::env::set_current_dir(dir.path()).unwrap();
286        std::fs::write(dir.path().join("rules.bend"), "law").unwrap();
287        let drive = dir.path().components().next().unwrap().as_os_str().to_owned();
288        let mut relative = std::ffi::OsString::from(drive);
289        relative.push("rules.bend");
290        let (resolved, _) = read_checked(&PathBuf::from(relative), "bend", MAX_LAW_FILE_BYTES).unwrap();
291        assert!(resolved.is_absolute(), "{}", resolved.display());
292        assert!(resolved.ends_with("rules.bend"), "{}", resolved.display());
293    }
294}