ryuk 0.1.0

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! Named filesystem disks, shaped like Laravel's `Storage` facade.
//!
//! ```no_run
//! use ryuk::storage::{Disk, Storage};
//!
//! # async fn demo() -> Result<(), ryuk::storage::StorageError> {
//! let storage = Storage::new()
//!     .disk("local", Disk::local("storage/app"))
//!     .disk("public", Disk::local("storage/app/public").with_url("http://localhost/storage"))
//!     .default_disk("local");
//! storage.get_default().put("notes/a.txt", "hello").await?;
//! assert_eq!(storage.get("public").url("avatars/me.png")?, "http://localhost/storage/avatars/me.png");
//! # Ok(()) }
//! ```
//!
//! With feature `s3`, `Disk::s3(S3Config::new(..))` gives the same API over any S3-compatible bucket,
//! see [`crate::s3`].
//!
//! Every path is relative to the disk root. Absolute paths, `..`, and symlinks that lead outside the
//! root are rejected with [`StorageError::InvalidPath`] (fail closed).
//!
//! # Uploads
//! Enable axum's `multipart` feature in your app (`axum = { version = "0.8", features = ["multipart"] }`):
//! ```ignore
//! async fn upload(State(s): State<Storage>, mut m: axum::extract::Multipart) -> Result<String, StatusCode> {
//!     while let Some(field) = m.next_field().await.map_err(|_| StatusCode::BAD_REQUEST)? {
//!         let bytes = field.bytes().await.map_err(|_| StatusCode::BAD_REQUEST)?;
//!         // never trust field.file_name() as a path: generate the name yourself
//!         let name = format!("uploads/{}.bin", uuid::Uuid::new_v4());
//!         s.get("public").put(&name, bytes).await.map_err(|_| StatusCode::BAD_REQUEST)?;
//!         return Ok(s.get("public").url(&name).unwrap());
//!     }
//!     Err(StatusCode::BAD_REQUEST)
//! }
//! ```

use std::collections::HashMap;
use std::io;
use std::path::{Component, Path, PathBuf};
use std::time::SystemTime;

use axum::Router;
use tower_http::services::ServeDir;

/// Storage failure.
#[derive(Debug, thiserror::Error)]
pub enum StorageError {
    /// The path is absolute, climbs out with `..`, or escapes the root through a symlink.
    #[error("invalid storage path: {0}")]
    InvalidPath(String),
    /// The disk has no `url` configured.
    #[error("disk has no url configured")]
    NoUrl,
    /// Underlying filesystem error. A missing file (local or S3 404) is `ErrorKind::NotFound`.
    #[error(transparent)]
    Io(#[from] io::Error),
    /// A remote disk (S3) answered with an error: status, error code and message, never credentials.
    #[error("remote storage error: {0}")]
    Remote(String),
    /// The operation does not exist for this kind of disk (e.g. `temporary_url` on a local disk).
    #[error("unsupported on this disk: {0}")]
    Unsupported(&'static str),
}

/// `Result` alias for storage operations.
pub type Result<T> = std::result::Result<T, StorageError>;

/// A local directory acting as a disk.
#[derive(Debug, Clone)]
struct LocalDisk {
    root: PathBuf,
    url: Option<String>,
}

impl LocalDisk {
    /// Public URL of `path` (no filesystem access; the path is still validated and percent-encoded).
    fn url(&self, path: &str) -> Result<String> {
        let base = self.url.as_deref().ok_or(StorageError::NoUrl)?;
        let rel = lexical(path)?;
        let segs: Vec<String> = rel
            .components()
            .map(|c| encode(&c.as_os_str().to_string_lossy()))
            .collect();
        Ok(format!("{}/{}", base.trim_end_matches('/'), segs.join("/")))
    }

    fn router<S: Clone + Send + Sync + 'static>(&self, mount: &str) -> Router<S> {
        // nosniff: a stored file whose content a browser can sniff as HTML/SVG and execute (an avatar
        // upload kept as `.svg`, say) must not run as same-origin script just because it is served here.
        Router::new()
            .nest_service(mount, ServeDir::new(&self.root))
            .layer(
                tower_http::set_header::SetResponseHeaderLayer::if_not_present(
                    axum::http::header::X_CONTENT_TYPE_OPTIONS,
                    axum::http::HeaderValue::from_static("nosniff"),
                ),
            )
    }

    /// Run a blocking closure with a capability handle on the root and the lexically-validated
    /// relative path. Every subsequent filesystem call is resolved *through* that handle in one
    /// guarded step (symlink components refused, resolution kept beneath the root by the OS itself,
    /// `openat2` on Linux) instead of checked and then re-resolved from a path string, which is what
    /// let a concurrently-swapped symlink win the old check-then-use race. A sandbox escape (symlink
    /// out of root, dangling symlink) surfaces as `PermissionDenied` from cap-std; that, like any
    /// traversal `lexical` already rejects, is reported as `InvalidPath`.
    async fn with_dir<T: Send + 'static>(
        &self,
        path: &str,
        f: impl FnOnce(&cap_std::fs::Dir, &Path) -> io::Result<T> + Send + 'static,
    ) -> Result<T> {
        let rel = lexical(path)?;
        let root = self.root.clone();
        let bad = StorageError::InvalidPath(path.into());
        tokio::task::spawn_blocking(move || {
            std::fs::create_dir_all(&root)?;
            let dir = cap_std::fs::Dir::open_ambient_dir(&root, cap_std::ambient_authority())?;
            f(&dir, &rel)
        })
        .await
        .map_err(|e| StorageError::Io(io::Error::other(e)))?
        .map_err(|e| {
            // `create_dir_all` hitting a non-directory (a symlink standing in for a real directory,
            // say) surfaces as `AlreadyExists`; a sandbox escape surfaces as `PermissionDenied`. Both
            // mean the path is unsafe for this operation, same as anything `lexical` already rejects.
            if matches!(
                e.kind(),
                io::ErrorKind::PermissionDenied | io::ErrorKind::AlreadyExists
            ) {
                bad
            } else {
                e.into()
            }
        })
    }

