tablo-core 0.4.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
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
use toasty::Db;
use topcoat::view::ViewExt;

use super::*;
use crate::{
    Ability, Panel, ResourceDef, lens,
    panel::test_support::{Dummy, Subscriber, dummy_table, mount, panel_for, response_html},
    schema::{Field, Schema},
};

#[test]
fn completion_fills_unnamed_keys_from_the_stored_projection() {
    let schema = Schema::new(Field::text(Dummy::fields().name()));
    let named = HashSet::new();
    let mut values = HashMap::from([("name".to_string(), "advisory".to_string())]);
    let stored = HashMap::from([("name".to_string(), "authoritative".to_string())]);
    complete(&schema, &mut values, &named, &stored);
    assert_eq!(
        values["name"], "authoritative",
        "an unnamed key reads the stored record"
    );

    let named = HashSet::from(["name".to_string()]);
    let mut values = HashMap::from([("name".to_string(), "posted".to_string())]);
    complete(&schema, &mut values, &named, &stored);
    assert_eq!(
        values["name"], "posted",
        "a named key keeps what was posted"
    );

    let mut values = HashMap::from([("name".to_string(), "stale".to_string())]);
    complete(&schema, &mut values, &HashSet::new(), &HashMap::new());
    assert!(!values.contains_key("name"), "nothing stored, nothing kept");
}

#[tokio::test]
async fn edit_post_requires_view_as_well_as_update() {
    use crate::resource::Resource;

    struct ViewDeniedResource;
    impl Resource for ViewDeniedResource {
        type Model = Dummy;
        type Form = ViewDeniedForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("dummies")
                .policy(|_cx: &Cx, ability: Ability<'_, Dummy>| match ability {
                    Ability::View(_record) => false,
                    Ability::Update(_record) => true,
                    _ => false,
                })
                .table(dummy_table())
                .form(Schema::new(Field::text(Dummy::fields().name())))
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = Dummy)]
    struct ViewDeniedForm {
        name: String,
    }
    let mut db = Db::builder()
        .models(toasty::models!(Dummy))
        .connect("sqlite::memory:")
        .await
        .unwrap();
    db.push_schema().await.unwrap();
    let row = toasty::create!(Dummy {
        name: "Ada".to_string(),
    })
    .exec(&mut db)
    .await
    .unwrap();
    let router = mount(db, panel_for::<ViewDeniedResource>()).expect("panel builds");
    let url = format!("/admin/dummies/{}/edit", row.id);
    let get = router
        .handle(
            http::Request::builder()
                .uri(&url)
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert_eq!(get.status(), http::StatusCode::FORBIDDEN);
    // A valid token still 403s on policy, not on CSRF.
    let token = uuid::Uuid::new_v4().to_string();
    let post = router
        .handle(
            http::Request::builder()
                .uri(&url)
                .method(http::Method::POST)
                .header(
                    http::header::CONTENT_TYPE,
                    "application/x-www-form-urlencoded",
                )
                .header(
                    http::header::COOKIE,
                    format!("{}={token}", crate::csrf::COOKIE_NAME),
                )
                .body(Body::from(format!("name=Ada&csrf_token={token}")))
                .unwrap(),
        )
        .await;
    assert_eq!(
        post.status(),
        http::StatusCode::FORBIDDEN,
        "view-denied edit POST must not mutate"
    );
    // Missing token is 403 even before policy.
    let no_token = router
        .handle(
            http::Request::builder()
                .uri(&url)
                .method(http::Method::POST)
                .header(
                    http::header::CONTENT_TYPE,
                    "application/x-www-form-urlencoded",
                )
                .body(Body::from("name=Ada"))
                .unwrap(),
        )
        .await;
    assert_eq!(no_token.status(), http::StatusCode::FORBIDDEN);
}

