foxy-io 0.3.12

A configuration-driven and hyper-extensible HTTP proxy library
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Tests for the mocking infrastructure

use foxy::Foxy;
use serde_json::json;
use serial_test::serial;
use std::time::Duration;

mod common;
mod mocks;

use common::{TestConfigProvider, TestRoute, init_test_logging};
use mocks::upstream_servers::{MockServerPresets, MockUpstreamBuilder};

#[tokio::test]
#[serial]
async fn test_mock_upstream_json_endpoint() {
    init_test_logging();

    let mock_upstream = MockUpstreamBuilder::new().await;
    mock_upstream
        .with_json_endpoint(
            "/api/data",
            200,
            json!({"message": "Hello from mock", "data": [1, 2, 3]}),
        )
        .await;

    let config = TestConfigProvider::new("mock_test")
        .with_value("server.port", 8080)
        .with_routes(vec![
            TestRoute::new(&mock_upstream.uri()).with_path("/api/*"),
        ]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();
    let response = client
        .get("http://127.0.0.1:8080/api/data")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response.status(), 200);

    let body: serde_json::Value = response.json().await.expect("Failed to parse JSON");
    assert_eq!(body["message"], "Hello from mock");
    assert_eq!(body["data"].as_array().unwrap().len(), 3);

    server_handle.abort();
}

#[tokio::test]
#[serial]
async fn test_mock_upstream_header_echo() {
    init_test_logging();

    let mock_upstream = MockUpstreamBuilder::new().await;
    mock_upstream.with_header_echo_endpoint("/echo").await;

    let config = TestConfigProvider::new("header_echo_test")
        .with_value("server.port", 8080)
        .with_routes(vec![
            TestRoute::new(&mock_upstream.uri()).with_path("/echo"),
        ]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();
    let response = client
        .get("http://127.0.0.1:8080/echo")
        .header("x-test-header", "test-value")
        .header("user-agent", "test-client")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response.status(), 200);

    let body: serde_json::Value = response.json().await.expect("Failed to parse JSON");
    let headers = body["headers"].as_object().unwrap();

    assert!(headers.contains_key("x-test-header"));
    assert!(headers.contains_key("user-agent"));

    server_handle.abort();
}

#[tokio::test]
#[serial]
async fn test_mock_upstream_header_requirement() {
    init_test_logging();

    let mock_upstream = MockUpstreamBuilder::new().await;
    mock_upstream
        .with_header_requirement(
            "/protected",
            "authorization",
            "Bearer secret-token",
            json!({"access": "granted"}),
        )
        .await;

    let config = TestConfigProvider::new("auth_test")
        .with_value("server.port", 8080)
        .with_routes(vec![
            TestRoute::new(&mock_upstream.uri()).with_path("/protected"),
        ]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();

    // Test without required header - should fail
    let response = client
        .get("http://127.0.0.1:8080/protected")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response.status(), 401);

    // Test with required header - should succeed
    let response = client
        .get("http://127.0.0.1:8080/protected")
        .header("authorization", "Bearer secret-token")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response.status(), 200);

    let body: serde_json::Value = response.json().await.expect("Failed to parse JSON");
    assert_eq!(body["access"], "granted");

    server_handle.abort();
}

#[tokio::test]
#[serial]
async fn test_mock_upstream_slow_endpoint() {
    init_test_logging();

    let mock_upstream = MockUpstreamBuilder::new().await;
    mock_upstream
        .with_slow_endpoint(
            "/slow",
            Duration::from_millis(500),
            json!({"message": "This was slow"}),
        )
        .await;

    let config = TestConfigProvider::new("slow_test")
        .with_value("server.port", 8080)
        .with_routes(vec![
            TestRoute::new(&mock_upstream.uri()).with_path("/slow"),
        ]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let start = std::time::Instant::now();

    let client = reqwest::Client::new();
    let response = client
        .get("http://127.0.0.1:8080/slow")
        .send()
        .await
        .expect("Request failed");

    let elapsed = start.elapsed();

    assert_eq!(response.status(), 200);
    assert!(elapsed >= Duration::from_millis(400)); // Account for some variance

    let body: serde_json::Value = response.json().await.expect("Failed to parse JSON");
    assert_eq!(body["message"], "This was slow");

    server_handle.abort();
}

#[tokio::test]
#[serial]
async fn test_mock_upstream_flaky_endpoint() {
    init_test_logging();

    let mock_upstream = MockUpstreamBuilder::new().await;
    mock_upstream.with_flaky_endpoint("/flaky").await;

    let config = TestConfigProvider::new("flaky_test")
        .with_value("server.port", 8080)
        .with_routes(vec![
            TestRoute::new(&mock_upstream.uri()).with_path("/flaky"),
        ]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();

    // First request should fail
    let response1 = client
        .get("http://127.0.0.1:8080/flaky")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response1.status(), 500);

    // Second request should succeed
    let response2 = client
        .get("http://127.0.0.1:8080/flaky")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response2.status(), 200);

    let body: serde_json::Value = response2.json().await.expect("Failed to parse JSON");
    assert_eq!(body["status"], "success");

    server_handle.abort();
}

