Skip to main content

agentmux_srv/server/
google_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The Google connectors' agent routes
5//! (docs/specs/SPEC_GOOGLE_CONNECTORS_GMAIL_CALENDAR_DRIVE_2026_10_14.md D3, D4):
6//!
7//! - `GET /api/v1/google/self/services`: the services the calling agent has a
8//!   grant on, so its MCP lists only those tools.
9//! - `POST /api/v1/google/calendar`: one `Calendar` action.
10//! - `POST /api/v1/google/drive`: one `Drive` action (`pick_files` opens Google's file picker
11//!   for the person).
12//! - `POST /api/v1/google/gmail`: one `Gmail` action.
13//!
14//! Both need an attributed caller (the agent's own `X-Agent-Token`): a grant
15//! belongs to an agent, so a request that names none has none.
16
17use axum::extract::State;
18use axum::http::StatusCode;
19use axum::response::{IntoResponse, Response};
20use axum::{Extension, Json};
21use serde::Deserialize;
22use serde_json::json;
23
24use super::app_api::bundle::SelfOwner;
25use super::caller::Caller;
26use super::AppState;
27use crate::backend::google::calendar::CalendarArgs;
28use crate::backend::google::calls::{calendar_read, drive_read, gmail_read, log_call, CallDeps};
29use crate::backend::google::drive::DriveArgs;
30use crate::backend::google::gmail_flow::{gmail_write, Answer, Approver};
31use crate::backend::google::gmail_write::WRITE_ACTIONS;
32use crate::backend::google::gmail::GmailArgs;
33use crate::backend::google::{access, LiveGoogleHttp, Service};
34use crate::backend::storage::store::AgentDefinition;
35use crate::identity::oauth_tokens::{KeychainSecrets, LiveHttp};
36
37fn error(status: StatusCode, msg: impl Into<String>) -> Response {
38    (status, Json(json!({ "error": msg.into() }))).into_response()
39}
40
41/// The calling agent's definition, or why there is none (answered 403).
42fn calling_agent(state: &AppState, caller: Option<&Caller>) -> Result<AgentDefinition, String> {
43    let Some(uid) = caller.and_then(Caller::uid) else {
44        return Err("the Google tools work only for an agent AgentMux started: this request carried no agent token".to_string());
45    };
46    SelfOwner::caller_row(uid, &state.mstore).map_err(|e| e.to_string())
47}
48
49/// `GET /api/v1/google/self/services`: `{ account, accounts, services: [{ service,
50/// level, account }] }` for the Google accounts the calling agent holds a grant on
51/// (`account` is the first); none when it has none.
52pub(crate) async fn handle_google_self_services(State(state): State<AppState>, caller: Option<Extension<Caller>>) -> Response {
53    let def = match calling_agent(&state, caller.as_deref()) {
54        Ok(d) => d,
55        // An unattributed caller has no grants; it isn't an error to ask.
56        Err(_) => return Json(json!({ "account": null, "services": [] })).into_response(),
57    };
58    match state.identity_store.google_grants_for_agent(&def.id) {
59        Ok(grants) => {
60            // One entry per grant, on whichever account it is (an agent may hold several, D7).
61            let mut accounts: Vec<String> = Vec::new();
62            let mut services = Vec::new();
63            for g in grants {
64                let Ok(Some((acct, _))) =
65                    crate::identity::resolver::resolve_account(&state.id_store, &state.identity_store, &g.account_id)
66                else {
67                    continue;
68                };
69                if acct.provider != "google" {
70                    continue;
71                }
72                let email = access::email_of(&acct);
73                if !accounts.contains(&email) {
74                    accounts.push(email.clone());
75                }
76                services.push(json!({ "service": g.service, "level": g.level, "account": email }));
77            }
78            Json(json!({ "account": accounts.first(), "accounts": accounts, "services": services })).into_response()
79        }
80        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
81    }
82}
83
84#[derive(Debug, Deserialize)]
85pub(crate) struct CalendarBody {
86    action: String,
87    /// The account's email, when the agent names one.
88    #[serde(default)]
89    account: Option<String>,
90    #[serde(flatten)]
91    args: CalendarArgs,
92}
93
94/// `POST /api/v1/google/calendar`: `{ account, result }`, or `{ error }`
95/// with a sentence the agent can act on.
96pub(crate) async fn handle_google_calendar(
97    State(state): State<AppState>,
98    caller: Option<Extension<Caller>>,
99    Json(body): Json<CalendarBody>,
100) -> Response {
101    let def = match calling_agent(&state, caller.as_deref()) {
102        Ok(d) => d,
103        Err(e) => return error(StatusCode::FORBIDDEN, e),
104    };
105    let deps = CallDeps {
106        google: &LiveGoogleHttp,
107        oauth: &LiveHttp,
108        secrets: &KeychainSecrets,
109        mstore: &state.mstore,
110        id_store: &state.id_store,
111        identity_store: &state.identity_store,
112    };
113    match calendar_read(&deps, &def, body.action.trim(), &body.args, body.account.as_deref(), chrono::Utc::now()).await {
114        Ok(v) => Json(v).into_response(),
115        Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
116    }
117}
118
119#[derive(Debug, Deserialize)]
120pub(crate) struct DriveBody {
121    action: String,
122    /// The account's email, when the agent names one.
123    #[serde(default)]
124    account: Option<String>,
125    #[serde(flatten)]
126    args: DriveArgs,
127}
128
129/// `POST /api/v1/google/drive`: `{ account, result }`, or `{ error }` with a sentence the agent
130/// can act on.
131pub(crate) async fn handle_google_drive(
132    State(state): State<AppState>,
133    caller: Option<Extension<Caller>>,
134    Json(body): Json<DriveBody>,
135) -> Response {
136    let def = match calling_agent(&state, caller.as_deref()) {
137        Ok(d) => d,
138        Err(e) => return error(StatusCode::FORBIDDEN, e),
139    };
140    let deps = CallDeps {
141        google: &LiveGoogleHttp,
142        oauth: &LiveHttp,
143        secrets: &KeychainSecrets,
144        mstore: &state.mstore,
145        id_store: &state.id_store,
146        identity_store: &state.identity_store,
147    };
148    let action = body.action.trim();
149    let result = if action == "pick_files" {
150        pick_files(&state, &deps, &def, body.account.as_deref()).await
151    } else {
152        drive_read(&deps, &def, action, &body.args, body.account.as_deref(), chrono::Utc::now()).await
153    };
154    match result {
155        Ok(v) => Json(v).into_response(),
156        Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
157    }
158}
159
160#[derive(Debug, Deserialize)]
161pub(crate) struct GmailBody {
162    action: String,
163    /// The account's email, when the agent names one.
164    #[serde(default)]
165    account: Option<String>,
166    #[serde(flatten)]
167    args: GmailArgs,
168}
169
170/// `POST /api/v1/google/gmail`: `{ account, result }`, or `{ error }` with a sentence the agent
171/// can act on.
172pub(crate) async fn handle_google_gmail(
173    State(state): State<AppState>,
174    caller: Option<Extension<Caller>>,
175    Json(body): Json<GmailBody>,
176) -> Response {
177    let def = match calling_agent(&state, caller.as_deref()) {
178        Ok(d) => d,
179        Err(e) => return error(StatusCode::FORBIDDEN, e),
180    };
181    let deps = CallDeps {
182        google: &LiveGoogleHttp,
183        oauth: &LiveHttp,
184        secrets: &KeychainSecrets,
185        mstore: &state.mstore,
186        id_store: &state.id_store,
187        identity_store: &state.identity_store,
188    };
189    let action = body.action.trim();
190    let result = if WRITE_ACTIONS.contains(&action) {
191        gmail_write(&deps, &HostApprover { state: &state }, &def, action, &body.args, body.account.as_deref(), chrono::Utc::now()).await
192    } else {
193        gmail_read(&deps, &def, action, &body.args, body.account.as_deref(), chrono::Utc::now()).await
194    };
195    match result {
196        Ok(v) => Json(v).into_response(),
197        Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
198    }
199}
200
201/// Tells the person in the agent's own pane that it is about to act, with a countdown that goes ahead
202/// on its own (`agent_notice`): they can stop it, hurry it, or say "Always" for this agent. With no
203/// pane for the agent there is nowhere to tell them and nothing is done.
204struct HostApprover<'a> {
205    state: &'a AppState,
206}
207
208impl Approver for HostApprover<'_> {
209    async fn ask(&self, def: &AgentDefinition, title: String, message: String, _yes: &str, _no: &str) -> Result<Answer, String> {
210        use crate::sagas::agent_notice::{self, Kind, Notice, Outcome};
211        let block = super::app_api::agent_block::find_agent_block_by_uid(&self.state.mstore, &def.id)?
212            .ok_or("you have no pane open to tell the person in, so this can't go ahead")?
213            .block
214            .oid;
215        let notice = Notice {
216            kind: Kind::Google,
217            block_id: block.clone(),
218            agent_id: def.id.clone(),
219            agent: def.name.clone(),
220            connection: String::new(),
221            headline: title,
222            body: message,
223            quote: String::new(),
224            always_label: format!("Always allow {} to do this", super::app_api::connections::one_line(&def.name, 40)),
225            waived: None,
226        };
227        let outcome = agent_notice::announce(self.state, notice, || super::app_api::agent_spawn::requester_here(self.state, &block)).await;
228        Ok(match outcome {
229            Outcome::Go(_) => Answer::Yes,
230            Outcome::Stopped => Answer::No,
231            Outcome::Gone => Answer::Unanswered,
232        })
233    }
234}
235
236/// The least time between two pickers opened for one account by agents, so a loop of
237/// `pick_files` calls can't fill the person's browser with tabs.
238const PICK_GAP: std::time::Duration = std::time::Duration::from_secs(60);
239
240fn last_picks() -> std::sync::MutexGuard<'static, std::collections::HashMap<String, std::time::Instant>> {
241    use std::sync::{Mutex, OnceLock};
242    static LAST: OnceLock<Mutex<std::collections::HashMap<String, std::time::Instant>>> = OnceLock::new();
243    LAST.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner())
244}
245
246/// Take the account's picker slot, or say it was taken a moment ago. The slot is held
247/// from the check, so two calls at once can't both open a picker; [`pick_release`] gives it
248/// back when the picker didn't open.
249fn pick_throttle(account_id: &str, now: std::time::Instant) -> Result<(), String> {
250    let mut last = last_picks();
251    if let Some(at) = last.get(account_id) {
252        if now.saturating_duration_since(*at) < PICK_GAP {
253            return Err("a file picker was opened for this account a moment ago: wait for the person to pick, then search_files".to_string());
254        }
255    }
256    last.insert(account_id.to_string(), now);
257    Ok(())
258}
259
260/// A picker that failed to open doesn't count against the account.
261fn pick_release(account_id: &str) {
262    last_picks().remove(account_id);
263}
264
265/// `pick_files`: open Google's file picker in the person's browser. The agent gets no ids
266/// back: it searches once the person has picked.
267async fn pick_files<G, O, S>(
268    state: &AppState,
269    deps: &CallDeps<'_, G, O, S>,
270    def: &AgentDefinition,
271    account: Option<&str>,
272) -> Result<serde_json::Value, String>
273where
274    G: crate::backend::google::GoogleHttp,
275    O: crate::identity::oauth_tokens::OAuthHttp,
276    S: crate::identity::oauth_tokens::TokenSecrets,
277{
278    let acc = access::access_for(&state.mstore, &state.id_store, &state.identity_store, def, Service::Drive, account)?;
279    let result = match pick_throttle(&acc.account.id, std::time::Instant::now()) {
280        Ok(()) => {
281            let started = start_picker_for(state, &acc.account).await;
282            if started.is_err() {
283                pick_release(&acc.account.id);
284            }
285            started.map(|_| {
286                json!({
287                    "started": true,
288                    "note": "A Google file picker is open in the person's browser. Nothing to wait for here: once they have picked, search_files lists what they gave you."
289                })
290            })
291        }
292        Err(e) => Err(e),
293    };
294    log_call(deps, &acc, def, Service::Drive, "pick_files", String::new(), &result, chrono::Utc::now());
295    result.map(|r| json!({ "account": acc.email(), "result": r }))
296}
297
298/// Start the picker for `account` with the client it was made with; the session id is
299/// polled with `account.oauth.poll`.
300async fn start_picker_for(state: &AppState, account: &crate::backend::storage::store::IdentityAccount) -> Result<String, String> {
301    let client = crate::identity::oauth_client::picker_client(&KeychainSecrets, account).await?;
302    let (session_id, _) = crate::identity::oauth_client::start_picker(
303        account.clone(),
304        client,
305        state.id_store.clone(),
306        state.identity_store.clone(),
307    )?;
308    Ok(session_id)
309}
310
311/// The services a grant can be set on today; the rest come with their stage.
312const BUILT_SERVICES: [&str; 3] = ["calendar", "drive", "gmail"];
313
314/// How many log lines the account panel shows.
315const PANEL_CALLS: usize = 100;
316
317/// `POST /api/v1/host/google`: the account panel's operations, from the host
318/// only. (Agents turn services on and off through `POST /api/v1/google/grant`.)
319/// - `account` `{ account_id }`: the agents bound to it with their levels,
320///   and its call log.
321/// - `set` `{ account_id, agent_id, service, level }`: `read`, `write` or
322///   `off`.
323/// - `pick` `{ account_id }`: open Google's file picker for the person; answers
324///   `{ session_id }` to poll with `account.oauth.poll`.
325pub(crate) async fn handle_host_google(
326    State(state): State<AppState>,
327    headers: axum::http::HeaderMap,
328    Json(body): Json<serde_json::Value>,
329) -> Response {
330    if !super::ui_handlers::from_host(&state, &headers).await {
331        return error(StatusCode::FORBIDDEN, "only the AgentMux host can change who uses a Google account");
332    }
333    let s = |k: &str| body.get(k).and_then(serde_json::Value::as_str).unwrap_or("").trim().to_string();
334    let account_id = s("account_id");
335    if account_id.is_empty() {
336        return error(StatusCode::BAD_REQUEST, "account_id is required");
337    }
338    let result = match s("op").as_str() {
339        "account" => account_panel(&state, &account_id),
340        "set" => set_grant(&state, &account_id, &s("agent_id"), &s("service"), &s("level")),
341        "pick" => pick_for_person(&state, &account_id).await,
342        other => Err(format!("no Google operation \"{other}\"")),
343    };
344    match result {
345        Ok(data) => Json(json!({ "data": data })).into_response(),
346        Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
347    }
348}
349
350async fn pick_for_person(state: &AppState, account_id: &str) -> Result<serde_json::Value, String> {
351    let account = state.id_store.identity_get(account_id).map_err(|e| e.to_string())?.ok_or("no such account")?;
352    let session_id = start_picker_for(state, &account).await?;
353    Ok(json!({ "session_id": session_id }))
354}
355
356fn account_panel(state: &AppState, account_id: &str) -> Result<serde_json::Value, String> {
357    let grants = state.identity_store.google_grants_for_account(account_id).map_err(|e| e.to_string())?;
358    // Agents bound to the account (the window's link, kept for now) and agents holding a grant on it.
359    let defs = state.mstore.agent_def_list().map_err(|e| e.to_string())?;
360    let mut agents = Vec::new();
361    for def in defs {
362        let links = crate::identity::resolver::effective_identity_links(&state.mstore, &state.identity_store, &def)
363            .map_err(|e| e.to_string())?;
364        let bound = links.iter().find(|l| l.provider == "google").map(|l| l.account_id.as_str()) == Some(account_id);
365        // An agent granted without being bound (an agent granted it, or it holds several accounts) is listed too.
366        if !bound && !grants.iter().any(|g| g.agent_id == def.id) {
367            continue;
368        }
369        let levels: serde_json::Map<String, serde_json::Value> =
370            grants.iter().filter(|g| g.agent_id == def.id).map(|g| (g.service.clone(), json!(g.level))).collect();
371        agents.push(json!({ "agentId": def.id, "name": def.name, "levels": levels }));
372    }
373    let calls = state.identity_store.google_calls(account_id, PANEL_CALLS).map_err(|e| e.to_string())?;
374    Ok(json!({ "agents": agents, "calls": calls, "services": BUILT_SERVICES }))
375}
376
377fn set_grant(state: &AppState, account_id: &str, agent_id: &str, service: &str, level: &str) -> Result<serde_json::Value, String> {
378    if !BUILT_SERVICES.contains(&service) {
379        return Err(format!("agents can't use Google's {service} yet"));
380    }
381    let level = crate::backend::storage::google_grants::GrantLevel::parse(level)?;
382    // A grant is all an agent needs; it need not be bound to the account first (spec D7).
383    state.mstore.agent_def_get(agent_id).map_err(|e| e.to_string())?.ok_or("no such agent")?;
384    let now = chrono::Utc::now().timestamp_millis();
385    state.identity_store.google_grant_set(agent_id, account_id, service, level, now).map_err(|e| e.to_string())?;
386    crate::identity::accounts_changed::announce();
387    tracing::info!(
388        target: "google",
389        account_id = %account_id,
390        agent_id = %agent_id,
391        service = %service,
392        level = level.map_or("off", |l| l.as_str()),
393        "google: grant set by the person"
394    );
395    Ok(json!(true))
396}
397
398// ── The `Google` tool: status, grant, ungrant ───────────────────────────────
399
400/// Every Google account on this computer, by email.
401fn google_accounts(state: &AppState) -> Result<Vec<crate::backend::storage::store::IdentityAccount>, String> {
402    let mut seen = std::collections::HashSet::new();
403    let mut out = Vec::new();
404    for store in [&state.id_store, &state.identity_store] {
405        for a in store.identity_list(Some("google")).map_err(|e| e.to_string())? {
406            if seen.insert(a.id.clone()) {
407                out.push(a);
408            }
409        }
410    }
411    out.sort_by_key(|a| access::email_of(a).to_ascii_lowercase());
412    Ok(out)
413}
414
415/// Whether a token supporting `supported` (`write`, `read` or `none`) can back a grant at `level`.
416fn grant_is_backed(level: crate::backend::storage::google_grants::GrantLevel, supported: &str) -> bool {
417    matches!((level, supported), (_, "write") | (crate::backend::storage::google_grants::GrantLevel::Read, "read"))
418}
419
420/// The highest level the account's token supports for `service`, from the scopes it was
421/// granted: `write`, `read` or `none`.
422fn supported_level(account: &crate::backend::storage::store::IdentityAccount, service: Service) -> &'static str {
423    let granted = access::granted_scopes_of(account);
424    let has_all = |level| service.scopes(level).iter().all(|s| granted.contains(s));
425    if has_all(crate::backend::storage::google_grants::GrantLevel::Write) {
426        "write"
427    } else if has_all(crate::backend::storage::google_grants::GrantLevel::Read) {
428        "read"
429    } else {
430        "none"
431    }
432}
433
434const SERVICES: [Service; 3] = [Service::Calendar, Service::Drive, Service::Gmail];
435
436/// `GET /api/v1/google/status`: the Google accounts connected here, what each can be used for
437/// and who holds what, so an agent knows what to grant or to ask the person for.
438pub(crate) async fn handle_google_status(State(state): State<AppState>, caller: Option<Extension<Caller>>) -> Response {
439    let def = match calling_agent(&state, caller.as_deref()) {
440        Ok(d) => d,
441        Err(e) => return error(StatusCode::FORBIDDEN, e),
442    };
443    match status_for(&state, Some(&def)) {
444        Ok(v) => Json(v).into_response(),
445        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
446    }
447}
448
449/// The accounts, what each supports and who holds what. `viewer` is the agent asking, whose own level
450/// is added as `yours`; a caller from another machine has no agent here and gets the holders alone.
451pub(crate) fn status_for(state: &AppState, viewer: Option<&AgentDefinition>) -> Result<serde_json::Value, String> {
452    let names: std::collections::HashMap<String, String> =
453        state.mstore.agent_def_list().map_err(|e| e.to_string())?.into_iter().map(|d| (d.id, d.name)).collect();
454    let mut accounts = Vec::new();
455    for acct in google_accounts(state)? {
456        let grants = state.identity_store.google_grants_for_account(&acct.id).map_err(|e| e.to_string())?;
457        let mut services = serde_json::Map::new();
458        for service in SERVICES {
459            let holders: Vec<_> = grants
460                .iter()
461                .filter(|g| g.service == service.as_str())
462                .map(|g| json!({ "agent": names.get(&g.agent_id).cloned().unwrap_or_else(|| g.agent_id.clone()), "level": g.level }))
463                .collect();
464            let mut entry = json!({ "connected_for": supported_level(&acct, service), "holders": holders });
465            if let Some(def) = viewer {
466                let mine = grants.iter().find(|g| g.service == service.as_str() && g.agent_id == def.id).map(|g| g.level.as_str());
467                entry["yours"] = json!(mine.unwrap_or("off"));
468            }
469            services.insert(service.as_str().to_string(), entry);
470        }
471        accounts.push(json!({ "account": access::email_of(&acct), "status": acct.status, "services": services }));
472    }
473    Ok(match viewer {
474        Some(def) => json!({ "you": def.name, "accounts": accounts }),
475        None => json!({ "accounts": accounts }),
476    })
477}
478
479#[derive(Debug, Deserialize)]
480pub(crate) struct GrantBody {
481    /// The Google account's email.
482    account: String,
483    /// The agent to grant, by name or id; the caller itself when absent.
484    #[serde(default)]
485    agent: Option<String>,
486    /// `calendar`, `drive` or `gmail`.
487    service: String,
488    /// `read`, `write` or `off`.
489    level: String,
490}
491
492/// `POST /api/v1/google/grant`: turn a service of a connected Google account on for an agent, or
493/// off. Any agent may do it (decided: "yes, agents can grant"); it is recorded as the agent that
494/// did it, in the account's log the person reads. Sends, shares, invites and deletes still wait
495/// for the person in the host window, which no agent can answer.
496pub(crate) async fn handle_google_grant(
497    State(state): State<AppState>,
498    caller: Option<Extension<Caller>>,
499    Json(body): Json<GrantBody>,
500) -> Response {
501    let actor = match calling_agent(&state, caller.as_deref()) {
502        Ok(d) => d,
503        Err(e) => return error(StatusCode::FORBIDDEN, e),
504    };
505    match grant_by_agent(&state, &actor, &body) {
506        Ok(v) => Json(v).into_response(),
507        Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
508    }
509}
510
511#[derive(Deserialize)]
512pub(crate) struct DisconnectBody {
513    /// The account's email (or its id).
514    account: String,
515}
516
517/// `POST /api/v1/google/disconnect`: end the connection to a Google account: Google's grant is
518/// revoked first, then the saved token, the account's grants and its log go. The same code as the
519/// window's delete. Any agent may ask (the person only signs in); it is noticed in the windows.
520pub(crate) async fn handle_google_disconnect(
521    State(state): State<AppState>,
522    caller: Option<Extension<Caller>>,
523    Json(body): Json<DisconnectBody>,
524) -> Response {
525    let actor = match calling_agent(&state, caller.as_deref()) {
526        Ok(d) => d,
527        Err(e) => return error(StatusCode::FORBIDDEN, e),
528    };
529    match disconnect_by_agent(&state, &actor, &body).await {
530        Ok(v) => Json(v).into_response(),
531        Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
532    }
533}
534
535async fn disconnect_by_agent(state: &AppState, actor: &AgentDefinition, body: &DisconnectBody) -> Result<serde_json::Value, String> {
536    let asked = body.account.trim();
537    let accounts = google_accounts(state)?;
538    // The same email can be connected twice (each connection has its own consent): both end.
539    let targets: Vec<_> = accounts.iter().filter(|a| a.id == asked || access::email_of(a).eq_ignore_ascii_case(asked)).collect();
540    if targets.is_empty() {
541        let have: Vec<_> = accounts.iter().map(access::email_of).collect();
542        return Err(if have.is_empty() {
543            "no Google account is connected".to_string()
544        } else {
545            format!("no connected Google account {asked}. Connected: {}", have.join(", "))
546        });
547    }
548    let defs = state.mstore.agent_def_list().map_err(|e| e.to_string())?;
549    let mut lost_access: Vec<String> = Vec::new();
550    let mut revoked = true;
551    let mut gone: Vec<String> = Vec::new();
552    for account in &targets {
553        let email = access::email_of(account);
554        let mut holders: Vec<String> = Vec::new();
555        for grant in state.identity_store.google_grants_for_account(&account.id).map_err(|e| e.to_string())? {
556            holders.push(defs.iter().find(|d| d.id == grant.agent_id).map_or(grant.agent_id.clone(), |d| d.name.clone()));
557        }
558        // Google's revoke comes first and must work: otherwise the connection stays, to try again.
559        let done = super::agent_handlers::delete_identity_account(&state.id_store, &state.identity_store, &state.broker, &account.id, true).await?;
560        if !done.deleted {
561            let why = done.revoke.get("detail").and_then(serde_json::Value::as_str).unwrap_or("Google did not answer");
562            let mut said = format!("Google didn't end the connection to {email} ({why}), so it was kept: try again, or the person removes it in Connectors");
563            // The same email connected twice: the ones before this were already ended, and the windows hear of them.
564            if !gone.is_empty() {
565                said.push_str(&format!(". Already disconnected: {} (agents who lost access: {})", gone.join(", "), lost_access.join(", ")));
566                crate::identity::accounts_changed::tell_windows(format!("{} disconnected a connection of {}", actor.name, gone[0]));
567            }
568            return Err(said);
569        }
570        gone.push(email);
571        for name in holders {
572            if !lost_access.contains(&name) {
573                lost_access.push(name);
574            }
575        }
576        revoked &= done.revoke.get("outcome").and_then(serde_json::Value::as_str) != Some("failed");
577        tracing::info!(target: "google", account_id = %account.id, by = %actor.name, "google: account disconnected by an agent");
578    }
579    let email = access::email_of(targets[0]);
580    crate::identity::accounts_changed::tell_windows(format!("{} disconnected the Google account {email}", actor.name));
581    Ok(json!({ "disconnected": email, "agents_who_lost_access": lost_access, "revoked_at_google": revoked }))
582}
583
584fn grant_by_agent(state: &AppState, actor: &AgentDefinition, body: &GrantBody) -> Result<serde_json::Value, String> {
585    grant_as(state, &actor.id, &actor.name, Some(actor), body)
586}
587
588/// A grant, recorded under `by_name` (`by_id`). With no `agent` in the body it goes to `yourself`, which a
589/// caller from another machine has none of: it names the agent here.
590pub(crate) fn grant_as(
591    state: &AppState,
592    by_id: &str,
593    by_name: &str,
594    yourself: Option<&AgentDefinition>,
595    body: &GrantBody,
596) -> Result<serde_json::Value, String> {
597    use crate::backend::storage::google_grants::GoogleCall;
598    let service = SERVICES
599        .into_iter()
600        .find(|s| s.as_str() == body.service.trim())
601        .ok_or_else(|| format!("service \"{}\": calendar, drive or gmail", body.service.trim()))?;
602    let level = crate::backend::storage::google_grants::GrantLevel::parse(&body.level)?;
603    let asked = body.account.trim();
604    let accounts = google_accounts(state)?;
605    let same_email: Vec<&crate::backend::storage::store::IdentityAccount> =
606        accounts.iter().filter(|a| access::email_of(a).eq_ignore_ascii_case(asked)).collect();
607    if same_email.is_empty() {
608        let have: Vec<_> = accounts.iter().map(access::email_of).collect();
609        return Err(if have.is_empty() {
610            "no Google account is connected: the person connects one in Accounts (they sign in and consent)".to_string()
611        } else {
612            format!("no connected Google account {asked}. Connected: {}", have.join(", "))
613        });
614    }
615    let target = body.agent.as_deref().map(str::trim).filter(|s| !s.is_empty());
616    let defs = state.mstore.agent_def_list().map_err(|e| e.to_string())?;
617    let target_def = match target {
618        None => yourself.cloned().ok_or("agent is required: name the agent on this computer to grant")?,
619        Some(t) => defs
620            .into_iter()
621            .find(|d| d.id == t || d.name.eq_ignore_ascii_case(t))
622            .ok_or_else(|| format!("no agent \"{t}\""))?,
623    };
624    // The same email can be connected twice (each connection has its own consent). Take the one that
625    // can back the level asked for; to turn a service off, the one the agent holds it on.
626    let account = same_email
627        .iter()
628        .copied()
629        .find(|a| match level {
630            Some(l) => grant_is_backed(l, supported_level(a, service)),
631            None => state
632                .identity_store
633                .google_grant_get(&target_def.id, &a.id, service.as_str())
634                .ok()
635                .flatten()
636                .is_some(),
637        })
638        .unwrap_or(same_email[0]);
639    let email = access::email_of(account);
640    if let Some(l) = level {
641        // The token must carry the scopes the level needs, or every call would fail later.
642        let supported = supported_level(account, service);
643        if !grant_is_backed(l, supported) {
644            return Err(format!(
645                "{email} was connected without {} {} access (it supports: {supported}): the person reconnects it with {} turned on",
646                service.as_str(),
647                l.as_str(),
648                service.as_str()
649            ));
650        }
651    }
652    let now = chrono::Utc::now().timestamp_millis();
653    set_grant_on_email(state, &target_def.id, (account, &same_email), service, level, now)?;
654    crate::identity::accounts_changed::announce();
655    let level_name = level.map_or("off", |l| l.as_str());
656    let line = GoogleCall {
657        at: now,
658        agent_id: by_id.to_string(),
659        agent_name: by_name.to_string(),
660        service: service.as_str().to_string(),
661        action: if level.is_some() { "grant".to_string() } else { "ungrant".to_string() },
662        ids: format!("{}:{level_name}", target_def.name),
663        outcome: "ok".to_string(),
664    };
665    if let Err(e) = state.identity_store.google_call_log(&account.id, &line) {
666        tracing::warn!(target: "google", error = %e, "google: logging a grant failed");
667    }
668    tracing::info!(
669        target: "google",
670        account_id = %account.id,
671        by = %by_name,
672        agent = %target_def.name,
673        service = %service.as_str(),
674        level = level_name,
675        "google: grant set by an agent"
676    );
677    crate::identity::accounts_changed::tell_windows(grant_notice(by_name, &target_def.name, service, level, &email));
678    Ok(json!({ "account": email, "agent": target_def.name, "service": service.as_str(), "level": level_name }))
679}
680
681/// Set an agent's grant on `chosen`, one of the connections of an email (`same_email`, all of them). The agent
682/// names an email, so one grant per email: the service is cleared on the email's other connections, or an
683/// ungrant (or a change of level) would leave an older grant usable.
684fn set_grant_on_email(
685    state: &AppState,
686    agent_id: &str,
687    (chosen, same_email): (&crate::backend::storage::store::IdentityAccount, &[&crate::backend::storage::store::IdentityAccount]),
688    service: Service,
689    level: Option<crate::backend::storage::google_grants::GrantLevel>,
690    now: i64,
691) -> Result<(), String> {
692    for other in same_email.iter().filter(|o| o.id != chosen.id) {
693        state.identity_store.google_grant_set(agent_id, &other.id, service.as_str(), None, now).map_err(|e| e.to_string())?;
694    }
695    state.identity_store.google_grant_set(agent_id, &chosen.id, service.as_str(), level, now).map_err(|e| e.to_string())
696}
697
698/// "Naki-2 gave Agent5 Calendar read on me@example.com", or "Naki-2 turned off Calendar for Agent5 on ...".
699fn grant_notice(by: &str, agent: &str, service: Service, level: Option<crate::backend::storage::google_grants::GrantLevel>, email: &str) -> String {
700    let name = service.as_str();
701    let name = format!("{}{}", name[..1].to_ascii_uppercase(), &name[1..]);
702    match level {
703        Some(l) => format!("{by} gave {agent} {name} {} on {email}", l.as_str()),
704        None => format!("{by} turned off {name} for {agent} on {email}"),
705    }
706}
707
708#[path = "google_connect.rs"]
709pub(crate) mod connect;
710
711#[cfg(test)]
712#[path = "google_handlers_tests.rs"]
713mod tests;