Skip to main content

agentmux_srv/server/
external_host.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! A headless server accepts the attestation of a registered external host.
5//!
6//! The CEF host proves the AgentMux window's connection with its IPC token
7//! (`operator_proof`). A headless server reached through a separate host process has no CEF host,
8//! and a shared secret would prove nothing, because every agent on the machine can read what srv
9//! can. So the external host is a key pair: it keeps the private key, and srv holds only the public
10//! key, registered once at boot (`--external-host-key-file`) before any connection or agent exists.
11//! There is no route or call that registers or replaces it, so a later or second registration
12//! cannot happen.
13//!
14//! What the host attests is one connection, by the challenge nonce the connection asked srv for
15//! (`operator.challenge`), for a short lease, naming the person. The host also gives each
16//! connection it proxies an id of its own, signed, in the `x-amx-conn` header; srv binds the
17//! challenge to that id, and the signed attestation carries it, so a connection that did not come
18//! through the host (one opened on loopback by anything else) can never be attested.
19//!
20//! Signed text, fixed field order, version first (the signature is Ed25519; fields are checked to
21//! hold no `|`):
22//!
23//! ```text
24//! amx-conn/v1|<workspace>|<conn>                                  the connection header
25//! amx-attest/v1|<workspace>|<conn>|<nonce>|<person>|<valid_until> an attestation
26//! amx-revoke/v1|<workspace>|<conn>|<issued_at>                    ending a connection's proof
27//! amx-host/v1|<workspace>|<op>|<issued_at>|<args>                 a call of the host's own (`host_control`)
28//! ```
29
30use std::collections::HashMap;
31use std::path::Path;
32use std::sync::{Arc, Mutex, OnceLock, Weak};
33
34use axum::http::{HeaderMap, StatusCode};
35use axum::response::{IntoResponse, Response};
36use axum::Json;
37use base64::engine::general_purpose::URL_SAFE_NO_PAD;
38use base64::Engine as _;
39use ed25519_dalek::{Signature, VerifyingKey};
40use serde::Deserialize;
41use serde_json::json;
42use sha2::{Digest, Sha256};
43
44use crate::backend::rpc::engine::WshRpcEngine;
45
46/// The header the host puts on the websocket upgrade of a connection it proxies: `<conn>.<signature>`.
47pub const CONN_HEADER: &str = "x-amx-conn";
48/// The key file's version.
49const KEY_FILE_VERSION: u32 = 1;
50/// The longest lease srv grants, whatever the host signed: the host asks for five minutes.
51const MAX_LEASE_SECS: u64 = 6 * 60;
52/// How old a revocation, or a call of the host's own, may be.
53const REVOKE_WINDOW_SECS: u64 = 60;
54
55/// Why a call was refused: the status and a line for the host.
56pub(crate) type Refusal = (StatusCode, &'static str);
57
58/// The registered host and the connections it proxied that are open now.
59pub(crate) struct Host {
60    workspace: String,
61    key: VerifyingKey,
62    live: Mutex<HashMap<String, Weak<WshRpcEngine>>>,
63}
64
65static HOST: OnceLock<Host> = OnceLock::new();
66
67/// The registered external host, if srv was started with one.
68pub(crate) fn host() -> Option<&'static Host> {
69    HOST.get()
70}
71
72/// Say in the log, once logging is up, that an external host key was registered at boot. Only the public key's fingerprint
73/// is written: a person comparing it with what the host reports can tell the two hold the same key.
74pub(crate) fn log_registered() {
75    if let Some(host) = host() {
76        tracing::info!(workspace = %host.workspace, fingerprint = %host.fingerprint(), "external host key registered");
77    }
78}
79
80/// Register the external host from its key file, once, at boot. A second registration is refused.
81pub(crate) fn register_from_file(path: &Path) -> Result<(), String> {
82    let text = std::fs::read_to_string(path).map_err(|e| format!("--external-host-key-file {}: {e}", path.display()))?;
83    set_once(&HOST, Host::from_file_text(&text).map_err(|e| format!("--external-host-key-file {}: {e}", path.display()))?)
84}
85
86fn set_once(cell: &OnceLock<Host>, host: Host) -> Result<(), String> {
87    cell.set(host).map_err(|_| "an external host is already registered".to_string())
88}
89
90fn plain(s: &str, min: usize, max: usize, extra: &str) -> bool {
91    (min..=max).contains(&s.len()) && s.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(c))
92}
93
94fn workspace_ok(s: &str) -> bool {
95    plain(s, 1, 64, "-")
96}
97
98fn conn_ok(s: &str) -> bool {
99    plain(s, 16, 64, "_-")
100}
101
102fn nonce_ok(s: &str) -> bool {
103    s.len() == 36 && s.chars().all(|c| c.is_ascii_hexdigit() || c == '-')
104}
105
106fn person_ok(s: &str) -> bool {
107    plain(s, 1, 128, "._@-")
108}
109
110#[derive(Debug, Deserialize)]
111struct KeyFile {
112    v: u32,
113    workspace: String,
114    public_key: String,
115}
116
117impl Host {
118    /// A host from its key file's text: `{"v":1,"workspace":"<id>","public_key":"<base64url, 32 bytes>"}`.
119    pub(crate) fn from_file_text(text: &str) -> Result<Host, String> {
120        let file: KeyFile = serde_json::from_str(text).map_err(|e| format!("not a key file: {e}"))?;
121        if file.v != KEY_FILE_VERSION {
122            return Err(format!("key file version {} is not supported", file.v));
123        }
124        if !workspace_ok(&file.workspace) {
125            return Err("the workspace id is not valid".to_string());
126        }
127        let bytes = URL_SAFE_NO_PAD.decode(file.public_key.trim()).map_err(|_| "the public key is not base64url".to_string())?;
128        let bytes: [u8; 32] = bytes.try_into().map_err(|_| "the public key is not 32 bytes".to_string())?;
129        let key = VerifyingKey::from_bytes(&bytes).map_err(|_| "the public key is not a valid Ed25519 key".to_string())?;
130        Ok(Host { workspace: file.workspace, key, live: Mutex::new(HashMap::new()) })
131    }
132
133    /// A short name for the public key: the first 8 bytes of the SHA-256 of its 32 bytes, as 16 hex characters. The key is
134    /// public, and this is all a log line says of it.
135    pub(crate) fn fingerprint(&self) -> String {
136        hex::encode(&Sha256::digest(self.key.as_bytes())[..8])
137    }
138
139    fn verify(&self, text: &str, signature_b64: &str) -> bool {
140        let Ok(bytes) = URL_SAFE_NO_PAD.decode(signature_b64.trim()) else { return false };
141        let Ok(bytes): Result<[u8; 64], _> = bytes.try_into() else { return false };
142        self.key.verify_strict(text.as_bytes(), &Signature::from_bytes(&bytes)).is_ok()
143    }
144
145    /// The connection id in an `x-amx-conn` header value, if the host signed it for this workspace.
146    pub(crate) fn conn_from_header(&self, value: &str) -> Option<String> {
147        let (id, sig) = value.trim().split_once('.')?;
148        if !conn_ok(id) || !self.verify(&format!("amx-conn/v1|{}|{id}", self.workspace), sig) {
149            return None;
150        }
151        Some(id.to_string())
152    }
153
154    /// Note that the connection `id` (proxied by the host) is `engine`. False when `id` is already
155    /// held by a connection that is still open: the first holder keeps it.
156    pub(crate) fn attach(&self, id: &str, engine: &Arc<WshRpcEngine>) -> bool {
157        let mut live = self.live.lock().unwrap_or_else(|e| e.into_inner());
158        live.retain(|_, w| w.strong_count() > 0);
159        if live.contains_key(id) {
160            return false;
161        }
162        live.insert(id.to_string(), Arc::downgrade(engine));
163        true
164    }
165
166    /// The connection `id` has closed.
167    pub(crate) fn detach(&self, id: &str) {
168        self.live.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
169    }
170
171    fn engine_of(&self, id: &str) -> Option<Arc<WshRpcEngine>> {
172        self.live.lock().unwrap_or_else(|e| e.into_inner()).get(id).and_then(Weak::upgrade)
173    }
174
175    /// The host attests the connection `nonce` was issued to. Everything is checked before the nonce is
176    /// spent; once it is, it is spent whatever else fails. Returns the person that is now vouched for.
177    fn attest(&self, req: &AttestRequest, now: u64) -> Result<String, Refusal> {
178        if req.v != 1 {
179            return Err((StatusCode::BAD_REQUEST, "unsupported version"));
180        }
181        if !nonce_ok(&req.nonce) || !conn_ok(&req.conn) || !person_ok(&req.person) || !workspace_ok(&req.workspace) {
182            return Err((StatusCode::BAD_REQUEST, "a field is not valid"));
183        }
184        if req.workspace != self.workspace {
185            return Err((StatusCode::FORBIDDEN, "signed for another workspace"));
186        }
187        let text = format!("amx-attest/v1|{}|{}|{}|{}|{}", req.workspace, req.conn, req.nonce, req.person, req.valid_until);
188        if !self.verify(&text, &req.sig) {
189            return Err((StatusCode::FORBIDDEN, "the signature is not the registered host's"));
190        }
191        if req.valid_until <= now || req.valid_until > now + MAX_LEASE_SECS {
192            return Err((StatusCode::FORBIDDEN, "the lease is over or too long"));
193        }
194        let Some(engine) = super::operator_proof::take_engine(&req.nonce) else {
195            return Err((StatusCode::CONFLICT, "that challenge is unknown, used or expired"));
196        };
197        if engine.gateway_conn().as_deref() != Some(req.conn.as_str()) {
198            return Err((StatusCode::FORBIDDEN, "that connection did not come through the host"));
199        }
200        if !engine.mark_operator_proven_for(&req.person, req.valid_until) {
201            return Err((StatusCode::CONFLICT, "that connection is registered as an agent"));
202        }
203        Ok(req.person.clone())
204    }
205
206    /// A call of the host's own (`host_control`: what srv is doing, a stop notice, a graceful shutdown) is the host's
207    /// and nobody else's: it is signed over its operation and arguments, for this workspace, and no older than a minute.
208    /// The instance key is not enough, because every agent can read it.
209    pub(crate) fn check_call(&self, op: &str, workspace: &str, issued_at: u64, args: &str, sig: &str, now: u64) -> Result<(), Refusal> {
210        if !workspace_ok(workspace) || !plain(op, 1, 32, "-") || args.contains('|') {
211            return Err((StatusCode::BAD_REQUEST, "a field is not valid"));
212        }
213        if workspace != self.workspace {
214            return Err((StatusCode::FORBIDDEN, "signed for another workspace"));
215        }
216        if !self.verify(&format!("amx-host/v1|{workspace}|{op}|{issued_at}|{args}"), sig) {
217            return Err((StatusCode::FORBIDDEN, "the signature is not the registered host's"));
218        }
219        if now.abs_diff(issued_at) > REVOKE_WINDOW_SECS {
220            return Err((StatusCode::FORBIDDEN, "the call is too old"));
221        }
222        Ok(())
223    }
224
225    /// The host ends the proof of one connection (the person signed out). Idempotent.
226    fn revoke(&self, req: &RevokeRequest, now: u64) -> Result<(), Refusal> {
227        if req.v != 1 || !conn_ok(&req.conn) || !workspace_ok(&req.workspace) {
228            return Err((StatusCode::BAD_REQUEST, "a field is not valid"));
229        }
230        if req.workspace != self.workspace {
231            return Err((StatusCode::FORBIDDEN, "signed for another workspace"));
232        }
233        let text = format!("amx-revoke/v1|{}|{}|{}", req.workspace, req.conn, req.issued_at);
234        if !self.verify(&text, &req.sig) {
235            return Err((StatusCode::FORBIDDEN, "the signature is not the registered host's"));
236        }
237        if now.abs_diff(req.issued_at) > REVOKE_WINDOW_SECS {
238            return Err((StatusCode::FORBIDDEN, "the revocation is too old"));
239        }
240        if let Some(engine) = self.engine_of(&req.conn) {
241            engine.clear_operator_proof();
242        }
243        Ok(())
244    }
245}
246
247/// Holds a connection's id while it is open and gives it back when it closes.
248pub(crate) struct ConnGuard(String);
249
250impl Drop for ConnGuard {
251    fn drop(&mut self) {
252        if let Some(host) = host() {
253            host.detach(&self.0);
254        }
255    }
256}
257
258/// A websocket upgrade's host-proxied identity: the verified id and the guard that frees it. `None`
259/// when no host is registered, the header is missing or not the host's signature, or the id is held.
260pub(crate) fn claim_connection(headers: &HeaderMap, engine: &Arc<WshRpcEngine>) -> Option<ConnGuard> {
261    let host = host()?;
262    let value = headers.get(CONN_HEADER)?.to_str().ok()?;
263    let id = host.conn_from_header(value)?;
264    if !host.attach(&id, engine) {
265        return None;
266    }
267    engine.set_gateway_conn(id.clone());
268    Some(ConnGuard(id))
269}
270
271#[derive(Debug, Deserialize)]
272pub(crate) struct NonceRequest {
273    nonce: String,
274}
275
276#[derive(Debug, Deserialize)]
277pub(crate) struct AttestRequest {
278    v: u32,
279    nonce: String,
280    conn: String,
281    workspace: String,
282    person: String,
283    valid_until: u64,
284    sig: String,
285}
286
287#[derive(Debug, Deserialize)]
288pub(crate) struct RevokeRequest {
289    v: u32,
290    conn: String,
291    workspace: String,
292    issued_at: u64,
293    sig: String,
294}
295
296fn refused((status, error): Refusal) -> Response {
297    (status, Json(json!({ "ok": false, "error": error }))).into_response()
298}
299
300fn not_registered() -> Response {
301    refused((StatusCode::NOT_FOUND, "no external host is registered"))
302}
303
304/// `POST /api/v1/host/external_nonce`: which host-proxied connection a challenge was issued to (its id),
305/// without spending the challenge. The host asks before it signs; a connection that did not come
306/// through the host answers `null`.
307pub(crate) async fn handle_nonce(Json(req): Json<NonceRequest>) -> Response {
308    let Some(_host) = host() else { return not_registered() };
309    if !nonce_ok(&req.nonce) {
310        return refused((StatusCode::BAD_REQUEST, "a field is not valid"));
311    }
312    let conn = super::operator_proof::peek_engine(&req.nonce).and_then(|e| e.gateway_conn());
313    Json(json!({ "ok": true, "conn": conn })).into_response()
314}
315
316/// `POST /api/v1/host/external_attest`: the registered host vouches for one connection.
317pub(crate) async fn handle_attest(Json(req): Json<AttestRequest>) -> Response {
318    let Some(host) = host() else { return not_registered() };
319    match host.attest(&req, agentmux_common::time::now_secs_u64()) {
320        Ok(person) => {
321            tracing::info!(person = %person, conn = %req.conn, "external host attested a connection");
322            Json(json!({ "ok": true, "valid_until": req.valid_until })).into_response()
323        }
324        Err(r) => refused(r),
325    }
326}
327
328/// `POST /api/v1/host/external_revoke`: the registered host ends one connection's proof.
329pub(crate) async fn handle_revoke(Json(req): Json<RevokeRequest>) -> Response {
330    let Some(host) = host() else { return not_registered() };
331    match host.revoke(&req, agentmux_common::time::now_secs_u64()) {
332        Ok(()) => Json(json!({ "ok": true })).into_response(),
333        Err(r) => refused(r),
334    }
335}
336
337#[cfg(test)]
338#[path = "external_host_tests.rs"]
339mod tests;