Skip to main content

agentmux_srv_core/backend/
route_audience.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which of srv's routes a container agent may call: a route srv serves is for everyone unless an
5//! entry here says otherwise, and a path that is neither served nor named here is refused.
6//!
7//! The rule (operator, 2026-10-28): a sandbox agent can do everything a native agent can do except
8//! directly update and run files on the machine. [`Audience::Everyone`] is the normal answer, so
9//! it is not written down: declaring a route (srv's `server/route_table.rs`) is what makes it
10//! everyone's. [`EXCEPTIONS`] is the whole boundary: a `NativeOnly` entry names the host capability
11//! (`host_exec`, `host_write` or `host_read`) that is the reason and tells the caller what to do
12//! instead; an `AppOnly` entry is the app's own plumbing. `docs/specs/container-agent-runtime.md`
13//! has the table of what is refused and why.
14//!
15//! Who each route is for is pinned, one line per route, in srv's
16//! `server/tests/route_audience.snapshot.txt`: a new route adds a line there that says `everyone`
17//! unless an entry here names it, so a route cannot be added without its audience being read. A
18//! path under srv's route namespaces that is neither served nor named, such as a route registered
19//! some way the table does not know, is refused with a message that says so; the container
20//! listener logs the path. Matched on the raw path, exactly as the router matches it.
21
22use super::audience::{Audience, HostCap, RuntimeCaps};
23
24/// Run a command on the host, in any form.
25pub const HOST_COMMANDS: &str = "container agents can't run commands on the host. Run it in your own shell in the container, \
26                             or ask a native agent or your leader.";
27/// The app's own plumbing: approvals and state the user's windows report.
28pub const APP_ONLY: &str = "this route is for the AgentMux app itself, not for agents.";
29/// Driving the operating system.
30pub const DESKTOP: &str = "desktop control can launch programs on the host, so container agents can't use it. \
31                       Ask a native agent or your leader.";
32/// Generic gateways that reach everything else.
33pub const GATEWAY: &str = "this is a generic gateway to the host that container agents can't use. Use the specific tool for what you need.";
34/// A streamed Browser pane runs its page in the server's own network position.
35pub const STREAMED_BROWSER: &str = "a streamed page runs with the server's own network reach, which a container agent does not have. Use your own Browser tool.";
36/// Reading host files for the windows.
37pub const HOST_FILES: &str = "this reads files on the host for the app's windows. A container agent reads its own files in /workspace directly; \
38                          to show one in a pane, open it with the editor.";
39/// Replacing the app.
40pub const UPGRADE: &str = "upgrading AgentMux replaces the app on the host, so container agents can't. Ask a native agent or your leader.";
41/// Global Memory is composed into every native agent's context at launch.
42pub const GLOBAL_MEMORY: &str = "Global Memory is read by every native agent at launch, so a container agent can read it but not change it. \
43                             Ask a native agent or your leader to write it.";
44/// Srv does this for a container agent.
45pub const SRV_DOES_IT: &str = "srv does this for container agents itself.";
46/// Peer-to-peer routes between AgentMux instances.
47pub const INSTANCE_ONLY: &str = "this route is for other AgentMux instances, not for agents.";
48/// The local hook an event job offers to scripts on this computer.
49pub const LOCAL_SCRIPTS: &str = "this is the hook a job offers to scripts on this computer, with its own secret; an agent starts a job with Run now.";
50/// What a path with no entry is told.
51pub const UNCLASSIFIED: &str = "this route has not been classified for container agents yet. Ask your leader to have its audience set.";
52
53/// How an entry matches a path.
54#[derive(Debug, Clone, Copy)]
55pub enum Match {
56    Exact(&'static str),
57    Prefix(&'static str),
58    /// A route as the router takes it: `:name` stands for one segment, `*name` for the rest.
59    Route(&'static str),
60}
61
62impl Match {
63    pub fn matches(&self, path: &str) -> bool {
64        match *self {
65            Match::Exact(p) => path == p,
66            Match::Prefix(p) => path.starts_with(p),
67            Match::Route(pattern) => route_matches(pattern, path),
68        }
69    }
70}
71
72fn route_matches(pattern: &str, path: &str) -> bool {
73    let mut pat = pattern.split('/');
74    let mut got = path.split('/');
75    loop {
76        match (pat.next(), got.next()) {
77            (None, None) => return true,
78            (Some(p), Some(g)) if p.starts_with('*') => return !g.is_empty(),
79            (Some(p), Some(g)) if p.starts_with(':') => {
80                if g.is_empty() {
81                    return false;
82                }
83            }
84            (Some(p), Some(g)) if p == g => {}
85            _ => return false,
86        }
87    }
88}
89
90/// The routes that are not for everyone, first match wins. Every other route srv serves is for
91/// everyone.
92pub const EXCEPTIONS: &[(Match, Audience)] = &[
93    // Commands on the host
94    (Match::Prefix("/api/v1/shell/"), Audience::NativeOnly(HostCap::Exec, HOST_COMMANDS)),
95    (Match::Prefix("/api/v1/ptyshell/"), Audience::NativeOnly(HostCap::Exec, HOST_COMMANDS)),
96    (Match::Prefix("/api/v1/conn/"), Audience::NativeOnly(HostCap::Exec, HOST_COMMANDS)),
97    (Match::Exact("/api/v1/askpass"), Audience::NativeOnly(HostCap::Exec, HOST_COMMANDS)),
98    // Driving the OS
99    (Match::Prefix("/api/v1/agent/desktop/"), Audience::NativeOnly(HostCap::Exec, DESKTOP)),
100    // The app's own plumbing
101    (Match::Prefix("/api/v1/host/"), Audience::AppOnly(APP_ONLY)),
102    // The app's and the relay's own controls: no agent tool calls them and the handlers don't check who asks
103    (Match::Prefix("/agentmux/reactive/poller/"), Audience::AppOnly(APP_ONLY)),
104    (Match::Exact("/agentmux/reactive/unregister"), Audience::AppOnly(APP_ONLY)),
105    (Match::Exact("/agentmux/reactive/ensure-signing-key"), Audience::AppOnly(APP_ONLY)),
106    (Match::Exact("/agentmux/reactive/agents"), Audience::AppOnly(APP_ONLY)),
107    (Match::Exact("/agentmux/reactive/audit"), Audience::AppOnly(APP_ONLY)),
108    (Match::Exact("/agentmux/audit/own"), Audience::AppOnly(APP_ONLY)),
109    (Match::Exact("/agentmux/agent/holding"), Audience::AppOnly(APP_ONLY)),
110    (Match::Exact("/agentmux/diag/sagas"), Audience::AppOnly(APP_ONLY)),
111    (Match::Prefix("/api/messaging/"), Audience::AppOnly(APP_ONLY)),
112    (Match::Exact("/api/post-chat-message"), Audience::AppOnly(APP_ONLY)),
113    (Match::Prefix("/webhook/"), Audience::AppOnly(APP_ONLY)),
114    // The web UI's streamed Browser pane (404 unless the headless server switched it on): its page reaches whatever the
115    // server reaches, so it is the signed-in person's, never a container agent's
116    (Match::Exact("/agentmux/streamed-browser"), Audience::AppOnly(STREAMED_BROWSER)),
117    // Generic gateways
118    (Match::Exact("/agentmux/service"), Audience::NativeOnly(HostCap::Exec, GATEWAY)),
119    (Match::Exact("/ws"), Audience::NativeOnly(HostCap::Exec, GATEWAY)),
120    (Match::Exact("/agentmux/wps/publish"), Audience::NativeOnly(HostCap::Exec, GATEWAY)),
121    // Host files: the windows read them to draw panes; a container agent reads its own in /workspace
122    (Match::Exact("/agentmux/stream-local-file"), Audience::NativeOnly(HostCap::Read, HOST_FILES)),
123    (Match::Exact("/agentmux/file"), Audience::NativeOnly(HostCap::Read, HOST_FILES)),
124    (Match::Exact("/agentmux/file-icon"), Audience::NativeOnly(HostCap::Read, HOST_FILES)),
125    // What every native agent reads at launch
126    (Match::Exact("/api/v1/agent/globalmemory/write"), Audience::NativeOnly(HostCap::Write, GLOBAL_MEMORY)),
127    (Match::Exact("/api/v1/agent/globalmemory/remove"), Audience::NativeOnly(HostCap::Write, GLOBAL_MEMORY)),
128    (Match::Exact("/api/v1/agent/globalmemory/revert"), Audience::NativeOnly(HostCap::Write, GLOBAL_MEMORY)),
129    (Match::Exact("/api/v1/agent/globalmemory/reach"), Audience::NativeOnly(HostCap::Write, GLOBAL_MEMORY)),
130    // Replacing the app
131    (Match::Exact("/api/v1/agent/self/upgrade"), Audience::NativeOnly(HostCap::Write, UPGRADE)),
132    // Srv's own work for a container agent
133    (Match::Exact("/agentmux/agents/self/keys"), Audience::AppOnly("srv signs for a container agent, which holds no key to fetch.")),
134    (Match::Exact("/api/v1/agent/self/mcp-beat"), Audience::AppOnly("health beats belong to persistent controllers; a container's turns are per-exec.")),
135    (Match::Exact("/agentmux/reactive/register"), Audience::AppOnly(SRV_DOES_IT)),
136    // Between instances
137    (Match::Exact("/agentmux/jobs/stop-run"), Audience::AppOnly(INSTANCE_ONLY)),
138    (Match::Prefix("/agentmux/viewer/"), Audience::AppOnly(INSTANCE_ONLY)),
139    (Match::Prefix("/.well-known/"), Audience::AppOnly(INSTANCE_ONLY)),
140    // A job's local hook
141    (Match::Route("/agentmux/hook/:job"), Audience::AppOnly(LOCAL_SCRIPTS)),
142];
143
144/// Whether srv serves a route at a path. Srv answers it from its route table and hands it to whoever asks
145/// here, so nothing in this crate can ask without saying what is served.
146pub type Served = fn(&str) -> bool;
147
148/// The audience of `path`: what an entry of [`EXCEPTIONS`] says, else everyone when srv serves a
149/// route at `path`, else `None`.
150pub fn audience_of(path: &str, served: Served) -> Option<Audience> {
151    match EXCEPTIONS.iter().find(|(m, _)| m.matches(path)) {
152        Some((_, audience)) => Some(*audience),
153        None if served(path) => Some(Audience::Everyone),
154        None => None,
155    }
156}
157
158/// Where srv's own routes live. A path under one that is neither served nor named might be a route the
159/// table does not know, so it is refused.
160const ROUTE_NAMESPACES: [&str; 2] = ["/api/", "/agentmux/"];
161
162/// Why a container agent may not call `path`, or `None` when it may. A path with no audience is refused
163/// as [`UNCLASSIFIED`] when it is under srv's route namespaces. Any other path is what the router's
164/// fallback serves (the frontend's files, or a 404), as it always was.
165pub fn refusal(path: &str, served: Served) -> Option<&'static str> {
166    match audience_of(path, served) {
167        Some(audience) => audience.refusal(RuntimeCaps::CONTAINER),
168        None if ROUTE_NAMESPACES.iter().any(|ns| path.starts_with(ns)) => Some(UNCLASSIFIED),
169        None => None,
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    /// A route as a request would carry it: `:name` and `*name` filled in.
178    fn sample(route: &str) -> String {
179        route.split('/').map(|s| if s.starts_with(':') || s.starts_with('*') { "x" } else { s }).collect::<Vec<_>>().join("/")
180    }
181
182    /// Srv serves nothing: the answers of the entries alone.
183    fn nothing(_: &str) -> bool {
184        false
185    }
186
187    /// No entry that an earlier one already claims.
188    #[test]
189    fn no_entry_is_dead() {
190        for (i, (m, _)) in EXCEPTIONS.iter().enumerate() {
191            if let Match::Route(p) = m {
192                let s = sample(p);
193                let first = EXCEPTIONS.iter().position(|(e, _)| e.matches(&s)).unwrap();
194                assert_eq!(first, i, "{p} is claimed by an earlier entry ({:?})", EXCEPTIONS[first].0);
195            }
196        }
197    }
198
199    /// A route srv serves is for everyone, unless an entry names it: the entry wins.
200    #[test]
201    fn a_served_route_is_for_everyone_unless_an_entry_names_it() {
202        let served: Served = |path| ["/api/v1/vault", "/api/v1/shell/create", "/agentmux/hook/x"].contains(&path);
203        assert_eq!(audience_of("/api/v1/vault", served), Some(Audience::Everyone));
204        assert_eq!(refusal("/api/v1/vault", served), None);
205        assert_eq!(refusal("/api/v1/shell/create", served), Some(HOST_COMMANDS));
206        assert_eq!(refusal("/agentmux/hook/x", served), Some(LOCAL_SCRIPTS));
207        assert_eq!(audience_of("/api/v1/vault", nothing), None);
208    }
209
210    #[test]
211    fn a_route_nobody_classified_is_refused_with_a_message_that_says_so() {
212        assert_eq!(refusal("/api/v1/not-a-route-yet", nothing), Some(UNCLASSIFIED));
213        assert_eq!(refusal("/agentmux/not-a-route-yet", nothing), Some(UNCLASSIFIED));
214        assert!(UNCLASSIFIED.contains("Ask your leader"));
215    }
216
217    /// The frontend's files and unknown paths are not routes: the router serves or 404s them, as before.
218    #[test]
219    fn a_path_the_frontend_fallback_serves_is_not_refused() {
220        for path in ["/assets/index-abc.js", "/index.html", "/favicon.ico", "/nope"] {
221            assert_eq!(refusal(path, nothing), None, "{path}");
222        }
223    }
224
225    #[test]
226    fn a_param_matches_one_segment_and_a_rest_matches_one_or_more() {
227        assert!(route_matches("/agentmux/work/:id", "/agentmux/work/12"));
228        assert!(!route_matches("/agentmux/work/:id", "/agentmux/work/"));
229        assert!(!route_matches("/agentmux/work/:id", "/agentmux/work/12/accept"));
230        assert!(route_matches("/docsite/*path", "/docsite/a/b/c.html"));
231        assert!(!route_matches("/docsite/*path", "/docsite/"));
232        assert!(route_matches("/", "/"));
233        assert!(!route_matches("/", "/x"));
234    }
235
236    /// Every entry names the capability it needs, or says it is the app's, so the boundary reads in
237    /// one pass.
238    #[test]
239    fn the_boundary_in_one_table() {
240        let mut table = String::new();
241        for (m, a) in EXCEPTIONS {
242            table.push_str(&format!("{:<12} {:?}\n", a.cap_name(), m));
243        }
244        assert!(table.contains("host_exec") && table.contains("host_write") && table.contains("host_read"), "{table}");
245    }
246}