jokoway 0.1.0-rc.1

Jokoway is a high-performance API Gateway built on Pingora (Rust) with dead-simple YAML configs.
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
use jokoway::config::models::{
    ApiSettings, BasicAuth, JokowayConfig, RateLimit, Route, Service, ServiceProtocol, Upstream,
    UpstreamServer,
};
use jokoway::extensions::api::{
    AddServiceRequest, AddUpstreamRequest, RemoveServiceRequest, RemoveUpstreamRequest,
    ServiceListResponse, SuccessResponse, UpstreamListResponse,
};
use jokoway::server::app::App;
use pingora::server::configuration::Opt;
use reqwest::Client;
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::time::sleep;

mod common;
use common::start_http_mock;
use wiremock::matchers::{method, path};
use wiremock::{Mock, ResponseTemplate};

// Helper to get a random port
async fn get_random_port() -> u16 {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    listener.local_addr().unwrap().port()
}

// Helper to start the app with specific API settings
async fn start_app_with_api(api_settings: ApiSettings) -> u16 {
    let port = get_random_port().await;
    let mut api_settings = api_settings;

    // Override listen address to use the random port
    api_settings.listen = format!("127.0.0.1:{}", port);

    let config = JokowayConfig {
        http_listen: "127.0.0.1:0".to_string(), // Disable HTTP for this test or use random
        api: Some(api_settings),
        ..Default::default()
    };

    let app = App::new(config, None, Opt::default(), vec![]);

    std::thread::spawn(move || {
        if let Err(e) = app.run() {
            eprintln!("App failed: {:?}", e);
        }
    });

    // Wait for server to start
    sleep(Duration::from_millis(500)).await;
    port
}

