llmposter 0.5.0

Drop-in mock server for OpenAI, Anthropic & Gemini APIs — library or standalone CLI. SSE streaming, tool calling, OAuth2, failure injection, streaming chaos, stateful scenarios, request capture, hot-reload, response templating, record/replay (VCR). Test LLM apps without burning tokens.
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
//! Auth gating for the embedded debug UI.
//!
//! When bearer auth is enabled, `/ui` and everything under it must
//! require a valid token too — the UI exposes captured request bodies,
//! so leaving it open while the LLM endpoints are locked down would
//! leak all traffic. Browsers can't attach an `Authorization` header
//! to a page load or `EventSource`, so a `?token=` query parameter is
//! accepted as an alternative on UI routes only.
#![cfg(feature = "ui")]

use llmposter::{Fixture, ServerBuilder};

fn chat_body() -> serde_json::Value {
    serde_json::json!({
        "model": "gpt-4",
        "messages": [{"role": "user", "content": "hi"}]
    })
}

#[tokio::test]
async fn should_serve_ui_unauthenticated_when_auth_disabled() {
    let server = ServerBuilder::new()
        .ui(true)
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    for path in ["/ui", "/ui/requests", "/ui/fixtures", "/ui/meta"] {
        let resp = client
            .get(format!("{}{}", server.url(), path))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 200, "GET {} without auth configured", path);
    }
}

#[tokio::test]
async fn should_reject_ui_without_token_when_auth_enabled() {
    let server = ServerBuilder::new()
        .ui(true)
        .with_bearer_token("valid-token")
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    for path in [
        "/ui",
        "/ui/requests",
        "/ui/fixtures",
        "/ui/meta",
        "/ui/events",
    ] {
        let resp = client
            .get(format!("{}{}", server.url(), path))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 401, "GET {} must require auth", path);
        // 401s still carry x-request-id like the LLM endpoints
        assert!(resp.headers().get("x-request-id").is_some());
        assert!(resp.headers().get("www-authenticate").is_some());
    }

    let resp = client
        .post(format!("{}/ui/debug", server.url()))
        .json(&serde_json::json!({"provider": "openai", "body": "{}"}))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401, "POST /ui/debug must require auth");
}

#[tokio::test]
async fn should_reject_ui_with_invalid_token() {
    let server = ServerBuilder::new()
        .ui(true)
        .with_bearer_token("valid-token")
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    let resp = client
        .get(format!("{}/ui/requests", server.url()))
        .header("Authorization", "Bearer wrong-token")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);

    let resp = client
        .get(format!("{}/ui/requests?token=wrong-token", server.url()))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
}

#[tokio::test]
async fn should_accept_ui_with_bearer_header() {
    let server = ServerBuilder::new()
        .ui(true)
        .with_bearer_token("valid-token")
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    for path in ["/ui", "/ui/requests", "/ui/fixtures", "/ui/meta"] {
        let resp = client
            .get(format!("{}{}", server.url(), path))
            .header("Authorization", "Bearer valid-token")
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 200, "GET {} with valid header", path);
    }
}

#[tokio::test]
async fn should_accept_ui_with_token_query_param() {
    let server = ServerBuilder::new()
        .ui(true)
        .with_bearer_token("valid-token")
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    for path in ["/ui", "/ui/requests", "/ui/events"] {
        let resp = client
            .get(format!("{}{}?token=valid-token", server.url(), path))
            .send()
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            200,
            "GET {}?token=... with valid token",
            path
        );
    }
}

