//! 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 base64::Engine as _;
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 a browser can `PUT` a file to as `key`, for `expires_in`
/// seconds: a direct upload, so the bytes skip the app's server.
pub fn presigned_upload_url(&self, key: &str, expires_in: u64) -> String {
self.presigned("PUT", 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 {
self.presigned("GET", key, expires_in, now)
}
fn presigned(
&self,
method: &str,
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!(
"{method}\n{path}\n{query}\nhost:{}\n\nhost\nUNSIGNED-PAYLOAD",
self.host
);
let signature = self.signature(&date, ×tamp, &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)>) {
self.signed(method, &self.path(key), &[], payload_sha256, extra, now)
}
/// A signed request on the bucket itself, with a query: listing.
fn signed_bucket(
&self,
query: &[(&str, &str)],
now: chrono::DateTime<chrono::Utc>,
) -> (String, Vec<(String, String)>) {
let path = if self.path_style {
format!("/{}", self.bucket)
} else {
"/".to_owned()
};
self.signed("GET", &path, query, EMPTY_SHA256, &[], now)
}
fn signed(
&self,
method: &str,
path: &str,
query: &[(&str, &str)],
payload_sha256: &str,
extra: &[(&str, &str)],
now: chrono::DateTime<chrono::Utc>,
) -> (String, Vec<(String, String)>) {
let (date, timestamp, scope) = self.scope(now);
let mut query: Vec<(String, String)> = query
.iter()
.map(|(k, v)| (encode(k, true), encode(v, true)))
.collect();
query.sort();
let query = query
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect::<Vec<_>>()
.join("&");
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{query}\n{lines}\n{names}\n{payload_sha256}");
let signature = self.signature(&date, ×tamp, &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));
let url = if query.is_empty() {
format!("{}://{}{path}", self.scheme, self.host)
} else {
format!("{}://{}{path}?{query}", self.scheme, self.host)
};
(url, 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()))
);
hex(&hmac(&self.signing_key(date), to_sign.as_bytes()))
}
/// The day's key: the secret, HMAC'd with the date, region and service.
fn signing_key(&self, date: &str) -> Vec<u8> {
[date, &self.region, "s3", "aws4_request"].iter().fold(
format!("AWS4{}", self.secret_access_key).into_bytes(),
|key, part| hmac(&key, part.as_bytes()),
)
}
}
/// What a presigned `POST` allows: how long the form works, how big the
/// file may be, and what type it must be. S3 refuses an upload outside
/// them.
#[derive(Debug, Clone)]
pub struct PostPolicy {
expires_in: u64,
size: Option<(u64, u64)>,
content_type: Option<ContentType>,
redirect: Option<String>,
}
#[derive(Debug, Clone)]
enum ContentType {
Exactly(String),
StartsWith(String),
}
impl PostPolicy {
/// A form that works for `expires_in` seconds.
pub fn new(expires_in: u64) -> Self {
Self {
expires_in,
size: None,
content_type: None,
redirect: None,
}
}
/// Files of at most `bytes`.
#[must_use]
pub fn max_size(mut self, bytes: u64) -> Self {
self.size = Some((self.size.map_or(0, |(min, _)| min), bytes));
self
}
/// Files of `min` to `max` bytes.
#[must_use]
pub fn size_between(mut self, min: u64, max: u64) -> Self {
self.size = Some((min, max));
self
}
/// Exactly this type, sent as the form's `Content-Type` field.
#[must_use]
pub fn content_type(mut self, content_type: &str) -> Self {
self.content_type = Some(ContentType::Exactly(content_type.to_owned()));
self
}
/// Where S3 sends the browser after the upload (`303`), with
/// `bucket`, `key` and `etag` in the query: a plain HTML form then
/// needs no JavaScript.
#[must_use]
pub fn redirect(mut self, url: &str) -> Self {
self.redirect = Some(url.to_owned());
self
}
/// A type starting with `prefix` (`"image/"`); the page sets the
/// form's `Content-Type` field to the file's type.
#[must_use]
pub fn content_type_starts_with(mut self, prefix: &str) -> Self {
self.content_type = Some(ContentType::StartsWith(prefix.to_owned()));
self
}
}
/// A form a browser can send a file to: `POST` `url` as
/// `multipart/form-data`, with `fields` first and the file last, in a
/// field named `file`.
#[derive(Debug, Clone, serde::Serialize)]
pub struct PresignedPost {
pub url: String,
pub fields: Vec<(String, String)>,
}
impl S3Signer {
/// A form a browser can `POST` a file to as `key`, directly to S3, as
/// Rails' and Laravel's direct uploads do; S3 checks the file against
/// `policy`. A key ending `${filename}` (`uploads/7/${filename}`)
/// lets the form name the file: any key starting with what's before it.
pub fn presigned_post(&self, key: &str, policy: &PostPolicy) -> PresignedPost {
self.presigned_post_at(key, policy, chrono::Utc::now())
}
/// A presigned `POST` as at `now`.
pub fn presigned_post_at(
&self,
key: &str,
policy: &PostPolicy,
now: chrono::DateTime<chrono::Utc>,
) -> PresignedPost {
let (date, timestamp, scope) = self.scope(now);
let credential = format!("{}/{scope}", self.access_key_id);
let key = key.trim_start_matches('/');
let expiration = (now
+ chrono::TimeDelta::seconds(i64::try_from(policy.expires_in).unwrap_or(i64::MAX / 2)))
.format("%Y-%m-%dT%H:%M:%S%.3fZ")
.to_string();
let mut conditions = vec![serde_json::json!({ "bucket": self.bucket })];
match key.strip_suffix("${filename}") {
Some(prefix) => conditions.push(serde_json::json!(["starts-with", "$key", prefix])),
None => conditions.push(serde_json::json!({ "key": key })),
}
let mut fields = vec![("key".to_owned(), key.to_owned())];
match &policy.content_type {
Some(ContentType::Exactly(content_type)) => {
conditions.push(serde_json::json!({ "Content-Type": content_type }));
fields.push(("Content-Type".to_owned(), content_type.clone()));
}
Some(ContentType::StartsWith(prefix)) => {
conditions.push(serde_json::json!(["starts-with", "$Content-Type", prefix]));
}
None => {}
}
if let Some(url) = &policy.redirect {
conditions.push(serde_json::json!({ "success_action_redirect": url }));
fields.push(("success_action_redirect".to_owned(), url.clone()));
}
if let Some((min, max)) = policy.size {
conditions.push(serde_json::json!(["content-length-range", min, max]));
}
conditions.push(serde_json::json!({ "x-amz-algorithm": "AWS4-HMAC-SHA256" }));
conditions.push(serde_json::json!({ "x-amz-credential": credential }));
conditions.push(serde_json::json!({ "x-amz-date": timestamp }));
let document = serde_json::json!({ "expiration": expiration, "conditions": conditions });
let encoded = base64::engine::general_purpose::STANDARD.encode(document.to_string());
let signature = hex(&hmac(&self.signing_key(&date), encoded.as_bytes()));
fields.extend([
("x-amz-algorithm".to_owned(), "AWS4-HMAC-SHA256".to_owned()),
("x-amz-credential".to_owned(), credential),
("x-amz-date".to_owned(), timestamp),
("policy".to_owned(), encoded),
("x-amz-signature".to_owned(), signature),
]);
let url = if self.path_style {
format!("{}://{}/{}", self.scheme, self.host, self.bucket)
} else {
format!("{}://{}/", self.scheme, self.host)
};
PresignedPost { url, fields }
}
}
/// 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(|_| ())
}
}
}
/// Whether a file is saved as `key`.
///
/// # Errors
///
/// If the folder can't be read, or S3 can't be reached.
pub async fn exists(&self, key: &str) -> Result<bool> {
Ok(self.size(key).await?.is_some())
}
/// The size in bytes of the file saved as `key`, if there is one.
///
/// # Errors
///
/// If the folder can't be read, or S3 can't be reached.
pub async fn size(&self, key: &str) -> Result<Option<u64>> {
match self {
Store::Disk(root) => match tokio::fs::metadata(disk_path(root, key)?).await {
Ok(meta) if meta.is_file() => Ok(Some(meta.len())),
Ok(_) => Ok(None),
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("HEAD", key, EMPTY_SHA256, &[], chrono::Utc::now());
Ok(request(reqwest::Method::HEAD, &url, headers, None)
.await?
.map(|(headers, _)| {
headers
.get(reqwest::header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse().ok())
.unwrap_or(0)
}))
}
}
}
/// Copies the file saved as `from` to `to`, in the store.
///
/// # Errors
///
/// If `from` is missing, or the copy fails.
pub async fn copy(&self, from: &str, to: &str) -> Result<()> {
match self {
Store::Disk(root) => {
let (from, to) = (disk_path(root, from)?, disk_path(root, to)?);
if let Some(dir) = to.parent() {
tokio::fs::create_dir_all(dir).await.map_err(io_error)?;
}
tokio::fs::copy(&from, &to)
.await
.map_err(io_error)
.map(|_| ())
}
Store::S3(s3) => {
let source = format!(
"/{}/{}",
s3.bucket,
encode(from.trim_start_matches('/'), false)
);
let (url, headers) = s3.signed_request(
"PUT",
to,
EMPTY_SHA256,
&[("x-amz-copy-source", &source)],
chrono::Utc::now(),
);
match request(reqwest::Method::PUT, &url, headers, None).await? {
Some(_) => Ok(()),
None => Err(Error::internal(format!(
"file storage: no file `{from}` to copy"
))),
}
}
}
}
/// Moves the file saved as `from` to `to` (`move` is Rust's keyword).
///
/// # Errors
///
/// If `from` is missing, or the move fails.
pub async fn rename(&self, from: &str, to: &str) -> Result<()> {
match self {
Store::Disk(root) => {
let (from, to) = (disk_path(root, from)?, disk_path(root, to)?);
if let Some(dir) = to.parent() {
tokio::fs::create_dir_all(dir).await.map_err(io_error)?;
}
tokio::fs::rename(&from, &to).await.map_err(io_error)
}
Store::S3(_) => {
self.copy(from, to).await?;
self.delete(from).await
}
}
}
/// The keys of every file under `prefix` (`""` for all), sorted:
/// `list("comments/12/")`.
///
/// # Errors
///
/// If the folder can't be read, or S3 can't be reached.
pub async fn list(&self, prefix: &str) -> Result<Vec<String>> {
let prefix = prefix.trim_start_matches('/');
let mut keys = match self {
Store::Disk(root) => {
let mut keys = Vec::new();
let mut dirs = vec![root.clone()];
while let Some(dir) = dirs.pop() {
let mut entries = match tokio::fs::read_dir(&dir).await {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(io_error(e)),
};
while let Some(entry) = entries.next_entry().await.map_err(io_error)? {
let path = entry.path();
if entry.file_type().await.map_err(io_error)?.is_dir() {
dirs.push(path);
} else if let Ok(relative) = path.strip_prefix(root) {
let key = relative
.components()
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
if key.starts_with(prefix) {
keys.push(key);
}
}
}
}
keys
}
Store::S3(s3) => {
let mut keys = Vec::new();
let mut token: Option<String> = None;
loop {
let mut query = vec![("list-type", "2"), ("prefix", prefix)];
if let Some(token) = &token {
query.push(("continuation-token", token));
}
let (url, headers) = s3.signed_bucket(&query, chrono::Utc::now());
let body = request(reqwest::Method::GET, &url, headers, None)
.await?
.map(|(_, body)| String::from_utf8_lossy(&body).into_owned())
.unwrap_or_default();
keys.extend(xml_values(&body, "Key"));
token = xml_values(&body, "NextContinuationToken")
.into_iter()
.next();
if !body.contains("<IsTruncated>true</IsTruncated>") || token.is_none() {
break;
}
}
keys
}
};
keys.sort();
Ok(keys)
}
/// A link to `key` that works for `expires_in` seconds and no longer,
/// for a private file: a presigned URL on S3, or on disk
/// `/files/<key>?token=…`, which [`SignedFiles`](crate::files::SignedFiles)
/// serves.
pub fn signed_url(&self, key: &str, expires_in: u64) -> String {
match self {
Store::Disk(_) => {
let key = key.trim_start_matches('/');
let expires = crate::time::now().timestamp()
+ i64::try_from(expires_in).unwrap_or(i64::MAX / 2);
let token =
crate::auth::sign_message("file", &crate::files::signed_text(key, expires));
crate::router::prefixed(format!(
"{}{}?token={token}",
crate::files::SIGNED_PREFIX,
crate::router::encode_path(key)
))
}
Store::S3(s3) => s3.presigned_url(key, expires_in),
}
}
/// 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())))
}
/// Another store, as `[storage.<name>]` in the config describes it (a
/// `bucket`, or a `root` folder, `storage/<name>` by default):
/// `storage::named("avatars")?`.
///
/// # Errors
///
/// When it names a bucket without the AWS variables, or outside an app.
pub fn named(name: &str) -> Result<Store> {
let config = crate::Config::current()?;
if let Some(bucket) = config.get_opt::<String>(&format!("storage.{name}.bucket"))? {
let mut s3 = S3Signer::from_env(&bucket).ok_or_else(|| {
Error::internal(format!(
"storage.{name}.bucket needs AWS_REGION, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY"
))
})?;
if let Some(endpoint) = config.get_opt::<String>(&format!("storage.{name}.endpoint"))? {
s3 = s3.with_endpoint(&endpoint);
}
return Ok(Store::S3(s3));
}
let root = config
.get_opt::<String>(&format!("storage.{name}.root"))?
.map_or_else(|| std::path::Path::new("storage").join(name), Into::into);
Ok(Store::Disk(root))
}
/// 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}"))
}
/// The hash of an empty body.
const EMPTY_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
/// The text of each `<tag>…</tag>` in an S3 XML answer, unescaped.
fn xml_values(xml: &str, tag: &str) -> Vec<String> {
let (open, close) = (format!("<{tag}>"), format!("</{tag}>"));
let mut values = Vec::new();
let mut rest = xml;
while let Some(start) = rest.find(&open) {
rest = &rest[start + open.len()..];
let Some(end) = rest.find(&close) else { break };
values.push(
rest[..end]
.replace("<", "<")
.replace(">", ">")
.replace(""", "\"")
.replace("'", "'")
.replace("&", "&"),
);
rest = &rest[end + close.len()..];
}
values
}
/// 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>> {
Ok(request(method, url, headers, body)
.await?
.map(|(_, body)| body))
}
/// A signed S3 request: the headers and body for a 2xx, `None` for a 404.
async fn request(
method: reqwest::Method,
url: &str,
headers: Vec<(String, String)>,
body: Option<Bytes>,
) -> Result<Option<(reqwest::header::HeaderMap, 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 headers = response.headers().clone();
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((headers, 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::*;
async fn exercise(store: &Store) {
let put = |key: &'static str, body: &'static str| {
store.put(key, Bytes::from_static(body.as_bytes()), "text/plain")
};
put("a/one.txt", "one").await.unwrap();
put("a/b/two.txt", "two!").await.unwrap();
put("c.txt", "c").await.unwrap();
assert!(store.exists("a/one.txt").await.unwrap());
assert!(!store.exists("a/none.txt").await.unwrap());
assert_eq!(store.size("a/b/two.txt").await.unwrap(), Some(4));
assert_eq!(store.size("a/none.txt").await.unwrap(), None);
assert_eq!(
store.list("").await.unwrap(),
["a/b/two.txt", "a/one.txt", "c.txt"]
);
assert_eq!(
store.list("a/").await.unwrap(),
["a/b/two.txt", "a/one.txt"]
);
store.copy("a/one.txt", "d/copy.txt").await.unwrap();
assert_eq!(store.get("d/copy.txt").await.unwrap().unwrap(), "one");
assert!(store.exists("a/one.txt").await.unwrap());
store.rename("a/one.txt", "e/moved.txt").await.unwrap();
assert!(!store.exists("a/one.txt").await.unwrap());
assert_eq!(store.get("e/moved.txt").await.unwrap().unwrap(), "one");
assert!(store.copy("missing.txt", "x.txt").await.is_err());
}
#[tokio::test]
async fn a_folder_lists_copies_and_moves() {
let root = std::env::temp_dir().join(format!("glacier-store-{}", crate::random::token()));
exercise(&Store::Disk(root.clone())).await;
let _ = std::fs::remove_dir_all(root);
}
/// A tiny S3: objects in memory, `/bucket/key` paths, listing two keys
/// a page. It checks requests are signed, not the signatures.
async fn fake_s3() -> String {
use http_body_util::{BodyExt, Full};
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
let objects: Arc<Mutex<BTreeMap<String, Bytes>>> = Arc::default();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
loop {
let (stream, _) = listener.accept().await.unwrap();
let objects = objects.clone();
let service = hyper::service::service_fn(
move |req: hyper::Request<hyper::body::Incoming>| {
let objects = objects.clone();
async move {
assert!(req.headers().contains_key("authorization"));
let method = req.method().clone();
let path = req.uri().path().to_owned();
let query = req.uri().query().unwrap_or("").to_owned();
let copy = req
.headers()
.get("x-amz-copy-source")
.map(|v| v.to_str().unwrap().to_owned());
let body = req.into_body().collect().await.unwrap().to_bytes();
let key = percent_encoding::percent_decode_str(
path.trim_start_matches("/bucket").trim_start_matches('/'),
)
.decode_utf8_lossy()
.into_owned();
let mut objects = objects.lock().unwrap();
let mut response = hyper::Response::builder();
let body = match method.as_str() {
"GET" if path == "/bucket" => {
let param = |name: &str| {
query.split('&').find_map(|pair| {
let (k, v) = pair.split_once('=')?;
(k == name).then(|| {
percent_encoding::percent_decode_str(v)
.decode_utf8_lossy()
.into_owned()
})
})
};
let prefix = param("prefix").unwrap_or_default();
let after = param("continuation-token").unwrap_or_default();
let keys: Vec<&String> = objects
.keys()
.filter(|k| k.starts_with(&prefix) && **k > after)
.collect();
let page = &keys[..keys.len().min(2)];
let mut xml = String::from("<ListBucketResult>");
for key in page {
xml.push_str(&format!(
"<Contents><Key>{key}</Key></Contents>"
));
}
if keys.len() > 2 {
xml.push_str(&format!(
"<IsTruncated>true</IsTruncated><NextContinuationToken>{}</NextContinuationToken>",
page[1]
));
}
xml.push_str("</ListBucketResult>");
Bytes::from(xml)
}
"PUT" => {
let value = match copy {
Some(source) => {
let source = percent_encoding::percent_decode_str(
source.trim_start_matches("/bucket/"),
)
.decode_utf8_lossy()
.into_owned();
objects.get(&source).cloned()
}
None => Some(body),
};
match value {
Some(value) => {
objects.insert(key, value);
}
None => response = response.status(404),
}
Bytes::new()
}
"GET" | "HEAD" => match objects.get(&key) {
Some(value) => {
response = response.header("content-length", value.len());
if method == "GET" {
value.clone()
} else {
Bytes::new()
}
}
None => {
response = response.status(404);
Bytes::new()
}
},
"DELETE" => {
objects.remove(&key);
response = response.status(204);
Bytes::new()
}
_ => unreachable!(),
};
Ok::<_, std::convert::Infallible>(
response.body(Full::new(body)).unwrap(),
)
}
},
);
tokio::spawn(async move {
let io = hyper_util::rt::TokioIo::new(stream);
let _ = hyper::server::conn::http1::Builder::new()
.serve_connection(io, service)
.await;
});
}
});
format!("http://{addr}")
}
#[test]
fn signs_post_policies_as_aws_documents() {
// AWS's "Example: Browser-Based Upload using HTTP POST (Using AWS
// Signature Version 4)": the policy, base64, and its signature.
let policy = "eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJzaWd2NGV4YW1wbGVidWNrZXQifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci91c2VyMS8iXSwNCiAgICB7ImFjbCI6ICJwdWJsaWMtcmVhZCJ9LA0KICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL3NpZ3Y0ZXhhbXBsZWJ1Y2tldC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiaW1hZ2UvIl0sDQogICAgeyJ4LWFtei1tZXRhLXV1aWQiOiAiMTQzNjUxMjM2NTEyNzQifSwNCiAgICB7IngtYW16LXNlcnZlci1zaWRlLWVuY3J5cHRpb24iOiAiQUVTMjU2In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIkeC1hbXotbWV0YS10YWciLCAiIl0sDQoNCiAgICB7IngtYW16LWNyZWRlbnRpYWwiOiAiQUtJQUlPU0ZPRE5ON0VYQU1QTEUvMjAxNTEyMjkvdXMtZWFzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LA0KICAgIHsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwNCiAgICB7IngtYW16LWRhdGUiOiAiMjAxNTEyMjlUMDAwMDAwWiIgfQ0KICBdDQp9";
let s3 = S3Signer::new(
"sigv4examplebucket",
"us-east-1",
"AKIAIOSFODNN7EXAMPLE",
"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
);
assert_eq!(
hex(&hmac(&s3.signing_key("20151229"), policy.as_bytes())),
"8afdbf4008c03f22c2cd3cdb72e4afbb1f6a588f3255ac628749a66d7f09699e"
);
}
#[test]
fn a_presigned_post_carries_its_policy() {
let s3 = example();
let at = may_24_2013();
let policy = PostPolicy::new(600)
.max_size(5_000_000)
.content_type_starts_with("image/")
.redirect("https://app.example/uploaded");
let post = s3.presigned_post_at("avatars/7/${filename}", &policy, at);
assert_eq!(post.url, "https://examplebucket.s3.amazonaws.com/");
let field = |name: &str| {
post.fields
.iter()
.find(|(n, _)| n == name)
.map(|(_, v)| v.clone())
.unwrap_or_else(|| panic!("no field {name}: {:?}", post.fields))
};
assert_eq!(field("key"), "avatars/7/${filename}");
assert_eq!(field("x-amz-date"), "20130524T000000Z");
assert_eq!(
field("success_action_redirect"),
"https://app.example/uploaded"
);
let document: serde_json::Value = serde_json::from_slice(
&base64::engine::general_purpose::STANDARD
.decode(field("policy"))
.unwrap(),
)
.unwrap();
assert_eq!(document["expiration"], "2013-05-24T00:10:00.000Z");
let conditions = document["conditions"].as_array().unwrap();
assert!(conditions.contains(&serde_json::json!(["starts-with", "$key", "avatars/7/"])));
assert!(conditions.contains(&serde_json::json!([
"starts-with",
"$Content-Type",
"image/"
])));
assert!(conditions.contains(&serde_json::json!(["content-length-range", 0, 5_000_000])));
assert!(conditions.contains(&serde_json::json!({ "bucket": "examplebucket" })));
assert_eq!(
field("x-amz-signature"),
hex(&hmac(
&s3.signing_key("20130524"),
field("policy").as_bytes()
))
);
// An exact key and type are fields of the form, and conditions.
let post = s3.presigned_post_at(
"a.pdf",
&PostPolicy::new(60).content_type("application/pdf"),
at,
);
assert!(
post.fields
.contains(&("Content-Type".to_owned(), "application/pdf".to_owned()))
);
}
#[test]
fn presigns_uploads_with_put() {
let s3 = example();
let at = "2013-05-24T00:00:00Z".parse().unwrap();
let get = s3.presigned("GET", "test.txt", 60, at);
let put = s3.presigned("PUT", "test.txt", 60, at);
let signature = |url: &str| url.rsplit_once("X-Amz-Signature=").unwrap().1.to_owned();
assert_eq!(
get.split_once("&X-Amz-Signature").unwrap().0,
put.split_once("&X-Amz-Signature").unwrap().0
);
assert_ne!(signature(&get), signature(&put));
}
#[tokio::test]
async fn an_s3_bucket_lists_copies_and_moves() {
let endpoint = fake_s3().await;
let s3 = S3Signer::new("bucket", "us-east-1", "key", "secret").with_endpoint(&endpoint);
exercise(&Store::S3(s3)).await;
}
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();
}
}