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_store::memory::InMemoryStore;
116    use serde_json::Value as JsonValue;
117    use std::sync::Arc;
118    use tower::ServiceExt;
119
120    use crate::routes::create_router;
121    use crate::state::AppState;
122    use ironflow_store::user_store::UserStore;
123
124    fn test_state() -> AppState {
125        let store = Arc::new(InMemoryStore::new());
126        let user_store: Arc<dyn UserStore> = 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        AppState::new(
137            store,
138            user_store,
139            engine,
140            jwt_config,
141            "test-worker-token".to_string(),
142        )
143    }
144
145    #[tokio::test]
146    async fn worker_token_valid() {
147        let state = test_state();
148        let app = create_router(state.clone(), None);
149
150        let req = Request::builder()
151            .uri("/api/v1/internal/runs/next")
152            .header("authorization", "Bearer test-worker-token")
153            .body(Body::empty())
154            .unwrap();
155
156        let resp = app.oneshot(req).await.unwrap();
157        assert_eq!(resp.status(), StatusCode::OK);
158    }
159
160    #[tokio::test]
161    async fn worker_token_missing() {
162        let state = test_state();
163        let app = create_router(state, None);
164
165        let req = Request::builder()
166            .uri("/api/v1/internal/runs/next")
167            .body(Body::empty())
168            .unwrap();
169
170        let resp = app.oneshot(req).await.unwrap();
171        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
172
173        let body = resp.into_body().collect().await.unwrap().to_bytes();
174        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
175        assert_eq!(json_val["error"]["code"], "INVALID_WORKER_TOKEN");
176    }
177
178    #[tokio::test]
179    async fn worker_token_invalid() {
180        let state = test_state();
181        let app = create_router(state, None);
182
183        let req = Request::builder()
184            .uri("/api/v1/internal/runs/next")
185            .header("authorization", "Bearer wrong-token")
186            .body(Body::empty())
187            .unwrap();
188
189        let resp = app.oneshot(req).await.unwrap();
190        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
191
192        let body = resp.into_body().collect().await.unwrap().to_bytes();
193        let json_val: JsonValue = serde_json::from_slice(&body).unwrap();
194        assert_eq!(json_val["error"]["code"], "INVALID_WORKER_TOKEN");
195    }
196
197    #[tokio::test]
198    async fn security_headers_present() {
199        let state = test_state();
200        let app = create_router(state, None);
201
202        let req = Request::builder()
203            .uri("/api/v1/health-check")
204            .body(Body::empty())
205            .unwrap();
206
207        let resp = app.oneshot(req).await.unwrap();
208
209        assert_eq!(
210            resp.headers().get("x-content-type-options").unwrap(),
211            "nosniff"
212        );
213        assert_eq!(resp.headers().get("x-frame-options").unwrap(), "DENY");
214        assert_eq!(
215            resp.headers().get("x-xss-protection").unwrap(),
216            "1; mode=block"
217        );
218        assert_eq!(
219            resp.headers().get("strict-transport-security").unwrap(),
220            "max-age=63072000; includeSubDomains"
221        );
222        assert!(
223            resp.headers()
224                .get("content-security-policy")
225                .unwrap()
226                .to_str()
227                .unwrap()
228                .contains("default-src 'self'")
229        );
230    }
231}