    /// Write `contents`, creating parent directories and replacing any existing file.
    async fn put(&self, path: &str, contents: impl AsRef<[u8]>) -> Result<()> {
        let contents = contents.as_ref().to_vec();
        self.with_dir(path, move |dir, rel| {
            if let Some(parent) = rel.parent().filter(|p| !p.as_os_str().is_empty()) {
                dir.create_dir_all(parent)?;
            }
            dir.write(rel, &contents)
        })
        .await
    }

    /// Append `contents` (creates the file if missing).
    async fn append(&self, path: &str, contents: impl AsRef<[u8]>) -> Result<()> {
        use std::io::Write;
        let contents = contents.as_ref().to_vec();
        self.with_dir(path, move |dir, rel| {
            if let Some(parent) = rel.parent().filter(|p| !p.as_os_str().is_empty()) {
                dir.create_dir_all(parent)?;
            }
            let mut o = cap_std::fs::OpenOptions::new();
            o.create(true).append(true);
            dir.open_with(rel, &o)?.write_all(&contents)
        })
        .await
    }

    /// Read a file.
    async fn get(&self, path: &str) -> Result<Vec<u8>> {
        self.with_dir(path, |dir, rel| dir.read(rel)).await
    }

    /// Read a file as UTF-8.
    async fn get_string(&self, path: &str) -> Result<String> {
        self.with_dir(path, |dir, rel| dir.read_to_string(rel))
            .await
    }

    /// Whether a file or directory exists.
    async fn exists(&self, path: &str) -> Result<bool> {
        self.with_dir(path, |dir, rel| dir.try_exists(rel)).await
    }

    /// Delete a file; a file that is already gone is fine.
    async fn delete(&self, path: &str) -> Result<()> {
        self.with_dir(path, |dir, rel| match dir.remove_file(rel) {
            Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
            _ => Ok(()),
        })
        .await
    }

    /// Copy a file, replacing the destination.
    async fn copy(&self, from: &str, to: &str) -> Result<()> {
        let dst = lexical(to)?;
        self.with_dir(from, move |dir, src| {
            if let Some(parent) = dst.parent().filter(|p| !p.as_os_str().is_empty()) {
                dir.create_dir_all(parent)?;
            }
            dir.copy(src, dir, &dst)?;
            Ok(())
        })
        .await
    }

