runique 2.1.11

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
//! Main request context: `AppError`, `RuniqueContext`, and Tera context construction.
use crate::app::templates::TemplateLoader;
use crate::auth::session::CurrentUser;
use crate::errors::error::ErrorContext;
use crate::flash::Message;
use crate::forms::{
    extractor::{Prisme, prisme_pipeline},
    field::RuniqueForm,
};
use crate::impl_from_error;
use crate::middleware::security::anti_bot::HoneypotFieldName;
use crate::utils::aliases::{AEngine, AppResult};
use crate::utils::url_params::UrlParams;
use crate::utils::{csp_nonce::CspNonce, csrf::CsrfToken};
use axum::{
    body::Body,
    extract::{FromRequest, FromRequestParts, Path},
    http::{Request as HttpRequest, StatusCode, method::Method},
    response::{Html, IntoResponse, Response},
};
use sea_orm::DbErr;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
use tera::Context;
use tower_sessions::Session;
use tracing::error;

// --- ERROR HANDLING ---

/// Application error returned by handlers: encapsulates an [`ErrorContext`] and implements [`IntoResponse`].
pub struct AppError {
    /// Error context: status code, message, type.
    pub context: ErrorContext,
}

impl AppError {
    /// Wraps an [`ErrorContext`] into an `AppError`.
    pub fn new(context: ErrorContext) -> Self {
        Self { context }
    }

    /// Converts a Tera rendering error into an `AppError`, logging detail in debug mode.
    pub fn map_tera(e: tera::Error, route: &str, tera: &tera::Tera) -> Box<Self> {
        // Log the detailed error in the console
        error!(
            template = route,
            error = ?e,
            "Template rendering error"
        );

        Box::new(Self {
            context: ErrorContext::from_tera_error(&e, route, tera),
        })
    }
}

impl_from_error!(anyhow::Error => from_anyhow, DbErr => database);

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = StatusCode::from_u16(self.context.status_code)
            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);

        //  Log the error in detail
        error!(
            status = status.as_u16(),
            error_type = ?self.context.error_type,
            message = %self.context.message,
            "AppError occurred"
        );

        let mut res = status.into_response();
        //  Insert ErrorContext so that the middleware can retrieve it
        res.extensions_mut().insert(Arc::new(self.context));
        res
    }
}

impl IntoResponse for Box<AppError> {
    fn into_response(self) -> Response {
        (*self).into_response()
    }
}

// --- TEMPLATE CONTEXT ---

/// Request context automatically extracted in handlers via `FromRequest`.
/// Contains the engine, session, flash messages, CSRF token, Tera context,
/// and the Prisme-extracted form data (query params on GET, body on POST).
#[derive(Clone)]
pub struct Request {
    /// Shared application engine.
    pub engine: AEngine,
    /// Session of the current request.
    pub session: Session,
    /// Session flash messages.
    pub notices: Message,
    /// Request CSRF token (masked in the Tera context).
    pub csrf_token: CsrfToken,
    /// Pre-filled Tera context (csrf_token, debug, messages, user…).
    pub context: Context,
    /// HTTP method of the request.
    pub method: Method,
    /// HTTP headers of the request.
    pub headers: axum::http::HeaderMap,
    /// Path parameters (`/{id}`).
    pub path_params: HashMap<String, String>,
    /// Raw query string (`?a=1&b=2`), preserved for typed deserialization.
    pub raw_query: String,
    /// Query string parameters.
    pub query_params: HashMap<String, String>,
    /// Current user (None if not authenticated).
    pub user: Option<CurrentUser>,
    /// Parsed form data from the request (query params on GET, body on POST).
    /// CSRF is validated — csrf_valid = false signals an invalid token.
    pub prisme: Prisme,
    /// Honeypot field name injected by anti_bot middleware (None if middleware not active).
    pub honeypot_field_name: Option<String>,
}

