grr-cli 0.13.2

Google tools from the terminal, at maximum performance: 401 methods across 14 Google APIs in one generated command tree, zero-config, over HTTP/3
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! OAuth2 authentication: PKCE loopback flow (RFC 8252) with an RFC 8628
//! device-flow fallback, tokens in the OS keyring.
//!
//! Multi-account: one OAuth client, one token per Google account. An auth
//! handle is bound to one account's store entry (the default account keeps
//! the legacy naming byte-for-byte); named accounts log in independently.

use std::path::PathBuf;
use std::sync::Arc;
use std::sync::LazyLock;
use std::time::Duration;

use anyhow::anyhow;
use reqwest::Client as HttpClient;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};

use crate::core::config::OAuthConfig;
use crate::core::error::{GrrError, Result};

mod device;
mod oauth;
mod server;
mod store;
mod token;

pub use device::DeviceAuthChallenge;
pub use token::TokenStorage;

use store::TokenStore;

const GOOGLE_TOKEN_URL: &str = "https://oauth2.googleapis.com/token";

/// Loopback redirect for the native-app flow (RFC 8252 §7.3).
pub(crate) const REDIRECT_URI: &str = "http://localhost:3434/oauth/callback";

/// The consent set: every scope the embedded index names, minus the ones
/// Google will not show a user (see [`APP_AUTH_SCOPES`]), plus a curated
/// floor for scopes no method declares. Requested in full at login —
/// per-call escalation is deliberately not implemented, so "which scopes do
/// I hold" is never a question: one credential, everything the index can
/// express, nothing to configure. A token keeps whatever it was granted, so
/// a build that widens this list needs one `grr auth login` to take effect.
pub fn scopes() -> &'static [String] {
    static SCOPES: LazyLock<Vec<String>> = LazyLock::new(|| {
        let mut set: Vec<String> = CURATED_SCOPES.iter().map(|s| (*s).to_owned()).collect();
        set.extend(crate::discovery::all_scopes());
        set.retain(|scope| !APP_AUTH_SCOPES.contains(&scope.as_str()));
        set.sort_unstable();
        set.dedup();
        set
    });
    &SCOPES
}

/// Space-separated consent string, per RFC 6749 §3.3.
pub(crate) fn scopes_joined() -> String {
    scopes().join(" ")
}

/// Scopes every release has carried since long before the set became
/// index-derived. The index names all of them today; keeping them as a floor
/// means a discovery regression cannot silently drop a scope that an
/// existing credential and an existing user rely on.
const CURATED_SCOPES: &[&str] = &[
    // Gmail
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/gmail.compose",
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/gmail.labels",
    "https://mail.google.com/",
    // Calendar
    "https://www.googleapis.com/auth/calendar",
    // Drive
    "https://www.googleapis.com/auth/drive",
    // People (contacts)
    "https://www.googleapis.com/auth/contacts",
    "https://www.googleapis.com/auth/contacts.other.readonly",
    // Chat
    "https://www.googleapis.com/auth/chat.messages",
    "https://www.googleapis.com/auth/chat.spaces",
    "https://www.googleapis.com/auth/chat.delete",
    "https://www.googleapis.com/auth/chat.memberships",
    "https://www.googleapis.com/auth/chat.messages.reactions",
    // Forms
    "https://www.googleapis.com/auth/forms.body",
    "https://www.googleapis.com/auth/forms.responses.readonly",
    // Search Console
    "https://www.googleapis.com/auth/webmasters.readonly",
];

