| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The waiting half of the device flow (`docs/hub.md`, section 2): polling |
| 5 | //! the hub every `interval` seconds until the person approves, refuses, or |
| 6 | //! lets the code expire. |
| 7 | |
| 8 | use std::time::Duration; |
| 9 | |
| 10 | use anyhow::{Result, anyhow, bail}; |
| 11 | use braid_hubproto::Token; |
| 12 | use braid_hubproto::api::{DevicePoll, DeviceStart}; |
| 13 | |
| 14 | use super::remote::HubError; |
| 15 | |
| 16 | /// What polling needs from the hub. |
| 17 | pub(crate) trait DeviceFlow { |
| 18 | /// `POST /v1/login/device/poll {"poll"}`. |
| 19 | fn poll(&self, poll: &str) -> Result<DevicePoll, HubError>; |
| 20 | } |
| 21 | |
| 22 | /// A sign-in the person approved. Its debug form shows the token's id |
| 23 | /// only. |
| 24 | #[derive(Debug)] |
| 25 | pub(crate) struct SignedIn { |
| 26 | /// The new token. |
| 27 | pub(crate) token: Token, |
| 28 | /// The account's GitHub login. |
| 29 | pub(crate) login: String, |
| 30 | /// When the token expires. |
| 31 | pub(crate) expires: String, |
| 32 | } |
| 33 | |
| 34 | /// Polls `flow` for the flow `start` began, sleeping with `sleep` between |
| 35 | /// polls: `interval` seconds, more after `slow_down` or a rate limit, until |
| 36 | /// `expires_in` seconds have been waited. |
| 37 | pub(crate) fn wait_for_approval( |
| 38 | flow: &impl DeviceFlow, |
| 39 | start: &DeviceStart, |
| 40 | mut sleep: impl FnMut(Duration), |
| 41 | ) -> Result<SignedIn> { |
| 42 | let expired = |
| 43 | || anyhow!("the code expired before the sign-in was approved: run `braid login` again"); |
| 44 | let mut interval = start.interval.max(1); |
| 45 | let mut waited = 0u64; |
| 46 | loop { |
| 47 | if waited >= start.expires_in { |
| 48 | return Err(expired()); |
| 49 | } |
| 50 | sleep(Duration::from_secs(interval)); |
| 51 | waited = waited.saturating_add(interval); |
| 52 | match flow.poll(&start.poll) { |
| 53 | Ok(DevicePoll::Pending) => {} |
| 54 | Ok(DevicePoll::SlowDown { interval: asked }) => interval = asked.max(interval), |
| 55 | Ok(DevicePoll::Denied) => { |
| 56 | bail!("the sign-in was denied: run `braid login` again to start over") |
| 57 | } |
| 58 | Ok(DevicePoll::Expired) => return Err(expired()), |
| 59 | Ok(DevicePoll::Ok { |
| 60 | token, |
| 61 | login, |
| 62 | expires, |
| 63 | }) => { |
| 64 | let token = Token::parse(&token) |
| 65 | .map_err(|_| anyhow!("the hub sent something that is not a braid hub token"))?; |
| 66 | return Ok(SignedIn { |
| 67 | token, |
| 68 | login, |
| 69 | expires, |
| 70 | }); |
| 71 | } |
| 72 | // Asked to wait: wait as long as the hub says, then poll again. |
| 73 | Err(HubError::Api { status: 429, body }) => { |
| 74 | interval = body.retry_after.unwrap_or(interval).max(interval); |
| 75 | } |
| 76 | Err(err) => return Err(err.into()), |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | #[cfg(test)] |
| 82 | mod tests { |
| 83 | use super::*; |
| 84 | use std::cell::RefCell; |
| 85 | |
| 86 | /// A hub that answers from a script. |
| 87 | struct Script(RefCell<Vec<Result<DevicePoll, HubError>>>); |
| 88 | |
| 89 | impl DeviceFlow for Script { |
| 90 | fn poll(&self, poll: &str) -> Result<DevicePoll, HubError> { |
| 91 | assert_eq!(poll, "flow-1"); |
| 92 | self.0.borrow_mut().remove(0) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | fn start(interval: u64, expires_in: u64) -> DeviceStart { |
| 97 | DeviceStart { |
| 98 | poll: "flow-1".to_owned(), |
| 99 | user_code: "ABCD-1234".to_owned(), |
| 100 | verification_uri: "https://github.com/login/device".to_owned(), |
| 101 | expires_in, |
| 102 | interval, |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | fn run( |
| 107 | answers: Vec<Result<DevicePoll, HubError>>, |
| 108 | start: &DeviceStart, |
| 109 | ) -> (Result<SignedIn>, Vec<u64>) { |
| 110 | let script = Script(RefCell::new(answers)); |
| 111 | let mut slept = Vec::new(); |
| 112 | let result = wait_for_approval(&script, start, |d| slept.push(d.as_secs())); |
| 113 | (result, slept) |
| 114 | } |
| 115 | |
| 116 | #[test] |
| 117 | fn polls_at_the_interval_and_slows_down_when_told() { |
| 118 | let token = Token::from_random([1; 5], [2; 32]); |
| 119 | let mut limited = HubError::api(429, "rate_limited", "wait"); |
| 120 | if let HubError::Api { body, .. } = &mut limited { |
| 121 | body.retry_after = Some(20); |
| 122 | } |
| 123 | let (result, slept) = run( |
| 124 | vec![ |
| 125 | Ok(DevicePoll::Pending), |
| 126 | Ok(DevicePoll::SlowDown { interval: 10 }), |
| 127 | Ok(DevicePoll::Pending), |
| 128 | Err(limited), |
| 129 | Ok(DevicePoll::Ok { |
| 130 | token: token.expose(), |
| 131 | login: "ada".to_owned(), |
| 132 | expires: "2027-01-01T00:00:00Z".to_owned(), |
| 133 | }), |
| 134 | ], |
| 135 | &start(5, 900), |
| 136 | ); |
| 137 | let signed = result.unwrap(); |
| 138 | assert_eq!(signed.token, token); |
| 139 | assert_eq!(signed.login, "ada"); |
| 140 | assert_eq!(slept, [5, 5, 10, 10, 20]); |
| 141 | } |
| 142 | |
| 143 | #[test] |
| 144 | fn denied_expired_and_out_of_time() { |
| 145 | let (result, _) = run(vec![Ok(DevicePoll::Denied)], &start(1, 60)); |
| 146 | assert!(result.unwrap_err().to_string().contains("denied")); |
| 147 | let (result, _) = run( |
| 148 | vec![Ok(DevicePoll::Pending), Ok(DevicePoll::Expired)], |
| 149 | &start(1, 60), |
| 150 | ); |
| 151 | assert!(result.unwrap_err().to_string().contains("expired")); |
| 152 | // The code's lifetime bounds the wait, whatever the hub says. |
| 153 | let (result, slept) = run( |
| 154 | vec![Ok(DevicePoll::Pending), Ok(DevicePoll::Pending)], |
| 155 | &start(5, 10), |
| 156 | ); |
| 157 | assert!(result.unwrap_err().to_string().contains("expired")); |
| 158 | assert_eq!(slept, [5, 5]); |
| 159 | // An interval of 0 still waits a second between polls. |
| 160 | let (_, slept) = run(vec![Ok(DevicePoll::Denied)], &start(0, 60)); |
| 161 | assert_eq!(slept, [1]); |
| 162 | // Other errors stop at once. |
| 163 | let (result, _) = run( |
| 164 | vec![Err(HubError::api(500, "internal", "broken"))], |
| 165 | &start(1, 60), |
| 166 | ); |
| 167 | assert!(result.unwrap_err().to_string().contains("broken")); |
| 168 | // A malformed token is refused. |
| 169 | let (result, _) = run( |
| 170 | vec![Ok(DevicePoll::Ok { |
| 171 | token: "nope".to_owned(), |
| 172 | login: "ada".to_owned(), |
| 173 | expires: String::new(), |
| 174 | })], |
| 175 | &start(1, 60), |
| 176 | ); |
| 177 | assert!(result.is_err()); |
| 178 | } |
| 179 | } |