Skip to main content

troupekit_kit/
laws.rs

1use crate::error::KitError;
2use std::path::{Component, PathBuf};
3use troupekit_trace::{trace, Trace};
4
5const MAX_LAW_FILE_BYTES: u64 = 1024 * 1024;
6const MAX_INLINE_LAW_BYTES: usize = 64 * 1024;
7const MAX_LAWS: usize = 64;
8
9/// The laws attached to an agent or graph, checked at `build`.
10/// 0.2 stores and validates them; no run proves them yet. `auto` asks
11/// the verifier to also derive laws from the code, and defaults to `true`.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Laws {
14    paths: Vec<PathBuf>,
15    inline: Vec<String>,
16    auto: bool,
17}
18
19impl Laws {
20    /// Returns the law files, as absolute paths resolved at `build`.
21    /// Each is an existing `.bend` file of at most 1 MiB of UTF-8.
22    /// Order is the order they were added.
23    pub fn paths(&self) -> &[PathBuf] {
24        &self.paths
25    }
26
27    /// Returns the inline laws in the order they were added.
28    /// Each is non-blank, at most 64 KiB and free of NUL bytes.
29    /// The text is kept exactly as given.
30    pub fn inline(&self) -> &[String] {
31        &self.inline
32    }
33
34    /// Reports whether laws derived from the code are wanted.
35    /// Set with `.auto_laws(..)`; `true` unless turned off.
36    /// 0.2 records the choice only.
37    pub fn auto(&self) -> bool {
38        self.auto
39    }
40
41    pub(crate) fn check(
42        owner: &str,
43        paths: &[PathBuf],
44        inline: &[String],
45        auto: bool,
46    ) -> Result<Laws, KitError> {
47        let fail = |m: String| KitError::config(owner, m);
48        let total = paths.len() + inline.len();
49        if total > MAX_LAWS {
50            return Err(fail(format!("takes at most {MAX_LAWS} laws, got {total}")));
51        }
52        let mut resolved = Vec::with_capacity(paths.len());
53        for path in paths {
54            resolved.push(
55                check_path(path).map_err(|m| fail(format!("law file `{}` {m}", path.display())))?,
56            );
57        }
58        for (i, law) in inline.iter().enumerate() {
59            let n = i + 1;
60            if law.trim().is_empty() {
61                return Err(fail(format!("inline law {n} is blank")));
62            }
63            if law.len() > MAX_INLINE_LAW_BYTES {
64                return Err(fail(format!("inline law {n} is over 64 KiB")));
65            }
66            if law.contains('\0') {
67                return Err(fail(format!("inline law {n} contains a NUL byte")));
68            }
69        }
70        assert_eq!(resolved.len(), paths.len());
71        for path in &resolved {
72            let shown = path.display().to_string();
73            trace!(
74                Trace::Laws,
75                "law.load",
76                owner = owner,
77                source = "file",
78                path = shown,
79                auto = auto,
80            );
81        }
82        for law in inline {
83            trace!(
84                Trace::Laws,
85                "law.load",
86                owner = owner,
87                source = "inline",
88                bytes = law.len(),
89                auto = auto,
90            );
91        }
92        Ok(Laws {
93            paths: resolved,
94            inline: inline.to_vec(),
95            auto,
96        })
97    }
98}
99
100impl Default for Laws {
101    fn default() -> Self {
102        Laws {
103            paths: Vec::new(),
104            inline: Vec::new(),
105            auto: true,
106        }
107    }
108}
109
110fn check_path(path: &PathBuf) -> Result<PathBuf, String> {
111    if path.as_os_str().is_empty() {
112        return Err("is empty".into());
113    }
114    if path.components().any(|c| c == Component::ParentDir) {
115        return Err("must not contain `..`".into());
116    }
117    if path.extension().is_none_or(|e| e != "bend") {
118        return Err("must be a .bend file".into());
119    }
120    let absolute = if path.is_absolute() {
121        path.clone()
122    } else {
123        std::env::current_dir()
124            .map_err(|e| format!("cannot be resolved: {e}"))?
125            .join(path)
126    };
127    let meta = match std::fs::metadata(&absolute) {
128        Ok(meta) => meta,
129        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err("does not exist".into()),
130        Err(e) => return Err(format!("cannot be read: {e}")),
131    };
132    if !meta.is_file() {
133        return Err("is not a regular file".into());
134    }
135    if meta.len() > MAX_LAW_FILE_BYTES {
136        return Err("is over 1 MiB".into());
137    }
138    let bytes = std::fs::read(&absolute).map_err(|e| format!("cannot be read: {e}"))?;
139    if bytes.len() as u64 > MAX_LAW_FILE_BYTES {
140        return Err("is over 1 MiB".into());
141    }
142    if std::str::from_utf8(&bytes).is_err() {
143        return Err("is not valid UTF-8".into());
144    }
145    Ok(absolute)
146}