Skip to main content

larust_storage/
lib.rs

1//! Laravel's `Storage::disk('local')`/`Storage::disk('public')`.
2//! `local()`/`public()` are - deliberately, still - plain, zero-config,
3//! compile-time-checked functions, not a stringly-typed `disk(name)`
4//! lookup with a runtime-failable name: there's nothing to look up for
5//! the two disks every app already has.
6//!
7//! `public()`'s root is `public/` itself - this framework's *existing*
8//! static-file docroot (`larust_core::Application::serve()`'s
9//! `ServeDir::new("public")`) - so a file written to `public/uploads/x.png`
10//! is already reachable at `/uploads/x.png` with no symlink machinery,
11//! unlike Laravel's own `storage/app/public` ↔ `public/storage` symlink
12//! convention.
13//!
14//! [`FilesystemConfig`] is the additive answer to "a third, named disk" -
15//! an app that genuinely needs a disk name to come from configuration (or
16//! just wants more than two disks) declares its own `config/filesystems.rs`
17//! (Laravel's own `config/filesystems.php`, real Rust instead), the same
18//! HashMap-of-named-configs shape `larust_orm::DatabaseConnections`
19//! already established for exactly this "explicit, app-owned, fails
20//! loudly on an unknown name" pattern - not a second, competing design
21//! invented just for this. `local()`/`public()` stay entirely untouched.
22
23use larust_core::axum::http::StatusCode;
24use larust_core::AppError;
25use std::collections::HashMap;
26use std::path::{Component, Path, PathBuf};
27
28/// Root: `storage/app/` (Laravel's own convention) - private, never
29/// served. `url()` always returns `None` on the disk this returns.
30pub fn local() -> Disk {
31    local_at(".")
32}
33
34/// Returns the private disk rooted below an explicit application root.
35pub fn local_at(root: impl AsRef<Path>) -> Disk {
36    Disk {
37        root: root.as_ref().join("storage/app"),
38        url_prefix: None,
39    }
40}
41
42/// Root: `public/` - this framework's existing static-file docroot.
43/// `url()` returns a `/`-prefixed, directly request-usable path.
44pub fn public() -> Disk {
45    public_at(".")
46}
47
48/// Returns the public disk rooted below an explicit application root.
49/// Use this with `Application::paths()` when a binary is launched from a
50/// directory other than its project root.
51pub fn public_at(root: impl AsRef<Path>) -> Disk {
52    Disk {
53        root: root.as_ref().join("public"),
54        url_prefix: Some(String::new()),
55    }
56}
57
58pub struct Disk {
59    root: PathBuf,
60    // `String`, not `&'static str` - the two built-in disks above only
61    // ever need a literal, but a [`DiskConfig`]-declared disk's prefix is
62    // built at runtime (from `.env`/config), which can't be `'static`
63    // without leaking memory. Both cases fit this one owned type equally
64    // well, so there's no reason for the built-in disks to keep the
65    // narrower one.
66    url_prefix: Option<String>,
67}
68
69impl Disk {
70    /// Writes `contents` to `path`, lazily creating any missing parent
71    /// directories first (`tokio::fs::create_dir_all`) - a disk's root
72    /// (or any subdirectory under it, e.g. `uploads/`) need not already
73    /// exist on disk before the first `put()`.
74    pub async fn put(&self, path: &str, contents: &[u8]) -> Result<(), AppError> {
75        let target = safe_join(&self.root, path)?;
76        reject_symlink_ancestors(&self.root, path).await?;
77        if let Some(parent) = target.parent() {
78            tokio::fs::create_dir_all(parent)
79                .await
80                .map_err(|source| AppError::Internal(Box::new(source)))?;
81        }
82        tokio::fs::write(&target, contents)
83            .await
84            .map_err(|source| AppError::Internal(Box::new(source)))
85    }
86
87    /// Returns `Ok(None)` for a missing file - not an error, the same
88    /// "a miss is a normal outcome" shape `larust_cache::get`'s own
89    /// `Result<Option<T>, AppError>` already established. A real I/O
90    /// failure (permissions, a disk error) is still `Err`.
91    pub async fn get(&self, path: &str) -> Result<Option<Vec<u8>>, AppError> {
92        let target = safe_join(&self.root, path)?;
93        reject_symlink_ancestors(&self.root, path).await?;
94        match tokio::fs::read(&target).await {
95            Ok(bytes) => Ok(Some(bytes)),
96            Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
97            Err(source) => Err(AppError::Internal(Box::new(source))),
98        }
99    }
100
101    pub async fn exists(&self, path: &str) -> Result<bool, AppError> {
102        let target = safe_join(&self.root, path)?;
103        reject_symlink_ancestors(&self.root, path).await?;
104        tokio::fs::try_exists(&target)
105            .await
106            .map_err(|source| AppError::Internal(Box::new(source)))
107    }
108
109    /// Not an error to delete a key that's already gone - same shape as
110    /// `larust_cache::forget`'s own "not an error to forget an
111    /// already-missing key" precedent.
112    pub async fn delete(&self, path: &str) -> Result<(), AppError> {
113        let target = safe_join(&self.root, path)?;
114        reject_symlink_ancestors(&self.root, path).await?;
115        match tokio::fs::remove_file(&target).await {
116            Ok(()) => Ok(()),
117            Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(()),
118            Err(source) => Err(AppError::Internal(Box::new(source))),
119        }
120    }
121
122    /// `Ok(None)` on `local()` (nothing under `storage/app/` is ever
123    /// served); `Ok(Some(...))`-with-a-`/`-prefixed, directly
124    /// request-usable path on `public()`. Runs `path` through the same
125    /// validation `put`/`get`/`exists`/`delete` do - an earlier version
126    /// of this method skipped that check entirely, which was inconsistent
127    /// (every other `Disk` method validates its path) without being
128    /// itself a traversal bug (`url()` never touches disk) - still worth
129    /// closing so a caller can't be misled into building a URL for a path
130    /// that `put`/`get` would actually reject. Does not check that `path`
131    /// already exists as a *file* - a URL can be built for one about to
132    /// be `put()`.
133    pub fn url(&self, path: &str) -> Result<Option<String>, AppError> {
134        let Some(prefix) = self.url_prefix.as_deref() else {
135            return Ok(None);
136        };
137        safe_join(&self.root, path)?;
138        Ok(Some(format!("{prefix}/{path}")))
139    }
140}
141
142/// One named disk's declaration inside a [`FilesystemConfig`] - a root
143/// path and, for a publicly-served disk, the URL prefix files under it
144/// are reachable at. Built with [`DiskConfig::private`]/[`DiskConfig::public`]
145/// rather than a struct literal, mirroring `local()`/`public()`'s own
146/// private-vs-served distinction (`url_prefix: None` vs `Some(..)`) so a
147/// config-declared disk can't accidentally end up in a state neither of
148/// the two built-in disks can.
149pub struct DiskConfig {
150    root: PathBuf,
151    url_prefix: Option<String>,
152}
153
154impl DiskConfig {
155    /// A disk with no URL at all - `Disk::url()` always returns `None`,
156    /// the same as [`local()`].
157    pub fn private(root: impl Into<PathBuf>) -> Self {
158        Self {
159            root: root.into(),
160            url_prefix: None,
161        }
162    }
163
164    /// A disk served at `url_prefix` - the same shape [`public()`] gives
165    /// you for `public/` itself, for a *different* root your app also
166    /// serves (e.g. a CDN-fronted directory, or a second `ServeDir` your
167    /// own `routes/web.rs` registers).
168    pub fn public(root: impl Into<PathBuf>, url_prefix: impl Into<String>) -> Self {
169        Self {
170            root: root.into(),
171            url_prefix: Some(url_prefix.into()),
172        }
173    }
174}
175
176/// A named collection of additional disks, declared by the app itself
177/// (typically in a `config/filesystems.rs` it writes, the same
178/// "add-your-own-config-file-when-you-need-it" pattern `config/blog.rs`-
179/// style app-specific config already establishes) - see this module's
180/// own doc comment for why this exists alongside, not instead of,
181/// `local()`/`public()`.
182///
183/// # Example
184///
185/// ```
186/// use larust_storage::{DiskConfig, FilesystemConfig};
187///
188/// // config/filesystems.rs
189/// fn config() -> FilesystemConfig {
190///     FilesystemConfig::new()
191///         .with_disk("exports", DiskConfig::private("storage/exports"))
192///         .with_disk("avatars", DiskConfig::public("storage/avatars", "/avatars"))
193/// }
194///
195/// # async fn example() -> Result<(), larust_core::AppError> {
196/// let filesystems = config();
197/// let exports = filesystems.disk("exports")?;
198/// exports.put("2024-01.csv", b"id,total\n").await?;
199/// # Ok(())
200/// # }
201/// ```
202#[derive(Default)]
203pub struct FilesystemConfig {
204    disks: HashMap<String, DiskConfig>,
205}
206
207impl FilesystemConfig {
208    pub fn new() -> Self {
209        Self::default()
210    }
211
212    /// Declares a disk under `name` - `with_*`, not a same-named `disk`,
213    /// so this builder method and [`FilesystemConfig::disk`]'s own
214    /// Laravel-shaped lookup (`Storage::disk('name')`) can both exist
215    /// without a name collision, matching this codebase's own existing
216    /// `with_error_pages`/`with_graceful_shutdown`/`with_sessions`
217    /// builder-method convention. Declaring the same name twice silently
218    /// keeps the *last* one - unlike `CommandRegistry::register`/
219    /// `JobRegistry::register`'s own panic-on-duplicate, a config file is
220    /// read top-to-bottom once at startup, not accumulated across
221    /// independent call sites the way those two registries are, so a
222    /// repeated name here is far more likely to be a deliberate override
223    /// (or a copy-pasted block someone forgot to rename) than the kind of
224    /// silently-shadowed registration a panic exists to catch.
225    #[must_use]
226    pub fn with_disk(mut self, name: impl Into<String>, config: DiskConfig) -> Self {
227        self.disks.insert(name.into(), config);
228        self
229    }
230
231    /// Looks up a declared disk by name - Laravel's own
232    /// `Storage::disk('name')`. Fails clearly - naming the missing key -
233    /// rather than panicking or silently falling back to some default,
234    /// the same "explicit, fails loudly on an unknown name" contract
235    /// `larust_orm::DatabaseConnections`'s own connection lookup already
236    /// established.
237    pub fn disk(&self, name: &str) -> Result<Disk, AppError> {
238        let config = self.disks.get(name).ok_or_else(|| {
239            AppError::Config(Box::new(std::io::Error::other(format!(
240                "no disk named {name:?} in FilesystemConfig - declared disks: {:?}",
241                {
242                    let mut names: Vec<&str> = self.disks.keys().map(String::as_str).collect();
243                    names.sort_unstable();
244                    names
245                }
246            ))))
247        })?;
248        Ok(Disk {
249            root: config.root.clone(),
250            url_prefix: config.url_prefix.clone(),
251        })
252    }
253}
254
255/// Rejects paths containing an existing symbolic-link ancestor. This closes
256/// the common deployment/configuration mistake where an upload directory is
257/// linked outside its configured disk root. A fully race-free guarantee
258/// requires platform-specific `openat`/`O_NOFOLLOW` style APIs, so callers
259/// should still keep storage roots owned by the application account.
260async fn reject_symlink_ancestors(root: &Path, relative: &str) -> Result<(), AppError> {
261    let mut current = root.to_path_buf();
262    for component in Path::new(relative).components() {
263        current.push(component.as_os_str());
264        match tokio::fs::symlink_metadata(&current).await {
265            Ok(metadata) if metadata.file_type().is_symlink() => return Err(invalid_path()),
266            Ok(_) => {}
267            Err(source) if source.kind() == std::io::ErrorKind::NotFound => break,
268            Err(source) => return Err(AppError::Internal(Box::new(source))),
269        }
270    }
271    Ok(())
272}
273
274/// Rejects anything except plain path segments - no `..`, no leading
275/// `/`, no Windows drive prefix (`Component::ParentDir`/`RootDir`/`Prefix`
276/// are all rejected, only `Component::Normal` passes, and an *empty*
277/// path - zero components at all - is rejected too, see below) - *before*
278/// ever joining onto `root`, so a rejected path never touches the
279/// filesystem at all. Checking components directly (not
280/// `canonicalize()`-then-check) is what makes this work for `put()` too,
281/// where the target doesn't exist yet - `canonicalize()` requires the
282/// path to already exist.
283///
284/// The empty-path case matters more than it looks: `Path::new("")
285/// .components()` yields zero components, so a naive "reject on a
286/// non-`Normal` component" loop passes it vacuously, and
287/// `root.join("")` returns `root` itself - meaning `Disk::put("", ..)`
288/// would write *the disk's own root* as a plain file, clobbering the
289/// directory `ServeDir::new("public")` (or `local()`'s `storage/app/`)
290/// expects to find there. Confirmed exploitable on a fresh checkout
291/// specifically (before the root directory exists at all - `put()`'s own
292/// `create_dir_all` has nothing to create for an empty relative path, so
293/// `write()` proceeds and creates a file named `public` in its place).
294///
295/// Two things this function deliberately does **not** defend against,
296/// scoped out rather than overlooked: it assumes every directory inside
297/// `root` is a real directory, never a symlink pointing outside it
298/// (nothing in this codebase creates one, but a future deploy/mount step
299/// could) - this only guards the *string* shape of `path`, not what the
300/// OS resolves it to. And it guards against *escaping* `root`, not
301/// against two different callers colliding on the same in-root path -
302/// `put()` silently overwrites whatever was already at `path`, the same
303/// way `tokio::fs::write` always does.
304fn safe_join(root: &Path, relative: &str) -> Result<PathBuf, AppError> {
305    let mut saw_a_component = false;
306    for component in Path::new(relative).components() {
307        if !matches!(component, Component::Normal(_)) {
308            return Err(invalid_path());
309        }
310        saw_a_component = true;
311    }
312    if !saw_a_component {
313        return Err(invalid_path());
314    }
315    Ok(root.join(relative))
316}
317
318fn invalid_path() -> AppError {
319    AppError::Http {
320        status: StatusCode::BAD_REQUEST,
321        message: "invalid storage path".to_string(),
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    // A scoped `tempfile::tempdir()` root, not the real `local()`/
330    // `public()` roots - those are CWD-relative (`storage/app`/`public`),
331    // which would pollute this crate's own directory during `cargo test`.
332    // `Disk`'s fields are private, so a direct struct literal is only
333    // reachable from tests in this same module, not from an app or an
334    // integration test in `tests/*.rs` - `local()`/`public()` are the
335    // only real, public ways to get a `Disk`.
336    fn disk(root: &Path, url_prefix: Option<&str>) -> Disk {
337        Disk {
338            root: root.to_path_buf(),
339            url_prefix: url_prefix.map(String::from),
340        }
341    }
342
343    #[tokio::test]
344    async fn put_get_exists_and_delete_round_trip() {
345        let dir = tempfile::tempdir().unwrap();
346        let disk = disk(dir.path(), Some(""));
347
348        assert!(!disk.exists("greeting.txt").await.unwrap());
349        assert_eq!(disk.get("greeting.txt").await.unwrap(), None);
350
351        disk.put("greeting.txt", b"hello").await.unwrap();
352        assert!(disk.exists("greeting.txt").await.unwrap());
353        assert_eq!(
354            disk.get("greeting.txt").await.unwrap(),
355            Some(b"hello".to_vec())
356        );
357
358        // Overwrite.
359        disk.put("greeting.txt", b"goodbye").await.unwrap();
360        assert_eq!(
361            disk.get("greeting.txt").await.unwrap(),
362            Some(b"goodbye".to_vec())
363        );
364
365        disk.delete("greeting.txt").await.unwrap();
366        assert!(!disk.exists("greeting.txt").await.unwrap());
367        assert_eq!(disk.get("greeting.txt").await.unwrap(), None);
368
369        // Deleting an already-missing key is not an error.
370        disk.delete("greeting.txt").await.unwrap();
371    }
372
373    #[tokio::test]
374    async fn put_lazily_creates_missing_parent_directories() {
375        let dir = tempfile::tempdir().unwrap();
376        let disk = disk(dir.path(), Some(""));
377
378        // `uploads/` doesn't exist yet under `dir` - this is the exact
379        // scenario a fresh `xr new` app's `public/uploads` was in before
380        // this crate existed (no code path created it ahead of time).
381        disk.put("uploads/photo.png", b"fake-bytes").await.unwrap();
382        assert_eq!(
383            disk.get("uploads/photo.png").await.unwrap(),
384            Some(b"fake-bytes".to_vec())
385        );
386    }
387
388    #[tokio::test]
389    async fn url_reflects_the_disks_prefix() {
390        let dir = tempfile::tempdir().unwrap();
391        let public_like = disk(dir.path(), Some(""));
392        let local_like = disk(dir.path(), None);
393
394        assert_eq!(
395            public_like.url("uploads/photo.png").unwrap(),
396            Some("/uploads/photo.png".to_string())
397        );
398        assert_eq!(local_like.url("uploads/photo.png").unwrap(), None);
399    }
400
401    #[tokio::test]
402    async fn url_validates_its_path_the_same_as_put_and_get() {
403        let dir = tempfile::tempdir().unwrap();
404        let disk = disk(dir.path(), Some(""));
405
406        assert!(disk.url("../secret.txt").is_err());
407        assert!(disk.url("").is_err());
408    }
409
410    /// `local()`/`public()` are hardcoded literals with no test anywhere
411    /// exercising `local()` at all otherwise - a typo in its root or
412    /// `url_prefix` would go completely undetected (`public()`'s
413    /// equivalents are at least proven correct end to end by
414    /// `demo/tests/upload_test.rs`, which calls the real `storage::
415    /// public()`).
416    #[test]
417    fn local_and_public_have_the_expected_shape() {
418        assert_eq!(local().url("x.txt").unwrap(), None);
419        assert_eq!(public().url("x.txt").unwrap(), Some("/x.txt".to_string()));
420    }
421
422    #[tokio::test]
423    async fn an_existing_symlink_ancestor_is_rejected() {
424        let dir = tempfile::tempdir().unwrap();
425        let root = dir.path().join("disk");
426        let outside = dir.path().join("outside");
427        tokio::fs::create_dir_all(&root).await.unwrap();
428        tokio::fs::create_dir_all(&outside).await.unwrap();
429
430        #[cfg(unix)]
431        std::os::unix::fs::symlink(&outside, root.join("linked")).unwrap();
432        #[cfg(windows)]
433        {
434            // Unlike Unix, creating a symlink on Windows needs either
435            // Administrator rights or Developer Mode enabled
436            // (`SeCreateSymbolicLinkPrivilege`) - a real, common gap on a
437            // freshly installed machine, not a framework bug. Skip rather
438            // than `.unwrap()`: failing to even create the fixture would
439            // otherwise panic this test and, since `cargo test --workspace`
440            // stops at the first failing crate, silently abort every
441            // later crate's tests too (alphabetically after `larust-
442            // storage`) without them ever running.
443            if let Err(e) = std::os::windows::fs::symlink_dir(&outside, root.join("linked")) {
444                if e.raw_os_error() == Some(1314) {
445                    eprintln!(
446                        "skipping an_existing_symlink_ancestor_is_rejected: \
447                         creating a symlink needs Administrator rights or \
448                         Developer Mode enabled on this machine"
449                    );
450                    return;
451                }
452                panic!("unexpected error creating test symlink: {e}");
453            }
454        }
455
456        let disk = disk(&root, Some(""));
457        assert!(disk.put("linked/escape.txt", b"blocked").await.is_err());
458    }
459
460    #[tokio::test]
461    async fn path_traversal_is_rejected_and_never_touches_disk() {
462        let dir = tempfile::tempdir().unwrap();
463        let disk_root = dir.path().join("disk_root");
464        tokio::fs::create_dir_all(&disk_root).await.unwrap();
465        let disk = disk(&disk_root, Some(""));
466
467        // A file placed just *outside* the disk root - a successful
468        // traversal would be able to reach it.
469        let outside_file = dir.path().join("secret.txt");
470        tokio::fs::write(&outside_file, b"top secret")
471            .await
472            .unwrap();
473
474        let traversal_attempts = [
475            "../secret.txt",
476            "uploads/../../secret.txt",
477            "/etc/passwd",
478            // Zero path components at all - `root.join("")` is `root`
479            // itself; without an explicit "saw at least one component"
480            // check this would let `put("", ..)` clobber the disk root.
481            "",
482        ];
483        for path in traversal_attempts {
484            assert!(
485                disk.get(path).await.is_err(),
486                "expected {path:?} to be rejected"
487            );
488            assert!(
489                disk.put(path, b"pwned").await.is_err(),
490                "expected {path:?} to be rejected"
491            );
492            assert!(
493                disk.delete(path).await.is_err(),
494                "expected {path:?} to be rejected"
495            );
496        }
497
498        // The file outside the disk root must be untouched.
499        assert_eq!(tokio::fs::read(&outside_file).await.unwrap(), b"top secret");
500    }
501
502    #[cfg(windows)]
503    #[tokio::test]
504    async fn a_windows_drive_prefixed_path_is_rejected() {
505        let dir = tempfile::tempdir().unwrap();
506        let disk = disk(dir.path(), Some(""));
507        assert!(disk.get("C:\\Windows\\System32\\config").await.is_err());
508
509        // Drive-relative, no separator - `Path`'s Windows parser still
510        // classifies the `C:` as `Component::Prefix` even with nothing
511        // following it, so this is rejected the same way, but only
512        // incidentally via `std::path`'s own classification rather than
513        // anything `safe_join` checks for by name - worth pinning down
514        // explicitly so a future refactor can't silently reintroduce it.
515        assert!(disk.get("C:foo").await.is_err());
516
517        // UNC-style (`\\server\share\...`) - also `Component::Prefix`.
518        assert!(disk.get("\\\\server\\share\\secret.txt").await.is_err());
519    }
520
521    #[tokio::test]
522    async fn a_declared_disk_actually_works_like_any_other_disk() {
523        let dir = tempfile::tempdir().unwrap();
524        let filesystems = FilesystemConfig::new()
525            .with_disk("exports", DiskConfig::private(dir.path().join("exports")));
526
527        let exports = filesystems.disk("exports").unwrap();
528        exports.put("2024-01.csv", b"id,total\n").await.unwrap();
529        assert_eq!(
530            exports.get("2024-01.csv").await.unwrap(),
531            Some(b"id,total\n".to_vec())
532        );
533        // `private` - no URL, same as `local()`.
534        assert_eq!(exports.url("2024-01.csv").unwrap(), None);
535    }
536
537    #[tokio::test]
538    async fn a_public_declared_disk_returns_a_prefixed_url() {
539        let dir = tempfile::tempdir().unwrap();
540        let filesystems = FilesystemConfig::new().with_disk(
541            "avatars",
542            DiskConfig::public(dir.path().join("avatars"), "/avatars"),
543        );
544
545        let avatars = filesystems.disk("avatars").unwrap();
546        assert_eq!(
547            avatars.url("42.png").unwrap(),
548            Some("/avatars/42.png".to_string())
549        );
550    }
551
552    #[test]
553    fn looking_up_an_undeclared_disk_name_fails_clearly() {
554        // `unwrap_err()` needs `Disk: Debug`, which it deliberately isn't
555        // (nothing else in this crate has ever needed it) - matched
556        // explicitly instead.
557        let filesystems = FilesystemConfig::new();
558        match filesystems.disk("nope") {
559            Err(error) => assert!(format!("{error}").contains("nope")),
560            Ok(_) => panic!("expected an error for an undeclared disk name"),
561        }
562    }
563
564    #[test]
565    fn declaring_the_same_name_twice_keeps_the_last_one() {
566        let filesystems = FilesystemConfig::new()
567            .with_disk("exports", DiskConfig::private("first"))
568            .with_disk("exports", DiskConfig::public("second", "/second"));
569
570        let exports = filesystems.disk("exports").unwrap();
571        // The second declaration's `public` shape won, not the first's
572        // `private` one - proven observably (not just "doesn't panic")
573        // via the one behavioral difference between them: whether `url()`
574        // returns anything at all.
575        assert_eq!(
576            exports.url("x.txt").unwrap(),
577            Some("/second/x.txt".to_string())
578        );
579    }
580
581    #[tokio::test]
582    async fn a_declared_disk_still_rejects_path_traversal() {
583        let dir = tempfile::tempdir().unwrap();
584        let filesystems = FilesystemConfig::new()
585            .with_disk("exports", DiskConfig::private(dir.path().join("exports")));
586        let exports = filesystems.disk("exports").unwrap();
587
588        assert!(exports.put("../escape.txt", b"pwned").await.is_err());
589    }
590}