glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! Files kept elsewhere: a [`Store`] on disk or in S3 (or anything that
//! speaks its API, such as MinIO), and presigned S3 URLs, as Active
//! Storage, Paperclip and the aws-sdk hand to clients, so a client can
//! fetch a private object directly for a while.

use bytes::Bytes;
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};

use crate::error::{Error, Result};

/// Signs S3 requests and URLs with AWS Signature Version 4.
///
/// ```
/// use glacier::storage::S3Signer;
/// let s3 = S3Signer::new("my-bucket", "eu-west-2", "AKIA…", "secret");
/// let url = s3.presigned_url("images/cover.png", 600);
/// assert!(url.starts_with("https://my-bucket.s3.eu-west-2.amazonaws.com/images/cover.png?"));
/// ```
#[derive(Debug, Clone)]
pub struct S3Signer {
    bucket: String,
    scheme: String,
    host: String,
    /// `/bucket/key` paths (MinIO, local S3) rather than the bucket in the
    /// host name.
    path_style: bool,
    region: String,
    access_key_id: String,
    secret_access_key: String,
}

impl S3Signer {
    pub fn new(
        bucket: &str,
        region: &str,
        access_key_id: impl Into<String>,
        secret_access_key: impl Into<String>,
    ) -> Self {
        Self {
            bucket: bucket.to_owned(),
            scheme: "https".to_owned(),
            host: format!("{bucket}.s3.{region}.amazonaws.com"),
            path_style: false,
            region: region.to_owned(),
            access_key_id: access_key_id.into(),
            secret_access_key: secret_access_key.into(),
        }
    }

    /// From `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION` and
    /// the bucket; `None` if any is missing.
    pub fn from_env(bucket: &str) -> Option<Self> {
        let var = |name| std::env::var(name).ok().filter(|v: &String| !v.is_empty());
        Some(Self::new(
            bucket,
            &var("AWS_REGION")?,
            var("AWS_ACCESS_KEY_ID")?,
            var("AWS_SECRET_ACCESS_KEY")?,
        ))
    }

    /// Signs for another host name, with the bucket still in it.
    pub fn with_host(mut self, host: impl Into<String>) -> Self {
        self.host = host.into();
        self
    }

    /// Talks to another S3-compatible service, with `/bucket/key` paths:
    /// `with_endpoint("http://localhost:9000")` for a local MinIO.
    pub fn with_endpoint(mut self, endpoint: &str) -> Self {
        let (scheme, host) = endpoint.split_once("://").unwrap_or(("https", endpoint));
        self.scheme = scheme.to_owned();
        self.host = host.trim_end_matches('/').to_owned();
        self.path_style = true;
        self
    }

    /// The object's path on the host: `/key`, or `/bucket/key`.
    fn path(&self, key: &str) -> String {
        let key = encode(key.trim_start_matches('/'), false);
        if self.path_style {
            format!("/{}/{key}", self.bucket)
        } else {
            format!("/{key}")
        }
    }

    /// A URL for `key` that works for `expires_in` seconds from now.
    pub fn presigned_url(&self, key: &str, expires_in: u64) -> String {
        self.presigned_url_at(key, expires_in, chrono::Utc::now())
    }

    /// A URL for `key` signed as at `now`.
    pub fn presigned_url_at(
        &self,
        key: &str,
        expires_in: u64,
        now: chrono::DateTime<chrono::Utc>,
    ) -> String {
        let (date, timestamp, scope) = self.scope(now);
        let credential = format!("{}/{scope}", self.access_key_id);
        let path = self.path(key);
        let query = format!(
            "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={}&X-Amz-Date={timestamp}\
             &X-Amz-Expires={expires_in}&X-Amz-SignedHeaders=host",
            encode(&credential, true)
        );
        let canonical = format!(
            "GET\n{path}\n{query}\nhost:{}\n\nhost\nUNSIGNED-PAYLOAD",
            self.host
        );
        let signature = self.signature(&date, &timestamp, &scope, &canonical);
        format!(
            "{}://{}{path}?{query}&X-Amz-Signature={signature}",
            self.scheme, self.host
        )
    }

