Skip to main content

latexml/
util.rs

1/// Engine preset helpers used by both the production
2/// `latexmlmath_oxide` binary and by the test harness. Always
3/// compiled — no test-only dependencies.
4pub mod preset;
5
6/// Integration-test harness. Gated behind the `test-utils` feature
7/// (default on) so the distribution build (`cargo build
8/// --no-default-features --profile maxperf --bin latexml_oxide`)
9/// drops `glob` from the dependency graph (audit DEP-02).
10#[cfg(feature = "test-utils")]
11#[macro_use]
12pub mod test;
13
14/// Unpacks a tar archive into `dest`. A source tree is untrusted input: a link in it could lead a read (`\input`) or a
15/// Lua write outside the job (OXIDIZED_DESIGN_DIVERGENCES #1081). So a symbolic link is made, after every other entry,
16/// only when its target, resolved component by component through the links already there, stays inside `dest` (zip
17/// 9.7's `extract` rule, `zip/src/path.rs` `resolve_enclosed`); a hard link only to a file inside `dest` (`tar`'s
18/// own check). Every other link, and every entry whose path would leave `dest`, is skipped with a counted Warning.
19pub fn unpack_tar<R: std::io::Read>(
20  mut archive: tar::Archive<R>,
21  dest: &std::path::Path,
22) -> std::io::Result<()> {
23  use latexml_core::common::error::warn_at_session_start;
24  let mut links = Vec::new();
25  for entry in archive.entries()? {
26    let mut entry = entry?;
27    let name = entry
28      .path()
29      .map(|p| p.display().to_string())
30      .unwrap_or_default();
31    let kind = entry.header().entry_type();
32    if kind.is_symlink() {
33      match (entry.path(), entry.link_name()) {
34        (Ok(path), Ok(Some(target))) => links.push((path.into_owned(), target.into_owned(), name)),
35        _ => warn_at_session_start(
36          "archive",
37          "link",
38          format!("the archive entry '{name}' is a link without a target; not unpacked"),
39        ),
40      }
41      continue;
42    }
43    if kind.is_hard_link() {
44      if entry.unpack_in(dest).ok() != Some(true) {
45        warn_at_session_start(
46          "archive",
47          "link",
48          format!(
49            "the archive entry '{name}' links to a file that does not resolve inside the source directory; not unpacked"
50          ),
51        );
52      }
53      continue;
54    }
55    if !entry.unpack_in(dest)? {
56      warn_at_session_start(
57        "archive",
58        "path",
59        format!("the archive entry '{name}' would land outside the source directory; not unpacked"),
60      );
61    }
62  }
63  let root = dest.canonicalize()?;
64  for (path, target, name) in links {
65    if !make_enclosed_link(&root, &path, &target) {
66      warn_at_session_start(
67        "archive",
68        "link",
69        format!(
70          "the archive entry '{name}' is a link to '{}' {LINK_NOT_MADE}; not unpacked",
71          target.display()
72        ),
73      );
74    }
75  }
76  normalize_unpacked_permissions(dest);
77  Ok(())
78}
79
80/// Maximum bytes read from a zip symlink entry's target payload (mirrors
81/// `zip`'s `MAX_SYMLINK_TARGET_LEN` / Linux `PATH_MAX`).
82const MAX_ZIP_SYMLINK_TARGET_LEN: u64 = 4096;
83
84/// Unpacks a `.zip` archive into `dest` with sandbox-safe permissions and
85/// symlink containment, used by both `latexml_oxide` and `cortex_worker`:
86/// - Every entry path is validated via `ZipFile::enclosed_name()` so `..` /
87///   absolute paths never land outside `dest` (skipped with a counted Warning).
88/// - Regular files and directories are written without inheriting archive exec
89///   or read-only mode bits, and permissions are normalized at the end
90///   (`a-x,u+rwX` on Unix; clearing `readonly` on non-Unix) so read-only
91///   archive directories (`0555`) never leave temp entries behind on drop and
92///   executable files (`0755`) lose their exec bits.
93/// - Symlinks are handled in a second pass after all files/dirs exist:
94///   in-archive symlinks stay symlinks (resolving to their target's text, via
95///   `make_enclosed_link`), while symlinks whose target would escape `dest`
96///   (e.g. `-> /etc/hostname`) are written as plain text files with a counted
97///   Warning instead of failing the whole paper.
98pub fn unpack_zip<R: std::io::Read + std::io::Seek>(
99  mut archive: zip::ZipArchive<R>,
100  dest: &std::path::Path,
101) -> Result<(), zip::result::ZipError> {
102  use std::io::Read as _;
103
104  use latexml_core::common::error::warn_at_session_start;
105
106  let mut links: Vec<(std::path::PathBuf, Vec<u8>, String)> = Vec::new();
107  for i in 0..archive.len() {
108    let mut entry = archive.by_index(i)?;
109    let raw_name = entry
110      .name()
111      .map(|s| s.into_owned())
112      .unwrap_or_else(|_| String::from_utf8_lossy(entry.name_raw()).into_owned());
113    let Some(rel_path) = entry.enclosed_name() else {
114      warn_at_session_start(
115        "archive",
116        "path",
117        format!(
118          "the archive entry '{raw_name}' would land outside the source directory; not unpacked"
119        ),
120      );
121      continue;
122    };
123    if entry.is_symlink() {
124      let mut target_bytes = Vec::new();
125      entry
126        .by_ref()
127        .take(MAX_ZIP_SYMLINK_TARGET_LEN + 1)
128        .read_to_end(&mut target_bytes)?;
129      if target_bytes.len() as u64 > MAX_ZIP_SYMLINK_TARGET_LEN {
130        warn_at_session_start(
131          "archive",
132          "link",
133          format!("the archive entry '{raw_name}' has an oversized symlink target; not unpacked"),
134        );
135        continue;
136      }
137      links.push((rel_path, target_bytes, raw_name));
138      continue;
139    }
140    let out_path = dest.join(&rel_path);
141    if entry.is_dir() {
142      std::fs::create_dir_all(&out_path)?;
143    } else {
144      if let Some(parent) = out_path.parent() {
145        std::fs::create_dir_all(parent)?;
146      }
147      let mut out = std::fs::File::create(&out_path)?;
148      std::io::copy(&mut entry, &mut out)?;
149    }
150  }
151
152  if !links.is_empty() {
153    let root = dest.canonicalize()?;
154    for (rel_path, target_bytes, raw_name) in links {
155      let target_path: Option<std::path::PathBuf> = {
156        #[cfg(unix)]
157        {
158          use std::os::unix::ffi::OsStrExt as _;
159          Some(std::path::PathBuf::from(std::ffi::OsStr::from_bytes(
160            &target_bytes,
161          )))
162        }
163        #[cfg(not(unix))]
164        {
165          std::str::from_utf8(&target_bytes)
166            .ok()
167            .map(std::path::PathBuf::from)
168        }
169      };
170
171      let linked = target_path
172        .as_deref()
173        .is_some_and(|target| make_enclosed_link(&root, &rel_path, target));
174
175      if !linked {
176        warn_at_session_start(
177          "archive",
178          "link",
179          format!(
180            "the archive entry '{raw_name}' is a link to '{}' {LINK_NOT_MADE}; unpacked as a plain file",
181            String::from_utf8_lossy(&target_bytes)
182          ),
183        );
184        // Write the escaping symlink as a plain file inside `root` (verifying
185        // its parent still canonicalizes inside `root`) so the paper still
186        // converts rather than failing on a stray symlink.
187        if let (Some(parent), Some(file_name)) = (rel_path.parent(), rel_path.file_name()) {
188          let parent_dir = root.join(parent);
189          std::fs::create_dir_all(&parent_dir)?;
190          if let Ok(real_parent) = parent_dir.canonicalize()
191            && real_parent.starts_with(&root)
192          {
193            let plain_path = real_parent.join(file_name);
194            std::fs::write(&plain_path, &target_bytes)?;
195          }
196        }
197      }
198    }
199  }
200
201  normalize_unpacked_permissions(dest);
202  Ok(())
203}
204
205/// Normalize permissions across an unpacked archive tree (`chmod -R a-x,u+rwX`
206/// on Unix, clearing `readonly` on non-Unix): strips execute bits from regular
207/// files and ensures owner read/write/traverse on directories so read-only
208/// archive directories (`0555`) never leave temporary files behind on cleanup.
209/// Walks real directories only (`file_type()`, never following symlinks) so
210/// in-archive directory link cycles (`a -> .`, #924) never loop.
211// Not Unix: `set_readonly(false)` clears the read-only attribute; the lint warns of Unix world-writable modes.
212#[cfg_attr(not(unix), allow(clippy::permissions_set_readonly_false))]
213fn normalize_unpacked_permissions(dir: &std::path::Path) {
214  fn fix_dir(path: &std::path::Path) {
215    #[cfg(unix)]
216    {
217      use std::os::unix::fs::PermissionsExt as _;
218      if let Ok(meta) = std::fs::symlink_metadata(path) {
219        let mode = (meta.permissions().mode() & !0o111) | 0o700;
220        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
221      }
222    }
223    #[cfg(not(unix))]
224    {
225      if let Ok(meta) = std::fs::symlink_metadata(path) {
226        let mut perms = meta.permissions();
227        if perms.readonly() {
228          perms.set_readonly(false);
229          let _ = std::fs::set_permissions(path, perms);
230        }
231      }
232    }
233  }
234
235  fn fix_file(path: &std::path::Path) {
236    #[cfg(unix)]
237    {
238      use std::os::unix::fs::PermissionsExt as _;
239      if let Ok(meta) = std::fs::symlink_metadata(path) {
240        let mode = (meta.permissions().mode() & !0o111) | 0o600;
241        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
242      }
243    }
244    #[cfg(not(unix))]
245    {
246      if let Ok(meta) = std::fs::symlink_metadata(path) {
247        let mut perms = meta.permissions();
248        if perms.readonly() {
249          perms.set_readonly(false);
250          let _ = std::fs::set_permissions(path, perms);
251        }
252      }
253    }
254  }
255
256  // Ensure the directory itself is owner-rwx BEFORE reading its entries (a
257  // read-only tar/zip dir like `0555` or `0444` must be traversable first).
258  fix_dir(dir);
259  let Ok(entries) = std::fs::read_dir(dir) else {
260    return;
261  };
262  for entry in entries.flatten() {
263    let Ok(ft) = entry.file_type() else {
264      continue;
265    };
266    let path = entry.path();
267    if ft.is_symlink() {
268      continue;
269    }
270    if ft.is_dir() {
271      normalize_unpacked_permissions(&path);
272    } else if ft.is_file() {
273      fix_file(&path);
274    }
275  }
276}
277
278/// Why an archive link was not made, for its counted Warning. On Unix a link is made when it resolves inside the
279/// source directory, so a refused one is absolute, escapes it, climbs (`..`) past a component that does not exist yet,
280/// or runs through a cycle; elsewhere [`make_enclosed_link`] makes none, and every link is reported.
281#[cfg(unix)]
282const LINK_NOT_MADE: &str = "that does not resolve inside the source directory";
283#[cfg(not(unix))]
284const LINK_NOT_MADE: &str = "and links are not made on this platform";
285
286/// Makes the symbolic link `path` (relative to `root`) to `target` when both the link's directory and the target,
287/// resolved physically one component at a time, stay inside `root`; false otherwise.
288fn make_enclosed_link(
289  root: &std::path::Path,
290  path: &std::path::Path,
291  target: &std::path::Path,
292) -> bool {
293  use std::path::Component;
294  if !path
295    .components()
296    .all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
297  {
298    return false;
299  }
300  let (Some(parent), Some(file_name)) = (path.parent(), path.file_name()) else {
301    return false;
302  };
303  let parent = root.join(parent);
304  if std::fs::create_dir_all(&parent).is_err() {
305    return false;
306  }
307  let Ok(mut current) = parent.canonicalize() else {
308    return false;
309  };
310  if !current.starts_with(root) {
311    return false;
312  }
313  let link = current.join(file_name);
314  // Once a component does not exist, a later `..` could mean another place once something is made there.
315  let mut missing = false;
316  for component in target.components() {
317    match component {
318      Component::CurDir => {},
319      Component::ParentDir => {
320        if missing || !current.pop() || !current.starts_with(root) {
321          return false;
322        }
323      },
324      Component::Normal(part) => {
325        current.push(part);
326        if missing {
327          continue;
328        }
329        match std::fs::symlink_metadata(&current) {
330          Ok(meta) if meta.file_type().is_symlink() => match current.canonicalize() {
331            Ok(real) if real.starts_with(root) => current = real,
332            _ => return false,
333          },
334          Ok(_) => {},
335          Err(_) => missing = true,
336        }
337      },
338      Component::RootDir | Component::Prefix(_) => return false,
339    }
340  }
341  if !current.starts_with(root) {
342    return false;
343  }
344  #[cfg(unix)]
345  {
346    std::os::unix::fs::symlink(target, &link).is_ok()
347  }
348  #[cfg(not(unix))]
349  {
350    let _ = (link, target);
351    false
352  }
353}
354
355#[cfg(test)]
356mod archive_unpack_tests {
357  use std::io::{Cursor, Write as _};
358
359  use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions};
360
361  use super::*;
362
363  fn build_zip(build: impl FnOnce(&mut ZipWriter<Cursor<Vec<u8>>>)) -> ZipArchive<Cursor<Vec<u8>>> {
364    let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
365    build(&mut writer);
366    let cursor = writer.finish().expect("finish zip");
367    ZipArchive::new(cursor).expect("open zip")
368  }
369
370  /// Synthetic zip covering read-only dirs (`0555`), executable files (`0755`),
371  /// in-archive symlinks, escaping symlinks, path traversal (`..`), and a
372  /// self-referential directory symlink cycle (`a -> .`, #924).
373  #[test]
374  fn unpack_zip_normalizes_permissions_and_contains_symlinks() {
375    let archive = build_zip(|zw| {
376      zw.add_directory("ro/", SimpleFileOptions::default().unix_permissions(0o555))
377        .unwrap();
378      zw.start_file(
379        "ro/part.tex",
380        SimpleFileOptions::default().unix_permissions(0o755),
381      )
382      .unwrap();
383      zw.write_all(b"INCLUDED_PART").unwrap();
384
385      zw.start_file(
386        "main.tex",
387        SimpleFileOptions::default().unix_permissions(0o444),
388      )
389      .unwrap();
390      zw.write_all(b"\\documentclass{article}\\begin{document}\\input{alias}\\end{document}\n")
391        .unwrap();
392
393      // In-archive symlink: must resolve to target's text (on Unix).
394      zw.add_symlink("alias.tex", "ro/part.tex", SimpleFileOptions::default())
395        .unwrap();
396      // Escaping symlink: must be unpacked as a plain file, not fail extraction.
397      zw.add_symlink("escape.tex", "/etc/hostname", SimpleFileOptions::default())
398        .unwrap();
399      // Self-referential directory link (#924): must not cause recursion cycles.
400      zw.add_symlink("loopdir", ".", SimpleFileOptions::default())
401        .unwrap();
402      // Path traversal entry: skipped via `enclosed_name`.
403      zw.start_file("../outside.tex", SimpleFileOptions::default())
404        .unwrap();
405      zw.write_all(b"ESCAPED").unwrap();
406    });
407
408    let parent = tempfile::tempdir().expect("outer tempdir");
409    let extract_dir = parent.path().join("work");
410    std::fs::create_dir(&extract_dir).unwrap();
411
412    unpack_zip(archive, &extract_dir).expect("unpack_zip must succeed");
413
414    // Path traversal never escapes `extract_dir`.
415    assert!(!parent.path().join("outside.tex").exists());
416
417    // Read-only dir and exec-bit file permissions normalized (`a-x,u+rwX`).
418    #[cfg(unix)]
419    {
420      use std::os::unix::fs::PermissionsExt as _;
421      let ro_mode = std::fs::symlink_metadata(extract_dir.join("ro"))
422        .unwrap()
423        .permissions()
424        .mode();
425      assert_eq!(
426        ro_mode & 0o700,
427        0o700,
428        "ro/ must be owner rwx: {ro_mode:#o}"
429      );
430      let part_mode = std::fs::symlink_metadata(extract_dir.join("ro/part.tex"))
431        .unwrap()
432        .permissions()
433        .mode();
434      assert_eq!(
435        part_mode & 0o111,
436        0,
437        "ro/part.tex must have no exec bits: {part_mode:#o}"
438      );
439      assert_eq!(
440        part_mode & 0o600,
441        0o600,
442        "ro/part.tex must be owner rw: {part_mode:#o}"
443      );
444
445      // In-archive symlink stays a symlink and resolves to target text.
446      let alias_meta = std::fs::symlink_metadata(extract_dir.join("alias.tex")).unwrap();
447      assert!(alias_meta.file_type().is_symlink());
448      assert_eq!(
449        std::fs::read_to_string(extract_dir.join("alias.tex")).unwrap(),
450        "INCLUDED_PART"
451      );
452    }
453
454    // Escaping symlink unpacked as a plain file containing target bytes, never a symlink.
455    let esc_meta = std::fs::symlink_metadata(extract_dir.join("escape.tex")).unwrap();
456    assert!(
457      esc_meta.file_type().is_file() && !esc_meta.file_type().is_symlink(),
458      "escaping symlink must be a plain file"
459    );
460    assert_eq!(
461      std::fs::read_to_string(extract_dir.join("escape.tex")).unwrap(),
462      "/etc/hostname"
463    );
464
465    // `find_main_tex` tolerates `loopdir -> .` without cycling and locates `main.tex`.
466    let main = crate::main_tex::find_main_tex(&extract_dir, true).expect("find_main_tex");
467    assert_eq!(main.file_name().and_then(|s| s.to_str()), Some("main.tex"));
468
469    // Cleanup of read-only directory succeeds cleanly with zero leftovers.
470    std::fs::remove_dir_all(&extract_dir).expect("remove_dir_all must succeed on normalized ro/");
471    assert!(!extract_dir.exists());
472  }
473}