Skip to main content

google_tool/
oauth.rs

1//! Google OAuth 2.0 Authorization Code flow helpers.
2//!
3//! This module deliberately exposes the state and PKCE verifier to the caller:
4//! the application must persist both, bound to the authenticated EME user,
5//! consume them once on callback, and validate state before exchanging a code.
6//! This crate does not own application sessions or credential persistence.
7
8use oauth2::{
9    AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge,
10    PkceCodeVerifier, RedirectUrl, RefreshToken, Scope, TokenResponse, TokenUrl,
11    basic::BasicClient,
12};
13use serde::{Deserialize, Serialize};
14use thiserror::Error;
15use url::Url;
16
17const GOOGLE_AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
18const GOOGLE_TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
19const CALENDAR_LIST_READONLY: &str =
20    "https://www.googleapis.com/auth/calendar.calendarlist.readonly";
21const CALENDAR_EVENTS_READONLY: &str = "https://www.googleapis.com/auth/calendar.events.readonly";
22const CALENDAR_EVENTS: &str = "https://www.googleapis.com/auth/calendar.events";
23
24/// Credentials and callback configuration for one Google OAuth application.
25#[derive(Clone)]
26pub struct GoogleOAuthConfig {
27    pub client_id: String,
28    pub client_secret: String,
29    pub redirect_uri: String,
30}
31
32/// Minimum EME permission requested from Google.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum CalendarScope {
35    ReadOnly,
36    ReadWrite,
37}
38
39/// Values that the server must persist for a pending authorization attempt.
40///
41/// Treat `state` and `pkce_verifier` as secrets. Never log or send them to
42/// the browser except for the authorization URL containing the state value.
43pub struct PendingAuthorization {
44    pub authorization_url: Url,
45    pub state: String,
46    pub pkce_verifier: String,
47}
48
49/// Token material returned by Google's token endpoint.
50///
51/// Refresh tokens are only returned when Google issues one; callers must keep
52/// an existing refresh token when reauthorization omits a replacement.
53#[derive(Clone, Serialize, Deserialize)]
54pub struct GoogleTokenSet {
55    pub access_token: String,
56    pub refresh_token: Option<String>,
57    pub expires_in_seconds: Option<u64>,
58    pub scopes: Vec<String>,
59}
60
61#[derive(Debug, Error)]
62pub enum GoogleOAuthError {
63    #[error("invalid Google OAuth configuration: {0}")]
64    Configuration(String),
65    #[error("Google OAuth request failed: {0}")]
66    Request(String),
67}
68
69fn client_id(config: &GoogleOAuthConfig) -> ClientId {
70    ClientId::new(config.client_id.clone())
71}
72
73fn client_secret(config: &GoogleOAuthConfig) -> ClientSecret {
74    ClientSecret::new(config.client_secret.clone())
75}
76
77fn auth_url() -> Result<AuthUrl, GoogleOAuthError> {
78    AuthUrl::new(GOOGLE_AUTH_URL.to_owned())
79        .map_err(|error| GoogleOAuthError::Configuration(error.to_string()))
80}
81
82fn token_url() -> Result<TokenUrl, GoogleOAuthError> {
83    TokenUrl::new(GOOGLE_TOKEN_URL.to_owned())
84        .map_err(|error| GoogleOAuthError::Configuration(error.to_string()))
85}
86
87fn redirect_url(config: &GoogleOAuthConfig) -> Result<RedirectUrl, GoogleOAuthError> {
88    RedirectUrl::new(config.redirect_uri.clone())
89        .map_err(|error| GoogleOAuthError::Configuration(error.to_string()))
90}
91
92fn http_client() -> Result<oauth2::reqwest::Client, GoogleOAuthError> {
93    oauth2::reqwest::ClientBuilder::new()
94        // OAuth token responses must not be redirected to an arbitrary host.
95        .redirect(oauth2::reqwest::redirect::Policy::none())
96        .build()
97        .map_err(|error| GoogleOAuthError::Request(error.to_string()))
98}
99
100/// Build a Google consent URL and fresh CSRF/PKCE values.
101///
102/// The caller must durably store `state` and `pkce_verifier` with the
103/// initiating EME user and a short expiry before redirecting the browser.
104pub fn authorization_request(
105    config: &GoogleOAuthConfig,
106    scope: CalendarScope,
107) -> Result<PendingAuthorization, GoogleOAuthError> {
108    let client = BasicClient::new(client_id(config))
109        .set_client_secret(client_secret(config))
110        .set_auth_uri(auth_url()?)
111        .set_token_uri(token_url()?)
112        .set_redirect_uri(redirect_url(config)?);
113    let (challenge, verifier) = PkceCodeChallenge::new_random_sha256();
114    let mut request = client
115        .authorize_url(CsrfToken::new_random)
116        .add_scope(Scope::new(CALENDAR_LIST_READONLY.to_owned()))
117        .add_extra_param("access_type", "offline")
118        .add_extra_param("include_granted_scopes", "false")
119        .add_extra_param("prompt", "consent")
120        .add_scope(Scope::new("openid".to_owned()))
121        .add_scope(Scope::new("email".to_owned()))
122        .set_pkce_challenge(challenge);
123    request = match scope {
124        CalendarScope::ReadOnly => {
125            request.add_scope(Scope::new(CALENDAR_EVENTS_READONLY.to_owned()))
126        }
127        CalendarScope::ReadWrite => request.add_scope(Scope::new(CALENDAR_EVENTS.to_owned())),
128    };
129    let (url, state) = request.url();
130    Ok(PendingAuthorization {
131        authorization_url: url,
132        state: state.secret().clone(),
133        pkce_verifier: verifier.secret().clone(),
134    })
135}
136
137/// Exchange a validated authorization code for Google tokens.
138pub async fn exchange_code(
139    config: &GoogleOAuthConfig,
140    code: String,
141    pkce_verifier: String,
142) -> Result<GoogleTokenSet, GoogleOAuthError> {
143    let client = BasicClient::new(client_id(config))
144        .set_client_secret(client_secret(config))
145        .set_auth_uri(auth_url()?)
146        .set_token_uri(token_url()?)
147        .set_redirect_uri(redirect_url(config)?);
148    let token = client
149        .exchange_code(AuthorizationCode::new(code))
150        .set_pkce_verifier(PkceCodeVerifier::new(pkce_verifier))
151        .request_async(&http_client()?)
152        .await
153        .map_err(|error| GoogleOAuthError::Request(error.to_string()))?;
154    Ok(token_set(&token))
155}
156
157/// Refresh an access token using a previously stored refresh token.
158pub async fn refresh_access_token(
159    config: &GoogleOAuthConfig,
160    refresh_token: &str,
161) -> Result<GoogleTokenSet, GoogleOAuthError> {
162    let client = BasicClient::new(client_id(config))
163        .set_client_secret(client_secret(config))
164        .set_auth_uri(auth_url()?)
165        .set_token_uri(token_url()?);
166    let token = client
167        .exchange_refresh_token(&RefreshToken::new(refresh_token.to_owned()))
168        .request_async(&http_client()?)
169        .await
170        .map_err(|error| GoogleOAuthError::Request(error.to_string()))?;
171    Ok(token_set(&token))
172}
173
174fn token_set<T: TokenResponse>(token: &T) -> GoogleTokenSet {
175    GoogleTokenSet {
176        access_token: token.access_token().secret().clone(),
177        refresh_token: token.refresh_token().map(|value| value.secret().clone()),
178        expires_in_seconds: token.expires_in().map(|value| value.as_secs()),
179        scopes: token
180            .scopes()
181            .map(|scopes| scopes.iter().map(|scope| scope.to_string()).collect())
182            .unwrap_or_default(),
183    }
184}
185
186/// Verified account identity returned by Google's OpenID Connect user-info endpoint.
187#[derive(Debug, Clone, Deserialize)]
188pub struct GoogleUserInfo {
189    pub sub: String,
190    pub email: String,
191    pub email_verified: bool,
192}
193
194/// Resolve the Google account associated with an access token.
195pub async fn fetch_user_info(access_token: &str) -> Result<GoogleUserInfo, GoogleOAuthError> {
196    let client = oauth2::reqwest::ClientBuilder::new()
197        .redirect(oauth2::reqwest::redirect::Policy::none())
198        .build()
199        .map_err(|error| GoogleOAuthError::Request(error.to_string()))?;
200    let response = client
201        .get("https://openidconnect.googleapis.com/v1/userinfo")
202        .bearer_auth(access_token)
203        .send()
204        .await
205        .map_err(|error| GoogleOAuthError::Request(error.to_string()))?
206        .error_for_status()
207        .map_err(|error| GoogleOAuthError::Request(error.to_string()))?;
208    response
209        .json::<GoogleUserInfo>()
210        .await
211        .map_err(|error| GoogleOAuthError::Request(error.to_string()))
212}
213
214/// Revoke a Google OAuth token using Google's fixed revocation endpoint.
215pub async fn revoke_token(token: &str) -> Result<(), GoogleOAuthError> {
216    let client = oauth2::reqwest::ClientBuilder::new()
217        .redirect(oauth2::reqwest::redirect::Policy::none())
218        .build()
219        .map_err(|error| GoogleOAuthError::Request(error.to_string()))?;
220    client
221        .post("https://oauth2.googleapis.com/revoke")
222        .form(&[("token", token)])
223        .send()
224        .await
225        .map_err(|error| GoogleOAuthError::Request(error.to_string()))?
226        .error_for_status()
227        .map_err(|error| GoogleOAuthError::Request(error.to_string()))?;
228    Ok(())
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    fn authorization_url(scope: CalendarScope) -> Url {
236        let config = GoogleOAuthConfig {
237            client_id: "test-client".to_owned(),
238            client_secret: "test-secret".to_owned(),
239            redirect_uri: "http://localhost:8080/integrations/google/oauth/callback".to_owned(),
240        };
241        authorization_request(&config, scope)
242            .expect("authorization URL should be constructed")
243            .authorization_url
244    }
245
246    fn query_parameter<'a>(url: &'a Url, name: &str) -> Option<String> {
247        url.query_pairs()
248            .find(|(key, _)| key == name)
249            .map(|(_, value)| value.into_owned())
250    }
251
252    #[test]
253    fn authorization_requests_show_consent_without_inheriting_old_scopes() {
254        let url = authorization_url(CalendarScope::ReadOnly);
255
256        assert_eq!(query_parameter(&url, "prompt").as_deref(), Some("consent"));
257        assert_eq!(
258            query_parameter(&url, "access_type").as_deref(),
259            Some("offline")
260        );
261        assert_eq!(
262            query_parameter(&url, "include_granted_scopes").as_deref(),
263            Some("false")
264        );
265
266        let scopes = query_parameter(&url, "scope").expect("scope parameter");
267        assert!(scopes.contains(CALENDAR_LIST_READONLY));
268        assert!(scopes.contains(CALENDAR_EVENTS_READONLY));
269        assert!(
270            !scopes
271                .split_whitespace()
272                .any(|scope| scope == CALENDAR_EVENTS)
273        );
274    }
275
276    #[test]
277    fn read_write_authorization_requests_write_scope() {
278        let url = authorization_url(CalendarScope::ReadWrite);
279        let scopes = query_parameter(&url, "scope").expect("scope parameter");
280
281        assert!(scopes.contains(CALENDAR_LIST_READONLY));
282        assert!(scopes.contains(CALENDAR_EVENTS));
283        assert!(
284            !scopes
285                .split_whitespace()
286                .any(|scope| scope == CALENDAR_EVENTS_READONLY)
287        );
288    }
289}