use bytes::Bytes;
use chrono::Utc;
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use slabs_core::{id, SlabError, SlabResult};
use slabs_db::Db;
use std::fmt;
use std::path::PathBuf;
use std::time::Duration;
use tokio::fs;
type HmacSha256 = Hmac<Sha256>;
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct BlobMeta {
pub id: String,
pub filename: String,
pub content_type: String,
pub byte_size: i64,
pub checksum_sha256: String,
pub storage_key: String,
pub created_at: String,
}
#[derive(Clone)]
pub struct S3Config {
pub endpoint: String,
pub region: String,
pub bucket: String,
pub access_key_id: String,
pub secret_access_key: String,
}
impl fmt::Debug for S3Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("S3Config")
.field("endpoint", &self.endpoint)
.field("region", &self.region)
.field("bucket", &self.bucket)
.field("access_key_id", &self.access_key_id)
.field("secret_access_key", &"<redacted>")
.finish()
}
}
impl S3Config {
#[must_use]
pub fn from_env() -> Option<Self> {
let bucket = std::env::var("SLABS_S3_BUCKET")
.ok()
.filter(|s| !s.is_empty())?;
let access_key_id = std::env::var("SLABS_S3_ACCESS_KEY_ID").ok()?;
let secret_access_key = std::env::var("SLABS_S3_SECRET_ACCESS_KEY").ok()?;
let region = std::env::var("SLABS_S3_REGION").unwrap_or_else(|_| "us-east-1".into());
let endpoint = std::env::var("SLABS_S3_ENDPOINT")
.unwrap_or_else(|_| format!("https://s3.{region}.amazonaws.com"));
Some(Self {
endpoint: endpoint.trim_end_matches('/').to_string(),
region,
bucket,
access_key_id,
secret_access_key,
})
}
}
#[derive(Debug, Clone)]
pub enum StorageBackend {
Local {
root_dir: PathBuf,
},
S3(S3Config),
}
#[derive(Debug, Clone)]
pub struct Storage {
db: Db,
backend: StorageBackend,
http: reqwest::Client,
}
impl Storage {
#[must_use]
pub fn new(db: Db, root_dir: PathBuf) -> Self {
Self::with_backend(db, StorageBackend::Local { root_dir })
}
#[must_use]
pub fn with_backend(db: Db, backend: StorageBackend) -> Self {
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(30))
.build()
.expect("failed to build reqwest client");
Self { db, backend, http }
}
pub async fn put(
&self,
filename: &str,
content_type: Option<&str>,
data: Bytes,
) -> SlabResult<BlobMeta> {
let blob_id = id::new("blb");
let clean_name = filename
.rsplit(['/', '\\'])
.next()
.filter(|s| !s.is_empty())
.unwrap_or("upload.bin")
.to_string();
let resolved_ct = content_type.filter(|s| !s.is_empty()).map_or_else(
|| {
mime_guess::from_path(&clean_name)
.first_or_octet_stream()
.to_string()
},
ToString::to_string,
);
let checksum_sha256 = sha256_hex(&data);
let shard = &checksum_sha256[..2];
let storage_key = format!("{shard}/{blob_id}");
match &self.backend {
StorageBackend::Local { root_dir } => {
let disk_path = root_dir.join(&storage_key);
if let Some(parent) = disk_path.parent() {
fs::create_dir_all(parent).await.map_err(|e| {
SlabError::internal(format!("failed to create storage dir: {e}"))
})?;
}
fs::write(&disk_path, &data)
.await
.map_err(|e| SlabError::internal(format!("failed to write blob: {e}")))?;
}
StorageBackend::S3(s3) => {
self.s3_request(s3, "PUT", &storage_key, Some(&resolved_ct), data.clone())
.await?;
}
}
let created_at = Utc::now().to_rfc3339();
let byte_size = i64::try_from(data.len())
.map_err(|_| SlabError::bad_request("blob exceeds maximum size"))?;
sqlx::query(
"INSERT INTO slabs_blobs (id, filename, content_type, byte_size, checksum_sha256, storage_key, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)",
)
.bind(&blob_id)
.bind(&clean_name)
.bind(&resolved_ct)
.bind(byte_size)
.bind(&checksum_sha256)
.bind(&storage_key)
.bind(&created_at)
.execute(self.db.pool())
.await?;
Ok(BlobMeta {
id: blob_id,
filename: clean_name,
content_type: resolved_ct,
byte_size,
checksum_sha256,
storage_key,
created_at,
})
}
#[cfg(feature = "images")]
pub async fn put_resized_image(
&self,
filename: &str,
data: Bytes,
max_width: u32,
max_height: u32,
) -> SlabResult<BlobMeta> {
if max_width == 0 || max_height == 0 {
return Err(SlabError::bad_request(
"max_width and max_height must be greater than zero",
));
}
let buf = tokio::task::spawn_blocking(move || -> SlabResult<Vec<u8>> {
let img = image::load_from_memory(&data)
.map_err(|e| SlabError::bad_request(format!("invalid image data: {e}")))?;
let resized = img.thumbnail(max_width, max_height);
let mut cursor = std::io::Cursor::new(Vec::new());
resized
.write_to(&mut cursor, image::ImageFormat::Png)
.map_err(|e| SlabError::internal(format!("failed to encode resized image: {e}")))?;
Ok(cursor.into_inner())
})
.await
.map_err(|e| SlabError::internal(format!("image resize task failed: {e}")))??;
let base = filename
.rsplit(['/', '\\'])
.next()
.filter(|s| !s.is_empty())
.unwrap_or("image");
let stem = std::path::Path::new(base)
.file_stem()
.and_then(|s| s.to_str())
.filter(|s| !s.is_empty())
.unwrap_or("image");
let out_name = format!("{stem}.png");
self.put(&out_name, Some("image/png"), Bytes::from(buf))
.await
}
pub async fn get(&self, blob_id: &str) -> SlabResult<(BlobMeta, Bytes)> {
let meta: BlobMeta = sqlx::query_as(
"SELECT id, filename, content_type, byte_size, checksum_sha256, storage_key, created_at
FROM slabs_blobs
WHERE id = ?",
)
.bind(blob_id)
.fetch_optional(self.db.pool())
.await?
.ok_or_else(|| SlabError::not_found(format!("blob `{blob_id}` not found")))?;
let data = match &self.backend {
StorageBackend::Local { root_dir } => {
let disk_path = root_dir.join(&meta.storage_key);
let raw = fs::read(&disk_path).await.map_err(|e| {
SlabError::internal(format!("failed to read blob `{blob_id}`: {e}"))
})?;
Bytes::from(raw)
}
StorageBackend::S3(s3) => {
self.s3_request(s3, "GET", &meta.storage_key, None, Bytes::new())
.await?
}
};
Ok((meta, data))
}
pub async fn delete(&self, blob_id: &str) -> SlabResult<()> {
let meta: Option<(String,)> =
sqlx::query_as("SELECT storage_key FROM slabs_blobs WHERE id = ?")
.bind(blob_id)
.fetch_optional(self.db.pool())
.await?;
if let Some((storage_key,)) = meta {
sqlx::query("DELETE FROM slabs_blobs WHERE id = ?")
.bind(blob_id)
.execute(self.db.pool())
.await?;
match &self.backend {
StorageBackend::Local { root_dir } => {
let _ = fs::remove_file(root_dir.join(storage_key)).await;
}
StorageBackend::S3(s3) => {
let _ = self
.s3_request(s3, "DELETE", &storage_key, None, Bytes::new())
.await;
}
}
}
Ok(())
}
async fn s3_request(
&self,
s3: &S3Config,
method: &str,
key: &str,
content_type: Option<&str>,
body: Bytes,
) -> SlabResult<Bytes> {
let canonical_uri = format!("/{}/{}", s3.bucket, key.trim_start_matches('/'));
let url = format!("{}{}", s3.endpoint, canonical_uri);
let host = s3
.endpoint
.strip_prefix("https://")
.or_else(|| s3.endpoint.strip_prefix("http://"))
.unwrap_or(&s3.endpoint)
.split('/')
.next()
.unwrap_or("localhost");
let now = Utc::now();
let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
let date_stamp = now.format("%Y%m%d").to_string();
let payload_hash = sha256_hex(&body);
let canonical_headers =
format!("host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n");
let signed_headers = "host;x-amz-content-sha256;x-amz-date";
let canonical_request = format!(
"{method}\n{canonical_uri}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}"
);
let credential_scope = format!("{date_stamp}/{}/s3/aws4_request", s3.region);
let string_to_sign = format!(
"AWS4-HMAC-SHA256\n{amz_date}\n{credential_scope}\n{}",
sha256_hex(canonical_request.as_bytes())
);
let k_date = hmac_sha256(
format!("AWS4{}", s3.secret_access_key).as_bytes(),
date_stamp.as_bytes(),
);
let k_region = hmac_sha256(&k_date, s3.region.as_bytes());
let k_service = hmac_sha256(&k_region, b"s3");
let k_signing = hmac_sha256(&k_service, b"aws4_request");
let signature = hex::encode(hmac_sha256(&k_signing, string_to_sign.as_bytes()));
let authorization = format!(
"AWS4-HMAC-SHA256 Credential={}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}",
s3.access_key_id
);
let mut req = match method {
"PUT" => self.http.put(&url),
"DELETE" => self.http.delete(&url),
_ => self.http.get(&url),
}
.header("host", host)
.header("x-amz-date", &amz_date)
.header("x-amz-content-sha256", &payload_hash)
.header("authorization", &authorization);
if let Some(ct) = content_type {
req = req.header("content-type", ct);
}
if !body.is_empty() {
req = req.body(body);
}
let resp = req
.send()
.await
.map_err(|e| SlabError::internal(format!("s3 {method} failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
let err_body = resp.text().await.unwrap_or_default();
return Err(SlabError::internal(format!(
"s3 {method} error {status}: {err_body}"
)));
}
resp.bytes()
.await
.map_err(|e| SlabError::internal(format!("s3 read body failed: {e}")))
}
}
fn sha256_hex(data: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(data);
hex::encode(hasher.finalize())
}
fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts keys of any size");
mac.update(data);
mac.finalize().into_bytes().to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
extract::{Path, State},
http::{HeaderMap, StatusCode},
routing::put,
Router,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
type MockS3Store = Arc<Mutex<HashMap<String, (String, Bytes)>>>;
#[tokio::test]
async fn s3_sigv4_put_get_delete_roundtrip() {
let store: MockS3Store = Arc::new(Mutex::new(HashMap::new()));
let app =
Router::new()
.route(
"/{bucket}/{*key}",
put(
|State(st): State<MockS3Store>,
Path((bucket, key)): Path<(String, String)>,
headers: HeaderMap,
body: Bytes| async move {
let auth = headers
.get("authorization")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string();
assert!(auth.starts_with("AWS4-HMAC-SHA256 Credential=ak_test/"));
assert!(headers.contains_key("x-amz-content-sha256"));
st.lock()
.unwrap()
.insert(format!("{bucket}/{key}"), (auth, body));
StatusCode::OK
},
)
.get(
|State(st): State<MockS3Store>,
Path((bucket, key)): Path<(String, String)>| async move {
match st.lock().unwrap().get(&format!("{bucket}/{key}")) {
Some((_, bytes)) => (StatusCode::OK, bytes.clone()),
None => (StatusCode::NOT_FOUND, Bytes::new()),
}
},
)
.delete(
|State(st): State<MockS3Store>,
Path((bucket, key)): Path<(String, String)>| async move {
st.lock().unwrap().remove(&format!("{bucket}/{key}"));
StatusCode::NO_CONTENT
},
),
)
.with_state(store);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let storage = Storage::with_backend(
db,
StorageBackend::S3(S3Config {
endpoint: format!("http://{addr}"),
region: "us-east-1".into(),
bucket: "slabs-uploads".into(),
access_key_id: "ak_test".into(),
secret_access_key: "sk_secret".into(),
}),
);
let meta = storage
.put(
"logo.txt",
Some("text/plain"),
Bytes::from_static(b"s3-sigv4-works"),
)
.await
.unwrap();
let (fetched_meta, fetched_bytes) = storage.get(&meta.id).await.unwrap();
assert_eq!(fetched_meta.filename, "logo.txt");
assert_eq!(fetched_bytes, Bytes::from_static(b"s3-sigv4-works"));
storage.delete(&meta.id).await.unwrap();
assert!(storage.get(&meta.id).await.is_err());
}
#[test]
fn s3_config_debug_redacts_secret_access_key() {
let cfg = S3Config {
endpoint: "https://s3.example.com".into(),
region: "us-east-1".into(),
bucket: "uploads".into(),
access_key_id: "AKIA_PUBLIC".into(),
secret_access_key: "super_secret_s3_key".into(),
};
let rendered = format!("{cfg:?}");
assert!(!rendered.contains("super_secret_s3_key"));
assert!(rendered.contains("AKIA_PUBLIC"));
assert!(rendered.contains("<redacted>"));
}
}
#[cfg(all(test, feature = "images"))]
mod image_tests {
use super::*;
use std::io::Cursor;
#[tokio::test]
async fn put_resized_image_scales_preserving_aspect_ratio_and_encodes_png() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let root_dir = std::env::temp_dir().join(format!("slabs_img_test_{}", id::new("tst")));
let storage = Storage::new(db, root_dir.clone());
let src = image::RgbaImage::from_pixel(40, 20, image::Rgba([32, 160, 240, 255]));
let mut src_cursor = Cursor::new(Vec::new());
image::DynamicImage::ImageRgba8(src)
.write_to(&mut src_cursor, image::ImageFormat::Png)
.unwrap();
let src_bytes = Bytes::from(src_cursor.into_inner());
let meta = storage
.put_resized_image("uploads/banner.jpg", src_bytes, 16, 16)
.await
.unwrap();
assert_eq!(meta.filename, "banner.png");
assert_eq!(meta.content_type, "image/png");
let (_fetched_meta, stored_bytes) = storage.get(&meta.id).await.unwrap();
let decoded = image::load_from_memory(&stored_bytes).unwrap();
assert_eq!(decoded.width(), 16);
assert_eq!(decoded.height(), 8);
let _ = std::fs::remove_dir_all(&root_dir);
}
}