diff --git a/Cargo.lock b/Cargo.lock index 6d0f4011..0caa8533 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -68,6 +68,16 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "atoi_simd" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cdb3708a128e559a30fb830e8a77a5022ee6902806925c216658652b452a44" +dependencies = [ + "debug_unsafe", + "rustversion", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -177,12 +187,35 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "calamine" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f431b67cba6122a1f7d26b7adafc71bbdf07026095fe811f5efc025d8748e1d8" +dependencies = [ + "atoi_simd", + "byteorder", + "codepage", + "encoding_rs", + "fast-float2", + "log", + "quick-xml", + "serde", + "zip", +] + [[package]] name = "cbc" version = "0.1.2" @@ -265,6 +298,15 @@ dependencies = [ "inout", ] +[[package]] +name = "codepage" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdff162541cd8b79de82e2edcc7eff3a8c2a6dc3d75152636028f96d93de3b26" +dependencies = [ + "encoding_rs", +] + [[package]] name = "const-oid" version = "0.10.2" @@ -338,6 +380,12 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "debug_unsafe" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eed2c4702fa172d1ce21078faa7c5203e69f5394d48cc436d25928394a867a2" + [[package]] name = "digest" version = "0.10.7" @@ -445,6 +493,12 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" +[[package]] +name = "fast-float2" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f" + [[package]] name = "fastrand" version = "2.5.0" @@ -1086,6 +1140,7 @@ version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" dependencies = [ + "encoding_rs", "memchr", ] @@ -1706,6 +1761,7 @@ version = "2.0.2" dependencies = [ "async-trait", "axum", + "calamine", "chrono", "futures", "log", diff --git a/README.md b/README.md index f76a41d4..bee271c3 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ else on request, so a host pays only for what it uses. | --- | --- | --- | | `cortex` (default) | `cortex`, `registry`, `config`, `registry::binder` | `CortexEngine` over both wires; `list_engines`, `build_engine`, `EngineCredential`, cached guarded `EngineBinder`, `MemoryConfig` (implies `safety`) | | `documents` | `documents` | Format sniffing and conversion to markdown, producing `StoreItem::Document` | -| `documents-office` | `documents::OfficeConverter` | PDF, DOCX and PPTX to markdown; XLSX is temporarily unsupported (implies `documents`) | +| `documents-office` | `documents::OfficeConverter` | PDF, DOCX, PPTX and XLSX to markdown (implies `documents`) | | `brain` | `brain` | Files into `tinymemory_tools::BrainDocument`s, by the source type their format implies (implies `documents`) | | `sources` | `sources` | Folder, file and conversation readers (implies `documents`) | | `sources-network` | `sources::fetch` and the network readers | GitHub, RSS and web-page readers and `fetch_url`, behind the SSRF guard (implies `sources`) | diff --git a/crates/tinymemory-integrations/Cargo.toml b/crates/tinymemory-integrations/Cargo.toml index fccf42ad..2bafb5ed 100644 --- a/crates/tinymemory-integrations/Cargo.toml +++ b/crates/tinymemory-integrations/Cargo.toml @@ -54,10 +54,15 @@ futures = { version = "0.3", optional = true } sha2 = { version = "0.11", optional = true } # --- documents-office --- -# Text out of PDFs, Word documents and PowerPoint decks. These readers are -# pure Rust with no system libraries. Spreadsheet import is temporarily -# disabled until a safe Calamine release is published. +# Text out of the formats people actually drop into memory — a contract PDF, a +# spec `.docx`, a pricing `.xlsx`, a deck. All pure Rust with no system +# libraries. `pdf-extract` reads a PDF's text layer. `zip` + `quick-xml` are +# the whole of `.docx` and `.pptx`, which are zip archives of XML. `.xlsx` is +# not — shared-string tables and cell typing make hand-parsing it a liability — +# so `calamine` reads that one. `zip` and `quick-xml` are the versions +# `calamine` already links, so the graph carries one copy of each. pdf-extract = { version = "0.12", optional = true } +calamine = { version = "0.38", optional = true } quick-xml = { version = "0.42", optional = true } zip = { version = "9", default-features = false, features = ["deflate"], optional = true } @@ -116,10 +121,10 @@ cortex = ["dep:async-trait", "dep:serde", "dep:serde_json", "dep:reqwest", "dep: # `documents`: format sniffing and conversion to markdown, emitting # `StoreItem::Document`. Does no I/O. documents = ["dep:async-trait", "dep:serde", "dep:serde_json", "dep:thiserror"] -# `documents::OfficeConverter`: PDF, DOCX and PPTX to markdown, for a +# `documents::OfficeConverter`: PDF, DOCX, PPTX and XLSX to markdown, for a # host to prepend to its `ConverterChain`. Off by default because a PDF parser -# is real weight. XLSX is recognized but temporarily unsupported. -documents-office = ["documents", "dep:pdf-extract", "dep:quick-xml", "dep:zip"] +# and a spreadsheet reader are real weight. +documents-office = ["documents", "dep:pdf-extract", "dep:calamine", "dep:quick-xml", "dep:zip"] # `brain`: converting raw files into `tinymemory_tools::BrainDocument`s # placed under the source type their format implies. brain = ["documents", "dep:tinymemory-tools"] diff --git a/crates/tinymemory-integrations/README.md b/crates/tinymemory-integrations/README.md index 34a6fe24..67f237cc 100644 --- a/crates/tinymemory-integrations/README.md +++ b/crates/tinymemory-integrations/README.md @@ -16,7 +16,7 @@ wants one integration enables one feature and links nothing else. | --- | --- | --- | --- | | `cortex`, `registry`, `config` | `cortex` (default) | `CortexEngine` over two wires (`cortexdb`, `tinyhumans`); `list_engines`, `build_engine`, `EngineCredential`, cached guarded `EngineBinder`; `MemoryConfig` | [`src/cortex/README.md`](src/cortex/README.md) | | `documents` | `documents` | Format sniffing and conversion to markdown, producing `StoreItem::Document`. No I/O. | [`src/documents/README.md`](src/documents/README.md) | -| `documents::OfficeConverter` | `documents-office` | PDF, DOCX and PPTX to markdown; XLSX is temporarily unsupported | (same) | +| `documents::OfficeConverter` | `documents-office` | PDF, DOCX, PPTX and XLSX to markdown, in process | (same) | | `sources` | `sources` | Readers and host source types, target/layout validation, sync state, batch storage and placement jobs; `collect_items`. Links no HTTP client. | [`src/sources/README.md`](src/sources/README.md) | | Source schemas | `schema` | Optional JSON Schema derives for the source configuration and reader types | (same) | | `sources::fetch`, GitHub, RSS and web-page readers | `sources-network` | The network readers and `fetch_url`, all behind the SSRF guard | (same) | @@ -38,7 +38,7 @@ already needs): | --- | --- | | `cortex` | `reqwest` (rustls TLS, streaming bodies), `tokio` (`time` only), `futures`, `sha2`, `tinyredact` (through mandatory binder safety) | | `documents` | nothing beyond the small set above | -| `documents-office` | `pdf-extract`, `quick-xml`, `zip` (all pure Rust, no system libraries) | +| `documents-office` | `pdf-extract`, `calamine`, `quick-xml`, `zip` (all pure Rust, no system libraries) | | `brain` | `tinymemory-tools` (for `BrainDocument`; it adds only `futures`, `chrono`, `log`) | | `sources` | `tinymemory-tools` (layout and background-job types; no Tokio), `url`, `regex`, `walkdir`, `chrono`, `log`, `tracing` | | `schema` | `schemars` | diff --git a/crates/tinymemory-integrations/src/documents/README.md b/crates/tinymemory-integrations/src/documents/README.md index 09db32cd..545d3045 100644 --- a/crates/tinymemory-integrations/src/documents/README.md +++ b/crates/tinymemory-integrations/src/documents/README.md @@ -41,7 +41,7 @@ caller's to state. | `ConvertedDocument` | markdown plus title, source format, language, and converter metadata | | `DocumentConverter` | the conversion seam — object-safe and async | | `NativeConverter` | markdown, text, HTML and code, with no dependencies | -| `OfficeConverter` | PDF, DOCX and PPTX, in-process (feature `documents-office`); XLSX is temporarily unsupported | +| `OfficeConverter` | PDF, DOCX, PPTX and XLSX, in-process (feature `documents-office`) | | `ConverterChain` | converters in priority order; first claim wins | | `document_item` / `converted_item` | the conversion wrapped as a `StoreItem::Document` | | `markdown_from_text` | the synchronous core, for callers that already hold text | @@ -67,23 +67,18 @@ conversion is a trait a host binds: let chain = ConverterChain::default().prepend(Box::new(MyPdfConverter)); ``` -The `documents-office` feature ships one such binding, `OfficeConverter`: PDF -(text layer only — a scanned PDF is refused as having no text; pages are -extracted one by one, normalized on their own and joined by `PAGE_BREAK`, a -form feed, so a reader can number them), DOCX and PPTX (slides in numeric -order), all pure Rust. It refuses hostile archive input rather than allocating -for it when declared uncompressed sizes exceed `MAX_DECOMPRESSED_BYTES` -(64 MiB). Unreadable documents are `Error::Invalid`. Parsing is CPU-bound; a -host on a shared executor calls `OfficeConverter::convert_blocking` from its +The `documents-office` feature ships one such binding, `OfficeConverter`: PDF (text +layer only — a scanned PDF is refused as having no text; pages are extracted +one by one, normalized on their own and joined by `PAGE_BREAK`, a form feed, +so a reader can number them), DOCX, PPTX (slides +in numeric order) and XLSX (one `sheet | cell | cell` line per row), all pure +Rust. It refuses hostile input rather than allocating for it: an archive whose +declared uncompressed size exceeds `MAX_DECOMPRESSED_BYTES` (64 MiB), and a +spreadsheet whose dense used range exceeds `MAX_SPREADSHEET_DENSE_CELLS` +(1,000,000). Unreadable documents are `Error::Invalid`. Parsing is CPU-bound; +a host on a shared executor calls `OfficeConverter::convert_blocking` from its own blocking pool. -XLSX and macro-enabled XLSM remain recognizable formats, but the built-in -spreadsheet reader is temporarily disabled while TinyMemory waits for a safe -Calamine release. `OfficeConverter::supports(DocumentFormat::Xlsx)` is false; -calling it directly returns `Error::UnsupportedFormat` with a restoration -message before opening the workbook. A host can still bind its own spreadsheet -converter. CSV and other plain text continue through `NativeConverter`. - A zip upload is told apart by its part names (`word/`, `xl/`, `ppt/`) read from the central directory, so an `.xlsx` sent as `application/octet-stream` still sniffs as XLSX. When the parts say nothing, an Office label refines the @@ -108,5 +103,6 @@ success. - `documents` — this module; depends only on `async-trait`, `serde`, `serde_json` and `thiserror`. -- `documents-office` — `OfficeConverter` (`pdf-extract`, `zip`, `quick-xml`). - Off by default; it links a PDF parser a text-only host has no use for. +- `documents-office` — `OfficeConverter` (`pdf-extract`, `calamine`, `zip`, + `quick-xml`). Off by default; it links a PDF parser and a spreadsheet reader + a text-only host has no use for. diff --git a/crates/tinymemory-integrations/src/documents/convert/mod.rs b/crates/tinymemory-integrations/src/documents/convert/mod.rs index ff736cdf..35cf66a7 100644 --- a/crates/tinymemory-integrations/src/documents/convert/mod.rs +++ b/crates/tinymemory-integrations/src/documents/convert/mod.rs @@ -246,10 +246,6 @@ impl DocumentConverter for ConverterChain { let format = document.format(); match self.converters.iter().find(|c| c.supports(format)) { Some(converter) => converter.convert(document).await, - None if format == DocumentFormat::Xlsx => Err(Error::UnsupportedFormat( - "spreadsheet import is temporarily disabled until a safe reader release is available" - .to_string(), - )), None => Err(Error::UnsupportedFormat(format!( "no converter handles {format}; this build converts {}", describe(&self.supported_formats()) diff --git a/crates/tinymemory-integrations/src/documents/format/mod.rs b/crates/tinymemory-integrations/src/documents/format/mod.rs index 44997290..0d048137 100644 --- a/crates/tinymemory-integrations/src/documents/format/mod.rs +++ b/crates/tinymemory-integrations/src/documents/format/mod.rs @@ -35,9 +35,8 @@ pub enum DocumentFormat { Pdf, /// Office Open XML word processing (`.docx`). Needs a real extractor. Docx, - /// Office Open XML spreadsheet (`.xlsx`, macro-enabled `.xlsm`). The - /// format remains recognizable, though TinyMemory's built-in reader is - /// temporarily disabled; a host may bind its own converter. + /// Office Open XML spreadsheet (`.xlsx`, macro-enabled `.xlsm`). Needs a + /// real extractor. Xlsx, /// Office Open XML presentation (`.pptx`). Needs a real extractor. Pptx, diff --git a/crates/tinymemory-integrations/src/documents/mod.rs b/crates/tinymemory-integrations/src/documents/mod.rs index 782fd0a4..cb1db49f 100644 --- a/crates/tinymemory-integrations/src/documents/mod.rs +++ b/crates/tinymemory-integrations/src/documents/mod.rs @@ -11,9 +11,8 @@ //! 2. **Turn it into markdown.** [`DocumentConverter`] is the seam; //! [`NativeConverter`] covers markdown, plain text, HTML and code with no //! dependencies; a host binds its own for PDF and Office documents, or -//! prepends `OfficeConverter` (feature `documents-office`) for PDF, DOCX and -//! PPTX. XLSX is still recognized but the built-in reader is temporarily -//! disabled; a host may provide its own converter. +//! prepends `OfficeConverter` (feature `documents-office`) for PDF, DOCX, PPTX and +//! XLSX. //! 3. **Wrap it as an item.** [`document_item`] produces a //! `StoreItem::Document` with the caller's //! [`MemoryMeta`](tinymemory_api::MemoryMeta), filling `language` from the diff --git a/crates/tinymemory-integrations/src/documents/office/mod.rs b/crates/tinymemory-integrations/src/documents/office/mod.rs index b76474b8..5324cf8e 100644 --- a/crates/tinymemory-integrations/src/documents/office/mod.rs +++ b/crates/tinymemory-integrations/src/documents/office/mod.rs @@ -2,7 +2,7 @@ //! //! [`crate::documents::convert::NativeConverter`] handles what is already text. This is //! the converter for the formats people actually drop into memory that are not -//! — a contract PDF, a spec `.docx`, a deck — so a host +//! — a contract PDF, a spec `.docx`, a pricing `.xlsx`, a deck — so a host //! does not have to bind an extractor of its own for them: //! //! ``` @@ -16,9 +16,12 @@ //! | PDF | `pdf-extract`, text layer only | each page's text, whitespace-normalized, pages joined by [`PAGE_BREAK`] | //! | DOCX | `zip` + `quick-xml` over `word/document.xml` | one paragraph per `w:p` | //! | PPTX | `zip` + `quick-xml` over `ppt/slides/slideN.xml` | slides in numeric order, one paragraph per `a:p` | -//! XLSX remains recognizable as a format but is temporarily unsupported while -//! the project waits for a safe Calamine release. Direct conversion returns a -//! helpful [`Error::UnsupportedFormat`] without opening the workbook. +//! | XLSX | `calamine` | one `sheet \| cell \| cell` line per non-empty row | +//! +//! A spreadsheet is flattened rather than rebuilt as a table because that is +//! what recall can use: a chunk reading `Q3 | EMEA | 412000` answers a question +//! about EMEA revenue, and the same data as aligned columns does not survive +//! chunking. //! //! ## Hostile input //! @@ -29,6 +32,18 @@ //! before any entry is read — and each entry read is capped as well, so an //! archive that lies about its sizes cannot force the allocation either. //! +//! A spreadsheet has one more: calamine materializes the dense bounding box of +//! a sheet's cells, so a tiny workbook with one cell at `A1` and one at +//! `XFD1048576` would allocate ~17 billion cells. The cells are scanned +//! sparsely first and a sheet whose box exceeds +//! [`MAX_SPREADSHEET_DENSE_CELLS`] is refused before that happens. The same +//! scan sums each cell's text, counting every reference to a shared string, +//! because reading a sheet copies the string into each cell: a workbook past +//! [`MAX_SPREADSHEET_TEXT_BYTES`] is refused too. And calamine reserves room +//! for the shared-string count a workbook declares while it opens it, so a +//! table declaring more entries than a sheet could hold cells is refused +//! before calamine sees it. +//! //! `pdf-extract` panics on some malformed documents rather than erroring; the //! panic is caught and reported as an unreadable document. //! @@ -43,6 +58,7 @@ mod normalize; mod ooxml; mod pdf; +mod xlsx; use async_trait::async_trait; @@ -57,15 +73,19 @@ use crate::documents::format::DocumentFormat; /// before it is refused as a likely zip bomb. See the module docs. pub const MAX_DECOMPRESSED_BYTES: u64 = 64 * 1024 * 1024; -/// The historical spreadsheet used-range cap, retained for API compatibility. -/// -/// The built-in spreadsheet reader is temporarily disabled, so the limit is -/// not currently applied by [`OfficeConverter`]. +/// The most cells a spreadsheet's dense used range may span before it is +/// refused. The used range of a real spreadsheet is a small fraction of the +/// grid, so this only bites hostile input; see the module docs. pub const MAX_SPREADSHEET_DENSE_CELLS: usize = 1_000_000; -/// Converts PDF, DOCX and PPTX documents to markdown, in-process. +/// The most cell text, in bytes, a spreadsheet may expand to across all its +/// sheets before it is refused. Every reference to a shared string counts, as +/// reading the sheet copies the string into each cell. +pub const MAX_SPREADSHEET_TEXT_BYTES: u64 = 64 * 1024 * 1024; + +/// Converts PDF, DOCX, PPTX and XLSX documents to markdown, in-process. /// -/// Claims exactly those three formats, so it composes with +/// Claims exactly those four formats, so it composes with /// [`crate::documents::convert::NativeConverter`] in a [`crate::documents::convert::ConverterChain`] /// without shadowing it. A document whose text cannot be read — malformed, /// over a cap, or a scanned PDF with no text layer — is [`Error::Invalid`] @@ -92,12 +112,7 @@ impl OfficeConverter { DocumentFormat::Pdf => paged(&pdf::extract(bytes)?), DocumentFormat::Docx => normalize::normalize(&ooxml::docx(bytes)?), DocumentFormat::Pptx => normalize::normalize(&ooxml::pptx(bytes)?), - DocumentFormat::Xlsx => { - return Err(Error::UnsupportedFormat( - "spreadsheet import is temporarily disabled until a safe reader release is available" - .to_string(), - )); - } + DocumentFormat::Xlsx => normalize::normalize(&xlsx::extract(bytes)?), other => { return Err(Error::UnsupportedFormat(format!( "the office converter does not handle {other}" @@ -132,7 +147,10 @@ impl DocumentConverter for OfficeConverter { fn supports(&self, format: DocumentFormat) -> bool { matches!( format, - DocumentFormat::Pdf | DocumentFormat::Docx | DocumentFormat::Pptx + DocumentFormat::Pdf + | DocumentFormat::Docx + | DocumentFormat::Xlsx + | DocumentFormat::Pptx ) } diff --git a/crates/tinymemory-integrations/src/documents/office/mod_tests.rs b/crates/tinymemory-integrations/src/documents/office/mod_tests.rs index e31c282f..993ba1db 100644 --- a/crates/tinymemory-integrations/src/documents/office/mod_tests.rs +++ b/crates/tinymemory-integrations/src/documents/office/mod_tests.rs @@ -1,4 +1,4 @@ -//! Tests for the office converter: PDF, DOCX and PPTX conversion plus explicit XLSX refusal. +//! Tests for the office converter: PDF, DOCX, PPTX and XLSX to markdown. //! //! Every fixture is built here rather than checked in, so each test says what //! it is asserting about instead of pointing at an opaque binary. @@ -75,8 +75,17 @@ fn pptx(slides: &[(u32, &str)]) -> Vec { package(&borrowed) } -/// A minimal XLSX-shaped archive from a worksheet's `sheetData` fragment. +/// A minimal XLSX archive from a worksheet's `sheetData` fragment. +/// +/// The parts are the smallest set calamine's Xlsx reader accepts: the +/// content-type map, the root and workbook relationships, and the workbook +/// itself. No shared strings or styles, which the reader tolerates. fn xlsx_with_sheet(sheet_data: &str) -> Vec { + xlsx_with_parts(sheet_data, &[]) +} + +/// A one-sheet workbook plus `extra` parts (a shared-string table, say). +fn xlsx_with_parts(sheet_data: &str, extra: &[(&str, &str)]) -> Vec { let content_types = r#" @@ -102,13 +111,27 @@ fn xlsx_with_sheet(sheet_data: &str) -> Vec { {sheet_data} "# ); - package(&[ + let mut parts = vec![ ("[Content_Types].xml", content_types), ("_rels/.rels", root_rels), ("xl/workbook.xml", workbook), ("xl/_rels/workbook.xml.rels", workbook_rels), - ("xl/worksheets/sheet1.xml", &worksheet), - ]) + ("xl/worksheets/sheet1.xml", worksheet.as_str()), + ]; + parts.extend_from_slice(extra); + package(&parts) +} + +fn shared_strings(unique_count: &str, strings: &[&str]) -> String { + let items: String = strings + .iter() + .map(|s| format!("{s}")) + .collect(); + format!( + r#" +{items}"#, + n = strings.len() + ) } /// A one-page PDF whose content stream is `content`, with a correct @@ -181,10 +204,11 @@ async fn refusal(name: &str, bytes: Vec) -> String { } #[test] -fn it_claims_supported_office_formats_but_not_xlsx() { +fn it_claims_the_four_office_formats_and_nothing_else() { for format in [ DocumentFormat::Pdf, DocumentFormat::Docx, + DocumentFormat::Xlsx, DocumentFormat::Pptx, ] { assert!(OfficeConverter.supports(format), "{format}"); @@ -197,7 +221,6 @@ fn it_claims_supported_office_formats_but_not_xlsx() { ] { assert!(!OfficeConverter.supports(format), "{format}"); } - assert!(!OfficeConverter.supports(DocumentFormat::Xlsx)); } #[tokio::test] @@ -243,31 +266,29 @@ async fn a_deck_refuses_malformed_central_directory_entry_metadata() { } #[tokio::test] -async fn spreadsheet_import_is_temporarily_disabled_with_a_helpful_error() { - // Keep format recognition intact, but reject before parsing workbook XML. +async fn a_small_spreadsheet_yields_one_line_per_row() { + // The dense-range guard must not refuse ordinary files, and the concrete + // (non-auto) Xlsx open must not either. let bytes = xlsx_with_sheet( r#"1alpha 2beta"#, ); - let reason = refusal("ledger.xlsx", bytes).await; - assert!( - reason.contains("spreadsheet import is temporarily disabled"), - "{reason}" - ); + let converted = convert("ledger.xlsx", bytes).await.unwrap(); + assert_eq!(converted.markdown, "Sheet1 | 1 | alpha\nSheet1 | 2 | beta"); + assert_eq!(converted.format, DocumentFormat::Xlsx); } #[tokio::test] -async fn a_spreadsheet_is_disabled_even_when_its_cells_are_far_apart() { - // Rejection must happen before a parser could materialize the used range. +async fn a_spreadsheet_with_far_cells_is_refused_not_allocated() { + // One cell at `A1` and one at `XFD1048576` passes the decompression cap + // (the archive is a few hundred bytes) yet would make calamine + // materialize a ~17-billion-cell dense grid. Refused before that. let bytes = xlsx_with_sheet( r#"1 2"#, ); let reason = refusal("spread.xlsx", bytes).await; - assert!( - reason.contains("spreadsheet import is temporarily disabled"), - "{reason}" - ); + assert!(reason.contains("used range"), "{reason}"); } #[tokio::test] @@ -286,14 +307,11 @@ async fn an_overexpanding_document_is_refused_not_allocated() { } #[tokio::test] -async fn an_overexpanding_spreadsheet_is_disabled_before_archive_parsing() { +async fn an_overexpanding_spreadsheet_is_refused_before_calamine_opens_it() { let zeroes = "\0".repeat(MAX_DECOMPRESSED_BYTES as usize + 1); let bytes = package(&[("xl/workbook.xml", &zeroes)]); let reason = refusal("bomb.xlsx", bytes).await; - assert!( - reason.contains("spreadsheet import is temporarily disabled"), - "{reason}" - ); + assert!(reason.contains("expands"), "{reason}"); } #[tokio::test] @@ -398,7 +416,7 @@ fn the_blocking_entry_point_converts_without_a_runtime() { } #[tokio::test] -async fn prepended_to_the_default_chain_it_covers_supported_formats() { +async fn prepended_to_the_default_chain_it_covers_every_format() { let chain = ConverterChain::default().prepend(Box::new(OfficeConverter)); assert_eq!( chain.supported_formats(), @@ -409,22 +427,15 @@ async fn prepended_to_the_default_chain_it_covers_supported_formats() { DocumentFormat::Code, DocumentFormat::Pdf, DocumentFormat::Docx, + DocumentFormat::Xlsx, DocumentFormat::Pptx, ] ); - // An unlabelled workbook is recognized and refused, while markdown still - // goes to the native converter behind it. + // An unlabelled workbook routes by its parts to the office converter, + // and markdown still goes to the native one behind it. let workbook = xlsx_with_sheet(r#"7"#); - let error = chain - .convert(&RawDocument::new(workbook)) - .await - .unwrap_err(); - assert!( - error - .to_string() - .contains("spreadsheet import is temporarily disabled"), - "{error}" - ); + let converted = chain.convert(&RawDocument::new(workbook)).await.unwrap(); + assert_eq!(converted.markdown, "Sheet1 | 7"); let notes = chain .convert(&RawDocument::new("# Notes").with_filename("notes.md")) .await @@ -433,13 +444,60 @@ async fn prepended_to_the_default_chain_it_covers_supported_formats() { } #[tokio::test] -async fn csv_plaintext_stays_with_the_native_converter() { - let chain = ConverterChain::default().prepend(Box::new(OfficeConverter)); - let converted = chain - .convert(&RawDocument::new("name,amount\nAda,3\n").with_filename("ledger.csv")) - .await - .unwrap(); - assert_eq!(converted.format, DocumentFormat::PlainText); - assert_eq!(converted.markdown, "name,amount\nAda,3\n"); - assert_eq!(converted.metadata["converter"], "native"); +async fn a_shared_string_cell_reads_through_the_table() { + let table = shared_strings("1", &["hello"]); + let bytes = xlsx_with_parts( + r#"0"#, + &[("xl/sharedStrings.xml", &table)], + ); + let converted = convert("ledger.xlsx", bytes).await.unwrap(); + assert_eq!(converted.markdown, "Sheet1 | hello"); +} + +#[tokio::test] +async fn an_absurd_shared_string_count_is_refused_before_calamine_reserves_it() { + // calamine reserves `uniqueCount` entries while it opens the workbook: a + // count past the bound would abort the process, not return an error. + for count in [ + "18446744073709551615", + "1000001", + "99999999999999999999999", + "+5", + "", + ] { + let table = shared_strings(count, &["x"]); + let bytes = xlsx_with_parts( + r#"0"#, + &[("xl/sharedStrings.xml", &table)], + ); + let reason = refusal("table.xlsx", bytes).await; + assert!( + reason.contains("shared-string table"), + "{count:?}: {reason}" + ); + } + // Checked wherever the table sits, not only under `xl/`. + let table = shared_strings("18446744073709551615", &["x"]); + let bytes = xlsx_with_parts( + r#"1"#, + &[("other/sharedStrings.xml", &table)], + ); + let reason = refusal("table.xlsx", bytes).await; + assert!(reason.contains("shared-string table"), "{reason}"); +} + +#[tokio::test] +async fn repeated_shared_string_references_count_against_the_text_budget() { + // One 4 KiB string referenced from enough cells to expand past the text + // budget: small as an archive, far below the cell bound, but every + // reference becomes its own copy when the sheet is read. + let long = "x".repeat(4096); + let table = shared_strings("1", &[&long]); + let cells = usize::try_from(MAX_SPREADSHEET_TEXT_BYTES / 4096).unwrap() + 1; + let rows: String = (1..=cells) + .map(|row| format!(r#"0"#)) + .collect(); + let bytes = xlsx_with_parts(&rows, &[("xl/sharedStrings.xml", &table)]); + let reason = refusal("repeat.xlsx", bytes).await; + assert!(reason.contains("cell text exceeds"), "{reason}"); } diff --git a/crates/tinymemory-integrations/src/documents/office/xlsx.rs b/crates/tinymemory-integrations/src/documents/office/xlsx.rs new file mode 100644 index 00000000..8c9f2ea3 --- /dev/null +++ b/crates/tinymemory-integrations/src/documents/office/xlsx.rs @@ -0,0 +1,178 @@ +//! Spreadsheets, flattened to one `sheet | cell | cell` line per row. + +use std::io::{BufReader, Cursor, Read}; + +use calamine::{Data, DataRef, Reader, Xlsx}; +use quick_xml::events::Event; +use zip::ZipArchive; + +use super::{MAX_SPREADSHEET_DENSE_CELLS, MAX_SPREADSHEET_TEXT_BYTES, ooxml, unreadable}; +use crate::documents::error::Result; + +/// Most entries a shared-string table may declare. Equal to +/// [`MAX_SPREADSHEET_DENSE_CELLS`]: a sheet that can hold at most that many +/// cells has no use for more distinct strings. +const MAX_SHARED_STRINGS: u64 = 1_000_000; + +/// Extracts every non-empty row of every sheet, in sheet order. +pub(super) fn extract(bytes: &[u8]) -> Result { + // The zip-bomb guard and the shared-string check run before calamine + // materializes anything. + let mut archive = ooxml::open(bytes, "spreadsheet")?; + check_shared_strings(&mut archive)?; + drop(archive); + + // Opened as a concrete `Xlsx` rather than auto-detected: the other formats + // calamine's auto-open falls back to (`.xls`, `.xlsb`, `.ods`) build their + // dense ranges during open — before the extent guard below could run — so + // accepting a mislabelled file would reopen the same allocation attack. + let mut workbook: Xlsx<_> = calamine::open_workbook_from_rs(Cursor::new(bytes)) + .map_err(|error| unreadable(format!("the spreadsheet could not be read: {error}")))?; + let mut out = String::new(); + // Text materialized so far, across every sheet: `worksheet_range` gives + // each shared-string reference its own copy, so the cell bound alone does + // not bound memory. + let mut text = 0u64; + for name in workbook.sheet_names() { + let Some(extent) = scan(&mut workbook, &name) else { + continue; + }; + if extent.cells > MAX_SPREADSHEET_DENSE_CELLS { + return Err(unreadable( + "the spreadsheet's used range exceeds the size this build can read safely" + .to_string(), + )); + } + text = text.saturating_add(extent.text); + if text > MAX_SPREADSHEET_TEXT_BYTES { + return Err(unreadable( + "the spreadsheet's cell text exceeds the size this build can read safely" + .to_string(), + )); + } + let Ok(range) = workbook.worksheet_range(&name) else { + continue; + }; + for row in range.rows() { + let cells: Vec = row + .iter() + .map(|cell| match cell { + Data::Empty => String::new(), + other => other.to_string(), + }) + .collect(); + if cells.iter().all(|cell| cell.trim().is_empty()) { + continue; + } + out.push_str(&name); + for cell in cells { + out.push_str(" | "); + out.push_str(cell.trim()); + } + out.push('\n'); + } + } + Ok(out) +} + +/// What `worksheet_range` would allocate for a sheet. +struct Extent { + /// Cells in the bounding box of the sheet's actual cells. + cells: usize, + /// Bytes of cell text, counting every reference to a shared string. + text: u64, +} + +/// A sheet's [`Extent`], found by a sparse scan that allocates no grid and +/// copies no text (shared strings are borrowed). `None` for a sheet that +/// cannot be read or has no cells. +fn scan(workbook: &mut Xlsx>, sheet: &str) -> Option { + let mut reader = workbook.worksheet_cells_reader(sheet).ok()?; + let (mut row_min, mut row_max) = (u32::MAX, 0); + let (mut col_min, mut col_max) = (u32::MAX, 0); + let mut text = 0u64; + while let Ok(Some(cell)) = reader.next_cell() { + text = text.saturating_add(text_bytes(cell.get_value())); + let (row, col) = cell.get_position(); + row_min = row_min.min(row); + row_max = row_max.max(row); + col_min = col_min.min(col); + col_max = col_max.max(col); + } + if row_min == u32::MAX { + return None; + } + let rows = u64::from(row_max - row_min) + 1; + let cols = u64::from(col_max - col_min) + 1; + Some(Extent { + cells: usize::try_from(rows.saturating_mul(cols)).unwrap_or(usize::MAX), + text, + }) +} + +/// The text a cell becomes: its own string, or a number's or date's short +/// rendering. +fn text_bytes(value: &DataRef<'_>) -> u64 { + let bytes = match value { + DataRef::String(s) | DataRef::DateTimeIso(s) | DataRef::DurationIso(s) => s.len(), + DataRef::SharedString(s) => s.len(), + DataRef::Empty => 0, + _ => 32, + }; + u64::try_from(bytes).unwrap_or(u64::MAX) +} + +/// Refuses a workbook whose shared-string table declares more entries than +/// [`MAX_SHARED_STRINGS`]. calamine reserves `sst/@uniqueCount` entries up +/// front while it opens the workbook, so an absurd count would abort the +/// process before any later guard ran. Every entry named `sharedStrings.xml` +/// is checked, wherever the workbook's relationships place it. +fn check_shared_strings(archive: &mut ZipArchive>) -> Result<()> { + for index in 0..archive.len() { + let entry = archive + .by_index(index) + .map_err(|error| unreadable(format!("the spreadsheet could not be read: {error}")))?; + let name = entry + .name() + .map_err(|error| unreadable(format!("the spreadsheet could not be read: {error}")))?; + if !name.to_ascii_lowercase().ends_with("sharedstrings.xml") { + continue; + } + if declared_unique_count(entry).is_some_and(|count| count > MAX_SHARED_STRINGS) { + return Err(unreadable( + "the spreadsheet's shared-string table declares more entries than this build can \ + read safely" + .to_string(), + )); + } + } + Ok(()) +} + +/// The `uniqueCount` an `` element declares. A value that is present but +/// not a plain decimal that fits is reported as `u64::MAX`, so it is refused +/// rather than trusted; `None` when the attribute or element is absent. +fn declared_unique_count(part: impl Read) -> Option { + let mut reader = quick_xml::Reader::from_reader(BufReader::new(part)); + let mut buf = Vec::new(); + loop { + match reader.read_event_into(&mut buf) { + Ok(Event::Start(e) | Event::Empty(e)) if e.local_name().as_ref() == "sst" => { + let attribute = e + .attributes() + .flatten() + .find(|a| a.key.local_name().as_ref() == "uniqueCount")?; + let value = attribute.value; + let plain = !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()); + return Some( + Some(value.as_ref()) + .filter(|_| plain) + .and_then(|v| v.parse().ok()) + .unwrap_or(u64::MAX), + ); + } + Ok(Event::Eof) | Err(_) => return None, + Ok(_) => buf.clear(), + } + } +} diff --git a/crates/tinymemory-integrations/tests/documents_office.rs b/crates/tinymemory-integrations/tests/documents_office.rs index 9dc46c75..34eb2b22 100644 --- a/crates/tinymemory-integrations/tests/documents_office.rs +++ b/crates/tinymemory-integrations/tests/documents_office.rs @@ -12,9 +12,9 @@ fn documents_office_feature_exposes_the_office_converter() { for format in [ DocumentFormat::Pdf, DocumentFormat::Docx, + DocumentFormat::Xlsx, DocumentFormat::Pptx, ] { assert!(chain.supports(format), "{format}"); } - assert!(!chain.supports(DocumentFormat::Xlsx)); } diff --git a/docs/architecture/integrations.md b/docs/architecture/integrations.md index b391dbbb..2e5f4834 100644 --- a/docs/architecture/integrations.md +++ b/docs/architecture/integrations.md @@ -97,7 +97,7 @@ extension, or `None`. The names are a wire contract: they land in | `ConvertedDocument` | markdown (never empty), title, format, language, source size, converter metadata | | `DocumentConverter` | the object-safe async seam: `name`, `supports(format)`, `convert(&RawDocument)` | | `NativeConverter` | markdown, plain text, HTML and code, with no dependencies | -| `OfficeConverter` | PDF, DOCX and PPTX (feature `documents-office`); XLSX remains recognized but is temporarily unsupported | +| `OfficeConverter` | PDF, DOCX, PPTX and XLSX (feature `documents-office`) | | `ConverterChain` | converters in priority order; the first that claims the format converts | | `check_size` | rejects an empty body or one over `MAX_DOCUMENT_BYTES` | | `markdown_from_text` | the synchronous core, for callers already holding text | @@ -117,21 +117,20 @@ listing what the build can convert, never a silent empty document. ### OfficeConverter Under `documents-office`, `OfficeConverter` is pure Rust (`pdf-extract`, `zip` + -`quick-xml`): +`quick-xml`, `calamine`): | Format | Reader | Markdown | | --- | --- | --- | | PDF | text layer only (a scanned PDF is refused as having no text) | page text, whitespace-normalised | | DOCX | `word/document.xml` | one paragraph per `w:p` | | PPTX | `ppt/slides/slideN.xml` | slides in numeric order | -| XLSX | temporarily disabled while awaiting a safe Calamine release | `Error::UnsupportedFormat`; the workbook is not opened | +| XLSX | `calamine` | one `sheet \| cell \| cell` line per non-empty row | It refuses hostile input: an archive whose declared uncompressed size exceeds -`MAX_DECOMPRESSED_BYTES` (64 MiB), each entry read being capped as well. XLSX -and XLSM are recognized by format sniffing but are not claimed by the built-in -converter; a host may bind its own `DocumentConverter`. CSV and plaintext stay -on the native text converter. A `pdf-extract` panic on a malformed file is -caught and reported as an unreadable document. Parsing is CPU-bound and runs inline in the async +`MAX_DECOMPRESSED_BYTES` (64 MiB), each entry read being capped as well, and a +spreadsheet whose dense used range exceeds `MAX_SPREADSHEET_DENSE_CELLS` +(1,000,000). A `pdf-extract` panic on a malformed file is caught and reported +as an unreadable document. Parsing is CPU-bound and runs inline in the async `convert`; a host on a shared executor calls `convert_blocking` from its own blocking pool. A host typically prepends it: diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index af013299..f14bce21 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -56,7 +56,7 @@ alone, so the contract is the only coupling point. | `tinymemory-tools` | (none) | Every module (`tools`, `context`, `recall`, `layout`, `brain`, `lifecycle`, `background`) is always built. | | `tinymemory-integrations` | `cortex` (default) | `cortex::CortexEngine` (both wires), `registry` (`list_engines`, `build_engine`), `config` (`MemoryConfig`) | | | `documents` | Format sniffing and conversion to markdown | -| | `documents-office` | PDF, DOCX and PPTX conversion; XLSX temporarily unsupported (implies `documents`) | +| | `documents-office` | PDF, DOCX, PPTX, XLSX conversion (implies `documents`) | | | `sources` | Readers for folders, files, conversations (implies `documents`) | | | `sources-network` | GitHub, RSS and web-page readers behind the SSRF guard (implies `sources`) | | | `safety` | Secret and PII scrubbing of a `StoreItem` | diff --git a/docs/architecture/testing.md b/docs/architecture/testing.md index 0e87343a..74b88b06 100644 --- a/docs/architecture/testing.md +++ b/docs/architecture/testing.md @@ -260,7 +260,7 @@ idempotency pairs, and every recall, answer and forget body for assertions. | File | Needs | Covers | | --- | --- | --- | | `feature_surface.rs` | `full` | the modules compose: scrub an item, store it in the reference engine, run the conformance suite, compile a context | -| `documents_office.rs` | `documents-office` | `OfficeConverter` prepends to the default `ConverterChain` and supports PDF, DOCX and PPTX, while XLSX remains recognized but unsupported | +| `documents_office.rs` | `documents-office` | `OfficeConverter` prepends to the default `ConverterChain` and supports PDF, DOCX, XLSX, PPTX | | `reader_dispatch.rs` | `sources` (`sources-network` for one test) | local readers are constructed for timers, network readers only for requests | | `legacy_import.rs` | `legacy-import` | importing v1 workspaces, every mapping, ordering and resumption | | `live_cortexdb.rs`, `office_live.rs` | `cortex` (+ `documents-office`) | a real CortexDB; skipped unless configured | diff --git a/docs/integration.md b/docs/integration.md index 5dedd96b..0216a0e1 100644 --- a/docs/integration.md +++ b/docs/integration.md @@ -45,7 +45,7 @@ tinymemory-integrations = { git = "https://github.com/tinyhumansai/tinymemory", | --- | --- | | `cortex` (default) | the CortexDB engine, both wires, plus `registry` and `config` | | `brain` | `brain_document`: a file converted and filed under its source | -| `documents-office` | PDF, DOCX and PPTX conversion for the brain; XLSX temporarily unsupported | +| `documents-office` | PDF, DOCX and XLSX conversion for the brain | | `full` | everything | For tests and offline development, enable `tinymemory-api`'s `conformance` diff --git a/docs/specs/memory-v2.md b/docs/specs/memory-v2.md index 0d2ef07b..981013b2 100644 --- a/docs/specs/memory-v2.md +++ b/docs/specs/memory-v2.md @@ -30,7 +30,7 @@ Three memory crates, plus the standalone redaction crate `tinyredact`. Their rel | --- | --- | | `tinymemory-api` | Pure safety vocabulary (classification/redaction behind `local-safety`) and the contract: `MemoryEngine`, request/response types, `MemoryMeta`, `MetaFilter`, namespaces, `EngineDescriptor`, `EngineStatus`, `Error`. No I/O. Feature `conformance`: the behavioural suite every engine must pass, plus a reference in-memory engine. | | `tinymemory-tools` | The agent tool spec `MemoryTools` (seven tools, host-fixed namespace and reach) and `context`, the `ContextCompiler` that builds `context.md` from an engine. | -| `tinymemory-integrations` | Everything that talks to the outside world, each behind a feature: `cortex` (default; the CortexDB engine, registered twice as `cortexdb` and `tinyhumans`, plus the registry `list_engines`/`build_engine` and `MemoryConfig`), `documents` and `documents-office` (format sniffing and conversion to markdown, emitting `StoreItem::Document`; PDF/DOCX/PPTX via `OfficeConverter` or a host `DocumentConverter`; XLSX remains recognized but temporarily unsupported), `sources` and `sources-network` (readers for folder, file, link, GitHub, RSS and conversations, with the SSRF guard), `safety` (secret/PII scrubbing applied to every item before `store`), and `legacy-import` (reads a v1 TinyCortex workspace and migrates it into any engine). | +| `tinymemory-integrations` | Everything that talks to the outside world, each behind a feature: `cortex` (default; the CortexDB engine, registered twice as `cortexdb` and `tinyhumans`, plus the registry `list_engines`/`build_engine` and `MemoryConfig`), `documents` and `documents-office` (format sniffing and conversion to markdown, emitting `StoreItem::Document`; PDF/DOCX/PPTX/XLSX via `OfficeConverter` or a host `DocumentConverter`), `sources` and `sources-network` (readers for folder, file, link, GitHub, RSS and conversations, with the SSRF guard), `safety` (secret/PII scrubbing applied to every item before `store`), and `legacy-import` (reads a v1 TinyCortex workspace and migrates it into any engine). | | `tinyredact` | Standalone local secret and personal identifier detection and scrubbing, usable independently of memory integrations. | Earlier designs split the engine, documents, sources, safety, context and