scribe-client 0.3.1

Rust client for the Scribe document conversion API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use std::time::Duration;

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use rand::Rng;
use serde::Deserialize;
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
use url::Url;

use crate::error::ScribeError;

/// A generated PKCE (RFC 7636) verifier/challenge pair. Always uses the
/// `S256` challenge method; there's no reason for a client we control to
/// use `plain`, even though the server supports it.
#[derive(Debug, Clone)]
pub struct PkceChallenge {
    verifier: String,
    challenge: String,
}

impl PkceChallenge {
    /// Generates a new random verifier and its S256 challenge.
    #[must_use]
    pub fn generate() -> Self {
        // RFC 7636 section 4.1: verifier is 43-128 chars from [A-Z a-z 0-9 - . _ ~].
        // 32 random bytes, base64url-no-pad-encoded, is 43 chars and pulls
        // only from that alphabet.
        let mut bytes = [0u8; 32];
        rand::rng().fill_bytes(&mut bytes);
        let verifier = URL_SAFE_NO_PAD.encode(bytes);
        let challenge = Self::derive_challenge(&verifier);
        PkceChallenge {
            verifier,
            challenge,
        }
    }

    fn derive_challenge(verifier: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(verifier.as_bytes());
        URL_SAFE_NO_PAD.encode(hasher.finalize())
    }

    #[must_use]
    pub fn verifier(&self) -> &str {
        &self.verifier
    }

    #[must_use]
    pub fn challenge(&self) -> &str {
        &self.challenge
    }
}

/// An access/refresh token pair returned by `POST /oauth/token`.
#[derive(Debug, Clone, PartialEq)]
pub struct TokenSet {
    pub access_token: String,
    pub refresh_token: Option<String>,
    pub expires_at: Option<OffsetDateTime>,
}

impl TokenSet {
    /// True if this token is missing or will expire within `skew`.
    #[must_use]
    pub fn needs_refresh(&self, skew: Duration) -> bool {
        match self.expires_at {
            None => false,
            Some(expires_at) => {
                expires_at
                    <= OffsetDateTime::now_utc()
                        + time::Duration::seconds(skew.as_secs().cast_signed())
            }
        }
    }
}

#[derive(Debug, Deserialize)]
struct TokenResponse {
    access_token: String,
    refresh_token: Option<String>,
    expires_in: Option<i64>,
}

#[derive(Debug, Deserialize)]
struct TokenErrorResponse {
    error: String,
    #[allow(dead_code)]
    #[serde(default)]
    error_description: Option<String>,
    #[serde(default)]
    message: Option<String>,
}

impl From<TokenResponse> for TokenSet {
    fn from(r: TokenResponse) -> Self {
        TokenSet {
            access_token: r.access_token,
            refresh_token: r.refresh_token,
            expires_at: r
                .expires_in
                .map(|secs| OffsetDateTime::now_utc() + time::Duration::seconds(secs)),
        }
    }
}

/// Drives the OAuth 2.0 Authorization Code + PKCE flow against a Scribe
/// server. This type does not open a browser or run a redirect listener;
/// the embedding application is responsible for presenting
/// [`AuthClient::authorization_url`] to the user and obtaining the
/// resulting `code` however fits its own UI.
pub struct AuthClient {
    http: reqwest::Client,
    base_url: Url,
    client_id: String,
    locale: Option<String>,
}

impl AuthClient {
    pub fn new(http: reqwest::Client, base_url: Url, client_id: impl Into<String>) -> Self {
        AuthClient {
            http,
            base_url,
            client_id: client_id.into(),
            locale: None,
        }
    }

    /// Asks the server for its messages in `locale`, a language tag such as
    /// `de` or `pt-BR`, usually the language the app's own interface is in.
    /// The sign-in page from [`Self::authorization_url`] opens in it too.
    /// Without one, the server uses the account's language, or English.
    #[must_use]
    pub fn with_locale(mut self, locale: impl Into<String>) -> Self {
        self.locale = Some(locale.into());
        self
    }

    pub(crate) fn locale(&self) -> Option<&str> {
        self.locale.as_deref()
    }

