livewire-rust 0.1.4

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
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
//! Local file uploads: a signed URL, a temporary directory, and the calls the browser makes.
//!
//! See `docs/uploads.md` for the contract this implements.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use laravel::http::{Request, Response, StatusCode, UploadedFile};
use serde::Deserialize;
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};

use crate::component::{Call, Component, ComponentContext};
use crate::config::LivewireConfig;
use crate::error::LivewireError;

/// The multipart body the upload endpoint reads: the client repeats `files[]`.
#[derive(Debug, Deserialize, laravel::validation::Validate)]
#[validate(anyone)]
struct UploadForm {
    #[validate(required)]
    files: Vec<UploadedFile>,
}

/// The signature an upload URL carries: the component, the expiry, and the application key.
fn sign(key: &[u8], id: &str, expires: u64) -> String {
    let mut hasher = Sha256::new();
    hasher.update(key);
    hasher.update(b"|");
    hasher.update(id.as_bytes());
    hasher.update(b"|");
    hasher.update(expires.to_string().as_bytes());

    let mut text = String::with_capacity(64);
    for byte in hasher.finalize() {
        use std::fmt::Write as _;
        let _ = write!(text, "{byte:02x}");
    }

    text
}

/// The upload URL for `id`, valid for the configured window.
///
/// # Errors
///
/// Fails when the application key or the clock is unavailable.
pub fn signed_url(config: &LivewireConfig, id: &str) -> Result<String, LivewireError> {
    let key = crate::render::app_key()?;
    let key_text = crate::engine::app_key().ok_or_else(|| LivewireError::Database {
        message: "the application key is unavailable".to_owned(),
    })?;
    let expires = now().ok_or_else(|| LivewireError::Database {
        message: "the clock is unavailable".to_owned(),
    })? + config.temporary_file_upload.max_upload_time * 60;

    Ok(format!(
        "{}?component={id}&expires={expires}&signature={}",
        crate::frontend::Endpoints::new(&key_text).upload(),
        sign(&key, id, expires)
    ))
}

/// Whether an upload URL was made for `id` and has not expired.
#[must_use]
pub fn signature_is_valid(id: &str, expires: u64, signature: &str) -> bool {
    if expires < now().unwrap_or(u64::MAX) {
        return false;
    }

    crate::render::app_key().is_ok_and(|key| sign(&key, id, expires) == signature)
}

/// The current Unix time, or `None` when the clock is unreadable.
fn now() -> Option<u64> {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .ok()
        .map(|duration| duration.as_secs())
}

/// A temporary file name that cannot leave the directory.
#[must_use]
pub fn temporary_name(client: &str) -> String {
    let extension = Path::new(client)
        .extension()
        .and_then(|extension| extension.to_str())
        .filter(|extension| {
            extension.len() <= 8 && extension.chars().all(|character| character.is_ascii_alphanumeric())
        })
        .map(|extension| format!(".{extension}"))
        .unwrap_or_default();

    format!("{}{extension}", laravel::str::random(20))
}

/// The dispatch entry the client listens for, which the upload manager handles.
fn dispatch(name: &str, params: Value) -> Value {
    Value::Object(Map::from_iter([
        ("name".to_owned(), Value::from(name)),
        ("params".to_owned(), params),
        ("self".to_owned(), Value::Bool(true)),
    ]))
}

/// Handles `_startUpload`, which answers with the URL the browser posts to.
///
/// # Errors
///
/// Fails when the application key is unavailable.
pub fn start_upload(
    context: &mut ComponentContext,
    config: &LivewireConfig,
    call: &Call,
) -> Result<Option<Value>, LivewireError> {
    let name: String = call.params.arg("name", 0)?;
    let url = signed_url(config, &context.id)?;

    context.push_effect(
        "dispatches",
        dispatch(
            "upload:generatedSignedUrl",
            Value::Object(Map::from_iter([
                ("name".to_owned(), Value::from(name)),
                ("url".to_owned(), Value::from(url)),
            ])),
        ),
    );

    Ok(None)
}

