rust-webx-host 0.3.0

rust-webx HTTP layer: Host builder, middleware pipeline, Trie-based router, hyper integration
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Integration tests for LRWF host.
//!
//! These tests spin up a minimal LRWF host and verify full HTTP cycles.

use std::net::TcpListener;
use std::sync::Arc;

async fn spawn_test_host(port: u16) {
    spawn_test_host_with(port, |b| b).await;
}

async fn spawn_test_host_with<F>(port: u16, configure: F)
where
    F: FnOnce(rust_webx_host::server::HostBuilder) -> rust_webx_host::server::HostBuilder,
{
    let addr = format!("127.0.0.1:{}", port);
    let builder = rust_webx_host::server::Host::builder()
        .mode(rust_webx_core::mode::AppMode::Development)
        .no_spa();
    let host = configure(builder).build();
    tokio::spawn(async move { host.run_at(&addr).await.unwrap() });
    tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
}

fn find_free_port() -> u16 {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    listener.local_addr().unwrap().port()
}

// ---------------------------------------------------------------------------
// 404 routing
// ---------------------------------------------------------------------------

#[tokio::test]
async fn integration_404_for_unregistered_route() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let client = reqwest::Client::new();
    let resp = client
        .get(format!("http://127.0.0.1:{}/nonexistent", port))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 404);
    let body: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(body["status"], 404);
    assert_eq!(body["title"], "Not Found");
    assert!(body["detail"].as_str().unwrap().contains("Not Found"));
}

#[tokio::test]
async fn integration_404_returns_problem_json() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let resp = reqwest::get(format!("http://127.0.0.1:{}/nope", port))
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 404);
    let content_type = resp
        .headers()
        .get("content-type")
        .unwrap()
        .to_str()
        .unwrap();
    assert!(
        content_type.contains("application/problem+json"),
        "expected application/problem+json, got {}",
        content_type
    );
    let body: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(body["status"], 404);
    assert_eq!(body["title"], "Not Found");
}

// ---------------------------------------------------------------------------
// OpenAPI endpoints
// ---------------------------------------------------------------------------

#[tokio::test]
async fn integration_health_check_openapi_available() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let client = reqwest::Client::new();
    let resp = client
        .get(format!("http://127.0.0.1:{}/api/openapi.html", port))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 200);
    let content_type = resp
        .headers()
        .get("content-type")
        .unwrap()
        .to_str()
        .unwrap();
    assert!(content_type.contains("text/html"));
}

#[tokio::test]
async fn integration_openapi_json_available() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let client = reqwest::Client::new();
    let resp = client
        .get(format!("http://127.0.0.1:{}/api/openapi.json", port))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 200);
    let body: serde_json::Value = resp.json().await.unwrap();
    assert!(body.get("openapi").is_some());
    assert!(body.get("info").is_some());
}

// ---------------------------------------------------------------------------
// Health endpoints (RFC 8407)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn integration_health_returns_pass_with_no_probes() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let resp = reqwest::get(format!("http://127.0.0.1:{}/health", port))
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 200);
    let content_type = resp
        .headers()
        .get("content-type")
        .unwrap()
        .to_str()
        .unwrap();
    assert!(
        content_type.contains("application/health+json"),
        "expected application/health+json, got {}",
        content_type
    );
    let body: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(body["status"], "pass");
    assert!(body.get("checks").is_none(), "empty registry should omit checks");
}

#[tokio::test]
async fn integration_healthz_alias_matches_health() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let client = reqwest::Client::new();
    let health_resp = client
        .get(format!("http://127.0.0.1:{}/health", port))
        .send()
        .await
        .unwrap();
    let healthz_resp = client
        .get(format!("http://127.0.0.1:{}/healthz", port))
        .send()
        .await
        .unwrap();

    assert_eq!(health_resp.status(), healthz_resp.status());
    let health_body: serde_json::Value = health_resp.json().await.unwrap();
    let healthz_body: serde_json::Value = healthz_resp.json().await.unwrap();
    assert_eq!(health_body, healthz_body);
}

#[tokio::test]
async fn integration_health_live_returns_pass() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let resp = reqwest::get(format!("http://127.0.0.1:{}/health/live", port))
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 200);
    let body: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(body["status"], "pass");
}

#[tokio::test]
async fn integration_health_ready_matches_health() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let client = reqwest::Client::new();
    let health_resp = client
        .get(format!("http://127.0.0.1:{}/health", port))
        .send()
        .await
        .unwrap();
    let ready_resp = client
        .get(format!("http://127.0.0.1:{}/health/ready", port))
        .send()
        .await
        .unwrap();

    assert_eq!(health_resp.status(), ready_resp.status());
    let health_body: serde_json::Value = health_resp.json().await.unwrap();
    let ready_body: serde_json::Value = ready_resp.json().await.unwrap();
    assert_eq!(health_body, ready_body);
}

