llmposter 0.4.8

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. 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
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::Mutex;
#[cfg(feature = "oauth")]
use std::sync::RwLock;

use axum::extract::State;
use axum::http::{header, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};

use crate::server::AppState;

/// OAuth introspect configuration for validating tokens issued by oauth-mock.
#[cfg(feature = "oauth")]
#[derive(Clone)]
pub(crate) struct OAuthIntrospect {
    /// Token introspection endpoint URL.
    pub url: String,
    /// OAuth client ID for introspection requests.
    pub client_id: String,
    /// OAuth client secret for introspection requests.
    pub client_secret: String,
    /// HTTP client for making introspection requests.
    pub client: reqwest::Client,
}

/// Result of checking a token against the hardcoded token store.
#[derive(Debug, PartialEq)]
pub enum TokenStatus {
    /// Token is valid (accepted).
    Valid,
    /// Token was explicitly exhausted or revoked (deny-listed).
    Exhausted,
    /// Token is not in the hardcoded store (may still be a valid OAuth token).
    Unknown,
}

/// Inner token store, guarded by a single `Mutex` so every mutation
/// or lookup sees a consistent snapshot of `(tokens, exhausted)`.
///
/// Using one lock instead of two separate `RwLock`s eliminates the
/// possibility of an ABBA deadlock across token admin + request
/// dispatch (previously safe via consistent lock ordering, but fragile
/// to future refactors).
#[derive(Default)]
struct TokenStore {
    /// Token → remaining uses (None = unlimited).
    tokens: HashMap<String, Option<u64>>,
    /// Tokens explicitly exhausted / revoked. Deny-list prevents
    /// OAuth fallthrough from bypassing use limits.
    exhausted: HashSet<String>,
}

/// Bearer token state for authentication enforcement.
/// Tracks valid tokens and their remaining uses.
pub struct AuthState {
    store: Mutex<TokenStore>,
    #[cfg(feature = "oauth")]
    oauth_introspect: RwLock<Option<OAuthIntrospect>>,
}

impl Default for AuthState {
    fn default() -> Self {
        Self::new()
    }
}

impl AuthState {
    /// Create a new, empty `AuthState` with no tokens registered.
    pub fn new() -> Self {
        Self {
            store: Mutex::new(TokenStore::default()),
            #[cfg(feature = "oauth")]
            oauth_introspect: RwLock::new(None),
        }
    }

    /// Add a token. `max_uses` of `None` = unlimited.
    /// Clears the token from the deny-list if it was previously exhausted or revoked,
    /// allowing the same token string to be re-issued.
    pub fn add_token(&self, token: &str, max_uses: Option<u64>) {
        let mut store = self.store.lock().unwrap_or_else(|e| e.into_inner());
        store.exhausted.remove(token);
        store.tokens.insert(token.to_string(), max_uses);
    }

    /// Check token validity and decrement use count.
    /// Returns `Valid`, `Exhausted` (deny-listed), or `Unknown` (not a hardcoded token).
    pub fn check_and_use(&self, token: &str) -> TokenStatus {
        let mut store = self.store.lock().unwrap_or_else(|e| e.into_inner());
        if store.exhausted.contains(token) {
            return TokenStatus::Exhausted;
        }
        match store.tokens.get_mut(token) {
            Some(Some(remaining)) if *remaining > 0 => {
                *remaining -= 1;
                if *remaining == 0 {
                    store.tokens.remove(token);
                    store.exhausted.insert(token.to_string());
                }
                TokenStatus::Valid
            }
            Some(Some(_)) => {
                store.tokens.remove(token);
                store.exhausted.insert(token.to_string());
                TokenStatus::Exhausted
            }
            Some(None) => TokenStatus::Valid,
            None => TokenStatus::Unknown,
        }
    }

    /// Revoke a token. Atomically removes from tokens and adds to deny-list.
    pub fn revoke(&self, token: &str) {
        let mut store = self.store.lock().unwrap_or_else(|e| e.into_inner());
        store.tokens.remove(token);
        store.exhausted.insert(token.to_string());
    }

    /// Set the OAuth introspect configuration for validating oauth-mock tokens.
    #[cfg(feature = "oauth")]
    pub(crate) fn set_oauth_introspect(&self, config: OAuthIntrospect) {
        *self
            .oauth_introspect
            .write()
            .unwrap_or_else(|e| e.into_inner()) = Some(config);
    }