    /// The URL and headers for a `method` request on `key` whose body
    /// hashes to `payload_sha256` (hex), signed as at `now`, with any
    /// `extra` headers (lower-case names) signed too.
    pub fn signed_request(
        &self,
        method: &str,
        key: &str,
        payload_sha256: &str,
        extra: &[(&str, &str)],
        now: chrono::DateTime<chrono::Utc>,
    ) -> (String, Vec<(String, String)>) {
        let (date, timestamp, scope) = self.scope(now);
        let path = self.path(key);
        let mut headers: Vec<(String, String)> = vec![
            ("host".into(), self.host.clone()),
            ("x-amz-content-sha256".into(), payload_sha256.to_owned()),
            ("x-amz-date".into(), timestamp.clone()),
        ];
        headers.extend(
            extra
                .iter()
                .map(|(n, v)| ((*n).to_owned(), (*v).trim().to_owned())),
        );
        headers.sort();
        let names = headers
            .iter()
            .map(|(n, _)| n.as_str())
            .collect::<Vec<_>>()
            .join(";");
        let lines: String = headers.iter().map(|(n, v)| format!("{n}:{v}\n")).collect();
        let canonical = format!("{method}\n{path}\n\n{lines}\n{names}\n{payload_sha256}");
        let signature = self.signature(&date, &timestamp, &scope, &canonical);
        let authorization = format!(
            "AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={names}, Signature={signature}",
            self.access_key_id
        );
        headers.retain(|(n, _)| n != "host");
        headers.push(("authorization".into(), authorization));
        (format!("{}://{}{path}", self.scheme, self.host), headers)
    }

    fn scope(&self, now: chrono::DateTime<chrono::Utc>) -> (String, String, String) {
        let date = now.format("%Y%m%d").to_string();
        let timestamp = now.format("%Y%m%dT%H%M%SZ").to_string();
        let scope = format!("{date}/{}/s3/aws4_request", self.region);
        (date, timestamp, scope)
    }

    fn signature(&self, date: &str, timestamp: &str, scope: &str, canonical: &str) -> String {
        let to_sign = format!(
            "AWS4-HMAC-SHA256\n{timestamp}\n{scope}\n{}",
            hex(&Sha256::digest(canonical.as_bytes()))
        );
        let key = [date, &self.region, "s3", "aws4_request"].iter().fold(
            format!("AWS4{}", self.secret_access_key).into_bytes(),
            |key, part| hmac(&key, part.as_bytes()),
        );
        hex(&hmac(&key, to_sign.as_bytes()))
    }
}

/// Where uploaded files are kept: a folder (development, tests) or an S3
/// bucket. Keys are paths such as `comments/12/thumb/shelf.png`.
#[derive(Debug, Clone)]
pub enum Store {
    Disk(std::path::PathBuf),
    S3(S3Signer),
}

impl Store {
    /// Saves `bytes` as `key`.
    ///
    /// # Errors
    ///
    /// If the folder can't be written, or S3 refuses or can't be reached.
    pub async fn put(&self, key: &str, bytes: Bytes, content_type: &str) -> Result<()> {
        match self {
            Store::Disk(root) => {
                let path = disk_path(root, key)?;
                if let Some(dir) = path.parent() {
                    tokio::fs::create_dir_all(dir).await.map_err(io_error)?;
                }
                tokio::fs::write(&path, &bytes).await.map_err(io_error)
            }
            Store::S3(s3) => {
                let hash = hex(&Sha256::digest(&bytes));
                let (url, headers) = s3.signed_request(
                    "PUT",
                    key,
                    &hash,
                    &[("content-type", content_type)],
                    chrono::Utc::now(),
                );
                send(reqwest::Method::PUT, &url, headers, Some(bytes))
                    .await
                    .map(|_| ())
            }
        }
    }

    /// The file saved as `key`, if there is one.
    ///
    /// # Errors
    ///
    /// If it can't be read, or S3 can't be reached.
    pub async fn get(&self, key: &str) -> Result<Option<Bytes>> {
        match self {
            Store::Disk(root) => match tokio::fs::read(disk_path(root, key)?).await {
                Ok(bytes) => Ok(Some(bytes.into())),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
                Err(e) => Err(io_error(e)),
            },
            Store::S3(s3) => {
                let (url, headers) = s3.signed_request(
                    "GET",
                    key,
                    &hex(&Sha256::digest(b"")),
                    &[],
                    chrono::Utc::now(),
                );
                send(reqwest::Method::GET, &url, headers, None).await
            }
        }
    }

