Skip to main content

agentmux_srv_core/backend/container/
runtime_socket.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! No container runtime socket, pipe or control folder, and no AgentMux data folder (the root `~/.agentmux`, its shared
5//! folder, every channel's and dev build's data, config, logs and runtime folders), is reachable through any mount of a
6//! container agent, or a folder that holds one (a home folder, the AgentMux root), whichever field the mount comes from (its volumes list, its workspace folder) and whoever wrote it (the
7//! definition, a template, a block's launch settings, another channel's registry). Sources are
8//! compared case-insensitively, with `\` as `/`, `.` and `..` resolved, and a link followed where the path exists.
9//! [`refused_mount`] is asked once, before an existing container is reused or a new one made; definitions that come in from
10//! outside (the shared registry, an old template) have the entries dropped ([`without_refused`]), and a definition saved with
11//! one is refused ([`refused_in_json`]).
12
13use std::path::PathBuf;
14
15use crate::backend::cli_messaging::normalized;
16
17/// A socket file or a named pipe whose name has one of these in it, and ends in `.sock`, is a runtime's.
18const BRANDS: [&str; 5] = ["docker", "podman", "containerd", "crio", "buildkit"];
19/// Names that are a runtime's pipe or socket whatever their folder.
20const NAMES: [&str; 5] = ["docker_engine", "docker_cli", "dockerdesktoplinuxengine", "podman-machine-default", "docker_engine_linux"];
21/// Where a source starting this way is a Windows named pipe.
22const PIPES: [&str; 3] = ["//./pipe", "//?/pipe", "npipe:"];
23/// Runtime sockets and folders on a Linux or macOS host, and inside Docker Desktop's and WSL's machines. A source is refused
24/// when it is one, is inside one, or holds one.
25const SYSTEM: &[&str] = &[
26    "/var/run/docker.sock",
27    "/run/docker.sock",
28    "/var/run/docker",
29    "/run/docker",
30    "/var/run/podman",
31    "/run/podman",
32    "/var/run/containerd",
33    "/run/containerd",
34    "/var/run/crio",
35    "/run/crio",
36    "/run/k3s",
37    "/run/buildkit",
38    "/run/snap.docker",
39    "/var/run/snap.docker",
40    "/var/lib/docker",
41    "/var/lib/containers",
42    "/var/lib/containerd",
43    "/var/lib/podman",
44    "/var/snap/docker",
45    "/mnt/wsl/docker-desktop",
46    "/mnt/wsl/docker-desktop-bind-mounts",
47    "/mnt/wsl/podman-sockets",
48    "/var/run/cri-dockerd.sock",
49    "/run/cri-dockerd.sock",
50];
51/// Under a user's home folder. A folder that holds one of these is refused only where the entry is there.
52const HOME: &[&str] = &[
53    ".docker/run",
54    ".docker/desktop",
55    ".colima",
56    ".lima",
57    ".rd",
58    ".local/share/containers",
59    ".local/share/docker",
60    "library/containers/com.docker.docker",
61    "appdata/local/docker",
62];
63/// Under the Windows data folders (`%PROGRAMDATA%`, `%LOCALAPPDATA%`), with the same rule.
64const DATA: &[&str] = &["docker", "dockerdesktop", "docker desktop"];
65
66/// The first of a container agent's volumes, or its workspace folder, that it may not mount, as the source (or, for a pipe,
67/// the whole entry): a host folder the CLI keeps its sessions in, or a container runtime's socket, pipe or folder.
68pub fn refused_mount(volumes: &[String], workspace: Option<&str>) -> Option<String> {
69    refused_mount_in(volumes, workspace, &homes(), &data_dirs())
70}
71
72fn refused_mount_in(volumes: &[String], workspace: Option<&str>, homes: &[PathBuf], data: &[PathBuf]) -> Option<String> {
73    refused_in(volumes, homes, data).or_else(|| workspace.map(str::trim).filter(|w| !w.is_empty()).and_then(|w| refused_entry(w, w, homes, data)))
74}
75
76/// [`refused_mount`] for a volumes list alone.
77pub fn refused_volume(volumes: &[String]) -> Option<String> {
78    refused_mount(volumes, None)
79}
80
81/// The volumes of a definition's `container_volumes` (a JSON array of specs); nothing for text that is not one.
82fn volumes_of(json: &str) -> Vec<String> {
83    serde_json::from_str(json).unwrap_or_default()
84}
85
86/// The first entry of a definition's `container_volumes` that a container may not mount.
87pub fn refused_in_json(json: &str) -> Option<String> {
88    refused_volume(&volumes_of(json))
89}
90
91/// A definition's `container_volumes` without the entries a container may not mount, for one that comes in from outside
92/// this AgentMux. The entries dropped are logged; a list with none is returned as it was.
93pub fn without_refused(json: &str) -> String {
94    let all = volumes_of(json);
95    let kept: Vec<&String> = all.iter().filter(|v| refused_volume(std::slice::from_ref(v)).is_none()).collect();
96    if kept.len() == all.len() {
97        return json.to_string();
98    }
99    tracing::warn!(dropped = all.len() - kept.len(), "a definition from outside listed a mount a container may not have (a container runtime's socket or folder); the entry is dropped");
100    serde_json::to_string(&kept).unwrap_or_else(|_| "[]".to_string())
101}
102
103fn refused_in(volumes: &[String], homes: &[PathBuf], data: &[PathBuf]) -> Option<String> {
104    volumes.iter().find_map(|spec| {
105        let (source, _, _) = super::parse_volume_spec(spec)?;
106        refused_entry(spec, source, homes, data)
107    })
108}
109
110/// `spec` is the whole entry as written, `source` the host side of it.
111fn refused_entry(spec: &str, source: &str, homes: &[PathBuf], data: &[PathBuf]) -> Option<String> {
112    if crate::backend::cli_messaging::refused_volume_source(std::iter::once(source)).is_some() {
113        return Some(source.to_string());
114    }
115    let raw = spec.replace('\\', "/").to_lowercase();
116    if PIPES.iter().any(|p| raw.starts_with(p)) {
117        // A pipe is named by its path; a form that does not split into a path (`npipe:`) by the whole entry.
118        return Some(if source.starts_with(['/', '\\']) { source.to_string() } else { spec.to_string() });
119    }
120    (is_host_path(source) && (names_runtime(source, homes, data) || reaches_agentmux_data(source, homes))).then(|| source.to_string())
121}
122
123/// The AgentMux roots a mount is compared with: `.agentmux` in each home folder, and the root this instance runs in.
124fn agentmux_roots(homes: &[PathBuf]) -> Vec<PathBuf> {
125    let mut roots: Vec<PathBuf> = homes.iter().map(|h| h.join(".agentmux")).collect();
126    roots.extend(agentmux_common::data_paths::agentmux_root().ok());
127    roots
128}
129
130/// A path as the forms a drive path takes across Windows, WSL and a POSIX shell (`c:/x`, `/mnt/c/x`, `/c/x`), so a mount
131/// spelled one way is compared with a folder spelled another. A path that is no drive path is its own only form.
132fn drive_forms(p: &str) -> Vec<String> {
133    let rest_of = |s: &str| s.strip_prefix('/').unwrap_or(s).to_string();
134    let drive = |s: &str| -> Option<(char, String)> {
135        let b = s.as_bytes();
136        if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b.len() == 2 || b[2] == b'/') {
137            return Some((b[0] as char, s[2..].to_string()));
138        }
139        let wsl = s.strip_prefix("/mnt/").or_else(|| s.strip_prefix('/'))?;
140        let mut chars = wsl.chars();
141        let letter = chars.next().filter(char::is_ascii_alphabetic)?;
142        let tail = chars.as_str();
143        (tail.is_empty() || tail.starts_with('/')).then(|| (letter, tail.to_string()))
144    };
145    let mut forms = vec![p.to_string()];
146    if let Some((letter, tail)) = drive(p) {
147        let tail = if tail.is_empty() { String::new() } else { format!("/{}", rest_of(&tail)) };
148        forms.extend([format!("{letter}:{tail}"), format!("/mnt/{letter}{tail}"), format!("/{letter}{tail}")]);
149    }
150    forms.sort();
151    forms.dedup();
152    forms
153}
154
155/// Every form of `source` that reaches somewhere: as written, spelled across drive conventions, and where a link leads.
156fn forms_of(source: &str, homes: &[PathBuf]) -> Vec<String> {
157    let mut paths = vec![comparable(source, homes)];
158    if let Ok(real) = std::fs::canonicalize(source.trim()) {
159        paths.push(comparable(&real.to_string_lossy(), &[]));
160    }
161    paths.iter().flat_map(|p| drive_forms(p)).collect()
162}
163
164/// The folders an instance keeps beside its `agents` folder: none of them is a clone's name.
165const INSTANCE_FOLDERS: [&str; 6] = ["data", "config", "logs", "runtime", "cef-cache", "agents"];
166
167/// Whether `rel`, a path inside an AgentMux root, is inside an agent's own workspace folder (`agents/<name>`, or the same
168/// under a channel or a dev build), where a container agent's workspace is made. The `agents` folder itself holds the others.
169fn in_a_workspace(rel: &str) -> bool {
170    let parts: Vec<&str> = rel.split('/').collect();
171    let after = match parts.as_slice() {
172        ["agents", rest @ ..] => rest,
173        ["channels", _, "agents", rest @ ..] | ["dev", _, "agents", rest @ ..] => rest,
174        // A dev build with a clone id: `dev/<branch>/<clone>/agents/<name>`. The clone is not one of an instance's own folders.
175        ["dev", _, clone, "agents", rest @ ..] if !INSTANCE_FOLDERS.contains(clone) => rest,
176        _ => return false,
177    };
178    !after.is_empty()
179}
180
181/// Whether a mount source is an AgentMux root, a folder holding one (a home folder), or inside a root anywhere but an
182/// agent's own workspace folder: its data, config, logs, runtime and shared folders, whatever channel or dev build.
183fn reaches_agentmux_data(source: &str, homes: &[PathBuf]) -> bool {
184    // Each root with whether it is there: a folder holding one is refused only where it is, as for a runtime's own folders.
185    let roots: Vec<(String, bool)> = agentmux_roots(homes)
186        .iter()
187        .flat_map(|r| {
188            let there = r.exists();
189            forms_of(&r.to_string_lossy(), homes).into_iter().map(move |form| (form, there))
190        })
191        .collect();
192    forms_of(source, homes).iter().any(|p| {
193        roots.iter().any(|(root, there)| {
194            if p == root || (*there && above(p, root)) {
195                return true;
196            }
197            p.strip_prefix(root.as_str()).and_then(|rest| rest.strip_prefix('/')).is_some_and(|rel| !in_a_workspace(rel))
198        })
199    })
200}
201
202/// Whether a volume source is a path on the host (a bind mount), not a named volume.
203fn is_host_path(source: &str) -> bool {
204    let b = source.as_bytes();
205    source.starts_with(['/', '\\', '~']) || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':')
206}
207
208/// A source as compared: the home folder in place of a leading `~`, then lower case and `/` separators, with no `.`, `..`
209/// or doubled separator, and none of Windows' extended-path prefix.
210fn comparable(source: &str, homes: &[PathBuf]) -> String {
211    let source = source.trim();
212    let expanded = match (source.strip_prefix('~'), homes.first()) {
213        (Some(rest), Some(home)) if rest.is_empty() || rest.starts_with(['/', '\\']) => format!("{}{rest}", home.to_string_lossy()),
214        _ => source.to_string(),
215    };
216    let flat = normalized(&expanded).to_lowercase();
217    flat.strip_prefix("/?/").map_or(flat.clone(), str::to_string)
218}
219
220/// `p` is `dir`, or inside it.
221fn inside(p: &str, dir: &str) -> bool {
222    p == dir || p.strip_prefix(dir).is_some_and(|rest| rest.starts_with('/'))
223}
224
225/// `p` is a folder above `dir`.
226fn above(p: &str, dir: &str) -> bool {
227    dir.strip_prefix(p).is_some_and(|rest| rest.starts_with('/')) || (p == "/" && dir.starts_with('/'))
228}
229
230/// Whether a path or any component of it is a runtime's socket or pipe by name.
231fn named_like_a_socket(p: &str) -> bool {
232    p.split('/').any(|c| NAMES.contains(&c) || (c.ends_with(".sock") && BRANDS.iter().any(|b| c.contains(b))))
233}
234
235fn names_runtime(source: &str, homes: &[PathBuf], data: &[PathBuf]) -> bool {
236    // The path as written, and where a link or a short name leads, when it exists on this host.
237    let mut forms = vec![comparable(source, homes)];
238    if let Ok(real) = std::fs::canonicalize(source.trim()) {
239        forms.push(comparable(&real.to_string_lossy(), &[]));
240    }
241    let under_home = |rel: &str| homes.iter().map(|h| h.join(rel)).collect::<Vec<_>>();
242    let user_entries: Vec<PathBuf> = HOME.iter().flat_map(|r| under_home(r)).chain(DATA.iter().flat_map(|r| data.iter().map(move |d| d.join(r)))).collect();
243    forms.iter().any(|p| {
244        named_like_a_socket(p)
245            || SYSTEM.iter().any(|dir| inside(p, dir) || above(p, dir))
246            || user_entries.iter().any(|entry| {
247                let dir = comparable(&entry.to_string_lossy(), &[]);
248                inside(p, &dir) || (above(p, &dir) && entry.exists())
249            })
250    })
251}
252
253/// The home folders of this user, as the environment names them.
254fn homes() -> Vec<PathBuf> {
255    ["HOME", "USERPROFILE"].iter().filter_map(|v| std::env::var_os(v)).map(PathBuf::from).filter(|p| p.as_os_str().len() > 1).collect()
256}
257
258/// The Windows folders Docker keeps its data in.
259fn data_dirs() -> Vec<PathBuf> {
260    ["PROGRAMDATA", "LOCALAPPDATA"].iter().filter_map(|v| std::env::var_os(v)).map(PathBuf::from).collect()
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use std::path::Path;
267
268    fn refused(spec: &str) -> bool {
269        refused_in(&[spec.to_string()], &[], &[]).is_some()
270    }
271
272    #[test]
273    fn a_socket_or_pipe_of_a_runtime_is_never_mounted_in_any_spelling() {
274        for spec in [
275            "/var/run/docker.sock:/var/run/docker.sock",
276            "/run/docker.sock:/x:ro",
277            "/var/run/docker.sock:/x",
278            "/run/podman/podman.sock:/x",
279            "/run/user/1000/podman/podman.sock:/x",
280            "/run/containerd/containerd.sock:/x",
281            "/var/run/crio/crio.sock:/x",
282            "/run/k3s/containerd/containerd.sock:/x",
283            "/mnt/wsl/docker-desktop/shared-sockets/host-services/docker.proxy.sock:/x",
284            "/somewhere/else/my-docker.sock:/x",
285            "//./pipe/docker_engine://./pipe/docker_engine",
286            "\\\\.\\pipe\\docker_engine:\\\\.\\pipe\\docker_engine",
287            "npipe:////./pipe/docker_engine:/x",
288            "//./pipe/podman-machine-default:/x",
289            "//?/pipe/anything:/x",
290        ] {
291            assert!(refused(spec), "{spec}");
292        }
293    }
294
295    #[test]
296    fn the_runtimes_folders_and_the_ones_above_them_are_refused() {
297        for spec in ["/var/run/docker:/x", "/run/podman:/x", "/var/lib/docker:/x", "/var/lib/containers/storage:/x", "/mnt/wsl/docker-desktop-bind-mounts:/x", "/var/lib:/x", "/var/run:/x", "/run:/x", "/var:/x", "/mnt/wsl:/x", "/:/x", "/var/run/:/x"] {
298            assert!(refused(spec), "{spec}");
299        }
300    }
301
302    #[test]
303    fn spellings_that_reach_the_same_place_are_refused_too() {
304        for spec in ["/var/run/./docker.sock:/x", "/VAR/RUN/Docker.sock:/x", "/var//run//docker.sock:/x", "/tmp/../var/run/docker.sock:/x", "\\var\\run\\docker.sock:/x", "/var/run/docker.sock/:/x", "/Var/Lib/Docker:/x"] {
305            assert!(refused(spec), "{spec}");
306        }
307    }
308
309    #[test]
310    fn an_ordinary_mount_is_left_alone() {
311        for spec in ["data:/data", "docker-data:/data", "/home/me/repo:/work", "/tmp:/t", "/var/log:/log:ro", "/srv/app:/app", "C:\\Users\\me\\repo:/work", "/var/run/postgresql:/pg", "/opt/docker-notes:/n", "/usr/local/bin/dockerfile-lint:/l"] {
312            assert!(!refused(spec), "{spec}");
313        }
314    }
315
316    #[test]
317    fn the_cli_session_folders_stay_refused_through_the_same_check() {
318        assert_eq!(refused_in(&["data:/d".into(), "/tmp/cc-socks/abc:/x".into()], &[], &[]).as_deref(), Some("/tmp/cc-socks/abc"));
319    }
320
321    #[test]
322    fn a_pipe_is_named_as_the_whole_entry_and_a_path_by_its_source() {
323        assert_eq!(refused_in(&["data:/d".into(), "/var/run/docker.sock:/x".into()], &[], &[]).as_deref(), Some("/var/run/docker.sock"));
324        assert_eq!(refused_in(&["npipe:////./pipe/docker_engine:/x".into()], &[], &[]).as_deref(), Some("npipe:////./pipe/docker_engine:/x"));
325    }
326
327    #[test]
328    fn a_folder_holding_a_per_user_runtime_entry_is_refused_only_where_the_entry_is() {
329        let with = tempfile::tempdir().unwrap();
330        std::fs::create_dir_all(with.path().join(".docker/run")).unwrap();
331        let without = tempfile::tempdir().unwrap();
332        let spec = |home: &Path, rel: &str| format!("{}:/x", home.join(rel).to_string_lossy().trim_end_matches(['/', '\\']));
333        let homes = |h: &Path| vec![h.to_path_buf()];
334        let check = |home: &Path, rel: &str| refused_in(&[spec(home, rel)], &homes(home), &[]).is_some();
335        assert!(check(with.path(), ""), "a home folder that holds Docker Desktop's socket folder");
336        assert!(check(with.path(), ".docker"), "the folder above it");
337        assert!(check(with.path(), ".docker/run"), "and the folder itself");
338        assert!(check(without.path(), ".colima/default"), "inside a runtime's folder, there or not");
339        assert!(!check(without.path(), ""), "a home folder with none of them in it");
340        assert!(!check(without.path(), ".docker"), "nor the folder above one that is not there");
341        assert!(!check(without.path(), "projects"));
342    }
343
344    /// The sources a container may not have, for a person whose home folder is `home`.
345    fn refused_at(home: &Path, spec: &str) -> bool {
346        refused_in(&[spec.to_string()], &[home.to_path_buf()], &[]).is_some()
347    }
348
349    /// `p` with `/` separators and none at the end.
350    fn slashed(p: &Path) -> String {
351        p.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/").trim_end_matches('/').to_string()
352    }
353
354    #[test]
355    fn the_agentmux_data_folders_and_the_folders_holding_them_are_never_mounted() {
356        let home = tempfile::tempdir().unwrap();
357        std::fs::create_dir_all(home.path().join(".agentmux/channels/stable/data")).unwrap();
358        let h = slashed(home.path());
359        for rel in [
360            "",
361            "/.agentmux",
362            "/.agentmux/shared",
363            "/.agentmux/shared/identities",
364            "/.agentmux/channels",
365            "/.agentmux/channels/stable",
366            "/.agentmux/channels/stable/data",
367            "/.agentmux/channels/stable/data/objects.db",
368            "/.agentmux/channels/local-main/config",
369            "/.agentmux/channels/stable/runtime",
370            "/.agentmux/dev/main/data",
371            "/.agentmux/dev/main/clone-1",
372            "/.agentmux/dev/main/clone-1/data",
373            "/.agentmux/dev/main/clone-1/agents",
374            "/.agentmux/dev/main/data/agents/aria",
375            "/.agentmux/dev/main/runtime/agents/aria",
376            "/.agentmux/dev/main/config/agents/aria",
377            "/.agentmux/agents",
378            "/.agentmux/channels/stable/agents",
379            "/.agentmux/something-else",
380        ] {
381            for spec in [format!("{h}{rel}:/x"), format!("{h}{rel}:/x:ro"), format!("{}:/x", format!("{h}{rel}").to_uppercase())] {
382                assert!(refused_at(home.path(), &spec), "{spec}");
383            }
384        }
385        assert!(refused_at(home.path(), &format!("{h}/.agentmux/channels/stable/agents/../data:/x")), "dots resolved");
386        // A home folder with no AgentMux root in it holds nothing to protect.
387        let bare = tempfile::tempdir().unwrap();
388        assert!(!refused_at(bare.path(), &format!("{}:/x", slashed(bare.path()))));
389        assert!(refused_at(bare.path(), &format!("{}/.agentmux/shared:/x", slashed(bare.path()))), "but a path inside the root is refused wherever it is");
390    }
391
392    #[test]
393    fn an_agents_own_workspace_and_ordinary_folders_are_left_alone() {
394        let home = tempfile::tempdir().unwrap();
395        let h = slashed(home.path());
396        for rel in [
397            "/.agentmux/agents/aria",
398            "/.agentmux/agents/aria/repo/src",
399            "/.agentmux/channels/stable/agents/aria",
400            "/.agentmux/dev/main/agents/aria/repo",
401            "/.agentmux/dev/main/clone-1/agents/aria",
402            "/.agentmux/dev/main/clone-1/agents/aria/repo/src",
403            "/projects/app",
404            "/.agentmux-notes",
405            "/.agentmuxer/x",
406        ] {
407            assert!(!refused_at(home.path(), &format!("{h}{rel}:/work")), "{rel}");
408        }
409        assert!(!refused_at(home.path(), "data:/d"), "a named volume");
410    }
411
412    #[test]
413    fn a_mount_spelled_across_windows_wsl_and_a_shell_is_the_same_mount() {
414        let home = PathBuf::from("C:\\Users\\Me");
415        // The folders are not on this machine, so only the paths inside the root are tested for.
416        for spec in [
417            "C:\\Users\\Me\\.agentmux:/x",
418            "c:/users/me/.agentmux/shared:/x",
419            "/mnt/c/users/me/.AgentMux/channels/stable/data:/x",
420            "/c/Users/Me/.agentmux:/x",
421        ] {
422            assert!(refused_at(&home, spec), "{spec}");
423        }
424        assert!(!refused_at(&home, "/mnt/c/Users/Me/.agentmux/agents/aria:/x"));
425        assert!(!refused_at(&home, "C:\\Users\\Me\\work:/x"));
426    }
427
428    #[test]
429    fn a_drive_path_has_each_spelling_it_takes_on_windows_wsl_and_a_shell() {
430        let forms = drive_forms("c:/users/me");
431        assert_eq!(forms, ["/c/users/me", "/mnt/c/users/me", "c:/users/me"]);
432        assert_eq!(drive_forms("/mnt/c"), ["/c", "/mnt/c", "c:"]);
433        assert_eq!(drive_forms("/home/me/.agentmux"), ["/home/me/.agentmux"], "a POSIX path is its own only form");
434        assert_eq!(drive_forms("/tmp/x"), ["/tmp/x"]);
435    }
436
437    #[cfg(windows)]
438    #[test]
439    fn a_home_folder_on_a_drive_is_refused_in_every_spelling_when_the_root_is_in_it() {
440        let home = tempfile::tempdir().unwrap();
441        std::fs::create_dir_all(home.path().join(".agentmux/shared")).unwrap();
442        let plain = slashed(home.path());
443        let lower = plain.to_lowercase();
444        let wsl = format!("/mnt/{}/{}", &lower[..1], lower[3..].trim_start_matches('/'));
445        for spec in [format!("{plain}:/x"), format!("{lower}:/x"), format!("{wsl}:/x"), format!("{}:/x", plain.replace('/', "\\"))] {
446            assert!(refused_at(home.path(), &spec), "{spec}");
447        }
448    }
449
450    #[cfg(unix)]
451    #[test]
452    fn a_link_from_a_workspace_to_the_data_folder_is_followed() {
453        let home = tempfile::tempdir().unwrap();
454        let data = home.path().join(".agentmux/channels/stable/data");
455        std::fs::create_dir_all(&data).unwrap();
456        let workspace = home.path().join(".agentmux/agents/aria");
457        std::fs::create_dir_all(&workspace).unwrap();
458        let link = workspace.join("innocent");
459        std::os::unix::fs::symlink(&data, &link).unwrap();
460        assert!(refused_at(home.path(), &format!("{}:/x", link.to_string_lossy())));
461        assert!(!refused_at(home.path(), &format!("{}:/x", workspace.to_string_lossy())));
462    }
463
464    #[test]
465    fn the_workspace_folder_is_held_to_the_data_rule_too() {
466        // A container agent whose workspace is a home folder that holds an AgentMux root, or the root, is refused; one in
467        // its own folder is not. A home folder of its own here, with a root in it, so nothing of this machine's is read.
468        let home = tempfile::tempdir().unwrap();
469        std::fs::create_dir_all(home.path().join(".agentmux/agents/aria")).unwrap();
470        let h = slashed(home.path());
471        let homes = [home.path().to_path_buf()];
472        let workspace = |path: &str| refused_mount_in(&[], Some(path), &homes, &[]);
473        assert_eq!(workspace(&h).as_deref(), Some(h.as_str()), "the home folder");
474        assert!(workspace(&format!("{h}/.agentmux")).is_some(), "the root");
475        assert!(workspace(&format!("{h}/.agentmux/shared")).is_some());
476        assert!(workspace(&format!("{h}/.agentmux/agents/aria")).is_none(), "an agent's own folder");
477        assert!(workspace("").is_none() && refused_mount_in(&[], None, &homes, &[]).is_none());
478    }
479
480    #[test]
481    fn a_leading_tilde_is_the_home_folder() {
482        let home = tempfile::tempdir().unwrap();
483        assert!(refused_in(&["~/.colima:/x".into()], &[home.path().to_path_buf()], &[]).is_some());
484        assert!(refused_in(&["~/projects:/x".into()], &[home.path().to_path_buf()], &[]).is_none());
485    }
486
487    #[test]
488    fn windows_data_folders_of_docker_are_refused() {
489        let data = tempfile::tempdir().unwrap();
490        std::fs::create_dir_all(data.path().join("docker")).unwrap();
491        let dir = data.path().to_string_lossy().to_string();
492        assert!(refused_in(&[format!("{dir}/Docker/x:/x")], &[], &[data.path().to_path_buf()]).is_some());
493        assert!(refused_in(&[format!("{dir}:/x")], &[], &[data.path().to_path_buf()]).is_some(), "the folder holding it");
494    }
495
496    #[test]
497    fn the_workspace_folder_is_held_to_the_same_rule() {
498        assert_eq!(refused_mount(&[], Some("/var/run/docker.sock")).as_deref(), Some("/var/run/docker.sock"));
499        assert_eq!(refused_mount(&[], Some("/var/run")).as_deref(), Some("/var/run"));
500        assert_eq!(refused_mount(&[], Some("//./pipe/docker_engine")).as_deref(), Some("//./pipe/docker_engine"));
501        assert_eq!(refused_mount(&["data:/d".into()], Some("/home/me/repo")), None);
502        assert_eq!(refused_mount(&[], Some("")), None);
503        assert_eq!(refused_mount(&[], None), None);
504    }
505
506    #[test]
507    fn a_definition_with_an_entry_a_container_may_not_have_is_refused_when_saved_and_stripped_when_it_comes_in() {
508        let json = r#"["data:/d","/var/run/docker.sock:/var/run/docker.sock","/home/me/repo:/work"]"#;
509        assert_eq!(refused_in_json(json).as_deref(), Some("/var/run/docker.sock"));
510        assert_eq!(refused_in_json(r#"["data:/d"]"#), None);
511        assert_eq!(refused_in_json("[]"), None);
512        assert_eq!(refused_in_json("not json"), None);
513        let kept: Vec<String> = serde_json::from_str(&without_refused(json)).unwrap();
514        assert_eq!(kept, ["data:/d", "/home/me/repo:/work"]);
515        let clean = r#"["data:/d"]"#;
516        assert_eq!(without_refused(clean), clean, "a list with nothing to drop is not rewritten");
517        assert_eq!(without_refused("[]"), "[]");
518    }
519
520    #[cfg(unix)]
521    #[test]
522    fn a_link_to_a_socket_is_followed() {
523        let dir = tempfile::tempdir().unwrap();
524        let real = dir.path().join("docker.sock");
525        std::fs::write(&real, b"").unwrap();
526        let link = dir.path().join("innocent");
527        std::os::unix::fs::symlink(&real, &link).unwrap();
528        assert!(refused(&format!("{}:/x", link.to_string_lossy())));
529    }
530}