swadhinbiswas 📦 v2.0.8: security fixes, documentation, testing improvements · 7/28/2026
84307b8
70 lines · 2.8 KB
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
use std::sync::Arc;

use futures::FutureExt;
use hyper::body::Incoming;
use hyper::{Request, StatusCode};

use crate::json_response;
use crate::middleware::HandlerFn;

/// Wraps a handler fn so that panics are caught, logged, and converted to 500 responses.
///
/// NOTE: We no longer manipulate the global panic hook per-request (that was a race
/// condition under concurrent load). The workspace `panic = "abort"` policy means
/// genuine panics terminate the process and the supervisor restarts it. This wrapper
/// uses `catch_unwind` to convert panics into 500 responses without touching global state.
pub fn with_panic_recovery(handler: HandlerFn) -> HandlerFn {
    Arc::new(move |req: Request<Incoming>| {
        let handler = handler.clone();
        Box::pin(async move {
            // SAFETY: The handler is wrapped in AssertUnwindSafe to catch panics.
            // The workspace `panic = "abort"` policy means genuine panics terminate
            // the process, so this is only needed for the catch_unwind path.
            // If the handler holds Rc/RefCell/&mut across the catch point, this
            // could lead to undefined states — but the handler is a Box<dyn Fn>
            // which is Send + Sync, so interior mutability is the only concern.
            let result = std::panic::AssertUnwindSafe(handler(req)).catch_unwind().await;

            match result {
                Ok(Ok(resp)) => Ok(resp),
                Ok(Err(e)) => {
                    tracing::error!(error = %e, "Handler returned error");
                    Ok(json_response(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        r#"{"detail":"Internal error"}"#,
                    ))
                }
                Err(panic) => {
                    let msg = if let Some(s) = panic.downcast_ref::<&str>() {
                        s.to_string()
                    } else if let Some(s) = panic.downcast_ref::<String>() {
                        s.clone()
                    } else {
                        "unknown panic".to_string()
                    };
                    tracing::error!(panic = true, message = %msg, "Handler panicked");
                    Ok(json_response(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        r#"{"detail":"Internal server error"}"#,
                    ))
                }
            }
        })
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_with_panic_recovery_returns_handler_fn() {
        let handler: HandlerFn = Arc::new(|_req: Request<Incoming>| {
            Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
        });
        let wrapped = with_panic_recovery(handler);
        // Smoke test: the wrapper is itself a HandlerFn with the same signature.
        let _wrapped_ref: &HandlerFn = &wrapped;
    }
}