/// Scopes the index names that are granted to a *service account*, never to a
/// user, and that Google therefore refuses to show on a user consent screen.
/// They are Chat's app-authentication surface: `chat.bot` "only supports app
/// authentication", the `chat.app.*` family is used by a Chat app's service
/// account (with administrator approval), and `chat.import` exists solely for
/// domain-wide delegation to a service account.
///
/// One of them in the request fails the *entire* authorization with
/// `Error 400: invalid_scope — Some requested scopes cannot be shown:
/// [...]`, granting nothing, so they must stay out of [`scopes`]. Nothing is
/// lost by leaving them out: a user credential cannot call the methods behind
/// them, because those methods authenticate as the app, not as the user.
///
/// Keep in sync with Google's Chat authentication docs
/// (<https://developers.google.com/workspace/chat/authenticate-authorize> and
/// <https://developers.google.com/workspace/chat/authorize-import>): a refresh
/// that adds another `chat.app.*` scope needs it listed here too, or login
/// stops working for everyone.
pub(crate) const APP_AUTH_SCOPES: &[&str] = &[
    "https://www.googleapis.com/auth/chat.bot",
    "https://www.googleapis.com/auth/chat.import",
    "https://www.googleapis.com/auth/chat.app.delete",
    "https://www.googleapis.com/auth/chat.app.memberships",
    "https://www.googleapis.com/auth/chat.app.memberships.readonly",
    "https://www.googleapis.com/auth/chat.app.messages.readonly",
    "https://www.googleapis.com/auth/chat.app.spaces",
    "https://www.googleapis.com/auth/chat.app.spaces.create",
    "https://www.googleapis.com/auth/chat.app.spaces.readonly",
    "https://www.googleapis.com/auth/chat.app.all.memberships.readonly",
    "https://www.googleapis.com/auth/chat.app.all.messages.readonly",
    "https://www.googleapis.com/auth/chat.app.all.spaces.readonly",
];

/// OAuth2 client with PKCE support
#[derive(Clone)]
pub struct GoogleAuth {
    config: OAuthConfig,
    http_client: HttpClient,
    token_storage: Arc<RwLock<Option<TokenStorage>>>,
    store: TokenStore,
    token_endpoint: String,
}

impl GoogleAuth {
    /// Create new GoogleAuth from config
    pub async fn new(config: OAuthConfig) -> Result<Self> {
        Self::with_store(config, TokenStore::auto().await?).await
    }

    /// Create an auth handle bound to one named account's own token
    /// (multi-account support). Same OAuth client and scopes; every store
    /// read and write targets that account's keyring entry / fallback file
    /// exclusively. The name is validated and normalized here (rejects
    /// spaces, colons, and path separators; lowercased).
    pub async fn new_for(config: OAuthConfig, account: impl Into<String>) -> Result<Self> {
        let account = store::validate_account_name(account.into().as_str())?;
        let store = TokenStore::auto_named(&account).await?;
        Self::with_store(config, store).await
    }

    async fn with_store(config: OAuthConfig, store: TokenStore) -> Result<Self> {
        let http_client = HttpClient::builder()
            .timeout(Duration::from_secs(30))
            .build()
            .map_err(|e| GrrError::Config(format!("Failed to create HTTP client: {}", e)))?;
        // The store is NOT read here. Reading the OS keyring raises an
        // approval prompt on unsigned binaries (macOS re-prompts per build),
        // and the constructor runs for every command — including `--dry-run`,
        // `schema`, and `api list`, which never need a credential. The first
        // read happens in `get_access_token`, the first moment a credential
        // is actually required.
        Ok(Self {
            config,
            http_client,
            token_storage: Arc::new(RwLock::new(None)),
            store,
            token_endpoint: GOOGLE_TOKEN_URL.to_string(),
        })
    }

    /// A handle bound to `account`'s own token store, reusing this handle's
    /// config (and thus the same OAuth client). The token cache is NOT
    /// shared: the new handle loads the named account's stored token.
    ///
    /// This is what `commands/auth.rs` uses to rebind a default handle when
    /// a per-command `--account` is present.
    pub async fn with_account_store(&self, account: impl Into<String>) -> Result<Self> {
        Self::new_for(self.config.clone(), account).await
    }

    /// A fresh handle on the DEFAULT account's store — today's exact entry
    /// naming, no account suffix.
    ///
    /// `grr auth login`/`status` rebuild their handle through this so a
    /// named `--account` and the default take the same code path; without
    /// an account it is behavior-identical to the original construction.
    pub async fn with_default_account_store(&self) -> Result<Self> {
        Self::with_store(self.config.clone(), TokenStore::default_named().await?).await
    }

