Skip to main content

renox_core/
storage.rs

1//! File storage on the local disk, or on S3-compatible storage (AWS S3,
2//! Cloudflare R2, MinIO) with the `s3` feature.
3//!
4//! Keys are relative paths like `products/abc.jpg`. Keys under `public/` are
5//! public: `storage.url(key)` links to them (served from `/storage/...` for the
6//! local disk, or `STORAGE_URL` for S3). Other keys are private; share them
7//! with `storage.temporary_url(key, ttl)`, a link that expires.
8//!
9//! `STORAGE_DISK=local` (default) keeps files in `STORAGE_PATH/app`.
10//! `STORAGE_DISK=s3` needs `S3_BUCKET`, `S3_REGION`, `S3_ACCESS_KEY_ID`,
11//! `S3_SECRET_ACCESS_KEY`, optionally `S3_ENDPOINT` (R2/MinIO) and
12//! `STORAGE_URL` (public base URL of the bucket or its CDN).
13//!
14//! More disks, each with a name, come from [`App::disk`](crate::App::disk),
15//! e.g. backups on another bucket; `state.disk_named("backups")` returns one:
16//!
17//! ```
18//! # use renox::prelude::*;
19//! use renox::storage::StorageConfig;
20//!
21//! # let _ =
22//! // BACKUPS_DISK=s3, BACKUPS_BUCKET=…; or BACKUPS_DISK=local, BACKUPS_PATH=…
23//! App::new().disk("backups", |config| StorageConfig::from_env(config, "BACKUPS"))
24//! # ;
25//! # async fn demo(state: AppState) -> Result {
26//! state.disk_named("backups")?.put("db/2026-10-03.sql.gz", vec![1, 2, 3].into()).await?;
27//! # Ok(()) }
28//! ```
29
30use std::path::{Component, Path, PathBuf};
31use std::time::Duration;
32
33use anyhow::Context;
34use axum::Router;
35use axum::body::Bytes;
36use axum::extract::{Path as UrlPath, State};
37use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE};
38use axum::response::{IntoResponse, Response};
39use axum::routing::get;
40
41use crate::signed::ValidSignature;
42use crate::{AppState, Config, Error, Result};
43
44#[derive(Clone)]
45enum Disk {
46    Local {
47        root: PathBuf,
48    },
49    #[cfg(feature = "s3")]
50    S3 {
51        store: std::sync::Arc<object_store::aws::AmazonS3>,
52        public_url: Option<String>,
53    },
54}
55
56/// A file storage disk: `state.storage`, or a named one from
57/// `state.disk_named(name)`.
58#[derive(Clone)]
59pub struct Storage {
60    disk: Disk,
61    /// `None` for `state.storage`, the name for `App::disk`'s disks.
62    name: Option<std::sync::Arc<str>>,
63    /// `APP_KEY`, for the encrypted files (`put_encrypted`).
64    key: Option<cookie::Key>,
65}
66
67/// Rejects keys that could escape the storage root.
68fn check_key(key: &str) -> Result<&str> {
69    let key = key.trim_start_matches('/');
70    let clean = !key.is_empty()
71        && Path::new(key)
72            .components()
73            .all(|c| matches!(c, Component::Normal(_)))
74        && !key.contains('\\');
75    if clean && !key.contains('\0') {
76        Ok(key)
77    } else {
78        Err(Error::BadRequest(format!(
79            "invalid storage key `{}`",
80            key.escape_debug()
81        )))
82    }
83}
84
85impl Storage {
86    pub(crate) fn from_config(config: &Config) -> anyhow::Result<Self> {
87        Self::open(&config.storage, config.storage_path.join("app"), None)
88    }
89
90    /// A named disk (`App::disk`), whose local files live in `settings.root`,
91    /// else `STORAGE_PATH/<name>`.
92    pub(crate) fn named(
93        config: &Config,
94        name: &str,
95        settings: &StorageConfig,
96    ) -> anyhow::Result<Self> {
97        Self::open(settings, config.storage_path.join(name), Some(name))
98    }
99
100    fn open(
101        settings: &StorageConfig,
102        default_root: PathBuf,
103        name: Option<&str>,
104    ) -> anyhow::Result<Self> {
105        let disk = match settings.disk {
106            DiskDriver::Local => Disk::Local {
107                root: settings.root.clone().unwrap_or(default_root),
108            },
109            #[cfg(feature = "s3")]
110            DiskDriver::S3 => s3(settings)?,
111            #[cfg(not(feature = "s3"))]
112            DiskDriver::S3 => {
113                let variable = match name {
114                    Some(name) => format!("the `{name}` disk's driver"),
115                    None => "STORAGE_DISK".to_owned(),
116                };
117                anyhow::bail!(
118                    "{variable}=s3 needs Renox's `s3` feature: renox = {{ features = [\"s3\"] }}"
119                )
120            }
121        };
122        Ok(Self {
123            disk,
124            name: name.map(Into::into),
125            key: None,
126        })
127    }
128
129    /// The disk with `APP_KEY` set, which `put_encrypted` and
130    /// `get_decrypted` need.
131    pub(crate) fn with_key(mut self, key: cookie::Key) -> Self {
132        self.key = Some(key);
133        self
134    }
135
136    fn app_key(&self) -> Result<&cookie::Key> {
137        self.key.as_ref().ok_or_else(|| {
138            anyhow::anyhow!("encrypted files need an APP_KEY (`rnx key:generate`)").into()
139        })
140    }
141
142    /// Encrypts `bytes` with AES-256-GCM and writes them to `key`. Each file
143    /// gets its own random data key, sealed with a key derived from `APP_KEY`
144    /// and kept in the file's header (`RNXE`, a version, the sealed key, the
145    /// nonce, the ciphertext). Read it back with [`get_decrypted`]; local
146    /// temporary URLs and `Download::decrypted` decrypt on the fly. A private
147    /// key (not under `public/`) is what you want: `/storage` serves files as
148    /// stored.
149    ///
150    /// ```
151    /// # use renox::prelude::*;
152    /// # async fn demo(state: AppState) -> Result {
153    /// state.storage.put_encrypted("ids/passport.jpg", vec![1, 2, 3].into()).await?;
154    /// let plain = state.storage.get_decrypted("ids/passport.jpg").await?;
155    /// assert_eq!(plain.as_deref(), Some(&[1u8, 2, 3][..]));
156    /// # Ok(()) }
157    /// ```
158    ///
159    /// [`get_decrypted`]: Storage::get_decrypted
160    pub async fn put_encrypted(&self, key: &str, bytes: Bytes) -> Result {
161        let sealed = crate::crypto::encrypt_file(self.app_key()?, &bytes)?;
162        self.put(key, sealed.into()).await
163    }
164
165    /// The decrypted content of a file written with [`put_encrypted`], or
166    /// `None` if there is no such key. Fails for a file that isn't encrypted,
167    /// was changed, or was sealed with another `APP_KEY`.
168    ///
169    /// [`put_encrypted`]: Storage::put_encrypted
170    pub async fn get_decrypted(&self, key: &str) -> Result<Option<Bytes>> {
171        let app_key = self.app_key()?;
172        match self.get(key).await? {
173            None => Ok(None),
174            Some(sealed) => Ok(Some(
175                crate::crypto::decrypt_file(app_key, &sealed)
176                    .with_context(|| format!("could not decrypt `{key}`"))?
177                    .into(),
178            )),
179        }
180    }
181
182    /// The file as a person may read it: decrypted when it is an encrypted
183    /// file this disk's `APP_KEY` opens, else as stored.
184    pub(crate) async fn get_readable(&self, key: &str) -> Result<Option<Bytes>> {
185        let Some(bytes) = self.get(key).await? else {
186            return Ok(None);
187        };
188        if let Some(app_key) = &self.key
189            && crate::crypto::is_encrypted_file(&bytes)
190            && let Ok(plain) = crate::crypto::decrypt_file(app_key, &bytes)
191        {
192            return Ok(Some(plain.into()));
193        }
194        Ok(Some(bytes))
195    }
196
197    /// Re-seals the encrypted files under `prefix` (`""` for the whole disk)
198    /// with this disk's `APP_KEY`, after the key was rotated: `old_app_key` is
199    /// the previous `APP_KEY` value. Only each file's header changes. Files
200    /// that aren't encrypted, or were already re-sealed, are skipped; the
201    /// count of files changed is returned.
202    pub async fn rewrap_encrypted(&self, prefix: &str, old_app_key: &str) -> Result<usize> {
203        let new = self.app_key()?;
204        let old = crate::crypto::parse_key(old_app_key)?;
205        let mut changed = 0;
206        for file in self.list(prefix).await? {
207            let Some(bytes) = self.get(&file.key).await? else {
208                continue;
209            };
210            if !crate::crypto::is_encrypted_file(&bytes)
211                || crate::crypto::decrypt_file(new, &bytes).is_ok()
212            {
213                continue;
214            }
215            let moved = crate::crypto::rewrap_file(&old, new, &bytes)
216                .with_context(|| format!("could not re-seal `{}`", file.key))?;
217            self.put(&file.key, moved.into()).await?;
218            changed += 1;
219        }
220        Ok(changed)
221    }
222
223    /// The disk's name: `None` for `state.storage`.
224    pub fn name(&self) -> Option<&str> {
225        self.name.as_deref()
226    }
227
228    /// Writes `bytes` to `key`, replacing any file there.
229    pub async fn put(&self, key: &str, bytes: Bytes) -> Result {
230        let key = check_key(key)?;
231        match &self.disk {
232            Disk::Local { root } => {
233                let path = root.join(key);
234                if let Some(dir) = path.parent() {
235                    tokio::fs::create_dir_all(dir)
236                        .await
237                        .with_context(|| format!("could not create {}", dir.display()))?;
238                }
239                tokio::fs::write(&path, &bytes)
240                    .await
241                    .with_context(|| format!("could not write {}", path.display()))?;
242            }
243            #[cfg(feature = "s3")]
244            Disk::S3 { store, .. } => {
245                use object_store::ObjectStoreExt;
246                store
247                    .put(&object_store::path::Path::from(key), bytes.into())
248                    .await
249                    .map_err(anyhow::Error::from)
250                    .with_context(|| format!("could not store `{key}`"))?;
251            }
252        }
253        Ok(())
254    }
255
256    /// The file's bytes, or `None` if there is no such key.
257    pub async fn get(&self, key: &str) -> Result<Option<Bytes>> {
258        let key = check_key(key)?;
259        match &self.disk {
260            Disk::Local { root } => match tokio::fs::read(root.join(key)).await {
261                Ok(bytes) => Ok(Some(bytes.into())),
262                Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
263                Err(err) => Err(anyhow::Error::from(err)
264                    .context(format!("could not read {}", root.join(key).display()))
265                    .into()),
266            },
267            #[cfg(feature = "s3")]
268            Disk::S3 { store, .. } => {
269                use object_store::ObjectStoreExt;
270                match store.get(&object_store::path::Path::from(key)).await {
271                    Ok(result) => Ok(Some(result.bytes().await.map_err(anyhow::Error::from)?)),
272                    Err(object_store::Error::NotFound { .. }) => Ok(None),
273                    Err(err) => Err(anyhow::Error::from(err)
274                        .context(format!("could not read `{key}`"))
275                        .into()),
276                }
277            }
278        }
279    }
280
281    /// Whether a file exists at `key`.
282    pub async fn exists(&self, key: &str) -> Result<bool> {
283        let key = check_key(key)?;
284        match &self.disk {
285            Disk::Local { root } => Ok(tokio::fs::try_exists(root.join(key)).await?),
286            #[cfg(feature = "s3")]
287            Disk::S3 { store, .. } => {
288                use object_store::ObjectStoreExt;
289                match store.head(&object_store::path::Path::from(key)).await {
290                    Ok(_) => Ok(true),
291                    Err(object_store::Error::NotFound { .. }) => Ok(false),
292                    Err(err) => Err(anyhow::Error::from(err).into()),
293                }
294            }
295        }
296    }
297
298    /// Deletes the file; deleting a missing key is not an error.
299    pub async fn delete(&self, key: &str) -> Result {
300        let key = check_key(key)?;
301        match &self.disk {
302            Disk::Local { root } => match tokio::fs::remove_file(root.join(key)).await {
303                Ok(()) => Ok(()),
304                Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
305                Err(err) => Err(anyhow::Error::from(err)
306                    .context(format!("could not delete {}", root.join(key).display()))
307                    .into()),
308            },
309            #[cfg(feature = "s3")]
310            Disk::S3 { store, .. } => {
311                use object_store::ObjectStoreExt;
312                match store.delete(&object_store::path::Path::from(key)).await {
313                    Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
314                    Err(err) => Err(anyhow::Error::from(err).into()),
315                }
316            }
317        }
318    }
319
320    /// The URL of a public file (a key under `public/`).
321    /// The files under `prefix` (a folder like `invoices/2026`, or `""`
322    /// for all), at any depth, sorted by key.
323    ///
324    /// ```
325    /// # use renox::prelude::*;
326    /// # async fn demo(state: AppState) -> Result {
327    /// for file in state.storage.list("invoices/2026").await? {
328    ///     println!("{} ({} bytes)", file.key, file.size);
329    /// }
330    /// state.storage.copy("public/logo.png", "public/logo-old.png").await?;
331    /// state.storage.rename("uploads/tmp/a.pdf", "invoices/2026/a.pdf").await?;
332    /// let removed = state.storage.delete_all("uploads/tmp").await?;
333    /// # let _ = removed; Ok(()) }
334    /// ```
335    pub async fn list(&self, prefix: &str) -> Result<Vec<FileInfo>> {
336        let prefix = check_prefix(prefix)?;
337        let mut files = match &self.disk {
338            Disk::Local { root } => {
339                let mut files = Vec::new();
340                let start = if prefix.is_empty() {
341                    root.clone()
342                } else {
343                    root.join(prefix)
344                };
345                let mut dirs = vec![start];
346                while let Some(dir) = dirs.pop() {
347                    let mut entries = match tokio::fs::read_dir(&dir).await {
348                        Ok(entries) => entries,
349                        Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
350                        Err(err) if err.kind() == std::io::ErrorKind::NotADirectory => continue,
351                        Err(err) => {
352                            return Err(anyhow::Error::from(err)
353                                .context(format!("could not list {}", dir.display()))
354                                .into());
355                        }
356                    };
357                    while let Some(entry) = entries.next_entry().await? {
358                        let meta = entry.metadata().await?;
359                        if meta.is_dir() {
360                            dirs.push(entry.path());
361                        } else if meta.is_file() {
362                            let relative = entry.path();
363                            let relative = relative.strip_prefix(root).unwrap_or(&relative);
364                            let key = relative
365                                .components()
366                                .map(|c| c.as_os_str().to_string_lossy())
367                                .collect::<Vec<_>>()
368                                .join("/");
369                            files.push(FileInfo {
370                                key,
371                                size: meta.len(),
372                                modified: meta.modified().ok().map(Into::into),
373                            });
374                        }
375                    }
376                }
377                files
378            }
379            #[cfg(feature = "s3")]
380            Disk::S3 { store, .. } => {
381                use futures_util::TryStreamExt;
382                use object_store::ObjectStore;
383                let path = (!prefix.is_empty()).then(|| object_store::path::Path::from(prefix));
384                store
385                    .list(path.as_ref())
386                    .map_ok(|meta| FileInfo {
387                        key: meta.location.to_string(),
388                        size: meta.size,
389                        modified: Some(meta.last_modified),
390                    })
391                    .try_collect()
392                    .await
393                    .map_err(anyhow::Error::from)?
394            }
395        };
396        files.sort_by(|a, b| a.key.cmp(&b.key));
397        Ok(files)
398    }
399
400    /// The size of a file in bytes, if it exists.
401    pub async fn size(&self, key: &str) -> Result<Option<u64>> {
402        let key = check_key(key)?;
403        match &self.disk {
404            Disk::Local { root } => match tokio::fs::metadata(root.join(key)).await {
405                Ok(meta) if meta.is_file() => Ok(Some(meta.len())),
406                Ok(_) => Ok(None),
407                Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
408                Err(err) => Err(anyhow::Error::from(err).into()),
409            },
410            #[cfg(feature = "s3")]
411            Disk::S3 { store, .. } => {
412                use object_store::ObjectStoreExt;
413                match store.head(&object_store::path::Path::from(key)).await {
414                    Ok(meta) => Ok(Some(meta.size)),
415                    Err(object_store::Error::NotFound { .. }) => Ok(None),
416                    Err(err) => Err(anyhow::Error::from(err).into()),
417                }
418            }
419        }
420    }
421
422    /// Copies a file, replacing `to` if it exists. A missing `from` is a
423    /// 404.
424    pub async fn copy(&self, from: &str, to: &str) -> Result {
425        let (from, to) = (check_key(from)?, check_key(to)?);
426        match &self.disk {
427            Disk::Local { root } => {
428                let target = root.join(to);
429                create_parent(&target).await?;
430                match tokio::fs::copy(root.join(from), &target).await {
431                    Ok(_) => Ok(()),
432                    Err(err) if err.kind() == std::io::ErrorKind::NotFound => Err(Error::NotFound),
433                    Err(err) => Err(anyhow::Error::from(err)
434                        .context(format!("could not copy `{from}` to `{to}`"))
435                        .into()),
436                }
437            }
438            #[cfg(feature = "s3")]
439            Disk::S3 { store, .. } => {
440                use object_store::ObjectStoreExt;
441                let (from, to) = (
442                    object_store::path::Path::from(from),
443                    object_store::path::Path::from(to),
444                );
445                match store.copy(&from, &to).await {
446                    Ok(()) => Ok(()),
447                    Err(object_store::Error::NotFound { .. }) => Err(Error::NotFound),
448                    Err(err) => Err(anyhow::Error::from(err).into()),
449                }
450            }
451        }
452    }
453
454    /// Moves a file (Laravel's `move`), replacing `to` if it exists. A
455    /// missing `from` is a 404.
456    pub async fn rename(&self, from: &str, to: &str) -> Result {
457        let (from, to) = (check_key(from)?, check_key(to)?);
458        match &self.disk {
459            Disk::Local { root } => {
460                let target = root.join(to);
461                create_parent(&target).await?;
462                match tokio::fs::rename(root.join(from), &target).await {
463                    Ok(()) => Ok(()),
464                    Err(err) if err.kind() == std::io::ErrorKind::NotFound => Err(Error::NotFound),
465                    Err(err) => Err(anyhow::Error::from(err)
466                        .context(format!("could not move `{from}` to `{to}`"))
467                        .into()),
468                }
469            }
470            #[cfg(feature = "s3")]
471            Disk::S3 { store, .. } => {
472                use object_store::ObjectStoreExt;
473                let (from, to) = (
474                    object_store::path::Path::from(from),
475                    object_store::path::Path::from(to),
476                );
477                match store.rename(&from, &to).await {
478                    Ok(()) => Ok(()),
479                    Err(object_store::Error::NotFound { .. }) => Err(Error::NotFound),
480                    Err(err) => Err(anyhow::Error::from(err).into()),
481                }
482            }
483        }
484    }
485
486    /// Deletes every file under `prefix` (not `""`: that would be all of
487    /// them); returns how many.
488    pub async fn delete_all(&self, prefix: &str) -> Result<usize> {
489        if check_prefix(prefix)?.is_empty() {
490            return Err(Error::BadRequest(
491                "delete_all needs a folder, not the whole disk".into(),
492            ));
493        }
494        let files = self.list(prefix).await?;
495        for file in &files {
496            self.delete(&file.key).await?;
497        }
498        Ok(files.len())
499    }
500
501    /// The public URL of `key` (under `public/`): `/storage/…` on the local
502    /// disk, or under `STORAGE_URL` on S3 when set.
503    pub fn url(&self, key: &str) -> String {
504        let key = key.trim_start_matches('/');
505        let rest = key.strip_prefix("public/").unwrap_or(key);
506        // A named disk's public files are served by `/_renox/disks/<name>/public/…`.
507        if let Some(name) = &self.name {
508            #[cfg(feature = "s3")]
509            if let Disk::S3 {
510                public_url: Some(base),
511                ..
512            } = &self.disk
513            {
514                return format!("{}/{}", base.trim_end_matches('/'), encode_path(key));
515            }
516            return format!(
517                "/_renox/disks/{}/public/{}",
518                encode_path(name),
519                encode_path(rest)
520            );
521        }
522        match &self.disk {
523            Disk::Local { .. } => format!("/storage/{}", encode_path(rest)),
524            #[cfg(feature = "s3")]
525            Disk::S3 { public_url, .. } => match public_url {
526                Some(base) => format!("{}/{}", base.trim_end_matches('/'), encode_path(key)),
527                None => format!("/storage/{}", encode_path(rest)),
528            },
529        }
530    }
531
532    /// A link to any file that works for `ttl`: signed by Renox for the local
533    /// disk, presigned by S3 otherwise (for at most 7 days).
534    pub async fn temporary_url(
535        &self,
536        state: &AppState,
537        key: &str,
538        ttl: Duration,
539    ) -> Result<String> {
540        let key = check_key(key)?;
541        match &self.disk {
542            Disk::Local { .. } => match &self.name {
543                Some(name) => state.sign_path(
544                    &format!("/_renox/disks/{}/{}", encode_path(name), encode_path(key)),
545                    ttl,
546                ),
547                None => state.sign_path(&format!("/_renox/files/{}", encode_path(key)), ttl),
548            },
549            #[cfg(feature = "s3")]
550            Disk::S3 { store, .. } => {
551                use object_store::signer::Signer;
552                // S3 presigns for at most 7 days.
553                let ttl = ttl.min(Duration::from_secs(7 * 24 * 60 * 60));
554                let url = store
555                    .signed_url(
556                        axum::http::Method::GET,
557                        &object_store::path::Path::from(key),
558                        ttl,
559                    )
560                    .await
561                    .map_err(anyhow::Error::from)?;
562                Ok(url.to_string())
563            }
564        }
565    }
566
567    /// Where public local files live, for serving `/storage`.
568    pub(crate) fn public_root(&self) -> Option<PathBuf> {
569        match &self.disk {
570            Disk::Local { root } if self.name.is_none() => Some(root.join("public")),
571            Disk::Local { .. } => None,
572            #[cfg(feature = "s3")]
573            Disk::S3 { .. } => None,
574        }
575    }
576}
577
578/// A folder prefix: `""` or a clean relative path.
579fn check_prefix(prefix: &str) -> Result<&str> {
580    let prefix = prefix.trim_matches('/');
581    if prefix.is_empty() {
582        return Ok(prefix);
583    }
584    check_key(prefix)
585}
586
587async fn create_parent(path: &Path) -> Result {
588    if let Some(dir) = path.parent() {
589        tokio::fs::create_dir_all(dir)
590            .await
591            .with_context(|| format!("could not create {}", dir.display()))?;
592    }
593    Ok(())
594}
595
596/// A stored file; from [`Storage::list`].
597#[derive(Debug, Clone, serde::Serialize)]
598#[non_exhaustive]
599pub struct FileInfo {
600    /// Its key, e.g. `invoices/2026/a.pdf`.
601    pub key: String,
602    /// Its size in bytes.
603    pub size: u64,
604    /// When it last changed, if the disk says.
605    pub modified: Option<chrono::DateTime<chrono::Utc>>,
606}
607
608fn encode_path(key: &str) -> String {
609    let mut out = String::new();
610    crate::routing::encode(&mut out, key, true);
611    out
612}
613
614setting_enum! {
615    /// Where a disk keeps its files, from `STORAGE_DISK` (or `<PREFIX>_DISK`).
616    pub enum DiskDriver ("STORAGE_DISK") {
617        /// A folder on this server (the default).
618        Local = "local",
619        /// An S3-compatible bucket (AWS S3, Cloudflare R2, MinIO); needs the `s3` feature.
620        S3 = "s3",
621    }
622}
623
624/// Settings for `state.storage`, from `STORAGE_DISK` and `S3_*`.
625#[derive(Clone)]
626#[non_exhaustive]
627pub struct StorageConfig {
628    /// A local folder or an S3 bucket.
629    pub disk: DiskDriver,
630    /// The S3 bucket, from `S3_BUCKET`.
631    pub bucket: Option<String>,
632    /// The S3 region, from `S3_REGION`.
633    pub region: Option<String>,
634    /// An S3-compatible endpoint, from `S3_ENDPOINT` (AWS when unset).
635    pub endpoint: Option<String>,
636    /// The S3 access key id, from `S3_ACCESS_KEY_ID`.
637    pub access_key_id: Option<String>,
638    /// The S3 secret key, from `S3_SECRET_ACCESS_KEY`.
639    pub secret_access_key: Option<String>,
640    /// Public base URL for keys under `public/` (bucket URL or CDN), for S3.
641    pub url: Option<String>,
642    /// Where a local disk keeps its files. `None`: `STORAGE_PATH/app` for
643    /// `state.storage`, `STORAGE_PATH/<name>` for a named disk.
644    pub root: Option<PathBuf>,
645}
646
647impl std::fmt::Debug for StorageConfig {
648    // Secrets show as `[hidden]`, so a logged config doesn't leak them.
649    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
650        f.debug_struct("StorageConfig")
651            .field("disk", &self.disk)
652            .field("bucket", &self.bucket)
653            .field("region", &self.region)
654            .field("endpoint", &self.endpoint)
655            .field("access_key_id", &self.access_key_id)
656            .field(
657                "secret_access_key",
658                &self.secret_access_key.as_ref().map(|_| "[hidden]"),
659            )
660            .field("url", &self.url)
661            .field("root", &self.root)
662            .finish()
663    }
664}
665
666impl StorageConfig {
667    /// A disk's settings from variables starting with `prefix`, for
668    /// [`App::disk`](crate::App::disk): `<PREFIX>_DISK` (`local` or `s3`,
669    /// default `local`), `<PREFIX>_PATH` (a local disk's folder),
670    /// `<PREFIX>_BUCKET`, `<PREFIX>_URL`, and `<PREFIX>_REGION`,
671    /// `<PREFIX>_ENDPOINT`, `<PREFIX>_ACCESS_KEY_ID`,
672    /// `<PREFIX>_SECRET_ACCESS_KEY`, which fall back to the `S3_*` ones.
673    pub fn from_env(config: &Config, prefix: &str) -> Result<Self> {
674        let prefix = prefix.trim_end_matches('_').to_ascii_uppercase();
675        let var = |name: &str| config.var(&format!("{prefix}_{name}"));
676        let shared = |name: &str, fallback: &Option<String>| var(name).or_else(|| fallback.clone());
677        Ok(Self {
678            disk: var("DISK")
679                .map(|v| DiskDriver::parse_as(&v, &format!("{prefix}_DISK")))
680                .transpose()?
681                .unwrap_or(DiskDriver::Local),
682            bucket: var("BUCKET"),
683            region: shared("REGION", &config.storage.region),
684            endpoint: shared("ENDPOINT", &config.storage.endpoint),
685            access_key_id: shared("ACCESS_KEY_ID", &config.storage.access_key_id),
686            secret_access_key: shared("SECRET_ACCESS_KEY", &config.storage.secret_access_key),
687            url: var("URL"),
688            root: var("PATH").map(PathBuf::from),
689        })
690    }
691}
692
693impl Default for StorageConfig {
694    fn default() -> Self {
695        Self {
696            disk: DiskDriver::Local,
697            bucket: None,
698            region: None,
699            endpoint: None,
700            access_key_id: None,
701            secret_access_key: None,
702            url: None,
703            root: None,
704        }
705    }
706}
707
708#[cfg(feature = "s3")]
709fn s3(config: &StorageConfig) -> anyhow::Result<Disk> {
710    use anyhow::Context;
711    let mut builder = object_store::aws::AmazonS3Builder::new()
712        .with_bucket_name(
713            config
714                .bucket
715                .clone()
716                .context("S3_BUCKET is required for STORAGE_DISK=s3")?,
717        )
718        .with_region(config.region.clone().unwrap_or_else(|| "auto".into()));
719    if let Some(endpoint) = &config.endpoint {
720        // A local MinIO or SeaweedFS usually speaks plain http.
721        builder = builder
722            .with_endpoint(endpoint)
723            .with_allow_http(endpoint.starts_with("http://"))
724            .with_virtual_hosted_style_request(false);
725    }
726    if let (Some(id), Some(secret)) = (&config.access_key_id, &config.secret_access_key) {
727        builder = builder
728            .with_access_key_id(id)
729            .with_secret_access_key(secret);
730    }
731    Ok(Disk::S3 {
732        store: std::sync::Arc::new(builder.build()?),
733        public_url: config.url.clone(),
734    })
735}
736
737/// `/_renox/files/{key}?expires=…&signature=…` for local temporary URLs.
738pub(crate) fn router() -> Router<AppState> {
739    Router::new()
740        .route("/_renox/files/{*key}", get(private_file))
741        .route("/_renox/disks/{disk}/{*key}", get(disk_file))
742        .layer(axum::middleware::map_response(
743            crate::app::user_file_headers,
744        ))
745}
746
747async fn private_file(
748    _: ValidSignature,
749    State(state): State<AppState>,
750    UrlPath(key): UrlPath<String>,
751) -> Result<Response> {
752    file_response(&state.storage, &key).await
753}
754
755/// A named disk's file: anyone may read `public/…`, the rest needs a
756/// signed link from `temporary_url`.
757async fn disk_file(
758    State(state): State<AppState>,
759    UrlPath((disk, key)): UrlPath<(String, String)>,
760    uri: axum::http::Uri,
761) -> Result<Response> {
762    let storage = state.disks.get(&disk).ok_or(Error::NotFound)?;
763    let public = key.starts_with("public/");
764    if !public && !crate::signed::verify(&state, &uri) {
765        return Err(Error::Forbidden);
766    }
767    let mut res = file_response(storage, &key).await?;
768    if public {
769        res.headers_mut().insert(
770            CACHE_CONTROL,
771            axum::http::HeaderValue::from_static("public, max-age=3600"),
772        );
773    }
774    Ok(res)
775}
776
777async fn file_response(storage: &Storage, key: &str) -> Result<Response> {
778    // An encrypted file is decrypted for the (authorized) request.
779    let bytes = storage.get_readable(key).await?.ok_or(Error::NotFound)?;
780    let upload = crate::upload::Upload::new(key, "", bytes.clone());
781    let content_type = upload.sniffed_type().unwrap_or("application/octet-stream");
782    Ok((
783        [
784            (CONTENT_TYPE, content_type),
785            (CACHE_CONTROL, "private, max-age=0"),
786        ],
787        bytes,
788    )
789        .into_response())
790}
791
792#[cfg(test)]
793mod tests {
794    use super::*;
795
796    #[test]
797    fn keys_cannot_escape_the_root() {
798        assert!(check_key("products/a.jpg").is_ok());
799        assert!(check_key("/products/a.jpg").is_ok());
800        for bad in ["../etc/passwd", "products/../../x", "", "a\\..\\b", "./x"] {
801            assert!(check_key(bad).is_err(), "{bad}");
802        }
803    }
804
805    fn local(root: &Path, name: Option<&str>) -> Storage {
806        let settings = StorageConfig::default();
807        Storage::open(&settings, root.to_path_buf(), name).unwrap()
808    }
809
810    /// A named disk can't use S3 without the feature, and the error names
811    /// the disk; only the default disk serves public files.
812    #[test]
813    fn named_disks_are_named_in_errors_and_serve_nothing() {
814        let dir = tempfile::tempdir().unwrap();
815        #[cfg(not(feature = "s3"))]
816        {
817            let settings = StorageConfig {
818                disk: DiskDriver::S3,
819                ..StorageConfig::default()
820            };
821            let err = Storage::open(&settings, dir.path().to_path_buf(), Some("backups"))
822                .err()
823                .unwrap();
824            assert!(
825                err.to_string().contains("the `backups` disk's driver=s3"),
826                "{err}"
827            );
828        }
829        assert!(local(dir.path(), Some("backups")).public_root().is_none());
830        assert!(local(dir.path(), None).public_root().is_some());
831    }
832
833    /// Local disk errors other than "not there" are errors naming the
834    /// path or keys, not `None`/404.
835    #[cfg(unix)]
836    #[tokio::test]
837    async fn local_disk_errors_name_what_failed() {
838        let dir = tempfile::tempdir().unwrap();
839        let disk = local(dir.path(), None);
840        disk.put("docs/a.txt", Bytes::from_static(b"a"))
841            .await
842            .unwrap();
843        disk.put("full/b.txt", Bytes::from_static(b"b"))
844            .await
845            .unwrap();
846        // A folder read as a file.
847        let err = disk.get("docs").await.unwrap_err();
848        assert!(format!("{err:?}").contains("could not read"), "{err:?}");
849        // A file used as a folder.
850        assert!(disk.size("docs/a.txt/inner").await.is_err());
851        let err = disk.copy("docs", "copy.txt").await.unwrap_err();
852        assert!(
853            format!("{err:?}").contains("could not copy `docs`"),
854            "{err:?}"
855        );
856        // A file moved onto a folder that has files.
857        let err = disk.rename("docs/a.txt", "full").await.unwrap_err();
858        assert!(
859            format!("{err:?}").contains("could not move `docs/a.txt`"),
860            "{err:?}"
861        );
862        // A symbolic link is listed as neither file nor folder; a link that
863        // points at itself can't be listed.
864        std::os::unix::fs::symlink(dir.path().join("docs/loop"), dir.path().join("docs/loop"))
865            .unwrap();
866        let keys: Vec<_> = disk
867            .list("docs")
868            .await
869            .unwrap()
870            .into_iter()
871            .map(|f| f.key)
872            .collect();
873        assert_eq!(keys, ["docs/a.txt"]);
874        let err = disk.list("docs/loop").await.unwrap_err();
875        assert!(format!("{err:?}").contains("could not list"), "{err:?}");
876    }
877}