/// Transport keys never reach the write.
#[tokio::test]
async fn transport_keys_never_reach_the_write() {
    use crate::schema::{Field, Schema};

    #[derive(Debug, toasty::Model, Clone)]
    struct Doc {
        #[key]
        #[auto]
        id: uuid::Uuid,
        path: String,
        title: String,
    }

    struct CapturingResource;
    impl crate::resource::Resource for CapturingResource {
        type Model = Doc;
        type Form = CapturingForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("docs")
                .policy(|_cx: &Cx, ability: Ability<'_, Doc>| {
                    matches!(ability, Ability::ViewAny | Ability::Create)
                })
                .table(crate::table::Table::new(crate::table::TextColumn::new(
                    lens!(Doc.title),
                )))
                .form(Schema::new((
                    Field::text(Doc::fields().title()),
                    Field::file(Doc::fields().path()),
                )))
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = Doc)]
    struct CapturingForm {
        title: String,
        path: String,
    }
    let db = Db::builder()
        .models(toasty::models!(Doc))
        .connect("sqlite::memory:")
        .await
        .unwrap();
    db.push_schema().await.unwrap();
    let router = mount(db.clone(), panel_for::<CapturingResource>()).expect("panel builds");
    let csrf = uuid::Uuid::new_v4().to_string();
    let boundary = "----TransportBoundary";
    let body = format!(
        "--{b}\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nx\r\n\
             --{b}\r\nContent-Disposition: form-data; name=\"path\"; filename=\"a.bin\"\r\nContent-Type: application/octet-stream\r\n\r\nBYTES\r\n\
             --{b}\r\nContent-Disposition: form-data; name=\"clear_path\"\r\n\r\n1\r\n\
             --{b}\r\nContent-Disposition: form-data; name=\"keep_path\"\r\n\r\njavascript:alert(1)\r\n\
             --{b}\r\nContent-Disposition: form-data; name=\"csrf_token\"\r\n\r\n{csrf}\r\n\
             --{b}--\r\n",
        b = boundary
    );
    let resp = router
        .handle(
            http::Request::builder()
                .method(http::Method::POST)
                .uri("/admin/docs/create")
                .header(
                    http::header::CONTENT_TYPE,
                    format!("multipart/form-data; boundary={boundary}"),
                )
                .header(
                    http::header::COOKIE,
                    format!("{}={csrf}", crate::csrf::COOKIE_NAME),
                )
                .body(Body::from(body))
                .unwrap(),
        )
        .await;
    assert!(
        resp.status().is_redirection(),
        "create succeeds, got {} {}",
        resp.status(),
        String::from_utf8_lossy(
            &http_body_util::BodyExt::collect(resp.into_body())
                .await
                .unwrap()
                .to_bytes()
        )
    );
    let mut db_q = db.clone();
    let docs = Doc::all().exec(&mut db_q).await.unwrap();
    assert_eq!(docs.len(), 1, "one row written");
    assert_eq!(docs[0].title, "x");
    assert_ne!(
        docs[0].path, "javascript:alert(1)",
        "a client-typed carry candidate must never be stored"
    );
}

/// A failing driver write surfaces the opaque mapping, never driver text.
#[tokio::test]
async fn a_driver_create_failure_does_not_echo_driver_text() {
    use topcoat::cookie::CookieJarCell;

    use crate::{
        resource::Resource,
        schema::{Field, Schema},
    };

    struct WritingResource;
    impl Resource for WritingResource {
        type Model = Dummy;
        type Form = WritingForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("dummies")
                .policy(|_cx: &Cx, ability: Ability<'_, Dummy>| {
                    matches!(ability, Ability::ViewAny | Ability::Create)
                })
                .table(crate::table::Table::new(crate::table::TextColumn::new(
                    lens!(Dummy.name),
                )))
                .form(Schema::new(Field::text(Dummy::fields().name())))
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = Dummy)]
    struct WritingForm {
        name: String,
    }
    let db = Db::builder()
        .models(toasty::models!(Dummy))
        .connect("sqlite::memory:")
        .await
        .unwrap();

    // Positive control carries driver text, so the assertions cannot pass vacuously.
    let mut raw = db.clone();
    let driver = toasty::create!(Dummy {
        name: "Ada".to_string(),
    })
    .exec(&mut raw)
    .await
    .expect_err("the table is missing")
    .to_string();
    drop(raw);
    assert!(
        driver.contains("no such table"),
        "the control must be a driver failure, got {driver:?}"
    );

    let token = uuid::Uuid::new_v4().to_string();
    let parts = http::Request::builder()
        .method(http::Method::POST)
        .uri("/admin/dummies/create")
        .header(
            http::header::CONTENT_TYPE,
            "application/x-www-form-urlencoded",
        )
        .header(
            http::header::COOKIE,
            format!("{}={token}", crate::csrf::COOKIE_NAME),
        )
        .body(())
        .unwrap()
        .into_parts()
        .0;
    let cx = crate::test_support::panel_cx::<WritingResource>(&db)
        .with_many((parts, CookieJarCell::new()));

    let error = resource_create_post::<WritingResource>(
        &cx,
        Body::from(format!("name=Ada&csrf_token={token}")),
    )
    .first()
    .await
    .expect_err("the write must fail");

    let rendered = error.to_string();
    assert!(
        rendered.contains("database unavailable"),
        "the opaque message must survive, got {rendered:?}"
    );
    assert!(
        !rendered.contains(&driver) && !rendered.contains("no such table"),
        "driver text must not reach the response: the driver said {driver:?}, the response said {rendered:?}"
    );
}

