1use 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
46pub const CONN_HEADER: &str = "x-amx-conn";
48const KEY_FILE_VERSION: u32 = 1;
50const MAX_LEASE_SECS: u64 = 6 * 60;
52const REVOKE_WINDOW_SECS: u64 = 60;
54
55pub(crate) type Refusal = (StatusCode, &'static str);
57
58pub(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
67pub(crate) fn host() -> Option<&'static Host> {
69 HOST.get()
70}
71
72pub(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
80pub(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 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 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 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 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 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 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 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 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
247pub(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
258pub(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
304pub(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
316pub(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
328pub(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;