Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
0.7.3: videos in chat (backend): mp4/mov/webm up to 100 MB, early 415, frames for bots (#373)
Oleksandr Ivanchenko22c31794e590
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a480ca70..405fe07e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).- **Dev mode reads any git repo.** Repos on GitLab, Gitea or any git server, and team folders with no remote, are watched with git, and what lands there shows on the Dev desk. Reviews, CI checks and Post to GitHub still work on GitHub repos only. The server needs git 2.31 or newer; without it, the desk says "Needs git on the server". (#366, #368)- **Connect GitHub in one place.** Every Connect GitHub (the Dev desk's status line and empty state, the Dev mode toast, Dev mode setup and Team settings) opens the same GitHub form right where you pressed it: a popover on the desktop, a sheet on the phone. It no longer jumps to Loose ends. The GitHub row in Loose ends says "Also used by Dev mode".- **Team settings say what Dev mode does with the repo.** Under Git Repo URL, one line: watched with GitHub connected, watched but needs Connect GitHub for reviews, can be watched once Dev mode is on, or read with git (reviews need GitHub).+- **Videos in chat.** MP4, MOV and WebM files up to 100 MB can be attached and shared by bots (other files stay at 20 MB), and they play right in the chat. The type comes from the file's bytes, not its name. A file kwant can't take is refused right after its first bytes instead of after the whole upload. With ffmpeg on the server, a bot reading a video gets its length and size and up to 6 frames; without ffmpeg it is told to install it.### Changed- **Dev mode reads commit history with git, not GitHub's API.** Each watched repo gets a copy in kwant's data folder, up to 1 GB each; a bigger repo reads "Too big to read". Repo addresses that point at this server, link-local addresses or cloud metadata addresses are refused, and https reads are pinned to the address that was checked. A team folder whose .git points somewhere else is refused. GitHub PRs, checks and logins still come from GitHub. (#366)diff --git a/src/server/attachments.rs b/src/server/attachments.rsindex 4d732f8a..bdeab261 100644--- a/src/server/attachments.rs+++ b/src/server/attachments.rs@@ -4,8 +4,12 @@//!//! Bytes are stored once per content under `<data dir>/attachments/<sha[0..2]>/<sha>`. A path is//! only ever built from a validated sha256, never from a name or id the client sent, and files are-//! served only through the auth guard with `nosniff`, a sandbox CSP and (except raster images)-//! `Content-Disposition: attachment`.+//! served only through the auth guard with `nosniff`, a sandbox CSP and (except raster images and+//! videos) `Content-Disposition: attachment`.+//!+//! Videos (MP4, MOV, WebM by their bytes) may be up to 100 MB; everything else up to 20 MB. A+//! file the bytes already rule out is refused after its first 16 bytes, not after the last one+//! (video-drop-073). `read_attachment` looks inside videos with ffmpeg ([`super::video`]).use super::continuity::SelfScope;use super::AppState;@@ -28,8 +32,15 @@ use std::path::{Path as FsPath, PathBuf};use tokio::io::{AsyncReadExt, AsyncWriteExt};use tower::ServiceExt;-/// Largest file a user can upload or an agent can share.+/// Largest file a user can upload or an agent can share, unless it is a video.pub const MAX_ATTACHMENT_BYTES: u64 = 20 * 1024 * 1024;+/// Largest video (MP4, MOV, WebM by its bytes).+pub const MAX_VIDEO_BYTES: u64 = 100 * 1024 * 1024;+/// Bytes of a file's start kept for sniffing; the type is known (or ruled out) once they are in.+const HEAD_BYTES: usize = 16;+/// After an early 413/415 the rest of the body is read and dropped, so the browser gets the+/// answer instead of a connection reset; at most this long.+const DRAIN_SECS: u64 = 30;/// Most files on one message.pub const MAX_ATTACHMENTS_PER_MESSAGE: usize = 10;/// Small text files are put into the prompt directly, up to this much in total.@@ -46,8 +57,14 @@ const READ_IMAGE_BYTES: i64 = 5 * 1024 * 1024;const MAX_SHARED_TEXT_BYTES: usize = 1024 * 1024;const MAX_NAME_CHARS: usize = 120;-/// Raster images: the only types shown inline; everything else downloads.+/// Raster images: shown inline as images.pub(crate) const INLINE_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];+/// Videos: served inline so a `<video>` can play them. Everything else downloads.+pub(crate) const INLINE_VIDEO_TYPES: [&str; 3] = ["video/mp4", "video/webm", "video/quicktime"];++pub fn is_video_mime(mime: &str) -> bool {+ INLINE_VIDEO_TYPES.contains(&mime)+}pub fn root(state: &AppState) -> PathBuf {state.config.data_dir.join("attachments")@@ -74,9 +91,23 @@ pub fn clean_name(raw: &str) -> String {}}-/// The file's type from its first bytes; text when it is all UTF-8 without NUL bytes (its-/// extension then picks markdown, CSV or JSON). Anything else is refused.-pub fn sniff(head: &[u8], is_text: bool, name: &str) -> Option<&'static str> {+/// ISO-BMFF major brands that are video (MP4 and its relatives). Other `ftyp` files (HEIC/AVIF+/// photos, M4A audio, camera raw) are not videos a browser plays, so they aren't taken as one.+fn video_brand(brand: &[u8]) -> Option<&'static str> {+ let b = std::str::from_utf8(brand).ok()?;+ if b == "qt " {+ return Some("video/quicktime");+ }+ let mp4 = matches!(b, "isom" | "mp41" | "mp42" | "mp71" | "avc1" | "M4V " | "M4VH" | "M4VP" | "dash" | "mmp4" | "MSNV" | "XAVC" | "f4v ")+ || (b.starts_with("iso") && matches!(b.as_bytes()[3], b'2'..=b'9'))+ || (b.starts_with("3gp") && matches!(b.as_bytes()[3], b'4'..=b'9'))+ || (b.starts_with("3g2") && matches!(b.as_bytes()[3], b'a'..=b'c'));+ mp4.then_some("video/mp4")+}++/// The type a file's magic bytes prove: an image, a PDF or a video. `None` for text and for+/// anything that isn't accepted.+pub fn sniff_magic(head: &[u8]) -> Option<&'static str> {if head.starts_with(b"\x89PNG\r\n\x1a\n") {return Some("image/png");}@@ -92,11 +123,47 @@ pub fn sniff(head: &[u8], is_text: bool, name: &str) -> Option<&'static str> {if head.starts_with(b"%PDF-") {return Some("application/pdf");}+ // ISO-BMFF: a box size, then `ftyp` and the major brand (MP4, MOV)+ if head.len() >= 12 && &head[4..8] == b"ftyp" {+ return video_brand(&head[8..12]);+ }+ // EBML: WebM (and Matroska, which browsers play the same way)+ if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) {+ return Some("video/webm");+ }+ None+}++/// Extensions that are never text, so a file named so is refused as soon as its first bytes+/// show no accepted magic, even if they happen to look like text.+const BINARY_EXTS: &[&str] = &[+ "7z", "aac", "apk", "avi", "bmp", "bz2", "dll", "dmg", "doc", "docx", "dylib", "exe", "flac", "flv", "gz", "heic", "heif",+ "ico", "img", "ipa", "iso", "m4a", "m4v", "mkv", "mov", "mp3", "mp4", "mpeg", "mpg", "msi", "numbers", "odp", "ods",+ "odt", "ogg", "opus", "pages", "pkg", "ppt", "pptx", "psd", "rar", "so", "tar", "tgz", "tif", "tiff", "wav", "webm", "wmv",+ "xls", "xlsx", "xz", "zip", "3gp", "avif",+];++fn extension(name: &str) -> String {+ name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default()+}++/// Whether a file can be refused from its first bytes (V3): they carry no accepted magic, and+/// either they already aren't UTF-8 text or the name's extension is a binary one. Text is+/// otherwise decided at the end.+fn ruled_out_early(head: &[u8], text_so_far: bool, name: &str) -> bool {+ head.len() >= HEAD_BYTES && sniff_magic(head).is_none() && (!text_so_far || BINARY_EXTS.contains(&extension(name).as_str()))+}++/// The file's type from its first bytes; text when it is all UTF-8 without NUL bytes (its+/// extension then picks markdown, CSV or JSON). Anything else is refused.+pub fn sniff(head: &[u8], is_text: bool, name: &str) -> Option<&'static str> {+ if let Some(m) = sniff_magic(head) {+ return Some(m);+ }if !is_text {return None;}- let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();- Some(match ext.as_str() {+ Some(match extension(name).as_str() {"md" | "markdown" => "text/markdown","csv" => "text/csv","json" => "application/json",@@ -138,23 +205,56 @@ impl Utf8Check {fn is_text(&self) -> bool {!self.bad && self.carry.is_empty()}++ /// No NUL and no invalid UTF-8 so far (a character may still be cut at the end).+ fn text_so_far(&self) -> bool {+ !self.bad+ }+}++/// Which cap a file passed.+#[derive(Debug, PartialEq, Clone, Copy)]+pub enum Cap {+ /// A video passed 100 MB.+ Video,+ /// Anything else passed 20 MB.+ Other,+ /// The declared length passed 100 MB before the type was known.+ Either,}#[derive(Debug, PartialEq)]pub enum StoreError {- TooLarge,+ TooLarge(Cap),Empty,Unsupported,Io,}+/// Error bodies: `error` (text for people) and a stable `code` (api.md); 413 adds `max_bytes`.fn store_error(e: StoreError) -> Response {+ let coded = |status: StatusCode, code: &str, text: &str, extra: Value| {+ let mut body = json!({"error": text, "code": code});+ if let (Some(b), Value::Object(x)) = (body.as_object_mut(), extra) {+ b.extend(x);+ }+ (status, Json(body)).into_response()+ };match e {- StoreError::TooLarge => error(StatusCode::PAYLOAD_TOO_LARGE, format!("files can be at most {} MB", MAX_ATTACHMENT_BYTES / 1024 / 1024)),- StoreError::Empty => error(StatusCode::BAD_REQUEST, "the file is empty"),- StoreError::Unsupported => error(+ StoreError::TooLarge(cap) => {+ let (text, max) = match cap {+ Cap::Video => ("Videos can be at most 100 MB.", MAX_VIDEO_BYTES),+ Cap::Other => ("Files can be at most 20 MB (videos up to 100 MB).", MAX_ATTACHMENT_BYTES),+ Cap::Either => ("Files can be at most 100 MB for videos and 20 MB for everything else.", MAX_VIDEO_BYTES),+ };+ coded(StatusCode::PAYLOAD_TOO_LARGE, "too_large", text, json!({"max_bytes": max}))+ }+ StoreError::Empty => coded(StatusCode::BAD_REQUEST, "empty", "The file is empty.", json!({})),+ StoreError::Unsupported => coded(StatusCode::UNSUPPORTED_MEDIA_TYPE,- "only images (PNG, JPEG, GIF, WebP), PDFs and text files (UTF-8: txt, md, csv, json, code) can be attached",+ "unsupported_type",+ "Only images (PNG, JPEG, GIF, WebP), videos (MP4, MOV, WebM), PDFs and text files (UTF-8: txt, md, csv, json, code) can be attached.",+ json!({}),),StoreError::Io => StatusCode::INTERNAL_SERVER_ERROR.into_response(),}@@ -176,11 +276,13 @@ struct Sink {size: u64,head: Vec<u8>,utf8: Utf8Check,+ /// The display name; only its extension is used, and only to refuse early.+ name: String,kept: bool,}impl Sink {- async fn new(root: &FsPath) -> Result<Self, StoreError> {+ async fn new(root: &FsPath, name: &str) -> Result<Self, StoreError> {let dir = root.join("tmp");tokio::fs::create_dir_all(&dir).await.map_err(|_| StoreError::Io)?;let tmp = dir.join(uuid::Uuid::new_v4().to_string());@@ -193,29 +295,39 @@ impl Sink {size: 0,head: Vec::new(),utf8: Utf8Check::default(),+ name: name.to_string(),kept: false,})}+ /// Takes the next chunk. Refuses as soon as the file is over its cap (100 MB once the head+ /// sniffed as video, else 20 MB) or its bytes rule it out ([`ruled_out_early`]).async fn push(&mut self, chunk: &[u8]) -> Result<(), StoreError> {+ if self.head.len() < HEAD_BYTES {+ let take = (HEAD_BYTES - self.head.len()).min(chunk.len());+ self.head.extend_from_slice(&chunk[..take]);+ }self.size += chunk.len() as u64;- if self.size > MAX_ATTACHMENT_BYTES {- return Err(StoreError::TooLarge);+ let video = sniff_magic(&self.head).is_some_and(is_video_mime);+ if video && self.size > MAX_VIDEO_BYTES {+ return Err(StoreError::TooLarge(Cap::Video));}- if self.head.len() < 16 {- let take = (16 - self.head.len()).min(chunk.len());- self.head.extend_from_slice(&chunk[..take]);+ if !video && self.size > MAX_ATTACHMENT_BYTES {+ return Err(StoreError::TooLarge(Cap::Other));}- self.hasher.update(chunk);self.utf8.feed(chunk);+ if ruled_out_early(&self.head, self.utf8.text_so_far(), &self.name) {+ return Err(StoreError::Unsupported);+ }+ self.hasher.update(chunk);self.file.write_all(chunk).await.map_err(|_| StoreError::Io)}- async fn finish(mut self, name: &str) -> Result<Stored, StoreError> {+ async fn finish(mut self) -> Result<Stored, StoreError> {if self.size == 0 {return Err(StoreError::Empty);}- let mime = sniff(&self.head, self.utf8.is_text(), name).ok_or(StoreError::Unsupported)?;+ let mime = sniff(&self.head, self.utf8.is_text(), &self.name).ok_or(StoreError::Unsupported)?;self.file.flush().await.map_err(|_| StoreError::Io)?;let sha256 = hex(&std::mem::take(&mut self.hasher).finalize());let dest = blob_path(&self.root, &sha256).ok_or(StoreError::Io)?;@@ -243,7 +355,7 @@ fn hex(bytes: &[u8]) -> String {/// Stores a file from disk (an agent's `share_file`).async fn store_file(root: &FsPath, path: &FsPath, name: &str) -> Result<Stored, StoreError> {let mut file = tokio::fs::File::open(path).await.map_err(|_| StoreError::Io)?;- let mut sink = Sink::new(root).await?;+ let mut sink = Sink::new(root, name).await?;let mut buf = vec![0u8; 64 * 1024];loop {let n = file.read(&mut buf).await.map_err(|_| StoreError::Io)?;@@ -252,13 +364,13 @@ async fn store_file(root: &FsPath, path: &FsPath, name: &str) -> Result<Stored,}sink.push(&buf[..n]).await?;}- sink.finish(name).await+ sink.finish().await}async fn store_bytes(root: &FsPath, bytes: &[u8], name: &str) -> Result<Stored, StoreError> {- let mut sink = Sink::new(root).await?;+ let mut sink = Sink::new(root, name).await?;sink.push(bytes).await?;- sink.finish(name).await+ sink.finish().await}fn error(status: StatusCode, message: impl Into<String>) -> Response {@@ -284,29 +396,52 @@ pub struct UploadQuery {pub name: Option<String>,}+/// Reads and drops the rest of a refused upload in the background (at most 100 MB or 30 s), so+/// the refusal reaches the browser instead of a reset connection it would report as status 0.+fn drain(mut stream: axum::body::BodyDataStream) {+ tokio::spawn(async move {+ let _ = tokio::time::timeout(std::time::Duration::from_secs(DRAIN_SECS), async {+ let mut seen = 0u64;+ while let Some(Ok(chunk)) = stream.next().await {+ seen += chunk.len() as u64;+ if seen > MAX_VIDEO_BYTES {+ break;+ }+ }+ })+ .await;+ });+}+/// `POST /api/attachments?name=<file name>` with the file as the raw body. 201 with the-/// attachment; it stays private to the uploader's UI until sent with a message.+/// attachment; it stays private to the uploader's UI until sent with a message. Refusals come+/// as soon as they are known: a declared length over 100 MB before any byte, a file its first+/// bytes rule out right after them, a cap at the byte that passes it (api.md).pub async fn upload(State(state): State<AppState>, Query(q): Query<UploadQuery>, headers: HeaderMap, body: Body) -> Response {let declared = headers.get(header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<u64>().ok());- if declared.is_some_and(|n| n > MAX_ATTACHMENT_BYTES) {- return store_error(StoreError::TooLarge);+ if declared.is_some_and(|n| n > MAX_VIDEO_BYTES) {+ return store_error(StoreError::TooLarge(Cap::Either));}let name = clean_name(q.name.as_deref().unwrap_or(""));let root = root(&state);- let mut sink = match Sink::new(&root).await {+ let mut sink = match Sink::new(&root, &name).await {Ok(s) => s,Err(e) => return store_error(e),};let mut stream = body.into_data_stream();while let Some(chunk) = stream.next().await {let Ok(chunk) = chunk else {- return error(StatusCode::BAD_REQUEST, "the upload was interrupted");+ return (StatusCode::BAD_REQUEST, Json(json!({"error": "The upload was interrupted.", "code": "interrupted"}))).into_response();};if let Err(e) = sink.push(&chunk).await {+ if matches!(e, StoreError::Unsupported | StoreError::TooLarge(_)) {+ drop(sink);+ drain(stream);+ }return store_error(e);}}- let stored = match sink.finish(&name).await {+ let stored = match sink.finish().await {Ok(s) => s,Err(e) => return store_error(e),};@@ -411,7 +546,7 @@ pub async fn content(State(state): State<AppState>, Path(id): Path<String>, Querif !(resp.status().is_success() || resp.status() == StatusCode::NOT_MODIFIED) {return resp;}- let inline = q.download.is_none() && INLINE_TYPES.contains(&a.mime.as_str());+ let inline = q.download.is_none() && (INLINE_TYPES.contains(&a.mime.as_str()) || is_video_mime(&a.mime));let h = resp.headers_mut();if let Ok(v) = HeaderValue::from_str(&a.mime) {h.insert(header::CONTENT_TYPE, v);@@ -508,13 +643,14 @@ pub fn tools() -> Vec<Value> {json!({"name": "read_attachment","description": "Read a file attached in this chat, by id. Text comes back as text, images as images; \- a PDF comes back as its text, page by page.",+ a PDF comes back as its text, page by page; a video as its length, size and up to 6 frames as images.","inputSchema": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]},}),json!({"name": "share_file","description": "Give the user a file as a download card in this chat. Either `path` (a file in your workspace) \- or `content` (text you write, e.g. a CSV or markdown report). Images, PDFs and text files, up to 20 MB.",+ or `content` (text you write, e.g. a CSV or markdown report). Images, PDFs and text files up to 20 MB; \+ videos (MP4, MOV, WebM) up to 100 MB.","inputSchema": {"type": "object","properties": {@@ -602,6 +738,9 @@ pub async fn tool_read(state: &AppState, scope: &SelfScope, args: &Value) -> (Valet data = base64::engine::general_purpose::STANDARD.encode(bytes);return (json!([{"type": "text", "text": a.name}, {"type": "image", "data": data, "mimeType": a.mime}]), false);}+ if is_video_mime(&a.mime) {+ return super::video::describe(&a.name, &a.mime, a.size, &path, &root(state).join("tmp")).await;+ }if a.mime == "application/pdf" {let Ok(bytes) = tokio::fs::read(&path).await else {return (text("Could not open the file.".into()), true);@@ -710,9 +849,12 @@ pub async fn tool_share(state: &AppState, scope: &SelfScope, args: &Value) -> (S};let stored = match stored {Ok(s) => s,- Err(StoreError::TooLarge) => return ("The file is larger than 20 MB.".into(), true),+ Err(StoreError::TooLarge(Cap::Video)) => return ("The video is larger than 100 MB.".into(), true),+ Err(StoreError::TooLarge(_)) => return ("The file is larger than 20 MB (videos up to 100 MB).".into(), true),Err(StoreError::Empty) => return ("The file is empty.".into(), true),- Err(StoreError::Unsupported) => return ("Only images, PDFs and UTF-8 text files can be shared.".into(), true),+ Err(StoreError::Unsupported) => {+ return ("Only images, videos (MP4, MOV, WebM), PDFs and UTF-8 text files can be shared.".into(), true)+ }Err(StoreError::Io) => return ("Could not read or store the file.".into(), true),};let context = origin.channel_id.clone().or_else(|| origin.thread_id.clone()).or_else(|| origin.direct_kwant_id.clone());@@ -812,6 +954,47 @@ mod tests {assert_eq!(sniff(b"{}", true, "x.json"), Some("application/json"));}+ fn ftyp(brand: &[u8; 4]) -> Vec<u8> {+ let mut h = b"\0\0\0\x20ftyp".to_vec();+ h.extend_from_slice(brand);+ h.extend_from_slice(b"\0\0\x02\0");+ h+ }++ #[test]+ fn videos_are_sniffed_from_bytes() {+ assert_eq!(sniff(&ftyp(b"isom"), false, "x.txt"), Some("video/mp4"));+ assert_eq!(sniff(&ftyp(b"mp42"), false, "clip.mov"), Some("video/mp4"));+ assert_eq!(sniff(&ftyp(b"iso5"), false, "x"), Some("video/mp4"));+ assert_eq!(sniff(&ftyp(b"3gp5"), false, "x"), Some("video/mp4"));+ assert_eq!(sniff(&ftyp(b"qt "), false, "clip.mp4"), Some("video/quicktime"));+ assert_eq!(sniff(b"\x1a\x45\xdf\xa3\x9f\x42\x86\x81\x01webm", false, "clip.mov"), Some("video/webm"));+ // ftyp files that aren't videos a browser plays: an iPhone photo, a voice memo+ for b in [b"heic", b"mif1", b"avif", b"M4A ", b"crx "] {+ assert_eq!(sniff(&ftyp(b), false, "x.mp4"), None, "{}", String::from_utf8_lossy(b));+ }+ assert_eq!(sniff(b"\0\0\0\x20ftyp", false, "x.mp4"), None, "no brand yet");+ assert!(is_video_mime("video/quicktime") && !is_video_mime("image/png") && !is_video_mime("video/x-msvideo"));+ }++ #[test]+ fn first_bytes_rule_out_what_cannot_be_accepted() {+ let zip = b"PK\x03\x04\x14\0\0\0\x08\0\0\0\0\0\0\0";+ assert!(ruled_out_early(zip, false, "holiday.mp4"), "a zip renamed .mp4");+ assert!(ruled_out_early(b"ID3\x04\0\0\0\0\0\x23TSSE\0\0\0", false, "song.mp3"));+ // Text-looking bytes under a binary extension can't become text/plain+ assert!(ruled_out_early(b"just ascii bytes here", true, "clip.mp4"));+ assert!(ruled_out_early(&ftyp(b"heic"), false, "IMG_1.HEIC"));+ // Not yet 16 bytes, or still decided at the end+ assert!(!ruled_out_early(b"PK\x03\x04", false, "a.zip"));+ assert!(!ruled_out_early(b"<template>hello</template>", true, "App.vue"));+ assert!(!ruled_out_early(b"-----BEGIN PRIVATE KEY-----", true, "server.key"));+ assert!(!ruled_out_early(b"no extension at all here", true, "Makefile"));+ // Accepted magic is never ruled out, whatever the name+ assert!(!ruled_out_early(&ftyp(b"isom"), false, "a.zip"));+ assert!(!ruled_out_early(b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n1 0", false, "x.exe"));+ }+#[test]fn utf8_check_spans_chunks() {let s = "héllo wörld".as_bytes();diff --git a/src/server/mod.rs b/src/server/mod.rsindex e0a1d07e..fb328339 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -21,6 +21,7 @@ pub mod turns;pub mod delegation;pub mod parked;pub mod attachments;+pub mod video;pub mod questions;pub mod activity;pub mod human_steps;diff --git a/src/server/video.rs b/src/server/video.rsnew file mode 100644index 00000000..b0137379--- /dev/null+++ b/src/server/video.rs@@ -0,0 +1,534 @@+//! Looking inside videos for `read_attachment` (video-drop-073 V5): ffprobe for length, size and+//! codec, then ffmpeg for up to six evenly spaced JPEG frames the bot sees as images.+//!+//! The file is untrusted media, so ffmpeg is held short:+//! - input is the blob path (`file:<data>/attachments/xx/<sha>`), never the name the user gave;+//! - the demuxer is forced from the sniffed type (`-f mov -enable_drefs 0`, or `-f matroska`), so+//! no format probing, no playlists, no external data references; `-protocol_whitelist file`;+//! - `-max_pixels` refuses frames with absurd dimensions, `-threads 2`, `ffmpeg -nostdin` (ffprobe+//! has no such flag: it gets a closed stdin like ffmpeg);+//! - an empty environment, its own session and process group, `nice 10`, `RLIMIT_FSIZE` and+//! `RLIMIT_CORE` 0, as the git reader (`dev::git`), plus a 2 GB memory cap (`RLIMIT_AS`) on+//! Linux only: macOS can't lower it, so there it is tried and skipped;+//! - output only into a fresh temp dir that is removed however the read ends;+//! - one deadline (20 s, as a PDF) for the whole read; on it the process group is killed;+//! - at most two video reads at once.+//!+//! Without ffmpeg/ffprobe the bot gets the size and [`NO_FFMPEG`].++use serde_json::{json, Value};+use std::ffi::{OsStr, OsString};+use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::time::{Duration, Instant};+use tokio::io::{AsyncRead, AsyncReadExt};++/// Longest a whole video read (probe and frames) may take.+pub const READ_SECS: u64 = 20;+/// The line a bot gets when the server has no ffmpeg.+pub const NO_FFMPEG: &str = "Install ffmpeg on the server to let bots look inside videos.";+/// Why a read stopped when ffmpeg or ffprobe couldn't be started.+const NO_START: &str = "ffmpeg couldn't start on this server.";+const MAX_FRAMES: usize = 6;+/// Longest side of a frame the bot gets.+const FRAME_EDGE: u32 = 1280;+/// Largest frame returned (the `read_attachment` image cap).+const MAX_FRAME_BYTES: u64 = 5 * 1024 * 1024;+/// Frames bigger than this many pixels aren't decoded (8K is 33 MP).+const MAX_PIXELS: &str = "40000000";+/// No file ffmpeg writes may pass this.+const OUT_FSIZE: u64 = 16 * 1024 * 1024;+/// Address space for one ffmpeg/ffprobe.+const MAX_AS: u64 = 2 * 1024 * 1024 * 1024;+/// Most ffprobe JSON read.+const MAX_PROBE_OUT: usize = 256 * 1024;+/// Video reads at once: decoding is CPU- and memory-heavy, and the server is small.+static SLOTS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(2);++/// Where ffprobe and ffmpeg live.+#[derive(Debug, Clone)]+pub struct Tools {+ pub ffprobe: PathBuf,+ pub ffmpeg: PathBuf,+}++fn is_executable(p: &Path) -> bool {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ p.metadata().is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)+ }+ #[cfg(not(unix))]+ {+ p.is_file()+ }+}++/// Both tools from the absolute directories of `path_var`, then `extra` (a Mac app's PATH lacks+/// Homebrew). `None` unless both are found.+pub fn find_tools(path_var: Option<&OsStr>, extra: &[&Path]) -> Option<Tools> {+ let mut dirs: Vec<PathBuf> = path_var.map(|p| std::env::split_paths(p).collect()).unwrap_or_default();+ dirs.extend(extra.iter().map(|p| p.to_path_buf()));+ // A relative entry ("." or "") would pick up a program from wherever the server runs+ dirs.retain(|d| d.is_absolute());+ let exe = if cfg!(windows) { ".exe" } else { "" };+ let find = |name: &str| dirs.iter().map(|d| d.join(format!("{name}{exe}"))).find(|p| is_executable(p));+ Some(Tools { ffprobe: find("ffprobe")?, ffmpeg: find("ffmpeg")? })+}++/// The server's ffmpeg, if it has one.+pub fn tools() -> Option<Tools> {+ find_tools(+ std::env::var_os("PATH").as_deref(),+ &[Path::new("/opt/homebrew/bin"), Path::new("/usr/local/bin"), Path::new("/opt/local/bin"), Path::new("/usr/bin")],+ )+}++/// What ffprobe says about a video.+#[derive(Debug, Default, PartialEq)]+pub struct Info {+ pub duration: Option<f64>,+ /// As shown: width and height swapped for a video recorded on its side.+ pub width: Option<u64>,+ pub height: Option<u64>,+ pub codec: Option<String>,+ pub fps: Option<f64>,+ pub audio: Option<String>,+}++fn ratio(s: &str) -> Option<f64> {+ let (n, d) = s.split_once('/')?;+ let (n, d) = (n.trim().parse::<f64>().ok()?, d.trim().parse::<f64>().ok()?);+ (d > 0.0 && n > 0.0).then(|| n / d)+}++/// The facts in ffprobe's JSON; `None` without a video stream.+pub fn parse_probe(out: &[u8]) -> Option<Info> {+ let v: Value = serde_json::from_slice(out).ok()?;+ let streams = v["streams"].as_array()?;+ let video = streams.iter().find(|s| s["codec_type"] == "video")?;+ let mut info = Info {+ duration: v["format"]["duration"].as_str().and_then(|d| d.parse::<f64>().ok()).filter(|d| d.is_finite() && *d > 0.0),+ width: video["width"].as_u64().filter(|w| *w > 0),+ height: video["height"].as_u64().filter(|h| *h > 0),+ codec: video["codec_name"].as_str().map(|c| c.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '_').take(24).collect()),+ fps: video["avg_frame_rate"].as_str().and_then(ratio).filter(|f| *f < 1000.0),+ audio: streams+ .iter()+ .find(|s| s["codec_type"] == "audio")+ .map(|a| a["codec_name"].as_str().unwrap_or("yes").chars().filter(|c| c.is_ascii_alphanumeric() || *c == '_').take(24).collect()),+ };+ let rotation = video["side_data_list"]+ .as_array()+ .and_then(|l| l.iter().find_map(|d| d["rotation"].as_f64()))+ .or_else(|| video["tags"]["rotate"].as_str().and_then(|r| r.parse::<f64>().ok()))+ .unwrap_or(0.0);+ if (rotation.abs() - 90.0).abs() < 1.0 || (rotation.abs() - 270.0).abs() < 1.0 {+ std::mem::swap(&mut info.width, &mut info.height);+ }+ Some(info)+}++/// `m:ss.s` (or `h:mm:ss`).+fn clock(secs: f64) -> String {+ let s = secs.max(0.0);+ if s >= 3600.0 {+ let t = s as u64;+ return format!("{}:{:02}:{:02}", t / 3600, t / 60 % 60, t % 60);+ }+ let m = (s / 60.0).floor();+ format!("{}:{:04.1}", m as u64, s - m * 60.0)+}++pub fn human_size(size: i64) -> String {+ let s = size.max(0) as f64;+ if s >= 1024.0 * 1024.0 {+ format!("{:.1} MB", s / 1024.0 / 1024.0)+ } else {+ format!("{} KB", ((s + 1023.0) / 1024.0).floor() as u64)+ }+}++fn summary(info: &Info) -> String {+ let mut parts = vec![match info.duration {+ Some(d) => format!("Duration {}", clock(d)),+ None => "Duration unknown".to_string(),+ }];+ if let (Some(w), Some(h)) = (info.width, info.height) {+ parts.push(format!("{w}×{h}"));+ }+ if let Some(c) = &info.codec {+ parts.push(c.clone());+ }+ if let Some(f) = info.fps {+ parts.push(if (f - f.round()).abs() < 0.01 { format!("{} fps", f.round() as u64) } else { format!("{f:.2} fps") });+ }+ parts.push(match &info.audio {+ Some(a) => format!("audio {a}"),+ None => "no audio".to_string(),+ });+ parts.join(" · ")+}++/// Where frames are taken: the middles of `n` equal slices, `n` = whole seconds up to 6 (at+/// least 1); one at the start when the length is unknown.+pub fn frame_times(duration: Option<f64>) -> Vec<f64> {+ let Some(d) = duration else { return vec![0.0] };+ let n = (d.floor() as usize).clamp(1, MAX_FRAMES);+ (0..n).map(|i| d * (2 * i + 1) as f64 / (2 * n) as f64).collect()+}++/// The input options for the sniffed type: the demuxer is never guessed from the bytes.+fn input_opts(mime: &str) -> Vec<&'static str> {+ let mut o = vec!["-protocol_whitelist", "file"];+ if mime == "video/webm" {+ o.extend(["-f", "matroska"]);+ } else {+ o.extend(["-f", "mov", "-enable_drefs", "0"]);+ }+ o.extend(["-max_pixels", MAX_PIXELS]);+ o+}++#[derive(Debug, PartialEq)]+enum RunError {+ Timeout,+ /// It ran and failed (or wrote too much): blame the file.+ Failed,+ /// It never started (missing, not executable, missing libraries, a limit refused): blame+ /// the server, not the file.+ Spawn,+}++/// A temp dir removed when dropped, however the read ends.+struct TempDir(PathBuf);++impl Drop for TempDir {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+}++async fn read_capped<R: AsyncRead + Unpin>(r: Option<R>, cap: usize) -> Result<Vec<u8>, RunError> {+ let Some(mut r) = r else { return Ok(Vec::new()) };+ let mut out = Vec::new();+ let mut buf = vec![0u8; 16 * 1024];+ loop {+ let n = r.read(&mut buf).await.map_err(|_| RunError::Failed)?;+ if n == 0 {+ return Ok(out);+ }+ if out.len() + n > cap {+ return Err(RunError::Failed);+ }+ out.extend_from_slice(&buf[..n]);+ }+}++/// Runs one ffmpeg/ffprobe as described in the module docs; its stdout on success.+async fn run(bin: &Path, args: &[OsString], cwd: &Path, until: Instant) -> Result<Vec<u8>, RunError> {+ let left = until.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or(RunError::Timeout)?;+ let mut cmd = tokio::process::Command::new(bin);+ cmd.args(args)+ .env_clear()+ .env("LC_ALL", "C")+ .current_dir(cwd)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .kill_on_drop(true);+ #[cfg(unix)]+ // SAFETY: setsid(2), nice(2), setrlimit(2) and signal(2) are async-signal-safe and touch no+ // memory of this process+ unsafe {+ cmd.pre_exec(|| {+ // Its own process group, so a timeout kills everything it started+ libc::setsid();+ libc::nice(10);+ let limit = |res, cap: u64| {+ let lim = libc::rlimit { rlim_cur: cap as libc::rlim_t, rlim_max: cap as libc::rlim_t };+ libc::setrlimit(res, &lim)+ };+ // Required everywhere, as in dev::git: no ffmpeg runs without them+ for (res, cap) in [(libc::RLIMIT_FSIZE, OUT_FSIZE), (libc::RLIMIT_CORE, 0)] {+ if limit(res, cap) != 0 {+ return Err(std::io::Error::last_os_error());+ }+ }+ // The memory cap is required on Linux, where RLIMIT_AS is enforced. macOS rejects+ // lowering it (EINVAL; Darwin maps it to RSS and doesn't enforce it), and Mac is the+ // main platform, so elsewhere it is best-effort: a refusal must not stop every video+ // read. The 20 s deadline, -max_pixels and -threads 2 still bound the work there.+ #[cfg(target_os = "linux")]+ if limit(libc::RLIMIT_AS, MAX_AS) != 0 {+ return Err(std::io::Error::last_os_error());+ }+ #[cfg(not(target_os = "linux"))]+ let _ = limit(libc::RLIMIT_AS, MAX_AS);+ libc::signal(libc::SIGXFSZ, libc::SIG_DFL);+ Ok(())+ });+ }+ let mut child = cmd.spawn().map_err(|_| RunError::Spawn)?;+ let mut group = crate::drivers::cli::ProcessGroup::of(&child);+ let out = child.stdout.take();+ let work = async {+ let out = read_capped(out, MAX_PROBE_OUT).await?;+ let status = child.wait().await.map_err(|_| RunError::Failed)?;+ Ok::<_, RunError>((out, status))+ };+ let (out, status) = tokio::time::timeout(left, work).await.map_err(|_| RunError::Timeout)??;+ group.disarm();+ if status.success() {+ Ok(out)+ } else {+ Err(RunError::Failed)+ }+}++fn file_arg(blob: &Path) -> OsString {+ let mut a = OsString::from("file:");+ a.push(blob.as_os_str());+ a+}++fn os(args: &[&str]) -> Vec<OsString> {+ args.iter().map(OsString::from).collect()+}++/// `read_attachment` for a video: MCP content blocks, and whether it is an error.+pub async fn describe(name: &str, mime: &str, size: i64, blob: &Path, tmp_parent: &Path) -> (Value, bool) {+ describe_with(tools(), name, mime, size, blob, tmp_parent, Duration::from_secs(READ_SECS)).await+}++pub async fn describe_with(+ tools: Option<Tools>,+ name: &str,+ mime: &str,+ size: i64,+ blob: &Path,+ tmp_parent: &Path,+ limit: Duration,+) -> (Value, bool) {+ let text = |t: String| json!([{"type": "text", "text": t}]);+ let label = format!("{name} ({mime}, {})", human_size(size));+ let Some(tools) = tools else {+ return (text(format!("{name} is a video ({mime}, {}). {NO_FFMPEG}", human_size(size))), false);+ };+ let Ok(_slot) = SLOTS.acquire().await else {+ return (text(format!("Couldn't look inside {label}: the server is shutting down.")), true);+ };+ let until = Instant::now() + limit;+ let dir = tmp_parent.join(format!("video-{}", uuid::Uuid::new_v4()));+ if tokio::fs::create_dir_all(&dir).await.is_err() {+ return (text(format!("Couldn't look inside {label}: no room for a temp folder.")), true);+ }+ let dir = TempDir(dir);+ let input = file_arg(blob);++ let mut probe = os(&["-v", "error", "-hide_banner"]);+ probe.extend(os(&input_opts(mime)));+ probe.extend(os(&[+ "-show_entries",+ "format=duration:stream=codec_type,codec_name,width,height,avg_frame_rate:stream_side_data=rotation:stream_tags=rotate",+ "-of",+ "json",+ ]));+ probe.push(input.clone());+ let info = match run(&tools.ffprobe, &probe, &dir.0, until).await.map(|o| parse_probe(&o)) {+ Ok(Some(info)) => info,+ Ok(None) | Err(RunError::Failed) => {+ return (text(format!("Couldn't look inside {label}: ffmpeg can't read it (it may be cut off or damaged).")), true)+ }+ Err(RunError::Timeout) => {+ return (text(format!("Couldn't look inside {label}: reading it took longer than {} seconds.", limit.as_secs())), true)+ }+ Err(RunError::Spawn) => return (text(format!("Couldn't look inside {label}: {NO_START}")), true),+ };++ let times = frame_times(info.duration);+ let scale = format!("scale=w='min({FRAME_EDGE},iw)':h='min({FRAME_EDGE},ih)':force_original_aspect_ratio=decrease");+ let mut frames: Vec<(f64, Vec<u8>)> = Vec::new();+ let mut timed_out = false;+ let mut no_start = false;+ for (i, t) in times.iter().enumerate() {+ let out = dir.0.join(format!("f{i}.jpg"));+ let mut args = os(&["-nostdin", "-v", "error", "-hide_banner", "-threads", "2"]);+ args.extend(os(&input_opts(mime)));+ args.extend(os(&["-ss", &format!("{t:.3}"), "-i"]));+ args.push(input.clone());+ args.extend(os(&["-map", "0:v:0", "-frames:v", "1", "-an", "-sn", "-dn", "-vf", &scale, "-q:v", "5", "-f", "image2", "-update", "1", "-y"]));+ args.push(out.clone().into_os_string());+ match run(&tools.ffmpeg, &args, &dir.0, until).await {+ Ok(_) => {}+ Err(RunError::Timeout) => {+ timed_out = true;+ break;+ }+ Err(RunError::Failed) => continue,+ // ffprobe ran but ffmpeg can't: the same for every frame+ Err(RunError::Spawn) => {+ no_start = true;+ break;+ }+ }+ if let Ok(meta) = tokio::fs::metadata(&out).await {+ if meta.len() > 0 && meta.len() <= MAX_FRAME_BYTES {+ if let Ok(bytes) = tokio::fs::read(&out).await {+ if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {+ frames.push((*t, bytes));+ }+ }+ }+ }+ }+ drop(dir);++ let mut head = format!("--- {label} ---\n{}", summary(&info));+ head.push_str(&match (frames.len(), timed_out) {+ (0, true) => format!("\nNo frames: making them took longer than {} seconds.", limit.as_secs()),+ (0, false) if no_start => format!("\nNo frames: {NO_START}"),+ (0, false) => "\nNo frames could be taken from it.".to_string(),+ (n, true) => format!("\n{n} of {} frames (the rest took longer than {} seconds):", times.len(), limit.as_secs()),+ (1, false) => "\n1 frame:".to_string(),+ (n, false) => format!("\n{n} frames, evenly spaced:"),+ });+ let mut blocks = vec![json!({"type": "text", "text": head})];+ use base64::Engine;+ for (i, (t, bytes)) in frames.iter().enumerate() {+ blocks.push(json!({"type": "text", "text": format!("frame {} at {}", i + 1, clock(*t))}));+ blocks.push(json!({"type": "image", "data": base64::engine::general_purpose::STANDARD.encode(bytes), "mimeType": "image/jpeg"}));+ }+ (Value::Array(blocks), false)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn probe_json_reads_rotation_audio_and_rates() {+ let j = br#"{"streams":[{"codec_type":"video","codec_name":"h264","width":1920,"height":1080,"avg_frame_rate":"30000/1001","side_data_list":[{"rotation":-90}]},{"codec_type":"audio","codec_name":"aac"}],"format":{"duration":"12.400000"}}"#;+ let i = parse_probe(j).unwrap();+ assert_eq!((i.width, i.height), (Some(1080), Some(1920)), "a phone video on its side shows upright");+ assert_eq!(i.duration, Some(12.4));+ assert_eq!(summary(&i), "Duration 0:12.4 · 1080×1920 · h264 · 29.97 fps · audio aac");+ let none = br#"{"streams":[{"codec_type":"audio","codec_name":"aac"}],"format":{}}"#;+ assert!(parse_probe(none).is_none(), "no video stream");+ assert!(parse_probe(b"not json").is_none());+ let bare = parse_probe(br#"{"streams":[{"codec_type":"video","codec_name":"vp9<script>","avg_frame_rate":"0/0"}],"format":{"duration":"N/A"}}"#).unwrap();+ assert_eq!(summary(&bare), "Duration unknown · vp9script · no audio");+ }++ #[test]+ fn frames_are_evenly_spaced_and_at_most_six() {+ assert_eq!(frame_times(None), vec![0.0]);+ assert_eq!(frame_times(Some(0.4)), vec![0.2]);+ assert_eq!(frame_times(Some(2.5)).len(), 2);+ let t = frame_times(Some(60.0));+ assert_eq!(t, vec![5.0, 15.0, 25.0, 35.0, 45.0, 55.0]);+ assert_eq!(clock(65.25), "1:05.2");+ assert_eq!(clock(3725.0), "1:02:05");+ }++ #[test]+ fn tools_come_from_absolute_dirs_only() {+ let tmp = tempfile::tempdir().unwrap();+ let empty = tmp.path().join("empty");+ std::fs::create_dir_all(&empty).unwrap();+ assert!(find_tools(Some(empty.as_os_str()), &[]).is_none(), "PATH without ffmpeg");+ assert!(find_tools(None, &[]).is_none());+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let bin = tmp.path().join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ for n in ["ffprobe", "ffmpeg"] {+ std::fs::write(bin.join(n), "#!/bin/sh\n").unwrap();+ std::fs::set_permissions(bin.join(n), std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let path = std::env::join_paths([empty.clone(), bin.clone()]).unwrap();+ assert_eq!(find_tools(Some(&path), &[]).unwrap().ffmpeg, bin.join("ffmpeg"));+ // Relative entries are skipped even when they hold the tools+ let rel = std::env::join_paths([PathBuf::from("."), PathBuf::from("bin")]).unwrap();+ assert!(find_tools(Some(&rel), &[]).is_none());+ std::fs::set_permissions(bin.join("ffmpeg"), std::fs::Permissions::from_mode(0o644)).unwrap();+ assert!(find_tools(Some(&path), &[]).is_none(), "not executable");+ }+ }++ #[tokio::test]+ async fn without_ffmpeg_the_bot_gets_the_size_and_one_line() {+ let tmp = tempfile::tempdir().unwrap();+ let (v, err) =+ describe_with(None, "clip.mp4", "video/mp4", 8 * 1024 * 1024, &tmp.path().join("x"), tmp.path(), Duration::from_secs(5)).await;+ assert!(!err);+ assert_eq!(v[0]["text"], format!("clip.mp4 is a video (video/mp4, 8.0 MB). {NO_FFMPEG}"));+ assert_eq!(v.as_array().unwrap().len(), 1);+ }++ /// A binary that can't be started (gone since the lookup, not executable, missing libraries)+ /// is the server's problem: the bot isn't told the file is damaged.+ #[tokio::test]+ async fn an_ffmpeg_that_cannot_start_is_not_blamed_on_the_file() {+ let tmp = tempfile::tempdir().unwrap();+ let blob = tmp.path().join("blob");+ std::fs::write(&blob, b"\0\0\0\x20ftypisom").unwrap();+ let not_exec = tmp.path().join("ffprobe");+ std::fs::write(¬_exec, "#!/bin/sh\n").unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(¬_exec, std::fs::Permissions::from_mode(0o644)).unwrap();+ }+ for ffprobe in [tmp.path().join("missing/ffprobe"), not_exec] {+ let tools = Tools { ffprobe: ffprobe.clone(), ffmpeg: tmp.path().join("missing/ffmpeg") };+ let (v, err) = describe_with(Some(tools), "clip.mp4", "video/mp4", 2048, &blob, tmp.path(), Duration::from_secs(5)).await;+ assert!(err, "{ffprobe:?}");+ assert_eq!(v[0]["text"], "Couldn't look inside clip.mp4 (video/mp4, 2 KB): ffmpeg couldn't start on this server.");+ }+ let left: Vec<_> = std::fs::read_dir(tmp.path()).unwrap().flatten().filter(|e| e.file_name().to_string_lossy().starts_with("video-")).collect();+ assert!(left.is_empty(), "temp dirs removed");+ }++ /// A hostile file that makes ffprobe (or ffmpeg) hang: the read stops at its deadline, the+ /// whole process group is killed and the temp dir is gone.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_hanging_ffmpeg_is_stopped_at_the_deadline_and_killed() {+ use std::os::unix::fs::PermissionsExt;+ let tmp = tempfile::tempdir().unwrap();+ let bin = tmp.path().join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ let pidfile = tmp.path().join("pid");+ // The fake tool forks a child that sleeps, so the kill has to reach the whole group+ let script = format!("#!/bin/sh\nsleep 60 &\necho $! > {}\nwait\n", pidfile.display());+ for n in ["ffprobe", "ffmpeg"] {+ std::fs::write(bin.join(n), &script).unwrap();+ std::fs::set_permissions(bin.join(n), std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let tools = Tools { ffprobe: bin.join("ffprobe"), ffmpeg: bin.join("ffmpeg") };+ let blob = tmp.path().join("blob");+ std::fs::write(&blob, b"\0\0\0\x20ftypisom").unwrap();+ let work = tmp.path().join("work");+ std::fs::create_dir_all(&work).unwrap();+ let start = Instant::now();+ let (v, err) = describe_with(Some(tools), "evil.mp4", "video/mp4", 16, &blob, &work, Duration::from_secs(1)).await;+ assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed());+ assert!(err);+ assert!(v[0]["text"].as_str().unwrap().contains("took longer than 1 seconds"), "{v}");+ assert_eq!(std::fs::read_dir(&work).unwrap().count(), 0, "temp dir removed");+ let pid: i32 = std::fs::read_to_string(&pidfile).unwrap().trim().parse().unwrap();+ // SIGKILL to the group is asynchronous; give the kernel a moment+ let mut gone = false;+ for _ in 0..50 {+ // SAFETY: kill(2) with signal 0 only checks the pid+ if unsafe { libc::kill(pid, 0) } != 0 {+ gone = true;+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ assert!(gone, "the sleeping grandchild was killed with the group");+ }+}diff --git a/tests/fixtures/testsrc.mov b/tests/fixtures/testsrc.movnew file mode 100644index 00000000..e04439a7Binary files /dev/null and b/tests/fixtures/testsrc.mov differdiff --git a/tests/fixtures/testsrc.mp4 b/tests/fixtures/testsrc.mp4new file mode 100644index 00000000..e59ad31bBinary files /dev/null and b/tests/fixtures/testsrc.mp4 differdiff --git a/tests/fixtures/testsrc.webm b/tests/fixtures/testsrc.webmnew file mode 100644index 00000000..66d4e226Binary files /dev/null and b/tests/fixtures/testsrc.webm differdiff --git a/tests/video_attachments_test.rs b/tests/video_attachments_test.rsnew file mode 100644index 00000000..f6011215--- /dev/null+++ b/tests/video_attachments_test.rs@@ -0,0 +1,256 @@+//! Videos as attachments (video-drop-073): mp4/mov/webm are recognised from their bytes, may be+//! up to 100 MB (everything else stays at 20 MB), are refused right after the first bytes when+//! they can't be accepted, play inline, are shared by agents, and read as a few frames.+//! Fixtures are 2–3 s ffmpeg `testsrc` clips (synthetic, no real footage).++mod common;++use axum::{+ body::{to_bytes, Body},+ http::{HeaderMap, Request, StatusCode},+};+use common::*;+use kwnt::server::continuity::{SelfScope, TurnOrigin};+use serde_json::{json, Value};+use std::time::Duration;+use tower::ServiceExt;++const MP4: &[u8] = include_bytes!("fixtures/testsrc.mp4");+const MOV: &[u8] = include_bytes!("fixtures/testsrc.mov");+const WEBM: &[u8] = include_bytes!("fixtures/testsrc.webm");++async fn upload_body(env: &Env, name: &str, body: Body, length: Option<u64>) -> (StatusCode, Value) {+ let mut req = Request::builder().method("POST").uri(format!("/api/attachments?name={name}"));+ if let Some(n) = length {+ req = req.header("content-length", n.to_string());+ }+ let resp = env.app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let s = resp.status();+ let b = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&b).unwrap_or(Value::Null))+}++async fn upload(env: &Env, name: &str, bytes: Vec<u8>) -> (StatusCode, Value) {+ upload_body(env, name, Body::from(bytes), None).await+}++async fn fetch(env: &Env, uri: &str, headers: &[(&str, &str)]) -> (StatusCode, HeaderMap, Vec<u8>) {+ let mut b = Request::builder().uri(uri);+ for (k, v) in headers {+ b = b.header(*k, *v);+ }+ let resp = env.app.clone().oneshot(b.body(Body::empty()).unwrap()).await.unwrap();+ let (parts, body) = resp.into_parts();+ (parts.status, parts.headers, to_bytes(body, usize::MAX).await.unwrap().to_vec())+}++fn tmp_files(env: &Env) -> usize {+ std::fs::read_dir(env.tmp.path().join("data/attachments/tmp")).map(|d| d.count()).unwrap_or(0)+}++/// A video head (`ftyp isom`) padded with zeros to `len` bytes.+fn fake_mp4(len: usize) -> Vec<u8> {+ let mut v = b"\0\0\0\x20ftypisom\0\0\x02\0isomiso2avc1mp41".to_vec();+ v.resize(len, 0);+ v+}++async fn self_call(env: &Env, token: &str, tool: &str, args: Value) -> Value {+ let (s, v) = call_with(+ &env.app,+ "POST",+ "/api/mcp/self",+ Some(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": tool, "arguments": args}})),+ &[("authorization", &format!("Bearer {token}"))],+ )+ .await;+ assert_eq!(s, StatusCode::OK);+ v["result"].clone()+}++fn text_of(result: &Value) -> String {+ result["content"].as_array().unwrap().iter().filter_map(|c| c["text"].as_str()).collect::<Vec<_>>().join("\n")+}++async fn direct_turn(env: &Env, token: &str, kwant: &str, workspace: Option<std::path::PathBuf>) {+ env.state.self_tools.lock().await.insert(+ token.into(),+ SelfScope {+ kwant_id: kwant.into(),+ kwant_name: "K".into(),+ origin: Some(TurnOrigin { direct_kwant_id: Some(kwant.into()), ..Default::default() }),+ workspace,+ ..Default::default()+ },+ );+}++#[tokio::test]+async fn videos_are_known_by_their_bytes_and_play_inline() {+ let env = setup().await;+ // Misleading names on purpose: the bytes decide+ for (name, bytes, mime) in [("clip.mov", MP4, "video/mp4"), ("clip.mp4", MOV, "video/quicktime"), ("clip.txt", WEBM, "video/webm")] {+ let (s, a) = upload(&env, name, bytes.to_vec()).await;+ assert_eq!(s, StatusCode::CREATED, "{name}: {a}");+ assert_eq!(a["mime"], mime, "{name}");+ assert_eq!(a["size"], bytes.len());+ let id = a["id"].as_str().unwrap();++ let (s, h, body) = fetch(&env, &format!("/api/attachments/{id}/content"), &[]).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(body, bytes);+ assert_eq!(h["content-type"], mime);+ assert!(h["content-disposition"].to_str().unwrap().starts_with("inline;"), "plays in a <video>");+ assert_eq!(h["x-content-type-options"], "nosniff");+ assert_eq!(h["content-security-policy"], "default-src 'none'; sandbox");+ assert_eq!(h["cross-origin-resource-policy"], "same-origin");+ let (_, h, _) = fetch(&env, &format!("/api/attachments/{id}/content?download=1"), &[]).await;+ assert!(h["content-disposition"].to_str().unwrap().starts_with("attachment;"));+ // Seeking needs ranges+ let (s, h, body) = fetch(&env, &format!("/api/attachments/{id}/content"), &[("range", "bytes=100-199")]).await;+ assert_eq!(s, StatusCode::PARTIAL_CONTENT);+ assert_eq!(body, &bytes[100..200]);+ assert_eq!(h["content-range"], format!("bytes 100-199/{}", bytes.len()));+ }++ // Not videos, whatever the name: a zip, an iPhone photo, an M4A voice memo+ let mut zip = b"PK\x03\x04\x14\0\0\0\x08\0".to_vec();+ zip.resize(4096, 7);+ let mut heic = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic".to_vec();+ heic.resize(4096, 0);+ let mut m4a = b"\0\0\0\x1cftypM4A \0\0\0\0M4A isom".to_vec();+ m4a.resize(4096, 0);+ for (name, bytes) in [("holiday.mp4", zip), ("IMG_0001.mov", heic), ("memo.mp4", m4a)] {+ let (s, v) = upload(&env, name, bytes).await;+ assert_eq!(s, StatusCode::UNSUPPORTED_MEDIA_TYPE, "{name}");+ assert_eq!(v["code"], "unsupported_type");+ assert!(v["error"].as_str().unwrap().contains("videos (MP4, MOV, WebM)"));+ }+ assert_eq!(tmp_files(&env), 0);+}++#[tokio::test]+async fn videos_may_be_100_mb_and_everything_else_20() {+ let env = setup().await;+ let (s, a) = upload(&env, "long.mp4", fake_mp4(25 * 1024 * 1024)).await;+ assert_eq!(s, StatusCode::CREATED, "{a}");+ assert_eq!(a["mime"], "video/mp4");++ let (s, v) = upload(&env, "big.txt", vec![b'a'; 25 * 1024 * 1024]).await;+ assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE);+ assert_eq!(v, json!({"error": "Files can be at most 20 MB (videos up to 100 MB).", "code": "too_large", "max_bytes": 20971520}));++ let (s, v) = upload(&env, "huge.mp4", fake_mp4(100 * 1024 * 1024 + 1)).await;+ assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE);+ assert_eq!(v, json!({"error": "Videos can be at most 100 MB.", "code": "too_large", "max_bytes": 104857600}));+ let (s, a) = upload(&env, "edge.mp4", fake_mp4(100 * 1024 * 1024)).await;+ assert_eq!(s, StatusCode::CREATED, "exactly 100 MB is fine: {a}");++ // A declared length over 100 MB is refused before any byte is read+ let (s, v) = upload_body(&env, "x.mp4", Body::from(fake_mp4(64)), Some(100 * 1024 * 1024 + 1)).await;+ assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE);+ assert_eq!(v["max_bytes"], 104857600);+ assert_eq!(v["error"], "Files can be at most 100 MB for videos and 20 MB for everything else.");+ assert_eq!(tmp_files(&env), 0, "refused uploads leave no temp file");+}++/// The competitor's complaint, and kwant's old behaviour: a file that can't be accepted was read+/// to the end before being refused. Now the refusal comes right after the first chunk, while+/// the client is still sending.+#[tokio::test]+async fn a_file_that_cannot_be_accepted_is_refused_before_the_body_ends() {+ let env = setup().await;+ let (tx, rx) = tokio::sync::mpsc::channel::<Result<Vec<u8>, std::io::Error>>(4);+ let mut zip = b"PK\x03\x04\x14\0\0\0\x08\0".to_vec();+ zip.resize(64 * 1024, 7);+ tx.send(Ok(zip)).await.unwrap();+ let body = Body::from_stream(tokio_stream::wrappers::ReceiverStream::new(rx));+ let (s, v) = tokio::time::timeout(Duration::from_secs(5), upload_body(&env, "holiday.mp4", body, Some(80 * 1024 * 1024)))+ .await+ .expect("answered while the body is still open");+ assert_eq!(s, StatusCode::UNSUPPORTED_MEDIA_TYPE, "{v}");+ assert_eq!(v["code"], "unsupported_type");+ // The rest is read and dropped (so a browser sees the 415, not a reset), never stored+ for _ in 0..8 {+ tx.send(Ok(vec![7u8; 1024 * 1024])).await.expect("the server keeps draining");+ }+ drop(tx);+ assert_eq!(tmp_files(&env), 0);++ // A text file with an unusual extension still goes through+ let (s, a) = upload(&env, "App.vue", b"<template><div>hello</div></template>\n".to_vec()).await;+ assert_eq!((s, a["mime"].as_str()), (StatusCode::CREATED, Some("text/plain")));+ let (s, _) = upload(&env, "server.key", b"-----BEGIN PRIVATE KEY-----\nMIIB\n".to_vec()).await;+ assert_eq!(s, StatusCode::CREATED);+}++#[tokio::test]+async fn agents_share_videos_and_see_them_as_frames() {+ let env = setup().await;+ let ws = env.tmp.path().join("team-ws");+ std::fs::create_dir_all(&ws).unwrap();+ std::fs::write(ws.join("demo.mp4"), MP4).unwrap();+ std::fs::write(ws.join("big.mp4"), fake_mp4(100 * 1024 * 1024 + 1)).unwrap();+ std::fs::write(ws.join("big.bin.txt"), vec![b'a'; 20 * 1024 * 1024 + 1]).unwrap();+ direct_turn(&env, "tok-ws", &env.a, Some(ws.clone())).await;++ let r = self_call(&env, "tok-ws", "share_file", json!({"path": "demo.mp4", "name": "demo.mp4"})).await;+ assert_eq!(r["isError"], false, "{r}");+ let card = messages(&env, &env.a).await.into_iter().find(|m| m.text == "Shared a file: demo.mp4").unwrap();+ let meta: Value = serde_json::from_str(card.meta.as_deref().unwrap()).unwrap();+ assert_eq!(meta["attachments"][0]["mime"], "video/mp4");+ let id = meta["attachments"][0]["id"].as_str().unwrap().to_string();+ let (_, h, _) = fetch(&env, &format!("/api/attachments/{id}/content"), &[]).await;+ assert!(h["content-disposition"].to_str().unwrap().starts_with("inline;"));++ let r = self_call(&env, "tok-ws", "share_file", json!({"path": "big.mp4", "name": "big.mp4"})).await;+ assert_eq!((r["isError"].as_bool(), text_of(&r).as_str()), (Some(true), "The video is larger than 100 MB."));+ let r = self_call(&env, "tok-ws", "share_file", json!({"path": "big.bin.txt", "name": "big.txt"})).await;+ assert_eq!((r["isError"].as_bool(), text_of(&r).as_str()), (Some(true), "The file is larger than 20 MB (videos up to 100 MB)."));++ let r = self_call(&env, "tok-ws", "read_attachment", json!({"id": id})).await;+ if kwnt::server::video::tools().is_none() {+ eprintln!("no ffmpeg here: checking the no-ffmpeg answer only");+ assert_eq!(r["isError"], false);+ assert!(text_of(&r).ends_with(kwnt::server::video::NO_FFMPEG), "{r}");+ return;+ }+ assert_eq!(r["isError"], false, "{r}");+ let blocks = r["content"].as_array().unwrap();+ let head = blocks[0]["text"].as_str().unwrap();+ assert!(head.starts_with("--- demo.mp4 (video/mp4, 23 KB) ---\nDuration 0:03.0 · 320×240 · h264 · 15 fps · audio aac"), "{head}");+ assert!(head.ends_with("3 frames, evenly spaced:"), "{head}");+ let images: Vec<&Value> = blocks.iter().filter(|b| b["type"] == "image").collect();+ assert_eq!(images.len(), 3);+ assert_eq!(blocks[1]["text"], "frame 1 at 0:00.5");+ use base64::Engine;+ for img in images {+ assert_eq!(img["mimeType"], "image/jpeg");+ let jpg = base64::engine::general_purpose::STANDARD.decode(img["data"].as_str().unwrap()).unwrap();+ assert!(jpg.starts_with(&[0xFF, 0xD8, 0xFF]) && jpg.len() < 5 * 1024 * 1024);+ }+ let left: Vec<_> = std::fs::read_dir(env.tmp.path().join("data/attachments/tmp")).unwrap().flatten().collect();+ assert!(left.is_empty(), "frame temp dirs are removed: {left:?}");+}++/// A cut-off file that still starts like an mp4 is stored (the bytes say video), but ffmpeg+/// can't read it: the bot is told so instead of getting nothing.+#[tokio::test]+async fn a_damaged_video_reads_as_a_clear_error() {+ if kwnt::server::video::tools().is_none() {+ eprintln!("no ffmpeg here: skipped");+ return;+ }+ let env = setup().await;+ let ws = env.tmp.path().join("ws");+ std::fs::create_dir_all(&ws).unwrap();+ std::fs::write(ws.join("cut.mp4"), fake_mp4(4096)).unwrap();+ direct_turn(&env, "tok", &env.a, Some(ws)).await;+ let r = self_call(&env, "tok", "share_file", json!({"path": "cut.mp4", "name": "cut.mp4"})).await;+ assert_eq!(r["isError"], false, "{r}");+ let card = messages(&env, &env.a).await.into_iter().find(|m| m.text == "Shared a file: cut.mp4").unwrap();+ let id = serde_json::from_str::<Value>(card.meta.as_deref().unwrap()).unwrap()["attachments"][0]["id"].as_str().unwrap().to_string();+ let r = self_call(&env, "tok", "read_attachment", json!({"id": id})).await;+ assert_eq!(r["isError"], true);+ assert_eq!(text_of(&r), "Couldn't look inside cut.mp4 (video/mp4, 4 KB): ffmpeg can't read it (it may be cut off or damaged).");+}