Skip to main content

grr_cli/core/auth/
mod.rs

1//! OAuth2 authentication: PKCE loopback flow (RFC 8252) with an RFC 8628
2//! device-flow fallback, tokens in the OS keyring.
3//!
4//! Multi-account: one OAuth client, one token per Google account. An auth
5//! handle is bound to one account's store entry (the default account keeps
6//! the legacy naming byte-for-byte); named accounts log in independently.
7
8use std::path::PathBuf;
9use std::sync::Arc;
10use std::sync::LazyLock;
11use std::time::Duration;
12
13use anyhow::anyhow;
14use reqwest::Client as HttpClient;
15use tokio::sync::RwLock;
16use tracing::{debug, info, warn};
17
18use crate::core::config::OAuthConfig;
19use crate::core::error::{GrrError, Result};
20
21mod device;
22mod oauth;
23mod server;
24mod store;
25mod token;
26
27pub use device::DeviceAuthChallenge;
28pub use token::TokenStorage;
29
30/// The device flow's scope intersection, for `grr auth login --device` (the
31/// module itself stays private).
32pub(crate) use device::device_flow_scopes;
33
34use store::TokenStore;
35
36const GOOGLE_TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
37
38/// Loopback redirect for the native-app flow (RFC 8252 §7.3).
39pub(crate) const REDIRECT_URI: &str = "http://localhost:3434/oauth/callback";
40
41/// Every scope the embedded index names, minus the ones Google will not show
42/// a user (see [`APP_AUTH_SCOPES`]), plus a curated floor for scopes no
43/// method declares. This is the *superset* a credential may hold — what
44/// `grr auth login --all-scopes` asks for, and what `grr api describe` counts
45/// against — but deliberately not what a login requests by default: see
46/// [`login_scopes`] for why the default is small. A token keeps whatever it
47/// was granted, so a build that widens this list needs one `grr auth login`
48/// to take effect.
49pub fn scopes() -> &'static [String] {
50    static SCOPES: LazyLock<Vec<String>> = LazyLock::new(|| {
51        let mut set: Vec<String> = CURATED_SCOPES.iter().map(|s| (*s).to_owned()).collect();
52        set.extend(crate::discovery::all_scopes());
53        set.retain(|scope| !APP_AUTH_SCOPES.contains(&scope.as_str()));
54        set.sort_unstable();
55        set.dedup();
56        set
57    });
58    &SCOPES
59}
60
61/// What `grr auth login` asks for when no flag says otherwise: the services
62/// every grr user touches, small enough that Google's consent screen
63/// completes with them ticked.
64///
65/// The size is the point. Google's granular-permission screen puts one
66/// checkbox per requested scope, and on an unverified project its submit
67/// stops completing somewhere between the 27 boxes that go through in a
68/// second and the 74 that never do — no error, no redirect, just a spinner
69/// until the callback times out. The whole index is ~112 scopes, so
70/// requesting all of it means a first-time user cannot finish a login at all.
71/// Google's own guidance for that screen says the same thing in policy terms:
72/// avoid bundling scopes at sign-in, and grow the grant with incremental
73/// authorization.
74///
75/// Everything else stays reachable: `grr auth login --service X` asks for one
76/// service's scopes, `--all-scopes` for the whole index, and because every
77/// login carries `include_granted_scopes` those requests *merge* with what the
78/// account already holds instead of replacing it.
79///
80/// `https://mail.google.com/` subsumes Gmail's granular scopes, so only it is
81/// requested here; the granular set stays reachable via
82/// `grr auth login --service gmail` for anyone who wants a narrower grant.
83const LOGIN_SCOPES: &[&str] = &[
84    "https://mail.google.com/",
85    "https://www.googleapis.com/auth/drive",
86    "https://www.googleapis.com/auth/calendar",
87    "https://www.googleapis.com/auth/calendar.events",
88    "https://www.googleapis.com/auth/tasks",
89    "https://www.googleapis.com/auth/documents",
90    "https://www.googleapis.com/auth/spreadsheets",
91    "https://www.googleapis.com/auth/presentations",
92    "https://www.googleapis.com/auth/userinfo.email",
93    "https://www.googleapis.com/auth/userinfo.profile",
94    "openid",
95];
96
97/// [`LOGIN_SCOPES`], filtered to scopes the embedded index actually declares —
98/// requesting one no build can declare is a consent hang of its own.
99pub fn login_scopes() -> Vec<String> {
100    let available = scopes();
101    LOGIN_SCOPES
102        .iter()
103        .filter(|scope| available.iter().any(|known| known.as_str() == **scope))
104        .map(|scope| (*scope).to_owned())
105        .collect()
106}
107
108/// Every scope one service's methods declare for `grr auth login --service`.
109/// The index is the same source the command tree and `grr api describe` read,
110/// so the set matches exactly what that service can be asked to do — and stays
111/// far below the size at which Google's consent screen stops submitting.
112/// `None` when the index has no such service.
113pub fn scopes_for_service(service: &str) -> Option<Vec<String>> {
114    let mut set: Vec<String> = Vec::new();
115    let entry = crate::discovery::services().get(service)?;
116    for method in &entry.methods {
117        for scope in &method.scopes {
118            if !APP_AUTH_SCOPES.contains(&scope.as_str()) {
119                set.push(scope.clone());
120            }
121        }
122    }
123    set.sort_unstable();
124    set.dedup();
125    Some(set)
126}
127
128/// Scopes every release has carried since long before the set became
129/// index-derived. The index names all of them today; keeping them as a floor
130/// means a discovery regression cannot silently drop a scope that an
131/// existing credential and an existing user rely on.
132const CURATED_SCOPES: &[&str] = &[
133    // Sign-in. No method in the index declares these, but every credential
134    // needs them to name the account: without `openid`/`userinfo.*` the token
135    // cannot answer `grr auth status`, and a login that omits them looks
136    // healthy while every profile call 403s.
137    "openid",
138    "https://www.googleapis.com/auth/userinfo.email",
139    "https://www.googleapis.com/auth/userinfo.profile",
140    // Gmail
141    "https://www.googleapis.com/auth/gmail.readonly",
142    "https://www.googleapis.com/auth/gmail.compose",
143    "https://www.googleapis.com/auth/gmail.modify",
144    "https://www.googleapis.com/auth/gmail.labels",
145    "https://mail.google.com/",
146    // Calendar
147    "https://www.googleapis.com/auth/calendar",
148    // Drive
149    "https://www.googleapis.com/auth/drive",
150    // People (contacts)
151    "https://www.googleapis.com/auth/contacts",
152    "https://www.googleapis.com/auth/contacts.other.readonly",
153    // Chat
154    "https://www.googleapis.com/auth/chat.messages",
155    "https://www.googleapis.com/auth/chat.spaces",
156    "https://www.googleapis.com/auth/chat.delete",
157    "https://www.googleapis.com/auth/chat.memberships",
158    "https://www.googleapis.com/auth/chat.messages.reactions",
159    // Forms
160    "https://www.googleapis.com/auth/forms.body",
161    "https://www.googleapis.com/auth/forms.responses.readonly",
162    // Search Console
163    "https://www.googleapis.com/auth/webmasters.readonly",
164];
165
166/// Scopes the index names that are granted to a *service account*, never to a
167/// user, and that Google therefore refuses to show on a user consent screen.
168/// They are Chat's app-authentication surface: `chat.bot` "only supports app
169/// authentication", the `chat.app.*` family is used by a Chat app's service
170/// account (with administrator approval), and `chat.import` exists solely for
171/// domain-wide delegation to a service account.
172///
173/// One of them in the request fails the *entire* authorization with
174/// `Error 400: invalid_scope — Some requested scopes cannot be shown:
175/// [...]`, granting nothing, so they must stay out of [`scopes`]. Nothing is
176/// lost by leaving them out: a user credential cannot call the methods behind
177/// them, because those methods authenticate as the app, not as the user.
178///
179/// Keep in sync with Google's Chat authentication docs
180/// (<https://developers.google.com/workspace/chat/authenticate-authorize> and
181/// <https://developers.google.com/workspace/chat/authorize-import>): a refresh
182/// that adds another `chat.app.*` scope needs it listed here too, or login
183/// stops working for everyone.
184pub(crate) const APP_AUTH_SCOPES: &[&str] = &[
185    "https://www.googleapis.com/auth/chat.bot",
186    "https://www.googleapis.com/auth/chat.import",
187    "https://www.googleapis.com/auth/chat.app.delete",
188    "https://www.googleapis.com/auth/chat.app.memberships",
189    "https://www.googleapis.com/auth/chat.app.memberships.readonly",
190    "https://www.googleapis.com/auth/chat.app.messages.readonly",
191    "https://www.googleapis.com/auth/chat.app.spaces",
192    "https://www.googleapis.com/auth/chat.app.spaces.create",
193    "https://www.googleapis.com/auth/chat.app.spaces.readonly",
194    "https://www.googleapis.com/auth/chat.app.all.memberships.readonly",
195    "https://www.googleapis.com/auth/chat.app.all.messages.readonly",
196    "https://www.googleapis.com/auth/chat.app.all.spaces.readonly",
197];
198
199/// OAuth2 client with PKCE support
200#[derive(Clone)]
201pub struct GoogleAuth {
202    config: OAuthConfig,
203    http_client: HttpClient,
204    token_storage: Arc<RwLock<Option<TokenStorage>>>,
205    store: TokenStore,
206    token_endpoint: String,
207}
208
209impl GoogleAuth {
210    /// Create new GoogleAuth from config
211    pub async fn new(config: OAuthConfig) -> Result<Self> {
212        Self::with_store(config, TokenStore::auto().await?).await
213    }
214
215    /// Create an auth handle bound to one named account's own token
216    /// (multi-account support). Same OAuth client and scopes; every store
217    /// read and write targets that account's keyring entry / fallback file
218    /// exclusively. The name is validated and normalized here (rejects
219    /// spaces, colons, and path separators; lowercased).
220    pub async fn new_for(config: OAuthConfig, account: impl Into<String>) -> Result<Self> {
221        let account = store::validate_account_name(account.into().as_str())?;
222        let store = TokenStore::auto_named(&account).await?;
223        Self::with_store(config, store).await
224    }
225
226    async fn with_store(mut config: OAuthConfig, store: TokenStore) -> Result<Self> {
227        let http_client = HttpClient::builder()
228            .timeout(Duration::from_secs(30))
229            .build()
230            .map_err(|e| GrrError::Config(format!("Failed to create HTTP client: {}", e)))?;
231        // The store is NOT read here. Reading the OS keyring raises an
232        // approval prompt on unsigned binaries (macOS re-prompts per build),
233        // and the constructor runs for every command — including `--dry-run`,
234        // `schema`, and `api list`, which never need a credential. The first
235        // read happens in `get_access_token`, the first moment a credential
236        // is actually required.
237        config.client_secret = config.client_secret.take().filter(|s| !s.is_empty());
238        config.device_client_secret = config.device_client_secret.take().filter(|s| !s.is_empty());
239        Ok(Self {
240            config,
241            http_client,
242            token_storage: Arc::new(RwLock::new(None)),
243            store,
244            token_endpoint: GOOGLE_TOKEN_URL.to_string(),
245        })
246    }
247
248    /// A handle bound to `account`'s own token store, reusing this handle's
249    /// config (and thus the same OAuth client). The token cache is NOT
250    /// shared: the new handle loads the named account's stored token.
251    ///
252    /// This is what `commands/auth.rs` uses to rebind a default handle when
253    /// a per-command `--account` is present.
254    pub async fn with_account_store(&self, account: impl Into<String>) -> Result<Self> {
255        Self::new_for(self.config.clone(), account).await
256    }
257
258    /// A fresh handle on the DEFAULT account's store — today's exact entry
259    /// naming, no account suffix.
260    ///
261    /// `grr auth login`/`status` rebuild their handle through this so a
262    /// named `--account` and the default take the same code path; without
263    /// an account it is behavior-identical to the original construction.
264    pub async fn with_default_account_store(&self) -> Result<Self> {
265        Self::with_store(self.config.clone(), TokenStore::default_named().await?).await
266    }
267
268    /// Token storage backend in use (for logs and `auth login` output).
269    pub fn token_backend(&self) -> &'static str {
270        self.store.backend()
271    }
272
273    /// The scope set the credential in hand holds — what Google actually
274    /// granted, or the requested set when its response was silent — split out
275    /// of [`TokenStorage::scope`]. Empty before any credential is loaded in
276    /// this process (nothing is read from the keyring here), and for a token
277    /// record written before the field existed.
278    ///
279    /// `grr auth status` reports this. Only the credential knows what it
280    /// holds: `auth login`'s count is what was *requested*, and the consent
281    /// screen lets a user approve a subset of that.
282    pub async fn granted_scopes(&self) -> Vec<String> {
283        self.token_storage
284            .read()
285            .await
286            .as_ref()
287            .map(|storage| {
288                storage
289                    .scope
290                    .split_whitespace()
291                    .map(str::to_owned)
292                    .collect()
293            })
294            .unwrap_or_default()
295    }
296
297    /// Construct an auth handle pre-loaded with an in-memory token.
298    ///
299    /// Test hook (`#[doc(hidden)]`): skips OAuth and persistent storage
300    /// entirely until a test explicitly installs a token path.
301    #[doc(hidden)]
302    pub async fn with_token(config: OAuthConfig, storage: TokenStorage) -> Result<Self> {
303        let this = Self::with_store(config, TokenStore::Memory).await?;
304        *this.token_storage.write().await = Some(storage);
305        Ok(this)
306    }
307
308    /// Override the OAuth2 token endpoint URL (test injection hook).
309    #[doc(hidden)]
310    pub fn with_token_endpoint(mut self, url: impl Into<String>) -> Self {
311        self.token_endpoint = url.into();
312        self
313    }
314
315    /// Redirect all token persistence to an explicit file (test injection
316    /// hook). Production code never touches the real credential store
317    /// because tests always pass a tempdir path here.
318    #[doc(hidden)]
319    pub fn with_token_path(mut self, path: PathBuf) -> Self {
320        self.store = TokenStore::file(path);
321        self
322    }
323
324    /// Get valid access token, refreshing if necessary
325    pub async fn get_access_token(&self) -> Result<String> {
326        // First credential use in this process (the constructor never reads
327        // the store — see `with_store`). The store read happens under the
328        // guard so two callers cannot both load it, and the guard is then
329        // dropped: everything below is network I/O — a refresh POST, or the
330        // interactive flow, which binds port 3434 and waits on the callback
331        // server for up to 300 s — and must never run holding the token lock.
332        let refreshed = {
333            let mut guard = self.token_storage.write().await;
334            if guard.is_none() {
335                *guard = self.store.load().await?;
336            }
337
338            // A logged-in user must never fall into the implicit OAuth flow
339            // just because the token was not loaded yet, so this runs before
340            // the None-means-fresh-install branch below.
341            match guard.as_ref() {
342                None => None,
343                Some(storage) if !storage.is_expired() => {
344                    debug!(
345                        "Using cached access token ({}s remaining)",
346                        storage.remaining_secs()
347                    );
348                    return Ok(storage.access_token.clone());
349                }
350                Some(storage) => {
351                    // A stored credential that cannot produce a fresh token
352                    // must never trigger the implicit browser flow:
353                    // `run_oauth_flow` binds port 3434 mid-API-call and wedges
354                    // callers for the callback timeout.
355                    let Some(refresh_token) = storage.refresh_token.clone() else {
356                        return Err(GrrError::Auth(
357                            anyhow!(
358                                "stored token is expired and has no refresh token; rerun `grr \
359                                 auth login`"
360                            )
361                            .into(),
362                        ));
363                    };
364
365                    // A refresh request carries no scope list, and RFC 6749
366                    // §5.1 lets Google omit `scope` when the grant is
367                    // unchanged — so the response's absent scope must fall
368                    // back to what the stored credential already holds, never
369                    // to the index superset `scopes()`. A fabricated grant
370                    // makes a later 403 look like a stale token instead of a
371                    // scope the account never approved.
372                    let stored_scopes: Vec<String> = storage
373                        .scope
374                        .split_whitespace()
375                        .map(str::to_owned)
376                        .collect();
377                    Some((refresh_token, stored_scopes))
378                }
379            }
380        };
381
382        if let Some((refresh_token, stored_scopes)) = refreshed {
383            info!("Refreshing expired access token");
384            match self.refresh_token(&refresh_token, &stored_scopes).await {
385                Ok(new_storage) => {
386                    *self.token_storage.write().await = Some(new_storage.clone());
387                    self.save_token(&new_storage).await?;
388                    return Ok(new_storage.access_token);
389                }
390                Err(e) => {
391                    warn!("Token refresh failed: {}", e);
392                    // Keep the expired storage in place: clearing it would
393                    // route subsequent callers into the implicit OAuth flow.
394                    return Err(GrrError::Auth(
395                        anyhow!("{e}; rerun `grr auth login`").into(),
396                    ));
397                }
398            }
399        }
400
401        // Fresh install / implicit install path: no stored token at all. The
402        // default set keeps the consent page small; widening is an explicit
403        // `grr auth login --service …` / `--all-scopes` after this.
404        info!("No valid token, starting OAuth flow");
405        let storage = self.run_oauth_flow(&login_scopes()).await?;
406        *self.token_storage.write().await = Some(storage.clone());
407        self.save_token(&storage).await?;
408        Ok(storage.access_token)
409    }
410
411    /// POST one form to one OAuth endpoint and parse the JSON body a single
412    /// time. `endpoint` is the URL — the token endpoint for the PKCE exchange
413    /// and the refresh grant, Google's device-code URL for the device flow
414    /// (the same request/parse plumbing, a different URL). `client_secret` is
415    /// appended when the caller names one — a parameter rather than a field
416    /// read, because the device flow authenticates as a *different* client
417    /// (type "TVs and Limited Input devices") than the browser flow, and one
418    /// request carrying both secrets would be rejected.
419    ///
420    /// Returns `(status, body)` rather than making a success decision here,
421    /// so each caller keeps its own logic and messages: the PKCE exchange
422    /// and the refresh grant report Google's error detail on non-2xx, while
423    /// the device poll reads `error` codes out of a 400 body. Four callers
424    /// previously duplicated this request/parse plumbing byte for byte.
425    async fn token_request(
426        &self,
427        endpoint: &str,
428        client_secret: Option<&str>,
429        mut form: Vec<(&str, String)>,
430    ) -> Result<(reqwest::StatusCode, serde_json::Value)> {
431        if let Some(secret) = client_secret.filter(|s| !s.is_empty()) {
432            form.push(("client_secret", secret.to_string()));
433        }
434
435        let response = self
436            .http_client
437            .post(endpoint)
438            .form(&form)
439            .send()
440            .await
441            .map_err(GrrError::Http)?;
442
443        let status = response.status();
444        let body_text = response.text().await.map_err(GrrError::Http)?;
445        let body: serde_json::Value = serde_json::from_str(&body_text).map_err(|e| {
446            GrrError::Auth(anyhow!("{endpoint} returned {status}: unparseable body ({e})").into())
447        })?;
448        Ok((status, body))
449    }
450
451    /// Refresh access token using refresh token.
452    /// The secret is sent only when configured (Google mandates it even
453    /// for Desktop clients; PKCE-only providers omit it entirely).
454    ///
455    /// `requested_scopes` is the scope the stored credential actually holds:
456    /// the refresh request sends no scope list, so when Google omits `scope`
457    /// from the response (RFC 6749 §5.1, unchanged grant) the stored grant is
458    /// the only truthful fallback — never the index superset.
459    async fn refresh_token(
460        &self,
461        refresh_token: &str,
462        requested_scopes: &[String],
463    ) -> Result<TokenStorage> {
464        let (status, token_data) = self
465            .token_request(
466                &self.token_endpoint,
467                self.config.client_secret.as_deref(),
468                vec![
469                    ("client_id", self.config.client_id.clone()),
470                    ("refresh_token", refresh_token.to_string()),
471                    ("grant_type", "refresh_token".to_string()),
472                ],
473            )
474            .await?;
475
476        if !status.is_success() {
477            // Google reports rejection reasons (e.g. invalid_grant) in the
478            // response body; surface them instead of a generic parse failure.
479            return Err(GrrError::Auth(
480                anyhow!(
481                    "token endpoint returned {}: {}",
482                    status,
483                    crate::core::error::json_error_detail(&token_data)
484                )
485                .into(),
486            ));
487        }
488
489        let mut storage = self::device::token_storage_from_response(&token_data, requested_scopes)?;
490
491        // Google only sometimes rotates the refresh token; when the
492        // response omits one, keep the stored value instead of clobbering
493        // it with None (which would brick all future refreshes).
494        if storage.refresh_token.is_none() {
495            storage.refresh_token = Some(refresh_token.to_string());
496        }
497
498        Ok(storage)
499    }
500
501    /// Revoke current token
502    pub async fn revoke(&self) -> Result<()> {
503        let mut storage_guard = self.token_storage.write().await;
504        *storage_guard = None;
505        self.store.delete().await?;
506        info!("Token revoked and removed");
507        Ok(())
508    }
509}
510
511/// Auth's own checks: the consent request shape, and the default login set
512/// that keeps Google's consent page submittable — small, inside [`scopes`],
513/// and free of everything a personal account can never be granted.
514#[cfg(test)]
515mod tests {
516    use super::*;
517
518    /// The regression this guards: an app-authentication scope in the consent
519    /// request makes Google reject the whole authorization — no scope is
520    /// granted at all, so login cannot complete. And the filter must be
521    /// surgical: Chat's *user* scopes stay in.
522    #[test]
523    fn the_consent_set_drops_app_authentication_scopes_only() {
524        let consent = scopes();
525        for scope in APP_AUTH_SCOPES {
526            assert!(
527                !consent.iter().any(|consented| consented == scope),
528                "{scope} is app-authentication-only; Google refuses to show it and \
529                 fails the entire authorization request"
530            );
531        }
532        for scope in [
533            "https://www.googleapis.com/auth/chat.messages",
534            "https://www.googleapis.com/auth/chat.admin.spaces",
535            "https://www.googleapis.com/auth/chat.memberships.app",
536        ] {
537            assert!(
538                consent.iter().any(|consented| consented == scope),
539                "{scope} is a user-consent scope and must stay in the request"
540            );
541        }
542    }
543
544    /// The default login set has to stay small enough that Google's consent
545    /// screen completes with every requested scope ticked.
546    #[test]
547    fn the_default_login_set_is_small_and_inside_the_full_set() {
548        let login = login_scopes();
549        let full = scopes();
550
551        // Past roughly 27 ticked boxes an unverified project's consent screen
552        // stops submitting with no error at all, so the default has to stay
553        // well below that — the number is the insurance policy.
554        assert!(
555            login.len() <= 20,
556            "the default login set is {} scopes: Google's consent screen stops \
557             submitting past ~27 ticked boxes, so this is a regression",
558            login.len()
559        );
560        assert!(
561            login.len() >= 10,
562            "the default set lost its core services: {login:?}"
563        );
564        for scope in &login {
565            assert!(
566                full.iter().any(|known| known == scope),
567                "{scope} is not in scopes() — requesting an undeclared scope hangs too"
568            );
569        }
570        // Not enumerated here: admin, `groups`, and legacy GData scopes cannot
571        // be granted to a personal account, only enlarge the consent page, and
572        // so must never enter the default set.
573    }
574
575    #[test]
576    fn service_scopes_come_from_the_index_and_stay_narrow() {
577        let docs = scopes_for_service("docs").unwrap_or_default();
578        assert!(!docs.is_empty(), "docs is one of the 14 services");
579        assert!(
580            docs.iter()
581                .any(|scope| scope == "https://www.googleapis.com/auth/documents")
582        );
583        assert!(
584            docs.len() < scopes().len(),
585            "one service's scopes must stay far below the whole index"
586        );
587        for scope in &docs {
588            assert!(
589                scopes().iter().any(|known| known == scope),
590                "{scope} is not in scopes()"
591            );
592        }
593        assert!(scopes_for_service("not-a-service").is_none());
594    }
595
596    /// `grr auth status` reports what the credential holds, not what a login
597    /// asked for: the recorded grant is Google's own response (or the
598    /// requested fallback when it was silent), and the field is empty until a
599    /// credential is actually in hand.
600    #[tokio::test]
601    async fn granted_scopes_read_the_stored_grant_not_the_request() -> anyhow::Result<()> {
602        let config = crate::core::config::OAuthConfig::default();
603        let granted = "openid https://www.googleapis.com/auth/calendar";
604
605        let loaded = GoogleAuth::with_token(
606            config.clone(),
607            TokenStorage {
608                access_token: "t".into(),
609                refresh_token: None,
610                expires_at: u64::MAX,
611                token_type: "Bearer".into(),
612                scope: granted.into(),
613            },
614        )
615        .await?;
616        assert_eq!(
617            loaded.granted_scopes().await,
618            vec![
619                "openid".to_owned(),
620                "https://www.googleapis.com/auth/calendar".to_owned()
621            ]
622        );
623
624        // A record written before the field existed, or one whose provider
625        // never named a scope, reads as empty — never as the index superset.
626        let empty = GoogleAuth::with_token(
627            config,
628            TokenStorage {
629                access_token: "t".into(),
630                refresh_token: None,
631                expires_at: u64::MAX,
632                token_type: "Bearer".into(),
633                scope: String::new(),
634            },
635        )
636        .await?;
637        assert!(empty.granted_scopes().await.is_empty());
638        Ok(())
639    }
640}