box-open-sdk 0.3.1

Box API client for Rust (open source, community, punk rock) — 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
// Code generated by box-gantry (vendored from runtimes/rust/gantryruntime/src/lib.rs). DO NOT EDIT.

//! The hand-written runtime the generated Box Rust SDK ships against
//! (TR-Rust.5). It implements the machine-readable runtime contract
//! (`gantry-contract` V1): generated code calls only these declarations, and
//! this crate supplies the behavior — a retrying async network layer (jittered
//! backoff, 401 refresh, Retry-After), auth-token threading, request builders,
//! and response accessors.
//!
//! It is the real implementation the compilable stubs stand in for during
//! generation-time verification (FR-5.3). Because it satisfies the same
//! signatures — `async fn` network entry points returning `Result<T, Error>`,
//! per the Rust manifest axes — the generated SDK compiles against it unchanged
//! (FR-5.2), which `crates/gantry-backend-rust/tests` enforces.
//!
//! Async threads cancellation through the future itself (no context parameter);
//! dropping a `fetch` future cancels the in-flight request.

mod auth;
mod jwt;

pub use auth::{Auth, CcgConfig, OAuthConfig, RefreshTokenStore};
pub use jwt::JwtConfig;

use std::collections::HashMap;
use std::time::Duration;

/// The safety ceiling on any single retry sleep, so a pathological server-sent
/// `Retry-After` (hours, years) can never suspend `fetch` far past the caller's
/// intent.
const MAX_RETRY_DELAY: Duration = Duration::from_secs(300);

/// A runtime error: a failed request, auth acquisition, or body decode. Opaque
/// by design — the message carries the detail, the type stays stable.
#[derive(Debug)]
pub struct Error(String);