/// A failing driver write on update surfaces the opaque mapping, never driver text.
#[tokio::test]
async fn a_driver_update_failure_does_not_echo_driver_text() {
    use topcoat::router::{
        RouteFn, RouteFuture, Router, RouterBuilderDiscoverExt, response::IntoResponse,
    };

    use crate::{
        RouterBuilderPanelExt,
        resource::Resource,
        schema::{Field, Schema},
    };

    #[derive(Debug, toasty::Model, Clone)]
    struct Ghost {
        #[key]
        #[auto]
        id: uuid::Uuid,
        #[unique]
        name: String,
    }

    struct EditingResource;
    impl Resource for EditingResource {
        type Model = Dummy;
        type Form = EditingForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("dummies")
                .policy(|_cx: &Cx, ability: Ability<'_, Dummy>| {
                    matches!(
                        ability,
                        Ability::ViewAny | Ability::View(_) | Ability::Update(_)
                    )
                })
                .table(crate::table::Table::new(crate::table::TextColumn::new(
                    lens!(Dummy.name),
                )))
                .form(Schema::new(Field::text(Dummy::fields().name())))
        }

        async fn update_record(
            _cx: &Cx,
            record: Dummy,
            _posted: crate::form::Posted<EditingForm>,
            ex: &mut dyn toasty::Executor,
        ) -> Result<Dummy> {
            toasty::create!(Ghost {
                name: "taken".to_string(),
            })
            .exec(&mut *ex)
            .await?;
            Ok(record)
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = Dummy)]
    struct EditingForm {
        name: String,
    }
    /// Runs the edit handler and returns its error as the response body.
    fn edit_error(cx: &Cx, body: Body) -> RouteFuture<'_> {
        Box::pin(async move {
            let error = resource_edit_post::<EditingResource>(cx, body)
                .first()
                .await
                .expect_err("the write must fail");
            error.to_string().into_response(cx)
        })
    }

    let mut db = Db::builder()
        .models(toasty::models!(Dummy, Ghost))
        .connect("sqlite::memory:")
        .await
        .unwrap();
    db.push_schema().await.unwrap();
    let row = toasty::create!(Dummy {
        name: "Ada".to_string(),
    })
    .exec(&mut db)
    .await
    .unwrap();
    toasty::create!(Ghost {
        name: "taken".to_string(),
    })
    .exec(&mut db)
    .await
    .unwrap();

    // Positive control carries driver text, so the assertions cannot pass vacuously.
    let mut raw = db.clone();
    let driver = toasty::create!(Ghost {
        name: "taken".to_string(),
    })
    .exec(&mut raw)
    .await
    .expect_err("the name is taken")
    .to_string();
    drop(raw);
    assert!(
        driver.contains("UNIQUE constraint failed"),
        "the control must be a driver failure, got {driver:?}"
    );

    // The route sits outside the panel's prefix, where the router's one panel still answers.
    let router = Router::builder()
        .discover()
        .app_context(db)
        .panel(
            Panel::new("admin")
                .auth(crate::Auth::disabled())
                .resource::<EditingResource>(),
        )
        .expect("panel builds")
        .route(RouteFn::new(
            http::Method::POST,
            "/capture/{id}",
            edit_error,
        ))
        .build();
    let token = uuid::Uuid::new_v4().to_string();
    let response = router
        .handle(
            http::Request::builder()
                .method(http::Method::POST)
                .uri(format!("/capture/{}", row.id))
                .header(
                    http::header::CONTENT_TYPE,
                    "application/x-www-form-urlencoded",
                )
                .header(
                    http::header::COOKIE,
                    format!("{}={token}", crate::csrf::COOKIE_NAME),
                )
                .body(Body::from(format!("name=Ada&csrf_token={token}")))
                .unwrap(),
        )
        .await;
    let rendered = String::from_utf8_lossy(
        &http_body_util::BodyExt::collect(response.into_body())
            .await
            .unwrap()
            .to_bytes(),
    )
    .to_string();

    assert!(
        rendered.contains("database unavailable"),
        "the opaque message must survive, got {rendered:?}"
    );
    assert!(
        !rendered.contains(&driver) && !rendered.contains("UNIQUE constraint failed"),
        "driver text must not reach the response: the driver said {driver:?}, the response said {rendered:?}"
    );
}

