#3720: budget hostile large parameters, and cap the TOC title (#5824)

This commit is contained in:
socrabs151 authored and GitHub committed 2026-11-17 06:19:32 +01:00
1 parent 93bf14883c
commit 406befeaa2
4 files changed
+97 -3

No files matched your search

+1 -1
View File
@@ -32,7 +32,7 @@ use toc::{insert_toc, remove_toc, toc_range};
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("references.toc", "Table of Contents", "References › Table of Contents", insert_toc).params(
r#"{"levels"?: 1-9, "title"?: string, "pageNumbers"?: bool, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "hyperlinks"?: bool, "headingStyles"?: bool, "outlineLevels"?: bool, "tcFields"?: bool, "styleLevels"?: {style name: 1-9}} (replaces an existing table; {} updates it)"#,
r#"{"levels"?: 1-9, "title"?: string (at most 1024 characters), "pageNumbers"?: bool, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none", "hyperlinks"?: bool, "headingStyles"?: bool, "outlineLevels"?: bool, "tcFields"?: bool, "styleLevels"?: {style name: 1-9}} (replaces an existing table; {} updates it)"#,
),
CommandSpec::new("references.updateToc", "Update Table", "References › Table of Contents", |s, _| {
update_toc(s)?;
+12
View File
@@ -1,6 +1,18 @@
use super::properties::{new_property_value, text_result};
use super::*;
#[test]
fn a_toc_title_is_capped() {
let mut s = Session::new(wordcraft_doc::Document::new());
let before = s.doc.body.len();
let long = "x".repeat(super::toc::MAX_TOC_TITLE + 1);
let r = s.run("references.toc", &json!({"title": long}));
assert!(matches!(r, Err(crate::CmdError::Params(_))), "{r:?}");
assert_eq!(s.doc.body.len(), before, "a rejected title changes nothing");
let at_cap = "x".repeat(super::toc::MAX_TOC_TITLE);
s.run("references.toc", &json!({"title": at_cap})).unwrap();
}
fn fields(s: &Session) -> Vec<(String, String)> {
let mut out = Vec::new();
for path in s.doc.para_paths(StoryRef::Body) {
+15 -2
View File
@@ -3,6 +3,18 @@ use super::{
StoryRef, TabAlign, TabLeader, TabStop, Value, delete_selection, p, sel_result,
};
/// A table-of-contents title is a heading, not document body: longer titles are rejected
/// instead of laying out megabytes of text (#3720).
pub(super) const MAX_TOC_TITLE: usize = 1024;
fn checked_title(v: &Value) -> Result<Option<&str>, CmdError> {
let Some(title) = p::str(v, "title") else { return Ok(None) };
if title.chars().count() > MAX_TOC_TITLE {
return Err(CmdError::Params(format!("`title` is longer than {MAX_TOC_TITLE} characters")));
}
Ok(Some(title))
}
/// A level range such as `1-3` (or one level, `2`), clamped to 1–9.
pub fn level_range(s: &str) -> Option<(u8, u8)> {
let mut it = s.split('-').map(|x| x.trim().parse::<u8>().ok());
@@ -382,6 +394,7 @@ pub(super) fn cached_toc_tabs(s: &Session) -> Vec<(String, Vec<TabStop>)> {
}
pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
let title = checked_title(v)?.unwrap_or("Contents").to_string();
let tabs = cached_toc_tabs(s);
range_toc_to_field(s)?;
let replace = v.as_object().is_some_and(|m| !m.is_empty());
@@ -410,7 +423,6 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
}
None => delete_selection(s)?,
};
let title = p::str(v, "title").unwrap_or("Contents").to_string();
if at.story != StoryRef::Body || at.path.depth() > 0 {
return Err(CmdError::Failed("a table of contents goes in the main text".into()));
}
@@ -440,6 +452,7 @@ pub(super) fn insert_toc(s: &mut Session, v: &Value) -> CmdResult {
/// (`title_above_break`): the field takes `v`'s settings, the title `v`'s `title` if one is given
/// (otherwise it is kept, as Word's Insert Table of Contents keeps it), and the entries are rebuilt.
fn replace_toc_above_break(s: &mut Session, v: &Value, start: usize, tabs: &[(String, Vec<TabStop>)]) -> Result<(), CmdError> {
let new_title = checked_title(v)?;
let instr = toc_instr(v);
let field = s.doc.para_mut(StoryRef::Body, &Path::top(start))?;
for o in &mut field.objects {
@@ -453,7 +466,7 @@ fn replace_toc_above_break(s: &mut Session, v: &Value, start: usize, tabs: &[(St
}
}
field.touch();
if let (Some(title), Some(i)) = (p::str(v, "title"), start.checked_sub(1)) {
if let (Some(title), Some(i)) = (new_title, start.checked_sub(1)) {
let old = s.doc.para_mut(StoryRef::Body, &Path::top(i))?;
let mut head = Paragraph::with_text(title, old.props_of_char(0).clone());
head.props = old.props.clone();
+69
View File
@@ -5,6 +5,7 @@ mod czech_test_dict;
use serde_json::json;
use std::sync::Arc;
use std::time::{Duration, Instant};
use wordcraft_doc::props::BorderStyle;
use wordcraft_doc::{Pos, StoryRef};
@@ -5184,6 +5185,74 @@ fn hostile_file_params_never_panic() {
let _ = std::fs::remove_dir_all(&base);
}
/// Large parameters must return and lay out within a generous wall-clock budget, so a regression
/// that loops or allocates without a cap fails here with its command id (#3720).
#[test]
fn hostile_large_params_stay_bounded() {
const BUDGET: Duration = Duration::from_secs(5);
let reg = cmd::registry();
// 1 MiB makes an uncapped copy or a quadratic scan visible without making the test itself
// expensive; the counts are large enough that an uncapped loop takes seconds.
let big = "x".repeat(1 << 20);
let mut deep = json!([]);
for _ in 0..64 {
deep = json!([deep]);
}
let junk = [
json!({
"text": big, "name": big, "label": big, "find": big, "replace": big,
"title": big, "author": big, "path": big,
}),
json!({
"count": 1_000_000_000u64, "copies": 1_000_000_000u64, "times": 1_000_000_000u64,
"cols": 1_000_000_000u64, "rows": 1_000_000_000u64, "level": 1_000_000_000u64,
"page": 1_000_000_000u64, "from": 1_000_000_000u64, "to": 1_000_000_000u64,
"id": 1_000_000_000u64,
}),
json!({"width": 3e38, "height": 3e38, "top": -3e38, "left": 3e38}),
json!({"path": deep}),
];
for spec in reg.all() {
if spec.id.starts_with("file.") || spec.id == "insert.picture" || spec.id == "insert.textFromFile" {
continue;
}
for j in &junk {
let mut s = Session::new(crate::sample::sample_document());
assert_ne!(s.read_aloud.backend, crate::speech::Backend::System, "tests must never start real speech");
let start = Instant::now();
let r = s.run(spec.id, j);
let elapsed = start.elapsed();
assert!(!caught_panic(&reg, &r), "{} panicked on large params: {r:?}", spec.id);
assert_within_budget(spec.id, elapsed, BUDGET);
// Laying the result out is not part of the command's budget; the layout tests
// cover long text separately. It still runs so a bad parameter reaches the layout.
s.clamp_selection();
let _ = s.layout();
}
}
}
fn assert_within_budget(id: &str, elapsed: Duration, budget: Duration) {
assert!(elapsed <= budget, "{id} took {elapsed:?} (budget {budget:?})");
}
/// The budget above fires: a command that runs past it is named, not ignored (#3720).
#[test]
#[should_panic(expected = "test.slow took")]
fn hostile_large_param_budget_flags_a_slow_command() {
let budget = Duration::from_millis(1);
let mut s = Session::new(crate::sample::sample_document());
let slow = crate::CommandSpec::new("test.slow", "Slow", "", |_, _| {
std::thread::sleep(Duration::from_millis(20));
Ok(json!({}))
})
.pure();
s.registry = Arc::new(crate::Registry::new(vec![slow]));
let start = Instant::now();
let _ = s.run("test.slow", &json!({}));
assert_within_budget("test.slow", start.elapsed(), budget);
}
/// A panic that `Session::run`'s guard turned into an error, in a command or one it ran: still a
/// crash path (#3718). Only the guard's own `"{id} panicked: "` counts, not an error that echoes
/// those words.