/// Handles `_finishUpload`, which writes the temporary names into the component's field.
///
/// # Errors
///
/// Fails when the field is unknown or the value does not fit its type.
pub fn finish_upload(
    component: &mut dyn Component,
    context: &mut ComponentContext,
    call: &Call,
) -> Result<Option<Value>, LivewireError> {
    let name: String = call.params.arg("name", 0)?;
    let paths: Vec<String> = call.params.arg("tmpFilenames", 1)?;
    let multiple: bool = call.params.optional("multiple", 2)?.unwrap_or(false);
    let append: bool = call.params.optional("append", 3)?.unwrap_or(false);

    let value = if multiple || append {
        Value::Array(paths.iter().map(|path| Value::from(path.clone())).collect())
    } else {
        paths
            .first()
            .map(|path| Value::from(path.clone()))
            .unwrap_or(Value::Null)
    };

    let root = name.split('.').next().unwrap_or(&name);
    let replaced = if let Value::Array(mut existing) = component_field(component, root) {
        existing.extend(value.as_array().cloned().unwrap_or_default());
        Value::Array(existing)
    } else {
        value
    };

    component.set_field(&name, replaced)?;

    context.push_effect(
        "dispatches",
        dispatch(
            "upload:finished",
            Value::Object(Map::from_iter([
                ("name".to_owned(), Value::from(name)),
                (
                    "tmpFilenames".to_owned(),
                    Value::Array(paths.iter().map(|path| Value::from(path.clone())).collect()),
                ),
            ])),
        ),
    );

    Ok(None)
}

/// The field's current value, as it crosses the wire.
fn component_field(component: &dyn Component, root: &str) -> Value {
    let mut data = Map::new();
    component.dehydrate_fields(&mut data);

    data.get(root).cloned().unwrap_or(Value::Null)
}

/// Handles `_uploadErrored`, which tells the browser the upload failed.
///
/// # Errors
///
/// Fails when the call carries no field name.
pub fn upload_errored(context: &mut ComponentContext, call: &Call) -> Result<Option<Value>, LivewireError> {
    let name: String = call.params.arg("name", 0)?;

    context.push_effect(
        "dispatches",
        dispatch(
            "upload:errored",
            Value::Object(Map::from_iter([("name".to_owned(), Value::from(name))])),
        ),
    );

    Ok(None)
}

/// Handles `_removeUpload`, which deletes a temporary file and tells the browser.
///
/// # Errors
///
/// Fails when the call carries no field name or file name.
pub async fn remove_upload(
    context: &mut ComponentContext,
    config: &LivewireConfig,
    call: &Call,
) -> Result<Option<Value>, LivewireError> {
    let name: String = call.params.arg("name", 0)?;
    let filename: String = call.params.arg("tmpFilename", 1)?;

    if filename_is_safe(&filename) {
        let _ = tokio::fs::remove_file(temporary_path(config).join(&filename)).await;
    }

    context.push_effect(
        "dispatches",
        dispatch(
            "upload:removed",
            Value::Object(Map::from_iter([
                ("name".to_owned(), Value::from(name)),
                ("tmpFilename".to_owned(), Value::from(filename)),
            ])),
        ),
    );

    Ok(None)
}

/// Whether a name the browser sent can name a file in the temporary directory.
#[must_use]
pub fn filename_is_safe(filename: &str) -> bool {
    !filename.is_empty()
        && !filename.contains("..")
        && !filename.contains('/')
        && !filename.contains('\\')
        && filename != "."
}

/// The most the temporary directory may hold, in bytes.
const DIRECTORY_LIMIT: u64 = 64 * 1024 * 1024;

/// How long a temporary file may sit unused before the next upload deletes it.
const UNUSED_LIFETIME_SECONDS: u64 = 60 * 60;

/// Deletes what an abandoned upload left, then the oldest files until the directory fits `max_bytes`.
///
/// The upload endpoint is public, so it cannot rely on a scheduled cleanup alone: a burst of
/// uploads with no visitor would otherwise fill the disk between runs. Deletion is oldest first,
/// which keeps the newest files — the ones a browser is still working with — longest.
pub async fn trim(directory: &Path, max_bytes: u64, unused: std::time::Duration) -> std::io::Result<u64> {
    let mut entries = match tokio::fs::read_dir(directory).await {
        Ok(entries) => entries,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
        Err(error) => return Err(error),
    };

    struct Candidate {
        path: std::path::PathBuf,
        bytes: u64,
        modified: std::time::SystemTime,
    }

    let mut files: Vec<Candidate> = Vec::new();
    let mut total = 0u64;
    let mut removed = 0u64;

    while let Some(entry) = entries.next_entry().await? {
        let Ok(metadata) = entry.metadata().await else {
            continue;
        };

        if !metadata.is_file() {
            continue;
        }

        let modified = metadata.modified().unwrap_or(std::time::SystemTime::UNIX_EPOCH);
        let abandoned = modified.elapsed().is_ok_and(|age| age > unused);

        if abandoned {
            if tokio::fs::remove_file(entry.path()).await.is_ok() {
                removed += 1;
            }

            continue;
        }

        total += metadata.len();
        files.push(Candidate {
            path: entry.path(),
            bytes: metadata.len(),
            modified,
        });
    }

    if total > max_bytes {
        files.sort_by_key(|file| file.modified);

        for file in files {
            if total <= max_bytes {
                break;
            }

            if tokio::fs::remove_file(&file.path).await.is_ok() {
                total = total.saturating_sub(file.bytes);
                removed += 1;
            }
        }
    }

    Ok(removed)
}

