box-open-sdk 0.2.0

Community, unofficial Box API client for Rust — typed models, async managers, and a reqwest runtime with retry, backoff, and token refresh.
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
// Code generated by box-gantry (vendored from runtimes/rust/gantryruntime/src/auth.rs). DO NOT EDIT.

//! The Box auth flows, each producing an [`Auth`] passed to
//! [`Client::new`](super::Client::new). `developer_token` is a fixed token;
//! `client_credentials` (CCG) and `oauth` exchange credentials at Box's token
//! endpoint and cache the resulting access token until shortly before it
//! expires (TR-Rust.5).
//!
//! JWT server auth (signing-key assertions) lands in the next runtime slice;
//! the three flows here cover fixed-token and both refresh-based exchanges.

use std::sync::Arc;
use std::time::{Duration, Instant};

use tokio::sync::Mutex;

use super::jwt::{JwtConfig, Signer};
use super::Error;

/// Box's OAuth 2.0 token endpoint, shared by every exchange flow.
const DEFAULT_TOKEN_URL: &str = "https://api.box.com/oauth2/token";

/// Where a user is sent to grant an OAuth 2.0 app access.
const AUTHORIZE_URL: &str = "https://account.box.com/api/oauth2/authorize";

/// Refresh a cached token this long before expiry so in-flight requests never
/// race an expiry.
const REFRESH_MARGIN: Duration = Duration::from_secs(60);

/// The configured authentication flow. Build one with [`Auth::developer_token`],
/// [`Auth::client_credentials`], or [`Auth::oauth`], then pass it to
/// [`Client::new`](super::Client::new).
pub struct Auth {
    source: Source,
}

/// One of the supported token sources.
enum Source {
    /// A fixed developer-console token.
    Developer(String),
    /// A cached token refreshed by re-posting a fixed grant form (CCG).
    Form(FormSource),
    /// A cached token refreshed with a rotating refresh token (OAuth 2.0).
    OAuth(OAuthSource),
    /// A cached token refreshed by signing a fresh JWT bearer assertion. Boxed:
    /// the parsed RSA key makes this variant far larger than the others.
    Jwt(Box<JwtSource>),
}

impl Auth {
    /// The simplest flow: a fixed access token from the Box developer console.
    pub fn developer_token(token: impl Into<String>) -> Auth {
        Auth {
            source: Source::Developer(token.into()),
        }
    }

    /// Client Credentials Grant: server-to-server auth with no signing key. Set
    /// exactly one subject on the config — `enterprise_id` for the service
    /// account, or `user_id` to act as a managed user.
    pub fn client_credentials(config: CcgConfig) -> Auth {
        let (subject_type, subject_id) = match &config.user_id {
            Some(user) => ("user", user.clone()),
            None => ("enterprise", config.enterprise_id.clone()),
        };
        let form = vec![
            ("grant_type".to_string(), "client_credentials".to_string()),
            ("client_id".to_string(), config.client_id),
            ("client_secret".to_string(), config.client_secret),
            ("box_subject_type".to_string(), subject_type.to_string()),
            ("box_subject_id".to_string(), subject_id),
        ];
        Auth {
            source: Source::Form(FormSource {
                http: auth_http_client(),
                token_url: config.token_url.unwrap_or_else(default_token_url),
                form,
                cached: Mutex::new(Cached::empty()),
            }),
        }
    }

    /// JWT server auth: sign a short-lived RSA assertion (from the app's
    /// `box_config.json`) and exchange it for an access token. Set exactly one
    /// subject on the config — `enterprise_id` or `user_id`.
    ///
    /// Fallible: the RSA private key is parsed (and if needed decrypted) up
    /// front, so a bad key fails here rather than on the first request.
    pub fn jwt(config: JwtConfig) -> Result<Auth, Error> {
        let signer = Signer::new(&config)?;
        Ok(Auth {
            source: Source::Jwt(Box::new(JwtSource {
                http: auth_http_client(),
                token_url: config.token_url.unwrap_or_else(default_token_url),
                client_id: config.client_id,
                client_secret: config.client_secret,
                signer,
                cached: Mutex::new(Cached::empty()),
            })),
        })
    }

