tablo-core 0.7.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
use toasty::Db;
use topcoat::{
    Result,
    context::Cx,
    router::Body,
    view::{View, view},
};

use crate::{
    DeclarationError, DeclarationErrorKind, Page, PageDef, Panel, SegmentFault, Site,
    panel::test_support::{Dummy, dummy_table, mount, mount_without_db, refusal, response_html},
    resource::{Resource, ResourceDef},
    test_support::memory_db,
};

struct Dashboard;
impl Page for Dashboard {
    async fn render(cx: &Cx) -> Result<impl View> {
        Ok(view! { cx => <h1>"Welcome home"</h1> })
    }
}

struct ReportsPage;
impl Page for ReportsPage {
    fn declare() -> PageDef {
        PageDef::new().navigation_order(-1)
    }

    async fn render(cx: &Cx) -> Result<impl View> {
        Ok(view! { cx => <h1>"Quarterly reports"</h1> })
    }
}

struct DummyResource;
impl Resource for DummyResource {
    type Model = Dummy;
    type Form = crate::NoForm<Self::Model>;

    fn declare() -> ResourceDef<Self> {
        ResourceDef::new().table(dummy_table())
    }
}

async fn db() -> Db {
    memory_db(toasty::models!(Dummy)).await
}

async fn get(router: &topcoat::router::Router, uri: &str) -> (http::StatusCode, String) {
    let request = http::Request::builder()
        .uri(uri)
        .body(Body::empty())
        .unwrap();
    let response = router.handle(request).await;
    (response.status(), response_html(response).await)
}

/// A page and the home page mount under the panel's own prefix, and their
/// sidebar entries resolve from the same place. The home entry leads even
/// when registered last.
#[tokio::test]
async fn pages_mount_under_the_prefix_with_their_sidebar_entries() {
    let panel = || {
        Panel::new("backoffice")
            .auth(crate::Auth::disabled())
            .resource::<DummyResource>()
            .page::<ReportsPage>()
            .home::<Dashboard>()
    };
    let registered = panel().registered();
    let entries: Vec<_> = registered
        .nav_items
        .iter()
        .map(|entry| {
            (
                entry.item.label.as_str(),
                entry.item.url(),
                entry.item.order,
            )
        })
        .collect();
    assert_eq!(
        entries,
        [
            ("Dashboard", Some("/backoffice"), 0),
            ("Dummies", Some("/backoffice/dummies"), 0),
            ("Reports", Some("/backoffice/reports"), -1),
        ]
    );
    let router = mount(db().await, panel()).expect("the panel builds");

    let (status, html) = get(&router, "/backoffice").await;
    assert_eq!(
        status,
        http::StatusCode::OK,
        "the home page replaces the redirect"
    );
    assert!(
        html.contains("Welcome home"),
        "home renders at the prefix: {html}"
    );

    let (status, html) = get(&router, "/backoffice/reports").await;
    assert_eq!(status, http::StatusCode::OK);
    assert!(
        html.contains("Quarterly reports"),
        "the page renders: {html}"
    );
}

/// Pages and resources share one slug namespace, in either order.
#[test]
fn a_page_slug_that_a_resource_holds_does_not_build() {
    struct DummiesPage;
    impl Page for DummiesPage {
        async fn render(cx: &Cx) -> Result<impl View> {
            Ok(view! { cx => "dummies" })
        }
    }

    let duplicate = || DeclarationErrorKind::DuplicateSlug {
        slug: "dummies".to_string(),
    };
    let errors = refusal(mount_without_db(
        Panel::new("admin")
            .resource::<DummyResource>()
            .page::<DummiesPage>(),
    ));
    assert_eq!(
        errors[0],
        DeclarationError::of::<DummiesPage>(Site::Registration, duplicate())
    );
    let errors = refusal(mount_without_db(
        Panel::new("admin")
            .page::<DummiesPage>()
            .resource::<DummyResource>(),
    ));
    assert_eq!(
        errors[0],
        DeclarationError::of::<DummyResource>(Site::Registration, duplicate())
    );
}

