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
use std::ops::Deref;

use ring::{rand, signature};

use google_cloud_token::{NopeTokenSourceProvider, TokenSourceProvider};

use crate::http::service_account_client::ServiceAccountClient;
use crate::http::storage_client::StorageClient;
use crate::sign::SignBy::PrivateKey;
use crate::sign::{create_signed_buffer, RsaKeyPair, SignBy, SignedURLError, SignedURLOptions};

///
/// #### Example building a client configuration with a custom retry strategy as middleware:
/// ```rust
/// #   use google_cloud_storage::client::Client;
/// #   use google_cloud_storage::client::ClientConfig;
/// #   use reqwest_middleware::ClientBuilder;
/// #   use reqwest_retry::policies::ExponentialBackoff;
/// #   use reqwest_retry::RetryTransientMiddleware;
/// #   use retry_policies::Jitter;
///
/// async fn configuration_with_exponential_backoff_retry_strategy() -> ClientConfig {
///   let retry_policy = ExponentialBackoff::builder()
///      .base(2)
///      .jitter(Jitter::Full)
///      .build_with_max_retries(3);
///
///   let mid_client = ClientBuilder::new(reqwest::Client::default())
///      // reqwest-retry already comes with a default retry stategy that matches http standards
///      // override it only if you need a custom one due to non standard behaviour
///      .with(RetryTransientMiddleware::new_with_policy(retry_policy))
///      .build();
///
///   ClientConfig {
///      http: Some(mid_client),
///      ..Default::default()
///   }
/// }
///
/// ```
#[derive(Debug)]
pub struct ClientConfig {
    pub http: Option<reqwest_middleware::ClientWithMiddleware>,
    pub storage_endpoint: String,
    pub service_account_endpoint: String,
    pub token_source_provider: Option<Box<dyn TokenSourceProvider>>,
    pub default_google_access_id: Option<String>,
    pub default_sign_by: Option<SignBy>,
    pub project_id: Option<String>,
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            http: None,
            storage_endpoint: "https://storage.googleapis.com".to_string(),
            token_source_provider: Some(Box::new(NopeTokenSourceProvider {})),
            service_account_endpoint: "https://iamcredentials.googleapis.com".to_string(),
            default_google_access_id: None,
            default_sign_by: None,
            project_id: None,
        }
    }
}

impl ClientConfig {
    pub fn anonymous(mut self) -> Self {
        self.token_source_provider = None;
        self
    }
}

#[cfg(feature = "auth")]
pub use google_cloud_auth;

#[cfg(feature = "auth")]
impl ClientConfig {
    pub async fn with_auth(self) -> Result<Self, google_cloud_auth::error::Error> {
        let ts = google_cloud_auth::token::DefaultTokenSourceProvider::new(Self::auth_config()).await?;
        Ok(self.with_token_source(ts).await)
    }

    pub async fn with_credentials(
        self,
        credentials: google_cloud_auth::credentials::CredentialsFile,
    ) -> Result<Self, google_cloud_auth::error::Error> {
        let ts = google_cloud_auth::token::DefaultTokenSourceProvider::new_with_credentials(
            Self::auth_config(),
            Box::new(credentials),
        )
        .await?;
        Ok(self.with_token_source(ts).await)
    }

    async fn with_token_source(mut self, ts: google_cloud_auth::token::DefaultTokenSourceProvider) -> Self {
        match &ts.source_credentials {
            // Credential file is used.
            Some(cred) => {
                self.project_id = cred.project_id.clone();
                if let Some(pk) = &cred.private_key {
                    self.default_sign_by = Some(PrivateKey(pk.clone().into_bytes()));
                }
                self.default_google_access_id = cred.client_email.clone();
            }
            // On Google Cloud
            None => {
                self.project_id = Some(google_cloud_metadata::project_id().await);
                self.default_sign_by = Some(SignBy::SignBytes);
                self.default_google_access_id = google_cloud_metadata::email("default").await.ok();
            }
        }
        self.token_source_provider = Some(Box::new(ts));
        self
    }

    fn auth_config() -> google_cloud_auth::project::Config<'static> {
        google_cloud_auth::project::Config {
            audience: None,
            scopes: Some(&crate::http::storage_client::SCOPES),
            sub: None,
        }
    }
}