    /// Move (rename) a file, replacing the destination.
    async fn move_(&self, from: &str, to: &str) -> Result<()> {
        let dst = lexical(to)?;
        self.with_dir(from, move |dir, src| {
            if let Some(parent) = dst.parent().filter(|p| !p.as_os_str().is_empty()) {
                dir.create_dir_all(parent)?;
            }
            dir.rename(src, dir, &dst)
        })
        .await
    }

    /// File size in bytes.
    async fn size(&self, path: &str) -> Result<u64> {
        self.with_dir(path, |dir, rel| Ok(dir.metadata(rel)?.len()))
            .await
    }

    /// Modification time.
    async fn last_modified(&self, path: &str) -> Result<SystemTime> {
        self.with_dir(path, |dir, rel| {
            Ok(dir.metadata(rel)?.modified()?.into_std())
        })
        .await
    }

    /// Files directly inside `dir` (`""` is the root), as sorted disk-relative paths.
    async fn files(&self, dir: &str) -> Result<Vec<String>> {
        self.list(dir, false).await
    }

    /// Directories directly inside `dir`, as sorted disk-relative paths.
    async fn directories(&self, dir: &str) -> Result<Vec<String>> {
        self.list(dir, true).await
    }

    async fn list(&self, dir: &str, want_dirs: bool) -> Result<Vec<String>> {
        let base = lexical(dir)?;
        self.with_dir(dir, move |d, rel| {
            let mut out = Vec::new();
            // read_dir("") would look up a child literally named "", not the dir's own entries.
            let entries: Box<dyn Iterator<Item = io::Result<cap_std::fs::DirEntry>>> =
                if rel.as_os_str().is_empty() {
                    Box::new(d.entries()?)
                } else {
                    Box::new(d.read_dir(rel)?)
                };
            for e in entries {
                let e = e?;
                // symlinks are listed as neither, so a listing cannot point outside the root
                let t = e.file_type()?;
                if !t.is_symlink() && t.is_dir() == want_dirs {
                    out.push(
                        base.join(e.file_name())
                            .to_string_lossy()
                            .replace('\\', "/"),
                    );
                }
            }
            out.sort();
            Ok(out)
        })
        .await
    }

    /// Create a directory and its parents.
    async fn make_directory(&self, path: &str) -> Result<()> {
        self.with_dir(path, |dir, rel| dir.create_dir_all(rel))
            .await
    }

    /// Delete a directory and everything in it. The disk root itself is refused.
    async fn delete_directory(&self, path: &str) -> Result<()> {
        if lexical(path)?.as_os_str().is_empty() {
            return Err(StorageError::InvalidPath(path.into()));
        }
        self.with_dir(path, |dir, rel| dir.remove_dir_all(rel))
            .await
    }
}

/// One storage disk: a local directory, or (feature `s3`) an S3-compatible bucket.
/// Every method behaves the same on both; see [`Disk::local`] and `Disk::s3`.
#[derive(Debug, Clone)]
pub struct Disk(Backend);

#[derive(Debug, Clone)]
enum Backend {
    Local(LocalDisk),
    #[cfg(feature = "s3")]
    S3(Box<crate::s3::S3Disk>),
}

macro_rules! delegate {
    ($self:ident.$m:ident($($a:expr),*)) => {
        match &$self.0 {
            Backend::Local(d) => d.$m($($a),*).await,
            #[cfg(feature = "s3")]
            Backend::S3(d) => d.$m($($a),*).await,
        }
    };
}

impl Disk {
    /// Disk rooted at `root` (created on first use).
    /// ```
    /// let d = ryuk::storage::Disk::local("storage/app");
    /// ```
    pub fn local(root: impl Into<PathBuf>) -> Self {
        Self(Backend::Local(LocalDisk {
            root: root.into(),
            url: None,
        }))
    }

