1use super::discovery::CloudSettings;
19use super::pkce::{refresh_token, RefreshTokenError};
20use crate::backend::storage::muxbus::MuxBusCredentials;
21
22fn trimmed(host: &str) -> &str {
23 host.trim_end_matches('/')
24}
25
26pub fn host_to_adopt(discovered: Option<&CloudSettings>, current: &MuxBusCredentials) -> Option<String> {
29 let published = discovered?;
30 let (host, stored) = (trimmed(&published.cognito.domain), trimmed(¤t.cognito_domain));
31 let same_client = !current.client_id.is_empty() && published.cognito.client_id == current.client_id;
32 let adopt = same_client && !host.is_empty() && !host.eq_ignore_ascii_case(stored) && published.allows_host_of(host);
33 adopt.then(|| host.to_string())
34}
35
36const DISCOVERED_HOST_PATIENCE: std::time::Duration = std::time::Duration::from_secs(15);
39
40pub async fn refresh(current: &MuxBusCredentials, discovered: Option<&CloudSettings>, http: &reqwest::Client) -> Result<MuxBusCredentials, RefreshTokenError> {
43 refresh_within(current, discovered, http, DISCOVERED_HOST_PATIENCE).await
44}
45
46async fn refresh_within(current: &MuxBusCredentials, discovered: Option<&CloudSettings>, http: &reqwest::Client, patience: std::time::Duration) -> Result<MuxBusCredentials, RefreshTokenError> {
47 if let Some(host) = host_to_adopt(discovered, current) {
48 let moved = MuxBusCredentials { cognito_domain: host.clone(), ..current.clone() };
49 match tokio::time::timeout(patience, refresh_token(&moved, http)).await {
50 Ok(Ok(refreshed)) => {
51 tracing::info!(from = %current.cognito_domain, to = %host, "cloud sign-in: refreshed on the host discovery names; it is the stored host now");
52 return Ok(refreshed);
53 }
54 Ok(Err(e)) => tracing::info!(discovered = %host, stored = %current.cognito_domain, error = %e, "cloud sign-in: the discovered host did not refresh; staying on the stored one"),
55 Err(_) => tracing::info!(discovered = %host, stored = %current.cognito_domain, "cloud sign-in: the discovered host did not answer in time; staying on the stored one"),
56 }
57 }
58 refresh_token(current, http).await
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64 use std::sync::atomic::{AtomicUsize, Ordering};
65 use std::sync::Arc;
66
67 const STORED: &str = "https://old-signin.example.test";
68 const DISCOVERED: &str = "https://new-signin.example.test";
69
70 fn creds(domain: &str) -> MuxBusCredentials {
71 MuxBusCredentials {
72 cognito_domain: domain.to_string(),
73 client_id: "client-a".into(),
74 access_token: "old-access".into(),
75 refresh_token: "refresh-1".into(),
76 id_token: "id-1".into(),
77 expires_at: 1,
78 user_email: "a@example.test".into(),
79 user_sub: "sub-1".into(),
80 }
81 }
82
83 fn published(domain: &str, client_id: &str) -> CloudSettings {
84 let doc = format!(
85 r#"{{"version":1,"api":"https://api.example.test","ws":"wss://ws.example.test","cognito":{{"domain":"{domain}","clientId":"{client_id}"}}}}"#
86 );
87 super::super::discovery::parse(&doc, "http://localhost:3100").unwrap()
89 }
90
91 async fn host(status: &'static str) -> (String, Arc<AtomicUsize>) {
93 use tokio::io::{AsyncReadExt, AsyncWriteExt};
94 let hits = Arc::new(AtomicUsize::new(0));
95 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
96 let url = format!("http://{}", listener.local_addr().unwrap());
97 let counted = hits.clone();
98 tokio::spawn(async move {
99 while let Ok((mut stream, _)) = listener.accept().await {
100 let counted = counted.clone();
101 tokio::spawn(async move {
102 let mut buf = [0u8; 4096];
103 let _ = stream.read(&mut buf).await;
104 counted.fetch_add(1, Ordering::SeqCst);
105 let body = if status.starts_with("200") { r#"{"access_token":"new-access","expires_in":3600}"# } else { r#"{"error":"invalid_grant"}"# };
106 let resp = format!("HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
107 let _ = stream.write_all(resp.as_bytes()).await;
108 });
109 }
110 });
111 (url, hits)
112 }
113
114 #[tokio::test]
115 async fn a_refresh_token_is_never_sent_to_a_host_that_is_not_agentmuxs_own() {
116 let (old, old_hits) = host("200 OK").await;
117 let (other, other_hits) = host("200 OK").await;
118 let mut production = super::super::discovery::parse(
119 r#"{"version":1,"api":"https://muxbus.agentmux.ai","ws":"wss://muxbus-ws.agentmux.ai","cognito":{"domain":"https://auth.agentmux.ai","clientId":"client-a"}}"#,
120 "https://muxbus.agentmux.ai",
121 )
122 .unwrap();
123 assert_eq!(host_to_adopt(Some(&production), &creds(&old)), Some("https://auth.agentmux.ai".to_string()), "a listed host is adopted");
124 production.cognito.domain = other.clone();
126 assert_eq!(host_to_adopt(Some(&production), &creds(&old)), None, "a host that is not on the list is never adopted");
127 let refreshed = refresh(&creds(&old), Some(&production), &reqwest::Client::new()).await.unwrap();
128 assert_eq!(refreshed.cognito_domain, old);
129 assert_eq!((old_hits.load(Ordering::SeqCst), other_hits.load(Ordering::SeqCst)), (1, 0), "the refresh token went to the stored host only");
130 }
131
132 #[test]
133 fn a_host_is_adopted_only_for_the_client_the_sign_in_was_issued_to_and_only_when_it_differs() {
134 let current = creds(STORED);
135 assert_eq!(host_to_adopt(Some(&published(DISCOVERED, "client-a")), ¤t), Some(DISCOVERED.to_string()));
136 assert_eq!(host_to_adopt(Some(&published("https://new-signin.example.test/", "client-a")), ¤t), Some(DISCOVERED.to_string()), "a trailing slash is not part of the host");
137 assert_eq!(host_to_adopt(Some(&published(STORED, "client-a")), ¤t), None, "already there");
138 assert_eq!(host_to_adopt(Some(&published("https://OLD-signin.example.test/", "client-a")), ¤t), None, "the same host in other letters");
139 assert_eq!(host_to_adopt(Some(&published(DISCOVERED, "client-b")), ¤t), None, "another client is another pool");
140 assert_eq!(host_to_adopt(Some(&published(DISCOVERED, "client-a")), &MuxBusCredentials { client_id: String::new(), ..current.clone() }), None, "no recorded client id: can't tell");
141 assert_eq!(host_to_adopt(None, ¤t), None, "no document: nothing to follow");
142 }
143
144 #[tokio::test]
145 async fn a_refresh_that_works_on_the_discovered_host_makes_it_the_stored_one() {
146 let (old, old_hits) = host("200 OK").await;
147 let (new, new_hits) = host("200 OK").await;
148 let refreshed = refresh(&creds(&old), Some(&published(&new, "client-a")), &reqwest::Client::new()).await.unwrap();
149 assert_eq!(refreshed.cognito_domain, new);
150 assert_eq!((refreshed.access_token.as_str(), refreshed.refresh_token.as_str(), refreshed.user_sub.as_str()), ("new-access", "refresh-1", "sub-1"));
151 assert_eq!((old_hits.load(Ordering::SeqCst), new_hits.load(Ordering::SeqCst)), (0, 1), "one call, to the new host");
152 }
153
154 #[tokio::test]
155 async fn a_discovered_host_that_fails_leaves_the_stored_one_working() {
156 for failing in ["400 Bad Request", "500 Internal Server Error", "502 Bad Gateway", "429 Too Many Requests"] {
157 let (old, old_hits) = host("200 OK").await;
158 let (new, new_hits) = host(failing).await;
159 let refreshed = refresh(&creds(&old), Some(&published(&new, "client-a")), &reqwest::Client::new()).await.unwrap();
160 assert_eq!(refreshed.cognito_domain, old, "{failing}: still the stored host");
161 assert_eq!(refreshed.access_token, "new-access");
162 assert_eq!((old_hits.load(Ordering::SeqCst), new_hits.load(Ordering::SeqCst)), (1, 1), "{failing}");
163 }
164 let (old, _) = host("200 OK").await;
166 let refreshed = refresh(&creds(&old), Some(&published("http://127.0.0.1:1", "client-a")), &reqwest::Client::new()).await.unwrap();
167 assert_eq!(refreshed.cognito_domain, old);
168 }
169
170 #[tokio::test]
171 async fn a_discovered_host_that_never_answers_does_not_hold_the_refresh() {
172 let silent = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
174 let silent_url = format!("http://{}", silent.local_addr().unwrap());
175 let _held = tokio::spawn(async move {
176 let mut open = Vec::new();
177 while let Ok((stream, _)) = silent.accept().await {
178 open.push(stream);
179 }
180 });
181 let (old, old_hits) = host("200 OK").await;
182 let refreshed = refresh_within(&creds(&old), Some(&published(&silent_url, "client-a")), &reqwest::Client::new(), std::time::Duration::from_millis(300)).await.unwrap();
183 assert_eq!(refreshed.cognito_domain, old, "the stored host answered once the discovered one ran out of time");
184 assert_eq!(old_hits.load(Ordering::SeqCst), 1);
185 }
186
187 #[tokio::test]
188 async fn when_neither_host_works_the_error_is_the_stored_hosts() {
189 let (old, _) = host("400 Bad Request").await;
190 let (new, _) = host("500 Internal Server Error").await;
191 let err = refresh(&creds(&old), Some(&published(&new, "client-a")), &reqwest::Client::new()).await.unwrap_err();
192 assert!(matches!(err, RefreshTokenError::Rejected { status: 400, .. }), "{err:?}");
193 let err = refresh(&creds("http://127.0.0.1:1"), Some(&published("http://127.0.0.1:2", "client-a")), &reqwest::Client::new()).await.unwrap_err();
194 assert!(matches!(err, RefreshTokenError::Network(_)), "a discovered host that is down does not turn an unreachable one into a rejection: {err:?}");
195 }
196
197 #[tokio::test]
198 async fn without_a_host_to_adopt_only_the_stored_host_is_called() {
199 let (old, old_hits) = host("200 OK").await;
200 let (other, other_hits) = host("200 OK").await;
201 let http = reqwest::Client::new();
202 refresh(&creds(&old), None, &http).await.unwrap();
203 refresh(&creds(&old), Some(&published(&old, "client-a")), &http).await.unwrap();
204 refresh(&creds(&old), Some(&published(&other, "client-b")), &http).await.unwrap();
205 assert_eq!((old_hits.load(Ordering::SeqCst), other_hits.load(Ordering::SeqCst)), (3, 0));
206 }
207
208 #[tokio::test]
209 async fn an_install_signed_in_on_the_old_host_keeps_working_through_each_phase_of_the_move() {
210 let (old, old_hits) = host("200 OK").await;
213 let http = reqwest::Client::new();
214 let mut stored = creds(&old);
215 refresh(&stored, Some(&published(&old, "client-a")), &http).await.unwrap();
216 let refreshed = refresh(&stored, Some(&published("http://127.0.0.1:1", "client-a")), &http).await.unwrap();
217 assert_eq!(refreshed.cognito_domain, old, "the new name does not exist yet");
218 let (new, _) = host("200 OK").await;
219 stored = refresh(&stored, Some(&published(&new, "client-a")), &http).await.unwrap();
220 assert_eq!(stored.cognito_domain, new, "the new name works: adopted");
221 assert_eq!(old_hits.load(Ordering::SeqCst), 2, "the old host served the first two refreshes; the third went to the new one");
222 let again = refresh(&stored, Some(&published(&new, "client-a")), &http).await.unwrap();
224 assert_eq!(again.cognito_domain, new);
225 }
226}