Merge pull request #2508 from Harrison-Booth/gc-a24-password-to-modify

XLSX: password to modify is kept on save and asked for on open
This commit is contained in:
FredApps
2026-11-26 20:29:34 +01:00
committed by GitHub
18 changed files with 243 additions and 16 deletions
Generated
+1
View File
@@ -2987,6 +2987,7 @@ dependencies = [
"gridcraft-math",
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.1",
"thiserror 2.0.21",
]
+2
View File
@@ -67,6 +67,8 @@ regex = { version = "1", default-features = false, features = ["std", "unicode",
quick-xml = "0.41"
zip = { version = "9.8.2", default-features = false, features = ["deflate"] }
sha2 = { version = "0.11", default-features = false }
# Verifying SHA-1 iterated protection hashes (`crates/model/src/password.rs`).
sha1 = { version = "0.11", default-features = false }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
# equations: RaTeX (MIT) lays LaTeX out as positioned glyphs, rules and paths. Exact pins: it is
+3 -1
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (XLSX password to modify is kept and enforced; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365)
@@ -170,6 +170,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-24 | PivotTables: right-clicking a value, subtotal or grand total cell offers Show Details in the cell menu, which lists the cell's source records on a new sheet as double-clicking does |
| 2026-10-24 | Sheet tabs: dragging the handle between the tabs and the horizontal scrollbar gives the tabs more or less of the bar, as in Excel; each open workbook keeps its own share |
| 2026-10-24 | Charts: 100% Stacked Area (`insert.chart` `{type: "area", subtype: "stacked100"}`), drawn as each value's share of its category's total; XLSX `percentStacked` area charts open as 100% stacked instead of stacked |
| 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) |
@@ -317,6 +318,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column |
| 2026-10-24 | minor | Macro interface on the Automate tab; progress log row |
| 2026-10-24 | minor | Macro engine and `macro.*` commands; catalog 275 / 291 → 276 / 292 (View › Macros › Record Macro); progress log row |
| 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) |
+30 -3
View File
@@ -3,12 +3,12 @@
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<CommandSpec> {
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),
@@ -59,6 +59,19 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
};
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
@@ -78,7 +91,7 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
// 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()))
@@ -87,6 +100,9 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
}
// 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);
}
@@ -106,6 +122,14 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
)
}
/// 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<Json> {
let path = match str_param(p, "path").map(str::to_string).or_else(|| s.active().and_then(|d| d.path.clone())) {
Some(p) => p,
@@ -114,6 +138,9 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
return ok();
}
};
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
// document keeps its file and its unsaved changes.
if std::path::Path::new(&path).extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) {
+4
View File
@@ -53,6 +53,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.
+4
View File
@@ -206,6 +206,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<io::FileKind>,
/// 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<String>,
/// 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
@@ -364,6 +367,7 @@ impl DocState {
sheet_selections: vec![],
unlocked_ranges: vec![],
content_kind: None,
read_only_source: None,
scripts_trusted,
trust,
touched: None,
+69
View File
@@ -5589,6 +5589,75 @@ fn encrypted_book(password: &str) -> Vec<u8> {
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();
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();
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 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");
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(&copy).is_ok());
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn encrypted_workbooks_open_with_their_password() {
const PW: &str = "synthetic-pw-5521";
+1
View File
@@ -15,6 +15,7 @@ test-support = []
[dependencies]
gridcraft-core = { workspace = true }
sha1 = { workspace = true }
sha2 = { workspace = true }
gridcraft-formula = { workspace = true }
gridcraft-math = { workspace = true }
+1 -1
View File
@@ -32,7 +32,7 @@ pub use style::{
};
pub use workbook::{
CalcMode, CalcSettings, DefinedName, DocProps, EQUATION_BUDGET_MESSAGE, MAX_EQUATION_LAYOUT_BYTES, PhoneticProps, PhoneticRun, PhoneticString,
RefHost, ShowObjects, Workbook, WorkbookView,
RefHost, ShowObjects, Workbook, WorkbookView, WriteReservation,
};
/// Font used for new workbooks. Only a name: renderers substitute an available open font
+15 -1
View File
@@ -160,6 +160,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::<sha1::Sha1>(password, &salt, *spin_count),
"SHA-512" => iterated::<sha2::Sha512>(password, &salt, *spin_count),
"SHA-384" => iterated::<sha2::Sha384>(password, &salt, *spin_count),
"SHA-256" => iterated::<sha2::Sha256>(password, &salt, *spin_count),
@@ -236,6 +237,19 @@ mod tests {
Ok(())
}
#[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() -> Result<(), Box<dyn std::error::Error>> {
let h = PasswordHash::new_sha512("s3cret", b"0123456789abcdef");
@@ -245,7 +259,7 @@ mod tests {
let PasswordHash::Iterated { hash, salt, .. } = h else { return Err("not an iterated hash".into()) };
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")?);
+13
View File
@@ -224,6 +224,9 @@ pub struct Workbook {
/// alone has none and is not written there.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub structure_password: Option<crate::PasswordHash>,
/// "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<WriteReservation>,
/// Custom fill lists (Options › Custom Lists) beyond the built-in ones.
pub custom_lists: Vec<Vec<String>>,
/// Named cell styles (Cell Styles gallery): name → style.
@@ -294,6 +297,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<crate::PasswordHash>,
}
/// The active sheet index of a [`Workbook`].
///
/// Every other part of a workbook value is immutable once shared (the engine keeps versions as
@@ -564,6 +576,7 @@ impl Workbook {
props: DocProps::default(),
protected_structure: false,
structure_password: None,
write_reservation: None,
custom_lists: vec![],
cell_styles: vec![],
phonetics: vec![],
+7
View File
@@ -6,6 +6,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();
@@ -95,6 +98,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();
+16
View File
@@ -458,6 +458,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 Some(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",
+22 -10
View File
@@ -122,6 +122,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 };
@@ -444,16 +465,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));
}
// 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!(""));
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;
+8
View File
@@ -295,6 +295,14 @@ fn read_workbook_properties(cx: &mut Ctx<'_>, wb: &mut Workbook, xml: &El) {
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) = 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")),
});
}
}
/// The single window modelled by GridCraft: prefer the first visible window,
+21
View File
@@ -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, r1c1: 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 & <Bob>".into(),
read_only_recommended: true,
password: Some(gridcraft_model::PasswordHash::new_sha512("modify-me", b"fedcba9876543210")),
});
wb.props = DocProps {
title: "T & <x>".into(),
subject: "S".into(),
@@ -532,6 +537,8 @@ fn assert_workbook_metadata_roundtrip(wb: &Workbook, back: &Workbook) {
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);
@@ -2031,6 +2038,20 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() {
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();
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)));
}
#[test]
fn workbook_view_settings_survive_a_round_trip() {
// #3057: a workbook Excel saved with the sheet tabs and both scroll bars hidden
+24
View File
@@ -239,6 +239,29 @@ 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 append_file_sharing(w: &mut String, wb: &Workbook) {
let Some(r) = &wb.write_reservation else { return };
w.push_str("<fileSharing");
if r.read_only_recommended {
w.push_str(" readOnlyRecommended=\"1\"");
}
// 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 {
Some(gridcraft_model::PasswordHash::Legacy(h)) => {
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, functions: FunctionInfo) -> Result<Vec<u8>, IoError> {
write_xlsx_named_with(wb, kind, None, functions)
}
@@ -479,6 +502,7 @@ fn write_workbook_xml(
// 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() { "<fileVersion appName=\"gridcraft\"/>" } else { &file_version });
append_file_sharing(&mut w, wb);
w.push_str("<workbookPr");
match wb.show_objects {
ShowObjects::All => {}
+2
View File
@@ -100,6 +100,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real
| `.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 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
@@ -196,6 +197,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
| 2026-10-26 | minor | PDF honors cell Context/LTR/RTL, preserves paragraph direction across wrapping, and mirrors RTL sheet geometry without reversing glyphs |
| 2026-10-26 | minor | Arabic PDF export embeds licensed glyph outlines, joins letters and marks, preserves logical text and reports unsupported glyphs before writing; Arabic runs take the embedded faces ahead of the CJK CID font, and CJK inside Arabic text is set in the CID font instead of failing the export |
| 2026-10-26 | minor | Alignment readingOrder 0/1/2 survives cell, named-style and differential-style round-trips; Format Cells exposes reading direction and CF priority preserves unspecified inheritance |
| 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-22 | minor | XLSX column widths: `customWidth` without `bestFit` is a width set by hand, others (AutoFit, widened by a number format) are automatic, as Excel 16.0 reads them; written the same way (`bestFit="1" customWidth="1"` for automatic widths). `.xls` reads COLINFO's fUserSet as set by hand (the shared craft-xls reader does not report fBestFit) (#1077) |
| 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI `<img>`) 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 (ふりがな, `<rPh sb="…" eb="…">` with `<phoneticPr>`) 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 `<phoneticPr>` without runs is kept on its own, and when duplicate `<si>` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) |