Skip to main content

tablo_core/panel/
build.rs

1//! Mounting a panel: [`RouterBuilderPanelExt::panel`], the declaration
2//! checks it runs, and the route-path helpers.
3
4use std::sync::Arc;
5
6use toasty::Db;
7use topcoat::{
8    Result,
9    asset::AssetConfig,
10    context::Cx,
11    metadata::{Metadata, Robots},
12    router::{
13        Body, LayoutFn, Methods, PageFn, Path, RouteFn, RouteFuture, RouterBuilder,
14        RouterBuilderDirectoryExt, error::redirect,
15    },
16};
17
18use super::{
19    Panel, Root,
20    commit_hook::missing_commit_hooks,
21    error_page,
22    files::served_root,
23    headers::{self, ServedDir},
24    host::PanelHost,
25    register::Registry,
26    shell::{LANGUAGE_SEGMENT, language_post},
27    state::{PanelState, Panels, current, under_prefix},
28};
29use crate::{
30    DeclarationError, DeclarationErrorKind, MountError, Site,
31    auth::{AuthHost, PanelGate, Realm},
32    bus::NotificationBus,
33    declaration::segment_fault,
34    naming::route_path,
35    resource::{MountScope, Mounts},
36    toasty_compat::model::AppSchema,
37    topcoat_compat::RUNTIME_PREFIX,
38};
39
40mod handle;
41mod shared;
42
43pub(crate) use self::handle::HandlePanel;
44pub use self::handle::PanelHandle;
45use self::{handle::request_mounts, shared::install_shared};
46
47/// Mounts a [`Panel`] on a router the app owns.
48///
49/// ```rust,no_run
50/// # use tablo_core::{Auth, Authenticator, NoForm, Panel, PanelUser, Resource, RouterBuilderPanelExt};
51/// # use topcoat::{context::Cx, router::{Router, RouterBuilderDiscoverExt}};
52/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
53/// # struct User { #[key] #[auto] id: uuid::Uuid, name: String }
54/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
55/// # struct Order { #[key] #[auto] id: uuid::Uuid, total: i64 }
56/// # struct UserResource;
57/// # impl Resource for UserResource { type Model = User; type Form = NoForm<User>; }
58/// # struct OrderResource;
59/// # impl Resource for OrderResource { type Model = Order; type Form = NoForm<Order>; }
60/// # struct Member;
61/// # impl PanelUser for Member {
62/// #     fn user_id(&self) -> String { String::new() }
63/// #     fn display_name(&self) -> &str { "" }
64/// #     fn can_access_panel(&self, _panel: &tablo_core::PanelId) -> bool { true }
65/// # }
66/// # struct Members;
67/// # impl Authenticator for Members {
68/// #     type User = Member;
69/// #     async fn verify(&self, _: &Cx, _: &str, _: &str) -> topcoat::Result<Option<Member>> { Ok(None) }
70/// #     async fn find_by_id(&self, _: &Cx, _: &str) -> topcoat::Result<Option<Member>> { Ok(None) }
71/// # }
72/// # fn main() -> topcoat::Result<()> {
73/// # let db: toasty::Db = todo!();
74/// let mut builder = Router::builder().discover().with(db);
75/// let admin = builder.panel(Panel::new("admin").resource::<UserResource>())?;
76/// let portal =
77///     builder.panel(Panel::new("portal").auth(Auth::custom(Members)).resource::<OrderResource>())?;
78/// let router = builder.build();
79/// assert!(admin.id() == "admin" && portal.id() == "/portal");
80/// # let _ = router;
81/// # Ok(())
82/// # }
83/// ```
84pub trait RouterBuilderPanelExt: Sized {
85    /// Mounts `panel` at its prefix with its routes, shell layout, and gating layers, and returns
86    /// its [`PanelHandle`]: what a job, a test or a public page keeps to reach the mounted panel,
87    /// and whose [`id`](PanelHandle::id) is the one
88    /// [`PanelUser::can_access_panel`](crate::PanelUser::can_access_panel) receives.
89    ///
90    /// The panel reads the router's `Db` and asset bundle, so `.with(db)` and
91    /// `.assets(..)` come first. The first panel mounted also installs what every panel shares:
92    /// cookies, the gate over Topcoat's runtime endpoints, and Topcoat's runtime layer with link
93    /// prefetching off unless the router already set those up. A panel keeps its sessions in its
94    /// own cookie, so the app's Topcoat sessions, if any, stay the app's. The runtime layer has no
95    /// path, so mount panels after the app's own pathless layers: a page re-run must reach
96    /// those layers already rewritten to a `GET`.
97    ///
98    /// # Errors
99    ///
100    /// A [`MountError`](crate::MountError) listing every declaration mistake, each a
101    /// [`DeclarationErrorKind`](crate::DeclarationErrorKind). A refused panel leaves the builder
102    /// empty: build no router from it.
103    fn panel(&mut self, panel: Panel) -> Result<PanelHandle>;
104}
105
106impl RouterBuilderPanelExt for RouterBuilder {
107    fn panel(&mut self, panel: Panel) -> Result<PanelHandle> {
108        let (builder, handle) = panel.mount(std::mem::take(self))?;
109        *self = builder;
110        Ok(handle)
111    }
112}
113
114impl Panel {
115    fn mount(self, mut builder: RouterBuilder) -> Result<(RouterBuilder, PanelHandle)> {
116        let db = builder.try_context::<Db>().cloned();
117        let services = crate::auth::mount::Services::of(&builder);
118        let mut registry = Registry::new(self.prefix.clone(), db.as_ref().map(AppSchema::of_db));
119        let Panel {
120            prefix,
121            host,
122            shell_assets,
123            brand,
124            dark_mode,
125            environment,
126            layout,
127            registrations,
128            content_security_policy,
129            content_security_policy_sources,
130            strict_transport_security,
131            configuration_errors,
132            uploads,
133            served_dirs,
134            login_hint,
135            user_menu,
136            banners,
137            auth,
138            mut endpoints,
139            notifications,
140            time_zone,
141            locales,
142            translations,
143            default_translations,
144            global_search,
145            limits,
146            commit_hooks,
147            auth_hooks,
148            required_models,
149            loads,
150        } = self;
151        let (mounts, mut errors) = registry.register_all(registrations, configuration_errors);
152        errors.extend(missing_commit_hooks(&registry.resources, &commit_hooks));
153        let commit_hooks = commit_hooks.into_iter().map(|(_, hook)| hook).collect();
154        let auth_hooks = auth_hooks.into_iter().map(|(_, hook)| hook).collect();
155        let serves_tenants = serves_tenants(&auth, &mounts);
156        errors.extend(registry.unoffered_auth_pages(&auth));
157        errors.extend(mount_errors(
158            &builder,
159            &prefix,
160            shell_assets.is_some(),
161            &served_dirs,
162        ));
163        match &db {
164            Some(db) => {
165                registry.check_all(
166                    db,
167                    &mounts,
168                    serves_tenants,
169                    uploads.is_some(),
170                    &limits,
171                    &mut errors,
172                );
173                let toggles = registry.resources.iter().any(|resource| resource.toggles);
174                errors.extend(
175                    crate::auth::mount::declaration_errors(
176                        db,
177                        &auth,
178                        toggles,
179                        notifications,
180                        services,
181                    )
182                    .into_iter()
183                    .map(DeclarationError::panel),
184                );
185                errors.extend(unregistered_models(db, &required_models));
186            }
187            None => errors.push(DeclarationError::panel(DeclarationErrorKind::MissingDb)),
188        }
189        let catalog = build_catalog(&locales, &default_translations, &translations, &mut errors);
190        let panel_headers = match content_security_policy
191            .resolve(&content_security_policy_sources)
192            .and_then(|policy| {
193                headers::PanelHeaders::new(
194                    prefix.clone(),
195                    policy.as_deref(),
196                    strict_transport_security,
197                )
198            }) {
199            Ok(layer) => Some(layer),
200            Err(kind) => {
201                errors.push(DeclarationError::panel(kind));
202                None
203            }
204        };
205        if !errors.is_empty() {
206            return Err(MountError::new(&prefix, errors).into());
207        }
208        let catalog = Arc::new(catalog.expect("a catalog that failed to build fails the mount"));
209        if builder.try_context::<Panels>().is_none() {
210            builder = install_shared(builder);
211        }
212        let pages = super::area::settings_paths(&prefix, &registry.auth_pages);
213        let Registry {
214            urls,
215            mounted_pages,
216            nav_items,
217            trails,
218            areas,
219            searches,
220            pages: mut page_routes,
221            routes,
222            root,
223            children,
224            ..
225        } = registry;
226        let searches = if global_search {
227            super::search::in_sidebar_order(searches, &nav_items)
228        } else {
229            Vec::new()
230        };
231        if !searches.is_empty() {
232            page_routes.push(PageFn::new(
233                http::Method::GET,
234                route_path(&format!("{prefix}/{}", super::search::SEARCH_SEGMENT)),
235                super::search::search_page,
236            ));
237            endpoints.push(super::search::shard_path());
238        }
239        let root_redirect = match root {
240            Some(Root::Redirect(target)) => Some(target),
241            Some(Root::Home) | None => None,
242        };
243        let (served_paths, signed_roots) = super::files::served_paths(&served_dirs);
244        let state = Arc::new(PanelState {
245            realm: Arc::new(Realm {
246                prefix: prefix.clone(),
247                id: crate::PanelId::new(&prefix),
248                host: host.clone(),
249                auth,
250                login_hint,
251                time_zone,
252                catalog,
253                notifications,
254                serves_tenants,
255                pages,
256                auth_hooks,
257            }),
258            nav_items,
259            trails,
260            areas,
261            brand,
262            dark_mode,
263            environment,
264            shell_assets,
265            children,
266            mounts,
267            root_redirect: root_redirect.clone(),
268            user_menu,
269            banners,
270            uploads,
271            served_paths,
272            signed_roots,
273            urls,
274            mounted_pages,
275            endpoints,
276            searches,
277            limits,
278            commit_hooks,
279            loads,
280        });
281        let prefix_path = route_path(&prefix);
282        builder = builder.layer(limits.body_cap(prefix_path.clone()));
283        builder = builder
284            .layer(panel_headers.expect("a policy the header codec rejects fails the mount"));
285        // Registered last of the prefix's layers, so it runs first.
286        builder = builder.layer(PanelGate::new(Arc::clone(&state.realm)));
287        // The auth form routes carry their own cap scoped by path.
288        builder = crate::auth::mount::routes(builder, &state.realm);
289        // Only a panel with a language to switch to answers the language menu's post.
290        if state.realm.catalog.locales().len() > 1 {
291            builder = builder.route(RouteFn::new(
292                http::Method::POST,
293                route_path(&format!("{prefix}/{LANGUAGE_SEGMENT}")),
294                language_post,
295            ));
296        }
297        // Search engines skip the panel's pages, as the layout's metadata asks.
298        builder = builder.layout(
299            LayoutFn::new(prefix_path.clone(), layout.unwrap_or(Panel::layout_shell))
300                .with(Metadata::new().robots(Robots::new().index(false).follow(false))),
301        );
302        // A failed page load shows the error page inside the shell, and a path no route serves
303        // reaches the gate to fail there.
304        builder = builder
305            .page(PageFn::new(
306                http::Method::GET,
307                route_path(&format!("{prefix}/{}", error_page::ERROR_SEGMENT)),
308                error_page::error_page,
309            ))
310            .route(RouteFn::new(
311                Methods::Any,
312                route_path(&format!("{prefix}/{{*rest}}")),
313                error_page::unmatched,
314            ));
315        for served in served_dirs {
316            builder = builder
317                .layer(headers::ServedFileHeaders::new(
318                    &served,
319                    Arc::clone(&state.realm),
320                ))
321                .serve_dir(route_path(&served.path), served.dir);
322        }
323        for page in page_routes {
324            builder = builder.page(page);
325        }
326        for route in routes {
327            builder = builder.route(route);
328        }
329        if root_redirect.is_some() {
330            builder = builder.route(RouteFn::new(
331                http::Method::GET,
332                prefix_path,
333                panel_root_redirect,
334            ));
335        }
336        let handle = PanelHandle {
337            db: db.expect("a panel without a `Db` fails the mount"),
338            mounts: Arc::clone(&state.mounts),
339            catalog: Arc::clone(&state.realm.catalog),
340            id: state.realm.id.clone(),
341            prefix: state.realm.prefix.clone(),
342            panel: Some(Arc::clone(&state)),
343            bus: builder
344                .try_context::<NotificationBus>()
345                .cloned()
346                .unwrap_or_else(NotificationBus::new),
347            base_url: builder.try_context::<topcoat::context::BaseUrl>().cloned(),
348        };
349        // The builder lends no mutable access: copy the list of handles and register it again.
350        let mut panels = builder.context::<Panels>().clone();
351        panels.0.push(state);
352        Ok((builder.with(panels), handle))
353    }
354}
355
356impl Registry {
357    /// Registers `registrations` and links their relations, returning the mounts and every error,
358    /// `configuration_errors` first.
359    fn register_all(
360        &mut self,
361        registrations: Vec<Box<dyn super::register::Registration>>,
362        configuration_errors: Vec<DeclarationError>,
363    ) -> (Arc<Mounts>, Vec<DeclarationError>) {
364        for registration in registrations {
365            registration.register(self);
366        }
367        self.link_relations();
368        self.check_root();
369        let mut errors = configuration_errors;
370        errors.append(&mut self.errors);
371        (Arc::new(std::mem::take(&mut self.mounts)), errors)
372    }
373
374    /// Checks every registered resource against `db`, whether the panel acts for tenants,
375    /// whether it installs an uploader, and the body cap its `limits` set.
376    fn check_all(
377        &self,
378        db: &Db,
379        mounts: &Arc<Mounts>,
380        serves_tenants: bool,
381        has_uploader: bool,
382        limits: &crate::Limits,
383        errors: &mut Vec<DeclarationError>,
384    ) {
385        let mut cx = validation_cx(db, mounts);
386        if serves_tenants {
387            cx = cx.with(crate::resource::ServesTenants);
388        }
389        for check in &self.page_checks {
390            check(&cx, errors);
391        }
392        for registered in &self.resources {
393            (registered.check)(&cx, errors);
394            // Without an uploader a file field would accept a file and keep only its name.
395            if !has_uploader {
396                errors.extend(registered.file_fields.iter().map(|field| DeclarationError {
397                    resource: Some(registered.name),
398                    site: Site::Form,
399                    kind: DeclarationErrorKind::FileFieldWithoutUploader {
400                        field: field.clone(),
401                    },
402                }));
403            }
404            // The body cap refuses a larger file first, so the field's own rule would never.
405            let cap = limits.body_bytes;
406            errors.extend(
407                registered
408                    .file_caps
409                    .iter()
410                    .filter(|(_, max)| *max >= cap)
411                    .map(|(field, max)| DeclarationError {
412                        resource: Some(registered.name),
413                        site: Site::Form,
414                        kind: DeclarationErrorKind::FieldRule {
415                            field: field.clone(),
416                            fault: crate::FieldRuleFault::AboveFormCap { max: *max, cap },
417                        },
418                    }),
419            );
420        }
421    }
422}
423
424/// Whether a panel with `auth` and `mounts` acts for tenants: it offers a tenant registration or
425/// settings page, or mounts a tenant-scoped resource. A resource that declares `Tenancy::none()`
426/// over tenant-owned rows serves every tenant, so it makes no tenant the panel's.
427fn serves_tenants(auth: &crate::auth::AuthConfig, mounts: &Mounts) -> bool {
428    auth.tenant_registration_page().is_some()
429        || auth.tenant_editor().is_some()
430        || mounts.scopes_tenants()
431}
432
433/// What refuses a panel at `prefix` before its resources are checked.
434fn mount_errors(
435    builder: &RouterBuilder,
436    prefix: &str,
437    shell_assets: bool,
438    served_dirs: &[headers::ServedDir],
439) -> Vec<DeclarationError> {
440    let mut errors = Vec::new();
441    let mut refuse = |kind| errors.push(DeclarationError::panel(kind));
442    if shell_assets && builder.try_context::<AssetConfig>().is_none() {
443        refuse(DeclarationErrorKind::ShellAssetsWithoutBundle);
444    }
445    if under_prefix(RUNTIME_PREFIX, prefix) || under_prefix(prefix, RUNTIME_PREFIX) {
446        refuse(DeclarationErrorKind::PrefixOverlapsRuntime {
447            prefix: prefix.to_string(),
448        });
449    }
450    for (index, served) in served_dirs.iter().enumerate() {
451        let root = served_root(&served.path);
452        if served_dirs[..index]
453            .iter()
454            .any(|seen| served_root(&seen.path) == root)
455        {
456            refuse(DeclarationErrorKind::ServeDir(
457                crate::ServeDirFault::Twice {
458                    path: served.path.clone(),
459                },
460            ));
461        }
462    }
463    if let Some(panels) = builder.try_context::<Panels>() {
464        for other in &panels.0 {
465            for ServedDir { path, .. } in served_dirs {
466                if other
467                    .served_paths
468                    .iter()
469                    .any(|served| served_root(served) == served_root(path))
470                {
471                    refuse(DeclarationErrorKind::ServeDir(
472                        crate::ServeDirFault::Taken {
473                            path: path.clone(),
474                            panel: other.realm.prefix.clone(),
475                        },
476                    ));
477                }
478            }
479            let other = &other.realm.prefix;
480            if under_prefix(other, prefix) || under_prefix(prefix, other) {
481                refuse(DeclarationErrorKind::PrefixOverlapsPanel {
482                    other: other.clone(),
483                });
484            }
485        }
486    }
487    errors
488}
489
490/// Redirects the panel root of a panel with no [`home`](Panel::home) page to the first declared
491/// resource's list.
492pub(crate) fn panel_root_redirect(cx: &Cx, _body: Body) -> RouteFuture<'_> {
493    Box::pin(async move {
494        // Re-checks the resolved user so a mis-mounted gate cannot leak the slug.
495        crate::auth::guard(cx)?;
496        let target = current(cx)
497            .and_then(|panel| panel.root_redirect.clone())
498            .ok_or_else(topcoat::router::error::not_found)?;
499        Err(redirect(target).into())
500    })
501}
502
503/// Reports whether `path` is a route pattern ending in a catch-all.
504pub(super) fn is_directory_pattern(path: &str) -> bool {
505    Path::from_str(path)
506        .ok()
507        .and_then(|parsed| parsed.segments().next_back())
508        .is_some_and(|segment| segment.as_catch_all().is_some())
509}
510
511/// Validates one path segment a panel derives routes from, refusing anything that cannot serve as a
512/// literal URL segment.
513pub(super) fn validate_route_segment(
514    item: &'static str,
515    segment: &str,
516) -> Result<(), DeclarationErrorKind> {
517    match segment_fault(segment) {
518        Some(fault) => Err(DeclarationErrorKind::InvalidSegment {
519            item,
520            segment: segment.to_string(),
521            fault,
522        }),
523        None => Ok(()),
524    }
525}
526
527/// The refusal of each of `required` that `db` does not register.
528fn unregistered_models(db: &Db, required: &[String]) -> Vec<DeclarationError> {
529    let schema = AppSchema::of_db(db);
530    required
531        .iter()
532        .filter(|model| !schema.registers(model))
533        .map(|model| {
534            DeclarationError::panel(DeclarationErrorKind::UnregisteredModel {
535                model: model.clone(),
536            })
537        })
538        .collect()
539}
540
541/// The panel's catalog over `locales`, with `defaults` under `translations`; `None`, with each
542/// fault pushed onto `errors`, when it does not build.
543fn build_catalog(
544    locales: &[topcoat::l10n::Locale],
545    defaults: &[(topcoat::l10n::Locale, String)],
546    translations: &[(topcoat::l10n::Locale, String)],
547    errors: &mut Vec<DeclarationError>,
548) -> Option<crate::i18n::Catalog> {
549    crate::i18n::Catalog::new(locales, defaults, translations)
550        .map_err(|faults| {
551            errors.extend(
552                faults
553                    .into_iter()
554                    .map(|fault| DeclarationError::panel(DeclarationErrorKind::Locale(fault))),
555            );
556        })
557        .ok()
558}
559
560/// Builds the context for the mount-time declaration checks and [`PanelHandle::context`] from `db`
561/// and
562/// the panel's `mounts`, with no request.
563fn validation_cx(db: &Db, mounts: &Arc<Mounts>) -> Cx {
564    let mut values = topcoat::context::ContextMap::new();
565    values.insert(db.clone());
566    values.insert(Arc::clone(mounts));
567    values.insert(AuthHost(&PanelHost));
568    values.insert(MountScope(|cx| {
569        topcoat::context::try_context::<Arc<Mounts>>(cx).map(|mounts| &**mounts)
570    }));
571    Cx::new().with_shared(Arc::new(values))
572}
573
574#[cfg(test)]
575mod tests;