impl<S> FromRequest<S> for Request
where
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request(req: HttpRequest<Body>, state: &S) -> Result<Self, Self::Rejection> {
        let err = |msg: &str| (StatusCode::INTERNAL_SERVER_ERROR, msg.to_string()).into_response();

        let (mut parts, body) = req.into_parts();
        let ex = &parts.extensions;

        let engine = ex
            .get::<AEngine>()
            .cloned()
            .ok_or_else(|| err("engine missing"))?;
        let csrf_token = ex
            .get::<CsrfToken>()
            .cloned()
            .ok_or_else(|| err("csrf missing"))?;
        let session = ex
            .get::<Session>()
            .cloned()
            .ok_or_else(|| err("session missing"))?;
        let nonce = ex.get::<CspNonce>().map(|n| n.as_str()).unwrap_or_default();
        let user = ex.get::<CurrentUser>().cloned();
        let honeypot_field_name = ex.get::<HoneypotFieldName>().map(|h| h.0.clone());

        let notices = Message {
            session: session.clone(),
        };
        let messages = notices.get_all().await;

        let mut context = Context::new();
        context.insert("debug", &engine.config.debug);
        context.insert(
            "csrf_token",
            &csrf_token
                .masked()
                .unwrap_or_else(|_| csrf_token.clone())
                .as_str(),
        );
        context.insert("csp_nonce", nonce);
        context.insert("static_runique", &engine.config.static_files);
        context.insert("messages", &messages);
        if let Some(ref u) = user {
            context.insert("current_user", u);
        }

        let path_params = Path::<HashMap<String, String>>::from_request_parts(&mut parts, state)
            .await
            .map(|Path(p)| p)
            .unwrap_or_default();

        let ico_image = std::env::var("ICON_IMAGE")
            .unwrap_or("/runique/static/favicon_runique.ico".to_string());
        let ico_image =
            crate::utils::resolve_og_image(&engine.security_hosts, engine.config.debug, &ico_image);
        context.insert("icon_image", &ico_image);

        let og_image =
            std::env::var("OG_IMAGE").unwrap_or("/runique/static/runique_320.avif".to_string());
        let og_image =
            crate::utils::resolve_og_image(&engine.security_hosts, engine.config.debug, &og_image);
        context.insert("og_image", &og_image);

        let raw_query = parts.uri.query().unwrap_or_default().to_string();
        let query_params =
            serde_urlencoded::from_str::<HashMap<String, String>>(&raw_query).unwrap_or_default();

        let method = parts.method.clone();
        let headers = parts.headers.clone();

        // Run Prisme pipeline (sentinel → aegis → CSRF check)
        let req = HttpRequest::from_parts(parts, body);
        let prisme = prisme_pipeline(req, state).await?;

        Ok(Self {
            engine,
            session,
            notices,
            csrf_token,
            context,
            method,
            headers,
            path_params,
            raw_query,
            query_params,
            user,
            prisme,
            honeypot_field_name,
        })
    }
}

impl Request {
    pub fn new(engine: AEngine, session: Session, csrf_token: CsrfToken, method: Method) -> Self {
        let mut context = tera::Context::new();
        // mod reload for templates in debug mode
        // The backend cannot be reloaded here because it is shared between requests
        context.insert("debug", &engine.config.debug);
        context.insert("static_runique", &engine.config.static_files);
        context.insert(
            "csrf_token",
            &csrf_token
                .masked()
                .unwrap_or_else(|_| csrf_token.clone())
                .as_str(),
        );

        Self {
            engine,
            session: session.clone(),
            notices: Message { session },
            csrf_token,
            context,
            method,
            headers: axum::http::HeaderMap::new(),
            path_params: HashMap::new(),
            raw_query: String::new(),
            query_params: HashMap::new(),
            user: None,
            prisme: Prisme {
                data: Default::default(),
                csrf_valid: true,
            },
            honeypot_field_name: None,
        }
    }

    /// Returns `true` if the request method is GET.
    pub fn is_get(&self) -> bool {
        self.method == Method::GET
    }

    /// Returns `true` if the request method is POST.
    pub fn is_post(&self) -> bool {
        self.method == Method::POST
    }

    /// Returns `true` if the request method is PUT.
    pub fn is_put(&self) -> bool {
        self.method == Method::PUT
    }