impl Error {
    pub(crate) fn new(message: impl Into<String>) -> Error {
        Error(message.into())
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::error::Error for Error {}

impl From<serde_json::Error> for Error {
    fn from(err: serde_json::Error) -> Self {
        Error(err.to_string())
    }
}

impl From<reqwest::Error> for Error {
    fn from(err: reqwest::Error) -> Self {
        Error(err.to_string())
    }
}

/// A body stream. Buffered by construction (the Rust manifest's streaming axis
/// is satisfied by full buffering here): keeping the bytes in hand makes both
/// request retries and response replay safe.
pub struct Stream(Vec<u8>);

impl Stream {
    /// An empty stream (e.g. an absent multipart file part).
    pub fn empty() -> Stream {
        Stream(Vec::new())
    }

    /// A stream over already-buffered bytes.
    pub fn from_bytes(bytes: Vec<u8>) -> Stream {
        Stream(bytes)
    }

    /// The buffered bytes.
    pub fn into_bytes(self) -> Vec<u8> {
        self.0
    }
}

/// The body assembled by the `with_*` builders before `fetch` executes it.
enum Body {
    /// A byte body with a fixed content type (JSON, form, buffered stream).
    Bytes { content_type: String, data: Vec<u8> },
    /// A Box-style multipart body: an `attributes` JSON part plus a file part.
    Multipart {
        attributes: Vec<u8>,
        file_name: String,
        file: Vec<u8>,
    },
}

/// The runtime-owned HTTP request envelope, assembled by the `with_*` builders
/// before `fetch` executes it.
pub struct Request {
    method: String,
    url: String,
    headers: Vec<(String, String)>,
    query: Vec<(String, String)>,
    body: Option<Body>,
}

/// The runtime-owned HTTP response envelope. The body is read fully so it can
/// be replayed as bytes or a stream and so retries stay safe.
pub struct Response {
    status: i64,
    headers: Vec<(String, String)>,
    body: Vec<u8>,
}

/// The runtime session: it holds the auth flow, HTTP client, base-URL
/// configuration, and retry policy shared by every manager.
pub struct Client {
    auth: Auth,
    http: reqwest::Client,
    base_urls: HashMap<String, String>,
    max_retries: u32,
}

impl Client {
    /// Build a runtime session for an authentication flow, with the default
    /// Box base URLs, a 60s HTTP timeout, and five retries.
    pub fn new(auth: Auth) -> Client {
        let http = reqwest::Client::builder()
            .timeout(Duration::from_secs(60))
            .build()
            .unwrap_or_default();
        Client {
            auth,
            http,
            max_retries: 5,
            base_urls: default_base_urls(),
        }
    }

    /// Override how many times a retriable failure is retried (fluent).
    pub fn with_max_retries(mut self, n: u32) -> Client {
        self.max_retries = n;
        self
    }

    /// Override one base-URL class for custom deployments (fluent).
    pub fn with_base_url(mut self, name: &str, base: &str) -> Client {
        self.base_urls
            .insert(name.to_string(), base.trim_end_matches('/').to_string());
        self
    }

    /// The configured base URL for a D-106 class, without a trailing slash.
    pub fn base_url(&self, name: &str) -> String {
        self.base_urls.get(name).cloned().unwrap_or_default()
    }

    /// A valid access token for the configured auth flow.
    pub async fn access_token(&self) -> Result<String, Error> {
        self.auth.access_token().await
    }

    /// Create a request envelope for a method and fully built URL.
    pub fn new_request(&self, method: &str, url: &str) -> Request {
        Request {
            method: method.to_string(),
            url: url.to_string(),
            headers: Vec::new(),
            query: Vec::new(),
            body: None,
        }
    }

    /// Execute the request with retries: exponential backoff + full jitter, a
    /// single 401 token refresh, and Retry-After (as a floor) on 429/5xx.
    ///
    /// Retries are gated on idempotency: a 429 means the request was rate-limited
    /// and never processed, so it retries for every method; a transport error or
    /// 5xx may have already committed a write, so those retry only for idempotent
    /// methods (GET/HEAD/PUT/DELETE/…). The 401 refresh applies to every method.
    pub async fn fetch(&self, request: Request) -> Result<Response, Error> {
        let method = reqwest::Method::from_bytes(request.method.as_bytes()).map_err(|_| {
            Error::new(format!(
                "gantryruntime: invalid method {:?}",
                request.method
            ))
        })?;
        let idempotent = method.is_idempotent();
        let mut token = self.access_token().await?;
        let mut refreshed = false;

        for attempt in 0..=self.max_retries {
            let mut builder = self
                .http
                .request(method.clone(), &request.url)
                .query(&request.query)
                .header("Authorization", format!("Bearer {token}"));
            for (name, value) in &request.headers {
                builder = builder.header(name, value);
            }
            builder = apply_body(builder, request.body.as_ref());

            let response = match builder.send().await {
                Ok(response) => response,
                Err(err) => {
                    // A transport error gives no response, so a non-idempotent
                    // request may or may not have committed — don't replay it.
                    if attempt == self.max_retries || !idempotent {
                        return Err(err.into());
                    }
                    sleep(backoff(attempt)).await;
                    continue;
                }
            };
            let response = read_response(response).await?;

            // A single force-refresh on 401: re-acquire past the token cache so
            // the retry doesn't just resend the same rejected token.
            if response.status == 401 && !refreshed {
                refreshed = true;
                token = self.auth.force_refresh(&token).await?;
                continue;
            }
            // Back off exponentially on rate-limit / server errors.
            if should_retry(response.status, idempotent) && attempt < self.max_retries {
                sleep(retry_delay(&response, attempt)).await;
                continue;
            }
            return Ok(response);
        }
        Err(Error::new("gantryruntime: retries exhausted"))
    }
}

/// The default Box base URLs by D-106 class (custom deployments override any
/// via `with_base_url`).
fn default_base_urls() -> HashMap<String, String> {
    [
        ("api", "https://api.box.com/2.0"),
        ("api_root", "https://api.box.com"),
        ("upload", "https://upload.box.com/api/2.0"),
        ("upload_session", "https://upload.box.com/api/2.0"),
        ("oauth_authorize", "https://account.box.com/api/oauth2"),
        ("download", "https://api.box.com/2.0"),
    ]
    .iter()
    .map(|(k, v)| (k.to_string(), v.to_string()))
    .collect()
}

/// Attach the assembled body (and its content type) to the request builder.
fn apply_body(builder: reqwest::RequestBuilder, body: Option<&Body>) -> reqwest::RequestBuilder {
    match body {
        None => builder,
        Some(Body::Bytes { content_type, data }) => builder
            .header("Content-Type", content_type)
            .body(data.clone()),
        Some(Body::Multipart {
            attributes,
            file_name,
            file,
        }) => {
            // A boundary that provably does not occur in either part, so the
            // payload's own bytes can never split the framing.
            let boundary = multipart_boundary(attributes, file);
            let payload = multipart_body(&boundary, attributes, file_name, file);
            builder
                .header(
                    "Content-Type",
                    format!("multipart/form-data; boundary={boundary}"),
                )
                .body(payload)
        }
    }
}

/// Build a Box-style multipart/form-data body: an `attributes` JSON field plus
/// a `file` part (G-7). `file_name` is escaped for the quoted header value.
fn multipart_body(boundary: &str, attributes: &[u8], file_name: &str, file: &[u8]) -> Vec<u8> {
    let mut out = Vec::new();
    out.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
    out.extend_from_slice(b"Content-Disposition: form-data; name=\"attributes\"\r\n");
    out.extend_from_slice(b"Content-Type: application/json\r\n\r\n");
    out.extend_from_slice(attributes);
    out.extend_from_slice(b"\r\n");
    out.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
    out.extend_from_slice(
        format!(
            "Content-Disposition: form-data; name=\"file\"; filename=\"{}\"\r\n",
            escape_filename(file_name)
        )
        .as_bytes(),
    );
    out.extend_from_slice(b"Content-Type: application/octet-stream\r\n\r\n");
    out.extend_from_slice(file);
    out.extend_from_slice(b"\r\n");
    out.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
    out
}

/// A multipart boundary guaranteed not to appear in either part — so no file
/// content can forge a delimiter and split the framing. Derived from a
/// nanosecond-seeded counter, re-rolled until it is collision-free (`mime/
/// multipart` gets this from a random boundary; we verify explicitly).
fn multipart_boundary(attributes: &[u8], file: &[u8]) -> String {
    let mut seed = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0x9e37_79b9_7f4a_7c15);
    loop {
        let candidate = format!("gantryruntimeXboundaryX{seed:016x}");
        let needle = candidate.as_bytes();
        if !contains_subslice(attributes, needle) && !contains_subslice(file, needle) {
            return candidate;
        }
        seed = seed
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
    }
}

/// Whether `haystack` contains `needle` as a contiguous subslice.
fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool {
    !needle.is_empty()
        && haystack.len() >= needle.len()
        && haystack
            .windows(needle.len())
            .any(|window| window == needle)
}

/// Escape a filename for a quoted `Content-Disposition` value (RFC 6266): strip
/// CR/LF so it can never inject header lines or a boundary, and backslash-escape
/// `\` and `"` so a quote can't close the value early.
fn escape_filename(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    for ch in name.chars() {
        match ch {
            '\r' | '\n' => {}
            '\\' | '"' => {
                out.push('\\');
                out.push(ch);
            }
            _ => out.push(ch),
        }
    }
    out
}

/// Read a response fully into the owned envelope.
async fn read_response(response: reqwest::Response) -> Result<Response, Error> {
    let status = response.status().as_u16() as i64;
    let headers = response
        .headers()
        .iter()
        .map(|(name, value)| {
            (
                name.as_str().to_string(),
                value.to_str().unwrap_or_default().to_string(),
            )
        })
        .collect();
    let body = response.bytes().await?.to_vec();
    Ok(Response {
        status,
        headers,
        body,
    })
}

/// Whether a response status warrants a retry for a request of this idempotency.
/// A 429 (rate-limited, never processed) retries for any method; a 5xx may have
/// committed a write, so it retries only for idempotent methods.
fn should_retry(status: i64, idempotent: bool) -> bool {
    status == 429 || (status >= 500 && idempotent)
}

/// Exponential backoff capped at 30s, with full jitter.
fn backoff(attempt: u32) -> Duration {
    let base = (500u64.saturating_mul(1u64 << attempt.min(20))).min(30_000);
    Duration::from_millis(jitter(base))
}

/// The delay before the next retry: exponential backoff (so repeated 429s/5xx
/// escalate), raised to a server-sent `Retry-After` as a floor when present, and
/// clamped to [`MAX_RETRY_DELAY`] so a hostile header can't stall the client.
fn retry_delay(response: &Response, attempt: u32) -> Duration {
    let mut delay = backoff(attempt);
    if let Some(value) = header_value(&response.headers, "retry-after") {
        if let Ok(secs) = value.trim().parse::<u64>() {
            delay = delay.max(Duration::from_secs(secs));
        }
    }
    delay.min(MAX_RETRY_DELAY)
}

/// A cheap, dependency-free full-jitter source: a uniform value in `[0, max]`
/// from a nanosecond-seeded xorshift (jitter only needs to decorrelate retries,
/// not be cryptographic).
fn jitter(max: u64) -> u64 {
    if max == 0 {
        return 0;
    }
    let mut x = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0x9e37_79b9_7f4a_7c15)
        | 1;
    x ^= x << 13;
    x ^= x >> 7;
    x ^= x << 17;
    x % (max + 1)
}

