Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(rag): refuse zip parts that inflate past a cap before reading them (#9506)
Thinh Lea25d4db2f5a8
diff --git a/src-tauri/plugins/tauri-plugin-rag/src/constants.rs b/src-tauri/plugins/tauri-plugin-rag/src/constants.rsindex 6cd7d9ff3..3b12cccb8 100644--- a/src-tauri/plugins/tauri-plugin-rag/src/constants.rs+++ b/src-tauri/plugins/tauri-plugin-rag/src/constants.rs@@ -6,3 +6,13 @@/// maximum that setting permits — a smaller value here would wrongly reject/// files the user explicitly allowed (e.g. a 21.5MB file with a 50MB setting).pub const MAX_PARSE_FILE_SIZE: u64 = 200 * 1024 * 1024;++/// Most one zip entry (a docx or pptx XML part, a spreadsheet part) may inflate+/// to, in bytes. `MAX_PARSE_FILE_SIZE` bounds the file on disk, but deflate+/// shrinks repeated bytes about a thousand to one, so a file well under that+/// limit can still unpack to many gigabytes. Real text parts are a few+/// megabytes; this leaves two orders of magnitude of headroom.+pub const MAX_ZIP_ENTRY_SIZE: u64 = 100 * 1024 * 1024;++/// Most all entries of one zip may inflate to together, in bytes.+pub const MAX_ZIP_TOTAL_SIZE: u64 = 256 * 1024 * 1024;diff --git a/src-tauri/plugins/tauri-plugin-rag/src/parser.rs b/src-tauri/plugins/tauri-plugin-rag/src/parser.rsindex 78d579720..68d1aae23 100644--- a/src-tauri/plugins/tauri-plugin-rag/src/parser.rs+++ b/src-tauri/plugins/tauri-plugin-rag/src/parser.rs@@ -1,4 +1,4 @@-use crate::{RagError, MAX_PARSE_FILE_SIZE};+use crate::{RagError, MAX_PARSE_FILE_SIZE, MAX_ZIP_ENTRY_SIZE, MAX_ZIP_TOTAL_SIZE};use std::borrow::Cow;use std::fs;use std::io::{Cursor, Read};@@ -126,6 +126,73 @@ pub fn parse_document(file_path: &str, file_type: &str) -> Result<String, RagErr}}+fn too_large_unpacked(limit: u64) -> RagError {+ RagError::ParseError(format!(+ "This file is larger than {} MB once unpacked",+ limit / (1024 * 1024)+ ))+}++/// Reads a zip entry as text, refusing to inflate more than `limit` bytes; the+/// error names `reported_limit`, which differs from `limit` when a shared+/// budget, not the per-entry cap, is what ran out.+/// The size of the file on disk says little: deflate shrinks repeated bytes+/// about a thousand to one, so a small file can unpack to gigabytes.+fn read_zip_entry_capped(+ entry: impl Read,+ limit: u64,+ reported_limit: u64,+) -> Result<String, RagError> {+ // Bytes first: the cut at `limit + 1` can land inside a multi-byte+ // character, and a UTF-8 error would hide that the entry was too large.+ let mut bytes = Vec::new();+ entry+ .take(limit + 1)+ .read_to_end(&mut bytes)+ .map_err(|e| RagError::ParseError(e.to_string()))?;+ if bytes.len() as u64 > limit {+ return Err(too_large_unpacked(reported_limit));+ }+ String::from_utf8(bytes).map_err(|e| RagError::ParseError(e.to_string()))+}++/// Parts of an xlsx/ods zip that `calamine` never reads, however large:+/// pictures, embedded objects and thumbnails. Everything else may be inflated+/// and parsed (sheet parts are found through relationship targets, which can+/// have any name), so it counts toward the caps.+fn is_unread_spreadsheet_part(name: &str) -> bool {+ let name = name.to_ascii_lowercase();+ ["xl/media/", "xl/embeddings/", "pictures/", "thumbnails/"]+ .iter()+ .any(|dir| name.starts_with(dir))+}++/// For formats `calamine` unpacks itself (xlsx, ods): refuse a zip whose parts+/// declare more than the caps before handing it over. A file that is not a zip+/// (xls) passes through; `calamine` reports its own errors.+fn check_zip_declared_sizes(file_path: &str) -> Result<(), RagError> {+ let Ok(mut zip) = ZipArchive::new(std::fs::File::open(file_path)?) else {+ return Ok(());+ };+ let mut total: u64 = 0;+ for i in 0..zip.len() {+ let Ok(entry) = zip.by_index_raw(i) else {+ continue;+ };+ if entry.name().is_ok_and(|n| is_unread_spreadsheet_part(&n)) {+ continue;+ }+ if entry.size() > MAX_ZIP_ENTRY_SIZE {+ return Err(too_large_unpacked(MAX_ZIP_ENTRY_SIZE));+ }+ total = total.saturating_add(entry.size());+ if total > MAX_ZIP_TOTAL_SIZE {+ return Err(too_large_unpacked(MAX_ZIP_TOTAL_SIZE));+ }+ }+ Ok(())+}+fn parse_docx(file_path: &str) -> Result<String, RagError> {let metadata = std::fs::metadata(file_path)?;if metadata.len() > MAX_PARSE_FILE_SIZE {@@ -135,14 +202,11 @@ fn parse_docx(file_path: &str) -> Result<String, RagError> {let mut zip = ZipArchive::new(file).map_err(|e| RagError::ParseError(e.to_string()))?;// Standard DOCX stores document text at word/document.xml- let mut doc_xml = match zip.by_name("word/document.xml") {+ let doc_xml = match zip.by_name("word/document.xml") {Ok(f) => f,Err(_) => return Err(RagError::ParseError("document.xml not found".into())),};- let mut xml_content = String::new();- doc_xml- .read_to_string(&mut xml_content)- .map_err(|e| RagError::ParseError(e.to_string()))?;+ let xml_content = read_zip_entry_capped(doc_xml, MAX_ZIP_ENTRY_SIZE, MAX_ZIP_ENTRY_SIZE)?;// Parse XML and extract text from w:t nodes; add newlines on w:p boundarieslet mut reader = Reader::from_str(&xml_content);@@ -335,6 +399,7 @@ fn parse_spreadsheet(file_path: &str) -> Result<String, RagError> {if metadata.len() > MAX_PARSE_FILE_SIZE {return Err(RagError::ParseError("File too large (max 200MB)".to_string()));}+ check_zip_declared_sizes(file_path)?;let mut workbook = open_workbook_auto(file_path).map_err(|e| RagError::ParseError(e.to_string()))?;let is_1904 = uses_1904_epoch(&workbook);@@ -380,10 +445,18 @@ fn parse_pptx(file_path: &str) -> Result<String, RagError> {slides.sort();let mut output = String::new();+ let mut budget = MAX_ZIP_TOTAL_SIZE;for slide_name in slides {- let mut file = zip.by_name(&slide_name).map_err(|e| RagError::ParseError(e.to_string()))?;- let mut xml = String::new();- file.read_to_string(&mut xml).map_err(|e| RagError::ParseError(e.to_string()))?;+ let file = zip.by_name(&slide_name).map_err(|e| RagError::ParseError(e.to_string()))?;+ // Once less than a whole entry's worth is left, it is the total+ // that a further slide would overrun, so that is the limit to report.+ let (limit, reported) = if budget < MAX_ZIP_ENTRY_SIZE {+ (budget, MAX_ZIP_TOTAL_SIZE)+ } else {+ (MAX_ZIP_ENTRY_SIZE, MAX_ZIP_ENTRY_SIZE)+ };+ let xml = read_zip_entry_capped(file, limit, reported)?;+ budget -= xml.len() as u64;output.push_str(&extract_pptx_text(&xml));output.push_str("\n\n");}@@ -629,6 +702,116 @@ mod tests {assert!(matches!(out, Err(RagError::ParseError(_))));}+ /// A tiny zip whose entries each inflate to the given number of bytes of+ /// spaces: the shape of a decompression bomb (deflate shrinks it about a+ /// thousand to one).+ fn bomb_zip_entries(name: &str, entries: &[(&str, u64)]) -> std::path::PathBuf {+ let path = std::env::temp_dir().join(format!("jan-rag-{}-{name}", std::process::id()));+ let mut zw = zip::ZipWriter::new(fs::File::create(&path).unwrap());+ let chunk = vec![b' '; 1024 * 1024];+ for (entry, len) in entries {+ zw.start_file(*entry, zip::write::SimpleFileOptions::default())+ .unwrap();+ let mut left = *len;+ while left > 0 {+ let n = left.min(chunk.len() as u64) as usize;+ zw.write_all(&chunk[..n]).unwrap();+ left -= n as u64;+ }+ }+ zw.finish().unwrap();+ path+ }++ fn bomb_zip(name: &str, entry: &str, len: u64) -> std::path::PathBuf {+ bomb_zip_entries(name, &[(entry, len)])+ }++ fn refused_as_too_large(out: Result<String, RagError>) -> bool {+ matches!(out, Err(RagError::ParseError(m)) if m.contains("unpacked"))+ }++ #[test]+ fn docx_part_that_inflates_past_the_cap_is_refused() {+ let path = bomb_zip("bomb.docx", "word/document.xml", MAX_ZIP_ENTRY_SIZE + 1);+ let out = parse_docx(path.to_str().unwrap());+ let _ = fs::remove_file(&path);+ assert!(refused_as_too_large(out));+ }++ #[test]+ fn pptx_slide_that_inflates_past_the_cap_is_refused() {+ let path = bomb_zip("bomb.pptx", "ppt/slides/slide1.xml", MAX_ZIP_ENTRY_SIZE + 1);+ let out = parse_pptx(path.to_str().unwrap());+ let _ = fs::remove_file(&path);+ assert!(refused_as_too_large(out));+ }++ #[test]+ fn spreadsheet_with_a_part_that_inflates_past_the_cap_is_refused() {+ let path = bomb_zip("bomb.xlsx", "docProps/custom.xml", MAX_ZIP_ENTRY_SIZE + 1);+ let out = parse_spreadsheet(path.to_str().unwrap());+ let _ = fs::remove_file(&path);+ assert!(refused_as_too_large(out));+ }++ #[test]+ fn docx_part_exactly_at_the_cap_is_still_read() {+ let path = bomb_zip("edge.docx", "word/document.xml", MAX_ZIP_ENTRY_SIZE);+ let out = parse_docx(path.to_str().unwrap());+ let _ = fs::remove_file(&path);+ assert!(!refused_as_too_large(out));+ }++ #[test]+ fn pptx_slides_that_together_inflate_past_the_total_are_refused_naming_the_total() {+ const SLIDE: u64 = 90 * 1024 * 1024;+ const _: () = assert!(SLIDE < MAX_ZIP_ENTRY_SIZE && 3 * SLIDE > MAX_ZIP_TOTAL_SIZE);+ let path = bomb_zip_entries(+ "total.pptx",+ &[+ ("ppt/slides/slide1.xml", SLIDE),+ ("ppt/slides/slide2.xml", SLIDE),+ ("ppt/slides/slide3.xml", SLIDE),+ ],+ );+ let out = parse_pptx(path.to_str().unwrap());+ let _ = fs::remove_file(&path);+ let total_mb = MAX_ZIP_TOTAL_SIZE / (1024 * 1024);+ assert!(+ matches!(&out, Err(RagError::ParseError(m)) if m.contains(&format!("{total_mb} MB"))),+ "{out:?}"+ );+ }++ #[test]+ fn spreadsheet_part_without_an_xml_extension_still_counts() {+ // Sheet parts are found through relationship targets and may have any+ // name, so only known media paths are exempt.+ for name in ["xl/worksheets/sheet1", "xl/worksheets/sheet1.XML"] {+ let path = bomb_zip("noext.xlsx", name, MAX_ZIP_ENTRY_SIZE + 1);+ let out = parse_spreadsheet(path.to_str().unwrap());+ let _ = fs::remove_file(&path);+ assert!(refused_as_too_large(out), "{name}");+ }+ }++ #[test]+ fn spreadsheet_media_that_inflates_past_the_cap_is_not_counted() {+ // calamine never reads media, so a large one is no reason to refuse.+ let path = bomb_zip("media.xlsx", "xl/media/image1.png", MAX_ZIP_ENTRY_SIZE + 1);+ let out = parse_spreadsheet(path.to_str().unwrap());+ let _ = fs::remove_file(&path);+ assert!(!refused_as_too_large(out));+ }++ #[test]+ fn an_oversize_entry_is_reported_as_too_large_even_when_the_cut_splits_a_character() {+ // "é" is two bytes, so a cut after 3 bytes lands inside the second one.+ let out = read_zip_entry_capped(std::io::Cursor::new("éééé".as_bytes()), 2, 2);+ assert!(refused_as_too_large(out));+ }+#[test]fn csv_cells_with_delimiters_quotes_or_newlines_are_quoted() {let path = std::env::temp_dir().join(format!(