    /// Removes `key`; removing a missing file is fine.
    ///
    /// # Errors
    ///
    /// If it can't be removed, or S3 can't be reached.
    pub async fn delete(&self, key: &str) -> Result<()> {
        match self {
            Store::Disk(root) => match tokio::fs::remove_file(disk_path(root, key)?).await {
                Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(io_error(e)),
                _ => Ok(()),
            },
            Store::S3(s3) => {
                let (url, headers) = s3.signed_request(
                    "DELETE",
                    key,
                    &hex(&Sha256::digest(b"")),
                    &[],
                    chrono::Utc::now(),
                );
                send(reqwest::Method::DELETE, &url, headers, None)
                    .await
                    .map(|_| ())
            }
        }
    }

    /// A URL a client can fetch `key` from for `expires_in` seconds: a
    /// presigned S3 URL, or the key's path under `/uploads` on disk.
    pub fn url(&self, key: &str, expires_in: u64) -> String {
        match self {
            Store::Disk(_) => format!("/uploads/{}", key.trim_start_matches('/')),
            Store::S3(s3) => s3.presigned_url(key, expires_in),
        }
    }
}

static CURRENT: std::sync::RwLock<Option<Store>> = std::sync::RwLock::new(None);

/// The app's store, from `[storage]` in the config: an S3 bucket when
/// `bucket` is set (with `AWS_REGION`, `AWS_ACCESS_KEY_ID` and
/// `AWS_SECRET_ACCESS_KEY`, and `endpoint` for MinIO and the like),
/// otherwise the folder in `root`, `storage` by default. Attachments
/// (`has_attached`) keep their files here.
pub fn current() -> Store {
    CURRENT
        .read()
        .unwrap_or_else(|e| e.into_inner())
        .clone()
        .unwrap_or_else(|| Store::Disk("storage".into()))
}

/// Makes `store` the app's store, as `[storage]` in the config does.
pub fn set_current(store: Store) {
    *CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(store);
}

/// The store `[storage]` describes, if it describes one.
///
/// # Errors
///
/// When `bucket` is set without the AWS variables.
pub fn from_config(config: &crate::Config) -> Result<Option<Store>> {
    if let Some(bucket) = config.get_opt::<String>("storage.bucket")? {
        let mut s3 = S3Signer::from_env(&bucket).ok_or_else(|| {
            Error::internal(
                "storage.bucket needs AWS_REGION, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY",
            )
        })?;
        if let Some(endpoint) = config.get_opt::<String>("storage.endpoint")? {
            s3 = s3.with_endpoint(&endpoint);
        }
        return Ok(Some(Store::S3(s3)));
    }
    Ok(config
        .get_opt::<String>("storage.root")?
        .map(|root| Store::Disk(root.into())))
}

/// Reads `[storage]`. `App::config` calls it.
pub(crate) fn configure(config: &crate::Config) -> Result<()> {
    if let Some(store) = from_config(config)? {
        set_current(store);
    }
    Ok(())
}

/// `key` under `root`, refusing keys that climb out of it.
fn disk_path(root: &std::path::Path, key: &str) -> Result<std::path::PathBuf> {
    let key = key.trim_start_matches('/');
    if key.split('/').any(|part| part == "..") {
        return Err(Error::bad_request(format!("invalid file key: {key}")));
    }
    Ok(root.join(key))
}

fn io_error(e: std::io::Error) -> Error {
    Error::internal(format!("file storage: {e}"))
}

/// Sends a signed S3 request: the body for a 2xx, `None` for a 404.
async fn send(
    method: reqwest::Method,
    url: &str,
    headers: Vec<(String, String)>,
    body: Option<Bytes>,
) -> Result<Option<Bytes>> {
    let client = reqwest::Client::new();
    let mut request = client.request(method, url);
    for (name, value) in headers {
        request = request.header(name, value);
    }
    if let Some(body) = body {
        request = request.body(body);
    }
    let response = request
        .send()
        .await
        .map_err(|e| Error::internal(format!("S3: {e}")))?;
    let status = response.status();
    if status == reqwest::StatusCode::NOT_FOUND {
        return Ok(None);
    }
    let bytes = response
        .bytes()
        .await
        .map_err(|e| Error::internal(format!("S3: {e}")))?;
    if !status.is_success() {
        return Err(Error::internal(format!(
            "S3 answered {status}: {}",
            String::from_utf8_lossy(&bytes)
        )));
    }
    Ok(Some(bytes))
}

