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    locale: Option<String>,
117}
118
119impl AuthClient {
120    pub fn new(http: reqwest::Client, base_url: Url, client_id: impl Into<String>) -> Self {
121        AuthClient {
122            http,
123            base_url,
124            client_id: client_id.into(),
125            locale: None,
126        }
127    }
128
129    /// Asks the server for its messages in `locale`, a language tag such as
130    /// `de` or `pt-BR`, usually the language the app's own interface is in.
131    /// The sign-in page from [`Self::authorization_url`] opens in it too.
132    /// Without one, the server uses the account's language, or English.
133    #[must_use]
134    pub fn with_locale(mut self, locale: impl Into<String>) -> Self {
135        self.locale = Some(locale.into());
136        self
137    }
138
139    pub(crate) fn locale(&self) -> Option<&str> {
140        self.locale.as_deref()
141    }
142
143    /// Builds the URL the user's browser should be sent to. `redirect_uri`
144    /// must match one registered for `client_id` server-side.
145    ///
146    /// The authorize request is wrapped in the server's `/auth/logout`
147    /// redirect, so whatever session the browser is holding for this server is
148    /// dropped before the authorize request is reached. Signing out only
149    /// clears this device's tokens: the browser's cookie store belongs to the
150    /// system, and an app has no way to reach into it. Without this, a session
151    /// cookie surviving sign-out lets the next sign-in complete without asking
152    /// for anything.
153    ///
154    /// Clearing it at sign-in rather than at sign-out is what keeps the
155    /// browser's SSO session with the identity provider intact, so a returning
156    /// user is asked for their email address instead of the whole credential
157    /// flow.
158    #[must_use]
159    pub fn authorization_url(&self, redirect_uri: &str, pkce: &PkceChallenge) -> Url {
160        self.authorization_url_with_challenge(redirect_uri, pkce.challenge())
161    }
162
163    /// [`AuthClient::authorization_url`] for callers that hold the challenge on
164    /// its own rather than the whole [`PkceChallenge`] — the FFI hands the
165    /// verifier to the host application to keep between the two halves of the
166    /// flow, so by this point only the challenge string is left.
167    #[must_use]
168    pub fn authorization_url_with_challenge(
169        &self,
170        redirect_uri: &str,
171        pkce_challenge: &str,
172    ) -> Url {
173        let mut authorize = self.base_url.clone();
174        authorize.set_path("/oauth/authorize");
175        authorize
176            .query_pairs_mut()
177            .append_pair("response_type", "code")
178            .append_pair("client_id", &self.client_id)
179            .append_pair("redirect_uri", redirect_uri)
180            .append_pair("code_challenge", pkce_challenge)
181            .append_pair("code_challenge_method", "S256");
182
183        // `next` is a path and query only, never an absolute URL: the server
184        // refuses external targets so it cannot be used as an open redirect.
185        let next = match authorize.query() {
186            Some(query) => format!("{}?{}", authorize.path(), query),
187            None => authorize.path().to_owned(),
188        };
189
190        let mut url = self.base_url.clone();
191        url.set_path("/auth/logout");
192        url.query_pairs_mut().append_pair("next", &next);
193        // The website keeps `locale` in a cookie that logging out leaves
194        // alone, so the sign-in page the redirects end on is in it too.
195        if let Some(locale) = &self.locale {
196            url.query_pairs_mut().append_pair("locale", locale);
197        }
198        url
199    }
200
201    /// Exchanges an authorization code (obtained after the user completes
202    /// the browser flow at [`AuthClient::authorization_url`]) for a token
203    /// set. `verifier` must be the same [`PkceChallenge`] used to build
204    /// that URL.
205    ///
206    /// # Errors
207    ///
208    /// Returns [`ScribeError::InvalidGrant`] if the code or verifier is
209    /// wrong or expired, or [`ScribeError::Http`]/[`ScribeError::Api`] on
210    /// other request failures.
211    pub async fn exchange_code(
212        &self,
213        redirect_uri: &str,
214        code: &str,
215        verifier: &str,
216    ) -> Result<TokenSet, ScribeError> {
217        let mut url = self.base_url.clone();
218        url.set_path("/oauth/token");
219        let body = [
220            ("grant_type", "authorization_code"),
221            ("client_id", &self.client_id),
222            ("redirect_uri", redirect_uri),
223            ("code", code),
224            ("code_verifier", verifier),
225        ];
226        self.send_token_request(url, &body).await
227    }
228
229    /// Exchanges a refresh token for a new token set.
230    ///
231    /// # Errors
232    ///
233    /// Returns [`ScribeError::InvalidGrant`] if the refresh token is wrong,
234    /// expired, or revoked, or [`ScribeError::Http`]/[`ScribeError::Api`] on
235    /// other request failures.
236    pub async fn refresh(&self, refresh_token: &str) -> Result<TokenSet, ScribeError> {
237        let mut url = self.base_url.clone();
238        url.set_path("/oauth/token");
239        let body = [
240            ("grant_type", "refresh_token"),
241            ("client_id", &self.client_id),
242            ("refresh_token", refresh_token),
243        ];
244        self.send_token_request(url, &body).await
245    }
246
247    /// Asks the server to invalidate a token, so signing out ends the session
248    /// there and then rather than leaving a refresh token usable until it
249    /// expires on its own.
250    ///
251    /// Pass the refresh token when there is one: revoking it takes the access
252    /// tokens issued alongside it with it. Passing an access token instead
253    /// revokes only that token.
254    ///
255    /// Per RFC 7009 the server answers successfully whether or not it
256    /// recognised the token, so a success here means the request was accepted,
257    /// not that something was necessarily revoked.
258    ///
259    /// # Errors
260    ///
261    /// Returns [`ScribeError::Http`] if the request could not be sent, or
262    /// [`ScribeError::Api`] if the server refused it.
263    pub async fn revoke(&self, token: &str) -> Result<(), ScribeError> {
264        let mut url = self.base_url.clone();
265        url.set_path("/oauth/revoke");
266        let body = [("client_id", self.client_id.as_str()), ("token", token)];
267        let response = accept_language(self.http.post(url), self.locale())
268            .form(&body)
269            .send()
270            .await?;
271        let status = response.status();
272        if status.is_success() {
273            return Ok(());
274        }
275
276        let text = response.text().await.unwrap_or_default();
277        let fallback = || "We couldn't sign you out completely.".to_string();
278        let (code, message) = match serde_json::from_str::<TokenErrorResponse>(&text) {
279            Ok(err) => (err.error, err.message.unwrap_or_else(fallback)),
280            Err(_) => ("server_error".to_string(), fallback()),
281        };
282        Err(ScribeError::Api {
283            status: status.as_u16(),
284            code,
285            message,
286        })
287    }
288
289    async fn send_token_request(
290        &self,
291        url: Url,
292        body: &[(&str, &str)],
293    ) -> Result<TokenSet, ScribeError> {
294        let response = accept_language(self.http.post(url), self.locale())
295            .form(body)
296            .send()
297            .await?;
298        let status = response.status();
299        if status.is_success() {
300            let parsed: TokenResponse = response.json().await?;
301            Ok(parsed.into())
302        } else {
303            let text = response.text().await.unwrap_or_default();
304            match serde_json::from_str::<TokenErrorResponse>(&text) {
305                Ok(err) if err.error == "invalid_grant" => Err(ScribeError::InvalidGrant {
306                    message: err.message.unwrap_or_else(|| {
307                        "Your session has expired. Please sign in again.".to_string()
308                    }),
309                }),
310                Ok(err) => Err(ScribeError::Api {
311                    status: status.as_u16(),
312                    code: err.error,
313                    message: err.message.unwrap_or_else(|| {
314                        "We couldn't sign you in. Please try again.".to_string()
315                    }),
316                }),
317                Err(_) => Err(ScribeError::Api {
318                    status: status.as_u16(),
319                    code: "server_error".to_string(),
320                    message: "We couldn't sign you in. Please try again.".to_string(),
321                }),
322            }
323        }
324    }
325}
326
327/// Adds `Accept-Language` for `locale`, which is how the server picks the
328/// language of what it says in a response.
329pub(crate) fn accept_language(
330    request: reqwest::RequestBuilder,
331    locale: Option<&str>,
332) -> reqwest::RequestBuilder {
333    match locale {
334        Some(locale) => request.header(reqwest::header::ACCEPT_LANGUAGE, locale),
335        None => request,
336    }
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    #[test]
344    fn generated_verifier_matches_rfc7636_charset_and_length() {
345        let pkce = PkceChallenge::generate();
346        assert_eq!(pkce.verifier().len(), 43);
347        assert!(pkce.verifier().chars().all(|c| c.is_ascii_alphanumeric()
348            || c == '-'
349            || c == '.'
350            || c == '_'
351            || c == '~'));
352    }
353
354    #[test]
355    fn challenge_is_deterministic_s256_of_verifier() {
356        // RFC 7636 appendix B test vector.
357        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
358        let expected_challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
359        assert_eq!(
360            PkceChallenge::derive_challenge(verifier),
361            expected_challenge
362        );
363    }
364
365    #[test]
366    fn two_generated_challenges_differ() {
367        let a = PkceChallenge::generate();
368        let b = PkceChallenge::generate();
369        assert_ne!(a.verifier(), b.verifier());
370        assert_ne!(a.challenge(), b.challenge());
371    }
372
373    #[test]
374    fn token_with_no_expiry_never_needs_refresh() {
375        let tokens = TokenSet {
376            access_token: "at".into(),
377            refresh_token: None,
378            expires_at: None,
379        };
380        assert!(!tokens.needs_refresh(Duration::from_secs(30)));
381    }
382
383    #[test]
384    fn token_well_outside_skew_does_not_need_refresh() {
385        let tokens = TokenSet {
386            access_token: "at".into(),
387            refresh_token: None,
388            expires_at: Some(OffsetDateTime::now_utc() + time::Duration::hours(1)),
389        };
390        assert!(!tokens.needs_refresh(Duration::from_secs(30)));
391    }
392
393    #[test]
394    fn token_within_skew_of_expiry_needs_refresh() {
395        let tokens = TokenSet {
396            access_token: "at".into(),
397            refresh_token: None,
398            expires_at: Some(OffsetDateTime::now_utc() + time::Duration::seconds(5)),
399        };
400        assert!(tokens.needs_refresh(Duration::from_secs(30)));
401    }
402
403    #[test]
404    fn already_expired_token_needs_refresh() {
405        let tokens = TokenSet {
406            access_token: "at".into(),
407            refresh_token: None,
408            expires_at: Some(OffsetDateTime::now_utc() - time::Duration::hours(1)),
409        };
410        assert!(tokens.needs_refresh(Duration::from_secs(30)));
411    }
412}