    /// Token storage backend in use (for logs and `auth login` output).
    pub fn token_backend(&self) -> &'static str {
        self.store.backend()
    }

    /// The shared HTTP client, which speaks HTTP/3 (QUIC) with an HTTP/2
    /// fallback.
    ///
    /// Exposed for `grr api`, which issues requests to arbitrary
    /// Discovery-derived URLs. Routing those through the same client is the
    /// point: the dynamic surface gets the same transport as the curated
    /// commands rather than quietly dropping to HTTP/1.1.
    pub fn http(&self) -> &HttpClient {
        &self.http_client
    }

    /// Construct an auth handle pre-loaded with an in-memory token.
    ///
    /// Test hook (`#[doc(hidden)]`): skips OAuth and persistent storage
    /// entirely until a test explicitly installs a token path.
    #[doc(hidden)]
    pub async fn with_token(config: OAuthConfig, storage: TokenStorage) -> Result<Self> {
        let this = Self::with_store(config, TokenStore::Memory).await?;
        *this.token_storage.write().await = Some(storage);
        Ok(this)
    }

    /// Override the OAuth2 token endpoint URL (test injection hook).
    #[doc(hidden)]
    pub fn with_token_endpoint(mut self, url: impl Into<String>) -> Self {
        self.token_endpoint = url.into();
        self
    }

    /// Redirect all token persistence to an explicit file (test injection
    /// hook). Production code never touches the real credential store
    /// because tests always pass a tempdir path here.
    #[doc(hidden)]
    pub fn with_token_path(mut self, path: PathBuf) -> Self {
        self.store = TokenStore::file(path);
        self
    }

    /// Get valid access token, refreshing if necessary
    pub async fn get_access_token(&self) -> Result<String> {
        let mut storage_guard = self.token_storage.write().await;

        // First credential use in this process (the constructor never reads
        // the store — see `with_store`). A logged-in user must never fall
        // into the implicit OAuth flow just because the token was not loaded
        // yet, so the store read happens before the None-means-fresh-install
        // branch below.
        if storage_guard.is_none() {
            *storage_guard = self.store.load().await?;
        }

        if let Some(storage) = storage_guard.as_ref() {
            if !storage.is_expired() {
                debug!(
                    "Using cached access token ({}s remaining)",
                    storage.remaining_secs()
                );
                return Ok(storage.access_token.clone());
            }

            // A stored credential that cannot produce a fresh token must never
            // trigger the implicit browser flow: `run_oauth_flow` binds port
            // 3434 mid-API-call and wedges callers for the callback timeout.
            let Some(refresh_token) = storage.refresh_token.clone() else {
                return Err(GrrError::Auth(
                    anyhow!(
                        "stored token is expired and has no refresh token; rerun `grr auth login`"
                    )
                    .into(),
                ));
            };

            info!("Refreshing expired access token");
            match self.refresh_token(&refresh_token).await {
                Ok(new_storage) => {
                    *storage_guard = Some(new_storage.clone());
                    self.save_token(&new_storage).await?;
                    return Ok(new_storage.access_token);
                }
                Err(e) => {
                    warn!("Token refresh failed: {}", e);
                    // Keep the expired storage in place: clearing it would
                    // route subsequent callers into the implicit OAuth flow.
                    return Err(GrrError::Auth(
                        anyhow!("{e}; rerun `grr auth login`").into(),
                    ));
                }
            }
        }

        // Fresh install / explicit login path: no stored token at all.
        info!("No valid token, starting OAuth flow");
        let storage = self.run_oauth_flow().await?;
        *storage_guard = Some(storage.clone());
        self.save_token(&storage).await?;
        Ok(storage.access_token)
    }

    /// POST one form to the OAuth token endpoint and parse the JSON body a
    /// single time. The client secret is appended when configured.
    ///
    /// Returns `(status, body)` rather than making a success decision here,
    /// so each caller keeps its own logic and messages: the PKCE exchange
    /// and the refresh grant report Google's error detail on non-2xx, while
    /// the device poll reads `error` codes out of a 400 body. Three callers
    /// previously duplicated this request/parse plumbing byte for byte.
    async fn token_request(
        &self,
        mut form: Vec<(&str, String)>,
    ) -> Result<(reqwest::StatusCode, serde_json::Value)> {
        if let Some(secret) = self
            .config
            .client_secret
            .as_deref()
            .filter(|s| !s.is_empty())
        {
            form.push(("client_secret", secret.to_string()));
        }

        let response = self
            .http_client
            .post(self.token_endpoint.as_str())
            .form(&form)
            .send()
            .await
            .map_err(GrrError::Http)?;

        let status = response.status();
        let body_text = response.text().await.map_err(GrrError::Http)?;
        let body: serde_json::Value = serde_json::from_str(&body_text).map_err(|e| {
            GrrError::Auth(
                anyhow!("token endpoint returned {status}: unparseable body ({e})").into(),
            )
        })?;
        Ok((status, body))
    }

    /// Refresh access token using refresh token.
    /// The secret is sent only when configured (Google mandates it even
    /// for Desktop clients; PKCE-only providers omit it entirely).
    async fn refresh_token(&self, refresh_token: &str) -> Result<TokenStorage> {
        let (status, token_data) = self
            .token_request(vec![
                ("client_id", self.config.client_id.clone()),
                ("refresh_token", refresh_token.to_string()),
                ("grant_type", "refresh_token".to_string()),
            ])
            .await?;

        if !status.is_success() {
            // Google reports rejection reasons (e.g. invalid_grant) in the
            // response body; surface them instead of a generic parse failure.
            return Err(GrrError::Auth(
                anyhow!(
                    "token endpoint returned {}: {}",
                    status,
                    crate::core::error::json_error_detail(&token_data)
                )
                .into(),
            ));
        }

        let mut storage = self::device::token_storage_from_response(&token_data, scopes())?;

        // Google only sometimes rotates the refresh token; when the
        // response omits one, keep the stored value instead of clobbering
        // it with None (which would brick all future refreshes).
        if storage.refresh_token.is_none() {
            storage.refresh_token = Some(refresh_token.to_string());
        }

        Ok(storage)
    }

    /// Revoke current token
    pub async fn revoke(&self) -> Result<()> {
        let mut storage_guard = self.token_storage.write().await;
        *storage_guard = None;
        self.store.delete().await?;
        info!("Token revoked and removed");
        Ok(())
    }
}

