redseat-api 0.2.0

Rust client for Redseat media servers
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! Google sign-in in the browser, for desktop apps: OAuth 2.0 for installed apps with a
//! loopback redirect and PKCE (S256). Not available on wasm.
//!
//! 1. [`GoogleSignIn::start`] listens on `127.0.0.1` at a random port and builds the
//!    authorization URL.
//! 2. The app opens [`GoogleSignIn::authorization_url`] in the browser (or calls
//!    [`open_browser`] with the `open-browser` feature).
//! 3. [`GoogleSignIn::finish`] waits for the redirect, answers the browser with a "you
//!    can close this window" page, and exchanges the code for tokens.
//!
//! The ID token then signs in to the cloud with
//! [`crate::CloudClient::sign_in_with_google_id_token`].

use std::sync::Arc;
use std::time::Duration;

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::Deserialize;
use sha2::{Digest, Sha256};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::watch;

use crate::error::{Error, Result};
use crate::http::HttpTransport;
use crate::transport::{Request, Transport};

pub const GOOGLE_AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
pub const GOOGLE_TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
/// How long [`GoogleSignIn::finish`] waits for the user by default.
pub const DEFAULT_SIGN_IN_TIMEOUT: Duration = Duration::from_secs(5 * 60);
const SCOPES: &str = "openid email profile";

/// A Google OAuth client of type "Desktop app". Its secret is not confidential for
/// installed apps, but it is still the caller's to supply.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GoogleDesktopConfig {
    pub client_id: String,
    pub client_secret: String,
    /// How long to wait for the browser redirect.
    pub timeout: Duration,
    pub auth_url: String,
    pub token_url: String,
}

impl GoogleDesktopConfig {
    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
        GoogleDesktopConfig {
            client_id: client_id.into(),
            client_secret: client_secret.into(),
            timeout: DEFAULT_SIGN_IN_TIMEOUT,
            auth_url: GOOGLE_AUTH_URL.to_owned(),
            token_url: GOOGLE_TOKEN_URL.to_owned(),
        }
    }

    /// Reads the JSON file Google Cloud gives for a "Desktop app" OAuth client
    /// (`{"installed": {"client_id": ..., "client_secret": ..., ...}}`).
    pub fn from_json(json: &str) -> Result<Self> {
        #[derive(Deserialize)]
        struct File {
            installed: Option<Installed>,
        }
        #[derive(Deserialize)]
        struct Installed {
            client_id: String,
            client_secret: String,
            auth_uri: Option<String>,
            token_uri: Option<String>,
        }
        let file: File = serde_json::from_str(json)
            .map_err(|error| Error::sign_in(format!("invalid Google client file: {error}")))?;
        let installed = file.installed.ok_or_else(|| {
            Error::sign_in("the Google client file is not for a \"Desktop app\" client")
        })?;
        let mut config = Self::new(installed.client_id, installed.client_secret);
        if let Some(auth_url) = installed.auth_uri {
            config.auth_url = auth_url;
        }
        if let Some(token_url) = installed.token_uri {
            config.token_url = token_url;
        }
        Ok(config)
    }
}

/// Tokens from Google. `id_token` is what the cloud wants.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GoogleTokens {
    pub id_token: String,
    pub access_token: Option<String>,
    pub refresh_token: Option<String>,
    /// Seconds.
    pub expires_in: Option<u64>,
}

/// Cancels a pending sign-in from anywhere: [`GoogleSignIn::finish`] then fails with
/// [`Error::Cancelled`].
#[derive(Debug, Clone)]
pub struct SignInCanceller(Arc<watch::Sender<bool>>);

impl SignInCanceller {
    pub fn cancel(&self) {
        self.0.send_replace(true);
    }
}

/// A sign-in waiting for the browser.
#[derive(Debug)]
pub struct GoogleSignIn {
    config: GoogleDesktopConfig,
    listener: TcpListener,
    url: String,
    redirect_uri: String,
    state: String,
    verifier: String,
    cancel: Arc<watch::Sender<bool>>,
}

fn random_token(bytes: usize) -> Result<String> {
    let mut buffer = vec![0u8; bytes];
    getrandom::fill(&mut buffer)
        .map_err(|e| Error::transport(format!("random generator failed: {e}")))?;
    Ok(URL_SAFE_NO_PAD.encode(buffer))
}

/// The PKCE S256 challenge of `verifier`.
fn pkce_challenge(verifier: &str) -> String {
    URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
}

