tablo-core 0.2.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
use toasty::Db;

use super::*;
use crate::{Ability, Panel, ReadOnly, ResourceDef, lens, panel::test_support::mount};

#[tokio::test]
async fn options_endpoint_searches_and_gates() {
    // `GET {parent}/options?field=&q=` narrows server-side,
    // allow-lists to searchable relationship selects, and mirrors gates.
    use http_body_util::BodyExt;

    use crate::resource::Resource;

    #[derive(Debug, toasty::Model, Clone)]
    struct OptAuthor {
        #[key]
        #[auto]
        id: uuid::Uuid,
        name: String,
    }
    struct OptAuthorResource;
    impl Resource for OptAuthorResource {
        type Model = OptAuthor;
        type Form = crate::NoForm<Self::Model>;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("opt-authors")
                .policy(ReadOnly)
                .table(crate::table::Table::new(
                    crate::table::TextColumn::new(lens!(OptAuthor.name)).searchable(),
                ))
        }
    }

    #[derive(Debug, toasty::Model, Clone)]
    struct OptPost {
        #[key]
        #[auto]
        id: uuid::Uuid,
        author_id: uuid::Uuid,
        title: String,
    }
    struct OptPostResource;
    impl Resource for OptPostResource {
        type Model = OptPost;
        type Form = OptPostForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("opt-posts")
                .policy(ReadOnly)
                .table(crate::table::Table::new(crate::table::TextColumn::new(
                    lens!(OptPost.title),
                )))
                .form(crate::schema::Schema::new(
                    crate::schema::Field::choice(OptPost::fields().author_id())
                        .relationship::<OptAuthorResource>(|a: &OptAuthor| a.name.clone())
                        .searchable(),
                ))
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = OptPost)]
    struct OptPostForm {
        author_id: uuid::Uuid,
    }
    async fn body_text(resp: http::Response<Body>) -> String {
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        String::from_utf8_lossy(&bytes).to_string()
    }

    let mut db = Db::builder()
        .models(toasty::models!(OptAuthor, OptPost))
        .connect("sqlite::memory:")
        .await
        .unwrap();
    db.push_schema().await.unwrap();
    for name in ["Ada", "Grace", "Alan"] {
        toasty::create!(OptAuthor {
            name: name.to_string(),
        })
        .exec(&mut db)
        .await
        .unwrap();
    }
    let router = mount(
        db,
        Panel::new("admin")
            .resource::<OptPostResource>()
            .resource::<OptAuthorResource>()
            .auth(crate::Auth::disabled()),
    )
    .expect("panel builds");

    // Narrowing works.
    let resp = router
        .handle(
            http::Request::builder()
                .uri("/admin/opt-posts/options?field=author_id&q=Ada")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert_eq!(resp.status(), http::StatusCode::OK);
    let html = body_text(resp).await;
    assert!(html.contains("Ada"), "search must return Ada, got {html}");
    assert!(!html.contains("Grace"), "search must narrow, got {html}");

    // Unknown field → 400.
    let resp = router
        .handle(
            http::Request::builder()
                .uri("/admin/opt-posts/options?field=nope&q=Ada")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert_eq!(resp.status(), http::StatusCode::BAD_REQUEST);

    // Missing field → 400.
    let resp = router
        .handle(
            http::Request::builder()
                .uri("/admin/opt-posts/options?q=Ada")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert_eq!(resp.status(), http::StatusCode::BAD_REQUEST);
    // Escaping itself is pinned where it can fail:
    // `an_option_escapes_its_value_and_label` feeds characters that must be
    // escaped and asserts the exact output. These fixtures are "Ada"/"Grace"/"Alan", so a
    // `!html.contains("<script")` here could never fail.
}

#[tokio::test]
async fn option_load_loads_no_relation() {
    // An option load projects a value and a label off the related record's
    // own columns, so it loads no relation. The source's detail query and its
    // list column both include `parent`, and `View` keeps a row only while
    // that relation is unloaded, so a rendered option proves the loader ran
    // the bare `scoped_query`, not either of those.
    use http_body_util::BodyExt;
    use toasty::stmt::{Include, List, Query};

    use crate::resource::Resource;

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

    #[derive(Debug, toasty::Model, Clone)]
    struct Child {
        #[key]
        #[auto]
        id: uuid::Uuid,
        name: String,
        #[index]
        parent_id: uuid::Uuid,
        #[belongs_to(key = parent_id, references = id)]
        parent: toasty::Deferred<Parent>,
    }

    fn with_parent() -> Query<List<Child>> {
        let inc: Include<Child, Parent> = Child::fields().parent().into();
        Query::<List<Child>>::all().include(inc)
    }

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

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("children")
                .policy(|_cx: &Cx, ability: Ability<'_, Child>| match ability {
                    Ability::ViewAny => true,
                    Ability::View(record) => record.parent.is_unloaded(),
                    _ => false,
                })
                .table(crate::table::Table::new(
                    crate::table::ComputedColumn::new("Name", |c: &Child| c.name.clone())
                        .include(Child::fields().parent()),
                ))
        }

        fn view_query(_cx: &Cx) -> Query<List<Child>> {
            with_parent()
        }
    }

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

    struct OwnerResource;
    impl Resource for OwnerResource {
        type Model = Owner;
        type Form = OwnerForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("owners")
                .table(crate::table::Table::new(crate::table::TextColumn::new(
                    lens!(Owner.name),
                )))
                .form(crate::schema::Schema::new(
                    crate::schema::Field::choice(Owner::fields().child_id())
                        .relationship::<ChildSource>(|c: &Child| c.name.clone())
                        .searchable(),
                ))
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = Owner)]
    struct OwnerForm {
        child_id: uuid::Uuid,
    }
    let mut db = Db::builder()
        .models(toasty::models!(Parent, Child, Owner))
        .connect("sqlite::memory:")
        .await
        .unwrap();
    db.push_schema().await.unwrap();
    let parent_id = uuid::Uuid::new_v4();
    toasty::create!(Parent {
        id: parent_id,
        name: "Ada".to_string(),
    })
    .exec(&mut db)
    .await
    .unwrap();
    toasty::create!(Child {
        name: "Only Child".to_string(),
        parent_id,
    })
    .exec(&mut db)
    .await
    .unwrap();

    let router = mount(
        db,
        Panel::new("admin")
            .resource::<OwnerResource>()
            .resource::<ChildSource>()
            .auth(crate::Auth::disabled()),
    )
    .expect("panel builds");
    let resp = router
        .handle(
            http::Request::builder()
                .uri("/admin/owners/options?field=child_id")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert!(resp.status().is_success());
    let html = String::from_utf8(
        resp.into_body()
            .collect()
            .await
            .unwrap()
            .to_bytes()
            .to_vec(),
    )
    .unwrap();
    assert!(
        html.contains("Only Child"),
        "the option must render, which it cannot if the loader loaded the source's include: {html}"
    );
}

