Cotton code
66 lines · 2.6 KB · RustRaw
//! Where a document's bytes live in the object store.//!//! Its permanent home is a `crate::documents` module the worker slice (2f)//! will own; it is here because `file_document` and `delete_document` need it//! today and a second copy of "which folder is yours" is the drift this rule//! exists to prevent./// The lowercased extension of a file name, without its dot, or `""`.////// `extensionOf` from `documents/extractText.ts` — the same rule, because the/// two path helpers below are the only callers the MCP tools have.pub fn extension_of(name: &str) -> String {    let Some(dot) = name.rfind('.') else {        return String::new();    };    if dot + 1 >= name.len() {        return String::new();    }    name[dot + 1..].to_lowercase()}/// `{workspace_id}/incoming/{sha256}.{ext}` — where an upload lands first.////// Keyed by the file's own sha256, so re-running a harvest overwrites rather/// than accumulating.pub fn staging_path_for(workspace_id: &str, sha256: &str, original_name: &str) -> String {    let ext = extension_of(original_name);    if ext.is_empty() {        format!("{workspace_id}/incoming/{sha256}")    } else {        format!("{workspace_id}/incoming/{sha256}.{ext}")    }}/// `{workspace_id}/{document_id}/original.{ext}` — the document's permanent/// home.pub fn original_path_for(workspace_id: &str, document_id: &str, original_name: &str) -> String {    let ext = extension_of(original_name);    if ext.is_empty() {        format!("{workspace_id}/{document_id}/original")    } else {        format!("{workspace_id}/{document_id}/original.{ext}")    }}/// Refuse a storage path that does not sit inside this workspace's own folder.////// THIS APPLIES TO PATHS READ BACK OUT OF THE FILE, not only to ones a caller/// supplied. `storage_path` and `decrypted_path` are SYNCED, DEVICE-WRITABLE/// columns: a poisoned op — a compromised client, a bad import, a bug on any/// device — can point them at any object in the store, and this server reaches/// the store with full authority, so the workspace prefix has to be enforced/// here or not at all.////// Traversal is REFUSED, never normalised: a caller that meant `a/../b` can say/// `b`, and one that did not mean it is better off with an error.pub fn assert_path_in_workspace(path: Option<&str>, workspace_id: &str) -> Result<String, String> {    let trimmed = path.unwrap_or("").trim().to_string();    if trimmed.is_empty()        || trimmed.contains("..")        || !trimmed.starts_with(&format!("{workspace_id}/"))    {        return Err("that file path does not sit inside your own workspace folder".to_string());    }    Ok(trimmed)}