    /// Validate a token via the oauth-mock introspect endpoint (localhost HTTP call).
    #[cfg(feature = "oauth")]
    pub(crate) async fn check_oauth_token(&self, token: &str) -> bool {
        let config = {
            let guard = self
                .oauth_introspect
                .read()
                .unwrap_or_else(|e| e.into_inner());
            match guard.as_ref() {
                Some(c) => c.clone(),
                None => return false,
            }
        };
        let resp = config
            .client
            .post(&config.url)
            .basic_auth(&config.client_id, Some(&config.client_secret))
            .form(&[("token", token)])
            .send()
            .await;
        match resp {
            Ok(r) => {
                if let Ok(body) = r.json::<serde_json::Value>().await {
                    body.get("active")
                        .and_then(|v| v.as_bool())
                        .unwrap_or(false)
                } else {
                    eprintln!(
                        "[llmposter] OAuth introspect: failed to parse response body as JSON"
                    );
                    false
                }
            }
            Err(e) => {
                eprintln!("[llmposter] OAuth introspect request failed: {e}");
                false
            }
        }
    }
}

/// Bearer auth middleware. Skips check if auth is not enabled.
pub(crate) async fn bearer_auth_check(
    State(state): State<Arc<AppState>>,
    request: axum::extract::Request,
    next: Next,
) -> Response {
    let auth = match &state.auth {
        Some(a) => a,
        None => return next.run(request).await,
    };

    let path = request.uri().path().to_string();

    // Auth applies only to LLM endpoints — all other routes pass through.
    let is_llm_route = path.starts_with("/v1/") || path.starts_with("/v1beta/");
    if !is_llm_route {
        return next.run(request).await;
    }
    let token = request
        .headers()
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| {
            // RFC 7235: auth-scheme is case-insensitive
            if v.len() > 7 && v[..7].eq_ignore_ascii_case("bearer ") {
                Some(&v[7..])
            } else {
                None
            }
        });

    match token {
        Some(t) => {
            let status = auth.check_and_use(t);
            let is_valid = match status {
                TokenStatus::Valid => true,
                TokenStatus::Exhausted => false,
                TokenStatus::Unknown => {
                    #[cfg(feature = "oauth")]
                    {
                        auth.check_oauth_token(t).await
                    }
                    #[cfg(not(feature = "oauth"))]
                    false
                }
            };
            if is_valid {
                next.run(request).await
            } else {
                capture_auth_reject(&state, request.method().as_str(), &path);
                auth_error_response(&path)
            }
        }
        _ => {
            capture_auth_reject(&state, request.method().as_str(), &path);
            auth_error_response(&path)
        }
    }
}

/// Record an auth-rejected request so `MockServer::get_requests()` shows
/// it alongside matched traffic. The body isn't buffered here — tests
/// that need to diff the rejected body can still read it from their own
/// client side, and avoiding the buffer keeps the auth hot path simple.
fn capture_auth_reject(state: &AppState, method: &str, path: &str) {
    crate::handler::capture_non_matched(
        state,
        method,
        path,
        "",
        crate::server::RequestOutcome::AuthRejected,
    );
}