    /// Builds the URL the user's browser should be sent to. `redirect_uri`
    /// must match one registered for `client_id` server-side.
    ///
    /// The authorize request is wrapped in the server's `/auth/logout`
    /// redirect, so whatever session the browser is holding for this server is
    /// dropped before the authorize request is reached. Signing out only
    /// clears this device's tokens: the browser's cookie store belongs to the
    /// system, and an app has no way to reach into it. Without this, a session
    /// cookie surviving sign-out lets the next sign-in complete without asking
    /// for anything.
    ///
    /// Clearing it at sign-in rather than at sign-out is what keeps the
    /// browser's SSO session with the identity provider intact, so a returning
    /// user is asked for their email address instead of the whole credential
    /// flow.
    #[must_use]
    pub fn authorization_url(&self, redirect_uri: &str, pkce: &PkceChallenge) -> Url {
        self.authorization_url_with_challenge(redirect_uri, pkce.challenge())
    }

    /// [`AuthClient::authorization_url`] for callers that hold the challenge on
    /// its own rather than the whole [`PkceChallenge`] — the FFI hands the
    /// verifier to the host application to keep between the two halves of the
    /// flow, so by this point only the challenge string is left.
    #[must_use]
    pub fn authorization_url_with_challenge(
        &self,
        redirect_uri: &str,
        pkce_challenge: &str,
    ) -> Url {
        let mut authorize = self.base_url.clone();
        authorize.set_path("/oauth/authorize");
        authorize
            .query_pairs_mut()
            .append_pair("response_type", "code")
            .append_pair("client_id", &self.client_id)
            .append_pair("redirect_uri", redirect_uri)
            .append_pair("code_challenge", pkce_challenge)
            .append_pair("code_challenge_method", "S256");

        // `next` is a path and query only, never an absolute URL: the server
        // refuses external targets so it cannot be used as an open redirect.
        let next = match authorize.query() {
            Some(query) => format!("{}?{}", authorize.path(), query),
            None => authorize.path().to_owned(),
        };

        let mut url = self.base_url.clone();
        url.set_path("/auth/logout");
        url.query_pairs_mut().append_pair("next", &next);
        // The website keeps `locale` in a cookie that logging out leaves
        // alone, so the sign-in page the redirects end on is in it too.
        if let Some(locale) = &self.locale {
            url.query_pairs_mut().append_pair("locale", locale);
        }
        url
    }

    /// Exchanges an authorization code (obtained after the user completes
    /// the browser flow at [`AuthClient::authorization_url`]) for a token
    /// set. `verifier` must be the same [`PkceChallenge`] used to build
    /// that URL.
    ///
    /// # Errors
    ///
    /// Returns [`ScribeError::InvalidGrant`] if the code or verifier is
    /// wrong or expired, or [`ScribeError::Http`]/[`ScribeError::Api`] on
    /// other request failures.
    pub async fn exchange_code(
        &self,
        redirect_uri: &str,
        code: &str,
        verifier: &str,
    ) -> Result<TokenSet, ScribeError> {
        let mut url = self.base_url.clone();
        url.set_path("/oauth/token");
        let body = [
            ("grant_type", "authorization_code"),
            ("client_id", &self.client_id),
            ("redirect_uri", redirect_uri),
            ("code", code),
            ("code_verifier", verifier),
        ];
        self.send_token_request(url, &body).await
    }

    /// Exchanges a refresh token for a new token set.
    ///
    /// # Errors
    ///
    /// Returns [`ScribeError::InvalidGrant`] if the refresh token is wrong,
    /// expired, or revoked, or [`ScribeError::Http`]/[`ScribeError::Api`] on
    /// other request failures.
    pub async fn refresh(&self, refresh_token: &str) -> Result<TokenSet, ScribeError> {
        let mut url = self.base_url.clone();
        url.set_path("/oauth/token");
        let body = [
            ("grant_type", "refresh_token"),
            ("client_id", &self.client_id),
            ("refresh_token", refresh_token),
        ];
        self.send_token_request(url, &body).await
    }

    /// Asks the server to invalidate a token, so signing out ends the session
    /// there and then rather than leaving a refresh token usable until it
    /// expires on its own.
    ///
    /// Pass the refresh token when there is one: revoking it takes the access
    /// tokens issued alongside it with it. Passing an access token instead
    /// revokes only that token.
    ///
    /// Per RFC 7009 the server answers successfully whether or not it
    /// recognised the token, so a success here means the request was accepted,
    /// not that something was necessarily revoked.
    ///
    /// # Errors
    ///
    /// Returns [`ScribeError::Http`] if the request could not be sent, or
    /// [`ScribeError::Api`] if the server refused it.
    pub async fn revoke(&self, token: &str) -> Result<(), ScribeError> {
        let mut url = self.base_url.clone();
        url.set_path("/oauth/revoke");
        let body = [("client_id", self.client_id.as_str()), ("token", token)];
        let response = accept_language(self.http.post(url), self.locale())
            .form(&body)
            .send()
            .await?;
        let status = response.status();
        if status.is_success() {
            return Ok(());
        }

        let text = response.text().await.unwrap_or_default();
        let fallback = || "We couldn't sign you out completely.".to_string();
        let (code, message) = match serde_json::from_str::<TokenErrorResponse>(&text) {
            Ok(err) => (err.error, err.message.unwrap_or_else(fallback)),
            Err(_) => ("server_error".to_string(), fallback()),
        };
        Err(ScribeError::Api {
            status: status.as_u16(),
            code,
            message,
        })
    }