/// Deletes the temporary uploads older than `age`, and reports how many it deleted.
///
/// A scheduled task runs this: an upload the browser never finished has no owner after its signed
/// URL expires, so the directory would otherwise keep it forever. A missing directory is not an
/// error; neither is a file that vanished while it was being read.
pub async fn prune(directory: &Path, age: std::time::Duration) -> std::io::Result<usize> {
    let mut entries = match tokio::fs::read_dir(directory).await {
        Ok(entries) => entries,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
        Err(error) => return Err(error),
    };

    let mut deleted = 0;

    while let Some(entry) = entries.next_entry().await? {
        let Ok(metadata) = entry.metadata().await else {
            continue;
        };

        if !metadata.is_file() {
            continue;
        }

        let old_enough = metadata
            .modified()
            .ok()
            .and_then(|modified| modified.elapsed().ok())
            .is_some_and(|elapsed| elapsed >= age);

        if old_enough && tokio::fs::remove_file(entry.path()).await.is_ok() {
            deleted += 1;
        }
    }

    Ok(deleted)
}

/// The largest file the configured rules allow, in bytes, when they declare `max:<kilobytes>`.
///
/// The rules are the framework's rule strings; this endpoint reads the size rule out of them,
/// because the typed form's own rules are compile-time and these are configuration.
#[must_use]
pub fn max_bytes(rules: &[String]) -> Option<u64> {
    rules.iter().find_map(|rule| {
        let kilobytes: u64 = rule.strip_prefix("max:")?.trim().parse().ok()?;

        Some(kilobytes.saturating_mul(1024))
    })
}

/// The directory the temporary uploads live in, relative to the application's private disk.
#[must_use]
pub fn temporary_directory(config: &LivewireConfig) -> String {
    config
        .temporary_file_upload
        .directory
        .clone()
        .unwrap_or_else(|| "livewire-tmp".to_owned())
}

/// Where that directory is on this host, which is how a file is deleted and how a preview is read.
#[must_use]
pub fn temporary_path(config: &LivewireConfig) -> PathBuf {
    Path::new("storage/app/private").join(temporary_directory(config))
}

/// The preview endpoint: serves a temporary file whose kind may be previewed.
pub async fn preview(
    registry: laravel::container::Inject<Arc<crate::registry::ComponentRegistry>>,
    laravel::routing::Params(filename): laravel::routing::Params<String>,
) -> Response {
    if !filename_is_safe(&filename) {
        return empty(StatusCode::FORBIDDEN);
    }

    let config = registry.config();
    let extension = Path::new(&filename)
        .extension()
        .and_then(|extension| extension.to_str())
        .unwrap_or_default()
        .to_ascii_lowercase();

    if !config
        .temporary_file_upload
        .preview_mimes
        .iter()
        .any(|mime| mime.eq_ignore_ascii_case(&extension))
    {
        return empty(StatusCode::FORBIDDEN);
    }

    let Ok(bytes) = tokio::fs::read(temporary_path(config).join(&filename)).await else {
        return empty(StatusCode::NOT_FOUND);
    };

    let mut response = Response::new(bytes);
    if let Ok(value) = content_type(&extension).parse() {
        response.headers_mut().insert("content-type", value);
    }

    // A temporary file is a visitor's bytes: never let the browser guess its type, never let it
    // run anything (an SVG may carry script), and name it so a download keeps the name.
    if let Ok(value) = "nosniff".parse() {
        response.headers_mut().insert("x-content-type-options", value);
    }
    if let Ok(value) = "default-src 'none'; sandbox".parse() {
        response.headers_mut().insert("content-security-policy", value);
    }
    if let Ok(value) = format!("inline; filename=\"{}\"", header_filename(&filename)).parse() {
        response.headers_mut().insert("content-disposition", value);
    }

    response
}

