1use axum::{
66 http::{header, HeaderValue, StatusCode},
67 response::{IntoResponse, Response},
68};
69use bytes::Bytes;
70use chrono::{SecondsFormat, Utc};
71use hmac::{Hmac, Mac};
72use serde::{Deserialize, Serialize};
73use sha2::{Digest, Sha256};
74use slabs_core::{id, SlabError, SlabResult};
75use slabs_db::Db;
76use std::fmt;
77use std::path::{Path, PathBuf};
78#[cfg(feature = "images")]
79use std::sync::Arc;
80use std::time::Duration;
81use tokio::fs;
82#[cfg(feature = "images")]
83use tokio::sync::Semaphore;
84
85type HmacSha256 = Hmac<Sha256>;
86
87pub const DEFAULT_MAX_BLOB_BYTES: usize = 10 * 1024 * 1024;
89
90#[cfg(feature = "images")]
91const IMAGE_DECODE_CONCURRENCY: usize = 4;
92
93pub fn validate_storage_key(key: &str) -> SlabResult<()> {
95 let Some((shard, blob_part)) = key.split_once('/') else {
96 return Err(SlabError::bad_request("invalid storage key"));
97 };
98 if shard.len() != 2
99 || !shard
100 .bytes()
101 .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
102 {
103 return Err(SlabError::bad_request("invalid storage key shard"));
104 }
105 let Some(suffix) = blob_part.strip_prefix("blb_") else {
106 return Err(SlabError::bad_request("invalid storage key prefix"));
107 };
108 if suffix.is_empty() || !suffix.bytes().all(|b| b.is_ascii_alphanumeric()) {
109 return Err(SlabError::bad_request("invalid storage key identifier"));
110 }
111 Ok(())
112}
113
114fn clean_filename(raw: &str) -> String {
115 let basename = raw.rsplit(['/', '\\']).next().unwrap_or("");
116 let filtered: String = basename
117 .chars()
118 .filter(|&c| !c.is_control() && !matches!(c, '\r' | '\n' | '\0' | '"' | ';' | '/' | '\\'))
119 .take(200)
120 .collect();
121 let trimmed = filtered.trim();
122 if trimmed.is_empty() || trimmed == "." || trimmed == ".." {
123 "upload.bin".to_string()
124 } else {
125 trimmed.to_string()
126 }
127}
128
129fn validate_content_type(ct: &str) -> SlabResult<()> {
130 if ct.chars().any(char::is_control) {
131 return Err(SlabError::bad_request(
132 "content_type contains invalid control characters",
133 ));
134 }
135 Ok(())
136}
137
138async fn reject_if_symlink(root_dir: &Path, storage_key: &str) -> SlabResult<PathBuf> {
139 validate_storage_key(storage_key)?;
140 let (shard, _) = storage_key
141 .split_once('/')
142 .ok_or_else(|| SlabError::bad_request("invalid storage key"))?;
143 let shard_dir = root_dir.join(shard);
144 if let Ok(meta) = fs::symlink_metadata(&shard_dir).await {
145 if meta.file_type().is_symlink() {
146 return Err(SlabError::forbidden("refusing to traverse symlinked shard"));
147 }
148 }
149 let disk_path = root_dir.join(storage_key);
150 if let Ok(meta) = fs::symlink_metadata(&disk_path).await {
151 if meta.file_type().is_symlink() {
152 return Err(SlabError::forbidden("refusing to access symlinked blob"));
153 }
154 }
155 Ok(disk_path)
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
160pub struct BlobMeta {
161 pub id: String,
163 pub filename: String,
165 pub content_type: String,
167 pub byte_size: i64,
169 pub checksum_sha256: String,
171 pub storage_key: String,
173 pub scope: Option<String>,
175 pub created_at: String,
177}
178
179impl BlobMeta {
180 #[must_use]
185 pub fn is_safe_inline_content_type(&self) -> bool {
186 let essence = self
187 .content_type
188 .split(';')
189 .next()
190 .unwrap_or("")
191 .trim()
192 .to_ascii_lowercase();
193 matches!(
194 essence.as_str(),
195 "image/png" | "image/jpeg" | "image/webp" | "image/gif"
196 )
197 }
198
199 #[must_use]
204 pub fn safe_content_disposition(&self, allow_inline_passive: bool) -> String {
205 let safe_name = clean_filename(&self.filename);
206 let disposition = if allow_inline_passive && self.is_safe_inline_content_type() {
207 "inline"
208 } else {
209 "attachment"
210 };
211 format!("{disposition}; filename=\"{safe_name}\"")
212 }
213
214 #[must_use]
218 pub fn into_safe_response(
219 &self,
220 bytes: impl Into<Bytes>,
221 allow_inline_passive: bool,
222 ) -> Response {
223 let ct = if self.content_type.chars().any(char::is_control) {
224 HeaderValue::from_static("application/octet-stream")
225 } else {
226 HeaderValue::from_str(&self.content_type)
227 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"))
228 };
229 let cd = HeaderValue::from_str(&self.safe_content_disposition(allow_inline_passive))
230 .unwrap_or_else(|_| HeaderValue::from_static("attachment; filename=\"upload.bin\""));
231
232 (
233 StatusCode::OK,
234 [
235 (header::CONTENT_TYPE, ct),
236 (header::CONTENT_DISPOSITION, cd),
237 (
238 header::X_CONTENT_TYPE_OPTIONS,
239 HeaderValue::from_static("nosniff"),
240 ),
241 (
242 header::CONTENT_SECURITY_POLICY,
243 HeaderValue::from_static("default-src 'none'; sandbox"),
244 ),
245 ],
246 bytes.into(),
247 )
248 .into_response()
249 }
250}
251
252#[derive(Clone)]
254pub struct S3Config {
255 pub endpoint: String,
257 pub region: String,
259 pub bucket: String,
261 pub access_key_id: String,
263 pub secret_access_key: String,
265}
266
267impl fmt::Debug for S3Config {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 f.debug_struct("S3Config")
270 .field("endpoint", &self.endpoint)
271 .field("region", &self.region)
272 .field("bucket", &self.bucket)
273 .field("access_key_id", &self.access_key_id)
274 .field("secret_access_key", &"<redacted>")
275 .finish()
276 }
277}
278
279impl S3Config {
280 #[must_use]
285 pub fn from_env() -> Option<Self> {
286 let bucket = std::env::var("SLABS_S3_BUCKET")
287 .ok()
288 .filter(|s| !s.is_empty())?;
289 let access_key_id = std::env::var("SLABS_S3_ACCESS_KEY_ID").ok()?;
290 let secret_access_key = std::env::var("SLABS_S3_SECRET_ACCESS_KEY").ok()?;
291 let region = std::env::var("SLABS_S3_REGION").unwrap_or_else(|_| "us-east-1".into());
292 let endpoint = std::env::var("SLABS_S3_ENDPOINT")
293 .unwrap_or_else(|_| format!("https://s3.{region}.amazonaws.com"));
294
295 Some(Self {
296 endpoint: endpoint.trim_end_matches('/').to_string(),
297 region,
298 bucket,
299 access_key_id,
300 secret_access_key,
301 })
302 }
303}
304
305#[derive(Debug, Clone)]
307pub enum StorageBackend {
308 Local {
310 root_dir: PathBuf,
312 },
313 S3(S3Config),
315}
316
317#[derive(Debug, Clone)]
319pub struct Storage {
320 db: Db,
321 backend: StorageBackend,
322 http: reqwest::Client,
323 max_blob_bytes: usize,
324 #[cfg(feature = "images")]
325 image_permits: Arc<Semaphore>,
326}
327
328impl Storage {
329 #[must_use]
331 pub fn new(db: Db, root_dir: PathBuf) -> Self {
332 Self::with_backend(db, StorageBackend::Local { root_dir })
333 }
334
335 #[must_use]
338 pub fn with_backend(db: Db, backend: StorageBackend) -> Self {
339 let http = reqwest::Client::builder()
340 .redirect(reqwest::redirect::Policy::none())
341 .timeout(Duration::from_secs(30))
342 .build()
343 .expect("failed to build reqwest client");
344 Self {
345 db,
346 backend,
347 http,
348 max_blob_bytes: DEFAULT_MAX_BLOB_BYTES,
349 #[cfg(feature = "images")]
350 image_permits: Arc::new(Semaphore::new(IMAGE_DECODE_CONCURRENCY)),
351 }
352 }
353
354 #[must_use]
356 pub fn with_max_blob_bytes(mut self, max_bytes: usize) -> Self {
357 self.max_blob_bytes = max_bytes;
358 self
359 }
360
361 #[must_use]
363 pub fn max_blob_bytes(&self) -> usize {
364 self.max_blob_bytes
365 }
366
367 pub async fn put(
373 &self,
374 filename: &str,
375 content_type: Option<&str>,
376 data: Bytes,
377 ) -> SlabResult<BlobMeta> {
378 self.put_with_scope(None, filename, content_type, data)
379 .await
380 }
381
382 pub async fn put_scoped(
389 &self,
390 scope: &str,
391 filename: &str,
392 content_type: Option<&str>,
393 data: &[u8],
394 ) -> SlabResult<BlobMeta> {
395 let trimmed = scope.trim();
396 if trimmed.is_empty() || trimmed.chars().any(char::is_control) {
397 return Err(SlabError::bad_request(
398 "blob scope must be a non-empty string without control characters",
399 ));
400 }
401 self.put_with_scope(
402 Some(trimmed),
403 filename,
404 content_type,
405 Bytes::copy_from_slice(data),
406 )
407 .await
408 }
409
410 async fn put_with_scope(
411 &self,
412 scope: Option<&str>,
413 filename: &str,
414 content_type: Option<&str>,
415 data: Bytes,
416 ) -> SlabResult<BlobMeta> {
417 if data.len() > self.max_blob_bytes {
418 return Err(SlabError::bad_request(format!(
419 "blob size {} exceeds maximum allowed {} bytes",
420 data.len(),
421 self.max_blob_bytes
422 )));
423 }
424
425 let blob_id = id::new("blb");
426 let clean_name = clean_filename(filename);
427
428 if let Some(ct) = content_type {
429 validate_content_type(ct)?;
430 }
431
432 let resolved_ct = content_type.filter(|s| !s.is_empty()).map_or_else(
433 || {
434 mime_guess::from_path(&clean_name)
435 .first_or_octet_stream()
436 .to_string()
437 },
438 ToString::to_string,
439 );
440 validate_content_type(&resolved_ct)?;
441
442 let checksum_sha256 = sha256_hex(&data);
443 let shard = &checksum_sha256[..2];
444 let storage_key = format!("{shard}/{blob_id}");
445 validate_storage_key(&storage_key)?;
446
447 let mut local_written_path: Option<PathBuf> = None;
448
449 match &self.backend {
450 StorageBackend::Local { root_dir } => {
451 let disk_path = reject_if_symlink(root_dir, &storage_key).await?;
452 if let Some(parent) = disk_path.parent() {
453 fs::create_dir_all(parent).await.map_err(|e| {
454 SlabError::internal(format!("failed to create storage dir: {e}"))
455 })?;
456 }
457 fs::write(&disk_path, &data)
458 .await
459 .map_err(|e| SlabError::internal(format!("failed to write blob: {e}")))?;
460 local_written_path = Some(disk_path);
461 }
462 StorageBackend::S3(s3) => {
463 self.s3_request(s3, "PUT", &storage_key, Some(&resolved_ct), data.clone())
464 .await?;
465 }
466 }
467
468 let created_at = Utc::now().to_rfc3339_opts(SecondsFormat::Micros, true);
469 let byte_size = i64::try_from(data.len())
470 .map_err(|_| SlabError::bad_request("blob exceeds maximum size"))?;
471
472 if let Err(err) = sqlx::query(
473 "INSERT INTO slabs_blobs (id, filename, content_type, byte_size, checksum_sha256, storage_key, scope, created_at)
474 VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
475 )
476 .bind(&blob_id)
477 .bind(&clean_name)
478 .bind(&resolved_ct)
479 .bind(byte_size)
480 .bind(&checksum_sha256)
481 .bind(&storage_key)
482 .bind(scope)
483 .bind(&created_at)
484 .execute(self.db.pool())
485 .await
486 {
487 if let Some(disk_path) = local_written_path {
488 let _ = fs::remove_file(&disk_path).await;
489 }
490 return Err(err.into());
491 }
492
493 Ok(BlobMeta {
494 id: blob_id,
495 filename: clean_name,
496 content_type: resolved_ct,
497 byte_size,
498 checksum_sha256,
499 storage_key,
500 scope: scope.map(ToOwned::to_owned),
501 created_at,
502 })
503 }
504
505 #[cfg(feature = "images")]
512 pub async fn put_resized_image(
513 &self,
514 filename: &str,
515 data: Bytes,
516 max_width: u32,
517 max_height: u32,
518 ) -> SlabResult<BlobMeta> {
519 if max_width == 0 || max_height == 0 {
520 return Err(SlabError::bad_request(
521 "max_width and max_height must be greater than zero",
522 ));
523 }
524 if data.len() > self.max_blob_bytes {
525 return Err(SlabError::bad_request(format!(
526 "image size {} exceeds maximum allowed {} bytes",
527 data.len(),
528 self.max_blob_bytes
529 )));
530 }
531
532 let _permit = self
533 .image_permits
534 .acquire()
535 .await
536 .map_err(|_| SlabError::internal("image decode semaphore closed"))?;
537
538 let buf = tokio::task::spawn_blocking(move || -> SlabResult<Vec<u8>> {
539 let mut reader = image::ImageReader::new(std::io::Cursor::new(&data))
540 .with_guessed_format()
541 .map_err(|e| SlabError::bad_request(format!("invalid image data: {e}")))?;
542
543 let mut limits = image::Limits::default();
544 limits.max_image_width = Some(8192);
545 limits.max_image_height = Some(8192);
546 limits.max_alloc = Some(64 * 1024 * 1024);
547 reader.limits(limits);
548
549 let img = reader
550 .decode()
551 .map_err(|e| SlabError::bad_request(format!("invalid or oversized image: {e}")))?;
552
553 let resized = img.thumbnail(max_width, max_height);
554 let mut cursor = std::io::Cursor::new(Vec::new());
555 resized
556 .write_to(&mut cursor, image::ImageFormat::Png)
557 .map_err(|e| SlabError::internal(format!("failed to encode resized image: {e}")))?;
558 Ok(cursor.into_inner())
559 })
560 .await
561 .map_err(|e| SlabError::internal(format!("image resize task failed: {e}")))??;
562
563 let clean = clean_filename(filename);
564 let stem = Path::new(&clean)
565 .file_stem()
566 .and_then(|s| s.to_str())
567 .filter(|s| !s.is_empty() && *s != "." && *s != "..")
568 .unwrap_or("image");
569 let out_name = format!("{stem}.png");
570
571 self.put(&out_name, Some("image/png"), Bytes::from(buf))
572 .await
573 }
574
575 pub async fn get(&self, blob_id: &str) -> SlabResult<(BlobMeta, Bytes)> {
584 let meta: BlobMeta = sqlx::query_as(
585 "SELECT id, filename, content_type, byte_size, checksum_sha256, storage_key, scope, created_at
586 FROM slabs_blobs
587 WHERE id = ?",
588 )
589 .bind(blob_id)
590 .fetch_optional(self.db.reader())
591 .await?
592 .ok_or_else(|| SlabError::not_found(format!("blob `{blob_id}` not found")))?;
593
594 let data = self.read_blob_bytes(&meta).await?;
595 Ok((meta, data))
596 }
597
598 pub async fn get_scoped(
604 &self,
605 blob_id: &str,
606 expected_scope: Option<&str>,
607 ) -> SlabResult<Option<(BlobMeta, Vec<u8>)>> {
608 let meta: Option<BlobMeta> = sqlx::query_as(
609 "SELECT id, filename, content_type, byte_size, checksum_sha256, storage_key, scope, created_at
610 FROM slabs_blobs
611 WHERE id = ?",
612 )
613 .bind(blob_id)
614 .fetch_optional(self.db.reader())
615 .await?;
616
617 let Some(meta) = meta else {
618 return Ok(None);
619 };
620 if meta.scope.as_deref() != expected_scope {
621 return Ok(None);
622 }
623
624 let data = self.read_blob_bytes(&meta).await?;
625 Ok(Some((meta, data.to_vec())))
626 }
627
628 async fn read_blob_bytes(&self, meta: &BlobMeta) -> SlabResult<Bytes> {
629 validate_storage_key(&meta.storage_key)?;
630
631 match &self.backend {
632 StorageBackend::Local { root_dir } => {
633 let disk_path = reject_if_symlink(root_dir, &meta.storage_key).await?;
634 let raw = fs::read(&disk_path).await.map_err(|e| {
635 SlabError::internal(format!("failed to read blob `{}`: {e}", meta.id))
636 })?;
637 Ok(Bytes::from(raw))
638 }
639 StorageBackend::S3(s3) => {
640 self.s3_request(s3, "GET", &meta.storage_key, None, Bytes::new())
641 .await
642 }
643 }
644 }
645
646 pub async fn delete(&self, blob_id: &str) -> SlabResult<()> {
651 let meta: Option<(String,)> =
652 sqlx::query_as("SELECT storage_key FROM slabs_blobs WHERE id = ?")
653 .bind(blob_id)
654 .fetch_optional(self.db.pool())
655 .await?;
656
657 if let Some((storage_key,)) = meta {
658 validate_storage_key(&storage_key)?;
659
660 sqlx::query("DELETE FROM slabs_blobs WHERE id = ?")
661 .bind(blob_id)
662 .execute(self.db.pool())
663 .await?;
664
665 match &self.backend {
666 StorageBackend::Local { root_dir } => {
667 if let Ok(disk_path) = reject_if_symlink(root_dir, &storage_key).await {
668 let _ = fs::remove_file(disk_path).await;
669 }
670 }
671 StorageBackend::S3(s3) => {
672 let _ = self
673 .s3_request(s3, "DELETE", &storage_key, None, Bytes::new())
674 .await;
675 }
676 }
677 }
678 Ok(())
679 }
680
681 async fn s3_request(
683 &self,
684 s3: &S3Config,
685 method: &str,
686 key: &str,
687 content_type: Option<&str>,
688 body: Bytes,
689 ) -> SlabResult<Bytes> {
690 let canonical_uri = format!("/{}/{}", s3.bucket, key.trim_start_matches('/'));
691 let url = format!("{}{}", s3.endpoint, canonical_uri);
692
693 let host = s3
694 .endpoint
695 .strip_prefix("https://")
696 .or_else(|| s3.endpoint.strip_prefix("http://"))
697 .unwrap_or(&s3.endpoint)
698 .split('/')
699 .next()
700 .unwrap_or("localhost");
701
702 let now = Utc::now();
703 let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
704 let date_stamp = now.format("%Y%m%d").to_string();
705 let payload_hash = sha256_hex(&body);
706
707 let canonical_headers =
708 format!("host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n");
709 let signed_headers = "host;x-amz-content-sha256;x-amz-date";
710 let canonical_request = format!(
711 "{method}\n{canonical_uri}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}"
712 );
713
714 let credential_scope = format!("{date_stamp}/{}/s3/aws4_request", s3.region);
715 let string_to_sign = format!(
716 "AWS4-HMAC-SHA256\n{amz_date}\n{credential_scope}\n{}",
717 sha256_hex(canonical_request.as_bytes())
718 );
719
720 let k_date = hmac_sha256(
721 format!("AWS4{}", s3.secret_access_key).as_bytes(),
722 date_stamp.as_bytes(),
723 );
724 let k_region = hmac_sha256(&k_date, s3.region.as_bytes());
725 let k_service = hmac_sha256(&k_region, b"s3");
726 let k_signing = hmac_sha256(&k_service, b"aws4_request");
727 let signature = hex::encode(hmac_sha256(&k_signing, string_to_sign.as_bytes()));
728
729 let authorization = format!(
730 "AWS4-HMAC-SHA256 Credential={}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}",
731 s3.access_key_id
732 );
733
734 let mut req = match method {
735 "PUT" => self.http.put(&url),
736 "DELETE" => self.http.delete(&url),
737 _ => self.http.get(&url),
738 }
739 .header("host", host)
740 .header("x-amz-date", &amz_date)
741 .header("x-amz-content-sha256", &payload_hash)
742 .header("authorization", &authorization);
743
744 if let Some(ct) = content_type {
745 req = req.header("content-type", ct);
746 }
747 if !body.is_empty() {
748 req = req.body(body);
749 }
750
751 let resp = req
752 .send()
753 .await
754 .map_err(|e| SlabError::internal(format!("s3 {method} failed: {e}")))?;
755
756 if !resp.status().is_success() {
757 let status = resp.status();
758 let err_body = resp.text().await.unwrap_or_default();
759 return Err(SlabError::internal(format!(
760 "s3 {method} error {status}: {err_body}"
761 )));
762 }
763
764 resp.bytes()
765 .await
766 .map_err(|e| SlabError::internal(format!("s3 read body failed: {e}")))
767 }
768}
769
770fn sha256_hex(data: &[u8]) -> String {
771 let mut hasher = Sha256::new();
772 hasher.update(data);
773 hex::encode(hasher.finalize())
774}
775
776fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
777 let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts keys of any size");
778 mac.update(data);
779 mac.finalize().into_bytes().to_vec()
780}
781
782#[cfg(test)]
783mod tests {
784 use super::*;
785 use axum::{
786 extract::{Path, State},
787 http::{HeaderMap, StatusCode},
788 routing::put,
789 Router,
790 };
791 use std::collections::HashMap;
792 use std::sync::{Arc, Mutex};
793
794 type MockS3Store = Arc<Mutex<HashMap<String, (String, Bytes)>>>;
795
796 #[tokio::test]
797 async fn s3_sigv4_put_get_delete_roundtrip() {
798 let store: MockS3Store = Arc::new(Mutex::new(HashMap::new()));
799
800 let app =
801 Router::new()
802 .route(
803 "/{bucket}/{*key}",
804 put(
805 |State(st): State<MockS3Store>,
806 Path((bucket, key)): Path<(String, String)>,
807 headers: HeaderMap,
808 body: Bytes| async move {
809 let auth = headers
810 .get("authorization")
811 .and_then(|v| v.to_str().ok())
812 .unwrap_or("")
813 .to_string();
814 assert!(auth.starts_with("AWS4-HMAC-SHA256 Credential=ak_test/"));
815 assert!(headers.contains_key("x-amz-content-sha256"));
816 st.lock()
817 .unwrap()
818 .insert(format!("{bucket}/{key}"), (auth, body));
819 StatusCode::OK
820 },
821 )
822 .get(
823 |State(st): State<MockS3Store>,
824 Path((bucket, key)): Path<(String, String)>| async move {
825 match st.lock().unwrap().get(&format!("{bucket}/{key}")) {
826 Some((_, bytes)) => (StatusCode::OK, bytes.clone()),
827 None => (StatusCode::NOT_FOUND, Bytes::new()),
828 }
829 },
830 )
831 .delete(
832 |State(st): State<MockS3Store>,
833 Path((bucket, key)): Path<(String, String)>| async move {
834 st.lock().unwrap().remove(&format!("{bucket}/{key}"));
835 StatusCode::NO_CONTENT
836 },
837 ),
838 )
839 .with_state(store);
840
841 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
842 let addr = listener.local_addr().unwrap();
843 tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
844
845 let db = Db::connect("sqlite::memory:").await.unwrap();
846 db.init_system_tables().await.unwrap();
847
848 let storage = Storage::with_backend(
849 db,
850 StorageBackend::S3(S3Config {
851 endpoint: format!("http://{addr}"),
852 region: "us-east-1".into(),
853 bucket: "slabs-uploads".into(),
854 access_key_id: "ak_test".into(),
855 secret_access_key: "sk_secret".into(),
856 }),
857 );
858
859 let meta = storage
860 .put(
861 "logo.txt",
862 Some("text/plain"),
863 Bytes::from_static(b"s3-sigv4-works"),
864 )
865 .await
866 .unwrap();
867 let (fetched_meta, fetched_bytes) = storage.get(&meta.id).await.unwrap();
868 assert_eq!(fetched_meta.filename, "logo.txt");
869 assert_eq!(fetched_bytes, Bytes::from_static(b"s3-sigv4-works"));
870
871 storage.delete(&meta.id).await.unwrap();
872 assert!(storage.get(&meta.id).await.is_err());
873 }
874
875 #[test]
876 fn validate_storage_key_rejects_traversal_and_malformed_keys() {
877 assert!(validate_storage_key("ab/blb_01j9xyz123").is_ok());
878 assert!(validate_storage_key("../etc/passwd").is_err());
879 assert!(validate_storage_key("/ab/blb_01j9xyz123").is_err());
880 assert!(validate_storage_key("ab/blb_123/../secret").is_err());
881 assert!(validate_storage_key("AB/blb_01j9xyz123").is_err());
882 assert!(validate_storage_key("ab/not_a_blob").is_err());
883 assert!(validate_storage_key("ab/blb_").is_err());
884 }
885
886 #[tokio::test]
887 async fn tampered_storage_key_in_db_is_rejected_on_get_and_delete() {
888 let db = Db::connect("sqlite::memory:").await.unwrap();
889 db.init_system_tables().await.unwrap();
890
891 let root_dir = std::env::temp_dir().join(format!("slabs_trav_test_{}", id::new("tst")));
892 let storage = Storage::new(db.clone(), root_dir.clone());
893
894 sqlx::query(
895 "INSERT INTO slabs_blobs (id, filename, content_type, byte_size, checksum_sha256, storage_key, created_at)
896 VALUES ('blb_evil', 'passwd', 'text/plain', 10, '00', '../../etc/passwd', '2026-01-01T00:00:00.000000Z')",
897 )
898 .execute(db.pool())
899 .await
900 .unwrap();
901
902 assert!(storage.get("blb_evil").await.is_err());
903 assert!(storage.delete("blb_evil").await.is_err());
904
905 let _ = std::fs::remove_dir_all(&root_dir);
906 }
907
908 #[test]
909 fn safe_response_forces_svg_and_html_to_attachment_and_allows_inline_png() {
910 let make_meta = |filename: &str, ct: &str| BlobMeta {
911 id: "blb_1".into(),
912 filename: filename.into(),
913 content_type: ct.into(),
914 byte_size: 4,
915 checksum_sha256: "deadbeef".into(),
916 storage_key: "de/blb_1".into(),
917 scope: None,
918 created_at: "2026-01-01T00:00:00.000000Z".into(),
919 };
920
921 let svg = make_meta("evil.svg", "image/svg+xml");
922 assert!(!svg.is_safe_inline_content_type());
923 assert_eq!(
924 svg.safe_content_disposition(true),
925 "attachment; filename=\"evil.svg\""
926 );
927 let resp = svg.into_safe_response(b"<svg/>".to_vec(), true);
928 assert_eq!(
929 resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
930 "attachment; filename=\"evil.svg\""
931 );
932 assert_eq!(
933 resp.headers().get(header::X_CONTENT_TYPE_OPTIONS).unwrap(),
934 "nosniff"
935 );
936 assert_eq!(
937 resp.headers().get(header::CONTENT_SECURITY_POLICY).unwrap(),
938 "default-src 'none'; sandbox"
939 );
940
941 let html = make_meta("page.html", "text/html; charset=utf-8");
942 assert!(!html.is_safe_inline_content_type());
943 assert!(html
944 .safe_content_disposition(true)
945 .starts_with("attachment;"));
946
947 let png = make_meta("avatar.png", "image/png");
948 assert!(png.is_safe_inline_content_type());
949 assert_eq!(
950 png.safe_content_disposition(true),
951 "inline; filename=\"avatar.png\""
952 );
953 assert_eq!(
954 png.safe_content_disposition(false),
955 "attachment; filename=\"avatar.png\""
956 );
957 }
958
959 #[tokio::test]
960 async fn put_enforces_max_blob_bytes_and_sanitizes_filenames_and_content_type() {
961 let db = Db::connect("sqlite::memory:").await.unwrap();
962 db.init_system_tables().await.unwrap();
963 let root_dir = std::env::temp_dir().join(format!("slabs_put_test_{}", id::new("tst")));
964 let storage = Storage::new(db, root_dir.clone()).with_max_blob_bytes(16);
965
966 let err = storage
968 .put("big.bin", None, Bytes::from(vec![0u8; 17]))
969 .await
970 .unwrap_err();
971 assert_eq!(err.status_code(), StatusCode::BAD_REQUEST);
972
973 let err = storage
975 .put(
976 "ok.txt",
977 Some("text/plain\r\nX-Injected: 1"),
978 Bytes::from_static(b"hi"),
979 )
980 .await
981 .unwrap_err();
982 assert_eq!(err.status_code(), StatusCode::BAD_REQUEST);
983
984 let meta = storage
986 .put("../../..", Some("text/plain"), Bytes::from_static(b"ok"))
987 .await
988 .unwrap();
989 assert_eq!(meta.filename, "upload.bin");
990
991 let meta2 = storage
992 .put(
993 "dir/a\"\r\n;b.txt",
994 Some("text/plain"),
995 Bytes::from_static(b"ok"),
996 )
997 .await
998 .unwrap();
999 assert_eq!(meta2.filename, "ab.txt");
1000
1001 let _ = std::fs::remove_dir_all(&root_dir);
1002 }
1003
1004 #[test]
1005 fn s3_config_debug_redacts_secret_access_key() {
1006 let cfg = S3Config {
1007 endpoint: "https://s3.example.com".into(),
1008 region: "us-east-1".into(),
1009 bucket: "uploads".into(),
1010 access_key_id: "AKIA_PUBLIC".into(),
1011 secret_access_key: "super_secret_s3_key".into(),
1012 };
1013 let rendered = format!("{cfg:?}");
1014 assert!(!rendered.contains("super_secret_s3_key"));
1015 assert!(rendered.contains("AKIA_PUBLIC"));
1016 assert!(rendered.contains("<redacted>"));
1017 }
1018
1019 #[tokio::test]
1020 async fn put_scoped_and_get_scoped_isolate_blobs_by_scope() {
1021 let db = Db::connect("sqlite::memory:").await.unwrap();
1022 db.init_system_tables().await.unwrap();
1023 let root_dir = std::env::temp_dir().join(format!("slabs_scope_test_{}", id::new("tst")));
1024 let storage = Storage::new(db, root_dir.clone());
1025
1026 assert!(storage
1028 .put_scoped(" ", "a.txt", Some("text/plain"), b"x")
1029 .await
1030 .is_err());
1031 assert!(storage
1032 .put_scoped("bad\nscope", "a.txt", Some("text/plain"), b"x")
1033 .await
1034 .is_err());
1035
1036 let app_blob = storage
1037 .put(
1038 "public.txt",
1039 Some("text/plain"),
1040 Bytes::from_static(b"app-upload"),
1041 )
1042 .await
1043 .unwrap();
1044 assert_eq!(app_blob.scope, None);
1045
1046 let bug_blob = storage
1047 .put_scoped(
1048 "bug_report",
1049 "screen.png",
1050 Some("image/png"),
1051 b"private-screenshot",
1052 )
1053 .await
1054 .unwrap();
1055 assert_eq!(bug_blob.scope.as_deref(), Some("bug_report"));
1056
1057 let (meta, bytes) = storage
1059 .get_scoped(&app_blob.id, None)
1060 .await
1061 .unwrap()
1062 .expect("unscoped blob should match None scope");
1063 assert_eq!(meta.scope, None);
1064 assert_eq!(bytes, b"app-upload");
1065 assert!(storage
1066 .get_scoped(&bug_blob.id, None)
1067 .await
1068 .unwrap()
1069 .is_none());
1070
1071 let (bug_meta, bug_bytes) = storage
1073 .get_scoped(&bug_blob.id, Some("bug_report"))
1074 .await
1075 .unwrap()
1076 .expect("bug_report blob should match its scope");
1077 assert_eq!(bug_meta.scope.as_deref(), Some("bug_report"));
1078 assert_eq!(bug_bytes, b"private-screenshot");
1079 assert!(storage
1080 .get_scoped(&app_blob.id, Some("bug_report"))
1081 .await
1082 .unwrap()
1083 .is_none());
1084 assert!(storage
1085 .get_scoped(&bug_blob.id, Some("other_scope"))
1086 .await
1087 .unwrap()
1088 .is_none());
1089 assert!(storage
1090 .get_scoped("blb_does_not_exist", None)
1091 .await
1092 .unwrap()
1093 .is_none());
1094
1095 let (compat_meta, compat_bytes) = storage.get(&bug_blob.id).await.unwrap();
1097 assert_eq!(compat_meta.scope.as_deref(), Some("bug_report"));
1098 assert_eq!(compat_bytes.as_ref(), b"private-screenshot");
1099
1100 let _ = std::fs::remove_dir_all(&root_dir);
1101 }
1102}
1103
1104#[cfg(all(test, feature = "images"))]
1105mod image_tests {
1106 use super::*;
1107 use std::io::Cursor;
1108
1109 #[tokio::test]
1110 async fn put_resized_image_scales_preserving_aspect_ratio_and_encodes_png() {
1111 let db = Db::connect("sqlite::memory:").await.unwrap();
1112 db.init_system_tables().await.unwrap();
1113
1114 let root_dir = std::env::temp_dir().join(format!("slabs_img_test_{}", id::new("tst")));
1115 let storage = Storage::new(db, root_dir.clone());
1116
1117 let src = image::RgbaImage::from_pixel(40, 20, image::Rgba([32, 160, 240, 255]));
1118 let mut src_cursor = Cursor::new(Vec::new());
1119 image::DynamicImage::ImageRgba8(src)
1120 .write_to(&mut src_cursor, image::ImageFormat::Png)
1121 .unwrap();
1122 let src_bytes = Bytes::from(src_cursor.into_inner());
1123
1124 let meta = storage
1125 .put_resized_image("uploads/banner.jpg", src_bytes, 16, 16)
1126 .await
1127 .unwrap();
1128 assert_eq!(meta.filename, "banner.png");
1129 assert_eq!(meta.content_type, "image/png");
1130
1131 let (_fetched_meta, stored_bytes) = storage.get(&meta.id).await.unwrap();
1132 let decoded = image::load_from_memory(&stored_bytes).unwrap();
1133 assert_eq!(decoded.width(), 16);
1134 assert_eq!(decoded.height(), 8);
1135
1136 let _ = std::fs::remove_dir_all(&root_dir);
1137 }
1138
1139 #[tokio::test]
1140 async fn put_resized_image_rejects_oversized_dimensions_decompression_bomb() {
1141 let db = Db::connect("sqlite::memory:").await.unwrap();
1142 db.init_system_tables().await.unwrap();
1143
1144 let root_dir = std::env::temp_dir().join(format!("slabs_bomb_test_{}", id::new("tst")));
1145 let storage = Storage::new(db, root_dir.clone());
1146
1147 let mut png_header = Vec::new();
1149 png_header.extend_from_slice(&[137, 80, 78, 71, 13, 10, 26, 10]); let mut ihdr = Vec::new();
1151 ihdr.extend_from_slice(b"IHDR");
1152 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);
1156 png_header.extend_from_slice(&13u32.to_be_bytes());
1157 png_header.extend_from_slice(&ihdr);
1158 png_header.extend_from_slice(&crc.to_be_bytes());
1159
1160 let err = storage
1161 .put_resized_image("bomb.png", Bytes::from(png_header), 64, 64)
1162 .await
1163 .unwrap_err();
1164 assert_eq!(err.status_code(), axum::http::StatusCode::BAD_REQUEST);
1165
1166 let _ = std::fs::remove_dir_all(&root_dir);
1167 }
1168
1169 fn crc32_ieee(data: &[u8]) -> u32 {
1170 let mut crc: u32 = 0xffff_ffff;
1171 for &byte in data {
1172 crc ^= u32::from(byte);
1173 for _ in 0..8 {
1174 let mask = (crc & 1).wrapping_neg();
1175 crc = (crc >> 1) ^ (0xedb8_8320 & mask);
1176 }
1177 }
1178 !crc
1179 }
1180}