#[tokio::test]
async fn integration_health_with_failing_probe_returns_fail() {
    let port = find_free_port();
    spawn_test_host_with(port, |b| {
        b.add_health_check("db", || {
            rust_webx_host::health::HealthStatus::fail("db unreachable")
        })
    })
    .await;

    let resp = reqwest::get(format!("http://127.0.0.1:{}/health", port))
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 503);
    let body: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(body["status"], "fail");
    let checks = body["checks"].as_array().expect("checks array present");
    assert_eq!(checks.len(), 1);
    assert_eq!(checks[0]["name"], "db");
    assert_eq!(checks[0]["status"], "fail");
    assert_eq!(checks[0]["detail"], "db unreachable");
}

#[tokio::test]
async fn integration_health_probe_evaluated_at_request_time() {
    use std::sync::atomic::{AtomicBool, Ordering};

    let healthy = Arc::new(AtomicBool::new(true));
    let flag = Arc::clone(&healthy);
    let port = find_free_port();
    spawn_test_host_with(port, move |b| {
        b.add_health_check("db", move || {
            if flag.load(Ordering::Relaxed) {
                rust_webx_host::health::HealthStatus::pass()
            } else {
                rust_webx_host::health::HealthStatus::fail("db down")
            }
        })
    })
    .await;

    let url = format!("http://127.0.0.1:{}/health", port);
    let ok = reqwest::get(&url).await.unwrap();
    assert_eq!(ok.status().as_u16(), 200);

    healthy.store(false, Ordering::Relaxed);
    let fail = reqwest::get(&url).await.unwrap();
    assert_eq!(fail.status().as_u16(), 503);
    let body: serde_json::Value = fail.json().await.unwrap();
    assert_eq!(body["status"], "fail");
}

// ---------------------------------------------------------------------------
// CORS preflight
// ---------------------------------------------------------------------------

#[tokio::test]
async fn integration_cors_preflight_returns_204() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let client = reqwest::Client::new();
    let resp = client
        .request(
            reqwest::Method::OPTIONS,
            format!("http://127.0.0.1:{}/api/openapi.json", port),
        )
        .header("origin", "https://example.com")
        .header("access-control-request-method", "GET")
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 204);
    let headers = resp.headers();
    assert!(
        headers.contains_key("access-control-allow-origin"),
        "missing access-control-allow-origin"
    );
    assert!(
        headers.contains_key("access-control-allow-methods"),
        "missing access-control-allow-methods"
    );
    assert!(
        headers.contains_key("access-control-allow-headers"),
        "missing access-control-allow-headers"
    );
}

#[tokio::test]
async fn integration_cors_actual_request_has_headers() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let resp = reqwest::Client::new()
        .get(format!("http://127.0.0.1:{}/health", port))
        .header("origin", "https://example.com")
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 200);
    assert!(
        resp.headers().contains_key("access-control-allow-origin"),
        "missing access-control-allow-origin on actual request"
    );
}

// ---------------------------------------------------------------------------
// Default security & observability middleware
// ---------------------------------------------------------------------------

#[tokio::test]
async fn integration_default_security_headers_present() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let resp = reqwest::get(format!("http://127.0.0.1:{}/health", port))
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 200);
    let headers = resp.headers();
    assert_eq!(headers.get("x-content-type-options").unwrap(), "nosniff");
    assert_eq!(headers.get("x-frame-options").unwrap(), "DENY");
    assert_eq!(
        headers.get("referrer-policy").unwrap(),
        "strict-origin-when-cross-origin"
    );
}

#[tokio::test]
async fn integration_default_request_id_present() {
    let port = find_free_port();
    spawn_test_host(port).await;

    let resp = reqwest::get(format!("http://127.0.0.1:{}/health", port))
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 200);
    let request_id = resp
        .headers()
        .get("x-request-id")
        .expect("x-request-id header present by default");
    assert!(!request_id.is_empty());
}

// ---------------------------------------------------------------------------
// use_middleware_with API + RateLimit short-circuit
// ---------------------------------------------------------------------------

#[tokio::test]
async fn integration_rate_limit_returns_429_when_exceeded() {
    let port = find_free_port();
    spawn_test_host_with(port, |b| {
        b.use_middleware_with(|| {
            Arc::new(rust_webx_host::rate_limit::RateLimitMiddleware::new(1.0, 2))
                as Arc<dyn rust_webx_core::middleware::IMiddleware>
        })
    })
    .await;

    let client = reqwest::Client::new();
    // First 2 requests: allowed (burst=2)
    let r1 = client
        .get(format!("http://127.0.0.1:{}/health", port))
        .send()
        .await
        .unwrap();
    let r2 = client
        .get(format!("http://127.0.0.1:{}/health", port))
        .send()
        .await
        .unwrap();
    assert_eq!(r1.status().as_u16(), 200);
    assert_eq!(r2.status().as_u16(), 200);

    // Third request immediately: should be rate-limited (429)
    let r3 = client
        .get(format!("http://127.0.0.1:{}/health", port))
        .send()
        .await
        .unwrap();
    assert_eq!(r3.status().as_u16(), 429);
    let ct = r3
        .headers()
        .get("content-type")
        .unwrap()
        .to_str()
        .unwrap();
    assert!(ct.contains("application/problem+json"));
    let body: serde_json::Value = r3.json().await.unwrap();
    assert_eq!(body["status"], 429);
    assert_eq!(body["title"], "Too Many Requests");
}