/// A name safe to put in a response header: letters, digits, dot, dash, underscore.
fn header_filename(filename: &str) -> String {
    filename
        .chars()
        .map(|character| {
            if character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_') {
                character
            } else {
                '_'
            }
        })
        .collect()
}

/// The content type a previewed extension is served with.
fn content_type(extension: &str) -> &'static str {
    match extension {
        "png" => "image/png",
        "gif" => "image/gif",
        "bmp" => "image/bmp",
        "svg" => "image/svg+xml",
        "jpg" | "jpeg" => "image/jpeg",
        "webp" => "image/webp",
        "wav" => "audio/wav",
        "mp3" | "mpga" => "audio/mpeg",
        "m4a" => "audio/mp4",
        "mp4" => "video/mp4",
        "mov" => "video/quicktime",
        "avi" => "video/x-msvideo",
        "wmv" => "video/x-ms-wmv",
        "pdf" => "application/pdf",
        _ => "application/octet-stream",
    }
}

/// The upload endpoint: stores the files a signed URL was made for.
pub async fn store(
    registry: laravel::container::Inject<Arc<crate::registry::ComponentRegistry>>,
    request: Request,
) -> Response {
    store_with(&request, registry.config()).await
}

/// Stores the files for `config`, which the route and the tests both use.
pub async fn store_with(request: &Request, config: &LivewireConfig) -> Response {
    let query: UploadQuery = match serde_urlencoded::from_str(request.uri().query().unwrap_or_default()) {
        Ok(query) => query,
        Err(_) => return empty(StatusCode::UNAUTHORIZED),
    };

    let (Some(expires), Some(signature)) = (query.expires, query.signature) else {
        return empty(StatusCode::UNAUTHORIZED);
    };

    // The URL names the component it was made for, and the client posts to that URL as it is.
    let Some(component) = query.component else {
        return empty(StatusCode::UNAUTHORIZED);
    };

    if !signature_is_valid(&component, expires, &signature) {
        return empty(StatusCode::UNAUTHORIZED);
    }

    let form: UploadForm = match request.validate().await {
        Ok(form) => form,
        Err(error) => {
            return LivewireError::MalformedPayload(error.to_string()).into_response(false);
        }
    };

    let directory = temporary_directory(config);
    if let Err(error) = tokio::fs::create_dir_all(&directory).await {
        return LivewireError::Database {
            message: error.to_string(),
        }
        .into_response(false);
    }

    if let Some(max) = max_bytes(&config.temporary_file_upload.rules)
        && form.files.iter().any(|file| file.size() > max)
    {
        let body = Value::Object(Map::from_iter([(
            "message".to_owned(),
            Value::from(format!("The file may not be larger than {} kilobytes.", max / 1024)),
        )]));
        let mut response = Response::new(body.to_string()).with_status(StatusCode::UNPROCESSABLE_ENTITY);
        if let Ok(value) = "application/json".parse() {
            response.headers_mut().insert("content-type", value);
        }

        return response;
    }

    let mut paths = Vec::with_capacity(form.files.len());
    for file in &form.files {
        let name = temporary_name(file.client_name());
        if let Err(error) = file.store_as(directory.clone(), name.clone()).await {
            return LivewireError::Database {
                message: error.to_string(),
            }
            .into_response(false);
        }

        paths.push(Value::from(format!("livewire-file:{name}")));
    }

    // The endpoint is public: each write also bounds the directory, deleting what an abandoned
    // upload left behind and the oldest files once the cap is reached.
    let _ = trim(
        Path::new(&directory),
        DIRECTORY_LIMIT,
        std::time::Duration::from_secs(UNUSED_LIFETIME_SECONDS),
    )
    .await;

    let body = Value::Object(Map::from_iter([("paths".to_owned(), Value::Array(paths))]));
    let mut response = Response::new(body.to_string());
    if let Ok(value) = "application/json".parse() {
        response.headers_mut().insert("content-type", value);
    }

    response
}

/// The query an upload URL carries.
#[derive(Debug, Deserialize)]
struct UploadQuery {
    component: Option<String>,
    expires: Option<u64>,
    signature: Option<String>,
}

/// An empty response with `status`, which the endpoint answers with when a guard fails.
fn empty(status: StatusCode) -> Response {
    Response::new("").with_status(status)
}

