Skip to main content

agent_works/script_tool/
law.rs

1use std::path::{Component, Path, PathBuf};
2
3use super::INTERPRETER_WHITELIST;
4
5/// Path-law violation at definition/install time. Fail-closed: reject what is illegal, no compromises.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum ScriptLawError {
8    /// Tool name is invalid (character set / reserved word / too long).
9    BadName { name: String },
10    /// `run` is empty.
11    EmptyRun,
12    /// `run[0]` is not an absolute path and not in the interpreter whitelist — rejected to prevent shadowing.
13    RelativeProgram { program: String },
14    /// The interpreter lacks a script file argument (`-File`/`-f`/`/c` not found), so the script path cannot be pinned.
15    InterpreterMissingScriptArg { interpreter: String },
16    /// The interpreter's script file argument is not an absolute path.
17    RelativeScriptArg { interpreter: String, arg: String },
18    /// A path inside a plugin escapes the plugin root after resolution (`../` escape / absolute path outside).
19    EscapedPluginRoot { path: String },
20    /// The script file does not exist at install/mount time (or is not a regular file).
21    ScriptFileMissing { path: String },
22    /// The script body (the non-interpreter form's `run[0]`) has no executable bit.
23    ScriptFileNotExecutable { path: String },
24}
25
26impl std::fmt::Display for ScriptLawError {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        match self {
29            Self::BadName { name } => write!(f, "script tool name `{name}` is invalid"),
30            Self::EmptyRun => write!(f, "`run` must not be empty"),
31            Self::RelativeProgram { program } => write!(
32                f,
33                "`run[0]` must be an absolute path (got `{program}`); \
34                 the only exception is the interpreter whitelist {INTERPRETER_WHITELIST:?} \
35                 with an absolute script file argument"
36            ),
37            Self::InterpreterMissingScriptArg { interpreter } => write!(
38                f,
39                "interpreter `{interpreter}` needs a script file argument \
40                 (`-File`/`-f` for powershell/pwsh, `/c` for cmd) so its absolute path can be pinned"
41            ),
42            Self::RelativeScriptArg { interpreter, arg } => write!(
43                f,
44                "script file argument `{arg}` of interpreter `{interpreter}` must be an absolute path"
45            ),
46            Self::EscapedPluginRoot { path } => {
47                write!(f, "script path `{path}` escapes the plugin root")
48            }
49            Self::ScriptFileMissing { path } => write!(
50                f,
51                "script file `{path}` does not exist (must be a regular file)"
52            ),
53            Self::ScriptFileNotExecutable { path } => write!(
54                f,
55                "script file `{path}` is not executable (chmod +x) — it runs directly as `run[0]`"
56            ),
57        }
58    }
59}
60
61impl std::error::Error for ScriptLawError {}
62
63/// Interpreter whitelist check: takes the file stem of `run[0]` (lowercased).
64fn interpreter_of(program: &str) -> Option<&'static str> {
65    let stem = Path::new(program)
66        .file_stem()
67        .and_then(|s| s.to_str())
68        .unwrap_or("")
69        .to_lowercase();
70    INTERPRETER_WHITELIST
71        .iter()
72        .find(|name| **name == stem)
73        .copied()
74}
75
76/// Index of the interpreter's "script file argument": powershell/pwsh → after `-File`/`-f`;
77/// cmd → after `/c`. Not found (or no argument after the flag) = cannot pin → error.
78/// Not an interpreter → `Ok(None)` (the script is `run[0]` itself).
79fn interpreter_script_arg_index(run: &[String]) -> Result<Option<usize>, ScriptLawError> {
80    let Some((program, args)) = run.split_first() else {
81        return Err(ScriptLawError::EmptyRun);
82    };
83    let Some(interpreter) = interpreter_of(program) else {
84        return Ok(None);
85    };
86    let flags: &[&str] = if interpreter == "cmd" {
87        &["/c"]
88    } else {
89        &["-file", "-f"]
90    };
91    for (offset, arg) in args.iter().enumerate() {
92        if flags.iter().any(|f| arg.eq_ignore_ascii_case(f)) {
93            // absolute index of the flag itself within run
94            let flag_index = offset + 1;
95            return run.get(flag_index + 1).map(|_| Some(flag_index + 1)).ok_or(
96                ScriptLawError::InterpreterMissingScriptArg {
97                    interpreter: interpreter.to_string(),
98                },
99            );
100        }
101    }
102    Err(ScriptLawError::InterpreterMissingScriptArg {
103        interpreter: interpreter.to_string(),
104    })
105}
106
107/// Index of the "script file" element: interpreter → its script argument position; otherwise 0.
108pub fn script_file_index(run: &[String]) -> Result<usize, ScriptLawError> {
109    if run.is_empty() {
110        return Err(ScriptLawError::EmptyRun);
111    }
112    Ok(interpreter_script_arg_index(run)?.unwrap_or(0))
113}
114
115/// Path law (anti-shadowing): `run[0]` is an absolute path, or the interpreter whitelist + an absolute script file argument.
116pub fn check_run_law(run: &[String]) -> Result<(), ScriptLawError> {
117    let Some((program, _)) = run.split_first() else {
118        return Err(ScriptLawError::EmptyRun);
119    };
120    match interpreter_script_arg_index(run)? {
121        Some(index) => {
122            let arg = &run[index];
123            if Path::new(arg).is_absolute() {
124                Ok(())
125            } else {
126                Err(ScriptLawError::RelativeScriptArg {
127                    interpreter: program.clone(),
128                    arg: arg.clone(),
129                })
130            }
131        }
132        None => {
133            if Path::new(program).is_absolute() {
134                Ok(())
135            } else {
136                Err(ScriptLawError::RelativeProgram {
137                    program: program.clone(),
138                })
139            }
140        }
141    }
142}
143
144/// Whether the script body is `run[0]` itself (non-interpreter form). Interpreter form → `false`
145/// (the script is read in, no executable bit needed). Invalid/empty errors out on the same criteria as [`check_run_law`].
146pub fn script_file_is_program(run: &[String]) -> Result<bool, ScriptLawError> {
147    Ok(interpreter_script_arg_index(run)?.is_none())
148}
149
150/// Script file check at install/mount time (fail-closed, the same law as a missing wasm file):
151/// it must be a regular file; when the script body is executed directly it must also have the
152/// executable bit on unix.
153///
154/// `path` is supplied by the caller: plugin install checks the **staging area** contents (bytes
155/// unchanged after the rename), global mount checks the final path. Not checked at load time —
156/// archived entries are left to self-check at execution time (see [`ScriptToolEntry::check_laws`]);
157/// once the file comes back the tool is alive again.
158pub fn check_script_file_on_disk(
159    path: &Path,
160    require_executable: bool,
161) -> Result<(), ScriptLawError> {
162    let missing = ScriptLawError::ScriptFileMissing {
163        path: path.display().to_string(),
164    };
165    let meta = std::fs::metadata(path).map_err(|_| missing.clone())?;
166    if !meta.is_file() {
167        return Err(missing);
168    }
169    #[cfg(unix)]
170    if require_executable {
171        use std::os::unix::fs::PermissionsExt;
172        if meta.permissions().mode() & 0o111 == 0 {
173            return Err(ScriptLawError::ScriptFileNotExecutable {
174                path: path.display().to_string(),
175            });
176        }
177    }
178    #[cfg(not(unix))]
179    let _ = require_executable;
180    Ok(())
181}
182
183/// Lexical normalization (does not touch the file system): consumes `.`, `..` steps back;
184/// stepping back past the start = escape → `None`.
185fn normalize_lexical(path: &Path) -> Option<PathBuf> {
186    let mut out = PathBuf::new();
187    for component in path.components() {
188        match component {
189            Component::CurDir => {}
190            Component::ParentDir => {
191                if !out.pop() {
192                    return None;
193                }
194            }
195            other => out.push(other.as_os_str()),
196        }
197    }
198    Some(out)
199}
200
201/// Resolve an in-plugin path (relative to the plugin root) to an absolute path and pin it.
202///
203/// - Relative path → resolved under `plugin_root`; absolute path → verified to be inside the plugin root;
204/// - After lexical normalization it must still be under the plugin root (`../` escape → [`ScriptLawError::EscapedPluginRoot`]).
205pub fn resolve_under_root(plugin_root: &Path, path: &str) -> Result<String, ScriptLawError> {
206    let escape = |p: &str| ScriptLawError::EscapedPluginRoot {
207        path: p.to_string(),
208    };
209    let root_norm = normalize_lexical(plugin_root).ok_or_else(|| escape(path))?;
210    let joined = if Path::new(path).is_absolute() {
211        PathBuf::from(path)
212    } else {
213        root_norm.join(path)
214    };
215    let normalized = normalize_lexical(&joined).ok_or_else(|| escape(path))?;
216    if normalized.starts_with(&root_norm) {
217        Ok(normalized.to_string_lossy().into_owned())
218    } else {
219        Err(escape(path))
220    }
221}
222
223/// Plugin script pinning at install time: resolve the script file element to an absolute path
224/// under the plugin root, then enforce the path law.
225///
226/// The same law as global scripts' "`run[0]` anti-shadowing" rule; plugins are not exempt.
227pub fn pin_from_plugin_root(
228    run: &[String],
229    plugin_root: &Path,
230) -> Result<Vec<String>, ScriptLawError> {
231    let index = script_file_index(run)?;
232    let mut pinned = run.to_vec();
233    pinned[index] = resolve_under_root(plugin_root, &run[index])?;
234    check_run_law(&pinned)?;
235    Ok(pinned)
236}