Skip to main content

aurelin_framework/validation/
browser.rs

1//! Browser and Inertia validation using request-scoped session flash data.
2//!
3//! Install [`flash_middleware`] inside the session layer, and pass page props
4//! through [`validation_page_props`] before rendering. Use
5//! [`BrowserValidated`] on form/JSON handlers, with authorization in an outer
6//! route layer. API requests retain the JSON validation response.
7
8use std::collections::BTreeMap;
9
10use axum::{
11    extract::{FromRequest, Request},
12    http::{HeaderMap, Method, StatusCode, Uri, header},
13    middleware::Next,
14    response::{IntoResponse, Response},
15};
16use axum_valid::{HasValidate, ValidRejection};
17use inertia_rs::axum::InertiaRequest;
18use serde::{Deserialize, Serialize};
19use tower_sessions::Session;
20use validator::Validate;
21
22use super::{ValidationIssue, http::ValidationResponse, issues};
23
24const FLASH_KEY: &str = "aurelin.validation.flash";
25
26/// Explicit application-owned projection of non-sensitive, non-file form fields.
27///
28/// Never include credentials, passwords, tokens, secrets, files, or entire input
29/// objects. The framework cannot determine whether an application-selected value
30/// is sensitive; the caller is responsible for that security decision.
31#[derive(Clone, Debug, Default, Deserialize, Serialize)]
32pub struct SafeOldInput(BTreeMap<String, String>);
33
34impl SafeOldInput {
35    /// Add one explicitly approved plain-text field.
36    pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
37        self.0.insert(name.into(), value.into());
38        self
39    }
40}
41
42/// Implement on request data to select only fields safe to flash back to users.
43pub trait OldInput {
44    fn safe_old_input(&self) -> SafeOldInput;
45}
46
47/// Flash data is removed on the next request, regardless of its route.
48#[derive(Clone, Debug, Default, Deserialize, Serialize)]
49pub struct ValidationFlash {
50    issues: Vec<ValidationIssue>,
51    bag: Option<String>,
52    old: SafeOldInput,
53}
54
55impl ValidationFlash {
56    /// First message per field, with an optional Inertia error-bag key.
57    pub fn errors(&self) -> serde_json::Value {
58        let mut fields = BTreeMap::new();
59        for issue in &self.issues {
60            fields.entry(issue.field.clone()).or_insert_with(|| issue.render_message());
61        }
62        match &self.bag {
63            Some(bag) => serde_json::json!({ bag: fields }),
64            None => serde_json::json!(fields),
65        }
66    }
67
68    /// The explicitly selected old input, for application-owned form rendering.
69    pub fn old_input(&self) -> &SafeOldInput {
70        &self.old
71    }
72}
73
74/// Read and remove validation flash once per request. Must run inside the session layer.
75pub async fn flash_middleware(session: Session, mut request: Request, next: Next) -> Response {
76    match session.remove::<ValidationFlash>(FLASH_KEY).await {
77        Ok(flash) => {
78            request.extensions_mut().insert(flash.unwrap_or_default());
79            next.run(request).await
80        }
81        Err(error) => {
82            tracing::error!(error = %error, "failed to read validation flash");
83            StatusCode::INTERNAL_SERVER_ERROR.into_response()
84        }
85    }
86}
87
88/// Add `errors` and `old` to route props before passing them to Inertia.
89///
90/// `inertia_rs` 0.4 inserts an empty `errors` prop before shared-prop merging,
91/// so registering it as a `SharedProps` provider does not work.
92pub fn validation_page_props(
93    request: &InertiaRequest,
94    mut props: serde_json::Map<String, serde_json::Value>,
95) -> serde_json::Value {
96    let flash = request.extension::<ValidationFlash>().cloned().unwrap_or_default();
97    props.insert("errors".into(), flash.errors());
98    props.insert("old".into(), serde_json::json!(flash.old));
99    serde_json::Value::Object(props)
100}
101
102/// An Axum extractor that validates after any outer authorization middleware.
103pub struct BrowserValidated<E>(pub E);
104
105impl<S, E> FromRequest<S> for BrowserValidated<E>
106where
107    S: Send + Sync,
108    E: HasValidate + FromRequest<S> + Send,
109    E::Validate: Validate + OldInput,
110{
111    type Rejection = Response;
112
113    async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
114        let headers = request.headers().clone();
115        let method = request.method().clone();
116        let session = request.extensions().get::<Session>().cloned();
117        let inner = E::from_request(request, state)
118            .await
119            .map_err(|error| ValidationResponse::from_rejection(ValidRejection::Inner(error)).into_response())?;
120        let Err(errors) = inner.get_validate().validate() else {
121            return Ok(Self(inner));
122        };
123        if wants_json(&headers) {
124            return Err(
125                ValidationResponse::from_rejection::<E::Rejection>(ValidRejection::Valid(errors)).into_response()
126            );
127        }
128        let Some(session) = session else {
129            return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response());
130        };
131        let bag = headers
132            .get("x-inertia-error-bag")
133            .and_then(|value| value.to_str().ok())
134            .filter(|value| !value.is_empty() && value.len() <= 128)
135            .map(str::to_owned);
136        let flash = ValidationFlash {
137            issues: issues(&errors, bag.as_deref()),
138            bag,
139            old: inner.get_validate().safe_old_input(),
140        };
141        if let Err(error) = session.insert(FLASH_KEY, flash).await {
142            tracing::error!(error = %error, "failed to write validation flash");
143            return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response());
144        }
145        let location = redirect_back(&headers);
146        let status = if method == Method::PUT
147            || method == Method::PATCH
148            || method == Method::DELETE
149            || method.as_str() == "QUERY"
150        {
151            StatusCode::SEE_OTHER
152        } else {
153            StatusCode::FOUND
154        };
155        Err((status, [(header::LOCATION, location), (header::VARY, "X-Inertia".to_owned())]).into_response())
156    }
157}
158
159fn wants_json(headers: &HeaderMap) -> bool {
160    if headers.contains_key("x-inertia") {
161        return false;
162    }
163    [header::ACCEPT, header::CONTENT_TYPE].iter().any(|name| {
164        headers
165            .get(name)
166            .and_then(|v| v.to_str().ok())
167            .is_some_and(|value| value.contains("/json") || value.contains("+json"))
168    })
169}
170
171fn redirect_back(headers: &HeaderMap) -> String {
172    let Some(uri) = headers.get(header::REFERER).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<Uri>().ok())
173    else {
174        return "/".into();
175    };
176    if let Some(authority) = uri.authority() {
177        let host = headers.get(header::HOST).and_then(|v| v.to_str().ok());
178        if host != Some(authority.as_str()) {
179            return "/".into();
180        }
181    }
182    uri.path_and_query()
183        .filter(|path| path.as_str().starts_with('/') && !path.as_str().starts_with("//"))
184        .map_or_else(|| "/".into(), |path| path.as_str().to_owned())
185}