From be3933a9adb49afc1e299f9fdce6856a9a0cae31 Mon Sep 17 00:00:00 2001 From: sudo-py-dev Date: Wed, 25 Nov 2026 07:34:44 +0200 Subject: [PATCH 1/3] Fix conversion bugs and harden release signing and tool lookup Bugs: - RTF: skip Word's \'hh fallback after \uN, so Cyrillic and Hebrew text no longer gains a stray Latin-1 character after every letter. - Office to PDF: find LibreOffice's output for names with extra dots ("a.v2.doc" -> "a.v2.pdf" instead of looking for "a.pdf"). - DOCX/ODT: keep the outer row and cell while reading a nested table, so earlier cells are no longer dropped. ODT gets the same depth and copy limits as DOCX. Hardening: - ffmpeg conversion inputs only allow the file and pipe protocols, as probing already did, so crafted playlists cannot make ffmpeg fetch URLs. - Tool lookup ignores empty or relative PATH entries instead of searching the current folder. - Release workflow builds rsign2 fresh instead of restoring the binary that receives the signing key from the Actions cache. Adds regression tests for the RTF and nested-table fixes and updates two plan tests for the new -protocol_whitelist argument. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 9 +-- src/exec.rs | 6 +- src/externals.rs | 8 ++- src/office.rs | 114 ++++++++++++++++++++++++++++++++-- src/plan.rs | 13 +++- 5 files changed, 132 insertions(+), 18 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2843f7f..2dac5f7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -169,14 +169,9 @@ jobs: with: path: dist merge-multiple: true - - name: Cache release signer - id: signer - uses: actions/cache@v6 - with: - path: ~/.cargo/bin/rsign - key: rsign2-0.6.7-${{ runner.os }}-${{ runner.arch }}-v1 - name: Install release signer - if: steps.signer.outputs.cache-hit != 'true' + # Built fresh on every release: a cached binary could be replaced by any + # workflow that can write this repository's Actions cache. run: cargo install rsign2 --locked --version 0.6.7 - name: Record package sizes run: | diff --git a/src/exec.rs b/src/exec.rs index 860bcf4..e4e833b 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -822,7 +822,11 @@ fn office(spec: &JobSpec, toolbox: &Toolbox, cancel: &AtomicBool) -> Result<(), run_plain(soffice, &args, cancel)?; let ext = "pdf"; let stem = input.file_stem().ok_or(JobError::NoOutput)?; - let produced = staging.path().join(stem).with_extension(ext); + // LibreOffice replaces only the last extension: "a.v2.doc" becomes "a.v2.pdf". + let mut name = stem.to_os_string(); + name.push("."); + name.push(ext); + let produced = staging.path().join(name); if !produced.is_file() { return Err(JobError::NoOutput); } diff --git a/src/externals.rs b/src/externals.rs index 32214fd..82b0db2 100644 --- a/src/externals.rs +++ b/src/externals.rs @@ -131,7 +131,13 @@ fn bundled_dirs() -> Vec { /// so a release always runs the exact tools it shipped with. fn find_program(names: &[&str]) -> Option { let path_dirs = std::env::var_os("PATH") - .map(|path| std::env::split_paths(&path).collect::>()) + // Empty or relative entries mean "the current folder", which may hold + // downloaded files; only absolute folders are searched. + .map(|path| { + std::env::split_paths(&path) + .filter(|d| d.is_absolute()) + .collect::>() + }) .unwrap_or_default(); let dirs: Vec = bundled_dirs().into_iter().chain(path_dirs).collect(); names.iter().find_map(|name| { diff --git a/src/office.rs b/src/office.rs index 87a5140..40e855a 100644 --- a/src/office.rs +++ b/src/office.rs @@ -20,7 +20,7 @@ const MAX_PART_BYTES: u64 = 64 << 20; const MAX_PPTX_CONTENT_BYTES: usize = 128 << 20; /// Largest plain-text input read whole. const MAX_TEXT_BYTES: u64 = 32 << 20; -/// Bound nested DOCX table state and total bytes copied while flattening tables. +/// Bound nested DOCX and ODF table state and total bytes copied while flattening tables. const MAX_DOCX_TABLE_DEPTH: usize = 32; const MAX_DOCX_TABLE_COPY_BYTES: usize = 64 << 20; /// Spreadsheet rows rendered per sheet. @@ -185,6 +185,8 @@ struct DocxState { tables: Vec>>, row: Vec, cell: String, + /// The enclosing row and cell, saved while a nested table is read. + outer: Vec<(Vec, String)>, table_copy_bytes: usize, } @@ -282,6 +284,10 @@ fn docx_blocks(xml: &str) -> Result, OfficeError> { if st.tables.len() >= MAX_DOCX_TABLE_DEPTH { return Err(corrupt("DOCX table nesting limit exceeded")); } + if !st.tables.is_empty() { + let saved = (std::mem::take(&mut st.row), std::mem::take(&mut st.cell)); + st.outer.push(saved); + } st.tables.push(Vec::new()); } "tr" => st.row.clear(), @@ -312,6 +318,13 @@ fn docx_blocks(xml: &str) -> Result, OfficeError> { if st.tables.is_empty() { st.blocks.push(Block::Table(rows)); } else { + if let Some((row, cell)) = st.outer.pop() { + st.row = row; + st.cell = cell; + } + if !st.cell.is_empty() { + st.append_nested_text("\n")?; + } // A nested table becomes text inside its parent cell. st.append_nested_table(&rows)?; } @@ -337,6 +350,9 @@ fn odf_blocks(xml: &str) -> Result, OfficeError> { let mut tables: Vec>> = Vec::new(); let mut row: Vec = Vec::new(); let mut cell = String::new(); + // The enclosing row and cell, saved while a nested table is read. + let mut outer: Vec<(Vec, String)> = Vec::new(); + let mut copied = 0usize; loop { match reader.read_event().map_err(corrupt)? { Event::Start(e) => match e.local_name().as_ref() { @@ -348,7 +364,15 @@ fn odf_blocks(xml: &str) -> Result, OfficeError> { } "p" => depth_text += 1, "list" => list_depth += 1, - "table" => tables.push(Vec::new()), + "table" => { + if tables.len() >= MAX_DOCX_TABLE_DEPTH { + return Err(corrupt("ODF table nesting limit exceeded")); + } + if !tables.is_empty() { + outer.push((std::mem::take(&mut row), std::mem::take(&mut cell))); + } + tables.push(Vec::new()); + } "table-row" => row.clear(), "table-cell" => cell.clear(), "page" if !blocks.is_empty() => blocks.push(Block::PageBreak), @@ -399,7 +423,21 @@ fn odf_blocks(xml: &str) -> Result, OfficeError> { } "table" => { if let Some(rows) = tables.pop() { - blocks.push(Block::Table(rows)); + if tables.is_empty() { + blocks.push(Block::Table(rows)); + } else if let Some((outer_row, outer_cell)) = outer.pop() { + // A nested table becomes text inside its parent cell. + (row, cell) = (outer_row, outer_cell); + let text = flatten_table(&rows); + copied = copied + .checked_add(text.len() + 1) + .filter(|&n| n <= MAX_DOCX_TABLE_COPY_BYTES) + .ok_or_else(|| corrupt("ODF nested table copy limit exceeded"))?; + if !cell.is_empty() { + cell.push('\n'); + } + cell.push_str(&text); + } } } _ => {} @@ -411,6 +449,14 @@ fn odf_blocks(xml: &str) -> Result, OfficeError> { Ok(blocks) } +/// A nested table as text: cells joined with ` | `, rows with line breaks. +fn flatten_table(rows: &[Vec]) -> String { + rows.iter() + .map(|row| row.join(" | ")) + .collect::>() + .join("\n") +} + /// One page per slide; the first text box becomes the slide's heading. fn pptx_blocks(path: &Path) -> Result, OfficeError> { pptx_blocks_with_limit(path, MAX_PPTX_CONTENT_BYTES) @@ -786,9 +832,22 @@ fn rtf_text(rtf: &str) -> String { { out.push(ch); } - // Skip the plain-text fallback that follows a Unicode escape. - if chars.peek().is_some_and(|c| !matches!(c, '\\' | '{' | '}')) { - chars.next(); + // Skip the fallback that follows a Unicode escape: one + // character, or one `\'hh` escape (what Word writes). + match chars.peek() { + Some('\\') => { + let mut ahead = chars.clone(); + ahead.next(); + if ahead.peek() == Some(&'\'') { + chars.next(); + chars.next(); + chars.by_ref().take(2).for_each(drop); + } + } + Some('{' | '}') | None => {} + Some(_) => { + chars.next(); + } } } _ => {} @@ -1126,6 +1185,42 @@ mod tests { assert_eq!(st.cell, "a | b\ncd", "reject before copying"); } + #[test] + fn docx_nested_table_keeps_outer_cells() { + let xml = r#" +A +beforexy +C +"#; + assert_eq!( + docx_blocks(xml).expect("parse"), + vec![Block::Table(vec![vec![ + "A".into(), + "before\nx | y".into(), + "C".into() + ]])] + ); + } + + #[test] + fn odf_nested_table_keeps_outer_cells() { + let xml = r#" + +A +beforexy +C + +"#; + assert_eq!( + odf_blocks(xml).expect("parse"), + vec![Block::Table(vec![vec![ + "A".into(), + "before\nx | y".into(), + "C".into() + ]])] + ); + } + #[test] fn odf_reads_headings_spaces_and_tables() { let xml = r#" @@ -1216,6 +1311,13 @@ mod tests { assert!(!text.contains("Arial")); } + #[test] + fn rtf_word_unicode_fallbacks_are_skipped() { + // Word writes each non-ASCII letter as \uN followed by a \'hh fallback. + let rtf = r"{\rtf1\ansi\ansicpg1251\uc1 \u1055\'cf\u1088\'f0\u1080\'e8 \u1513\'f9!}"; + assert_eq!(rtf_text(rtf), "При ש!"); + } + #[test] fn docx_round_trip_through_writer_and_reader() { let dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/plan.rs b/src/plan.rs index 0cb35ee..c40e905 100644 --- a/src/plan.rs +++ b/src/plan.rs @@ -154,7 +154,10 @@ impl Args { } fn input(self, path: &Path) -> Self { - self.flag("-i", input_url(path, None)) + // A crafted playlist or container must not make ffmpeg open URLs or + // other protocols: user files may only read local files. + self.flag("-protocol_whitelist", "file,pipe") + .flag("-i", input_url(path, None)) } fn output(mut self, path: &Path) -> PendingPlan { @@ -2132,7 +2135,11 @@ mod tests { ) .unwrap(); let cmd = joined(&p); - assert!(cmd.contains("-loop 1 -framerate 30 -i file:/in/photo.png")); + assert!( + cmd.contains( + "-loop 1 -framerate 30 -protocol_whitelist file,pipe -i file:/in/photo.png" + ) + ); assert!(cmd.contains("xfade=transition=slideright:duration=1.000000:offset=1.000000")); assert!(cmd.contains("anullsrc") && cmd.contains("acrossfade")); assert_eq!(p.expected_secs, Some(4.0)); @@ -2278,7 +2285,7 @@ mod tests { ) .expect("plan"); let cmd = joined(&p); - assert!(cmd.contains("-ss 5.000 -to 15.000 -i")); + assert!(cmd.contains("-ss 5.000 -to 15.000 -protocol_whitelist file,pipe -i")); assert!( cmd.contains( "-vf crop=640:360:10:20,transpose=1,subtitles=filename=/s/it\\\\\\'s\\\\: a\\,b.srt" From 60413c6f494c10eb8f5202aff127309aad8af430 Mon Sep 17 00:00:00 2001 From: sudo-py-dev Date: Wed, 25 Nov 2026 08:01:54 +0200 Subject: [PATCH 2/3] Address review: RTF \ucN, ODF copy budget, HLS crypto inputs - RTF: track the \ucN fallback count per group (default 1), so \uc0 keeps a following \'hh escape as text and \uc2 skips two units. - ODF: append nested tables through the same budgeted helper as DOCX, so oversized nested copies are rejected before allocating. - Conversion inputs also allow the crypto protocol, so local AES-128 HLS segments still decode; network protocols stay blocked. Co-Authored-By: Claude Opus 5.5 --- src/office.rs | 131 ++++++++++++++++++++++++++++++++------------------ src/plan.rs | 15 +++--- 2 files changed, 90 insertions(+), 56 deletions(-) diff --git a/src/office.rs b/src/office.rs index 40e855a..a437f0a 100644 --- a/src/office.rs +++ b/src/office.rs @@ -190,32 +190,45 @@ struct DocxState { table_copy_bytes: usize, } +/// Appends `text` to a table cell, charging `copied` before any byte is copied. +fn append_budgeted(cell: &mut String, copied: &mut usize, text: &str) -> Result<(), OfficeError> { + *copied = copied + .checked_add(text.len()) + .filter(|&bytes| bytes <= MAX_DOCX_TABLE_COPY_BYTES) + .ok_or_else(|| corrupt("nested table copy limit exceeded"))?; + cell.push_str(text); + Ok(()) +} + +/// Appends a nested table to its parent cell as text: cells joined with ` | `, +/// rows with line breaks. Every copied byte, including separators, is charged +/// before allocation; the budget is shared across the entire document. +fn append_nested_rows( + cell: &mut String, + copied: &mut usize, + rows: &[Vec], +) -> Result<(), OfficeError> { + for (row_index, row) in rows.iter().enumerate() { + if row_index > 0 { + append_budgeted(cell, copied, "\n")?; + } + for (cell_index, text) in row.iter().enumerate() { + if cell_index > 0 { + append_budgeted(cell, copied, " | ")?; + } + append_budgeted(cell, copied, text)?; + } + } + Ok(()) +} + impl DocxState { fn append_nested_text(&mut self, text: &str) -> Result<(), OfficeError> { - self.table_copy_bytes = self - .table_copy_bytes - .checked_add(text.len()) - .filter(|&bytes| bytes <= MAX_DOCX_TABLE_COPY_BYTES) - .ok_or_else(|| corrupt("DOCX nested table copy limit exceeded"))?; - self.cell.push_str(text); - Ok(()) + append_budgeted(&mut self.cell, &mut self.table_copy_bytes, text) } fn append_nested_table(&mut self, rows: &[Vec]) -> Result<(), OfficeError> { - // Append directly so every copied byte, including separators, is charged - // before allocation. The budget is shared across the entire document. - for (row_index, row) in rows.iter().enumerate() { - if row_index > 0 { - self.append_nested_text("\n")?; - } - for (cell_index, cell) in row.iter().enumerate() { - if cell_index > 0 { - self.append_nested_text(" | ")?; - } - self.append_nested_text(cell)?; - } - } - Ok(()) + append_nested_rows(&mut self.cell, &mut self.table_copy_bytes, rows) } fn push_text(&mut self, text: &str) { @@ -428,15 +441,10 @@ fn odf_blocks(xml: &str) -> Result, OfficeError> { } else if let Some((outer_row, outer_cell)) = outer.pop() { // A nested table becomes text inside its parent cell. (row, cell) = (outer_row, outer_cell); - let text = flatten_table(&rows); - copied = copied - .checked_add(text.len() + 1) - .filter(|&n| n <= MAX_DOCX_TABLE_COPY_BYTES) - .ok_or_else(|| corrupt("ODF nested table copy limit exceeded"))?; if !cell.is_empty() { - cell.push('\n'); + append_budgeted(&mut cell, &mut copied, "\n")?; } - cell.push_str(&text); + append_nested_rows(&mut cell, &mut copied, &rows)?; } } } @@ -449,14 +457,6 @@ fn odf_blocks(xml: &str) -> Result, OfficeError> { Ok(blocks) } -/// A nested table as text: cells joined with ` | `, rows with line breaks. -fn flatten_table(rows: &[Vec]) -> String { - rows.iter() - .map(|row| row.join(" | ")) - .collect::>() - .join("\n") -} - /// One page per slide; the first text box becomes the slide's heading. fn pptx_blocks(path: &Path) -> Result, OfficeError> { pptx_blocks_with_limit(path, MAX_PPTX_CONTENT_BYTES) @@ -767,14 +767,21 @@ fn rtf_text(rtf: &str) -> String { // Brace depth at which an ignored group started, if any. let mut skip_from: Option = None; let mut depth = 0usize; + // Fallback units after each `\uN` (`\ucN`, scoped to its group; default 1). + let mut uc = 1usize; + let mut outer_uc: Vec = Vec::new(); while let Some(c) = chars.next() { match c { - '{' => depth += 1, + '{' => { + depth += 1; + outer_uc.push(uc); + } '}' => { if skip_from == Some(depth) { skip_from = None; } depth = depth.saturating_sub(1); + uc = outer_uc.pop().unwrap_or(1); } '\\' => { let mut word = String::new(); @@ -817,6 +824,9 @@ fn rtf_text(rtf: &str) -> String { if chars.peek() == Some(&' ') { chars.next(); } + if word == "uc" { + uc = param.parse().unwrap_or(1); + } if SKIP_GROUPS.contains(&word.as_str()) && skip_from.is_none() { skip_from = Some(depth); } @@ -832,21 +842,25 @@ fn rtf_text(rtf: &str) -> String { { out.push(ch); } - // Skip the fallback that follows a Unicode escape: one - // character, or one `\'hh` escape (what Word writes). - match chars.peek() { - Some('\\') => { - let mut ahead = chars.clone(); - ahead.next(); - if ahead.peek() == Some(&'\'') { + // Skip the `\ucN` fallback units that follow a Unicode + // escape: each is one character or one `\'hh` escape + // (what Word writes). `\uc0` means there is none. + for _ in 0..uc { + match chars.peek() { + Some('\\') => { + let mut ahead = chars.clone(); + ahead.next(); + if ahead.peek() != Some(&'\'') { + break; + } chars.next(); chars.next(); chars.by_ref().take(2).for_each(drop); } - } - Some('{' | '}') | None => {} - Some(_) => { - chars.next(); + Some('{' | '}') | None => break, + Some(_) => { + chars.next(); + } } } } @@ -1221,6 +1235,18 @@ mod tests { ); } + #[test] + fn odf_nested_payload_hits_copy_budget_before_copying() { + let xml = format!( + "{}{}{}", + "".repeat(18), + "x".repeat(4 << 20), + "".repeat(18) + ); + assert!(matches!(odf_blocks(&xml), + Err(OfficeError::Corrupt(message)) if message.contains("copy limit"))); + } + #[test] fn odf_reads_headings_spaces_and_tables() { let xml = r#" @@ -1318,6 +1344,15 @@ mod tests { assert_eq!(rtf_text(rtf), "При ש!"); } + #[test] + fn rtf_fallback_count_follows_uc_and_its_group() { + // `\uc0` means no fallback, so the hex escape is real text. + assert_eq!(rtf_text(r"{\rtf1\ansi\uc0\u945\'42}"), "αB"); + // `\ucN` is scoped to its group and restored when the group ends. + let rtf = r"{\uc2\u945ab{\uc0\u946\'43}\u947xyZ}"; + assert_eq!(rtf_text(rtf), "αβCγZ"); + } + #[test] fn docx_round_trip_through_writer_and_reader() { let dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/plan.rs b/src/plan.rs index c40e905..6f439f5 100644 --- a/src/plan.rs +++ b/src/plan.rs @@ -155,8 +155,9 @@ impl Args { fn input(self, path: &Path) -> Self { // A crafted playlist or container must not make ffmpeg open URLs or - // other protocols: user files may only read local files. - self.flag("-protocol_whitelist", "file,pipe") + // other protocols: user files may only read local files. `crypto` + // decrypts local AES-128 HLS segments and can only wrap those. + self.flag("-protocol_whitelist", "file,pipe,crypto") .flag("-i", input_url(path, None)) } @@ -2135,11 +2136,9 @@ mod tests { ) .unwrap(); let cmd = joined(&p); - assert!( - cmd.contains( - "-loop 1 -framerate 30 -protocol_whitelist file,pipe -i file:/in/photo.png" - ) - ); + assert!(cmd.contains( + "-loop 1 -framerate 30 -protocol_whitelist file,pipe,crypto -i file:/in/photo.png" + )); assert!(cmd.contains("xfade=transition=slideright:duration=1.000000:offset=1.000000")); assert!(cmd.contains("anullsrc") && cmd.contains("acrossfade")); assert_eq!(p.expected_secs, Some(4.0)); @@ -2285,7 +2284,7 @@ mod tests { ) .expect("plan"); let cmd = joined(&p); - assert!(cmd.contains("-ss 5.000 -to 15.000 -protocol_whitelist file,pipe -i")); + assert!(cmd.contains("-ss 5.000 -to 15.000 -protocol_whitelist file,pipe,crypto -i")); assert!( cmd.contains( "-vf crop=640:360:10:20,transpose=1,subtitles=filename=/s/it\\\\\\'s\\\\: a\\,b.srt" From 44a206ddfaea39f6213781e63f51f7d9505f2df7 Mon Sep 17 00:00:00 2001 From: sudo-py-dev Date: Wed, 25 Nov 2026 08:11:02 +0200 Subject: [PATCH 3/3] Address review: escaped RTF fallback symbols, crypto in probes - RTF: an escaped symbol such as \{ after \uN counts as one whole fallback unit, so it is skipped instead of leaking into the text. - Probing allows the crypto protocol like conversion inputs do, so a local HLS playlist that starts with AES-128 segments can be probed. Co-Authored-By: Claude Opus 5.5 --- src/ffmpeg.rs | 3 ++- src/office.rs | 20 ++++++++++++-------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/ffmpeg.rs b/src/ffmpeg.rs index 9cfbf5c..0234ead 100644 --- a/src/ffmpeg.rs +++ b/src/ffmpeg.rs @@ -115,7 +115,8 @@ fn add_input(args: &mut Vec, path: &Path, demuxer: Option<&str>) { args.extend(["-f".into(), format.into()]); } if demuxer.is_none() { - args.extend(["-protocol_whitelist".into(), "file,pipe".into()]); + // Same set as conversion inputs: local files and AES-128 HLS segments. + args.extend(["-protocol_whitelist".into(), "file,pipe,crypto".into()]); } args.extend(["-i".into(), input_url(path, demuxer)]); } diff --git a/src/office.rs b/src/office.rs index a437f0a..b58afdc 100644 --- a/src/office.rs +++ b/src/office.rs @@ -843,19 +843,21 @@ fn rtf_text(rtf: &str) -> String { out.push(ch); } // Skip the `\ucN` fallback units that follow a Unicode - // escape: each is one character or one `\'hh` escape - // (what Word writes). `\uc0` means there is none. + // escape: each is one character, one `\'hh` escape (what + // Word writes) or one escaped symbol such as `\{`. + // `\uc0` means there is none. for _ in 0..uc { match chars.peek() { Some('\\') => { let mut ahead = chars.clone(); ahead.next(); - if ahead.peek() != Some(&'\'') { - break; - } - chars.next(); - chars.next(); - chars.by_ref().take(2).for_each(drop); + let len = match ahead.peek() { + Some('\'') => 4, + Some(c) if !c.is_ascii_alphabetic() => 2, + // A control word ends the fallback. + _ => break, + }; + chars.by_ref().take(len).for_each(drop); } Some('{' | '}') | None => break, Some(_) => { @@ -1351,6 +1353,8 @@ mod tests { // `\ucN` is scoped to its group and restored when the group ends. let rtf = r"{\uc2\u945ab{\uc0\u946\'43}\u947xyZ}"; assert_eq!(rtf_text(rtf), "αβCγZ"); + // An escaped symbol such as `\{` is one whole fallback unit. + assert_eq!(rtf_text(r"{\rtf1\ansi\uc2\u945\'61\{Z}"), "αZ"); } #[test]