laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
use laravel::Application;
use laravel::config::Env;
use laravel::config::session::Driver;
use laravel::crypt::{Cipher, Encrypter};
use laravel::http::client::Attachment;
use laravel::http::middleware::{LimitBody, LimitUploads};
use laravel::http::{HeaderValue, Json, Middleware, Next, Request, Response, UploadedFile};
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::validation::{Valid, Validate};
use serde_json::{Value, json};

const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR";

fn describe(file: Option<&UploadedFile>) -> Value {
    match file {
        Some(file) => json!({
            "client_name": file.client_name(),
            "client_extension": file.client_extension(),
            "client_content_type": file.client_content_type(),
            "content_type": file.content_type(),
            "extension": file.extension(),
            "size": file.size(),
        }),
        None => Value::Null,
    }
}

struct SeesUploads;

impl Middleware for SeesUploads {
    async fn handle(&self, mut request: Request, next: Next) -> laravel::Result<Response> {
        request.load_input().await?;
        let seen = request.validate::<AvatarForm>().await?.avatar.is_some().to_string();
        let mut response = next.run(request).await;
        response
            .headers_mut()
            .insert("x-middleware-saw-file", HeaderValue::from_str(&seen).unwrap());
        Ok(response)
    }
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct AvatarForm {
    avatar: Option<UploadedFile>,
    name: Option<String>,
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct NoteForm {
    note: Option<String>,
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct VideoForm {
    video: Option<UploadedFile>,
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct GalleryForm {
    #[serde(default)]
    photos: Vec<UploadedFile>,
    user: Option<UserAvatar>,
    captions: Option<Vec<String>>,
}

#[derive(serde::Deserialize, Validate)]
struct UserAvatar {
    avatar: Option<UploadedFile>,
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Profile {
    #[validate(required)]
    name: String,
    #[validate(required, image, max_kilobytes = 1)]
    avatar: UploadedFile,
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Import {
    #[validate(extensions("csv"))]
    contacts: Option<UploadedFile>,
    #[validate(required, mimes("jpg", "png"))]
    photos: Vec<UploadedFile>,
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Document {
    #[validate(required, mimes("image/*", "pdf"))]
    file: UploadedFile,
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct AvatarChoice {
    avatar: Option<UploadedFile>,
    #[validate(required_without("avatar"))]
    avatar_url: Option<String>,
    #[validate(prohibited)]
    attachment: Option<UploadedFile>,
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Attachments {
    #[validate(required, each(max_kilobytes = 1))]
    files: Vec<UploadedFile>,
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Listing {
    cover: Cover,
    gallery: Vec<Cover>,
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Album {
    #[validate(min_items = 2)]
    items: Vec<AlbumItem>,
}

#[derive(serde::Deserialize, Validate)]
struct AlbumItem {
    caption: Option<String>,
    photo: Option<UploadedFile>,
}

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct Portrait {
    #[serde(alias = "picture")]
    #[validate(image)]
    photo: Option<UploadedFile>,
}

#[derive(serde::Deserialize, Validate)]
struct Cover {
    #[validate(required, image)]
    photo: UploadedFile,
    #[validate(max_length = 5)]
    caption: Option<String>,
}

fn png(size: usize) -> Vec<u8> {
    [PNG, &vec![0; size - PNG.len()]].concat()
}

fn app() -> Application {
    app_with(|_| {})
}

fn app_with(configure: impl FnOnce(&mut laravel::config::Config) + 'static) -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_config(|config, _| {
            config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
            config.session.driver = Driver::Memory;
            configure(config);
        })
        .with_routing(|routing, _| {
            routing.web(|route: &mut Router| {
                route.post("/profile", async |Valid(profile): Valid<Profile>| {
                    format!("{}: {}", profile.name, profile.avatar.client_name())
                });
                route.post("/import", async |Valid(import): Valid<Import>| {
                    let photos: Vec<_> = import.photos.iter().map(|photo| photo.client_name()).collect();
                    let contacts = import.contacts.as_ref().map(|contacts| contacts.client_name());
                    format!("{} {}", photos.join(" "), contacts.unwrap_or("no contacts"))
                });
                route.post("/attachments", async |Valid(attachments): Valid<Attachments>| {
                    let names: Vec<_> = attachments.files.iter().map(UploadedFile::client_name).collect();
                    names.join(" ")
                });
                route.post("/listing", async |Valid(listing): Valid<Listing>| {
                    let gallery: Vec<_> = listing
                        .gallery
                        .iter()
                        .map(|cover| cover.caption.as_deref().unwrap_or(cover.photo.client_name()))
                        .collect();
                    format!("{} {}", listing.cover.photo.client_name(), gallery.join(" "))
                });
                route.post("/album", async |Valid(album): Valid<Album>| {
                    let items = album.items.iter().map(|item| match (&item.caption, &item.photo) {
                        (Some(caption), None) => caption.clone(),
                        (None, Some(photo)) => photo.client_name().to_owned(),
                        _ => "?".to_owned(),
                    });
                    items.collect::<Vec<_>>().join(" ")
                });
                route.post("/portrait", async |Valid(portrait): Valid<Portrait>| {
                    portrait
                        .photo
                        .map_or("no photo".to_owned(), |photo| photo.client_name().to_owned())
                });
                route.post("/attachment", async |Valid(document): Valid<Document>| {
                    document.file.client_name().to_owned()
                });
                route.post("/avatar-choice", async |Valid(choice): Valid<AvatarChoice>| {
                    let avatar = choice.avatar.as_ref().map(UploadedFile::client_name);
                    let attachment = choice.attachment.as_ref().map(UploadedFile::client_name);
                    format!("{avatar:?} {:?} {attachment:?}", choice.avatar_url)
                });
                route.post("/avatar", async |Valid(form): Valid<AvatarForm>| {
                    Json(json!({
                        "avatar": describe(form.avatar.as_ref()),
                        "name": form.name,
                        "has_avatar": form.avatar.is_some(),
                    }))
                });
                route.put("/avatar", async |Valid(form): Valid<AvatarForm>| {
                    Json(json!({ "method": "PUT", "avatar": describe(form.avatar.as_ref()) }))
                });
                route.post("/gallery", async |Valid(gallery): Valid<GalleryForm>| {
                    let name = |file: &UploadedFile| file.client_name().to_owned();
                    let user_avatar = gallery.user.as_ref().and_then(|user| user.avatar.as_ref());
                    Json(json!({
                        "photos": gallery.photos.iter().map(name).collect::<Vec<_>>(),
                        "second": gallery.photos.get(1).map(name),
                        "user_avatar": user_avatar.map(name),
                        "caption": gallery.captions,
                    }))
                });
                route.post("/temporary", async |Valid(form): Valid<AvatarForm>| {
                    let file = form.avatar.unwrap();
                    let contents = file.bytes().await.unwrap();
                    json!({ "path": file.path(), "length": contents.len() }).to_string()
                });
                route
                    .post("/small", async |Valid(form): Valid<AvatarForm>| {
                        form.avatar.is_some().to_string()
                    })
                    .middleware(LimitUploads::bytes(100));
                route
                    .post("/seen", async |Valid(form): Valid<AvatarForm>| {
                        form.avatar.is_some().to_string()
                    })
                    .middleware(SeesUploads);
                route
                    .put("/large", async |Valid(form): Valid<VideoForm>| {
                        form.video.map_or(0, |video| video.size()).to_string()
                    })
                    .middleware(LimitUploads::bytes(10_000));
                route
                    .post("/notes", async |Valid(form): Valid<NoteForm>| {
                        form.note.map_or(0, |note| note.len()).to_string()
                    })
                    .middleware(LimitUploads::bytes(10_000))
                    .middleware(LimitBody::bytes(100));
            });
            routing.api(|route: &mut Router| {
                route.delete("/posts/1", || async { "deleted" });
                route.put("/stream", |mut multipart: axum::extract::Multipart| async move {
                    let mut fields = Vec::new();
                    while let Some(field) = multipart.next_field().await.unwrap() {
                        let name = field.name().unwrap_or_default().to_owned();
                        let length = field.bytes().await.unwrap().len();
                        fields.push(format!("{name}:{length}"));
                    }
                    fields.join(",")
                });
            });
        })
        .with_middleware(|middleware, _| {
            middleware.prepend(LimitUploads::bytes(2_000));
        })
        .create()
}

#[tokio::test]
async fn files_are_uploaded_with_the_forms_fields() {
    let response = app()
        .post("/avatar")
        .attach("avatar", Attachment::from_data(PNG, "Taylor's photo.PNG"))
        .form([("name", "  Taylor  ")])
        .await;

    response.assert_ok().assert_json(json!({
        "avatar": {
            "client_name": "Taylor's photo.PNG",
            "client_extension": "PNG",
            "client_content_type": "image/png",
            "content_type": "image/png",
            "extension": "png",
            "size": PNG.len(),
        },
        "name": "Taylor",
        "has_avatar": true,
    }));
}

#[tokio::test]
async fn a_files_content_decides_its_type_whatever_its_name() {
    let response = app()
        .post("/avatar")
        .attach("avatar", Attachment::from_data(PNG, "notes.txt"))
        .await;

    assert_eq!(response.json()["avatar"]["client_content_type"], "text/plain");
    assert_eq!(response.json()["avatar"]["content_type"], "image/png");
    assert_eq!(response.json()["avatar"]["extension"], "png");

    let text = app()
        .post("/avatar")
        .attach("avatar", Attachment::from_data("Just text", "notes.txt"))
        .await;
    assert_eq!(text.json()["avatar"]["content_type"], Value::Null);
}

#[tokio::test]
async fn lists_and_nested_names_are_dot_paths() {
    let response = app()
        .post("/gallery")
        .attach("photos[]", Attachment::from_data(PNG, "one.png"))
        .attach("photos[]", Attachment::from_data(PNG, "two.png"))
        .attach("user[avatar]", Attachment::from_data(PNG, "me.png"))
        .form([("captions[]", "First"), ("captions[]", "Second")])
        .await;

    response.assert_ok().assert_json(json!({
        "photos": ["one.png", "two.png"],
        "second": "two.png",
        "user_avatar": "me.png",
        "caption": ["First", "Second"],
    }));
}

#[tokio::test]
async fn an_empty_file_input_uploads_nothing() {
    let response = app()
        .post("/avatar")
        .attach("avatar", Attachment::from_data(Vec::new(), ""))
        .await;

    response.assert_ok();
    assert_eq!(response.json()["has_avatar"], false);
}

#[tokio::test]
async fn uploads_are_deleted_when_the_request_is_done() {
    let response = app()
        .post("/temporary")
        .attach("avatar", Attachment::from_data(PNG, "photo.png"))
        .await;
    let body: Value = serde_json::from_str(&response.text()).unwrap();

    assert_eq!(body["length"], PNG.len());
    let path = std::path::PathBuf::from(body["path"].as_str().unwrap());
    assert!(!path.exists(), "{path:?} should be deleted");
}

#[tokio::test]
async fn uploads_are_held_to_the_routes_upload_limit() {
    let response = app()
        .post("/small")
        .attach("avatar", Attachment::from_data(vec![0; 1000], "photo.png"))
        .await;

    response.assert_status(413).assert_see("Content Too Large");
    assert!(response.error().is_some_and(|error| {
        error.to_string()
            == "the request body is larger than its 100-byte limit (`LimitUploads`): The POST data is too large."
    }));
}

#[tokio::test]
async fn text_fields_are_held_to_the_body_limit_and_files_to_the_upload_limit() {
    let app = app();
    let response = app
        .post("/notes")
        .form([("note", "x".repeat(60)), ("title", "y".repeat(60))])
        .attach("photo", Attachment::from_data(vec![0; 5000], "photo.png"))
        .await;
    response.assert_status(413);
    assert!(response.error().is_some_and(|error| {
        error
            .to_string()
            .starts_with("the form's text fields are larger than their 100-byte limit (`LimitBody`)")
    }));
    app.post("/notes")
        .form([("note", "x".repeat(60))])
        .attach("photo", Attachment::from_data(vec![0; 5000], "photo.png"))
        .await
        .assert_ok()
        .assert_see("60");
}

#[tokio::test]
async fn middleware_see_uploads_once_they_read_the_body_and_so_does_the_handler() {
    app()
        .post("/seen")
        .attach("avatar", Attachment::from_data(PNG, "photo.png"))
        .await
        .assert_see("true")
        .assert_header("x-middleware-saw-file", "true");
}

#[tokio::test]
async fn client_names_leave_out_directories() {
    for (sent, kept) in [("../../.env", ".env"), ("C:\\Users\\taylor\\photo.png", "photo.png")] {
        let response = app()
            .post("/avatar")
            .attach("avatar", Attachment::from_data(PNG, sent))
            .await;

        response.assert_ok();
        assert_eq!(response.json()["avatar"]["client_name"], kept);
    }
}

#[tokio::test]
async fn forms_with_files_spoof_their_method() {
    let response = app()
        .post("/avatar")
        .attach("avatar", Attachment::from_data(PNG, "photo.png"))
        .form([("_method", "PUT")])
        .await;

    response.assert_ok();
    assert_eq!(response.json()["method"], "PUT");
    assert_eq!(response.json()["avatar"]["client_name"], "photo.png");
}

#[tokio::test]
async fn the_query_string_may_spoof_the_method() {
    app()
        .post("/api/posts/1?_method=DELETE")
        .json(json!({}))
        .await
        .assert_ok()
        .assert_see("deleted");
}

#[tokio::test]
async fn malformed_multipart_bodies_are_bad_requests() {
    app()
        .post("/avatar")
        .form([("not", "multipart")])
        .header("content-type", "multipart/form-data; boundary=nope")
        .await
        .assert_status(400);
}

#[tokio::test]
async fn method_spoofing_leaves_the_upload_for_the_route() {
    app()
        .post("/api/stream")
        .form([("_method", "PUT")])
        .attach("avatar", Attachment::from_data(vec![1; 1_500], "photo.png"))
        .await
        .assert_ok()
        .assert_see("_method:3,avatar:1500");
}

#[tokio::test]
async fn uploads_over_the_global_limit_are_spoofed_under_the_routes() {
    app()
        .post("/large")
        .form([("_method", "PUT")])
        .attach("video", Attachment::from_data(vec![0; 5_000], "clip.mp4"))
        .await
        .assert_ok()
        .assert_see("5000");
}

#[tokio::test]
async fn a_method_after_a_file_isnt_seen() {
    let body = concat!(
        "--b\r\nContent-Disposition: form-data; name=\"avatar\"; filename=\"a.png\"\r\n\r\npng\r\n",
        "--b\r\nContent-Disposition: form-data; name=\"_method\"\r\n\r\nPUT\r\n",
        "--b--\r\n",
    );
    let request = http::Request::post("/avatar")
        .header("host", "localhost")
        .header("sec-fetch-site", "same-origin")
        .header("content-type", "multipart/form-data; boundary=b")
        .body(laravel::axum::body::Body::from(body))
        .unwrap();
    let response = tower::ServiceExt::oneshot(app().into_router(), request).await.unwrap();
    let bytes = http_body_util::BodyExt::collect(response.into_body())
        .await
        .unwrap()
        .to_bytes();
    let json: Value = serde_json::from_slice(&bytes).unwrap();

    assert_eq!(json["has_avatar"], true, "{json}");
    assert!(json.get("method").is_none(), "{json}");
}

#[tokio::test]
async fn forms_may_upload_only_so_many_files_and_fields() {
    let app = app_with(|config| {
        config.server.max_file_uploads = 2;
        config.server.max_input_vars = 2;
    });

    let response = app
        .post("/gallery")
        .attach("photos[]", Attachment::from_data(PNG, "1.png"))
        .attach("photos[]", Attachment::from_data(PNG, "2.png"))
        .attach("photos[]", Attachment::from_data(PNG, "3.png"))
        .await;
    response.assert_status(413).assert_see("Content Too Large");
    assert!(
        response
            .error()
            .is_some_and(|error| error.to_string().contains("more than 2 files"))
    );
    let response = app
        .post("/gallery")
        .form([("a", "1"), ("b", "2"), ("c", "3")])
        .attach("photos[]", Attachment::from_data(PNG, "1.png"))
        .await;
    response.assert_status(413).assert_see("Content Too Large");
    assert!(
        response
            .error()
            .is_some_and(|error| error.to_string().contains("more than 2 fields"))
    );
}

#[tokio::test]
async fn forms_without_files_may_send_only_so_many_fields_too() {
    let app = app_with(|config| config.server.max_input_vars = 2);

    app.post("/avatar").form([("a", "1"), ("b", "2")]).await.assert_ok();
    let response = app.post("/avatar").form([("a", "1"), ("b", "2"), ("c", "3")]).await;
    response.assert_status(413).assert_see("Content Too Large");
    assert!(
        response
            .error()
            .is_some_and(|error| error.to_string().contains("more than 2 fields"))
    );
}

#[tokio::test]
async fn file_inputs_left_empty_dont_count_toward_the_limit() {
    let app = app_with(|config| config.server.max_file_uploads = 2);

    let response = app
        .post("/gallery")
        .attach("photos[]", Attachment::from_data(PNG, "1.png"))
        .attach("photos[]", Attachment::from_data(PNG, "2.png"))
        .attach("photos[]", Attachment::from_data(Vec::new(), ""))
        .await;

    response.assert_ok();
    assert_eq!(response.json()["photos"], json!(["1.png", "2.png"]));
}

#[tokio::test]
async fn file_rules_check_the_upload_under_the_fields_name() {
    let app = app();
    let profile = |avatar: Attachment| app.post("/profile").form([("name", "Taylor")]).attach("avatar", avatar);

    profile(Attachment::from_data(png(1024), "me.png"))
        .await
        .assert_ok()
        .assert_see("Taylor: me.png");
    app.post("/profile")
        .form([("name", "Taylor")])
        .await
        .assert_invalid_messages(&[("avatar", "The avatar field is required.")]);
    profile(Attachment::from_data("Just text", "me.png"))
        .await
        .assert_invalid_messages(&[("avatar", "The avatar field must be an image.")]);
    profile(Attachment::from_data(png(1025), "me.png"))
        .await
        .assert_invalid_messages(&[("avatar", "The avatar field must not be greater than 1 kilobytes.")]);
    app.post("/profile")
        .form([("name", "Taylor"), ("avatar", "me.png")])
        .await
        .assert_invalid_messages(&[("avatar", "The avatar field must be an image.")]);
}

#[tokio::test]
async fn fake_files_have_the_size_asked_for_and_no_detected_type() {
    let response = app()
        .post("/avatar")
        .attach("avatar", Attachment::fake("report.pdf", 1))
        .await;

    response
        .assert_ok()
        .assert_json_path("avatar.size", 1024)
        .assert_json_path("avatar.client_content_type", "application/pdf")
        .assert_json_path("avatar.content_type", Value::Null);
    let app = app();
    app.post("/profile")
        .form([("name", "Taylor")])
        .attach("avatar", Attachment::fake("me.png", 1))
        .await
        .assert_invalid_messages(&[("avatar", "The avatar field must be an image.")]);
}

#[tokio::test]
async fn fake_images_are_pngs_of_the_size_asked_for() {
    let app = app();

    app.post("/profile")
        .form([("name", "Taylor")])
        .attach("avatar", Attachment::fake_image("me.png", 3, 2))
        .await
        .assert_ok()
        .assert_see("Taylor: me.png");
    let response = app
        .post("/temporary")
        .attach("avatar", Attachment::fake_image("wide.png", 300, 1))
        .await;
    response.assert_ok();
    // A row of 300 pixels in an uncompressed PNG makes the file larger than 300 bytes...
    response.assert_json_path_where("length", |length: usize| length > 300);
}

#[test]
#[should_panic(expected = "a fake image is a PNG, so its name ends in `.png`, not `me.jpg`")]
fn fake_images_need_a_png_name() {
    let _ = Attachment::fake_image("me.jpg", 1, 1);
}

#[tokio::test]
async fn mimes_accepts_extensions_and_mime_types() {
    let app = app();

    app.post("/attachment")
        .attach("file", Attachment::from_data(PNG, "photo.png"))
        .await
        .assert_ok()
        .assert_see("photo.png");
    app.post("/attachment")
        .attach("file", Attachment::from_data(b"%PDF-1.7\n%".to_vec(), "invoice.pdf"))
        .await
        .assert_ok()
        .assert_see("invoice.pdf");
    app.post("/attachment")
        .attach("file", Attachment::from_data("Just text", "notes.png"))
        .await
        .assert_invalid_messages(&[("file", "The file field must be a file of type: image/*, pdf.")]);
}

#[tokio::test]
async fn file_rules_check_every_file_of_a_list_and_skip_a_missing_optional_file() {
    let app = app();

    app.post("/import")
        .attach("photos[]", Attachment::from_data(PNG, "one.png"))
        .attach("photos[]", Attachment::from_data(PNG, "two.png"))
        .await
        .assert_ok()
        .assert_see("one.png two.png no contacts");
    app.post("/import")
        .attach("photos[]", Attachment::from_data(PNG, "one.png"))
        .attach("photos[]", Attachment::from_data("Just text", "two.png"))
        .await
        .assert_invalid_messages(&[("photos", "The photos field must be a file of type: jpg, png.")]);
    app.post("/import")
        .attach("photos[0]", Attachment::from_data(PNG, "one.png"))
        .attach("photos[+1]", Attachment::from_data("Just text", "two.png"))
        .await
        .assert_invalid_messages(&[("photos", "The photos field must be a file of type: jpg, png.")]);
    app.post("/import")
        .attach("photos[]", Attachment::from_data(PNG, "one.png"))
        .attach("contacts", Attachment::from_data("a@example.com", "list.CSV"))
        .await
        .assert_ok()
        .assert_see("one.png list.CSV");
    app.post("/import")
        .attach("photos[]", Attachment::from_data(PNG, "one.png"))
        .attach("contacts", Attachment::from_data("a@example.com", "list.txt"))
        .await
        .assert_invalid_messages(&[(
            "contacts",
            "The contacts field must have one of the following extensions: csv.",
        )]);
}

#[tokio::test]
async fn each_checks_every_file_of_a_list() {
    let app = app();

    app.post("/attachments")
        .attach("files[]", Attachment::from_data(vec![b'a'; 10], "small.txt"))
        .attach("files[]", Attachment::from_data(vec![b'a'; 1025], "large.txt"))
        .await
        .assert_invalid_messages(&[("files.1", "The files.1 field must not be greater than 1 kilobytes.")]);
    app.post("/attachments")
        .attach("files[]", Attachment::from_data(vec![b'a'; 1024], "one.txt"))
        .attach("files[]", Attachment::from_data(vec![b'a'; 100], "two.txt"))
        .await
        .assert_ok()
        .assert_see("one.txt two.txt");
}

#[tokio::test]
async fn text_under_a_file_lists_name_doesnt_skip_its_files_rules() {
    let app = app();

    // Text in the same multipart body under the file list's name conflicts with the uploads.
    for field in ["files[]", "files[0]"] {
        app.post("/attachments")
            .form([("files", "x")])
            .attach(field, Attachment::from_data(vec![b'a'; 1100], "large.txt"))
            .await
            .assert_invalid_messages(&[("files", "The files field must be an array.")]);
    }
    // Query parameters never bleed into body validation, so ?files=x doesn't collide with uploads
    // and the file's own rules still run.
    for (query, field) in [
        ("?files=x", "files[]"),
        ("?files=x", "files[0]"),
        ("?files[]=x", "files[]"),
    ] {
        app.post(format!("/attachments{query}"))
            .attach(field, Attachment::from_data(vec![b'a'; 1100], "large.txt"))
            .await
            .assert_invalid_messages(&[("files.0", "The files.0 field must not be greater than 1 kilobytes.")]);
    }
}

#[tokio::test]
async fn nested_structs_and_lists_that_hold_only_files_check_their_rules() {
    let app = app();

    app.post("/listing")
        .attach("cover[photo]", Attachment::from_data(PNG, "cover.png"))
        .attach("gallery[0][photo]", Attachment::from_data(PNG, "one.png"))
        .attach("gallery[1][photo]", Attachment::from_data(PNG, "two.png"))
        .await
        .assert_ok()
        .assert_see("cover.png one.png two.png");
    app.post("/listing")
        .form([("gallery[0][caption]", "Lakeside")])
        .attach("cover[photo]", Attachment::from_data("Just text", "cover.png"))
        .attach("gallery[0][photo]", Attachment::from_data(PNG, "one.png"))
        .attach("gallery[1][photo]", Attachment::from_data("Just text", "two.png"))
        .await
        .assert_invalid_messages(&[
            ("cover.photo", "The cover.photo field must be an image."),
            (
                "gallery.0.caption",
                "The gallery.0.caption field must not be greater than 5 characters.",
            ),
            ("gallery.1.photo", "The gallery.1.photo field must be an image."),
        ]);
}

#[tokio::test]
async fn presence_rules_count_an_upload_as_a_submitted_value() {
    let app = app();

    app.post("/avatar-choice")
        .attach("avatar", Attachment::from_data(PNG, "me.png"))
        .await
        .assert_ok()
        .assert_see("Some(\"me.png\") None None");
    app.post("/avatar-choice")
        .form([("avatar_url", "https://example.com/me.png")])
        .attach("attachment", Attachment::from_data(PNG, "extra.png"))
        .await
        .assert_invalid_messages(&[("attachment", "The attachment field is prohibited.")]);
    app.post("/avatar-choice")
        .form([("note", "none")])
        .await
        .assert_invalid_messages(&[(
            "avatar_url",
            "The avatar url field is required when avatar is not present.",
        )]);
}

#[tokio::test]
async fn a_text_field_in_a_file_list_is_invalid() {
    app()
        .post("/import")
        .form([("photos[1]", "not-a-file")])
        .attach("photos[0]", Attachment::from_data(PNG, "one.png"))
        .attach("payload", Attachment::from_data(vec![b'A'; 1500], "evil.exe"))
        .await
        .assert_redirect()
        .assert_invalid_messages(&[("photos.1", "The photos.1 field is invalid.")]);
}

#[tokio::test]
async fn a_file_under_a_fields_alias_checks_the_fields_rules() {
    let app = app();

    app.post("/portrait")
        .attach("picture", Attachment::from_data("Just text", "evil.png"))
        .await
        .assert_invalid_messages(&[("picture", "The picture field must be an image.")]);
    app.post("/portrait")
        .attach("picture", Attachment::from_data(PNG, "me.png"))
        .await
        .assert_ok()
        .assert_see("me.png");
}

#[tokio::test]
async fn text_entries_of_a_list_with_a_file_reach_the_handler() {
    app()
        .post("/album")
        .form([("items[][caption]", "Lakeside")])
        .attach("items[1][photo]", Attachment::from_data(PNG, "one.png"))
        .await
        .assert_ok()
        .assert_see("Lakeside one.png");
}

#[tokio::test]
async fn an_upload_doesnt_decode_as_a_text_field() {
    let app = app();

    app.post("/profile")
        .attach("name", Attachment::from_data(PNG, "name.png"))
        .attach("avatar", Attachment::from_data(PNG, "me.png"))
        .await
        .assert_invalid_messages(&[("name", "The name field must be a string.")]);
    app.post("/profile")
        .form([("name", "Taylor")])
        .attach("name", Attachment::from_data(PNG, "name.png"))
        .attach("avatar", Attachment::from_data(PNG, "me.png"))
        .await
        .assert_invalid_messages(&[("name", "The name field is invalid.")]);
}

#[tokio::test]
async fn an_upload_and_other_input_at_overlapping_paths_are_invalid() {
    let app = app();

    app.post("/avatar-choice")
        .form([("avatar_url", "")])
        .attach("avatar_url", Attachment::from_data(PNG, "me.png"))
        .await
        .assert_invalid_messages(&[("avatar_url", "The avatar url field is invalid.")]);
    app.post("/avatar-choice")
        .form([("avatar_url", "https://example.com/me.png")])
        .attach("avatar_url[0]", Attachment::from_data(PNG, "me.png"))
        .await
        .assert_invalid_messages(&[("avatar_url", "The avatar url field is invalid.")]);
    // A query parameter with the same name as a multipart upload never collides with the body.
    app.post("/profile?avatar=evil")
        .form([("name", "Taylor")])
        .attach("avatar", Attachment::from_data(PNG, "me.png"))
        .await
        .assert_ok();
    app.post("/attachments")
        .attach("files[0]", Attachment::from_data(vec![b'a'; 10], "small.txt"))
        .attach("files", Attachment::from_data(vec![b'a'; 1100], "large.txt"))
        .await
        .assert_invalid_messages(&[("files", "The files field is invalid.")]);
}

#[tokio::test]
async fn files_without_a_name_are_dropped_as_text_fields_are() {
    app()
        .post("/gallery")
        .attach("", Attachment::from_data(PNG, "a.png"))
        .attach("[]", Attachment::from_data(PNG, "b.png"))
        .attach("[x]", Attachment::from_data(PNG, "c.png"))
        .attach("photos[]", Attachment::from_data(PNG, "one.png"))
        .await
        .assert_ok()
        .assert_json_path("photos", json!(["one.png"]));
}

#[tokio::test]
async fn custom_rules_and_dotted_map_keys_inspect_uploaded_files_through_input_value() {
    use std::collections::BTreeMap;

    use laravel::validation::{Field, InputValue, RuleError, ValidationRule};

    struct NamedPng;
    impl ValidationRule for NamedPng {
        async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
            let Some(file) = field.value.and_then(InputValue::as_file) else {
                return Err(field.reject("The :attribute field must be an uploaded file."));
            };
            if file.client_name().ends_with(".png") {
                Ok(())
            } else {
                Err(field.reject("The :attribute file must end with .png."))
            }
        }
    }

    struct MatchesAvatarName;
    impl ValidationRule for MatchesAvatarName {
        async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
            let avatar_name = field
                .get("avatar")
                .and_then(InputValue::as_file)
                .map(UploadedFile::client_name);
            if field.value.and_then(InputValue::as_str) == avatar_name {
                Ok(())
            } else {
                Err(field.reject("The :attribute must match the avatar filename."))
            }
        }
    }

    #[derive(Debug, serde::Deserialize, Validate)]
    #[validate(anyone)]
    #[expect(dead_code, reason = "only validated")]
    struct CustomUploads {
        #[validate(required, NamedPng)]
        avatar: UploadedFile,
        #[validate(MatchesAvatarName)]
        expected_name: Option<String>,
        #[validate(each(NamedPng))]
        gallery: Vec<UploadedFile>,
        #[validate(image)]
        documents: BTreeMap<String, UploadedFile>,
    }

    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.api(|route: &mut Router| {
                route.post("/custom-uploads", |Valid(form): Valid<CustomUploads>| async move {
                    let docs: Vec<_> = form
                        .documents
                        .into_iter()
                        .map(|(k, f)| (k, f.client_name().to_owned()))
                        .collect();
                    Json(json!({ "avatar": form.avatar.client_name(), "docs": docs }))
                });
            });
        })
        .create();

    app.post("/api/custom-uploads")
        .form([("expected_name", "me.png")])
        .attach("avatar", Attachment::from_data(PNG, "me.png"))
        .attach("gallery[]", Attachment::from_data(PNG, "one.png"))
        .attach("documents[a.b]", Attachment::from_data(PNG, "doc.png"))
        .await
        .assert_ok()
        .assert_json(json!({ "avatar": "me.png", "docs": [["a.b", "doc.png"]] }));

    app.post("/api/custom-uploads")
        .form([("expected_name", "other.png")])
        .attach("avatar", Attachment::from_data(PNG, "me.jpg"))
        .attach("gallery[]", Attachment::from_data(PNG, "bad.gif"))
        .attach("documents[a.b]", Attachment::from_data("not an image", "doc.txt"))
        .await
        .assert_status(422)
        .assert_json_path(
            "errors",
            json!({
                "avatar": ["The avatar file must end with .png."],
                "expected_name": ["The expected name must match the avatar filename."],
                "gallery.0": ["The gallery.0 file must end with .png."],
                "documents": ["The documents field must be an image."],
            }),
        );
}