use crate::tools::{str_arg, Tool, ToolError, SHELL_KILL_GRACE};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::ffi::OsString;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;
pub const ENV_SCRIPTS_DIR: &str = "ECLIPSE_SCRIPTS_DIR";
const HEAD_BYTES: u64 = 4096;
const MAX_DESCRIPTION_CHARS: usize = 200;
const MAX_LISTED: usize = 200;
const MAX_NAMED_IN_DESCRIPTION: usize = 20;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScriptInfo {
pub name: String,
pub description: Option<String>,
pub path: PathBuf,
pub executable: bool,
pub escapes: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Listing {
pub scripts: Vec<ScriptInfo>,
pub omitted: usize,
pub exists: bool,
}
pub fn first_comment(head: &str) -> Option<String> {
let mut lines = head.lines();
let first = lines.next()?;
let rest = if first.starts_with("#!") {
lines
} else {
head.lines()
};
for line in rest {
if !line.starts_with('#') {
continue;
}
let text = line.trim_start_matches('#').trim();
if text.is_empty() {
continue;
}
let mut chars = text.chars();
let kept: String = chars.by_ref().take(MAX_DESCRIPTION_CHARS).collect();
return Some(if chars.next().is_some() {
format!("{kept}...")
} else {
kept
});
}
None
}
fn read_head(path: &Path) -> Option<String> {
let mut buf = Vec::new();
std::fs::File::open(path)
.ok()?
.take(HEAD_BYTES)
.read_to_end(&mut buf)
.ok()?;
Some(String::from_utf8_lossy(&buf).into_owned())
}
#[cfg(unix)]
fn is_executable(meta: &std::fs::Metadata) -> bool {
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode() & 0o111 != 0
}
#[cfg(not(unix))]
fn is_executable(_: &std::fs::Metadata) -> bool {
true
}
pub fn list_scripts(dir: &Path) -> Result<Listing, String> {
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Listing::default()),
Err(e) => return Err(format!("cannot read {}: {e}", dir.display())),
};
let canonical_dir = std::fs::canonicalize(dir).ok();
let mut names: Vec<String> = entries
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter(|n| !n.starts_with('.'))
.collect();
names.sort();
let omitted = names.len().saturating_sub(MAX_LISTED);
names.truncate(MAX_LISTED);
let mut scripts = Vec::new();
for name in names {
let path = dir.join(&name);
let Ok(canonical) = std::fs::canonicalize(&path) else {
continue;
};
let Ok(meta) = std::fs::metadata(&canonical) else {
continue;
};
if !meta.is_file() {
continue;
}
let escapes = !canonical_dir
.as_ref()
.is_some_and(|d| canonical.starts_with(d));
scripts.push(ScriptInfo {
description: if escapes {
None
} else {
read_head(&canonical).and_then(|h| first_comment(&h))
},
executable: is_executable(&meta),
name,
path,
escapes,
});
}
Ok(Listing {
scripts,
omitted,
exists: true,
})
}
pub fn resolve(dir: &Path, name: &str) -> Result<PathBuf, String> {
let (canonical, meta) = locate(dir, name)?;
if !is_executable(&meta) {
return Err(format!(
"{} is not executable; make it so with `chmod +x {}` and call it again",
canonical.display(),
canonical.display()
));
}
Ok(canonical)
}
pub fn locate_file(dir: &Path, name: &str) -> Result<PathBuf, String> {
locate(dir, name).map(|(path, _)| path)
}
fn locate(dir: &Path, name: &str) -> Result<(PathBuf, std::fs::Metadata), String> {
if name.trim().is_empty() {
return Err(
"the name is empty; give the file name of a script, or `list` to see them".into(),
);
}
if name.contains('\0') {
return Err("the name contains a NUL byte".into());
}
if Path::new(name).is_absolute() || name.starts_with('/') {
return Err(format!(
"it is an absolute path; a script is called by its file name inside the scripts directory ({})",
dir.display()
));
}
if name.contains('/') || name.contains('\\') {
return Err(
"it contains a path separator; scripts are called by file name only, and the scripts directory has no subdirectories".into(),
);
}
if name.contains("..") {
return Err(
"it contains `..`; a script cannot be named by walking out of the scripts directory"
.into(),
);
}
let canonical_dir = std::fs::canonicalize(dir).map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
format!(
"the scripts directory {} does not exist yet, so there is no such script",
dir.display()
)
} else {
format!(
"the scripts directory {} cannot be resolved ({e})",
dir.display()
)
}
})?;
let canonical = std::fs::canonicalize(dir.join(name)).map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
format!(
"there is no such file in {} (or it is a symlink to nothing); `list` shows what exists",
dir.display()
)
} else {
format!("it cannot be resolved ({e})")
}
})?;
if !canonical.starts_with(&canonical_dir) {
return Err(format!(
"it resolves to {}, which is outside the scripts directory ({}); a symlink may not lead out of it",
canonical.display(),
canonical_dir.display()
));
}
let meta = std::fs::metadata(&canonical)
.map_err(|e| format!("{} cannot be read ({e})", canonical.display()))?;
if !meta.is_file() {
return Err(format!("{} is not a regular file", canonical.display()));
}
Ok((canonical, meta))
}
pub fn path_with(dir: &Path) -> Option<OsString> {
let current = std::env::var_os("PATH")?;
let exe = std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(Path::to_path_buf));
let paths = exe
.into_iter()
.chain(std::env::split_paths(¤t))
.chain(std::iter::once(dir.to_path_buf()));
std::env::join_paths(paths).ok()
}
pub fn command(dir: &Path, script: &Path, args: &[String]) -> std::process::Command {
let mut cmd = std::process::Command::new(script);
cmd.args(args).current_dir(dir).env(ENV_SCRIPTS_DIR, dir);
if let Some(path) = path_with(dir) {
cmd.env("PATH", path);
}
cmd
}
fn prepare(dir: &Path, name: &str, args: &[String]) -> Result<Run, ToolError> {
let script = resolve(dir, name)
.map_err(|why| ToolError::Failed(format!("script {name:?} refused: {why}")))?;
Ok(Run {
dir: dir.to_path_buf(),
script,
args: args.to_vec(),
})
}
struct Run {
dir: PathBuf,
script: PathBuf,
args: Vec<String>,
}
impl Run {
fn plan(
&self,
sandbox: &crate::sandbox::Sandbox,
extra_rw: &[PathBuf],
) -> Result<crate::sandbox::Plan, ToolError> {
let args: Vec<std::ffi::OsString> =
self.args.iter().map(std::ffi::OsString::from).collect();
sandbox.plan_with(self.script.as_os_str(), &args, &self.dir, extra_rw)
}
fn command(&self, plan: &crate::sandbox::Plan) -> tokio::process::Command {
let mut cmd = tokio::process::Command::new(&plan.program);
cmd.args(&plan.args).current_dir(&self.dir);
apply_env(&mut cmd, &self.dir);
cmd
}
}
pub fn apply_env(cmd: &mut tokio::process::Command, dir: &Path) {
cmd.env(ENV_SCRIPTS_DIR, dir);
if let Some(path) = path_with(dir) {
cmd.env("PATH", path);
}
}
pub fn start_error(e: &std::io::Error) -> String {
#[cfg(unix)]
if e.raw_os_error() == Some(libc::ENOEXEC) {
return format!(
"failed to start: {e}. The file has no `#!` line, so there is no interpreter to run \
it with: begin it with one, for example `#!/bin/sh` or `#!/usr/bin/env python3`"
);
}
format!("failed to start: {e}")
}
#[derive(Debug, PartialEq, Eq)]
enum Action {
List,
Run { name: String, args: Vec<String> },
}
fn invalid(message: impl Into<String>) -> ToolError {
ToolError::InvalidArgs(message.into())
}
fn parse(args: &Value) -> Result<Action, ToolError> {
let list = match args.get("list") {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(_) => return Err(invalid("`list` must be a boolean")),
};
let name = match args.get("name") {
None | Some(Value::Null) => None,
Some(Value::String(_)) => Some(str_arg(args, "name")?.to_string()),
Some(_) => return Err(invalid("`name` must be a string")),
};
let script_args = match args.get("args") {
None | Some(Value::Null) => None,
Some(Value::Array(items)) => {
let mut out = Vec::with_capacity(items.len());
for (i, item) in items.iter().enumerate() {
match item {
Value::String(s) => out.push(s.clone()),
_ => return Err(invalid(format!("`args[{i}]` must be a string"))),
}
}
Some(out)
}
Some(_) => return Err(invalid("`args` must be an array of strings")),
};
if list {
if name.is_some() || script_args.is_some() {
return Err(invalid(
"`list: true` cannot be combined with `name` or `args`: either list the scripts or run one",
));
}
return Ok(Action::List);
}
match name {
Some(name) => Ok(Action::Run {
name,
args: script_args.unwrap_or_default(),
}),
None => Err(invalid(
"give `name` to run a script, or `list: true` to see what there is",
)),
}
}
pub struct ScriptTool {
dir: PathBuf,
timeout: Duration,
max_bytes: usize,
kill_grace: Duration,
sandbox: crate::sandbox::Sandbox,
description: String,
}
impl ScriptTool {
pub fn new(dir: PathBuf, timeout: Duration, max_bytes: usize) -> Self {
let description = describe_directory(&dir);
Self {
dir,
timeout,
max_bytes,
kill_grace: SHELL_KILL_GRACE,
sandbox: crate::sandbox::Sandbox::off(),
description,
}
}
pub fn with_sandbox(mut self, sandbox: crate::sandbox::Sandbox) -> Self {
self.sandbox = sandbox;
self
}
fn render_list(&self) -> Result<String, ToolError> {
let listing = list_scripts(&self.dir).map_err(ToolError::Failed)?;
let mut out = format!("scripts directory: {}\n", self.dir.display());
if !listing.exists {
out.push_str("it does not exist yet; `write_file` creates it with the first script\n");
}
if listing.scripts.is_empty() {
out.push_str("no scripts\n");
return Ok(out);
}
for script in &listing.scripts {
out.push_str(&script.name);
if script.escapes {
out.push_str(" (not runnable: a symlink that leads outside the directory)");
} else if !script.executable {
out.push_str(" (not executable: needs chmod +x)");
}
if let Some(d) = &script.description {
out.push_str(": ");
out.push_str(d);
}
out.push('\n');
}
if listing.omitted > 0 {
out.push_str(&format!("[{} more not listed]\n", listing.omitted));
}
Ok(out)
}
}
fn describe_directory(dir: &Path) -> String {
let mut text = format!(
"Run a script from the scripts directory ({dir}), or list what is there. A script is a \
saved workflow: when you work out a procedure worth repeating, write it as a file in that \
directory with `write_file`, make it executable with `chmod +x` through `shell`, and from then \
on call it by name instead of working it out again. `{{\"list\": true}}` lists the scripts with \
their first comment line; `{{\"name\": \"backup-media\", \"args\": [\"--dry-run\"]}}` runs one with \
the scripts directory as its working directory and reports the exit code, stdout and stderr. A \
name is a bare file name: no path, no `..`.",
dir = dir.display()
);
match list_scripts(dir) {
Ok(listing) if !listing.scripts.is_empty() => {
let total = listing.scripts.len() + listing.omitted;
let names: Vec<&str> = listing
.scripts
.iter()
.take(MAX_NAMED_IN_DESCRIPTION)
.map(|s| s.name.as_str())
.collect();
text.push_str(&format!(
" Scripts when this run started: {}",
names.join(", ")
));
if total > names.len() {
text.push_str(&format!(" and {} more", total - names.len()));
}
text.push_str(". Call `list` for the current set.");
}
Ok(_) => text.push_str(" There are no scripts yet."),
Err(_) => {}
}
text
}
#[async_trait]
impl Tool for ScriptTool {
fn name(&self) -> &str {
"script"
}
fn description(&self) -> &str {
&self.description
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"list": {
"type": "boolean",
"description": "List the scripts and what each says it does. Cannot be combined with `name` or `args`."
},
"name": {
"type": "string",
"description": "The script's file name in the scripts directory, for example `backup-media.sh`: no path, no `..`."
},
"args": {
"type": "array",
"items": {"type": "string"},
"description": "Arguments passed to the script, one string each."
}
}
})
}
fn describe_call(&self, args: &Value) -> String {
if args.get("list") == Some(&Value::Bool(true)) {
return "list the scripts".to_string();
}
let name = args.get("name").and_then(Value::as_str).unwrap_or("?");
match args
.get("args")
.filter(|a| a.as_array().is_some_and(|a| !a.is_empty()))
{
Some(a) => format!(
"run script {name:?} with arguments {a} from {}",
self.dir.display()
),
None => format!("run script {name:?} from {}", self.dir.display()),
}
}
fn needs_approval(&self, args: &Value) -> bool {
!matches!(parse(args), Ok(Action::List))
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let (name, script_args) = match parse(&args)? {
Action::List => return self.render_list(),
Action::Run { name, args } => (name, args),
};
let run = prepare(&self.dir, &name, &script_args)?;
let plan = run.plan(&self.sandbox, &[])?;
crate::tools::run_built(
|| run.command(&plan),
self.timeout,
self.max_bytes,
self.kill_grace,
)
.await
}
async fn call_scoped(
&self,
args: Value,
scope: &crate::tools::CallScope<'_>,
) -> Result<String, ToolError> {
let (name, script_args) = match parse(&args)? {
Action::List => return self.render_list(),
Action::Run { name, args } => (name, args),
};
let run = prepare(&self.dir, &name, &script_args)?;
let bridge = crate::tools_bridge::Bridge::bind()?;
let plan = run.plan(&self.sandbox, &[bridge.dir().to_path_buf()])?;
crate::tools_bridge::run_with_bridge_built(
|| run.command(&plan),
&bridge,
self.max_bytes,
self.timeout,
self.kill_grace,
scope,
)
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{Policy, ToolsConfig};
use crate::tools::{AllowAll, Approver, ToolRegistry};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
#[test]
fn the_scripts_directory_is_last_on_path() {
let dir = Path::new("/tmp/eclipse-path-order/scripts");
let path = path_with(dir).expect("PATH is set in the test environment");
let entries: Vec<PathBuf> = std::env::split_paths(&path).collect();
assert_eq!(entries.last(), Some(&dir.to_path_buf()), "{entries:?}");
assert!(
entries.len() > 2,
"the inherited PATH and this binary's directory are still there: {entries:?}"
);
assert!(
!entries.contains(&PathBuf::from("/usr/bin")) || entries[0] != dir,
"the scripts directory is not first"
);
}
fn write_script(dir: &Path, name: &str, body: &str, mode: u32) -> PathBuf {
std::fs::create_dir_all(dir).unwrap();
let path = dir.join(name);
std::fs::write(&path, body).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
}
let _ = mode;
path
}
#[cfg(unix)]
fn process_alive(pid: i32) -> bool {
let exists = unsafe { libc::kill(pid, 0) } == 0;
let zombie = std::fs::read_to_string(format!("/proc/{pid}/stat"))
.map(|s| {
s.rsplit(')')
.next()
.unwrap_or("")
.trim_start()
.starts_with('Z')
})
.unwrap_or(false);
exists && !zombie
}
fn tool(dir: &Path) -> ScriptTool {
ScriptTool::new(dir.to_path_buf(), Duration::from_secs(10), 4096)
}
async fn call(tool: &ScriptTool, args: Value) -> Result<String, ToolError> {
tool.call(args).await
}
async fn call_retrying(tool: &ScriptTool, args: Value) -> Result<String, ToolError> {
let mut last = None;
for attempt in 0..5 {
match call(tool, args.clone()).await {
Ok(out) if !out.contains("Text file busy") => return Ok(out),
Ok(out) => last = Some(Ok(out)),
Err(e) if !e.to_string().contains("Text file busy") => return Err(e),
Err(e) => last = Some(Err(e)),
}
tokio::time::sleep(std::time::Duration::from_millis(10 * (attempt + 1))).await;
}
last.unwrap()
}
fn refused(result: Result<String, ToolError>) -> String {
match result {
Err(e) => e.to_string(),
Ok(out) => panic!("expected a refusal, got: {out}"),
}
}
#[test]
fn a_description_is_the_first_comment_line_after_a_shebang() {
assert_eq!(
first_comment("#!/bin/sh\n# Back up the media\nset -e\n").as_deref(),
Some("Back up the media")
);
assert_eq!(
first_comment("## Title \n").as_deref(),
Some("Title"),
"no shebang, several hashes, trailing spaces"
);
assert_eq!(
first_comment("#!/bin/sh\n\nset -e\n# later one\n").as_deref(),
Some("later one"),
"the first line that starts with a hash, wherever it is"
);
assert_eq!(
first_comment("#!/bin/sh\n#\n#####\n# real\n").as_deref(),
Some("real"),
"an empty comment is a separator, not a description"
);
assert_eq!(first_comment("#!/bin/sh\necho hi\n"), None);
assert_eq!(first_comment(""), None);
assert_eq!(
first_comment("#!/bin/sh\r\n# crlf\r\n").as_deref(),
Some("crlf")
);
}
#[test]
fn a_long_description_is_cut_and_says_so() {
let text = format!("# {}\n", "x".repeat(500));
let d = first_comment(&text).unwrap();
assert!(d.ends_with("..."));
assert_eq!(d.chars().count(), MAX_DESCRIPTION_CHARS + 3);
}
#[test]
fn a_missing_directory_lists_as_nothing_rather_than_an_error() {
let tmp = tempfile::tempdir().unwrap();
let listing = list_scripts(&tmp.path().join("scripts")).unwrap();
assert!(!listing.exists && listing.scripts.is_empty());
}
#[tokio::test]
async fn the_list_is_sorted_and_carries_each_scripts_description() {
let tmp = tempfile::tempdir().unwrap();
write_script(tmp.path(), "zeta.sh", "#!/bin/sh\n# Last one\n", 0o755);
write_script(tmp.path(), "alpha.sh", "#!/bin/sh\n# First one\n", 0o755);
write_script(tmp.path(), "bare", "echo no comment\n", 0o755);
write_script(tmp.path(), ".hidden", "# secret\n", 0o755);
std::fs::create_dir(tmp.path().join("subdir")).unwrap();
let out = call(&tool(tmp.path()), json!({"list": true}))
.await
.unwrap();
let lines: Vec<&str> = out.lines().skip(1).collect();
assert_eq!(
lines,
["alpha.sh: First one", "bare", "zeta.sh: Last one"],
"{out}"
);
assert!(out.starts_with(&format!("scripts directory: {}", tmp.path().display())));
}
#[tokio::test]
async fn listing_an_empty_or_missing_directory_says_there_are_none() {
let tmp = tempfile::tempdir().unwrap();
let missing = tmp.path().join("scripts");
let out = call(&tool(&missing), json!({"list": true})).await.unwrap();
assert!(
out.contains("no scripts") && out.contains("does not exist yet"),
"{out}"
);
std::fs::create_dir(&missing).unwrap();
let out = call(&tool(&missing), json!({"list": true})).await.unwrap();
assert!(
out.contains("no scripts") && !out.contains("does not exist"),
"{out}"
);
}
#[cfg(unix)]
#[tokio::test]
async fn a_file_that_is_not_executable_is_listed_and_flagged() {
let tmp = tempfile::tempdir().unwrap();
write_script(tmp.path(), "later.sh", "# not yet\n", 0o644);
let out = call(&tool(tmp.path()), json!({"list": true}))
.await
.unwrap();
assert!(
out.contains("later.sh (not executable: needs chmod +x): not yet"),
"{out}"
);
}
#[cfg(unix)]
#[tokio::test]
async fn a_listing_never_reads_through_a_symlink_that_leaves_the_directory() {
let tmp = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
write_script(outside.path(), "secret", "# TOP-SECRET-LINE\n", 0o755);
let dir = tmp.path().join("scripts");
std::fs::create_dir(&dir).unwrap();
std::os::unix::fs::symlink(outside.path().join("secret"), dir.join("peek")).unwrap();
let out = call(&tool(&dir), json!({"list": true})).await.unwrap();
assert!(out.contains("peek (not runnable"), "{out}");
assert!(!out.contains("TOP-SECRET-LINE"), "{out}");
}
#[tokio::test]
async fn only_the_head_of_a_script_is_read_for_its_description() {
let tmp = tempfile::tempdir().unwrap();
let body = format!(
"#!/bin/sh\n{}\n# too late\n",
"x".repeat(HEAD_BYTES as usize * 4)
);
write_script(tmp.path(), "big.sh", &body, 0o755);
let listing = list_scripts(tmp.path()).unwrap();
assert_eq!(listing.scripts[0].description, None);
}
#[tokio::test]
async fn a_listing_stops_describing_after_a_ceiling_and_says_how_many_it_left_out() {
let tmp = tempfile::tempdir().unwrap();
for i in 0..MAX_LISTED + 5 {
write_script(tmp.path(), &format!("s{i:04}"), "# x\n", 0o755);
}
let out = call(&tool(tmp.path()), json!({"list": true}))
.await
.unwrap();
assert!(
out.contains("[5 more not listed]"),
"{}",
&out[out.len() - 60..]
);
}
#[tokio::test]
async fn list_combined_with_a_name_or_arguments_is_refused_rather_than_guessed() {
let tmp = tempfile::tempdir().unwrap();
let t = tool(tmp.path());
for args in [
json!({"list": true, "name": "x"}),
json!({"list": true, "args": []}),
json!({"list": true, "name": ""}),
] {
let e = call(&t, args).await.unwrap_err();
assert!(
matches!(e, ToolError::InvalidArgs(ref m) if m.contains("cannot be combined")),
"{e}"
);
}
let e = refused(call(&t, json!({"list": false})).await);
assert!(e.contains("give `name`"), "{e}");
let e = refused(call(&t, json!({})).await);
assert!(e.contains("give `name`"), "{e}");
}
#[tokio::test]
async fn a_present_argument_of_the_wrong_type_is_invalid_not_defaulted() {
let tmp = tempfile::tempdir().unwrap();
let t = tool(tmp.path());
for (args, field) in [
(json!({"list": "yes"}), "`list`"),
(json!({"list": 1}), "`list`"),
(json!({"name": 5}), "`name`"),
(json!({"name": ["a"]}), "`name`"),
(json!({"name": "a", "args": "--x"}), "`args`"),
(json!({"name": "a", "args": ["ok", 3]}), "`args[1]`"),
(json!({"name": "a", "args": [null]}), "`args[0]`"),
] {
let e = call(&t, args.clone()).await.unwrap_err();
assert!(
matches!(&e, ToolError::InvalidArgs(m) if m.contains(field)),
"{args}: {e}"
);
}
}
#[cfg(unix)]
#[tokio::test]
async fn a_script_runs_with_its_arguments_from_the_scripts_directory() {
let tmp = tempfile::tempdir().unwrap();
write_script(
tmp.path(),
"show.sh",
"#!/bin/sh\necho \"args: $1|$2\"\necho \"cwd: $(pwd)\"\necho \"dir: $ECLIPSE_SCRIPTS_DIR\"\necho oops >&2\nexit 3\n",
0o755,
);
let out = call(
&tool(tmp.path()),
json!({"name": "show.sh", "args": ["--dry-run", "two words"]}),
)
.await
.unwrap();
let canon = std::fs::canonicalize(tmp.path()).unwrap();
assert!(out.starts_with("exit code: 3\n"), "{out}");
assert!(out.contains("args: --dry-run|two words"), "{out}");
assert!(out.contains(&format!("cwd: {}", canon.display())), "{out}");
assert!(
out.contains(&format!("dir: {}", tmp.path().display())),
"{out}"
);
assert!(out.contains("stderr:\noops"), "{out}");
}
#[cfg(unix)]
#[tokio::test]
async fn a_read_only_promise_without_bubblewrap_refuses_a_script_too() {
let tmp = tempfile::tempdir().unwrap();
let marker = tmp.path().join("ran");
write_script(
tmp.path(),
"touch-marker.sh",
&format!("#!/bin/sh\ntouch {}\n", marker.display()),
0o755,
);
let tool = tool(tmp.path()).with_sandbox(crate::sandbox::Sandbox::without_bwrap(
crate::config::ShellIsolate::Fs,
));
let e = call(&tool, json!({"name": "touch-marker.sh"}))
.await
.unwrap_err()
.to_string();
assert!(e.contains("which is not on PATH"), "{e}");
assert!(!marker.exists(), "the script must not have run");
}
#[cfg(unix)]
#[tokio::test]
async fn a_script_has_no_stdin_and_sees_its_directory_first_on_path() {
let tmp = tempfile::tempdir().unwrap();
write_script(tmp.path(), "helper", "#!/bin/sh\necho from-helper\n", 0o755);
write_script(
tmp.path(),
"main.sh",
"#!/bin/sh\ncat | wc -c\nhelper\n",
0o755,
);
let out = call_retrying(&tool(tmp.path()), json!({"name": "main.sh"}))
.await
.unwrap();
assert!(out.contains("exit code: 0"), "{out}");
assert!(
out.contains("\n0\n"),
"stdin reads end-of-file at once: {out}"
);
assert!(out.contains("from-helper"), "{out}");
}
#[cfg(unix)]
#[tokio::test]
async fn a_name_that_is_not_a_plain_file_name_in_the_directory_is_refused_with_a_reason() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("scripts");
write_script(&dir, "ok.sh", "#!/bin/sh\necho ok\n", 0o755);
write_script(&dir, "plain.txt", "echo no\n", 0o644);
write_script(tmp.path(), "outside.sh", "echo out\n", 0o755);
std::fs::create_dir(dir.join("adir")).unwrap();
let t = tool(&dir);
let absolute = tmp.path().join("outside.sh").display().to_string();
for (name, why) in [
("", "empty"),
(" ", "empty"),
("../outside.sh", "path separator"),
("sub/ok.sh", "path separator"),
("sub\\ok.sh", "path separator"),
("..", "`..`"),
("a..b", "`..`"),
(absolute.as_str(), "absolute path"),
("/etc/passwd", "absolute path"),
("missing.sh", "no such file"),
("adir", "not a regular file"),
("plain.txt", "chmod +x"),
] {
let e = refused(call(&t, json!({"name": name})).await);
assert!(
e.contains(&format!("script {name:?} refused")),
"{name:?}: {e}"
);
assert!(e.contains(why), "{name:?} should say {why:?}: {e}");
}
assert!(call(&t, json!({"name": "ok.sh"}))
.await
.unwrap()
.contains("ok"));
}
#[cfg(unix)]
#[tokio::test]
async fn a_symlink_out_of_the_directory_is_refused_and_one_inside_is_not() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("scripts");
let target = write_script(
tmp.path(),
"elsewhere.sh",
"#!/bin/sh\necho escaped\n",
0o755,
);
std::fs::create_dir_all(&dir).unwrap();
std::os::unix::fs::symlink(&target, dir.join("out")).unwrap();
write_script(&dir, "real.sh", "#!/bin/sh\necho real\n", 0o755);
std::os::unix::fs::symlink(dir.join("real.sh"), dir.join("alias")).unwrap();
std::os::unix::fs::symlink(dir.join("nowhere"), dir.join("dangling")).unwrap();
let t = tool(&dir);
let e = refused(call(&t, json!({"name": "out"})).await);
assert!(e.contains("outside the scripts directory"), "{e}");
let ok = call(&t, json!({"name": "alias"})).await.unwrap();
assert!(ok.contains("real"), "{ok}");
let e = refused(call(&t, json!({"name": "dangling"})).await);
assert!(e.contains("no such file"), "{e}");
}
#[cfg(unix)]
#[tokio::test]
async fn a_script_with_no_shebang_says_what_to_add_instead_of_a_bare_os_error() {
let tmp = tempfile::tempdir().unwrap();
write_script(tmp.path(), "bare.sh", "echo hi\n", 0o755);
let e = refused(call(&tool(tmp.path()), json!({"name": "bare.sh"})).await);
assert!(e.contains("no `#!` line") && e.contains("#!/bin/sh"), "{e}");
}
#[tokio::test]
async fn a_directory_that_does_not_exist_refuses_a_name_and_says_so() {
let tmp = tempfile::tempdir().unwrap();
let t = tool(&tmp.path().join("scripts"));
let e = refused(call(&t, json!({"name": "x.sh"})).await);
assert!(e.contains("does not exist yet"), "{e}");
}
#[cfg(unix)]
#[tokio::test]
async fn a_script_that_overruns_the_timeout_is_killed_with_the_child_it_started() {
let tmp = tempfile::tempdir().unwrap();
write_script(
tmp.path(),
"hang.sh",
"#!/bin/sh\nsleep 300 &\necho $! > child.pid\nwait\n",
0o755,
);
let mut t = tool(tmp.path());
t.timeout = Duration::from_secs(1);
t.kill_grace = Duration::from_millis(300);
let started = std::time::Instant::now();
let e = refused(call(&t, json!({"name": "hang.sh"})).await);
assert!(e.contains("timed out after 1s"), "{e}");
assert!(started.elapsed() < Duration::from_secs(8));
let pid: i32 = std::fs::read_to_string(tmp.path().join("child.pid"))
.unwrap()
.trim()
.parse()
.unwrap();
for _ in 0..100 {
if !process_alive(pid) {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
let alive = process_alive(pid);
assert!(!alive, "child {pid} survived the timeout");
}
#[cfg(unix)]
#[tokio::test]
async fn a_script_that_floods_its_output_is_cut_at_the_cap() {
let tmp = tempfile::tempdir().unwrap();
write_script(tmp.path(), "flood.sh", "#!/bin/sh\nyes\n", 0o755);
let t = ScriptTool::new(tmp.path().to_path_buf(), Duration::from_secs(10), 256);
let out = call(&t, json!({"name": "flood.sh"})).await.unwrap();
assert!(out.contains("[truncated]"), "{out}");
assert!(out.len() < 400, "{}", out.len());
}
#[test]
fn an_approval_prompt_names_the_script_and_its_arguments() {
let tmp = tempfile::tempdir().unwrap();
let t = tool(tmp.path());
let with = t.describe_call(&json!({"name": "backup-media", "args": ["--dry-run"]}));
assert!(
with.contains("backup-media") && with.contains("--dry-run"),
"{with}"
);
assert!(with.contains(&tmp.path().display().to_string()), "{with}");
let without = t.describe_call(&json!({"name": "backup-media"}));
assert!(
without.contains("backup-media") && !without.contains("arguments"),
"{without}"
);
assert_eq!(t.describe_call(&json!({"list": true})), "list the scripts");
let odd = t.describe_call(&json!({"name": "a\nb", "args": 5}));
assert!(!odd.contains('\n'), "{odd}");
}
struct Counting(AtomicUsize);
#[async_trait]
impl Approver for Counting {
async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
self.0.fetch_add(1, Ordering::SeqCst);
crate::approvals::Decision::Deny("no".to_string())
}
}
#[tokio::test]
async fn under_ask_a_listing_is_answered_without_a_prompt_and_a_run_is_not() {
let tmp = tempfile::tempdir().unwrap();
write_script(tmp.path(), "a.sh", "# a\n", 0o755);
let mut registry = ToolRegistry::new(4096);
registry.register(Arc::new(tool(tmp.path())), Policy::Ask);
let approver = Counting(AtomicUsize::new(0));
let out = registry
.dispatch("script", r#"{"list":true}"#, &approver)
.await;
assert!(
!out.is_error && out.output.contains("a.sh: a"),
"{}",
out.output
);
assert_eq!(
approver.0.load(Ordering::SeqCst),
0,
"a listing is not asked about"
);
for call in [
r#"{"name":"a.sh"}"#,
r#"{"list":true,"name":"a.sh"}"#,
r#"{"list":"yes","name":"a.sh"}"#,
r#"{}"#,
] {
let out = registry.dispatch("script", call, &approver).await;
assert!(
out.is_error && out.output.contains("declined"),
"{call}: {}",
out.output
);
}
assert_eq!(approver.0.load(Ordering::SeqCst), 4);
let mut registry = ToolRegistry::new(4096);
registry.register(Arc::new(tool(tmp.path())), Policy::Deny);
let out = registry
.dispatch("script", r#"{"list":true}"#, &AllowAll)
.await;
assert!(out.is_error && out.output.contains("disabled by policy"));
}
#[test]
fn the_description_names_the_scripts_there_were_and_points_at_list_for_the_rest() {
let tmp = tempfile::tempdir().unwrap();
let empty = tool(tmp.path());
assert!(empty.description().contains("no scripts yet"));
assert!(empty
.description()
.contains(&tmp.path().display().to_string()));
for i in 0..MAX_NAMED_IN_DESCRIPTION + 3 {
write_script(tmp.path(), &format!("s{i:02}.sh"), "# x\n", 0o755);
}
let full = tool(tmp.path());
let d = full.description();
assert!(d.contains("s00.sh") && d.contains("and 3 more"), "{d}");
assert!(
!d.contains(&format!("s{:02}.sh", MAX_NAMED_IN_DESCRIPTION)),
"{d}"
);
assert!(d.contains("`list`"), "{d}");
}
#[test]
fn the_tool_registers_with_a_schema_that_needs_no_arguments_to_be_present() {
let tmp = tempfile::tempdir().unwrap();
let cfg = ToolsConfig::default();
let registry = ToolRegistry::from_config_full(
&cfg,
tmp.path().to_path_buf(),
Vec::new(),
Some(tmp.path().join("scripts")),
);
let d = registry
.descriptors()
.into_iter()
.find(|d| d.name == "script")
.expect("script is registered");
assert_eq!(d.policy, Policy::Ask);
assert_eq!(
d.parameters["properties"]["args"]["items"]["type"],
"string"
);
assert!(d.parameters.get("required").is_none());
}
}