relay-core-http 0.1.1

REST/SSE HTTP API adapter for relay-core: language-agnostic integration boundary for external tools
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
use std::net::SocketAddr;
use std::sync::Arc;

use axum::{
    Router,
    extract::State,
    http::{
        HeaderValue, Method, Request, StatusCode,
        header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, ORIGIN, WWW_AUTHENTICATE},
    },
    middleware::{self, Next},
    response::{IntoResponse, Response},
};
use tower_http::cors::CorsLayer;
use tower_http::trace::TraceLayer;
use relay_core_runtime::CoreState;
use tracing::info;

use crate::routes;

/// Configuration for the HTTP API server.
#[derive(Debug, Clone)]
pub struct HttpApiConfig {
    /// Address to bind (e.g. `127.0.0.1:8082`)
    pub addr: SocketAddr,
    pub bearer_token: Option<String>,
    pub allowed_origins: Vec<HeaderValue>,
}

impl HttpApiConfig {
    pub fn new(port: u16) -> Self {
        Self {
            addr: SocketAddr::from(([127, 0, 0, 1], port)),
            bearer_token: None,
            allowed_origins: Vec::new(),
        }
    }

    pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
        self.bearer_token = Some(token.into());
        self
    }

    pub fn with_allowed_origins(mut self, origins: impl IntoIterator<Item = HeaderValue>) -> Self {
        self.allowed_origins = origins.into_iter().collect();
        self
    }
}

/// HTTP API server handle.
pub struct HttpApiServer {
    config: HttpApiConfig,
    state: Arc<CoreState>,
}

impl HttpApiServer {
    pub fn new(config: HttpApiConfig, state: Arc<CoreState>) -> Self {
        Self { config, state }
    }

    /// Start the server; resolves when the server exits or an error occurs.
    pub async fn run(self) -> Result<(), Box<dyn std::error::Error>> {
        let app = build_router(self.state, Arc::new(self.config.clone()));
        let listener = tokio::net::TcpListener::bind(self.config.addr).await?;
        info!("relay-core HTTP API listening on {}", self.config.addr);
        axum::serve(listener, app).await?;
        Ok(())
    }
}

fn build_router(state: Arc<CoreState>, config: Arc<HttpApiConfig>) -> Router {
    let router = Router::new()
        .merge(routes::version::router())
        .merge(routes::metrics::router(state.clone()))
        .merge(routes::flows::router(state.clone()))
        .merge(routes::rules::router(state.clone()))
        .merge(routes::intercepts::router(state.clone()))
        .merge(routes::events::router(state))
        .route_layer(middleware::from_fn_with_state(config.clone(), require_bearer_token))
        .layer(TraceLayer::new_for_http());

    if config.allowed_origins.is_empty() {
        router
    } else {
        router.layer(
            CorsLayer::new()
                .allow_origin(config.allowed_origins.clone())
                .allow_methods([
                    Method::GET,
                    Method::POST,
                    Method::PUT,
                    Method::DELETE,
                    Method::OPTIONS,
                ])
                .allow_headers([AUTHORIZATION, CONTENT_TYPE, ACCEPT, ORIGIN]),
        )
    }
}