impl GoogleSignIn {
    /// Listens on the loopback and builds the authorization URL.
    pub async fn start(config: GoogleDesktopConfig) -> Result<Self> {
        let listener = TcpListener::bind(("127.0.0.1", 0))
            .await
            .map_err(|e| Error::transport(format!("cannot listen on the loopback: {e}")))?;
        let port = listener
            .local_addr()
            .map_err(|e| Error::transport(format!("cannot listen on the loopback: {e}")))?
            .port();
        let redirect_uri = format!("http://127.0.0.1:{port}");
        let state = random_token(16)?;
        // 32 bytes give the 43 characters PKCE asks for at least.
        let verifier = random_token(32)?;

        let mut url = url::Url::parse(&config.auth_url)
            .map_err(|e| Error::transport(format!("invalid authorization URL: {e}")))?;
        url.query_pairs_mut()
            .append_pair("client_id", &config.client_id)
            .append_pair("redirect_uri", &redirect_uri)
            .append_pair("response_type", "code")
            .append_pair("scope", SCOPES)
            .append_pair("code_challenge", &pkce_challenge(&verifier))
            .append_pair("code_challenge_method", "S256")
            .append_pair("state", &state)
            .append_pair("prompt", "select_account");

        Ok(GoogleSignIn {
            config,
            listener,
            url: url.into(),
            redirect_uri,
            state,
            verifier,
            cancel: Arc::new(watch::channel(false).0),
        })
    }

    /// The URL to open in the browser.
    pub fn authorization_url(&self) -> &str {
        &self.url
    }

    /// `http://127.0.0.1:<port>`.
    pub fn redirect_uri(&self) -> &str {
        &self.redirect_uri
    }

    pub fn canceller(&self) -> SignInCanceller {
        SignInCanceller(self.cancel.clone())
    }

    /// Waits for the browser redirect, then exchanges the code for tokens. Fails with
    /// [`Error::Timeout`] after the configured timeout, [`Error::Cancelled`] when
    /// cancelled, and [`Error::SignIn`] when Google or the user refused, or the
    /// redirect does not carry this sign-in's `state`.
    pub async fn finish(self) -> Result<GoogleTokens> {
        let code = self.wait_for_code().await?;
        self.exchange_code(&code).await
    }

    async fn wait_for_code(&self) -> Result<String> {
        let mut cancelled = self.cancel.subscribe();
        let wait = async {
            loop {
                let (stream, _) = self
                    .listener
                    .accept()
                    .await
                    .map_err(|e| Error::transport(format!("loopback listener failed: {e}")))?;
                if let Some(result) = self.handle_redirect(stream).await {
                    return result;
                }
            }
        };
        tokio::select! {
            result = wait => result,
            _ = tokio::time::sleep(self.config.timeout) => Err(Error::Timeout {
                message: "no answer from the browser in time".to_owned(),
                path: None,
            }),
            _ = cancelled.wait_for(|cancelled| *cancelled) => {
                Err(Error::Cancelled { message: "sign-in cancelled".to_owned() })
            }
        }
    }

    /// Answers one browser request. `None` when it is not the redirect (a favicon,
    /// a preconnect): keep waiting.
    async fn handle_redirect(&self, mut stream: TcpStream) -> Option<Result<String>> {
        let head = tokio::time::timeout(Duration::from_secs(5), read_head(&mut stream))
            .await
            .ok()??;
        let target = head.split_whitespace().nth(1)?.to_owned();
        let url = url::Url::parse(&format!("http://127.0.0.1{target}")).ok()?;
        let param = |name: &str| {
            url.query_pairs()
                .find(|(key, _)| key == name)
                .map(|(_, value)| value.into_owned())
        };
        let (code, error, state) = (param("code"), param("error"), param("state"));
        if url.path() != "/" || (code.is_none() && error.is_none()) {
            respond(&mut stream, "404 Not Found", "Not found", "").await;
            return None;
        }

        let result = if state.as_deref() != Some(self.state.as_str()) {
            Err(Error::sign_in(
                "the browser answer does not belong to this sign-in (state mismatch)",
            ))
        } else if let Some(error) = error {
            Err(Error::sign_in(format!(
                "Google refused the sign-in: {error}"
            )))
        } else {
            code.ok_or_else(|| Error::sign_in("no authorization code"))
        };
        match &result {
            Ok(_) => {
                respond(
                    &mut stream,
                    "200 OK",
                    "Signed in",
                    "You are signed in to Redseat. You can close this window.",
                )
                .await
            }
            Err(_) => {
                respond(
                    &mut stream,
                    "400 Bad Request",
                    "Sign-in failed",
                    "The sign-in did not complete. You can close this window and try again.",
                )
                .await
            }
        }
        Some(result)
    }

