Skip to main content

agentmux_srv/server/
dispatch_guard.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which websocket connection may call which command, decided at dispatch.
5//!
6//! The instance key opens `/ws`, and a native agent has it in its environment, so holding it proves nothing
7//! about who is calling. A command is the AgentMux window's alone unless `backend::rpc::action_access` lists it:
8//!
9//! - a connection the host proved is the window (`RpcContext::operator_proven_now`) calls anything;
10//! - any connection calls an open command (`OPEN`: reads the window shows anyone who can open it, and the calls
11//!   the handler itself decides per caller);
12//! - a connection registered as an agent reaches only the open commands and the ones whose handler checks the
13//!   pane (`OWN_PANE`); everything else is refused, whatever the agent's own rules say;
14//! - any other connection is refused with the words the app matches to prove the connection again.
15//!
16//! A headless srv with no registered external host and no sign-in of its own has nothing that could vouch for a
17//! connection, so it admits an unproven one and logs once per connection (the same fallback as the composer's
18//! `agentinput`, `agent_handlers::composer_origin`); with either present the guard is strict.
19//!
20//! A dev build runs the guard like any other. `AGENTMUX_DEV_OPEN_RPC=1`, given when a dev instance is started, turns
21//! it off for the harnesses in `tools/tests` that drive an unproven connection; any other mode ignores it.
22
23use std::sync::atomic::{AtomicBool, Ordering};
24use std::sync::{Arc, OnceLock};
25
26use crate::backend::rpc::action_access;
27use crate::backend::rpc::engine::{DispatchGuard, WshRpcEngine};
28use crate::backend::rpc_types::RpcContext;
29
30/// The environment variable that turns the guard off, in a dev build only.
31pub(crate) const DEV_SWITCH: &str = "AGENTMUX_DEV_OPEN_RPC";
32
33/// What the decision reads besides the call: how this srv was started.
34#[derive(Debug, Clone, Copy, Default)]
35pub(crate) struct Mode {
36    /// The dev switch was given and this is a dev build.
37    pub dev_open: bool,
38    /// A headless srv (no CEF host).
39    pub headless: bool,
40    /// A registered external host that attests connections.
41    pub external_host: bool,
42    /// A browser can sign in to this srv, or one has.
43    pub local_sign_in: bool,
44}
45
46#[derive(Debug, PartialEq, Eq)]
47pub(crate) enum Verdict {
48    Allow,
49    /// Allowed because nothing could prove the caller (headless, no host, no sign-in): the caller logs it.
50    AllowUnproven,
51    Refuse(String),
52}
53
54pub(crate) fn decide(command: &str, data: &serde_json::Value, ctx: &RpcContext, mode: Mode) -> Verdict {
55    if mode.dev_open || action_access::is_open_for(command, data) {
56        return Verdict::Allow;
57    }
58    if !ctx.agent_id.is_empty() {
59        return if action_access::is_own_pane(command) {
60            Verdict::Allow
61        } else {
62            Verdict::Refuse(format!("FORBIDDEN: {command} is the AgentMux window's call; an agent reaches AgentMux with its MuxAPI tools"))
63        };
64    }
65    if ctx.operator_proven_now() {
66        return Verdict::Allow;
67    }
68    if mode.headless && !mode.external_host && !mode.local_sign_in && !ctx.operator_proven {
69        return Verdict::AllowUnproven;
70    }
71    match ctx.operator_only(&format!("{command} is the AgentMux window's call")) {
72        Err(refusal) => Verdict::Refuse(refusal),
73        Ok(()) => Verdict::Allow,
74    }
75}
76
77/// How this srv was started, read once.
78fn mode() -> Mode {
79    // The srv's own tests drive commands over sockets that are not the window (the router's tests, the live ones); the
80    // guard is tested with explicit modes, through `decide` and `guard_with`.
81    #[cfg(test)]
82    return Mode { dev_open: true, ..Mode::default() };
83    #[cfg(not(test))]
84    live_mode()
85}
86
87#[cfg(not(test))]
88fn live_mode() -> Mode {
89    static DEV_OPEN: OnceLock<bool> = OnceLock::new();
90    let dev_open = *DEV_OPEN.get_or_init(|| {
91        dev_open_from(agentmux_common::RuntimeMode::from_env(), std::env::var(DEV_SWITCH).ok().as_deref())
92    });
93    Mode {
94        dev_open,
95        headless: crate::headless::active(),
96        external_host: super::external_host::host().is_some(),
97        local_sign_in: super::local_session_routes::sign_in_exists(),
98    }
99}
100
101/// The switch counts only in a dev build.
102pub(crate) fn dev_open_from(runtime: Option<agentmux_common::RuntimeMode>, var: Option<&str>) -> bool {
103    matches!(runtime, Some(agentmux_common::RuntimeMode::Dev { .. })) && matches!(var, Some("1") | Some("true"))
104}
105
106/// Guard `engine`'s connection. The unproven-admission is logged once for this connection.
107pub(crate) fn install(engine: &Arc<WshRpcEngine>) {
108    engine.set_dispatch_guard(guard_with(mode));
109}
110
111fn guard_with(mode: impl Fn() -> Mode + Send + Sync + 'static) -> DispatchGuard {
112    let logged = AtomicBool::new(false);
113    Arc::new(move |command: &str, data: &serde_json::Value, ctx: &RpcContext| {
114        // The window's own calls, keystrokes among them, take no further look.
115        if ctx.agent_id.is_empty() && ctx.operator_proven_now() {
116            return Ok(());
117        }
118        match decide(command, data, ctx, mode()) {
119            Verdict::Allow => Ok(()),
120            Verdict::AllowUnproven => {
121                if !logged.swap(true, Ordering::Relaxed) {
122                    tracing::warn!(client_type = %ctx.client_type, "a connection no host proved calls the window's commands, in a headless srv with no host to prove it");
123                }
124                Ok(())
125            }
126            Verdict::Refuse(refusal) => Err(refusal),
127        }
128    })
129}
130
131#[cfg(test)]
132#[path = "tests/dispatch_guard_tests.rs"]
133mod dispatch_guard_tests;