#[tokio::test]
async fn integration_metrics_endpoint_when_enabled() {
    let port = find_free_port();
    spawn_test_host_with(port, |b| {
        b.configure(|app| {
            app.useOptions(|o| o.metrics.enabled = true);
        })
    })
    .await;

    let resp = reqwest::get(format!("http://127.0.0.1:{}/metrics", port))
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 200);
    let ct = resp
        .headers()
        .get("content-type")
        .unwrap()
        .to_str()
        .unwrap();
    assert!(ct.contains("text/plain"));
    let body = resp.text().await.unwrap();
    assert!(body.contains("http_requests_total"));
}

#[tokio::test]
async fn integration_use_middleware_with_runs_in_pipeline() {
    use rust_webx_core::http::IHttpContext;
    use rust_webx_core::middleware::IMiddleware;
    use std::ops::ControlFlow;

    struct HeaderTagMiddleware;
    #[async_trait::async_trait]
    impl IMiddleware for HeaderTagMiddleware {
        async fn invoke(
            &self,
            ctx: &mut dyn IHttpContext,
        ) -> rust_webx_core::error::Result<ControlFlow<()>> {
            ctx.response_mut().set_header("x-tagged", "true");
            Ok(ControlFlow::Continue(()))
        }
    }

    let port = find_free_port();
    spawn_test_host_with(port, |b| {
        b.use_middleware_with(|| Arc::new(HeaderTagMiddleware) as Arc<dyn IMiddleware>)
    })
    .await;

    let resp = reqwest::get(format!("http://127.0.0.1:{}/health", port))
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 200);
    assert_eq!(resp.headers().get("x-tagged").unwrap(), "true");
}

// ---------------------------------------------------------------------------
// Compression middleware
// ---------------------------------------------------------------------------

#[tokio::test]
async fn integration_compression_gzips_large_response() {
    use rust_webx_host::compression::{CompressionConfig, CompressionMiddleware};

    let port = find_free_port();
    spawn_test_host_with(port, |b| {
        b.use_middleware_with(|| {
            Arc::new(CompressionMiddleware::with_config(
                CompressionConfig::default().min_size(10),
            )) as Arc<dyn rust_webx_core::middleware::IMiddleware>
        })
    })
    .await;

    // Disable reqwest's auto-decompression so we can verify content-encoding header.
    let client = reqwest::Client::builder()
        .no_gzip()
        .build()
        .unwrap();

    let resp = client
        .get(format!("http://127.0.0.1:{}/api/openapi.json", port))
        .header("accept-encoding", "gzip")
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 200);
    assert_eq!(
        resp.headers().get("content-encoding").unwrap(),
        "gzip",
        "large response should be gzipped"
    );

    // Manually decompress to verify the body is valid JSON.
    use std::io::Read;
    let compressed = resp.bytes().await.unwrap();
    let mut decoder = flate2::read::GzDecoder::new(&compressed[..]);
    let mut decompressed = String::new();
    decoder.read_to_string(&mut decompressed).unwrap();
    let body: serde_json::Value = serde_json::from_str(&decompressed).unwrap();
    assert!(body.get("openapi").is_some());
}

#[tokio::test]
async fn integration_compression_skips_small_response() {
    let port = find_free_port();
    spawn_test_host_with(port, |b| {
        b.use_middleware::<rust_webx_host::compression::CompressionMiddleware>()
    })
    .await;

    let resp = reqwest::Client::new()
        .get(format!("http://127.0.0.1:{}/health/live", port))
        .header("accept-encoding", "gzip")
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 200);
    assert!(
        resp.headers().get("content-encoding").is_none(),
        "small response should not be compressed"
    );
}

#[tokio::test]
async fn integration_compression_skips_without_accept_encoding() {
    let port = find_free_port();
    spawn_test_host_with(port, |b| {
        b.use_middleware::<rust_webx_host::compression::CompressionMiddleware>()
    })
    .await;

    let resp = reqwest::Client::new()
        .get(format!("http://127.0.0.1:{}/api/openapi.json", port))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status().as_u16(), 200);
    assert!(
        resp.headers().get("content-encoding").is_none(),
        "should not compress without accept-encoding"
    );
}