diff --git a/crates/engine/src/cmd/review.rs b/crates/engine/src/cmd/review.rs index 7eafa26db..56fb3ee38 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| { // FORMULATEXT reads a sheet's protection: its results are recalculated. cx.recalc_all = true; @@ -192,13 +192,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 { @@ -317,7 +329,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)? @@ -449,7 +461,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 e60efe7f9..0f2dd7828 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -1143,43 +1143,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 3c87e2f8d..691b81fed 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7430,6 +7430,45 @@ 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(); + // The workbook password, like the sheet's, also keeps OpenDocument's SHA-256 digest. + let book = s.doc().unwrap().wb.structure_password.clone().unwrap(); + assert_eq!(book.odf_key(), gridcraft_model::PasswordHash::new_sha256_digest("b00k").odf_key()); + 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(); +} + /// Renaming a sheet renames a PivotTable's source to it, and the PivotTable still refreshes. #[test] fn sheet_rename_renames_a_pivot_source() { diff --git a/crates/model/src/b64.rs b/crates/model/src/b64.rs index f36ede104..41fb3c201 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,39 @@ pub fn encode(data: &[u8]) -> String { out } +/// The 6-bit value of a base64 character (inverse of [`ALPHABET`]). +fn value(c: u8) -> Option { + 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 None, + }; + Some(u32::from(v)) +} + +/// 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 = value(c)?; 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 +108,18 @@ 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"[..])); + // The lookup is the alphabet's inverse, and nothing else decodes. + for c in 0..=u8::MAX { + assert_eq!(super::value(c), super::ALPHABET.iter().position(|a| *a == c).map(|i| i as u32), "{c}"); + } + } + #[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/features/print.rs b/crates/model/src/features/print.rs index c4cf82bad..bbceaecff 100644 --- a/crates/model/src/features/print.rs +++ b/crates/model/src/features/print.rs @@ -199,8 +199,8 @@ impl Default for PrintSettings { #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct SheetProtection { - /// Hash of the password (Excel-compatible, written to XLSX `sheetProtection`; never the - /// password itself). + /// Hash of the password, never the password itself. XLSX `sheetProtection` writes its Excel + /// form ([`crate::PasswordHash::excel`]); a digest alone has none and is not written there. #[serde(default, skip_serializing_if = "Option::is_none")] pub password: Option, /// The internal hash older GridCraft JSON workbooks stored ([`password_hash`]); still diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 9522e4e3d..9c3377665 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..aa28ad97c 100644 --- a/crates/model/src/password.rs +++ b/crates/model/src/password.rs @@ -1,8 +1,10 @@ //! 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 -//! security, but verification really checks the password: an unsupported variant is refused, -//! never accepted. +//! (`algorithmName`, `hashValue`, `saltValue`, `spinCount`); and the unsalted SHA-256 digest +//! OpenDocument stores (`table:protection-key`). A sheet or workbook password set in GridCraft +//! keeps both an Excel form and the SHA-256 one, so it survives saving in either format (edit +//! ranges keep only the Excel form). Protection is a convenience, not security, but verification +//! really checks the password: an unsupported variant is refused, never accepted. use serde::{Deserialize, Serialize}; use sha2::Digest; @@ -12,13 +14,82 @@ pub const DEFAULT_SPIN_COUNT: u32 = 100_000; /// Largest spin count accepted when verifying (the documented maximum); a file asking for more /// would only make verification hang. pub const MAX_SPIN_COUNT: u32 = 10_000_000; +/// Largest decoded hash or salt accepted from a file (a SHA-512 hash is 64 bytes, Excel's salts +/// 16); anything longer is damaged, and decoding it would only allocate. +const MAX_STORED_BYTES: usize = 1024; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(from = "StoredHash", into = "StoredHash")] pub enum PasswordHash { /// The legacy 16-bit hash. 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 in `table:protection-key` (ODF 1.3 part 3 §19.701) when + /// `table:protection-key-digest-algorithm` (§19.702) names SHA-256. A writer writes both + /// attributes; a key under any other or no digest algorithm is not this form. + 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 }, +} + +/// How a [`PasswordHash`] is saved in a GridCraft JSON workbook. A password set in GridCraft +/// (`Both` with an iterated Excel form, the usual case) is saved in the `Iterated` shape older +/// GridCraft versions read, with the SHA-256 digest in an extra `odf` field they ignore, so an +/// ordinary Protect Sheet or Protect Workbook doesn't make a workbook unreadable to them. The +/// shapes older versions don't know (`Sha256Digest`, and `Both` over a legacy hash) come only +/// from OpenDocument files, which those versions can't open either. +#[derive(Serialize, Deserialize)] +enum StoredHash { + Legacy(u16), + Iterated { + algorithm: String, + hash: String, + salt: String, + spin_count: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + odf: Option, + }, + Sha256Digest(String), + Both { + excel: Box, + odf: String, + }, +} + +impl From for PasswordHash { + fn from(s: StoredHash) -> PasswordHash { + match s { + StoredHash::Legacy(h) => PasswordHash::Legacy(h), + StoredHash::Iterated { algorithm, hash, salt, spin_count, odf } => { + let iterated = PasswordHash::Iterated { algorithm, hash, salt, spin_count }; + match odf { + Some(odf) => PasswordHash::Both { excel: Box::new(iterated), odf }, + None => iterated, + } + } + StoredHash::Sha256Digest(k) => PasswordHash::Sha256Digest(k), + StoredHash::Both { excel, odf } => PasswordHash::Both { excel, odf }, + } + } +} + +impl From for StoredHash { + fn from(h: PasswordHash) -> StoredHash { + match h { + PasswordHash::Legacy(h) => StoredHash::Legacy(h), + PasswordHash::Iterated { algorithm, hash, salt, spin_count } => StoredHash::Iterated { algorithm, hash, salt, spin_count, odf: None }, + PasswordHash::Sha256Digest(k) => StoredHash::Sha256Digest(k), + PasswordHash::Both { excel, odf } => match *excel { + PasswordHash::Iterated { algorithm, hash, salt, spin_count } => { + StoredHash::Iterated { algorithm, hash, salt, spin_count, odf: Some(odf) } + } + excel => StoredHash::Both { excel: Box::new(excel), odf }, + }, + } + } } impl PasswordHash { @@ -33,11 +104,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()); @@ -45,7 +154,9 @@ impl PasswordHash { if *spin_count > MAX_SPIN_COUNT { return Err(format!("the password uses a spin count of {spin_count}, more than the {MAX_SPIN_COUNT} allowed")); } - let (Some(want), Some(salt)) = (crate::b64::decode(hash), crate::b64::decode(salt)) else { + let (Some(want), Some(salt)) = + (crate::b64::decode_limited(hash, MAX_STORED_BYTES), crate::b64::decode_limited(salt, MAX_STORED_BYTES)) + else { return Err("the stored password hash is damaged".into()); }; let got = match algorithm.to_ascii_uppercase().replace('_', "-").as_str() { @@ -60,6 +171,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); @@ -130,6 +251,73 @@ mod tests { assert!(!other("SHA-256", 2).verify("s3cret")?); let broken = PasswordHash::Iterated { algorithm: "SHA-512".into(), hash: "!!".into(), salt: salt.clone(), spin_count: 1 }; assert!(broken.verify("s3cret").is_err()); + let huge_salt = PasswordHash::Iterated { algorithm: "SHA-512".into(), hash, salt: "A".repeat(4 * MAX_STORED_BYTES), spin_count: 1 }; + assert!(huge_salt.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(()) + } + + /// An ordinary password set in GridCraft is saved in the shape an older GridCraft reads (its + /// `PasswordHash` had only `Legacy` and `Iterated`), and reads back with both forms. + #[test] + fn a_gridcraft_password_is_saved_so_older_versions_read_it() -> Result<(), Box> { + #[derive(Debug, PartialEq, Deserialize)] + enum OlderPasswordHash { + Legacy(u16), + Iterated { algorithm: String, hash: String, salt: String, spin_count: u32 }, + } + let both = PasswordHash::new_for_files("pa55", b"0123456789abcdef"); + let saved = serde_json::to_string(&both)?; + let older: OlderPasswordHash = serde_json::from_str(&saved)?; + let Some(PasswordHash::Iterated { algorithm, hash, salt, spin_count }) = both.excel().cloned() else { + return Err("no Excel form".into()); + }; + assert_eq!(older, OlderPasswordHash::Iterated { algorithm, hash, salt, spin_count }); + // This version reads both forms back. + let back: PasswordHash = serde_json::from_str(&saved)?; + assert_eq!(back, both); + assert!(back.verify("pa55")?); + // What an older version saved still opens. + let excel_only = PasswordHash::new_sha512("pa55", b"0123456789abcdef"); + let back: PasswordHash = serde_json::from_str(&serde_json::to_string(&excel_only)?)?; + assert_eq!(back, excel_only); + assert_eq!(serde_json::from_str::("{\"Legacy\":52250}")?, PasswordHash::Legacy(52250)); + // A legacy hash with a digest has no older shape and keeps its own. + let legacy_both = PasswordHash::Both { excel: Box::new(PasswordHash::Legacy(52250)), odf: "AA==".into() }; + assert_eq!(serde_json::from_str::(&serde_json::to_string(&legacy_both)?)?, legacy_both); Ok(()) } } diff --git a/crates/model/src/workbook.rs b/crates/model/src/workbook.rs index 4402b368b..7669f0125 100644 --- a/crates/model/src/workbook.rs +++ b/crates/model/src/workbook.rs @@ -219,7 +219,9 @@ pub struct Workbook { pub props: DocProps, /// Workbook structure protection. pub protected_structure: bool, - /// Password of the structure protection (XLSX `workbookProtection`), never the password. + /// Hash of the structure protection's password, never the password. XLSX + /// `workbookProtection` writes its Excel form ([`crate::PasswordHash::excel`]); a digest + /// alone has none and is not written there. #[serde(default, skip_serializing_if = "Option::is_none")] pub structure_password: Option, /// Custom fill lists (Options › Custom Lists) beyond the built-in ones. diff --git a/crates/xlsx/src/sheet_write/parts.rs b/crates/xlsx/src/sheet_write/parts.rs index 2c0c5b483..a5a06b31d 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/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index f5857a6f6..05137bd16 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -2242,6 +2242,29 @@ fn remove_personal_information_is_kept_and_honoured() { 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); +} + #[test] fn cell_padding_is_dropped_by_xlsx_and_nothing_else_is() { // SpreadsheetML has no cell padding: it is not written, and everything else in the style is. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d6237efe6..9bf453a11 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-14 · **Change:** minor (the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, ``, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; 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 +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-14 · **Change:** minor (a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, ``, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; 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** @@ -83,7 +83,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 (including the Excel 2010 `x14:conditionalFormattings` extension, MS-XLSX 2.4.6: `cellIs`, `expression`, `containsBlanks`/`notContainsBlanks`, `containsErrors`/`notContainsErrors`, `duplicateValues`/`uniqueValues`, `top10`, `aboveAverage` and `timePeriod` rules are read, with `xm:f` formulas and an inline `x14:dxf`; x14 data bars (beyond the solid fill a main-section data bar links to), icon sets, colour scales and the text rules `containsText`, `notContainsText`, `beginsWith` and `endsWith` are skipped with a warning and lost on save. Cell-value and formula rules referring to another sheet are written in the extension using `{78C0D931-6437-407d-A8EE-F0AAD7539E65}`; in the tested synthetic files, Excel for Mac 16.114 also wrote cross-sheet `expression` rules there and opened them without a repair prompt. Excel for Mac 16.114 stores cross-sheet `cfvo` rules for colour scales, data bars and icon sets only in x14; GridCraft writes those rules in the main section, and drops x14-only rules of those kinds on read with a warning. A rule with a 3-D span stays in the main section, since MS-XLSX 2.6.27 forbids `sheet-range-reference` in `xm:f`. Colour scale, data bar and icon set rules (whose cfvo formulas can also refer to other sheets) are always written in the main section), 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), form controls (buttons, scroll bars and spin buttons: control properties parts, `` and VML `x:ClientData`; a VML-only control is read too; a button's command, fixed input range or output cell travels in a hidden defined name and comes back only onto the same button while the file still assigns its macro, or none for a command), 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), other form controls (check boxes, list boxes, drop-downs; written in the same `` element and VML drawing as the modelled ones, also those only the VML drawing lists, with no `` entry), 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` Legacy formula behavior | R/W | yes | yes | Formulas without dynamic-array metadata (`cm`) open with Excel's implicit `@`; implied operators are removed on save without `cm`, while explicit single-value `@` is kept as `_xlfn.SINGLE`; formulas the analyzer cannot finish are saved as read. | `roundtrip.rs`, `fixtures.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, and without a warning yet: the XLSX save path has no warning channel), 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` | @@ -161,6 +161,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-11-14 | 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. GridCraft JSON (`.json`) workbooks keep such a password in the shape earlier GridCraft versions read (the SHA-512 hash, with the digest in an extra `odf` field they ignore), so they still open there | | 2026-11-14 | minor | Style model: `Alignment::padding` (left, right, top, bottom, hundredths of a point; none where a file states none) keeps an OpenDocument cell's padding; styles differing only by padding stay apart. XLSX and XLS read none and the XLSX writer leaves it out; GridCraft does not draw it yet | | 2026-11-14 | minor | XLSX fonts' outlined (hollow) letters, ``, are read and written back after `` as Excel writes them, in cell fonts and differential formats (a differential format that turns it off, ``, keeps that too); they were dropped before. Two fonts differing only in it are different styles. Set by `home.formatCells {style: {font: {outline: true}}}`; GridCraft does not draw outlined text yet (it shows solid) | | 2026-11-13 | minor | PDF of a right-to-left sheet keeps explicit Left and Right alignment on the side the grid shows them |