    /// Resume the OAuth 2.0 authorization-code flow from a previously stored
    /// refresh token, exchanging it for access tokens as needed. Box rotates
    /// the refresh token on each exchange, so the newest one is retained.
    ///
    /// The rotated token is held in memory only; use [`Auth::oauth_with_store`]
    /// to persist each rotation durably across restarts.
    pub fn oauth(config: OAuthConfig, refresh_token: impl Into<String>) -> Auth {
        Self::oauth_source(config, refresh_token.into(), None)
    }

    /// Like [`Auth::oauth`], but persists each rotated refresh token through a
    /// [`RefreshTokenStore`] before returning — so an app restart reloads the
    /// live token instead of a refresh token Box has already invalidated.
    pub fn oauth_with_store(
        config: OAuthConfig,
        refresh_token: impl Into<String>,
        store: Arc<dyn RefreshTokenStore>,
    ) -> Auth {
        Self::oauth_source(config, refresh_token.into(), Some(store))
    }

    fn oauth_source(
        config: OAuthConfig,
        refresh_token: String,
        store: Option<Arc<dyn RefreshTokenStore>>,
    ) -> Auth {
        Auth {
            source: Source::OAuth(OAuthSource {
                http: auth_http_client(),
                token_url: config.token_url.clone().unwrap_or_else(default_token_url),
                client_id: config.client_id,
                client_secret: config.client_secret,
                store,
                state: Mutex::new(OAuthState {
                    token: String::new(),
                    expiry: Instant::now(),
                    refresh_token,
                    // The caller-supplied token is already durable.
                    refresh_token_persisted: true,
                }),
            }),
        }
    }

    /// A valid access token for the configured flow.
    pub(crate) async fn access_token(&self) -> Result<String, Error> {
        match &self.source {
            Source::Developer(token) => Ok(token.clone()),
            Source::Form(source) => source.access_token().await,
            Source::OAuth(source) => source.access_token().await,
            Source::Jwt(source) => source.access_token().await,
        }
    }

    /// Force-acquire a token after the current one was rejected (a 401),
    /// bypassing the freshness cache. Single-flight: if another task already
    /// replaced the rejected `stale` token, that new token is returned instead
    /// of refreshing again. A fixed developer token has nothing to refresh, so
    /// it is returned unchanged (the retry then surfaces the 401).
    pub(crate) async fn force_refresh(&self, stale: &str) -> Result<String, Error> {
        match &self.source {
            Source::Developer(token) => Ok(token.clone()),
            Source::Form(source) => source.force_refresh(stale).await,
            Source::OAuth(source) => source.force_refresh(stale).await,
            Source::Jwt(source) => source.force_refresh(stale).await,
        }
    }
}

/// A durable store for the rotating OAuth refresh token. Box invalidates the
/// previous refresh token on each exchange, so an app that restarts must reload
/// the newest one — implement this to persist each rotation (a file, a DB row,
/// a secret manager).
///
/// `save` is `async` so a store can do real I/O without blocking the executor
/// (do the I/O with async APIs, or offload sync work via
/// `tokio::task::spawn_blocking`). It runs before a freshly rotated token is
/// returned; its failure propagates on the rotating call, and the runtime keeps
/// retrying persistence on later calls until it succeeds, so a rotation is never
/// silently treated as durable when it is not.
#[async_trait::async_trait]
pub trait RefreshTokenStore: Send + Sync {
    /// Persist the newly rotated refresh token durably.
    async fn save(&self, refresh_token: &str) -> Result<(), Error>;
}

/// The cached token if it is present and not within the refresh margin of
/// expiry (shared by both caching sources).
fn fresh_token(token: &str, expiry: Instant) -> Option<String> {
    if !token.is_empty() && expiry.saturating_duration_since(Instant::now()) > REFRESH_MARGIN {
        Some(token.to_string())
    } else {
        None
    }
}

