agentmux_common/data_paths/dir_links.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Directory helpers `DataPaths` leans on: the history link (a junction or symlink that
5//! keeps one history folder across per-channel stores) and the owner-only root.
6
7use std::path::Path;
8
9/// Best-effort: ensure `link_path` (a `projects/` subdirectory inside an
10/// [`super::isolated_auth_enabled`]-isolated provider credential dir) is a
11/// directory junction (Windows) / symlink (Unix) pointing at
12/// `target_dir` (the always-global [`super::DataPaths::identity_history_dir`]),
13/// so a provider's session transcripts stay reachable across a
14/// channel/build change even though the credential directory around them
15/// is per-channel isolated. See
16/// `docs/specs/SPEC_AGENT_IDENTITY_HISTORY_PERSISTENCE_PROTOCOL_2026_08_16.md`
17/// §4.1.
18///
19/// A Windows **junction** (not a symlink) is used deliberately —
20/// `std::os::windows::fs::symlink_dir` requires `SeCreateSymbolicLinkPrivilege`
21/// (admin, or Developer Mode enabled), which this app cannot assume every
22/// user has; junctions need no special privilege. Uses the `junction`
23/// crate (`FSCTL_SET_REPARSE_POINT` under the hood) rather than
24/// hand-rolled reparse-point FFI, for the same reason this codebase's own
25/// `bundle.rs` comment notes about Windows symlink privilege requirements
26/// — this is credential-adjacent storage, not a place to improvise
27/// low-level filesystem code.
28///
29/// Idempotent: a no-op if `link_path` is already a link pointing at
30/// `target_dir`. If a REAL directory already exists at `link_path` (data
31/// written before this function existed, or before `isolated_auth_enabled`
32/// applied to this bundle), its entries are moved into `target_dir` one
33/// by one via `rename` (atomic, same-volume — always true here, both
34/// live under the single `~/.agentmux` tree) before the now-empty
35/// directory is replaced with the link. **Never deletes or overwrites
36/// data**: an entry whose name already exists at the target is left
37/// exactly where it was, under the old per-channel path, rather than
38/// risking clobbering real history — it becomes reachable again once a
39/// human resolves the name collision, rather than silently lost. Any
40/// I/O error at any step is returned to the caller, who is expected to
41/// treat this as best-effort (log and continue spawning) per the same
42/// philosophy as the jekt-key injection in `agent_config.rs`.
43pub fn ensure_history_link(link_path: &std::path::Path, target_dir: &std::path::Path) -> std::io::Result<()> {
44 std::fs::create_dir_all(target_dir)?;
45 // The `junction` crate creates the link via a plain `fs::create_dir`
46 // (not `create_dir_all`) on `link_path` itself, so its parent must
47 // already exist. Unix's `symlink` has the same requirement. Real
48 // production callers already have this (the isolated identity dir is
49 // created before this function runs), but this function must not
50 // depend on caller ordering to be correct/testable on its own.
51 if let Some(parent) = link_path.parent() {
52 std::fs::create_dir_all(parent)?;
53 }
54
55 if link_points_at(link_path, target_dir) {
56 return Ok(());
57 }
58 clear_link_path(link_path, target_dir)?;
59 create_dir_link(link_path, target_dir)
60}
61
62/// Whether `link_path` is already a link to `target_dir`.
63fn link_points_at(link_path: &std::path::Path, target_dir: &std::path::Path) -> bool {
64 #[cfg(windows)]
65 let points_at = junction::exists(link_path).unwrap_or(false)
66 && junction::get_target(link_path).ok().as_deref() == Some(target_dir);
67 #[cfg(unix)]
68 let points_at = std::fs::symlink_metadata(link_path)
69 .map(|m| m.file_type().is_symlink())
70 .unwrap_or(false)
71 && std::fs::read_link(link_path).ok().as_deref() == Some(target_dir);
72 #[cfg(not(any(windows, unix)))]
73 let points_at = false;
74 points_at
75}
76
77/// Makes room for the link at `link_path`: a real directory is emptied into `target_dir`
78/// and removed, a link to somewhere else is dropped, a plain file is an error, nothing is fine.
79fn clear_link_path(link_path: &std::path::Path, target_dir: &std::path::Path) -> std::io::Result<()> {
80 match std::fs::symlink_metadata(link_path) {
81 Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => migrate_real_dir(link_path, target_dir)?,
82 Ok(meta) if meta.file_type().is_symlink() => {
83 // A link already exists but pointed at something else (stale/
84 // wrong target from a prior version of this function). Safe
85 // to drop: no data lives directly at a link path, only at
86 // whatever it points to, which this doesn't touch.
87 #[cfg(windows)]
88 {
89 // `junction::delete` drops the reparse point and leaves an empty
90 // directory behind, which the new junction cannot be created over.
91 let _ = junction::delete(link_path);
92 let _ = std::fs::remove_dir(link_path);
93 }
94 #[cfg(unix)]
95 {
96 let _ = std::fs::remove_file(link_path);
97 }
98 }
99 Ok(_) => {
100 // A plain file (or anything else that's neither a real
101 // directory nor a link) sits where a link needs to go.
102 // Nothing in this codebase is expected to ever put a file
103 // named "projects" here, but reagentx P2 on PR #2605 caught
104 // that the previous version of this match arm silently
105 // deleted it via remove_file/junction::delete with no
106 // migration — directly contradicting this function's own
107 // never-delete-data guarantee. Surface an error instead of
108 // guessing what to do with unexpected real data.
109 return Err(std::io::Error::new(
110 std::io::ErrorKind::AlreadyExists,
111 format!(
112 "ensure_history_link: {} exists and is neither a directory nor a link; \
113 refusing to delete it",
114 link_path.display()
115 ),
116 ));
117 }
118 Err(_) => {
119 // Nothing at link_path yet — normal first-time case.
120 }
121 }
122 Ok(())
123}
124
125/// Moves what is in the real directory `link_path` into `target_dir` and removes it.
126fn migrate_real_dir(link_path: &std::path::Path, target_dir: &std::path::Path) -> std::io::Result<()> {
127 // Pre-existing REAL directory: migrate its contents (never
128 // clobbering an existing target entry), then remove the
129 // now-empty directory so a link can take its place.
130 for entry in std::fs::read_dir(link_path)? {
131 let entry = entry?;
132 let dest = target_dir.join(entry.file_name());
133 if !dest.exists() {
134 std::fs::rename(entry.path(), &dest)?;
135 }
136 }
137 // Only remove if migration left it empty (i.e. every entry
138 // moved, or there were none) — a leftover name collision
139 // means real, un-migrated data is still here, and this must
140 // not silently paper over that by leaving a directory where
141 // a link was expected. Surfacing the removal error is the
142 // signal to the caller that this bundle needs manual review.
143 std::fs::remove_dir(link_path)?;
144 Ok(())
145}
146
147/// Creates the link `link_path` to `target_dir`: a junction on Windows, a symlink on Unix.
148fn create_dir_link(link_path: &std::path::Path, target_dir: &std::path::Path) -> std::io::Result<()> {
149 #[cfg(windows)]
150 {
151 junction::create(target_dir, link_path)?;
152 }
153 #[cfg(unix)]
154 {
155 std::os::unix::fs::symlink(target_dir, link_path)?;
156 }
157 #[cfg(not(any(windows, unix)))]
158 {
159 return Err(std::io::Error::new(
160 std::io::ErrorKind::Unsupported,
161 "ensure_history_link: no directory-link mechanism on this platform",
162 ));
163 }
164
165 Ok(())
166}
167
168/// What [`ensure_owner_only_dir`] did.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum OwnerOnlyOutcome {
171 /// The directory did not exist; it was created with mode `0700`.
172 Created,
173 /// It existed with group/other permission bits set; those were removed.
174 /// `previous_mode` is the old permission bits (e.g. `0o755`).
175 Tightened { previous_mode: u32 },
176 /// It already had no group/other access. Nothing changed.
177 AlreadyPrivate,
178 /// Nothing to do here: not a Unix platform (Windows scopes the user
179 /// profile, and so `~/.agentmux`, to its owner through ACLs), or `dir`
180 /// is the user's home directory itself — a misconfigured
181 /// `AGENTMUX_HOME_OVERRIDE`/`AGENTMUX_DATA_HOME` pointing at `$HOME`
182 /// must not chmod the whole home to `0700`.
183 NotApplicable,
184}
185
186/// Make `dir` owner-only on Unix: create it `0700` if missing (its parents
187/// with the normal umask — they are the user's, not AgentMux's), or strip
188/// group/other bits from an existing directory, keeping the owner bits as
189/// they were. See [`super::DataPaths::ensure_dirs`] for why (#3682).
190///
191/// Follows a symlinked root to its target, as every other access to the root
192/// already does. Errors if `dir` exists but is not a directory.
193pub fn ensure_owner_only_dir(dir: &Path) -> std::io::Result<OwnerOnlyOutcome> {
194 ensure_owner_only_dir_inner(dir, dirs::home_dir().as_deref())
195}
196
197pub(super) fn ensure_owner_only_dir_inner(dir: &Path, user_home: Option<&Path>) -> std::io::Result<OwnerOnlyOutcome> {
198 #[cfg(unix)]
199 {
200 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
201
202 if let Some(home) = user_home {
203 let same = match (std::fs::canonicalize(dir), std::fs::canonicalize(home)) {
204 (Ok(a), Ok(b)) => a == b,
205 _ => dir == home,
206 };
207 if same {
208 return Ok(OwnerOnlyOutcome::NotApplicable);
209 }
210 }
211
212 match std::fs::metadata(dir) {
213 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
214 if let Some(parent) = dir.parent() {
215 std::fs::create_dir_all(parent)?;
216 }
217 // Non-recursive on purpose: only the root itself is ours to
218 // make private. The requested mode is still masked by the
219 // umask, which can only remove bits — never add group/other.
220 match std::fs::DirBuilder::new().mode(0o700).create(dir) {
221 Ok(()) => return Ok(OwnerOnlyOutcome::Created),
222 // Lost a race with a concurrent launch: fall through and
223 // check what that one created.
224 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
225 Err(e) => return Err(e),
226 }
227 }
228 Err(e) => return Err(e),
229 Ok(_) => {}
230 }
231
232 let meta = std::fs::metadata(dir)?;
233 if !meta.is_dir() {
234 return Err(std::io::Error::new(
235 std::io::ErrorKind::AlreadyExists,
236 format!("{} exists and is not a directory", dir.display()),
237 ));
238 }
239 let mode = meta.permissions().mode() & 0o777;
240 if mode & 0o077 == 0 {
241 return Ok(OwnerOnlyOutcome::AlreadyPrivate);
242 }
243 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(mode & 0o700))?;
244 Ok(OwnerOnlyOutcome::Tightened { previous_mode: mode })
245 }
246 #[cfg(not(unix))]
247 {
248 let _ = (dir, user_home);
249 Ok(OwnerOnlyOutcome::NotApplicable)
250 }
251}