#[tokio::test]
async fn should_accept_percent_encoded_query_token() {
    // RFC 6750 b64token charset includes '+', '/', and '=' — all of
    // which encodeURIComponent percent-encodes in a query string.
    let server = ServerBuilder::new()
        .ui(true)
        .with_bearer_token("tok+base64/chars=")
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    let resp = client
        .get(format!(
            "{}/ui/requests?token=tok%2Bbase64%2Fchars%3D",
            server.url()
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
}

#[tokio::test]
async fn should_accept_raw_plus_in_query_token() {
    // The 401 hint says "open /ui?token=<your-bearer-token>" — users
    // paste tokens verbatim, and base64 tokens contain literal '+'.
    // Query decoding must treat '+' as itself, not as a form-encoded
    // space (tokens can never contain spaces, so nothing is lost).
    let server = ServerBuilder::new()
        .ui(true)
        .with_bearer_token("tok+base64/chars=")
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    let resp = client
        .get(format!(
            "{}/ui/requests?token=tok+base64/chars=",
            server.url()
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
}

#[tokio::test]
async fn should_not_consume_token_uses_for_ui_requests() {
    let server = ServerBuilder::new()
        .ui(true)
        .with_bearer_token_uses("one-shot", 1)
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    // UI access must not burn the token's single use.
    for _ in 0..3 {
        let resp = client
            .get(format!("{}/ui/requests?token=one-shot", server.url()))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
    }

    // The single LLM use is still available...
    let resp = client
        .post(format!("{}/v1/chat/completions", server.url()))
        .header("Authorization", "Bearer one-shot")
        .json(&chat_body())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // ...and exactly one: the second LLM call is rejected.
    let resp = client
        .post(format!("{}/v1/chat/completions", server.url()))
        .header("Authorization", "Bearer one-shot")
        .json(&chat_body())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
}

#[tokio::test]
async fn should_reject_exhausted_token_for_ui() {
    let server = ServerBuilder::new()
        .ui(true)
        .with_bearer_token_uses("one-shot", 1)
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    // Burn the token's single use on an LLM call.
    let resp = client
        .post(format!("{}/v1/chat/completions", server.url()))
        .header("Authorization", "Bearer one-shot")
        .json(&chat_body())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // The exhausted token no longer opens the UI.
    let resp = client
        .get(format!("{}/ui/requests?token=one-shot", server.url()))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
}

#[tokio::test]
async fn should_return_html_401_for_ui_page_and_json_for_ui_api() {
    let server = ServerBuilder::new()
        .ui(true)
        .with_bearer_token("valid-token")
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

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

    // The page route gets a human-readable HTML hint...
    let resp = client
        .get(format!("{}/ui", server.url()))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .to_string();
    assert!(
        content_type.starts_with("text/html"),
        "expected text/html on /ui 401, got {}",
        content_type
    );
    let body = resp.text().await.unwrap();
    assert!(
        body.contains("?token="),
        "401 page should explain how to pass a token"
    );

    // ...while the JSON API routes answer in JSON.
    let resp = client
        .get(format!("{}/ui/requests", server.url()))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .to_string();
    assert!(
        content_type.starts_with("application/json"),
        "expected application/json on /ui/requests 401, got {}",
        content_type
    );
}

#[tokio::test]
async fn should_not_accept_query_token_on_llm_endpoints() {
    // The ?token= escape hatch exists for browser SSE only — the LLM
    // endpoints stay spec-realistic and accept the header exclusively.
    let server = ServerBuilder::new()
        .ui(true)
        .with_bearer_token("valid-token")
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    let resp = client
        .post(format!(
            "{}/v1/chat/completions?token=valid-token",
            server.url()
        ))
        .json(&chat_body())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
}

#[tokio::test]
async fn should_allow_unauthenticated_ui_when_opted_out() {
    // ui_auth(false): the LLM endpoints still enforce tokens, but the
    // UI stays open — for setups where auth exists only to exercise a
    // client's 401 handling on a localhost-bound server.
    let server = ServerBuilder::new()
        .ui(true)
        .ui_auth(false)
        .with_bearer_token("valid-token")
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    let resp = client
        .get(format!("{}/ui", server.url()))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200, "UI must be open after ui_auth(false)");

    let resp = client
        .post(format!("{}/v1/chat/completions", server.url()))
        .json(&chat_body())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401, "LLM endpoints must still enforce auth");
}

#[cfg(feature = "oauth")]
#[tokio::test]
async fn should_accept_oauth_issued_token_for_ui() {
    let server = ServerBuilder::new()
        .ui(true)
        .with_oauth_defaults()
        .fixture(Fixture::new().respond_with_content("hello"))
        .build()
        .await
        .unwrap();

    let client = reqwest::Client::new();
    let oauth_url = server.oauth_url().expect("OAuth URL should be set");
    let (client_id, client_secret) = server
        .oauth_client_credentials()
        .await
        .expect("should have credentials");

    let token_resp = client
        .post(format!("{}/token", oauth_url))
        .form(&[
            ("grant_type", "client_credentials"),
            ("client_id", client_id.as_str()),
            ("client_secret", client_secret.as_str()),
        ])
        .send()
        .await
        .unwrap();
    assert_eq!(token_resp.status(), 200);
    let token_body: serde_json::Value = token_resp.json().await.unwrap();
    let access_token = token_body["access_token"]
        .as_str()
        .expect("must have access_token");

    // OAuth-issued tokens open the UI via header and query param alike.
    let resp = client
        .get(format!("{}/ui/requests", server.url()))
        .header("Authorization", format!("Bearer {}", access_token))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    let resp = client
        .get(format!(
            "{}/ui/requests?token={}",
            server.url(),
            access_token
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
}