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 -5
View File
@@ -112,6 +112,11 @@ offline, same-origin so no CORS). It is a thin client over a **session-aware API
- `GET/PUT /api/settings/defaults` — the global default settings template. - `GET/PUT /api/settings/defaults` — the global default settings template.
- `POST /api/uploads` — store an uploaded file (base64) in the shared upload dir; - `POST /api/uploads` — store an uploaded file (base64) in the shared upload dir;
returns metadata (kind, token count, path). Attach the returned id to a chat turn. returns metadata (kind, token count, path). Attach the returned id to a chat turn.
- `GET /api/sessions/{id}/download?path=…&name=…` — serve a file the agent shared
via `share_file` as an attachment (`application/octet-stream`,
`Content-Disposition: attachment`, `X-Content-Type-Options: nosniff`). The path is
re-validated server-side against the session's allowed roots (see **Agent mode**);
an out-of-bounds path is a 400, an unknown session a 404 — no bytes leak.
- `PATCH /api/sessions/{id}` — rename (only before the first interaction) and/or - `PATCH /api/sessions/{id}` — rename (only before the first interaction) and/or
replace the session's own settings instance. replace the session's own settings instance.
@@ -202,9 +207,11 @@ copied into `data/` once on first run (the original is left in place).
## Agent mode ## Agent mode
The GUI model can **act**, not just chat. Tools are **always on** — there is no The GUI model can **act**, not just chat. Tools are **always on** — there is no
toggle, because the framework could not function without them. The agent has a single toggle, because the framework could not function without them. The agent's tool
universal tool, **`shell_exec`** (a shell is universal: file ops, programs, system surface is small and deliberate: **`shell_exec`** (a shell is universal: file ops,
inspection, web via curl, git, …). A bounded server-side loop drives programs, system inspection, web via curl, git, …), **`notepad`** (agent-curated
persistent memory, see below) and **`share_file`** (hand the user a download link
for a file on its filesystem, see below). A bounded server-side loop drives
`model → shell_exec → result → model → … → final answer`, persisting the whole `model → shell_exec → result → model → … → final answer`, persisting the whole
trajectory and streaming progress events — `delta` (the model's thinking and final trajectory and streaming progress events — `delta` (the model's thinking and final
answer, token by token), `tool_call` / `tool_result` (every command and its output answer, token by token), `tool_call` / `tool_result` (every command and its output
@@ -220,6 +227,19 @@ isolated machine; the agent then only ever sees that environment. Execution sits
behind a `ShellRunner` trait (useful for tests and alternate runners), with no behind a `ShellRunner` trait (useful for tests and alternate runners), with no
per-call confirmation gate and no separate "isolated" tool backend. per-call confirmation gate and no separate "isolated" tool backend.
**Sharing a file (`share_file`).** When the agent produces a file the user should
be able to download, it calls `share_file(path, name?)`; the tool returns a
same-origin Markdown link (`[name](/api/sessions/{id}/download?path=…)`) the model
pastes into its reply, and the GUI renders it as a download chip. This is the
outbound complement to uploads. The safety boundary is **containment, not trust**:
a shared path must canonicalize inside one of two allowed roots — the session's
**personal folder** or the shared **`uploads/`** dir — so `..` traversal and symlink
escapes are refused, only regular files are served, and a **64 MiB** cap applies.
The download endpoint re-validates independently (author ≠ verifier): it never
trusts the tool's earlier check, forces `Content-Disposition: attachment` +
`application/octet-stream` + `nosniff` (no inline rendering of model-chosen bytes),
and returns a bare 400 on any out-of-bounds path without leaking existence or bytes.
## Architecture ## Architecture
``` ```
@@ -298,9 +318,10 @@ later adaptation round.
## Status ## Status
Working and tested (162 tests, plus 3 real-file tests run on demand). Text, images, Working and tested (191 tests, plus 3 real-file tests run on demand). Text, images,
the full client-side tool loop, the Anthropic endpoint, the web GUI (session the full client-side tool loop, the Anthropic endpoint, the web GUI (session
context, streaming, stats, **file/image upload**, assistant **Markdown/LaTeX context, streaming, stats, **file/image upload**, **file download** (`share_file`
→ containment-checked attachment endpoint), assistant **Markdown/LaTeX
rendering** with native MathML) and **agent mode** (the model using `shell_exec` rendering** with native MathML) and **agent mode** (the model using `shell_exec`
on the host) have been validated live against the real Inkling engine. The on the host) have been validated live against the real Inkling engine. The
**context compositor** (named sections stored in SQLite — `SYSTEM_PROMPT` / **context compositor** (named sections stored in SQLite — `SYSTEM_PROMPT` /
+26 -6
View File
@@ -10,6 +10,7 @@
//! testable without the engine and independent of the concrete runner. //! testable without the engine and independent of the concrete runner.
pub mod notepad; pub mod notepad;
pub mod share;
pub mod shell; pub mod shell;
use std::future::Future; 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. /// Default cap on model↔tool iterations, so a misbehaving model cannot loop forever.
pub const MAX_ITERS: usize = 24; pub const MAX_ITERS: usize = 24;
/// The tools offered to the agent: the universal `shell_exec` (action) and the /// The tools offered to the agent: the universal `shell_exec` (action), the
/// `notepad` (per-session context management). /// `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 { pub fn agent_tools() -> Json {
json!([ json!([
shell::shell_exec_declaration(), 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, session_id: &str,
tc: &ToolCall, tc: &ToolCall,
default_cwd: Option<&str>, default_cwd: Option<&str>,
workspace_root: Option<&std::path::Path>,
) -> String { ) -> String {
let args: Json = match serde_json::from_str(&tc.function.arguments) { let args: Json = match serde_json::from_str(&tc.function.arguments) {
Ok(v) => v, Ok(v) => v,
@@ -96,6 +100,7 @@ async fn execute_tool(
} }
} }
"notepad" => notepad::execute(store, session_id, &args).await, "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}'"), other => format!("error: unknown tool '{other}'"),
} }
} }
@@ -142,6 +147,9 @@ pub struct LoopContext {
pub runner: Arc<dyn ShellRunner>, pub runner: Arc<dyn ShellRunner>,
pub store: Arc<dyn Store>, pub store: Arc<dyn Store>,
pub default_cwd: Option<String>, 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 max_iters: usize,
pub progress: Option<UnboundedSender<AgentEvent>>, pub progress: Option<UnboundedSender<AgentEvent>>,
} }
@@ -166,6 +174,7 @@ where
runner, runner,
store, store,
default_cwd, default_cwd,
workspace_root,
max_iters, max_iters,
progress, progress,
} = ctx; } = ctx;
@@ -229,8 +238,15 @@ where
arguments: tc.function.arguments.clone(), arguments: tc.function.arguments.clone(),
}, },
); );
let output = let output = execute_tool(
execute_tool(&runner, &store, session_id, tc, default_cwd.as_deref()).await; &runner,
&store,
session_id,
tc,
default_cwd.as_deref(),
workspace_root.as_deref(),
)
.await;
emit( emit(
&progress, &progress,
AgentEvent::ToolResult { AgentEvent::ToolResult {
@@ -386,6 +402,7 @@ mod tests {
runner, runner,
store: store.clone(), store: store.clone(),
default_cwd: None, default_cwd: None,
workspace_root: None,
max_iters: 8, max_iters: 8,
progress: Some(tx), progress: Some(tx),
}, },
@@ -441,6 +458,7 @@ mod tests {
runner, runner,
store, store,
default_cwd: None, default_cwd: None,
workspace_root: None,
max_iters: 3, max_iters: 3,
progress: None, progress: None,
}, },
@@ -471,7 +489,7 @@ mod tests {
arguments: "{}".into(), 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")); assert!(out.contains("unknown tool"));
} }
@@ -520,6 +538,7 @@ mod tests {
runner, runner,
store: store.clone(), store: store.clone(),
default_cwd: None, default_cwd: None,
workspace_root: None,
max_iters: 8, max_iters: 8,
progress: None, progress: None,
}, },
@@ -584,6 +603,7 @@ mod tests {
runner, runner,
store: store.clone(), store: store.clone(),
default_cwd: Some("/tmp".into()), default_cwd: Some("/tmp".into()),
workspace_root: None,
max_iters: 8, max_iters: 8,
progress: None, 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}");
}
}
+122
View File
@@ -0,0 +1,122 @@
//! Download endpoint for files the agent shares via the `share_file` tool.
//!
//! `GET /api/sessions/{id}/download?path=…&name=…` serves a shared file as an
//! attachment. The endpoint does NOT trust that the tool ran: it re-validates the
//! path independently against the same containment rule ([`share::validate_shared`])
//! — the session's personal folder and the shared uploads dir, canonicalized, a
//! regular file within the size cap. The bytes are served as
//! `application/octet-stream` with `Content-Disposition: attachment` and
//! `nosniff`, so a shared HTML/SVG file downloads rather than executing inline.
use std::path::Path;
use axum::extract::{Path as AxumPath, Query, State};
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use serde::Deserialize;
use super::routes::{AppState, Error};
use super::sessions::with_store;
use crate::agent::share;
#[derive(Deserialize)]
pub(crate) struct DownloadQuery {
/// Absolute path of the file (as produced by `share_file`).
path: String,
/// Optional download filename override.
#[serde(default)]
name: Option<String>,
}
/// `Content-Disposition: attachment` with an ASCII fallback filename plus an
/// RFC 5987 UTF-8 `filename*` so non-ASCII names survive intact.
fn content_disposition(name: &str) -> String {
let ascii: String = name
.chars()
.map(|c| {
if c.is_ascii() && !c.is_control() && !matches!(c, '"' | '\\') {
c
} else {
'_'
}
})
.collect();
let ascii = if ascii.trim().is_empty() {
"download".to_string()
} else {
ascii
};
format!(
"attachment; filename=\"{ascii}\"; filename*=UTF-8''{}",
share::pct_encode(name)
)
}
pub(crate) async fn download(
State(st): State<AppState>,
AxumPath(id): AxumPath<String>,
Query(q): Query<DownloadQuery>,
) -> Result<Response, Error> {
let sess = with_store(&st, {
let id = id.clone();
move |s| s.get_session(&id)
})
.await?
.ok_or_else(|| Error::not_found("session not found"))?;
let roots = share::allowed_roots(sess.folder.as_deref(), Some(&st.workspace_root));
let (canon, _size) =
share::validate_shared(Path::new(&q.path), &roots).map_err(Error::bad_request)?;
let name = share::display_name(&canon, q.name.as_deref());
// Read off the async runtime; validate_shared already enforced the size cap.
let bytes = tokio::task::spawn_blocking(move || std::fs::read(&canon))
.await
.map_err(|e| Error::internal(format!("download task failed: {e}")))?
.map_err(|e| Error::internal(format!("download read failed: {e}")))?;
let disposition = content_disposition(&name);
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/octet-stream"),
);
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_str(&disposition)
.map_err(|e| Error::internal(format!("bad filename: {e}")))?,
);
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
headers.insert(
header::CONTENT_LENGTH,
HeaderValue::from_str(&bytes.len().to_string())
.map_err(|e| Error::internal(format!("bad length: {e}")))?,
);
Ok((StatusCode::OK, headers, bytes).into_response())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn disposition_is_attachment_with_ascii_and_utf8_names() {
let d = content_disposition("report.pdf");
assert!(d.starts_with("attachment; "), "{d}");
assert!(d.contains("filename=\"report.pdf\""), "{d}");
assert!(d.contains("filename*=UTF-8''report.pdf"), "{d}");
// Non-ASCII gets an ASCII fallback and a percent-encoded UTF-8 name.
let d = content_disposition("relazione àèì.pdf");
assert!(d.contains("filename=\"relazione ___.pdf\""), "{d}");
assert!(
d.contains("filename*=UTF-8''relazione%20%C3%A0%C3%A8%C3%AC.pdf"),
"{d}"
);
// Quotes/backslashes are neutralized in the ASCII fallback.
let d = content_disposition("a\"b\\c");
assert!(d.contains("filename=\"a_b_c\""), "{d}");
}
}
+1
View File
@@ -5,6 +5,7 @@
//! [`routes`] the axum router. //! [`routes`] the axum router.
pub mod anthropic; pub mod anthropic;
mod files;
pub mod formatter; pub mod formatter;
pub mod routes; pub mod routes;
pub mod service; pub mod service;
+2 -1
View File
@@ -15,7 +15,7 @@ use std::sync::Arc;
use super::anthropic::{self, AnthropicRequest, AnthropicStream}; use super::anthropic::{self, AnthropicRequest, AnthropicStream};
use super::service::ChatService; use super::service::ChatService;
use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList}; use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList};
use super::{sessions, uploads, web}; use super::{files, sessions, uploads, web};
use crate::store::Store; use crate::store::Store;
/// Build the router. Mount this inside any axum `Router` or serve it directly. /// Build the router. Mount this inside any axum `Router` or serve it directly.
@@ -81,6 +81,7 @@ fn build_router(state: AppState, auth: AuthConfig) -> Router {
.route("/api/sessions/{id}/messages", get(sessions::get_messages)) .route("/api/sessions/{id}/messages", get(sessions::get_messages))
.route("/api/sessions/{id}/notepad", get(sessions::get_notepad)) .route("/api/sessions/{id}/notepad", get(sessions::get_notepad))
.route("/api/sessions/{id}/chat", post(sessions::session_chat)) .route("/api/sessions/{id}/chat", post(sessions::session_chat))
.route("/api/sessions/{id}/download", get(files::download))
.route( .route(
"/api/uploads", "/api/uploads",
// Uploads arrive as base64 JSON: a 32 MiB decoded file becomes // Uploads arrive as base64 JSON: a 32 MiB decoded file becomes
+2
View File
@@ -559,6 +559,7 @@ pub(crate) async fn session_chat(
let store2 = store.clone(); let store2 = store.clone();
let sid = id.clone(); let sid = id.clone();
let folder = sess.folder.clone(); let folder = sess.folder.clone();
let ws_root = st.workspace_root.clone();
let tx_model = tx.clone(); let tx_model = tx.clone();
let svc_pw = st.service.clone(); let svc_pw = st.service.clone();
let store_pw = store.clone(); let store_pw = store.clone();
@@ -632,6 +633,7 @@ pub(crate) async fn session_chat(
runner, runner,
store: store2, store: store2,
default_cwd: folder, default_cwd: folder,
workspace_root: Some(ws_root),
max_iters: agent::MAX_ITERS, max_iters: agent::MAX_ITERS,
progress: Some(tx.clone()), progress: Some(tx.clone()),
}, },
+15 -3
View File
@@ -202,7 +202,11 @@ pub struct NotepadEntry {
/// the DB rows are the source of truth afterwards). /// the DB rows are the source of truth afterwards).
const SYSTEM_PROMPT_SECTION: &str = "{identity}{speaker_note}\n{session_prompt}"; const SYSTEM_PROMPT_SECTION: &str = "{identity}{speaker_note}\n{session_prompt}";
const TOOL_USE_SECTION_PRE_NOTEPAD: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti."; const TOOL_USE_SECTION_PRE_NOTEPAD: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti.";
const TOOL_USE_SECTION: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti. notepad(action, key?, text?) gestisce il tuo blocco appunti persistente, sempre visibile sopra il dialogo: action=set crea o aggiorna la entry etichettata `key` con `text` (upsert idempotente); action=remove cancella la entry `key`; action=clear svuota tutto. Fissa qui ciò che deve sopravvivere allo scorrere della finestra di contesto: goal, decisioni e razionale, stato/next-step, vincoli, pitfall, path e identificatori chiave. Non usarlo per log o documenti lunghi né per dati effimeri del singolo task. È bounded: quando si avvicina al limite consolida le entry vecchie; non c'è eviction automatica, decidi tu cosa tenere. Tieni le entry brevi."; const TOOL_USE_SECTION_PRE_SHARE: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti. notepad(action, key?, text?) gestisce il tuo blocco appunti persistente, sempre visibile sopra il dialogo: action=set crea o aggiorna la entry etichettata `key` con `text` (upsert idempotente); action=remove cancella la entry `key`; action=clear svuota tutto. Fissa qui ciò che deve sopravvivere allo scorrere della finestra di contesto: goal, decisioni e razionale, stato/next-step, vincoli, pitfall, path e identificatori chiave. Non usarlo per log o documenti lunghi né per dati effimeri del singolo task. È bounded: quando si avvicina al limite consolida le entry vecchie; non c'è eviction automatica, decidi tu cosa tenere. Tieni le entry brevi.";
/// Prose appended to the notepad-era TOOL_USE manual to document `share_file`.
/// Kept separate so the seed can refresh untouched older rows without duplicating
/// the long notepad text (and never clobber a user-edited section).
const SHARE_FILE_SUFFIX: &str = " share_file(path, name?) espone un file che hai su disco come link di scaricamento cliccabile nella chat web: restituisce un link Markdown già pronto da incollare testualmente nella risposta per l'utente. Usalo quando produci un file che l'utente deve scaricare (report, script, dati, immagini, archivi). Sono ammessi solo file regolari dentro la tua cartella personale o la cartella uploads condivisa, entro 64 MiB; `path` può essere assoluto o relativo alla tua cartella personale, `name` opzionalmente sostituisce il nome del file scaricato.";
/// The storage interface. Synchronous; call via `spawn_blocking` from async code. /// The storage interface. Synchronous; call via `spawn_blocking` from async code.
pub trait Store: Send + Sync { pub trait Store: Send + Sync {
@@ -405,19 +409,27 @@ fn migrate(conn: &Connection) -> Result<()> {
/// Seed the static context sections once (idempotent); afterwards the stored /// Seed the static context sections once (idempotent); afterwards the stored
/// rows are authoritative and editable. /// rows are authoritative and editable.
fn seed_context_sections(conn: &Connection) -> Result<()> { fn seed_context_sections(conn: &Connection) -> Result<()> {
// The current TOOL_USE manual = notepad-era prose + the share_file paragraph.
let tool_use = format!("{TOOL_USE_SECTION_PRE_SHARE}{SHARE_FILE_SUFFIX}");
conn.execute( conn.execute(
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('SYSTEM_PROMPT', ?1, 0)", "INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('SYSTEM_PROMPT', ?1, 0)",
params![SYSTEM_PROMPT_SECTION], params![SYSTEM_PROMPT_SECTION],
)?; )?;
conn.execute( conn.execute(
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('TOOL_USE', ?1, 1)", "INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('TOOL_USE', ?1, 1)",
params![TOOL_USE_SECTION], params![tool_use],
)?; )?;
// Refresh an untouched pre-notepad TOOL_USE row so the notepad manual reaches // Refresh an untouched pre-notepad TOOL_USE row so the notepad manual reaches
// existing databases; a user-edited row (content differs) is left alone. // existing databases; a user-edited row (content differs) is left alone.
conn.execute( conn.execute(
"UPDATE context_sections SET content = ?1 WHERE name = 'TOOL_USE' AND content = ?2", "UPDATE context_sections SET content = ?1 WHERE name = 'TOOL_USE' AND content = ?2",
params![TOOL_USE_SECTION, TOOL_USE_SECTION_PRE_NOTEPAD], params![tool_use, TOOL_USE_SECTION_PRE_NOTEPAD],
)?;
// Likewise refresh an untouched notepad-era row so the share_file manual
// reaches databases created before share_file existed.
conn.execute(
"UPDATE context_sections SET content = ?1 WHERE name = 'TOOL_USE' AND content = ?2",
params![tool_use, TOOL_USE_SECTION_PRE_SHARE],
)?; )?;
Ok(()) Ok(())
} }
+81
View File
@@ -618,3 +618,84 @@ async fn upload_accepts_large_binary_over_default_body_limit() {
assert_eq!(meta["kind"], "binary"); assert_eq!(meta["kind"], "binary");
let _ = std::fs::remove_file(meta["path"].as_str().unwrap()); let _ = std::fs::remove_file(meta["path"].as_str().unwrap());
} }
#[tokio::test]
async fn download_serves_shared_file_as_attachment_and_blocks_escape() {
use strata_ctl::agent::share;
let (app, store) = build_app().await;
let sess = store
.create_session(
"Share",
"test-model",
&strata_ctl::store::SessionSettings::default(),
)
.unwrap();
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let folder = std::env::temp_dir().join(format!("strata-dl-{nanos}"));
std::fs::create_dir_all(&folder).unwrap();
store
.set_folder(&sess.id, folder.to_str().unwrap())
.unwrap();
let file = folder.join("report.txt");
std::fs::write(&file, b"hello download").unwrap();
let outside = std::env::temp_dir().join(format!("strata-dl-out-{nanos}.txt"));
std::fs::write(&outside, b"secret").unwrap();
// Happy path: the exact URL the tool produces downloads the file as an
// attachment, with a non-inline content type and nosniff.
let url = share::download_url(&sess.id, &file, Some("report.txt"));
let resp = app
.clone()
.oneshot(Request::builder().uri(&url).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let h = resp.headers();
assert_eq!(
h.get(axum::http::header::CONTENT_TYPE).unwrap(),
"application/octet-stream"
);
let cd = h
.get(axum::http::header::CONTENT_DISPOSITION)
.unwrap()
.to_str()
.unwrap();
assert!(cd.starts_with("attachment;"), "{cd}");
assert!(cd.contains("filename=\"report.txt\""), "{cd}");
assert_eq!(h.get("x-content-type-options").unwrap(), "nosniff");
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(&bytes[..], b"hello download");
// Escape: an absolute path outside the allowed roots is refused, no leak.
let bad = share::download_url(&sess.id, &outside, None);
let (st, text) = req(&app, Method::GET, &bad, None).await;
assert_eq!(st, StatusCode::BAD_REQUEST, "{text}");
assert!(!text.contains("secret"), "{text}");
// `..` traversal out of the personal folder is refused too.
let trav = folder.join("../").join(outside.file_name().unwrap());
let bad2 = share::download_url(&sess.id, &trav, None);
let (st2, _) = req(&app, Method::GET, &bad2, None).await;
assert_eq!(st2, StatusCode::BAD_REQUEST);
// Unknown session -> 404.
let (st3, _) = req(
&app,
Method::GET,
&format!(
"/api/sessions/nope/download?path={}",
share::pct_encode(file.to_str().unwrap())
),
None,
)
.await;
assert_eq!(st3, StatusCode::NOT_FOUND);
let _ = std::fs::remove_dir_all(&folder);
let _ = std::fs::remove_file(&outside);
}
+10
View File
@@ -169,6 +169,16 @@ body.resizing { cursor: col-resize; user-select: none; }
.content.rendered li > ul, .content.rendered li > ol { margin: 0.2em 0; } .content.rendered li > ul, .content.rendered li > ol { margin: 0.2em 0; }
.content.rendered a { color: var(--accent); text-decoration: none; } .content.rendered a { color: var(--accent); text-decoration: none; }
.content.rendered a:hover { text-decoration: underline; } .content.rendered a:hover { text-decoration: underline; }
/* Agent-shared download links read as a distinct chip; the server already forces
Content-Disposition: attachment, so clicking downloads rather than navigates. */
.content.rendered a.download-link {
display: inline-flex; align-items: center; gap: 6px;
padding: 3px 10px; margin: 2px 0;
background: var(--panel-2); border: 1px solid var(--border); border-radius: 999px;
color: var(--accent); font-size: 0.85rem; text-decoration: none;
}
.content.rendered a.download-link::before { content: "\2B07"; font-size: 0.9em; }
.content.rendered a.download-link:hover { border-color: var(--accent); text-decoration: none; }
.content.rendered blockquote { .content.rendered blockquote {
margin: 0 0 0.6em; padding: 0.2em 0 0.2em 0.9em; margin: 0 0 0.6em; padding: 0.2em 0 0.2em 0.9em;
border-left: 3px solid var(--border); color: var(--muted); border-left: 3px solid var(--border); color: var(--muted);
+15
View File
@@ -60,6 +60,19 @@ function el(tag, cls, text) {
return n; return n;
} }
// Mark agent-shared download links (relative /api/sessions/…/download) so they
// download in place via the same-origin `download` attribute and read as a chip.
// The server already forces Content-Disposition: attachment and a safe type.
function enhanceDownloadLinks(node) {
for (const a of node.querySelectorAll("a[href]")) {
const href = a.getAttribute("href") || "";
if (href.startsWith("/api/sessions/") && href.includes("/download")) {
a.classList.add("download-link");
a.setAttribute("download", "");
}
}
}
function messageNode(role, content, reasoning, usage, ts, html) { function messageNode(role, content, reasoning, usage, ts, html) {
const wrap = el("div", `msg ${role}`); const wrap = el("div", `msg ${role}`);
const roleNode = el("div", "role", role === "user" ? "Tu" : "Assistente"); const roleNode = el("div", "role", role === "user" ? "Tu" : "Assistente");
@@ -77,6 +90,7 @@ function messageNode(role, content, reasoning, usage, ts, html) {
// Server-sanitized Markdown/LaTeX (assistant only): safe to inject. // Server-sanitized Markdown/LaTeX (assistant only): safe to inject.
contentNode.classList.add("rendered"); contentNode.classList.add("rendered");
contentNode.innerHTML = html; contentNode.innerHTML = html;
enhanceDownloadLinks(contentNode);
} else { } else {
contentNode.textContent = content || ""; contentNode.textContent = content || "";
} }
@@ -497,6 +511,7 @@ async function agentTurn(content, t, attachments) {
if (ev.content_html != null) { if (ev.content_html != null) {
L.contentNode.classList.add("rendered"); L.contentNode.classList.add("rendered");
L.contentNode.innerHTML = ev.content_html; L.contentNode.innerHTML = ev.content_html;
enhanceDownloadLinks(L.contentNode);
} }
L.det.open = false; L.det.open = false;
if (ev.response.usage) L.bubble.appendChild(el("div", "usage", usageText(ev.response.usage))); if (ev.response.usage) L.bubble.appendChild(el("div", "usage", usageText(ev.response.usage)));