Skip to main content

beyondigital_auth_sdk/
flows.rs

1//! Protocol pieces behind the client: the device flow poll loop (RFC 8628), token exchange constants (RFC 8693) and the
2//! pushed authorization request body and answer (RFC 9126).
3//!
4//! Nothing here puts a secret in an error: a device code, a token or a pushed request body is never echoed, and a
5//! malformed answer is reported by its kind only.
6use std::fmt;
7use std::future::Future;
8use std::pin::Pin;
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::{Arc, OnceLock};
11use std::time::{Duration, Instant};
12
13use serde_json::Value;
14use tokio::sync::Notify;
15
16use crate::client::TokenResponse;
17use crate::error::AuthError;
18use crate::wire::{form_urlencode, non_blank};
19
20pub const DEVICE_CODE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
21pub const TOKEN_EXCHANGE_GRANT: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
22/// The only token type the service exchanges (`subject_token_type`, `actor_token_type` and `requested_token_type`).
23pub const TOKEN_TYPE_ACCESS_TOKEN: &str = "urn:ietf:params:oauth:token-type:access_token";
24
25pub const DEFAULT_DEVICE_INTERVAL_SECONDS: u64 = 5;
26pub const SLOW_DOWN_STEP_SECONDS: u64 = 5;
27
28// ── Device flow ───────────────────────────────────────────────────────────────────────────
29
30/// The answer to a device authorization request: show `user_code` and `verification_uri` to the person.
31#[derive(Clone, PartialEq)]
32pub struct DeviceAuthorization {
33    /// Secret the device polls with. Never show it (it is also left out of `Debug`).
34    pub device_code: String,
35    /// What the person types at `verification_uri`.
36    pub user_code: String,
37    pub verification_uri: String,
38    /// `verification_uri` with the code filled in, for a QR code or a link.
39    pub verification_uri_complete: Option<String>,
40    /// Seconds until the codes expire.
41    pub expires_in: f64,
42    /// Minimum seconds between polls.
43    pub interval: Option<u64>,
44}
45
46impl fmt::Debug for DeviceAuthorization {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        f.debug_struct("DeviceAuthorization")
49            .field("user_code", &self.user_code)
50            .field("verification_uri", &self.verification_uri)
51            .field("verification_uri_complete", &self.verification_uri_complete)
52            .field("expires_in", &self.expires_in)
53            .field("interval", &self.interval)
54            .finish_non_exhaustive()
55    }
56}
57
58fn http_url(value: &Value) -> Option<&str> {
59    let text = value.as_str()?;
60    crate::wire::origin_of(text)?;
61    Some(text)
62}
63
64/// Validate the service's device authorization answer; the error never echoes it.
65pub fn parse_device_authorization(body: &Value) -> Result<DeviceAuthorization, AuthError> {
66    let malformed = || {
67        AuthError::Config("The service returned a malformed device authorization response".into())
68    };
69    let text = |name: &str| -> Option<String> {
70        let value = body.get(name)?.as_str()?;
71        non_blank(value).then(|| value.to_string())
72    };
73    let optional_url = |name: &str| -> Result<Option<String>, AuthError> {
74        match body.get(name) {
75            None | Some(Value::Null) => Ok(None),
76            Some(value) => http_url(value)
77                .map(|u| Some(u.to_string()))
78                .ok_or_else(malformed),
79        }
80    };
81    let device_code = text("device_code").ok_or_else(malformed)?;
82    let user_code = text("user_code").ok_or_else(malformed)?;
83    let verification_uri = body
84        .get("verification_uri")
85        .and_then(http_url)
86        .ok_or_else(malformed)?
87        .to_string();
88    let verification_uri_complete = optional_url("verification_uri_complete")?;
89    let expires_in = body
90        .get("expires_in")
91        .and_then(Value::as_f64)
92        .filter(|n| n.is_finite() && *n > 0.0)
93        .ok_or_else(malformed)?;
94    let interval = match body.get("interval") {
95        None | Some(Value::Null) => None,
96        Some(value) => Some(value.as_u64().filter(|n| *n > 0).ok_or_else(malformed)?),
97    };
98    Ok(DeviceAuthorization {
99        device_code,
100        user_code,
101        verification_uri,
102        verification_uri_complete,
103        expires_in,
104        interval,
105    })
106}
107
108/// Stops a device flow: clone it, hand one copy to the poll and call [`cancel`](Self::cancel) on the other.
109#[derive(Clone, Default)]
110pub struct CancelToken {
111    inner: Arc<CancelInner>,
112}
113
114#[derive(Default)]
115struct CancelInner {
116    cancelled: AtomicBool,
117    notify: Notify,
118}
119
120impl fmt::Debug for CancelToken {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        f.debug_struct("CancelToken")
123            .field("cancelled", &self.is_cancelled())
124            .finish()
125    }
126}
127
128impl CancelToken {
129    pub fn new() -> Self {
130        Self::default()
131    }
132    pub fn cancel(&self) {
133        self.inner.cancelled.store(true, Ordering::SeqCst);
134        self.inner.notify.notify_waiters();
135    }
136    pub fn is_cancelled(&self) -> bool {
137        self.inner.cancelled.load(Ordering::SeqCst)
138    }
139    async fn cancelled(&self) {
140        loop {
141            let notified = self.inner.notify.notified();
142            tokio::pin!(notified);
143            // Register interest before the flag is read, so a cancel in between is not missed.
144            notified.as_mut().enable();
145            if self.is_cancelled() {
146                return;
147            }
148            notified.await;
149        }
150    }
151}
152
153/// Waits for a duration. Replace it in tests so no real time passes.
154pub type SleepFn = Arc<dyn Fn(Duration) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
155/// A monotonic clock: time since any fixed origin. Replace it in tests.
156pub type ClockFn = Arc<dyn Fn() -> Duration + Send + Sync>;
157
158/// Test hooks and cancellation for the device poll.
159#[derive(Clone, Default)]
160pub struct DevicePollOptions {
161    /// Replaces the real wait. It is given the full wait and must not return early on its own.
162    pub sleep: Option<SleepFn>,
163    /// Replaces the monotonic clock the device code's own deadline is judged against.
164    pub now: Option<ClockFn>,
165    /// Stops the wait and the flow with [`AuthError::Cancelled`].
166    pub cancel: Option<CancelToken>,
167}
168
169impl fmt::Debug for DevicePollOptions {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        f.debug_struct("DevicePollOptions")
172            .field("sleep", &self.sleep.is_some())
173            .field("now", &self.now.is_some())
174            .field("cancel", &self.cancel)
175            .finish()
176    }
177}
178
179fn process_clock() -> Duration {
180    static START: OnceLock<Instant> = OnceLock::new();
181    START.get_or_init(Instant::now).elapsed()
182}
183
184fn cancelled() -> AuthError {
185    AuthError::Cancelled("The device flow was cancelled".into())
186}
187
188/// Poll until the person decides (RFC 8628 section 3.5).
189///
190/// The wait comes before every poll; `slow_down` adds five seconds to every later wait; `authorization_pending` waits
191/// again; every other error (including `access_denied` and `expired_token`) ends the flow and is returned as the
192/// service sent it. The device code's own lifetime is enforced here too: no request is made once the next wait would
193/// pass it. A network failure is returned, not retried: call this again with the same authorization to resume.
194pub async fn poll_for_device_token<F, Fut>(
195    device: &DeviceAuthorization,
196    mut request_token: F,
197    options: &DevicePollOptions,
198) -> Result<TokenResponse, AuthError>
199where
200    F: FnMut() -> Fut,
201    Fut: Future<Output = Result<TokenResponse, AuthError>>,
202{
203    let clock = |options: &DevicePollOptions| match &options.now {
204        Some(now) => now(),
205        None => process_clock(),
206    };
207    let mut interval = device
208        .interval
209        .filter(|n| *n > 0)
210        .unwrap_or(DEFAULT_DEVICE_INTERVAL_SECONDS);
211    let lifetime = Duration::try_from_secs_f64(device.expires_in).unwrap_or(Duration::MAX);
212    let deadline = clock(options).saturating_add(lifetime);
213    loop {
214        let wait = Duration::from_secs(interval);
215        if clock(options).saturating_add(wait) > deadline {
216            return Err(AuthError::oauth(
217                "expired_token",
218                "The device code expired before the person approved",
219                400,
220            ));
221        }
222        if options
223            .cancel
224            .as_ref()
225            .is_some_and(CancelToken::is_cancelled)
226        {
227            return Err(cancelled());
228        }
229        match (&options.sleep, &options.cancel) {
230            (Some(sleep), _) => sleep(wait).await,
231            (None, Some(cancel)) => {
232                tokio::select! {
233                    () = tokio::time::sleep(wait) => {}
234                    () = cancel.cancelled() => {}
235                }
236            }
237            (None, None) => tokio::time::sleep(wait).await,
238        }
239        if options
240            .cancel
241            .as_ref()
242            .is_some_and(CancelToken::is_cancelled)
243        {
244            return Err(cancelled());
245        }
246        match request_token().await {
247            Err(AuthError::OAuth { ref error, .. }) if error == "authorization_pending" => {}
248            Err(AuthError::OAuth { ref error, .. }) if error == "slow_down" => {
249                interval += SLOW_DOWN_STEP_SECONDS;
250            }
251            other => return other,
252        }
253    }
254}
255
256// ── Pushed authorization requests ──────────────────────────────────────────────────────────
257
258/// The answer to a pushed authorization request.
259#[derive(Debug, Clone, PartialEq)]
260pub struct PushedAuthorization {
261    /// Opaque, single use, and only this client can present it.
262    pub request_uri: String,
263    /// Seconds it stays valid.
264    pub expires_in: f64,
265}
266
267/// Parameters the SDK sets itself or that authenticate the client: not allowed in `extra`.
268const OWNED_PARAMETERS: &[&str] = &[
269    "response_type",
270    "client_id",
271    "redirect_uri",
272    "scope",
273    "state",
274    "nonce",
275    "code_challenge",
276    "code_challenge_method",
277    "resource",
278    "client_secret",
279    "client_assertion",
280    "client_assertion_type",
281    "request_uri",
282    "request",
283];
284
285/// The authorize parameters of a pushed request, in order. `client_id` is set again by client authentication.
286///
287/// `extra` carries more authorize parameters (`prompt`, `login_hint`, `max_age`, `organization` ...). Not allowed:
288/// anything that authenticates the client, `request`, `request_uri`, or a parameter this function already owns (in any
289/// letter case).
290#[allow(clippy::too_many_arguments)]
291pub fn pushed_request_params(
292    client_id: &str,
293    redirect_uri: &str,
294    code_challenge: &str,
295    state: Option<&str>,
296    scope: Option<&str>,
297    nonce: Option<&str>,
298    resource: &[String],
299    extra: &[(String, String)],
300) -> Result<Vec<(String, String)>, AuthError> {
301    let mut pairs = vec![
302        ("response_type".to_string(), "code".to_string()),
303        ("client_id".to_string(), client_id.to_string()),
304        ("redirect_uri".to_string(), redirect_uri.to_string()),
305    ];
306    for (name, value) in [("scope", scope), ("state", state), ("nonce", nonce)] {
307        if let Some(value) = value.filter(|v| !v.is_empty()) {
308            pairs.push((name.to_string(), value.to_string()));
309        }
310    }
311    pairs.push(("code_challenge".into(), code_challenge.into()));
312    pairs.push(("code_challenge_method".into(), "S256".into()));
313    for item in resource {
314        pairs.push(("resource".to_string(), item.clone()));
315    }
316    for (name, value) in extra {
317        if OWNED_PARAMETERS.contains(&name.to_ascii_lowercase().as_str()) {
318            return Err(AuthError::Config(format!(
319                "The extra parameter {name} is not allowed: it is set by the SDK or authenticates the client"
320            )));
321        }
322        pairs.push((name.clone(), value.clone()));
323    }
324    Ok(pairs)
325}
326
327pub fn parse_pushed_authorization(body: &Value) -> Result<PushedAuthorization, AuthError> {
328    let malformed = || {
329        AuthError::Config("The service returned a malformed pushed authorization response".into())
330    };
331    let request_uri = body
332        .get("request_uri")
333        .and_then(Value::as_str)
334        .filter(|s| non_blank(s))
335        .ok_or_else(malformed)?;
336    let expires_in = body
337        .get("expires_in")
338        .and_then(Value::as_f64)
339        .filter(|n| n.is_finite() && *n > 0.0)
340        .ok_or_else(malformed)?;
341    Ok(PushedAuthorization {
342        request_uri: request_uri.to_string(),
343        expires_in,
344    })
345}
346
347/// The authorize URL for a pushed request: only `client_id` and `request_uri` (RFC 9126 section 4).
348pub fn build_authorization_url_from_request_uri(
349    issuer_url: &str,
350    client_id: &str,
351    request_uri: &str,
352) -> Result<String, AuthError> {
353    if !non_blank(client_id) {
354        return Err(AuthError::Config("client_id is required".into()));
355    }
356    if !non_blank(request_uri) {
357        return Err(AuthError::Config("request_uri is required".into()));
358    }
359    Ok(format!(
360        "{}/oauth/authorize?client_id={}&request_uri={}",
361        issuer_url.trim_end_matches('/'),
362        form_urlencode(client_id),
363        form_urlencode(request_uri)
364    ))
365}