autumn-web 0.4.0

An opinionated, convention-over-configuration web framework for Rust
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Global exception filter middleware.
//!
//! Intercepts error responses produced by [`AutumnError`](crate::AutumnError)
//! and passes them through a chain of user-registered filters before the
//! response is sent to the client.
//!
//! # How it works
//!
//! When `AutumnError::into_response()` runs, it stashes an
//! [`AutumnErrorInfo`] clone into the response extensions. The
//! [`ExceptionFilterLayer`] middleware checks for this extension after the
//! inner service returns. If present, it runs the filter chain, giving each
//! filter a chance to transform, log, or replace the response.
//!
//! # Examples
//!
//! ```rust,no_run
//! use autumn_web::middleware::ExceptionFilter;
//! use autumn_web::middleware::AutumnErrorInfo;
//! use axum::response::Response;
//!
//! struct LoggingFilter;
//!
//! impl ExceptionFilter for LoggingFilter {
//!     fn filter(&self, error: &AutumnErrorInfo, response: Response) -> Response {
//!         eprintln!("Error {}: {}", error.status, error.message);
//!         response
//!     }
//! }
//!
//! # #[autumn_web::main]
//! # async fn main() {
//! autumn_web::app()
//!     .exception_filter(LoggingFilter)
//!     // .routes(...)
//! #   .routes(vec![])
//! #   ;
//! # }
//! ```

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use axum::http::{Request, StatusCode};
use axum::response::{IntoResponse, Response};
use http::HeaderValue;
use pin_project_lite::pin_project;
use tower::{Layer, Service};

/// Metadata extracted from an [`AutumnError`](crate::AutumnError) and stashed
/// in the response extensions.
///
/// Exception filters receive this to inspect the original error without
/// needing to parse the response body.
#[derive(Clone, Debug)]
pub struct AutumnErrorInfo {
    /// The HTTP status code of the error.
    pub status: StatusCode,
    /// The human-readable error message.
    pub message: String,
    /// Optional field-level validation details (for 422 responses).
    pub details: Option<std::collections::HashMap<String, Vec<String>>>,
    /// Optional explicit Problem Details type URI.
    pub problem_type: Option<&'static str>,
}

impl AutumnErrorInfo {
    /// Build the default Problem Details JSON error response from this info.
    ///
    /// Useful when a filter wants to log or enrich but keep the standard
    /// response format. Server-error details are sanitized because this helper
    /// does not know whether the current profile is development or production.
    #[must_use]
    pub fn into_default_response(self) -> Response {
        problem_response_from_info(&self, None, None, false)
    }
}

/// Exception filter that rebuilds framework errors as request-aware Problem
/// Details responses before HTML error-page negotiation runs.
pub struct ProblemDetailsFilter {
    pub is_dev: bool,
}

impl ExceptionFilter for ProblemDetailsFilter {
    fn filter(&self, error: &AutumnErrorInfo, response: Response) -> Response {
        let context = response
            .extensions()
            .get::<crate::middleware::error_page_filter::ErrorPageRequestContext>();
        let request_id = context.and_then(|ctx| ctx.request_id.clone()).or_else(|| {
            response
                .headers()
                .get("x-request-id")
                .and_then(|value| value.to_str().ok())
                .map(str::to_owned)
        });
        let instance = context.map(|ctx| ctx.uri.path().to_owned());
        let mut preserved_headers = response.headers().clone();
        preserved_headers.remove(http::header::CONTENT_TYPE);
        preserved_headers.remove(http::header::CONTENT_LENGTH);

        let mut out = problem_response_from_info(error, request_id, instance, self.is_dev);
        out.headers_mut().extend(preserved_headers);
        out.headers_mut().insert(
            http::header::CONTENT_TYPE,
            HeaderValue::from_static("application/problem+json"),
        );

        if let Some(wants_html) = response
            .extensions()
            .get::<crate::middleware::error_page_filter::WantsHtml>()
            .cloned()
        {
            out.extensions_mut().insert(wants_html);
        }
        if let Some(ctx) = context.cloned() {
            out.extensions_mut().insert(ctx);
        }
        out.extensions_mut().insert(error.clone());
        out
    }
}

