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
Space documents: add, remove and open a page at the quote (10c part 2, stacked on #601) (#614)
Oleksandr Ivanchenkoe64605e21a9d
diff --git a/src/sandbox/cite.rs b/src/sandbox/cite.rsindex ef8438a0..6dd475c8 100644--- a/src/sandbox/cite.rs+++ b/src/sandbox/cite.rs@@ -315,6 +315,56 @@ fn joined(text: &str) -> Vec<char> {page_lines(text).join("\n").chars().collect()}+/// [`joined`] with, for each of its characters, the byte offset in `text` it came from (a joined+/// space or line break points at the next word's first character).+fn joined_with_offsets(text: &str) -> (Vec<char>, Vec<usize>) {+ let (mut chars, mut at) = (Vec::new(), Vec::new());+ let mut start = 0;+ for line in text.split('\n') {+ let base = start;+ start += line.len() + 1;+ let (mut gap, mut any) = (false, false);+ for (i, c) in line.char_indices() {+ if c.is_whitespace() {+ gap = any;+ continue;+ }+ if !any && !chars.is_empty() {+ chars.push('\n');+ at.push(base + i);+ } else if gap {+ chars.push(' ');+ at.push(base + i);+ }+ chars.push(c);+ at.push(base + i);+ (gap, any) = (false, true);+ }+ }+ (chars, at)+}++/// Where `quote` is in `text` when [`cite_text`] would cite it from there (word for word, once,+/// in whole words), as a byte range of `text` itself, so a viewer can highlight the very words a+/// cited link points at without matching them again. `None` when it would refuse.+pub fn locate(text: &str, quote: &str) -> Option<std::ops::Range<usize>> {+ let q = normalize(quote);+ if q.is_empty() {+ return None;+ }+ let pat: Vec<char> = q.chars().collect();+ let (hay, at) = joined_with_offsets(text);+ let [p] = all_matches(&hay, &pat)[..] else {+ return None;+ };+ let e = p + pat.len();+ if mid_word(&hay, p) || mid_word(&hay, e) {+ return None;+ }+ let last = at[e - 1];+ Some(at[p]..last + text[last..].chars().next()?.len_utf8())+}+/// Every place `pat` is in `hay`, as start positions.fn all_matches(hay: &[char], pat: &[char]) -> Vec<usize> {(0..hay.len()).filter(|&p| match_at(hay, p, pat).is_some()).collect()@@ -562,6 +612,29 @@ mod tests {assert!(cite_text(&page("Send your résumé"), "your resume").unwrap_err().contains("accents (\"your résumé\")"));}+ #[test]+ fn locate_finds_the_very_words_cite_ticks_in_the_original_text() {+ let text = "# Returns\r\n\n You can return any item\nwithin 30 days. Café closes at 5.\n";+ // Runs of spaces and a line break inside the quote: the range covers the page's own text+ let r = locate(text, "return any item within 30 days").unwrap();+ assert_eq!(&text[r], "return any item\nwithin 30 days");+ let r = locate(text, "Café closes").unwrap();+ assert_eq!(&text[r], "Café closes");+ assert_eq!(&text[locate(text, "Returns").unwrap()], "Returns");+ // Whatever cite_text refuses, locate doesn't place: not there, twice, mid-word, other case, empty+ let twice = "Open daily. Open daily.";+ for (t, q) in [(text, "return any item within 60 days"), (twice, "Open daily."), (text, "eturn any"), (text, "café"), (text, " ")] {+ assert_eq!(locate(t, q), None, "{q:?}");+ assert!(cite_text(&page(t), q).is_err(), "{q:?}");+ }+ // And whatever it cites, locate places, at the same words+ for q in ["You can return", "30 days. Café", "closes at 5."] {+ let c = cite_text(&page(text), q).unwrap();+ let r = locate(text, q).unwrap();+ assert_eq!(normalize(&text[r]), c.quote, "{q:?}");+ }+ }+#[test]fn block_ids_carry_a_32_bit_hash() {let b = blocks("Body text here.");diff --git a/src/server/attachments.rs b/src/server/attachments.rsindex 3b02c2f6..fb648fc9 100644--- a/src/server/attachments.rs+++ b/src/server/attachments.rs@@ -437,7 +437,7 @@ pub struct UploadQuery {/// 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) {+pub(super) 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;diff --git a/src/server/auth.rs b/src/server/auth.rsindex 82b2c503..1cbebe0f 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -411,6 +411,11 @@ pub fn person_only(method: &Method, path: &str) -> bool {// Dev mode (0.7): the watched repo, its cards, Fix it and Dismiss, release notes and the// backup command are the person's; bots never read the desk either (D3)["", "api", "spaces", _, "dev_mode" | "dev", ..] => true,+ // A space's documents are what its bots quote as fact (10c): only the person adds or+ // removes them, so a bot can't write the words it then cites; the list, cite and page+ // reads stay open+ ["", "api", "spaces", _, "docs"] => *method == Method::POST,+ ["", "api", "spaces", _, "docs", _] => *method == Method::DELETE,["", "api", "dev", ..] => true,["", "api", "spaces" | "kwants", _, "approvals"] => *method != Method::GET && *method != Method::HEAD,// A team's instructions go into every member's prompt (PUT and PATCH both set them), and a@@ -933,6 +938,12 @@ mod tests {let (get, post, put, del) = (Method::GET, Method::POST, Method::PUT, Method::DELETE);assert!(person_only(&get, "/api/sandbox/t1/passwords"));assert!(person_only(&get, "/api/tool-notes"));+ assert!(person_only(&post, "/api/spaces/s1/docs"));+ assert!(person_only(&post, "/api/spaces/s1/docs/"));+ assert!(person_only(&del, "/api/spaces/s1/docs/faq.md"));+ assert!(!person_only(&get, "/api/spaces/s1/docs"));+ assert!(!person_only(&post, "/api/spaces/s1/docs/cite"));+ assert!(!person_only(&get, "/api/spaces/s1/docs/page"));assert!(person_only(&post, "/api/tool-notes"));assert!(person_only(&Method::PATCH, "/api/tool-notes/n1"));assert!(person_only(&del, "/api/tool-notes/n1/"));diff --git a/src/server/mod.rs b/src/server/mod.rsindex 88575305..00f01115 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -311,8 +311,10 @@ pub fn create_router(state: AppState) -> Router {.route("/api/approvals/:id/resolve", post(routes::resolve_approval)).route("/api/approvals/:id/retry", post(routes::retry_expired_approval)).route("/api/spaces/:id/approvals", get(approval_modes::get_space).put(approval_modes::put_space))- .route("/api/spaces/:id/docs", get(space_docs::list))+ .route("/api/spaces/:id/docs", get(space_docs::list).post(space_docs::upload)).route("/api/spaces/:id/docs/cite", post(space_docs::cite))+ .route("/api/spaces/:id/docs/page", get(space_docs::page))+ .route("/api/spaces/:id/docs/:name", delete(space_docs::remove)).route("/api/spaces/:id/dev_mode", get(dev::routes::get_mode).put(dev::routes::put_mode)).route("/api/spaces/:id/dev_mode/check", post(dev::routes::check)).route("/api/spaces/:id/dev_mode/seen", post(dev::routes::desk_seen))diff --git a/src/server/routes.rs b/src/server/routes.rsindex c59359bb..e734ba9c 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -3195,7 +3195,8 @@ async fn run_kwant_turn_inner(}// 10c: a space with its own documents tells the bot how to quote them with the word-for-word// check (the web cite call lives in the browser block, which doesn't know the space)- if !opts.no_tools && !opts.fresh_eyes {+ // (QA F1: chat, routine and hand-off turns only, the allow-list tool notes use)+ if !opts.no_tools && !opts.fresh_eyes && super::tool_notes::wants(opts.purpose.as_deref()) {let space = crate::db::spaces::SpaceId::new(&target_kwant.space_id);lessons.push_str(&super::space_docs::prompt_block(state, &space).await);}diff --git a/src/server/space_docs.rs b/src/server/space_docs.rsindex d62e9a15..e12c72f1 100644--- a/src/server/space_docs.rs+++ b/src/server/space_docs.rs@@ -6,13 +6,19 @@//! - `POST /api/spaces/:id/docs/cite` `{file, quote}`: the quote checked against that file, one//! [`FrameText`] per PDF page (`kwant-doc://<space>/<file>#page=N`), answered as the web cite//! answers (`{quote, url, link}`) or refused with cite.rs's own reason (422).+//! - `GET /api/spaces/:id/docs/page?file=&page="e=`: one page's text for the viewer, split+//! around the quote where cite would tick it ([`page_view`]).+//! - `POST /api/spaces/:id/docs?name=&replace=1` (the file as the raw body) and+//! `DELETE /api/spaces/:id/docs/:name`: the person adds and removes documents. Both are+//! person-only (`auth::person_only`): a bot must never write the words it then quotes.//!//! The folder is `<space's data folder>/docs` ([`docs_dir`]): one per space, outside every bot's//! work folder, so a bot working in its folder can't write the words it then cites. Only the//! folder's own files are read (no subfolders), each opened from the folder's descriptor without//! following a link ([`safe_fs::Dir`]); a `docs` that is itself a link is refused. Text, Markdown//! and PDF (its text layer, the reader attachments use: no OCR, no model call), 2 MB a file, 200-//! files a space. Nothing here writes.+//! files a space. Only [`upload`] and [`remove`] write: one at a time, a new file through a hidden+//! temporary file in the folder and a rename, so a reader never sees half a document.#![allow(clippy::result_large_err)]use super::AppState;@@ -20,14 +26,19 @@ use crate::db::spaces::SpaceId;use crate::sandbox::cite::{self, FrameText};use crate::sandbox::safe_fs::{self, Dir, Kind};use axum::{- extract::{Path, State},- http::StatusCode,+ body::Body,+ extract::{Path, Query, State},+ http::{header, HeaderMap, StatusCode},response::{IntoResponse, Response},Json,};+use futures::StreamExt;use serde::{Deserialize, Serialize};use serde_json::json;+use std::collections::HashMap;use std::path::PathBuf;+use std::sync::{Mutex, OnceLock};+use std::time::SystemTime;/// The largest document kwant reads.pub const MAX_FILE_BYTES: u64 = 2 * 1024 * 1024;@@ -39,11 +50,24 @@ const MAX_SCAN: usize = 2_000;const PAGE_COUNT_SECS: u64 = 5;/// The kinds of file read, by extension (any case).const KINDS: [&str; 4] = ["md", "markdown", "txt", "pdf"];+/// A new document's name is at most this many bytes (file systems stop at 255).+const MAX_NAME_BYTES: usize = 200;+/// Characters of page text the viewer gets on each side of the quote (or after the page start).+pub const PAGE_SIDE_CHARS: usize = 20_000;fn error(status: StatusCode, message: impl Into<String>) -> Response {(status, Json(json!({ "error": message.into() }))).into_response()}+/// A refusal with a `code` the UI can tell apart: `{error, code}`.+fn refuse(status: StatusCode, code: &str, message: impl Into<String>) -> Response {+ (status, Json(json!({ "error": message.into(), "code": code }))).into_response()+}++fn docs_link() -> Response {+ refuse(StatusCode::CONFLICT, "docs_link", "the space's docs isn't a plain folder (a link or a file); kwant only reads and writes a real docs folder")+}+/// Where a space's documents live: `docs` in the space's own data folder (the data folder itself/// for Default).pub fn docs_dir(data_dir: &std::path::Path, space: &SpaceId) -> PathBuf {@@ -53,12 +77,31 @@ pub fn docs_dir(data_dir: &std::path::Path, space: &SpaceId) -> PathBuf {/// Why `name` can't name a document: it must be a plain file name in the folder (no separator,/// no `..`, no leading dot) of a kind kwant reads.pub fn bad_name(name: &str) -> Option<&'static str> {+ plain_name_problem(name).or_else(|| kind_of(name).is_none().then_some(WRONG_KIND))+}++const WRONG_KIND: &str = "only .md, .markdown, .txt and .pdf documents can be read";++/// Why `name` isn't a plain file name in the folder (any kind).+fn plain_name_problem(name: &str) -> Option<&'static str> {if name.trim().is_empty() {Some("file is required: a document's name, as the list gives it")} else if name.contains(['/', '\\', '\0']) || name.contains("..") || name.starts_with('.') || name != name.trim() {Some("file must be a document's own name in the space's docs folder (no folders, no ..)")+ } else {+ None+ }+}++/// Why a new document can't be called `name`: 400 `bad_name` (not a plain one-line name, or too+/// long), 415 `wrong_kind` (a kind kwant doesn't read).+pub fn upload_name_problem(name: &str) -> Option<(StatusCode, &'static str, &'static str)> {+ if let Some(why) = plain_name_problem(name) {+ Some((StatusCode::BAD_REQUEST, "bad_name", why))+ } else if name.len() > MAX_NAME_BYTES || name.chars().any(char::is_control) {+ Some((StatusCode::BAD_REQUEST, "bad_name", "a document's name is one line of at most 200 bytes"))} else if kind_of(name).is_none() {- Some("only .md, .markdown, .txt and .pdf documents can be read")+ Some((StatusCode::UNSUPPORTED_MEDIA_TYPE, "wrong_kind", WRONG_KIND))} else {None}@@ -165,6 +208,57 @@ async fn pdf_page_count(bytes: Vec<u8>) -> Option<usize> {tokio::time::timeout(std::time::Duration::from_secs(PAGE_COUNT_SECS), job).await.ok()?.ok()?}+/// Page counts already read, by (folder, name, size, modified) (QA F4): a list the UI asks for+/// again parses only the PDFs that changed. Cleared when it passes a few spaces' worth.+type PageKey = (PathBuf, String, u64, SystemTime);+fn page_counts() -> &'static Mutex<HashMap<PageKey, usize>> {+ static COUNTS: OnceLock<Mutex<HashMap<PageKey, usize>>> = OnceLock::new();+ COUNTS.get_or_init(Default::default)+}+const PAGE_COUNTS_KEPT: usize = 4 * MAX_FILES;++/// One listed document, opened again from the folder's descriptor: `None` when it is gone or+/// was swapped for a link since the folder was listed.+async fn doc_info(dir: &std::path::Path, docs: &Dir, name: String, len: u64) -> Option<DocInfo> {+ let file = docs.open_file(std::path::Path::new(&name)).ok()?;+ let meta = file.metadata().ok();+ let size = meta.as_ref().map_or(len, |m| m.len());+ let mtime = meta.and_then(|m| m.modified().ok());+ let modified = mtime.map(|t| chrono::DateTime::<chrono::Utc>::from(t).to_rfc3339());+ let too_large = size > MAX_FILE_BYTES;+ let pages = if is_pdf(&name) && !too_large {+ let key = mtime.map(|t| (dir.to_path_buf(), name.clone(), size, t));+ let known = key+ .as_ref()+ .and_then(|k| page_counts().lock().ok()?.get(k).copied());+ match known {+ Some(n) => Some(n),+ None => {+ let n = match safe_fs::read_capped(file, MAX_FILE_BYTES) {+ Ok(bytes) => pdf_page_count(bytes).await,+ Err(_) => None,+ };+ if let (Some(n), Some(k), Ok(mut m)) = (n, key, page_counts().lock()) {+ if m.len() >= PAGE_COUNTS_KEPT {+ m.clear();+ }+ m.insert(k, n);+ }+ n+ }+ }+ } else {+ None+ };+ Some(DocInfo {+ name,+ size,+ modified,+ pages,+ too_large,+ })+}+/// The space's documents, sorted by name, at most [`MAX_FILES`]; the flag says some were left out./// Links, folders and other kinds of file are skipped.pub async fn list_docs(dir: &std::path::Path) -> Result<(Vec<DocInfo>, bool), Response> {@@ -174,20 +268,7 @@ pub async fn list_docs(dir: &std::path::Path) -> Result<(Vec<DocInfo>, bool), Relet (names, more) = doc_names(&docs)?;let mut out = Vec::with_capacity(names.len());for (name, len) in names {- // Opened again from the folder's descriptor: a file swapped for a link since the list is left out- let Ok(file) = docs.open_file(std::path::Path::new(&name)) else { continue };- let meta = file.metadata().ok();- let size = meta.as_ref().map_or(len, |m| m.len());- let modified = meta.and_then(|m| m.modified().ok()).map(|t| chrono::DateTime::<chrono::Utc>::from(t).to_rfc3339());- let too_large = size > MAX_FILE_BYTES;- let pages = match (is_pdf(&name), too_large) {- (true, false) => match safe_fs::read_capped(file, MAX_FILE_BYTES) {- Ok(bytes) => pdf_page_count(bytes).await,- Err(_) => None,- },- _ => None,- };- out.push(DocInfo { name, size, modified, pages, too_large });+ out.extend(doc_info(dir, &docs, name, len).await);}Ok((out, more))}@@ -271,6 +352,377 @@ pub async fn cite(State(state): State<AppState>, Path(id): Path<String>, Json(bo}}+// ── Adding, removing and viewing (the person's Documents tab) ──────────────────────────++/// Writes to docs folders one at a time, so "already there", the 200 limit and the rename are+/// checked together and two uploads of one name can't both win.+fn writes() -> &'static tokio::sync::Mutex<()> {+ static WRITES: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();+ WRITES.get_or_init(Default::default)+}++/// The docs folder to write in, made (with the space's folder) when missing; never through a link.+fn docs_for_write(data_dir: &std::path::Path, space: &SpaceId) -> Result<Dir, Response> {+ let dir = docs_dir(data_dir, space);+ match open_docs(&dir) {+ Ok(Some(d)) => return Ok(d),+ Ok(None) => {}+ Err(r) if r.status() == StatusCode::CONFLICT => return Err(docs_link()),+ Err(r) => return Err(r),+ }+ let made = dir+ .strip_prefix(data_dir)+ .ok()+ .and_then(|rel| Dir::open(data_dir).ok()?.make_dirs(rel).ok());+ made.ok_or_else(|| {+ error(+ StatusCode::INTERNAL_SERVER_ERROR,+ "couldn't make the space's docs folder",+ )+ })+}++/// What the folder already has under a name.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Existing {+ Nothing,+ File,+ /// A link, a folder or anything else that isn't a regular file+ Other,+}++fn existing(docs: &Dir, name: &str) -> Existing {+ match docs.open_file(std::path::Path::new(name)) {+ Ok(_) => Existing::File,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Existing::Nothing,+ Err(_) => Existing::Other,+ }+}++/// Writes `bytes` as `name`: into a new hidden file in the same folder (`.upload-<id>.part`, never+/// listed), then renamed over `name`, so a reader sees the old document or the whole new one. A+/// link at `name` is replaced, never written through.+fn write_doc(docs: &Dir, name: &str, bytes: &[u8]) -> std::io::Result<()> {+ let tmp = format!(".upload-{}.part", uuid::Uuid::new_v4().simple());+ docs.replace_file(std::ffi::OsStr::new(name), &tmp, &mut &bytes[..], 0o644)+}++/// Refuses bytes kwant couldn't read back as a document of `name`'s kind: text must be UTF-8, and+/// a PDF must have a text layer (the same reader as cite, so what is added can be quoted).+async fn check_content(name: &str, bytes: &[u8]) -> Result<(), Response> {+ if is_pdf(name) {+ let pages = super::attachments::pdf_pages(bytes.to_vec())+ .await+ .map_err(|why| {+ refuse(+ StatusCode::UNPROCESSABLE_ENTITY,+ "unreadable",+ format!("Couldn't read {name}: {why}."),+ )+ })?;+ if pages.iter().all(|p| p.trim().is_empty()) {+ return Err(refuse(+ StatusCode::UNPROCESSABLE_ENTITY,+ "no_text",+ format!("PDF has no text layer: {name} looks like scanned pages, so there are no words a bot could quote. kwant doesn't read pictures of text."),+ ));+ }+ } else if std::str::from_utf8(bytes).is_err() {+ return Err(refuse(+ StatusCode::UNPROCESSABLE_ENTITY,+ "unreadable",+ format!("{name} isn't UTF-8 text"),+ ));+ }+ Ok(())+}++fn too_large() -> Response {+ refuse(+ StatusCode::PAYLOAD_TOO_LARGE,+ "too_large",+ "kwant reads documents up to 2 MB",+ )+}++/// The request body, refused (413) past [`MAX_FILE_BYTES`]: by its declared length before any+/// byte, else at the byte that passes it. The rest of a refused body is drained in the background.+async fn read_body(headers: &HeaderMap, body: Body) -> Result<Vec<u8>, Response> {+ let mut stream = body.into_data_stream();+ 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_FILE_BYTES) {+ super::attachments::drain(stream);+ return Err(too_large());+ }+ let mut out = Vec::new();+ while let Some(chunk) = stream.next().await {+ let Ok(chunk) = chunk else {+ return Err(refuse(+ StatusCode::BAD_REQUEST,+ "interrupted",+ "The upload was interrupted.",+ ));+ };+ if (out.len() + chunk.len()) as u64 > MAX_FILE_BYTES {+ super::attachments::drain(stream);+ return Err(too_large());+ }+ out.extend_from_slice(&chunk);+ }+ Ok(out)+}++fn yes(v: Option<&str>) -> bool {+ matches!(v.map(str::trim), Some("1" | "true" | "yes"))+}++#[derive(Debug, Default, Deserialize)]+pub struct UploadQuery {+ #[serde(default)]+ pub name: String,+ pub replace: Option<String>,+}++/// `POST /api/spaces/:id/docs?name=<file name>[&replace=1]` with the file as the raw body (as+/// `/api/attachments` takes it): 201 with its list entry. 400 `bad_name`, 415 `wrong_kind`, 413+/// `too_large`, 409 `exists` (without `replace=1`), `docs_link` or `full` (200 documents), 422+/// `no_text` (a PDF without a text layer) or `unreadable`. Person-only (`auth::person_only`).+pub async fn upload(+ State(state): State<AppState>,+ Path(id): Path<String>,+ Query(q): Query<UploadQuery>,+ headers: HeaderMap,+ body: Body,+) -> Response {+ let space = match super::spaces::active_space(&state, &id).await {+ Ok(s) => s,+ Err(r) => {+ super::attachments::drain(body.into_data_stream());+ return r;+ }+ };+ let name = q.name.as_str();+ if let Some((status, code, why)) = upload_name_problem(name) {+ super::attachments::drain(body.into_data_stream());+ return refuse(status, code, why);+ }+ let bytes = match read_body(&headers, body).await {+ Ok(b) => b,+ Err(r) => return r,+ };+ if let Err(r) = check_content(name, &bytes).await {+ return r;+ }+ let _one = writes().lock().await;+ let dir = docs_dir(&state.config.data_dir, &space);+ let docs = match docs_for_write(&state.config.data_dir, &space) {+ Ok(d) => d,+ Err(r) => return r,+ };+ let there = existing(&docs, name);+ if there != Existing::Nothing && !yes(q.replace.as_deref()) {+ return refuse(+ StatusCode::CONFLICT,+ "exists",+ format!("{name} is already in this space's documents; add it with replace to swap it"),+ );+ }+ if there == Existing::Nothing {+ let (names, more) = match doc_names(&docs) {+ Ok(n) => n,+ Err(r) => return r,+ };+ if more || names.len() >= MAX_FILES {+ return refuse(+ StatusCode::CONFLICT,+ "full",+ "this space has 200 documents, the most kwant reads; remove one first",+ );+ }+ }+ if let Err(e) = write_doc(&docs, name, &bytes) {+ tracing::warn!(error = %e, "space document not written");+ return match there {+ Existing::Other => refuse(StatusCode::CONFLICT, "exists", format!("{name} is a folder or something else that isn't a document; kwant won't replace it")),+ _ => error(StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't write {name}")),+ };+ }+ tracing::info!(space = %space.as_str(), size = bytes.len(), replaced = there != Existing::Nothing, "space document added");+ match doc_info(&dir, &docs, name.to_string(), bytes.len() as u64).await {+ Some(info) => (StatusCode::CREATED, Json(info)).into_response(),+ None => error(+ StatusCode::INTERNAL_SERVER_ERROR,+ format!("{name} was written but couldn't be read back"),+ ),+ }+}++/// `DELETE /api/spaces/:id/docs/:name`: 204, 404 `not_found`, 400 `bad_name` (not a document's+/// own name, or not a plain file there: a link is left alone), 409 `docs_link`. Person-only.+pub async fn remove(+ State(state): State<AppState>,+ Path((id, name)): Path<(String, String)>,+) -> Response {+ let space = match super::spaces::active_space(&state, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ if let Some(why) = bad_name(&name) {+ return refuse(StatusCode::BAD_REQUEST, "bad_name", why);+ }+ let _one = writes().lock().await;+ let docs = match open_docs(&docs_dir(&state.config.data_dir, &space)) {+ Ok(Some(d)) => d,+ Ok(None) => {+ return refuse(+ StatusCode::NOT_FOUND,+ "not_found",+ format!("no document named {name} in this space"),+ )+ }+ Err(r) if r.status() == StatusCode::CONFLICT => return docs_link(),+ Err(r) => return r,+ };+ match existing(&docs, &name) {+ Existing::Nothing => refuse(+ StatusCode::NOT_FOUND,+ "not_found",+ format!("no document named {name} in this space"),+ ),+ Existing::Other => refuse(+ StatusCode::BAD_REQUEST,+ "bad_name",+ format!("{name} isn't a plain file in the space's docs folder"),+ ),+ Existing::File => match docs.remove_file(std::ffi::OsStr::new(&name)) {+ Ok(()) => {+ tracing::info!(space = %space.as_str(), "space document removed");+ StatusCode::NO_CONTENT.into_response()+ }+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => refuse(+ StatusCode::NOT_FOUND,+ "not_found",+ format!("no document named {name} in this space"),+ ),+ Err(_) => error(+ StatusCode::INTERNAL_SERVER_ERROR,+ format!("couldn't remove {name}"),+ ),+ },+ }+}++/// One page of a document for the viewer, split around the quote.+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]+pub struct PageView {+ pub file: String,+ pub page: usize,+ pub pages: usize,+ pub text_before: String,+ #[serde(rename = "match")]+ pub matched: String,+ pub text_after: String,+ pub cut_before: bool,+ pub cut_after: bool,+}++/// The last `n` characters of `s`, and whether some were cut.+fn keep_last(s: &str, n: usize) -> (String, bool) {+ match s.char_indices().rev().nth(n.saturating_sub(1)) {+ Some((i, _)) if n > 0 && i > 0 => (s[i..].to_string(), true),+ _ if n == 0 => (String::new(), !s.is_empty()),+ _ => (s.to_string(), false),+ }+}++/// The first `n` characters of `s`, and whether some were cut.+fn keep_first(s: &str, n: usize) -> (String, bool) {+ match s.char_indices().nth(n) {+ Some((i, _)) => (s[..i].to_string(), true),+ None => (s.to_string(), false),+ }+}++/// Page `page` (from 1) of a document read as `pages`: `None` when there is no such page. With a+/// quote that cite would tick on this very page (word for word, once in the document, whole+/// words: [`cite::cite_text`], then [`cite::locate`] for where), the text is split around it;+/// otherwise `matched` is empty and `text_after` is the page. Each side keeps at most+/// [`PAGE_SIDE_CHARS`] characters, nearest the match.+pub fn page_view(+ space: &SpaceId,+ file: &str,+ pages: &[String],+ page: usize,+ quote: &str,+) -> Option<PageView> {+ let text = pages.get(page.checked_sub(1)?)?;+ let here = doc_url(space, file, is_pdf(file).then_some(page));+ let hit = if quote.trim().is_empty() {+ None+ } else {+ cite::cite_text(&frames(space, file, pages), quote)+ .ok()+ .filter(|c| c.url == here)+ .and_then(|_| cite::locate(text, quote))+ };+ let (before, matched, after) = match hit {+ Some(r) => (&text[..r.start], &text[r.clone()], &text[r.end..]),+ None => ("", "", text.as_str()),+ };+ let (text_before, cut_before) = keep_last(before, PAGE_SIDE_CHARS);+ let (text_after, cut_after) = keep_first(after, PAGE_SIDE_CHARS);+ Some(PageView {+ file: file.to_string(),+ page,+ pages: pages.len(),+ text_before,+ matched: matched.to_string(),+ text_after,+ cut_before,+ cut_after,+ })+}++#[derive(Debug, Default, Deserialize)]+pub struct PageQuery {+ #[serde(default)]+ pub file: String,+ pub page: Option<usize>,+ #[serde(default)]+ pub quote: String,+}++/// `GET /api/spaces/:id/docs/page?file=&page="e=`: [`PageView`] (page 1 by default). Errors+/// as cite's: 400 bad name, 404 no such file (or page), 409 docs is a link, 413, 422. Open to+/// bots like the list and cite: it only reads.+pub async fn page(+ State(state): State<AppState>,+ Path(id): Path<String>,+ Query(q): Query<PageQuery>,+) -> Response {+ let space = match super::spaces::active_space(&state, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ let file = q.file.trim();+ let pages = match read_doc(&docs_dir(&state.config.data_dir, &space), file).await {+ Ok(p) => p,+ Err(r) => return r,+ };+ let n = q.page.unwrap_or(1);+ match page_view(&space, file, &pages, n, &q.quote) {+ Some(v) => Json(v).into_response(),+ None => refuse(+ StatusCode::NOT_FOUND,+ "no_page",+ format!("{file} has no page {n} (it has {})", pages.len()),+ ),+ }+}+/// The lines a bot's turn gets when its space has documents: where they are listed and the call/// that cites one. Empty when the space has none, so other turns' prompts don't change.pub async fn prompt_block(state: &AppState, space: &SpaceId) -> String {@@ -453,4 +905,411 @@ mod tests {assert!(p.contains("'http://127.0.0.1:8787/api/spaces/shop/docs/cite'"), "{p}");assert!(p.contains("never from memory"), "{p}");}++ #[test]+ fn new_names_are_plain_one_line_names_of_a_kind_kwant_reads() {+ let long = format!("{}.md", "a".repeat(MAX_NAME_BYTES));+ for (name, want) in [+ ("faq.md", None),+ ("Returns Policy.PDF", None),+ ("../secret.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),+ ("sub/faq.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),+ ("sub\\faq.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),+ (".hidden.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),+ ("..", Some((StatusCode::BAD_REQUEST, "bad_name"))),+ ("", Some((StatusCode::BAD_REQUEST, "bad_name"))),+ ("faq.md ", Some((StatusCode::BAD_REQUEST, "bad_name"))),+ ("a\nb.md", Some((StatusCode::BAD_REQUEST, "bad_name"))),+ (long.as_str(), Some((StatusCode::BAD_REQUEST, "bad_name"))),+ ("photo.png", Some((StatusCode::UNSUPPORTED_MEDIA_TYPE, "wrong_kind"))),+ ("faq", Some((StatusCode::UNSUPPORTED_MEDIA_TYPE, "wrong_kind"))),+ ] {+ assert_eq!(upload_name_problem(name).map(|(s, c, _)| (s, c)), want, "{name:?}");+ }+ }++ #[test]+ fn the_page_view_splits_around_a_ticked_quote_and_cuts_long_sides() {+ let s = space();+ let page = "Intro.\n\nYou can return any item within 30 days.\nShipping is free.".to_string();+ let v = page_view(&s, "faq.md", std::slice::from_ref(&page), 1, "return any item").unwrap();+ assert_eq!((v.text_before.as_str(), v.matched.as_str(), v.text_after.as_str()), ("Intro.\n\nYou can ", "return any item", " within 30 days.\nShipping is free."));+ assert_eq!((v.page, v.pages, v.cut_before, v.cut_after), (1, 1, false, false));+ // No quote, a quote not there, or one cite refuses: the whole page after, nothing matched+ for q in ["", "return any item within 60 days", "eturn"] {+ let v = page_view(&s, "faq.md", std::slice::from_ref(&page), 1, q).unwrap();+ assert_eq!((v.text_before.as_str(), v.matched.as_str(), v.text_after.as_str()), ("", "", page.as_str()), "{q:?}");+ }+ assert_eq!(page_view(&s, "faq.md", std::slice::from_ref(&page), 2, ""), None);+ assert_eq!(page_view(&s, "faq.md", std::slice::from_ref(&page), 0, ""), None);+ // A PDF: the quote is matched on its own page only+ let pdf = vec!["Page one words.".to_string(), "Budget is 42 euros.".to_string()];+ assert_eq!(page_view(&s, "p.pdf", &pdf, 2, "Budget is 42 euros").unwrap().matched, "Budget is 42 euros");+ assert_eq!(page_view(&s, "p.pdf", &pdf, 1, "Budget is 42 euros").unwrap().matched, "");+ // On two pages: cite refuses, so nothing is highlighted+ let twice = vec!["Open daily.".to_string(), "Open daily.".to_string()];+ assert_eq!(page_view(&s, "p.pdf", &twice, 1, "Open daily.").unwrap().matched, "");+ // Long sides keep the characters nearest the match (multi-byte text cut on a character)+ let long = format!("{} MARKER {}", "é".repeat(PAGE_SIDE_CHARS + 5), "ü".repeat(PAGE_SIDE_CHARS + 7));+ let v = page_view(&s, "big.txt", std::slice::from_ref(&long), 1, "MARKER").unwrap();+ assert_eq!((v.text_before.chars().count(), v.text_after.chars().count()), (PAGE_SIDE_CHARS, PAGE_SIDE_CHARS));+ assert_eq!((v.cut_before, v.matched.as_str(), v.cut_after), (true, "MARKER", true));+ let v = page_view(&s, "big.txt", std::slice::from_ref(&long), 1, "").unwrap();+ assert_eq!((v.text_before.as_str(), v.cut_before, v.text_after.chars().count(), v.cut_after), ("", false, PAGE_SIDE_CHARS, true));+ let exact = "x".repeat(PAGE_SIDE_CHARS);+ assert_eq!(keep_last(&exact, PAGE_SIDE_CHARS), (exact.clone(), false));+ assert_eq!(keep_first(&exact, PAGE_SIDE_CHARS), (exact.clone(), false));+ }++ #[test]+ fn a_write_goes_through_a_hidden_temporary_file_and_replaces_a_link_instead_of_following_it() {+ // `_tmp` keeps the folder alive; only the unix link check below reads it+ let (_tmp, dir) = docs_folder();+ let docs = Dir::open(&dir).unwrap();+ write_doc(&docs, "new.md", b"fresh words").unwrap();+ assert_eq!(std::fs::read(dir.join("new.md")).unwrap(), b"fresh words");+ write_doc(&docs, "new.md", b"second words").unwrap();+ assert_eq!(std::fs::read(dir.join("new.md")).unwrap(), b"second words");+ let left: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).filter(|n| n.starts_with('.')).collect();+ assert!(left.is_empty(), "{left:?}");+ // The temporary name is never listed or readable as a document+ assert!(bad_name(".upload-0123.part").is_some());+ #[cfg(unix)]+ {+ std::fs::write(_tmp.path().join("secret.md"), "outside").unwrap();+ std::os::unix::fs::symlink(_tmp.path().join("secret.md"), dir.join("link.md")).unwrap();+ assert_eq!(existing(&docs, "link.md"), Existing::Other);+ write_doc(&docs, "link.md", b"inside").unwrap();+ assert_eq!(std::fs::read_to_string(_tmp.path().join("secret.md")).unwrap(), "outside");+ assert!(std::fs::symlink_metadata(dir.join("link.md")).unwrap().file_type().is_file());+ }+ assert_eq!(existing(&docs, "faq.md"), Existing::File);+ assert_eq!(existing(&docs, "nope.md"), Existing::Nothing);+ }++ #[tokio::test]+ async fn the_list_reuses_page_counts_until_the_pdf_changes() {+ let (_tmp, dir) = docs_folder();+ let key_for = |dir: &std::path::Path| {+ let m = std::fs::metadata(dir.join("plan.pdf")).unwrap();+ (dir.to_path_buf(), "plan.pdf".to_string(), m.len(), m.modified().unwrap())+ };+ assert_eq!(list_docs(&dir).await.unwrap().0[1].pages, Some(2));+ let key = key_for(&dir);+ assert_eq!(page_counts().lock().unwrap().get(&key), Some(&2));+ // A cached count is answered without parsing (planted 7 is what comes back)+ page_counts().lock().unwrap().insert(key, 7);+ assert_eq!(list_docs(&dir).await.unwrap().0[1].pages, Some(7));+ // Changed bytes (a new size): parsed again+ let mut bytes = TWO_PAGES.to_vec();+ bytes.extend_from_slice(b"\n%padding\n");+ std::fs::write(dir.join("plan.pdf"), bytes).unwrap();+ assert_eq!(list_docs(&dir).await.unwrap().0[1].pages, Some(2));+ }++ /// A one-page PDF with no text on it (a scanned page has pictures, this one nothing).+ fn textless_pdf() -> Vec<u8> {+ let objs = [+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R >>",+ "<< /Length 0 >>\nstream\n\nendstream",+ ];+ let mut out = String::from("%PDF-1.4\n");+ let mut offsets = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offsets.push(out.len());+ out.push_str(&format!("{} 0 obj\n{o}\nendobj\n", i + 1));+ }+ let xref = out.len();+ out.push_str(&format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1));+ for o in offsets {+ out.push_str(&format!("{o:010} 00000 n \n"));+ }+ out.push_str(&format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1));+ out.into_bytes()+ }++ /// The routes as the server serves them: the router with its token and person-only checks.+ mod routes {+ use super::*;+ use axum::body::to_bytes;+ use axum::http::Request;+ use serde_json::Value;+ use tower::ServiceExt;++ struct Env {+ app: axum::Router,+ state: AppState,+ tmp: tempfile::TempDir,+ }++ async fn setup() -> Env {+ let tmp = tempfile::tempdir().unwrap();+ let db = crate::db::Database::init(tmp.path()).await.unwrap();+ let config = crate::config::Config { data_dir: tmp.path().to_path_buf(), ..Default::default() };+ let state = AppState::new(+ config.clone(),+ db,+ crate::tools::ToolRunner::new(tmp.path().join("workspace")),+ crate::broker::PermissionBroker::new(),+ crate::router::LayaRouter::new(config.laya_url.clone()),+ );+ Env { app: crate::server::create_router(state.clone()), state, tmp }+ }++ fn docs(e: &Env) -> PathBuf {+ docs_dir(e.tmp.path(), &SpaceId::default_space())+ }++ fn person(e: &Env) -> String {+ e.state.api_token.reveal().to_string()+ }++ /// A bot's turn token in #general of the default space.+ async fn bot_token(e: &Env) -> String {+ use crate::server::continuity::{SelfScope, TurnOrigin};+ let space = SpaceId::default_space();+ let new = crate::db::models::NewKwant {+ name: "Ana".into(),+ title: "Reporter".into(),+ persona_prompt: String::new(),+ soul: String::new(),+ avatar_sprite: "s".into(),+ driver_type: "cli".into(),+ preferred_model: "codex".into(),+ };+ let bot = e.state.db.create_kwant(&space, &new).await.unwrap();+ let general = e.state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap();+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ origin: Some(TurnOrigin { channel_id: Some(general.id.clone()), ..Default::default() }),+ turn_id: Some("t-docs".into()),+ ..Default::default()+ };+ crate::server::mcp_runtime::prepare_turn_with_self(&e.state, &bot, Some("t-docs".into()), None, Some(scope)).await.unwrap().1+ }++ async fn call(e: &Env, method: &str, uri: &str, bearer: &str, body: Vec<u8>) -> (StatusCode, Value) {+ let req = Request::builder()+ .method(method)+ .uri(uri)+ .header("authorization", format!("Bearer {bearer}"))+ .body(Body::from(body))+ .unwrap();+ let resp = e.app.clone().oneshot(req).await.unwrap();+ let status = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+ }++ const BASE: &str = "/api/spaces/spc_default/docs";++ async fn add(e: &Env, name: &str, bytes: &[u8]) -> (StatusCode, Value) {+ call(e, "POST", &format!("{BASE}?name={name}"), &person(e), bytes.to_vec()).await+ }++ #[tokio::test]+ async fn the_person_adds_a_document_and_it_is_listed_and_quotable() {+ let e = setup().await;+ assert!(!docs(&e).exists());+ let (s, v) = add(&e, "Returns%20Policy.md", b"You can return any item within 30 days.").await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ assert_eq!((v["name"].as_str(), v["size"].as_u64()), (Some("Returns Policy.md"), Some(39)));+ assert!(v["modified"].is_string() && v.get("pages").is_none(), "{v}");+ assert_eq!(std::fs::read(docs(&e).join("Returns Policy.md")).unwrap(), b"You can return any item within 30 days.");+ let (s, v) = add(&e, "plan.pdf", TWO_PAGES).await;+ assert_eq!((s, v["pages"].as_u64()), (StatusCode::CREATED, Some(2)), "{v}");+ let (_, list) = call(&e, "GET", BASE, &person(&e), Vec::new()).await;+ let names: Vec<&str> = list["docs"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap()).collect();+ assert_eq!(names, ["Returns Policy.md", "plan.pdf"]);+ // Nothing half-written left behind+ let hidden = std::fs::read_dir(docs(&e)).unwrap().filter(|d| d.as_ref().unwrap().file_name().to_string_lossy().starts_with('.')).count();+ assert_eq!(hidden, 0);+ }++ #[tokio::test]+ async fn each_refusal_has_its_status_and_code_and_writes_nothing() {+ let e = setup().await;+ add(&e, "faq.md", b"first").await;+ let big = vec![b'a'; MAX_FILE_BYTES as usize + 1];+ for (name, bytes, status, code) in [+ ("..%2Fescape.md", b"x".to_vec(), StatusCode::BAD_REQUEST, "bad_name"),+ ("sub%2Fescape.md", b"x".to_vec(), StatusCode::BAD_REQUEST, "bad_name"),+ ("%2Ehidden.md", b"x".to_vec(), StatusCode::BAD_REQUEST, "bad_name"),+ ("a%0Ab.md", b"x".to_vec(), StatusCode::BAD_REQUEST, "bad_name"),+ ("", b"x".to_vec(), StatusCode::BAD_REQUEST, "bad_name"),+ ("photo.png", b"x".to_vec(), StatusCode::UNSUPPORTED_MEDIA_TYPE, "wrong_kind"),+ ("readme", b"x".to_vec(), StatusCode::UNSUPPORTED_MEDIA_TYPE, "wrong_kind"),+ ("big.txt", big, StatusCode::PAYLOAD_TOO_LARGE, "too_large"),+ ("faq.md", b"second".to_vec(), StatusCode::CONFLICT, "exists"),+ ("scan.pdf", textless_pdf(), StatusCode::UNPROCESSABLE_ENTITY, "no_text"),+ ("broken.pdf", b"%PDF-1.7\nnot really".to_vec(), StatusCode::UNPROCESSABLE_ENTITY, "unreadable"),+ ("latin1.txt", vec![b'c', b'a', b'f', 0xE9], StatusCode::UNPROCESSABLE_ENTITY, "unreadable"),+ ] {+ let (s, v) = add(&e, name, &bytes).await;+ assert_eq!((s, v["code"].as_str()), (status, Some(code)), "{name}: {v}");+ }+ let (s, v) = add(&e, "scan.pdf", &textless_pdf()).await;+ assert!(v["error"].as_str().unwrap().starts_with("PDF has no text layer"), "{s} {v}");+ assert!(!e.tmp.path().join("escape.md").exists());+ assert_eq!(std::fs::read(docs(&e).join("faq.md")).unwrap(), b"first");+ let mut left: Vec<String> = std::fs::read_dir(docs(&e)).unwrap().map(|d| d.unwrap().file_name().into_string().unwrap()).collect();+ left.sort();+ assert_eq!(left, ["faq.md"]);+ // A declared length over 2 MB is refused before the body is read+ let req = Request::builder()+ .method("POST")+ .uri(format!("{BASE}?name=huge.md"))+ .header("authorization", format!("Bearer {}", person(&e)))+ .header("content-length", (MAX_FILE_BYTES + 1).to_string())+ .body(Body::from(vec![b'a'; MAX_FILE_BYTES as usize + 1]))+ .unwrap();+ assert_eq!(e.app.clone().oneshot(req).await.unwrap().status(), StatusCode::PAYLOAD_TOO_LARGE);+ // An unknown space+ let (s, _) = call(&e, "POST", "/api/spaces/nope/docs?name=a.md", &person(&e), b"x".to_vec()).await;+ assert_eq!(s, StatusCode::NOT_FOUND);+ }++ #[tokio::test]+ async fn replace_swaps_the_words_and_a_link_is_replaced_not_followed() {+ let e = setup().await;+ add(&e, "faq.md", b"old words").await;+ let (s, v) = call(&e, "POST", &format!("{BASE}?name=faq.md&replace=1"), &person(&e), b"new words".to_vec()).await;+ assert_eq!((s, v["size"].as_u64()), (StatusCode::CREATED, Some(9)), "{v}");+ assert_eq!(std::fs::read(docs(&e).join("faq.md")).unwrap(), b"new words");+ // A failed replace keeps the old document+ let (s, _) = call(&e, "POST", &format!("{BASE}?name=faq.md&replace=1"), &person(&e), vec![0xFF, 0xFE]).await;+ assert_eq!(s, StatusCode::UNPROCESSABLE_ENTITY);+ assert_eq!(std::fs::read(docs(&e).join("faq.md")).unwrap(), b"new words");+ #[cfg(unix)]+ {+ std::fs::write(e.tmp.path().join("secret.md"), "outside").unwrap();+ std::os::unix::fs::symlink(e.tmp.path().join("secret.md"), docs(&e).join("link.md")).unwrap();+ let (s, v) = add(&e, "link.md", b"inside").await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::CONFLICT, Some("exists")), "{v}");+ let (s, _) = call(&e, "POST", &format!("{BASE}?name=link.md&replace=1"), &person(&e), b"inside".to_vec()).await;+ assert_eq!(s, StatusCode::CREATED);+ assert_eq!(std::fs::read_to_string(e.tmp.path().join("secret.md")).unwrap(), "outside");+ assert!(std::fs::symlink_metadata(docs(&e).join("link.md")).unwrap().file_type().is_file());+ // A folder with a document's name is never replaced+ std::fs::create_dir(docs(&e).join("dir.md")).unwrap();+ let (s, v) = call(&e, "POST", &format!("{BASE}?name=dir.md&replace=1"), &person(&e), b"x".to_vec()).await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::CONFLICT, Some("exists")), "{v}");+ assert!(docs(&e).join("dir.md").is_dir());+ }+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn a_docs_folder_that_is_a_link_is_never_written_through() {+ let e = setup().await;+ let elsewhere = e.tmp.path().join("elsewhere");+ std::fs::create_dir(&elsewhere).unwrap();+ std::fs::write(elsewhere.join("faq.md"), "theirs").unwrap();+ std::os::unix::fs::symlink(&elsewhere, docs(&e)).unwrap();+ let (s, v) = add(&e, "new.md", b"x").await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::CONFLICT, Some("docs_link")), "{v}");+ let (s, v) = call(&e, "DELETE", &format!("{BASE}/faq.md"), &person(&e), Vec::new()).await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::CONFLICT, Some("docs_link")), "{v}");+ assert!(!elsewhere.join("new.md").exists() && elsewhere.join("faq.md").exists());+ }++ #[tokio::test]+ async fn a_space_takes_two_hundred_documents_and_replacing_one_still_works() {+ let e = setup().await;+ std::fs::create_dir_all(docs(&e)).unwrap();+ for i in 0..MAX_FILES {+ std::fs::write(docs(&e).join(format!("{i:03}.txt")), "x").unwrap();+ }+ let (s, v) = add(&e, "one-more.md", b"x").await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::CONFLICT, Some("full")), "{v}");+ let (s, _) = call(&e, "POST", &format!("{BASE}?name=000.txt&replace=1"), &person(&e), b"y".to_vec()).await;+ assert_eq!(s, StatusCode::CREATED);+ std::fs::remove_file(docs(&e).join("199.txt")).unwrap();+ assert_eq!(add(&e, "one-more.md", b"x").await.0, StatusCode::CREATED);+ }++ #[tokio::test]+ async fn the_person_removes_a_document_and_nothing_outside_the_folder() {+ let e = setup().await;+ add(&e, "faq.md", b"x").await;+ std::fs::write(e.tmp.path().join("secret.md"), "outside").unwrap();+ assert_eq!(call(&e, "DELETE", &format!("{BASE}/faq.md"), &person(&e), Vec::new()).await.0, StatusCode::NO_CONTENT);+ assert!(!docs(&e).join("faq.md").exists());+ for (name, status, code) in [+ ("faq.md", StatusCode::NOT_FOUND, "not_found"),+ ("..%2Fsecret.md", StatusCode::BAD_REQUEST, "bad_name"),+ ("%2E%2E%2Fsecret.md", StatusCode::BAD_REQUEST, "bad_name"),+ ("photo.png", StatusCode::BAD_REQUEST, "bad_name"),+ ] {+ let (s, v) = call(&e, "DELETE", &format!("{BASE}/{name}"), &person(&e), Vec::new()).await;+ assert_eq!((s, v["code"].as_str()), (status, Some(code)), "{name}: {v}");+ }+ assert!(e.tmp.path().join("secret.md").exists());+ #[cfg(unix)]+ {+ std::os::unix::fs::symlink(e.tmp.path().join("secret.md"), docs(&e).join("link.md")).unwrap();+ let (s, v) = call(&e, "DELETE", &format!("{BASE}/link.md"), &person(&e), Vec::new()).await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::BAD_REQUEST, Some("bad_name")), "{v}");+ assert!(e.tmp.path().join("secret.md").exists() && std::fs::symlink_metadata(docs(&e).join("link.md")).is_ok());+ }+ // No docs folder at all: 404+ let e = setup().await;+ assert_eq!(call(&e, "DELETE", &format!("{BASE}/faq.md"), &person(&e), Vec::new()).await.0, StatusCode::NOT_FOUND);+ }++ #[tokio::test]+ async fn a_bot_can_read_and_quote_but_never_add_or_remove() {+ let e = setup().await;+ add(&e, "faq.md", b"You can return any item within 30 days.").await;+ let bot = bot_token(&e).await;+ for (method, uri) in [("POST", format!("{BASE}?name=mine.md")), ("POST", format!("{BASE}?name=faq.md&replace=1")), ("DELETE", format!("{BASE}/faq.md"))] {+ let (s, v) = call(&e, method, &uri, &bot, b"words I made up".to_vec()).await;+ assert_eq!((s, v["code"].as_str()), (StatusCode::FORBIDDEN, Some("person_only")), "{method} {uri}: {v}");+ }+ assert!(!docs(&e).join("mine.md").exists());+ assert_eq!(std::fs::read(docs(&e).join("faq.md")).unwrap(), b"You can return any item within 30 days.");+ // Any other bearer that isn't the API token is refused the same way+ assert_eq!(call(&e, "DELETE", &format!("{BASE}/faq.md"), "not-the-token", Vec::new()).await.0, StatusCode::FORBIDDEN);+ let (s, v) = call(&e, "GET", &format!("{BASE}/page?file=faq.md"e=return%20any%20item"), &bot, Vec::new()).await;+ assert_eq!((s, v["match"].as_str()), (StatusCode::OK, Some("return any item")), "{v}");+ assert_eq!(call(&e, "GET", BASE, &bot, Vec::new()).await.0, StatusCode::OK);+ }++ #[tokio::test]+ async fn the_page_route_gives_the_page_split_around_the_quote() {+ let e = setup().await;+ add(&e, "faq.md", b"# Returns\n\nYou can return any item\nwithin 30 days.\n").await;+ add(&e, "plan.pdf", TWO_PAGES).await;+ let (s, v) = call(&e, "GET", &format!("{BASE}/page?file=faq.md"e=return%20any%20item%20within%2030%20days"), &person(&e), Vec::new()).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["file"], "faq.md");+ assert_eq!((v["page"].as_u64(), v["pages"].as_u64()), (Some(1), Some(1)));+ assert_eq!((v["text_before"].as_str(), v["match"].as_str(), v["text_after"].as_str()), (Some("# Returns\n\nYou can "), Some("return any item\nwithin 30 days"), Some(".\n")));+ assert_eq!((v["cut_before"].as_bool(), v["cut_after"].as_bool()), (Some(false), Some(false)));+ let (_, v) = call(&e, "GET", &format!("{BASE}/page?file=faq.md"), &person(&e), Vec::new()).await;+ assert_eq!((v["match"].as_str(), v["text_after"].as_str()), (Some(""), Some("# Returns\n\nYou can return any item\nwithin 30 days.\n")));+ let (_, v) = call(&e, "GET", &format!("{BASE}/page?file=faq.md"e=within%2060%20days"), &person(&e), Vec::new()).await;+ assert_eq!(v["match"], "");+ let (s, v) = call(&e, "GET", &format!("{BASE}/page?file=plan.pdf&page=2"e=Budget%20is%2042%20euros"), &person(&e), Vec::new()).await;+ assert_eq!((s, v["match"].as_str(), v["pages"].as_u64()), (StatusCode::OK, Some("Budget is 42 euros"), Some(2)), "{v}");+ // Every refusal is JSON with an error: the Documents tab probes with an empty file and+ // reads a bare 404 (no JSON) as "these routes aren't there yet"+ for (uri, status) in [+ ("page?file=plan.pdf&page=3", StatusCode::NOT_FOUND),+ ("page?file=plan.pdf&page=0", StatusCode::NOT_FOUND),+ ("page?file=faq.md&page=2", StatusCode::NOT_FOUND),+ ("page?file=missing.md", StatusCode::NOT_FOUND),+ ("page?file=..%2Fkwnt.db", StatusCode::BAD_REQUEST),+ ("page?file=&page=1", StatusCode::BAD_REQUEST),+ ("page", StatusCode::BAD_REQUEST),+ ] {+ let (s, v) = call(&e, "GET", &format!("{BASE}/{uri}"), &person(&e), Vec::new()).await;+ assert_eq!(s, status, "{uri}");+ assert!(v["error"].as_str().is_some_and(|m| !m.is_empty()), "{uri}: {v}");+ }+ }+ }}