    /// S3-compatible disk (AWS, MinIO, R2, Backblaze B2, Spaces, Wasabi, ...). See [`crate::s3`].
    /// ```
    /// use ryuk::s3::S3Config;
    /// let d = ryuk::storage::Disk::s3(S3Config::new("bucket", "us-east-1", "key", "secret"));
    /// ```
    #[cfg(feature = "s3")]
    pub fn s3(config: crate::s3::S3Config) -> Self {
        Self(Backend::S3(Box::new(crate::s3::S3Disk::new(config))))
    }

    /// Public base URL, used by [`Disk::url`] (on an S3 disk this is the `url` config value).
    /// ```
    /// let d = ryuk::storage::Disk::local("p").with_url("https://x.test/storage");
    /// assert_eq!(d.url("a b.txt").unwrap(), "https://x.test/storage/a%20b.txt");
    /// ```
    pub fn with_url(mut self, url: impl Into<String>) -> Self {
        match &mut self.0 {
            Backend::Local(d) => d.url = Some(url.into()),
            #[cfg(feature = "s3")]
            Backend::S3(d) => d.set_url(url.into()),
        }
        self
    }

    /// Public URL of `path` (no I/O; the path is still validated and percent-encoded).
    /// An S3 disk without `url` falls back to the bucket address (works for public buckets only).
    pub fn url(&self, path: &str) -> Result<String> {
        match &self.0 {
            Backend::Local(d) => d.url(path),
            #[cfg(feature = "s3")]
            Backend::S3(d) => d.url(path),
        }
    }

    /// Time-limited signed URL (AWS SigV4 query signing, like Laravel's `temporaryUrl`), S3 disks only.
    /// `expires_in` is at most 7 days. Local disks return [`StorageError::Unsupported`].
    /// ```no_run
    /// # fn demo(disk: &ryuk::storage::Disk) -> Result<(), ryuk::storage::StorageError> {
    /// let link = disk.temporary_url("reports/q1.pdf", std::time::Duration::from_secs(300))?;
    /// # Ok(()) }
    /// ```
    pub fn temporary_url(&self, path: &str, expires_in: std::time::Duration) -> Result<String> {
        let _ = (path, expires_in);
        match &self.0 {
            Backend::Local(_) => Err(StorageError::Unsupported("temporary_url on a local disk")),
            #[cfg(feature = "s3")]
            Backend::S3(d) => d.temporary_url(path, expires_in),
        }
    }