#[tokio::test]
async fn test_api_basic_auth() {
    let _ = env_logger::try_init();

    let api_settings = ApiSettings {
        basic_auth: Some(vec![
            BasicAuth {
                username: "admin".to_string(),
                password: "secret".to_string(),
            },
            BasicAuth {
                username: "ops".to_string(),
                password: "hunter2".to_string(),
            },
        ]),
        ..Default::default()
    };

    let port = start_app_with_api(api_settings).await;
    let base_url = format!("http://127.0.0.1:{}", port);
    let client = Client::new();

    // 1. Test without auth - should fail
    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);

    // 2. Test with incorrect auth - should fail
    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .basic_auth("admin", Some("wrong"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);

    // 3. Test with correct auth - should succeed
    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .basic_auth("admin", Some("secret"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // 4. Test with another correct auth - should succeed
    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .basic_auth("ops", Some("hunter2"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
}

#[tokio::test]
async fn test_api_api_keys() {
    let _ = env_logger::try_init();

    let api_settings = ApiSettings {
        api_keys: Some(vec!["key-1".to_string(), "key-2".to_string()]),
        ..Default::default()
    };

    let port = start_app_with_api(api_settings).await;
    let base_url = format!("http://127.0.0.1:{}", port);
    let client = Client::new();

    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);

    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .header("X-API-Key", "wrong")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);

    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .header("X-API-Key", "key-1")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .header("Authorization", "Bearer wrong")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);

    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .header("Authorization", "Bearer key-2")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
}

#[tokio::test]
async fn test_api_auth_basic_or_api_key() {
    let _ = env_logger::try_init();

    let api_settings = ApiSettings {
        basic_auth: Some(vec![BasicAuth {
            username: "admin".to_string(),
            password: "secret".to_string(),
        }]),
        api_keys: Some(vec!["key-1".to_string()]),
        ..Default::default()
    };

    let port = start_app_with_api(api_settings).await;
    let base_url = format!("http://127.0.0.1:{}", port);
    let client = Client::new();

    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .basic_auth("admin", Some("secret"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .header("X-API-Key", "key-1")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
}

#[tokio::test]
async fn test_api_rate_limit() {
    let api_settings = ApiSettings {
        rate_limit: Some(RateLimit {
            requests_per_second: 1,
            burst: 1,
        }),
        ..Default::default()
    };

    let port = start_app_with_api(api_settings).await;
    let base_url = format!("http://127.0.0.1:{}", port);
    let client = Client::new();

    // 1. First request - should succeed
    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // 2. Immediate second request - should be rate limited (allow some leeway for slow CI)
    // We send multiple requests to ensure we hit the limit
    let mut limited = false;
    for _ in 0..5 {
        let resp = client
            .get(format!("{}/upstreams/list", base_url))
            .send()
            .await
            .unwrap();
        if resp.status() == 429 {
            limited = true;
            break;
        }
    }
    assert!(limited, "Should have been rate limited");

    // 3. Wait for 1 second and try again - should succeed
    sleep(Duration::from_secs(2)).await; // Wait slightly more than 1s
    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
}

#[tokio::test]
async fn test_api_upstreams() {
    let port = start_app_with_api(ApiSettings::default()).await;
    let base_url = format!("http://127.0.0.1:{}", port);
    let client = Client::new();

    // 1. List upstreams - initially empty
    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let list: UpstreamListResponse = resp.json().await.unwrap();
    assert!(list.upstreams.is_empty());

    // 2. Add upstream
    let upstream = Upstream {
        name: "test-upstream".to_string(),
        servers: vec![UpstreamServer {
            host: "127.0.0.1:8080".to_string(),
            ..Default::default()
        }],
        ..Default::default()
    };
    let resp = client
        .post(format!("{}/upstreams/add", base_url))
        .json(&AddUpstreamRequest { upstream })
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let success: SuccessResponse = resp.json().await.unwrap();
    assert!(success.success);

    // 3. Verify upstream exists
    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .send()
        .await
        .unwrap();
    let list: UpstreamListResponse = resp.json().await.unwrap();
    assert_eq!(list.upstreams.len(), 1);
    assert_eq!(list.upstreams[0], "test-upstream");

    // 4. Update upstream
    let updated_upstream = Upstream {
        name: "test-upstream".to_string(),
        servers: vec![UpstreamServer {
            host: "127.0.0.1:9090".to_string(), // Changed port
            ..Default::default()
        }],
        ..Default::default()
    };
    let resp = client
        .post(format!("{}/upstreams/update", base_url))
        .json(&jokoway::extensions::api::UpdateUpstreamRequest {
            name: "test-upstream".to_string(),
            upstream: updated_upstream,
        })
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // 5. Remove upstream
    let resp = client
        .post(format!("{}/upstreams/remove", base_url))
        .json(&RemoveUpstreamRequest {
            name: "test-upstream".to_string(),
        })
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // 6. Verify removal
    let resp = client
        .get(format!("{}/upstreams/list", base_url))
        .send()
        .await
        .unwrap();
    let list: UpstreamListResponse = resp.json().await.unwrap();
    assert!(list.upstreams.is_empty());
}

#[tokio::test]
async fn test_api_services() {
    let port = start_app_with_api(ApiSettings::default()).await;
    let base_url = format!("http://127.0.0.1:{}", port);
    let client = Client::new();

    // 1. List services - initially empty
    let resp = client
        .get(format!("{}/services/list", base_url))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let list: ServiceListResponse = resp.json().await.unwrap();
    assert!(list.services.is_empty());

    // 2. Add service
    let service = Service {
        name: "test-service".to_string(),
        host: "example.com".to_string(),
        protocols: vec![ServiceProtocol::Http],
        routes: vec![Route {
            name: "test-route".to_string(),
            rule: "PathPrefix(`/`)".to_string(),
            ..Default::default()
        }],
        ..Default::default()
    };
    let resp = client
        .post(format!("{}/services/add", base_url))
        .json(&AddServiceRequest { service })
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let success: SuccessResponse = resp.json().await.unwrap();
    assert!(success.success);

    // 3. Verify service exists
    let resp = client
        .get(format!("{}/services/list", base_url))
        .send()
        .await
        .unwrap();
    let list: ServiceListResponse = resp.json().await.unwrap();
    assert_eq!(list.services.len(), 1);
    assert_eq!(list.services[0].name, "test-service");

    // 4. Update service
    let updated_service = Service {
        name: "test-service".to_string(),
        host: "updated.example.com".to_string(), // Changed host
        protocols: vec![ServiceProtocol::Http],
        routes: vec![Route {
            name: "test-route".to_string(),
            rule: "PathPrefix(`/updated`)".to_string(),
            ..Default::default()
        }],
        ..Default::default()
    };
    let resp = client
        .post(format!("{}/services/update", base_url))
        .json(&jokoway::extensions::api::UpdateServiceRequest {
            name: "test-service".to_string(),
            service: updated_service,
        })
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // 5. Remove service
    let resp = client
        .post(format!("{}/services/remove", base_url))
        .json(&RemoveServiceRequest {
            name: "test-service".to_string(),
        })
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // 6. Verify removal
    let resp = client
        .get(format!("{}/services/list", base_url))
        .send()
        .await
        .unwrap();
    let list: ServiceListResponse = resp.json().await.unwrap();
    assert!(list.services.is_empty());
}

#[tokio::test]
async fn test_proxy_via_api() {
    // 1. Setup Mock Upstream
    let mock_server = start_http_mock().await;
    Mock::given(method("GET"))
        .and(path("/target"))
        .respond_with(ResponseTemplate::new(200).set_body_string("I am the target"))
        .mount(&mock_server)
        .await;

    let mock_addr = mock_server.uri().replace("http://", "");

    // 2. Setup Jokoway with API
    let api_port = get_random_port().await;
    let proxy_port = get_random_port().await;

    let api_settings = ApiSettings {
        listen: format!("127.0.0.1:{}", api_port),
        ..Default::default()
    };

    let config = JokowayConfig {
        http_listen: format!("127.0.0.1:{}", proxy_port),
        api: Some(api_settings),
        ..Default::default()
    };

    let app = App::new(config, None, Opt::default(), vec![]);

    std::thread::spawn(move || {
        if let Err(e) = app.run() {
            eprintln!("App failed: {:?}", e);
        }
    });

    sleep(Duration::from_millis(500)).await;

    let api_base = format!("http://127.0.0.1:{}", api_port);
    let proxy_base = format!("http://127.0.0.1:{}", proxy_port);
    let client = Client::new();

    // 3. Add Upstream via API
    let upstream = Upstream {
        name: "dynamic-upstream".to_string(),
        servers: vec![UpstreamServer {
            host: mock_addr,
            ..Default::default()
        }],
        ..Default::default()
    };
    let resp = client
        .post(format!("{}/upstreams/add", api_base))
        .json(&AddUpstreamRequest { upstream })
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // 4. Add Service via API
    let service = Service {
        name: "dynamic-service".to_string(),
        host: "dynamic-upstream".to_string(), // Matches upstream name
        protocols: vec![ServiceProtocol::Http],
        routes: vec![Route {
            name: "dynamic-route".to_string(),
            rule: "PathPrefix(`/target`)".to_string(),
            ..Default::default()
        }],
        ..Default::default()
    };
    let resp = client
        .post(format!("{}/services/add", api_base))
        .json(&AddServiceRequest { service })
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // 5. Test Proxy
    // We need to send a request to the proxy with the correct Host header
    let resp = client
        .get(format!("{}/target", proxy_base))
        .header("Host", "dynamic.test")
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let body = resp.text().await.unwrap();
    assert_eq!(body, "I am the target");
}