Compare commits

..
Author SHA1 Message Date
Dylan M. Taylor 052ee60218 Get Data: refuse an import whose dense rows would be too large
data.getData and data.fromTextCsv built every row densely before
writing it: JSON records were padded to the union of all keys (found
with a quadratic Vec::contains scan), and CSV cells were expanded over
the whole used rectangle. A few sparse records or one far-away CSV
cell therefore allocated billions of slots.

The importer now collects JSON keys with a HashSet, refuses more keys
than a sheet has columns, and checks the projected rows x columns
against MAX_IMPORT_CELLS (10,000,000) before building any row.
2026-11-02 20:34:32 -05:00
2 changed files with 55 additions and 74 deletions
+3 -73
View File
@@ -6,10 +6,6 @@ const MAX_XML_PART: u64 = 64 * 1024 * 1024;
/// Most zip entries looked at while validating a written package.
const MAX_ENTRIES: usize = 200_000;
/// Decompressed bytes that comparing one package's relationship kinds may read in total: the
/// relationship parts themselves and the targets whose content is checked.
const RELATIONSHIP_BUDGET: u64 = 512 * 1024 * 1024;
/// Relationship kinds (lower case) whose absence after a save isn't a loss: the calculation chain is
/// a cache Excel rebuilds, and GridCraft never writes it.
pub(super) const REBUILT_KINDS: [&str; 1] = ["calcchain"];
@@ -121,28 +117,6 @@ fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result<Vec<u8>, String> {
Ok(buf)
}
enum PartError {
/// Reading the part would spend more than the remaining budget.
OverBudget,
Unreadable,
}
/// Reads a part like [`read_zip_part`], charging the decompressed bytes to `budget`.
fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Result<Vec<u8>, PartError> {
let f = zip.by_name(name).map_err(|_| PartError::Unreadable)?;
// One byte past what is left shows that the part doesn't fit.
let limit = MAX_XML_PART.min(budget.saturating_add(1));
let mut buf = Vec::new();
f.take(limit).read_to_end(&mut buf).map_err(|_| PartError::Unreadable)?;
let read = buf.len() as u64;
if read > *budget {
*budget = 0;
return Err(PartError::OverBudget);
}
*budget -= read;
Ok(buf)
}
/// Whether the producer flagged its cached results as stale with `<calcPr fullCalcOnLoad="1">`:
/// libraries that don't calculate write it, and store 0 or nothing as every formula's value.
pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
@@ -258,30 +232,19 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
/// nothing are left out, as a save may rightly drop them: a link to a place in the workbook
/// (`#Sheet1!A1`, written as a cell's `location`) and a target part with nothing in it.
pub(super) fn relationship_kinds(bytes: &[u8]) -> Result<BTreeMap<String, String>, String> {
relationship_kinds_within(bytes, RELATIONSHIP_BUDGET)
}
/// [`relationship_kinds`] reading at most `budget` decompressed bytes. `Err` once the relationship
/// parts alone need more: their kinds can't be listed completely.
fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<String, String>, String> {
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
let names = zip_names(&mut zip);
let by_key: HashMap<String, &String> = names.iter().map(|n| (part_key(n), n)).collect();
// Several relationships name the same part; each fresh check decompressed it again, so
// repeated references to one highly compressible part multiplied the work. The verdict is
// remembered per (part, named content) and the decompression the package can cause is
// budgeted as a whole, the relationship parts included: many large, unreferenced rels parts
// would otherwise each spend a full per-part allowance.
// budgeted as a whole (finding: repeated decompression).
let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new();
let mut budget: u64 = 512 * 1024 * 1024;
let mut kinds = BTreeMap::new();
for n in names.iter().filter(|n| part_key(n).ends_with(".rels")) {
let Some(src_dir) = rels_source_dir(&part_key(n)) else { continue };
let xml = match read_zip_part_within(&mut zip, n, &mut budget) {
Ok(xml) => xml,
Err(PartError::OverBudget) => return Err(format!("{n}: relationship check stopped at its decompression limit")),
Err(PartError::Unreadable) => continue,
};
let Ok(els) = xml_elements(&xml) else { continue };
let Ok(els) = read_zip_part(&mut zip, n).and_then(|xml| xml_elements(&xml)) else { continue };
for (_, attrs) in els.iter().filter(|(el, _)| el == "Relationship") {
let Some(kind) = attr(attrs, "Type").and_then(|t| t.rsplit('/').next()) else { continue };
let target = attr(attrs, "Target").unwrap_or("");
@@ -366,36 +329,3 @@ fn holds_something_uncached(zip: &mut Zip<'_>, name: &str, marker: &'static str,
buf.clear();
}
}
#[cfg(test)]
mod tests {
use std::io::Write as _;
use super::*;
/// A package with `count` relationship parts of `size` bytes each, none of them describing an
/// existing part.
fn many_rels(count: usize, size: usize) -> Vec<u8> {
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
let head = r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom" Target="https://example.com" TargetMode="External"/>"#;
let tail = "</Relationships>";
let filler = " ".repeat(size.saturating_sub(head.len() + tail.len()));
for i in 0..count {
z.start_file(format!("xl/_rels/part{i}.xml.rels"), opts).unwrap();
z.write_all(head.as_bytes()).unwrap();
z.write_all(filler.as_bytes()).unwrap();
z.write_all(tail.as_bytes()).unwrap();
}
z.finish().unwrap().into_inner()
}
#[test]
fn relationship_parts_count_against_the_decompression_budget() {
// Each part fits the per-part allowance, but together they need more than the budget.
let bytes = many_rels(8, 64 * 1024);
assert!(relationship_kinds_within(&bytes, 256 * 1024).is_err());
let kinds = relationship_kinds_within(&bytes, 1024 * 1024).unwrap();
assert_eq!(kinds.get("custom").map(String::as_str), Some("custom"));
}
}
+52 -1
View File
@@ -42,6 +42,15 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// Most cells (rows × columns, blanks included) Get Data imports. The rows are built densely
/// before they are written, so a few sparse records or one far-away CSV cell must not expand
/// into a rectangle of billions of slots.
const MAX_IMPORT_CELLS: u64 = 10_000_000;
fn too_many_cells() -> EngineError {
EngineError::Other(format!("The data is too large to import ({MAX_IMPORT_CELLS} cells at most)."))
}
pub(super) fn from_csv(s: &mut Session, p: &Json) -> Result<Json> {
let bytes = if let Some(t) = str_param(p, "text") {
t.as_bytes().to_vec()
@@ -57,15 +66,22 @@ pub(super) fn from_csv(s: &mut Session, p: &Json) -> Result<Json> {
if text.trim_start().starts_with('[') {
let arr: Vec<Json> = serde_json::from_str(&text).map_err(|e| bad("data.getData", e.to_string()))?;
let mut keys: Vec<String> = Vec::new();
let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
for o in &arr {
if let Some(m) = o.as_object() {
for k in m.keys() {
if !keys.contains(k) {
if seen.insert(k.as_str()) {
keys.push(k.clone());
}
}
}
}
if keys.len() > gridcraft_core::MAX_COLS as usize {
return Err(EngineError::Other("The data has more fields than a sheet has columns.".into()));
}
if (arr.len() as u64 + 1).saturating_mul(keys.len().max(1) as u64) > MAX_IMPORT_CELLS {
return Err(too_many_cells());
}
let mut out = vec![keys.iter().map(|k| json!(k)).collect::<Vec<_>>()];
for o in &arr {
out.push(keys.iter().map(|k| o.get(k).cloned().unwrap_or(Json::Null)).collect());
@@ -79,6 +95,9 @@ pub(super) fn from_csv(s: &mut Session, p: &Json) -> Result<Json> {
let wb = gridcraft_xlsx::read_csv(&bytes, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
let sh = wb.sheet(0).ok_or(EngineError::NoDocument)?;
let Some(u) = sh.used_range() else { return Err(EngineError::Other("The file is empty.".into())) };
if u.count() > MAX_IMPORT_CELLS {
return Err(too_many_cells());
}
(u.start.row..=u.end.row)
.map(|r| {
(u.start.col..=u.end.col)
@@ -129,3 +148,35 @@ pub(super) fn queries(s: &mut Session, _: &Json) -> Result<Json> {
.collect(),
))
}
#[cfg(test)]
mod tests {
use serde_json::json;
use crate::Session;
fn s() -> Session {
let mut s = Session::new();
s.new_workbook();
s
}
#[test]
fn sparse_imports_are_refused_before_their_rows_are_built() {
let mut s = s();
let sheets = s.doc().unwrap().wb.sheets.len();
// 5,000 records with one field each: 5,001 × 5,000 slots once every record gets every field.
let records: Vec<_> = (0..5_000).map(|i| json!({ format!("k{i}"): i })).collect();
let text = serde_json::to_string(&records).unwrap();
let err = s.execute("data.getData", json!({"text": text})).expect_err("too many cells");
assert!(err.to_string().contains("too large"), "{err}");
// A CSV whose last line reaches 16,001 columns, 1,000 lines down.
let text = format!("1{}{}x", "\n".repeat(999), ",".repeat(16_000));
let err = s.execute("data.fromTextCsv", json!({"text": text})).expect_err("too many cells");
assert!(err.to_string().contains("too large"), "{err}");
assert_eq!(s.doc().unwrap().wb.sheets.len(), sheets);
// Small imports still work.
let out = s.execute("data.getData", json!({"text": r#"[{"a": 1}, {"b": 2}]"#})).unwrap();
assert_eq!((out["rows"].as_u64(), out["cols"].as_u64()), (Some(3), Some(2)), "{out}");
}
}