/// `page_with` adjusts the page for its own panel: another panel mounts the page as it declares
/// itself.
#[tokio::test]
async fn page_with_adjusts_the_page_for_its_panel_only() {
    let panel = |prefix: &str| {
        Panel::new(prefix)
            .auth(crate::Auth::disabled())
            .resource::<DummyResource>()
    };
    let portal = mount(
        db().await,
        panel("portal").page_with::<ReportsPage>(|def| def.slug("figures").access(|_| false)),
    )
    .expect("the portal builds");
    assert_eq!(
        get(&portal, "/portal/figures").await.0,
        http::StatusCode::FORBIDDEN
    );
    assert_eq!(
        get(&portal, "/portal/reports").await.0,
        http::StatusCode::NOT_FOUND
    );

    let admin = mount(db().await, panel("admin").page::<ReportsPage>()).expect("the admin builds");
    assert_eq!(get(&admin, "/admin/reports").await.0, http::StatusCode::OK);
}

#[test]
fn a_page_slug_that_is_not_one_segment_does_not_build() {
    struct NestedPage;
    impl Page for NestedPage {
        fn declare() -> PageDef {
            PageDef::new().slug("reports/q3")
        }

        async fn render(cx: &Cx) -> Result<impl View> {
            Ok(view! { cx => "nested" })
        }
    }

    let errors = refusal(mount_without_db(Panel::new("admin").page::<NestedPage>()));
    assert_eq!(
        errors[0].kind,
        DeclarationErrorKind::InvalidSegment {
            item: "PageDef::slug",
            segment: "reports/q3".to_string(),
            fault: SegmentFault::Char('/'),
        }
    );
}

#[test]
fn a_second_home_page_does_not_build() {
    let errors = refusal(mount_without_db(
        Panel::new("admin")
            .home::<Dashboard>()
            .home::<ReportsPage>(),
    ));
    assert_eq!(
        errors[0],
        DeclarationError::of::<ReportsPage>(Site::Registration, DeclarationErrorKind::SecondHome)
    );
}

/// A page type mounts once per panel, as home or page: two registrations would serve one def.
#[test]
fn a_page_registered_twice_does_not_build() {
    let duplicate = DeclarationError::of::<ReportsPage>(
        Site::Registration,
        DeclarationErrorKind::DuplicatePage,
    );
    let errors = refusal(mount_without_db(
        Panel::new("admin")
            .page::<ReportsPage>()
            .page_with::<ReportsPage>(|def| def.slug("figures")),
    ));
    assert_eq!(errors[0], duplicate);
    let errors = refusal(mount_without_db(
        Panel::new("admin")
            .home::<ReportsPage>()
            .page::<ReportsPage>(),
    ));
    assert_eq!(errors[0], duplicate);
}

/// `can_open` answers what the page's `GET` would: the request's panel mounts the page and its
/// access admits the request.
#[tokio::test]
async fn can_open_answers_for_the_requests_panel() {
    struct ClosedPage;
    impl Page for ClosedPage {
        fn declare() -> PageDef {
            PageDef::new().access(|_| false)
        }

        async fn render(cx: &Cx) -> Result<impl View> {
            Ok(view! { cx => "closed" })
        }
    }

    struct Probe;
    impl Page for Probe {
        async fn render(cx: &Cx) -> Result<impl View> {
            let answers = format!(
                "reports={} closed={}",
                crate::can_open::<ReportsPage>(cx),
                crate::can_open::<ClosedPage>(cx),
            );
            Ok(view! { cx => <p>(answers)</p> })
        }
    }

    let panel = |prefix: &str| {
        Panel::new(prefix)
            .auth(crate::Auth::disabled())
            .resource::<DummyResource>()
            .home::<Probe>()
    };
    let admin = mount(
        db().await,
        panel("admin").page::<ReportsPage>().page::<ClosedPage>(),
    )
    .expect("the admin builds");
    let (_, html) = get(&admin, "/admin").await;
    assert!(html.contains("reports=true closed=false"), "{html}");

    let portal = mount(db().await, panel("portal")).expect("the portal builds");
    let (_, html) = get(&portal, "/portal").await;
    assert!(html.contains("reports=false closed=false"), "{html}");
}

