Skip to main content

agentmux_srv/server/
google_connect.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! `Google` `connect`, `connect_status` and `cancel`: an agent connects a Google account itself
5//! (docs/specs/SPEC_GOOGLE_PHASE_B_AGENTMUXS_OWN_CLIENT_2026_11_01.md §7, §9, D3). It runs the
6//! same flow as the Accounts panel's Connect (`oauth_client::start`), so the two can't drift,
7//! except that the consent page is not opened in the system browser: the agent opens it in a
8//! Browser pane it drives (the account picker, the unverified-app screen, the scope boxes), and
9//! stops for the person only at a password, a second factor or an administrator's block.
10//!
11//! - `POST /api/v1/google/connect`: start the flow; answers the consent URL and the origins its
12//!   pane may stay on.
13//! - `POST /api/v1/google/connect/status`: where the flow is (waiting for the person, connected,
14//!   failed); it may wait a few seconds for a change.
15//! - `POST /api/v1/google/connect/cancel`: end a flow that waits.
16//!
17//! The token never reaches the agent: it goes from Google to the keychain inside srv. A session
18//! belongs to the agent that started it. Every connect is recorded under that agent, in the
19//! account's log once the account exists.
20
21use 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
41/// How long `connect` waits for the flow to produce its consent URL.
42const URL_WAIT: Duration = Duration::from_secs(5);
43/// The most `connect_status` waits for a change in one call.
44const MAX_STATUS_WAIT_SECS: u64 = 25;
45/// How often a waiting call looks at the session again.
46const POLL_EVERY: Duration = Duration::from_millis(100);
47/// How often the task that records a connect looks at its flow.
48const RECORD_POLL_EVERY: Duration = Duration::from_millis(500);
49
50/// The agent that started each flow, by session id: only it may ask after it or cancel it.
51fn 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
56/// The sites a consent pane stays on, beside the page's own loopback callback.
57const GOOGLE_ORIGINS: [&str; 3] = ["*.google.com", "*.gstatic.com", "*.googleusercontent.com"];
58
59#[derive(Debug, Deserialize)]
60pub(crate) struct ConnectBody {
61    /// `calendar`, `drive` and/or `gmail`: what to turn on.
62    #[serde(default)]
63    services: Vec<String>,
64    /// `read` (default) or `write`, for every service named.
65    #[serde(default)]
66    level: Option<String>,
67    /// The Google account to start on (the account picker's `login_hint`).
68    #[serde(default)]
69    login_hint: Option<String>,
70    /// A connected account to authorize again (more services, or a reconnect), by email.
71    #[serde(default)]
72    account: Option<String>,
73}
74
75#[derive(Debug, Deserialize)]
76pub(crate) struct SessionBody {
77    session: String,
78    /// `connect_status`: wait up to this many seconds for the flow to change.
79    #[serde(default)]
80    wait_seconds: Option<u64>,
81}
82
83/// The scopes a connect asks for: the services named at `level`, plus every scope the account
84/// already holds (D3: always the union, whether or not Google carries earlier grants over on an
85/// installed app).
86pub(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
98/// The origins a consent pane may stay on: Google's, and the loopback address Google redirects
99/// to when the person has consented (read from the URL's `redirect_uri`).
100pub(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
128/// The agents whose connect is starting (the keychain read and the flow's first answer are awaits),
129/// so two overlapping requests from one agent can't both pass the one-waiting-connect check.
130fn 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/// An agent's place for one connect, held while it starts; the session in `owners` takes over after.
136#[derive(Debug)]
137struct StartSlot(String);
138
139impl StartSlot {
140    /// Takes the agent's slot, or says why it can't have one (a connect is starting or waiting).
141    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
162/// Whether this agent already has a connect that hasn't ended.
163fn 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
168/// `POST /api/v1/google/connect`.
169pub(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    // The client the Accounts panel would use: the one saved here, else AgentMux's own. A
200    // keychain that can't be read means none, as there.
201    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    // `start` answers a placeholder first (an empty URL); the real consent URL comes from the flow's task.
224    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
249/// Whether a flow has its consent URL (or has ended): not the pending status, and not the empty
250/// URL `start` answers before the flow's task has built the real one.
251fn 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
259/// Records the connect under the agent that started it once its account is committed, whether or
260/// not the agent asks again; the task ends with the flow (success, failure, cancel or timeout).
261async 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
274/// The session's status once `done` holds for it, or the last one seen after `wait`.
275async 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
288/// `POST /api/v1/google/connect/status`.
289pub(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
342/// What each service of the new account can be used for, as `Google status` shows it.
343fn 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
353/// Records the connect under the agent that did it, in the account's log the person reads.
354fn 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
370/// `POST /api/v1/google/connect/cancel`.
371pub(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    // A flow already committing its account can't be cancelled and ends as connected: keep the owner
385    // so connect_status can still report it and log the connect under this agent.
386    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;