From 95c0800c2224446e892298c15528af9d9e07e8bc Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:40:24 -0500 Subject: [PATCH 01/10] XLSX: password to modify (#921): kept on save, asked for on open or open read-only --- ROADMAP.md | 4 ++- crates/engine/src/cmd/file.rs | 17 +++++++++++-- crates/engine/src/io.rs | 4 +++ crates/engine/src/tests.rs | 40 ++++++++++++++++++++++++++++++ crates/model/src/lib.rs | 4 ++- crates/model/src/workbook.rs | 13 ++++++++++ crates/ui-egui/src/dialogs.rs | 19 +++++++++++++- crates/ui-egui/src/lib.rs | 7 ++++++ crates/xlsx/src/read.rs | 8 ++++++ crates/xlsx/src/tests/roundtrip.rs | 7 ++++++ crates/xlsx/src/write.rs | 17 +++++++++++++ docs/file-format-parity.md | 4 ++- 12 files changed, 138 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index da06359b5..03db59417 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** minor (accounting negatives such as `$(1,234)` read as numbers; INDEX with one index on a 2-D reference is #REF! as in Excel; earlier: Page Setup paper sizes: JIS B4/B5/B6, the Japanese postcards and envelopes, and A6; long flat operator chains up to Excel's formula limit) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (accounting negatives such as `$(1,234)` read as numbers; INDEX with one index on a 2-D reference is #REF! as in Excel; earlier: Page Setup paper sizes: JIS B4/B5/B6, the Japanese postcards and envelopes, and A6; long flat operator chains up to Excel's formula limit) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-24 | XLSX: a password to modify (`fileSharing`) is kept on save, and opening such a file asks for the password or opens it read-only (never checked against Excel) (#921) | | 2026-10-23 | Accounting negatives in text: `$(1,234)`, `$ (5)` and `(5)%` read as negative numbers when typed, coerced by arithmetic or passed to VALUE, like Excel 365; `(-5)`, `((5))`, `$5%` and dates or times in parentheses stay text | | 2026-10-23 | Calc: `INDEX(A1:C3,2)` (one index on a reference of several rows and columns) is `#REF!` as in Excel, instead of the whole row; `INDEX(A1:C3,2,)` still gives the row | | 2026-10-22 | Formula hardening: digits too many for a finite number are text, so `"1 <400 digits>/<400 digits>"` no longer coerces to NaN; a NaN column index in VLOOKUP, HLOOKUP and the D-functions is `#VALUE!` instead of an index underflow; REGEXREPLACE stops building a result as soon as it can only be too long (a worst case went from 1 GB to 7 MB) (#2163, #2162) | @@ -226,6 +227,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | Progress log: password to modify (#921) | | 2026-10-23 | minor | Progress log: accounting negatives in number text | | 2026-10-23 | minor | Progress log: INDEX with one index on a 2-D reference is #REF! | | 2026-10-22 | trivial | Progress log: formula hardening (#2163, #2162) | diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index b3e7309e2..7f6e9e366 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -8,7 +8,7 @@ use crate::DocState; pub fn specs() -> Vec { vec![ cmd!(noundo "file.new", "New Workbook", ["File"], Some("Cmd+N"), "{sample?: \"budget\"|\"sales\"|\"grades\"}", always, new_workbook), - cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open), + cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook, {modifyPassword} for one with a password to modify (or {readOnly: true} to open it without; Save then asks for a new file), and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open), cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html/.pdf by extension)", has_doc, save), cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} (.xlsx, .csv, .tsv, .json, .html, or .pdf: a PDF of the active sheet)", has_doc, save_as), cmd!(query "file.saveBytes", "Encode Workbook", [], None, "{format?: xlsx|csv|tsv|json|html} → {base64}", has_doc, save_bytes), @@ -57,6 +57,19 @@ fn open(s: &mut Session, p: &Json) -> Result { }; let encrypted = gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Encrypted; let (mut wb, warnings) = crate::io::open_bytes_with(&name, &bytes, str_param(p, "password"), bool_param(p, "csvAsText").unwrap_or(false))?; + // A password to modify: the right one or a read-only open, or the workbook doesn't open. + let mut read_only = false; + if let Some(hash) = wb.write_reservation.as_ref().and_then(|r| r.password.as_ref()) { + read_only = bool_param(p, "readOnly").unwrap_or(false); + match str_param(p, "modifyPassword") { + _ if read_only => {} + None => return Err(EngineError::Other(format!("'{name}' {}", crate::io::MODIFY_PASSWORD_REQUIRED))), + Some(pw) if !hash.verify(pw).map_err(|e| bad("file.open", e))? => { + return Err(EngineError::Other(crate::io::WRONG_PASSWORD.into())); + } + Some(_) => {} + } + } wb.source_dir = str_param(p, "path").and_then(crate::io::source_dir); // What `CELL("filename")` reports (#1489). A workbook opened from bytes knows its name but // never a folder, so it reports `[name]Sheet` with none; an import reports the file it came @@ -76,7 +89,7 @@ fn open(s: &mut Session, p: &Json) -> Result { // An import has no save target: ordinary Save must ask for a new destination. Neither does a // workbook decrypted with its password, so Save never replaces the encrypted original with // an unprotected copy. - let path = str_param(p, "path").filter(|_| !imported && !encrypted).map(str::to_string); + let path = str_param(p, "path").filter(|_| !imported && !encrypted && !read_only).map(str::to_string); // Replace an untouched blank Book1 like Excel does. if s.documents().len() == 1 && s.active().is_some_and(|d| d.path.is_none() && !d.is_dirty() && d.undo.is_empty() && d.wb.sheets.iter().all(|sh| sh.cells.is_empty())) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index be47e0a67..6453cec7a 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -41,6 +41,10 @@ impl FileKind { /// The error for an encrypted workbook opened without a password contains this. The interface /// asks for the password when it sees it; programmatic callers pass `password` instead. pub const PASSWORD_REQUIRED: &str = "is password-protected. Enter its password to open it."; +/// The error for a workbook with a password to modify, opened with neither that password +/// (`modifyPassword`) nor `readOnly`, contains this. The interface asks for the password or a +/// read-only open when it sees it. +pub const MODIFY_PASSWORD_REQUIRED: &str = "is reserved by its author. Enter the password to modify it, or open it read-only."; /// The error for a wrong password contains this. pub const WRONG_PASSWORD: &str = "The password is incorrect."; /// The first open warning of a workbook decrypted with its password. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f4c47bb62..0a5da6bd6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4142,6 +4142,46 @@ fn encrypted_book(password: &str) -> Vec { gridcraft_xlsx::testing::encrypt_workbook(&xlsx, password) } +#[test] +fn a_password_to_modify_asks_for_it_or_a_read_only_open() { + const PW: &str = "synthetic-modify-pw"; + let mut src = s(); + src.execute("cell.set", json!({"cell": "A1", "input": "42"})).unwrap(); + src.doc_mut().unwrap().wb.write_reservation = Some(gridcraft_model::WriteReservation { + password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")), + ..Default::default() + }); + let bytes = crate::io::save_bytes(&src.doc().unwrap().wb, "book.xlsx").unwrap(); + let b64 = crate::io::base64_encode(&bytes); + let open = |s: &mut Session, extra: serde_json::Value| { + let mut p = json!({"name": "Reserved.xlsx", "base64": b64}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + s.execute("file.open", p) + }; + let mut s = Session::new(); + let err = open(&mut s, json!({})).unwrap_err().to_string(); + assert!(err.contains(crate::io::MODIFY_PASSWORD_REQUIRED), "{err}"); + assert!(s.take_ui_requests().is_empty(), "programmatic calls never open dialogs"); + for wrong in ["not-it", ""] { + let err = open(&mut s, json!({"modifyPassword": wrong})).unwrap_err().to_string(); + assert!(err.contains(crate::io::WRONG_PASSWORD), "{err}"); + } + assert!(s.documents().is_empty()); + + // Read-only: opens, keeps the reservation, but has no file to save over. + open(&mut s, json!({"readOnly": true})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Number(42.0)); + assert!(s.doc().unwrap().wb.write_reservation.is_some()); + + // The password: opens, and the reservation survives a save. + let mut s = Session::new(); + open(&mut s, json!({"modifyPassword": PW})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Number(42.0)); + let saved = crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap(); + let (back, _) = crate::io::open_bytes("book.xlsx", &saved).unwrap(); + assert!(back.write_reservation.and_then(|r| r.password).is_some_and(|h| h.verify(PW) == Ok(true))); +} + #[test] fn encrypted_workbooks_open_with_their_password() { const PW: &str = "synthetic-pw-5521"; diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 071de683c..f731422a8 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -25,7 +25,9 @@ pub use style::{ Alignment, BorderLine, BorderStyle, Borders, Color, Fill, Font, HAlign, NumFmt, PatternType, Style, StyleId, StyleTable, Theme, Underline, VAlign, VertAlign, }; -pub use workbook::{CalcMode, CalcSettings, DefinedName, DocProps, PhoneticProps, PhoneticRun, PhoneticString, ShowObjects, Workbook}; +pub use workbook::{ + CalcMode, CalcSettings, DefinedName, DocProps, PhoneticProps, PhoneticRun, PhoneticString, ShowObjects, Workbook, WriteReservation, +}; /// Font used for new workbooks. Only a name: renderers substitute an available open font /// (e.g. the metric-compatible Carlito) when it isn't installed. diff --git a/crates/model/src/workbook.rs b/crates/model/src/workbook.rs index 3b943d295..e930961b6 100644 --- a/crates/model/src/workbook.rs +++ b/crates/model/src/workbook.rs @@ -154,6 +154,9 @@ pub struct Workbook { /// Password of the structure protection (XLSX `workbookProtection`), never the password. #[serde(default, skip_serializing_if = "Option::is_none")] pub structure_password: Option, + /// "Password to modify" (XLSX `fileSharing`): the file opens read-only unless it is given. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub write_reservation: Option, /// Custom fill lists (Options › Custom Lists) beyond the built-in ones. pub custom_lists: Vec>, /// Named cell styles (Cell Styles gallery): name → style. @@ -205,6 +208,15 @@ impl Default for Workbook { } } +/// The write-reservation of a file (XLSX `fileSharing`): who reserved it, whether it asks to open +/// read-only, and the hash of its password to modify, never the password. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct WriteReservation { + pub user_name: String, + pub read_only_recommended: bool, + pub password: Option, +} + impl Workbook { /// A new workbook with one sheet, "Sheet1". pub fn new() -> Workbook { @@ -220,6 +232,7 @@ impl Workbook { props: DocProps::default(), protected_structure: false, structure_password: None, + write_reservation: None, custom_lists: vec![], cell_styles: vec![], phonetics: vec![], diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e83db2fa1..6419db68e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -347,6 +347,22 @@ impl Dialog { // An empty password from the start, so OK on the untouched field says "incorrect" // rather than asking for the password again. let mut values = params.clone(); + // A workbook with a password to modify asks for that, or a read-only open. + if p("modify").as_bool().unwrap_or(false) { + values["modifyPassword"] = json!(""); + values["readOnly"] = json!(false); + return Dialog::form( + "openPassword", + "Password", + "file.open", + vec![ + Note(format!("'{file}' is reserved by its author. Enter the password to modify it, or open it read-only.")), + Password { key: "modifyPassword", label: "Password:" }, + Check { key: "readOnly", label: "Read Only" }, + ], + values, + ); + } values["password"] = json!(""); Dialog::form( "openPassword", @@ -1504,7 +1520,8 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { } // A wrong password: say so, clear the field and stay open for another try. Err(e) if d.name == "openPassword" => { - d.values.insert("password".into(), json!("")); + let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" }; + d.values.insert(field.into(), json!("")); app.message = Some((d.title.clone(), crate::clean_error(&e))); } Err(e) => app.message = Some((d.title.clone(), crate::clean_error(&e))), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 14c442331..4ba19a8e2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -838,6 +838,9 @@ impl SheetApp { Ok(r) => self.after_open(Some(path), &r), // A password-protected workbook: ask for the password; the dialog opens it. Err(e) if e.contains(gridcraft_engine::io::PASSWORD_REQUIRED) => self.open_dialog("openPassword", json!({"path": path})), + Err(e) if e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { + self.open_dialog("openPassword", json!({"path": path, "modify": true})) + } Err(e) => self.message = Some(("GridCraft".into(), clean_error(&e))), } self.after_engine(); @@ -1253,6 +1256,10 @@ impl SheetApp { self.backstage = None; self.open_dialog("openPassword", json!({"name": name, "base64": b64})); } + Err(e) if e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { + self.backstage = None; + self.open_dialog("openPassword", json!({"name": name, "base64": b64, "modify": true})); + } Err(e) => self.message = Some(("GridCraft".into(), clean_error(&e))), } self.after_engine(); diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 774567bf8..8900b22fd 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -246,6 +246,14 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { wb.protected_structure = p.flag("lockStructure", false); wb.structure_password = if wb.protected_structure { crate::sheet_read::read_password(p, "workbook") } else { None }; } + if let Some(f) = wb_xml.child("fileSharing") { + // The iterated hash has bare attribute names; the legacy one is `reservationPassword`. + wb.write_reservation = Some(gridcraft_model::WriteReservation { + user_name: f.attr("userName").unwrap_or("").to_string(), + read_only_recommended: f.flag("readOnlyRecommended", false), + password: crate::sheet_read::read_password(f, "").or_else(|| crate::sheet_read::read_password(f, "reservation")), + }); + } let active_tab = wb_xml.path(&["bookViews", "workbookView"]).and_then(|v| v.attr_u32("activeTab")).unwrap_or(0) as usize; // Sheets. `file_to_model[i]` maps the i-th to a model sheet index. diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 5b79438db..462cb8449 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -23,6 +23,11 @@ fn sample() -> Workbook { wb.calc = CalcSettings { mode: CalcMode::Manual, iterative: true, max_iterations: 42, max_change: 0.5, precision_as_displayed: true }; wb.protected_structure = true; wb.structure_password = Some(gridcraft_model::PasswordHash::new_sha512("s3cret", b"0123456789abcdef")); + wb.write_reservation = Some(gridcraft_model::WriteReservation { + user_name: "Ann & ".into(), + read_only_recommended: true, + password: Some(gridcraft_model::PasswordHash::new_sha512("modify-me", b"fedcba9876543210")), + }); wb.props = DocProps { title: "T & ".into(), subject: "S".into(), @@ -495,6 +500,8 @@ fn full_roundtrip() { assert!(back.protected_structure); assert_eq!(back.structure_password, wb.structure_password); assert!(back.structure_password.as_ref().unwrap().verify("s3cret").unwrap()); + assert_eq!(back.write_reservation, wb.write_reservation); + assert!(back.write_reservation.as_ref().and_then(|r| r.password.as_ref()).unwrap().verify("modify-me").unwrap()); assert_eq!(back.props, wb.props); assert_eq!(back.theme, wb.theme); assert_eq!(back.names, wb.names); diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index cf208d6cd..1a8373060 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -345,6 +345,23 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) // only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it. let file_version = crate::passthrough::workbook_elements(wb, "fileVersion"); w.push_str(if file_version.is_empty() { "" } else { &file_version }); + if let Some(r) = &wb.write_reservation { + w.push_str(" { + let _ = write!(w, " reservationPassword=\"{h:04X}\""); + } + Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), + None => {} + } + w.push_str("/>"); + } w.push_str(" {} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index cf567f8bd..bfbc51c9f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-21 · **Change:** minor (.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) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (.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) · **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** @@ -60,6 +60,7 @@ values) is still dropped. | `.xml` XML Spreadsheet 2003 | R/W | no | no | Simple to support | — | | `.ods` OpenDocument Spreadsheet | R/W | **values only** (#100) | no | Sheets, values, dates, merges, repeated cells, cached formula results; no formulas, formatting, charts; encrypted ODS refused | `ods_tests.rs` | | Password-encrypted workbooks (Agile/Standard encryption) | R | **yes** (#11): asks for the password on open; Agile (AES-128/192/256, SHA-1/256/384/512) and Standard (AES, SHA-1) | no (opens with no save path; Save As writes it without the password) | Clean-room from [MS-OFFCRYPTO] on the CFB reader. RC4, Extensible and certificate-only encryption refused with a message. Data-integrity HMAC not checked | `crypto/tests.rs`, `encrypted_tests.rs` | +| Password to modify (XLSX `fileSharing`) | R/W | **yes** (#921): asks for the password, or opens read-only; a read-only open has no save target | yes (hash, user name and read-only-recommended kept) | Legacy `reservationPassword` and iterated SHA-256/384/512 hashes. Never checked against Excel: its prompt wording and read-only behaviour are unobserved; `readOnlyRecommended` alone does not prompt | `roundtrip.rs`, `engine/src/tests.rs` | | `.xlw` Excel 4.0 workbook, `.wk*`, `.dbf` | open only (some) | no | no | Rare | — | ## Text and data formats @@ -110,6 +111,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | XLSX: a password to modify (`fileSharing`) is read and written, and opening such a file asks for it or opens read-only (#921) | | 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI ``) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged | | 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `` with ``) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `` without runs is kept on its own, and when duplicate `` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) | | 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (``, also Hebr, Jpan and the rest) are read and written back in file order after ``; they were dropped before. A hostile file is held to 64 entries of 256 characters | From ae50127952243b594ffd54de41ac3b3f4a1bf6ae Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:44:33 -0500 Subject: [PATCH 02/10] XLSX password to modify: fix dialog return type and test's Arc workbook edit --- crates/engine/src/tests.rs | 2 +- crates/ui-egui/src/dialogs.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0a5da6bd6..f160b8a2a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4147,7 +4147,7 @@ fn a_password_to_modify_asks_for_it_or_a_read_only_open() { const PW: &str = "synthetic-modify-pw"; let mut src = s(); src.execute("cell.set", json!({"cell": "A1", "input": "42"})).unwrap(); - src.doc_mut().unwrap().wb.write_reservation = Some(gridcraft_model::WriteReservation { + std::sync::Arc::make_mut(&mut src.doc_mut().unwrap().wb).write_reservation = Some(gridcraft_model::WriteReservation { password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")), ..Default::default() }); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6419db68e..3c57ad7fd 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -351,7 +351,7 @@ impl Dialog { if p("modify").as_bool().unwrap_or(false) { values["modifyPassword"] = json!(""); values["readOnly"] = json!(false); - return Dialog::form( + return Some(Dialog::form( "openPassword", "Password", "file.open", @@ -361,7 +361,7 @@ impl Dialog { Check { key: "readOnly", label: "Read Only" }, ], values, - ); + )); } values["password"] = json!(""); Dialog::form( From 38fa0dc050ef1f684fc08292405e34adf43c7681 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:02:07 -0500 Subject: [PATCH 03/10] XLSX password to modify: address review comments - A read-only open refuses Save to the file it came from; Save As to another file still works, so the reservation holds. - Verify SHA-1 password-to-modify hashes, as XLSX fileSharing allows. - An encrypted and reserved workbook asks for the password to modify after its decryption password, keeping the decryption password. --- Cargo.lock | 1 + crates/engine/src/cmd/file.rs | 6 ++++++ crates/engine/src/lib.rs | 4 ++++ crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ crates/model/Cargo.toml | 1 + crates/model/src/password.rs | 16 +++++++++++++++- crates/ui-egui/src/dialogs.rs | 9 +++++++++ docs/file-format-parity.md | 4 ++-- 8 files changed, 63 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7f5203188..ecf7a9ba4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1627,6 +1627,7 @@ dependencies = [ "gridcraft-formula", "serde", "serde_json", + "sha1", "sha2", "thiserror 2.0.21", ] diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 7f6e9e366..bd454a9ad 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -98,6 +98,9 @@ fn open(s: &mut Session, p: &Json) -> Result { } // Someone else may have made the file: its active content asks before it runs. let mut doc = DocState::new(wb, path, title, crate::Trust::FromFile); + if read_only { + doc.read_only_source = str_param(p, "path").map(str::to_string); + } if crate::io::FileKind::from_path(&name).is_none() && gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Xlsx { doc.content_kind = Some(crate::io::FileKind::Xlsx); } @@ -125,6 +128,9 @@ fn save(s: &mut Session, p: &Json) -> Result { return ok(); } }; + if s.active().and_then(|d| d.read_only_source.as_deref()) == Some(path.as_str()) { + return Err(bad("file.save", "is reserved by its author and open read-only. Save As to another file.")); + } // A PDF is a print of the sheet (Page Setup applies), not a copy of the workbook: the // document keeps its file and its unsaved changes. if std::path::Path::new(&path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b4ab60f3a..f6b90d605 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -189,6 +189,9 @@ pub struct DocState { /// The format `path`'s content was recognised as when its extension doesn't name one (an /// XLSX called `budget.dat`): Save writes it back in that format. pub content_kind: Option, + /// The file a read-only open came from (`readOnly` on a workbook with a password to modify). + /// Save never writes over it, so the reservation holds; Save As to another file still works. + pub read_only_source: Option, /// Whether the scripts stored in this workbook may run (`automate.runScript`). A workbook /// that arrives already carrying scripts (opened from a file) starts untrusted until the /// user trusts it in this session (`automate.trustScripts`); one with no scripts starts @@ -283,6 +286,7 @@ impl DocState { sheet_selections: vec![], unlocked_ranges: vec![], content_kind: None, + read_only_source: None, scripts_trusted, trust, } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f160b8a2a..fecb11fee 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4182,6 +4182,31 @@ fn a_password_to_modify_asks_for_it_or_a_read_only_open() { assert!(back.write_reservation.and_then(|r| r.password).is_some_and(|h| h.verify(PW) == Ok(true))); } +#[test] +fn a_read_only_open_never_saves_over_its_reserved_file() { + const PW: &str = "synthetic-modify-pw"; + let dir = std::env::temp_dir().join(format!("gridcraft-read-only-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("reserved.xlsx").to_string_lossy().into_owned(); + let copy = dir.join("copy.xlsx").to_string_lossy().into_owned(); + let mut src = s(); + std::sync::Arc::make_mut(&mut src.doc_mut().unwrap().wb).write_reservation = Some(gridcraft_model::WriteReservation { + password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")), + ..Default::default() + }); + let bytes = crate::io::save_bytes(&src.doc().unwrap().wb, "book.xlsx").unwrap(); + std::fs::write(&path, &bytes).unwrap(); + + let mut s = Session::new(); + s.execute("file.open", json!({"path": path, "readOnly": true})).unwrap(); + let err = s.execute("file.save", json!({"path": path})).unwrap_err().to_string(); + assert!(err.contains("read-only"), "{err}"); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched"); + s.execute("file.saveAs", json!({"path": copy})).unwrap(); + assert!(std::fs::metadata(©).is_ok()); + std::fs::remove_dir_all(&dir).ok(); +} + #[test] fn encrypted_workbooks_open_with_their_password() { const PW: &str = "synthetic-pw-5521"; diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml index 761cf0093..02c66415a 100644 --- a/crates/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] gridcraft-core = { workspace = true } +sha1 = { workspace = true } sha2 = { workspace = true } gridcraft-formula = { workspace = true } serde = { workspace = true } diff --git a/crates/model/src/password.rs b/crates/model/src/password.rs index 59b9aafba..994cf324e 100644 --- a/crates/model/src/password.rs +++ b/crates/model/src/password.rs @@ -49,6 +49,7 @@ impl PasswordHash { return Err("the stored password hash is damaged".into()); }; let got = match algorithm.to_ascii_uppercase().replace('_', "-").as_str() { + "SHA-1" => iterated::(password, &salt, *spin_count), "SHA-512" => iterated::(password, &salt, *spin_count), "SHA-384" => iterated::(password, &salt, *spin_count), "SHA-256" => iterated::(password, &salt, *spin_count), @@ -114,6 +115,19 @@ mod tests { assert_eq!(legacy_hash(""), 0xCE4B); } + #[test] + fn sha1_iterated_hash_verifies_the_correct_password() { + // Known answer for "s3cret", salt "0123456789abcdef", spin count 10, computed outside this code. + let h = PasswordHash::Iterated { + algorithm: "SHA-1".into(), + hash: "b2+ArdbduWEP3TNb+4NZg6qjkEk=".into(), + salt: crate::b64::encode(b"0123456789abcdef"), + spin_count: 10, + }; + assert!(h.verify("s3cret").unwrap()); + assert!(!h.verify("s3cret ").unwrap()); + } + #[test] fn iterated_hash_verifies_and_refuses_what_it_cannot_check() { let h = PasswordHash::new_sha512("s3cret", b"0123456789abcdef"); @@ -123,7 +137,7 @@ mod tests { let PasswordHash::Iterated { hash, salt, .. } = h else { return }; let other = |algorithm: &str, spin_count| PasswordHash::Iterated { algorithm: algorithm.into(), hash: hash.clone(), salt: salt.clone(), spin_count }; - assert!(other("SHA-1", 10).verify("s3cret").is_err()); + assert!(!other("SHA-1", 10).verify("s3cret").unwrap()); assert!(other("MD5", 10).verify("s3cret").is_err()); assert!(other("SHA-512", MAX_SPIN_COUNT + 1).verify("s3cret").is_err()); assert!(!other("SHA-256", 2).verify("s3cret").unwrap()); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 3c57ad7fd..99a417692 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1518,6 +1518,15 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { Err(e) if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) => { d.values.insert("askOverwrite".into(), json!(true)); } + // Encrypted and reserved: the password opened it, so the form turns to the password to + // modify. The decryption password stays in the values for the retry. + Err(e) if d.name == "openPassword" && e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { + let mut params = Json::Object(d.values.clone()); + params["modify"] = json!(true); + if let Some(next) = Dialog::open(app, "openPassword", params) { + d = Dialog { back: d.back.take(), ..next }; + } + } // A wrong password: say so, clear the field and stay open for another try. Err(e) if d.name == "openPassword" => { let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" }; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index bfbc51c9f..667abc55d 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -60,7 +60,7 @@ values) is still dropped. | `.xml` XML Spreadsheet 2003 | R/W | no | no | Simple to support | — | | `.ods` OpenDocument Spreadsheet | R/W | **values only** (#100) | no | Sheets, values, dates, merges, repeated cells, cached formula results; no formulas, formatting, charts; encrypted ODS refused | `ods_tests.rs` | | Password-encrypted workbooks (Agile/Standard encryption) | R | **yes** (#11): asks for the password on open; Agile (AES-128/192/256, SHA-1/256/384/512) and Standard (AES, SHA-1) | no (opens with no save path; Save As writes it without the password) | Clean-room from [MS-OFFCRYPTO] on the CFB reader. RC4, Extensible and certificate-only encryption refused with a message. Data-integrity HMAC not checked | `crypto/tests.rs`, `encrypted_tests.rs` | -| Password to modify (XLSX `fileSharing`) | R/W | **yes** (#921): asks for the password, or opens read-only; a read-only open has no save target | yes (hash, user name and read-only-recommended kept) | Legacy `reservationPassword` and iterated SHA-256/384/512 hashes. Never checked against Excel: its prompt wording and read-only behaviour are unobserved; `readOnlyRecommended` alone does not prompt | `roundtrip.rs`, `engine/src/tests.rs` | +| Password to modify (XLSX `fileSharing`) | R/W | **yes** (#921): asks for the password, or opens read-only; a read-only open never saves over its file | yes (hash, user name and read-only-recommended kept) | Legacy `reservationPassword` and iterated SHA-1/256/384/512 hashes. Never checked against Excel: its prompt wording and read-only behaviour are unobserved; `readOnlyRecommended` alone does not prompt | `roundtrip.rs`, `engine/src/tests.rs` | | `.xlw` Excel 4.0 workbook, `.wk*`, `.dbf` | open only (some) | no | no | Rare | — | ## Text and data formats @@ -111,7 +111,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| -| 2026-10-24 | minor | XLSX: a password to modify (`fileSharing`) is read and written, and opening such a file asks for it or opens read-only (#921) | +| 2026-10-24 | minor | XLSX: a password to modify (`fileSharing`) is read and written, and opening such a file asks for it or opens read-only (#921); a read-only open refuses Save to its own file; SHA-1 modify hashes verify; an encrypted and reserved file asks for the modify password after its decryption password | | 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI ``) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged | | 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `` with ``) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `` without runs is kept on its own, and when duplicate `` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) | | 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (``, also Hebr, Jpan and the rest) are read and written back in file order after ``; they were dropped before. A hostile file is held to 64 entries of 256 characters | From ce64da3286516119304e7f7057567b2adbec1591 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:35:28 -0500 Subject: [PATCH 04/10] XLSX password to modify: compare the reserved file by identity on Save; keep a legacy hash only beside a userName (#2508) --- crates/engine/src/cmd/file.rs | 10 +++++++++- crates/engine/src/tests.rs | 4 ++++ crates/xlsx/src/tests/roundtrip.rs | 12 ++++++++++++ crates/xlsx/src/write.rs | 4 +++- 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e3c23dd03..4fde819f3 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -120,6 +120,14 @@ fn open(s: &mut Session, p: &Json) -> Result { ) } +/// Whether two paths name one file, whatever their spelling (`./book.xlsx`, a symlink). +fn same_file(a: &str, b: &str) -> bool { + match (std::fs::canonicalize(a), std::fs::canonicalize(b)) { + (Ok(x), Ok(y)) => x == y, + _ => a == b, + } +} + fn save(s: &mut Session, p: &Json) -> Result { let path = match str_param(p, "path").map(str::to_string).or_else(|| s.active().and_then(|d| d.path.clone())) { Some(p) => p, @@ -128,7 +136,7 @@ fn save(s: &mut Session, p: &Json) -> Result { return ok(); } }; - if s.active().and_then(|d| d.read_only_source.as_deref()) == Some(path.as_str()) { + if s.active().and_then(|d| d.read_only_source.as_deref()).is_some_and(|src| same_file(src, &path)) { return Err(bad("file.save", "is reserved by its author and open read-only. Save As to another file.")); } // A PDF is a print of the sheet (Page Setup applies), not a copy of the workbook: the diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 98acfddd0..39928c7f9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4423,6 +4423,10 @@ fn a_read_only_open_never_saves_over_its_reserved_file() { let err = s.execute("file.save", json!({"path": path})).unwrap_err().to_string(); assert!(err.contains("read-only"), "{err}"); assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched"); + let dotted = dir.join(".").join("reserved.xlsx").to_string_lossy().into_owned(); + let err = s.execute("file.save", json!({"path": dotted})).unwrap_err().to_string(); + assert!(err.contains("read-only"), "the same file under another spelling: {err}"); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched"); s.execute("file.saveAs", json!({"path": copy})).unwrap(); assert!(std::fs::metadata(©).is_ok()); std::fs::remove_dir_all(&dir).ok(); diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index e90ff1781..35c73d568 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1491,3 +1491,15 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() { assert!(t.filter.is_empty(), "the criteria landed on the wrong table column: {:?}", t.filter); assert!(b.autofilter.is_none(), "a sheet filter inside a table would be invalid"); } + +#[test] +fn legacy_reservation_password_is_written_with_a_user_name() { + let mut wb = sample(); + wb.write_reservation = + Some(WriteReservation { user_name: String::new(), read_only_recommended: false, password: Some(PasswordHash::Legacy(0x83AF)) }); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + assert!(back.write_reservation.is_some_and(|r| r.password.is_none()), "no userName, so no reservationPassword"); + wb.write_reservation.as_mut().unwrap().user_name = "Ann".into(); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + assert_eq!(back.write_reservation.and_then(|r| r.password), Some(PasswordHash::Legacy(0x83AF))); +} diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index c3ba698f3..34fb2ed89 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -352,9 +352,11 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) let _ = write!(w, " userName=\"{}\"", esc_attr(&r.user_name)); } match &r.password { - Some(gridcraft_model::PasswordHash::Legacy(h)) => { + // Office needs a userName beside a legacy reservationPassword; without one the hash is left out. + Some(gridcraft_model::PasswordHash::Legacy(h)) if !r.user_name.is_empty() => { let _ = write!(w, " reservationPassword=\"{h:04X}\""); } + Some(gridcraft_model::PasswordHash::Legacy(_)) => {} Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), None => {} } From 1e3fc9ee37f42f3f11f30a721b4be7f2a20dadf5 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 06:52:05 -0500 Subject: [PATCH 05/10] XLSX: keep a legacy modify password on save when the workbook has no user name --- crates/xlsx/src/tests/roundtrip.rs | 4 +++- crates/xlsx/src/write.rs | 12 +++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 35c73d568..0f8929711 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1498,7 +1498,9 @@ fn legacy_reservation_password_is_written_with_a_user_name() { wb.write_reservation = Some(WriteReservation { user_name: String::new(), read_only_recommended: false, password: Some(PasswordHash::Legacy(0x83AF)) }); let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); - assert!(back.write_reservation.is_some_and(|r| r.password.is_none()), "no userName, so no reservationPassword"); + let r = back.write_reservation.expect("the reservation survived"); + assert_eq!(r.password, Some(PasswordHash::Legacy(0x83AF)), "a nameless legacy password is kept, under a placeholder name"); + assert!(!r.user_name.is_empty()); wb.write_reservation.as_mut().unwrap().user_name = "Ann".into(); let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); assert_eq!(back.write_reservation.and_then(|r| r.password), Some(PasswordHash::Legacy(0x83AF))); diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 761c731ce..814e6dd5e 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -348,15 +348,17 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) if r.read_only_recommended { w.push_str(" readOnlyRecommended=\"1\""); } - if !r.user_name.is_empty() { - let _ = write!(w, " userName=\"{}\"", esc_attr(&r.user_name)); + // Office needs a userName beside a legacy reservationPassword, so a nameless one gets a placeholder + // rather than losing the password. + let legacy = matches!(r.password, Some(gridcraft_model::PasswordHash::Legacy(_))); + let name = if r.user_name.is_empty() && legacy { "GridCraft" } else { r.user_name.as_str() }; + if !name.is_empty() { + let _ = write!(w, " userName=\"{}\"", esc_attr(name)); } match &r.password { - // Office needs a userName beside a legacy reservationPassword; without one the hash is left out. - Some(gridcraft_model::PasswordHash::Legacy(h)) if !r.user_name.is_empty() => { + Some(gridcraft_model::PasswordHash::Legacy(h)) => { let _ = write!(w, " reservationPassword=\"{h:04X}\""); } - Some(gridcraft_model::PasswordHash::Legacy(_)) => {} Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), None => {} } From 2c976a6e6baa3560375cc672c3af9e77413c5954 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:51:09 -0500 Subject: [PATCH 06/10] Import engine error in file commands --- crates/engine/src/cmd/file.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index d11be6027..54ad9e4f2 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -3,7 +3,7 @@ use serde_json::{Value as Json, json}; use super::{CommandSpec, Result, Session, always, bad, bool_param, cmd, edit, has_doc, ok, str_param, target_sheet, u32_param}; -use crate::DocState; +use crate::{DocState, EngineError}; pub fn specs() -> Vec { vec![ From 15eef6b4343a5ed9656686e7d0ccdaeb9ea4a278 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:59:52 -0500 Subject: [PATCH 07/10] Extract XLSX write validation helper --- crates/xlsx/src/write.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 8e025c8a8..0c9236063 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -204,6 +204,16 @@ fn check_sheet_names(wb: &Workbook) -> Result<(), IoError> { /// Workbook name written in a PivotChart's link when the file name isn't known. const DEFAULT_BOOK_NAME: &str = "Workbook.xlsx"; +fn check_write_xlsx(wb: &Workbook) -> Result<(), IoError> { + if wb.sheets.is_empty() { + return Err(IoError::Format("a workbook needs at least one sheet".into())); + } + if wb.sheets.iter().any(|sheet| sheet.cell_pictures.keys().any(|c| sheet.cell(*c).is_some_and(|cell| cell.formula.is_some()))) { + return Err(IoError::Format("a static cell picture cannot also contain a formula".into())); + } + check_sheet_names(wb) +} + pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { write_xlsx_named(wb, kind, None) } @@ -211,13 +221,7 @@ pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { /// Writes the workbook for the file `book_name` (a bare file name). A PivotChart is bound to its /// PivotTable in Excel only when its link starts with the workbook in brackets. pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) -> Result, IoError> { - if wb.sheets.is_empty() { - return Err(IoError::Format("a workbook needs at least one sheet".into())); - } - if wb.sheets.iter().any(|sheet| sheet.cell_pictures.keys().any(|c| sheet.cell(*c).is_some_and(|cell| cell.formula.is_some()))) { - return Err(IoError::Format("a static cell picture cannot also contain a formula".into())); - } - check_sheet_names(wb)?; + check_write_xlsx(wb)?; let mut out = Out { parts: vec![], overrides: vec![], From cd6fe4f8bd81595f34a0cc4436c0291fd0a62ba7 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:05:24 -0500 Subject: [PATCH 08/10] Extract file sharing XML writer --- crates/xlsx/src/write.rs | 45 +++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 0c9236063..ac08434c9 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -214,6 +214,29 @@ fn check_write_xlsx(wb: &Workbook) -> Result<(), IoError> { check_sheet_names(wb) } +fn append_file_sharing(w: &mut String, wb: &Workbook) { + let Some(r) = &wb.write_reservation else { return }; + w.push_str(" { + let _ = write!(w, " reservationPassword=\"{h:04X}\""); + } + Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), + None => {} + } + w.push_str("/>"); +} + pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { write_xlsx_named(wb, kind, None) } @@ -263,27 +286,7 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) // only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it. let file_version = crate::passthrough::workbook_elements(wb, "fileVersion"); w.push_str(if file_version.is_empty() { "" } else { &file_version }); - if let Some(r) = &wb.write_reservation { - w.push_str(" { - let _ = write!(w, " reservationPassword=\"{h:04X}\""); - } - Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), - None => {} - } - w.push_str("/>"); - } + append_file_sharing(&mut w, wb); w.push_str(" {} From 2be4be9dd2b5b35fc627c9ada4d594b78f4ce56e Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:04:18 -0600 Subject: [PATCH 09/10] Reduce dialog display complexity --- crates/ui-egui/src/dialogs/show.rs | 42 ++++++++++++++++-------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/dialogs/show.rs b/crates/ui-egui/src/dialogs/show.rs index e0a24a548..9b02051c4 100644 --- a/crates/ui-egui/src/dialogs/show.rs +++ b/crates/ui-egui/src/dialogs/show.rs @@ -121,6 +121,27 @@ pub(crate) fn build_params(d: &Dialog) -> Json { v } +fn command_error(app: &mut SheetApp, d: &mut Dialog, e: String) { + if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) { + // Data Analysis asks before replacing data in its output range. + d.values.insert("askOverwrite".into(), json!(true)); + } else if d.name == "openPassword" && e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) { + // The decryption password opened an encrypted, reserved workbook; ask for the modify password. + let mut params = Json::Object(d.values.clone()); + params["modify"] = json!(true); + if let Some(next) = Dialog::open(app, "openPassword", params) { + *d = Dialog { back: d.back.take(), ..next }; + } + } else if d.name == "openPassword" { + // A wrong password: say so, clear the field and stay open for another try. + let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" }; + d.values.insert(field.into(), json!("")); + app.message = Some((d.title.clone(), crate::clean_error(&e))); + } else { + app.message = Some((d.title.clone(), crate::clean_error(&e))); + } +} + /// Takes and draws the active dialog, dispatches its body by name, consumes picture-inbox results, runs OK/confirm commands, handles Esc/close and restores the back-dialog stack. pub fn show(app: &mut SheetApp, ctx: &egui::Context) { let Some(mut d) = app.dialog.take() else { return }; @@ -431,26 +452,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { app.after_open(path.as_deref(), &r); } } - // Data Analysis asks before replacing data in its output range. - Err(e) if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) => { - d.values.insert("askOverwrite".into(), json!(true)); - } - // Encrypted and reserved: the password opened it, so the form turns to the password to - // modify. The decryption password stays in the values for the retry. - Err(e) if d.name == "openPassword" && e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { - let mut params = Json::Object(d.values.clone()); - params["modify"] = json!(true); - if let Some(next) = Dialog::open(app, "openPassword", params) { - d = Dialog { back: d.back.take(), ..next }; - } - } - // A wrong password: say so, clear the field and stay open for another try. - Err(e) if d.name == "openPassword" => { - let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" }; - d.values.insert(field.into(), json!("")); - app.message = Some((d.title.clone(), crate::clean_error(&e))); - } - Err(e) => app.message = Some((d.title.clone(), crate::clean_error(&e))), + Err(e) => command_error(app, &mut d, e), } } else if confirm { open = false; From 5d578bef00919d072c9620edd24c366d0b310708 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:05:11 -0600 Subject: [PATCH 10/10] Record model SHA-1 dependency in lockfile --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index dfdde30e7..1c69b16c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2150,6 +2150,7 @@ dependencies = [ "gridcraft-math", "serde", "serde_json", + "sha1 0.11.0", "sha2 0.11.1", "thiserror 2.0.21", ]