Skip to main content

glacier/
storage.rs

1//! Files kept elsewhere: a [`Store`] on disk or in S3 (or anything that
2//! speaks its API, such as MinIO), and presigned S3 URLs, as Active
3//! Storage, Paperclip and the aws-sdk hand to clients, so a client can
4//! fetch a private object directly for a while.
5
6use base64::Engine as _;
7use bytes::Bytes;
8use hmac::{Hmac, Mac};
9use sha2::{Digest, Sha256};
10
11use crate::error::{Error, Result};
12
13/// Signs S3 requests and URLs with AWS Signature Version 4.
14///
15/// ```
16/// use glacier::storage::S3Signer;
17/// let s3 = S3Signer::new("my-bucket", "eu-west-2", "AKIA…", "secret");
18/// let url = s3.presigned_url("images/cover.png", 600);
19/// assert!(url.starts_with("https://my-bucket.s3.eu-west-2.amazonaws.com/images/cover.png?"));
20/// ```
21#[derive(Debug, Clone)]
22pub struct S3Signer {
23    bucket: String,
24    scheme: String,
25    host: String,
26    /// `/bucket/key` paths (MinIO, local S3) rather than the bucket in the
27    /// host name.
28    path_style: bool,
29    region: String,
30    access_key_id: String,
31    secret_access_key: String,
32}
33
34impl S3Signer {
35    pub fn new(
36        bucket: &str,
37        region: &str,
38        access_key_id: impl Into<String>,
39        secret_access_key: impl Into<String>,
40    ) -> Self {
41        Self {
42            bucket: bucket.to_owned(),
43            scheme: "https".to_owned(),
44            host: format!("{bucket}.s3.{region}.amazonaws.com"),
45            path_style: false,
46            region: region.to_owned(),
47            access_key_id: access_key_id.into(),
48            secret_access_key: secret_access_key.into(),
49        }
50    }
51
52    /// From `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION` and
53    /// the bucket; `None` if any is missing.
54    pub fn from_env(bucket: &str) -> Option<Self> {
55        let var = |name| std::env::var(name).ok().filter(|v: &String| !v.is_empty());
56        Some(Self::new(
57            bucket,
58            &var("AWS_REGION")?,
59            var("AWS_ACCESS_KEY_ID")?,
60            var("AWS_SECRET_ACCESS_KEY")?,
61        ))
62    }
63
64    /// Signs for another host name, with the bucket still in it.
65    pub fn with_host(mut self, host: impl Into<String>) -> Self {
66        self.host = host.into();
67        self
68    }
69
70    /// Talks to another S3-compatible service, with `/bucket/key` paths:
71    /// `with_endpoint("http://localhost:9000")` for a local MinIO.
72    pub fn with_endpoint(mut self, endpoint: &str) -> Self {
73        let (scheme, host) = endpoint.split_once("://").unwrap_or(("https", endpoint));
74        self.scheme = scheme.to_owned();
75        self.host = host.trim_end_matches('/').to_owned();
76        self.path_style = true;
77        self
78    }
79
80    /// The object's path on the host: `/key`, or `/bucket/key`.
81    fn path(&self, key: &str) -> String {
82        let key = encode(key.trim_start_matches('/'), false);
83        if self.path_style {
84            format!("/{}/{key}", self.bucket)
85        } else {
86            format!("/{key}")
87        }
88    }
89
90    /// A URL for `key` that works for `expires_in` seconds from now.
91    pub fn presigned_url(&self, key: &str, expires_in: u64) -> String {
92        self.presigned_url_at(key, expires_in, chrono::Utc::now())
93    }
94
95    /// A URL a browser can `PUT` a file to as `key`, for `expires_in`
96    /// seconds: a direct upload, so the bytes skip the app's server.
97    pub fn presigned_upload_url(&self, key: &str, expires_in: u64) -> String {
98        self.presigned("PUT", key, expires_in, chrono::Utc::now())
99    }
100
101    /// A URL for `key` signed as at `now`.
102    pub fn presigned_url_at(
103        &self,
104        key: &str,
105        expires_in: u64,
106        now: chrono::DateTime<chrono::Utc>,
107    ) -> String {
108        self.presigned("GET", key, expires_in, now)
109    }
110
111    fn presigned(
112        &self,
113        method: &str,
114        key: &str,
115        expires_in: u64,
116        now: chrono::DateTime<chrono::Utc>,
117    ) -> String {
118        let (date, timestamp, scope) = self.scope(now);
119        let credential = format!("{}/{scope}", self.access_key_id);
120        let path = self.path(key);
121        let query = format!(
122            "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={}&X-Amz-Date={timestamp}\
123             &X-Amz-Expires={expires_in}&X-Amz-SignedHeaders=host",
124            encode(&credential, true)
125        );
126        let canonical = format!(
127            "{method}\n{path}\n{query}\nhost:{}\n\nhost\nUNSIGNED-PAYLOAD",
128            self.host
129        );
130        let signature = self.signature(&date, &timestamp, &scope, &canonical);
131        format!(
132            "{}://{}{path}?{query}&X-Amz-Signature={signature}",
133            self.scheme, self.host
134        )
135    }
136
137    /// The URL and headers for a `method` request on `key` whose body
138    /// hashes to `payload_sha256` (hex), signed as at `now`, with any
139    /// `extra` headers (lower-case names) signed too.
140    pub fn signed_request(
141        &self,
142        method: &str,
143        key: &str,
144        payload_sha256: &str,
145        extra: &[(&str, &str)],
146        now: chrono::DateTime<chrono::Utc>,
147    ) -> (String, Vec<(String, String)>) {
148        self.signed(method, &self.path(key), &[], payload_sha256, extra, now)
149    }
150
151    /// A signed request on the bucket itself, with a query: listing.
152    fn signed_bucket(
153        &self,
154        query: &[(&str, &str)],
155        now: chrono::DateTime<chrono::Utc>,
156    ) -> (String, Vec<(String, String)>) {
157        let path = if self.path_style {
158            format!("/{}", self.bucket)
159        } else {
160            "/".to_owned()
161        };
162        self.signed("GET", &path, query, EMPTY_SHA256, &[], now)
163    }
164
165    fn signed(
166        &self,
167        method: &str,
168        path: &str,
169        query: &[(&str, &str)],
170        payload_sha256: &str,
171        extra: &[(&str, &str)],
172        now: chrono::DateTime<chrono::Utc>,
173    ) -> (String, Vec<(String, String)>) {
174        let (date, timestamp, scope) = self.scope(now);
175        let mut query: Vec<(String, String)> = query
176            .iter()
177            .map(|(k, v)| (encode(k, true), encode(v, true)))
178            .collect();
179        query.sort();
180        let query = query
181            .iter()
182            .map(|(k, v)| format!("{k}={v}"))
183            .collect::<Vec<_>>()
184            .join("&");
185        let mut headers: Vec<(String, String)> = vec![
186            ("host".into(), self.host.clone()),
187            ("x-amz-content-sha256".into(), payload_sha256.to_owned()),
188            ("x-amz-date".into(), timestamp.clone()),
189        ];
190        headers.extend(
191            extra
192                .iter()
193                .map(|(n, v)| ((*n).to_owned(), (*v).trim().to_owned())),
194        );
195        headers.sort();
196        let names = headers
197            .iter()
198            .map(|(n, _)| n.as_str())
199            .collect::<Vec<_>>()
200            .join(";");
201        let lines: String = headers.iter().map(|(n, v)| format!("{n}:{v}\n")).collect();
202        let canonical = format!("{method}\n{path}\n{query}\n{lines}\n{names}\n{payload_sha256}");
203        let signature = self.signature(&date, &timestamp, &scope, &canonical);
204        let authorization = format!(
205            "AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={names}, Signature={signature}",
206            self.access_key_id
207        );
208        headers.retain(|(n, _)| n != "host");
209        headers.push(("authorization".into(), authorization));
210        let url = if query.is_empty() {
211            format!("{}://{}{path}", self.scheme, self.host)
212        } else {
213            format!("{}://{}{path}?{query}", self.scheme, self.host)
214        };
215        (url, headers)
216    }
217
218    fn scope(&self, now: chrono::DateTime<chrono::Utc>) -> (String, String, String) {
219        let date = now.format("%Y%m%d").to_string();
220        let timestamp = now.format("%Y%m%dT%H%M%SZ").to_string();
221        let scope = format!("{date}/{}/s3/aws4_request", self.region);
222        (date, timestamp, scope)
223    }
224
225    fn signature(&self, date: &str, timestamp: &str, scope: &str, canonical: &str) -> String {
226        let to_sign = format!(
227            "AWS4-HMAC-SHA256\n{timestamp}\n{scope}\n{}",
228            hex(&Sha256::digest(canonical.as_bytes()))
229        );
230        hex(&hmac(&self.signing_key(date), to_sign.as_bytes()))
231    }
232
233    /// The day's key: the secret, HMAC'd with the date, region and service.
234    fn signing_key(&self, date: &str) -> Vec<u8> {
235        [date, &self.region, "s3", "aws4_request"].iter().fold(
236            format!("AWS4{}", self.secret_access_key).into_bytes(),
237            |key, part| hmac(&key, part.as_bytes()),
238        )
239    }
240}
241
242/// What a presigned `POST` allows: how long the form works, how big the
243/// file may be, and what type it must be. S3 refuses an upload outside
244/// them.
245#[derive(Debug, Clone)]
246pub struct PostPolicy {
247    expires_in: u64,
248    size: Option<(u64, u64)>,
249    content_type: Option<ContentType>,
250    redirect: Option<String>,
251}
252
253#[derive(Debug, Clone)]
254enum ContentType {
255    Exactly(String),
256    StartsWith(String),
257}
258
259impl PostPolicy {
260    /// A form that works for `expires_in` seconds.
261    pub fn new(expires_in: u64) -> Self {
262        Self {
263            expires_in,
264            size: None,
265            content_type: None,
266            redirect: None,
267        }
268    }
269
270    /// Files of at most `bytes`.
271    #[must_use]
272    pub fn max_size(mut self, bytes: u64) -> Self {
273        self.size = Some((self.size.map_or(0, |(min, _)| min), bytes));
274        self
275    }
276
277    /// Files of `min` to `max` bytes.
278    #[must_use]
279    pub fn size_between(mut self, min: u64, max: u64) -> Self {
280        self.size = Some((min, max));
281        self
282    }
283
284    /// Exactly this type, sent as the form's `Content-Type` field.
285    #[must_use]
286    pub fn content_type(mut self, content_type: &str) -> Self {
287        self.content_type = Some(ContentType::Exactly(content_type.to_owned()));
288        self
289    }
290
291    /// Where S3 sends the browser after the upload (`303`), with
292    /// `bucket`, `key` and `etag` in the query: a plain HTML form then
293    /// needs no JavaScript.
294    #[must_use]
295    pub fn redirect(mut self, url: &str) -> Self {
296        self.redirect = Some(url.to_owned());
297        self
298    }
299
300    /// A type starting with `prefix` (`"image/"`); the page sets the
301    /// form's `Content-Type` field to the file's type.
302    #[must_use]
303    pub fn content_type_starts_with(mut self, prefix: &str) -> Self {
304        self.content_type = Some(ContentType::StartsWith(prefix.to_owned()));
305        self
306    }
307}
308
309/// A form a browser can send a file to: `POST` `url` as
310/// `multipart/form-data`, with `fields` first and the file last, in a
311/// field named `file`.
312#[derive(Debug, Clone, serde::Serialize)]
313pub struct PresignedPost {
314    pub url: String,
315    pub fields: Vec<(String, String)>,
316}
317
318impl S3Signer {
319    /// A form a browser can `POST` a file to as `key`, directly to S3, as
320    /// Rails' and Laravel's direct uploads do; S3 checks the file against
321    /// `policy`. A key ending `${filename}` (`uploads/7/${filename}`)
322    /// lets the form name the file: any key starting with what's before it.
323    pub fn presigned_post(&self, key: &str, policy: &PostPolicy) -> PresignedPost {
324        self.presigned_post_at(key, policy, chrono::Utc::now())
325    }
326
327    /// A presigned `POST` as at `now`.
328    pub fn presigned_post_at(
329        &self,
330        key: &str,
331        policy: &PostPolicy,
332        now: chrono::DateTime<chrono::Utc>,
333    ) -> PresignedPost {
334        let (date, timestamp, scope) = self.scope(now);
335        let credential = format!("{}/{scope}", self.access_key_id);
336        let key = key.trim_start_matches('/');
337        let expiration = (now
338            + chrono::TimeDelta::seconds(i64::try_from(policy.expires_in).unwrap_or(i64::MAX / 2)))
339        .format("%Y-%m-%dT%H:%M:%S%.3fZ")
340        .to_string();
341        let mut conditions = vec![serde_json::json!({ "bucket": self.bucket })];
342        match key.strip_suffix("${filename}") {
343            Some(prefix) => conditions.push(serde_json::json!(["starts-with", "$key", prefix])),
344            None => conditions.push(serde_json::json!({ "key": key })),
345        }
346        let mut fields = vec![("key".to_owned(), key.to_owned())];
347        match &policy.content_type {
348            Some(ContentType::Exactly(content_type)) => {
349                conditions.push(serde_json::json!({ "Content-Type": content_type }));
350                fields.push(("Content-Type".to_owned(), content_type.clone()));
351            }
352            Some(ContentType::StartsWith(prefix)) => {
353                conditions.push(serde_json::json!(["starts-with", "$Content-Type", prefix]));
354            }
355            None => {}
356        }
357        if let Some(url) = &policy.redirect {
358            conditions.push(serde_json::json!({ "success_action_redirect": url }));
359            fields.push(("success_action_redirect".to_owned(), url.clone()));
360        }
361        if let Some((min, max)) = policy.size {
362            conditions.push(serde_json::json!(["content-length-range", min, max]));
363        }
364        conditions.push(serde_json::json!({ "x-amz-algorithm": "AWS4-HMAC-SHA256" }));
365        conditions.push(serde_json::json!({ "x-amz-credential": credential }));
366        conditions.push(serde_json::json!({ "x-amz-date": timestamp }));
367        let document = serde_json::json!({ "expiration": expiration, "conditions": conditions });
368        let encoded = base64::engine::general_purpose::STANDARD.encode(document.to_string());
369        let signature = hex(&hmac(&self.signing_key(&date), encoded.as_bytes()));
370        fields.extend([
371            ("x-amz-algorithm".to_owned(), "AWS4-HMAC-SHA256".to_owned()),
372            ("x-amz-credential".to_owned(), credential),
373            ("x-amz-date".to_owned(), timestamp),
374            ("policy".to_owned(), encoded),
375            ("x-amz-signature".to_owned(), signature),
376        ]);
377        let url = if self.path_style {
378            format!("{}://{}/{}", self.scheme, self.host, self.bucket)
379        } else {
380            format!("{}://{}/", self.scheme, self.host)
381        };
382        PresignedPost { url, fields }
383    }
384}
385
386/// Where uploaded files are kept: a folder (development, tests) or an S3
387/// bucket. Keys are paths such as `comments/12/thumb/shelf.png`.
388#[derive(Debug, Clone)]
389pub enum Store {
390    Disk(std::path::PathBuf),
391    S3(S3Signer),
392}
393
394impl Store {
395    /// Saves `bytes` as `key`.
396    ///
397    /// # Errors
398    ///
399    /// If the folder can't be written, or S3 refuses or can't be reached.
400    pub async fn put(&self, key: &str, bytes: Bytes, content_type: &str) -> Result<()> {
401        match self {
402            Store::Disk(root) => {
403                let path = disk_path(root, key)?;
404                if let Some(dir) = path.parent() {
405                    tokio::fs::create_dir_all(dir).await.map_err(io_error)?;
406                }
407                tokio::fs::write(&path, &bytes).await.map_err(io_error)
408            }
409            Store::S3(s3) => {
410                let hash = hex(&Sha256::digest(&bytes));
411                let (url, headers) = s3.signed_request(
412                    "PUT",
413                    key,
414                    &hash,
415                    &[("content-type", content_type)],
416                    chrono::Utc::now(),
417                );
418                send(reqwest::Method::PUT, &url, headers, Some(bytes))
419                    .await
420                    .map(|_| ())
421            }
422        }
423    }
424
425    /// The file saved as `key`, if there is one.
426    ///
427    /// # Errors
428    ///
429    /// If it can't be read, or S3 can't be reached.
430    pub async fn get(&self, key: &str) -> Result<Option<Bytes>> {
431        match self {
432            Store::Disk(root) => match tokio::fs::read(disk_path(root, key)?).await {
433                Ok(bytes) => Ok(Some(bytes.into())),
434                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
435                Err(e) => Err(io_error(e)),
436            },
437            Store::S3(s3) => {
438                let (url, headers) = s3.signed_request(
439                    "GET",
440                    key,
441                    &hex(&Sha256::digest(b"")),
442                    &[],
443                    chrono::Utc::now(),
444                );
445                send(reqwest::Method::GET, &url, headers, None).await
446            }
447        }
448    }
449
450    /// Removes `key`; removing a missing file is fine.
451    ///
452    /// # Errors
453    ///
454    /// If it can't be removed, or S3 can't be reached.
455    pub async fn delete(&self, key: &str) -> Result<()> {
456        match self {
457            Store::Disk(root) => match tokio::fs::remove_file(disk_path(root, key)?).await {
458                Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(io_error(e)),
459                _ => Ok(()),
460            },
461            Store::S3(s3) => {
462                let (url, headers) = s3.signed_request(
463                    "DELETE",
464                    key,
465                    &hex(&Sha256::digest(b"")),
466                    &[],
467                    chrono::Utc::now(),
468                );
469                send(reqwest::Method::DELETE, &url, headers, None)
470                    .await
471                    .map(|_| ())
472            }
473        }
474    }
475
476    /// Whether a file is saved as `key`.
477    ///
478    /// # Errors
479    ///
480    /// If the folder can't be read, or S3 can't be reached.
481    pub async fn exists(&self, key: &str) -> Result<bool> {
482        Ok(self.size(key).await?.is_some())
483    }
484
485    /// The size in bytes of the file saved as `key`, if there is one.
486    ///
487    /// # Errors
488    ///
489    /// If the folder can't be read, or S3 can't be reached.
490    pub async fn size(&self, key: &str) -> Result<Option<u64>> {
491        match self {
492            Store::Disk(root) => match tokio::fs::metadata(disk_path(root, key)?).await {
493                Ok(meta) if meta.is_file() => Ok(Some(meta.len())),
494                Ok(_) => Ok(None),
495                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
496                Err(e) => Err(io_error(e)),
497            },
498            Store::S3(s3) => {
499                let (url, headers) =
500                    s3.signed_request("HEAD", key, EMPTY_SHA256, &[], chrono::Utc::now());
501                Ok(request(reqwest::Method::HEAD, &url, headers, None)
502                    .await?
503                    .map(|(headers, _)| {
504                        headers
505                            .get(reqwest::header::CONTENT_LENGTH)
506                            .and_then(|v| v.to_str().ok())
507                            .and_then(|v| v.parse().ok())
508                            .unwrap_or(0)
509                    }))
510            }
511        }
512    }
513
514    /// Copies the file saved as `from` to `to`, in the store.
515    ///
516    /// # Errors
517    ///
518    /// If `from` is missing, or the copy fails.
519    pub async fn copy(&self, from: &str, to: &str) -> Result<()> {
520        match self {
521            Store::Disk(root) => {
522                let (from, to) = (disk_path(root, from)?, disk_path(root, to)?);
523                if let Some(dir) = to.parent() {
524                    tokio::fs::create_dir_all(dir).await.map_err(io_error)?;
525                }
526                tokio::fs::copy(&from, &to)
527                    .await
528                    .map_err(io_error)
529                    .map(|_| ())
530            }
531            Store::S3(s3) => {
532                let source = format!(
533                    "/{}/{}",
534                    s3.bucket,
535                    encode(from.trim_start_matches('/'), false)
536                );
537                let (url, headers) = s3.signed_request(
538                    "PUT",
539                    to,
540                    EMPTY_SHA256,
541                    &[("x-amz-copy-source", &source)],
542                    chrono::Utc::now(),
543                );
544                match request(reqwest::Method::PUT, &url, headers, None).await? {
545                    Some(_) => Ok(()),
546                    None => Err(Error::internal(format!(
547                        "file storage: no file `{from}` to copy"
548                    ))),
549                }
550            }
551        }
552    }
553
554    /// Moves the file saved as `from` to `to` (`move` is Rust's keyword).
555    ///
556    /// # Errors
557    ///
558    /// If `from` is missing, or the move fails.
559    pub async fn rename(&self, from: &str, to: &str) -> Result<()> {
560        match self {
561            Store::Disk(root) => {
562                let (from, to) = (disk_path(root, from)?, disk_path(root, to)?);
563                if let Some(dir) = to.parent() {
564                    tokio::fs::create_dir_all(dir).await.map_err(io_error)?;
565                }
566                tokio::fs::rename(&from, &to).await.map_err(io_error)
567            }
568            Store::S3(_) => {
569                self.copy(from, to).await?;
570                self.delete(from).await
571            }
572        }
573    }
574
575    /// The keys of every file under `prefix` (`""` for all), sorted:
576    /// `list("comments/12/")`.
577    ///
578    /// # Errors
579    ///
580    /// If the folder can't be read, or S3 can't be reached.
581    pub async fn list(&self, prefix: &str) -> Result<Vec<String>> {
582        let prefix = prefix.trim_start_matches('/');
583        let mut keys = match self {
584            Store::Disk(root) => {
585                let mut keys = Vec::new();
586                let mut dirs = vec![root.clone()];
587                while let Some(dir) = dirs.pop() {
588                    let mut entries = match tokio::fs::read_dir(&dir).await {
589                        Ok(entries) => entries,
590                        Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
591                        Err(e) => return Err(io_error(e)),
592                    };
593                    while let Some(entry) = entries.next_entry().await.map_err(io_error)? {
594                        let path = entry.path();
595                        if entry.file_type().await.map_err(io_error)?.is_dir() {
596                            dirs.push(path);
597                        } else if let Ok(relative) = path.strip_prefix(root) {
598                            let key = relative
599                                .components()
600                                .map(|c| c.as_os_str().to_string_lossy())
601                                .collect::<Vec<_>>()
602                                .join("/");
603                            if key.starts_with(prefix) {
604                                keys.push(key);
605                            }
606                        }
607                    }
608                }
609                keys
610            }
611            Store::S3(s3) => {
612                let mut keys = Vec::new();
613                let mut token: Option<String> = None;
614                loop {
615                    let mut query = vec![("list-type", "2"), ("prefix", prefix)];
616                    if let Some(token) = &token {
617                        query.push(("continuation-token", token));
618                    }
619                    let (url, headers) = s3.signed_bucket(&query, chrono::Utc::now());
620                    let body = request(reqwest::Method::GET, &url, headers, None)
621                        .await?
622                        .map(|(_, body)| String::from_utf8_lossy(&body).into_owned())
623                        .unwrap_or_default();
624                    keys.extend(xml_values(&body, "Key"));
625                    token = xml_values(&body, "NextContinuationToken")
626                        .into_iter()
627                        .next();
628                    if !body.contains("<IsTruncated>true</IsTruncated>") || token.is_none() {
629                        break;
630                    }
631                }
632                keys
633            }
634        };
635        keys.sort();
636        Ok(keys)
637    }
638
639    /// A link to `key` that works for `expires_in` seconds and no longer,
640    /// for a private file: a presigned URL on S3, or on disk
641    /// `/files/<key>?token=…`, which [`SignedFiles`](crate::files::SignedFiles)
642    /// serves.
643    pub fn signed_url(&self, key: &str, expires_in: u64) -> String {
644        match self {
645            Store::Disk(_) => {
646                let key = key.trim_start_matches('/');
647                let expires = crate::time::now().timestamp()
648                    + i64::try_from(expires_in).unwrap_or(i64::MAX / 2);
649                let token =
650                    crate::auth::sign_message("file", &crate::files::signed_text(key, expires));
651                crate::router::prefixed(format!(
652                    "{}{}?token={token}",
653                    crate::files::SIGNED_PREFIX,
654                    crate::router::encode_path(key)
655                ))
656            }
657            Store::S3(s3) => s3.presigned_url(key, expires_in),
658        }
659    }
660
661    /// A URL a client can fetch `key` from for `expires_in` seconds: a
662    /// presigned S3 URL, or the key's path under `/uploads` on disk.
663    pub fn url(&self, key: &str, expires_in: u64) -> String {
664        match self {
665            Store::Disk(_) => format!("/uploads/{}", key.trim_start_matches('/')),
666            Store::S3(s3) => s3.presigned_url(key, expires_in),
667        }
668    }
669}
670
671static CURRENT: std::sync::RwLock<Option<Store>> = std::sync::RwLock::new(None);
672
673/// The app's store, from `[storage]` in the config: an S3 bucket when
674/// `bucket` is set (with `AWS_REGION`, `AWS_ACCESS_KEY_ID` and
675/// `AWS_SECRET_ACCESS_KEY`, and `endpoint` for MinIO and the like),
676/// otherwise the folder in `root`, `storage` by default. Attachments
677/// (`has_attached`) keep their files here.
678pub fn current() -> Store {
679    CURRENT
680        .read()
681        .unwrap_or_else(|e| e.into_inner())
682        .clone()
683        .unwrap_or_else(|| Store::Disk("storage".into()))
684}
685
686/// Makes `store` the app's store, as `[storage]` in the config does.
687pub fn set_current(store: Store) {
688    *CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(store);
689}
690
691/// The store `[storage]` describes, if it describes one.
692///
693/// # Errors
694///
695/// When `bucket` is set without the AWS variables.
696pub fn from_config(config: &crate::Config) -> Result<Option<Store>> {
697    if let Some(bucket) = config.get_opt::<String>("storage.bucket")? {
698        let mut s3 = S3Signer::from_env(&bucket).ok_or_else(|| {
699            Error::internal(
700                "storage.bucket needs AWS_REGION, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY",
701            )
702        })?;
703        if let Some(endpoint) = config.get_opt::<String>("storage.endpoint")? {
704            s3 = s3.with_endpoint(&endpoint);
705        }
706        return Ok(Some(Store::S3(s3)));
707    }
708    Ok(config
709        .get_opt::<String>("storage.root")?
710        .map(|root| Store::Disk(root.into())))
711}
712
713/// Another store, as `[storage.<name>]` in the config describes it (a
714/// `bucket`, or a `root` folder, `storage/<name>` by default):
715/// `storage::named("avatars")?`.
716///
717/// # Errors
718///
719/// When it names a bucket without the AWS variables, or outside an app.
720pub fn named(name: &str) -> Result<Store> {
721    let config = crate::Config::current()?;
722    if let Some(bucket) = config.get_opt::<String>(&format!("storage.{name}.bucket"))? {
723        let mut s3 = S3Signer::from_env(&bucket).ok_or_else(|| {
724            Error::internal(format!(
725                "storage.{name}.bucket needs AWS_REGION, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY"
726            ))
727        })?;
728        if let Some(endpoint) = config.get_opt::<String>(&format!("storage.{name}.endpoint"))? {
729            s3 = s3.with_endpoint(&endpoint);
730        }
731        return Ok(Store::S3(s3));
732    }
733    let root = config
734        .get_opt::<String>(&format!("storage.{name}.root"))?
735        .map_or_else(|| std::path::Path::new("storage").join(name), Into::into);
736    Ok(Store::Disk(root))
737}
738
739/// Reads `[storage]`. `App::config` calls it.
740pub(crate) fn configure(config: &crate::Config) -> Result<()> {
741    if let Some(store) = from_config(config)? {
742        set_current(store);
743    }
744    Ok(())
745}
746
747/// `key` under `root`, refusing keys that climb out of it.
748fn disk_path(root: &std::path::Path, key: &str) -> Result<std::path::PathBuf> {
749    let key = key.trim_start_matches('/');
750    if key.split('/').any(|part| part == "..") {
751        return Err(Error::bad_request(format!("invalid file key: {key}")));
752    }
753    Ok(root.join(key))
754}
755
756fn io_error(e: std::io::Error) -> Error {
757    Error::internal(format!("file storage: {e}"))
758}
759
760/// The hash of an empty body.
761const EMPTY_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
762
763/// The text of each `<tag>…</tag>` in an S3 XML answer, unescaped.
764fn xml_values(xml: &str, tag: &str) -> Vec<String> {
765    let (open, close) = (format!("<{tag}>"), format!("</{tag}>"));
766    let mut values = Vec::new();
767    let mut rest = xml;
768    while let Some(start) = rest.find(&open) {
769        rest = &rest[start + open.len()..];
770        let Some(end) = rest.find(&close) else { break };
771        values.push(
772            rest[..end]
773                .replace("&lt;", "<")
774                .replace("&gt;", ">")
775                .replace("&quot;", "\"")
776                .replace("&apos;", "'")
777                .replace("&amp;", "&"),
778        );
779        rest = &rest[end + close.len()..];
780    }
781    values
782}
783
784/// Sends a signed S3 request: the body for a 2xx, `None` for a 404.
785async fn send(
786    method: reqwest::Method,
787    url: &str,
788    headers: Vec<(String, String)>,
789    body: Option<Bytes>,
790) -> Result<Option<Bytes>> {
791    Ok(request(method, url, headers, body)
792        .await?
793        .map(|(_, body)| body))
794}
795
796/// A signed S3 request: the headers and body for a 2xx, `None` for a 404.
797async fn request(
798    method: reqwest::Method,
799    url: &str,
800    headers: Vec<(String, String)>,
801    body: Option<Bytes>,
802) -> Result<Option<(reqwest::header::HeaderMap, Bytes)>> {
803    let client = reqwest::Client::new();
804    let mut request = client.request(method, url);
805    for (name, value) in headers {
806        request = request.header(name, value);
807    }
808    if let Some(body) = body {
809        request = request.body(body);
810    }
811    let response = request
812        .send()
813        .await
814        .map_err(|e| Error::internal(format!("S3: {e}")))?;
815    let status = response.status();
816    if status == reqwest::StatusCode::NOT_FOUND {
817        return Ok(None);
818    }
819    let headers = response.headers().clone();
820    let bytes = response
821        .bytes()
822        .await
823        .map_err(|e| Error::internal(format!("S3: {e}")))?;
824    if !status.is_success() {
825        return Err(Error::internal(format!(
826            "S3 answered {status}: {}",
827            String::from_utf8_lossy(&bytes)
828        )));
829    }
830    Ok(Some((headers, bytes)))
831}
832
833fn hmac(key: &[u8], data: &[u8]) -> Vec<u8> {
834    let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC takes any key");
835    mac.update(data);
836    mac.finalize().into_bytes().to_vec()
837}
838
839fn hex(bytes: &[u8]) -> String {
840    bytes.iter().map(|b| format!("{b:02x}")).collect()
841}
842
843/// AWS's URI encoding: unreserved characters stay, the rest are `%XX`;
844/// `/` stays in paths.
845fn encode(text: &str, slash: bool) -> String {
846    let mut out = String::new();
847    for byte in text.bytes() {
848        match byte {
849            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
850                out.push(byte as char);
851            }
852            b'/' if !slash => out.push('/'),
853            _ => out.push_str(&format!("%{byte:02X}")),
854        }
855    }
856    out
857}
858
859#[cfg(test)]
860mod tests {
861    use super::*;
862
863    async fn exercise(store: &Store) {
864        let put = |key: &'static str, body: &'static str| {
865            store.put(key, Bytes::from_static(body.as_bytes()), "text/plain")
866        };
867        put("a/one.txt", "one").await.unwrap();
868        put("a/b/two.txt", "two!").await.unwrap();
869        put("c.txt", "c").await.unwrap();
870        assert!(store.exists("a/one.txt").await.unwrap());
871        assert!(!store.exists("a/none.txt").await.unwrap());
872        assert_eq!(store.size("a/b/two.txt").await.unwrap(), Some(4));
873        assert_eq!(store.size("a/none.txt").await.unwrap(), None);
874        assert_eq!(
875            store.list("").await.unwrap(),
876            ["a/b/two.txt", "a/one.txt", "c.txt"]
877        );
878        assert_eq!(
879            store.list("a/").await.unwrap(),
880            ["a/b/two.txt", "a/one.txt"]
881        );
882        store.copy("a/one.txt", "d/copy.txt").await.unwrap();
883        assert_eq!(store.get("d/copy.txt").await.unwrap().unwrap(), "one");
884        assert!(store.exists("a/one.txt").await.unwrap());
885        store.rename("a/one.txt", "e/moved.txt").await.unwrap();
886        assert!(!store.exists("a/one.txt").await.unwrap());
887        assert_eq!(store.get("e/moved.txt").await.unwrap().unwrap(), "one");
888        assert!(store.copy("missing.txt", "x.txt").await.is_err());
889    }
890
891    #[tokio::test]
892    async fn a_folder_lists_copies_and_moves() {
893        let root = std::env::temp_dir().join(format!("glacier-store-{}", crate::random::token()));
894        exercise(&Store::Disk(root.clone())).await;
895        let _ = std::fs::remove_dir_all(root);
896    }
897
898    /// A tiny S3: objects in memory, `/bucket/key` paths, listing two keys
899    /// a page. It checks requests are signed, not the signatures.
900    async fn fake_s3() -> String {
901        use http_body_util::{BodyExt, Full};
902        use std::collections::BTreeMap;
903        use std::sync::{Arc, Mutex};
904        let objects: Arc<Mutex<BTreeMap<String, Bytes>>> = Arc::default();
905        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
906        let addr = listener.local_addr().unwrap();
907        tokio::spawn(async move {
908            loop {
909                let (stream, _) = listener.accept().await.unwrap();
910                let objects = objects.clone();
911                let service = hyper::service::service_fn(
912                    move |req: hyper::Request<hyper::body::Incoming>| {
913                        let objects = objects.clone();
914                        async move {
915                            assert!(req.headers().contains_key("authorization"));
916                            let method = req.method().clone();
917                            let path = req.uri().path().to_owned();
918                            let query = req.uri().query().unwrap_or("").to_owned();
919                            let copy = req
920                                .headers()
921                                .get("x-amz-copy-source")
922                                .map(|v| v.to_str().unwrap().to_owned());
923                            let body = req.into_body().collect().await.unwrap().to_bytes();
924                            let key = percent_encoding::percent_decode_str(
925                                path.trim_start_matches("/bucket").trim_start_matches('/'),
926                            )
927                            .decode_utf8_lossy()
928                            .into_owned();
929                            let mut objects = objects.lock().unwrap();
930                            let mut response = hyper::Response::builder();
931                            let body = match method.as_str() {
932                                "GET" if path == "/bucket" => {
933                                    let param = |name: &str| {
934                                        query.split('&').find_map(|pair| {
935                                            let (k, v) = pair.split_once('=')?;
936                                            (k == name).then(|| {
937                                                percent_encoding::percent_decode_str(v)
938                                                    .decode_utf8_lossy()
939                                                    .into_owned()
940                                            })
941                                        })
942                                    };
943                                    let prefix = param("prefix").unwrap_or_default();
944                                    let after = param("continuation-token").unwrap_or_default();
945                                    let keys: Vec<&String> = objects
946                                        .keys()
947                                        .filter(|k| k.starts_with(&prefix) && **k > after)
948                                        .collect();
949                                    let page = &keys[..keys.len().min(2)];
950                                    let mut xml = String::from("<ListBucketResult>");
951                                    for key in page {
952                                        xml.push_str(&format!(
953                                            "<Contents><Key>{key}</Key></Contents>"
954                                        ));
955                                    }
956                                    if keys.len() > 2 {
957                                        xml.push_str(&format!(
958                                        "<IsTruncated>true</IsTruncated><NextContinuationToken>{}</NextContinuationToken>",
959                                        page[1]
960                                    ));
961                                    }
962                                    xml.push_str("</ListBucketResult>");
963                                    Bytes::from(xml)
964                                }
965                                "PUT" => {
966                                    let value = match copy {
967                                        Some(source) => {
968                                            let source = percent_encoding::percent_decode_str(
969                                                source.trim_start_matches("/bucket/"),
970                                            )
971                                            .decode_utf8_lossy()
972                                            .into_owned();
973                                            objects.get(&source).cloned()
974                                        }
975                                        None => Some(body),
976                                    };
977                                    match value {
978                                        Some(value) => {
979                                            objects.insert(key, value);
980                                        }
981                                        None => response = response.status(404),
982                                    }
983                                    Bytes::new()
984                                }
985                                "GET" | "HEAD" => match objects.get(&key) {
986                                    Some(value) => {
987                                        response = response.header("content-length", value.len());
988                                        if method == "GET" {
989                                            value.clone()
990                                        } else {
991                                            Bytes::new()
992                                        }
993                                    }
994                                    None => {
995                                        response = response.status(404);
996                                        Bytes::new()
997                                    }
998                                },
999                                "DELETE" => {
1000                                    objects.remove(&key);
1001                                    response = response.status(204);
1002                                    Bytes::new()
1003                                }
1004                                _ => unreachable!(),
1005                            };
1006                            Ok::<_, std::convert::Infallible>(
1007                                response.body(Full::new(body)).unwrap(),
1008                            )
1009                        }
1010                    },
1011                );
1012                tokio::spawn(async move {
1013                    let io = hyper_util::rt::TokioIo::new(stream);
1014                    let _ = hyper::server::conn::http1::Builder::new()
1015                        .serve_connection(io, service)
1016                        .await;
1017                });
1018            }
1019        });
1020        format!("http://{addr}")
1021    }
1022
1023    #[test]
1024    fn signs_post_policies_as_aws_documents() {
1025        // AWS's "Example: Browser-Based Upload using HTTP POST (Using AWS
1026        // Signature Version 4)": the policy, base64, and its signature.
1027        let policy = "eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJzaWd2NGV4YW1wbGVidWNrZXQifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci91c2VyMS8iXSwNCiAgICB7ImFjbCI6ICJwdWJsaWMtcmVhZCJ9LA0KICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL3NpZ3Y0ZXhhbXBsZWJ1Y2tldC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiaW1hZ2UvIl0sDQogICAgeyJ4LWFtei1tZXRhLXV1aWQiOiAiMTQzNjUxMjM2NTEyNzQifSwNCiAgICB7IngtYW16LXNlcnZlci1zaWRlLWVuY3J5cHRpb24iOiAiQUVTMjU2In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIkeC1hbXotbWV0YS10YWciLCAiIl0sDQoNCiAgICB7IngtYW16LWNyZWRlbnRpYWwiOiAiQUtJQUlPU0ZPRE5ON0VYQU1QTEUvMjAxNTEyMjkvdXMtZWFzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LA0KICAgIHsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwNCiAgICB7IngtYW16LWRhdGUiOiAiMjAxNTEyMjlUMDAwMDAwWiIgfQ0KICBdDQp9";
1028        let s3 = S3Signer::new(
1029            "sigv4examplebucket",
1030            "us-east-1",
1031            "AKIAIOSFODNN7EXAMPLE",
1032            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
1033        );
1034        assert_eq!(
1035            hex(&hmac(&s3.signing_key("20151229"), policy.as_bytes())),
1036            "8afdbf4008c03f22c2cd3cdb72e4afbb1f6a588f3255ac628749a66d7f09699e"
1037        );
1038    }
1039
1040    #[test]
1041    fn a_presigned_post_carries_its_policy() {
1042        let s3 = example();
1043        let at = may_24_2013();
1044        let policy = PostPolicy::new(600)
1045            .max_size(5_000_000)
1046            .content_type_starts_with("image/")
1047            .redirect("https://app.example/uploaded");
1048        let post = s3.presigned_post_at("avatars/7/${filename}", &policy, at);
1049        assert_eq!(post.url, "https://examplebucket.s3.amazonaws.com/");
1050        let field = |name: &str| {
1051            post.fields
1052                .iter()
1053                .find(|(n, _)| n == name)
1054                .map(|(_, v)| v.clone())
1055                .unwrap_or_else(|| panic!("no field {name}: {:?}", post.fields))
1056        };
1057        assert_eq!(field("key"), "avatars/7/${filename}");
1058        assert_eq!(field("x-amz-date"), "20130524T000000Z");
1059        assert_eq!(
1060            field("success_action_redirect"),
1061            "https://app.example/uploaded"
1062        );
1063        let document: serde_json::Value = serde_json::from_slice(
1064            &base64::engine::general_purpose::STANDARD
1065                .decode(field("policy"))
1066                .unwrap(),
1067        )
1068        .unwrap();
1069        assert_eq!(document["expiration"], "2013-05-24T00:10:00.000Z");
1070        let conditions = document["conditions"].as_array().unwrap();
1071        assert!(conditions.contains(&serde_json::json!(["starts-with", "$key", "avatars/7/"])));
1072        assert!(conditions.contains(&serde_json::json!([
1073            "starts-with",
1074            "$Content-Type",
1075            "image/"
1076        ])));
1077        assert!(conditions.contains(&serde_json::json!(["content-length-range", 0, 5_000_000])));
1078        assert!(conditions.contains(&serde_json::json!({ "bucket": "examplebucket" })));
1079        assert_eq!(
1080            field("x-amz-signature"),
1081            hex(&hmac(
1082                &s3.signing_key("20130524"),
1083                field("policy").as_bytes()
1084            ))
1085        );
1086        // An exact key and type are fields of the form, and conditions.
1087        let post = s3.presigned_post_at(
1088            "a.pdf",
1089            &PostPolicy::new(60).content_type("application/pdf"),
1090            at,
1091        );
1092        assert!(
1093            post.fields
1094                .contains(&("Content-Type".to_owned(), "application/pdf".to_owned()))
1095        );
1096    }
1097
1098    #[test]
1099    fn presigns_uploads_with_put() {
1100        let s3 = example();
1101        let at = "2013-05-24T00:00:00Z".parse().unwrap();
1102        let get = s3.presigned("GET", "test.txt", 60, at);
1103        let put = s3.presigned("PUT", "test.txt", 60, at);
1104        let signature = |url: &str| url.rsplit_once("X-Amz-Signature=").unwrap().1.to_owned();
1105        assert_eq!(
1106            get.split_once("&X-Amz-Signature").unwrap().0,
1107            put.split_once("&X-Amz-Signature").unwrap().0
1108        );
1109        assert_ne!(signature(&get), signature(&put));
1110    }
1111
1112    #[tokio::test]
1113    async fn an_s3_bucket_lists_copies_and_moves() {
1114        let endpoint = fake_s3().await;
1115        let s3 = S3Signer::new("bucket", "us-east-1", "key", "secret").with_endpoint(&endpoint);
1116        exercise(&Store::S3(s3)).await;
1117    }
1118
1119    fn example() -> S3Signer {
1120        S3Signer::new(
1121            "examplebucket",
1122            "us-east-1",
1123            "AKIAIOSFODNN7EXAMPLE",
1124            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
1125        )
1126        .with_host("examplebucket.s3.amazonaws.com")
1127    }
1128
1129    fn may_24_2013() -> chrono::DateTime<chrono::Utc> {
1130        chrono::DateTime::parse_from_rfc3339("2013-05-24T00:00:00Z")
1131            .unwrap()
1132            .to_utc()
1133    }
1134
1135    #[test]
1136    fn signs_urls_as_aws_documents() {
1137        // AWS's "Authenticating Requests: Using Query Parameters" example.
1138        let url = example().presigned_url_at("test.txt", 86400, may_24_2013());
1139        assert!(url.starts_with("https://examplebucket.s3.amazonaws.com/test.txt?"));
1140        assert!(url.contains(
1141            "X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2Fus-east-1%2Fs3%2Faws4_request"
1142        ));
1143        assert!(url.ends_with(
1144            "&X-Amz-Signature=aeeed9bbccd4d02ee5c0109b86d86835f995330da4c265957d157751f604d404"
1145        ));
1146    }
1147
1148    #[test]
1149    fn signs_requests_as_aws_documents() {
1150        // AWS's "Authenticating Requests: Using the Authorization Header"
1151        // GET Object example.
1152        let empty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
1153        let (url, headers) = example().signed_request(
1154            "GET",
1155            "test.txt",
1156            empty,
1157            &[("range", "bytes=0-9")],
1158            may_24_2013(),
1159        );
1160        assert_eq!(url, "https://examplebucket.s3.amazonaws.com/test.txt");
1161        let authorization = &headers
1162            .iter()
1163            .find(|(n, _)| n == "authorization")
1164            .unwrap()
1165            .1;
1166        assert!(
1167            authorization.ends_with(
1168                "Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
1169            ),
1170            "{authorization}"
1171        );
1172        assert!(authorization.contains("SignedHeaders=host;range;x-amz-content-sha256;x-amz-date"));
1173    }
1174
1175    #[test]
1176    fn uses_path_style_for_other_endpoints() {
1177        let s3 = S3Signer::new("bucket", "eu-west-2", "id", "secret")
1178            .with_endpoint("http://localhost:9000");
1179        assert!(
1180            s3.presigned_url("a/b.png", 60)
1181                .starts_with("http://localhost:9000/bucket/a/b.png?")
1182        );
1183    }
1184
1185    #[tokio::test]
1186    async fn keeps_files_on_disk() {
1187        let root = std::env::temp_dir().join(format!("glacier-store-{}", std::process::id()));
1188        let store = Store::Disk(root.clone());
1189        store
1190            .put(
1191                "comments/1/original/a.png",
1192                Bytes::from_static(b"png"),
1193                "image/png",
1194            )
1195            .await
1196            .unwrap();
1197        assert_eq!(
1198            store
1199                .get("comments/1/original/a.png")
1200                .await
1201                .unwrap()
1202                .as_deref(),
1203            Some(&b"png"[..])
1204        );
1205        assert_eq!(
1206            store.url("comments/1/original/a.png", 60),
1207            "/uploads/comments/1/original/a.png"
1208        );
1209        store.delete("comments/1/original/a.png").await.unwrap();
1210        assert!(
1211            store
1212                .get("comments/1/original/a.png")
1213                .await
1214                .unwrap()
1215                .is_none()
1216        );
1217        store.delete("missing").await.unwrap();
1218        assert!(
1219            store
1220                .put("../escape", Bytes::new(), "text/plain")
1221                .await
1222                .is_err()
1223        );
1224        std::fs::remove_dir_all(root).ok();
1225    }
1226}