fn problem_response_from_info(
    error: &AutumnErrorInfo,
    request_id: Option<String>,
    instance: Option<String>,
    is_dev: bool,
) -> Response {
    let body = crate::error::problem_details(
        error.status,
        error.message.clone(),
        error.details.as_ref(),
        error.problem_type,
        request_id,
        instance,
        is_dev,
    );
    let mut response = (error.status, axum::Json(body)).into_response();
    response.headers_mut().insert(
        http::header::CONTENT_TYPE,
        HeaderValue::from_static("application/problem+json"),
    );
    response
}

/// Trait for global exception filters.
///
/// Implement this trait to intercept error responses before they are sent
/// to the client. Filters can log, transform, or completely replace the
/// response.
///
/// # Examples
///
/// ```rust
/// use autumn_web::middleware::{ExceptionFilter, AutumnErrorInfo};
/// use axum::response::Response;
///
/// struct SentryFilter;
///
/// impl ExceptionFilter for SentryFilter {
///     fn filter(&self, error: &AutumnErrorInfo, response: Response) -> Response {
///         // Log to Sentry, metrics, etc.
///         eprintln!("[sentry] {} {}", error.status, error.message);
///         response // pass through unchanged
///     }
/// }
/// ```
pub trait ExceptionFilter: Send + Sync + 'static {
    /// Inspect and optionally transform an error response.
    ///
    /// `error` contains the original error metadata. `response` is the
    /// current HTTP response (which may have been modified by a previous
    /// filter in the chain). Return the response to send to the client.
    fn filter(&self, error: &AutumnErrorInfo, response: Response) -> Response;
}

/// Tower [`Layer`] that applies the exception filter chain.
///
/// Applied automatically by [`AppBuilder::run`](crate::app::AppBuilder::run)
/// when at least one exception filter is registered.
#[derive(Clone)]
pub struct ExceptionFilterLayer {
    filters: Arc<Vec<Arc<dyn ExceptionFilter>>>,
}

impl ExceptionFilterLayer {
    /// Create a new layer with the given filter chain.
    #[must_use]
    pub fn new(filters: Vec<Arc<dyn ExceptionFilter>>) -> Self {
        Self {
            filters: Arc::new(filters),
        }
    }
}

impl<S> Layer<S> for ExceptionFilterLayer {
    type Service = ExceptionFilterService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        ExceptionFilterService {
            inner,
            filters: Arc::clone(&self.filters),
        }
    }
}

/// Tower [`Service`] produced by [`ExceptionFilterLayer`].
#[derive(Clone)]
pub struct ExceptionFilterService<S> {
    inner: S,
    filters: Arc<Vec<Arc<dyn ExceptionFilter>>>,
}

impl<S, ReqBody> Service<Request<ReqBody>> for ExceptionFilterService<S>
where
    S: Service<Request<ReqBody>, Response = Response>,
{
    type Response = Response;
    type Error = S::Error;
    type Future = ExceptionFilterFuture<S::Future>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
        ExceptionFilterFuture {
            inner: self.inner.call(req),
            filters: Arc::clone(&self.filters),
        }
    }
}

pin_project! {
    /// Future that applies exception filters to error responses.
    pub struct ExceptionFilterFuture<F> {
        #[pin]
        inner: F,
        filters: Arc<Vec<Arc<dyn ExceptionFilter>>>,
    }
}