/// A mutation answers 303 with the flash cookie, never the query (#126, topcoat#408).
#[tokio::test]
async fn mutation_redirect_carries_the_flash_cookie_instead_of_a_query() {
    use crate::resource::Resource;

    const COOKIE_NAME: &str = crate::notification::COOKIE_NAME;

    struct NotifyingResource;
    impl Resource for NotifyingResource {
        type Model = Dummy;
        type Form = NotifyingForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("dummies")
                .policy(|_cx: &Cx, ability: Ability<'_, Dummy>| {
                    matches!(ability, Ability::ViewAny | Ability::Create)
                })
                .table(crate::table::Table::new(crate::table::TextColumn::new(
                    lens!(Dummy.name),
                )))
                .form(crate::schema::Schema::new(crate::schema::Field::text(
                    Dummy::fields().name(),
                )))
        }

        async fn create_record(
            _cx: &Cx,
            _form: NotifyingForm,
            ex: &mut dyn toasty::Executor,
        ) -> Result<Dummy> {
            toasty::create!(Dummy {
                name: "created".to_string(),
            })
            .exec(&mut *ex)
            .await
            .map_err(|error| -> topcoat::Error { error.into() })
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = Dummy)]
    struct NotifyingForm {
        // Optional so the csrf-only POST parses.
        #[form(optional)]
        name: String,
    }
    let db = Db::builder()
        .models(toasty::models!(Dummy))
        .connect("sqlite::memory:")
        .await
        .unwrap();
    db.push_schema().await.unwrap();
    let router = mount(db, panel_for::<NotifyingResource>()).expect("panel builds");
    let token = uuid::Uuid::new_v4().to_string();
    let resp = router
        .handle(
            http::Request::builder()
                .uri("/admin/dummies/create")
                .method(http::Method::POST)
                .header(
                    http::header::CONTENT_TYPE,
                    "application/x-www-form-urlencoded",
                )
                .header(
                    http::header::COOKIE,
                    format!("{}={token}", crate::csrf::COOKIE_NAME),
                )
                .body(Body::from(format!("csrf_token={token}")))
                .unwrap(),
        )
        .await;
    assert_eq!(
        resp.status(),
        http::StatusCode::SEE_OTHER,
        "a completed mutation is a 303 Post/Redirect/Get"
    );
    let location = resp
        .headers()
        .get(http::header::LOCATION)
        .expect("the redirect names its target")
        .to_str()
        .unwrap()
        .to_string();
    assert!(
        !location.contains("notification"),
        "the toast must not ride the query, got {location}"
    );
    let set_cookie = resp
        .headers()
        .get_all(http::header::SET_COOKIE)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .find(|v| v.starts_with(&format!("{COOKIE_NAME}=")))
        .expect("the flash cookie flushes on the Err redirect")
        .to_string();
    assert!(
        set_cookie.contains("success") && set_cookie.contains("Created"),
        "the cookie carries the toast status and title: {set_cookie}"
    );
    assert!(
        set_cookie.contains("Secure") && set_cookie.contains("HttpOnly"),
        "the flushed cookie keeps the __Host- contract: {set_cookie}"
    );
}

