Skip to main content

latexml_core/util/
private_files.rs

1//! Files trusted only when this user wrote them. A format dump is loaded as the format, and the
2//! caches holding dumps live in shared places (`$TMPDIR`), where another local user could put a
3//! file, or a directory, there first.
4
5use std::path::Path;
6
7/// The process's effective user id.
8#[cfg(unix)]
9pub fn user_id() -> u32 { rustix::process::geteuid().as_raw() }
10/// No user ids to compare off Unix.
11#[cfg(not(unix))]
12pub fn user_id() -> u32 { 0 }
13
14/// Whether `path` is this user's own and no one else can write to it, and is not a symbolic link.
15#[cfg(unix)]
16pub fn private_to_user(path: &Path) -> bool {
17  use std::os::unix::fs::MetadataExt;
18  // A symbolic link is never private: its own mode bits are 0o777 on Linux but follow the umask on
19  // macOS (0o755), so the write-bit test alone trusts a link there.
20  std::fs::symlink_metadata(path).is_ok_and(|meta| {
21    !meta.file_type().is_symlink() && meta.uid() == user_id() && meta.mode() & 0o022 == 0
22  })
23}
24/// No ownership to check off Unix.
25#[cfg(not(unix))]
26pub fn private_to_user(_path: &Path) -> bool { true }
27
28/// Whether `dir` is private to this user inside a directory this user or the superuser owns, so no
29/// one else can have put it, or what it holds, there.
30#[cfg(unix)]
31pub fn trusted_dir(dir: &Path) -> bool {
32  use std::os::unix::fs::MetadataExt;
33  private_to_user(dir)
34    && dir
35      .parent()
36      .and_then(|parent| std::fs::metadata(parent).ok())
37      .is_some_and(|meta| meta.uid() == user_id() || meta.uid() == 0)
38}
39/// No ownership to check off Unix.
40#[cfg(not(unix))]
41pub fn trusted_dir(_dir: &Path) -> bool { true }
42
43/// Creates `dir` for this user alone, or makes it private if this user owns it, and requires it to
44/// be a [`trusted_dir`].
45pub fn private_dir(dir: &Path) -> Result<(), String> {
46  std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
47  #[cfg(unix)]
48  {
49    use std::os::unix::fs::{MetadataExt, PermissionsExt};
50    let meta =
51      std::fs::symlink_metadata(dir).map_err(|e| format!("cannot read {}: {e}", dir.display()))?;
52    if meta.uid() != user_id() || meta.file_type().is_symlink() {
53      return Err(format!("{} belongs to another user", dir.display()));
54    }
55    if meta.mode() & 0o022 != 0 {
56      std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
57        .map_err(|e| format!("cannot make {} private: {e}", dir.display()))?;
58    }
59  }
60  if trusted_dir(dir) {
61    Ok(())
62  } else {
63    Err(format!(
64      "{} is inside another user's directory",
65      dir.display()
66    ))
67  }
68}
69
70/// Makes the file at `path` readable by all and writable by this user alone (0644), as a file
71/// [`private_to_user`] accepts must be whatever the umask.
72pub fn publish_read_only(path: &Path) -> std::io::Result<()> {
73  #[cfg(unix)]
74  {
75    use std::os::unix::fs::PermissionsExt;
76    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o644))?;
77  }
78  #[cfg(not(unix))]
79  let _ = path;
80  Ok(())
81}
82
83#[cfg(all(test, unix))]
84mod tests {
85  use std::os::unix::fs::PermissionsExt;
86
87  use super::*;
88
89  #[test]
90  fn only_this_users_files_no_one_else_can_write_are_trusted() {
91    let root = std::env::temp_dir().join(format!(
92      "latexml-private-files-{}-{:?}",
93      std::process::id(),
94      std::thread::current().id()
95    ));
96    let dir = root.join("cache");
97    private_dir(&dir).expect("create a private directory");
98    assert_eq!(
99      std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777 & 0o022,
100      0
101    );
102    assert!(trusted_dir(&dir));
103
104    let file = dir.join("dump.txt");
105    std::fs::write(&file, "dump").unwrap();
106    std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o666)).unwrap();
107    assert!(
108      !private_to_user(&file),
109      "a file everyone can write is trusted"
110    );
111    publish_read_only(&file).unwrap();
112    assert!(private_to_user(&file));
113
114    let link = dir.join("link.txt");
115    std::os::unix::fs::symlink(&file, &link).unwrap();
116    assert!(!private_to_user(&link), "a symbolic link is trusted");
117
118    std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o777)).unwrap();
119    assert!(
120      !trusted_dir(&dir),
121      "a directory everyone can write is trusted"
122    );
123    private_dir(&dir).expect("make the directory private again");
124    assert!(trusted_dir(&dir));
125    std::fs::remove_dir_all(&root).unwrap();
126  }
127}