#[derive(Clone)]
pub struct Client {
    default_google_access_id: Option<String>,
    default_sign_by: Option<SignBy>,
    storage_client: StorageClient,
    service_account_client: ServiceAccountClient,
}

impl Deref for Client {
    type Target = StorageClient;

    fn deref(&self) -> &Self::Target {
        &self.storage_client
    }
}

impl Client {
    /// New client
    pub fn new(config: ClientConfig) -> Self {
        let ts = match config.token_source_provider {
            Some(tsp) => Some(tsp.token_source()),
            None => {
                tracing::trace!("Use anonymous access due to lack of token");
                None
            }
        };
        let http = config
            .http
            .unwrap_or_else(|| reqwest_middleware::ClientBuilder::new(reqwest::Client::default()).build());

        let service_account_client =
            ServiceAccountClient::new(ts.clone(), config.service_account_endpoint.as_str(), http.clone());
        let storage_client = StorageClient::new(ts, config.storage_endpoint.as_str(), http);

        Self {
            default_google_access_id: config.default_google_access_id,
            default_sign_by: config.default_sign_by,
            storage_client,
            service_account_client,
        }
    }

    /// Get signed url.
    /// SignedURL returns a URL for the specified object. Signed URLs allow anyone
    /// access to a restricted resource for a limited time without needing a
    /// Google account or signing in. For more information about signed URLs, see
    /// https://cloud.google.com/storage/docs/accesscontrol#signed_urls_query_string_authentication
    ///
    /// Using the client defaults:
    /// ```
    /// use google_cloud_storage::client::Client;
    /// use google_cloud_storage::sign::{SignedURLOptions, SignedURLMethod};
    ///
    /// async fn run(client: Client) {
    ///     let url_for_download = client.signed_url("bucket", "file.txt", None, None, SignedURLOptions::default()).await;
    ///     let url_for_upload = client.signed_url("bucket", "file.txt", None, None, SignedURLOptions {
    ///         method: SignedURLMethod::PUT,
    ///         ..Default::default()
    ///     }).await;
    /// }
    /// ```
    ///
    /// Overwriting the client defaults:
    /// ```
    /// use google_cloud_storage::client::Client;
    /// use google_cloud_storage::sign::{SignBy, SignedURLOptions, SignedURLMethod};
    ///
    /// async fn run(client: Client) {
    /// #   let private_key = SignBy::PrivateKey(vec![]);
    ///
    ///     let url_for_download = client.signed_url("bucket", "file.txt", Some("google_access_id".to_string()), Some(private_key.clone()), SignedURLOptions::default()).await;
    ///     let url_for_upload = client.signed_url("bucket", "file.txt", Some("google_access_id".to_string()), Some(private_key.clone()), SignedURLOptions {
    ///         method: SignedURLMethod::PUT,
    ///         ..Default::default()
    ///     }).await;
    /// }
    /// ```
    #[cfg_attr(feature = "trace", tracing::instrument(skip_all))]
    pub async fn signed_url(
        &self,
        bucket: &str,
        object: &str,
        google_access_id: Option<String>,
        sign_by: Option<SignBy>,
        opts: SignedURLOptions,
    ) -> Result<String, SignedURLError> {
        // use the one from the options or the default one or error out

        let google_access_id = match &google_access_id {
            Some(overwritten_gai) => overwritten_gai.to_owned(),
            None => {
                let default_gai = &self
                    .default_google_access_id
                    .clone()
                    .ok_or(SignedURLError::InvalidOption("No default google_access_id is found"))?;

                default_gai.to_owned()
            }
        };

        // use the one from the options or the default one or error out
        let sign_by = match &sign_by {
            Some(overwritten_sign_by) => overwritten_sign_by.to_owned(),
            None => {
                let default_sign_by = &self
                    .default_sign_by
                    .clone()
                    .ok_or(SignedURLError::InvalidOption("No default sign_by is found"))?;

                default_sign_by.to_owned()
            }
        };

        let (signed_buffer, mut builder) = create_signed_buffer(bucket, object, &google_access_id, &opts)?;
        tracing::trace!("signed_buffer={:?}", String::from_utf8_lossy(&signed_buffer));

        // create signature
        let signature = match &sign_by {
            PrivateKey(private_key) => {
                // if sign_by is a collection of private keys we check that at least one is present
                if private_key.is_empty() {
                    return Err(SignedURLError::InvalidOption("No keys present"));
                }
                let key_pair = &RsaKeyPair::try_from(private_key)?;
                let mut signed = vec![0; key_pair.public().modulus_len()];
                key_pair
                    .sign(
                        &signature::RSA_PKCS1_SHA256,
                        &rand::SystemRandom::new(),
                        signed_buffer.as_slice(),
                        &mut signed,
                    )
                    .map_err(|e| SignedURLError::CertError(e.to_string()))?;
                signed
            }
            SignBy::SignBytes => {
                let path = format!("projects/-/serviceAccounts/{}", google_access_id);
                self.service_account_client
                    .sign_blob(&path, signed_buffer.as_slice())
                    .await
                    .map_err(SignedURLError::SignBlob)?
            }
        };
        builder
            .query_pairs_mut()
            .append_pair("X-Goog-Signature", &hex::encode(signature));
        Ok(builder.to_string())
    }
}

