//! End-to-end tests of the session-aware GUI API (`/api/sessions...`): the //! server holds context across turns, persists messages + usage, streams, and //! serves the embedded web GUI. Driven through the mock engine + a byte //! formatter, with an in-memory SQLite store. use std::sync::Arc; use std::time::Duration; use axum::body::Body; use axum::http::{header::CONTENT_TYPE, Method, Request, StatusCode}; use tower::ServiceExt; use strata_ctl::api::formatter::{Decoder, Formatter, Piece, Prompt}; use strata_ctl::api::service::ChatService; use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest}; use strata_ctl::api::{router_with_store, AuthConfig}; use strata_ctl::engine::Engine; use strata_ctl::store::{NewMessage, SqliteStore, Store}; const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py"); struct ByteFormatter; impl Formatter for ByteFormatter { fn model_name(&self) -> &str { "test-model" } fn build_prompt(&self, req: &ChatRequest) -> Result { let text = req .messages .iter() .rev() .find_map(|m| m.text()) .unwrap_or("") .to_string(); Ok(Prompt { ids: text.bytes().map(u32::from).collect(), max_new: req.max_new(64), sampling: Default::default(), temp_files: Vec::new(), }) } fn decoder(&self) -> Box { Box::new(ByteDecoder) } } struct ByteDecoder; impl Decoder for ByteDecoder { fn push(&mut self, id: u32) -> Vec { if id < 256 { vec![Piece::Content(char::from(id as u8).to_string())] } else { Vec::new() } } fn finish(&mut self, _reason: Option<&str>) -> Vec { Vec::new() } } async fn build_app() -> (axum::Router, Arc) { let engine = Arc::new( Engine::start( "python3", &[MOCK.to_string()], None, Duration::from_secs(10), ) .await .expect("mock engine starts"), ); let svc = ChatService::new(engine, Arc::new(ByteFormatter)); let store = Arc::new(SqliteStore::open_in_memory().unwrap()); let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos(); let root = std::env::temp_dir().join(format!("strata-ctl-test-{nanos}")); let app = router_with_store(svc, store.clone(), AuthConfig::default(), root, None); (app, store) } async fn req( app: &axum::Router, method: Method, uri: &str, body: Option, ) -> (StatusCode, String) { let mut b = Request::builder().method(method).uri(uri); if body.is_some() { b = b.header(CONTENT_TYPE, "application/json"); } let r = b .body(match body { Some(v) => Body::from(v.to_string()), None => Body::empty(), }) .unwrap(); let resp = app.clone().oneshot(r).await.unwrap(); let status = resp.status(); let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) .await .unwrap(); (status, String::from_utf8_lossy(&bytes).into_owned()) } async fn create_session(app: &axum::Router) -> String { let (st, text) = req( app, Method::POST, "/api/sessions", Some(serde_json::json!({})), ) .await; assert_eq!(st, StatusCode::OK, "{text}"); let v: serde_json::Value = serde_json::from_str(&text).unwrap(); v["id"].as_str().unwrap().to_string() } #[tokio::test] async fn mcp_connector_crud_and_validation() { let (app, _store) = build_app().await; // Empty catalog. let (st, text) = req(&app, Method::GET, "/api/mcp/connectors", None).await; assert_eq!(st, StatusCode::OK); assert_eq!( serde_json::from_str::(&text) .unwrap() .as_array() .unwrap() .len(), 0 ); // Upsert; the name is sanitized into a namespace-safe id ("GMail" -> "gmail"). let (st, _) = req( &app, Method::PUT, "/api/mcp/connectors/GMail", Some(serde_json::json!({"url":"http://192.168.50.117:8080/","token":"test-token-value"})), ) .await; assert_eq!(st, StatusCode::OK); let (_, text) = req(&app, Method::GET, "/api/mcp/connectors", None).await; let v: serde_json::Value = serde_json::from_str(&text).unwrap(); assert_eq!(v[0]["name"], "gmail"); assert_eq!(v[0]["url"], "http://192.168.50.117:8080/"); assert_eq!(v[0]["token"], "test-token-value"); // An empty token is rejected. let (st, _) = req( &app, Method::PUT, "/api/mcp/connectors/bad", Some(serde_json::json!({"url":"http://x/","token":""})), ) .await; assert_eq!(st, StatusCode::BAD_REQUEST); // Discovery for an unknown connector is a 404 before any network attempt. let (st, _) = req(&app, Method::POST, "/api/mcp/connectors/nope/tools", None).await; assert_eq!(st, StatusCode::NOT_FOUND); // Delete, then deleting again is a 404. let (st, _) = req(&app, Method::DELETE, "/api/mcp/connectors/gmail", None).await; assert_eq!(st, StatusCode::NO_CONTENT); let (st, _) = req(&app, Method::DELETE, "/api/mcp/connectors/gmail", None).await; assert_eq!(st, StatusCode::NOT_FOUND); } #[tokio::test] async fn memory_enable_rejected_without_service() { let (app, _store) = build_app().await; let id = create_session(&app).await; // No memory service in this app -> enabling the one-way latch is refused. let (st, text) = req( &app, Method::PATCH, &format!("/api/sessions/{id}"), Some(serde_json::json!({"settings": {"memory_enabled": true}})), ) .await; assert_eq!(st, StatusCode::BAD_REQUEST, "{text}"); // The rejected enable did not persist: the session stays off. let (_, text) = req(&app, Method::GET, &format!("/api/sessions/{id}"), None).await; let v: serde_json::Value = serde_json::from_str(&text).unwrap(); assert_eq!(v["settings"]["memory_enabled"], false); } #[tokio::test] async fn todos_endpoint_exposes_the_task_list() { let (app, store) = build_app().await; let id = create_session(&app).await; // Empty list initially. let (st, text) = req( &app, Method::GET, &format!("/api/sessions/{id}/todos"), None, ) .await; assert_eq!(st, StatusCode::OK, "{text}"); assert_eq!( serde_json::from_str::(&text) .unwrap() .as_array() .unwrap() .len(), 0 ); // Seed via the store (the agent writes through the todo tool). store.add_todo(&id, "first step").unwrap(); let second = store.add_todo(&id, "second step").unwrap(); store .update_todo(&id, second.seq, Some("doing"), None) .unwrap(); let (_, text) = req( &app, Method::GET, &format!("/api/sessions/{id}/todos"), None, ) .await; let v: serde_json::Value = serde_json::from_str(&text).unwrap(); let arr = v.as_array().unwrap(); assert_eq!(arr.len(), 2); assert_eq!(arr[0]["seq"], 1); assert_eq!(arr[0]["status"], "pending"); assert_eq!(arr[1]["seq"], 2); assert_eq!(arr[1]["status"], "doing"); assert_eq!(arr[1]["content"], "second step"); } #[tokio::test] async fn session_holds_context_and_persists_usage() { let (app, _store) = build_app().await; let id = create_session(&app).await; assert!(id.starts_with("sess_")); // Turn 1 (non-stream): the mock emits 'efghi'. let (st, text) = req( &app, Method::POST, &format!("/api/sessions/{id}/chat"), Some(serde_json::json!({"content": "hi"})), ) .await; assert_eq!(st, StatusCode::OK, "{text}"); let v: serde_json::Value = serde_json::from_str(&text).unwrap(); assert_eq!(v["choices"][0]["message"]["content"], "efghi"); // Persisted: user + assistant, with usage on the assistant turn. let (st, text) = req( &app, Method::GET, &format!("/api/sessions/{id}/messages"), None, ) .await; assert_eq!(st, StatusCode::OK); let v: serde_json::Value = serde_json::from_str(&text).unwrap(); let msgs = v["messages"].as_array().unwrap(); assert_eq!(msgs.len(), 2); assert_eq!(v["total"], 2); assert_eq!(msgs[0]["role"], "user"); assert_eq!(msgs[0]["content"], "hi"); assert_eq!(msgs[1]["role"], "assistant"); assert_eq!(msgs[1]["content"], "efghi"); assert_eq!(msgs[1]["completion_tokens"], 5); // Turn 2: context is retained server-side (4 messages now). let (st, _) = req( &app, Method::POST, &format!("/api/sessions/{id}/chat"), Some(serde_json::json!({"content": "again"})), ) .await; assert_eq!(st, StatusCode::OK); let (_, text) = req( &app, Method::GET, &format!("/api/sessions/{id}/messages"), None, ) .await; let v: serde_json::Value = serde_json::from_str(&text).unwrap(); let msgs = v["messages"].as_array().unwrap(); assert_eq!(msgs.len(), 4); assert_eq!(v["total"], 4); assert_eq!(msgs[2]["content"], "again"); // Stats aggregate across the session. let (st, text) = req(&app, Method::GET, "/api/stats", None).await; assert_eq!(st, StatusCode::OK); let s: serde_json::Value = serde_json::from_str(&text).unwrap(); assert_eq!(s["sessions"], 1); assert_eq!(s["messages"], 4); assert_eq!(s["completion_tokens"], 10); // Expanded dashboard payload: totals, per-session/daily breakdown, and the // live engine status + since-startup performance gauge layered on top. assert_eq!( s["total_tokens"], s["prompt_tokens"].as_u64().unwrap() + s["completion_tokens"].as_u64().unwrap() ); assert_eq!(s["tool_calls"], 0); assert_eq!(s["by_session"].as_array().unwrap().len(), 1); assert_eq!(s["by_session"][0]["messages"], 4); assert_eq!(s["daily"].as_array().unwrap().len(), 1); assert_eq!(s["engine"]["model"], "test-model"); assert_eq!(s["engine"]["max_context"], 8192); assert_eq!(s["engine"]["busy"], false); // Two non-stream completions were served and recorded by the perf meter, // whose token-weighted decode speed comes from the mock's DONE timings. assert_eq!(s["perf"]["requests"], 2); assert!(s["perf"]["decode_tps"].as_f64().unwrap() > 0.0); } #[tokio::test] async fn session_stream_persists_and_ends_with_done() { let (app, _store) = build_app().await; let id = create_session(&app).await; let (st, text) = req( &app, Method::POST, &format!("/api/sessions/{id}/chat"), Some(serde_json::json!({"content": "hi", "stream": true})), ) .await; assert_eq!(st, StatusCode::OK, "{text}"); let data: Vec<&str> = text .lines() .filter(|l| l.starts_with("data: ")) .map(|l| &l["data: ".len()..]) .collect(); assert_eq!(data.last().copied(), Some("[DONE]")); let mut content = String::new(); for line in &data[..data.len() - 1] { let v: serde_json::Value = serde_json::from_str(line).unwrap(); if let Some(c) = v["choices"][0]["delta"]["content"].as_str() { content.push_str(c); } } assert_eq!(content, "efghi"); // The streamed assistant turn was persisted too. let (_, text) = req( &app, Method::GET, &format!("/api/sessions/{id}/messages"), None, ) .await; let v: serde_json::Value = serde_json::from_str(&text).unwrap(); let msgs = v["messages"].as_array().unwrap(); assert_eq!(msgs.len(), 2); assert_eq!(msgs[1]["content"], "efghi"); assert_eq!(msgs[1]["completion_tokens"], 5); } #[tokio::test] async fn messages_endpoint_returns_only_the_sliding_window() { let (app, store) = build_app().await; let id = create_session(&app).await; // Seed a long history directly (60 messages, alternating user/assistant). for i in 0..60 { store .append_message( &id, NewMessage { role: if i % 2 == 0 { "user" } else { "assistant" }, content: "x", reasoning_content: None, tool_calls_json: None, tool_call_id: None, prompt_tokens: 0, completion_tokens: 0, }, ) .unwrap(); } // One chat turn runs window::select over the 60-message history and persists // the evicted start — the model's window. The GUI must see that same window. let (st, _) = req( &app, Method::POST, &format!("/api/sessions/{id}/chat"), Some(serde_json::json!({"content": "hi"})), ) .await; assert_eq!(st, StatusCode::OK); let (_, text) = req( &app, Method::GET, &format!("/api/sessions/{id}/messages"), None, ) .await; let v: serde_json::Value = serde_json::from_str(&text).unwrap(); let msgs = v["messages"].as_array().unwrap(); let total = v["total"].as_u64().unwrap(); assert_eq!(total, 62); // 60 seeded + the new user + assistant turns // Bounded window (MAIN_AREA + BUFFER), never the whole history. assert!( msgs.len() <= 50, "window must be bounded, got {}", msgs.len() ); assert!(msgs.len() < total as usize); // The window snaps to a user-turn boundary (never mid-exchange). assert_eq!(msgs[0]["role"], "user"); // The full history is still in the store — nothing was deleted. assert_eq!(store.messages(&id).unwrap().len(), 62); } #[tokio::test] async fn gui_is_served_and_delete_cascades() { let (app, store) = build_app().await; let id = create_session(&app).await; req( &app, Method::POST, &format!("/api/sessions/{id}/chat"), Some(serde_json::json!({"content": "hi"})), ) .await; // The GUI shell and its assets are served from the binary. let resp = app .clone() .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap()) .await .unwrap(); assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.headers()[CONTENT_TYPE], "text/html; charset=utf-8"); let body = axum::body::to_bytes(resp.into_body(), usize::MAX) .await .unwrap(); assert!(String::from_utf8_lossy(&body).contains("strata")); let (st, _) = req(&app, Method::GET, "/assets/app.js", None).await; assert_eq!(st, StatusCode::OK); // Deleting the session cascades to its messages. let (st, _) = req(&app, Method::DELETE, &format!("/api/sessions/{id}"), None).await; assert_eq!(st, StatusCode::NO_CONTENT); assert!(store.messages(&id).unwrap().is_empty()); assert!(store.list_sessions().unwrap().is_empty()); } #[tokio::test] async fn unknown_session_is_404() { let (app, _store) = build_app().await; let (st, _) = req(&app, Method::GET, "/api/sessions/nope", None).await; assert_eq!(st, StatusCode::NOT_FOUND); let (st, _) = req( &app, Method::POST, "/api/sessions/nope/chat", Some(serde_json::json!({"content": "hi"})), ) .await; assert_eq!(st, StatusCode::NOT_FOUND); } #[tokio::test] async fn agent_mode_streams_events_and_persists() { let (app, store) = build_app().await; let id = create_session(&app).await; // The mock answers directly (no tool calls), exercising the agent final path. let (st, text) = req( &app, Method::POST, &format!("/api/sessions/{id}/chat"), Some(serde_json::json!({"content": "hi", "agent": true})), ) .await; assert_eq!(st, StatusCode::OK, "{text}"); let data: Vec<&str> = text .lines() .filter(|l| l.starts_with("data: ")) .map(|l| &l["data: ".len()..]) .collect(); assert_eq!(data.last().copied(), Some("[DONE]")); let mut saw_final = false; for line in &data[..data.len() - 1] { let v: serde_json::Value = serde_json::from_str(line).unwrap(); if v["type"] == "final" { saw_final = true; assert_eq!(v["response"]["choices"][0]["message"]["content"], "efghi"); } } assert!(saw_final, "no final agent event: {text}"); // The final assistant turn is persisted. let msgs = store.messages(&id).unwrap(); assert_eq!(msgs.last().unwrap().role, "assistant"); assert_eq!(msgs.last().unwrap().content, "efghi"); } #[tokio::test] async fn first_interaction_creates_personal_folder() { let (app, store) = build_app().await; let id = create_session(&app).await; assert!(store.get_session(&id).unwrap().unwrap().folder.is_none()); req( &app, Method::POST, &format!("/api/sessions/{id}/chat"), Some(serde_json::json!({"content": "ciao"})), ) .await; let s = store.get_session(&id).unwrap().unwrap(); let folder = s .folder .expect("personal folder created at first interaction"); assert!(std::path::Path::new(&folder).is_dir()); assert!( folder.contains("/sessions/"), "folder under sessions/: {folder}" ); assert!(s.name_locked); let _ = std::fs::remove_dir_all(&folder); } #[tokio::test] async fn name_is_generated_editable_then_locked() { let (app, store) = build_app().await; let id = create_session(&app).await; let sess = store.get_session(&id).unwrap().unwrap(); // Framework-assigned friendly name (not the old "Nuova chat"), unlocked. assert!(sess.title.contains('-'), "title: {}", sess.title); assert!(!sess.name_locked); // Rename before the first interaction is allowed. let (st, _) = req( &app, Method::PATCH, &format!("/api/sessions/{id}"), Some(serde_json::json!({"title": "Mio titolo"})), ) .await; assert_eq!(st, StatusCode::OK); assert_eq!(store.get_session(&id).unwrap().unwrap().title, "Mio titolo"); // The first interaction locks the name. req( &app, Method::POST, &format!("/api/sessions/{id}/chat"), Some(serde_json::json!({"content": "ciao"})), ) .await; assert!(store.get_session(&id).unwrap().unwrap().name_locked); // Rename after the first interaction is rejected; the name is unchanged. let (st, _) = req( &app, Method::PATCH, &format!("/api/sessions/{id}"), Some(serde_json::json!({"title": "Troppo tardi"})), ) .await; assert_eq!(st, StatusCode::BAD_REQUEST); assert_eq!(store.get_session(&id).unwrap().unwrap().title, "Mio titolo"); // Delete still works. let (st, _) = req(&app, Method::DELETE, &format!("/api/sessions/{id}"), None).await; assert_eq!(st, StatusCode::NO_CONTENT); assert!(store.get_session(&id).unwrap().is_none()); } #[tokio::test] async fn settings_are_copied_on_create_and_isolated() { let (app, store) = build_app().await; // Seed the global defaults template. let (st, _) = req( &app, Method::PUT, "/api/settings/defaults", Some(serde_json::json!({"system_prompt": "base", "temperature": 0.9})), ) .await; assert_eq!(st, StatusCode::OK); // A new session snapshots the defaults. let (st, text) = req( &app, Method::POST, "/api/sessions", Some(serde_json::json!({})), ) .await; assert_eq!(st, StatusCode::OK, "{text}"); let v: serde_json::Value = serde_json::from_str(&text).unwrap(); let id = v["id"].as_str().unwrap().to_string(); assert_eq!(v["settings"]["system_prompt"], "base"); assert_eq!(v["settings"]["temperature"], 0.9); // Editing this session's settings affects only it. let (st, _) = req( &app, Method::PATCH, &format!("/api/sessions/{id}"), Some(serde_json::json!({"settings": {"notes": "scopo: test", "temperature": 0.2}})), ) .await; assert_eq!(st, StatusCode::OK); let s = store.get_session(&id).unwrap().unwrap(); assert_eq!(s.settings.notes.as_deref(), Some("scopo: test")); assert_eq!(s.settings.temperature, Some(0.2)); // The global defaults are untouched. assert_eq!( store.get_defaults().unwrap().unwrap().temperature, Some(0.9) ); // Changing the globals affects only FUTURE sessions, not the existing one. req( &app, Method::PUT, "/api/settings/defaults", Some(serde_json::json!({"temperature": 0.5})), ) .await; assert_eq!( store .get_session(&id) .unwrap() .unwrap() .settings .temperature, Some(0.2) ); let id2 = create_session(&app).await; assert_eq!( store .get_session(&id2) .unwrap() .unwrap() .settings .temperature, Some(0.5) ); } #[tokio::test] async fn upload_routes_by_kind_and_attaches_to_chat() { use base64::Engine; let (app, store) = build_app().await; let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes); // Small text file -> kind "text", tokens measured, bytes on disk under uploads/. let (st, text) = req( &app, Method::POST, "/api/uploads", Some(serde_json::json!({"name": "nota.txt", "data": b64(b"contenuto di prova")})), ) .await; assert_eq!(st, StatusCode::OK, "{text}"); let meta: serde_json::Value = serde_json::from_str(&text).unwrap(); assert_eq!(meta["kind"], "text"); assert!(meta["tokens"].as_u64().unwrap() > 0); let path = meta["path"].as_str().unwrap().to_string(); assert!(std::path::Path::new(&path).is_file()); assert!(path.contains("/uploads/"), "shared upload dir: {path}"); let text_id = meta["id"].as_str().unwrap().to_string(); // Binary (NUL / invalid UTF-8) -> kind "binary", never inlined. let (st, text) = req( &app, Method::POST, "/api/uploads", Some(serde_json::json!({"name": "dat.bin", "data": b64(&[0u8, 1, 2, 255])})), ) .await; assert_eq!(st, StatusCode::OK, "{text}"); let bin: serde_json::Value = serde_json::from_str(&text).unwrap(); assert_eq!(bin["kind"], "binary"); let bin_id = bin["id"].as_str().unwrap().to_string(); // Image (PNG magic) -> kind "image" (routed through Vision, not inline text). let png = [0x89u8, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n', 0, 0]; let (st, text) = req( &app, Method::POST, "/api/uploads", Some(serde_json::json!({"name": "foto.png", "data": b64(&png)})), ) .await; assert_eq!(st, StatusCode::OK, "{text}"); let img: serde_json::Value = serde_json::from_str(&text).unwrap(); assert_eq!(img["kind"], "image"); // Chat attaching text + binary: the persisted user turn carries the inline // text and the binary path reminder — never the binary bytes themselves. let id = create_session(&app).await; let (st, _) = req( &app, Method::POST, &format!("/api/sessions/{id}/chat"), Some(serde_json::json!({"content": "vedi allegati", "attachments": [text_id, bin_id]})), ) .await; assert_eq!(st, StatusCode::OK); let msgs = store.messages(&id).unwrap(); let user = &msgs[0].content; assert!(user.contains("contenuto di prova"), "inline text: {user}"); assert!(user.contains("dat.bin"), "binary path reminder: {user}"); assert!(user.contains("/uploads/"), "path present: {user}"); let _ = std::fs::remove_file(&path); } #[tokio::test] async fn upload_accepts_large_binary_over_default_body_limit() { use base64::Engine; let (app, _store) = build_app().await; // ~3 MiB of binary -> ~4 MiB of base64, above axum's 2 MiB default body limit // (which used to 413-reject images/PDFs/exes before reaching the handler). let bytes = vec![0u8; 3 * 1024 * 1024]; let data = base64::engine::general_purpose::STANDARD.encode(&bytes); let (st, text) = req( &app, Method::POST, "/api/uploads", Some(serde_json::json!({"name": "big.bin", "data": data})), ) .await; assert_eq!(st, StatusCode::OK, "{text}"); let meta: serde_json::Value = serde_json::from_str(&text).unwrap(); assert_eq!(meta["kind"], "binary"); 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); }