/// A cached access token and its expiry instant.
struct Cached {
    token: String,
    expiry: Instant,
}

impl Cached {
    fn empty() -> Cached {
        Cached {
            token: String::new(),
            expiry: Instant::now(),
        }
    }

    fn fresh(&self) -> Option<String> {
        fresh_token(&self.token, self.expiry)
    }

    fn store(&mut self, token: String, ttl: Duration) {
        self.expiry = Instant::now() + ttl;
        self.token = token;
    }
}

/// A token source that refreshes by re-posting a fixed grant form (CCG).
struct FormSource {
    http: reqwest::Client,
    token_url: String,
    form: Vec<(String, String)>,
    cached: Mutex<Cached>,
}

impl FormSource {
    async fn access_token(&self) -> Result<String, Error> {
        let mut cached = self.cached.lock().await;
        if let Some(token) = cached.fresh() {
            return Ok(token);
        }
        self.refresh_locked(&mut cached).await
    }

    async fn force_refresh(&self, stale: &str) -> Result<String, Error> {
        let mut cached = self.cached.lock().await;
        // Single-flight: a concurrent 401 may already have replaced the token.
        if let Some(token) = cached.fresh() {
            if token != stale {
                return Ok(token);
            }
        }
        self.refresh_locked(&mut cached).await
    }

    async fn refresh_locked(&self, cached: &mut Cached) -> Result<String, Error> {
        let response = post_token_form(&self.http, &self.token_url, &self.form).await?;
        cached.store(response.access_token.clone(), response.ttl());
        Ok(response.access_token)
    }
}

/// A token source that refreshes by signing a fresh JWT bearer assertion and
/// exchanging it (server auth with a signing key). Like [`FormSource`], but the
/// grant form is re-minted each refresh — each assertion is single-use.
struct JwtSource {
    http: reqwest::Client,
    token_url: String,
    client_id: String,
    client_secret: String,
    signer: Signer,
    cached: Mutex<Cached>,
}

impl JwtSource {
    async fn access_token(&self) -> Result<String, Error> {
        let mut cached = self.cached.lock().await;
        if let Some(token) = cached.fresh() {
            return Ok(token);
        }
        self.refresh_locked(&mut cached).await
    }

    async fn force_refresh(&self, stale: &str) -> Result<String, Error> {
        let mut cached = self.cached.lock().await;
        // Single-flight: a concurrent 401 may already have replaced the token.
        if let Some(token) = cached.fresh() {
            if token != stale {
                return Ok(token);
            }
        }
        self.refresh_locked(&mut cached).await
    }

    async fn refresh_locked(&self, cached: &mut Cached) -> Result<String, Error> {
        let assertion = self.signer.assertion(&self.token_url)?;
        let form = vec![
            (
                "grant_type".to_string(),
                "urn:ietf:params:oauth:grant-type:jwt-bearer".to_string(),
            ),
            ("assertion".to_string(), assertion),
            ("client_id".to_string(), self.client_id.clone()),
            ("client_secret".to_string(), self.client_secret.clone()),
        ];
        let response = post_token_form(&self.http, &self.token_url, &form).await?;
        cached.store(response.access_token.clone(), response.ttl());
        Ok(response.access_token)
    }
}

/// The OAuth 2.0 refresh-token source: it rotates the refresh token Box returns
/// (Box invalidates the old one each exchange) and, when configured, persists
/// each rotation through a [`RefreshTokenStore`].
struct OAuthSource {
    http: reqwest::Client,
    token_url: String,
    client_id: String,
    client_secret: String,
    store: Option<Arc<dyn RefreshTokenStore>>,
    state: Mutex<OAuthState>,
}

struct OAuthState {
    token: String,
    expiry: Instant,
    refresh_token: String,
    /// Whether `refresh_token` is known durable in the store. The initial token
    /// came from the caller (already stored); only later rotations start `false`
    /// until their `save` succeeds.
    refresh_token_persisted: bool,
}