/// Through the real panel, two empty `unique()` submits re-render inline and write nothing.
#[tokio::test]
async fn two_empty_submits_on_a_unique_field_re_render_and_write_nothing() {
    use crate::{
        resource::{Resource, ResourceDef},
        schema::{Field, Schema},
        table::{Table, TextColumn},
    };

    struct SubscriberResource;
    impl Resource for SubscriberResource {
        type Model = Subscriber;
        type Form = SubscriberForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("subscribers")
                .policy(|_cx: &Cx, ability: Ability<'_, Subscriber>| {
                    matches!(ability, Ability::ViewAny | Ability::Create)
                })
                .table(Table::new(TextColumn::new(lens!(Subscriber.email))))
                .form(Schema::new(
                    Field::text(Subscriber::fields().email()).unique(),
                ))
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = Subscriber)]
    struct SubscriberForm {
        email: String,
    }
    let db = Db::builder()
        .models(toasty::models!(Subscriber))
        .connect("sqlite::memory:")
        .await
        .unwrap();
    db.push_schema().await.unwrap();
    let router = mount(db.clone(), panel_for::<SubscriberResource>()).expect("panel builds");

    let csrf = uuid::Uuid::new_v4().to_string();
    for (attempt, submitted) in ["+", ""].into_iter().enumerate() {
        let attempt = attempt + 1;
        let resp = router
            .handle(
                http::Request::builder()
                    .method(http::Method::POST)
                    .uri("/admin/subscribers/create")
                    .header(
                        http::header::CONTENT_TYPE,
                        "application/x-www-form-urlencoded",
                    )
                    .header(
                        http::header::COOKIE,
                        format!("{}={csrf}", crate::csrf::COOKIE_NAME),
                    )
                    .body(Body::from(format!("email={submitted}&csrf_token={csrf}")))
                    .unwrap(),
            )
            .await;
        assert_eq!(
            resp.status(),
            http::StatusCode::OK,
            "empty submit {attempt} must re-render, not redirect or fail"
        );
        let body = http_body_util::BodyExt::collect(resp.into_body())
            .await
            .unwrap()
            .to_bytes();
        let html = String::from_utf8_lossy(&body);
        assert!(
            html.contains("Email is required"),
            "empty submit {attempt} must carry the presence error, got {html}"
        );
    }

    let mut db_check = db;
    let stored = Subscriber::all().exec(&mut db_check).await.unwrap();
    assert!(
        stored.is_empty(),
        "two empty submits must write nothing, got {} rows",
        stored.len()
    );
}

/// A forged `keep_<field>` without `holds` leaves the field empty.
#[tokio::test]
async fn a_forged_carry_is_refused_by_the_default_holds() {
    #[derive(Debug, toasty::Model, Clone)]
    struct Doc {
        #[key]
        #[auto]
        id: uuid::Uuid,
        title: String,
        path: String,
    }

    struct NoHoldsUploader;

    impl crate::Uploader for NoHoldsUploader {
        async fn store(
            &self,
            _filename: &str,
            _bytes: &[u8],
        ) -> std::result::Result<String, String> {
            Ok("/uploads/stored.bin".to_string())
        }
    }

    struct DocResource;

    impl crate::resource::Resource for DocResource {
        type Model = Doc;
        type Form = DocForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("docs")
                .policy(|_cx: &Cx, ability: Ability<'_, Doc>| {
                    matches!(ability, Ability::ViewAny | Ability::Create)
                })
                .table(crate::table::Table::new(crate::table::TextColumn::new(
                    lens!(Doc.title),
                )))
                .form(Schema::new((
                    Field::text(Doc::fields().title()),
                    Field::file(Doc::fields().path()),
                )))
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = Doc)]
    struct DocForm {
        title: String,
        path: String,
    }
    let db = Db::builder()
        .models(toasty::models!(Doc))
        .connect("sqlite::memory:")
        .await
        .unwrap();
    db.push_schema().await.unwrap();
    let router = mount(
        db.clone(),
        Panel::new("admin")
            .uploads(NoHoldsUploader)
            .resource::<DocResource>()
            .auth(crate::Auth::disabled()),
    )
    .expect("panel builds");

    let csrf = uuid::Uuid::new_v4().to_string();
    let response = router
        .handle(
            http::Request::builder()
                .method(http::Method::POST)
                .uri("/admin/docs/create")
                .header(
                    http::header::CONTENT_TYPE,
                    "application/x-www-form-urlencoded",
                )
                .header(
                    http::header::COOKIE,
                    format!("{}={csrf}", crate::csrf::COOKIE_NAME),
                )
                .body(Body::from(format!(
                    "title=Doc&keep_path=javascript:alert(1)&csrf_token={csrf}"
                )))
                .unwrap(),
        )
        .await;
    assert_eq!(response.status(), 200, "the forged carry must re-render");
    let html = response_html(response).await;
    assert!(
        html.contains("Path is required"),
        "the forged carry must leave the field empty, got {html}"
    );
    let mut db_q = db.clone();
    assert!(
        Doc::all().exec(&mut db_q).await.unwrap().is_empty(),
        "a forged carry must not create a record"
    );
}