1use std::collections::HashMap;
2use std::future::Future;
3use std::net::SocketAddr;
4use std::sync::Arc;
5use std::time::Duration;
6
7use anyhow::anyhow;
8use axum::Router;
9use axum::handler::HandlerWithoutStateExt;
10use axum::middleware::{from_fn, from_fn_with_state};
11use tokio::net::TcpListener;
12use tokio::sync::watch;
13use tower_http::services::ServeDir;
14use tower_http::trace::TraceLayer;
15use tracing_subscriber::EnvFilter;
16
17use crate::auth::{Gate, LoginThrottle, User};
18use crate::crypto::parse_key;
19use crate::db::{Db, Migration, MigrationStatus, Migrator};
20use crate::events::Event;
21use crate::mail::Mailer;
22use crate::queue::{Handlers, Job, Queue, Worker};
23use crate::routing::RouteInfo;
24use crate::schedule::Schedule;
25use crate::timezone::Zone;
26use crate::{
27 AppState, Config, Environment, Error, Module, Registry, Result, RouteTable, Views, assets,
28 auth, csrf, session, view,
29};
30
31const SHUTDOWN_GRACE: Duration = Duration::from_secs(30);
33
34const USAGE: &str = "\
35Usage: <app> [command]
36
37Commands:
38 serve Start the web server, queue workers and scheduler (default)
39 migrate Run pending migrations
40 migrate:rollback [--step N]
41 Undo the last N batches of migrations (default 1)
42 migrate:fresh [--seed] Drop all tables, run every migration, optionally seed
43 migrate:status List migrations and whether they have run
44 db:check Compare the registered models with the tables the migrations build
45 db:diff [name] [--yes] Write a migration for what changed in the registered models
46 db:seed Run the seeders
47 queue:work [--queue a,b] [--workers N] [--once]
48 Run queued jobs (until stopped, or --once for what's there)
49 queue:failed List failed jobs
50 queue:retry <id|all> Put failed jobs back on the queue
51 queue:flush Delete failed jobs
52 queue:forget <id> Delete one failed job
53 queue:prune-failed [--hours N]
54 Delete failed jobs older than N hours (default 168)
55 queue:prune-batches [--hours N]
56 Delete batches finished more than N hours ago (default 24)
57 webhook:failed List webhook calls whose processing failed
58 webhook:retry <id> Process a stored webhook call again
59 webhook:endpoints List the outbound webhook endpoints
60 webhook:deliveries [--endpoint N] [--failed]
61 List outbound webhook deliveries, newest first
62 webhook:redeliver <id> Send a stored outbound delivery again
63 webhook:prune-deliveries [--days N]
64 Delete deliveries older than N days (default 30)
65 ui:publish [--force] Copy the UI kit (renox/ui.html and its CSS) into the app to change it
66 sequence:list List the numbering series (`Sequence`) and their last numbers
67 cache:prune Delete expired rows of the database cache store
68 session:prune Delete expired sessions (SESSION_DRIVER=database)
69 idempotency:prune [--days N]
70 Delete offline-form keys older than N days (default 7)
71 import:prune [--days N] Delete the records of imports whose undo window ended N days ago (default 0)
72 schedule:list List scheduled tasks and when they run next
73 schedule:run <task> Run one scheduled task now
74 schedule:work Run scheduled tasks (when SCHEDULER=false for serve)
75 route:list List every route with its name, module and guards
76 view:check Compile every template; check route names and typed views
77 state:diagram [Model] Print a state machine as a Mermaid diagram (no name: list them)
78 view:data [--out P] Write .vscode/renox-components.json for editor autocomplete
79 db:shell Run SQL against the database (`.tables`, `.quit`)
80 down [--secret S] [--retry N]
81 Maintenance mode: answer 503 (visit /S to bypass it)
82 up Leave maintenance mode
83 help Show this message";
84
85pub struct App {
110 config: Option<Config>,
111 modules: Vec<Box<dyn Module>>,
112 migrations: Vec<Migration>,
113 gates: HashMap<String, Gate>,
114 async_gates: HashMap<String, crate::auth::AsyncGate>,
115 gate_before: Option<crate::auth::GateBefore>,
116 registry: Registry,
117 embedded: Option<crate::Embedded>,
118 csp: crate::security::Csp,
119 permissions_policy: crate::security::PermissionsPolicy,
120 provided: HashMap<std::any::TypeId, Arc<dyn std::any::Any + Send + Sync>>,
121 layers: Vec<AppLayer>,
122 limiters: HashMap<String, crate::rate_limit::LimitRule>,
123 detect_locale: bool,
124 rtl_locales: Option<Vec<String>>,
125 disks: Vec<(String, DiskSettings)>,
126 uploads: crate::upload::Pipeline,
127 mailers: Vec<(String, MailerSettings)>,
128 mailer_limits: HashMap<String, crate::queue::Limit>,
129 xsrf_cookie: bool,
130 settings_seed: Option<std::path::PathBuf>,
131 theme: Option<crate::theme::Theme>,
132 theme_chooser: Option<crate::theme::ThemeFn>,
133 pwa: Option<crate::pwa::Pwa>,
134 pwa_chooser: Option<crate::pwa::PwaFn>,
135}
136
137type MailerSettings = Box<dyn Fn(&Config) -> Result<crate::mail::MailConfig> + Send + Sync>;
139
140type DiskSettings = Box<dyn Fn(&Config) -> Result<crate::storage::StorageConfig> + Send + Sync>;
142
143type AppLayer = Box<dyn Fn(Router<AppState>) -> Router<AppState> + Send + Sync>;
146
147impl App {
148 pub fn new() -> Self {
150 Self {
151 config: None,
152 modules: Vec::new(),
153 migrations: Vec::new(),
154 gates: HashMap::new(),
155 async_gates: HashMap::new(),
156 gate_before: None,
157 registry: Registry::default(),
158 embedded: None,
159 csp: crate::security::Csp::default(),
160 permissions_policy: crate::security::PermissionsPolicy::default(),
161 provided: HashMap::new(),
162 layers: Vec::new(),
163 limiters: HashMap::new(),
164 detect_locale: false,
165 rtl_locales: None,
166 disks: Vec::new(),
167 uploads: crate::upload::Pipeline::new(),
168 mailers: Vec::new(),
169 mailer_limits: HashMap::new(),
170 xsrf_cookie: false,
171 settings_seed: None,
172 theme: None,
173 theme_chooser: None,
174 pwa: None,
175 pwa_chooser: None,
176 }
177 }
178
179 pub fn detect_locale(mut self) -> Self {
193 self.detect_locale = true;
194 self
195 }
196
197 pub fn rtl_locales(mut self, locales: &[&str]) -> Self {
209 self.rtl_locales = Some(locales.iter().map(|l| (*l).to_owned()).collect());
210 self
211 }
212
213 pub fn layer<L>(mut self, layer: L) -> Self
237 where
238 L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static,
239 L::Service: tower::Service<axum::extract::Request> + Clone + Send + Sync + 'static,
240 <L::Service as tower::Service<axum::extract::Request>>::Response:
241 axum::response::IntoResponse + 'static,
242 <L::Service as tower::Service<axum::extract::Request>>::Error:
243 Into<std::convert::Infallible> + 'static,
244 <L::Service as tower::Service<axum::extract::Request>>::Future: Send + 'static,
245 {
246 self.layers
247 .push(Box::new(move |router| router.layer(layer.clone())));
248 self
249 }
250
251 pub fn csp(mut self, allow: impl FnOnce(&mut crate::security::Csp)) -> Self {
254 allow(&mut self.csp);
255 self
256 }
257
258 pub fn permissions_policy(
274 mut self,
275 allow: impl FnOnce(&mut crate::security::PermissionsPolicy),
276 ) -> Self {
277 allow(&mut self.permissions_policy);
278 self
279 }
280
281 pub fn embed(mut self, embedded: crate::Embedded) -> Self {
285 self.embedded = Some(embedded);
286 self
287 }
288
289 pub fn with_config(config: Config) -> Self {
291 Self {
292 config: Some(config),
293 ..Self::new()
294 }
295 }
296
297 pub fn config(mut self, config: Config) -> Self {
299 self.config = Some(config);
300 self
301 }
302
303 pub fn module(mut self, module: impl Module) -> Self {
305 self.modules.push(Box::new(module));
306 self
307 }
308
309 pub fn migrations(mut self, migrations: &[Migration]) -> Self {
311 self.migrations.extend_from_slice(migrations);
312 self
313 }
314
315 pub fn seeder<F, Fut>(mut self, seeder: F) -> Self
332 where
333 F: Fn(AppState) -> Fut + Send + Sync + 'static,
334 Fut: Future<Output = Result> + Send + 'static,
335 {
336 self.registry.seeder(seeder);
337 self
338 }
339
340 pub fn gate(
350 mut self,
351 name: &str,
352 check: impl Fn(&User) -> bool + Send + Sync + 'static,
353 ) -> Self {
354 self.gates.insert(name.to_owned(), Arc::new(check));
355 self
356 }
357
358 pub fn gate_before(
389 mut self,
390 check: impl Fn(&User, &str) -> Option<bool> + Send + Sync + 'static,
391 ) -> Self {
392 self.gate_before = Some(Arc::new(check));
393 self
394 }
395
396 pub fn gate_async<F, Fut>(mut self, name: &str, check: F) -> Self
399 where
400 F: Fn(User, AppState) -> Fut + Send + Sync + 'static,
401 Fut: Future<Output = Result<bool>> + Send + 'static,
402 {
403 self.async_gates.insert(
404 name.to_owned(),
405 Arc::new(move |user, state| Box::pin(check(user, state))),
406 );
407 self
408 }
409
410 pub fn webhook<W: crate::webhook::Webhook>(mut self) -> Self {
413 self.registry.webhook::<W>();
414 self
415 }
416
417 pub fn model<M: crate::db::Model>(mut self) -> Self {
426 self.registry.model::<M>();
427 self
428 }
429
430 pub fn state_machine<M: crate::state_machine::StateMachine>(mut self) -> Self {
433 self.registry.model::<M>();
434 crate::state_machine::register::<M>();
435 self
436 }
437
438 pub fn view_data<T: crate::ViewData>(mut self) -> Self {
451 self.registry.view_data::<T>();
452 self
453 }
454
455 pub fn live_component<C: crate::live_component::LiveComponent>(mut self) -> Self {
457 self.registry.live_component::<C>();
458 self
459 }
460
461 pub fn job<J: Job>(mut self) -> Self {
463 self.registry.job::<J>();
464 self
465 }
466
467 pub fn webhook_event<E: Event>(
470 mut self,
471 name: &str,
472 map: impl Fn(&E) -> serde_json::Value + Send + Sync + 'static,
473 ) -> Self {
474 self.registry.webhook_event(name, map);
475 self
476 }
477
478 pub fn listen<E, F, Fut>(mut self, listener: F) -> Self
480 where
481 E: Event,
482 F: Fn(E, AppState) -> Fut + Send + Sync + 'static,
483 Fut: Future<Output = Result> + Send + 'static,
484 {
485 self.registry.listen(listener);
486 self
487 }
488
489 pub fn settings<T: crate::settings::SettingsGroup>(mut self) -> Self {
493 self.registry.settings::<T>();
494 self
495 }
496
497 pub fn settings_in_views<T: crate::settings::SettingsGroup>(mut self) -> Self {
501 self.registry.settings_in_views::<T>();
502 self
503 }
504
505 pub fn settings_from(mut self, path: impl Into<std::path::PathBuf>) -> Self {
511 self.settings_seed = Some(path.into());
512 self
513 }
514
515 pub fn command<F, Fut>(mut self, name: &str, about: &str, run: F) -> Self
518 where
519 F: Fn(crate::command::Args, AppState) -> Fut + Send + Sync + 'static,
520 Fut: Future<Output = Result> + Send + 'static,
521 {
522 self.registry.command(name, about, run);
523 self
524 }
525
526 pub fn typed_command<T: crate::command::AppCommand>(mut self) -> Self {
529 self.registry.typed_command::<T>();
530 self
531 }
532
533 pub fn rate_limiter(
537 mut self,
538 name: &str,
539 rule: impl Fn(&crate::rate_limit::LimitRequest) -> crate::rate_limit::Limit
540 + Send
541 + Sync
542 + 'static,
543 ) -> Self {
544 self.limiters
545 .insert(name.to_owned(), std::sync::Arc::new(rule));
546 self
547 }
548
549 pub fn report<F, Fut>(mut self, reporter: F) -> Self
553 where
554 F: Fn(crate::report::ErrorReport, AppState) -> Fut + Send + Sync + 'static,
555 Fut: Future<Output = ()> + Send + 'static,
556 {
557 self.registry.report(reporter);
558 self
559 }
560
561 pub fn channel<F, Fut>(mut self, name: &str, send: F) -> Self
564 where
565 F: Fn(crate::auth::Recipient, serde_json::Value, AppState) -> Fut + Send + Sync + 'static,
566 Fut: Future<Output = Result> + Send + 'static,
567 {
568 self.registry.channel(name, send);
569 self
570 }
571
572 pub fn channel_rate_limit(mut self, name: &str, max: u32, per: std::time::Duration) -> Self {
586 self.registry.channel_rate_limit(name, max, per);
587 self
588 }
589
590 pub fn mailer_rate_limit(mut self, name: &str, max: u32, per: std::time::Duration) -> Self {
607 self.mailer_limits
608 .insert(name.to_owned(), crate::queue::Limit::new(max, per));
609 self
610 }
611
612 pub fn xsrf_cookie(mut self) -> Self {
618 self.xsrf_cookie = true;
619 self
620 }
621
622 pub fn mailer(
640 mut self,
641 name: &str,
642 settings: impl Fn(&Config) -> Result<crate::mail::MailConfig> + Send + Sync + 'static,
643 ) -> Self {
644 self.mailers.push((name.to_owned(), Box::new(settings)));
645 self
646 }
647
648 pub fn disk(
667 mut self,
668 name: &str,
669 settings: impl Fn(&Config) -> Result<crate::storage::StorageConfig> + Send + Sync + 'static,
670 ) -> Self {
671 self.disks.push((name.to_owned(), Box::new(settings)));
672 self
673 }
674
675 pub fn uploads(mut self, pipeline: crate::upload::Pipeline) -> Self {
688 self.uploads = pipeline;
689 self
690 }
691
692 pub fn provide<T: Send + Sync + 'static>(mut self, value: T) -> Self {
698 self.provided
699 .insert(std::any::TypeId::of::<T>(), Arc::new(value));
700 self
701 }
702
703 pub fn theme(mut self, theme: crate::theme::Theme) -> Self {
715 self.theme = Some(theme);
716 self
717 }
718
719 pub fn pwa(mut self, pwa: crate::pwa::Pwa) -> Self {
734 self.pwa = Some(pwa);
735 self
736 }
737
738 pub fn theme_for<F, Fut>(mut self, choose: F) -> Self
756 where
757 F: Fn(crate::theme::ThemeRequest) -> Fut + Send + Sync + 'static,
758 Fut: Future<Output = Result<Option<crate::theme::Theme>>> + Send + 'static,
759 {
760 self.theme_chooser = Some(crate::theme::theme_fn(choose));
761 self
762 }
763
764 pub fn pwa_for<F, Fut>(mut self, resolve: F) -> Self
787 where
788 F: Fn(crate::pwa::PwaRequest) -> Fut + Send + Sync + 'static,
789 Fut: Future<Output = Result<Option<crate::pwa::PwaBrand>>> + Send + 'static,
790 {
791 self.pwa_chooser = Some(crate::pwa::pwa_fn(resolve));
792 self
793 }
794
795 pub fn share<F, Fut, T>(mut self, key: &str, compute: F) -> Self
797 where
798 F: Fn(crate::view::ViewContext) -> Fut + Send + Sync + 'static,
799 Fut: Future<Output = Result<T>> + Send + 'static,
800 T: serde::Serialize,
801 {
802 self.registry.share(key, compute);
803 self
804 }
805
806 pub fn nav(mut self, menu: &str, link: crate::nav::NavLink) -> Self {
808 self.registry.nav(menu, link);
809 self
810 }
811
812 pub fn signing_key(mut self, key_id: &str, secret: &str) -> Self {
814 self.registry.signing_key(key_id, secret);
815 self
816 }
817
818 pub fn nav_hide(mut self, menu: &str, key: &str) -> Self {
820 self.registry.nav_hide(menu, key);
821 self
822 }
823
824 pub fn templates(
826 mut self,
827 hook: impl Fn(&mut minijinja::Environment<'static>) + Send + Sync + 'static,
828 ) -> Self {
829 self.registry.templates(hook);
830 self
831 }
832
833 pub fn schedule(mut self, define: impl FnOnce(&mut Schedule)) -> Self {
835 define(self.registry.schedule());
836 self
837 }
838
839 pub async fn boot(mut self) -> Result<Kernel> {
841 let config = match self.config {
842 Some(config) => config,
843 None => Config::load()?,
844 };
845
846 self.registry.job::<crate::mail::SendMail>();
847 self.registry.job::<crate::mail::SendMailVia>();
848 self.registry
849 .job::<crate::auth::notifications::SendToChannel>();
850 self.registry
851 .job::<crate::auth::passwordless::SendLoginSecret>();
852 self.registry.job::<crate::webhook::ProcessWebhook>();
853 self.registry
854 .job::<crate::webhook::outbound::DeliverWebhook>();
855 #[cfg(feature = "server-events")]
856 self.registry.job::<crate::analytics::ServerEvent>();
857 let mut migrations = crate::queue::MIGRATIONS.to_vec();
858 migrations.push(crate::cache::MIGRATION);
859 migrations.push(crate::session::MIGRATION);
860 migrations.push(crate::grid::MIGRATION);
861 migrations.push(crate::import::MIGRATION);
862 migrations.extend(crate::webhook::MIGRATIONS);
863 migrations.push(crate::db::SEQUENCE_MIGRATION);
864 migrations.push(crate::state_machine::MIGRATION);
865 migrations.push(crate::custom_fields::MIGRATION);
866 migrations.push(crate::idempotency::MIGRATION);
867 migrations.extend(self.migrations);
868 for module in &self.modules {
869 migrations.extend_from_slice(module.migrations());
870 self.registry.contributions.set_module(module.name());
871 module.register(&mut self.registry);
872 }
873 let Registry {
874 jobs,
875 listeners,
876 mut schedule,
877 duplicate_job,
878 webhooks,
879 webhook_events,
880 live_components,
881 duplicate_live,
882 commands,
883 templates,
884 components,
885 mut shares,
886 channels,
887 channel_limits,
888 reporters,
889 permissions,
890 second_factor,
891 duplicate_second_factor,
892 mut account_sections,
893 auth,
894 assets: static_assets,
895 provided: mut module_provided,
896 seeders,
897 models,
898 view_data,
899 settings_groups,
900 settings_module,
901 nav_links,
902 nav_hidden,
903 signing_keys,
904 contributions,
905 } = self.registry;
906 if !settings_groups.is_empty() && !settings_module {
907 return Err(anyhow!(
908 "settings groups are declared (`App::settings`), but the `Settings` module isn't \
909 on: add `.module(renox::settings::Settings)`"
910 )
911 .into());
912 }
913 let mut seen = std::collections::HashSet::new();
914 for group in &settings_groups {
915 if !seen.insert(group.key) {
916 return Err(anyhow!("two settings groups have the key `{}`", group.key).into());
917 }
918 }
919 let settings_seed = match &self.settings_seed {
920 Some(path) => crate::settings::read_seed(path)?,
921 None => None,
922 };
923 if settings_groups.iter().any(|group| group.shared) {
924 shares.push((
925 "settings".to_owned(),
926 crate::view::share_fn(|ctx: crate::view::ViewContext| async move {
927 ctx.state.settings_for_views().await
928 }),
929 ));
930 }
931 module_provided.extend(self.provided);
933 check_assets(&static_assets)?;
934 let static_assets: Arc<[crate::registry::StaticAsset]> = static_assets.into();
935 if let Some(name) = duplicate_job {
936 return Err(anyhow!("job `{name}` is registered twice").into());
937 }
938 if let Some(name) = duplicate_live {
939 return Err(anyhow!("live component `{name}` is registered twice").into());
940 }
941 if duplicate_second_factor {
942 return Err(
943 anyhow!("two modules set a second login step (`Registry::second_factor`)").into(),
944 );
945 }
946 let nav = crate::nav::Nav::build(nav_links, nav_hidden)?;
947 check_commands(&commands)?;
948 schedule.check()?;
949 let zone: Zone = config.timezone;
950
951 let migrator = Migrator::new(migrations)?;
952 let key = match &config.key {
953 Some(key) => parse_key(key)?,
954 None => parse_key(&crate::generate_key())?,
955 };
956 let db = crate::db::connect(&config).await?.with_key(key.clone());
958
959 let mut router = Router::new();
960 let mut fallback: Option<axum::routing::MethodRouter<AppState>> = None;
961 let mut domains: Vec<(
963 crate::domain::DomainPattern,
964 Router<AppState>,
965 Option<axum::routing::MethodRouter<AppState>>,
966 )> = Vec::new();
967 let mut routes = RouteTable::default();
968 let mut listing: Vec<RouteInfo> = Vec::new();
969 let contributions = Arc::new(contributions);
971 for module in &self.modules {
972 tracing::debug!(module = module.name(), "registering module");
973 let parts = module.routes_with(&contributions).into_parts();
974 check_clashes(&listing, &parts.listing, None, module.name())?;
975 router = merge_routes(router, parts.router, module.name())?;
976 for (name, path) in parts.names {
977 routes.insert(name, path)?;
978 }
979 listing.extend(parts.listing.into_iter().map(|info| RouteInfo {
980 module: module.name().to_owned(),
981 ..info
982 }));
983 if let Some(handler) = parts.fallback {
984 if fallback.is_some() {
985 return Err(anyhow!(
986 "two modules set a fallback route (`{}` is the second)",
987 module.name()
988 )
989 .into());
990 }
991 fallback = Some(handler);
992 }
993 for (text, domain_routes) in parts.domains {
994 let pattern = crate::domain::DomainPattern::parse(&text)?;
995 let inner = domain_routes.into_parts();
996 if !inner.domains.is_empty() {
997 return Err(anyhow!(
998 "Routes::domain(\"{text}\", …) inside another domain (module `{}`)",
999 module.name()
1000 )
1001 .into());
1002 }
1003 check_clashes(
1004 &listing,
1005 &inner.listing,
1006 Some(pattern.as_str()),
1007 module.name(),
1008 )?;
1009 let at = match domains.iter().position(|(p, _, _)| *p == pattern) {
1010 Some(at) => at,
1011 None => {
1012 domains.push((pattern.clone(), Router::new(), None));
1013 domains.len() - 1
1014 }
1015 };
1016 let (_, domain_router, domain_fallback) = &mut domains[at];
1017 *domain_router =
1018 merge_routes(std::mem::take(domain_router), inner.router, module.name())?;
1019 if let Some(handler) = inner.fallback {
1020 if domain_fallback.is_some() {
1021 return Err(anyhow!(
1022 "two fallbacks for the domain `{text}` (module `{}`)",
1023 module.name()
1024 )
1025 .into());
1026 }
1027 *domain_fallback = Some(handler);
1028 }
1029 for (name, path) in inner.names {
1030 routes.set_domain(&name, pattern.as_str());
1031 routes.insert(name, path)?;
1032 }
1033 listing.extend(inner.listing.into_iter().map(|info| RouteInfo {
1034 module: module.name().to_owned(),
1035 domain: Some(pattern.as_str().to_owned()),
1036 ..info
1037 }));
1038 }
1039 }
1040 for layer in self.layers.iter().rev() {
1042 router = layer(router);
1043 for (_, domain_router, _) in &mut domains {
1044 *domain_router = layer(std::mem::take(domain_router));
1045 }
1046 }
1047 listing.extend(framework_routes(
1048 &config,
1049 self.pwa.is_some(),
1050 self.pwa_chooser.is_some(),
1051 ));
1052 listing.sort_by(|a, b| (&a.path, &a.method).cmp(&(&b.path, &b.method)));
1053 if config.scheduler
1056 && listing
1057 .iter()
1058 .any(|info| info.middleware.iter().any(|m| m == "offline"))
1059 && !schedule.has("idempotency:prune")
1060 {
1061 schedule.daily_at("03:30", "idempotency:prune", |state| async move {
1062 crate::idempotency::prune_retained(&state, None).await?;
1063 Ok(())
1064 });
1065 }
1066 for info in &listing {
1068 if let Some(name) = &info.name {
1069 routes.set_method(name, &info.method);
1070 }
1071 }
1072 for route in &listing {
1074 for mark in &route.middleware {
1075 if let Some(name) = mark.strip_prefix("throttle:")
1076 && !name.contains('/')
1077 && !self.limiters.contains_key(name)
1078 {
1079 return Err(anyhow!(
1080 "{} {} uses throttle_by(\"{name}\"), but there's no App::rate_limiter(\"{name}\", …)",
1081 route.method,
1082 route.path
1083 )
1084 .into());
1085 }
1086 }
1087 }
1088 for route in &listing {
1089 for provider in route
1090 .middleware
1091 .iter()
1092 .filter_map(|m| m.strip_prefix("webhook:"))
1093 {
1094 if !webhooks.contains_key(provider) {
1095 return Err(anyhow!(
1096 "the route {} receives `{provider}` webhooks, but they're not registered: \
1097 add `app.webhook::<…>()` in the module's `register`",
1098 route.path
1099 )
1100 .into());
1101 }
1102 }
1103 }
1104 let routes = Arc::new(routes);
1105
1106 let storage = crate::storage::Storage::from_config(&config)?.with_key(key.clone());
1107 let mut disks = HashMap::new();
1108 for (name, settings) in &self.disks {
1109 let valid = !name.is_empty()
1110 && name
1111 .chars()
1112 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
1113 if !valid {
1114 return Err(anyhow!(
1115 "disk name `{name}`: use letters, digits, `-` and `_` (App::disk)"
1116 )
1117 .into());
1118 }
1119 let disk = crate::storage::Storage::named(&config, name, &settings(&config)?)?
1120 .with_key(key.clone());
1121 if disks.insert(name.clone(), disk).is_some() {
1122 return Err(anyhow!("two disks are named `{name}` (App::disk)").into());
1123 }
1124 }
1125 let embedded = self.embedded.filter(|_| !config.debug);
1127 let shared_counters =
1129 (config.cache_store == crate::CacheStore::Database).then(|| db.clone());
1130 let versions = Arc::new(crate::embedded::AssetVersions::new(
1131 &config.public_path,
1132 embedded.map(|e| e.public),
1133 ));
1134 let views = Views::new(
1135 &config,
1136 routes.clone(),
1137 storage.clone(),
1138 embedded.map(|e| e.views),
1139 Arc::new(templates),
1140 Arc::new(components.iter().map(|c| c.contract()).collect()),
1141 zone,
1142 versions,
1143 )
1144 .with_typed(
1145 view_data,
1146 shares.iter().map(|(key, _)| key.clone()).collect(),
1147 );
1148 let mut security =
1149 crate::security::Security::new(&config, &self.csp, &self.permissions_policy, &listing)?;
1150 security.xsrf_cookie = self.xsrf_cookie;
1151 let security = Arc::new(security);
1152 let mut mailers = HashMap::new();
1153 for (name, settings) in &self.mailers {
1154 let mailer = Mailer::open(&settings(&config)?, &config)?;
1155 if mailers.insert(name.clone(), mailer).is_some() {
1156 return Err(anyhow!("two mailers are named `{name}` (App::mailer)").into());
1157 }
1158 }
1159 for name in self.mailer_limits.keys() {
1160 if name != "default" && !mailers.contains_key(name) {
1161 return Err(anyhow!(
1162 "App::mailer_rate_limit names `{name}`, but no mailer has that name: add it with App::mailer"
1163 )
1164 .into());
1165 }
1166 }
1167 for name in channel_limits.keys() {
1168 if !channels.contains_key(name) {
1169 return Err(anyhow!(
1170 "App::channel_rate_limit names `{name}`, but no channel has that name: add it with App::channel"
1171 )
1172 .into());
1173 }
1174 }
1175 let mut failover = Vec::new();
1176 for name in &config.mail.failover {
1177 let mailer = mailers.get(name).ok_or_else(|| {
1178 anyhow!("MAIL_FAILOVER names `{name}`, but no mailer has that name: add it with App::mailer")
1179 })?;
1180 failover.push((name.clone(), mailer.clone()));
1181 }
1182 let mailer = Mailer::from_config(&config)?.with_failover(failover);
1183 let state = AppState::new(crate::state::AppStateInner {
1184 security,
1185 webhooks: Arc::new(webhooks),
1186 webhook_events: Arc::new(webhook_events),
1187 live_components: Arc::new(live_components),
1188 mailer,
1189 mailers: Arc::new(mailers),
1190 themes: crate::theme::ThemeRegistry::new(
1191 self.theme.as_ref(),
1192 self.theme_chooser.clone(),
1193 ),
1194 pwa: self.pwa.clone().map(Arc::new),
1195 channel_limits: Arc::new(channel_limits),
1196 mailer_limits: Arc::new(self.mailer_limits),
1197 queue: Queue::new(db.clone(), key.clone()),
1198 cache: crate::cache::Cache::new(config.cache_store, db.clone())?,
1199 storage,
1200 disks: Arc::new(disks),
1201 uploads: self.uploads.clone(),
1202 http: crate::http::Http::default(),
1203 fakes: Arc::default(),
1204 settings_store: Arc::new(crate::settings::Store::new(settings_groups, settings_seed)),
1205 translator: Arc::new(match embedded {
1206 Some(files) => crate::i18n::Translator::embedded(files.lang)?,
1207 None => crate::i18n::Translator::load(&config.lang_path, config.debug)?,
1208 }),
1209 session_mirror: (config.session_driver == crate::SessionDriver::Database
1211 && config.env == Environment::Testing)
1212 .then(Default::default),
1213 live: (config.debug && config.env == Environment::Local).then(|| {
1214 crate::live::Live::start(vec![
1215 config.views_path.clone(),
1216 config.public_path.clone(),
1217 config.lang_path.clone(),
1218 ])
1219 }),
1220 notification_hub: Arc::new(crate::auth::notifications::Hub::new()),
1221 listeners: Arc::new(listeners),
1222 inspector: (config.debug && config.env == Environment::Local)
1223 .then(|| Arc::new(crate::inspector::Inspector::default())),
1224 config: Arc::new(config),
1225 routes,
1226 views,
1227 db,
1228 key,
1229 gates: Arc::new(crate::auth::Access {
1230 gates: self.gates,
1231 before: self.gate_before,
1232 permissions,
1233 }),
1234 async_gates: Arc::new(self.async_gates),
1235 shares: Arc::new(shares),
1236 channels: Arc::new(channels),
1237 reporters: Arc::new(reporters),
1238 second_factor: second_factor.map(Arc::new),
1239 nav: Arc::new(nav),
1240 signing_keys: Arc::new(signing_keys),
1241 contributions,
1242 account_sections: {
1243 account_sections.sort_by_key(|section| section.order);
1244 Arc::new(account_sections)
1245 },
1246 auth,
1247 limiters: Arc::new(
1248 self.limiters
1249 .into_iter()
1250 .map(|(name, rule)| (name, crate::rate_limit::NamedLimiter::new(rule)))
1251 .collect(),
1252 ),
1253 provided: Arc::new(module_provided),
1254 throttle: Arc::new(LoginThrottle::new(shared_counters.clone())),
1255 detect_locale: self.detect_locale,
1256 rtl_locales: self.rtl_locales.map(Arc::new),
1257 });
1258 if let Some(second) = &state.second_factor
1259 && state.url(&second.challenge, &[]).is_err()
1260 {
1261 return Err(anyhow!(
1262 "the second login step's challenge route `{}` doesn't exist",
1263 second.challenge
1264 )
1265 .into());
1266 }
1267
1268 let public = embedded.map(|e| e.public);
1269 let pwa = match self.pwa.take() {
1270 Some(pwa) => {
1271 let precache = assets::precache_urls();
1272 let assets = pwa
1273 .assets_with(
1274 |view| state.views.render(view, serde_json::json!({})),
1275 &precache,
1276 "",
1277 public,
1278 )
1279 .map_err(|e| anyhow!("{e:#}"))?;
1280 let resolver = self
1281 .pwa_chooser
1282 .take()
1283 .map(|choose| Arc::new(crate::pwa::PwaResolver::new(choose, precache)));
1284 Some((Arc::new(pwa), Arc::new(assets), resolver))
1285 }
1286 None if self.pwa_chooser.is_some() => {
1287 return Err(anyhow!("App::pwa_for needs App::pwa").into());
1288 }
1289 None => None,
1290 };
1291 let pwa = pwa.as_ref();
1292 let default = build_router(router, state.clone(), public, fallback, &static_assets, pwa);
1293 let router = if domains.is_empty() {
1294 default
1295 } else {
1296 let hosts = domains
1297 .into_iter()
1298 .map(|(pattern, router, fallback)| {
1299 (
1300 pattern,
1301 build_router(router, state.clone(), public, fallback, &static_assets, pwa),
1302 )
1303 })
1304 .collect();
1305 crate::domain::dispatch(hosts, default)
1306 };
1307 Ok(Kernel {
1308 listing,
1309 router,
1310 state,
1311 migrator,
1312 seeders,
1313 models,
1314 handlers: Arc::new(jobs),
1315 schedule,
1316 zone,
1317 commands,
1318 })
1319 }
1320
1321 pub async fn into_router(self) -> Result<Router> {
1323 Ok(self.boot().await?.router)
1324 }
1325
1326 pub fn run(self) -> Result {
1329 let args: Vec<String> = std::env::args().skip(1).collect();
1330 tokio::runtime::Builder::new_multi_thread()
1331 .enable_all()
1332 .build()?
1333 .block_on(self.run_command(&args))
1334 }
1335
1336 pub async fn run_args(self, args: impl IntoIterator<Item = impl Into<String>>) -> Result {
1347 let args: Vec<String> = args.into_iter().map(Into::into).collect();
1348 Box::pin(self.run_command(&args)).await
1352 }
1353
1354 pub async fn serve(self) -> Result {
1356 Box::pin(self.run_command(&[])).await
1357 }
1358
1359 async fn run_command(self, args: &[String]) -> Result {
1360 let command = args.first().map(String::as_str).unwrap_or("serve");
1361 if matches!(command, "help" | "--help" | "-h") {
1362 let mut modules = Registry::default();
1364 for module in &self.modules {
1365 module.register(&mut modules);
1366 }
1367 let mut commands = self.registry.commands.clone();
1368 commands.extend(modules.commands);
1369 println!("{USAGE}{}", app_commands_help(&commands));
1370 return Ok(());
1371 }
1372
1373 let config = match self.config.clone() {
1374 Some(config) => config,
1375 None => Config::load()?,
1376 };
1377 let long_running = matches!(command, "serve" | "queue:work" | "schedule:work");
1378 init_tracing(&config, long_running);
1379 if command == "serve" && config.key.is_none() && config.env != Environment::Testing {
1380 tracing::warn!(
1381 "APP_KEY is not set; using a temporary key, so sessions end on restart. \
1382 Run `rnx key:generate`."
1383 );
1384 }
1385 let kernel = App {
1386 config: Some(config),
1387 ..self
1388 }
1389 .boot()
1390 .await?;
1391
1392 match command {
1393 "serve" => kernel.serve().await?,
1394 "migrate" => print_done("Migrated", &kernel.migrate().await?),
1395 "migrate:rollback" => {
1396 let steps = flag_value(args, "--step")?.unwrap_or(1);
1397 print_done("Rolled back", &kernel.rollback(steps).await?);
1398 }
1399 "migrate:fresh" => {
1400 println!("Dropped all tables.");
1401 print_done("Migrated", &kernel.fresh().await?);
1402 if args.iter().any(|a| a == "--seed") {
1403 kernel.seed().await?;
1404 println!("Seeded.");
1405 }
1406 }
1407 "db:diff" if !kernel.commands.iter().any(|c| c.name == "db:diff") => {
1408 crate::db::auto_migration::run(&kernel, &args[1..]).await?
1409 }
1410 "db:check" if !kernel.commands.iter().any(|c| c.name == "db:check") => {
1411 kernel.db_check().await?
1412 }
1413 "view:check" if !kernel.commands.iter().any(|c| c.name == "view:check") => {
1414 let problems = kernel.state.views.check(&kernel.state.routes);
1415 for problem in &problems {
1416 println!("{problem}");
1417 }
1418 let checked = kernel.state.views.names().len();
1419 println!("Checked {checked} templates: {} problems.", problems.len());
1420 if !problems.is_empty() {
1421 return Err(anyhow!("{} template problem(s)", problems.len()).into());
1422 }
1423 }
1424 "state:diagram" if !kernel.commands.iter().any(|c| c.name == "state:diagram") => {
1425 match args.get(1) {
1426 Some(name) => match crate::state_machine::machine_info(name) {
1427 Some(info) => println!("{}", info.mermaid.trim_end()),
1428 None => {
1429 return Err(anyhow!(
1430 "no state machine called `{name}` (register it with App::state_machine); known: {}",
1431 crate::state_machine::machine_names().join(", ")
1432 )
1433 .into());
1434 }
1435 },
1436 None => {
1437 for name in crate::state_machine::machine_names() {
1438 println!("{name}");
1439 }
1440 }
1441 }
1442 }
1443 "view:data" if !kernel.commands.iter().any(|c| c.name == "view:data") => {
1444 let path = std::path::Path::new(
1445 flag_text(args, "--out").unwrap_or(".vscode/renox-components.json"),
1446 );
1447 if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
1448 std::fs::create_dir_all(dir)?;
1449 }
1450 let mut text = serde_json::to_string_pretty(&kernel.state.views.custom_data())
1451 .map_err(|e| anyhow!(e))?;
1452 text.push('\n');
1453 std::fs::write(path, text)?;
1454 println!("Wrote {}.", path.display());
1455 }
1456 "migrate:status" => {
1457 for m in kernel.migration_status().await? {
1458 let note = if m.missing {
1459 " (applied, but its file is gone)"
1460 } else if m.changed {
1461 " (edited after it ran; the edit won't run)"
1462 } else {
1463 ""
1464 };
1465 match m.batch {
1466 Some(batch) => println!(" ran (batch {batch}) {}{note}", m.name),
1467 None => println!(" pending {}", m.name),
1468 }
1469 }
1470 }
1471 "db:seed" => {
1472 kernel.seed().await?;
1473 println!("Seeded.");
1474 }
1475 "queue:work" => {
1476 let queues: Vec<String> = flag_text(args, "--queue")
1477 .map(|q| q.split(',').map(|s| s.trim().to_owned()).collect())
1478 .unwrap_or_default();
1479 let worker = kernel.worker(queues);
1480 if args.iter().any(|a| a == "--once") {
1481 println!("Ran {} job(s).", worker.drain().await?);
1482 } else {
1483 let workers = flag_value(args, "--workers")?.unwrap_or(1) as usize;
1484 let (stop, stopped) = watch::channel(false);
1485 let running = tokio::spawn(worker.run(workers, stopped));
1486 shutdown_signal().await;
1487 let _ = stop.send(true);
1488 let _ = running.await;
1489 }
1490 }
1491 "webhook:failed" => {
1492 let failed = crate::webhook::WebhookCall::failed(&kernel.state.db).await?;
1493 if failed.is_empty() {
1494 println!("No failed webhook calls.");
1495 }
1496 for call in failed {
1497 println!(
1498 " #{} {} {}: {}",
1499 call.id,
1500 call.provider,
1501 call.event_id,
1502 call.error
1503 .unwrap_or_default()
1504 .lines()
1505 .next()
1506 .unwrap_or_default()
1507 );
1508 }
1509 }
1510 "webhook:retry" => {
1511 let id: i64 = args
1512 .get(1)
1513 .and_then(|id| id.parse().ok())
1514 .ok_or_else(|| anyhow!("usage: webhook:retry <id>"))?;
1515 if crate::webhook::retry(&kernel.state, id).await? {
1516 println!("Webhook call #{id} queued again.");
1517 } else {
1518 return Err(anyhow!("there is no webhook call #{id}").into());
1519 }
1520 }
1521 "webhook:endpoints" => {
1522 let endpoints = crate::webhook::outbound::Endpoint::list(&kernel.state.db).await?;
1523 if endpoints.is_empty() {
1524 println!("No webhook endpoints.");
1525 }
1526 for e in endpoints {
1527 let state = if e.enabled {
1528 "enabled".to_owned()
1529 } else {
1530 format!("disabled: {}", e.disabled_reason.unwrap_or_default())
1531 };
1532 let events = if e.events.is_empty() {
1533 "all events".to_owned()
1534 } else {
1535 e.events.join(",")
1536 };
1537 println!(
1538 " #{} {} ({state}) {events} failures={}",
1539 e.id, e.url, e.consecutive_failures
1540 );
1541 }
1542 }
1543 "webhook:deliveries" => {
1544 let endpoint = flag_value(args, "--endpoint")?.map(i64::from);
1545 let failed = args.iter().any(|a| a == "--failed");
1546 let deliveries = crate::webhook::outbound::Delivery::list(
1547 &kernel.state.db,
1548 endpoint,
1549 failed,
1550 100,
1551 )
1552 .await?;
1553 if deliveries.is_empty() {
1554 println!("No webhook deliveries.");
1555 }
1556 for d in deliveries {
1557 let code = d
1558 .response_status
1559 .map(|c| format!(" {c}"))
1560 .unwrap_or_default();
1561 let error = d.error.map(|e| format!(": {e}")).unwrap_or_default();
1562 println!(
1563 " #{} endpoint #{} {} {} attempt {}{code}{error}",
1564 d.id, d.endpoint_id, d.event_type, d.status, d.attempt
1565 );
1566 }
1567 }
1568 "webhook:redeliver" => {
1569 let id: i64 = args
1570 .get(1)
1571 .and_then(|id| id.parse().ok())
1572 .ok_or_else(|| anyhow!("usage: webhook:redeliver <id>"))?;
1573 if crate::webhook::outbound::Delivery::redeliver(&kernel.state, id).await? {
1574 println!("Webhook delivery #{id} queued again.");
1575 } else {
1576 return Err(anyhow!("there is no webhook delivery #{id}").into());
1577 }
1578 }
1579 "webhook:prune-deliveries" => {
1580 let days = flag_value(args, "--days")?.unwrap_or(30);
1581 let age = Duration::from_secs(u64::from(days) * 86_400);
1582 println!(
1583 "Deleted {} webhook delivery record(s) older than {days} day(s).",
1584 crate::webhook::outbound::Delivery::prune(&kernel.state.db, age).await?
1585 );
1586 }
1587 "queue:failed" => {
1588 let failed = kernel.state.queue.failed().await?;
1589 if failed.is_empty() {
1590 println!("No failed jobs.");
1591 }
1592 for job in failed {
1593 println!(" #{} {} ({}): {}", job.id, job.job, job.queue, job.error);
1594 }
1595 }
1596 "queue:retry" => {
1597 let id = match args.get(1).map(String::as_str) {
1598 Some("all") => None,
1599 Some(id) => Some(
1600 id.parse()
1601 .map_err(|_| anyhow!("expected a job id or `all`"))?,
1602 ),
1603 None => return Err(anyhow!("usage: queue:retry <id|all>").into()),
1604 };
1605 let queued = match id {
1606 Some(id) => u64::from(kernel.state.queue.retry(id).await?),
1607 None => kernel.state.queue.retry_all().await?,
1608 };
1609 println!("Queued {queued} job(s) again.");
1610 }
1611 "queue:forget" => {
1612 let id: i64 = args
1613 .get(1)
1614 .and_then(|id| id.parse().ok())
1615 .ok_or_else(|| anyhow!("usage: queue:forget <id>"))?;
1616 if kernel.state.queue.forget_failed(id).await? {
1617 println!("Deleted failed job {id}.");
1618 } else {
1619 return Err(anyhow!("no failed job {id}").into());
1620 }
1621 }
1622 "queue:prune-failed" => {
1623 let hours = flag_value(args, "--hours")?.unwrap_or(168);
1624 let age = Duration::from_secs(u64::from(hours) * 3600);
1625 println!(
1626 "Deleted {} failed job(s) older than {hours} hour(s).",
1627 kernel.state.queue.prune_failed(age).await?
1628 );
1629 }
1630 "queue:prune-batches" => {
1631 let hours = flag_value(args, "--hours")?.unwrap_or(24);
1632 let age = Duration::from_secs(u64::from(hours) * 3600);
1633 println!(
1634 "Deleted {} batch(es) finished more than {hours} hour(s) ago.",
1635 kernel.state.queue.prune_batches(age).await?
1636 );
1637 }
1638 "queue:flush" => println!(
1639 "Deleted {} failed job(s).",
1640 kernel.state.queue.flush_failed().await?
1641 ),
1642 "ui:publish" => {
1643 let force = args.iter().any(|a| a == "--force");
1644 crate::assets::publish_ui(&kernel.state.config, force)?;
1645 }
1646 "session:prune" => println!(
1647 "Deleted {} expired session(s).",
1648 crate::Session::prune_expired(&kernel.state.db).await?
1649 ),
1650 "sequence:list" => {
1651 let rows = crate::db::Sequence::list(&kernel.state.db).await?;
1652 if rows.is_empty() {
1653 println!("No numbering series.");
1654 }
1655 for row in rows {
1656 println!(
1657 " {} scope={:?} period={:?} last={}",
1658 row.series, row.scope, row.period, row.last
1659 );
1660 }
1661 }
1662 "cache:prune" => println!(
1663 "Deleted {} expired cache row(s).",
1664 kernel.state.cache.prune().await?
1665 ),
1666 "idempotency:prune" => {
1667 let days = flag_value(args, "--days")?;
1668 println!(
1669 "Deleted {} idempotency key(s) past retention.",
1670 crate::idempotency::prune_retained(&kernel.state, days).await?
1671 );
1672 }
1673 "import:prune" => {
1674 let days = flag_value(args, "--days")?.unwrap_or(0);
1675 let age = Duration::from_secs(u64::from(days) * 86_400);
1676 println!(
1677 "Deleted {} import record(s) whose undo window ended more than {days} day(s) ago.",
1678 crate::import::prune(&kernel.state, age).await?
1679 );
1680 }
1681 "schedule:list" => {
1682 if kernel.schedule.is_empty() {
1683 println!("No scheduled tasks.");
1684 }
1685 for run in kernel.schedule.upcoming(kernel.zone) {
1686 let when = match run.at {
1687 Some(at) => run
1688 .zone
1689 .local(at.timestamp())
1690 .format("%Y-%m-%d %H:%M")
1691 .to_string(),
1692 None => "never".to_owned(),
1693 };
1694 println!(" {when:<16} {:<18} {}", run.zone, run.name);
1695 }
1696 }
1697 "schedule:run" => {
1698 let Some(name) = args.get(1).filter(|a| !a.starts_with('-')) else {
1699 return Err(anyhow!("usage: schedule:run <task>").into());
1700 };
1701 kernel.run_scheduled(name).await?;
1702 println!("Ran `{name}`.");
1703 }
1704 "schedule:work" => {
1705 let (stop, stopped) = watch::channel(false);
1706 let running = tokio::spawn(kernel.schedule.clone().run(
1707 kernel.state.clone(),
1708 kernel.zone,
1709 stopped,
1710 ));
1711 shutdown_signal().await;
1712 let _ = stop.send(true);
1713 let _ = running.await;
1714 }
1715 "route:list" => print_routes(kernel.routes()),
1716 "db:shell" => crate::shell::run(kernel.db()).await?,
1717 "down" => {
1718 let secret = flag_text(args, "--secret").map(str::to_owned);
1719 let retry = flag_value(args, "--retry")?.map(u64::from);
1720 let mut options = crate::maintenance::DownOptions::new();
1721 if let Some(secret) = &secret {
1722 options = options.secret(secret.clone());
1723 }
1724 if let Some(retry) = retry {
1725 options = options.retry(retry);
1726 }
1727 crate::maintenance::down(&kernel.state.config.storage_path, options)?;
1728 match secret {
1729 Some(secret) => println!("The app is down. Visit /{secret} to bypass it."),
1730 None => println!("The app is down."),
1731 }
1732 }
1733 "up" => match crate::maintenance::up(&kernel.state.config.storage_path)? {
1734 true => println!("The app is up."),
1735 false => println!("The app was not down."),
1736 },
1737 other if kernel.commands.iter().any(|c| c.name == other) => {
1738 kernel.call(other, args[1..].iter().cloned()).await?;
1739 }
1740 other => {
1741 return Err(anyhow!(
1742 "unknown command `{other}`\n\n{USAGE}{}",
1743 app_commands_help(&kernel.commands)
1744 )
1745 .into());
1746 }
1747 }
1748 Ok(())
1749 }
1750}
1751
1752fn inherited_listener() -> Result<Option<TcpListener>> {
1756 let mut fds = listenfd::ListenFd::from_env();
1757 let Some(listener) = fds
1758 .take_tcp_listener(0)
1759 .map_err(|err| anyhow!("the socket systemd passed isn't a TCP listener: {err}"))?
1760 else {
1761 return Ok(None);
1762 };
1763 listener
1764 .set_nonblocking(true)
1765 .map_err(anyhow::Error::from)?;
1766 Ok(Some(
1767 TcpListener::from_std(listener).map_err(anyhow::Error::from)?,
1768 ))
1769}
1770
1771const BUILT_IN_COMMANDS: &[&str] = &[
1778 "serve",
1779 "migrate",
1780 "migrate:rollback",
1781 "migrate:fresh",
1782 "migrate:status",
1783 "db:seed",
1784 "queue:work",
1785 "queue:failed",
1786 "queue:retry",
1787 "queue:flush",
1788 "queue:forget",
1789 "queue:prune-failed",
1790 "queue:prune-batches",
1791 "webhook:failed",
1792 "webhook:retry",
1793 "webhook:endpoints",
1794 "webhook:deliveries",
1795 "webhook:redeliver",
1796 "webhook:prune-deliveries",
1797 "sequence:list",
1798 "cache:prune",
1799 "session:prune",
1800 "idempotency:prune",
1801 "import:prune",
1802 "ui:publish",
1803 "schedule:list",
1804 "schedule:run",
1805 "schedule:work",
1806 "route:list",
1807 "db:shell",
1808 "down",
1809 "up",
1810 "help",
1811];
1812
1813fn check_commands(commands: &[crate::command::Command]) -> Result {
1814 let mut seen = std::collections::HashSet::new();
1815 for command in commands {
1816 let name = command.name.as_str();
1817 if name.is_empty() || name.starts_with('-') || name.contains(char::is_whitespace) {
1818 return Err(anyhow!("`{name}` is not a valid command name").into());
1819 }
1820 if BUILT_IN_COMMANDS.contains(&name) {
1821 return Err(anyhow!("the command `{name}` is built in; choose another name").into());
1822 }
1823 if !seen.insert(name) {
1824 return Err(anyhow!("the command `{name}` is registered twice").into());
1825 }
1826 }
1827 Ok(())
1828}
1829
1830fn app_commands_help(commands: &[crate::command::Command]) -> String {
1831 if commands.is_empty() {
1832 return String::new();
1833 }
1834 let mut out = String::from("\n\nApp commands:\n");
1835 for command in commands {
1836 out.push_str(&format!(" {:<26}{}\n", command.name, command.about));
1837 }
1838 out.trim_end().to_owned()
1839}
1840
1841impl Default for App {
1842 fn default() -> Self {
1843 Self::new()
1844 }
1845}
1846
1847pub struct Kernel {
1849 router: Router,
1850 listing: Vec<RouteInfo>,
1851 state: AppState,
1852 migrator: Migrator,
1853 seeders: Vec<crate::registry::Seeder>,
1854 models: Vec<crate::db::schema::ModelInfo>,
1855 handlers: Handlers,
1856 schedule: Schedule,
1857 zone: Zone,
1858 commands: Vec<crate::command::Command>,
1859}
1860
1861impl Kernel {
1862 pub(crate) async fn scratch_db(&self) -> Result<Db> {
1864 let db = crate::db::connect_scratch(&self.state.config).await?;
1865 self.migrator.run(&db).await?;
1866 Ok(db)
1867 }
1868
1869 async fn db_check(&self) -> Result {
1871 let db = self.scratch_db().await?;
1872 let reports = crate::db::schema_check::check(&db, &self.models).await;
1873 crate::db::drop_scratch(&db).await;
1874 let (text, problems) = crate::db::schema_check::render(&reports?);
1875 print!("{text}");
1876 if problems > 0 {
1877 return Err(anyhow::anyhow!("{problems} problem(s) in the models").into());
1878 }
1879 Ok(())
1880 }
1881
1882 pub(crate) fn models(&self) -> &[crate::db::schema::ModelInfo] {
1884 &self.models
1885 }
1886
1887 pub async fn call(
1889 &self,
1890 name: &str,
1891 args: impl IntoIterator<Item = impl Into<String>>,
1892 ) -> Result {
1893 let command = self
1894 .commands
1895 .iter()
1896 .find(|c| c.name == name)
1897 .ok_or_else(|| anyhow!("unknown command `{name}`"))?;
1898 let run = (command.run)(self.state.clone(), crate::command::Args::new(args));
1899 crate::context::scope_app(self.state.clone(), run).await
1900 }
1901
1902 pub async fn run_scheduled(&self, name: &str) -> Result {
1906 self.schedule.run_now(self.state.clone(), name).await
1907 }
1908
1909 pub fn router(&self) -> Router {
1911 self.router.clone()
1912 }
1913
1914 pub fn routes(&self) -> &[RouteInfo] {
1916 &self.listing
1917 }
1918
1919 pub fn state(&self) -> &AppState {
1921 &self.state
1922 }
1923
1924 pub fn db(&self) -> &Db {
1926 &self.state.db
1927 }
1928
1929 pub fn mailer(&self) -> &Mailer {
1931 &self.state.mailer
1932 }
1933
1934 pub fn worker(&self, queues: Vec<String>) -> Worker {
1936 Worker::new(self.state.clone(), self.handlers.clone(), queues)
1937 }
1938
1939 pub async fn run_jobs(&self) -> Result<usize> {
1941 self.worker(Vec::new()).drain().await
1942 }
1943
1944 pub async fn serve(self) -> Result {
1947 let config = self.state.config.clone();
1948 let listener = match inherited_listener()? {
1949 Some(listener) => {
1950 tracing::info!("using the socket systemd passed (socket activation)");
1951 listener
1952 }
1953 None => TcpListener::bind(config.addr()).await?,
1954 };
1955 tracing::info!(
1956 "{} listening on http://{}",
1957 config.name,
1958 listener.local_addr()?
1959 );
1960
1961 let (stop, stopped) = watch::channel(false);
1962 let mut background = Vec::new();
1963 if config.queue_workers > 0 {
1964 tracing::info!(workers = config.queue_workers, "queue workers started");
1965 let worker = self.worker(Vec::new());
1966 background.push(tokio::spawn(
1967 worker.run(config.queue_workers, stopped.clone()),
1968 ));
1969 }
1970 if config.scheduler && !self.schedule.is_empty() {
1971 tracing::info!("scheduler started");
1972 background.push(tokio::spawn(self.schedule.clone().run(
1973 self.state.clone(),
1974 self.zone,
1975 stopped,
1976 )));
1977 }
1978
1979 let service = self
1980 .router
1981 .into_make_service_with_connect_info::<SocketAddr>();
1982 let live = self.state.live.clone();
1983 let notification_hub = self.state.notification_hub.clone();
1984 axum::serve(listener, service)
1985 .with_graceful_shutdown(async move {
1986 shutdown_signal().await;
1987 if let Some(live) = live {
1990 live.stop();
1991 }
1992 notification_hub.stop();
1993 })
1994 .await?;
1995
1996 let _ = stop.send(true);
1997 let finished = async {
1998 for task in background {
1999 let _ = task.await;
2000 }
2001 };
2002 if tokio::time::timeout(SHUTDOWN_GRACE, finished)
2003 .await
2004 .is_err()
2005 {
2006 tracing::warn!("background work was still running after {SHUTDOWN_GRACE:?}");
2007 }
2008 tracing::info!("{} stopped", config.name);
2009 Ok(())
2010 }
2011
2012 pub async fn migrate(&self) -> Result<Vec<String>> {
2014 let done = self.migrator.run(self.db()).await?;
2015 Ok(done.into_iter().map(str::to_owned).collect())
2016 }
2017
2018 pub async fn rollback(&self, batches: u32) -> Result<Vec<String>> {
2020 Ok(self.migrator.rollback(self.db(), batches).await?)
2021 }
2022
2023 pub async fn fresh(&self) -> Result<Vec<String>> {
2025 let done = self.migrator.fresh(self.db()).await?;
2026 Ok(done.into_iter().map(str::to_owned).collect())
2027 }
2028
2029 pub async fn migration_status(&self) -> Result<Vec<MigrationStatus>> {
2031 Ok(self.migrator.status(self.db()).await?)
2032 }
2033
2034 pub async fn seed(&self) -> Result {
2036 for seeder in &self.seeders {
2037 crate::context::scope_app(self.state.clone(), seeder(self.state.clone())).await?;
2040 }
2041 Ok(())
2042 }
2043}
2044
2045fn framework_routes(config: &Config, pwa: bool, pwa_for: bool) -> Vec<RouteInfo> {
2047 let route = |method: &str, path: &str| RouteInfo {
2048 method: method.to_owned(),
2049 path: path.to_owned(),
2050 name: None,
2051 module: "renox".to_owned(),
2052 middleware: Vec::new(),
2053 domain: None,
2054 };
2055 let mut routes = vec![
2056 route("GET", "/health"),
2057 route("GET", "/robots.txt"),
2058 route("GET", "/favicon.ico"),
2059 route("GET", "/_renox/{asset}"),
2060 route("GET", "/_renox/theme/{hash}.css"),
2061 route("GET", "/_renox/files/{*key}"),
2062 route("POST", "/_renox/grid/{grid}/prefs"),
2063 route("DELETE", "/_renox/grid/{grid}/prefs"),
2064 route("POST", "/_renox/live/{component}/{action}"),
2065 route("GET", "/_renox/csrf"),
2066 route("GET", "/storage/{*path}"),
2067 ];
2068 if pwa {
2069 routes.push(route("GET", "/manifest.webmanifest"));
2070 routes.push(route("GET", "/sw.js"));
2071 routes.push(route("GET", crate::pwa::OFFLINE_ROUTE));
2072 routes.push(route("GET", "/_renox/pwa/icons/{file}"));
2073 if pwa_for {
2074 routes.push(route("GET", "/_renox/pwa/icons/{hash}/{file}"));
2075 }
2076 }
2077 if config.debug {
2078 routes.push(route("GET", "/_renox/mail"));
2079 routes.push(route("GET", "/_renox/mail/{id}"));
2080 }
2081 if config.debug && config.env == Environment::Local {
2082 routes.push(route("GET", "/_renox/live"));
2083 }
2084 routes
2085}
2086
2087fn print_routes(routes: &[RouteInfo]) {
2088 print!("{}", route_table(routes));
2089}
2090
2091fn route_table(routes: &[RouteInfo]) -> String {
2093 use std::fmt::Write as _;
2094 let mut out = String::new();
2095 let with_domains = routes.iter().any(|r| r.domain.is_some());
2096 let rows: Vec<Vec<String>> = routes
2097 .iter()
2098 .map(|r| {
2099 let mut row = vec![
2100 r.method.clone(),
2101 r.path.clone(),
2102 r.name.clone().unwrap_or_default(),
2103 r.module.clone(),
2104 r.middleware
2105 .iter()
2106 .map(|guard| {
2107 if is_role_guard(guard) {
2108 format!("{guard}*")
2109 } else {
2110 guard.clone()
2111 }
2112 })
2113 .collect::<Vec<_>>()
2114 .join(", "),
2115 ];
2116 if with_domains {
2117 row.insert(0, r.domain.clone().unwrap_or_default());
2118 }
2119 row
2120 })
2121 .collect();
2122 let mut header: Vec<String> = ["METHOD", "PATH", "NAME", "MODULE", "MIDDLEWARE"]
2123 .map(str::to_owned)
2124 .to_vec();
2125 if with_domains {
2126 header.insert(0, "DOMAIN".into());
2127 }
2128 let mut widths: Vec<usize> = header.iter().map(String::len).collect();
2129 for row in &rows {
2130 for (width, cell) in widths.iter_mut().zip(row) {
2131 *width = (*width).max(cell.chars().count());
2132 }
2133 }
2134 for row in std::iter::once(&header).chain(&rows) {
2135 let line: Vec<String> = row
2136 .iter()
2137 .zip(&widths)
2138 .map(|(cell, width)| format!("{cell:<width$}", width = *width))
2139 .collect();
2140 let _ = writeln!(out, "{}", line.join(" ").trim_end());
2141 }
2142 if routes
2143 .iter()
2144 .flat_map(|r| &r.middleware)
2145 .any(|g| is_role_guard(g))
2146 {
2147 out.push_str(
2148 "\n* role and permission guards count the user's global roles plus the roles \
2149 given in the request's active scope (permissions::set_scope).\n",
2150 );
2151 }
2152 out
2153}
2154
2155fn is_role_guard(guard: &str) -> bool {
2157 guard.starts_with("role:") || guard.starts_with("permission:")
2158}
2159
2160fn print_done(verb: &str, names: &[String]) {
2161 if names.is_empty() {
2162 println!("Nothing to do.");
2163 }
2164 for name in names {
2165 println!("{verb}: {name}");
2166 }
2167}
2168
2169fn flag_text<'a>(args: &'a [String], flag: &str) -> Option<&'a str> {
2170 let i = args.iter().position(|a| a == flag)?;
2171 args.get(i + 1).map(String::as_str)
2172}
2173
2174fn flag_value(args: &[String], flag: &str) -> Result<Option<u32>> {
2175 if !args.iter().any(|a| a == flag) {
2176 return Ok(None);
2177 }
2178 match flag_text(args, flag).and_then(|v| v.parse().ok()) {
2179 Some(value) => Ok(Some(value)),
2180 None => Err(anyhow!("{flag} needs a number").into()),
2181 }
2182}
2183
2184async fn guard(
2187 limit: Option<Duration>,
2188 req: axum::extract::Request,
2189 next: axum::middleware::Next,
2190) -> axum::response::Response {
2191 use axum::response::IntoResponse;
2192 let run = futures_util::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(next.run(req)));
2193 let outcome = match limit {
2194 Some(limit) => match tokio::time::timeout(limit, run).await {
2195 Ok(outcome) => outcome,
2196 Err(_) => {
2197 return Error::Internal(anyhow!(
2198 "the request took longer than REQUEST_TIMEOUT ({}s)",
2199 limit.as_secs()
2200 ))
2201 .into_response();
2202 }
2203 },
2204 None => run.await,
2205 };
2206 outcome.unwrap_or_else(|panic| {
2207 let message = crate::error::panic_message(&*panic);
2208 Error::Internal(anyhow!("the handler panicked: {message}")).into_response()
2209 })
2210}
2211
2212const BACKSTOP_GRACE: Duration = Duration::from_secs(1);
2215
2216async fn backstop(
2221 limit: Option<Duration>,
2222 req: axum::extract::Request,
2223 next: axum::middleware::Next,
2224) -> axum::response::Response {
2225 use axum::response::IntoResponse;
2226 let Some(limit) = limit else {
2227 return next.run(req).await;
2228 };
2229 match tokio::time::timeout(limit + BACKSTOP_GRACE, next.run(req)).await {
2230 Ok(res) => res,
2231 Err(_) => Error::Internal(anyhow!(
2232 "the request took longer than REQUEST_TIMEOUT ({}s) before reaching its handler",
2233 limit.as_secs()
2234 ))
2235 .into_response(),
2236 }
2237}
2238
2239fn merge_routes(
2241 router: Router<AppState>,
2242 other: Router<AppState>,
2243 module: &str,
2244) -> Result<Router<AppState>> {
2245 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| router.merge(other))).map_err(
2246 |panic| {
2247 let message = crate::error::panic_message(&*panic);
2248 anyhow!("the routes of the `{module}` module clash: {message}").into()
2249 },
2250 )
2251}
2252
2253fn check_clashes(
2256 listing: &[RouteInfo],
2257 new: &[RouteInfo],
2258 domain: Option<&str>,
2259 module: &str,
2260) -> Result {
2261 for info in new {
2262 let clash = listing.iter().find(|other| {
2263 other.domain.as_deref() == domain
2264 && other.path == info.path
2265 && (other.method == info.method || other.method == "*" || info.method == "*")
2266 });
2267 if let Some(other) = clash {
2268 let on = domain.map(|d| format!(" on {d}")).unwrap_or_default();
2269 return Err(anyhow!(
2270 "{} {}{on} is defined by both the `{}` and the `{module}` module",
2271 info.method,
2272 info.path,
2273 other.module,
2274 )
2275 .into());
2276 }
2277 }
2278 Ok(())
2279}
2280
2281fn check_assets(assets: &[crate::registry::StaticAsset]) -> Result<()> {
2283 let mut seen = std::collections::HashSet::new();
2284 for asset in assets {
2285 if !asset.path.starts_with('/') || asset.path.contains(['{', '}']) {
2286 return Err(anyhow!(
2287 "Registry::asset(\"{}\", …): the path must start with `/` and have no `{{…}}` parameters",
2288 asset.path
2289 )
2290 .into());
2291 }
2292 if !seen.insert(asset.path) {
2293 return Err(anyhow!(
2294 "two modules serve a file at `{}` (Registry::asset)",
2295 asset.path
2296 )
2297 .into());
2298 }
2299 }
2300 Ok(())
2301}
2302
2303fn build_router(
2304 router: Router<AppState>,
2305 state: AppState,
2306 embedded_public: Option<&'static [(&'static str, &'static [u8])]>,
2307 fallback: Option<axum::routing::MethodRouter<AppState>>,
2308 static_assets: &[crate::registry::StaticAsset],
2309 pwa: Option<&crate::pwa::PwaParts>,
2310) -> Router {
2311 let fallback = fallback.map(|handler| handler.with_state(state.clone()));
2313 let not_found = move |req: axum::extract::Request| {
2314 let fallback = fallback.clone();
2315 async move {
2316 match fallback {
2317 Some(handler) => match tower::ServiceExt::oneshot(handler, req).await {
2318 Ok(res) => res,
2319 Err(never) => match never {},
2320 },
2321 None => axum::response::IntoResponse::into_response(Error::NotFound),
2322 }
2323 }
2324 };
2325 let router = router
2326 .merge(crate::storage::router())
2327 .merge(crate::grid::router())
2328 .merge(csrf::router())
2329 .merge(crate::live_component::route::router());
2330 let router = if state.config.debug {
2331 router
2332 .merge(crate::mail::preview_router())
2333 .merge(crate::inspector::router())
2334 } else {
2335 router
2336 };
2337 let public = state.config.public_path.clone();
2338 let router = if let Some(files) = embedded_public {
2339 let files = crate::embedded::public_map(files);
2340 let not_found = not_found.clone();
2341 router.fallback(move |req: axum::extract::Request| {
2342 let (files, not_found) = (files.clone(), not_found.clone());
2343 async move {
2344 let res = crate::embedded::serve(&files, req.uri());
2345 if res.status() == axum::http::StatusCode::NOT_FOUND {
2346 not_found(req).await
2347 } else {
2348 res
2349 }
2350 }
2351 })
2352 } else if public.is_dir() {
2353 let files = ServeDir::new(public).fallback(not_found.clone().into_service());
2356 router.fallback(move |req: axum::extract::Request| {
2357 let files = files.clone();
2358 async move {
2359 if req
2362 .uri()
2363 .path()
2364 .split('/')
2365 .any(|segment| segment.len() > 255)
2366 {
2367 return axum::response::IntoResponse::into_response(Error::NotFound);
2368 }
2369 let versioned = crate::embedded::is_versioned(req.uri());
2370 match tower::ServiceExt::oneshot(files, req).await {
2371 Ok(res) => {
2372 let mut res = axum::response::IntoResponse::into_response(res);
2373 if versioned && res.status().is_success() {
2374 res.headers_mut().insert(
2375 axum::http::header::CACHE_CONTROL,
2376 axum::http::HeaderValue::from_static(
2377 "public, max-age=31536000, immutable",
2378 ),
2379 );
2380 }
2381 res
2382 }
2383 Err(never) => match never {},
2384 }
2385 }
2386 })
2387 } else {
2388 router.fallback(not_found)
2389 };
2390
2391 let request_timeout = state.config.request_timeout;
2392 let router: Router = router
2393 .layer(from_fn(
2394 move |req: axum::extract::Request, next: axum::middleware::Next| {
2395 guard(request_timeout, req, next)
2396 },
2397 ))
2398 .layer(from_fn_with_state(
2399 state.clone(),
2400 crate::maintenance::middleware,
2401 ))
2402 .layer(from_fn_with_state(state.clone(), view::middleware))
2403 .layer(from_fn(csrf::middleware))
2404 .layer(from_fn_with_state(state.clone(), auth::middleware))
2405 .layer(from_fn_with_state(state.clone(), crate::i18n::middleware))
2406 .layer(from_fn_with_state(state.clone(), session::middleware))
2407 .layer(from_fn_with_state(
2409 state.clone(),
2410 crate::context::middleware,
2411 ))
2412 .layer(from_fn(
2413 move |req: axum::extract::Request, next: axum::middleware::Next| {
2414 backstop(request_timeout, req, next)
2415 },
2416 ))
2417 .layer(from_fn_with_state(
2419 state.clone(),
2420 crate::inspector::middleware,
2421 ))
2422 .merge(assets::router())
2423 .merge(assets::module_router(static_assets))
2424 .merge(crate::health::router())
2425 .merge(robots(&state, embedded_public))
2426 .merge(pwa_routes(&state, embedded_public, pwa))
2427 .merge(favicon(&state, embedded_public))
2428 .merge(crate::live::router())
2429 .merge(public_files(&state))
2430 .layer(axum::extract::DefaultBodyLimit::max(
2431 state.config.upload_max_size,
2432 ))
2433 .layer(
2434 TraceLayer::new_for_http().make_span_with(|req: &axum::extract::Request| {
2435 let ip = crate::ClientIp::of(req).map(|ip| ip.to_string());
2436 let id = req
2437 .headers()
2438 .get(crate::request_id::HEADER)
2439 .and_then(|v| v.to_str().ok())
2440 .unwrap_or_default();
2441 tracing::info_span!(
2442 "request",
2443 id = %id,
2444 method = %req.method(),
2445 uri = %req.uri(),
2446 ip = ip.as_deref().unwrap_or("unknown"),
2447 )
2448 }),
2449 )
2450 .layer(from_fn(crate::request_id::middleware))
2451 .with_state(state.clone());
2452 let limit = state.config.upload_max_size;
2454 let spoofing = from_fn(
2455 move |req: axum::extract::Request, next: axum::middleware::Next| {
2456 crate::method::middleware(req, next, limit)
2457 },
2458 );
2459 Router::new()
2462 .fallback_service(tower::Layer::layer(&spoofing, router))
2463 .layer(from_fn_with_state(state, crate::security::middleware))
2464}
2465
2466fn has_public_file(
2468 state: &AppState,
2469 embedded_public: Option<&'static [(&'static str, &'static [u8])]>,
2470 name: &str,
2471) -> bool {
2472 match embedded_public {
2473 Some(files) => files.iter().any(|(path, _)| *path == name),
2474 None => state.config.public_path.join(name).is_file(),
2475 }
2476}
2477
2478fn robots(
2480 state: &AppState,
2481 embedded_public: Option<&'static [(&'static str, &'static [u8])]>,
2482) -> Router<AppState> {
2483 if has_public_file(state, embedded_public, "robots.txt") {
2484 Router::new()
2485 } else {
2486 crate::seo::robots_router(state)
2487 }
2488}
2489
2490fn pwa_routes(
2493 state: &AppState,
2494 embedded_public: Option<&'static [(&'static str, &'static [u8])]>,
2495 pwa: Option<&crate::pwa::PwaParts>,
2496) -> Router<AppState> {
2497 let Some((pwa, assets, resolver)) = pwa else {
2498 return Router::new();
2499 };
2500 if let Some(resolver) = resolver {
2501 return resolver.clone().router(
2502 pwa.clone(),
2503 assets.clone(),
2504 !has_public_file(state, embedded_public, "manifest.webmanifest"),
2505 !has_public_file(state, embedded_public, "sw.js"),
2506 );
2507 }
2508 let mut router = assets
2509 .clone()
2510 .router(!has_public_file(state, embedded_public, "sw.js"));
2511 if !has_public_file(state, embedded_public, "manifest.webmanifest") {
2512 router = router.merge(pwa.clone().manifest_router());
2513 }
2514 router
2515}
2516
2517fn favicon(
2521 state: &AppState,
2522 embedded_public: Option<&'static [(&'static str, &'static [u8])]>,
2523) -> Router<AppState> {
2524 if has_public_file(state, embedded_public, "favicon.ico") {
2525 return Router::new();
2526 }
2527 Router::new().route(
2528 "/favicon.ico",
2529 axum::routing::get(|| async {
2530 (
2531 axum::http::StatusCode::NO_CONTENT,
2532 [(axum::http::header::CACHE_CONTROL, "public, max-age=86400")],
2533 )
2534 }),
2535 )
2536}
2537
2538fn public_files(state: &AppState) -> Router<AppState> {
2540 match state.storage.public_root() {
2541 Some(root) => Router::new()
2542 .nest_service("/storage", ServeDir::new(root))
2543 .layer(axum::middleware::map_response(user_file_headers)),
2544 None => Router::new(),
2545 }
2546}
2547
2548pub(crate) async fn user_file_headers(
2553 mut res: axum::response::Response,
2554) -> axum::response::Response {
2555 use axum::http::HeaderValue;
2556 use axum::http::header::{
2557 CONTENT_DISPOSITION, CONTENT_SECURITY_POLICY, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS,
2558 };
2559
2560 let content_type = res
2561 .headers()
2562 .get(CONTENT_TYPE)
2563 .and_then(|v| v.to_str().ok())
2564 .unwrap_or_default()
2565 .to_ascii_lowercase();
2566 let headers = res.headers_mut();
2567 headers.insert(
2568 CONTENT_SECURITY_POLICY,
2569 HeaderValue::from_static(
2570 "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox",
2571 ),
2572 );
2573 headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
2574 let document = ["html", "xml", "javascript", "ecmascript"]
2575 .iter()
2576 .any(|kind| content_type.contains(kind))
2577 && !content_type.contains("svg");
2578 if document {
2579 headers.insert(CONTENT_DISPOSITION, HeaderValue::from_static("attachment"));
2580 }
2581 res
2582}
2583
2584fn init_tracing(config: &Config, long_running: bool) {
2586 let default = match (long_running, config.debug) {
2587 (true, true) => "info,renox=debug",
2588 (true, false) => "info",
2589 (false, _) => "warn",
2590 };
2591 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default));
2592 let file = config.log_file.as_ref().and_then(|path| {
2596 match std::fs::OpenOptions::new()
2597 .create(true)
2598 .append(true)
2599 .open(path)
2600 {
2601 Ok(file) => Some(std::sync::Mutex::new(file)),
2602 Err(err) => {
2603 eprintln!("LOG_FILE {}: {err}; logging to stdout", path.display());
2604 None
2605 }
2606 }
2607 });
2608 let json = config.log_format == crate::LogFormat::Json;
2609 let builder = tracing_subscriber::fmt().with_env_filter(filter);
2610 let _ = match (json, file) {
2611 (true, Some(file)) => builder
2612 .json()
2613 .with_current_span(true)
2614 .with_span_list(false)
2615 .with_writer(file)
2616 .try_init(),
2617 (true, None) => builder
2618 .json()
2619 .with_current_span(true)
2620 .with_span_list(false)
2621 .try_init(),
2622 (false, Some(file)) => builder.with_ansi(false).with_writer(file).try_init(),
2623 (false, None) => builder.try_init(),
2624 };
2625}
2626
2627async fn shutdown_signal() {
2628 let ctrl_c = async {
2629 let _ = tokio::signal::ctrl_c().await;
2630 };
2631
2632 #[cfg(unix)]
2633 let terminate = async {
2634 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
2635 Ok(mut signal) => {
2636 signal.recv().await;
2637 }
2638 Err(_) => std::future::pending().await,
2639 }
2640 };
2641 #[cfg(not(unix))]
2642 let terminate = std::future::pending::<()>();
2643
2644 tokio::select! {
2645 _ = ctrl_c => {},
2646 _ = terminate => {},
2647 }
2648 tracing::info!("shutdown signal received");
2649}
2650
2651#[cfg(test)]
2652mod tests {
2653 use super::*;
2654
2655 fn route(path: &str, middleware: &[&str]) -> RouteInfo {
2656 RouteInfo {
2657 method: "GET".into(),
2658 path: path.into(),
2659 name: None,
2660 module: "app".into(),
2661 middleware: middleware.iter().map(|m| (*m).to_owned()).collect(),
2662 domain: None,
2663 }
2664 }
2665
2666 #[test]
2667 fn route_list_says_role_guards_count_the_active_scope() {
2668 let plain = route_table(&[route("/", &["auth"])]);
2669 assert!(!plain.contains('*'), "{plain}");
2670 let table = route_table(&[
2671 route("/orders", &["auth", "permission:orders.view"]),
2672 route("/drafts", &["role:editor"]),
2673 route("/admin", &["gate:admin"]),
2674 ]);
2675 assert!(table.contains("auth, permission:orders.view*"), "{table}");
2676 assert!(table.contains("role:editor*"), "{table}");
2677 assert!(table.contains("gate:admin\n"), "{table}");
2678 assert!(
2679 table.contains("active scope (permissions::set_scope)"),
2680 "{table}"
2681 );
2682 }
2683
2684 struct Note;
2685 impl crate::db::FromRow for Note {
2686 fn from_row(_: &crate::db::Row) -> Result<Self, crate::db::DbError> {
2687 Ok(Note)
2688 }
2689 }
2690 impl crate::db::Model for Note {
2691 const TABLE: &'static str = "notes";
2692 const COLUMNS: &'static [&'static str] = &["id"];
2693 type Key = i64;
2694 fn id(&self) -> i64 {
2695 0
2696 }
2697 fn set_id(&mut self, _: i64) {}
2698 fn values(&self) -> Vec<crate::db::DbValue> {
2699 Vec::new()
2700 }
2701 }
2702
2703 struct Registers;
2704 impl Module for Registers {
2705 fn name(&self) -> &'static str {
2706 "registers"
2707 }
2708 fn register(&self, app: &mut Registry) {
2709 app.model::<crate::auth::User>();
2710 }
2711 }
2712
2713 #[tokio::test]
2714 async fn models_are_kept_once_from_the_app_and_modules() {
2715 let boot = |app: App| async move { app.config(Config::default()).boot().await.unwrap() };
2716 let one = boot(
2717 App::new()
2718 .model::<crate::auth::User>()
2719 .model::<crate::auth::User>()
2720 .module(Registers),
2721 )
2722 .await;
2723 assert_eq!(one.models().len(), 1);
2724 assert_eq!(one.models()[0].table, "users");
2725 let two = boot(
2726 App::new()
2727 .model::<crate::auth::User>()
2728 .model::<Note>()
2729 .module(Registers),
2730 )
2731 .await;
2732 assert_eq!(two.models().len(), 2);
2733 }
2734}