impl OAuthSource {
    async fn access_token(&self) -> Result<String, Error> {
        let mut state = self.state.lock().await;
        self.retry_persist(&mut state).await;
        if let Some(token) = fresh_token(&state.token, state.expiry) {
            return Ok(token);
        }
        self.refresh_locked(&mut state).await
    }

    async fn force_refresh(&self, stale: &str) -> Result<String, Error> {
        let mut state = self.state.lock().await;
        self.retry_persist(&mut state).await;
        // Single-flight: a concurrent 401 may already have replaced the token.
        if let Some(token) = fresh_token(&state.token, state.expiry) {
            if token != stale {
                return Ok(token);
            }
        }
        self.refresh_locked(&mut state).await
    }

    /// Best-effort retry of a rotation whose earlier `save` failed, so a
    /// transient store outage doesn't leave the durable copy behind the live
    /// token forever. The first failure was already surfaced by `refresh_locked`;
    /// these retries stay silent so a still-down store can't wedge every call.
    async fn retry_persist(&self, state: &mut OAuthState) {
        if state.refresh_token_persisted {
            return;
        }
        match &self.store {
            Some(store) => {
                if store.save(&state.refresh_token).await.is_ok() {
                    state.refresh_token_persisted = true;
                }
            }
            None => state.refresh_token_persisted = true,
        }
    }

    async fn refresh_locked(&self, state: &mut OAuthState) -> Result<String, Error> {
        let form = vec![
            ("grant_type".to_string(), "refresh_token".to_string()),
            ("refresh_token".to_string(), state.refresh_token.clone()),
            ("client_id".to_string(), self.client_id.clone()),
            ("client_secret".to_string(), self.client_secret.clone()),
        ];
        let response = post_token_form(&self.http, &self.token_url, &form).await?;
        state.token = response.access_token.clone();
        state.expiry = Instant::now() + response.ttl();
        if let Some(refresh) = &response.refresh_token {
            state.refresh_token = refresh.clone();
            // The rotation isn't durable until the store confirms it. Box has
            // already invalidated the previous token, so on a save failure we
            // keep the new token in memory (marked unpersisted, retried on later
            // calls) but surface the error now.
            state.refresh_token_persisted = self.store.is_none();
            if let Some(store) = &self.store {
                store.save(refresh).await?;
                state.refresh_token_persisted = true;
            }
        }
        Ok(response.access_token)
    }
}

/// The Client Credentials Grant config: server-to-server auth with no signing
/// key. Set exactly one subject — `enterprise_id` for the service account, or
/// `user_id` to act as a managed user. Derives `Default` so the optional
/// `user_id`/`token_url` can be elided with `..Default::default()`.
#[derive(Clone, Default)]
pub struct CcgConfig {
    pub client_id: String,
    pub client_secret: String,
    pub enterprise_id: String,
    /// Optional: act as a managed user instead of the enterprise service account.
    pub user_id: Option<String>,
    /// Optional: defaults to Box's token endpoint (custom deployments).
    pub token_url: Option<String>,
}

/// The OAuth 2.0 authorization-code config. Use [`OAuthConfig::authorize_url`]
/// to build the redirect, [`OAuthConfig::exchange_code`] to turn the returned
/// code into an [`Auth`], or [`Auth::oauth`] to resume from a stored refresh
/// token.
#[derive(Clone)]
pub struct OAuthConfig {
    pub client_id: String,
    pub client_secret: String,
    /// Optional: defaults to Box's token endpoint (custom deployments).
    pub token_url: Option<String>,
}

impl OAuthConfig {
    /// Build the URL to redirect a user to so they can grant access. `state` is
    /// echoed back to the redirect URI for CSRF protection.
    pub fn authorize_url(&self, redirect_uri: &str, state: &str) -> String {
        let query = form_urlencode(&[
            ("response_type", "code"),
            ("client_id", &self.client_id),
            ("redirect_uri", redirect_uri),
            ("state", state),
        ]);
        format!("{AUTHORIZE_URL}?{query}")
    }

