Skip to main content

agentmux_srv_core/backend/storage/
google_grants.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Which agents may use which Google service of a connected account, and what
5//! they did with it (docs/specs/SPEC_GOOGLE_CONNECTORS_GMAIL_CALENDAR_DRIVE_2026_10_14.md
6//! D4, D7).
7//!
8//! - `db_google_grants`: per agent (its definition id, the uid a verified call
9//!   carries), per account, per service (`calendar`, `drive`, `gmail`), a level:
10//!   `read`, or `write` (read and write). No row is `off`, the default.
11//! - `db_google_calls`: one row per tool call: when, which agent, which action,
12//!   the ids it touched and how it ended. Never content. Kept 30 days.
13//!
14//! In the identity store, beside the account links, so every channel on the
15//! computer sees the same grants.
16
17use rusqlite::params;
18use serde::{Deserialize, Serialize};
19
20use super::store::Store;
21use super::StoreError;
22
23/// The tables, created on every open of the identity store, with no schema
24/// version bump.
25pub(crate) const SCHEMA: &str = "
26    CREATE TABLE IF NOT EXISTS db_google_grants (
27        agent_id   TEXT NOT NULL,
28        account_id TEXT NOT NULL,
29        service    TEXT NOT NULL,
30        level      TEXT NOT NULL,
31        updated_at INTEGER NOT NULL DEFAULT 0,
32        PRIMARY KEY (agent_id, account_id, service)
33    );
34    CREATE TABLE IF NOT EXISTS db_google_calls (
35        id         INTEGER PRIMARY KEY AUTOINCREMENT,
36        account_id TEXT NOT NULL,
37        at         INTEGER NOT NULL,
38        agent_id   TEXT NOT NULL DEFAULT '',
39        agent_name TEXT NOT NULL DEFAULT '',
40        service    TEXT NOT NULL,
41        action     TEXT NOT NULL,
42        ids        TEXT NOT NULL DEFAULT '',
43        outcome    TEXT NOT NULL DEFAULT ''
44    );
45    CREATE INDEX IF NOT EXISTS idx_google_calls_account ON db_google_calls(account_id, at);";
46
47/// How long a call's log line is kept.
48pub const CALLS_RETENTION_MS: i64 = 30 * 24 * 60 * 60 * 1000;
49
50/// The Google services an account can be used for.
51pub const SERVICES: [&str; 3] = ["calendar", "drive", "gmail"];
52
53/// What an agent may do with one service of one account.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
55#[serde(rename_all = "lowercase")]
56pub enum GrantLevel {
57    Read,
58    /// Read and write.
59    Write,
60}
61
62impl GrantLevel {
63    pub fn as_str(self) -> &'static str {
64        match self {
65            GrantLevel::Read => "read",
66            GrantLevel::Write => "write",
67        }
68    }
69
70    /// `read`, `write`; `off` (or empty) is no level.
71    pub fn parse(s: &str) -> Result<Option<GrantLevel>, String> {
72        match s.trim() {
73            "read" => Ok(Some(GrantLevel::Read)),
74            "write" => Ok(Some(GrantLevel::Write)),
75            "off" | "" => Ok(None),
76            other => Err(format!("level \"{other}\": read, write or off")),
77        }
78    }
79}
80
81/// One agent's grant on one service of one account.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct GoogleGrant {
84    pub agent_id: String,
85    pub account_id: String,
86    pub service: String,
87    pub level: GrantLevel,
88}
89
90/// Which log lines a count takes.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum CallsCounted {
93    All,
94    /// Those that succeeded.
95    Ok,
96    /// Those where a question was put to the person (see `google_calls_count`).
97    Asked,
98}
99
100/// One line of an account's call log.
101#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
102pub struct GoogleCall {
103    pub at: i64,
104    pub agent_id: String,
105    pub agent_name: String,
106    pub service: String,
107    pub action: String,
108    /// The ids it touched (calendar, event or file ids), comma-separated.
109    pub ids: String,
110    /// `ok`, or why it didn't (`refused: …`, `error: …`).
111    pub outcome: String,
112}
113
114fn check_service(service: &str) -> Result<(), StoreError> {
115    if SERVICES.contains(&service) {
116        Ok(())
117    } else {
118        Err(StoreError::Other(format!("no Google service \"{service}\"")))
119    }
120}
121
122fn row_to_grant(r: &rusqlite::Row) -> rusqlite::Result<GoogleGrant> {
123    let level: String = r.get(3)?;
124    Ok(GoogleGrant {
125        agent_id: r.get(0)?,
126        account_id: r.get(1)?,
127        service: r.get(2)?,
128        level: if level == "write" { GrantLevel::Write } else { GrantLevel::Read },
129    })
130}
131
132impl Store {
133    /// Set an agent's level on one service of one account; `None` is off.
134    pub fn google_grant_set(
135        &self,
136        agent_id: &str,
137        account_id: &str,
138        service: &str,
139        level: Option<GrantLevel>,
140        now_ms: i64,
141    ) -> Result<(), StoreError> {
142        check_service(service)?;
143        let conn = self.conn().lock().unwrap();
144        match level {
145            Some(l) => conn.execute(
146                "INSERT INTO db_google_grants (agent_id, account_id, service, level, updated_at)
147                 VALUES (?1, ?2, ?3, ?4, ?5)
148                 ON CONFLICT(agent_id, account_id, service) DO UPDATE SET level = excluded.level, updated_at = excluded.updated_at",
149                params![agent_id, account_id, service, l.as_str(), now_ms],
150            )?,
151            None => conn.execute(
152                "DELETE FROM db_google_grants WHERE agent_id = ?1 AND account_id = ?2 AND service = ?3",
153                params![agent_id, account_id, service],
154            )?,
155        };
156        Ok(())
157    }
158
159    /// An agent's level on one service of one account, `None` when off.
160    pub fn google_grant_get(&self, agent_id: &str, account_id: &str, service: &str) -> Result<Option<GrantLevel>, StoreError> {
161        Ok(self
162            .google_grants_for_agent(agent_id)?
163            .into_iter()
164            .find(|g| g.account_id == account_id && g.service == service)
165            .map(|g| g.level))
166    }
167
168    /// Every grant an agent has.
169    pub fn google_grants_for_agent(&self, agent_id: &str) -> Result<Vec<GoogleGrant>, StoreError> {
170        let conn = self.conn().lock().unwrap();
171        let mut stmt = conn.prepare(
172            "SELECT agent_id, account_id, service, level FROM db_google_grants WHERE agent_id = ?1 ORDER BY account_id, service",
173        )?;
174        let rows = stmt.query_map(params![agent_id], row_to_grant)?;
175        rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
176    }
177
178    /// Every grant on an account.
179    pub fn google_grants_for_account(&self, account_id: &str) -> Result<Vec<GoogleGrant>, StoreError> {
180        let conn = self.conn().lock().unwrap();
181        let mut stmt = conn.prepare(
182            "SELECT agent_id, account_id, service, level FROM db_google_grants WHERE account_id = ?1 ORDER BY agent_id, service",
183        )?;
184        let rows = stmt.query_map(params![account_id], row_to_grant)?;
185        rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
186    }
187
188    /// Forget an account's grants and log (on disconnect).
189    pub fn google_account_forget(&self, account_id: &str) -> Result<(), StoreError> {
190        let conn = self.conn().lock().unwrap();
191        conn.execute("DELETE FROM db_google_grants WHERE account_id = ?1", params![account_id])?;
192        conn.execute("DELETE FROM db_google_calls WHERE account_id = ?1", params![account_id])?;
193        Ok(())
194    }
195
196    /// Write one line of an account's call log, and drop lines past
197    /// [`CALLS_RETENTION_MS`].
198    pub fn google_call_log(&self, account_id: &str, call: &GoogleCall) -> Result<(), StoreError> {
199        let conn = self.conn().lock().unwrap();
200        conn.execute(
201            "INSERT INTO db_google_calls (account_id, at, agent_id, agent_name, service, action, ids, outcome)
202             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
203            params![account_id, call.at, call.agent_id, call.agent_name, call.service, call.action, call.ids, call.outcome],
204        )?;
205        conn.execute("DELETE FROM db_google_calls WHERE at < ?1", params![call.at - CALLS_RETENTION_MS])?;
206        Ok(())
207    }
208
209    /// How many log lines `agent_id` has for `service`'s `actions` on the account since `since_ms`,
210    /// of the kind `which` says. Counted in the store, so what other agents and other actions logged
211    /// cannot push a line out of it.
212    pub fn google_calls_count(
213        &self,
214        account_id: &str,
215        agent_id: &str,
216        service: &str,
217        actions: &[&str],
218        since_ms: i64,
219        which: CallsCounted,
220    ) -> Result<usize, StoreError> {
221        let conn = self.conn().lock().unwrap();
222        let marks = vec!["?"; actions.len()].join(",");
223        let sql = format!(
224            "SELECT COUNT(*) FROM db_google_calls WHERE account_id = ? AND agent_id = ? AND service = ? AND at > ?
225               AND action IN ({marks}){}",
226            match which {
227                CallsCounted::All => "",
228                CallsCounted::Ok => " AND outcome = 'ok'",
229                // A question was put to the person: done, or answered no, or not answered. Not a call
230                // refused before it (a limit, a bad id, a missing scope, a failed read).
231                CallsCounted::Asked => " AND (outcome = 'ok' OR outcome LIKE 'error: the person %')",
232            }
233        );
234        let mut args: Vec<rusqlite::types::Value> = vec![account_id.to_string().into(), agent_id.to_string().into(), service.to_string().into(), since_ms.into()];
235        args.extend(actions.iter().map(|a| rusqlite::types::Value::from(a.to_string())));
236        let n: i64 = conn.query_row(&sql, rusqlite::params_from_iter(args), |r| r.get(0))?;
237        Ok(n.max(0) as usize)
238    }
239
240    /// An account's newest log lines first.
241    pub fn google_calls(&self, account_id: &str, limit: usize) -> Result<Vec<GoogleCall>, StoreError> {
242        let conn = self.conn().lock().unwrap();
243        let mut stmt = conn.prepare(
244            "SELECT at, agent_id, agent_name, service, action, ids, outcome FROM db_google_calls
245              WHERE account_id = ?1 ORDER BY at DESC, id DESC LIMIT ?2",
246        )?;
247        let rows = stmt.query_map(params![account_id, limit as i64], |r| {
248            Ok(GoogleCall {
249                at: r.get(0)?,
250                agent_id: r.get(1)?,
251                agent_name: r.get(2)?,
252                service: r.get(3)?,
253                action: r.get(4)?,
254                ids: r.get(5)?,
255                outcome: r.get(6)?,
256            })
257        })?;
258        rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
259    }
260}
261
262#[cfg(test)]
263#[path = "google_grants_tests.rs"]
264mod tests;