Skip to main content

agentmux_srv_core/backend/google/
access.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Which Google account an agent uses for a service, and at what level, or a
5//! sentence saying why it can't and who can change that (D4).
6//!
7//! The accounts are those the agent holds a grant on for the service (it may hold
8//! several, and names one by email when it does); the level is that grant, off
9//! unless a person or an agent set it.
10
11use std::sync::Arc;
12
13use crate::backend::storage::google_grants::GrantLevel;
14use crate::backend::storage::store::{AgentDefinition, IdentityAccount, Store};
15
16use super::Service;
17
18/// What an agent may use.
19#[derive(Debug, Clone)]
20pub struct Access {
21    pub account: IdentityAccount,
22    pub level: GrantLevel,
23    /// Whose grant this is, and for which service: [`Access::still_held`] asks about both.
24    pub agent_id: String,
25    pub service: Service,
26}
27
28impl Access {
29    pub fn email(&self) -> String {
30        email_of(&self.account)
31    }
32
33    /// Asked again once Google has answered, or just before a request goes out: the account may have been
34    /// disconnected, or the grant turned off (or lowered below `needed`), while the call ran. The
35    /// call then returns this sentence and none of Google's content.
36    pub fn still_held(&self, id_store: &Arc<Store>, identity_store: &Arc<Store>, needed: GrantLevel) -> Result<(), String> {
37        let email = self.email();
38        match crate::identity::resolver::resolve_account(id_store, identity_store, &self.account.id) {
39            Ok(Some(_)) => {}
40            Ok(None) => return Err(format!("{email} was disconnected while this call ran, so nothing from it is returned")),
41            Err(e) => return Err(format!("store: {e}")),
42        }
43        match identity_store.google_grant_get(&self.agent_id, &self.account.id, self.service.as_str()) {
44            Ok(Some(level)) if level >= needed => Ok(()),
45            Ok(_) => Err(format!(
46                "your {} access to {email} was removed while this call ran, so nothing from it is returned",
47                service_name(self.service)
48            )),
49            Err(e) => Err(format!("store: {e}")),
50        }
51    }
52
53    /// The scopes the account's token was granted.
54    pub fn granted_scopes(&self) -> Vec<String> {
55        granted_scopes_of(&self.account)
56    }
57}
58
59/// The scopes `account`'s token was granted, as Google named them.
60pub fn granted_scopes_of(account: &IdentityAccount) -> Vec<String> {
61    account
62        .context
63        .get("granted_scopes")
64        .and_then(serde_json::Value::as_array)
65        .map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect())
66        .unwrap_or_default()
67}
68
69/// The account's email, else its name.
70pub fn email_of(account: &IdentityAccount) -> String {
71    account
72        .context
73        .get("email")
74        .and_then(serde_json::Value::as_str)
75        .filter(|s| !s.is_empty())
76        .map(str::to_string)
77        .unwrap_or_else(|| if account.display_name.is_empty() { account.name.clone() } else { account.display_name.clone() })
78}
79
80/// The Google account bound to `def`, if any.
81pub fn bound_account(
82    mstore: &Store,
83    id_store: &Arc<Store>,
84    identity_store: &Arc<Store>,
85    def: &AgentDefinition,
86) -> Result<Option<IdentityAccount>, String> {
87    let links = crate::identity::resolver::effective_identity_links(mstore, identity_store, def)
88        .map_err(|e| format!("store: {e}"))?;
89    let Some(link) = links.into_iter().find(|l| l.provider == "google") else {
90        return Ok(None);
91    };
92    crate::identity::resolver::resolve_account(id_store, identity_store, &link.account_id)
93        .map(|found| found.map(|(a, _)| a))
94        .map_err(|e| format!("store: {e}"))
95}
96
97/// Every Google account `def` holds a grant on for `service`, by email. Several are allowed
98/// (the spec's D7): a grant is all an agent needs, so it can read more than one mailbox.
99pub fn granted_accounts(
100    id_store: &Arc<Store>,
101    identity_store: &Arc<Store>,
102    def: &AgentDefinition,
103    service: Service,
104) -> Result<Vec<Access>, String> {
105    let grants = identity_store.google_grants_for_agent(&def.id).map_err(|e| format!("store: {e}"))?;
106    let mut held = Vec::new();
107    for g in grants.into_iter().filter(|g| g.service == service.as_str()) {
108        if let Ok(Some((account, _))) = crate::identity::resolver::resolve_account(id_store, identity_store, &g.account_id) {
109            if account.provider == "google" {
110                held.push(Access { account, level: g.level, agent_id: def.id.clone(), service });
111            }
112        }
113    }
114    held.sort_by_key(|a| a.email().to_ascii_lowercase());
115    Ok(held)
116}
117
118/// The account and level `def` may use `service` with. `account` is the
119/// email the agent named, if it named one; without one, the single account it holds
120/// the service on.
121pub fn access_for(
122    _mstore: &Store,
123    id_store: &Arc<Store>,
124    identity_store: &Arc<Store>,
125    def: &AgentDefinition,
126    service: Service,
127    account: Option<&str>,
128) -> Result<Access, String> {
129    let name = service_name(service);
130    let mut held = granted_accounts(id_store, identity_store, def, service)?;
131    let list = || held.iter().map(Access::email).collect::<Vec<_>>().join(", ");
132    if let Some(asked) = account.map(str::trim).filter(|s| !s.is_empty()) {
133        return match held.iter().find(|a| a.email().eq_ignore_ascii_case(asked)) {
134            Some(found) => Ok(found.clone()),
135            None if held.is_empty() => Err(format!(
136                "{asked}'s {name} is off for you. Google grant turns it on for you (Google status lists the connected accounts)"
137            )),
138            None => Err(format!("you don't hold {name} on {asked}. You hold it on: {}", list())),
139        };
140    }
141    match held.len() {
142        0 => Err(format!(
143            "no Google account has {name} turned on for you. Google status lists the connected accounts; Google grant turns {name} on for you"
144        )),
145        1 => Ok(held.remove(0)),
146        _ => Err(format!("you hold {name} on several Google accounts: {}. Name one with account", list())),
147    }
148}
149
150fn service_name(service: Service) -> &'static str {
151    match service {
152        Service::Calendar => "Calendar",
153        Service::Drive => "Drive",
154        Service::Gmail => "Gmail",
155    }
156}