Skip to main content

google_tool/
token_manager.rs

1//! Coordinates and caches OAuth access-token refreshes per external connection.
2//!
3//! Agent tools and management APIs share this manager. Concurrent calls for
4//! one connection wait on the same lock and reuse the resulting access token;
5//! different Google accounts refresh independently. Only the short-lived
6//! access token is cached. Refresh tokens are never copied into this cache.
7
8use std::{
9    collections::HashMap,
10    future::Future,
11    sync::Arc,
12    time::{Duration, Instant},
13};
14
15use agent_storage::ExternalConnectionId;
16use sha2::{Digest, Sha256};
17use tokio::sync::Mutex;
18
19use crate::{GoogleOAuthConfig, GoogleOAuthError, GoogleTokenSet, refresh_access_token};
20
21#[derive(Default)]
22pub struct GoogleOAuthTokenManager {
23    connections: Mutex<HashMap<ExternalConnectionId, Arc<Mutex<Option<CachedAccessToken>>>>>,
24}
25
26struct CachedAccessToken {
27    refresh_token_hash: [u8; 32],
28    access_token: String,
29    expires_at: Instant,
30}
31
32impl GoogleOAuthTokenManager {
33    pub fn new() -> Self {
34        Self::default()
35    }
36
37    /// Return a valid access token, refreshing at most once concurrently for
38    /// a given connection. A changed refresh token invalidates the cached token.
39    pub async fn refresh_access_token(
40        &self,
41        connection_id: ExternalConnectionId,
42        config: &GoogleOAuthConfig,
43        refresh_token: &str,
44    ) -> Result<String, GoogleOAuthError> {
45        let refresh_token_hash: [u8; 32] = Sha256::digest(refresh_token.as_bytes()).into();
46        self.get_or_refresh(connection_id, refresh_token_hash, || {
47            refresh_access_token(config, refresh_token)
48        })
49        .await
50    }
51
52    /// Invalidate cached access tokens after disconnect or reauthorization.
53    /// The per-connection lock is retained so invalidation cannot race a refresh.
54    pub async fn invalidate(&self, connection_id: ExternalConnectionId) {
55        let connection = self.connections.lock().await.get(&connection_id).cloned();
56        if let Some(connection) = connection {
57            *connection.lock().await = None;
58        }
59    }
60
61    async fn get_or_refresh<F, Fut>(
62        &self,
63        connection_id: ExternalConnectionId,
64        refresh_token_hash: [u8; 32],
65        refresh: F,
66    ) -> Result<String, GoogleOAuthError>
67    where
68        F: FnOnce() -> Fut + Send,
69        Fut: Future<Output = Result<GoogleTokenSet, GoogleOAuthError>> + Send,
70    {
71        let connection = {
72            let mut connections = self.connections.lock().await;
73            connections
74                .entry(connection_id)
75                .or_insert_with(|| Arc::new(Mutex::new(None)))
76                .clone()
77        };
78        let mut cached = connection.lock().await;
79        if let Some(token) = cached.as_ref().filter(|token| {
80            token.refresh_token_hash == refresh_token_hash
81                && token.expires_at > Instant::now() + Duration::from_secs(30)
82        }) {
83            return Ok(token.access_token.clone());
84        }
85
86        let token = refresh().await?;
87        let access_token = token.access_token;
88        // Google normally returns a one-hour token. Use a conservative fallback
89        // when the provider omits expires_in, stop using it 30 seconds early,
90        // and cap local reuse at one minute to limit stale-token time after revocation.
91        let lifetime = token
92            .expires_in_seconds
93            .unwrap_or(300)
94            .saturating_sub(30)
95            .clamp(1, 60);
96        *cached = Some(CachedAccessToken {
97            refresh_token_hash,
98            access_token: access_token.clone(),
99            expires_at: Instant::now() + Duration::from_secs(lifetime),
100        });
101        Ok(access_token)
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108    use std::sync::atomic::{AtomicUsize, Ordering};
109    use tokio::time::sleep;
110
111    fn token(access_token: &str) -> GoogleTokenSet {
112        GoogleTokenSet {
113            access_token: access_token.into(),
114            refresh_token: None,
115            expires_in_seconds: Some(3600),
116            scopes: Vec::new(),
117        }
118    }
119
120    #[tokio::test]
121    async fn concurrent_refreshes_for_one_connection_share_one_access_token() {
122        let manager = Arc::new(GoogleOAuthTokenManager::new());
123        let connection_id = ExternalConnectionId::new();
124        let refresh_count = Arc::new(AtomicUsize::new(0));
125        let mut tasks = Vec::new();
126
127        for _ in 0..8 {
128            let manager = manager.clone();
129            let refresh_count = refresh_count.clone();
130            tasks.push(tokio::spawn(async move {
131                manager
132                    .get_or_refresh(connection_id, [7; 32], || async move {
133                        refresh_count.fetch_add(1, Ordering::SeqCst);
134                        sleep(Duration::from_millis(10)).await;
135                        Ok(token("shared-access-token"))
136                    })
137                    .await
138                    .unwrap()
139            }));
140        }
141
142        for task in tasks {
143            assert_eq!(task.await.unwrap(), "shared-access-token");
144        }
145        assert_eq!(refresh_count.load(Ordering::SeqCst), 1);
146    }
147
148    #[tokio::test]
149    async fn different_connections_can_refresh_in_parallel() {
150        let manager = Arc::new(GoogleOAuthTokenManager::new());
151        let active = Arc::new(AtomicUsize::new(0));
152        let maximum = Arc::new(AtomicUsize::new(0));
153        let mut tasks = Vec::new();
154
155        for _ in 0..2 {
156            let manager = manager.clone();
157            let active = active.clone();
158            let maximum = maximum.clone();
159            tasks.push(tokio::spawn(async move {
160                manager
161                    .get_or_refresh(ExternalConnectionId::new(), [8; 32], || async move {
162                        let current = active.fetch_add(1, Ordering::SeqCst) + 1;
163                        maximum.fetch_max(current, Ordering::SeqCst);
164                        sleep(Duration::from_millis(30)).await;
165                        active.fetch_sub(1, Ordering::SeqCst);
166                        Ok(token("independent-access-token"))
167                    })
168                    .await
169                    .unwrap();
170            }));
171        }
172
173        for task in tasks {
174            task.await.unwrap();
175        }
176        assert_eq!(maximum.load(Ordering::SeqCst), 2);
177    }
178
179    #[tokio::test]
180    async fn explicit_invalidation_forces_a_new_refresh() {
181        let manager = GoogleOAuthTokenManager::new();
182        let connection_id = ExternalConnectionId::new();
183        let first = manager
184            .get_or_refresh(connection_id, [3; 32], || async { Ok(token("first")) })
185            .await
186            .unwrap();
187        manager.invalidate(connection_id).await;
188        let second = manager
189            .get_or_refresh(connection_id, [3; 32], || async { Ok(token("second")) })
190            .await
191            .unwrap();
192        assert_eq!(first, "first");
193        assert_eq!(second, "second");
194    }
195
196    #[tokio::test]
197    async fn a_changed_refresh_token_invalidates_the_cached_access_token() {
198        let manager = GoogleOAuthTokenManager::new();
199        let connection_id = ExternalConnectionId::new();
200        let first = manager
201            .get_or_refresh(connection_id, [1; 32], || async { Ok(token("first")) })
202            .await
203            .unwrap();
204        let second = manager
205            .get_or_refresh(connection_id, [2; 32], || async { Ok(token("second")) })
206            .await
207            .unwrap();
208        assert_eq!(first, "first");
209        assert_eq!(second, "second");
210    }
211}