1use 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
47pub trait RouterBuilderPanelExt: Sized {
85 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(®istry.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, ®istry.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 builder = builder.layer(PanelGate::new(Arc::clone(&state.realm)));
287 builder = crate::auth::mount::routes(builder, &state.realm);
289 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 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 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 let mut panels = builder.context::<Panels>().clone();
351 panels.0.push(state);
352 Ok((builder.with(panels), handle))
353 }
354}
355
356impl Registry {
357 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 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 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 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
424fn 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
433fn 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
490pub(crate) fn panel_root_redirect(cx: &Cx, _body: Body) -> RouteFuture<'_> {
493 Box::pin(async move {
494 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
503pub(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
511pub(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
527fn 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
541fn 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
560fn 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;