/// Build provider-specific 401 response based on request path.
fn auth_error_response(path: &str) -> Response {
    let body = if path.starts_with("/v1/messages") {
        // Anthropic
        serde_json::json!({
            "type": "error",
            "error": {
                "type": "authentication_error",
                "message": "Invalid bearer token"
            }
        })
    } else if path.starts_with("/v1beta/models") {
        // Gemini
        serde_json::json!({
            "error": {
                "code": 401,
                "message": "Invalid bearer token",
                "status": "UNAUTHENTICATED"
            }
        })
    } else {
        // OpenAI / Responses
        serde_json::json!({
            "error": {
                "message": "Invalid bearer token",
                "type": "authentication_error",
                "param": null,
                "code": "invalid_api_key"
            }
        })
    };
    (
        StatusCode::UNAUTHORIZED,
        [
            (header::CONTENT_TYPE, "application/json"),
            (header::WWW_AUTHENTICATE, "Bearer realm=\"api\""),
        ],
        body.to_string(),
    )
        .into_response()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn should_accept_valid_token() {
        let state = AuthState::new();
        state.add_token("tok-1", None);
        assert_eq!(state.check_and_use("tok-1"), TokenStatus::Valid);
    }

    #[test]
    fn should_reject_unknown_token() {
        let state = AuthState::new();
        assert_eq!(state.check_and_use("unknown"), TokenStatus::Unknown);
    }

    #[test]
    fn should_expire_after_n_uses() {
        let state = AuthState::new();
        state.add_token("tok-1", Some(2));
        assert_eq!(state.check_and_use("tok-1"), TokenStatus::Valid);
        assert_eq!(state.check_and_use("tok-1"), TokenStatus::Valid);
        assert_eq!(state.check_and_use("tok-1"), TokenStatus::Exhausted);
    }

    #[test]
    fn should_remove_revoked_token() {
        let state = AuthState::new();
        state.add_token("tok-1", None);
        state.revoke("tok-1");
        assert_eq!(state.check_and_use("tok-1"), TokenStatus::Exhausted);
    }

    #[test]
    fn should_accept_unlimited_token_many_times() {
        let state = AuthState::new();
        state.add_token("unlimited", None);
        for _ in 0..100 {
            assert_eq!(state.check_and_use("unlimited"), TokenStatus::Valid);
        }
    }

    #[test]
    fn should_support_default_trait() {
        let state = AuthState::default();
        state.add_token("tok", None);
        assert_eq!(state.check_and_use("tok"), TokenStatus::Valid);
    }

    #[test]
    fn should_reject_zero_use_token() {
        let state = AuthState::new();
        state.add_token("zero", Some(0));
        assert_eq!(state.check_and_use("zero"), TokenStatus::Exhausted);
    }

    #[test]
    fn should_allow_re_add_after_revoke() {
        let state = AuthState::new();
        state.add_token("tok", None);
        state.revoke("tok");
        assert_eq!(state.check_and_use("tok"), TokenStatus::Exhausted);
        // Re-adding should clear the deny-list and restore access
        state.add_token("tok", None);
        assert_eq!(state.check_and_use("tok"), TokenStatus::Valid);
    }

    #[test]
    fn should_allow_re_add_after_exhaustion() {
        let state = AuthState::new();
        state.add_token("tok", Some(1));
        assert_eq!(state.check_and_use("tok"), TokenStatus::Valid);
        assert_eq!(state.check_and_use("tok"), TokenStatus::Exhausted);
        // Re-adding should clear the deny-list and restore access
        state.add_token("tok", Some(2));
        assert_eq!(state.check_and_use("tok"), TokenStatus::Valid);
        assert_eq!(state.check_and_use("tok"), TokenStatus::Valid);
        assert_eq!(state.check_and_use("tok"), TokenStatus::Exhausted);
    }

    #[cfg(feature = "oauth")]
    #[tokio::test]
    async fn should_return_false_when_introspect_unreachable() {
        let state = AuthState::new();
        state.set_oauth_introspect(OAuthIntrospect {
            url: "http://127.0.0.1:1/introspect".to_string(),
            client_id: "test".to_string(),
            client_secret: "secret".to_string(),
            client: reqwest::Client::builder()
                .timeout(std::time::Duration::from_millis(100))
                .build()
                .unwrap(),
        });
        assert!(!state.check_oauth_token("any").await);
    }

    #[cfg(feature = "oauth")]
    #[tokio::test]
    async fn should_return_false_when_introspect_not_configured() {
        let state = AuthState::new();
        assert!(!state.check_oauth_token("any").await);
    }

    #[cfg(feature = "oauth")]
    #[tokio::test]
    async fn should_return_false_when_introspect_returns_non_json() {
        use axum::{routing::post, Router};

        // Spin up a tiny server that returns non-JSON on POST
        let app = Router::new().route("/introspect", post(|| async { "this is not json" }));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        tokio::spawn(async move {
            axum::serve(listener, app).await.ok();
        });

        let state = AuthState::new();
        state.set_oauth_introspect(OAuthIntrospect {
            url: format!("http://127.0.0.1:{}/introspect", port),
            client_id: "test".to_string(),
            client_secret: "secret".to_string(),
            client: reqwest::Client::new(),
        });
        assert!(!state.check_oauth_token("any").await);
    }
}