#[cfg(test)]
mod test {

    use serial_test::serial;

    use crate::client::{Client, ClientConfig};
    use crate::http::buckets::get::GetBucketRequest;

    use crate::http::storage_client::test::bucket_name;
    use crate::sign::{SignedURLMethod, SignedURLOptions};

    async fn create_client() -> (Client, String) {
        let config = ClientConfig::default().with_auth().await.unwrap();
        let project_id = config.project_id.clone();
        (Client::new(config), project_id.unwrap())
    }

    #[tokio::test]
    #[serial]
    async fn test_sign() {
        let (client, project) = create_client().await;
        let bucket_name = bucket_name(&project, "object");
        let data = "aiueo";
        let content_type = "application/octet-stream";

        // upload
        let option = SignedURLOptions {
            method: SignedURLMethod::PUT,
            content_type: Some(content_type.to_string()),
            ..SignedURLOptions::default()
        };
        let url = client
            .signed_url(&bucket_name, "signed_uploadtest", None, None, 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());

        //download
        let option = SignedURLOptions {
            content_type: Some(content_type.to_string()),
            ..SignedURLOptions::default()
        };
        let url = client
            .signed_url(&bucket_name, "signed_uploadtest", None, None, 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);
    }

    #[tokio::test]
    #[serial]
    async fn test_sign_with_overwrites() {
        let (client, project) = create_client().await;
        let bucket_name = bucket_name(&project, "object");
        let data = "aiueo";
        let content_type = "application/octet-stream";
        let overwritten_gai = client.default_google_access_id.as_ref().unwrap();
        let overwritten_sign_by = client.default_sign_by.as_ref().unwrap();

        // upload
        let option = SignedURLOptions {
            method: SignedURLMethod::PUT,
            content_type: Some(content_type.to_string()),
            ..SignedURLOptions::default()
        };
        let url = client
            .signed_url(
                &bucket_name,
                "signed_uploadtest",
                Some(overwritten_gai.to_owned()),
                Some(overwritten_sign_by.to_owned()),
                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());

        //download
        let option = SignedURLOptions {
            content_type: Some(content_type.to_string()),
            ..SignedURLOptions::default()
        };

        let url = client
            .signed_url(
                &bucket_name,
                "signed_uploadtest",
                Some(overwritten_gai.to_owned()),
                Some(overwritten_sign_by.to_owned()),
                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);
    }

    #[tokio::test]
    #[serial]
    async fn test_anonymous() {
        let project = ClientConfig::default().with_auth().await.unwrap().project_id.unwrap();
        let bucket = bucket_name(&project, "anonymous");

        let config = ClientConfig::default().anonymous();
        let client = Client::new(config);
        let result = client
            .get_bucket(&GetBucketRequest {
                bucket: bucket.clone(),
                ..Default::default()
            })
            .await
            .unwrap();
        assert_eq!(result.name, bucket);
    }
}