Skip to main content

agentmux_srv_core/backend/container/
gateway_fwd.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The gateway forwarder: how a container agent's model-gateway request is tied to its own container where srv cannot see
5//! which container it comes from (Docker Desktop: every container arrives from one address).
6//!
7//! A helper container, [`container_name`], runs `agentmux-mcp gateway-fwd` on the agents network. Container agents are
8//! pointed at it (`key_route`); it sees each one's own address, puts it in a stamp
9//! ([`agentmux_common::gateway_stamp`]) on the request, and passes the request to srv. srv accepts the stamp only with the
10//! proof made from this launch's secret ([`verify_stamp`]), so the address in it is the one the forwarder saw.
11//!
12//! The helper gets no agent token, no Vault access, no mount and no capability. The secret reaches it only in its
13//! environment at creation, is made for each srv launch, and is never logged or written to a file. It is not restarted, it
14//! is removed when it stops, and srv removes it when srv ends ([`remove`]); one left by a srv that did not end cleanly has
15//! another launch's secret and is replaced at the next turn.
16
17use std::collections::HashMap;
18use std::net::IpAddr;
19use std::sync::OnceLock;
20use std::time::Duration;
21
22use agentmux_common::gateway_stamp::{self, Refusal};
23use axum::http::HeaderMap;
24use bollard::container::{Config, CreateContainerOptions, RemoveContainerOptions, StartContainerOptions};
25use bollard::models::{ContainerInspectResponse, HostConfig, RestartPolicy, RestartPolicyNameEnum};
26
27use super::{ContainerManager, AGENTMUX_DOCKER_NETWORK};
28
29/// What every forwarder's name starts with.
30pub const CONTAINER_PREFIX: &str = "agentmux-gateway-fwd";
31/// The label that names the helper as AgentMux's, and what the container list says it is.
32pub const HELPER_LABEL: &str = "ai.agentmux.helper";
33pub const HELPER_TEXT: &str = "AgentMux gateway forwarder";
34/// The port it listens on, on the agents network.
35pub const PORT: u16 = 4799;
36const ENV_SECRET: &str = "AGENTMUX_GWFWD_SECRET";
37const ENV_UPSTREAM: &str = "AGENTMUX_GWFWD_UPSTREAM";
38const ENV_PORT: &str = "AGENTMUX_GWFWD_PORT";
39
40/// Said when the forwarder cannot be had: nothing falls back to srv's own address.
41const NOT_RUNNING: &str = "AgentMux could not start its gateway forwarder, which ties this agent's model access to its container on this machine. Run the agent on this machine instead of in a container, or move it to a plan account, and tell the AgentMux team if this keeps happening.";
42
43/// This launch's secret, made on first use.
44fn secret() -> &'static str {
45    static SECRET: OnceLock<String> = OnceLock::new();
46    SECRET.get_or_init(|| format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple()))
47}
48
49/// This srv instance's forwarder's name: the prefix and a short mark of its data directory. Two AgentMux instances on one
50/// machine (another channel, a dev build) share the Docker daemon and the agents network, and each has its own secret, so each
51/// has its own forwarder and neither replaces or removes the other's. The same instance makes the same name at every launch.
52/// Its address on the agents network is found by this name (Docker's own DNS on that network).
53pub fn container_name() -> &'static str {
54    static NAME: OnceLock<String> = OnceLock::new();
55    NAME.get_or_init(|| {
56        use sha2::{Digest, Sha256};
57        let seed = agentmux_common::data_paths::agentmux_root().ok().map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| secret().to_string());
58        let d = Sha256::digest(seed.as_bytes());
59        format!("{CONTAINER_PREFIX}-{:02x}{:02x}{:02x}{:02x}", d[0], d[1], d[2], d[3])
60    })
61}
62
63/// Whether a container name is a gateway forwarder's, any instance's.
64pub fn is_forwarder_name(name: &str) -> bool {
65    name == CONTAINER_PREFIX || name.strip_prefix(CONTAINER_PREFIX).is_some_and(|rest| rest.starts_with('-'))
66}
67
68/// The forwarder's base URL, as a container on the agents network reaches it.
69pub fn url() -> String {
70    format!("http://{}:{PORT}", container_name())
71}
72
73/// The container a request was stamped for, when its stamp is good for this request now.
74pub fn verify_stamp(headers: &HeaderMap, method: &str, target: &str) -> Result<IpAddr, Refusal> {
75    verify_stamp_at(headers, method, target, agentmux_common::time::now_secs_u64())
76}
77
78fn verify_stamp_at(headers: &HeaderMap, method: &str, target: &str, now: u64) -> Result<IpAddr, Refusal> {
79    let get = |name: &str| headers.get(name).and_then(|v| v.to_str().ok());
80    gateway_stamp::verify(secret().as_bytes(), get(gateway_stamp::HEADER_PEER), get(gateway_stamp::HEADER_TS), get(gateway_stamp::HEADER_PROOF), method, target, now)
81}
82
83/// The three headers the forwarder would put on a request from `peer` to `target`, made now with this launch's secret. Only so a test of
84/// srv's side can send one: the real ones are made in the helper container, which has its own copy of the secret.
85#[doc(hidden)]
86pub fn stamp_headers(peer: IpAddr, method: &str, target: &str) -> Vec<(&'static str, String)> {
87    stamp_headers_at(peer, method, target, agentmux_common::time::now_secs_u64())
88}
89
90/// [`stamp_headers`] for a forwarder whose clock reads `ts`.
91#[doc(hidden)]
92pub fn stamp_headers_at(peer: IpAddr, method: &str, target: &str, ts: u64) -> Vec<(&'static str, String)> {
93    vec![
94        (gateway_stamp::HEADER_PEER, peer.to_string()),
95        (gateway_stamp::HEADER_TS, ts.to_string()),
96        (gateway_stamp::HEADER_PROOF, gateway_stamp::proof(secret().as_bytes(), peer, ts, method, target)),
97    ]
98}
99
100/// What the helper is made with. No mount, no capability, no restart, nothing but the agents network and the name of the host.
101pub(super) fn forwarder_config(image: &str, upstream: &str, secret: &str) -> Config<String> {
102    Config {
103        image: Some(image.to_string()),
104        cmd: Some(vec!["agentmux-mcp".to_string(), "gateway-fwd".to_string()]),
105        env: Some(vec![format!("{ENV_SECRET}={secret}"), format!("{ENV_UPSTREAM}={upstream}"), format!("{ENV_PORT}={PORT}")]),
106        labels: Some(HashMap::from([(HELPER_LABEL.to_string(), HELPER_TEXT.to_string())])),
107        host_config: Some(HostConfig {
108            network_mode: Some(AGENTMUX_DOCKER_NETWORK.to_string()),
109            extra_hosts: Some(vec!["host.docker.internal:host-gateway".to_string()]),
110            cap_drop: Some(vec!["ALL".to_string()]),
111            security_opt: Some(vec!["no-new-privileges".to_string()]),
112            readonly_rootfs: Some(true),
113            restart_policy: Some(RestartPolicy { name: Some(RestartPolicyNameEnum::NO), maximum_retry_count: None }),
114            auto_remove: Some(true),
115            pids_limit: Some(128),
116            memory: Some(128 * 1024 * 1024),
117            ..Default::default()
118        }),
119        ..Default::default()
120    }
121}
122
123/// Whether an existing container is this launch's forwarder for this image and this srv address, and is running.
124fn is_current(details: &ContainerInspectResponse, image: &str, upstream: &str) -> bool {
125    let running = details.state.as_ref().and_then(|s| s.running).unwrap_or(false);
126    let config = details.config.as_ref();
127    let env = config.and_then(|c| c.env.as_deref()).unwrap_or_default();
128    let has = |entry: String| env.iter().any(|e| *e == entry);
129    running && config.and_then(|c| c.image.as_deref()) == Some(image) && has(format!("{ENV_SECRET}={}", secret())) && has(format!("{ENV_UPSTREAM}={upstream}"))
130}
131
132static LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
133
134/// Makes sure this launch's forwarder is running for an agent container's image and returns its base URL, or says why not.
135/// `env` is the turn's environment, whose `AGENTMUX_LOCAL_URL` is where srv is reached from a container.
136pub(super) async fn ensure(cm: &ContainerManager, agent_container: &str, env: &[(String, String)]) -> Result<String, String> {
137    let upstream = env.iter().find(|(k, _)| k == "AGENTMUX_LOCAL_URL").map(|(_, v)| v.trim_end_matches('/').to_string()).filter(|v| !v.is_empty()).ok_or_else(|| NOT_RUNNING.to_string())?;
138    let image = cm.inner.docker.inspect_container(agent_container, None).await.ok().and_then(|d| d.config).and_then(|c| c.image).ok_or_else(|| NOT_RUNNING.to_string())?;
139    // One at a time, so two turns starting together make one forwarder.
140    let _one = LOCK.lock().await;
141    if let Ok(existing) = cm.inner.docker.inspect_container(container_name(), None).await {
142        if is_current(&existing, &image, &upstream) {
143            return Ok(url());
144        }
145        // Another launch's, another image, or not running.
146        let _ = cm.inner.docker.remove_container(container_name(), Some(RemoveContainerOptions { force: true, ..Default::default() })).await;
147    }
148    if !cm.ensure_network_exists().await {
149        return Err(NOT_RUNNING.to_string());
150    }
151    let created = cm.inner.docker.create_container(Some(CreateContainerOptions { name: container_name(), platform: None }), forwarder_config(&image, &upstream, secret())).await;
152    let started = match created {
153        Ok(c) if !c.id.is_empty() => cm.inner.docker.start_container(&c.id, None::<StartContainerOptions<String>>).await.is_ok(),
154        _ => false,
155    };
156    if !started || !stays_up(cm).await {
157        tracing::warn!(image = %image, "gateway forwarder: could not start; a container agent's model access is refused until it can");
158        return Err(NOT_RUNNING.to_string());
159    }
160    tracing::info!(container = container_name(), "gateway forwarder: started on the agents network");
161    Ok(url())
162}
163
164/// Whether the forwarder is still there after a moment: one that cannot run (an image from before it existed) exits at once,
165/// and is removed, as it has `auto_remove`.
166async fn stays_up(cm: &ContainerManager) -> bool {
167    for _ in 0..2 {
168        tokio::time::sleep(Duration::from_millis(700)).await;
169        let running = cm.inner.docker.inspect_container(container_name(), None).await.ok().and_then(|d| d.state).and_then(|s| s.running).unwrap_or(false);
170        if !running {
171            return false;
172        }
173    }
174    true
175}
176
177/// Removes the forwarder, if there is one: when srv ends, and before a launch's own is made. Best effort.
178pub async fn remove(cm: &ContainerManager) {
179    let _one = LOCK.lock().await;
180    if cm.inner.docker.remove_container(container_name(), Some(RemoveContainerOptions { force: true, ..Default::default() })).await.is_ok() {
181        tracing::info!(container = container_name(), "gateway forwarder: removed");
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use agentmux_common::gateway_stamp::{proof, HEADER_PEER, HEADER_PROOF, HEADER_TS};
189    use bollard::models::{ContainerConfig, ContainerState};
190
191    const TARGET: &str = "/api/v1/model/anthropic/v1/messages";
192
193    fn peer() -> IpAddr {
194        "172_30_0_9".replace('_', ".").parse().unwrap()
195    }
196
197    fn stamped(secret: &str, ts: u64, method: &str, target: &str) -> HeaderMap {
198        let mut h = HeaderMap::new();
199        h.insert(HEADER_PEER, peer().to_string().parse().unwrap());
200        h.insert(HEADER_TS, ts.to_string().parse().unwrap());
201        h.insert(HEADER_PROOF, proof(secret.as_bytes(), peer(), ts, method, target).parse().unwrap());
202        h
203    }
204
205    #[test]
206    fn the_forwarder_is_made_with_nothing_to_spare() {
207        let config = forwarder_config("agentmux-agent:1", "http://host.docker.internal:7", "s3cret");
208        let host = config.host_config.as_ref().unwrap();
209        assert!(host.mounts.is_none() && host.binds.is_none(), "no mount, so no Docker socket and no host file");
210        assert_eq!(host.cap_drop.as_deref(), Some(&["ALL".to_string()][..]));
211        assert_eq!(host.readonly_rootfs, Some(true));
212        assert_eq!(host.auto_remove, Some(true), "removed when it stops");
213        assert!(matches!(host.restart_policy.as_ref().and_then(|p| p.name.as_ref()), Some(RestartPolicyNameEnum::NO)), "no restart policy");
214        assert_eq!(host.network_mode.as_deref(), Some(AGENTMUX_DOCKER_NETWORK));
215        assert!(host.privileged.is_none() && host.cap_add.is_none() && host.pid_mode.is_none() && host.volumes_from.is_none());
216        assert_eq!(config.labels.as_ref().and_then(|l| l.get(HELPER_LABEL)).map(String::as_str), Some(HELPER_TEXT), "named as AgentMux's gateway forwarder");
217        assert_eq!(config.cmd.as_deref().map(|c| c.join(" ")).as_deref(), Some("agentmux-mcp gateway-fwd"));
218        let env = config.env.unwrap();
219        assert!(env.iter().any(|e| e == &format!("{ENV_SECRET}=s3cret")), "the secret is in its environment, and only there");
220        assert!(!config.cmd.unwrap().iter().any(|a| a.contains("s3cret")), "never in a command line");
221        for e in &env {
222            assert!(!e.contains("AUTH_KEY") && !e.contains("amxc_") && !e.contains("amxg_"), "no agent token or instance key: {}", e.split('=').next().unwrap());
223        }
224    }
225
226    #[test]
227    fn an_existing_forwarder_is_kept_only_for_this_launch_image_and_address() {
228        let made = |env: Vec<String>, image: &str, running: bool| ContainerInspectResponse {
229            state: Some(ContainerState { running: Some(running), ..Default::default() }),
230            config: Some(ContainerConfig { image: Some(image.to_string()), env: Some(env), ..Default::default() }),
231            ..Default::default()
232        };
233        let env = |secret: &str, upstream: &str| vec![format!("{ENV_SECRET}={secret}"), format!("{ENV_UPSTREAM}={upstream}")];
234        let up = "http://host.docker.internal:7";
235        assert!(is_current(&made(env(secret(), up), "img:1", true), "img:1", up));
236        assert!(!is_current(&made(env(secret(), up), "img:1", false), "img:1", up), "not running");
237        assert!(!is_current(&made(env("another-launchs", up), "img:1", true), "img:1", up), "another launch's secret");
238        assert!(!is_current(&made(env(secret(), up), "img:2", true), "img:1", up), "another image");
239        assert!(!is_current(&made(env(secret(), "http://host.docker.internal:8"), "img:1", true), "img:1", up), "srv is at another port");
240    }
241
242    #[test]
243    fn srv_accepts_a_stamp_only_with_this_launchs_proof_for_this_request() {
244        let now = 5000;
245        let good = stamped(secret(), now, "POST", TARGET);
246        assert_eq!(verify_stamp_at(&good, "POST", TARGET, now), Ok(peer()));
247        assert_eq!(verify_stamp_at(&HeaderMap::new(), "POST", TARGET, now), Err(Refusal::Missing), "a request straight to srv has no stamp");
248        assert_eq!(verify_stamp_at(&stamped("a-guess", now, "POST", TARGET), "POST", TARGET, now), Err(Refusal::BadProof), "a stamp made without the secret");
249        assert_eq!(verify_stamp_at(&good, "GET", TARGET, now), Err(Refusal::BadProof), "moved to another method");
250        assert_eq!(verify_stamp_at(&good, "POST", "/api/v1/model/openrouter/v1/messages", now), Err(Refusal::BadProof), "moved to another path");
251        assert_eq!(verify_stamp_at(&good, "POST", TARGET, now + 31), Err(Refusal::Expired));
252        let outside = "/api/v1/containers";
253        assert_eq!(verify_stamp_at(&stamped(secret(), now, "GET", outside), "GET", outside, now), Err(Refusal::OutsidePrefix), "never on another path, even with the secret");
254    }
255
256    #[test]
257    fn the_forwarder_is_found_by_its_name_on_the_agents_network() {
258        assert_eq!(url(), format!("http://{}:{PORT}", container_name()));
259        assert!(container_name().starts_with("agentmux-"), "inside the names AgentMux's container list and cleanup already look at");
260        assert!(is_forwarder_name(container_name()) && is_forwarder_name(CONTAINER_PREFIX));
261        assert!(!is_forwarder_name("agentmux-gateway-fwdx") && !is_forwarder_name("agentmux-boxy"));
262    }
263
264    #[test]
265    fn each_instance_has_its_own_forwarder_name_and_the_same_one_every_launch() {
266        assert_eq!(container_name(), container_name());
267        let mark = container_name().strip_prefix(CONTAINER_PREFIX).unwrap();
268        assert!(mark.len() == 9 && mark.starts_with('-') && mark[1..].chars().all(|c| c.is_ascii_hexdigit()), "{mark}");
269    }
270}