Skip to main content

artifactize_core/platform/
unix.rs

1//! Unix private file modes, process control, signals, and termios.
2//! Pinned file access lives in artifactize-tools.
3
4mod descriptors;
5pub(crate) mod ipc;
6mod process;
7
8use std::{
9    fs::{self, DirBuilder, File, OpenOptions, Permissions},
10    future::Future,
11    io,
12    os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt},
13    path::Path,
14};
15
16pub(crate) use tempfile::TempDir as PrivateTempDir;
17use tokio::signal::unix::{SignalKind, signal};
18
19pub(crate) use process::{
20    Child, hide_console_window, kill_saved_group, kill_saved_session, process_start_time,
21    running_process_start_time, spawn_detached, spawn_gated, spawn_now, spawn_run, spawn_watched,
22    spawn_windowless,
23};
24
25/// Give the heap memory freed so far back to the system. glibc keeps freed memory in its
26/// arenas for reuse, so a long-lived process that once read much stays that large; macOS's
27/// allocator returns it by itself.
28pub(crate) fn release_free_memory() {
29    #[cfg(all(target_os = "linux", target_env = "gnu"))]
30    // SAFETY: malloc_trim only releases memory that is already free, under glibc's own locks.
31    unsafe {
32        libc::malloc_trim(0);
33    }
34}
35
36/// No Windows-style pending sharing disposition survives group cleanup.
37pub(crate) fn remove_tree(path: &Path) -> io::Result<()> {
38    std::fs::remove_dir_all(path)
39}
40
41/// POSIX file locks are advisory, and unlinking a name never invalidates another handle's
42/// access to it, so a plain metadata or open race like Windows's never happens here.
43pub(crate) fn transient_file_access(_error: &io::Error) -> bool {
44    false
45}
46
47/// Owner-only directory mode (rwx------): these directories hold credentials, Agent sessions,
48/// sockets and review state, so no other local user may list or enter them.
49const PRIVATE_DIR_MODE: u32 = 0o700;
50
51/// Owner-only file mode (rw-------): these files hold credentials, Agent transcripts and review
52/// evidence, so no other local user may read them.
53const PRIVATE_FILE_MODE: u32 = 0o600;
54
55/// How a private directory and file are described in messages.
56pub(crate) const PRIVATE_DIRECTORY: &str = "owner-only (mode 0700)";
57pub(crate) const PRIVATE_FILE: &str = "readable by their owner only (mode 0600)";
58
59/// The group and other permission bits; a private path has none of them set.
60pub(crate) const GROUP_OTHER_BITS: u32 = 0o077;
61
62/// Group/other write bits let another user replace system-alias or IPC parent
63/// directories, so neither the alias nor the endpoint under them can be trusted.
64const GROUP_OTHER_WRITE_BITS: u32 = 0o022;
65
66/// The permission bits of a mode, without the file type and set-id bits, so a file can be
67/// compared with [`PRIVATE_FILE_MODE`] exactly.
68const PERMISSION_BITS: u32 = 0o777;
69
70/// Create a directory and its missing parents as 0700; existing ones keep their mode.
71pub(crate) fn create_private_dir_all(path: &Path) -> io::Result<()> {
72    DirBuilder::new()
73        .recursive(true)
74        .mode(PRIVATE_DIR_MODE)
75        .create(path)
76}
77
78/// Create one directory as exactly 0700, whatever the umask.
79pub(crate) fn create_private_dir(path: &Path) -> io::Result<()> {
80    DirBuilder::new().mode(PRIVATE_DIR_MODE).create(path)?;
81    fs::set_permissions(path, Permissions::from_mode(PRIVATE_DIR_MODE))
82}
83
84/// A new 0700 temporary directory below `parent`.
85pub(crate) fn private_tempdir_in(prefix: &str, parent: &Path) -> io::Result<PrivateTempDir> {
86    let directory = tempfile::Builder::new()
87        .prefix(prefix)
88        .permissions(Permissions::from_mode(PRIVATE_DIR_MODE))
89        .tempdir_in(parent)?;
90    fs::set_permissions(directory.path(), Permissions::from_mode(PRIVATE_DIR_MODE))?;
91    Ok(directory)
92}
93
94/// A private scratch directory that shares its exact basename with an existing lease.
95pub(crate) fn private_named_dir(parent: &Path, name: &str) -> io::Result<PrivateTempDir> {
96    let directory = tempfile::Builder::new()
97        .prefix(name)
98        .rand_bytes(0)
99        .permissions(Permissions::from_mode(PRIVATE_DIR_MODE))
100        .tempdir_in(parent)?;
101    fs::set_permissions(directory.path(), Permissions::from_mode(PRIVATE_DIR_MODE))?;
102    Ok(directory)
103}
104
105/// Whether a directory grants nothing to its group or others.
106pub(crate) fn is_private_dir(path: &Path) -> io::Result<bool> {
107    Ok(fs::metadata(path)?.mode() & GROUP_OTHER_BITS == 0)
108}
109
110/// Whether an open file is a regular, single-link 0600 file.
111pub(crate) fn is_private_file(file: &File) -> io::Result<bool> {
112    let metadata = file.metadata()?;
113    Ok(metadata.is_file()
114        && metadata.mode() & PERMISSION_BITS == PRIVATE_FILE_MODE
115        && metadata.nlink() == 1)
116}
117
118/// Options that create files as 0600.
119pub(crate) fn private_options() -> OpenOptions {
120    let mut options = OpenOptions::new();
121    options.mode(PRIVATE_FILE_MODE);
122    options
123}
124
125/// Make an open file 0600.
126pub(crate) fn restrict_file(file: &File) -> io::Result<()> {
127    file.set_permissions(Permissions::from_mode(PRIVATE_FILE_MODE))
128}
129
130/// Persist a directory's entries, such as a file just renamed into it.
131pub(crate) fn sync_dir(path: &Path) -> io::Result<()> {
132    File::open(path).and_then(|directory| directory.sync_all())
133}
134
135/// A file's identity on its volume: its device and inode.
136pub(crate) fn file_identity(file: &File) -> io::Result<super::FileIdentity> {
137    let metadata = file.metadata()?;
138    Ok(super::FileIdentity {
139        volume: metadata.dev(),
140        index: metadata.ino(),
141    })
142}
143
144/// The effective user, the owner that private paths must have.
145pub(crate) fn current_user() -> u32 {
146    // SAFETY: geteuid has no preconditions and does not mutate process identity.
147    unsafe { libc::geteuid() }
148}
149
150/// Whether an open file or directory belongs to the current user and grants nothing to its
151/// group or others.
152pub(crate) fn is_owner_only(file: &File) -> io::Result<bool> {
153    let metadata = file.metadata()?;
154    Ok(metadata.mode() & GROUP_OTHER_BITS == 0 && metadata.uid() == current_user())
155}
156
157/// Environment variable names compare exactly.
158pub(crate) const ENV_NAMES_IGNORE_CASE: bool = false;
159
160/// The variable naming the user's home directory.
161pub(crate) const HOME_VARIABLES: &[&str] = &["HOME"];
162
163/// Variables programs read their temporary directory from. `TMP` and `TEMP` are set too, for
164/// programs written for Windows.
165pub(crate) const TEMP_VARIABLES: &[&str] = &["TMPDIR", "TMP", "TEMP"];
166
167/// Variables naming a per-user state directory, in order; artifactize keeps its state in an
168/// `artifactize` folder below the first one set, and otherwise below `HOME`.
169pub(crate) const STATE_VARIABLES: &[&str] = &["XDG_STATE_HOME"];
170
171/// The variables naming the signed-in user, in order.
172pub(crate) const USER_VARIABLES: &[&str] = &["USER", "LOGNAME"];
173
174/// The user's home directory.
175pub(crate) fn home_directory() -> Option<std::path::PathBuf> {
176    std::env::var_os(HOME_VARIABLES[0])
177        .filter(|path| !path.is_empty())
178        .map(Into::into)
179}
180
181/// A path from the raw bytes a tool such as git prints: any bytes name a Unix path.
182pub(crate) fn path_from_bytes(bytes: &[u8]) -> std::path::PathBuf {
183    use std::os::unix::ffi::OsStringExt;
184    std::ffi::OsString::from_vec(bytes.to_vec()).into()
185}
186
187/// Unix programs end a line with LF only.
188pub(crate) const CRLF_LINE_ENDINGS: bool = false;
189
190/// Whether a terminal that cannot hide input is still read, visibly, after a warning. A Unix
191/// terminal always can; failing to hide input is an error.
192pub const VISIBLE_INPUT_FALLBACK: bool = false;
193
194/// The operating system's host name, without depending on a proc filesystem.
195pub(crate) fn host_name() -> Option<String> {
196    hostname::get().ok()?.into_string().ok()
197}
198
199/// The absolute form of `path` with a leading macOS system alias (`/tmp`, `/var`, `/etc`)
200/// replaced by its fixed `/private` target. The alias and its parents must be root-owned
201/// and not replaceable; descendants are left for the caller to open without following links.
202#[cfg(target_os = "macos")]
203pub(crate) fn resolve_system_aliases(path: &Path) -> io::Result<std::path::PathBuf> {
204    let absolute = std::path::absolute(path)?;
205    for name in ["tmp", "var", "etc"] {
206        let alias = Path::new("/").join(name);
207        if let Ok(suffix) = absolute.strip_prefix(&alias) {
208            let metadata = alias.symlink_metadata()?;
209            let target = Path::new("/private").join(name);
210            let link = fs::read_link(&alias)?;
211            let link = if link.is_absolute() {
212                link
213            } else {
214                Path::new("/").join(link)
215            };
216            if !metadata.is_symlink() || metadata.uid() != 0 || link != target {
217                return Err(io::Error::other(format!(
218                    "Refusing an untrusted system alias: {}",
219                    alias.display()
220                )));
221            }
222            for parent in [Path::new("/"), Path::new("/private")] {
223                let metadata = parent.symlink_metadata()?;
224                if !metadata.is_dir()
225                    || metadata.uid() != 0
226                    || metadata.mode() & GROUP_OTHER_WRITE_BITS != 0
227                {
228                    return Err(io::Error::other(
229                        "System alias parents must not be replaceable.",
230                    ));
231                }
232            }
233            return Ok(target.join(suffix));
234        }
235    }
236    Ok(absolute)
237}
238
239/// The absolute form of `path`; this system has no aliased system roots.
240#[cfg(not(target_os = "macos"))]
241pub(crate) fn resolve_system_aliases(path: &Path) -> io::Result<std::path::PathBuf> {
242    std::path::absolute(path)
243}
244
245/// Register for SIGINT and SIGTERM now; the future completes at the first of them.
246pub fn stop_requested() -> io::Result<impl Future<Output = ()> + Send + 'static> {
247    let mut interrupt = signal(SignalKind::interrupt())?;
248    let mut terminate = signal(SignalKind::terminate())?;
249    Ok(async move {
250        tokio::select! { _ = interrupt.recv() => {}, _ = terminate.recv() => {} }
251    })
252}
253
254/// Turns terminal echo off until dropped, so a pasted secret is not shown.
255pub struct HiddenInput(libc::termios);
256
257impl HiddenInput {
258    pub fn new() -> io::Result<Self> {
259        let mut termios = std::mem::MaybeUninit::uninit();
260        // SAFETY: tcgetattr fills the struct on success; it is read only then.
261        let saved = unsafe {
262            if libc::tcgetattr(libc::STDIN_FILENO, termios.as_mut_ptr()) != 0 {
263                return Err(io::Error::last_os_error());
264            }
265            termios.assume_init()
266        };
267        let mut hidden = saved;
268        hidden.c_lflag &= !libc::ECHO;
269        // SAFETY: a valid termios for the same descriptor.
270        if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &hidden) } != 0 {
271            return Err(io::Error::last_os_error());
272        }
273        Ok(Self(saved))
274    }
275}
276
277impl Drop for HiddenInput {
278    fn drop(&mut self) {
279        // SAFETY: restores the attributes read in `new`.
280        unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &self.0) };
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    /// Unlike Windows, no error here is ever transient in this sense; the predicate is a
289    /// permanent no-op, not a gap in detecting a race that would need retrying.
290    #[test]
291    fn transient_file_access_is_always_false() {
292        assert!(!transient_file_access(&io::Error::from_raw_os_error(5)));
293        assert!(!transient_file_access(&io::Error::new(
294            io::ErrorKind::PermissionDenied,
295            "permission denied"
296        )));
297    }
298}