/// Whether a call is one of the upload calls, which the dispatcher handles before any action.
#[must_use]
pub fn is_upload_call(method: &str) -> bool {
    matches!(
        method,
        "_startUpload" | "_finishUpload" | "_uploadErrored" | "_removeUpload"
    )
}

#[cfg(test)]
mod tests {
    use super::{filename_is_safe, max_bytes, temporary_name};

    #[test]
    fn the_size_rule_is_read_from_the_configured_rules() {
        let rules = ["required".to_owned(), "file".to_owned(), "max:12288".to_owned()];

        assert_eq!(max_bytes(&rules), Some(12_288 * 1024));
        assert_eq!(max_bytes(&[]), None, "no rule means no limit");
        assert_eq!(
            max_bytes(&["max:oops".to_owned()]),
            None,
            "an unreadable rule does not guess"
        );
    }

    #[tokio::test]
    async fn trim_keeps_the_newest_files_and_deletes_the_rest() {
        let directory = std::env::temp_dir().join(format!("livewire-trim-{}", laravel::str::random(8)));
        tokio::fs::create_dir_all(&directory).await.expect("a directory");

        for name in ["a", "b", "c"] {
            tokio::fs::write(directory.join(name), [0u8; 10]).await.expect("a file");
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        }

        // Ten bytes each, a cap of twenty-five: the oldest goes.
        assert_eq!(
            super::trim(&directory, 25, std::time::Duration::from_secs(3_600))
                .await
                .expect("a trim"),
            1
        );
        assert!(!directory.join("a").exists(), "the oldest file went");
        assert!(
            directory.join("b").exists() && directory.join("c").exists(),
            "the newest stay"
        );

        // Nothing is recent enough when the lifetime is zero.
        assert_eq!(
            super::trim(&directory, 1_024, std::time::Duration::ZERO)
                .await
                .expect("a trim"),
            2
        );
        assert!(
            tokio::fs::read_dir(&directory)
                .await
                .expect("entries")
                .next_entry()
                .await
                .expect("an entry")
                .is_none()
        );

        tokio::fs::remove_dir(&directory).await.expect("cleanup");
    }

    #[test]
    fn a_temporary_name_cannot_leave_its_directory() {
        let name = temporary_name("../../etc/passwd");

        assert!(filename_is_safe(&name), "{name}");
        assert!(!name.contains('/'), "{name}");
        assert!(!name.contains(".."), "{name}");
        assert_eq!(name.len(), 20, "a name without an extension keeps none: {name}");

        let photo = temporary_name("holiday.jpg");
        assert!(photo.ends_with(".jpg"), "{photo}");
        assert_eq!(photo.len(), 24, "twenty random characters and the extension: {photo}");
    }

    #[test]
    fn a_name_the_browser_sends_is_checked() {
        assert!(filename_is_safe("abc.txt"));
        assert!(!filename_is_safe(""));
        assert!(!filename_is_safe(".."));
        assert!(!filename_is_safe("../x"));
        assert!(!filename_is_safe("a/b"));
        assert!(!filename_is_safe("a\\b"));
    }
}

#[cfg(test)]
mod prune_tests {
    use std::time::Duration;

    use super::prune;

    async fn count_entries(directory: &std::path::Path) -> usize {
        let mut entries = tokio::fs::read_dir(directory).await.expect("the directory");
        let mut count = 0;

        while entries.next_entry().await.expect("an entry").is_some() {
            count += 1;
        }

        count
    }

    #[tokio::test]
    async fn prune_deletes_what_is_old_enough_and_keeps_the_rest() {
        let directory = std::env::temp_dir().join(format!("livewire-prune-{}", laravel::str::random(8)));
        tokio::fs::create_dir_all(&directory)
            .await
            .expect("a directory to prune");
        tokio::fs::write(directory.join("one.txt"), b"one")
            .await
            .expect("a file");
        tokio::fs::write(directory.join("two.txt"), b"two")
            .await
            .expect("another file");

        assert_eq!(
            prune(&directory, Duration::from_secs(3_600)).await.expect("a prune"),
            0,
            "fresh files stay"
        );
        assert_eq!(count_entries(&directory).await, 2);

        assert_eq!(
            prune(&directory, Duration::ZERO).await.expect("a prune"),
            2,
            "and old enough means old enough"
        );
        assert_eq!(count_entries(&directory).await, 0);

        tokio::fs::remove_dir(&directory).await.expect("cleanup");

        assert_eq!(
            prune(&directory, Duration::ZERO)
                .await
                .expect("a missing directory is not an error"),
            0
        );
    }
}