Skip to main content

scribe_client/
auth.rs

1use std::time::Duration;
2
3use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
4use rand::Rng;
5use serde::Deserialize;
6use sha2::{Digest, Sha256};
7use time::OffsetDateTime;
8use url::Url;
9
10use crate::error::ScribeError;
11
12/// A generated PKCE (RFC 7636) verifier/challenge pair. Always uses the
13/// `S256` challenge method; there's no reason for a client we control to
14/// use `plain`, even though the server supports it.
15#[derive(Debug, Clone)]
16pub struct PkceChallenge {
17    verifier: String,
18    challenge: String,
19}
20
21impl PkceChallenge {
22    /// Generates a new random verifier and its S256 challenge.
23    #[must_use]
24    pub fn generate() -> Self {
25        // RFC 7636 section 4.1: verifier is 43-128 chars from [A-Z a-z 0-9 - . _ ~].
26        // 32 random bytes, base64url-no-pad-encoded, is 43 chars and pulls
27        // only from that alphabet.
28        let mut bytes = [0u8; 32];
29        rand::rng().fill_bytes(&mut bytes);
30        let verifier = URL_SAFE_NO_PAD.encode(bytes);
31        let challenge = Self::derive_challenge(&verifier);
32        PkceChallenge {
33            verifier,
34            challenge,
35        }
36    }
37
38    fn derive_challenge(verifier: &str) -> String {
39        let mut hasher = Sha256::new();
40        hasher.update(verifier.as_bytes());
41        URL_SAFE_NO_PAD.encode(hasher.finalize())
42    }
43
44    #[must_use]
45    pub fn verifier(&self) -> &str {
46        &self.verifier
47    }
48
49    #[must_use]
50    pub fn challenge(&self) -> &str {
51        &self.challenge
52    }
53}
54
55/// An access/refresh token pair returned by `POST /oauth/token`.
56#[derive(Debug, Clone, PartialEq)]
57pub struct TokenSet {
58    pub access_token: String,
59    pub refresh_token: Option<String>,
60    pub expires_at: Option<OffsetDateTime>,
61}
62
63impl TokenSet {
64    /// True if this token is missing or will expire within `skew`.
65    #[must_use]
66    pub fn needs_refresh(&self, skew: Duration) -> bool {
67        match self.expires_at {
68            None => false,
69            Some(expires_at) => {
70                expires_at
71                    <= OffsetDateTime::now_utc()
72                        + time::Duration::seconds(skew.as_secs().cast_signed())
73            }
74        }
75    }
76}
77
78#[derive(Debug, Deserialize)]
79struct TokenResponse {
80    access_token: String,
81    refresh_token: Option<String>,
82    expires_in: Option<i64>,
83}
84
85#[derive(Debug, Deserialize)]
86struct TokenErrorResponse {
87    error: String,
88    #[allow(dead_code)]
89    #[serde(default)]
90    error_description: Option<String>,
91    #[serde(default)]
92    message: Option<String>,
93}
94
95impl From<TokenResponse> for TokenSet {
96    fn from(r: TokenResponse) -> Self {
97        TokenSet {
98            access_token: r.access_token,
99            refresh_token: r.refresh_token,
100            expires_at: r
101                .expires_in
102                .map(|secs| OffsetDateTime::now_utc() + time::Duration::seconds(secs)),
103        }
104    }
105}
106
107/// Drives the OAuth 2.0 Authorization Code + PKCE flow against a Scribe
108/// server. This type does not open a browser or run a redirect listener;
109/// the embedding application is responsible for presenting
110/// [`AuthClient::authorization_url`] to the user and obtaining the
111/// resulting `code` however fits its own UI.
112pub struct AuthClient {
113    http: reqwest::Client,
114    base_url: Url,
115    client_id: String,
116}
117
118impl AuthClient {
119    pub fn new(http: reqwest::Client, base_url: Url, client_id: impl Into<String>) -> Self {
120        AuthClient {
121            http,
122            base_url,
123            client_id: client_id.into(),
124        }
125    }
126
127    /// Builds the URL the user's browser should be sent to. `redirect_uri`
128    /// must match one registered for `client_id` server-side.
129    ///
130    /// The authorize request is wrapped in the server's `/auth/logout`
131    /// redirect, so whatever session the browser is holding for this server is
132    /// dropped before the authorize request is reached. Signing out only
133    /// clears this device's tokens: the browser's cookie store belongs to the
134    /// system, and an app has no way to reach into it. Without this, a session
135    /// cookie surviving sign-out lets the next sign-in complete without asking
136    /// for anything.
137    ///
138    /// Clearing it at sign-in rather than at sign-out is what keeps the
139    /// browser's SSO session with the identity provider intact, so a returning
140    /// user is asked for their email address instead of the whole credential
141    /// flow.
142    #[must_use]
143    pub fn authorization_url(&self, redirect_uri: &str, pkce: &PkceChallenge) -> Url {
144        self.authorization_url_with_challenge(redirect_uri, pkce.challenge())
145    }
146
147    /// [`AuthClient::authorization_url`] for callers that hold the challenge on
148    /// its own rather than the whole [`PkceChallenge`] — the FFI hands the
149    /// verifier to the host application to keep between the two halves of the
150    /// flow, so by this point only the challenge string is left.
151    #[must_use]
152    pub fn authorization_url_with_challenge(
153        &self,
154        redirect_uri: &str,
155        pkce_challenge: &str,
156    ) -> Url {
157        let mut authorize = self.base_url.clone();
158        authorize.set_path("/oauth/authorize");
159        authorize
160            .query_pairs_mut()
161            .append_pair("response_type", "code")
162            .append_pair("client_id", &self.client_id)
163            .append_pair("redirect_uri", redirect_uri)
164            .append_pair("code_challenge", pkce_challenge)
165            .append_pair("code_challenge_method", "S256");
166
167        // `next` is a path and query only, never an absolute URL: the server
168        // refuses external targets so it cannot be used as an open redirect.
169        let next = match authorize.query() {
170            Some(query) => format!("{}?{}", authorize.path(), query),
171            None => authorize.path().to_owned(),
172        };
173
174        let mut url = self.base_url.clone();
175        url.set_path("/auth/logout");
176        url.query_pairs_mut().append_pair("next", &next);
177        url
178    }
179
180    /// Exchanges an authorization code (obtained after the user completes
181    /// the browser flow at [`AuthClient::authorization_url`]) for a token
182    /// set. `verifier` must be the same [`PkceChallenge`] used to build
183    /// that URL.
184    ///
185    /// # Errors
186    ///
187    /// Returns [`ScribeError::InvalidGrant`] if the code or verifier is
188    /// wrong or expired, or [`ScribeError::Http`]/[`ScribeError::Api`] on
189    /// other request failures.
190    pub async fn exchange_code(
191        &self,
192        redirect_uri: &str,
193        code: &str,
194        verifier: &str,
195    ) -> Result<TokenSet, ScribeError> {
196        let mut url = self.base_url.clone();
197        url.set_path("/oauth/token");
198        let body = [
199            ("grant_type", "authorization_code"),
200            ("client_id", &self.client_id),
201            ("redirect_uri", redirect_uri),
202            ("code", code),
203            ("code_verifier", verifier),
204        ];
205        self.send_token_request(url, &body).await
206    }
207
208    /// Exchanges a refresh token for a new token set.
209    ///
210    /// # Errors
211    ///
212    /// Returns [`ScribeError::InvalidGrant`] if the refresh token is wrong,
213    /// expired, or revoked, or [`ScribeError::Http`]/[`ScribeError::Api`] on
214    /// other request failures.
215    pub async fn refresh(&self, refresh_token: &str) -> Result<TokenSet, ScribeError> {
216        let mut url = self.base_url.clone();
217        url.set_path("/oauth/token");
218        let body = [
219            ("grant_type", "refresh_token"),
220            ("client_id", &self.client_id),
221            ("refresh_token", refresh_token),
222        ];
223        self.send_token_request(url, &body).await
224    }
225
226    /// Asks the server to invalidate a token, so signing out ends the session
227    /// there and then rather than leaving a refresh token usable until it
228    /// expires on its own.
229    ///
230    /// Pass the refresh token when there is one: revoking it takes the access
231    /// tokens issued alongside it with it. Passing an access token instead
232    /// revokes only that token.
233    ///
234    /// Per RFC 7009 the server answers successfully whether or not it
235    /// recognised the token, so a success here means the request was accepted,
236    /// not that something was necessarily revoked.
237    ///
238    /// # Errors
239    ///
240    /// Returns [`ScribeError::Http`] if the request could not be sent, or
241    /// [`ScribeError::Api`] if the server refused it.
242    pub async fn revoke(&self, token: &str) -> Result<(), ScribeError> {
243        let mut url = self.base_url.clone();
244        url.set_path("/oauth/revoke");
245        let body = [("client_id", self.client_id.as_str()), ("token", token)];
246        let response = self.http.post(url).form(&body).send().await?;
247        let status = response.status();
248        if status.is_success() {
249            return Ok(());
250        }
251
252        let text = response.text().await.unwrap_or_default();
253        let fallback = || "We couldn't sign you out completely.".to_string();
254        let (code, message) = match serde_json::from_str::<TokenErrorResponse>(&text) {
255            Ok(err) => (err.error, err.message.unwrap_or_else(fallback)),
256            Err(_) => ("server_error".to_string(), fallback()),
257        };
258        Err(ScribeError::Api {
259            status: status.as_u16(),
260            code,
261            message,
262        })
263    }
264
265    async fn send_token_request(
266        &self,
267        url: Url,
268        body: &[(&str, &str)],
269    ) -> Result<TokenSet, ScribeError> {
270        let response = self.http.post(url).form(body).send().await?;
271        let status = response.status();
272        if status.is_success() {
273            let parsed: TokenResponse = response.json().await?;
274            Ok(parsed.into())
275        } else {
276            let text = response.text().await.unwrap_or_default();
277            match serde_json::from_str::<TokenErrorResponse>(&text) {
278                Ok(err) if err.error == "invalid_grant" => Err(ScribeError::InvalidGrant {
279                    message: err.message.unwrap_or_else(|| {
280                        "Your session has expired. Please sign in again.".to_string()
281                    }),
282                }),
283                Ok(err) => Err(ScribeError::Api {
284                    status: status.as_u16(),
285                    code: err.error,
286                    message: err.message.unwrap_or_else(|| {
287                        "We couldn't sign you in. Please try again.".to_string()
288                    }),
289                }),
290                Err(_) => Err(ScribeError::Api {
291                    status: status.as_u16(),
292                    code: "server_error".to_string(),
293                    message: "We couldn't sign you in. Please try again.".to_string(),
294                }),
295            }
296        }
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    #[test]
305    fn generated_verifier_matches_rfc7636_charset_and_length() {
306        let pkce = PkceChallenge::generate();
307        assert_eq!(pkce.verifier().len(), 43);
308        assert!(pkce.verifier().chars().all(|c| c.is_ascii_alphanumeric()
309            || c == '-'
310            || c == '.'
311            || c == '_'
312            || c == '~'));
313    }
314
315    #[test]
316    fn challenge_is_deterministic_s256_of_verifier() {
317        // RFC 7636 appendix B test vector.
318        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
319        let expected_challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
320        assert_eq!(
321            PkceChallenge::derive_challenge(verifier),
322            expected_challenge
323        );
324    }
325
326    #[test]
327    fn two_generated_challenges_differ() {
328        let a = PkceChallenge::generate();
329        let b = PkceChallenge::generate();
330        assert_ne!(a.verifier(), b.verifier());
331        assert_ne!(a.challenge(), b.challenge());
332    }
333
334    #[test]
335    fn token_with_no_expiry_never_needs_refresh() {
336        let tokens = TokenSet {
337            access_token: "at".into(),
338            refresh_token: None,
339            expires_at: None,
340        };
341        assert!(!tokens.needs_refresh(Duration::from_secs(30)));
342    }
343
344    #[test]
345    fn token_well_outside_skew_does_not_need_refresh() {
346        let tokens = TokenSet {
347            access_token: "at".into(),
348            refresh_token: None,
349            expires_at: Some(OffsetDateTime::now_utc() + time::Duration::hours(1)),
350        };
351        assert!(!tokens.needs_refresh(Duration::from_secs(30)));
352    }
353
354    #[test]
355    fn token_within_skew_of_expiry_needs_refresh() {
356        let tokens = TokenSet {
357            access_token: "at".into(),
358            refresh_token: None,
359            expires_at: Some(OffsetDateTime::now_utc() + time::Duration::seconds(5)),
360        };
361        assert!(tokens.needs_refresh(Duration::from_secs(30)));
362    }
363
364    #[test]
365    fn already_expired_token_needs_refresh() {
366        let tokens = TokenSet {
367            access_token: "at".into(),
368            refresh_token: None,
369            expires_at: Some(OffsetDateTime::now_utc() - time::Duration::hours(1)),
370        };
371        assert!(tokens.needs_refresh(Duration::from_secs(30)));
372    }
373}