Skip to main content

agentmux_srv/server/
files_root.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Files pane confined to one folder: a container agent's folder, shown to the person.
5//!
6//! A container agent's `/workspace` is a folder of the host that the agent can change while a window reads
7//! it, so a link or junction it swaps in later could make a Files pane show the person's own files, which
8//! the agent could then read back from a screenshot of the pane. So such a pane carries `files:root`, the
9//! canonical host folder it was opened on, and srv checks it on the requests the pane makes that name it
10//! (the listing, the watch, the preview stream, opening in the Editor, and the changes): the path is
11//! resolved again at each access, links and junctions included, and refused unless it lies inside the
12//! root. The pane lists, navigates, previews and opens files in the Editor; it changes nothing.
13//!
14
15use std::path::{Path, PathBuf};
16
17use crate::backend::rpc_types::{CommandPaneOpenData, FsError, FsErrorKind, FsListResult};
18use crate::server::AppState;
19
20/// The block meta key that confines a Files pane. Written when the pane is opened; a client may not write it.
21pub(crate) const FILES_ROOT_META_KEY: &str = "files:root";
22
23/// The folder `block_id`'s Files pane is confined to, if it is.
24pub(crate) fn root_of(state: &AppState, block_id: &str) -> Option<PathBuf> {
25    let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten()?;
26    let root = crate::backend::obj::meta_get_string(&block.meta, FILES_ROOT_META_KEY, "");
27    (!root.trim().is_empty()).then(|| PathBuf::from(root))
28}
29
30/// `path` as it is now (links and junctions resolved), if it lies inside `root`.
31pub(crate) fn confine(root: &Path, path: &str) -> Result<PathBuf, String> {
32    let canonical = crate::server::browser_uploads::canonical;
33    let root = canonical(root).map_err(|_| "The folder this pane shows can't be read any more.".to_string())?;
34    let real = canonical(Path::new(path.trim())).map_err(|_| "That doesn't exist any more.".to_string())?;
35    if real.starts_with(&root) {
36        Ok(real)
37    } else {
38        Err(format!(
39            "This pane shows only {} from an agent's workspace, and {} is outside it: a link in the workspace leads out of it. Nothing outside the workspace is shown here.",
40            root.display(),
41            real.display()
42        ))
43    }
44}
45
46/// `path` as the pane `block_id` may use it: for a confined pane, resolved now and inside its root (else
47/// the reason); for any other, as asked.
48pub(crate) async fn bound_path(state: &AppState, block_id: Option<&str>, path: &str) -> Result<String, String> {
49    let Some(root) = block_id.and_then(|b| root_of(state, b)) else {
50        return Ok(path.to_string());
51    };
52    let asked = path.to_string();
53    tokio::task::spawn_blocking(move || confine(&root, &asked))
54        .await
55        .map_err(|e| format!("filesystem task failed: {e}"))?
56        .map(|real| real.to_string_lossy().into_owned())
57}
58
59/// Whether `block_id` is a pane confined to a folder.
60pub(crate) fn is_confined(state: &AppState, block_id: Option<&str>) -> bool {
61    block_id.is_some_and(|b| root_of(state, b).is_some())
62}
63
64/// The refusal for a change asked of a confined pane.
65pub(crate) const READ_ONLY: &str = "This folder is shown read-only from an agent's workspace: nothing in it can be changed from this pane.";
66
67/// The refusal for handing a file to another program from a confined pane.
68pub(crate) const NO_PROGRAMS: &str = "This folder is shown read-only from an agent's workspace: nothing in it can be opened with another program from this pane.";
69
70/// Refuses a change from the pane `block_id` when it is confined.
71pub(crate) fn refuse_change(state: &AppState, block_id: Option<&str>) -> Result<(), String> {
72    match block_id {
73        Some(block) if root_of(state, block).is_some() => Err(READ_ONLY.to_string()),
74        _ => Ok(()),
75    }
76}
77
78/// The meta of a Files pane confined to `folder` (resolved), which the pane's title calls `of`.
79pub(crate) fn confined_meta(folder: &Path, of: &str) -> crate::backend::obj::MetaMapType {
80    let host = folder.to_string_lossy().into_owned();
81    let mut meta = crate::backend::obj::MetaMapType::new();
82    meta.insert("view".into(), "files".into());
83    meta.insert("files:path".into(), host.clone().into());
84    meta.insert(FILES_ROOT_META_KEY.into(), host.into());
85    meta.insert("frame:title".into(), format!("{of} (read-only, from the agent's workspace)").into());
86    meta
87}
88
89/// `pane.open` from a confined pane: only a file inside its folder, opened in an Editor. Its path is
90/// replaced by the resolved one, and the answer is the pane's folder (none: the open is from no such pane).
91pub(crate) async fn bind_pane_open(state: &AppState, cmd: &mut CommandPaneOpenData) -> Result<Option<PathBuf>, String> {
92    let from = [cmd.split_reference_block_id.as_deref(), cmd.stack_onto_block_id.as_deref()]
93        .into_iter()
94        .flatten()
95        .find_map(|b| root_of(state, b).map(|root| (b.to_string(), root)));
96    let Some((from, root)) = from else { return Ok(None) };
97    let remote = cmd.connection.as_deref().map(str::trim).is_some_and(|c| !c.is_empty() && c != "local");
98    let Some(file) = cmd.file.clone().filter(|_| cmd.view == "editor" && cmd.meta.is_none() && !remote) else {
99        return Err("From this folder, shown read-only from an agent's workspace, only a file inside it can be opened, in an Editor.".to_string());
100    };
101    cmd.file = Some(bound_path(state, Some(&from), &file).await?);
102    Ok(Some(root))
103}
104
105/// A listing that failed because the folder lies outside the pane's root.
106pub(crate) fn outside_listing(path: &str, message: String) -> FsListResult {
107    FsListResult {
108        path: path.to_string(),
109        entries: Vec::new(),
110        cursor: None,
111        error: Some(FsError { kind: FsErrorKind::PermissionDenied, message }),
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    fn folders() -> (PathBuf, PathBuf, PathBuf) {
120        let top = std::env::temp_dir().join(format!("agentmux-froot-{}-{}", std::process::id(), uuid::Uuid::new_v4().simple()));
121        let root = top.join("ws");
122        let outside = top.join("private");
123        std::fs::create_dir_all(root.join("src")).unwrap();
124        std::fs::create_dir_all(&outside).unwrap();
125        std::fs::write(outside.join("secret.txt"), "the person's own file").unwrap();
126        (top, root, outside)
127    }
128
129    #[test]
130    fn a_folder_inside_the_root_is_allowed_and_one_outside_is_refused() {
131        let (top, root, outside) = folders();
132        assert!(confine(&root, &root.join("src").to_string_lossy()).is_ok());
133        assert!(confine(&root, &root.to_string_lossy()).is_ok());
134        assert!(confine(&root, &outside.to_string_lossy()).unwrap_err().contains("outside it"));
135        assert!(confine(&root, &root.join("..").join("private").to_string_lossy()).is_err());
136        let _ = std::fs::remove_dir_all(top);
137    }
138
139    /// The folder was inside the root when the pane opened and a link was put in its place after.
140    #[test]
141    fn a_symlink_swapped_in_after_the_pane_opened_is_refused() {
142        let (top, root, outside) = folders();
143        let dir = root.join("src");
144        assert!(confine(&root, &dir.to_string_lossy()).is_ok());
145        std::fs::remove_dir_all(&dir).unwrap();
146        #[cfg(unix)]
147        let linked = std::os::unix::fs::symlink(&outside, &dir).is_ok();
148        #[cfg(windows)]
149        let linked = std::os::windows::fs::symlink_dir(&outside, &dir).is_ok();
150        if linked {
151            let err = confine(&root, &dir.to_string_lossy()).unwrap_err();
152            assert!(err.contains("outside it"), "{err}");
153        } else {
154            eprintln!("symlinks are not allowed here: the swapped-symlink check was skipped");
155        }
156        let _ = std::fs::remove_dir_all(top);
157    }
158
159    /// A Windows junction needs no privilege: made with `mklink /J`.
160    #[cfg(windows)]
161    #[test]
162    fn a_junction_swapped_in_after_the_pane_opened_is_refused() {
163        let (top, root, outside) = folders();
164        let dir = root.join("src");
165        assert!(confine(&root, &dir.to_string_lossy()).is_ok());
166        std::fs::remove_dir_all(&dir).unwrap();
167        let made = std::process::Command::new("cmd")
168            .args(["/C", "mklink", "/J", &dir.to_string_lossy(), &outside.to_string_lossy()])
169            .output()
170            .map(|o| o.status.success())
171            .unwrap_or(false);
172        assert!(made, "mklink /J failed");
173        let err = confine(&root, &dir.to_string_lossy()).unwrap_err();
174        assert!(err.contains("outside it"), "{err}");
175        let _ = std::fs::remove_dir_all(top);
176    }
177
178    /// A state holding a Files pane confined to `root`, and one that is not.
179    fn state_with_panes(root: &Path) -> AppState {
180        let state = crate::server::tests::test_state();
181        let mut meta = crate::backend::obj::MetaMapType::default();
182        meta.insert(FILES_ROOT_META_KEY.into(), root.to_string_lossy().into_owned().into());
183        let mut confined = crate::backend::obj::Block { oid: "confined".into(), meta, ..Default::default() };
184        state.mstore.insert(&mut confined).unwrap();
185        let mut open = crate::backend::obj::Block { oid: "open".into(), ..Default::default() };
186        state.mstore.insert(&mut open).unwrap();
187        state
188    }
189
190    #[tokio::test]
191    async fn a_confined_pane_gets_only_paths_inside_its_root() {
192        let (top, root, outside) = folders();
193        let state = state_with_panes(&root);
194        let inside = root.join("src").to_string_lossy().into_owned();
195        let secret = outside.join("secret.txt").to_string_lossy().into_owned();
196        assert!(bound_path(&state, Some("confined"), &inside).await.is_ok());
197        assert!(bound_path(&state, Some("confined"), &secret).await.unwrap_err().contains("outside it"));
198        // A pane that is not confined, and a request naming no pane, are as before.
199        assert_eq!(bound_path(&state, Some("open"), &secret).await.unwrap(), secret);
200        assert_eq!(bound_path(&state, None, &secret).await.unwrap(), secret);
201        assert!(is_confined(&state, Some("confined")));
202        assert!(!is_confined(&state, Some("open")) && !is_confined(&state, None));
203        let _ = std::fs::remove_dir_all(top);
204    }
205
206    #[tokio::test]
207    async fn a_confined_pane_hands_nothing_to_another_program() {
208        let (top, root, _outside) = folders();
209        let file = root.join("src").join("a.sh");
210        std::fs::write(&file, "x").unwrap();
211        let state = state_with_panes(&root);
212        for reveal in [false, true] {
213            let cmd = crate::backend::rpc_types::FsPathReq {
214                path: file.to_string_lossy().into_owned(),
215                block_id: Some("confined".into()),
216                confirmed: None,
217            };
218            let err = crate::server::fs_handlers::open_or_reveal_bound(&state, cmd, reveal).await.unwrap_err();
219            assert_eq!(err, NO_PROGRAMS);
220        }
221        let _ = std::fs::remove_dir_all(top);
222    }
223
224    #[tokio::test]
225    async fn pane_open_from_a_confined_pane_is_one_file_inside_it_in_an_editor() {
226        let (top, root, outside) = folders();
227        std::fs::write(root.join("src").join("a.txt"), "x").unwrap();
228        let state = state_with_panes(&root);
229        let open = |view: &str, file: &std::path::Path| CommandPaneOpenData {
230            view: view.into(),
231            file: Some(file.to_string_lossy().into_owned()),
232            split_reference_block_id: Some("confined".into()),
233            ..Default::default()
234        };
235        let mut ok = open("editor", &root.join("src").join("a.txt"));
236        bind_pane_open(&state, &mut ok).await.unwrap();
237        assert!(ok.file.unwrap().ends_with("a.txt"));
238        let mut elsewhere = open("editor", &outside.join("secret.txt"));
239        assert!(bind_pane_open(&state, &mut elsewhere).await.unwrap_err().contains("outside it"));
240        let mut terminal = open("term", &root);
241        assert!(bind_pane_open(&state, &mut terminal).await.is_err());
242        // From a pane that is not confined, nothing changes.
243        let mut free = open("editor", &outside.join("secret.txt"));
244        free.split_reference_block_id = Some("open".into());
245        bind_pane_open(&state, &mut free).await.unwrap();
246        let _ = std::fs::remove_dir_all(top);
247    }
248
249    #[test]
250    fn a_missing_folder_is_not_reported_as_outside() {
251        let (top, root, _outside) = folders();
252        let err = confine(&root, &root.join("gone").to_string_lossy()).unwrap_err();
253        assert!(err.contains("doesn't exist"), "{err}");
254        let _ = std::fs::remove_dir_all(top);
255    }
256}