    async fn exchange_code(&self, code: &str) -> Result<GoogleTokens> {
        let transport = HttpTransport::new(&self.config.token_url)?;
        let form = [
            ("code", code),
            ("client_id", &self.config.client_id),
            ("client_secret", &self.config.client_secret),
            ("redirect_uri", &self.redirect_uri),
            ("grant_type", "authorization_code"),
            ("code_verifier", &self.verifier),
        ]
        .iter()
        .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
        .collect();
        let response = transport
            .request(Request::post(self.config.token_url.clone()).form(form))
            .await
            .map_err(|error| match error {
                Error::Unauthorized { message, .. } | Error::Transport { message, .. } => {
                    Error::sign_in(format!("Google token exchange failed: {message}"))
                }
                other => other,
            })?;

        #[derive(Deserialize)]
        struct TokenAnswer {
            id_token: Option<String>,
            access_token: Option<String>,
            refresh_token: Option<String>,
            expires_in: Option<u64>,
        }
        let answer: TokenAnswer = response.json()?;
        Ok(GoogleTokens {
            id_token: answer
                .id_token
                .ok_or_else(|| Error::sign_in("Google answered without an ID token"))?,
            access_token: answer.access_token,
            refresh_token: answer.refresh_token,
            expires_in: answer.expires_in,
        })
    }
}

/// Reads a request head (up to 16 KiB).
async fn read_head(stream: &mut TcpStream) -> Option<String> {
    let mut head = Vec::new();
    let mut buffer = [0u8; 2048];
    while !head.windows(4).any(|w| w == b"\r\n\r\n") {
        if head.len() > 16 * 1024 {
            return None;
        }
        let n = stream.read(&mut buffer).await.ok()?;
        if n == 0 {
            break;
        }
        head.extend_from_slice(&buffer[..n]);
    }
    Some(String::from_utf8_lossy(&head).into_owned())
}

async fn respond(stream: &mut TcpStream, status: &str, title: &str, message: &str) {
    let body = format!(
        "<!doctype html><html><head><meta charset=\"utf-8\"><title>{title}</title></head>\
         <body style=\"font-family:system-ui,sans-serif;text-align:center;margin-top:20vh\">\
         <h1>{title}</h1><p>{message}</p></body></html>"
    );
    let response = format!(
        "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\n\
         Cache-Control: no-store\r\nConnection: close\r\n\r\n{body}",
        body.len()
    );
    // The browser may already be gone: nothing to do then.
    let _ = stream.write_all(response.as_bytes()).await;
    let _ = stream.shutdown().await;
}

/// Opens `url` in the default browser.
#[cfg(feature = "open-browser")]
pub fn open_browser(url: &str) -> Result<()> {
    webbrowser::open(url).map_err(|e| Error::transport(format!("cannot open the browser: {e}")))
}

