agent: share_file tool + containment-checked download endpoint

The agent can hand the user a same-origin download link for a file on its
filesystem (outbound complement to uploads). share_file(path, name?) returns a
Markdown link the GUI renders as a download chip.

Safety is containment, not trust: a shared path must canonicalize inside the
session personal folder or the shared uploads/ dir (.. and symlink escapes
refused), regular files only, 64 MiB cap. GET /api/sessions/{id}/download
re-validates independently (author != verifier), forces attachment +
application/octet-stream + nosniff, bare 400 out-of-bounds, 404 unknown session.

TOOL_USE seed migration appends the share_file manual without clobbering
user-edited rows. README documents the tool surface, endpoint and boundary;
Status refreshed to the verified 191 passed / 3 ignored.
This commit is contained in:
adm committed 2026-11-29 01:23:18 +01:00
1 parent 28568f0e89
commit 2f5b263d4e
11 files changed
+668 -15

No files matched your search

+26 -6
View File
@@ -10,6 +10,7 @@
//! testable without the engine and independent of the concrete runner.
pub mod notepad;
pub mod share;
pub mod shell;
use std::future::Future;
@@ -26,12 +27,14 @@ use shell::{ShellRequest, ShellRunner};
/// Default cap on model↔tool iterations, so a misbehaving model cannot loop forever.
pub const MAX_ITERS: usize = 24;
/// The tools offered to the agent: the universal `shell_exec` (action) and the
/// `notepad` (per-session context management).
/// The tools offered to the agent: the universal `shell_exec` (action), the
/// `notepad` (per-session context management) and `share_file` (hand the user a
/// download link for a file the agent has on disk).
pub fn agent_tools() -> Json {
json!([
shell::shell_exec_declaration(),
notepad::notepad_declaration()
notepad::notepad_declaration(),
share::share_file_declaration()
])
}
@@ -78,6 +81,7 @@ async fn execute_tool(
session_id: &str,
tc: &ToolCall,
default_cwd: Option<&str>,
workspace_root: Option<&std::path::Path>,
) -> String {
let args: Json = match serde_json::from_str(&tc.function.arguments) {
Ok(v) => v,
@@ -96,6 +100,7 @@ async fn execute_tool(
}
}
"notepad" => notepad::execute(store, session_id, &args).await,
"share_file" => share::execute(session_id, &args, default_cwd, workspace_root).await,
other => format!("error: unknown tool '{other}'"),
}
}
@@ -142,6 +147,9 @@ pub struct LoopContext {
pub runner: Arc<dyn ShellRunner>,
pub store: Arc<dyn Store>,
pub default_cwd: Option<String>,
/// Parent of the per-session folders and the shared uploads dir; the second
/// root `share_file` may expose files from. None in tests without a workspace.
pub workspace_root: Option<std::path::PathBuf>,
pub max_iters: usize,
pub progress: Option<UnboundedSender<AgentEvent>>,
}
@@ -166,6 +174,7 @@ where
runner,
store,
default_cwd,
workspace_root,
max_iters,
progress,
} = ctx;
@@ -229,8 +238,15 @@ where
arguments: tc.function.arguments.clone(),
},
);
let output =
execute_tool(&runner, &store, session_id, tc, default_cwd.as_deref()).await;
let output = execute_tool(
&runner,
&store,
session_id,
tc,
default_cwd.as_deref(),
workspace_root.as_deref(),
)
.await;
emit(
&progress,
AgentEvent::ToolResult {
@@ -386,6 +402,7 @@ mod tests {
runner,
store: store.clone(),
default_cwd: None,
workspace_root: None,
max_iters: 8,
progress: Some(tx),
},
@@ -441,6 +458,7 @@ mod tests {
runner,
store,
default_cwd: None,
workspace_root: None,
max_iters: 3,
progress: None,
},
@@ -471,7 +489,7 @@ mod tests {
arguments: "{}".into(),
},
};
let out = execute_tool(&runner, &store, &sess.id, &tc, None).await;
let out = execute_tool(&runner, &store, &sess.id, &tc, None, None).await;
assert!(out.contains("unknown tool"));
}
@@ -520,6 +538,7 @@ mod tests {
runner,
store: store.clone(),
default_cwd: None,
workspace_root: None,
max_iters: 8,
progress: None,
},
@@ -584,6 +603,7 @@ mod tests {
runner,
store: store.clone(),
default_cwd: Some("/tmp".into()),
workspace_root: None,
max_iters: 8,
progress: None,
},
+368
View File
@@ -0,0 +1,368 @@
//! The agent's `share_file` tool: expose a file the agent has on disk as a
//! download link the user can click in the web chat.
//!
//! The model calls `share_file(path, name?)`; the server validates the path and
//! hands back a ready Markdown link (`[name](/api/sessions/{id}/download?…)`)
//! that the model pastes into its reply. The GUI renders it clickable (relative
//! URLs pass [`crate::render`]'s scheme allowlist) and the download endpoint
//! serves the bytes as an attachment.
//!
//! Security boundary (the tool is NOT trusted by the endpoint — both validate
//! independently via [`validate_shared`]): a shareable file must be a regular
//! file, within a size cap, and contained in one of two roots only — the
//! session's personal folder and the shared `uploads` dir. Paths are
//! canonicalized first, so `..` traversal and symlink escapes are rejected.
use std::path::{Path, PathBuf};
use serde_json::{json, Value as Json};
/// Cap on a shareable/downloadable file. The endpoint reads the file into memory
/// to serve it, so this bounds both abuse and peak RSS. Generous for chat
/// artifacts (reports, scripts, datasets, images, archives).
pub const MAX_SHARE_BYTES: u64 = 64 * 1024 * 1024;
/// The OpenAI function declaration offered to the model for the agent.
pub fn share_file_declaration() -> Json {
json!({
"type": "function",
"function": {
"name": "share_file",
"description": "Expose a file you have on disk as a download link the user can click \
in the web chat. Call this when you produce a file the user should download (a \
report, script, dataset, image, archive...). It returns a ready Markdown link: \
paste that link verbatim into your reply so the user can download the file. Only \
regular files inside your personal session folder or the shared uploads folder \
are allowed (max 64 MiB); anything else is refused. `path` may be absolute or \
relative to your personal folder; `name` optionally overrides the download filename.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Path of the file to share (absolute, or relative to your personal folder)."
},
"name": {
"type": "string",
"description": "Optional download filename shown to the user (defaults to the file's own name)."
}
},
"required": ["path"]
}
}
})
}
/// The only roots a shared file may live in: the session's personal folder and
/// the shared uploads dir. Shared by the tool and the download endpoint so the
/// containment rule has a single source of truth.
pub fn allowed_roots(folder: Option<&str>, workspace_root: Option<&Path>) -> Vec<PathBuf> {
let mut roots = Vec::new();
if let Some(f) = folder {
roots.push(PathBuf::from(f));
}
if let Some(w) = workspace_root {
roots.push(w.join("uploads"));
}
roots
}
/// Validate that `path` is a shareable file: canonicalize (resolving symlinks and
/// `..`), require a regular file within the size cap, and require containment in
/// one of `roots` (each canonicalized). Returns the canonical path and its size.
/// The error string is safe to show the model; it never echoes file contents.
pub fn validate_shared(path: &Path, roots: &[PathBuf]) -> Result<(PathBuf, u64), String> {
let canon = path
.canonicalize()
.map_err(|_| format!("file not found: {}", path.display()))?;
let meta = std::fs::metadata(&canon).map_err(|e| format!("cannot stat file: {e}"))?;
if !meta.is_file() {
return Err("not a regular file (directories and devices cannot be shared)".into());
}
let size = meta.len();
if size > MAX_SHARE_BYTES {
return Err(format!(
"file too large ({size} > {MAX_SHARE_BYTES} bytes); share a smaller file"
));
}
let contained = roots.iter().any(|root| {
root.canonicalize()
.map(|rc| canon.starts_with(&rc))
.unwrap_or(false)
});
if !contained {
return Err("path is outside the allowed folders (your personal folder or uploads)".into());
}
Ok((canon, size))
}
/// Percent-encode a query value (RFC 3986 unreserved set kept literal). Space
/// becomes `%20` and `+` becomes `%2B`, so form decoding never misreads them.
pub fn pct_encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.as_bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
out.push(*b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
/// A safe download filename: an explicit `name` override or the file's own name,
/// stripped of control chars, quotes, backslashes and separators. Never empty.
pub fn display_name(path: &Path, name: Option<&str>) -> String {
let base = match name {
Some(n) if !n.trim().is_empty() => n.trim().to_string(),
_ => path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "download".to_string()),
};
let san: String = base
.chars()
.filter(|c| !c.is_control() && !matches!(c, '"' | '\\' | '/'))
.collect();
let san = san.trim().to_string();
if san.is_empty() {
"download".to_string()
} else {
san
}
}
/// The relative download URL the model pastes as a Markdown link.
pub fn download_url(session_id: &str, path: &Path, name: Option<&str>) -> String {
let mut url = format!(
"/api/sessions/{session_id}/download?path={}",
pct_encode(&path.to_string_lossy())
);
if let Some(n) = name {
url.push_str(&format!("&name={}", pct_encode(n)));
}
url
}
/// Execute a `share_file` tool call, returning the text the model reads as the
/// tool result (a ready-to-paste Markdown link on success). Filesystem work runs
/// off the async runtime.
pub async fn execute(
session_id: &str,
args: &Json,
default_cwd: Option<&str>,
workspace_root: Option<&Path>,
) -> String {
let path_arg = args
.get("path")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
let name_arg = args
.get("name")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
if path_arg.is_empty() {
return "error: share_file requires a non-empty 'path'".into();
}
let raw = PathBuf::from(&path_arg);
let abs = if raw.is_absolute() {
raw
} else {
match default_cwd {
Some(c) => Path::new(c).join(raw),
None => {
return "error: relative path given but the session has no personal folder yet"
.into()
}
}
};
let roots = allowed_roots(default_cwd, workspace_root);
let sid = session_id.to_string();
let res = tokio::task::spawn_blocking(move || validate_shared(&abs, &roots)).await;
match res {
Ok(Ok((canon, size))) => {
let name = display_name(&canon, name_arg.as_deref());
let url = download_url(&sid, &canon, Some(&name));
format!(
"File '{name}' is ready ({size} bytes). Paste this Markdown link in your reply so \
the user can download it: [{name}]({url})"
)
}
Ok(Err(e)) => format!("error: {e}"),
Err(e) => format!("error: share_file task failed: {e}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
fn tmpdir() -> PathBuf {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("strata_share_{nanos:016x}{n:08x}"));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn declaration_shape() {
let d = share_file_declaration();
assert_eq!(d["type"], "function");
assert_eq!(d["function"]["name"], "share_file");
assert_eq!(d["function"]["parameters"]["required"][0], "path");
}
#[test]
fn validate_accepts_contained_file_and_rejects_outside() {
let root = tmpdir();
let inside = root.join("ok.txt");
std::fs::write(&inside, b"ciao").unwrap();
let roots = vec![root.clone()];
let (canon, size) = validate_shared(&inside, &roots).unwrap();
assert_eq!(size, 4);
assert!(canon.starts_with(root.canonicalize().unwrap()));
// A file outside every root is refused.
let outside =
std::env::temp_dir().join(format!("strata_outside_{}.txt", std::process::id()));
std::fs::write(&outside, b"x").unwrap();
assert!(validate_shared(&outside, &roots).is_err());
let _ = std::fs::remove_file(&outside);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn validate_rejects_traversal_and_symlink_escape() {
let root = tmpdir();
let outside = tmpdir();
let secret = outside.join("secret.txt");
std::fs::write(&secret, b"top secret").unwrap();
let roots = vec![root.clone()];
// `..` traversal out of the root.
let traversal = root
.join("../")
.join(outside.file_name().unwrap())
.join("secret.txt");
assert!(validate_shared(&traversal, &roots).is_err());
// A symlink inside the root pointing outside resolves out -> refused.
let link = root.join("link.txt");
#[cfg(unix)]
std::os::unix::fs::symlink(&secret, &link).unwrap();
#[cfg(unix)]
assert!(validate_shared(&link, &roots).is_err());
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(&outside);
}
#[test]
fn validate_rejects_directory_and_oversize() {
let root = tmpdir();
let roots = vec![root.clone()];
// A directory is not a regular file.
assert!(validate_shared(&root, &roots).is_err());
// Sparse file just over the cap (set_len is cheap, no real bytes written).
let big = root.join("big.bin");
let f = std::fs::File::create(&big).unwrap();
f.set_len(MAX_SHARE_BYTES + 1).unwrap();
drop(f);
let err = validate_shared(&big, &roots).unwrap_err();
assert!(err.contains("too large"), "{err}");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn pct_encode_keeps_unreserved_and_escapes_rest() {
assert_eq!(pct_encode("aZ09-._~"), "aZ09-._~");
assert_eq!(pct_encode("a b"), "a%20b");
assert_eq!(pct_encode("a+b"), "a%2Bb");
assert_eq!(pct_encode("/x/y.txt"), "%2Fx%2Fy.txt");
assert_eq!(pct_encode("à"), "%C3%A0");
}
#[test]
fn display_name_sanitizes_and_falls_back() {
let p = Path::new("/tmp/report.pdf");
assert_eq!(display_name(p, None), "report.pdf");
assert_eq!(display_name(p, Some("mio file.pdf")), "mio file.pdf");
assert_eq!(display_name(p, Some("a\"b\\c/d")), "abcd");
assert_eq!(display_name(p, Some(" ")), "report.pdf");
assert_eq!(display_name(Path::new("/"), None), "download");
}
#[test]
fn download_url_encodes_path_and_name() {
let url = download_url("sess_1", Path::new("/tmp/a b.txt"), Some("a b.txt"));
assert!(
url.starts_with("/api/sessions/sess_1/download?path="),
"{url}"
);
assert!(url.contains("%2Ftmp%2Fa%20b.txt"), "{url}");
assert!(url.contains("&name=a%20b.txt"), "{url}");
}
#[tokio::test]
async fn execute_relative_path_resolves_against_cwd_and_returns_link() {
let root = tmpdir();
std::fs::write(root.join("out.csv"), b"a,b\n1,2\n").unwrap();
let out = execute(
"sess_x",
&json!({"path": "out.csv"}),
Some(root.to_str().unwrap()),
None,
)
.await;
assert!(out.contains("[out.csv]"), "{out}");
assert!(out.contains("/api/sessions/sess_x/download?path="), "{out}");
let _ = std::fs::remove_dir_all(&root);
}
#[tokio::test]
async fn execute_rejects_empty_missing_and_outside() {
let root = tmpdir();
assert!(execute(
"s",
&json!({"path": ""}),
Some(root.to_str().unwrap()),
None
)
.await
.contains("non-empty"));
assert!(execute(
"s",
&json!({"path": "nope.txt"}),
Some(root.to_str().unwrap()),
None
)
.await
.contains("not found"));
// Absolute path outside the roots is refused even with a cwd set.
let outside =
std::env::temp_dir().join(format!("strata_exec_out_{}.txt", std::process::id()));
std::fs::write(&outside, b"x").unwrap();
let out = execute(
"s",
&json!({"path": outside.to_str().unwrap()}),
Some(root.to_str().unwrap()),
None,
)
.await;
assert!(out.contains("outside"), "{out}");
let _ = std::fs::remove_file(&outside);
let _ = std::fs::remove_dir_all(&root);
}
#[tokio::test]
async fn execute_relative_without_folder_is_refused() {
let out = execute("s", &json!({"path": "rel.txt"}), None, None).await;
assert!(out.contains("no personal folder"), "{out}");
}
}