    /// Router serving this disk read-only under `mount` (e.g. `/storage`). Merge it into your app.
    /// Note: `ServeDir` follows symlinks, so do not put untrusted symlinks inside a served disk.
    /// An S3 disk has nothing to serve: its router is empty (404); link to [`Disk::url`] instead.
    pub fn router<S: Clone + Send + Sync + 'static>(&self, mount: &str) -> Router<S> {
        match &self.0 {
            Backend::Local(d) => d.router(mount),
            #[cfg(feature = "s3")]
            Backend::S3(_) => Router::new(),
        }
    }

    /// Write `contents`, creating parent directories and replacing any existing file.
    pub async fn put(&self, path: &str, contents: impl AsRef<[u8]>) -> Result<()> {
        delegate!(self.put(path, contents))
    }

    /// Like [`Disk::put`] but sets the `Content-Type` on S3 disks (ignored on local disks).
    pub async fn put_with(
        &self,
        path: &str,
        contents: impl AsRef<[u8]>,
        content_type: &str,
    ) -> Result<()> {
        #[cfg(not(feature = "s3"))]
        let _ = content_type;
        match &self.0 {
            Backend::Local(d) => d.put(path, contents).await,
            #[cfg(feature = "s3")]
            Backend::S3(d) => d.put_with(path, contents, Some(content_type)).await,
        }
    }

    /// Append `contents` (creates the file if missing). On S3 this reads, then rewrites the object.
    pub async fn append(&self, path: &str, contents: impl AsRef<[u8]>) -> Result<()> {
        delegate!(self.append(path, contents))
    }

    /// Read a file.
    pub async fn get(&self, path: &str) -> Result<Vec<u8>> {
        delegate!(self.get(path))
    }

    /// Read a file as UTF-8.
    pub async fn get_string(&self, path: &str) -> Result<String> {
        delegate!(self.get_string(path))
    }

    /// Whether a file exists (locally also directories; on S3 only objects).
    pub async fn exists(&self, path: &str) -> Result<bool> {
        delegate!(self.exists(path))
    }

    /// Opposite of [`Disk::exists`].
    pub async fn missing(&self, path: &str) -> Result<bool> {
        Ok(!self.exists(path).await?)
    }

    /// Delete a file; a file that is already gone is fine.
    pub async fn delete(&self, path: &str) -> Result<()> {
        delegate!(self.delete(path))
    }

    /// Copy a file, replacing the destination (server-side `CopyObject` on S3).
    pub async fn copy(&self, from: &str, to: &str) -> Result<()> {
        delegate!(self.copy(from, to))
    }

    /// Move (rename) a file, replacing the destination.
    pub async fn move_(&self, from: &str, to: &str) -> Result<()> {
        delegate!(self.move_(from, to))
    }

    /// File size in bytes. A missing file is an `Io` error of kind `NotFound`.
    pub async fn size(&self, path: &str) -> Result<u64> {
        delegate!(self.size(path))
    }

    /// Modification time.
    pub async fn last_modified(&self, path: &str) -> Result<SystemTime> {
        delegate!(self.last_modified(path))
    }

    /// Files directly inside `dir` (`""` is the root), as sorted disk-relative paths.
    pub async fn files(&self, dir: &str) -> Result<Vec<String>> {
        delegate!(self.files(dir))
    }

    /// Directories directly inside `dir`, as sorted disk-relative paths.
    pub async fn directories(&self, dir: &str) -> Result<Vec<String>> {
        delegate!(self.directories(dir))
    }

    /// Create a directory and its parents. A no-op on S3 (prefixes exist only through their objects).
    pub async fn make_directory(&self, path: &str) -> Result<()> {
        delegate!(self.make_directory(path))
    }

    /// Delete a directory and everything in it. The disk root itself is refused.
    pub async fn delete_directory(&self, path: &str) -> Result<()> {
        delegate!(self.delete_directory(path))
    }
}

/// Registry of named disks.
#[derive(Debug, Clone, Default)]
pub struct Storage {
    disks: HashMap<String, Disk>,
    default: String,
}

impl Storage {
    /// Empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a disk; the first one registered is the default.
    pub fn disk(mut self, name: &str, disk: Disk) -> Self {
        if self.default.is_empty() {
            self.default = name.into();
        }
        self.disks.insert(name.into(), disk);
        self
    }

    /// Choose the default disk.
    pub fn default_disk(mut self, name: &str) -> Self {
        self.default = name.into();
        self
    }

    /// The disk called `name`. Panics when it was never registered (a startup misconfiguration);
    /// use [`Storage::try_disk`] to handle that.
    pub fn get(&self, name: &str) -> &Disk {
        self.try_disk(name)
            .unwrap_or_else(|| panic!("storage disk `{name}` is not configured"))
    }

    /// Fallible lookup.
    pub fn try_disk(&self, name: &str) -> Option<&Disk> {
        self.disks.get(name)
    }

    /// The default disk (panics when none is registered).
    pub fn get_default(&self) -> &Disk {
        self.get(&self.default)
    }

    /// `local` (`STORAGE_ROOT`, default `storage/app`) and `public` (`<root>/public`, served at
    /// `APP_URL/storage`, `APP_URL` default `http://127.0.0.1:3000`). Default disk: `local`.
    ///
    /// With feature `s3` and `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_BUCKET` set, an `s3`
    /// disk is added too (`AWS_DEFAULT_REGION` default `us-east-1`, `AWS_ENDPOINT`, `AWS_URL`,
    /// `AWS_SESSION_TOKEN`, `AWS_USE_PATH_STYLE_ENDPOINT`). `FILESYSTEM_DISK` picks the default disk.
    pub fn from_env() -> Self {
        let root =
            PathBuf::from(std::env::var("STORAGE_ROOT").unwrap_or_else(|_| "storage/app".into()));
        let app = std::env::var("APP_URL").unwrap_or_else(|_| "http://127.0.0.1:3000".into());
        let st = Self::new().disk("local", Disk::local(&root)).disk(
            "public",
            Disk::local(root.join("public"))
                .with_url(format!("{}/storage", app.trim_end_matches('/'))),
        );
        #[cfg(feature = "s3")]
        let st = match crate::s3::S3Config::from_env() {
            Some(c) => st.disk("s3", Disk::s3(c)),
            None => st,
        };
        let default = std::env::var("FILESYSTEM_DISK")
            .ok()
            .filter(|d| !d.is_empty())
            .unwrap_or_else(|| "local".into());
        st.default_disk(&default)
    }

