From 72778aba99e6c9796394677beb69d91d5e7aa06d Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 11 Nov 2026 09:04:34 +0000 Subject: [PATCH] model, engine, xlsx: protection passwords keep both file forms; one shared base64 A sheet or workbook protection password set in GridCraft is now kept as PasswordHash::Both: Excel's salted SHA-512 hash and the unsalted SHA-256 digest OpenDocument stores (PasswordHash::Sha256Digest). Unprotecting verifies it; XLSX writes the form it can store, and a digest alone keeps its protection without the password. Edit ranges keep only the SHA-512 form. The public gridcraft_model::b64 (with a bounded decode_limited) replaces the private base64 copies in engine io.rs, xlsx crypto.rs and xlsx testing.rs. --- crates/engine/src/cmd/review.rs | 27 ++++++-- crates/engine/src/io.rs | 35 +---------- crates/engine/src/tests.rs | 36 +++++++++++ crates/model/src/b64.rs | 40 ++++++++---- crates/model/src/lib.rs | 2 +- crates/model/src/password.rs | 92 +++++++++++++++++++++++++++- crates/xlsx/src/crypto.rs | 21 +------ crates/xlsx/src/sheet_write/parts.rs | 4 ++ crates/xlsx/src/testing.rs | 10 +-- crates/xlsx/src/tests/roundtrip.rs | 23 +++++++ docs/file-format-parity.md | 5 +- 11 files changed, 211 insertions(+), 84 deletions(-) diff --git a/crates/engine/src/cmd/review.rs b/crates/engine/src/cmd/review.rs index de9c98ecd..a1760868c 100644 --- a/crates/engine/src/cmd/review.rs +++ b/crates/engine/src/cmd/review.rs @@ -161,7 +161,7 @@ fn protect_sheet(s: &mut Session, p: &Json) -> Result { }; let d = s.doc()?; let what = d.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default(); - let prot = SheetProtection { password: str_param(p, "password").filter(|x| !x.is_empty()).map(|pw| new_password_hash(d, &what, pw)), ..prot }; + let prot = SheetProtection { password: str_param(p, "password").filter(|x| !x.is_empty()).map(|pw| new_protection_hash(d, &what, pw)), ..prot }; edit(s, |cx| { cx.sheet_mut(sheet)?.protection = Some(prot.clone()); Ok(Json::Null) @@ -187,13 +187,25 @@ fn unprotect_sheet(s: &mut Session, p: &Json) -> Result { }) } -/// A new Excel-compatible (SHA-512, salted) hash of `pw`. The salt mixes `what` is protected -/// with the document, a counter and the clock, so equal passwords get different hashes. +/// A new hash of a sheet's or the workbook's protection password, in every form a file keeps +/// (Excel's salted SHA-512 and OpenDocument's SHA-256 digest), so it survives saving in either +/// format. +fn new_protection_hash(d: &DocState, what: &str, pw: &str) -> PasswordHash { + PasswordHash::new_for_files(pw, &new_salt(d, what)) +} + +/// A new Excel-compatible (SHA-512, salted) hash of `pw`: edit ranges only have this form. fn new_password_hash(d: &DocState, what: &str, pw: &str) -> PasswordHash { + PasswordHash::new_sha512(pw, &new_salt(d, what)) +} + +/// A salt mixing `what` is protected with the document, a counter and the clock, so equal +/// passwords get different hashes. +fn new_salt(d: &DocState, what: &str) -> [u8; 16] { static SALT_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let n = SALT_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let seed = format!("{what}\u{0}{n}\u{0}{}\u{0}{}", d.uid, gridcraft_calc::now_serial().to_bits()); - PasswordHash::new_sha512(pw, &gridcraft_model::password::salt_from(seed.as_bytes())) + gridcraft_model::password::salt_from(seed.as_bytes()) } fn range_text(r: &EditRange) -> String { @@ -312,7 +324,7 @@ fn protect_workbook(s: &mut Session, p: &Json) -> Result { return Ok(json!({"on": on})); } let password = if on { - str_param(p, "password").filter(|pw| !pw.is_empty()).map(|pw| new_password_hash(d, "workbook", pw)) + str_param(p, "password").filter(|pw| !pw.is_empty()).map(|pw| new_protection_hash(d, "workbook", pw)) } else { if let Some(h) = &d.wb.structure_password && !h.verify(str_param(p, "password").unwrap_or("")).map_err(EngineError::Other)? @@ -429,7 +441,10 @@ mod tests { let mut s = book(); s.execute("review.protectSheet", json!({"password": "pa55"})).unwrap(); let prot = s.doc().unwrap().wb.active().unwrap().protection.clone().unwrap(); - assert!(matches!(&prot.password, Some(PasswordHash::Iterated { algorithm, .. }) if algorithm == "SHA-512")); + // Kept in both forms: Excel's salted SHA-512 and OpenDocument's SHA-256 digest. + let password = prot.password.as_ref().unwrap(); + assert!(matches!(password.excel(), Some(PasswordHash::Iterated { algorithm, .. }) if algorithm == "SHA-512")); + assert_eq!(password.odf_key(), PasswordHash::new_sha256_digest("pa55").odf_key()); assert!(s.execute("review.unprotectSheet", json!({})).is_err()); assert!(s.execute("review.unprotectSheet", json!({"password": "pass"})).is_err()); // Protecting again can't swap the password out from under it. diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 602c17ccd..032347abf 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -972,43 +972,14 @@ pub fn write_file(path: &str, _bytes: &[u8]) -> Result<()> { Err(EngineError::Other(format!("{path}: no file system in the browser"))) } -const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - pub fn base64_encode(data: &[u8]) -> String { - let mut out = String::with_capacity(data.len().div_ceil(3) * 4); - for chunk in data.chunks(3) { - let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)]; - let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32; - for i in 0..4 { - if i <= chunk.len() { - out.push(B64[((n >> (18 - 6 * i)) & 63) as usize] as char); - } else { - out.push('='); - } - } - } - out + gridcraft_model::b64::encode(data) } +/// Base64, or a `data:` URL's base64 payload. pub fn base64_decode(s: &str) -> Option> { let s = s.split_once(',').filter(|(h, _)| h.starts_with("data:")).map(|(_, b)| b).unwrap_or(s); - let mut out = Vec::with_capacity(s.len() / 4 * 3); - let mut buf = 0u32; - let mut bits = 0; - for c in s.bytes() { - if c == b'=' || c.is_ascii_whitespace() { - continue; - } - let v = B64.iter().position(|&x| x == c)? as u32; - buf = (buf << 6) | v; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push((buf >> bits) as u8); - buf &= (1 << bits) - 1; - } - } - Some(out) + gridcraft_model::b64::decode(s) } /// Pixel size of a PNG or JPEG from its header. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 75e5eac96..e570d805e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5649,3 +5649,39 @@ fn pivot_new_sheet_destination_respects_workbook_structure_protection() { } assert!(s.execute("insert.pivotTable", json!({"source": "A1:B3", "location": "New"})).is_err()); } + +/// A password set in GridCraft is kept in every form a file stores; XLSX writes its Excel form, +/// so a sheet or workbook password survives saving and reopening and still unprotects. +#[test] +fn passwords_set_in_gridcraft_survive_xlsx_saving() { + let mut s = s(); + s.execute("review.protectSheet", json!({"password": "pa55"})).unwrap(); + s.execute("review.protectWorkbook", json!({"on": true, "password": "b00k"})).unwrap(); + let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap(); + let mut t = super::tests::s(); + t.execute("file.open", json!({"name": "book.xlsx", "base64": saved["base64"]})).unwrap(); + assert!(t.execute("review.unprotectSheet", json!({})).is_err()); + assert!(t.execute("review.unprotectSheet", json!({"password": "nope"})).is_err()); + t.execute("review.unprotectSheet", json!({"password": "pa55"})).unwrap(); + assert!(t.execute("review.protectWorkbook", json!({"on": false, "password": "nope"})).is_err()); + t.execute("review.protectWorkbook", json!({"on": false, "password": "b00k"})).unwrap(); + assert!(!t.doc().unwrap().wb.protected_structure); +} + +/// A password held only as a SHA-256 digest (as OpenDocument stores it) unprotects with the +/// password; XLSX has no form for it, so saving keeps the protection without the password. +#[test] +fn sha256_digest_passwords_unprotect_and_save_to_xlsx_without_the_password() { + let mut s = s(); + s.execute("review.protectSheet", json!({})).unwrap(); + let digest = gridcraft_model::PasswordHash::new_sha256_digest("pa55"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().protection.as_mut().unwrap().password = Some(digest); + let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap(); + assert!(s.execute("review.unprotectSheet", json!({"password": "nope"})).is_err()); + s.execute("review.unprotectSheet", json!({"password": "pa55"})).unwrap(); + let mut t = super::tests::s(); + t.execute("file.open", json!({"name": "book.xlsx", "base64": saved["base64"]})).unwrap(); + let prot = t.doc().unwrap().wb.sheets[0].protection.clone().unwrap(); + assert_eq!(prot.password, None); + t.execute("review.unprotectSheet", json!({})).unwrap(); +} diff --git a/crates/model/src/b64.rs b/crates/model/src/b64.rs index f36ede104..00d49ffc9 100644 --- a/crates/model/src/b64.rs +++ b/crates/model/src/b64.rs @@ -1,17 +1,18 @@ -//! Minimal base64 for serde (image bytes in JSON). +//! Standard base64 (RFC 4648 §4): for serde (image bytes in JSON), and for every crate that +//! reads or writes it in a file (encryption descriptors, password hashes, `data:` URLs). use serde::{Deserialize, Deserializer, Serializer}; -const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; pub fn encode(data: &[u8]) -> String { let mut out = String::with_capacity(data.len().div_ceil(3) * 4); for chunk in data.chunks(3) { let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)]; - let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32; - for i in 0..4 { + let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + for (i, shift) in [18u32, 12, 6, 0].iter().enumerate() { if i <= chunk.len() { - out.push(A[((n >> (18 - 6 * i)) & 63) as usize] as char); + out.push(char::from(ALPHABET.get(((n >> shift) & 63) as usize).copied().unwrap_or(b'A'))); } else { out.push('='); } @@ -20,21 +21,26 @@ pub fn encode(data: &[u8]) -> String { out } +/// Decodes base64, whitespace and padding ignored; `None` for any other character. pub fn decode(s: &str) -> Option> { - let mut out = Vec::with_capacity(s.len() / 4 * 3); - let mut buf = 0u32; - let mut bits = 0; - for c in s.bytes() { - if c == b'=' || c.is_ascii_whitespace() { - continue; - } - let v = A.iter().position(|&x| x == c)? as u32; + decode_limited(s, usize::MAX) +} + +/// [`decode`], also `None` when the output would pass `limit` bytes (for input from a file). +pub fn decode_limited(s: &str, limit: usize) -> Option> { + let mut out = Vec::with_capacity((s.len() / 4 * 3).min(limit).min(1 << 20)); + let (mut buf, mut bits) = (0u32, 0u32); + for c in s.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=') { + let v = ALPHABET.iter().position(|a| *a == c)? as u32; buf = (buf << 6) | v; bits += 6; if bits >= 8 { bits -= 8; out.push((buf >> bits) as u8); buf &= (1 << bits) - 1; + if out.len() > limit { + return None; + } } } Some(out) @@ -89,6 +95,14 @@ pub mod opt { #[cfg(test)] mod tests { + #[test] + fn decoding_is_bounded_and_strict() { + assert_eq!(super::decode_limited("AAAA", 3).as_deref(), Some(&[0u8, 0, 0][..])); + assert_eq!(super::decode_limited("AAAAAAAA", 3), None); + assert_eq!(super::decode("AA!A"), None); + assert_eq!(super::decode(" QU Jj\n").as_deref(), Some(&b"ABc"[..])); + } + #[test] fn roundtrip() -> Result<(), Box> { for data in [&b""[..], b"a", b"ab", b"abc", b"hello world", &[0, 255, 128, 7]] { diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 35cfa315f..0b1cb77fd 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -4,7 +4,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] -mod b64; +pub mod b64; pub mod cell; mod cellmap; pub mod features; diff --git a/crates/model/src/password.rs b/crates/model/src/password.rs index f46de4b44..d8c238efb 100644 --- a/crates/model/src/password.rs +++ b/crates/model/src/password.rs @@ -1,6 +1,8 @@ //! Excel-compatible password hashes for protection (ECMA-376 Part 1 §18.2.29 and §18.3.1.66 //! attribute sets): the legacy 16-bit hash (`password="CC1A"`) and the iterated, salted hash -//! (`algorithmName`, `hashValue`, `saltValue`, `spinCount`). Protection is a convenience, not +//! (`algorithmName`, `hashValue`, `saltValue`, `spinCount`); and the unsalted SHA-256 digest +//! OpenDocument stores (`table:protection-key`). A password set in GridCraft keeps both an +//! Excel form and the SHA-256 one, so it survives saving in either format. Protection is a convenience, not //! security, but verification really checks the password: an unsupported variant is refused, //! never accepted. @@ -19,6 +21,12 @@ pub enum PasswordHash { Legacy(u16), /// An iterated, salted hash as stored in the file: algorithm name, base64 hash and salt. Iterated { algorithm: String, hash: String, salt: String, spin_count: u32 }, + /// The base64 SHA-256 digest of the password's UTF-8 bytes, unsalted: the form OpenDocument + /// stores (ODF 1.3 part 3 §19.699, `table:protection-key`). + Sha256Digest(String), + /// A password set in GridCraft, kept in the form each file format stores: Excel's hash + /// (which verifies it) and the SHA-256 digest. + Both { excel: Box, odf: String }, } impl PasswordHash { @@ -33,11 +41,49 @@ impl PasswordHash { } } + /// A SHA-256 digest of a new password (the form OpenDocument stores). + pub fn new_sha256_digest(password: &str) -> PasswordHash { + PasswordHash::Sha256Digest(sha256_digest(password)) + } + + /// A new password in every form a file keeps: Excel's (SHA-512, salted) and the SHA-256 + /// digest, so it survives saving in either format. + pub fn new_for_files(password: &str, salt: &[u8]) -> PasswordHash { + PasswordHash::Both { excel: Box::new(PasswordHash::new_sha512(password, salt)), odf: sha256_digest(password) } + } + + /// The hash as Excel stores it, if it has that form. Not recursive: a `Both` read from a + /// damaged file that nests another `Both` has no Excel form. + pub fn excel(&self) -> Option<&PasswordHash> { + match self { + PasswordHash::Legacy(_) | PasswordHash::Iterated { .. } => Some(self), + PasswordHash::Sha256Digest(_) => None, + PasswordHash::Both { excel, .. } => match excel.as_ref() { + h @ (PasswordHash::Legacy(_) | PasswordHash::Iterated { .. }) => Some(h), + PasswordHash::Sha256Digest(_) | PasswordHash::Both { .. } => None, + }, + } + } + + /// The SHA-256 digest (base64), if it has that form. + pub fn odf_key(&self) -> Option<&str> { + match self { + PasswordHash::Sha256Digest(k) | PasswordHash::Both { odf: k, .. } => Some(k), + PasswordHash::Legacy(_) | PasswordHash::Iterated { .. } => None, + } + } + /// Whether `password` matches. `Err` when the hash can't be checked (unsupported algorithm, /// broken base64, spin count over [`MAX_SPIN_COUNT`]). pub fn verify(&self, password: &str) -> Result { match self { PasswordHash::Legacy(h) => Ok(legacy_hash(password) == *h), + // Checked through its Excel form (one level only: see `excel`), else its digest. + PasswordHash::Both { odf, .. } => match self.excel() { + Some(excel) => excel.verify(password), + None => verify_sha256_digest(odf, password), + }, + PasswordHash::Sha256Digest(hash) => verify_sha256_digest(hash, password), PasswordHash::Iterated { algorithm, hash, salt, spin_count } => { if algorithm.is_empty() { return Err("the stored password hash is damaged".into()); @@ -60,6 +106,16 @@ impl PasswordHash { } } +/// The base64 SHA-256 digest of `password`'s UTF-8 bytes. +fn sha256_digest(password: &str) -> String { + crate::b64::encode(&sha2::Sha256::digest(password.as_bytes())) +} + +fn verify_sha256_digest(hash: &str, password: &str) -> Result { + let want = crate::b64::decode_limited(hash, 64).ok_or_else(|| "the stored password hash is damaged".to_string())?; + Ok(sha2::Sha256::digest(password.as_bytes()).as_slice() == want.as_slice()) +} + /// A 16-byte salt derived from `seed` (callers mix in what varies: names, a counter, the clock). pub fn salt_from(seed: &[u8]) -> [u8; 16] { let h = sha2::Sha512::digest(seed); @@ -132,4 +188,38 @@ mod tests { assert!(broken.verify("s3cret").is_err()); Ok(()) } + + #[test] + fn sha256_digests_verify() -> Result<(), Box> { + // SHA-256 of "abc", base64. + let h = PasswordHash::Sha256Digest("ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=".into()); + assert_eq!(h, PasswordHash::new_sha256_digest("abc")); + assert!(h.verify("abc")?); + assert!(!h.verify("abd")?); + assert!(PasswordHash::Sha256Digest("!!".into()).verify("abc").is_err()); + assert_eq!(h.excel(), None); + assert_eq!(h.odf_key(), Some("ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=")); + Ok(()) + } + + #[test] + fn passwords_set_in_gridcraft_keep_both_forms() -> Result<(), Box> { + let h = PasswordHash::new_for_files("pa55", b"0123456789abcdef"); + assert_eq!(h.excel(), Some(&PasswordHash::new_sha512("pa55", b"0123456789abcdef"))); + assert_eq!(h.odf_key(), PasswordHash::new_sha256_digest("pa55").odf_key()); + assert!(h.verify("pa55")?); + assert!(!h.verify("pass")?); + // Each form checks the password on its own. + assert!(h.excel().ok_or("no Excel form")?.verify("pa55")?); + assert!(PasswordHash::Sha256Digest(h.odf_key().ok_or("no digest")?.into()).verify("pa55")?); + // A nested `Both` (only a damaged file makes one) has no Excel form and falls back to its digest. + let nested = PasswordHash::Both { excel: Box::new(h.clone()), odf: PasswordHash::new_sha256_digest("x").odf_key().unwrap_or("").into() }; + assert_eq!(nested.excel(), None); + assert!(nested.verify("x")?); + assert!(!nested.verify("pa55")?); + // The JSON form round-trips. + let back: PasswordHash = serde_json::from_str(&serde_json::to_string(&h)?)?; + assert_eq!(back, h); + Ok(()) + } } diff --git a/crates/xlsx/src/crypto.rs b/crates/xlsx/src/crypto.rs index bf495d747..46d9447f3 100644 --- a/crates/xlsx/src/crypto.rs +++ b/crates/xlsx/src/crypto.rs @@ -512,26 +512,7 @@ fn agile(xml: &[u8], package: &[u8], password: &str) -> Result, DecryptE /// Standard base64 (whitespace ignored), as Agile's XML uses for every binary value. fn base64(s: &str) -> Result, DecryptError> { - let mut out = Vec::with_capacity(s.len() / 4 * 3); - let (mut buf, mut bits) = (0u32, 0u32); - for c in s.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=') { - let v = match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' => 62, - b'/' => 63, - _ => return Err(malformed("invalid base64")), - }; - buf = (buf << 6) | u32::from(v); - bits += 6; - if bits >= 8 { - bits -= 8; - out.push((buf >> bits) as u8); - buf &= (1 << bits) - 1; - } - } - Ok(out) + gridcraft_model::b64::decode(s).ok_or_else(|| malformed("invalid base64")) } #[cfg(test)] diff --git a/crates/xlsx/src/sheet_write/parts.rs b/crates/xlsx/src/sheet_write/parts.rs index 040e2b9bd..9abb95912 100644 --- a/crates/xlsx/src/sheet_write/parts.rs +++ b/crates/xlsx/src/sheet_write/parts.rs @@ -317,7 +317,11 @@ pub(super) fn threaded_xml(sheet: &Sheet, ids: &BTreeMap>, /// [`crate::sheet_read::read_password`]). pub(crate) fn password_attrs(h: &gridcraft_model::PasswordHash, prefix: &str) -> String { let name = |base: &str| crate::sheet_read::password_attr(prefix, base); + // A SHA-256 digest alone (OpenDocument's form) has no Excel form: the protection is kept + // without its password. A password set in GridCraft writes its Excel form. + let Some(h) = h.excel() else { return String::new() }; match h { + gridcraft_model::PasswordHash::Sha256Digest(_) | gridcraft_model::PasswordHash::Both { .. } => String::new(), gridcraft_model::PasswordHash::Legacy(h) => format!(" {}=\"{h:04X}\"", name("password")), gridcraft_model::PasswordHash::Iterated { algorithm, hash, salt, spin_count } => format!( " {}=\"{}\" {}=\"{}\" {}=\"{}\" {}=\"{spin_count}\"", diff --git a/crates/xlsx/src/testing.rs b/crates/xlsx/src/testing.rs index a82283644..4ace77ed1 100644 --- a/crates/xlsx/src/testing.rs +++ b/crates/xlsx/src/testing.rs @@ -192,15 +192,7 @@ fn encrypt_cbc(key: &[u8], iv: &[u8], data: &[u8]) -> Vec { } fn base64_encode(b: &[u8]) -> String { - const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut s = String::new(); - for c in b.chunks(3) { - let n = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); - for i in 0..4 { - s.push(if i <= c.len() { T[(n >> (18 - 6 * i)) as usize & 63] as char } else { '=' }); - } - } - s + gridcraft_model::b64::encode(b) } fn package(size: usize, body: Vec) -> Vec { diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 4eb6c3cfe..3121c7e65 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1741,3 +1741,26 @@ fn remove_personal_information_is_kept_and_honoured() { assert_eq!(book.child("workbookPr").and_then(|p| p.attr("filterPrivacy")), None); assert!(String::from_utf8(pkg.read("docProps/core.xml").unwrap().unwrap()).unwrap().contains("Jane Example")); } + +/// A password set in GridCraft (both forms) is written as its Excel form, which reads back and +/// verifies; a SHA-256 digest alone has no XLSX form, so its protection is kept without it. +#[test] +fn protection_passwords_write_the_form_xlsx_stores() { + let mut wb = Workbook::new(); + wb.protected_structure = true; + wb.structure_password = Some(PasswordHash::new_for_files("b00k", b"0123456789abcdef")); + let both = PasswordHash::new_for_files("pa55", b"fedcba9876543210"); + let sheet = wb.sheet_mut(0).unwrap(); + sheet.protection = Some(SheetProtection { password: Some(both.clone()), ..Default::default() }); + let mut digest_only = Sheet::new("Digest"); + digest_only.protection = Some(SheetProtection { password: Some(PasswordHash::new_sha256_digest("pa55")), ..Default::default() }); + wb.sheets.push(Arc::new(digest_only)); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + assert_eq!(back.structure_password.as_ref(), wb.structure_password.as_ref().and_then(PasswordHash::excel)); + assert!(back.structure_password.as_ref().unwrap().verify("b00k").unwrap()); + let read = back.sheets[0].protection.as_ref().and_then(|p| p.password.clone()); + assert_eq!(read.as_ref(), both.excel()); + assert!(read.unwrap().verify("pa55").unwrap()); + let digest = back.sheets[1].protection.as_ref().unwrap(); + assert_eq!(digest.password, None); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d2660dde0..ed8d0afb3 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-03 · **Change:** minor (a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-11 · **Change:** minor (a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -78,7 +78,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real |---|---|---|---|---|---| | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection (a sheet or workbook password set in GridCraft is kept as its salted SHA-512 hash, which XLSX stores, and as the SHA-256 digest OpenDocument stores; a digest alone has no XLSX form, so saving keeps that protection without its password), Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), pictures in headers and footers (`&G`, #1257: their VML drawing and images are written back unchanged; they are not shown, and can't be inserted), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | @@ -158,6 +158,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | A sheet or workbook protection password set in GridCraft is kept both as Excel's salted SHA-512 hash and as a SHA-256 digest (the form OpenDocument stores); XLSX writes the SHA-512 form, and a digest-only password keeps its protection without the password; one shared base64 implementation | | 2026-11-03 | minor | SYLK (`.slk`) import: values, R1C1 formulas as A1 (shared formulas too) with cached results, number formats and column widths; import only (#1481) | | 2026-11-03 | minor | Opening a web page (HTML) reads its first table as a sheet, whatever the file is called: a web app's "Export to Excel" saved as `.xls` no longer opens as lines of markup. Values read as in a CSV (or as text with `csvAsText`), `` cells are bold and centred, `` names the sheet, and a page not named `.htm`/`.html` opens with a warning (#3166) | | 2026-11-03 | minor | XLSX `` (Remove personal information from file properties on save) is read and written back, and while it is on GridCraft saves no author (`dc:creator`) and no company, as Excel leaves them empty (#3089, file part) |