Skip to main content

ironflow_api/
middleware.rs

1//! Middleware for internal route protection and HTTP security hardening.
2
3use axum::Json;
4use axum::extract::Request;
5use axum::http::header::{
6    CONTENT_SECURITY_POLICY, STRICT_TRANSPORT_SECURITY, X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS,
7    X_XSS_PROTECTION,
8};
9use axum::http::{HeaderValue, StatusCode};
10use axum::middleware::Next;
11use axum::response::{IntoResponse, Response};
12use serde_json::json;
13use subtle::ConstantTimeEq;
14
15/// Axum middleware that validates a static worker token.
16///
17/// Extracts `Authorization: Bearer {token}` and compares against the
18/// expected token. Returns 401 if missing or invalid.
19pub async fn worker_token_auth(req: Request, next: Next) -> Response {
20    let expected = req.extensions().get::<WorkerToken>().map(|t| t.0.clone());
21
22    let provided = req
23        .headers()
24        .get("authorization")
25        .and_then(|v| v.to_str().ok())
26        .and_then(|v| v.strip_prefix("Bearer "))
27        .map(|t| t.to_string());
28
29    match (expected, provided) {
30        (Some(expected), Some(provided))
31            if expected.as_bytes().ct_eq(provided.as_bytes()).into() =>
32        {
33            next.run(req).await
34        }
35        _ => (
36            StatusCode::UNAUTHORIZED,
37            Json(json!({
38                "error": {
39                    "code": "INVALID_WORKER_TOKEN",
40                    "message": "Invalid or missing worker token",
41                }
42            })),
43        )
44            .into_response(),
45    }
46}
47
48/// Newtype wrapper for the static worker token, stored in request extensions.
49#[derive(Clone)]
50pub struct WorkerToken(pub String);
51
52/// Middleware that records API request metrics (counter + duration histogram).
53///
54/// Emits `ironflow_api_requests_total` and `ironflow_api_request_duration_seconds`
55/// for every request. Only compiled when the `prometheus` feature is enabled.
56#[cfg(feature = "prometheus")]
57pub async fn request_metrics(req: Request, next: Next) -> Response {
58    use std::time::Instant;
59
60    use ironflow_core::metric_names::{API_REQUEST_DURATION_SECONDS, API_REQUESTS_TOTAL};
61    use metrics::{counter, histogram};
62
63    let method = req.method().to_string();
64    let path = req.uri().path().to_string();
65    let start = Instant::now();
66
67    let resp = next.run(req).await;
68
69    let status = resp.status().as_u16().to_string();
70    let duration = start.elapsed().as_secs_f64();
71
72    counter!(API_REQUESTS_TOTAL, "method" => method.clone(), "path" => path.clone(), "status" => status).increment(1);
73    histogram!(API_REQUEST_DURATION_SECONDS, "method" => method, "path" => path).record(duration);
74
75    resp
76}
77
78/// Middleware that injects standard HTTP security headers on every response.
79///
80/// Headers set:
81/// - `X-Content-Type-Options: nosniff` — prevents MIME-type sniffing
82/// - `X-Frame-Options: DENY` — blocks clickjacking via iframes
83/// - `X-XSS-Protection: 1; mode=block` — legacy XSS filter hint
84/// - `Strict-Transport-Security: max-age=63072000; includeSubDomains` — enforces HTTPS for 2 years
85/// - `Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'`
86pub async fn security_headers(req: Request, next: Next) -> Response {
87    let mut resp = next.run(req).await;
88    let headers = resp.headers_mut();
89
90    headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
91    headers.insert(X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
92    headers.insert(X_XSS_PROTECTION, HeaderValue::from_static("1; mode=block"));
93    headers.insert(
94        STRICT_TRANSPORT_SECURITY,
95        HeaderValue::from_static("max-age=63072000; includeSubDomains"),
96    );
97    headers.insert(
98        CONTENT_SECURITY_POLICY,
99        HeaderValue::from_static(
100            "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'",
101        ),
102    );
103
104    resp
105}
106
107#[cfg(test)]
108mod tests {
109
110    use axum::body::Body;
111    use axum::http::{Request, StatusCode};
112    use http_body_util::BodyExt;
113    use ironflow_core::providers::claude::ClaudeCodeProvider;
114    use ironflow_engine::engine::Engine;
115    use ironflow_engine::notify::Event;
116    use ironflow_store::memory::InMemoryStore;
117    use serde_json::Value as JsonValue;
118    use std::sync::Arc;
119    use tokio::sync::broadcast;
120    use tower::ServiceExt;
121
122    use crate::routes::{RouterConfig, create_router};
123    use crate::state::AppState;
124
125    fn test_state() -> AppState {
126        let store = Arc::new(InMemoryStore::new());
127        let provider = Arc::new(ClaudeCodeProvider::new());
128        let engine = Arc::new(Engine::new(store.clone(), provider));
129        let jwt_config = Arc::new(ironflow_auth::jwt::JwtConfig {
130            secret: "test-secret".to_string(),
131            access_token_ttl_secs: 900,
132            refresh_token_ttl_secs: 604800,
133            cookie_domain: None,
134            cookie_secure: false,
135        });
136        let (event_sender, _) = broadcast::channel::<Event>(1);
137        AppState::new(
138            store,
139            engine,
140            jwt_config,
141            "test-worker-token".to_string(),
142            event_sender,
143        )
144    }
145
146    #[tokio::test]
147    async fn worker_token_valid() {
148        let state = test_state();
149        let app = create_router(state.clone(), RouterConfig::default());
150
151        let req = Request::builder()
152            .uri("/api/v1/internal/runs/next")
153            .header("authorization", "Bearer test-worker-token")
154            .body(Body::empty())
155            .unwrap();
156
157        let resp = app.oneshot(req).await.unwrap();
158        assert_eq!(resp.status(), StatusCode::OK);
159    }
160
161    #[tokio::test]
162    async fn worker_token_missing() {
163        let state = test_state();
164        let app = create_router(state, RouterConfig::default());
165
166        let req = Request::builder()
167            .uri("/api/v1/internal/runs/next")
168            .body(Body::empty())
169            .unwrap();
170
171        let resp = app.oneshot(req).await.unwrap();
172        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
173
174        let body = resp.into_body().collect().await.unwrap().to_bytes();
175        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
176        assert_eq!(json_val["error"]["code"], "INVALID_WORKER_TOKEN");
177    }
178
179    #[tokio::test]
180    async fn worker_token_invalid() {
181        let state = test_state();
182        let app = create_router(state, RouterConfig::default());
183
184        let req = Request::builder()
185            .uri("/api/v1/internal/runs/next")
186            .header("authorization", "Bearer wrong-token")
187            .body(Body::empty())
188            .unwrap();
189
190        let resp = app.oneshot(req).await.unwrap();
191        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
192
193        let body = resp.into_body().collect().await.unwrap().to_bytes();
194        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
195        assert_eq!(json_val["error"]["code"], "INVALID_WORKER_TOKEN");
196    }
197
198    #[tokio::test]
199    async fn security_headers_present() {
200        let state = test_state();
201        let app = create_router(state, RouterConfig::default());
202
203        let req = Request::builder()
204            .uri("/api/v1/health-check")
205            .body(Body::empty())
206            .unwrap();
207
208        let resp = app.oneshot(req).await.unwrap();
209
210        assert_eq!(
211            resp.headers().get("x-content-type-options").unwrap(),
212            "nosniff"
213        );
214        assert_eq!(resp.headers().get("x-frame-options").unwrap(), "DENY");
215        assert_eq!(
216            resp.headers().get("x-xss-protection").unwrap(),
217            "1; mode=block"
218        );
219        assert_eq!(
220            resp.headers().get("strict-transport-security").unwrap(),
221            "max-age=63072000; includeSubDomains"
222        );
223        assert!(
224            resp.headers()
225                .get("content-security-policy")
226                .unwrap()
227                .to_str()
228                .unwrap()
229                .contains("default-src 'self'")
230        );
231    }
232}