/// The panel routes `{prefix}/login` and `{prefix}/logout` itself: a page
/// named after either is a registration error, not a duplicate-route panic
/// inside the router build.
#[test]
fn a_page_slug_the_panel_routes_itself_does_not_build() {
    struct LoginPage;
    impl Page for LoginPage {
        async fn render(cx: &Cx) -> Result<impl View> {
            Ok(view! { cx => "login" })
        }
    }

    let errors = refusal(mount_without_db(Panel::new("admin").page::<LoginPage>()));
    assert_eq!(
        errors[0],
        DeclarationError::of::<LoginPage>(
            Site::Registration,
            DeclarationErrorKind::ReservedSlug {
                slug: "login".to_string(),
            },
        )
    );
}

/// Without a home page, the root still redirects to the first resource, and
/// the redirect carries the clickjacking directive like every response.
#[tokio::test]
async fn without_a_home_page_the_root_redirects_to_the_first_resource() {
    let router = mount(
        db().await,
        Panel::new("admin")
            .auth(crate::Auth::disabled())
            .resource::<DummyResource>()
            .page::<ReportsPage>(),
    )
    .expect("the panel builds");
    let request = http::Request::builder()
        .uri("/admin")
        .body(Body::empty())
        .unwrap();
    let response = router.handle(request).await;
    assert_eq!(response.status(), http::StatusCode::TEMPORARY_REDIRECT);
    assert_eq!(
        response.headers().get(http::header::LOCATION).unwrap(),
        "/admin/dummies"
    );
    assert!(
        response
            .headers()
            .get(http::header::CONTENT_SECURITY_POLICY)
            .and_then(|value| value.to_str().ok())
            .is_some_and(|policy| policy.contains("frame-ancestors")),
        "the root redirect must carry the directive"
    );
}

/// A page re-checks the resolved user before rendering: with auth enforced
/// and no user, it answers the login redirect and never renders.
#[tokio::test]
async fn a_page_redirects_to_login_without_a_resolved_user() {
    use topcoat::{context::CxTestBuilder, router::response::IntoResponse, view::ViewExt};

    let (parts, ()) = http::Request::builder()
        .uri("/admin/reports")
        .body(())
        .unwrap()
        .into_parts();
    let cx = CxTestBuilder::new()
        .request_context(parts)
        .request_context(crate::panel::test_support::current_panel(
            crate::panel::test_support::panel_state("/admin", crate::Auth::password()),
        ))
        .build();
    let Err(error) = super::page_handler::<ReportsPage>(&cx, Body::empty())
        .single()
        .await
    else {
        panic!("a page must not render without a resolved user");
    };
    let response = error.into_response(&cx).expect("the gate redirect renders");
    let location = response
        .headers()
        .get(http::header::LOCATION)
        .and_then(|value| value.to_str().ok())
        .unwrap_or_default();
    assert!(
        location.starts_with("/admin/login"),
        "an anonymous page request redirects to login, got {location}"
    );
}

/// A page whose `access` refuses answers 403 and leaves the sidebar, as does a resource the
/// user cannot `ViewAny`; what the user may open stays.
#[tokio::test]
async fn the_sidebar_lists_only_what_the_user_may_open() {
    struct SecretPage;
    impl Page for SecretPage {
        fn declare() -> PageDef {
            PageDef::new().access(|_| false)
        }

        async fn render(cx: &Cx) -> Result<impl View> {
            Ok(view! { cx => <h1>"Secret"</h1> })
        }
    }

    struct OpenResource;
    impl Resource for OpenResource {
        type Model = Dummy;
        type Form = crate::NoForm<Self::Model>;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("open")
                .policy(crate::policy::ReadOnly)
                .table(dummy_table())
        }
    }

    let router = mount(
        db().await,
        Panel::new("admin")
            .auth(crate::Auth::disabled())
            .home::<Dashboard>()
            .resource::<OpenResource>()
            // Its policy is the default, which denies every ability.
            .resource::<DummyResource>()
            .page::<ReportsPage>()
            .page::<SecretPage>(),
    )
    .expect("the panel builds");

    let (status, _) = get(&router, "/admin/secret").await;
    assert_eq!(status, http::StatusCode::FORBIDDEN);

    let (status, html) = get(&router, "/admin").await;
    assert_eq!(status, http::StatusCode::OK);
    for (href, listed) in [
        ("/admin/reports", true),
        ("/admin/open", true),
        ("/admin/secret", false),
        ("/admin/dummies", false),
    ] {
        assert_eq!(
            html.contains(&format!("href=\"{href}\"")),
            listed,
            "{href} listed: {listed}, got {html}"
        );
    }
}