slabs-storage 0.2.0

Low-level blob storage battery: local disk + S3-compatible SigV4 backend (AWS S3, Cloudflare R2, MinIO, Tigris)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Blob storage backed by the local filesystem or an S3-compatible object store.
//!
//! # Owned table and environment variables
//!
//! This crate stores blob metadata in the `slabs_blobs` table created by `Db::init_system_tables`.
//! Each row stores `id` (`blb_<ulid>`), `filename`, `content_type`, `byte_size`,
//! `checksum_sha256`, `storage_key`, and `created_at`.
//!
//! [`S3Config::from_env`] reads these environment variables to configure [`StorageBackend::S3`]:
//!
//! - `SLABS_S3_BUCKET` (required, must be non-empty)
//! - `SLABS_S3_ACCESS_KEY_ID` (required)
//! - `SLABS_S3_SECRET_ACCESS_KEY` (required)
//! - `SLABS_S3_REGION` (optional, defaults to `"us-east-1"`)
//! - `SLABS_S3_ENDPOINT` (optional, defaults to `https://s3.<region>.amazonaws.com`)
//!
//! When required S3 variables are absent, [`S3Config::from_env`] returns `None` and callers fall
//! back to [`StorageBackend::Local`].
//!
//! # Agent invariants
//!
//! - [`StorageBackend::Local`] writes files to `<root_dir>/<2-char-sha256-prefix>/<blob_id>`.
//! - [`StorageBackend::S3`] signs path-style requests with AWS `SigV4` and works with AWS S3,
//!   Cloudflare R2, `MinIO`, Tigris, and Garage.
//! - [`Storage::put`] strips directory segments from `filename` (defaulting to `"upload.bin"`),
//!   guesses the MIME type when `content_type` is omitted, writes object bytes first, and then
//!   inserts the `slabs_blobs` metadata row.
//! - [`Storage::delete`] deletes the `slabs_blobs` row first and removes the backend object on
//!   a best-effort basis. Deleting an unknown `blob_id` succeeds.
//! - Metadata queries run on the database pool directly and do not join an open SQLite transaction.
//!
//! # Example
//!
//! ```rust,no_run
//! use bytes::Bytes;
//! use slabs_db::Db;
//! use slabs_storage::{S3Config, Storage, StorageBackend};
//! use std::path::PathBuf;
//!
//! # async fn run() -> slabs_core::SlabResult<()> {
//! let db = Db::connect("sqlite::memory:").await?;
//! db.init_system_tables().await?;
//!
//! let backend = match S3Config::from_env() {
//!     Some(cfg) => StorageBackend::S3(cfg),
//!     None => StorageBackend::Local {
//!         root_dir: PathBuf::from("./storage"),
//!     },
//! };
//! let storage = Storage::with_backend(db, backend);
//!
//! let meta = storage
//!     .put("avatar.png", None, Bytes::from_static(b"png-bytes"))
//!     .await?;
//! let (_meta, bytes) = storage.get(&meta.id).await?;
//! assert_eq!(bytes.as_ref(), b"png-bytes");
//! # Ok(())
//! # }
//! ```

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>;

/// Metadata for a stored blob recorded in the `slabs_blobs` table.
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct BlobMeta {
    /// Unique blob identifier (`blb_<ulid>`).
    pub id: String,
    /// Sanitized basename of the uploaded file.
    pub filename: String,
    /// Resolved MIME content type.
    pub content_type: String,
    /// Blob payload length in bytes.
    pub byte_size: i64,
    /// Lowercase hex SHA-256 digest of the blob payload.
    pub checksum_sha256: String,
    /// Sharded key (`<2-char-sha256-prefix>/<blob_id>`) used on disk or in S3.
    pub storage_key: String,
    /// RFC 3339 creation timestamp.
    pub created_at: String,
}

/// Configuration for an S3-compatible object store (AWS S3, Cloudflare R2, `MinIO`, Tigris, Garage).
#[derive(Clone)]
pub struct S3Config {
    /// Base endpoint URL without a trailing slash (for example `https://s3.us-east-1.amazonaws.com`).
    pub endpoint: String,
    /// Signing region (for example `"us-east-1"` or `"auto"`).
    pub region: String,
    /// Target bucket name.
    pub bucket: String,
    /// AWS-style access key ID.
    pub access_key_id: String,
    /// AWS-style secret access key used for `SigV4` request signing.
    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 {
    /// Load S3 configuration from `SLABS_S3_*` environment variables.
    ///
    /// Returns `None` if `SLABS_S3_BUCKET`, `SLABS_S3_ACCESS_KEY_ID`, or
    /// `SLABS_S3_SECRET_ACCESS_KEY` is missing or if `SLABS_S3_BUCKET` is empty.
    #[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,
        })
    }
}

/// Storage backend target for [`Storage`].
#[derive(Debug, Clone)]
pub enum StorageBackend {
    /// Store blobs on the local filesystem under `root_dir`.
    Local {
        /// Root directory where sharded blob files live.
        root_dir: PathBuf,
    },
    /// Store blobs in an S3-compatible object store using path-style AWS `SigV4` signing.
    S3(S3Config),
}

/// Blob storage handle backed by [`StorageBackend`] and the `slabs_blobs` table.
#[derive(Debug, Clone)]
pub struct Storage {
    db: Db,
    backend: StorageBackend,
    http: reqwest::Client,
}

impl Storage {
    /// Create a local-filesystem storage handle rooted at `root_dir`.
    #[must_use]
    pub fn new(db: Db, root_dir: PathBuf) -> Self {
        Self::with_backend(db, StorageBackend::Local { root_dir })
    }

    /// Create a storage handle with an explicit [`StorageBackend`] and a 30-second HTTP timeout.
    #[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 }
    }

    /// Write `data` to the configured backend and insert its metadata row into `slabs_blobs`.
    ///
    /// Strips directory components from `filename` and guesses the MIME type when `content_type`
    /// is `None` or empty.
    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,
        })
    }

    /// Decode an uploaded image, resize it to fit within `max_width` by `max_height` preserving
    /// aspect ratio, re-encode it as PNG, and store it via [`Storage::put`].
    ///
    /// Normalizes the stored filename extension to `.png` and stores with content type `"image/png"`.
    #[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
    }

    /// Fetch a blob's metadata row from `slabs_blobs` and read its bytes from the backend.
    ///
    /// Returns [`SlabError::NotFound`] if `blob_id` does not exist in `slabs_blobs`.
    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))
    }

    /// Delete the `slabs_blobs` row for `blob_id` and remove its backend object on a best-effort basis.
    ///
    /// Succeeds without error if `blob_id` does not exist.
    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(())
    }

    /// Sign and send a path-style AWS Signature Version 4 (`SigV4`) S3 request.
    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);
    }
}