runique 2.2.0

A Django-inspired web framework for Rust with ORM, templates, and comprehensive security middleware
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Build pipeline: validation → core construction → middleware → statics.
//!
//! Construction order:
//!   1. Validation (each staging + cross-dependencies)
//!   2. DB connection (if DatabaseConfig provided)
//!   3. Core (Templates → Engine → URLs)
//!   4. Admin panel (merged before middleware stack)
//!   5. Password reset routes
//!   6. Middleware staging (slots sort + apply)
//!   7. Static files

use std::sync::Arc;

use axum::{
    Router,
    http::{HeaderName, HeaderValue},
};
use tower_http::{services::ServeDir, set_header::SetResponseHeaderLayer};

use super::super::error_build::BuildError;
use super::super::runique_app::RuniqueApp;
use super::super::templates::TemplateLoader;
use super::RuniqueAppBuilder;
use crate::admin::build_admin_router;
use crate::config::RuniqueConfig;
use crate::engine::RuniqueEngine;
use crate::macros::{add_urls, register_name_url};
use crate::middleware::HostPolicy;
use crate::utils::aliases::new;
use crate::utils::runique_log::log_init;

#[cfg(feature = "orm")]
use crate::middleware::session::session_db::RuniqueSessionStore;

impl RuniqueAppBuilder {
    /// Validates and builds the application.
    ///
    /// # Construction Pipeline
    /// 1. **Validation** of all components (Core, Middleware, Statics)
    /// 2. **Construction** of the Core (Templates → Engine → URLs)
    /// 3. **Automatic reorganization** of middlewares by slots
    /// 4. **Application** of static files (if enabled)
    pub async fn build(mut self) -> Result<RuniqueApp, BuildError> {
        // Step 0: tracing (before everything else)
        // log_init early so get_log() works in TemplateLoader::init() and middleware staging.
        log_init(self.config.log.clone());
        let log_guards = self.config.log.init_subscriber();

        // Step 1: validation
        self.validate()?;
        if !self.all_ready() {
            return Err(BuildError::validation(
                "One or more components are not ready for construction",
            ));
        }

        // Step 2: DB connection (if DatabaseConfig provided)
        //   - `with_database(db)`        → already connected, taken as is
        //   - `with_database_config(cfg)` → `connect()` during build
        #[cfg(feature = "orm")]
        let db = self.core.connect().await?;

        // Step 3: destructuring
        let extensions = self.core.extensions;
        let config = self.config;
        let url_registry = self.core.url_registry;
        let mut middleware = self.middleware;
        let statics_enabled = self.statics.enabled;
        let static_cache = self.statics.static_cache;
        let media_cache = self.statics.media_cache;
        let router = self.router;

        // Step 4: core construction — strict order: Templates → Config → Engine → URLs

        let tera = new(TemplateLoader::init(&config, url_registry.clone())
            .map_err(|e| BuildError::template(e.to_string()))?);

        let config = new(config);
        crate::utils::password::password_init(config.password.clone());

        // HSTS `preload` requires `includeSubDomains` + `max-age ≥ 1 an` to be
        // accepted on the browser preload list — warn once at boot if the combo
        // is invalid (the header would otherwise be silently ignored for preload).
        if config.security.hsts_preload_misconfigured() {
            tracing::warn!(
                max_age = config.security.hsts_max_age,
                include_subdomains = config.security.hsts_include_subdomains,
                "HSTS_PRELOAD set but combo invalid (needs includeSubDomains + max-age ≥ 31536000) — ignored by browsers for preload"
            );
        }

        let engine = new(RuniqueEngine {
            config: (*config).clone(),
            tera: tera.clone(),
            #[cfg(feature = "orm")]
            db: new(db),
            features: {
                let mut f = middleware.features.clone();
                f.exclusive_login = middleware.exclusive_login;
                f
            },
            url_registry,
            security_csp: {
                let mut policy = middleware.security_policy.take().unwrap_or_default();
                if self.admin.enabled {
                    policy.merge_htmx_hashes();
                }
                new(policy)
            },
            security_hosts: new(HostPolicy::new(
                middleware.allowed_hosts.clone(),
                middleware.features.enable_host_validation,
            )),
            csrf_exempt_paths: Arc::new(middleware.csrf_exempt_paths.clone()),
            permissions_policy: Arc::new(middleware.permissions_policy.take().unwrap_or_default()),
            trusted_proxies: Arc::new(match middleware.trusted_proxies_config.take() {
                // Explicit config always wins; otherwise the default is edge-aware
                // (private ranges behind a proxy, but `none()` when Runique is the
                // ACME TLS edge — closes SEC2). See `TrustedProxies::default_for_edge`.
                Some(c) => c.build(),
                None => {
                    crate::middleware::security::trusted_proxies::TrustedProxies::default_for_edge(
                        config.security.acme_enabled,
                    )
                }
            }),
            session_store: std::sync::LazyLock::new(|| std::sync::RwLock::new(None)),
            session_db_store: std::sync::LazyLock::new(|| std::sync::RwLock::new(None)),
            extensions,
        });

        add_urls(&engine);

        // Step 4b: admin + password reset — merged BEFORE the middleware stack.
        // `.layer()` in Axum only covers routes present at call time;
        // merging after means admin routes run without Session/CSRF/Extensions.
        let router = router.unwrap_or_default();

        let router = if let Some(pr) = self.password_reset {
            let forgot_path = pr.config.forgot_route.clone();
            let reset_path = format!(
                "{}/{{token}}/{{encrypted_email}}",
                pr.config.reset_route.trim_end_matches('/')
            );
            let pr_router = pr.handler.build_router(Arc::new(pr.config));
            register_name_url(&engine, "forgot_password", &forgot_path);
            register_name_url(&engine, "reset_password", &reset_path);
            router.merge(pr_router)
        } else {
            router
        };

        let router = if self.admin.enabled {
            // Public base URL (mount prefix + admin path) — what `{% url %}`
            // must resolve to, not the path the router is built from.
            let admin_prefix = self.admin.public_prefix();
            let robots_txt = self.admin.robots_txt;
            let sitemap_url = self.admin.sitemap_url.clone();
            if let Some(level) = crate::utils::runique_log::get_log()
                .builder
                .as_ref()
                .and_then(|b| b.registry)
            {
                let count = self
                    .admin
                    .state
                    .as_ref()
                    .map(|s| s.registry.all().count())
                    .unwrap_or(0);
                crate::runique_log!(level, resources = count, "admin registry");
            }
            // Close the `resource_key` referential-integrity gap: drop rights that
            // point at a resource key no longer in the registry (see
            // `prune_orphan_droits`). Static resources → boot is the only window.
            let valid_keys: Vec<String> = self
                .admin
                .state
                .as_ref()
                .map(|s| s.registry.keys().into_iter().map(str::to_string).collect())
                .unwrap_or_default();
            if !valid_keys.is_empty() {
                let refs: Vec<&str> = valid_keys.iter().map(String::as_str).collect();
                let level = crate::utils::runique_log::get_log()
                    .builder
                    .as_ref()
                    .and_then(|b| b.registry);
                match crate::admin::permissions::prune_orphan_droits(engine.db.as_ref(), &refs)
                    .await
                {
                    Ok(n) if n > 0 => {
                        if let Some(level) = level {
                            crate::runique_log!(
                                level,
                                pruned = n,
                                "orphan group rights pruned at boot"
                            );
                        }
                    }
                    Ok(_) => {}
                    Err(e) => {
                        if let Some(level) = level {
                            crate::runique_log!(level, error = %e, "orphan rights prune failed — stale grants may remain");
                        }
                    }
                }
            }

            let admin_router = build_admin_router(self.admin, engine.db.clone());
            add_urls(&engine);
            register_name_url(&engine, "admin", &admin_prefix);
            let mut r = router.merge(admin_router);
            if robots_txt {
                r = r.route(
                    "/robots.txt",
                    axum::routing::get(move || {
                        let sitemap_line = sitemap_url
                            .map(|u| format!("Sitemap: {}\n", u))
                            .unwrap_or_default();
                        // No `Disallow` for the admin prefix on purpose: this file
                        // is public, so naming the path would publish the very
                        // prefix a dev may have chosen to stay discreet — and it
                        // would only ask crawlers not to fetch it, not to leave it
                        // out of the index. De-indexing is handled where it cannot
                        // leak, by the `X-Robots-Tag` header on the admin router.
                        let body = format!(
                            "User-agent: *\n\n{}Content-Signal: ai-train=yes, search=yes, ai-input=yes\n",
                            sitemap_line
                        );
                        async move { body }
                    }),
                );
            }
            r
        } else {
            router
        };

        if let Some(level) = crate::utils::runique_log::get_log()
            .builder
            .as_ref()
            .and_then(|b| b.routes)
        {
            let count = engine
                .url_registry
                .read()
                .map(|guard| guard.len())
                .unwrap_or(0);
            crate::runique_log!(level, routes = count, "url registry");
        }

        // Step 5: middleware staging — automatic slot sort and apply
        let _exclusive_login = middleware.exclusive_login;
        let (router, session_store) =
            middleware.apply_to_router(router, config, engine.clone(), tera);
        if let Some(store) = session_store
            && let Ok(mut guard) = engine.session_store.write()
        {
            *guard = Some(store);
        }

        #[cfg(feature = "orm")]
        {
            let db_store = RuniqueSessionStore::new(engine.db.clone());
            if let Ok(mut guard) = engine.session_db_store.write() {
                *guard = Some(Arc::new(db_store));
            }
        }

        // Step 6: static files (conditional)
        let router = if statics_enabled {
            Self::attach_static_files(router, &engine.config, static_cache, media_cache)
        } else {
            router
        };

        Ok(RuniqueApp {
            engine,
            router,
            _log_guards: log_guards,
        })
    }

