Skip to main content
← rust.krizaka.comkrizaka.com

krizaka_rust/
device_flow.rs

1//! OAuth device flow (RFC 8628) for a Mac app that signs in to a provider (GitHub first: a GitHub App's user-to-server
2//! token), with no client secret on the Mac. The rules live here, with no network: the app gives a [`Transport`] (one
3//! form POST that answers JSON), and the tokens are kept through [`crate::secrets::SecretStore`] (the Keychain), on the
4//! Rust side only — the page sees [`Session`] (connected as whom), never a token.
5//!
6//! Steps: [`start`] asks a code; the app shows [`DeviceCode::user_code`] and [`DeviceCode::verification_uri`];
7//! [`wait`] polls (honouring `slow_down`, stopping on `expired_token` / `access_denied`); [`TokenVault::save`] keeps the
8//! tokens; [`TokenVault::access_token`] returns a valid one, refreshing it when it is about to expire;
9//! [`TokenVault::sign_out`] removes both secrets (revoking at the provider is the person's, in its settings).
10
11use crate::secrets::{SecretError, SecretStore};
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use std::time::Duration;
15
16/// The app's HTTP client could not do the request (offline, refused, not JSON…). The text is the client's own.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct TransportError(pub String);
19
20impl std::fmt::Display for TransportError {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        write!(f, "the request failed: {}", self.0)
23    }
24}
25
26impl std::error::Error for TransportError {}
27
28/// One form POST that answers JSON (`Accept: application/json`). The app supplies it (ureq, reqwest…); tests mock it.
29pub trait Transport {
30    fn post_form(&self, url: &str, fields: &[(&str, &str)]) -> Result<Value, TransportError>;
31}
32
33/// A provider's two endpoints and the app's public client id (no secret: the device flow has none).
34#[derive(Debug, Clone)]
35pub struct Provider {
36    pub device_code_url: String,
37    pub token_url: String,
38    pub client_id: String,
39}
40
41impl Provider {
42    /// GitHub (github.com); a firm on GitHub Enterprise builds its own `Provider` with its host.
43    pub fn github(client_id: &str) -> Self {
44        Provider {
45            device_code_url: "https://github.com/login/device/code".into(),
46            token_url: "https://github.com/login/oauth/access_token".into(),
47            client_id: client_id.into(),
48        }
49    }
50}
51
52/// What the person sees: the code to type and where.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct DeviceCode {
55    #[serde(skip_serializing)]
56    pub device_code: String,
57    pub user_code: String,
58    pub verification_uri: String,
59    pub expires_in: u64,
60    pub interval: u64,
61}
62
63/// The tokens, with the instant (unix seconds) the access token stops being valid; the refresh token is optional (a
64/// provider without expiring tokens gives none).
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66pub struct Tokens {
67    pub access_token: String,
68    pub refresh_token: Option<String>,
69    pub expires_at: Option<u64>,
70}
71
72/// How the flow ends when it is not a token.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum Failure {
75    Expired,
76    Denied,
77    /// The request could not be made.
78    Transport(TransportError),
79    /// The provider refused for another reason: its `error` code.
80    Provider(String),
81    /// The provider's answer lacks what the flow needs (the name of what is missing).
82    Malformed(&'static str),
83}
84
85impl Failure {
86    /// The stable code the page reads.
87    pub fn code(&self) -> &'static str {
88        match self {
89            Failure::Expired => "device_expired",
90            Failure::Denied => "device_denied",
91            Failure::Transport(_) => "device_transport",
92            Failure::Provider(_) => "device_provider",
93            Failure::Malformed(_) => "device_malformed",
94        }
95    }
96}
97
98impl std::fmt::Display for Failure {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        match self {
101            Failure::Expired => write!(f, "the code expired, start again"),
102            Failure::Denied => write!(f, "the request was denied"),
103            Failure::Transport(e) => write!(f, "{e}"),
104            Failure::Provider(code) => write!(f, "the provider refused: {code}"),
105            Failure::Malformed(what) => write!(f, "the provider's answer lacks {what}"),
106        }
107    }
108}
109
110impl std::error::Error for Failure {
111    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
112        match self {
113            Failure::Transport(e) => Some(e),
114            _ => None,
115        }
116    }
117}
118
119impl From<TransportError> for Failure {
120    fn from(error: TransportError) -> Self {
121        Failure::Transport(error)
122    }
123}
124
125/// Why the token vault failed: the secret store, or the refresh the vault tried.
126#[derive(Debug)]
127pub enum VaultError {
128    Secrets(SecretError),
129    Refresh(Failure),
130}
131
132impl VaultError {
133    /// The stable code the page reads: the one of the failure underneath.
134    pub fn code(&self) -> &'static str {
135        match self {
136            VaultError::Secrets(e) => e.code(),
137            VaultError::Refresh(f) => f.code(),
138        }
139    }
140}
141
142impl std::fmt::Display for VaultError {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        match self {
145            VaultError::Secrets(e) => write!(f, "{e}"),
146            VaultError::Refresh(e) => write!(f, "the refresh failed: {e}"),
147        }
148    }
149}
150
151impl std::error::Error for VaultError {
152    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
153        match self {
154            VaultError::Secrets(e) => Some(e),
155            VaultError::Refresh(e) => Some(e),
156        }
157    }
158}
159
160impl From<SecretError> for VaultError {
161    fn from(error: SecretError) -> Self {
162        VaultError::Secrets(error)
163    }
164}
165
166/// The smallest wait between two polls, whatever the provider says (it asks 5 s).
167// @fixed: RFC 8628 §3.5 default interval
168pub const DEFAULT_INTERVAL: u64 = 5;
169/// Added to the interval on `slow_down`.
170// @fixed: RFC 8628 §3.5
171pub const SLOW_DOWN_STEP: u64 = 5;
172/// How long a device code lives when the provider does not say.
173// @fixed: RFC 8628 §3.2 lets the provider choose; fifteen minutes is the usual window to type a code
174pub const DEFAULT_EXPIRES_IN: u64 = 900;
175/// A token is refreshed this many seconds before it expires.
176// @fixed: a margin for the clock and the round trip, not a business setting
177pub const REFRESH_MARGIN: u64 = 60;
178
179fn text(v: &Value, key: &str) -> Option<String> {
180    v.get(key).and_then(Value::as_str).map(str::to_owned)
181}
182
183/// Step 1: ask the provider for a device and user code.
184pub fn start(t: &dyn Transport, p: &Provider, scope: &str) -> Result<DeviceCode, Failure> {
185    let mut fields = vec![("client_id", p.client_id.as_str())];
186    if !scope.is_empty() {
187        fields.push(("scope", scope));
188    }
189    let v = t.post_form(&p.device_code_url, &fields)?;
190    if let Some(e) = text(&v, "error") {
191        return Err(Failure::Provider(e));
192    }
193    let missing = Failure::Malformed;
194    Ok(DeviceCode {
195        device_code: text(&v, "device_code").ok_or_else(|| missing("device_code"))?,
196        user_code: text(&v, "user_code").ok_or_else(|| missing("user_code"))?,
197        verification_uri: text(&v, "verification_uri")
198            .ok_or_else(|| missing("verification_uri"))?,
199        expires_in: v
200            .get("expires_in")
201            .and_then(Value::as_u64)
202            .unwrap_or(DEFAULT_EXPIRES_IN),
203        interval: v
204            .get("interval")
205            .and_then(Value::as_u64)
206            .unwrap_or(DEFAULT_INTERVAL)
207            .max(1),
208    })
209}
210
211fn tokens_from(v: &Value, now: u64) -> Option<Tokens> {
212    Some(Tokens {
213        access_token: text(v, "access_token")?,
214        refresh_token: text(v, "refresh_token"),
215        expires_at: v.get("expires_in").and_then(Value::as_u64).map(|s| now + s),
216    })
217}
218
219/// One poll of the token endpoint: `Ok(None)` = keep waiting (the second value is the new interval).
220fn poll_once(
221    t: &dyn Transport,
222    p: &Provider,
223    code: &DeviceCode,
224    interval: u64,
225    now: u64,
226) -> Result<Result<Tokens, u64>, Failure> {
227    let v = t.post_form(
228        &p.token_url,
229        &[
230            ("client_id", p.client_id.as_str()),
231            ("device_code", code.device_code.as_str()),
232            ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
233        ],
234    )?;
235    if let Some(tokens) = tokens_from(&v, now) {
236        return Ok(Ok(tokens));
237    }
238    match text(&v, "error").as_deref() {
239        Some("authorization_pending") => Ok(Err(interval)),
240        Some("slow_down") => Ok(Err(interval + SLOW_DOWN_STEP)),
241        Some("expired_token") => Err(Failure::Expired),
242        Some("access_denied") => Err(Failure::Denied),
243        Some(other) => Err(Failure::Provider(other.into())),
244        None => Err(Failure::Malformed("a token or an error")),
245    }
246}
247
248/// Step 2: poll until the person approves, the code expires or the request is denied. `sleep` and `now` are the app's
249/// (tests pass a recorder and a counter), `cancelled` lets the window close the wait.
250pub fn wait(
251    t: &dyn Transport,
252    p: &Provider,
253    code: &DeviceCode,
254    sleep: &mut dyn FnMut(Duration),
255    now: &dyn Fn() -> u64,
256    cancelled: &dyn Fn() -> bool,
257) -> Result<Tokens, Failure> {
258    let deadline = now() + code.expires_in;
259    let mut interval = code.interval;
260    loop {
261        sleep(Duration::from_secs(interval));
262        if cancelled() {
263            return Err(Failure::Denied);
264        }
265        if now() >= deadline {
266            return Err(Failure::Expired);
267        }
268        match poll_once(t, p, code, interval, now())? {
269            Ok(tokens) => return Ok(tokens),
270            Err(next) => interval = next,
271        }
272    }
273}
274
275/// Exchange a refresh token for a new pair (the provider rotates the refresh token: the old one is spent).
276pub fn refresh(
277    t: &dyn Transport,
278    p: &Provider,
279    refresh_token: &str,
280    now: u64,
281) -> Result<Tokens, Failure> {
282    let v = t.post_form(
283        &p.token_url,
284        &[
285            ("client_id", p.client_id.as_str()),
286            ("grant_type", "refresh_token"),
287            ("refresh_token", refresh_token),
288        ],
289    )?;
290    tokens_from(&v, now).ok_or_else(|| match text(&v, "error") {
291        Some(code) => Failure::Provider(code),
292        None => Failure::Malformed("a token or an error"),
293    })
294}
295
296/// What the page may know: whether the person is connected, never a token.
297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298pub struct Session {
299    pub connected: bool,
300}
301
302/// The tokens in a [`SecretStore`] (the Keychain), under `<prefix>.access` / `.refresh` / `.expires`.
303pub struct TokenVault<'a> {
304    store: &'a dyn SecretStore,
305    prefix: String,
306}
307
308impl<'a> TokenVault<'a> {
309    pub fn new(store: &'a dyn SecretStore, prefix: &str) -> Self {
310        TokenVault {
311            store,
312            prefix: prefix.into(),
313        }
314    }
315
316    fn key(&self, part: &str) -> String {
317        format!("{}.{part}", self.prefix)
318    }
319
320    pub fn save(&self, tokens: &Tokens) -> Result<(), SecretError> {
321        self.store.set(&self.key("access"), &tokens.access_token)?;
322        match &tokens.refresh_token {
323            Some(r) => self.store.set(&self.key("refresh"), r)?,
324            None => self.store.remove(&self.key("refresh"))?,
325        }
326        match tokens.expires_at {
327            Some(e) => self.store.set(&self.key("expires"), &e.to_string())?,
328            None => self.store.remove(&self.key("expires"))?,
329        }
330        Ok(())
331    }
332
333    pub fn load(&self) -> Result<Option<Tokens>, SecretError> {
334        let Some(access_token) = self.store.get(&self.key("access"))? else {
335            return Ok(None);
336        };
337        Ok(Some(Tokens {
338            access_token,
339            refresh_token: self.store.get(&self.key("refresh"))?,
340            expires_at: self
341                .store
342                .get(&self.key("expires"))?
343                .and_then(|s| s.parse().ok()),
344        }))
345    }
346
347    pub fn session(&self) -> Result<Session, SecretError> {
348        Ok(Session {
349            connected: self.load()?.is_some(),
350        })
351    }
352
353    /// Removes both secrets at once; signing out twice is signing out.
354    pub fn sign_out(&self) -> Result<(), SecretError> {
355        for part in ["access", "refresh", "expires"] {
356            self.store.remove(&self.key(part))?;
357        }
358        Ok(())
359    }
360
361    /// A valid access token: the stored one, or a refreshed one when it expires within [`REFRESH_MARGIN`]. `Ok(None)`
362    /// = not connected, or the refresh was refused (the person signs in again; the dead tokens are removed).
363    pub fn access_token(
364        &self,
365        t: &dyn Transport,
366        p: &Provider,
367        now: u64,
368    ) -> Result<Option<String>, VaultError> {
369        let Some(tokens) = self.load()? else {
370            return Ok(None);
371        };
372        let fresh = tokens.expires_at.map_or(true, |e| e > now + REFRESH_MARGIN);
373        if fresh {
374            return Ok(Some(tokens.access_token));
375        }
376        let Some(refresh_token) = tokens.refresh_token else {
377            self.sign_out()?;
378            return Ok(None);
379        };
380        match refresh(t, p, &refresh_token, now) {
381            Ok(new) => {
382                self.save(&new)?;
383                Ok(Some(new.access_token))
384            }
385            Err(Failure::Provider(m))
386                if m.starts_with("bad_refresh_token") || m == "incorrect_client_credentials" =>
387            {
388                self.sign_out()?;
389                Ok(None)
390            }
391            Err(f) => Err(VaultError::Refresh(f)),
392        }
393    }
394}
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399    use crate::secrets::{Checked, MemorySecrets};
400    use serde_json::json;
401    use std::cell::{Cell, RefCell};
402
403    type Call = (String, Vec<(String, String)>);
404
405    /// A mocked provider: answers are queued, requests are recorded.
406    struct Mock {
407        answers: RefCell<Vec<Result<Value, TransportError>>>,
408        calls: RefCell<Vec<Call>>,
409    }
410
411    impl Mock {
412        fn new(answers: Vec<Result<Value, TransportError>>) -> Self {
413            Mock {
414                answers: RefCell::new(answers.into_iter().rev().collect()),
415                calls: RefCell::new(vec![]),
416            }
417        }
418    }
419
420    impl Transport for Mock {
421        fn post_form(&self, url: &str, fields: &[(&str, &str)]) -> Result<Value, TransportError> {
422            self.calls.borrow_mut().push((
423                url.into(),
424                fields
425                    .iter()
426                    .map(|(k, v)| (k.to_string(), v.to_string()))
427                    .collect(),
428            ));
429            self.answers.borrow_mut().pop().expect("no more answers")
430        }
431    }
432
433    fn provider() -> Provider {
434        Provider::github("Iv-test-client")
435    }
436
437    fn code_answer() -> Value {
438        json!({"device_code": "dc-1", "user_code": "WDJB-MJHT", "verification_uri": "https://github.com/login/device", "expires_in": 900, "interval": 5})
439    }
440
441    fn token_answer() -> Value {
442        json!({"access_token": "ghu_fake", "refresh_token": "ghr_fake", "expires_in": 28800})
443    }
444
445    fn pending() -> Result<Value, TransportError> {
446        Ok(json!({"error": "authorization_pending"}))
447    }
448
449    #[test]
450    fn a_failure_is_a_std_error_with_a_stable_code_and_its_cause() {
451        fn is_error<E: std::error::Error + Send + Sync + 'static>() {}
452        is_error::<Failure>();
453        is_error::<VaultError>();
454        let transport = Failure::Transport(TransportError("offline".into()));
455        assert!(std::error::Error::source(&transport).is_some());
456        assert!(std::error::Error::source(&Failure::Expired).is_none());
457        let codes: Vec<_> = [
458            Failure::Expired,
459            Failure::Denied,
460            transport,
461            Failure::Provider("x".into()),
462            Failure::Malformed("x"),
463        ]
464        .iter()
465        .map(Failure::code)
466        .collect();
467        assert_eq!(
468            codes,
469            [
470                "device_expired",
471                "device_denied",
472                "device_transport",
473                "device_provider",
474                "device_malformed"
475            ]
476        );
477    }
478
479    #[test]
480    fn start_reads_the_code_to_show_and_sends_only_the_public_client_id() {
481        let t = Mock::new(vec![Ok(code_answer())]);
482        let c = start(&t, &provider(), "").unwrap();
483        assert_eq!(c.user_code, "WDJB-MJHT");
484        assert_eq!(c.verification_uri, "https://github.com/login/device");
485        let calls = t.calls.borrow();
486        assert_eq!(calls[0].0, "https://github.com/login/device/code");
487        assert_eq!(
488            calls[0].1,
489            vec![("client_id".to_string(), "Iv-test-client".to_string())]
490        );
491        // the device code never reaches the page
492        assert!(!serde_json::to_string(&c).unwrap().contains("dc-1"));
493    }
494
495    #[test]
496    fn start_refuses_an_incomplete_or_errored_answer() {
497        let t = Mock::new(vec![
498            Ok(json!({"user_code": "X"})),
499            Ok(json!({"error": "device_flow_disabled"})),
500        ]);
501        assert!(start(&t, &provider(), "").is_err());
502        assert_eq!(
503            start(&t, &provider(), "").unwrap_err(),
504            Failure::Provider("device_flow_disabled".into())
505        );
506    }
507
508    #[test]
509    fn wait_polls_at_the_interval_slows_down_and_returns_the_tokens() {
510        let t = Mock::new(vec![
511            Ok(code_answer()),
512            pending(),
513            Ok(json!({"error": "slow_down"})),
514            Ok(token_answer()),
515        ]);
516        let c = start(&t, &provider(), "").unwrap();
517        let slept = RefCell::new(vec![]);
518        let clock = Cell::new(1000);
519        let tokens = wait(
520            &t,
521            &provider(),
522            &c,
523            &mut |d| {
524                slept.borrow_mut().push(d.as_secs());
525                clock.set(clock.get() + d.as_secs());
526            },
527            &|| clock.get(),
528            &|| false,
529        )
530        .unwrap();
531        assert_eq!(*slept.borrow(), vec![5, 5, 10]);
532        assert_eq!(tokens.access_token, "ghu_fake");
533        assert_eq!(tokens.refresh_token.as_deref(), Some("ghr_fake"));
534        assert_eq!(tokens.expires_at, Some(1020 + 28800));
535        let calls = t.calls.borrow();
536        assert!(calls[1].1.contains(&(
537            "grant_type".into(),
538            "urn:ietf:params:oauth:grant-type:device_code".into()
539        )));
540    }
541
542    #[test]
543    fn wait_ends_on_expiry_denial_cancel_and_unknown_errors() {
544        for (answer, want) in [
545            (Ok(json!({"error": "expired_token"})), Failure::Expired),
546            (Ok(json!({"error": "access_denied"})), Failure::Denied),
547            (
548                Ok(json!({"error": "unsupported_grant_type"})),
549                Failure::Provider("unsupported_grant_type".into()),
550            ),
551            (
552                Err(TransportError("offline".into())),
553                Failure::Transport(TransportError("offline".into())),
554            ),
555        ] {
556            let t = Mock::new(vec![Ok(code_answer()), answer]);
557            let c = start(&t, &provider(), "").unwrap();
558            let r = wait(&t, &provider(), &c, &mut |_| {}, &|| 0, &|| false);
559            assert_eq!(r.unwrap_err(), want);
560        }
561        // closed window: no poll at all
562        let t = Mock::new(vec![Ok(code_answer())]);
563        let c = start(&t, &provider(), "").unwrap();
564        assert_eq!(
565            wait(&t, &provider(), &c, &mut |_| {}, &|| 0, &|| true).unwrap_err(),
566            Failure::Denied
567        );
568        assert_eq!(t.calls.borrow().len(), 1);
569        // local deadline passed
570        let t = Mock::new(vec![Ok(code_answer())]);
571        let c = start(&t, &provider(), "").unwrap();
572        let clock = Cell::new(0);
573        let r = wait(
574            &t,
575            &provider(),
576            &c,
577            &mut |_| clock.set(clock.get() + 1000),
578            &|| clock.get(),
579            &|| false,
580        );
581        assert_eq!(r.unwrap_err(), Failure::Expired);
582    }
583
584    fn vault_with(store: &Checked<MemorySecrets>, expires_at: Option<u64>, refresh: Option<&str>) {
585        TokenVault::new(store, "gh")
586            .save(&Tokens {
587                access_token: "ghu_old".into(),
588                refresh_token: refresh.map(str::to_owned),
589                expires_at,
590            })
591            .unwrap();
592    }
593
594    #[test]
595    fn a_valid_token_is_returned_and_an_expiring_one_is_refreshed_and_rotated() {
596        let store = Checked(MemorySecrets::default());
597        let vault = TokenVault::new(&store, "gh");
598        assert_eq!(
599            vault
600                .access_token(&Mock::new(vec![]), &provider(), 0)
601                .unwrap(),
602            None
603        );
604        vault_with(&store, Some(10_000), Some("ghr_old"));
605        // fresh: no network
606        assert_eq!(
607            vault
608                .access_token(&Mock::new(vec![]), &provider(), 1000)
609                .unwrap()
610                .as_deref(),
611            Some("ghu_old")
612        );
613        // within the margin: refreshed, both stored again
614        let t = Mock::new(vec![Ok(
615            json!({"access_token": "ghu_new", "refresh_token": "ghr_new", "expires_in": 28800}),
616        )]);
617        assert_eq!(
618            vault
619                .access_token(&t, &provider(), 9_990)
620                .unwrap()
621                .as_deref(),
622            Some("ghu_new")
623        );
624        let sent = &t.calls.borrow()[0].1;
625        assert!(sent.contains(&("refresh_token".into(), "ghr_old".into())));
626        assert!(sent.contains(&("grant_type".into(), "refresh_token".into())));
627        let saved = vault.load().unwrap().unwrap();
628        assert_eq!(saved.refresh_token.as_deref(), Some("ghr_new"));
629        assert_eq!(saved.expires_at, Some(9_990 + 28800));
630    }
631
632    #[test]
633    fn a_refused_refresh_or_a_missing_refresh_token_signs_out_locally() {
634        let store = Checked(MemorySecrets::default());
635        let vault = TokenVault::new(&store, "gh");
636        vault_with(&store, Some(10), Some("ghr_dead"));
637        let t = Mock::new(vec![Ok(json!({"error": "bad_refresh_token"}))]);
638        assert_eq!(vault.access_token(&t, &provider(), 100).unwrap(), None);
639        assert!(!vault.session().unwrap().connected);
640        vault_with(&store, Some(10), None);
641        assert_eq!(
642            vault
643                .access_token(&Mock::new(vec![]), &provider(), 100)
644                .unwrap(),
645            None
646        );
647        assert_eq!(store.get("gh.access").unwrap(), None);
648    }
649
650    #[test]
651    fn a_network_error_while_refreshing_keeps_the_tokens() {
652        let store = Checked(MemorySecrets::default());
653        let vault = TokenVault::new(&store, "gh");
654        vault_with(&store, Some(10), Some("ghr"));
655        let t = Mock::new(vec![Err(TransportError("offline".into()))]);
656        assert!(vault.access_token(&t, &provider(), 100).is_err());
657        assert!(vault.session().unwrap().connected);
658    }
659
660    #[test]
661    fn sign_out_removes_every_secret_and_twice_is_fine() {
662        let store = Checked(MemorySecrets::default());
663        vault_with(&store, Some(10), Some("r"));
664        let vault = TokenVault::new(&store, "gh");
665        vault.sign_out().unwrap();
666        vault.sign_out().unwrap();
667        for k in ["gh.access", "gh.refresh", "gh.expires"] {
668            assert_eq!(store.get(k).unwrap(), None, "{k}");
669        }
670    }
671
672    #[test]
673    fn the_session_the_page_sees_holds_no_token() {
674        let store = Checked(MemorySecrets::default());
675        vault_with(&store, None, None);
676        let s = serde_json::to_string(&TokenVault::new(&store, "gh").session().unwrap()).unwrap();
677        assert_eq!(s, r#"{"connected":true}"#);
678    }
679}