agentmux_srv_core/backend/container/mounts/
credential_mode.rs1use std::collections::HashMap;
15use std::sync::{Mutex, OnceLock};
16
17use bollard::exec::{CreateExecOptions, StartExecOptions, StartExecResults};
18use futures_util::StreamExt as _;
19
20use super::{ContainerManager, ContainerMountSpec, CLAUDE_CREDENTIALS_FILE, CONTAINER_CLAUDE_DIR};
21
22const SCRIPT: &str = r#"d="$1"; f="$2"
27if [ -d "$d" ] && [ "$(stat -c %u "$d")" = "$3" ]; then
28 chmod 700 "$d"
29 find "$d" -maxdepth 1 -type f ! -path "$f" -user "$3" -exec chmod go-rwx {} +
30fi
31if [ -f "$f" ] && [ ! -L "$f" ]; then
32 # Root-owned is Docker Desktop's synthesized owner only when root here is root there: under a user
33 # namespace (rootless Docker or Podman, userns-remap) root is the host user, and the file is theirs.
34 read -r inside outside _ </proc/self/uid_map
35 [ "$(stat -c %u "$f")" = 0 ] && [ "$inside $outside" = "0 0" ] && chown "$3:$4" "$f"
36 [ "$(stat -c %u "$f")" = "$3" ] && chmod 600 "$f"
37 stat -c '%u:%g %a' "$f"
38else
39 echo none
40fi"#;
41
42#[derive(Debug, PartialEq, Eq)]
44pub(super) enum Outcome {
45 Private,
47 NoFile,
49 Presented(String),
51}
52
53pub(super) fn outcome(output: &str, uid: u64, gid: u64) -> Option<Outcome> {
54 let last = output.lines().map(str::trim).rfind(|l| !l.is_empty())?;
55 if last == "none" {
56 return Some(Outcome::NoFile);
57 }
58 let (owner, mode) = last.split_once(' ')?;
59 Some(if owner == format!("{uid}:{gid}") && mode == "600" { Outcome::Private } else { Outcome::Presented(last.to_string()) })
60}
61
62fn secured() -> &'static Mutex<HashMap<String, String>> {
65 static SECURED: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
66 SECURED.get_or_init(Default::default)
67}
68
69impl ContainerManager {
70 pub(in crate::backend::container) async fn prepare_home(&self, container_name: &str, spec: &ContainerMountSpec) {
72 self.own_memory_parents(container_name, spec).await;
73 self.secure_credentials_once(container_name).await;
74 }
75
76 pub(in crate::backend::container) async fn secure_credentials_once(&self, container_name: &str) {
78 let started = self.inner.docker.inspect_container(container_name, None).await.ok().and_then(|c| c.state?.started_at).unwrap_or_default();
79 if !started.is_empty() && secured().lock().unwrap().get(container_name) == Some(&started) {
80 return;
81 }
82 if self.secure_credentials(container_name).await && !started.is_empty() {
83 secured().lock().unwrap().insert(container_name.to_string(), started);
84 }
85 }
86
87 async fn secure_credentials(&self, container_name: &str) -> bool {
89 let Some((uid, gid)) = self.exec_identity(container_name).await else {
90 tracing::warn!(container = container_name, "container agent: can't tell which user runs turns; the credentials stay as the host presents them");
91 return false;
92 };
93 let file = format!("{CONTAINER_CLAUDE_DIR}/{CLAUDE_CREDENTIALS_FILE}");
94 let (uid_arg, gid_arg) = (uid.to_string(), gid.to_string());
95 let argv = ["sh", "-c", SCRIPT, "sh", CONTAINER_CLAUDE_DIR, file.as_str(), uid_arg.as_str(), gid_arg.as_str()];
96 let ran = async {
97 let exec = self
98 .inner
99 .docker
100 .create_exec(
101 container_name,
102 CreateExecOptions { user: Some("root"), cmd: Some(argv.to_vec()), attach_stdout: Some(true), attach_stderr: Some(true), ..Default::default() },
103 )
104 .await?;
105 let mut out = String::new();
106 if let StartExecResults::Attached { mut output, .. } =
107 self.inner.docker.start_exec(&exec.id, Some(StartExecOptions { detach: false, ..Default::default() })).await?
108 {
109 while let Some(Ok(chunk)) = output.next().await {
110 out.push_str(&String::from_utf8_lossy(&chunk.into_bytes()));
111 }
112 }
113 Ok::<_, crate::backend::container::ContainerError>((self.inspect_exec(&exec.id).await?, out))
114 }
115 .await;
116 match ran {
117 Ok((Some(0), out)) => {
118 match outcome(&out, uid, gid) {
119 Some(Outcome::Private) => tracing::info!(container = container_name, "container agent: credentials are the agent's alone (600)"),
120 Some(Outcome::NoFile) => {}
121 Some(Outcome::Presented(seen)) => tracing::warn!(
122 container = container_name,
123 seen,
124 "container agent: the credentials file is {seen} (uid:gid mode) as the container sees it, not the agent's own, so it was left as it is; \
125 if the agent can't sign in, the host file's owner is the thing to check"
126 ),
127 None => tracing::warn!(container = container_name, "container agent: couldn't read back the credentials file's owner"),
128 }
129 true
130 }
131 Ok((code, _)) => {
132 tracing::warn!(container = container_name, ?code, "container agent: tightening the credentials failed");
133 false
134 }
135 Err(e) => {
136 tracing::warn!(container = container_name, error = %e, "container agent: couldn't tighten the credentials");
137 false
138 }
139 }
140 }
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146
147 #[test]
148 fn the_scripts_last_line_says_what_the_host_presents() {
149 assert_eq!(outcome("1000:1000 600\n", 1000, 1000), Some(Outcome::Private));
150 assert_eq!(outcome("none\n", 1000, 1000), Some(Outcome::NoFile));
151 assert_eq!(outcome("0:0 777\n", 1000, 1000), Some(Outcome::Presented("0:0 777".into())));
152 assert_eq!(outcome("1000:1000 666", 1000, 1000), Some(Outcome::Presented("1000:1000 666".into())));
153 assert_eq!(outcome("chmod: nope\n1001:1001 600\n", 1000, 1000), Some(Outcome::Presented("1001:1001 600".into())));
154 assert_eq!(outcome("", 1000, 1000), None);
155 assert_eq!(outcome("garbage", 1000, 1000), None);
156 }
157
158 #[cfg(target_os = "linux")]
159 pub mod on_linux {
160 use super::super::SCRIPT;
161 use std::os::unix::fs::{MetadataExt, PermissionsExt};
162 use std::process::Command;
163
164 fn mode(p: &std::path::Path) -> u32 {
165 std::fs::metadata(p).unwrap().permissions().mode() & 0o777
166 }
167 fn set(p: &std::path::Path, m: u32) {
168 std::fs::set_permissions(p, std::fs::Permissions::from_mode(m)).unwrap();
169 }
170
171 #[test]
174 fn the_script_makes_the_config_dir_and_credentials_the_agents_alone() {
175 let root = std::env::temp_dir().join(format!("agentmux-cred-mode-{}", std::process::id()));
176 let dir = root.join(".claude");
177 let memory = dir.join("projects/-workspace/memory");
178 std::fs::create_dir_all(&memory).unwrap();
179 let creds = dir.join(".credentials.json");
180 let settings = dir.join("settings.json");
181 let note = memory.join("a.md");
182 for f in [&creds, &settings, ¬e] {
183 std::fs::write(f, "x").unwrap();
184 set(f, 0o666);
185 }
186 set(&dir, 0o755);
187 let me = std::fs::metadata(&dir).unwrap();
188 let run_as = |uid: u32| {
189 let out = Command::new("sh")
190 .args(["-c", SCRIPT, "sh"])
191 .arg(&dir)
192 .arg(&creds)
193 .arg(uid.to_string())
194 .arg(me.gid().to_string())
195 .output()
196 .unwrap();
197 assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
198 String::from_utf8_lossy(&out.stdout).into_owned()
199 };
200
201 let run = || run_as(me.uid());
202
203 if me.uid() != 0 {
207 let out = run_as(me.uid() + 1);
208 assert_eq!(super::super::outcome(&out, me.uid() as u64 + 1, me.gid() as u64), Some(super::super::Outcome::Presented(format!("{}:{} 666", me.uid(), me.gid()))), "{out}");
209 assert_eq!((mode(&dir), mode(&creds), mode(&settings)), (0o755, 0o666, 0o666));
210 }
211
212 let out = run();
213 assert_eq!(super::super::outcome(&out, me.uid() as u64, me.gid() as u64), Some(super::super::Outcome::Private), "{out}");
214 assert_eq!(mode(&dir), 0o700);
215 assert_eq!(mode(&creds), 0o600);
216 assert_eq!(mode(&settings), 0o600, "a top-level file beside it");
217 assert_eq!(mode(¬e), 0o666, "the memory folder is bound from the host and is not touched");
218 run();
219 assert_eq!(mode(&creds), 0o600, "running it again changes nothing");
220
221 std::fs::remove_file(&creds).unwrap();
223 assert_eq!(super::super::outcome(&run(), 0, 0), Some(super::super::Outcome::NoFile));
224 std::os::unix::fs::symlink(&settings, &creds).unwrap();
225 assert_eq!(super::super::outcome(&run(), 0, 0), Some(super::super::Outcome::NoFile));
226 let _ = std::fs::remove_dir_all(&root);
227 }
228 }
229}