async fn sleep(duration: Duration) {
    tokio::time::sleep(duration).await;
}

/// Case-insensitive header lookup (HTTP header names are case-insensitive).
fn header_value<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
    headers
        .iter()
        .find(|(key, _)| key.eq_ignore_ascii_case(name))
        .map(|(_, value)| value.as_str())
}

/// Return the request with the header set (replacing any prior value).
pub fn with_header(mut request: Request, name: &str, value: &str) -> Request {
    request
        .headers
        .retain(|(key, _)| !key.eq_ignore_ascii_case(name));
    request.headers.push((name.to_string(), value.to_string()));
    request
}

/// Return the request with the query parameter appended, encoded at send time.
pub fn with_query(mut request: Request, name: &str, value: &str) -> Request {
    request.query.push((name.to_string(), value.to_string()));
    request
}

/// Return the request with the serialized JSON body and content type set.
pub fn with_json_body(mut request: Request, body: &[u8]) -> Request {
    request.body = Some(Body::Bytes {
        content_type: "application/json".to_string(),
        data: body.to_vec(),
    });
    request
}

/// Return the request with an application/x-www-form-urlencoded body (the
/// OAuth2 token endpoints).
pub fn with_form_body(mut request: Request, form: &[u8]) -> Request {
    request.body = Some(Body::Bytes {
        content_type: "application/x-www-form-urlencoded".to_string(),
        data: form.to_vec(),
    });
    request
}