#[cfg(test)]
mod tests {
    #[test]
    fn reads_the_google_desktop_client_file() {
        let config = GoogleDesktopConfig::from_json(
            r#"{"installed":{"client_id":"id.apps.googleusercontent.com","project_id":"p",
            "auth_uri":"https://accounts.google.com/o/oauth2/auth",
            "token_uri":"https://oauth2.googleapis.com/token","client_secret":"secret",
            "redirect_uris":["http://localhost"]}}"#,
        )
        .unwrap();
        assert_eq!(config.client_id, "id.apps.googleusercontent.com");
        assert_eq!(config.client_secret, "secret");
        assert_eq!(config.auth_url, "https://accounts.google.com/o/oauth2/auth");

        let web =
            GoogleDesktopConfig::from_json(r#"{"web":{"client_id":"a","client_secret":"b"}}"#);
        assert!(matches!(web, Err(Error::SignIn { .. })));
        assert!(GoogleDesktopConfig::from_json("not json").is_err());
    }

    use super::*;
    use crate::test_support::serve_http;

    fn query(url: &str) -> std::collections::HashMap<String, String> {
        url::Url::parse(url)
            .unwrap()
            .query_pairs()
            .map(|(k, v)| (k.into_owned(), v.into_owned()))
            .collect()
    }

    /// The browser: sends `GET target` to the loopback and returns the answer.
    async fn browser(redirect_uri: &str, target: &str) -> String {
        let address = redirect_uri.trim_start_matches("http://");
        let mut stream = TcpStream::connect(address).await.unwrap();
        stream
            .write_all(format!("GET {target} HTTP/1.1\r\nHost: {address}\r\n\r\n").as_bytes())
            .await
            .unwrap();
        let mut answer = String::new();
        stream.read_to_string(&mut answer).await.unwrap();
        answer
    }

    #[tokio::test]
    async fn builds_the_authorization_url_with_pkce() {
        let sign_in = GoogleSignIn::start(GoogleDesktopConfig::new("cid", "secret"))
            .await
            .unwrap();
        let url = sign_in.authorization_url();
        assert!(url.starts_with("https://accounts.google.com/o/oauth2/v2/auth?"));
        let params = query(url);
        assert_eq!(params["client_id"], "cid");
        assert_eq!(params["redirect_uri"], sign_in.redirect_uri());
        assert!(sign_in.redirect_uri().starts_with("http://127.0.0.1:"));
        assert_eq!(params["response_type"], "code");
        assert_eq!(params["scope"], "openid email profile");
        assert_eq!(params["code_challenge_method"], "S256");
        assert_eq!(params["state"], sign_in.state);
        assert_eq!(params["code_challenge"], pkce_challenge(&sign_in.verifier));
        assert!(!params.contains_key("client_secret"));
        assert!(sign_in.verifier.len() >= 43);

        let other = GoogleSignIn::start(GoogleDesktopConfig::new("cid", "secret"))
            .await
            .unwrap();
        assert_ne!(other.state, sign_in.state);
        assert_ne!(other.verifier, sign_in.verifier);
    }

    #[test]
    fn pkce_challenge_matches_rfc_7636() {
        // RFC 7636, appendix B.
        assert_eq!(
            pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
            "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
        );
    }

    #[tokio::test]
    async fn handles_the_redirect_and_exchanges_the_code() {
        let (token_server, mut token_requests) = serve_http(
            "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\"}",
        )
        .await;
        let mut config = GoogleDesktopConfig::new("cid", "csecret");
        config.token_url = format!("http://{token_server}/token");
        let sign_in = GoogleSignIn::start(config).await.unwrap();
        let (redirect_uri, state, verifier) = (
            sign_in.redirect_uri().to_owned(),
            sign_in.state.clone(),
            sign_in.verifier.clone(),
        );
        let finish = tokio::spawn(sign_in.finish());

        let favicon = browser(&redirect_uri, "/favicon.ico").await;
        assert!(favicon.starts_with("HTTP/1.1 404"));
        let page = browser(
            &redirect_uri,
            &format!("/?state={state}&code=4%2Fabc&scope=email"),
        )
        .await;
        assert!(page.starts_with("HTTP/1.1 200 OK"));
        assert!(page.contains("You can close this window"));

        let tokens = finish.await.unwrap().unwrap();
        assert_eq!(tokens.id_token, "gid");
        assert_eq!(tokens.access_token.as_deref(), Some("acc"));
        assert_eq!(tokens.expires_in, Some(3599));

        let request = token_requests.recv().await.unwrap();
        assert!(request.starts_with("POST /token HTTP/1.1"));
        let body = request.split("\r\n\r\n").nth(1).unwrap();
        let form: std::collections::HashMap<String, String> =
            url::form_urlencoded::parse(body.as_bytes())
                .into_owned()
                .collect();
        assert_eq!(form["code"], "4/abc");
        assert_eq!(form["code_verifier"], verifier);
        assert_eq!(form["client_secret"], "csecret");
        assert_eq!(form["redirect_uri"], redirect_uri);
        assert_eq!(form["grant_type"], "authorization_code");
    }

    #[tokio::test]
    async fn refuses_a_redirect_with_another_state() {
        let sign_in = GoogleSignIn::start(GoogleDesktopConfig::new("cid", "s"))
            .await
            .unwrap();
        let redirect_uri = sign_in.redirect_uri().to_owned();
        let finish = tokio::spawn(sign_in.finish());
        let page = browser(&redirect_uri, "/?state=forged&code=abc").await;
        assert!(page.starts_with("HTTP/1.1 400"));
        let error = finish.await.unwrap().unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::SignIn);
    }

    #[tokio::test]
    async fn reports_a_refused_consent() {
        let sign_in = GoogleSignIn::start(GoogleDesktopConfig::new("cid", "s"))
            .await
            .unwrap();
        let (redirect_uri, state) = (sign_in.redirect_uri().to_owned(), sign_in.state.clone());
        let finish = tokio::spawn(sign_in.finish());
        browser(
            &redirect_uri,
            &format!("/?state={state}&error=access_denied"),
        )
        .await;
        let error = finish.await.unwrap().unwrap_err();
        assert_eq!(
            error.to_string(),
            "Google refused the sign-in: access_denied"
        );
    }

    #[tokio::test]
    async fn can_be_cancelled_or_time_out() {
        let sign_in = GoogleSignIn::start(GoogleDesktopConfig::new("cid", "s"))
            .await
            .unwrap();
        let canceller = sign_in.canceller();
        canceller.cancel();
        let error = sign_in.finish().await.unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::Cancelled);

        let mut config = GoogleDesktopConfig::new("cid", "s");
        config.timeout = Duration::from_millis(20);
        let error = GoogleSignIn::start(config)
            .await
            .unwrap()
            .finish()
            .await
            .unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::Timeout);
    }
}