use axum::{
http::{header, HeaderValue, StatusCode},
response::{IntoResponse, Response},
};
use bytes::Bytes;
use chrono::{SecondsFormat, 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::{Path, PathBuf};
#[cfg(feature = "images")]
use std::sync::Arc;
use std::time::Duration;
use tokio::fs;
#[cfg(feature = "images")]
use tokio::sync::Semaphore;
type HmacSha256 = Hmac<Sha256>;
pub const DEFAULT_MAX_BLOB_BYTES: usize = 10 * 1024 * 1024;
#[cfg(feature = "images")]
const IMAGE_DECODE_CONCURRENCY: usize = 4;
pub fn validate_storage_key(key: &str) -> SlabResult<()> {
let Some((shard, blob_part)) = key.split_once('/') else {
return Err(SlabError::bad_request("invalid storage key"));
};
if shard.len() != 2
|| !shard
.bytes()
.all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
{
return Err(SlabError::bad_request("invalid storage key shard"));
}
let Some(suffix) = blob_part.strip_prefix("blb_") else {
return Err(SlabError::bad_request("invalid storage key prefix"));
};
if suffix.is_empty() || !suffix.bytes().all(|b| b.is_ascii_alphanumeric()) {
return Err(SlabError::bad_request("invalid storage key identifier"));
}
Ok(())
}
fn clean_filename(raw: &str) -> String {
let basename = raw.rsplit(['/', '\\']).next().unwrap_or("");
let filtered: String = basename
.chars()
.filter(|&c| !c.is_control() && !matches!(c, '\r' | '\n' | '\0' | '"' | ';' | '/' | '\\'))
.take(200)
.collect();
let trimmed = filtered.trim();
if trimmed.is_empty() || trimmed == "." || trimmed == ".." {
"upload.bin".to_string()
} else {
trimmed.to_string()
}
}
fn validate_content_type(ct: &str) -> SlabResult<()> {
if ct.chars().any(char::is_control) {
return Err(SlabError::bad_request(
"content_type contains invalid control characters",
));
}
Ok(())
}
async fn reject_if_symlink(root_dir: &Path, storage_key: &str) -> SlabResult<PathBuf> {
validate_storage_key(storage_key)?;
let (shard, _) = storage_key
.split_once('/')
.ok_or_else(|| SlabError::bad_request("invalid storage key"))?;
let shard_dir = root_dir.join(shard);
if let Ok(meta) = fs::symlink_metadata(&shard_dir).await {
if meta.file_type().is_symlink() {
return Err(SlabError::forbidden("refusing to traverse symlinked shard"));
}
}
let disk_path = root_dir.join(storage_key);
if let Ok(meta) = fs::symlink_metadata(&disk_path).await {
if meta.file_type().is_symlink() {
return Err(SlabError::forbidden("refusing to access symlinked blob"));
}
}
Ok(disk_path)
}
#[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 scope: Option<String>,
pub created_at: String,
}
impl BlobMeta {
#[must_use]
pub fn is_safe_inline_content_type(&self) -> bool {
let essence = self
.content_type
.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase();
matches!(
essence.as_str(),
"image/png" | "image/jpeg" | "image/webp" | "image/gif"
)
}
#[must_use]
pub fn safe_content_disposition(&self, allow_inline_passive: bool) -> String {
let safe_name = clean_filename(&self.filename);
let disposition = if allow_inline_passive && self.is_safe_inline_content_type() {
"inline"
} else {
"attachment"
};
format!("{disposition}; filename=\"{safe_name}\"")
}
#[must_use]
pub fn into_safe_response(
&self,
bytes: impl Into<Bytes>,
allow_inline_passive: bool,
) -> Response {
let ct = if self.content_type.chars().any(char::is_control) {
HeaderValue::from_static("application/octet-stream")
} else {
HeaderValue::from_str(&self.content_type)
.unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"))
};
let cd = HeaderValue::from_str(&self.safe_content_disposition(allow_inline_passive))
.unwrap_or_else(|_| HeaderValue::from_static("attachment; filename=\"upload.bin\""));
(
StatusCode::OK,
[
(header::CONTENT_TYPE, ct),
(header::CONTENT_DISPOSITION, cd),
(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
),
(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static("default-src 'none'; sandbox"),
),
],
bytes.into(),
)
.into_response()
}
}
#[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,
max_blob_bytes: usize,
#[cfg(feature = "images")]
image_permits: Arc<Semaphore>,
}
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()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(30))
.build()
.expect("failed to build reqwest client");
Self {
db,
backend,
http,
max_blob_bytes: DEFAULT_MAX_BLOB_BYTES,
#[cfg(feature = "images")]
image_permits: Arc::new(Semaphore::new(IMAGE_DECODE_CONCURRENCY)),
}
}
#[must_use]
pub fn with_max_blob_bytes(mut self, max_bytes: usize) -> Self {
self.max_blob_bytes = max_bytes;
self
}
#[must_use]
pub fn max_blob_bytes(&self) -> usize {
self.max_blob_bytes
}
pub async fn put(
&self,
filename: &str,
content_type: Option<&str>,
data: Bytes,
) -> SlabResult<BlobMeta> {
self.put_with_scope(None, filename, content_type, data)
.await
}
pub async fn put_scoped(
&self,
scope: &str,
filename: &str,
content_type: Option<&str>,
data: &[u8],
) -> SlabResult<BlobMeta> {
let trimmed = scope.trim();
if trimmed.is_empty() || trimmed.chars().any(char::is_control) {
return Err(SlabError::bad_request(
"blob scope must be a non-empty string without control characters",
));
}
self.put_with_scope(
Some(trimmed),
filename,
content_type,
Bytes::copy_from_slice(data),
)
.await
}
async fn put_with_scope(
&self,
scope: Option<&str>,
filename: &str,
content_type: Option<&str>,
data: Bytes,
) -> SlabResult<BlobMeta> {
if data.len() > self.max_blob_bytes {
return Err(SlabError::bad_request(format!(
"blob size {} exceeds maximum allowed {} bytes",
data.len(),
self.max_blob_bytes
)));
}
let blob_id = id::new("blb");
let clean_name = clean_filename(filename);
if let Some(ct) = content_type {
validate_content_type(ct)?;
}
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,
);
validate_content_type(&resolved_ct)?;
let checksum_sha256 = sha256_hex(&data);
let shard = &checksum_sha256[..2];
let storage_key = format!("{shard}/{blob_id}");
validate_storage_key(&storage_key)?;
let mut local_written_path: Option<PathBuf> = None;
match &self.backend {
StorageBackend::Local { root_dir } => {
let disk_path = reject_if_symlink(root_dir, &storage_key).await?;
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}")))?;
local_written_path = Some(disk_path);
}
StorageBackend::S3(s3) => {
self.s3_request(s3, "PUT", &storage_key, Some(&resolved_ct), data.clone())
.await?;
}
}
let created_at = Utc::now().to_rfc3339_opts(SecondsFormat::Micros, true);
let byte_size = i64::try_from(data.len())
.map_err(|_| SlabError::bad_request("blob exceeds maximum size"))?;
if let Err(err) = sqlx::query(
"INSERT INTO slabs_blobs (id, filename, content_type, byte_size, checksum_sha256, storage_key, scope, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(&blob_id)
.bind(&clean_name)
.bind(&resolved_ct)
.bind(byte_size)
.bind(&checksum_sha256)
.bind(&storage_key)
.bind(scope)
.bind(&created_at)
.execute(self.db.pool())
.await
{
if let Some(disk_path) = local_written_path {
let _ = fs::remove_file(&disk_path).await;
}
return Err(err.into());
}
Ok(BlobMeta {
id: blob_id,
filename: clean_name,
content_type: resolved_ct,
byte_size,
checksum_sha256,
storage_key,
scope: scope.map(ToOwned::to_owned),
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",
));
}
if data.len() > self.max_blob_bytes {
return Err(SlabError::bad_request(format!(
"image size {} exceeds maximum allowed {} bytes",
data.len(),
self.max_blob_bytes
)));
}
let _permit = self
.image_permits
.acquire()
.await
.map_err(|_| SlabError::internal("image decode semaphore closed"))?;
let buf = tokio::task::spawn_blocking(move || -> SlabResult<Vec<u8>> {
let mut reader = image::ImageReader::new(std::io::Cursor::new(&data))
.with_guessed_format()
.map_err(|e| SlabError::bad_request(format!("invalid image data: {e}")))?;
let mut limits = image::Limits::default();
limits.max_image_width = Some(8192);
limits.max_image_height = Some(8192);
limits.max_alloc = Some(64 * 1024 * 1024);
reader.limits(limits);
let img = reader
.decode()
.map_err(|e| SlabError::bad_request(format!("invalid or oversized image: {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 clean = clean_filename(filename);
let stem = Path::new(&clean)
.file_stem()
.and_then(|s| s.to_str())
.filter(|s| !s.is_empty() && *s != "." && *s != "..")
.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, scope, created_at
FROM slabs_blobs
WHERE id = ?",
)
.bind(blob_id)
.fetch_optional(self.db.reader())
.await?
.ok_or_else(|| SlabError::not_found(format!("blob `{blob_id}` not found")))?;
let data = self.read_blob_bytes(&meta).await?;
Ok((meta, data))
}
pub async fn get_scoped(
&self,
blob_id: &str,
expected_scope: Option<&str>,
) -> SlabResult<Option<(BlobMeta, Vec<u8>)>> {
let meta: Option<BlobMeta> = sqlx::query_as(
"SELECT id, filename, content_type, byte_size, checksum_sha256, storage_key, scope, created_at
FROM slabs_blobs
WHERE id = ?",
)
.bind(blob_id)
.fetch_optional(self.db.reader())
.await?;
let Some(meta) = meta else {
return Ok(None);
};
if meta.scope.as_deref() != expected_scope {
return Ok(None);
}
let data = self.read_blob_bytes(&meta).await?;
Ok(Some((meta, data.to_vec())))
}
async fn read_blob_bytes(&self, meta: &BlobMeta) -> SlabResult<Bytes> {
validate_storage_key(&meta.storage_key)?;
match &self.backend {
StorageBackend::Local { root_dir } => {
let disk_path = reject_if_symlink(root_dir, &meta.storage_key).await?;
let raw = fs::read(&disk_path).await.map_err(|e| {
SlabError::internal(format!("failed to read blob `{}`: {e}", meta.id))
})?;
Ok(Bytes::from(raw))
}
StorageBackend::S3(s3) => {
self.s3_request(s3, "GET", &meta.storage_key, None, Bytes::new())
.await
}
}
}
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 {
validate_storage_key(&storage_key)?;
sqlx::query("DELETE FROM slabs_blobs WHERE id = ?")
.bind(blob_id)
.execute(self.db.pool())
.await?;
match &self.backend {
StorageBackend::Local { root_dir } => {
if let Ok(disk_path) = reject_if_symlink(root_dir, &storage_key).await {
let _ = fs::remove_file(disk_path).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 validate_storage_key_rejects_traversal_and_malformed_keys() {
assert!(validate_storage_key("ab/blb_01j9xyz123").is_ok());
assert!(validate_storage_key("../etc/passwd").is_err());
assert!(validate_storage_key("/ab/blb_01j9xyz123").is_err());
assert!(validate_storage_key("ab/blb_123/../secret").is_err());
assert!(validate_storage_key("AB/blb_01j9xyz123").is_err());
assert!(validate_storage_key("ab/not_a_blob").is_err());
assert!(validate_storage_key("ab/blb_").is_err());
}
#[tokio::test]
async fn tampered_storage_key_in_db_is_rejected_on_get_and_delete() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let root_dir = std::env::temp_dir().join(format!("slabs_trav_test_{}", id::new("tst")));
let storage = Storage::new(db.clone(), root_dir.clone());
sqlx::query(
"INSERT INTO slabs_blobs (id, filename, content_type, byte_size, checksum_sha256, storage_key, created_at)
VALUES ('blb_evil', 'passwd', 'text/plain', 10, '00', '../../etc/passwd', '2026-01-01T00:00:00.000000Z')",
)
.execute(db.pool())
.await
.unwrap();
assert!(storage.get("blb_evil").await.is_err());
assert!(storage.delete("blb_evil").await.is_err());
let _ = std::fs::remove_dir_all(&root_dir);
}
#[test]
fn safe_response_forces_svg_and_html_to_attachment_and_allows_inline_png() {
let make_meta = |filename: &str, ct: &str| BlobMeta {
id: "blb_1".into(),
filename: filename.into(),
content_type: ct.into(),
byte_size: 4,
checksum_sha256: "deadbeef".into(),
storage_key: "de/blb_1".into(),
scope: None,
created_at: "2026-01-01T00:00:00.000000Z".into(),
};
let svg = make_meta("evil.svg", "image/svg+xml");
assert!(!svg.is_safe_inline_content_type());
assert_eq!(
svg.safe_content_disposition(true),
"attachment; filename=\"evil.svg\""
);
let resp = svg.into_safe_response(b"<svg/>".to_vec(), true);
assert_eq!(
resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
"attachment; filename=\"evil.svg\""
);
assert_eq!(
resp.headers().get(header::X_CONTENT_TYPE_OPTIONS).unwrap(),
"nosniff"
);
assert_eq!(
resp.headers().get(header::CONTENT_SECURITY_POLICY).unwrap(),
"default-src 'none'; sandbox"
);
let html = make_meta("page.html", "text/html; charset=utf-8");
assert!(!html.is_safe_inline_content_type());
assert!(html
.safe_content_disposition(true)
.starts_with("attachment;"));
let png = make_meta("avatar.png", "image/png");
assert!(png.is_safe_inline_content_type());
assert_eq!(
png.safe_content_disposition(true),
"inline; filename=\"avatar.png\""
);
assert_eq!(
png.safe_content_disposition(false),
"attachment; filename=\"avatar.png\""
);
}
#[tokio::test]
async fn put_enforces_max_blob_bytes_and_sanitizes_filenames_and_content_type() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let root_dir = std::env::temp_dir().join(format!("slabs_put_test_{}", id::new("tst")));
let storage = Storage::new(db, root_dir.clone()).with_max_blob_bytes(16);
let err = storage
.put("big.bin", None, Bytes::from(vec![0u8; 17]))
.await
.unwrap_err();
assert_eq!(err.status_code(), StatusCode::BAD_REQUEST);
let err = storage
.put(
"ok.txt",
Some("text/plain\r\nX-Injected: 1"),
Bytes::from_static(b"hi"),
)
.await
.unwrap_err();
assert_eq!(err.status_code(), StatusCode::BAD_REQUEST);
let meta = storage
.put("../../..", Some("text/plain"), Bytes::from_static(b"ok"))
.await
.unwrap();
assert_eq!(meta.filename, "upload.bin");
let meta2 = storage
.put(
"dir/a\"\r\n;b.txt",
Some("text/plain"),
Bytes::from_static(b"ok"),
)
.await
.unwrap();
assert_eq!(meta2.filename, "ab.txt");
let _ = std::fs::remove_dir_all(&root_dir);
}
#[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>"));
}
#[tokio::test]
async fn put_scoped_and_get_scoped_isolate_blobs_by_scope() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let root_dir = std::env::temp_dir().join(format!("slabs_scope_test_{}", id::new("tst")));
let storage = Storage::new(db, root_dir.clone());
assert!(storage
.put_scoped(" ", "a.txt", Some("text/plain"), b"x")
.await
.is_err());
assert!(storage
.put_scoped("bad\nscope", "a.txt", Some("text/plain"), b"x")
.await
.is_err());
let app_blob = storage
.put(
"public.txt",
Some("text/plain"),
Bytes::from_static(b"app-upload"),
)
.await
.unwrap();
assert_eq!(app_blob.scope, None);
let bug_blob = storage
.put_scoped(
"bug_report",
"screen.png",
Some("image/png"),
b"private-screenshot",
)
.await
.unwrap();
assert_eq!(bug_blob.scope.as_deref(), Some("bug_report"));
let (meta, bytes) = storage
.get_scoped(&app_blob.id, None)
.await
.unwrap()
.expect("unscoped blob should match None scope");
assert_eq!(meta.scope, None);
assert_eq!(bytes, b"app-upload");
assert!(storage
.get_scoped(&bug_blob.id, None)
.await
.unwrap()
.is_none());
let (bug_meta, bug_bytes) = storage
.get_scoped(&bug_blob.id, Some("bug_report"))
.await
.unwrap()
.expect("bug_report blob should match its scope");
assert_eq!(bug_meta.scope.as_deref(), Some("bug_report"));
assert_eq!(bug_bytes, b"private-screenshot");
assert!(storage
.get_scoped(&app_blob.id, Some("bug_report"))
.await
.unwrap()
.is_none());
assert!(storage
.get_scoped(&bug_blob.id, Some("other_scope"))
.await
.unwrap()
.is_none());
assert!(storage
.get_scoped("blb_does_not_exist", None)
.await
.unwrap()
.is_none());
let (compat_meta, compat_bytes) = storage.get(&bug_blob.id).await.unwrap();
assert_eq!(compat_meta.scope.as_deref(), Some("bug_report"));
assert_eq!(compat_bytes.as_ref(), b"private-screenshot");
let _ = std::fs::remove_dir_all(&root_dir);
}
}
#[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);
}
#[tokio::test]
async fn put_resized_image_rejects_oversized_dimensions_decompression_bomb() {
let db = Db::connect("sqlite::memory:").await.unwrap();
db.init_system_tables().await.unwrap();
let root_dir = std::env::temp_dir().join(format!("slabs_bomb_test_{}", id::new("tst")));
let storage = Storage::new(db, root_dir.clone());
let mut png_header = Vec::new();
png_header.extend_from_slice(&[137, 80, 78, 71, 13, 10, 26, 10]); let mut ihdr = Vec::new();
ihdr.extend_from_slice(b"IHDR");
ihdr.extend_from_slice(&10_000u32.to_be_bytes()); ihdr.extend_from_slice(&10_000u32.to_be_bytes()); ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); let crc = crc32_ieee(&ihdr);
png_header.extend_from_slice(&13u32.to_be_bytes());
png_header.extend_from_slice(&ihdr);
png_header.extend_from_slice(&crc.to_be_bytes());
let err = storage
.put_resized_image("bomb.png", Bytes::from(png_header), 64, 64)
.await
.unwrap_err();
assert_eq!(err.status_code(), axum::http::StatusCode::BAD_REQUEST);
let _ = std::fs::remove_dir_all(&root_dir);
}
fn crc32_ieee(data: &[u8]) -> u32 {
let mut crc: u32 = 0xffff_ffff;
for &byte in data {
crc ^= u32::from(byte);
for _ in 0..8 {
let mask = (crc & 1).wrapping_neg();
crc = (crc >> 1) ^ (0xedb8_8320 & mask);
}
}
!crc
}
}