1use std::collections::HashMap;
22use std::sync::{Mutex, MutexGuard, OnceLock};
23use std::time::Duration;
24
25use axum::extract::State;
26use axum::http::StatusCode;
27use axum::response::{IntoResponse, Response};
28use axum::{Extension, Json};
29use serde::Deserialize;
30use serde_json::json;
31
32use super::{calling_agent, error, google_accounts, supported_level, SERVICES};
33use crate::backend::google::access;
34use crate::backend::google::Service;
35use crate::backend::storage::google_grants::{GoogleCall, GrantLevel};
36use crate::backend::storage::store::Store;
37use crate::identity::oauth_client::{self, FlowTarget, OAuthStatus, StartOptions};
38use crate::server::caller::Caller;
39use crate::server::AppState;
40
41const URL_WAIT: Duration = Duration::from_secs(5);
43const MAX_STATUS_WAIT_SECS: u64 = 25;
45const POLL_EVERY: Duration = Duration::from_millis(100);
47const RECORD_POLL_EVERY: Duration = Duration::from_millis(500);
49
50fn owners() -> MutexGuard<'static, HashMap<String, String>> {
52 static OWNERS: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
53 OWNERS.get_or_init(Mutex::default).lock().unwrap_or_else(|e| e.into_inner())
54}
55
56const GOOGLE_ORIGINS: [&str; 3] = ["*.google.com", "*.gstatic.com", "*.googleusercontent.com"];
58
59#[derive(Debug, Deserialize)]
60pub(crate) struct ConnectBody {
61 #[serde(default)]
63 services: Vec<String>,
64 #[serde(default)]
66 level: Option<String>,
67 #[serde(default)]
69 login_hint: Option<String>,
70 #[serde(default)]
72 account: Option<String>,
73}
74
75#[derive(Debug, Deserialize)]
76pub(crate) struct SessionBody {
77 session: String,
78 #[serde(default)]
80 wait_seconds: Option<u64>,
81}
82
83pub(crate) fn union_scopes(services: &[Service], level: GrantLevel, held: &[String]) -> Vec<String> {
87 let mut out: Vec<String> = held.to_vec();
88 for service in services {
89 for scope in service.scopes(level) {
90 if !out.contains(&scope) {
91 out.push(scope);
92 }
93 }
94 }
95 out
96}
97
98pub(crate) fn pane_origins(auth_url: &str) -> Vec<String> {
101 let mut out: Vec<String> = GOOGLE_ORIGINS.iter().map(|s| s.to_string()).collect();
102 if let Ok(url) = url::Url::parse(auth_url) {
103 let redirect = url.query_pairs().find(|(k, _)| k == "redirect_uri").map(|(_, v)| v.into_owned());
104 if let Some(origin) = redirect.and_then(|r| url::Url::parse(&r).ok()).and_then(|r| agentmux_common::url_guard::origin_string(&r)) {
105 out.push(origin);
106 }
107 }
108 out
109}
110
111fn parse_services(names: &[String]) -> Result<Vec<Service>, String> {
112 if names.is_empty() {
113 return Err("services is required: calendar, drive and/or gmail".to_string());
114 }
115 let mut out = Vec::new();
116 for name in names {
117 let service = SERVICES
118 .into_iter()
119 .find(|s| s.as_str() == name.trim().to_ascii_lowercase())
120 .ok_or_else(|| format!("service \"{}\": calendar, drive or gmail", name.trim()))?;
121 if !out.contains(&service) {
122 out.push(service);
123 }
124 }
125 Ok(out)
126}
127
128fn starting() -> MutexGuard<'static, std::collections::HashSet<String>> {
131 static STARTING: OnceLock<Mutex<std::collections::HashSet<String>>> = OnceLock::new();
132 STARTING.get_or_init(Mutex::default).lock().unwrap_or_else(|e| e.into_inner())
133}
134
135#[derive(Debug)]
137struct StartSlot(String);
138
139impl StartSlot {
140 fn take(agent_id: &str) -> Result<StartSlot, String> {
142 let mut starting = starting();
143 if starting.contains(agent_id) {
144 return Err("a connect of yours is just starting: wait for it, then use connect_status".to_string());
145 }
146 if let Some(sid) = waiting_session_of(agent_id) {
147 return Err(format!(
148 "a connect is already waiting for the person (session {sid}): finish it with connect_status, or end it with cancel, before starting another"
149 ));
150 }
151 starting.insert(agent_id.to_string());
152 Ok(StartSlot(agent_id.to_string()))
153 }
154}
155
156impl Drop for StartSlot {
157 fn drop(&mut self) {
158 starting().remove(&self.0);
159 }
160}
161
162fn waiting_session_of(agent_id: &str) -> Option<String> {
164 let mine: Vec<String> = owners().iter().filter(|(_, a)| a.as_str() == agent_id).map(|(s, _)| s.clone()).collect();
165 mine.into_iter().find(|sid| oauth_client::manager().poll(sid).is_some_and(|s| !s.is_terminal()))
166}
167
168pub(crate) async fn handle_google_connect(
170 State(state): State<AppState>,
171 caller: Option<Extension<Caller>>,
172 Json(body): Json<ConnectBody>,
173) -> Response {
174 let actor = match calling_agent(&state, caller.as_deref()) {
175 Ok(d) => d,
176 Err(e) => return error(StatusCode::FORBIDDEN, e),
177 };
178 match start_connect(&state, &actor.id, &actor.name, &body).await {
179 Ok(v) => Json(v).into_response(),
180 Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
181 }
182}
183
184async fn start_connect(state: &AppState, agent_id: &str, agent_name: &str, body: &ConnectBody) -> Result<serde_json::Value, String> {
185 let services = parse_services(&body.services)?;
186 let level = GrantLevel::parse(body.level.as_deref().unwrap_or("read"))?.ok_or("level: read or write")?;
187 let _slot = StartSlot::take(agent_id)?;
188 let (target, held) = match body.account.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
189 None => (FlowTarget::New { name: String::new() }, Vec::new()),
190 Some(email) => {
191 let account = google_accounts(state)?
192 .into_iter()
193 .find(|a| access::email_of(a).eq_ignore_ascii_case(email))
194 .ok_or_else(|| format!("no connected Google account {email}: leave account out to connect a new one"))?;
195 let held = access::granted_scopes_of(&account);
196 (FlowTarget::Existing(account), held)
197 }
198 };
199 let saved = tokio::task::spawn_blocking(|| crate::identity::oauth_tokens::load_saved_client("google"))
202 .await
203 .map_err(|e| format!("keychain task: {e}"))
204 .and_then(|r| r)
205 .unwrap_or_else(|e| {
206 tracing::warn!(target: "google", error = %e, "google connect: the saved OAuth client could not be read");
207 None
208 });
209 let opts = StartOptions {
210 target,
211 byo: None,
212 saved,
213 extra_scopes: union_scopes(&services, level, &held),
214 save_client: false,
215 cloud_signed_in: false,
216 replace_user: false,
217 open_system_browser: false,
218 login_hint: body.login_hint.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string),
219 };
220 let (session, _placeholder) = oauth_client::start("google", opts, state.id_store.clone(), state.identity_store.clone())?;
221 owners().insert(session.clone(), agent_id.to_string());
222 tokio::spawn(record_when_connected(state.identity_store.clone(), session.clone(), agent_id.to_string(), agent_name.to_string()));
223 let status = wait_for(&session, URL_WAIT, url_ready).await;
225 match status {
226 OAuthStatus::UrlAvailable { auth_url } => {
227 tracing::info!(target: "google", agent = %agent_name, session = %session, "google connect started by an agent");
228 let names: Vec<&str> = services.iter().map(|s| s.as_str()).collect();
229 Ok(json!({
230 "session": session,
231 "auth_url": auth_url,
232 "allowed_origins": pane_origins(&auth_url),
233 "services": names,
234 "level": level.as_str(),
235 }))
236 }
237 OAuthStatus::Failed { error } => {
238 owners().remove(&session);
239 Err(error)
240 }
241 _ => {
242 oauth_client::manager().cancel(&session);
243 owners().remove(&session);
244 Err("the sign-in did not start: try connect again".to_string())
245 }
246 }
247}
248
249fn url_ready(status: &OAuthStatus) -> bool {
252 match status {
253 OAuthStatus::Pending => false,
254 OAuthStatus::UrlAvailable { auth_url } => !auth_url.is_empty(),
255 _ => true,
256 }
257}
258
259async fn record_when_connected(store: std::sync::Arc<Store>, session: String, agent_id: String, agent_name: String) {
262 loop {
263 match oauth_client::manager().poll(&session) {
264 Some(OAuthStatus::Success { account_id, granted_scopes, .. }) => {
265 record_connect(&store, &agent_id, &agent_name, &account_id, &granted_scopes);
266 return;
267 }
268 Some(status) if !status.is_terminal() => tokio::time::sleep(RECORD_POLL_EVERY).await,
269 _ => return,
270 }
271 }
272}
273
274async fn wait_for(session: &str, wait: Duration, done: impl Fn(&OAuthStatus) -> bool) -> OAuthStatus {
276 let deadline = tokio::time::Instant::now() + wait;
277 loop {
278 let Some(status) = oauth_client::manager().poll(session) else {
279 return OAuthStatus::Failed { error: "that connect is gone (it timed out or was cancelled)".to_string() };
280 };
281 if done(&status) || tokio::time::Instant::now() >= deadline {
282 return status;
283 }
284 tokio::time::sleep(POLL_EVERY).await;
285 }
286}
287
288pub(crate) async fn handle_google_connect_status(
290 State(state): State<AppState>,
291 caller: Option<Extension<Caller>>,
292 Json(body): Json<SessionBody>,
293) -> Response {
294 let actor = match calling_agent(&state, caller.as_deref()) {
295 Ok(d) => d,
296 Err(e) => return error(StatusCode::FORBIDDEN, e),
297 };
298 if let Err(e) = owns(&actor.id, &body.session) {
299 return error(StatusCode::UNPROCESSABLE_ENTITY, e);
300 }
301 let wait = Duration::from_secs(body.wait_seconds.unwrap_or(0).min(MAX_STATUS_WAIT_SECS));
302 let status = wait_for(&body.session, wait, |s| !matches!(s, OAuthStatus::Pending | OAuthStatus::UrlAvailable { .. })).await;
303 let answer = status_answer(&state, &body.session, &status);
304 if !matches!(status, OAuthStatus::Pending | OAuthStatus::UrlAvailable { .. }) {
305 owners().remove(&body.session);
306 }
307 Json(answer).into_response()
308}
309
310fn owns(agent_id: &str, session: &str) -> Result<(), String> {
311 match owners().get(session) {
312 Some(owner) if owner == agent_id => Ok(()),
313 Some(_) => Err("that connect was started by another agent".to_string()),
314 None => Err("no connect with that session: it ended, or it was never started here".to_string()),
315 }
316}
317
318fn status_answer(state: &AppState, session: &str, status: &OAuthStatus) -> serde_json::Value {
319 match status {
320 OAuthStatus::Pending | OAuthStatus::UrlAvailable { .. } => json!({
321 "session": session,
322 "state": "waiting",
323 "say": "Waiting for the sign-in to finish in the pane. If the page asks for a password, a code or an administrator's approval, \
324 hand the pane to the person (Browser handoff) and say what to do; then ask again."
325 }),
326 OAuthStatus::Success { account_id, missing_scopes, email, .. } => {
327 let services = connected_services(state, account_id);
328 json!({
329 "session": session,
330 "state": "connected",
331 "account": email,
332 "services": services,
333 "missing_scopes": missing_scopes,
334 "say": if missing_scopes.is_empty() { "Connected." } else { "Connected, but some permissions were left unticked on the consent screen: they are in missing_scopes. Connect again to ask for them." },
335 })
336 }
337 OAuthStatus::Failed { error } => json!({ "session": session, "state": "failed", "error": error }),
338 _ => json!({ "session": session, "state": "failed", "error": "the sign-in ended in a state a Google connect never reaches" }),
339 }
340}
341
342fn connected_services(state: &AppState, account_id: &str) -> serde_json::Value {
344 let Ok(accounts) = google_accounts(state) else { return json!({}) };
345 let Some(account) = accounts.iter().find(|a| a.id == account_id) else { return json!({}) };
346 let mut out = serde_json::Map::new();
347 for service in SERVICES {
348 out.insert(service.as_str().to_string(), json!(supported_level(account, service)));
349 }
350 serde_json::Value::Object(out)
351}
352
353fn record_connect(store: &Store, agent_id: &str, agent_name: &str, account_id: &str, granted: &[String]) {
355 let line = GoogleCall {
356 at: chrono::Utc::now().timestamp_millis(),
357 agent_id: agent_id.to_string(),
358 agent_name: agent_name.to_string(),
359 service: "account".to_string(),
360 action: "connect".to_string(),
361 ids: format!("{} scopes", granted.len()),
362 outcome: "ok".to_string(),
363 };
364 if let Err(e) = store.google_call_log(account_id, &line) {
365 tracing::warn!(target: "google", error = %e, "google: logging a connect failed");
366 }
367 tracing::info!(target: "google", account_id = %account_id, by = %agent_name, "google: account connected by an agent");
368}
369
370pub(crate) async fn handle_google_connect_cancel(
372 State(state): State<AppState>,
373 caller: Option<Extension<Caller>>,
374 Json(body): Json<SessionBody>,
375) -> Response {
376 let actor = match calling_agent(&state, caller.as_deref()) {
377 Ok(d) => d,
378 Err(e) => return error(StatusCode::FORBIDDEN, e),
379 };
380 if let Err(e) = owns(&actor.id, &body.session) {
381 return error(StatusCode::UNPROCESSABLE_ENTITY, e);
382 }
383 let cancelled = oauth_client::manager().cancel(&body.session);
384 if cancelled {
387 owners().remove(&body.session);
388 }
389 Json(json!({ "session": body.session, "cancelled": cancelled })).into_response()
390}
391
392#[cfg(test)]
393#[path = "google_connect_tests.rs"]
394mod tests;