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
use crate::http::storage_client;
use crate::http::storage_client::StorageClient;
use google_cloud_auth::{create_token_source_from_project, Config, Project};
use std::ops::Deref;
use std::sync::Arc;
use crate::sign::{signed_url, SignBy, SignedURLError, SignedURLOptions};
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error(transparent)]
Auth(#[from] google_cloud_auth::error::Error),
#[error(transparent)]
Metadata(#[from] google_cloud_metadata::Error),
#[error("error: {0}")]
Other(&'static str),
}
pub struct Client {
private_key: Option<String>,
service_account_email: String,
project_id: String,
storage_client: StorageClient,
}
impl Deref for Client {
type Target = StorageClient;
fn deref(&self) -> &Self::Target {
&self.storage_client
}
}
impl Client {
pub async fn new() -> Result<Self, Error> {
let project = google_cloud_auth::project().await?;
Self::from(&project).await
}
pub async fn from(project: &google_cloud_auth::Project) -> Result<Self, Error> {
let ts = create_token_source_from_project(
project,
Config {
audience: None,
scopes: Some(&storage_client::SCOPES),
},
)
.await?;
match project {
Project::FromFile(cred) => Ok(Client {
private_key: cred.private_key.clone(),
service_account_email: cred
.client_email
.as_ref()
.ok_or(Error::Other("no client_email was found"))?
.to_string(),
project_id: cred
.project_id
.as_ref()
.ok_or(Error::Other("no project_id was found"))?
.to_string(),
storage_client: StorageClient::new(Arc::from(ts)),
}),
Project::FromMetadataServer(info) => Ok(Client {
private_key: None,
service_account_email: google_cloud_metadata::email("default").await?,
project_id: info
.project_id
.as_ref()
.ok_or(Error::Other("no project_id was found"))?
.to_string(),
storage_client: StorageClient::new(Arc::from(ts)),
}),
}
}
pub fn project_id(&self) -> &str {
&self.project_id
}
#[cfg(not(feature = "trace"))]
pub async fn signed_url(
&self,
bucket: &str,
object: &str,
opts: SignedURLOptions,
) -> Result<String, SignedURLError> {
self._signed_url(bucket, object, opts).await
}
#[cfg(feature = "trace")]
#[tracing::instrument(skip_all)]
pub async fn signed_url(
&self,
bucket: &str,
object: &str,
opts: SignedURLOptions,
) -> Result<String, SignedURLError> {
self._signed_url(bucket, object, opts).await
}
#[inline(always)]
async fn _signed_url(&self, bucket: &str, object: &str, opts: SignedURLOptions) -> Result<String, SignedURLError> {
let signable = match &opts.sign_by {
SignBy::PrivateKey(v) => !v.is_empty(),
_ => true,
};
if !opts.google_access_id.is_empty() && signable {
return signed_url(bucket, object, opts);
}
let mut opts = opts;
if let Some(private_key) = &self.private_key {
opts.sign_by = SignBy::PrivateKey(private_key.as_bytes().to_vec());
}
if !self.service_account_email.is_empty() && opts.google_access_id.is_empty() {
opts.google_access_id = self.service_account_email.to_string();
}
signed_url(bucket, object, opts)
}
}
#[cfg(test)]
mod test {
use crate::client::Client;
use crate::http::buckets::delete::DeleteBucketRequest;
use crate::http::buckets::iam_configuration::{PublicAccessPrevention, UniformBucketLevelAccess};
use crate::http::buckets::insert::{
BucketCreationConfig, InsertBucketParam, InsertBucketRequest, RetentionPolicyCreationConfig,
};
use crate::http::buckets::{lifecycle, Billing, Cors, IamConfiguration, Lifecycle, Website};
use serial_test::serial;
use std::collections::HashMap;
use crate::http::buckets::list::ListBucketsRequest;
use crate::sign::{SignedURLMethod, SignedURLOptions};
#[ctor::ctor]
fn init() {
let _ = tracing_subscriber::fmt::try_init();
}
#[tokio::test]
#[serial]
async fn buckets() {
let prefix = Some("rust-bucket-test".to_string());
let client = Client::new().await.unwrap();
let result = client
.list_buckets(
&ListBucketsRequest {
project: client.project_id().to_string(),
prefix,
..Default::default()
},
None,
)
.await
.unwrap();
assert_eq!(result.items.len(), 1);
}
#[tokio::test]
#[serial]
async fn create_bucket() {
let mut labels = HashMap::new();
labels.insert("labelkey".to_string(), "labelvalue".to_string());
let config = BucketCreationConfig {
location: "ASIA-NORTHEAST1".to_string(),
storage_class: Some("STANDARD".to_string()),
default_event_based_hold: true,
labels: Some(labels),
website: Some(Website {
main_page_suffix: "_suffix".to_string(),
not_found_page: "notfound.html".to_string(),
}),
iam_configuration: Some(IamConfiguration {
uniform_bucket_level_access: Some(UniformBucketLevelAccess {
enabled: true,
locked_time: None,
}),
public_access_prevention: Some(PublicAccessPrevention::Enforced),
}),
billing: Some(Billing { requester_pays: false }),
retention_policy: Some(RetentionPolicyCreationConfig {
retention_period: 10000,
}),
cors: Some(vec![Cors {
origin: vec!["*".to_string()],
method: vec!["GET".to_string(), "HEAD".to_string()],
response_header: vec!["200".to_string()],
max_age_seconds: 100,
}]),
lifecycle: Some(Lifecycle {
rule: vec![lifecycle::Rule {
action: Some(lifecycle::rule::Action {
r#type: lifecycle::rule::ActionType::Delete,
storage_class: None,
}),
condition: Some(lifecycle::rule::Condition {
age: 365,
is_live: Some(true),
..Default::default()
}),
}],
}),
rpo: None,
..Default::default()
};
let client = Client::new().await.unwrap();
let bucket_name = format!("rust-test-{}", chrono::Utc::now().timestamp());
let req = InsertBucketRequest {
name: bucket_name.clone(),
param: InsertBucketParam {
project: client.project_id().to_string(),
..Default::default()
},
bucket: config,
};
let result = client.insert_bucket(&req, None).await.unwrap();
client
.delete_bucket(
&DeleteBucketRequest {
bucket: result.name.to_string(),
..Default::default()
},
None,
)
.await
.unwrap();
assert_eq!(result.name, bucket_name);
assert_eq!(result.storage_class, req.bucket.storage_class.unwrap());
assert_eq!(result.location, req.bucket.location);
assert!(result.iam_configuration.is_some());
assert!(
result
.iam_configuration
.unwrap()
.uniform_bucket_level_access
.unwrap()
.enabled
);
}
#[tokio::test]
#[serial]
async fn sign() {
let client = Client::new().await.unwrap();
let bucket_name = "rust-object-test";
let data = "aiueo";
let content_type = "application/octet-stream";
let option = SignedURLOptions {
method: SignedURLMethod::PUT,
content_type: Some(content_type.to_string()),
..SignedURLOptions::default()
};
let url = client
.signed_url(bucket_name, "signed_uploadtest", option)
.await
.unwrap();
println!("uploading={:?}", url);
let request = reqwest::Client::default()
.put(url)
.header("content-type", content_type)
.body(data.as_bytes());
let result = request.send().await.unwrap();
let status = result.status();
assert!(status.is_success(), "{:?}", result.text().await.unwrap());
let option = SignedURLOptions {
content_type: Some(content_type.to_string()),
..SignedURLOptions::default()
};
let url = client
.signed_url(bucket_name, "signed_uploadtest", option)
.await
.unwrap();
println!("downloading={:?}", url);
let result = reqwest::Client::default()
.get(url)
.header("content-type", content_type)
.send()
.await
.unwrap()
.text()
.await
.unwrap();
assert_eq!(result, data);
}
}