diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index aef368179..b9ebec35b 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -36,6 +36,11 @@ impl FileKind { pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec)> { let kind = FileKind::from_path(name); let sniffed = gridcraft_xlsx::sniff(bytes); + if sniffed == gridcraft_xlsx::Format::Encrypted { + return Err(EngineError::Other(format!( + "'{name}' is password-protected. GridCraft can't open encrypted workbooks yet; remove the password in Excel and try again." + ))); + } if sniffed == gridcraft_xlsx::Format::Xlsx || kind == Some(FileKind::Xlsx) { let (wb, report) = gridcraft_xlsx::read_xlsx(bytes).map_err(|e| EngineError::Other(format!("We can't open '{name}': {e}")))?; return Ok((wb, report.warnings)); @@ -244,3 +249,18 @@ pub fn image_size(data: &[u8]) -> Option<(u32, u32)> { } None } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encrypted_workbook_is_reported_not_misread() { + // A CFB/OLE2 header: Excel's password-protected container. + let cfb = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1, 0, 0, 0, 0]; + let err = open_bytes("secret.xlsx", &cfb).unwrap_err(); + let msg = err.to_string(); + assert!(msg.contains("password-protected"), "got: {msg}"); + assert!(!msg.contains("zip"), "must not surface the zip error: {msg}"); + } +} diff --git a/crates/xlsx/src/lib.rs b/crates/xlsx/src/lib.rs index 7c724763a..5ee9bd787 100644 --- a/crates/xlsx/src/lib.rs +++ b/crates/xlsx/src/lib.rs @@ -93,6 +93,7 @@ impl Default for CsvOptions { pub enum Format { Xlsx, Csv, + Encrypted, Unknown, } @@ -101,6 +102,10 @@ pub fn sniff(bytes: &[u8]) -> Format { if bytes.starts_with(b"PK\x03\x04") || bytes.starts_with(b"PK\x05\x06") || bytes.starts_with(b"PK\x07\x08") { return Format::Xlsx; } + // CFB/OLE2 compound file: Excel password-protected files. + if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) { + return Format::Encrypted; + } if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) || bytes.starts_with(&[0xEF, 0xBB, 0xBF]) { return Format::Csv; } diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index 451801fbd..125924107 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -105,6 +105,8 @@ fn writing() { fn sniffing_formats() { assert_eq!(sniff(b"PK\x03\x04rest"), Format::Xlsx); assert_eq!(sniff(b"a,b\n1,2"), Format::Csv); + // An Excel password-protected file is a CFB/OLE2 compound file, not a zip. + assert_eq!(sniff(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1, 0, 0]), Format::Encrypted); assert_eq!(sniff(&[0xD0, 0xCF, 0x11, 0xE0, 0, 0, 1, 2]), Format::Unknown); assert_eq!(sniff(b""), Format::Unknown); assert_eq!(sniff(&[0xFF, 0xFE, b'a', 0]), Format::Csv);