Skip to main content

subspace_github_auth/
device.rs

1//! The device flow (RFC 8628): GitHub gives a code for the user to enter at
2//! `github.com/login/device`, and Subspace polls the token endpoint until
3//! the user approves, declines or the code expires. It needs no client
4//! secret, so builds without one use it.
5
6use std::time::{Duration, Instant};
7
8use serde::Deserialize;
9use subspace_core::Secret;
10
11use crate::token::{self, Granted, Reply};
12use crate::{AuthError, Cancel, Endpoints, Pending, Prompt, SignedIn, Started};
13
14pub const DEVICE_CODE_PATH: &str = "/login/device/code";
15pub const GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:device_code";
16/// RFC 8628's default polling interval, in seconds.
17const DEFAULT_INTERVAL: u64 = 5;
18/// How much `slow_down` adds to the interval, in seconds.
19const SLOW_DOWN_STEP: u64 = 5;
20/// GitHub's device codes last 15 minutes.
21const DEFAULT_EXPIRY: u64 = 15 * 60;
22
23/// GitHub's answer to a device-code request.
24#[derive(Debug, PartialEq, Eq)]
25pub struct DeviceCode {
26    pub device_code: Secret,
27    pub user_code: String,
28    pub verification_uri: String,
29    pub expires_in: u64,
30    pub interval: u64,
31}
32
33#[derive(Deserialize)]
34struct Raw {
35    device_code: Option<String>,
36    user_code: Option<String>,
37    verification_uri: Option<String>,
38    expires_in: Option<u64>,
39    interval: Option<u64>,
40    error: Option<String>,
41    error_description: Option<String>,
42}
43
44/// Reads a device-code answer.
45pub fn parse_code(body: &[u8]) -> Result<DeviceCode, AuthError> {
46    let raw: Raw = serde_json::from_slice(body)
47        .map_err(|_| AuthError::Service("GitHub's answer was not understood.".into()))?;
48    if raw.error.is_some() {
49        return Err(token::failure(raw.error.as_deref(), raw.error_description));
50    }
51    let (Some(device_code), Some(user_code), Some(verification_uri)) =
52        (raw.device_code, raw.user_code, raw.verification_uri)
53    else {
54        return Err(token::failure(None, None));
55    };
56    Ok(DeviceCode {
57        device_code: Secret::new(device_code),
58        user_code,
59        verification_uri,
60        expires_in: raw.expires_in.unwrap_or(DEFAULT_EXPIRY),
61        interval: raw.interval.unwrap_or(DEFAULT_INTERVAL),
62    })
63}
64
65/// What to do after one poll.
66#[derive(Debug, PartialEq, Eq)]
67pub enum Poll {
68    /// Wait `interval` seconds and poll again.
69    Again {
70        interval: u64,
71    },
72    Done(Result<Granted, AuthError>),
73}
74
75/// The next step after `reply`, polling every `interval` seconds so far.
76pub fn after(reply: Reply, interval: u64) -> Poll {
77    match reply {
78        Reply::Token(granted) => Poll::Done(Ok(granted)),
79        Reply::Pending => Poll::Again { interval },
80        Reply::SlowDown(next) => Poll::Again {
81            interval: next.unwrap_or(0).max(interval + SLOW_DOWN_STEP),
82        },
83        Reply::Failed(error) => Poll::Done(Err(error)),
84    }
85}
86
87/// Asks GitHub for a device code.
88pub(crate) fn start(
89    client_id: &str,
90    endpoints: &Endpoints,
91    time_limit: Duration,
92) -> Result<Started, AuthError> {
93    let code = request_code(client_id, endpoints)?;
94    let prompt = Prompt::Device {
95        user_code: code.user_code.clone(),
96        verification_uri: code.verification_uri.clone(),
97    };
98    let started = Instant::now();
99    let pending = DevicePending {
100        endpoints: endpoints.clone(),
101        client_id: client_id.to_owned(),
102        expires: started + Duration::from_secs(code.expires_in),
103        limit: started + time_limit,
104        code,
105    };
106    Ok(Started {
107        prompt,
108        pending: Box::new(pending),
109    })
110}
111
112fn request_code(client_id: &str, endpoints: &Endpoints) -> Result<DeviceCode, AuthError> {
113    let network = |error: ureq::Error| AuthError::Network(error.to_string());
114    let mut response = subspace_core::http::agent()
115        .post(format!("{}{DEVICE_CODE_PATH}", endpoints.oauth))
116        .header("Accept", "application/json")
117        .send_form([("client_id", client_id), ("scope", crate::config::SCOPES)])
118        .map_err(network)?;
119    let body = response
120        .body_mut()
121        .with_config()
122        .limit(token::REPLY_LIMIT)
123        .read_to_vec()
124        .map_err(network)?;
125    parse_code(&body)
126}
127
128struct DevicePending {
129    endpoints: Endpoints,
130    client_id: String,
131    code: DeviceCode,
132    expires: Instant,
133    limit: Instant,
134}
135
136impl DevicePending {
137    /// The error once the code expired or the time limit passed.
138    fn overdue(&self) -> Option<AuthError> {
139        let now = Instant::now();
140        if now >= self.expires {
141            return Some(AuthError::Expired);
142        }
143        (now >= self.limit).then_some(AuthError::TimedOut)
144    }
145
146    fn poll(&self) -> Result<Reply, AuthError> {
147        let form = [
148            ("client_id", self.client_id.as_str()),
149            ("device_code", self.code.device_code.expose()),
150            ("grant_type", GRANT_TYPE),
151        ];
152        token::request(&self.endpoints.oauth, &form)
153    }
154}
155
156impl Pending for DevicePending {
157    fn finish(self: Box<Self>, cancel: &Cancel) -> Result<SignedIn, AuthError> {
158        let mut interval = self.code.interval;
159        loop {
160            crate::sleep(Duration::from_secs(interval), cancel)?;
161            if let Some(error) = self.overdue() {
162                return Err(error);
163            }
164            match after(self.poll()?, interval) {
165                Poll::Again { interval: next } => interval = next,
166                Poll::Done(granted) => return crate::signed_in(&self.endpoints, granted?),
167            }
168        }
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::{Poll, after, parse_code};
175    use crate::AuthError;
176    use crate::token::{Granted, Reply};
177    use subspace_core::Secret;
178
179    #[test]
180    fn a_device_code_answer_gives_the_code_to_show_and_the_polling_interval() {
181        let code = parse_code(
182            br#"{"device_code":"secret-device","user_code":"WDJB-MJHT","verification_uri":"https://github.com/login/device","expires_in":899,"interval":5}"#,
183        )
184        .unwrap();
185        assert_eq!(code.user_code, "WDJB-MJHT");
186        assert_eq!(code.verification_uri, "https://github.com/login/device");
187        assert_eq!((code.expires_in, code.interval), (899, 5));
188        assert!(!format!("{code:?}").contains("secret-device"));
189    }
190
191    #[test]
192    fn a_disabled_device_flow_is_a_clear_error() {
193        let error = parse_code(br#"{"error":"device_flow_disabled","error_description":"Device Flow must be explicitly enabled for this App","error_uri":"https://docs.github.com"}"#)
194            .unwrap_err();
195        assert_eq!(error, AuthError::DeviceFlowDisabled);
196        assert!(error.to_string().contains("gh auth login"));
197        assert!(matches!(parse_code(b"{}"), Err(AuthError::Service(_))));
198    }
199
200    #[test]
201    fn polling_waits_slows_down_and_stops_as_github_says() {
202        assert_eq!(after(Reply::Pending, 5), Poll::Again { interval: 5 });
203        assert_eq!(
204            after(Reply::SlowDown(None), 5),
205            Poll::Again { interval: 10 }
206        );
207        assert_eq!(
208            after(Reply::SlowDown(Some(15)), 5),
209            Poll::Again { interval: 15 }
210        );
211        assert_eq!(
212            after(Reply::SlowDown(Some(1)), 5),
213            Poll::Again { interval: 10 }
214        );
215        assert_eq!(
216            after(Reply::Failed(AuthError::Denied), 5),
217            Poll::Done(Err(AuthError::Denied))
218        );
219        assert_eq!(
220            after(Reply::Failed(AuthError::Expired), 5),
221            Poll::Done(Err(AuthError::Expired))
222        );
223        let granted = Granted {
224            token: Secret::new("token"),
225            scopes: Vec::new(),
226        };
227        assert_eq!(
228            after(Reply::Token(granted.clone()), 5),
229            Poll::Done(Ok(granted))
230        );
231    }
232}