    // ─── Internal validation ──────────────────────────────────────────────────

    fn validate(&self) -> Result<(), BuildError> {
        self.core.validate()?;
        self.middleware.validate()?;
        self.statics.validate()?;
        self.admin.validate()?;
        self.cross_validate()
    }

    fn cross_validate(&self) -> Result<(), BuildError> {
        if self.config.debug {
            return Ok(());
        }

        use crate::app::error_build::{CheckError, CheckReport};

        let mut report = CheckReport::new();
        #[cfg(feature = "acme")]
        let sec = &self.config.security;
        let srv = &self.config.server;

        if crate::config::server::secret_key_is_weak(&srv.secret_key) {
            report.add(
                CheckError::new(
                    "Security",
                    "SECRET_KEY is missing, empty, the default value, or shorter than 32 characters",
                )
                .with_suggestion(
                    "Set SECRET_KEY to a random 32+ character string in your .env file (the `runique` CLI can generate one)",
                ),
            );
        }

        #[cfg(feature = "acme")]
        if sec.acme_enabled {
            if sec.acme_domain.is_none() {
                report.add(
                    CheckError::new("ACME", "ACME_ENABLED=true but ACME_DOMAIN is not set")
                        .with_suggestion(
                            "Set ACME_DOMAIN to your production domain in your .env file",
                        ),
                );
            }
            if sec.acme_email.is_none() {
                report.add(
                    CheckError::new("ACME", "ACME_ENABLED=true but ACME_EMAIL is not set")
                        .with_suggestion(
                            "Set ACME_EMAIL to your Let's Encrypt contact email in your .env file",
                        ),
                );
            }
        }

        if report.has_errors() {
            return Err(BuildError::check(report));
        }

        Ok(())
    }