    /// Exchange an authorization code for an [`Auth`] that refreshes itself
    /// thereafter.
    pub async fn exchange_code(&self, code: &str, redirect_uri: &str) -> Result<Auth, Error> {
        let http = auth_http_client();
        let token_url = self.token_url.clone().unwrap_or_else(default_token_url);
        let form = vec![
            ("grant_type".to_string(), "authorization_code".to_string()),
            ("code".to_string(), code.to_string()),
            ("client_id".to_string(), self.client_id.clone()),
            ("client_secret".to_string(), self.client_secret.clone()),
            ("redirect_uri".to_string(), redirect_uri.to_string()),
        ];
        let response = post_token_form(&http, &token_url, &form).await?;
        let refresh_token = response.refresh_token.clone().ok_or_else(|| {
            Error::new("gantryruntime: authorization-code exchange returned no refresh_token")
        })?;
        let ttl = response.ttl();
        let source = OAuthSource {
            http,
            token_url,
            client_id: self.client_id.clone(),
            client_secret: self.client_secret.clone(),
            store: None,
            state: Mutex::new(OAuthState {
                token: response.access_token,
                expiry: Instant::now() + ttl,
                refresh_token,
                refresh_token_persisted: true,
            }),
        };
        Ok(Auth {
            source: Source::OAuth(source),
        })
    }
}

/// The subset of the token endpoint's JSON response we consume.
struct TokenResponse {
    access_token: String,
    refresh_token: Option<String>,
    expires_in: u64,
}

impl TokenResponse {
    fn ttl(&self) -> Duration {
        Duration::from_secs(self.expires_in)
    }
}

/// POST a form-encoded grant to the token endpoint and decode the response,
/// surfacing a non-2xx body as the error.
async fn post_token_form(
    http: &reqwest::Client,
    token_url: &str,
    form: &[(String, String)],
) -> Result<TokenResponse, Error> {
    let pairs: Vec<(&str, &str)> = form.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
    let body = form_urlencode(&pairs);
    let response = http
        .post(token_url)
        .header("Content-Type", "application/x-www-form-urlencoded")
        .header("Accept", "application/json")
        .body(body)
        .send()
        .await?;
    let status = response.status();
    let bytes = response.bytes().await?;
    if !status.is_success() {
        let detail = String::from_utf8_lossy(&bytes);
        return Err(Error::new(format!(
            "gantryruntime: token endpoint returned {}: {}",
            status.as_u16(),
            detail.trim()
        )));
    }
    let json: serde_json::Value = serde_json::from_slice(&bytes)?;
    let access_token = json
        .get("access_token")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| Error::new("gantryruntime: token endpoint returned no access_token"))?;
    Ok(TokenResponse {
        access_token,
        refresh_token: json
            .get("refresh_token")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string()),
        expires_in: json.get("expires_in").and_then(|v| v.as_u64()).unwrap_or(0),
    })
}

/// The dedicated auth HTTP client (a shorter timeout than the API client).
fn auth_http_client() -> reqwest::Client {
    reqwest::Client::builder()
        .timeout(Duration::from_secs(30))
        .build()
        .unwrap_or_default()
}

fn default_token_url() -> String {
    DEFAULT_TOKEN_URL.to_string()
}

/// Encode key/value pairs as `application/x-www-form-urlencoded`.
fn form_urlencode(pairs: &[(&str, &str)]) -> String {
    let mut out = String::new();
    for (name, value) in pairs {
        if !out.is_empty() {
            out.push('&');
        }
        percent_encode_into(&mut out, name);
        out.push('=');
        percent_encode_into(&mut out, value);
    }
    out
}

/// Percent-encode into `out` per the `application/x-www-form-urlencoded`
/// unreserved set (spaces become `+`).
fn percent_encode_into(out: &mut String, value: &str) {
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char)
            }
            b' ' => out.push('+'),
            _ => out.push_str(&format!("%{byte:02X}")),
        }
    }
}