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:
1 parent
28568f0e89
commit
2f5b263d4e
11 files changed
+668
-15
No files matched your search
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
//! [`routes`] the axum router.
|
||||
|
||||
pub mod anthropic;
|
||||
mod files;
|
||||
pub mod formatter;
|
||||
pub mod routes;
|
||||
pub mod service;
|
||||
|
||||
+2
-1
@@ -15,7 +15,7 @@ use std::sync::Arc;
|
||||
use super::anthropic::{self, AnthropicRequest, AnthropicStream};
|
||||
use super::service::ChatService;
|
||||
use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList};
|
||||
use super::{sessions, uploads, web};
|
||||
use super::{files, sessions, uploads, web};
|
||||
use crate::store::Store;
|
||||
|
||||
/// 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}/notepad", get(sessions::get_notepad))
|
||||
.route("/api/sessions/{id}/chat", post(sessions::session_chat))
|
||||
.route("/api/sessions/{id}/download", get(files::download))
|
||||
.route(
|
||||
"/api/uploads",
|
||||
// Uploads arrive as base64 JSON: a 32 MiB decoded file becomes
|
||||
|
||||
@@ -559,6 +559,7 @@ pub(crate) async fn session_chat(
|
||||
let store2 = store.clone();
|
||||
let sid = id.clone();
|
||||
let folder = sess.folder.clone();
|
||||
let ws_root = st.workspace_root.clone();
|
||||
let tx_model = tx.clone();
|
||||
let svc_pw = st.service.clone();
|
||||
let store_pw = store.clone();
|
||||
@@ -632,6 +633,7 @@ pub(crate) async fn session_chat(
|
||||
runner,
|
||||
store: store2,
|
||||
default_cwd: folder,
|
||||
workspace_root: Some(ws_root),
|
||||
max_iters: agent::MAX_ITERS,
|
||||
progress: Some(tx.clone()),
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user