    fn all_ready(&self) -> bool {
        self.core.is_ready()
            && self.middleware.is_ready()
            && self.statics.is_ready()
            && self.admin.is_ready()
    }

    // ─── Static files attachment ──────────────────────────────────────────────

    pub(super) fn attach_static_files(
        mut router: Router,
        config: &RuniqueConfig,
        static_cache: &'static str,
        media_cache: &'static str,
    ) -> Router {
        // HSTS is host-scoped: once any page emits it (via the CSP middleware,
        // gated + configured by `SecurityConfig::hsts_header_value`), the browser
        // applies it to the whole host, static assets included. So static file
        // responses only carry the per-asset headers here — no HSTS to keep
        // config as the single source of truth (never a hardcoded preload).
        let security_headers = || {
            tower::ServiceBuilder::new()
                .layer(SetResponseHeaderLayer::if_not_present(
                    HeaderName::from_static("x-content-type-options"),
                    HeaderValue::from_static("nosniff"),
                ))
                .layer(SetResponseHeaderLayer::if_not_present(
                    HeaderName::from_static("x-frame-options"),
                    HeaderValue::from_static("DENY"),
                ))
                .layer(SetResponseHeaderLayer::if_not_present(
                    HeaderName::from_static("referrer-policy"),
                    HeaderValue::from_static("strict-origin-when-cross-origin"),
                ))
        };

        let static_headers = security_headers().layer(SetResponseHeaderLayer::if_not_present(
            HeaderName::from_static("cache-control"),
            HeaderValue::from_static(static_cache),
        ));

        let media_headers = security_headers().layer(SetResponseHeaderLayer::if_not_present(
            HeaderName::from_static("cache-control"),
            HeaderValue::from_static(media_cache),
        ));

        router = router
            .nest_service(
                &config.static_files.static_url,
                static_headers
                    .clone()
                    .service(ServeDir::new(&config.static_files.staticfiles_dirs)),
            )
            .nest_service(
                &config.static_files.media_url,
                media_headers.service(ServeDir::new(&config.static_files.media_root)),
            );

        if !config.static_files.static_runique_url.is_empty() {
            router = router.nest_service(
                &config.static_files.static_runique_url,
                static_headers.service(ServeDir::new(&config.static_files.static_runique_path)),
            );
        }

        if let Some(level) = crate::utils::runique_log::get_log()
            .builder
            .as_ref()
            .and_then(|b| b.statics)
        {
            crate::runique_log!(
                level,
                static_url = %config.static_files.static_url,
                static_dir = %config.static_files.staticfiles_dirs,
                media_url = %config.static_files.media_url,
                media_dir = %config.static_files.media_root,
                "static files attached"
            );
        }

        router
    }
}