1use std::sync::Mutex;
19use std::time::{Duration, Instant};
20
21use serde::Deserialize;
22
23pub const DISCOVERY_PATH: &str = "/.well-known/agentmux-cloud.json";
25
26const CACHE_TTL: Duration = Duration::from_secs(300);
28const FETCH_TIMEOUT: Duration = Duration::from_secs(5);
29
30pub const PRODUCTION_HOSTS: &[&str] = &[
37 "auth.agentmux.ai",
38 "cloud.agentmux.ai",
39 "muxbus.agentmux.ai",
40 "muxbus-ws.agentmux.ai",
41 "auth.muxbus.agentmux.ai",
42];
43
44pub const STAGING_HOSTS: &[&str] = &[
47 "auth.staging.agentmux.ai",
48 "cloud.staging.agentmux.ai",
49 "muxbus.staging.agentmux.ai",
50 "muxbus-ws.staging.agentmux.ai",
51];
52
53#[derive(Debug, Clone, PartialEq, Eq, Default)]
55enum HostRule {
56 #[default]
58 Production,
59 Staging,
60 Local,
62 Own(String),
64}
65
66fn bare_host(url: &str) -> Option<String> {
69 let url = url::Url::parse(url).ok()?;
70 if !url.username().is_empty() || url.password().is_some() || url.port().is_some() {
71 return None;
72 }
73 Some(url.host_str()?.to_ascii_lowercase())
74}
75
76impl HostRule {
77 fn for_base(rest_base: &str) -> HostRule {
78 if rest_base.starts_with("http://") {
79 return HostRule::Local;
80 }
81 match bare_host(rest_base) {
82 Some(host) if PRODUCTION_HOSTS.contains(&host.as_str()) => HostRule::Production,
83 Some(host) if STAGING_HOSTS.contains(&host.as_str()) => HostRule::Staging,
84 Some(host) => HostRule::Own(host),
85 None => HostRule::Production,
86 }
87 }
88
89 fn allows(&self, url: &str) -> bool {
91 if *self == HostRule::Local {
92 return true;
93 }
94 let Some(host) = bare_host(url) else {
95 return false;
96 };
97 let host = host.as_str();
98 match self {
99 HostRule::Production => PRODUCTION_HOSTS.contains(&host),
100 HostRule::Staging => STAGING_HOSTS.contains(&host),
101 HostRule::Own(own) => host == own || PRODUCTION_HOSTS.contains(&host) || STAGING_HOSTS.contains(&host),
102 HostRule::Local => true,
103 }
104 }
105}
106
107#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
109pub struct CloudSettings {
110 pub api: String,
112 pub ws: String,
114 #[serde(default)]
116 pub console: String,
117 pub cognito: CognitoSettings,
118 #[serde(skip)]
120 rule: HostRule,
121}
122
123impl CloudSettings {
124 pub fn allows_host_of(&self, url: &str) -> bool {
127 self.rule.allows(url)
128 }
129}
130
131#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
132#[serde(rename_all = "camelCase")]
133pub struct CognitoSettings {
134 pub domain: String,
136 pub client_id: String,
138 #[serde(default)]
139 pub region: String,
140 #[serde(default)]
141 pub user_pool_id: String,
142 #[serde(default)]
145 pub identity_providers: Vec<String>,
146}
147
148pub const DIRECT_IDENTITY_PROVIDERS: &[&str] = &["Google", "SignInWithApple"];
151
152pub fn check_identity_provider(
156 discovered: Option<&CloudSettings>,
157 requested: Option<&str>,
158) -> Result<Option<String>, String> {
159 let Some(provider) = requested else {
160 return Ok(None);
161 };
162 if !DIRECT_IDENTITY_PROVIDERS.contains(&provider) {
163 return Err(format!("AgentMux Cloud has no sign-in with \"{provider}\""));
164 }
165 if let Some(published) = discovered.map(|s| &s.cognito.identity_providers) {
166 if !published.is_empty() && !published.iter().any(|p| p == provider) {
167 return Err(format!("AgentMux Cloud doesn't offer sign-in with {provider} right now"));
168 }
169 }
170 Ok(Some(provider.to_string()))
171}
172
173pub fn parse(body: &str, rest_base: &str) -> Option<CloudSettings> {
178 check(body, rest_base).ok()
179}
180
181fn check(body: &str, rest_base: &str) -> Result<CloudSettings, String> {
183 let value: serde_json::Value = serde_json::from_str(body).map_err(|_| "not JSON".to_string())?;
184 if value.get("version").and_then(|v| v.as_u64()) != Some(1) {
185 return Err("not a version 1 document".to_string());
186 }
187 let mut settings: CloudSettings = serde_json::from_value(value).map_err(|_| "a field is missing".to_string())?;
188 let local = rest_base.starts_with("http://");
189 let secure = |url: &str, scheme: &str, dev: &str| url.starts_with(scheme) || (local && url.starts_with(dev));
190 let ok = secure(&settings.api, "https://", "http://")
191 && secure(&settings.ws, "wss://", "ws://")
192 && secure(&settings.cognito.domain, "https://", "http://")
193 && !settings.cognito.client_id.is_empty();
194 if !ok {
195 return Err("a URL scheme or the client id is not acceptable".to_string());
196 }
197 settings.rule = HostRule::for_base(rest_base);
198 let named = [
199 ("api", &settings.api),
200 ("ws", &settings.ws),
201 ("console", &settings.console),
202 ("cognito.domain", &settings.cognito.domain),
203 ];
204 for (field, url) in named {
205 if !url.is_empty() && !settings.rule.allows(url) {
206 return Err(format!("{field} names a host that is not AgentMux's own"));
207 }
208 }
209 Ok(settings)
210}
211
212struct Cache {
213 fetched_at: Instant,
214 last_good: Option<CloudSettings>,
216}
217
218static CACHE: Mutex<Option<Cache>> = Mutex::new(None);
219
220pub async fn cloud_settings(http: &reqwest::Client) -> Option<CloudSettings> {
226 if let Some(cache) = CACHE.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
227 if cache.fetched_at.elapsed() < CACHE_TTL {
228 return cache.last_good.clone();
229 }
230 }
231 let base = super::relay::rest_base_url();
232 let fetched = fetch(http, &base).await;
233 let mut guard = CACHE.lock().unwrap_or_else(|e| e.into_inner());
234 let last_good = keep_last_good(guard.as_ref().and_then(|c| c.last_good.as_ref()), fetched);
235 *guard = Some(Cache { fetched_at: Instant::now(), last_good: last_good.clone() });
236 last_good
237}
238
239fn keep_last_good(previous: Option<&CloudSettings>, fetched: Option<CloudSettings>) -> Option<CloudSettings> {
241 fetched.or_else(|| previous.cloned())
242}
243
244async fn fetch(http: &reqwest::Client, base: &str) -> Option<CloudSettings> {
245 let url = format!("{}{}", base.trim_end_matches('/'), DISCOVERY_PATH);
246 let sent = http.get(&url).timeout(FETCH_TIMEOUT).send().await;
247 crate::connectivity::report_http(crate::connectivity::Service::Muxbus, &sent);
248 let resp = match sent {
249 Ok(r) => r,
250 Err(e) => {
251 tracing::debug!(url = %url, error = %e, "cloud discovery: fetch failed; using defaults");
252 return None;
253 }
254 };
255 if !resp.status().is_success() {
256 tracing::debug!(url = %url, status = %resp.status(), "cloud discovery: no document; using defaults");
257 return None;
258 }
259 let body = resp.text().await.ok()?;
260 match check(&body, base) {
261 Ok(settings) => Some(settings),
262 Err(why) => {
263 tracing::warn!(url = %url, reason = %why, "cloud discovery: document refused; using defaults");
264 None
265 }
266 }
267}
268
269pub async fn ws_url(http: &reqwest::Client) -> String {
272 if let Some(url) = std::env::var("AGENTMUX_MUXBUS_WS_URL")
275 .ok()
276 .filter(|v| !v.is_empty())
277 {
278 return url;
279 }
280 cloud_settings(http)
281 .await
282 .map(|s| s.ws)
283 .unwrap_or_else(|| super::cloud_subscriber::MUXBUS_WS_URL.to_string())
284}
285
286pub fn resolve_login(
290 discovered: Option<&CloudSettings>,
291 supplied_domain: &str,
292 supplied_client_id: &str,
293) -> Result<(String, String), String> {
294 if let Some(s) = discovered.filter(|s| s.allows_host_of(&s.cognito.domain)) {
295 return Ok((s.cognito.domain.clone(), s.cognito.client_id.clone()));
296 }
297 if !supplied_domain.is_empty() && !supplied_client_id.is_empty() {
298 return Ok((supplied_domain.to_string(), supplied_client_id.to_string()));
299 }
300 Err("AgentMux Cloud sign-in isn't configured: the cloud publishes no settings and this build has none".to_string())
301}
302
303pub fn client_id_superseded(discovered: Option<&CloudSettings>, stored_client_id: &str) -> bool {
308 match discovered {
309 Some(s) => !stored_client_id.is_empty() && s.cognito.client_id != stored_client_id,
310 None => false,
311 }
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317
318 const DOC: &str = r#"{
319 "version": 1,
320 "api": "https://muxbus.agentmux.ai",
321 "ws": "wss://muxbus-ws.agentmux.ai",
322 "console": "https://cloud.agentmux.ai",
323 "cognito": { "domain": "https://auth.agentmux.ai", "clientId": "abc123", "region": "us-east-1", "userPoolId": "us-east-1_X" },
324 "someFutureField": true
325 }"#;
326
327 const BASE: &str = "https://muxbus.agentmux.ai";
329
330 #[test]
331 fn a_version_1_document_parses_and_ignores_unknown_fields() {
332 let s = parse(DOC, BASE).unwrap();
333 assert_eq!(s.ws, "wss://muxbus-ws.agentmux.ai");
334 assert_eq!(s.cognito.client_id, "abc123");
335 assert_eq!(s.cognito.user_pool_id, "us-east-1_X");
336 assert!(s.cognito.identity_providers.is_empty(), "an older document has no provider list");
337 }
338
339 #[test]
340 fn the_published_identity_providers_parse() {
341 let doc = DOC.replace("\"region\"", "\"identityProviders\": [\"Google\", \"SignInWithApple\"], \"region\"");
342 let s = parse(&doc, BASE).unwrap();
343 assert_eq!(s.cognito.identity_providers, vec!["Google", "SignInWithApple"]);
344 }
345
346 #[test]
347 fn a_sign_in_provider_must_be_known_and_published() {
348 let old = parse(DOC, BASE).unwrap();
349 let google_only = parse(
350 &DOC.replace("\"region\"", "\"identityProviders\": [\"Google\"], \"region\""),
351 BASE,
352 )
353 .unwrap();
354 assert_eq!(check_identity_provider(Some(&google_only), None), Ok(None));
355 assert_eq!(check_identity_provider(Some(&google_only), Some("Google")), Ok(Some("Google".to_string())));
356 assert!(check_identity_provider(Some(&google_only), Some("SignInWithApple")).is_err(), "not published");
357 assert!(check_identity_provider(Some(&old), Some("SignInWithApple")).is_ok());
359 assert!(check_identity_provider(None, Some("Google")).is_ok());
360 assert!(check_identity_provider(None, Some("Facebook")).is_err());
361 assert!(check_identity_provider(None, Some("Google&prompt=none")).is_err());
362 assert!(check_identity_provider(None, Some("")).is_err());
363 }
364
365 #[test]
366 fn other_versions_and_incomplete_documents_are_ignored() {
367 let base = BASE;
368 assert!(parse(&DOC.replace("\"version\": 1", "\"version\": 2"), base).is_none());
369 assert!(parse(&DOC.replace("\"clientId\": \"abc123\"", "\"clientId\": \"\""), base).is_none());
370 assert!(parse(r#"{"version":1,"api":"https://a","ws":"wss://b"}"#, base).is_none());
371 assert!(parse("not json", base).is_none());
372 }
373
374 #[test]
375 fn insecure_urls_are_refused_except_from_a_local_dev_relay() {
376 let plain = DOC.replace("wss://muxbus-ws", "ws://muxbus-ws");
377 assert!(parse(&plain, BASE).is_none());
378 assert!(parse(&plain, "http://localhost:3100").is_some());
379 let plain_auth = DOC.replace("https://auth.agentmux.ai", "http://auth.agentmux.ai");
380 assert!(parse(&plain_auth, BASE).is_none());
381 }
382
383 #[test]
384 fn login_uses_the_published_pair_else_the_builds_else_errors() {
385 let s = parse(DOC, BASE).unwrap();
386 assert_eq!(
387 resolve_login(Some(&s), "https://compiled", "compiled-id").unwrap(),
388 ("https://auth.agentmux.ai".to_string(), "abc123".to_string())
389 );
390 assert_eq!(
391 resolve_login(None, "https://compiled", "compiled-id").unwrap(),
392 ("https://compiled".to_string(), "compiled-id".to_string())
393 );
394 assert!(resolve_login(None, "https://compiled", "").is_err());
395 assert!(resolve_login(None, "", "compiled-id").is_err(), "half a pair is no pair");
396 assert!(resolve_login(None, "", "").is_err());
397 }
398
399 #[test]
400 fn a_sign_in_from_another_client_is_superseded_only_when_the_cloud_says_so() {
401 let s = parse(DOC, BASE).unwrap();
402 assert!(client_id_superseded(Some(&s), "old-client"));
403 assert!(!client_id_superseded(Some(&s), "abc123"));
404 assert!(!client_id_superseded(None, "old-client"), "no document: can't tell");
405 assert!(!client_id_superseded(Some(&s), ""), "no recorded client id: can't tell");
406 }
407
408 #[test]
409 fn the_host_lists_are_pinned() {
410 assert_eq!(
412 PRODUCTION_HOSTS,
413 ["auth.agentmux.ai", "cloud.agentmux.ai", "muxbus.agentmux.ai", "muxbus-ws.agentmux.ai", "auth.muxbus.agentmux.ai"]
414 );
415 assert_eq!(
416 STAGING_HOSTS,
417 [
418 "auth.staging.agentmux.ai",
419 "cloud.staging.agentmux.ai",
420 "muxbus.staging.agentmux.ai",
421 "muxbus-ws.staging.agentmux.ai"
422 ]
423 );
424 }
425
426 #[test]
427 fn every_listed_host_is_accepted_in_every_field_it_may_be_published_in() {
428 for host in PRODUCTION_HOSTS {
429 let doc = DOC
430 .replace("https://muxbus.agentmux.ai", &format!("https://{host}"))
431 .replace("wss://muxbus-ws.agentmux.ai", &format!("wss://{host}"))
432 .replace("https://cloud.agentmux.ai", &format!("https://{host}"))
433 .replace("https://auth.agentmux.ai", &format!("https://{host}"));
434 assert!(parse(&doc, BASE).is_some(), "{host}");
435 }
436 }
437
438 #[test]
439 fn a_document_naming_another_host_in_any_field_is_refused() {
440 let other = "other.example.test";
441 for (field, doc) in [
442 ("api", DOC.replace("https://muxbus.agentmux.ai", &format!("https://{other}"))),
443 ("ws", DOC.replace("wss://muxbus-ws.agentmux.ai", &format!("wss://{other}"))),
444 ("console", DOC.replace("https://cloud.agentmux.ai", &format!("https://{other}"))),
445 ("cognito.domain", DOC.replace("https://auth.agentmux.ai", &format!("https://{other}"))),
446 ] {
447 assert!(parse(&doc, BASE).is_none(), "{field}");
448 let why = check(&doc, BASE).unwrap_err();
449 assert!(why.starts_with(field) && !why.contains(other), "the reason names the field, not the host: {why}");
450 }
451 }
452
453 #[test]
454 fn a_host_is_matched_exactly_not_by_its_suffix_and_without_credentials_or_a_port() {
455 for bad in [
456 "https://evil.auth.agentmux.ai",
457 "https://auth.agentmux.ai.evil.test",
458 "https://agentmux.ai",
459 "https://xauth.agentmux.ai",
460 "https://auth.agentmux.ai@evil.test",
461 "https://evil.test@auth.agentmux.ai",
462 "https://auth.agentmux.ai:8443",
463 "https://auth.staging.agentmux.ai",
464 "https://auth.agentmux.ai.",
465 ] {
466 let doc = DOC.replace("https://auth.agentmux.ai", bad);
467 assert!(parse(&doc, BASE).is_none(), "{bad}");
468 }
469 assert!(parse(&DOC.replace("https://auth.agentmux.ai", "https://AUTH.AgentMux.ai/login"), BASE).is_some());
471 assert!(parse(&DOC.replace("https://auth.agentmux.ai", "https://auth.agentmux.ai:443"), BASE).is_some());
472 }
473
474 #[test]
475 fn the_list_is_chosen_by_the_base_the_document_came_from() {
476 let staging = DOC.replace(".agentmux.ai", ".staging.agentmux.ai");
477 assert!(parse(&staging, "https://muxbus.staging.agentmux.ai").is_some());
479 assert!(parse(&staging, BASE).is_none());
480 assert!(parse(DOC, "https://muxbus.staging.agentmux.ai").is_none());
481 assert!(parse(DOC, "https://cloud.agentmux.ai").is_some());
483 assert!(parse(&staging, "https://cloud.staging.agentmux.ai").is_some());
484 assert!(parse(DOC, "https://cloud.staging.agentmux.ai").is_none());
485 assert!(parse(&staging, "https://cloud.agentmux.ai").is_none());
486 assert!(parse(&DOC.replace("https://auth.agentmux.ai", "http://127.0.0.1:9000"), "http://localhost:3100").is_some());
488 let own = "https://relay.example.test";
490 assert!(parse(&DOC.replace("https://muxbus.agentmux.ai", own), own).is_some());
491 assert!(parse(&DOC.replace("https://muxbus.agentmux.ai", "https://other.example.test"), own).is_none());
492 assert!(parse(&DOC.replace("https://auth.agentmux.ai", "https://auth.example.test"), own).is_none());
493 }
494
495 #[test]
496 fn a_sign_in_never_starts_at_a_host_that_is_not_the_documents_to_name() {
497 let mut s = parse(DOC, BASE).unwrap();
499 s.cognito.domain = "https://other.example.test".to_string();
500 assert_eq!(
501 resolve_login(Some(&s), "https://compiled", "compiled-id").unwrap(),
502 ("https://compiled".to_string(), "compiled-id".to_string()),
503 "the compiled pair keeps working"
504 );
505 }
506
507 async fn fake_relay(status: &'static str, body: String) -> String {
509 use tokio::io::{AsyncReadExt, AsyncWriteExt};
510 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
511 let addr = listener.local_addr().unwrap();
512 tokio::spawn(async move {
513 while let Ok((mut stream, _)) = listener.accept().await {
514 let body = body.clone();
515 tokio::spawn(async move {
516 let mut buf = [0u8; 2048];
517 let _ = stream.read(&mut buf).await;
518 let resp = format!(
519 "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
520 body.len()
521 );
522 let _ = stream.write_all(resp.as_bytes()).await;
523 });
524 }
525 });
526 format!("http://{addr}")
527 }
528
529 #[tokio::test]
530 async fn a_relay_serving_the_document_is_discovered() {
531 let base = fake_relay("200 OK", DOC.to_string()).await;
532 let s = fetch(&reqwest::Client::new(), &base).await.expect("document served");
533 assert_eq!(s.cognito.client_id, "abc123");
534 }
535
536 #[tokio::test]
537 async fn an_unreachable_relay_or_one_without_the_document_is_not_discovered() {
538 let http = reqwest::Client::new();
539 assert!(fetch(&http, "http://127.0.0.1:1").await.is_none());
541 let base = fake_relay("404 Not Found", "{}".to_string()).await;
542 assert!(fetch(&http, &base).await.is_none());
543 let base = fake_relay("200 OK", DOC.replace("\"version\": 1", "\"version\": 2")).await;
544 assert!(fetch(&http, &base).await.is_none());
545 }
546
547 #[test]
548 fn a_failed_fetch_keeps_the_last_good_document() {
549 let old = parse(DOC, BASE).unwrap();
550 let new = parse(&DOC.replace("abc123", "def456"), BASE).unwrap();
551 assert_eq!(keep_last_good(Some(&old), None), Some(old.clone()));
552 assert_eq!(keep_last_good(Some(&old), Some(new.clone())), Some(new));
553 assert_eq!(keep_last_good(None, None), None);
554 }
555}