Skip to main content

agentmux_srv/server/
agent_config_guard.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Who `writeagentconfig` may write for. The AgentMux window, proven by its host, writes any
5//! agent's launch files; a connection registered as an agent (`bus:register`) writes only its
6//! own, into its own workspace; any other connection writes nothing. The file lands where the
7//! caller says and the `.mcp.json` it carries signs as the named agent, so without this an
8//! agent could drop files into another agent's workspace or into any folder it can name. That
9//! includes an agent that never registers: every agent holds the instance auth key, which opens
10//! a connection that is neither the window nor an agent. A leader's edit of another agent's
11//! definition goes through the definition API (which records who made it), not through this
12//! raw write.
13
14use std::path::Path;
15
16use crate::backend::rpc::actor::{actor_of, Actor};
17use crate::backend::rpc_types::RpcContext;
18use crate::backend::storage::store::Store;
19
20/// `Ok` if `ctx` may write `cmd_agent_id`'s launch files into `working_dir`: the proven window
21/// anywhere, an agent only its own workspace, an unproven connection nowhere.
22pub(crate) fn check_agent_config_write(
23    store: &Store,
24    ctx: &RpcContext,
25    cmd_agent_id: Option<&str>,
26    working_dir: &Path,
27    auto_allocate: bool,
28) -> Result<(), String> {
29    match actor_of(ctx) {
30        Actor::Operator | Actor::Person(_) => return Ok(()),
31        Actor::Unproven | Actor::Srv => {
32            return Err("FORBIDDEN: only the AgentMux window, or an agent for its own workspace, writes agent config (this connection is neither)".to_string())
33        }
34        Actor::Agent(_) => {}
35    }
36    let own_only = "FORBIDDEN: an agent writes only its own config, into its own workspace";
37    let named = cmd_agent_id.map(str::trim).filter(|id| !id.is_empty()).ok_or(own_only)?;
38    crate::server::app_api::check_s1(store, ctx, named).map_err(|_| own_only.to_string())?;
39    // `auto_allocate` makes a sibling folder `<dir>-N`, which is outside the workspace.
40    if auto_allocate {
41        return Err(own_only.to_string());
42    }
43    let id = crate::backend::agent_resolve::resolve_agent_id(store, &ctx.agent_id).map_err(|_| own_only.to_string())?;
44    let workspace = store
45        .agent_def_get(&id)
46        .ok()
47        .flatten()
48        .map(|def| def.working_directory)
49        .filter(|dir| !dir.is_empty())
50        .ok_or("FORBIDDEN: this agent has no workspace on record to write into")?;
51    let inside = match (std::fs::canonicalize(working_dir), std::fs::canonicalize(expand(&workspace))) {
52        (Ok(dir), Ok(ws)) => dir.starts_with(ws),
53        _ => false,
54    };
55    if inside { Ok(()) } else { Err(own_only.to_string()) }
56}
57
58fn expand(path: &str) -> std::path::PathBuf {
59    crate::backend::base::expand_home_dir_safe(path)
60}
61
62#[cfg(test)]
63mod tests {
64    use super::check_agent_config_write;
65    use crate::backend::rpc_types::RpcContext;
66    use crate::backend::storage::agents::test_agent_def;
67
68    fn agent(slug: &str) -> RpcContext {
69        RpcContext { agent_id: slug.into(), ..Default::default() }
70    }
71
72    fn store_with(slug: &str, workspace: &std::path::Path) -> crate::backend::storage::store::Store {
73        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
74        let mut def = test_agent_def(slug, slug, "claude", "host", 1, "");
75        def.working_directory = workspace.to_string_lossy().to_string();
76        store.agent_def_insert(&mut def).unwrap();
77        store
78    }
79
80    #[test]
81    fn an_agent_writes_only_its_own_workspace() {
82        let tmp = tempfile::tempdir().unwrap();
83        let (mine, other) = (tmp.path().join("mine"), tmp.path().join("other"));
84        std::fs::create_dir_all(mine.join("sub")).unwrap();
85        std::fs::create_dir_all(&other).unwrap();
86        let store = store_with("mine", &mine);
87
88        let ok = |dir: &std::path::Path, id: &str, alloc| check_agent_config_write(&store, &agent("mine"), Some(id), dir, alloc);
89        assert!(ok(&mine, "mine", false).is_ok());
90        assert!(ok(&mine.join("sub"), "mine", false).is_ok());
91        assert!(ok(&other, "mine", false).is_err(), "another agent's workspace");
92        assert!(ok(&mine.join("..").join("other"), "mine", false).is_err(), "out through ..");
93        assert!(ok(&mine, "victim", false).is_err(), "files that sign as another agent");
94        assert!(ok(&mine, "", false).is_err(), "no agent named");
95        assert!(ok(&mine, "mine", true).is_err(), "auto_allocate makes a sibling folder");
96        assert!(ok(&mine.join("not-yet"), "mine", false).is_err(), "a folder that doesn't exist");
97    }
98
99    #[test]
100    fn the_proven_window_is_left_alone_and_a_connection_that_is_neither_it_nor_an_agent_writes_nothing() {
101        let tmp = tempfile::tempdir().unwrap();
102        let store = store_with("mine", tmp.path());
103        assert!(check_agent_config_write(&store, &RpcContext::operator_for_tests(), Some("victim"), tmp.path(), true).is_ok());
104        let e = check_agent_config_write(&store, &RpcContext::default(), Some("mine"), tmp.path(), false).unwrap_err();
105        assert!(e.starts_with("FORBIDDEN"), "{e}");
106    }
107}