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
#![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;
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| {
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| {
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
}
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(),
)
}
}
}