Skip to main content

pidge_gmail/
auth.rs

1//! Google sign-in: authorization code + PKCE on a loopback redirect, token
2//! exchange and refresh, and an access-token source for [`crate::GmailProvider`].
3//!
4//! pidge cannot ship a Google OAuth client for everyone (`gmail.modify` is a
5//! restricted scope), so whoever runs pidge brings their own: a "Desktop
6//! app" client locally (`PIDGE_GOOGLE_CLIENT_ID` / `PIDGE_GOOGLE_CLIENT_SECRET`),
7//! a "Web application" client when hosted. Google treats a desktop client's
8//! secret as non-confidential, but its token endpoint still wants it.
9//!
10//! Token persistence reuses `pidge-client`'s [`TokenBackend`] seam, so the
11//! CLI's keychain/file store ([`pidge_client::auth::LocalBackend`]) and the
12//! hosted server's secret store both work unchanged.
13
14use std::sync::Arc;
15use std::time::Duration;
16
17use base64::Engine;
18use base64::engine::general_purpose::URL_SAFE_NO_PAD_INDIFFERENT;
19use chrono::Utc;
20use pidge_client::auth::browser_flow::{
21    make_code_challenge, make_code_verifier, make_random, wait_for_callback,
22};
23use pidge_client::auth::{TokenBackend, TokenSet};
24use pidge_core::provider::{ProviderError, ProviderResult};
25use serde::Deserialize;
26
27/// Google's authorization endpoint.
28pub const GOOGLE_AUTH_BASE: &str = "https://accounts.google.com/o/oauth2/v2/auth";
29/// Google's token endpoint.
30pub const GOOGLE_TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
31
32/// The scopes pidge asks Google for, space separated.
33///
34/// - `openid email`: the id token's `email` claim names the account.
35/// - `gmail.modify`: read, label, archive, trash, draft and send. Never
36///   permanent deletion (that would need the full `mail.google.com` scope).
37/// - `calendar.events`: read and write events on the user's calendars.
38/// - `calendar.freebusy`: `freeBusy.query` for other people. It is the
39///   narrowest scope that endpoint accepts; `calendar.readonly` would also
40///   work but grants reading every calendar's details, which pidge never
41///   needs (it only uses the `primary` calendar, so no `calendarList` read).
42pub const SCOPES: &str = "openid email https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.freebusy";
43
44/// How long the loopback flow waits for the browser.
45const CALLBACK_TIMEOUT: Duration = Duration::from_secs(300);
46
47/// A Google OAuth client.
48#[derive(Clone, PartialEq, Eq)]
49pub struct GoogleOAuthConfig {
50    pub client_id: String,
51    pub client_secret: String,
52    /// Authorization endpoint (default [`GOOGLE_AUTH_BASE`]).
53    pub auth_base: String,
54    /// Token endpoint (default [`GOOGLE_TOKEN_URL`]).
55    pub token_url: String,
56}
57
58impl std::fmt::Debug for GoogleOAuthConfig {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        f.debug_struct("GoogleOAuthConfig")
61            .field("client_id", &self.client_id)
62            .field("client_secret", &"<redacted>")
63            .field("auth_base", &self.auth_base)
64            .field("token_url", &self.token_url)
65            .finish()
66    }
67}
68
69impl GoogleOAuthConfig {
70    /// A client with Google's real endpoints.
71    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
72        Self {
73            client_id: client_id.into(),
74            client_secret: client_secret.into(),
75            auth_base: GOOGLE_AUTH_BASE.to_string(),
76            token_url: GOOGLE_TOKEN_URL.to_string(),
77        }
78    }
79
80    /// From `PIDGE_GOOGLE_CLIENT_ID` and `PIDGE_GOOGLE_CLIENT_SECRET`; `None`
81    /// unless both are set and non-empty.
82    pub fn from_env() -> Option<Self> {
83        let get = |k: &str| {
84            std::env::var(k)
85                .ok()
86                .map(|v| v.trim().to_string())
87                .filter(|v| !v.is_empty())
88        };
89        Some(Self::new(
90            get("PIDGE_GOOGLE_CLIENT_ID")?,
91            get("PIDGE_GOOGLE_CLIENT_SECRET")?,
92        ))
93    }
94}
95
96/// The URL to send the user's browser to. `challenge` is the PKCE S256
97/// challenge, `state` the CSRF nonce. `access_type=offline` plus
98/// `prompt=consent` makes Google return a refresh token every time.
99pub fn authorize_url(
100    cfg: &GoogleOAuthConfig,
101    redirect_uri: &str,
102    challenge: &str,
103    state: &str,
104    login_hint: Option<&str>,
105) -> String {
106    let mut url = url::Url::parse(&cfg.auth_base)
107        .unwrap_or_else(|_| url::Url::parse(GOOGLE_AUTH_BASE).expect("constant URL parses"));
108    {
109        let mut q = url.query_pairs_mut();
110        q.append_pair("client_id", &cfg.client_id)
111            .append_pair("redirect_uri", redirect_uri)
112            .append_pair("response_type", "code")
113            .append_pair("scope", SCOPES)
114            .append_pair("access_type", "offline")
115            .append_pair("prompt", "consent")
116            .append_pair("include_granted_scopes", "true")
117            .append_pair("code_challenge", challenge)
118            .append_pair("code_challenge_method", "S256")
119            .append_pair("state", state);
120        if let Some(hint) = login_hint.map(str::trim).filter(|h| !h.is_empty()) {
121            q.append_pair("login_hint", hint);
122        }
123    }
124    url.into()
125}
126
127#[derive(Deserialize)]
128struct TokenResponse {
129    access_token: String,
130    #[serde(default)]
131    expires_in: Option<i64>,
132    #[serde(default)]
133    refresh_token: Option<String>,
134    #[serde(default)]
135    scope: Option<String>,
136    #[serde(default)]
137    id_token: Option<String>,
138}
139
140#[derive(Deserialize, Default)]
141struct TokenError {
142    #[serde(default)]
143    error: String,
144    #[serde(default)]
145    error_description: String,
146}
147
148/// POST a form to the token endpoint. `invalid_grant` (a revoked or
149/// expired refresh token, or a stale code) is `Auth` with an empty account;
150/// callers that know the account fill it in.
151async fn token_request(
152    http: &reqwest::Client,
153    cfg: &GoogleOAuthConfig,
154    form: &[(&str, &str)],
155) -> ProviderResult<TokenResponse> {
156    let resp = crate::http::send_with_retry(http.post(&cfg.token_url).form(form)).await?;
157    let status = resp.status();
158    let text = resp.text().await.map_err(crate::http::transport)?;
159    if status.is_success() {
160        return serde_json::from_str(&text)
161            .map_err(|e| ProviderError::Other(format!("unreadable Google token response: {e}")));
162    }
163    let err: TokenError = serde_json::from_str(&text).unwrap_or_default();
164    let message = if err.error_description.is_empty() {
165        format!("{} (HTTP {})", err.error, status.as_u16())
166    } else {
167        format!("{}: {}", err.error, err.error_description)
168    };
169    Err(match err.error.as_str() {
170        "invalid_grant" | "unauthorized_client" | "invalid_client" => ProviderError::Auth {
171            account: String::new(),
172            message,
173        },
174        _ => ProviderError::Other(format!("Google token endpoint: {message}")),
175    })
176}
177
178fn expires_at(expires_in: Option<i64>) -> chrono::DateTime<Utc> {
179    Utc::now() + chrono::Duration::seconds(expires_in.unwrap_or(3600).max(0))
180}
181
182/// The `email` claim of an id token. Not verified: the token came straight
183/// from Google's token endpoint over TLS, in answer to our own code.
184fn email_from_id_token(id_token: &str) -> Option<String> {
185    let payload = id_token.split('.').nth(1)?;
186    let bytes = URL_SAFE_NO_PAD_INDIFFERENT.decode(payload).ok()?;
187    let claims: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
188    claims
189        .get("email")
190        .and_then(|v| v.as_str())
191        .map(|s| s.to_ascii_lowercase())
192}
193
194/// Exchange an authorization code for tokens; also returns the account's
195/// address from the id token.
196pub async fn exchange_code(
197    http: &reqwest::Client,
198    cfg: &GoogleOAuthConfig,
199    code: &str,
200    verifier: &str,
201    redirect_uri: &str,
202) -> ProviderResult<(TokenSet, String)> {
203    let r = token_request(
204        http,
205        cfg,
206        &[
207            ("grant_type", "authorization_code"),
208            ("code", code),
209            ("code_verifier", verifier),
210            ("redirect_uri", redirect_uri),
211            ("client_id", &cfg.client_id),
212            ("client_secret", &cfg.client_secret),
213        ],
214    )
215    .await?;
216    let email = r
217        .id_token
218        .as_deref()
219        .and_then(email_from_id_token)
220        .ok_or_else(|| ProviderError::Other("Google did not say which account signed in".into()))?;
221    let refresh_token = r.refresh_token.ok_or_else(|| {
222        ProviderError::Other("Google returned no refresh token; sign in again".into())
223    })?;
224    Ok((
225        TokenSet {
226            access_token: r.access_token,
227            refresh_token,
228            expires_at: expires_at(r.expires_in),
229            scope: r.scope,
230        },
231        email,
232    ))
233}
234
235/// Refresh `tokens`. Google usually leaves `refresh_token` out of a refresh
236/// response: the old one stays valid and is kept.
237pub async fn refresh(
238    http: &reqwest::Client,
239    cfg: &GoogleOAuthConfig,
240    tokens: &TokenSet,
241) -> ProviderResult<TokenSet> {
242    let r = token_request(
243        http,
244        cfg,
245        &[
246            ("grant_type", "refresh_token"),
247            ("refresh_token", &tokens.refresh_token),
248            ("client_id", &cfg.client_id),
249            ("client_secret", &cfg.client_secret),
250        ],
251    )
252    .await?;
253    Ok(TokenSet {
254        access_token: r.access_token,
255        refresh_token: r
256            .refresh_token
257            .filter(|t| !t.is_empty())
258            .unwrap_or_else(|| tokens.refresh_token.clone()),
259        expires_at: expires_at(r.expires_in),
260        scope: r.scope.or_else(|| tokens.scope.clone()),
261    })
262}
263
264/// The whole local sign-in: listen on `127.0.0.1:<random port>`, hand the
265/// authorization URL to `on_open` (open a browser, print it), wait up to
266/// five minutes for Google's redirect, check `state`, exchange the code.
267pub async fn run_loopback_flow(
268    cfg: &GoogleOAuthConfig,
269    on_open: impl FnOnce(&str),
270) -> ProviderResult<(TokenSet, String)> {
271    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
272        .await
273        .map_err(|e| ProviderError::Other(format!("could not listen for the sign-in: {e}")))?;
274    let port = listener
275        .local_addr()
276        .map_err(|e| ProviderError::Other(format!("could not listen for the sign-in: {e}")))?
277        .port();
278    let redirect_uri = format!("http://127.0.0.1:{port}");
279    let verifier = make_code_verifier();
280    let challenge = make_code_challenge(&verifier);
281    let state = make_random(32);
282    on_open(&authorize_url(cfg, &redirect_uri, &challenge, &state, None));
283    let params = wait_for_callback(listener, CALLBACK_TIMEOUT, "Google sign-in")
284        .await
285        .map_err(|e| ProviderError::Other(e.to_string()))?;
286    if params.state != state {
287        return Err(ProviderError::Invalid(
288            "the sign-in answer did not match this sign-in (state mismatch)".into(),
289        ));
290    }
291    let http = http_client()?;
292    exchange_code(&http, cfg, &params.code, &verifier, &redirect_uri).await
293}
294
295/// A `reqwest::Client` with pidge's user agent.
296pub(crate) fn http_client() -> ProviderResult<reqwest::Client> {
297    reqwest::Client::builder()
298        .user_agent(format!("pidge/{}", env!("CARGO_PKG_VERSION")))
299        .build()
300        .map_err(crate::http::transport)
301}
302
303/// Access tokens for one Google account, refreshed on demand and saved
304/// back through `backend`.
305pub struct GoogleAuth {
306    http: reqwest::Client,
307    cfg: GoogleOAuthConfig,
308    backend: Arc<dyn TokenBackend>,
309    email: String,
310    /// Serializes refreshes so two concurrent calls don't both spend the
311    /// refresh token.
312    refresh_lock: tokio::sync::Mutex<()>,
313}
314
315impl GoogleAuth {
316    pub fn new(
317        http: reqwest::Client,
318        cfg: GoogleOAuthConfig,
319        backend: Arc<dyn TokenBackend>,
320        email: impl Into<String>,
321    ) -> Self {
322        Self {
323            http,
324            cfg,
325            backend,
326            email: email.into(),
327            refresh_lock: tokio::sync::Mutex::new(()),
328        }
329    }
330
331    /// The account's address.
332    pub fn email(&self) -> &str {
333        &self.email
334    }
335
336    /// The HTTP client this account's calls share.
337    pub fn http(&self) -> &reqwest::Client {
338        &self.http
339    }
340
341    fn auth_error(&self, message: impl Into<String>) -> ProviderError {
342        ProviderError::Auth {
343            account: self.email.clone(),
344            message: message.into(),
345        }
346    }
347
348    async fn load(&self) -> ProviderResult<TokenSet> {
349        self.backend
350            .load(&self.email)
351            .await
352            .map_err(|e| ProviderError::Other(format!("could not read stored tokens: {e}")))?
353            .ok_or_else(|| self.auth_error("no stored session"))
354    }
355
356    /// A valid access token, refreshing (and saving) first when the stored
357    /// one is within a minute of expiry.
358    pub async fn access_token(&self) -> ProviderResult<String> {
359        let tokens = self.load().await?;
360        if !tokens.needs_refresh() {
361            return Ok(tokens.access_token);
362        }
363        let _guard = self.refresh_lock.lock().await;
364        // Another task may have refreshed while we waited.
365        let tokens = self.load().await?;
366        if !tokens.needs_refresh() {
367            return Ok(tokens.access_token);
368        }
369        let fresh = refresh(&self.http, &self.cfg, &tokens)
370            .await
371            .map_err(|e| match e {
372                ProviderError::Auth { message, .. } => self.auth_error(message),
373                other => other,
374            })?;
375        self.backend
376            .save(&self.email, &fresh)
377            .await
378            .map_err(|e| ProviderError::Other(format!("could not save refreshed tokens: {e}")))?;
379        Ok(fresh.access_token)
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use crate::test_support::MemoryBackend;
387    use chrono::Duration as ChronoDuration;
388    use wiremock::matchers::{body_string_contains, method, path};
389    use wiremock::{Mock, MockServer, ResponseTemplate};
390
391    fn cfg(server: &MockServer) -> GoogleOAuthConfig {
392        GoogleOAuthConfig {
393            client_id: "cid".into(),
394            client_secret: "secret".into(),
395            auth_base: format!("{}/auth", server.uri()),
396            token_url: format!("{}/token", server.uri()),
397        }
398    }
399
400    #[test]
401    fn authorize_url_asks_for_offline_access_with_pkce() {
402        let c = GoogleOAuthConfig::new("cid", "s");
403        let u = url::Url::parse(&authorize_url(
404            &c,
405            "http://127.0.0.1:5555",
406            "CH",
407            "ST",
408            Some("jane@example.com"),
409        ))
410        .unwrap();
411        assert_eq!(u.host_str(), Some("accounts.google.com"));
412        let q: std::collections::HashMap<_, _> = u.query_pairs().into_owned().collect();
413        assert_eq!(q["access_type"], "offline");
414        assert_eq!(q["prompt"], "consent");
415        assert_eq!(q["code_challenge_method"], "S256");
416        assert_eq!(q["code_challenge"], "CH");
417        assert_eq!(q["state"], "ST");
418        assert_eq!(q["redirect_uri"], "http://127.0.0.1:5555");
419        assert_eq!(q["login_hint"], "jane@example.com");
420        assert!(q["scope"].contains("gmail.modify"));
421    }
422
423    #[tokio::test]
424    async fn exchange_reads_the_email_from_the_id_token() {
425        let server = MockServer::start().await;
426        let claims = URL_SAFE_NO_PAD_INDIFFERENT.encode(br#"{"email":"Jane@Example.com"}"#);
427        Mock::given(method("POST"))
428            .and(path("/token"))
429            .and(body_string_contains("code_verifier=VER"))
430            .and(body_string_contains("grant_type=authorization_code"))
431            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
432                "access_token": "AT",
433                "refresh_token": "RT",
434                "expires_in": 3599,
435                "scope": SCOPES,
436                "id_token": format!("h.{claims}.s"),
437            })))
438            .mount(&server)
439            .await;
440        let (t, email) = exchange_code(
441            &reqwest::Client::new(),
442            &cfg(&server),
443            "CODE",
444            "VER",
445            "http://127.0.0.1:1",
446        )
447        .await
448        .unwrap();
449        assert_eq!(email, "jane@example.com");
450        assert_eq!(t.access_token, "AT");
451        assert_eq!(t.refresh_token, "RT");
452    }
453
454    #[tokio::test]
455    async fn refresh_keeps_the_old_refresh_token() {
456        let server = MockServer::start().await;
457        Mock::given(method("POST"))
458            .and(path("/token"))
459            .and(body_string_contains("refresh_token=OLD_RT"))
460            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
461                "access_token": "NEW_AT",
462                "expires_in": 3599
463            })))
464            .expect(1)
465            .mount(&server)
466            .await;
467        let backend = Arc::new(MemoryBackend::default());
468        backend.put(
469            "jane@example.com",
470            TokenSet {
471                access_token: "OLD_AT".into(),
472                refresh_token: "OLD_RT".into(),
473                expires_at: Utc::now() - ChronoDuration::seconds(10),
474                scope: Some(SCOPES.into()),
475            },
476        );
477        let auth = GoogleAuth::new(
478            reqwest::Client::new(),
479            cfg(&server),
480            backend.clone(),
481            "jane@example.com",
482        );
483        assert_eq!(auth.access_token().await.unwrap(), "NEW_AT");
484        let stored = backend.get("jane@example.com").unwrap();
485        assert_eq!(stored.access_token, "NEW_AT");
486        assert_eq!(stored.refresh_token, "OLD_RT");
487        assert_eq!(stored.scope.as_deref(), Some(SCOPES));
488        // Fresh now: no second refresh.
489        assert_eq!(auth.access_token().await.unwrap(), "NEW_AT");
490    }
491
492    #[tokio::test]
493    async fn invalid_grant_is_an_auth_error_for_the_account() {
494        let server = MockServer::start().await;
495        Mock::given(method("POST"))
496            .and(path("/token"))
497            .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({
498                "error": "invalid_grant",
499                "error_description": "Token has been expired or revoked."
500            })))
501            .mount(&server)
502            .await;
503        let backend = Arc::new(MemoryBackend::default());
504        backend.put(
505            "jane@example.com",
506            TokenSet {
507                access_token: "OLD_AT".into(),
508                refresh_token: "OLD_RT".into(),
509                expires_at: Utc::now() - ChronoDuration::seconds(10),
510                scope: None,
511            },
512        );
513        let auth = GoogleAuth::new(
514            reqwest::Client::new(),
515            cfg(&server),
516            backend,
517            "jane@example.com",
518        );
519        match auth.access_token().await.unwrap_err() {
520            ProviderError::Auth { account, message } => {
521                assert_eq!(account, "jane@example.com");
522                assert!(message.contains("invalid_grant"));
523            }
524            other => panic!("expected Auth, got {other:?}"),
525        }
526    }
527}