#[tokio::test]
async fn options_endpoint_rejects_non_searchable_and_overflows() {
    // Non-searchable selects never serve search (400);
    // filtered overflow answers 200 with the keep-typing hint.
    use http_body_util::BodyExt;

    use crate::resource::Resource;

    #[derive(Debug, toasty::Model, Clone)]
    struct BigA {
        #[key]
        #[auto]
        id: uuid::Uuid,
        name: String,
    }
    struct BigAResource;
    impl Resource for BigAResource {
        type Model = BigA;
        type Form = crate::NoForm<Self::Model>;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("big-as")
                .policy(ReadOnly)
                .table(crate::table::Table::new(
                    crate::table::TextColumn::new(lens!(BigA.name)).searchable(),
                ))
        }
    }

    #[derive(Debug, toasty::Model, Clone)]
    struct BigP {
        #[key]
        #[auto]
        id: uuid::Uuid,
        author_id: uuid::Uuid,
        /// A text column for the table declaration: every
        /// servable resource needs one, and `author_id` is a Uuid.
        name: String,
    }
    struct SearchableParent;
    impl Resource for SearchableParent {
        type Model = BigP;
        type Form = SearchableParentForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("big-ps")
                .table(crate::table::Table::new(crate::table::TextColumn::new(
                    lens!(BigP.name),
                )))
                .form(crate::schema::Schema::new(
                    crate::schema::Field::choice(BigP::fields().author_id())
                        .relationship::<BigAResource>(|a: &BigA| a.name.clone())
                        .searchable(),
                ))
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = BigP)]
    struct SearchableParentForm {
        author_id: uuid::Uuid,
    }
    struct PlainParent;
    impl Resource for PlainParent {
        type Model = BigP;
        type Form = PlainParentForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("plain-ps")
                .table(crate::table::Table::new(crate::table::TextColumn::new(
                    lens!(BigP.name),
                )))
                .form(crate::schema::Schema::new(
                    crate::schema::Field::choice(BigP::fields().author_id())
                        .relationship::<BigAResource>(|a: &BigA| a.name.clone()),
                ))
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = BigP)]
    struct PlainParentForm {
        author_id: uuid::Uuid,
    }
    let mut db = Db::builder()
        .models(toasty::models!(BigA, BigP))
        .connect("sqlite::memory:")
        .await
        .unwrap();
    db.push_schema().await.unwrap();
    for i in 0..=crate::schema::MAX_RELATIONSHIP_OPTIONS {
        toasty::create!(BigA {
            name: format!("author-{i}"),
        })
        .exec(&mut db)
        .await
        .unwrap();
    }
    let router = mount(
        db,
        Panel::new("admin")
            .resource::<SearchableParent>()
            .resource::<PlainParent>()
            .resource::<BigAResource>()
            .auth(crate::Auth::disabled()),
    )
    .expect("panel builds");

    // Non-searchable → 400 (keeps today's cap error path, never search).
    let resp = router
        .handle(
            http::Request::builder()
                .uri("/admin/plain-ps/options?field=author_id&q=author-1")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert_eq!(resp.status(), http::StatusCode::BAD_REQUEST);

    // Empty q on over-cap searchable → 200 with keep-typing hint.
    let resp = router
        .handle(
            http::Request::builder()
                .uri("/admin/big-ps/options?field=author_id&q=")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert_eq!(resp.status(), http::StatusCode::OK);
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let html = String::from_utf8_lossy(&bytes).to_string();
    assert!(
        html.contains("keep typing"),
        "filtered overflow must hint, got {html}"
    );
}

/// The endpoint renders options through the field's own `option_view`, so a
/// label or value carrying markup reaches the page escaped.
#[tokio::test]
async fn an_option_escapes_its_value_and_label() {
    use topcoat::context::CxTestBuilder;

    let cx = CxTestBuilder::new().build();
    let html = crate::schema::option_view(
        &cx,
        "a\"b".to_string(),
        "<script>x</script>".to_string(),
        false,
    )
    .single()
    .await
    .unwrap()
    .render(&cx);
    assert!(
        !html.contains("<script>") && html.contains("&lt;script&gt;"),
        "the label must be escaped, got {html}"
    );
    assert!(
        !html.contains("value=\"a\"b\""),
        "the value must be escaped, got {html}"
    );
}