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
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::time::Duration;
use base64::prelude::*;
use once_cell::sync::Lazy;
use regex::Regex;
use sha2::{Digest, Sha256};
use time::format_description::well_known::iso8601::{EncodedConfig, TimePrecision};
use time::format_description::well_known::{self, Iso8601};
use time::macros::format_description;
use time::OffsetDateTime;
use url;
use url::{ParseError, Url};
use crate::http;
use crate::sign::SignedURLError::InvalidOption;
static SPACE_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r" +").unwrap());
static TAB_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"[\t]+").unwrap());
pub enum SignedURLMethod {
DELETE,
GET,
HEAD,
POST,
PUT,
}
impl SignedURLMethod {
pub fn as_str(&self) -> &str {
match self {
SignedURLMethod::DELETE => "DELETE",
SignedURLMethod::GET => "GET",
SignedURLMethod::HEAD => "HEAD",
SignedURLMethod::POST => "POST",
SignedURLMethod::PUT => "PUT",
}
}
}
pub trait URLStyle {
fn host(&self, bucket: &str) -> String;
fn path(&self, bucket: &str, object: &str) -> String;
}
pub struct PathStyle {}
const HOST: &str = "storage.googleapis.com";
impl URLStyle for PathStyle {
fn host(&self, _bucket: &str) -> String {
HOST.to_string()
}
fn path(&self, bucket: &str, object: &str) -> String {
if object.is_empty() {
return bucket.to_string();
}
format!("{bucket}/{object}")
}
}
#[derive(Clone)]
pub enum SignBy {
PrivateKey(Vec<u8>),
SignBytes,
}
impl Debug for SignBy {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
SignBy::PrivateKey(_) => f.write_str("private_key"),
SignBy::SignBytes => f.write_str("sign_bytes"),
}
}
}
pub struct SignedURLOptions {
pub google_access_id: String,
pub sign_by: SignBy,
pub method: SignedURLMethod,
pub expires: std::time::Duration,
pub content_type: Option<String>,
pub headers: Vec<String>,
pub query_parameters: HashMap<String, Vec<String>>,
pub md5: Option<String>,
pub style: Box<dyn URLStyle + Send + Sync>,
pub insecure: bool,
}
impl Default for SignedURLOptions {
fn default() -> Self {
Self {
google_access_id: "".to_string(),
sign_by: SignBy::PrivateKey(vec![]),
method: SignedURLMethod::GET,
expires: std::time::Duration::from_secs(600),
content_type: None,
headers: vec![],
query_parameters: Default::default(),
md5: None,
style: Box::new(PathStyle {}),
insecure: false,
}
}
}
#[derive(thiserror::Error, Debug)]
pub enum SignedURLError {
#[error("invalid option {0}")]
InvalidOption(&'static str),
#[error(transparent)]
ParseError(#[from] ParseError),
#[error("cert error by: {0}")]
CertError(String),
#[error(transparent)]
SignBlob(#[from] http::Error),
}
pub(crate) fn create_signed_buffer(
bucket: &str,
name: &str,
opts: &SignedURLOptions,
) -> Result<(Vec<u8>, Url), SignedURLError> {
let now = OffsetDateTime::now_utc();
validate_options(opts, &now)?;
let headers = v4_sanitize_headers(&opts.headers);
let host = opts.style.host(bucket);
let mut builder = {
let url = if opts.insecure {
format!("http://{}", &host)
} else {
format!("https://{}", &host)
};
url::Url::parse(&url)
}?;
let signed_headers = {
let mut header_names = extract_header_names(&headers);
header_names.push("host");
if opts.content_type.is_some() {
header_names.push("content-type");
}
if opts.md5.is_some() {
header_names.push("content-md5");
}
header_names.sort_unstable();
header_names.join(";")
};
const CONFIG: EncodedConfig = well_known::iso8601::Config::DEFAULT
.set_use_separators(false)
.set_time_precision(TimePrecision::Second { decimal_digits: None })
.encode();
let timestamp = now.format(&Iso8601::<CONFIG>).unwrap();
let credential_scope = format!(
"{}/auto/storage/goog4_request",
now.format(format_description!("[year][month][day]")).unwrap()
);
{
let mut query = builder.query_pairs_mut();
query.append_pair("X-Goog-Algorithm", "GOOG4-RSA-SHA256");
query.append_pair("X-Goog-Credential", &format!("{}/{}", opts.google_access_id, credential_scope));
query.append_pair("X-Goog-Date", ×tamp);
query.append_pair("X-Goog-Expires", opts.expires.as_secs().to_string().as_str());
query.append_pair("X-Goog-SignedHeaders", &signed_headers);
for (k, values) in &opts.query_parameters {
for value in values {
query.append_pair(k.as_str(), value.as_str());
}
}
}
let escaped_query = builder.query().unwrap().replace('+', "%20");
tracing::trace!("escaped_query={}", escaped_query);
let header_with_value = {
let mut header_with_value = vec![format!("host:{host}")];
header_with_value.extend_from_slice(&headers);
if let Some(content_type) = &opts.content_type {
header_with_value.push(format!("content-type:{content_type}"))
}
if let Some(md5) = &opts.md5 {
header_with_value.push(format!("content-md5:{md5}"))
}
header_with_value.sort();
header_with_value
};
let path = opts.style.path(bucket, name);
builder.set_path(&path);
let buffer = {
let mut buffer = format!(
"{}\n{}\n{}\n{}\n\n{}\n",
opts.method.as_str(),
builder.path().replace('+', "%20"),
escaped_query,
header_with_value.join("\n"),
signed_headers
)
.into_bytes();
let sha256_header = header_with_value.iter().any(|h| {
let ret = h.to_lowercase().starts_with("x-goog-content-sha256") && h.contains(':');
if ret {
let v: Vec<&str> = h.splitn(2, ':').collect();
buffer.extend_from_slice(v[1].as_bytes());
}
ret
});
if !sha256_header {
buffer.extend_from_slice("UNSIGNED-PAYLOAD".as_bytes());
}
buffer
};
tracing::trace!("raw_buffer={:?}", String::from_utf8_lossy(&buffer));
let hex_digest = hex::encode(Sha256::digest(buffer));
let mut signed_buffer: Vec<u8> = vec![];
signed_buffer.extend_from_slice("GOOG4-RSA-SHA256\n".as_bytes());
signed_buffer.extend_from_slice(format!("{timestamp}\n").as_bytes());
signed_buffer.extend_from_slice(format!("{credential_scope}\n").as_bytes());
signed_buffer.extend_from_slice(hex_digest.as_bytes());
Ok((signed_buffer, builder))
}
fn v4_sanitize_headers(hdrs: &[String]) -> Vec<String> {
let mut sanitized = HashMap::<String, Vec<String>>::new();
for hdr in hdrs {
let trimmed = hdr.trim().to_string();
let split: Vec<&str> = trimmed.split(':').collect();
if split.len() < 2 {
continue;
}
let key = split[0].trim().to_lowercase();
let space_removed = SPACE_REGEX.replace_all(split[1].trim(), " ");
let value = TAB_REGEX.replace_all(space_removed.as_ref(), "\t");
if !value.is_empty() {
sanitized.entry(key).or_default().push(value.to_string());
}
}
let mut sanitized_headers = Vec::with_capacity(sanitized.len());
for (key, value) in sanitized {
sanitized_headers.push(format!("{}:{}", key, value.join(",")));
}
sanitized_headers
}
fn extract_header_names(kvs: &[String]) -> Vec<&str> {
return kvs
.iter()
.map(|header| {
let name_value: Vec<&str> = header.split(':').collect();
name_value[0]
})
.collect();
}
fn validate_options(opts: &SignedURLOptions, _now: &OffsetDateTime) -> Result<(), SignedURLError> {
if opts.google_access_id.is_empty() {
return Err(InvalidOption("storage: missing required GoogleAccessID"));
}
if opts.expires.is_zero() {
return Err(InvalidOption("missing required expires option"));
}
if let Some(md5) = &opts.md5 {
match BASE64_STANDARD.decode(md5) {
Ok(v) => {
if v.len() != 16 {
return Err(InvalidOption("storage: invalid MD5 checksum length"));
}
}
Err(_e) => return Err(InvalidOption("storage: invalid MD5 checksum")),
}
}
if opts.expires > Duration::from_secs(604801) {
return Err(InvalidOption("storage: expires must be within seven days from now"));
}
Ok(())
}
#[cfg(test)]
mod test {
use std::collections::HashMap;
use std::time::Duration;
use serial_test::serial;
use google_cloud_auth::credentials::CredentialsFile;
use crate::sign::{create_signed_buffer, SignBy, SignedURLOptions};
#[ctor::ctor]
fn init() {
let _ = tracing_subscriber::fmt::try_init();
}
#[tokio::test]
#[serial]
async fn create_signed_buffer_test() {
let file = CredentialsFile::new().await.unwrap();
let param = {
let mut param = HashMap::new();
param.insert("tes t+".to_string(), vec!["++ +".to_string()]);
param
};
let opts = SignedURLOptions {
sign_by: SignBy::PrivateKey(file.private_key.unwrap().into()),
google_access_id: file.client_email.unwrap(),
expires: Duration::from_secs(3600),
query_parameters: param,
..Default::default()
};
let (signed_buffer, _builder) = create_signed_buffer("rust-object-test", "test1", &opts).unwrap();
assert_eq!(signed_buffer.len(), 134)
}
}