aiclient-api 0.1.0

A unified AI gateway daemon exposing OpenAI-compatible and Anthropic-compatible API endpoints, backed by GitHub Copilot and Kiro (AWS CodeWhisperer)
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
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use anyhow::Result;
use async_trait::async_trait;
use serde_json::json;

use aiclient_api::config::types::Config;
use aiclient_api::providers::{Model, Provider, ProviderRequest, ProviderResponse};
use aiclient_api::server::state::AppState;

// ---------------------------------------------------------------------------
// Mock Provider
// ---------------------------------------------------------------------------

struct MockProvider {
    provider_name: String,
    called: Arc<AtomicBool>,
}

impl MockProvider {
    fn new(name: &str) -> Self {
        Self {
            provider_name: name.to_string(),
            called: Arc::new(AtomicBool::new(false)),
        }
    }

    fn was_called(&self) -> bool {
        self.called.load(Ordering::Relaxed)
    }
}

#[async_trait]
impl Provider for MockProvider {
    fn name(&self) -> &str {
        &self.provider_name
    }

    fn is_healthy(&self) -> bool {
        true
    }

    async fn list_models(&self) -> Result<Vec<Model>> {
        Ok(vec![Model {
            id: format!("{}/test-model", self.provider_name),
            provider: self.provider_name.clone(),
            vendor: "mock".to_string(),
            display_name: "Test Model".to_string(),
            max_input_tokens: Some(128_000),
            max_output_tokens: Some(4_096),
            supports_streaming: true,
            supports_tools: true,
            supports_vision: false,
            supports_thinking: false,
        }])
    }