async fn require_bearer_token(
    State(config): State<Arc<HttpApiConfig>>,
    request: Request<axum::body::Body>,
    next: Next,
) -> Response {
    if request.method() == Method::OPTIONS {
        return next.run(request).await;
    }

    let Some(expected_token) = config.bearer_token.as_deref() else {
        return next.run(request).await;
    };

    let expected_value = format!("Bearer {}", expected_token);
    let is_authorized = request
        .headers()
        .get(AUTHORIZATION)
        .and_then(|value| value.to_str().ok())
        .map(|value| value == expected_value)
        .unwrap_or(false);

    if is_authorized {
        return next.run(request).await;
    }

    (
        StatusCode::UNAUTHORIZED,
        [
            (WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")),
            (CONTENT_TYPE, HeaderValue::from_static("application/json")),
        ],
        serde_json::json!({
            "error": "missing_or_invalid_bearer_token"
        })
        .to_string(),
    )
        .into_response()
}

#[cfg(test)]
mod tests {
    use super::{HttpApiConfig, build_router};
    use axum::{
        body::{Body, to_bytes},
        http::{HeaderValue, Method, Request, StatusCode, header::ACCESS_CONTROL_ALLOW_ORIGIN},
    };
    use relay_core_api::flow::Flow;
    use relay_core_api::policy::ProxyPolicy;
    use relay_core_runtime::{CoreState, audit::AuditActor};
    use std::sync::Arc;
    use tokio::time::{Duration, sleep};
    use tower::ServiceExt;
    use serde_json::json;

    fn sample_http_flow(host: &str, path: &str, method: &str, status: u16, ts: i64) -> Flow {
        let flow_id = format!(
            "00000000-0000-0000-0000-{:012}",
            (ts as u64) % 1_000_000_000_000
        );
        let minute = ((ts / 60_000) % 60) as i64;
        let second = ((ts / 1_000) % 60) as i64;
        let millis = (ts % 1_000).abs();
        let start_rfc3339 = format!("2023-11-14T22:{:02}:{:02}.{:03}Z", minute, second, millis);
        serde_json::from_value(json!({
            "id": flow_id,
            "start_time": start_rfc3339,
            "end_time": start_rfc3339,
            "network": {
                "client_ip": "127.0.0.1",
                "client_port": 12000,
                "server_ip": "127.0.0.1",
                "server_port": 8080,
                "protocol": "TCP",
                "tls": false,
                "tls_version": null,
                "sni": null
            },
            "layer": {
                "type": "Http",
                "data": {
                    "request": {
                        "method": method,
                        "url": format!("http://{}{}", host, path),
                        "version": "HTTP/1.1",
                        "headers": [],
                        "cookies": [],
                        "query": [],
                        "body": null
                    },
                    "response": {
                        "status": status,
                        "status_text": "OK",
                        "version": "HTTP/1.1",
                        "headers": [],
                        "cookies": [],
                        "body": null,
                        "timing": {
                            "time_to_first_byte": null,
                            "time_to_last_byte": null
                        }
                    },
                    "error": null
                }
            },
            "tags": []
        }))
        .expect("flow json should deserialize")
    }

    #[tokio::test]
    async fn status_endpoint_is_available_without_auth_by_default() {
        let state = Arc::new(CoreState::new(None).await);
        let app = build_router(state, Arc::new(HttpApiConfig::new(8082)));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/api/v1/status")
                    .method(Method::GET)
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should succeed");

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body should be readable");
        let json: serde_json::Value = serde_json::from_slice(&body).expect("body should be valid json");
        assert_eq!(json["phase"], "created");
        assert_eq!(json["running"], false);
        assert!(json.get("started_at_ms").is_none());
    }

    #[tokio::test]
    async fn intercepts_endpoint_uses_shared_snapshot_shape() {
        let state = Arc::new(CoreState::new(None).await);
        let app = build_router(state, Arc::new(HttpApiConfig::new(8082)));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/api/v1/intercepts")
                    .method(Method::GET)
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should succeed");

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body should be readable");
        let json: serde_json::Value = serde_json::from_slice(&body).expect("body should be valid json");
        assert_eq!(json["pending_count"], 0);
        assert_eq!(json["ws_pending_count"], 0);
    }

    #[tokio::test]
    async fn audit_endpoint_uses_shared_snapshot_shape() {
        let state = Arc::new(CoreState::new(None).await);
        state.update_policy_from(
            AuditActor::Http,
            "policy".to_string(),
            ProxyPolicy {
                transparent_enabled: true,
                ..Default::default()
            },
        );
        let _ = state
            .resolve_intercept_with_modifications_from(
                AuditActor::Probe,
                "missing-flow:request".to_string(),
                "drop",
                None,
            )
            .await;
        let app = build_router(state, Arc::new(HttpApiConfig::new(8082)));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/api/v1/audit?actor=http&kind=policy_updated&outcome=success&limit=1")
                    .method(Method::GET)
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should succeed");

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body should be readable");
        let json: serde_json::Value = serde_json::from_slice(&body).expect("body should be valid json");
        assert!(json["events"].is_array());
        assert_eq!(json["events"].as_array().map(|v| v.len()), Some(1));
        assert_eq!(json["events"][0]["actor"], "http");
        assert_eq!(json["events"][0]["kind"], "policy_updated");
        assert_eq!(json["events"][0]["outcome"], "success");
    }

    #[tokio::test]
    async fn prometheus_metrics_endpoint_returns_text_format() {
        let state = Arc::new(CoreState::new(None).await);
        let app = build_router(state, Arc::new(HttpApiConfig::new(8082)));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/api/v1/metrics/prometheus")
                    .method(Method::GET)
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should succeed");

        assert_eq!(response.status(), StatusCode::OK);
        let content_type = response
            .headers()
            .get(axum::http::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or_default();
        assert_eq!(content_type, "text/plain; version=0.0.4; charset=utf-8");
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body should be readable");
        let text = String::from_utf8(body.to_vec()).expect("prometheus body should be utf-8");
        assert!(text.contains("relay_core_flows_total "));
        assert!(text.contains("relay_core_audit_events_total "));
    }

    #[tokio::test]
    async fn flows_endpoint_returns_pagination_metadata() {
        let state = Arc::new(CoreState::new(None).await);
        let flow_a = sample_http_flow("api.example.com", "/a", "GET", 200, 1_700_000_001_000);
        let flow_b = sample_http_flow("api.example.com", "/b", "POST", 201, 1_700_000_002_000);
        let flow_c = sample_http_flow("api.example.com", "/c", "GET", 500, 1_700_000_003_000);
        let flow_b_id = flow_b.id.to_string();
        state.upsert_flow(Box::new(flow_a));
        state.upsert_flow(Box::new(flow_b));
        state.upsert_flow(Box::new(flow_c));
        sleep(Duration::from_millis(30)).await;

        let app = build_router(state, Arc::new(HttpApiConfig::new(8082)));
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/api/v1/flows?host=api.example.com&limit=1&offset=1")
                    .method(Method::GET)
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should succeed");

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body should be readable");
        let json: serde_json::Value = serde_json::from_slice(&body).expect("body should be valid json");
        assert_eq!(json["returned"], 1);
        assert_eq!(json["limit"], 1);
        assert_eq!(json["offset"], 1);
        assert_eq!(json["items"].as_array().map(|v| v.len()), Some(1));
        assert_eq!(json["items"][0]["id"], flow_b_id);
    }

    #[tokio::test]
    async fn status_endpoint_requires_bearer_token_when_configured() {
        let state = Arc::new(CoreState::new(None).await);
        let app = build_router(
            state,
            Arc::new(HttpApiConfig::new(8082).with_bearer_token("secret-token")),
        );

        let unauthorized = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/api/v1/status")
                    .method(Method::GET)
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should succeed");
        assert_eq!(unauthorized.status(), StatusCode::UNAUTHORIZED);

        let authorized = app
            .oneshot(
                Request::builder()
                    .uri("/api/v1/status")
                    .method(Method::GET)
                    .header("Authorization", "Bearer secret-token")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should succeed");
        assert_eq!(authorized.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn cors_is_not_open_by_default() {
        let state = Arc::new(CoreState::new(None).await);
        let app = build_router(state, Arc::new(HttpApiConfig::new(8082)));

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/api/v1/status")
                    .method(Method::GET)
                    .header("Origin", "https://example.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should succeed");

        assert!(response.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN).is_none());
    }

    #[tokio::test]
    async fn cors_allows_explicit_origin_only() {
        let state = Arc::new(CoreState::new(None).await);
        let app = build_router(
            state,
            Arc::new(
                HttpApiConfig::new(8082).with_allowed_origins([HeaderValue::from_static(
                    "https://allowed.example",
                )]),
            ),
        );

        let allowed = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/api/v1/status")
                    .method(Method::GET)
                    .header("Origin", "https://allowed.example")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should succeed");
        assert_eq!(
            allowed.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN),
            Some(&HeaderValue::from_static("https://allowed.example"))
        );

        let denied = app
            .oneshot(
                Request::builder()
                    .uri("/api/v1/status")
                    .method(Method::GET)
                    .header("Origin", "https://denied.example")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should succeed");
        assert!(denied.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN).is_none());
    }
}