Skip to main content

rtflow_http/
auth_middleware.rs

1//! HTTP token authentication middleware.
2//!
3//! Wraps an existing [`Handler`] to enforce HMAC token verification
4//! before delegating to the inner handler.
5use super::response::ResponseWriter;
6use super::router::Handler;
7use rtflow_rtsp::token_auth::TokenConfig;
8use std::sync::Arc;
9
10/// Wrap a handler with HMAC token authentication.
11///
12/// Requests must include a valid token in the query parameter configured
13/// by `TokenConfig::param_name`. Invalid or missing tokens receive a
14/// 403 Forbidden response with a JSON error body.
15pub fn with_token_auth(handler: Handler, config: TokenConfig) -> Handler {
16    Arc::new(move |req, writer| {
17        let handler = handler.clone();
18        let config = config.clone();
19        Box::pin(async move {
20            // Extract path without query for verification
21            let path = req.path.split('?').next().unwrap_or(&req.path);
22
23            // Look for token in query parameters
24            let token = req.query.get(&config.param_name).map(String::as_str);
25
26            match token {
27                Some(token) if rtflow_rtsp::token_auth::verify_token(&config, path, token) => {
28                    handler(req, writer).await
29                }
30                _ => write_forbidden(writer).await,
31            }
32        })
33    })
34}
35
36/// Wrap a handler with token auth, but bypass authentication for specific paths.
37///
38/// Useful for exempting `/health`, `/metrics`, or player pages from auth.
39pub fn with_token_auth_bypass(
40    handler: Handler,
41    config: TokenConfig,
42    bypass: Vec<String>,
43) -> Handler {
44    Arc::new(move |req, writer| {
45        let handler = handler.clone();
46        let config = config.clone();
47        let bypass = bypass.clone();
48        Box::pin(async move {
49            let path = req.path.split('?').next().unwrap_or(&req.path);
50
51            // Check bypass list
52            if bypass.iter().any(|b| path.starts_with(b)) {
53                return handler(req, writer).await;
54            }
55
56            let token = req.query.get(&config.param_name).map(String::as_str);
57            match token {
58                Some(token) if rtflow_rtsp::token_auth::verify_token(&config, path, token) => {
59                    handler(req, writer).await
60                }
61                _ => write_forbidden(writer).await,
62            }
63        })
64    })
65}
66
67async fn write_forbidden<W: tokio::io::AsyncWrite + Unpin>(
68    mut writer: ResponseWriter<W>,
69) -> rtflow_core::error::Result<ResponseWriter<W>> {
70    let body = r#"{"error":"forbidden","message":"valid token required"}"#;
71    writer
72        .write_body(403, "application/json", body.as_bytes())
73        .await?;
74    Ok(writer)
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use crate::ConnWriter;
81
82    fn test_config() -> TokenConfig {
83        TokenConfig::new(b"test-secret".to_vec())
84    }
85
86    fn ok_handler() -> Handler {
87        Arc::new(|_req, mut writer: ResponseWriter<ConnWriter>| {
88            Box::pin(async move {
89                writer.write_body(200, "text/plain", b"OK").await?;
90                Ok(writer)
91            })
92        })
93    }
94
95    #[test]
96    fn with_token_auth_creates_handler() {
97        let handler = ok_handler();
98        let config = test_config();
99        let _wrapped = with_token_auth(handler, config);
100        // Just verify it compiles and creates without panic
101    }
102
103    #[test]
104    fn with_token_auth_bypass_creates_handler() {
105        let handler = ok_handler();
106        let config = test_config();
107        let bypass = vec!["/health".to_string(), "/metrics".to_string()];
108        let _wrapped = with_token_auth_bypass(handler, config, bypass);
109    }
110}