    async fn chat(&self, request: ProviderRequest) -> Result<ProviderResponse> {
        self.called.store(true, Ordering::Relaxed);
        Ok(ProviderResponse::Complete(json!({
            "id": "mock-response",
            "content": [{"type": "text", "text": "Hello from mock"}],
            "model": request.model,
            "role": "assistant",
            "stop_reason": "end_turn",
        })))
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn test_config(default_provider: &str, api_key: &str) -> Config {
    Config {
        default_provider: default_provider.to_string(),
        api_key: api_key.to_string(),
        ..Config::default()
    }
}

async fn build_test_server_with_provider(
    provider_name: &str,
    api_key: &str,
) -> (axum_test::TestServer, Arc<MockProvider>) {
    let config = test_config(provider_name, api_key);
    let state = AppState::new(config);
    let mock = Arc::new(MockProvider::new(provider_name));
    {
        let mut providers = state.providers.write().await;
        providers.insert(provider_name.to_string(), mock.clone() as Arc<dyn Provider>);
    }
    let app = aiclient_api::server::build_router(state);
    let server = axum_test::TestServer::new(app);
    (server, mock)
}

async fn build_test_server_with_two_providers(
    api_key: &str,
) -> (axum_test::TestServer, Arc<MockProvider>, Arc<MockProvider>) {
    let config = test_config("provider_a", api_key);
    let state = AppState::new(config);
    let mock_a = Arc::new(MockProvider::new("provider_a"));
    let mock_b = Arc::new(MockProvider::new("provider_b"));
    {
        let mut providers = state.providers.write().await;
        providers.insert("provider_a".to_string(), mock_a.clone() as Arc<dyn Provider>);
        providers.insert("provider_b".to_string(), mock_b.clone() as Arc<dyn Provider>);
    }
    let app = aiclient_api::server::build_router(state);
    let server = axum_test::TestServer::new(app);
    (server, mock_a, mock_b)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

/// Send POST /v1/chat/completions with an OpenAI-format body and verify the
/// response is valid OpenAI JSON (contains "choices", "object", "model").
#[tokio::test]
async fn test_openai_endpoint_with_mock_provider() {
    let (server, _mock) = build_test_server_with_provider("mock", "").await;

    let body = json!({
        "model": "test-model",
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/chat/completions")
        .json(&body)
        .await;

    response.assert_status_ok();

    let json: serde_json::Value = response.json();
    assert_eq!(json["object"], "chat.completion");
    assert!(json["choices"].is_array(), "response should contain choices array");
    let choices = json["choices"].as_array().unwrap();
    assert!(!choices.is_empty(), "choices should not be empty");
    assert!(json["model"].is_string(), "response should contain model");
    // The converted response should have message.content with the mock text
    let message = &choices[0]["message"];
    assert_eq!(message["role"], "assistant");
    assert!(
        message["content"].as_str().unwrap().contains("Hello from mock"),
        "content should contain mock response text"
    );
}

/// Send POST /v1/messages with an Anthropic-format body and verify the
/// response is valid Anthropic JSON (contains "type": "message", "content" blocks).
#[tokio::test]
async fn test_anthropic_endpoint_with_mock_provider() {
    let (server, _mock) = build_test_server_with_provider("mock", "").await;

    let body = json!({
        "model": "test-model",
        "max_tokens": 1024,
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/messages")
        .json(&body)
        .await;

    response.assert_status_ok();

    let json: serde_json::Value = response.json();
    // The mock returns Anthropic-style content blocks, and to_anthropic
    // should pass them through or re-wrap them.
    assert_eq!(json["role"], "assistant");
    assert!(json["content"].is_array(), "response should contain content array");
    let content = json["content"].as_array().unwrap();
    assert!(!content.is_empty(), "content should not be empty");
    assert_eq!(content[0]["type"], "text");
    assert!(
        content[0]["text"].as_str().unwrap().contains("Hello from mock"),
        "text block should contain mock response text"
    );
}

/// Register two providers ("provider_a" and "provider_b"). Send a request
/// with model "provider_a/test-model" and verify provider_a was called while
/// provider_b was not.
#[tokio::test]
async fn test_model_routing_with_prefix() {
    let (server, mock_a, mock_b) = build_test_server_with_two_providers("").await;

    let body = json!({
        "model": "provider_a/test-model",
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/chat/completions")
        .json(&body)
        .await;

    response.assert_status_ok();
    assert!(mock_a.was_called(), "provider_a should have been called");
    assert!(!mock_b.was_called(), "provider_b should NOT have been called");
}

/// Set api_key in config. Send a request WITHOUT an Authorization header.
/// Assert 401 Unauthorized.
#[tokio::test]
async fn test_auth_middleware_rejects_without_key() {
    let (server, _mock) = build_test_server_with_provider("mock", "test123").await;

    let body = json!({
        "model": "test-model",
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/chat/completions")
        .json(&body)
        .await;

    response.assert_status(axum::http::StatusCode::UNAUTHORIZED);
}

/// Set api_key in config. Send a request WITH the correct Bearer token.
/// Assert 200 OK.
#[tokio::test]
async fn test_auth_middleware_accepts_correct_key() {
    let (server, _mock) = build_test_server_with_provider("mock", "test123").await;

    let body = json!({
        "model": "test-model",
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/chat/completions")
        .add_header(
            axum::http::header::AUTHORIZATION,
            axum::http::HeaderValue::from_static("Bearer test123"),
        )
        .json(&body)
        .await;

    response.assert_status_ok();
}

/// Register a mock provider with known models. GET /v1/models and assert the
/// response contains the expected model list.
#[tokio::test]
async fn test_models_endpoint() {
    let (server, _mock) = build_test_server_with_provider("mock", "").await;

    let response = server.get("/v1/models").await;

    response.assert_status_ok();

    let json: serde_json::Value = response.json();
    assert_eq!(json["object"], "list");
    let data = json["data"].as_array().expect("data should be an array");
    assert!(!data.is_empty(), "models list should not be empty");

    // The mock provider returns one model: "mock/test-model"
    let model_ids: Vec<&str> = data
        .iter()
        .filter_map(|m| m["id"].as_str())
        .collect();
    assert!(
        model_ids.contains(&"mock/test-model"),
        "models list should contain mock/test-model, got: {:?}",
        model_ids
    );
    assert_eq!(data[0]["owned_by"], "mock");
}

// ---------------------------------------------------------------------------
// Router tests
// ---------------------------------------------------------------------------

/// Register provider_a and provider_b. Send a request with model "test-model"
/// (no prefix) and header `X-Provider: provider_b`. Assert provider_b was
/// called, provider_a was not.
#[tokio::test]
async fn test_model_routing_with_x_provider_header() {
    let (server, mock_a, mock_b) = build_test_server_with_two_providers("").await;

    let body = json!({
        "model": "test-model",
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/chat/completions")
        .add_header(
            axum::http::HeaderName::from_static("x-provider"),
            axum::http::HeaderValue::from_static("provider_b"),
        )
        .json(&body)
        .await;

    response.assert_status_ok();
    assert!(!mock_a.was_called(), "provider_a should NOT have been called");
    assert!(mock_b.was_called(), "provider_b should have been called");
}

/// Register provider_a as the default provider. Send a request with model
/// "test-model" (no prefix, no X-Provider header). Assert provider_a was
/// called.
#[tokio::test]
async fn test_model_routing_falls_back_to_default() {
    let (server, mock_a) = build_test_server_with_provider("provider_a", "").await;

    let body = json!({
        "model": "test-model",
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/chat/completions")
        .json(&body)
        .await;

    response.assert_status_ok();
    assert!(mock_a.was_called(), "provider_a (default) should have been called");
}

/// Send a request with model "nonexistent/test-model". The router should fail
/// to find a provider named "nonexistent" and return a non-200 response.
#[tokio::test]
async fn test_model_routing_unknown_prefix_returns_error() {
    let (server, _mock) = build_test_server_with_provider("mock", "").await;

    let body = json!({
        "model": "nonexistent/test-model",
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/chat/completions")
        .json(&body)
        .await;

    assert!(
        response.status_code() != axum::http::StatusCode::OK,
        "unknown provider prefix should result in a non-200 response, got {}",
        response.status_code()
    );
}

// ---------------------------------------------------------------------------
// Auth middleware tests
// ---------------------------------------------------------------------------

/// Set api_key to "secret". Send a request with "Bearer wrong". Assert 401.
#[tokio::test]
async fn test_auth_middleware_wrong_key_returns_401() {
    let (server, _mock) = build_test_server_with_provider("mock", "secret").await;

    let body = json!({
        "model": "test-model",
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/chat/completions")
        .add_header(
            axum::http::header::AUTHORIZATION,
            axum::http::HeaderValue::from_static("Bearer wrong"),
        )
        .json(&body)
        .await;

    response.assert_status(axum::http::StatusCode::UNAUTHORIZED);
}

/// Set api_key to "" (empty). Send a request without any Authorization header.
/// Assert 200 (empty api_key disables auth enforcement).
#[tokio::test]
async fn test_auth_middleware_no_key_config_allows_all() {
    let (server, _mock) = build_test_server_with_provider("mock", "").await;

    let body = json!({
        "model": "test-model",
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/chat/completions")
        .json(&body)
        .await;

    response.assert_status_ok();
}

/// Set api_key to "secret". Send with "Basic secret" instead of "Bearer secret".
/// Assert 401 (wrong auth scheme).
#[tokio::test]
async fn test_auth_middleware_invalid_format_returns_401() {
    let (server, _mock) = build_test_server_with_provider("mock", "secret").await;

    let body = json!({
        "model": "test-model",
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/chat/completions")
        .add_header(
            axum::http::header::AUTHORIZATION,
            axum::http::HeaderValue::from_static("Basic secret"),
        )
        .json(&body)
        .await;

    response.assert_status(axum::http::StatusCode::UNAUTHORIZED);
}

// ---------------------------------------------------------------------------
// Error format tests
// ---------------------------------------------------------------------------

/// Send a body with "messages" as a non-array value to /v1/chat/completions.
/// The response should be in OpenAI error format: `error.message` and
/// `error.type` fields.
#[tokio::test]
async fn test_openai_endpoint_error_format() {
    let (server, _mock) = build_test_server_with_provider("mock", "").await;

    // "messages" must be an array; passing a string forces a deserialization error.
    let body = json!({
        "model": "test-model",
        "messages": "not-an-array"
    });

    let response = server
        .post("/v1/chat/completions")
        .json(&body)
        .await;

    assert!(
        response.status_code() != axum::http::StatusCode::OK,
        "invalid request should not return 200"
    );

    let json: serde_json::Value = response.json();
    assert!(
        json["error"]["message"].is_string(),
        "OpenAI error response should have error.message, got: {json}"
    );
    assert!(
        json["error"]["type"].is_string(),
        "OpenAI error response should have error.type, got: {json}"
    );
}

/// Send a body missing the required `max_tokens` field to /v1/messages.
/// The response should be in Anthropic error format: `type: "error"`,
/// `error.type`, and `error.message` fields.
#[tokio::test]
async fn test_anthropic_endpoint_error_format() {
    let (server, _mock) = build_test_server_with_provider("mock", "").await;

    // AnthropicMessagesRequest.max_tokens is required; omitting it triggers
    // a deserialization error on the conversion path.
    let body = json!({
        "model": "test-model",
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
        // max_tokens intentionally omitted
    });

    let response = server
        .post("/v1/messages")
        .json(&body)
        .await;

    assert!(
        response.status_code() != axum::http::StatusCode::OK,
        "missing max_tokens should not return 200"
    );

    let json: serde_json::Value = response.json();
    assert_eq!(
        json["type"], "error",
        "Anthropic error response should have type: \"error\", got: {json}"
    );
    assert!(
        json["error"]["type"].is_string(),
        "Anthropic error response should have error.type, got: {json}"
    );
    assert!(
        json["error"]["message"].is_string(),
        "Anthropic error response should have error.message, got: {json}"
    );
}

/// Set api_key to "test123". Send to /v1/messages without an Authorization
/// header. The auth middleware error should be in Anthropic format (has
/// `type: "error"`).
#[tokio::test]
async fn test_anthropic_auth_error_format() {
    let (server, _mock) = build_test_server_with_provider("mock", "test123").await;

    let body = json!({
        "model": "test-model",
        "max_tokens": 1024,
        "messages": [
            {"role": "user", "content": "Hello"}
        ]
    });

    let response = server
        .post("/v1/messages")
        .json(&body)
        .await;

    response.assert_status(axum::http::StatusCode::UNAUTHORIZED);

    let json: serde_json::Value = response.json();
    assert_eq!(
        json["type"], "error",
        "Anthropic auth error should have type: \"error\", got: {json}"
    );
    assert!(
        json["error"]["type"].is_string(),
        "Anthropic auth error should have error.type, got: {json}"
    );
}

/// Set api_key to "secret". GET /healthz without any Authorization header.
/// Assert 200 (health endpoint is outside the auth middleware).
#[tokio::test]
async fn test_healthz_no_auth_required() {
    let (server, _mock) = build_test_server_with_provider("mock", "secret").await;

    let response = server.get("/healthz").await;

    response.assert_status_ok();
}