pub struct AuthConfigBuilder {
    config: OAuthConfig,
}

impl AuthConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: OAuthConfig::default(),
        }
    }

    pub fn client_id(mut self, id: impl Into<String>) -> Self {
        self.config.client_id = id.into();
        self
    }

    pub fn client_secret(mut self, secret: Option<String>) -> Self {
        // Empty strings behave as absent: the secret is omitted everywhere.
        self.config.client_secret = secret.filter(|s| !s.is_empty());
        self
    }

    pub async fn build(self) -> Result<GoogleAuth> {
        GoogleAuth::new(self.config).await
    }
}

impl Default for AuthConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The regression this guards: an app-authentication scope in the consent
    /// request makes Google reject the whole authorization — no scope is
    /// granted at all, so login cannot complete. And the filter must be
    /// surgical: Chat's *user* scopes stay in.
    #[test]
    fn the_consent_set_drops_app_authentication_scopes_only() {
        let consent = scopes();
        for scope in APP_AUTH_SCOPES {
            assert!(
                !consent.iter().any(|consented| consented == scope),
                "{scope} is app-authentication-only; Google refuses to show it and \
                 fails the entire authorization request"
            );
        }
        for scope in [
            "https://www.googleapis.com/auth/chat.messages",
            "https://www.googleapis.com/auth/chat.admin.spaces",
            "https://www.googleapis.com/auth/chat.memberships.app",
        ] {
            assert!(
                consent.iter().any(|consented| consented == scope),
                "{scope} is a user-consent scope and must stay in the request"
            );
        }
    }
}