    async fn send_token_request(
        &self,
        url: Url,
        body: &[(&str, &str)],
    ) -> Result<TokenSet, ScribeError> {
        let response = accept_language(self.http.post(url), self.locale())
            .form(body)
            .send()
            .await?;
        let status = response.status();
        if status.is_success() {
            let parsed: TokenResponse = response.json().await?;
            Ok(parsed.into())
        } else {
            let text = response.text().await.unwrap_or_default();
            match serde_json::from_str::<TokenErrorResponse>(&text) {
                Ok(err) if err.error == "invalid_grant" => Err(ScribeError::InvalidGrant {
                    message: err.message.unwrap_or_else(|| {
                        "Your session has expired. Please sign in again.".to_string()
                    }),
                }),
                Ok(err) => Err(ScribeError::Api {
                    status: status.as_u16(),
                    code: err.error,
                    message: err.message.unwrap_or_else(|| {
                        "We couldn't sign you in. Please try again.".to_string()
                    }),
                }),
                Err(_) => Err(ScribeError::Api {
                    status: status.as_u16(),
                    code: "server_error".to_string(),
                    message: "We couldn't sign you in. Please try again.".to_string(),
                }),
            }
        }
    }
}

/// Adds `Accept-Language` for `locale`, which is how the server picks the
/// language of what it says in a response.
pub(crate) fn accept_language(
    request: reqwest::RequestBuilder,
    locale: Option<&str>,
) -> reqwest::RequestBuilder {
    match locale {
        Some(locale) => request.header(reqwest::header::ACCEPT_LANGUAGE, locale),
        None => request,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn generated_verifier_matches_rfc7636_charset_and_length() {
        let pkce = PkceChallenge::generate();
        assert_eq!(pkce.verifier().len(), 43);
        assert!(pkce.verifier().chars().all(|c| c.is_ascii_alphanumeric()
            || c == '-'
            || c == '.'
            || c == '_'
            || c == '~'));
    }

    #[test]
    fn challenge_is_deterministic_s256_of_verifier() {
        // RFC 7636 appendix B test vector.
        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let expected_challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
        assert_eq!(
            PkceChallenge::derive_challenge(verifier),
            expected_challenge
        );
    }

    #[test]
    fn two_generated_challenges_differ() {
        let a = PkceChallenge::generate();
        let b = PkceChallenge::generate();
        assert_ne!(a.verifier(), b.verifier());
        assert_ne!(a.challenge(), b.challenge());
    }

    #[test]
    fn token_with_no_expiry_never_needs_refresh() {
        let tokens = TokenSet {
            access_token: "at".into(),
            refresh_token: None,
            expires_at: None,
        };
        assert!(!tokens.needs_refresh(Duration::from_secs(30)));
    }

    #[test]
    fn token_well_outside_skew_does_not_need_refresh() {
        let tokens = TokenSet {
            access_token: "at".into(),
            refresh_token: None,
            expires_at: Some(OffsetDateTime::now_utc() + time::Duration::hours(1)),
        };
        assert!(!tokens.needs_refresh(Duration::from_secs(30)));
    }

    #[test]
    fn token_within_skew_of_expiry_needs_refresh() {
        let tokens = TokenSet {
            access_token: "at".into(),
            refresh_token: None,
            expires_at: Some(OffsetDateTime::now_utc() + time::Duration::seconds(5)),
        };
        assert!(tokens.needs_refresh(Duration::from_secs(30)));
    }

    #[test]
    fn already_expired_token_needs_refresh() {
        let tokens = TokenSet {
            access_token: "at".into(),
            refresh_token: None,
            expires_at: Some(OffsetDateTime::now_utc() - time::Duration::hours(1)),
        };
        assert!(tokens.needs_refresh(Duration::from_secs(30)));
    }
}