#[tokio::test]
#[serial]
async fn test_mock_server_presets_rest_api() {
    init_test_logging();

    let mock_upstream = MockServerPresets::rest_api().await;

    let config = TestConfigProvider::new("rest_api_test")
        .with_value("server.port", 8080)
        .with_routes(vec![TestRoute::new(&mock_upstream.uri()).with_path("/*")]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();

    // Test GET /users
    let response = client
        .get("http://127.0.0.1:8080/users")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response.status(), 200);

    let users: serde_json::Value = response.json().await.expect("Failed to parse JSON");
    assert!(users.is_array());
    assert_eq!(users.as_array().unwrap().len(), 2);

    // Test GET /users/1
    let response = client
        .get("http://127.0.0.1:8080/users/1")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response.status(), 200);

    let user: serde_json::Value = response.json().await.expect("Failed to parse JSON");
    assert_eq!(user["id"], 1);
    assert_eq!(user["name"], "Alice");

    server_handle.abort();
}

#[tokio::test]
#[serial]
async fn test_mock_server_presets_auth_server() {
    init_test_logging();

    let mock_upstream = MockServerPresets::auth_server().await;

    let config = TestConfigProvider::new("auth_server_test")
        .with_value("server.port", 8080)
        .with_routes(vec![TestRoute::new(&mock_upstream.uri()).with_path("/*")]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();

    // Test login
    let login_response = client
        .post("http://127.0.0.1:8080/login")
        .json(&json!({"username": "admin", "password": "secret"}))
        .send()
        .await
        .expect("Login request failed");

    assert_eq!(login_response.status(), 200);

    let login_body: serde_json::Value = login_response.json().await.expect("Failed to parse JSON");
    assert_eq!(login_body["token"], "valid-token");

    // Test protected endpoint with token
    let protected_response = client
        .get("http://127.0.0.1:8080/protected")
        .header("authorization", "Bearer valid-token")
        .send()
        .await
        .expect("Protected request failed");

    assert_eq!(protected_response.status(), 200);

    let protected_body: serde_json::Value = protected_response
        .json()
        .await
        .expect("Failed to parse JSON");
    assert_eq!(protected_body["message"], "Access granted");

    server_handle.abort();
}

#[tokio::test]
#[serial]
async fn test_mock_server_presets_error_server() {
    init_test_logging();

    let mock_upstream = MockServerPresets::error_server().await;

    let config = TestConfigProvider::new("error_server_test")
        .with_value("server.port", 8080)
        .with_routes(vec![TestRoute::new(&mock_upstream.uri()).with_path("/*")]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();

    // Test various HTTP status codes
    let status_codes = [400, 401, 403, 404, 429, 500, 502, 503];

    for status in status_codes {
        let response = client
            .get(format!("http://127.0.0.1:8080/status/{status}"))
            .send()
            .await
            .expect("Request failed");

        assert_eq!(response.status(), status);
        let body: serde_json::Value = response.json().await.expect("Failed to parse JSON");

        if (400..500).contains(&status) {
            assert_eq!(body["error"], "client error");
        } else if status >= 500 {
            assert_eq!(body["error"], "server error");
        }
        assert_eq!(body["code"], status);
    }

    // Test slow endpoint (2 second delay)
    let start_time = std::time::Instant::now();
    let slow_response = client
        .get("http://127.0.0.1:8080/slow")
        .send()
        .await
        .expect("Slow request failed");
    let elapsed = start_time.elapsed();

    assert_eq!(slow_response.status(), 200);
    assert!(
        elapsed.as_secs() >= 2,
        "Slow endpoint should take at least 2 seconds"
    );

    let slow_body: serde_json::Value = slow_response.json().await.expect("Failed to parse JSON");
    assert_eq!(slow_body["message"], "This was slow");

    // Test flaky endpoint (should fail first, then succeed)
    let flaky_response1 = client
        .get("http://127.0.0.1:8080/flaky")
        .send()
        .await
        .expect("Flaky request 1 failed");
    assert_eq!(flaky_response1.status(), 500);

    let flaky_response2 = client
        .get("http://127.0.0.1:8080/flaky")
        .send()
        .await
        .expect("Flaky request 2 failed");
    assert_eq!(flaky_response2.status(), 200);

    let flaky_body: serde_json::Value = flaky_response2.json().await.expect("Failed to parse JSON");
    assert_eq!(flaky_body["status"], "success");
    assert_eq!(flaky_body["attempt"], "retry");

    server_handle.abort();
}

#[tokio::test]
#[serial]
async fn test_mock_upstream_text_endpoint() {
    init_test_logging();

    let mock_upstream = MockUpstreamBuilder::new().await;
    mock_upstream
        .with_text_endpoint("GET", "/text", 200, "Hello, World!")
        .await;

    let config = TestConfigProvider::new("text_endpoint_test")
        .with_value("server.port", 8080)
        .with_routes(vec![TestRoute::new(&mock_upstream.uri()).with_path("/*")]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();

    let response = client
        .get("http://127.0.0.1:8080/text")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response.status(), 200);
    assert_eq!(
        response.headers().get("content-type").unwrap(),
        "text/plain"
    );

    let text = response.text().await.expect("Failed to get text");
    assert_eq!(text, "Hello, World!");

    server_handle.abort();
}

#[tokio::test]
#[serial]
async fn test_mock_upstream_query_requirement() {
    init_test_logging();

    let mock_upstream = MockUpstreamBuilder::new().await;
    mock_upstream
        .with_query_requirement(
            "/search",
            "q",
            "test",
            json!({"results": ["item1", "item2"]}),
        )
        .await;

    let config = TestConfigProvider::new("query_requirement_test")
        .with_value("server.port", 8080)
        .with_routes(vec![TestRoute::new(&mock_upstream.uri()).with_path("/*")]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();

    // Test without required query parameter first (should fail)
    let response = client
        .get("http://127.0.0.1:8080/search")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response.status(), 400);
    let body: serde_json::Value = response.json().await.expect("Failed to parse JSON");
    assert_eq!(body["error"], "Missing required query parameter: q");

    // Test with correct query parameter (should succeed)
    let response = client
        .get("http://127.0.0.1:8080/search?q=test")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response.status(), 200);
    let body: serde_json::Value = response.json().await.expect("Failed to parse JSON");
    assert_eq!(body["results"].as_array().unwrap().len(), 2);

    server_handle.abort();
}

#[tokio::test]
#[serial]
async fn test_mock_upstream_large_response() {
    init_test_logging();

    let mock_upstream = MockUpstreamBuilder::new().await;
    mock_upstream
        .with_large_response_endpoint("/large", 10)
        .await; // 10KB response

    let config = TestConfigProvider::new("large_response_test")
        .with_value("server.port", 8080)
        .with_routes(vec![TestRoute::new(&mock_upstream.uri()).with_path("/*")]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();

    let response = client
        .get("http://127.0.0.1:8080/large")
        .send()
        .await
        .expect("Request failed");

    assert_eq!(response.status(), 200);

    let body: serde_json::Value = response.json().await.expect("Failed to parse JSON");
    assert_eq!(body["size_kb"], 10);

    // Verify the data field contains the expected amount of data
    let data_str = body["data"].as_str().expect("Data should be a string");
    assert_eq!(data_str.len(), 10 * 1024); // 10KB
    assert!(data_str.chars().all(|c| c == 'x')); // All 'x' characters

    server_handle.abort();
}

#[tokio::test]
#[serial]
async fn test_mock_upstream_cors_endpoint() {
    init_test_logging();

    let mock_upstream = MockUpstreamBuilder::new().await;
    mock_upstream
        .with_cors_endpoint("/api/data", json!({"message": "CORS enabled"}))
        .await;

    let config = TestConfigProvider::new("cors_test")
        .with_value("server.port", 8080)
        .with_routes(vec![TestRoute::new(&mock_upstream.uri()).with_path("/*")]);

    let foxy = Foxy::loader()
        .with_provider(config)
        .build()
        .await
        .expect("Failed to build Foxy instance");

    let server_handle = tokio::spawn(async move { foxy.start().await });

    tokio::time::sleep(Duration::from_millis(100)).await;

    let client = reqwest::Client::new();

    // Test OPTIONS preflight request
    let options_response = client
        .request(reqwest::Method::OPTIONS, "http://127.0.0.1:8080/api/data")
        .send()
        .await
        .expect("OPTIONS request failed");

    assert_eq!(options_response.status(), 200);
    assert_eq!(
        options_response
            .headers()
            .get("access-control-allow-origin")
            .unwrap(),
        "*"
    );
    assert_eq!(
        options_response
            .headers()
            .get("access-control-allow-methods")
            .unwrap(),
        "GET, POST, PUT, DELETE, OPTIONS"
    );

    // Test actual GET request with CORS headers
    let get_response = client
        .get("http://127.0.0.1:8080/api/data")
        .send()
        .await
        .expect("GET request failed");

    assert_eq!(get_response.status(), 200);
    assert_eq!(
        get_response
            .headers()
            .get("access-control-allow-origin")
            .unwrap(),
        "*"
    );

    let body: serde_json::Value = get_response.json().await.expect("Failed to parse JSON");
    assert_eq!(body["message"], "CORS enabled");

    server_handle.abort();
}