agentmux_srv/server/
operator_proof.rs1use 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
45const TTL: Duration = Duration::from_secs(60);
47const MAX_PENDING: usize = 256;
49
50#[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#[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 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 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
112pub fn issue(engine: &Arc<WshRpcEngine>) -> String {
114 challenges().issue(engine, Instant::now())
115}
116
117pub(super) fn peek_engine(nonce: &str) -> Option<Arc<WshRpcEngine>> {
120 challenges().peek(nonce, Instant::now())
121}
122
123pub(super) fn take_engine(nonce: &str) -> Option<Arc<WshRpcEngine>> {
126 challenges().take(nonce, Instant::now())
127}
128
129pub 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
137pub(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
144pub(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
165pub(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;