Skip to main content

agentmux_srv_core/backend/vault/
files.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Files that hold a Vault value for one command: `Terminal` `run` with
5//! `secret_files` (SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md ยง4.3),
6//! for tools that read a key only from a file (`--key-file`,
7//! `GOOGLE_APPLICATION_CREDENTIALS`).
8//!
9//! Each command gets a fresh folder of its own under `<data home>/vault-files/`,
10//! readable by the user alone (0700 and 0600 on Unix; on Windows the folder is
11//! inside the user's profile, which only the user, SYSTEM and Administrators can
12//! read). [`SecretDir`] overwrites and removes it when it is dropped, that is when
13//! the command's runner ends. A folder left by a crash is removed when srv next
14//! starts ([`init`]).
15
16use std::io::Write;
17use std::path::{Path, PathBuf};
18use std::sync::OnceLock;
19
20static ROOT: OnceLock<PathBuf> = OnceLock::new();
21
22const FOLDER: &str = "vault-files";
23
24/// Sets the folder's place and removes whatever a crashed srv left there.
25pub fn init(data_home: &Path) {
26    let root = data_home.join(FOLDER);
27    if root.exists() {
28        if let Err(e) = remove(&root) {
29            tracing::warn!(error = %e, "vault: couldn't remove the secret files a previous run left");
30        }
31    }
32    let _ = ROOT.set(root);
33}
34
35fn root() -> PathBuf {
36    ROOT.get().cloned().unwrap_or_else(|| std::env::temp_dir().join(format!("agentmux-{FOLDER}")))
37}
38
39/// Overwrites every file under `dir` with zeros, then removes the folder.
40fn remove(dir: &Path) -> std::io::Result<()> {
41    if let Ok(entries) = std::fs::read_dir(dir) {
42        for e in entries.flatten() {
43            let p = e.path();
44            if p.is_dir() {
45                let _ = remove(&p);
46            } else if let Ok(meta) = e.metadata() {
47                if let Ok(mut f) = std::fs::OpenOptions::new().write(true).open(&p) {
48                    let _ = f.write_all(&vec![0u8; meta.len() as usize]);
49                    let _ = f.sync_all();
50                }
51            }
52        }
53    }
54    std::fs::remove_dir_all(dir)
55}
56
57fn private_dir(path: &Path) -> std::io::Result<()> {
58    let mut b = std::fs::DirBuilder::new();
59    b.recursive(true);
60    #[cfg(unix)]
61    {
62        use std::os::unix::fs::DirBuilderExt;
63        b.mode(0o700);
64    }
65    b.create(path)
66}
67
68/// One command's folder. Dropping it removes its files.
69#[derive(Debug)]
70pub struct SecretDir {
71    path: PathBuf,
72}
73
74impl SecretDir {
75    pub fn create() -> Result<Self, String> {
76        let root = root();
77        private_dir(&root).map_err(|e| format!("couldn't make the folder for secret files: {e}"))?;
78        let path = root.join(uuid::Uuid::new_v4().to_string());
79        private_dir(&path).map_err(|e| format!("couldn't make the folder for secret files: {e}"))?;
80        Ok(SecretDir { path })
81    }
82
83    /// Writes `value` to a new file named `name`, readable by the user alone, and
84    /// returns its path.
85    pub fn write(&self, name: &str, value: &str) -> Result<PathBuf, String> {
86        let file = self.path.join(name);
87        let mut o = std::fs::OpenOptions::new();
88        o.write(true).create_new(true);
89        #[cfg(unix)]
90        {
91            use std::os::unix::fs::OpenOptionsExt;
92            o.mode(0o600);
93        }
94        let mut f = o.open(&file).map_err(|e| format!("couldn't write the secret file for {name}: {e}"))?;
95        f.write_all(value.as_bytes()).and_then(|_| f.sync_all()).map_err(|e| format!("couldn't write the secret file for {name}: {e}"))?;
96        Ok(file)
97    }
98
99    pub fn path(&self) -> &Path {
100        &self.path
101    }
102}
103
104impl Drop for SecretDir {
105    fn drop(&mut self) {
106        if let Err(e) = remove(&self.path) {
107            tracing::warn!(error = %e, "vault: couldn't remove a command's secret files; they go when srv next starts");
108        }
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn a_folder_holds_its_files_until_dropped() {
118        let dir = SecretDir::create().unwrap();
119        let file = dir.write("SERVICE_KEY", "not-a-real-key-123").unwrap();
120        assert_eq!(std::fs::read_to_string(&file).unwrap(), "not-a-real-key-123");
121        assert!(dir.write("SERVICE_KEY", "again").is_err(), "a name is written once");
122        let folder = dir.path().to_path_buf();
123        drop(dir);
124        assert!(!folder.exists(), "the folder goes with the command");
125    }
126
127    #[cfg(unix)]
128    #[test]
129    fn files_and_folders_are_the_users_alone() {
130        use std::os::unix::fs::PermissionsExt;
131        let dir = SecretDir::create().unwrap();
132        let file = dir.write("K", "value-value").unwrap();
133        assert_eq!(std::fs::metadata(dir.path()).unwrap().permissions().mode() & 0o777, 0o700);
134        assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);
135    }
136
137    #[test]
138    fn init_removes_what_a_crash_left() {
139        let home = std::env::temp_dir().join(format!("agentmux-files-test-{}", uuid::Uuid::new_v4()));
140        let left = home.join(FOLDER).join("old");
141        std::fs::create_dir_all(&left).unwrap();
142        std::fs::write(left.join("K"), "left over").unwrap();
143        init(&home);
144        assert!(!home.join(FOLDER).exists());
145        let _ = std::fs::remove_dir_all(&home);
146    }
147}