impl<F, E> Future for ExceptionFilterFuture<F>
where
    F: Future<Output = Result<Response, E>>,
{
    type Output = Result<Response, E>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        match this.inner.poll(cx) {
            Poll::Ready(Ok(response)) => {
                // Check if this response came from AutumnError and clone the info out
                if let Some(error_info) = response.extensions().get::<AutumnErrorInfo>().cloned() {
                    let mut response = response;
                    let filters = this.filters;
                    for filter in filters.iter() {
                        response = filter.filter(&error_info, response);
                    }
                    Poll::Ready(Ok(response))
                } else {
                    Poll::Ready(Ok(response))
                }
            }
            Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
            Poll::Pending => Poll::Pending,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::Router;
    use axum::body::Body;
    use axum::routing::get;
    use http::Request;
    use tower::ServiceExt;

    use crate::error::AutumnError;

    #[tokio::test]
    async fn filter_receives_error_info() {
        use std::sync::atomic::{AtomicBool, Ordering};

        static CALLED: AtomicBool = AtomicBool::new(false);

        struct TestFilter;
        impl ExceptionFilter for TestFilter {
            fn filter(&self, error: &AutumnErrorInfo, response: Response) -> Response {
                assert_eq!(error.status, StatusCode::NOT_FOUND);
                assert_eq!(error.message, "not here");
                CALLED.store(true, Ordering::SeqCst);
                response
            }
        }

        let app = Router::new()
            .route(
                "/",
                get(|| async {
                    Err::<String, AutumnError>(AutumnError::not_found_msg("not here"))
                }),
            )
            .layer(ExceptionFilterLayer::new(vec![Arc::new(TestFilter)]));

        let response = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        assert!(CALLED.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn filter_can_replace_response() {
        struct ReplaceFilter;
        impl ExceptionFilter for ReplaceFilter {
            fn filter(&self, _error: &AutumnErrorInfo, _response: Response) -> Response {
                (StatusCode::SERVICE_UNAVAILABLE, "custom error page").into_response()
            }
        }

        let app = Router::new()
            .route(
                "/",
                get(|| async { Err::<String, AutumnError>(AutumnError::not_found_msg("gone")) }),
            )
            .layer(ExceptionFilterLayer::new(vec![Arc::new(ReplaceFilter)]));

        let response = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(&body[..], b"custom error page");
    }

    #[tokio::test]
    async fn problem_details_filter_preserves_existing_response_headers() {
        let error = AutumnErrorInfo {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            message: "database unavailable".into(),
            details: None,
            problem_type: None,
        };
        let mut original = (StatusCode::INTERNAL_SERVER_ERROR, "old error body").into_response();
        original.headers_mut().insert(
            "access-control-allow-origin",
            http::HeaderValue::from_static("https://client.example"),
        );
        original
            .headers_mut()
            .insert("x-frame-options", http::HeaderValue::from_static("DENY"));
        original.headers_mut().insert(
            "content-security-policy",
            http::HeaderValue::from_static("default-src 'self'"),
        );
        original.headers_mut().insert(
            http::header::CONTENT_TYPE,
            http::HeaderValue::from_static("text/plain; charset=utf-8"),
        );

        let response = ProblemDetailsFilter { is_dev: false }.filter(&error, original);

        assert_eq!(
            response.headers()["access-control-allow-origin"],
            "https://client.example"
        );
        assert_eq!(response.headers()["x-frame-options"], "DENY");
        assert_eq!(
            response.headers()["content-security-policy"],
            "default-src 'self'"
        );
        assert_eq!(
            response.headers()[http::header::CONTENT_TYPE],
            "application/problem+json"
        );
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["detail"], "Internal server error");
    }

    #[tokio::test]
    async fn success_responses_bypass_filters() {
        use std::sync::atomic::{AtomicBool, Ordering};

        static CALLED: AtomicBool = AtomicBool::new(false);

        struct NeverFilter;
        impl ExceptionFilter for NeverFilter {
            fn filter(&self, _error: &AutumnErrorInfo, response: Response) -> Response {
                CALLED.store(true, Ordering::SeqCst);
                response
            }
        }

        let app = Router::new()
            .route("/", get(|| async { "ok" }))
            .layer(ExceptionFilterLayer::new(vec![Arc::new(NeverFilter)]));

        let response = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert!(!CALLED.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn multiple_filters_run_in_order() {
        use std::sync::atomic::{AtomicU32, Ordering};

        static COUNTER: AtomicU32 = AtomicU32::new(0);

        struct OrderFilter(u32);
        impl ExceptionFilter for OrderFilter {
            fn filter(&self, _error: &AutumnErrorInfo, response: Response) -> Response {
                let current = COUNTER.fetch_add(1, Ordering::SeqCst);
                assert_eq!(current, self.0, "filters should run in registration order");
                response
            }
        }

        COUNTER.store(0, Ordering::SeqCst);

        let app = Router::new()
            .route(
                "/",
                get(|| async { Err::<String, AutumnError>(AutumnError::bad_request_msg("oops")) }),
            )
            .layer(ExceptionFilterLayer::new(vec![
                Arc::new(OrderFilter(0)),
                Arc::new(OrderFilter(1)),
                Arc::new(OrderFilter(2)),
            ]));

        app.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(COUNTER.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn error_info_into_default_response() {
        let info = AutumnErrorInfo {
            status: StatusCode::NOT_FOUND,
            message: "not found".into(),
            details: None,
            problem_type: None,
        };
        let response = info.into_default_response();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn default_response_hides_internal_error_detail() {
        let info = AutumnErrorInfo {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            message: "database password leaked".into(),
            details: None,
            problem_type: None,
        };
        let response = info.into_default_response();

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["detail"], "Internal server error");
    }
}