Skip to main content

agentmux_srv_core/backend/container/mounts/
credential_mode.rs

1//! Who owns, and who can read, the credentials inside a container agent.
2//!
3//! The bound account's `.credentials.json` is a single-file bind of a host file, so what a
4//! container sees of it is whatever the host presents: a Linux host shows its own owner and
5//! mode, Docker Desktop shows a synthesized root-owned `rwxrwxrwx`. The agent's `~/.claude`
6//! volume is created from the image. When a container starts (or has been restarted since it was
7//! last looked at) a root exec tightens what is the turn user's: `~/.claude` and its top-level
8//! files to the agent alone, and the credentials file to `600`. A credentials file that root owns is
9//! handed to the turn user first, unless the container runs in a user namespace (rootless Docker or
10//! Podman), where root is the host user. One owned by a real host user is left exactly as it is: through the
11//! bind a `chown` would change the host's file, and a `chmod 600` could lock the agent out of a file
12//! it can read today. It then reads the file back, and says in the log what it is.
13
14use 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
22/// The script. `$1` the config dir, `$2` the credentials file, `$3`:`$4` the turn user. Prints the
23/// credentials file's `uid:gid mode` last, or `none` when there is no file. Nothing is changed that
24/// the turn user does not own (or that root owned and was just handed over): taking a mode from
25/// someone else's file could lock the agent out of it.
26const 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/// What the credentials file ended up as, from the script's last line.
43#[derive(Debug, PartialEq, Eq)]
44pub(super) enum Outcome {
45    /// Owned by the turn user, `600`.
46    Private,
47    /// There is no credentials file (no account bound, not signed in yet).
48    NoFile,
49    /// It is this `uid:gid mode` and not the agent's: a real host user's file, or a layer that ignores the change.
50    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
62/// The container's `StartedAt` when its credentials were last looked at, so a restart or a
63/// recreate is looked at again and nothing else is.
64fn 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    /// Everything a new container's home needs before its first turn.
71    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    /// Once per start of the container: a running one that was not looked at, a restarted one, a new one.
77    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    /// Best-effort: a failure is logged and the container carries on.
88    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        /// A `.claude` dir as an image-made volume leaves it (755, files 644) with a world-writable
172        /// credentials file owned by whoever runs the test, the script run as that user.
173        #[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, &note] {
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            // Files that belong to somebody else (here: the turn user is another uid) are left exactly
204            // as they are, so a `600` can't lock the agent out of a file it reads today. (Run as root,
205            // the fixture is root's, which the script hands over by design, so this part needs a user.)
206            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(&note), 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            // A symlink in the credentials' place is not followed, and there being no file is fine.
222            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}