    /// Returns `true` if the request method is DELETE.
    pub fn is_delete(&self) -> bool {
        self.method == Method::DELETE
    }
    /// Unique generic rendering to avoid duplication
    pub fn render(&mut self, template: &str) -> AppResult<Response> {
        let html_result = if self.engine.config.debug {
            // In debug mode, Tera is fully reinitialized with the Loader
            // This applies Regex on {% messages %}, {% form.xxx %}, etc.
            match TemplateLoader::init(&self.engine.config, self.engine.url_registry.clone()) {
                Ok(dev_tera) => {
                    let res = dev_tera.render(template, &self.context);
                    if let Err(ref e) = res {
                        // Detailed log of the Tera error with all sources
                        error!(
                            template = template,
                            error_kind = ?e.kind,
                            error_message = %e,
                            "Tera rendering failed in debug mode"
                        );

                        // Log the full error chain (source)
                        // Uses the source() method from the std::error::Error trait
                        use std::error::Error as StdError;
                        if let Some(source) = e.source() {
                            error!(
                                source_error = %source,
                                "Tera error source"
                            );
                        }
                    }
                    res
                }
                Err(e) => {
                    error!(
                        template = template,
                        error = %e,
                        "Failed to initialize TemplateLoader in debug mode"
                    );
                    return Err(AppError::map_tera(
                        tera::Error::msg(e.to_string()),
                        template,
                        &self.engine.tera,
                    ));
                }
            }
        } else {
            // Production mode: uses the already transformed instance
            self.engine.tera.render(template, &self.context)
        };

        html_result
            .map(|html| Html(html).into_response())
            .map_err(|e| AppError::map_tera(e, template, &self.engine.tera))
    }

    /// Fluent insertion with builder pattern
    pub fn insert(mut self, key: &str, value: impl serde::Serialize) -> Self {
        self.context.insert(key, &value);
        self
    }

    /// Immediate rendering with additional data
    pub fn render_with(
        mut self,
        template: &str,
        data: Vec<(&str, serde_json::Value)>,
    ) -> AppResult<Response> {
        for (k, v) in data {
            self.context.insert(k, &v);
        }
        self.render(template)
    }

    /// Returns a reference to the database connection.
    pub fn db(&self) -> &sea_orm::DatabaseConnection {
        &self.engine.db
    }

    /// Returns a path segment as a string slice (`/users/{id}` → `get_path("id")`).
    pub fn get_path(&self, key: &str) -> Option<&str> {
        self.path_params.get(key).map(|s| s.as_str())
    }

    /// Parses a path segment into any type implementing `FromStr`.
    pub fn get_path_as<T: FromStr>(&self, key: &str) -> Option<T> {
        self.path_params.get(key)?.parse().ok()
    }

    /// Returns a query parameter as a string slice (`?page=2` → `get_query("page")`).
    pub fn get_query(&self, key: &str) -> Option<&str> {
        self.query_params.get(key).map(|s| s.as_str())
    }

    /// Deserializes the full query string into a typed struct.
    /// The struct must derive `serde::Deserialize` and `Default`.
    /// Unknown keys are ignored; missing keys produce the `Default` value.
    /// Empty values (`key=`) are dropped so that `Option<i32>` fields receive `None`
    /// rather than causing a parse failure that silently resets the whole struct.
    pub fn query<T: DeserializeOwned + Default>(&self) -> T {
        let cleaned = self
            .raw_query
            .split('&')
            .filter(|pair| pair.split('=').nth(1).is_none_or(|v| !v.is_empty()))
            .collect::<Vec<_>>()
            .join("&");
        serde_urlencoded::from_str(&cleaned).unwrap_or_default()
    }

    /// Returns an `UrlParams` combining path and query — to be passed to `form.cleaned()`
    pub fn url_params(&self) -> UrlParams<'_> {
        UrlParams::new(&self.path_params, &self.query_params)
    }

    /// Constructs a form `T`, fills it with submitted data (POST body or query string on GET),
    /// and injects the honeypot field if the anti-bot middleware is active.
    /// Call `form.is_valid().await` before reading cleaned values or calling `save()`.
    pub fn form<T: RuniqueForm>(&self) -> T {
        let masked = self
            .csrf_token
            .masked()
            .unwrap_or_else(|_| self.csrf_token.clone());
        let mut form = T::build(self.engine.tera.clone(), masked.as_str());
        form.get_form_mut()
            .set_url_params(&self.path_params, &self.query_params);

        if let Some(ref hp_name) = self.honeypot_field_name {
            form.get_form_mut().set_honeypot(hp_name);
            if self.is_post() && self.prisme.data.get(hp_name).is_some_and(|v| !v.is_empty()) {
                form.get_form_mut().force_invalid = true;
            }
        }

        form.get_form_mut()
            .fill(&self.prisme.data, self.method.clone());
        form
    }
}