fn hmac(key: &[u8], data: &[u8]) -> Vec<u8> {
    let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC takes any key");
    mac.update(data);
    mac.finalize().into_bytes().to_vec()
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// AWS's URI encoding: unreserved characters stay, the rest are `%XX`;
/// `/` stays in paths.
fn encode(text: &str, slash: bool) -> String {
    let mut out = String::new();
    for byte in text.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char);
            }
            b'/' if !slash => out.push('/'),
            _ => out.push_str(&format!("%{byte:02X}")),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn example() -> S3Signer {
        S3Signer::new(
            "examplebucket",
            "us-east-1",
            "AKIAIOSFODNN7EXAMPLE",
            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        )
        .with_host("examplebucket.s3.amazonaws.com")
    }

    fn may_24_2013() -> chrono::DateTime<chrono::Utc> {
        chrono::DateTime::parse_from_rfc3339("2013-05-24T00:00:00Z")
            .unwrap()
            .to_utc()
    }

    #[test]
    fn signs_urls_as_aws_documents() {
        // AWS's "Authenticating Requests: Using Query Parameters" example.
        let url = example().presigned_url_at("test.txt", 86400, may_24_2013());
        assert!(url.starts_with("https://examplebucket.s3.amazonaws.com/test.txt?"));
        assert!(url.contains(
            "X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2Fus-east-1%2Fs3%2Faws4_request"
        ));
        assert!(url.ends_with(
            "&X-Amz-Signature=aeeed9bbccd4d02ee5c0109b86d86835f995330da4c265957d157751f604d404"
        ));
    }

    #[test]
    fn signs_requests_as_aws_documents() {
        // AWS's "Authenticating Requests: Using the Authorization Header"
        // GET Object example.
        let empty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
        let (url, headers) = example().signed_request(
            "GET",
            "test.txt",
            empty,
            &[("range", "bytes=0-9")],
            may_24_2013(),
        );
        assert_eq!(url, "https://examplebucket.s3.amazonaws.com/test.txt");
        let authorization = &headers
            .iter()
            .find(|(n, _)| n == "authorization")
            .unwrap()
            .1;
        assert!(
            authorization.ends_with(
                "Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
            ),
            "{authorization}"
        );
        assert!(authorization.contains("SignedHeaders=host;range;x-amz-content-sha256;x-amz-date"));
    }

    #[test]
    fn uses_path_style_for_other_endpoints() {
        let s3 = S3Signer::new("bucket", "eu-west-2", "id", "secret")
            .with_endpoint("http://localhost:9000");
        assert!(
            s3.presigned_url("a/b.png", 60)
                .starts_with("http://localhost:9000/bucket/a/b.png?")
        );
    }

    #[tokio::test]
    async fn keeps_files_on_disk() {
        let root = std::env::temp_dir().join(format!("glacier-store-{}", std::process::id()));
        let store = Store::Disk(root.clone());
        store
            .put(
                "comments/1/original/a.png",
                Bytes::from_static(b"png"),
                "image/png",
            )
            .await
            .unwrap();
        assert_eq!(
            store
                .get("comments/1/original/a.png")
                .await
                .unwrap()
                .as_deref(),
            Some(&b"png"[..])
        );
        assert_eq!(
            store.url("comments/1/original/a.png", 60),
            "/uploads/comments/1/original/a.png"
        );
        store.delete("comments/1/original/a.png").await.unwrap();
        assert!(
            store
                .get("comments/1/original/a.png")
                .await
                .unwrap()
                .is_none()
        );
        store.delete("missing").await.unwrap();
        assert!(
            store
                .put("../escape", Bytes::new(), "text/plain")
                .await
                .is_err()
        );
        std::fs::remove_dir_all(root).ok();
    }
}