Skip to main content

agentmux_srv/server/
operator_proof.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Proof that a websocket connection is the AgentMux window's.
5//!
6//! Every agent holds the instance auth key, so a connection that never sent
7//! `bus:register` proves nothing by itself. Operator-only actions need the
8//! host's proof (`RpcContext::operator_only`):
9//!
10//! 1. the window asks srv for a challenge over its own websocket
11//!    (`operator.challenge`) and gets a single-use nonce bound to that
12//!    connection;
13//! 2. it hands the nonce to the CEF host (`operator_attest`), which posts it to
14//!    `POST /api/v1/host/operator_attest` with its IPC token, which agents never
15//!    see;
16//! 3. srv marks the connection the nonce was issued to as the operator's.
17//!
18//! A nonce is used once and expires after [`TTL`]. Registering the connection
19//! as an agent afterwards drops the proof (`WshRpcEngine::set_rpc_context`).
20//!
21//! A headless srv has no CEF host. A browser the person signed in there (a
22//! confirmed `local_session`, which the person approved by comparing a check
23//! phrase in a terminal) is their window too: [`vouch_for_signed_in_browser`]
24//! gives its connection the same proof. An agent never has such a session: it
25//! holds the key, which takes the other path in `auth_middleware`.
26
27use std::collections::HashMap;
28use std::sync::{Arc, LazyLock, Mutex, Weak};
29use std::time::{Duration, Instant};
30
31use axum::extract::State;
32use axum::http::{HeaderMap, StatusCode};
33use axum::response::{IntoResponse, Response};
34use axum::Json;
35use serde::{Deserialize, Serialize};
36use serde_json::json;
37
38use crate::backend::rpc::engine::WshRpcEngine;
39use crate::backend::rpc_types::{NoArgsReq, RpcContext};
40
41use super::AppState;
42
43pub const COMMAND_OPERATOR_CHALLENGE: &str = "operator.challenge";
44
45/// How long a challenge waits for the host's attestation.
46const TTL: Duration = Duration::from_secs(60);
47/// The most challenges waiting at once; past it the oldest is dropped.
48const MAX_PENDING: usize = 256;
49
50/// `operator.challenge`'s answer: the nonce to hand to the CEF host.
51#[derive(Debug, Clone, Serialize, ts_rs::TS)]
52#[ts(export, export_to = "../../../frontend/types/rpc/")]
53pub struct OperatorChallengeResult {
54    pub nonce: String,
55}
56
57struct Pending {
58    engine: Weak<WshRpcEngine>,
59    issued: Instant,
60}
61
62/// Challenges waiting for the host, by nonce.
63#[derive(Default)]
64struct Challenges {
65    pending: HashMap<String, Pending>,
66}
67
68impl Challenges {
69    fn issue(&mut self, engine: &Arc<WshRpcEngine>, now: Instant) -> String {
70        self.pending.retain(|_, p| now.duration_since(p.issued) < TTL && p.engine.strong_count() > 0);
71        while self.pending.len() >= MAX_PENDING {
72            let oldest = self.pending.iter().min_by_key(|(_, p)| p.issued).map(|(n, _)| n.clone());
73            match oldest {
74                Some(n) => self.pending.remove(&n),
75                None => break,
76            };
77        }
78        let nonce = uuid::Uuid::new_v4().to_string();
79        self.pending.insert(nonce.clone(), Pending { engine: Arc::downgrade(engine), issued: now });
80        nonce
81    }
82
83    /// The connection `nonce` was issued to, if it is still waiting, unexpired
84    /// and open. The nonce is spent either way.
85    fn take(&mut self, nonce: &str, now: Instant) -> Option<Arc<WshRpcEngine>> {
86        let p = self.pending.remove(nonce)?;
87        if now.duration_since(p.issued) >= TTL {
88            return None;
89        }
90        p.engine.upgrade()
91    }
92}
93
94impl Challenges {
95    /// The connection `nonce` was issued to, if it is still waiting, unexpired and open. The nonce
96    /// is not spent.
97    fn peek(&self, nonce: &str, now: Instant) -> Option<Arc<WshRpcEngine>> {
98        let p = self.pending.get(nonce)?;
99        if now.duration_since(p.issued) >= TTL {
100            return None;
101        }
102        p.engine.upgrade()
103    }
104}
105
106static CHALLENGES: LazyLock<Mutex<Challenges>> = LazyLock::new(Default::default);
107
108fn challenges() -> std::sync::MutexGuard<'static, Challenges> {
109    CHALLENGES.lock().unwrap_or_else(|e| e.into_inner())
110}
111
112/// A fresh single-use nonce bound to `engine`'s connection.
113pub fn issue(engine: &Arc<WshRpcEngine>) -> String {
114    challenges().issue(engine, Instant::now())
115}
116
117/// The connection `nonce` was issued to, without spending it (a registered external host asks which
118/// connection a challenge belongs to before it signs: `server::external_host`).
119pub(super) fn peek_engine(nonce: &str) -> Option<Arc<WshRpcEngine>> {
120    challenges().peek(nonce, Instant::now())
121}
122
123/// Spend `nonce` and hand back the connection it was issued to, for a caller that decides whether to
124/// mark it (`server::external_host`). The nonce is spent either way.
125pub(super) fn take_engine(nonce: &str) -> Option<Arc<WshRpcEngine>> {
126    challenges().take(nonce, Instant::now())
127}
128
129/// Spend `nonce` and mark the connection it was issued to as the operator's.
130/// False when the nonce is unknown, used, expired, its connection closed, or
131/// that connection has registered as an agent.
132pub fn attest(nonce: &str) -> bool {
133    let engine = challenges().take(nonce, Instant::now());
134    engine.is_some_and(|e| e.mark_operator_proven())
135}
136
137/// Mark a connection the person's when a browser they signed in opened it
138/// (`session` is set only for a confirmed local session). The proof is dropped
139/// again if the connection registers as an agent, like the app window's.
140pub(super) fn vouch_for_signed_in_browser(engine: &WshRpcEngine, session: Option<&super::local_session::SessionId>) -> bool {
141    session.is_some() && engine.mark_operator_proven()
142}
143
144/// Register `operator.challenge` on one connection's engine. The handler holds
145/// only a weak reference to the engine that owns it.
146pub(super) fn register_challenge(engine: &Arc<WshRpcEngine>) {
147    let weak = Arc::downgrade(engine);
148    engine.register_typed(COMMAND_OPERATOR_CHALLENGE, move |_req: Option<NoArgsReq>, ctx: RpcContext| {
149        let weak = weak.clone();
150        async move {
151            if !ctx.agent_id.is_empty() {
152                return Err("FORBIDDEN: a connection registered as an agent isn't the AgentMux window".to_string());
153            }
154            let engine = weak.upgrade().ok_or("this connection is closing")?;
155            Ok(OperatorChallengeResult { nonce: issue(&engine) })
156        }
157    });
158}
159
160#[derive(Debug, Deserialize)]
161pub(crate) struct AttestRequest {
162    nonce: String,
163}
164
165/// `POST /api/v1/host/operator_attest`: the CEF host vouches, with its own
166/// token, for the connection a challenge was issued to. The instance auth
167/// key, which every agent has, isn't enough.
168pub(crate) async fn handle_host_attest(
169    State(state): State<AppState>,
170    headers: HeaderMap,
171    Json(req): Json<AttestRequest>,
172) -> Response {
173    if !super::ui_handlers::from_host(&state, &headers).await {
174        let error = "only the AgentMux host can prove the operator's window";
175        return (StatusCode::FORBIDDEN, Json(json!({ "ok": false, "error": error }))).into_response();
176    }
177    if attest(&req.nonce) {
178        Json(json!({ "ok": true })).into_response()
179    } else {
180        let error = "that challenge is unknown, used or expired";
181        (StatusCode::CONFLICT, Json(json!({ "ok": false, "error": error }))).into_response()
182    }
183}
184
185#[cfg(test)]
186#[path = "operator_proof_tests.rs"]
187mod tests;