    /// Router serving the `public` disk at `/storage`. Merge it: `app.merge(storage.public_router())`.
    pub fn public_router<S: Clone + Send + Sync + 'static>(&self) -> Router<S> {
        self.get("public").router("/storage")
    }
}

/// Reject anything but plain relative names; `.` segments are dropped.
pub(crate) fn lexical(path: &str) -> Result<PathBuf> {
    let bad = || StorageError::InvalidPath(path.into());
    if path.contains('\0') || path.contains('\\') {
        return Err(bad());
    }
    let mut out = PathBuf::new();
    for c in Path::new(path).components() {
        match c {
            Component::Normal(n) => out.push(n),
            Component::CurDir => {}
            _ => return Err(bad()),
        }
    }
    Ok(out)
}

pub(crate) fn encode(seg: &str) -> String {
    let mut s = String::new();
    for b in seg.bytes() {
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
            s.push(b as char);
        } else {
            s.push_str(&format!("%{b:02X}"));
        }
    }
    s
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    fn tmp() -> PathBuf {
        static N: AtomicU32 = AtomicU32::new(0);
        std::env::temp_dir().join(format!(
            "ryuk-storage-{}-{}",
            std::process::id(),
            N.fetch_add(1, Ordering::SeqCst)
        ))
    }

    #[tokio::test]
    async fn crud_roundtrip() {
        let base = tmp();
        let d = Disk::local(base.join("d"));
        d.put("a/b.txt", "hi").await.unwrap();
        d.append("a/b.txt", " there").await.unwrap();
        assert_eq!(d.get_string("a/b.txt").await.unwrap(), "hi there");
        assert_eq!(d.size("a/b.txt").await.unwrap(), 8);
        assert!(d.exists("a/b.txt").await.unwrap() && d.missing("zzz").await.unwrap());
        d.last_modified("a/b.txt").await.unwrap();
        d.copy("a/b.txt", "c/copy.txt").await.unwrap();
        d.move_("a/b.txt", "m/moved.txt").await.unwrap();
        assert!(d.missing("a/b.txt").await.unwrap());
        assert_eq!(d.files("c").await.unwrap(), vec!["c/copy.txt"]);
        assert_eq!(d.directories("").await.unwrap(), vec!["a", "c", "m"]);
        d.delete("c/copy.txt").await.unwrap();
        d.delete("c/copy.txt").await.unwrap();
        d.make_directory("x/y").await.unwrap();
        d.delete_directory("x").await.unwrap();
        assert!(d.delete_directory("").await.is_err());
        std::fs::remove_dir_all(&base).ok();
    }

    #[tokio::test]
    async fn rejects_traversal() {
        let base = tmp();
        let d = Disk::local(base.join("d"));
        for p in ["../x", "a/../../x", "/etc/passwd", "a\\..\\x", "a\0b"] {
            assert!(
                matches!(d.put(p, "x").await, Err(StorageError::InvalidPath(_))),
                "{p}"
            );
            assert!(
                matches!(d.get(p).await, Err(StorageError::InvalidPath(_))),
                "{p}"
            );
        }
        assert!(!base.join("x").exists());
        std::fs::remove_dir_all(&base).ok();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn rejects_symlink_escape() {
        let base = tmp();
        let outside = base.join("outside");
        std::fs::create_dir_all(&outside).unwrap();
        std::fs::write(outside.join("secret"), "s").unwrap();
        let d = Disk::local(base.join("d"));
        d.put("ok.txt", "1").await.unwrap();
        std::os::unix::fs::symlink(&outside, base.join("d/link")).unwrap();
        std::os::unix::fs::symlink(base.join("nowhere"), base.join("d/dangling")).unwrap();
        assert!(matches!(
            d.get("link/secret").await,
            Err(StorageError::InvalidPath(_))
        ));
        assert!(matches!(
            d.put("link/new", "x").await,
            Err(StorageError::InvalidPath(_))
        ));
        assert!(matches!(
            d.put("dangling", "x").await,
            Err(StorageError::InvalidPath(_))
        ));
        assert!(!outside.join("new").exists() && !base.join("nowhere").exists());
        assert_eq!(d.files("").await.unwrap(), vec!["ok.txt"]);
        std::fs::remove_dir_all(&base).ok();
    }

    /// The old `canonicalize`-then-`std::fs` implementation checked a symlink's target, then did the
    /// real write through a *different* lookup of the same path string, racing a writer who swaps the
    /// symlink in between. 3000 writes while another task flips the link between "safe" and "escapes
    /// root" must never land a single byte outside root: cap-std resolves the write in one guarded step,
    /// so there is nothing to race.
    #[cfg(unix)]
    #[tokio::test]
    async fn symlink_swap_race_never_escapes_root() {
        let base = tmp();
        let safe_dir = base.join("safe");
        let outside_dir = base.join("outside");
        std::fs::create_dir_all(&safe_dir).unwrap();
        std::fs::create_dir_all(&outside_dir).unwrap();
        let d = Disk::local(base.join("d"));
        d.make_directory("").await.unwrap();
        let link = base.join("d/link");

        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let (flip_stop, outside_for_flip) = (stop.clone(), outside_dir.clone());
        let flip = tokio::task::spawn_blocking(move || {
            let outside_dir = outside_for_flip;
            while !flip_stop.load(std::sync::atomic::Ordering::Relaxed) {
                let _ = std::fs::remove_file(&link);
                let _ = std::os::unix::fs::symlink(&outside_dir, &link);
                let _ = std::fs::remove_file(&link);
                let _ = std::os::unix::fs::symlink(&safe_dir, &link);
            }
        });

        for i in 0..3000 {
            let _ = d
                .put(&format!("link/race_{i}.txt"), format!("payload-{i}"))
                .await;
        }
        stop.store(true, std::sync::atomic::Ordering::Relaxed);
        flip.await.unwrap();

        let escaped: Vec<_> = std::fs::read_dir(&outside_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name())
            .collect();
        assert!(escaped.is_empty(), "race landed outside root: {escaped:?}");
        std::fs::remove_dir_all(&base).ok();
    }

    #[test]
    fn registry_and_urls() {
        let s = Storage::new()
            .disk("local", Disk::local("l"))
            .disk("public", Disk::local("p").with_url("http://h/storage/"))
            .default_disk("local");
        assert_eq!(
            s.get("public").url("a/b c.png").unwrap(),
            "http://h/storage/a/b%20c.png"
        );
        assert!(matches!(s.get_default().url("a"), Err(StorageError::NoUrl)));
        assert!(s.get("public").url("../a").is_err());
        assert!(s.try_disk("nope").is_none());
    }

    #[tokio::test]
    async fn public_router_serves_files() {
        use tower::ServiceExt;
        let base = tmp();
        let s = Storage::new().disk("public", Disk::local(base.join("pub")));
        s.get("public").put("hello.txt", "hey").await.unwrap();
        let app: Router = s.public_router();
        let req = |uri: &str| {
            axum::http::Request::get(uri)
                .body(axum::body::Body::empty())
                .unwrap()
        };
        let ok = app
            .clone()
            .oneshot(req("/storage/hello.txt"))
            .await
            .unwrap();
        assert_eq!(ok.status(), 200);
        // A stored file a browser could sniff as HTML/SVG and run must never execute as same-origin script.
        assert_eq!(
            ok.headers().get("x-content-type-options").unwrap(),
            "nosniff"
        );
        assert_ne!(
            app.oneshot(req("/storage/..%2Fsecret"))
                .await
                .unwrap()
                .status(),
            200
        );
        std::fs::remove_dir_all(&base).ok();
    }
}