agent_works/script_tool/
law.rs1use std::path::{Component, Path, PathBuf};
2
3use super::INTERPRETER_WHITELIST;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum ScriptLawError {
8 BadName { name: String },
10 EmptyRun,
12 RelativeProgram { program: String },
14 InterpreterMissingScriptArg { interpreter: String },
16 RelativeScriptArg { interpreter: String, arg: String },
18 EscapedPluginRoot { path: String },
20 ScriptFileMissing { path: String },
22 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
63fn 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
76fn 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 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
107pub 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
115pub 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
144pub fn script_file_is_program(run: &[String]) -> Result<bool, ScriptLawError> {
147 Ok(interpreter_script_arg_index(run)?.is_none())
148}
149
150pub 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
183fn 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
201pub 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
223pub 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}