use bytes::Bytes;
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
use crate::error::{Error, Result};
#[derive(Debug, Clone)]
pub struct S3Signer {
bucket: String,
scheme: String,
host: String,
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(),
}
}
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")?,
))
}
pub fn with_host(mut self, host: impl Into<String>) -> Self {
self.host = host.into();
self
}
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
}
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}")
}
}
pub fn presigned_url(&self, key: &str, expires_in: u64) -> String {
self.presigned_url_at(key, expires_in, chrono::Utc::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, ×tamp, &scope, &canonical);
format!(
"{}://{}{path}?{query}&X-Amz-Signature={signature}",
self.scheme, self.host
)
}
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, ×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));
(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()))
}
}
#[derive(Debug, Clone)]
pub enum Store {
Disk(std::path::PathBuf),
S3(S3Signer),
}
impl Store {
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(|_| ())
}
}
}
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
}
}
}
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(|_| ())
}
}
}
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);
pub fn current() -> Store {
CURRENT
.read()
.unwrap_or_else(|e| e.into_inner())
.clone()
.unwrap_or_else(|| Store::Disk("storage".into()))
}
pub fn set_current(store: Store) {
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(store);
}
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())))
}
pub(crate) fn configure(config: &crate::Config) -> Result<()> {
if let Some(store) = from_config(config)? {
set_current(store);
}
Ok(())
}
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}"))
}
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()
}
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() {
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() {
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();
}
}