Skip to main content

redseat_api/
google.rs

1//! Google sign-in in the browser, for desktop apps: OAuth 2.0 for installed apps with a
2//! loopback redirect and PKCE (S256). Not available on wasm.
3//!
4//! 1. [`GoogleSignIn::start`] listens on `127.0.0.1` at a random port and builds the
5//!    authorization URL.
6//! 2. The app opens [`GoogleSignIn::authorization_url`] in the browser (or calls
7//!    [`open_browser`] with the `open-browser` feature).
8//! 3. [`GoogleSignIn::finish`] waits for the redirect, answers the browser with a "you
9//!    can close this window" page, and exchanges the code for tokens.
10//!
11//! The ID token then signs in to the cloud with
12//! [`crate::CloudClient::sign_in_with_google_id_token`].
13
14use std::sync::Arc;
15use std::time::Duration;
16
17use base64::Engine;
18use base64::engine::general_purpose::URL_SAFE_NO_PAD;
19use serde::Deserialize;
20use sha2::{Digest, Sha256};
21use tokio::io::{AsyncReadExt, AsyncWriteExt};
22use tokio::net::{TcpListener, TcpStream};
23use tokio::sync::watch;
24
25use crate::error::{Error, Result};
26use crate::http::HttpTransport;
27use crate::transport::{Request, Transport};
28
29pub const GOOGLE_AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
30pub const GOOGLE_TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
31/// How long [`GoogleSignIn::finish`] waits for the user by default.
32pub const DEFAULT_SIGN_IN_TIMEOUT: Duration = Duration::from_secs(5 * 60);
33const SCOPES: &str = "openid email profile";
34
35/// A Google OAuth client of type "Desktop app". Its secret is not confidential for
36/// installed apps, but it is still the caller's to supply.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct GoogleDesktopConfig {
39    pub client_id: String,
40    pub client_secret: String,
41    /// How long to wait for the browser redirect.
42    pub timeout: Duration,
43    pub auth_url: String,
44    pub token_url: String,
45}
46
47impl GoogleDesktopConfig {
48    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
49        GoogleDesktopConfig {
50            client_id: client_id.into(),
51            client_secret: client_secret.into(),
52            timeout: DEFAULT_SIGN_IN_TIMEOUT,
53            auth_url: GOOGLE_AUTH_URL.to_owned(),
54            token_url: GOOGLE_TOKEN_URL.to_owned(),
55        }
56    }
57
58    /// Reads the JSON file Google Cloud gives for a "Desktop app" OAuth client
59    /// (`{"installed": {"client_id": ..., "client_secret": ..., ...}}`).
60    pub fn from_json(json: &str) -> Result<Self> {
61        #[derive(Deserialize)]
62        struct File {
63            installed: Option<Installed>,
64        }
65        #[derive(Deserialize)]
66        struct Installed {
67            client_id: String,
68            client_secret: String,
69            auth_uri: Option<String>,
70            token_uri: Option<String>,
71        }
72        let file: File = serde_json::from_str(json)
73            .map_err(|error| Error::sign_in(format!("invalid Google client file: {error}")))?;
74        let installed = file.installed.ok_or_else(|| {
75            Error::sign_in("the Google client file is not for a \"Desktop app\" client")
76        })?;
77        let mut config = Self::new(installed.client_id, installed.client_secret);
78        if let Some(auth_url) = installed.auth_uri {
79            config.auth_url = auth_url;
80        }
81        if let Some(token_url) = installed.token_uri {
82            config.token_url = token_url;
83        }
84        Ok(config)
85    }
86}
87
88/// Tokens from Google. `id_token` is what the cloud wants.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct GoogleTokens {
91    pub id_token: String,
92    pub access_token: Option<String>,
93    pub refresh_token: Option<String>,
94    /// Seconds.
95    pub expires_in: Option<u64>,
96}
97
98/// Cancels a pending sign-in from anywhere: [`GoogleSignIn::finish`] then fails with
99/// [`Error::Cancelled`].
100#[derive(Debug, Clone)]
101pub struct SignInCanceller(Arc<watch::Sender<bool>>);
102
103impl SignInCanceller {
104    pub fn cancel(&self) {
105        self.0.send_replace(true);
106    }
107}
108
109/// A sign-in waiting for the browser.
110#[derive(Debug)]
111pub struct GoogleSignIn {
112    config: GoogleDesktopConfig,
113    listener: TcpListener,
114    url: String,
115    redirect_uri: String,
116    state: String,
117    verifier: String,
118    cancel: Arc<watch::Sender<bool>>,
119}
120
121fn random_token(bytes: usize) -> Result<String> {
122    let mut buffer = vec![0u8; bytes];
123    getrandom::fill(&mut buffer)
124        .map_err(|e| Error::transport(format!("random generator failed: {e}")))?;
125    Ok(URL_SAFE_NO_PAD.encode(buffer))
126}
127
128/// The PKCE S256 challenge of `verifier`.
129fn pkce_challenge(verifier: &str) -> String {
130    URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
131}
132
133impl GoogleSignIn {
134    /// Listens on the loopback and builds the authorization URL.
135    pub async fn start(config: GoogleDesktopConfig) -> Result<Self> {
136        let listener = TcpListener::bind(("127.0.0.1", 0))
137            .await
138            .map_err(|e| Error::transport(format!("cannot listen on the loopback: {e}")))?;
139        let port = listener
140            .local_addr()
141            .map_err(|e| Error::transport(format!("cannot listen on the loopback: {e}")))?
142            .port();
143        let redirect_uri = format!("http://127.0.0.1:{port}");
144        let state = random_token(16)?;
145        // 32 bytes give the 43 characters PKCE asks for at least.
146        let verifier = random_token(32)?;
147
148        let mut url = url::Url::parse(&config.auth_url)
149            .map_err(|e| Error::transport(format!("invalid authorization URL: {e}")))?;
150        url.query_pairs_mut()
151            .append_pair("client_id", &config.client_id)
152            .append_pair("redirect_uri", &redirect_uri)
153            .append_pair("response_type", "code")
154            .append_pair("scope", SCOPES)
155            .append_pair("code_challenge", &pkce_challenge(&verifier))
156            .append_pair("code_challenge_method", "S256")
157            .append_pair("state", &state)
158            .append_pair("prompt", "select_account");
159
160        Ok(GoogleSignIn {
161            config,
162            listener,
163            url: url.into(),
164            redirect_uri,
165            state,
166            verifier,
167            cancel: Arc::new(watch::channel(false).0),
168        })
169    }
170
171    /// The URL to open in the browser.
172    pub fn authorization_url(&self) -> &str {
173        &self.url
174    }
175
176    /// `http://127.0.0.1:<port>`.
177    pub fn redirect_uri(&self) -> &str {
178        &self.redirect_uri
179    }
180
181    pub fn canceller(&self) -> SignInCanceller {
182        SignInCanceller(self.cancel.clone())
183    }
184
185    /// Waits for the browser redirect, then exchanges the code for tokens. Fails with
186    /// [`Error::Timeout`] after the configured timeout, [`Error::Cancelled`] when
187    /// cancelled, and [`Error::SignIn`] when Google or the user refused, or the
188    /// redirect does not carry this sign-in's `state`.
189    pub async fn finish(self) -> Result<GoogleTokens> {
190        let code = self.wait_for_code().await?;
191        self.exchange_code(&code).await
192    }
193
194    async fn wait_for_code(&self) -> Result<String> {
195        let mut cancelled = self.cancel.subscribe();
196        let wait = async {
197            loop {
198                let (stream, _) = self
199                    .listener
200                    .accept()
201                    .await
202                    .map_err(|e| Error::transport(format!("loopback listener failed: {e}")))?;
203                if let Some(result) = self.handle_redirect(stream).await {
204                    return result;
205                }
206            }
207        };
208        tokio::select! {
209            result = wait => result,
210            _ = tokio::time::sleep(self.config.timeout) => Err(Error::Timeout {
211                message: "no answer from the browser in time".to_owned(),
212                path: None,
213            }),
214            _ = cancelled.wait_for(|cancelled| *cancelled) => {
215                Err(Error::Cancelled { message: "sign-in cancelled".to_owned() })
216            }
217        }
218    }
219
220    /// Answers one browser request. `None` when it is not the redirect (a favicon,
221    /// a preconnect): keep waiting.
222    async fn handle_redirect(&self, mut stream: TcpStream) -> Option<Result<String>> {
223        let head = tokio::time::timeout(Duration::from_secs(5), read_head(&mut stream))
224            .await
225            .ok()??;
226        let target = head.split_whitespace().nth(1)?.to_owned();
227        let url = url::Url::parse(&format!("http://127.0.0.1{target}")).ok()?;
228        let param = |name: &str| {
229            url.query_pairs()
230                .find(|(key, _)| key == name)
231                .map(|(_, value)| value.into_owned())
232        };
233        let (code, error, state) = (param("code"), param("error"), param("state"));
234        if url.path() != "/" || (code.is_none() && error.is_none()) {
235            respond(&mut stream, "404 Not Found", "Not found", "").await;
236            return None;
237        }
238
239        let result = if state.as_deref() != Some(self.state.as_str()) {
240            Err(Error::sign_in(
241                "the browser answer does not belong to this sign-in (state mismatch)",
242            ))
243        } else if let Some(error) = error {
244            Err(Error::sign_in(format!(
245                "Google refused the sign-in: {error}"
246            )))
247        } else {
248            code.ok_or_else(|| Error::sign_in("no authorization code"))
249        };
250        match &result {
251            Ok(_) => {
252                respond(
253                    &mut stream,
254                    "200 OK",
255                    "Signed in",
256                    "You are signed in to Redseat. You can close this window.",
257                )
258                .await
259            }
260            Err(_) => {
261                respond(
262                    &mut stream,
263                    "400 Bad Request",
264                    "Sign-in failed",
265                    "The sign-in did not complete. You can close this window and try again.",
266                )
267                .await
268            }
269        }
270        Some(result)
271    }
272
273    async fn exchange_code(&self, code: &str) -> Result<GoogleTokens> {
274        let transport = HttpTransport::new(&self.config.token_url)?;
275        let form = [
276            ("code", code),
277            ("client_id", &self.config.client_id),
278            ("client_secret", &self.config.client_secret),
279            ("redirect_uri", &self.redirect_uri),
280            ("grant_type", "authorization_code"),
281            ("code_verifier", &self.verifier),
282        ]
283        .iter()
284        .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
285        .collect();
286        let response = transport
287            .request(Request::post(self.config.token_url.clone()).form(form))
288            .await
289            .map_err(|error| match error {
290                Error::Unauthorized { message, .. } | Error::Transport { message, .. } => {
291                    Error::sign_in(format!("Google token exchange failed: {message}"))
292                }
293                other => other,
294            })?;
295
296        #[derive(Deserialize)]
297        struct TokenAnswer {
298            id_token: Option<String>,
299            access_token: Option<String>,
300            refresh_token: Option<String>,
301            expires_in: Option<u64>,
302        }
303        let answer: TokenAnswer = response.json()?;
304        Ok(GoogleTokens {
305            id_token: answer
306                .id_token
307                .ok_or_else(|| Error::sign_in("Google answered without an ID token"))?,
308            access_token: answer.access_token,
309            refresh_token: answer.refresh_token,
310            expires_in: answer.expires_in,
311        })
312    }
313}
314
315/// Reads a request head (up to 16 KiB).
316async fn read_head(stream: &mut TcpStream) -> Option<String> {
317    let mut head = Vec::new();
318    let mut buffer = [0u8; 2048];
319    while !head.windows(4).any(|w| w == b"\r\n\r\n") {
320        if head.len() > 16 * 1024 {
321            return None;
322        }
323        let n = stream.read(&mut buffer).await.ok()?;
324        if n == 0 {
325            break;
326        }
327        head.extend_from_slice(&buffer[..n]);
328    }
329    Some(String::from_utf8_lossy(&head).into_owned())
330}
331
332async fn respond(stream: &mut TcpStream, status: &str, title: &str, message: &str) {
333    let body = format!(
334        "<!doctype html><html><head><meta charset=\"utf-8\"><title>{title}</title></head>\
335         <body style=\"font-family:system-ui,sans-serif;text-align:center;margin-top:20vh\">\
336         <h1>{title}</h1><p>{message}</p></body></html>"
337    );
338    let response = format!(
339        "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\n\
340         Cache-Control: no-store\r\nConnection: close\r\n\r\n{body}",
341        body.len()
342    );
343    // The browser may already be gone: nothing to do then.
344    let _ = stream.write_all(response.as_bytes()).await;
345    let _ = stream.shutdown().await;
346}
347
348/// Opens `url` in the default browser.
349#[cfg(feature = "open-browser")]
350pub fn open_browser(url: &str) -> Result<()> {
351    webbrowser::open(url).map_err(|e| Error::transport(format!("cannot open the browser: {e}")))
352}
353
354#[cfg(test)]
355mod tests {
356    #[test]
357    fn reads_the_google_desktop_client_file() {
358        let config = GoogleDesktopConfig::from_json(
359            r#"{"installed":{"client_id":"id.apps.googleusercontent.com","project_id":"p",
360            "auth_uri":"https://accounts.google.com/o/oauth2/auth",
361            "token_uri":"https://oauth2.googleapis.com/token","client_secret":"secret",
362            "redirect_uris":["http://localhost"]}}"#,
363        )
364        .unwrap();
365        assert_eq!(config.client_id, "id.apps.googleusercontent.com");
366        assert_eq!(config.client_secret, "secret");
367        assert_eq!(config.auth_url, "https://accounts.google.com/o/oauth2/auth");
368
369        let web =
370            GoogleDesktopConfig::from_json(r#"{"web":{"client_id":"a","client_secret":"b"}}"#);
371        assert!(matches!(web, Err(Error::SignIn { .. })));
372        assert!(GoogleDesktopConfig::from_json("not json").is_err());
373    }
374
375    use super::*;
376    use crate::test_support::serve_http;
377
378    fn query(url: &str) -> std::collections::HashMap<String, String> {
379        url::Url::parse(url)
380            .unwrap()
381            .query_pairs()
382            .map(|(k, v)| (k.into_owned(), v.into_owned()))
383            .collect()
384    }
385
386    /// The browser: sends `GET target` to the loopback and returns the answer.
387    async fn browser(redirect_uri: &str, target: &str) -> String {
388        let address = redirect_uri.trim_start_matches("http://");
389        let mut stream = TcpStream::connect(address).await.unwrap();
390        stream
391            .write_all(format!("GET {target} HTTP/1.1\r\nHost: {address}\r\n\r\n").as_bytes())
392            .await
393            .unwrap();
394        let mut answer = String::new();
395        stream.read_to_string(&mut answer).await.unwrap();
396        answer
397    }
398
399    #[tokio::test]
400    async fn builds_the_authorization_url_with_pkce() {
401        let sign_in = GoogleSignIn::start(GoogleDesktopConfig::new("cid", "secret"))
402            .await
403            .unwrap();
404        let url = sign_in.authorization_url();
405        assert!(url.starts_with("https://accounts.google.com/o/oauth2/v2/auth?"));
406        let params = query(url);
407        assert_eq!(params["client_id"], "cid");
408        assert_eq!(params["redirect_uri"], sign_in.redirect_uri());
409        assert!(sign_in.redirect_uri().starts_with("http://127.0.0.1:"));
410        assert_eq!(params["response_type"], "code");
411        assert_eq!(params["scope"], "openid email profile");
412        assert_eq!(params["code_challenge_method"], "S256");
413        assert_eq!(params["state"], sign_in.state);
414        assert_eq!(params["code_challenge"], pkce_challenge(&sign_in.verifier));
415        assert!(!params.contains_key("client_secret"));
416        assert!(sign_in.verifier.len() >= 43);
417
418        let other = GoogleSignIn::start(GoogleDesktopConfig::new("cid", "secret"))
419            .await
420            .unwrap();
421        assert_ne!(other.state, sign_in.state);
422        assert_ne!(other.verifier, sign_in.verifier);
423    }
424
425    #[test]
426    fn pkce_challenge_matches_rfc_7636() {
427        // RFC 7636, appendix B.
428        assert_eq!(
429            pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
430            "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
431        );
432    }
433
434    #[tokio::test]
435    async fn handles_the_redirect_and_exchanges_the_code() {
436        let (token_server, mut token_requests) = serve_http(
437            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 65\r\nConnection: close\r\n\r\n{\"id_token\":\"gid\",\"access_token\":\"acc\",\"expires_in\":3599,\"x\":\"y\"}",
438        )
439        .await;
440        let mut config = GoogleDesktopConfig::new("cid", "csecret");
441        config.token_url = format!("http://{token_server}/token");
442        let sign_in = GoogleSignIn::start(config).await.unwrap();
443        let (redirect_uri, state, verifier) = (
444            sign_in.redirect_uri().to_owned(),
445            sign_in.state.clone(),
446            sign_in.verifier.clone(),
447        );
448        let finish = tokio::spawn(sign_in.finish());
449
450        let favicon = browser(&redirect_uri, "/favicon.ico").await;
451        assert!(favicon.starts_with("HTTP/1.1 404"));
452        let page = browser(
453            &redirect_uri,
454            &format!("/?state={state}&code=4%2Fabc&scope=email"),
455        )
456        .await;
457        assert!(page.starts_with("HTTP/1.1 200 OK"));
458        assert!(page.contains("You can close this window"));
459
460        let tokens = finish.await.unwrap().unwrap();
461        assert_eq!(tokens.id_token, "gid");
462        assert_eq!(tokens.access_token.as_deref(), Some("acc"));
463        assert_eq!(tokens.expires_in, Some(3599));
464
465        let request = token_requests.recv().await.unwrap();
466        assert!(request.starts_with("POST /token HTTP/1.1"));
467        let body = request.split("\r\n\r\n").nth(1).unwrap();
468        let form: std::collections::HashMap<String, String> =
469            url::form_urlencoded::parse(body.as_bytes())
470                .into_owned()
471                .collect();
472        assert_eq!(form["code"], "4/abc");
473        assert_eq!(form["code_verifier"], verifier);
474        assert_eq!(form["client_secret"], "csecret");
475        assert_eq!(form["redirect_uri"], redirect_uri);
476        assert_eq!(form["grant_type"], "authorization_code");
477    }
478
479    #[tokio::test]
480    async fn refuses_a_redirect_with_another_state() {
481        let sign_in = GoogleSignIn::start(GoogleDesktopConfig::new("cid", "s"))
482            .await
483            .unwrap();
484        let redirect_uri = sign_in.redirect_uri().to_owned();
485        let finish = tokio::spawn(sign_in.finish());
486        let page = browser(&redirect_uri, "/?state=forged&code=abc").await;
487        assert!(page.starts_with("HTTP/1.1 400"));
488        let error = finish.await.unwrap().unwrap_err();
489        assert_eq!(error.kind(), crate::ErrorKind::SignIn);
490    }
491
492    #[tokio::test]
493    async fn reports_a_refused_consent() {
494        let sign_in = GoogleSignIn::start(GoogleDesktopConfig::new("cid", "s"))
495            .await
496            .unwrap();
497        let (redirect_uri, state) = (sign_in.redirect_uri().to_owned(), sign_in.state.clone());
498        let finish = tokio::spawn(sign_in.finish());
499        browser(
500            &redirect_uri,
501            &format!("/?state={state}&error=access_denied"),
502        )
503        .await;
504        let error = finish.await.unwrap().unwrap_err();
505        assert_eq!(
506            error.to_string(),
507            "Google refused the sign-in: access_denied"
508        );
509    }
510
511    #[tokio::test]
512    async fn can_be_cancelled_or_time_out() {
513        let sign_in = GoogleSignIn::start(GoogleDesktopConfig::new("cid", "s"))
514            .await
515            .unwrap();
516        let canceller = sign_in.canceller();
517        canceller.cancel();
518        let error = sign_in.finish().await.unwrap_err();
519        assert_eq!(error.kind(), crate::ErrorKind::Cancelled);
520
521        let mut config = GoogleDesktopConfig::new("cid", "s");
522        config.timeout = Duration::from_millis(20);
523        let error = GoogleSignIn::start(config)
524            .await
525            .unwrap()
526            .finish()
527            .await
528            .unwrap_err();
529        assert_eq!(error.kind(), crate::ErrorKind::Timeout);
530    }
531}