/// Return the request with a streaming body (buffered here).
pub fn with_stream_body(mut request: Request, body: Stream, content_type: &str) -> Request {
    request.body = Some(Body::Bytes {
        content_type: content_type.to_string(),
        data: body.into_bytes(),
    });
    request
}

/// Return the request with a Box-style multipart body: an `attributes` JSON
/// part plus a file part (G-7).
pub fn with_multipart_body(
    mut request: Request,
    attributes: &[u8],
    file_name: &str,
    file: Stream,
) -> Request {
    request.body = Some(Body::Multipart {
        attributes: attributes.to_vec(),
        file_name: file_name.to_string(),
        file: file.into_bytes(),
    });
    request
}

/// Read the whole response body.
pub fn response_bytes(response: &Response) -> Result<Vec<u8>, Error> {
    Ok(response.body.clone())
}

/// The response body as a stream, for binary downloads (FR-7.4).
pub fn response_stream(response: &Response) -> Stream {
    Stream::from_bytes(response.body.clone())
}

/// A response header value, empty when absent (redirect Location, Retry-After
/// surfacing).
pub fn response_header(response: &Response, name: &str) -> String {
    header_value(&response.headers, name)
        .unwrap_or_default()
        .to_string()
}

/// The response status code.
pub fn status_code(response: &Response) -> i64 {
    response.status
}