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
/* This Source Code Form is subject to the terms of the Mozilla Public
   License, v. 2.0. If a copy of the MPL was not distributed with this
   file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

//! A Backblaze B2 API library that can send and receive data via arbitrary HTTP
//! clients.
//!
//! The full API is supported.
//!
//! # Examples
//!
//! ```no_run
//! # fn calculate_sha1(data: &[u8]) -> String { String::default() }
//! # use anyhow;
//! use std::env;
//! use b2_client as b2;
//!
//! # #[cfg(feature = "with_surf")]
//! # async fn upload_file() -> anyhow::Result<()> {
//! let key = env::var("B2_KEY").ok().unwrap();
//! let key_id = env::var("B2_KEY_ID").ok().unwrap();
//!
//! let client = b2::client::SurfClient::default();
//! let mut auth = b2::authorize_account(client, &key, &key_id).await?;
//!
//! let mut upload_auth = b2::get_upload_authorization_by_id(
//!     &mut auth,
//!     "my-bucket-id"
//! ).await?;
//!
//! let file = b2::UploadFile::builder()
//!     .file_name("my-file.txt")?
//!     .sha1_checksum("61b8d6600ac94d912874f569a9341120f680c9f8")
//!     .build()?;
//!
//! let data = b"very important information";
//!
//! let file_info = b2::upload_file(&mut upload_auth, file, data).await?;
//!
//! # Ok(())
//! # }
//! ```
//!
//! # Differences from the B2 Service API
//!
//! * The B2 endpoint `b2_get_upload_part_url` is
//!   [get_upload_part_authorization].
//! * The B2 endpoint `b2_get_upload_url` is [get_upload_authorization].
//! * The word "file" is often added for clarity; e.g., the B2 endpoint
//!   `b2_copy_part` is [copy_file_part].

// Increase the recursion limit for a macro in a test in validate.rs.
#![cfg_attr(test, recursion_limit = "256")]


pub mod account;
pub mod bucket;
pub mod file;

pub mod client;
pub mod error;

mod types;
mod validate;

pub mod prelude {
    #![allow(unused_imports)]

    pub(crate) use super::{
        account::{Authorization, Capability},
        types::{B2Result, Duration},
        require_capability,
    };
}

macro_rules! require_capability {
    ($auth:expr, $cap:expr) => {
        if ! $auth.has_capability($cap) {
            return Err($crate::error::Error::Unauthorized($cap));
        }
    }
}
pub(crate) use require_capability;


pub use account::*;
pub use bucket::*;
pub use file::*;

pub use client::HttpClient;
pub use error::Error;

#[cfg(all(test, feature = "with_surf"))]
pub(crate) mod test_utils {
    use std::boxed::Box;
    use crate::{
        account::{Authorization, Capability, Capabilities},
        client::SurfClient,
    };
    use surf_vcr::*;
    use surf::http::Method;


    /// Create a SurfClient with the surf-vcr middleware.
    ///
    /// We remove the following data from the recorded sessions:
    ///
    /// * From request/response headers and bodies:
    ///     * `accountId`
    ///     * `authorizationToken`
    ///     * `keys` dictionary (response only)
    ///
    /// The `keys` dictionary in a response is replaced with a single key object
    /// containing fake data.
    ///
    /// The potentially-senstive data that we do not remove includes:
    ///
    /// * From request/response bodies:
    ///     * `applicationKeyId`
    ///     * `bucketId`
    ///
    /// You may optionally pass in functions to make additional modifications to
    /// a response or request as needed for specific tests. Note that if the
    /// response body is not valid JSON, nothing in the response can be
    /// modified.
    pub async fn create_test_client(
        mode: VcrMode, cassette: &'static str,
        req_mod: Option<Box<dyn Fn(&mut VcrRequest) + Send + Sync + 'static>>,
        res_mod: Option<Box<dyn Fn(&mut VcrResponse) + Send + Sync + 'static>>,
    ) -> std::result::Result<SurfClient, VcrError> {
        #![allow(clippy::option_map_unit_fn)]

        let vcr = VcrMiddleware::new(mode, cassette).await.unwrap()
            .with_modify_request(move |req| {
                let val = match req.method {
                    Method::Get => "Basic hidden-account-id".into(),
                    _ => "hidden-authorization-token".into(),
                };

                req.headers.entry("authorization".into())
                    .and_modify(|v| *v = vec![val]);

                req.headers.entry("user-agent".into())
                    .and_modify(|v| {
                        // We need to replace the version number with a constant
                        // value.

                        let range = if v[0].len() > 7 {
                            let start = v[0][7..]
                                .find(|c| char::is_ascii_digit(&c))
                                .expect("User-agent string is incorrect");

                            let end = v[0][start..].find(';')
                                .expect("User-agent string is incorrect");

                            Some((start + 7, end + start))
                        } else {
                            None
                        };

                        if let Some((start, end)) = range {
                            v[0].replace_range(start..end, "version");
                        }
                    });

                if let Body::Str(body) = &mut req.body {
                    let body_json: Result<serde_json::Value, _> =
                        serde_json::from_str(body);

                    if let Ok(mut body) = body_json {
                        body.get_mut("accountId")
                            .map(|v| *v =
                                serde_json::json!("hidden-account-id"));

                        req.body = Body::Str(body.to_string());
                    }
                };

                if let Some(req_mod) = req_mod.as_ref() {
                    req_mod(req);
                }
            })
            .with_modify_response(move |res| {
                // If the response isn't JSON, there's nothing we need to
                // modify.
                let mut json: serde_json::Value = match &mut res.body {
                    Body::Str(s) => match serde_json::from_str(s) {
                        Ok(json) => json,
                        Err(_) => return,
                    },
                    _ => return,
                };

                json = hide_response_account_id(json);

                json.get_mut("authorizationToken")
                    .map(|v| *v = serde_json::json!(
                        "hidden-authorization-token")
                    );

                json.get_mut("keys")
                    .map(|v| *v = serde_json::json!([{
                        "accountId": "hidden-account-id",
                        "applicationKeyId": "hidden-app-key-id",
                        "bucketId": "abcdefghijklmnop",
                        "capabilities": [
                            "listFiles",
                            "readFiles",
                        ],
                        "expirationTimestamp": null,
                        "keyName": "dev-b2-client-tester",
                        "namePrefix": null,
                        "options": ["s3"],
                        "nextApplicationId": null,
                    }]));

                res.body = Body::Str(json.to_string());

                if let Some(res_mod) = res_mod.as_ref() {
                    res_mod(res);
                }
            });

        let surf = surf::Client::new()
            .with(vcr);

        let client = SurfClient::default()
            .with_client(surf);

        Ok(client)
    }

    fn hide_response_account_id(mut json: serde_json::Value)
    -> serde_json::Value {
        #![allow(clippy::option_map_unit_fn)]

        if let Some(buckets) = json.get_mut("buckets")
            .and_then(|b| b.as_array_mut())
        {
            for bucket in buckets.iter_mut() {
                bucket.get_mut("accountId")
                    .map(|v| *v = serde_json::json!("hidden-account-id"));
            }
        }

        json.get_mut("accountId")
            .map(|v| *v = serde_json::json!("hidden-account-id"));

        json
    }

    /// Create an [Authorization] with the specified capabilities.
    ///
    /// If the `B2_CLIENT_TEST_KEY` and `B2_CLIENT_TEST_KEY_ID` environment
    /// variables are set, their values are used to make an authorization
    /// request against the B2 API.
    ///
    /// Otherwise, a fake authorization is created with values usable for
    /// pre-recorded sessions in unit tests.
    pub async fn create_test_auth(
        client: SurfClient,
        capabilities: Vec<Capability>
    ) -> Authorization<SurfClient> {
        use super::account::authorize_account;

        let key = std::env::var("B2_CLIENT_TEST_KEY").ok();
        let key_id = std::env::var("B2_CLIENT_TEST_KEY_ID").ok();

        assert!(key.as_ref().xor(key_id.as_ref()).is_none(),
            concat!(
                "Either both or neither of the B2_CLIENT_TEST_KEY and ",
                "B2_CLIENT_TEST_KEY_ID environment variables must be set"
            )
        );

        if let Some(key) = key {
            let auth = authorize_account(client, &key, &key_id.unwrap())
                .await.unwrap();

            for cap in capabilities {
                assert!(auth.capabilities().has_capability(cap));
            }

            auth
        } else {
            Authorization::new(
                client,
                "some-account-id".into(),
                "some-key-id".into(),
                Capabilities::new(capabilities, None, None, None),
                "https://api002.backblazeb2.com".into(),
                "https://f002.backblazeb2.com".into(),
                100000000,
                5000000,
                "https://s3.us-west-002.backblazeb2.com".into(),
            )
        }
    }
}