Skip to main content

agentmux_srv/server/
auth.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Origin checks and the auth middlewares.
5//! Split out of server/mod.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.1).
6
7use super::*;
8use agentmux_common::AUTH_KEY_HEADER;
9
10// ---- Origin checks ----
11
12/// A loopback origin ([`is_loopback_origin`]), or one a headless srv was
13/// told to accept with `--allowed-origin` (a reverse proxy's public origin).
14/// Used by CORS and by [`ws_origin_guard`].
15pub(crate) fn is_allowed_origin(origin: &str) -> bool {
16    is_loopback_origin(origin) || crate::headless::is_extra_allowed_origin(origin)
17}
18
19/// `http://127.0.0.1` or `http://localhost`, optionally with a numeric
20/// port: where the desktop frontend is served from (the CEF host's loopback
21/// server, or the Vite dev server). A headless srv behind a reverse proxy can
22/// also accept the proxy's origin; see [`is_allowed_origin`], which CORS and
23/// [`ws_origin_guard`] use.
24pub(crate) fn is_loopback_origin(origin: &str) -> bool {
25    ["http://127.0.0.1", "http://localhost"].iter().any(|host| {
26        origin.strip_prefix(host).is_some_and(|rest| {
27            rest.is_empty()
28                || rest
29                    .strip_prefix(':')
30                    .is_some_and(|port| !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()))
31        })
32    })
33}
34
35/// Refuse a WebSocket upgrade whose `Origin` is neither loopback nor allowed
36/// by `--allowed-origin` ([`is_allowed_origin`]).
37///
38/// CORS does not apply to WebSocket upgrades, so without this any web page
39/// holding the auth key could open `/ws` (cross-site WebSocket hijacking).
40/// The key is not sent automatically the way a cookie would be, so this is
41/// defense in depth rather than a fix for a reachable attack. Browsers always
42/// send `Origin` on an upgrade; srv's native clients (launcher, agentmux-mcp)
43/// send none, so a missing header is allowed.
44pub(super) async fn ws_origin_guard(req: Request<Body>, next: Next) -> Response {
45    let origin = req.headers().get(header::ORIGIN).map(|v| v.to_str().unwrap_or(""));
46    match origin {
47        Some(o) if !is_allowed_origin(o) => {
48            tracing::warn!(origin = %o, "refused /ws upgrade from an origin that isn't allowed");
49            (StatusCode::FORBIDDEN, Json(json!({"error": "origin not allowed"}))).into_response()
50        }
51        _ => next.run(req).await,
52    }
53}
54
55// ---- Auth Middleware ----
56
57/// Auth middleware matching Go pkg/authkey/authkey.go:18-42.
58pub(super) async fn auth_middleware(
59    State(state): State<AppState>,
60    mut req: Request<Body>,
61    next: Next,
62) -> Response {
63    if req.method() == Method::OPTIONS {
64        return next.run(req).await;
65    }
66
67    let auth_key = req
68        .headers()
69        .get(AUTH_KEY_HEADER)
70        .and_then(|v| v.to_str().ok())
71        .map(|s| s.to_string());
72
73    // 2026-05-11 audit (C3): the query-string `?authkey=` fallback
74    // bypasses CORS preflight and is preserved in browser history,
75    // navigation `Referer` headers, server access logs, etc. — a CSRF
76    // amplifier whenever the key leaks. It is allowed **only** on the
77    // WebSocket upgrade route (`/ws`), where the browser WS API doesn't
78    // permit custom headers and there is no other practical channel
79    // for the key. Every other route requires the header.
80    let auth_key = auth_key.or_else(|| {
81        if req.uri().path() != "/ws" {
82            return None;
83        }
84        req.uri().query().and_then(|q| {
85            q.split('&')
86                .filter_map(|pair| pair.split_once('='))
87                .find(|(k, _)| *k == "authkey")
88                .map(|(_, v)| v.to_string())
89        })
90    });
91
92    // A headless srv that serves its own UI also admits a browser the person signed in
93    // (`local_session_routes`): the session stands in for the key, on that browser's requests only.
94    if auth_key.is_none() && super::local_session_routes::enabled() {
95        return match super::local_session_routes::admit_session(&req) {
96            Some(session) => {
97                req.extensions_mut().insert(ReactiveAuthVia::FullAuthKey);
98                // The WebSocket handler closes its socket when this session ends.
99                req.extensions_mut().insert(session);
100                next.run(req).await
101            }
102            None => unauthorized(),
103        };
104    }
105
106    match auth_key {
107        Some(key) if secret_eq(key.as_bytes(), state.auth_key.as_bytes()) => {
108            // Identity M4a: `caller_middleware` derives a `Caller` only for a
109            // request marked as full-key authenticated — never by default.
110            req.extensions_mut().insert(ReactiveAuthVia::FullAuthKey);
111            next.run(req).await
112        }
113        Some(key) => match crate::backend::container::credential::grant_for(&key) {
114            Some(grant) => admit_container_agent(grant, req, next).await,
115            None => unauthorized(),
116        },
117        None => unauthorized(),
118    }
119}
120
121pub(super) fn unauthorized() -> Response {
122    (StatusCode::UNAUTHORIZED, Json(json!({"error": "unauthorized"}))).into_response()
123}
124
125/// A container agent's token: allowed on a route the table serves ([`super::route_table`]) unless its
126/// audience refuses it ([`crate::backend::route_audience`]); a refusal carries its reason. Elsewhere it
127/// stands in for the instance key it replaced (so jekt tiers and identity
128/// behave as for any agent), with the caller pinned to the grant's agent by
129/// `caller_middleware`.
130pub(super) async fn admit_container_agent(
131    grant: crate::backend::container::credential::ContainerGrant,
132    mut req: Request<Body>,
133    next: Next,
134) -> Response {
135    use crate::backend::container::credential::route_needs_identity;
136    let path = req.uri().path().to_string();
137    let refused = if let Some(why) = crate::backend::container::routes::refusal_message(&path, super::route_table::serves) {
138        Some(why)
139    } else if route_needs_identity(&path) && grant.agent_token.is_none() {
140        Some("this container agent has no identity token".to_string())
141    } else {
142        None
143    };
144    if let Some(reason) = refused {
145        tracing::warn!(block_id = %grant.block_id, %path, reason, "container agent request refused");
146        return (StatusCode::FORBIDDEN, Json(json!({"error": reason}))).into_response();
147    }
148    req.extensions_mut().insert(ReactiveAuthVia::FullAuthKey);
149    req.extensions_mut().insert(grant);
150    next.run(req).await
151}
152
153/// Auth middleware for the two LAN-forwarding-relevant reactive routes
154/// (`/agentmux/reactive/agent`, `/agentmux/reactive/inject`) — accepts
155/// EITHER `state.auth_key` (the normal, full-access case: every other
156/// caller of these two routes, e.g. agentmux-mcp's SendMessage tool for a
157/// plain host-tier inject) OR `state.lan_key` (a LAN peer forwarding a
158/// jekt or looking up which agents this instance hosts).
159///
160/// Deliberately a SEPARATE middleware from `auth_middleware`, applied to a
161/// standalone router merged at the top level rather than nested inside
162/// `authed_routes` — nesting would put `authed_routes`'s own
163/// `route_layer(auth_middleware)` on the outside, rejecting the LAN key
164/// before this middleware ever ran. This is why these two routes live in
165/// their own `lan_forward_routes` router in `router()`, not in
166/// `reactive_routes`.
167///
168/// `state.lan_key` grants access to ONLY the `lan_forward_routes` — never the rest
169/// of `/agentmux/service`, `/agentmux/file`, shell creation, credential/
170/// identity endpoints, etc. See `Config::lan_key`'s doc comment for why
171/// this exists.
172/// Which of the two credentials `lan_or_full_auth_middleware` accepted
173/// authenticated this specific request. Inserted into the request's
174/// extensions so `handle_reactive_inject` can force `delivery_tier = "lan"`
175/// whenever `LanKey` authenticated the request, regardless of what the JSON
176/// body itself claims — closing the bypass where a `lan_key`-only holder
177/// could otherwise just self-label a request "host" to dodge LAN's stricter
178/// verification entirely. See
179/// docs/specs/SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md §3 for the full
180/// rationale, including why the reverse (downgrading a "lan" claim seen
181/// under `FullAuthKey`) is deliberately NOT done — reagentx P0 found that
182/// same-host forwarding (Tier 2a/2b in `reactive.rs`) legitimately
183/// re-authenticates an already-LAN-originated jekt with a sibling
184/// instance's own full `auth_key`, so downgrading there silently discarded
185/// an already-detected signature failure's forced-sensitive escalation.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub(crate) enum ReactiveAuthVia {
188    FullAuthKey,
189    LanKey,
190}
191
192pub(super) async fn lan_or_full_auth_middleware(
193    State(state): State<AppState>,
194    mut req: Request<Body>,
195    next: Next,
196) -> Response {
197    if req.method() == Method::OPTIONS {
198        return next.run(req).await;
199    }
200
201    let auth_key = req
202        .headers()
203        .get(AUTH_KEY_HEADER)
204        .and_then(|v| v.to_str().ok());
205
206    match auth_key {
207        Some(key) if secret_eq(key.as_bytes(), state.auth_key.as_bytes()) => {
208            req.extensions_mut().insert(ReactiveAuthVia::FullAuthKey);
209            next.run(req).await
210        }
211        Some(key) if secret_eq(key.as_bytes(), state.lan_key.as_bytes()) => {
212            // Another machine got through with the LAN key: it can find and reach us.
213            if let Some(peer) = req.extensions().get::<axum::extract::ConnectInfo<std::net::SocketAddr>>() {
214                crate::backend::lan::mdns_health::note_inbound_peer(peer.0.ip());
215            }
216            req.extensions_mut().insert(ReactiveAuthVia::LanKey);
217            next.run(req).await
218        }
219        Some(key) => match crate::backend::container::credential::grant_for(key) {
220            Some(grant) => admit_container_agent(grant, req, next).await,
221            None => unauthorized(),
222        },
223        None => unauthorized(),
224    }
225}