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 executable file mode (rwx------): installed runtime binaries under `$STATE/chat/runtimes/`.
52const PRIVATE_EXECUTABLE_MODE: u32 = 0o700;
53
54/// Owner-only file mode (rw-------): these files hold credentials, Agent transcripts and review
55/// evidence, so no other local user may read them.
56const PRIVATE_FILE_MODE: u32 = 0o600;
57
58/// How a private directory and file are described in messages.
59pub(crate) const PRIVATE_DIRECTORY: &str = "owner-only (mode 0700)";
60pub(crate) const PRIVATE_FILE: &str = "readable by their owner only (mode 0600)";
61
62/// The group and other permission bits; a private path has none of them set.
63pub(crate) const GROUP_OTHER_BITS: u32 = 0o077;
64
65/// Group/other write bits let another user replace system-alias or IPC parent
66/// directories, so neither the alias nor the endpoint under them can be trusted.
67const GROUP_OTHER_WRITE_BITS: u32 = 0o022;
68
69/// The permission bits of a mode, without the file type and set-id bits, so a file can be
70/// compared with [`PRIVATE_FILE_MODE`] exactly.
71const PERMISSION_BITS: u32 = 0o777;
72
73/// Create a directory and its missing parents as 0700; existing ones keep their mode.
74pub(crate) fn create_private_dir_all(path: &Path) -> io::Result<()> {
75    DirBuilder::new()
76        .recursive(true)
77        .mode(PRIVATE_DIR_MODE)
78        .create(path)
79}
80
81/// Create one directory as exactly 0700, whatever the umask.
82pub(crate) fn create_private_dir(path: &Path) -> io::Result<()> {
83    DirBuilder::new().mode(PRIVATE_DIR_MODE).create(path)?;
84    fs::set_permissions(path, Permissions::from_mode(PRIVATE_DIR_MODE))
85}
86
87/// A new 0700 temporary directory below `parent`.
88pub(crate) fn private_tempdir_in(prefix: &str, parent: &Path) -> io::Result<PrivateTempDir> {
89    let directory = tempfile::Builder::new()
90        .prefix(prefix)
91        .permissions(Permissions::from_mode(PRIVATE_DIR_MODE))
92        .tempdir_in(parent)?;
93    fs::set_permissions(directory.path(), Permissions::from_mode(PRIVATE_DIR_MODE))?;
94    Ok(directory)
95}
96
97/// A private scratch directory that shares its exact basename with an existing lease.
98pub(crate) fn private_named_dir(parent: &Path, name: &str) -> io::Result<PrivateTempDir> {
99    let directory = tempfile::Builder::new()
100        .prefix(name)
101        .rand_bytes(0)
102        .permissions(Permissions::from_mode(PRIVATE_DIR_MODE))
103        .tempdir_in(parent)?;
104    fs::set_permissions(directory.path(), Permissions::from_mode(PRIVATE_DIR_MODE))?;
105    Ok(directory)
106}
107
108/// Whether a directory grants nothing to its group or others.
109pub(crate) fn is_private_dir(path: &Path) -> io::Result<bool> {
110    Ok(fs::metadata(path)?.mode() & GROUP_OTHER_BITS == 0)
111}
112
113/// Whether an open file is a regular, single-link 0600 file.
114pub(crate) fn is_private_file(file: &File) -> io::Result<bool> {
115    let metadata = file.metadata()?;
116    Ok(metadata.is_file()
117        && metadata.mode() & PERMISSION_BITS == PRIVATE_FILE_MODE
118        && metadata.nlink() == 1)
119}
120
121/// Options that create files as 0600.
122pub(crate) fn private_options() -> OpenOptions {
123    let mut options = OpenOptions::new();
124    options.mode(PRIVATE_FILE_MODE);
125    options
126}
127
128/// Make an open file 0600.
129pub(crate) fn restrict_file(file: &File) -> io::Result<()> {
130    file.set_permissions(Permissions::from_mode(PRIVATE_FILE_MODE))
131}
132
133/// Restrict an installed executable binary to owner-only read/write/execute (`0700`).
134pub(crate) fn restrict_executable_file(file: &File) -> io::Result<()> {
135    file.set_permissions(Permissions::from_mode(PRIVATE_EXECUTABLE_MODE))
136}
137
138/// Directory holding installed console entrypoints inside a Python virtual environment.
139pub(crate) fn venv_bin_dir(venv: &Path) -> std::path::PathBuf {
140    venv.join("bin")
141}
142
143/// Persist a directory's entries, such as a file just renamed into it.
144pub(crate) fn sync_dir(path: &Path) -> io::Result<()> {
145    File::open(path).and_then(|directory| directory.sync_all())
146}
147
148/// A file's identity on its volume: its device and inode.
149pub(crate) fn file_identity(file: &File) -> io::Result<super::FileIdentity> {
150    let metadata = file.metadata()?;
151    Ok(super::FileIdentity {
152        volume: metadata.dev(),
153        index: metadata.ino(),
154    })
155}
156
157/// The effective user, the owner that private paths must have.
158pub(crate) fn current_user() -> u32 {
159    // SAFETY: geteuid has no preconditions and does not mutate process identity.
160    unsafe { libc::geteuid() }
161}
162
163/// Whether an open file or directory belongs to the current user and grants nothing to its
164/// group or others.
165pub(crate) fn is_owner_only(file: &File) -> io::Result<bool> {
166    let metadata = file.metadata()?;
167    Ok(metadata.mode() & GROUP_OTHER_BITS == 0 && metadata.uid() == current_user())
168}
169
170/// Environment variable names compare exactly.
171pub(crate) const ENV_NAMES_IGNORE_CASE: bool = false;
172
173/// The variable naming the user's home directory.
174pub(crate) const HOME_VARIABLES: &[&str] = &["HOME"];
175
176/// Variables programs read their temporary directory from. `TMP` and `TEMP` are set too, for
177/// programs written for Windows.
178pub(crate) const TEMP_VARIABLES: &[&str] = &["TMPDIR", "TMP", "TEMP"];
179
180/// Variables naming a per-user state directory, in order; artifactize keeps its state in an
181/// `artifactize` folder below the first one set, and otherwise below `HOME`.
182pub(crate) const STATE_VARIABLES: &[&str] = &["XDG_STATE_HOME"];
183
184/// The variables naming the signed-in user, in order.
185pub(crate) const USER_VARIABLES: &[&str] = &["USER", "LOGNAME"];
186
187/// The user's home directory.
188pub(crate) fn home_directory() -> Option<std::path::PathBuf> {
189    std::env::var_os(HOME_VARIABLES[0])
190        .filter(|path| !path.is_empty())
191        .map(Into::into)
192}
193
194/// A path from the raw bytes a tool such as git prints: any bytes name a Unix path.
195pub(crate) fn path_from_bytes(bytes: &[u8]) -> std::path::PathBuf {
196    use std::os::unix::ffi::OsStringExt;
197    std::ffi::OsString::from_vec(bytes.to_vec()).into()
198}
199
200/// Unix programs end a line with LF only.
201pub(crate) const CRLF_LINE_ENDINGS: bool = false;
202
203/// Whether a terminal that cannot hide input is still read, visibly, after a warning. A Unix
204/// terminal always can; failing to hide input is an error.
205pub const VISIBLE_INPUT_FALLBACK: bool = false;
206
207/// The operating system's host name, without depending on a proc filesystem.
208pub(crate) fn host_name() -> Option<String> {
209    hostname::get().ok()?.into_string().ok()
210}
211
212/// The absolute form of `path` with a leading macOS system alias (`/tmp`, `/var`, `/etc`)
213/// replaced by its fixed `/private` target. The alias and its parents must be root-owned
214/// and not replaceable; descendants are left for the caller to open without following links.
215#[cfg(target_os = "macos")]
216pub(crate) fn resolve_system_aliases(path: &Path) -> io::Result<std::path::PathBuf> {
217    let absolute = std::path::absolute(path)?;
218    for name in ["tmp", "var", "etc"] {
219        let alias = Path::new("/").join(name);
220        if let Ok(suffix) = absolute.strip_prefix(&alias) {
221            let metadata = alias.symlink_metadata()?;
222            let target = Path::new("/private").join(name);
223            let link = fs::read_link(&alias)?;
224            let link = if link.is_absolute() {
225                link
226            } else {
227                Path::new("/").join(link)
228            };
229            if !metadata.is_symlink() || metadata.uid() != 0 || link != target {
230                return Err(io::Error::other(format!(
231                    "Refusing an untrusted system alias: {}",
232                    alias.display()
233                )));
234            }
235            for parent in [Path::new("/"), Path::new("/private")] {
236                let metadata = parent.symlink_metadata()?;
237                if !metadata.is_dir()
238                    || metadata.uid() != 0
239                    || metadata.mode() & GROUP_OTHER_WRITE_BITS != 0
240                {
241                    return Err(io::Error::other(
242                        "System alias parents must not be replaceable.",
243                    ));
244                }
245            }
246            return Ok(target.join(suffix));
247        }
248    }
249    Ok(absolute)
250}
251
252/// The absolute form of `path`; this system has no aliased system roots.
253#[cfg(not(target_os = "macos"))]
254pub(crate) fn resolve_system_aliases(path: &Path) -> io::Result<std::path::PathBuf> {
255    std::path::absolute(path)
256}
257
258/// Register now: an interrupt, termination request or controlling-terminal hangup stops work.
259pub fn stop_requested() -> io::Result<impl Future<Output = ()> + Send + 'static> {
260    let mut interrupt = signal(SignalKind::interrupt())?;
261    let mut terminate = signal(SignalKind::terminate())?;
262    let mut hangup = signal(SignalKind::hangup())?;
263    Ok(async move {
264        tokio::select! {
265            _ = interrupt.recv() => {},
266            _ = terminate.recv() => {},
267            _ = hangup.recv() => {},
268        }
269    })
270}
271
272/// Turns terminal echo off until dropped, so a pasted secret is not shown.
273pub struct HiddenInput(libc::termios);
274
275impl HiddenInput {
276    pub fn new() -> io::Result<Self> {
277        let mut termios = std::mem::MaybeUninit::uninit();
278        // SAFETY: tcgetattr fills the struct on success; it is read only then.
279        let saved = unsafe {
280            if libc::tcgetattr(libc::STDIN_FILENO, termios.as_mut_ptr()) != 0 {
281                return Err(io::Error::last_os_error());
282            }
283            termios.assume_init()
284        };
285        let mut hidden = saved;
286        hidden.c_lflag &= !libc::ECHO;
287        // SAFETY: a valid termios for the same descriptor.
288        if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &hidden) } != 0 {
289            return Err(io::Error::last_os_error());
290        }
291        Ok(Self(saved))
292    }
293}
294
295impl Drop for HiddenInput {
296    fn drop(&mut self) {
297        // SAFETY: restores the attributes read in `new`.
298        unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &self.0) };
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305
306    const HANGUP_PROBE: &str = "ARTIFACTIZE_TEST_TERMINAL_HANGUP";
307
308    #[test]
309    fn terminal_hangup_completes_the_portable_stop_future() {
310        // Isolate the signal so a missing subscription cannot terminate the test runner.
311        let mut child = crate::test_os::test_command(
312            "platform::unix::tests::terminal_hangup_probe",
313            &[(HANGUP_PROBE, "1".into())],
314        );
315        let output =
316            crate::test_os::finish(crate::test_os::start(&mut child), "terminal hangup probe");
317        assert!(output.status.success(), "{output:?}");
318    }
319
320    #[tokio::test]
321    async fn terminal_hangup_probe() {
322        if std::env::var_os(HANGUP_PROBE).is_none() {
323            return;
324        }
325        let stop = stop_requested().unwrap();
326        // SIGHUP is Unix-specific; the portable interrupt also has a cross-OS seam test.
327        crate::test_os::hangup_self();
328        stop.await;
329    }
330
331    /// Unlike Windows, no error here is ever transient in this sense; the predicate is a
332    /// permanent no-op, not a gap in detecting a race that would need retrying.
333    #[test]
334    fn transient_file_access_is_always_false() {
335        assert!(!transient_file_access(&io::Error::from_raw_os_error(5)));
336        assert!(!transient_file_access(&io::Error::new(
337            io::ErrorKind::PermissionDenied,
338            "permission denied"
339        )));
340    }
341}