bitrouter 1.0.0-alpha.28

BitRouter: an LLM API router. CLI + assembly 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
//! PolicyHook enforcement + combination-semantics tests.

use std::sync::Arc;

use crate::metering::{
    ChargeEvidence, ChargeStatus, EffectivePricingRates, MeteringStore, PricingSource,
    RequestMetric,
};
use crate::policy::hook::PolicyHook;
use crate::policy::policy::Policy;
use crate::policy::store::PolicyStore;
use bitrouter_sdk::PluginId;
use bitrouter_sdk::caller::CallerContext;
use bitrouter_sdk::language_model::{
    GenerationParams, HookDecision, Message, PipelineContext, PipelineRequest, PreRequestHook,
    Prompt, Role, Tool,
};

fn test_charge_evidence(charge_micro_usd: i64) -> ChargeEvidence {
    ChargeEvidence {
        status: ChargeStatus::Computed,
        charge_micro_usd: Some(charge_micro_usd),
        normalized_usage: Default::default(),
        effective_rates: EffectivePricingRates::default(),
        pricing_source: PricingSource::Configured,
        pricing_version: "sha256:test".to_string(),
        unknown_reason: None,
    }
}

fn ctx(model: &str, policy_id: Option<&str>) -> PipelineContext {
    let prompt = Prompt {
        model: model.to_string(),
        system: None,
        system_provider_metadata: Default::default(),
        messages: vec![Message::text(Role::User, "hi")],
        tools: Vec::new(),
        params: GenerationParams::default(),
        response_format: None,
        tool_choice: None,
        stream: false,
    };
    let req = PipelineRequest::new(model, CallerContext::new("k1", "u1"), prompt);
    let mut ctx = PipelineContext::new(req);
    // simulate what AuthHook writes into the context metadata
    if let Some(pid) = policy_id {
        ctx.set_metadata(
            &PluginId::new("bitrouter-auth"),
            serde_json::json!({ "api_key_id": "k1", "user_id": "u1", "policy_id": pid }),
        );
    }
    ctx
}

/// Build a context whose request declares the given tools.
fn ctx_with_tools(tools: &[&str], policy_id: Option<&str>) -> PipelineContext {
    let prompt = Prompt {
        model: "m".to_string(),
        system: None,
        system_provider_metadata: Default::default(),
        messages: vec![Message::text(Role::User, "hi")],
        tools: tools
            .iter()
            .map(|name| Tool::Function {
                name: name.to_string(),
                description: None,
                parameters: serde_json::json!({}),
                strict: None,
                provider_metadata: Default::default(),
            })
            .collect(),
        params: GenerationParams::default(),
        response_format: None,
        tool_choice: None,
        stream: false,
    };
    let req = PipelineRequest::new("m", CallerContext::new("k1", "u1"), prompt);
    let mut ctx = PipelineContext::new(req);
    if let Some(pid) = policy_id {
        ctx.set_metadata(
            &PluginId::new("bitrouter-auth"),
            serde_json::json!({ "api_key_id": "k1", "user_id": "u1", "policy_id": pid }),
        );
    }
    ctx
}

async fn fresh_metering() -> MeteringStore {
    let db = crate::db::connect("sqlite::memory:").await.unwrap();
    crate::db::run_migrations(&db).await.unwrap();
    MeteringStore::new(db)
}

#[tokio::test]
async fn no_policy_bound_permits_everything() {
    let store = Arc::new(PolicyStore::new());
    let hook = PolicyHook::new(store, None);
    let mut c = ctx("any-model", None);
    assert!(matches!(
        hook.check(&mut c).await.unwrap(),
        HookDecision::Allow
    ));
}

#[tokio::test]
async fn denied_model_is_forbidden() {
    let store = Arc::new(PolicyStore::from_policies([Policy {
        id: "p1".into(),
        denied_models: vec!["forbidden-model".into()],
        ..Default::default()
    }]));
    let hook = PolicyHook::new(store, None);

    let mut allowed = ctx("ok-model", Some("p1"));
    assert!(matches!(
        hook.check(&mut allowed).await.unwrap(),
        HookDecision::Allow
    ));

    let mut denied = ctx("forbidden-model", Some("p1"));
    match hook.check(&mut denied).await.unwrap() {
        HookDecision::Deny(reason) => {
            let err: bitrouter_sdk::BitrouterError = reason.into();
            assert_eq!(err.status(), 403);
        }
        HookDecision::Allow => panic!("denied model must be forbidden"),
    }
}

#[tokio::test]
async fn allowlist_restricts_models() {
    let store = Arc::new(PolicyStore::from_policies([Policy {
        id: "p1".into(),
        allowed_models: Some(vec!["gpt-5".into()]),
        ..Default::default()
    }]));
    let hook = PolicyHook::new(store, None);

    let mut ok = ctx("gpt-5", Some("p1"));
    assert!(matches!(
        hook.check(&mut ok).await.unwrap(),
        HookDecision::Allow
    ));
    let mut nope = ctx("claude", Some("p1"));
    assert!(matches!(
        hook.check(&mut nope).await.unwrap(),
        HookDecision::Deny(_)
    ));
}

#[tokio::test]
async fn expired_policy_is_forbidden() {
    let store = Arc::new(PolicyStore::from_policies([Policy {
        id: "p1".into(),
        expires_at: Some(chrono::Utc::now() - chrono::Duration::hours(1)),
        ..Default::default()
    }]));
    let hook = PolicyHook::new(store, None);
    let mut c = ctx("gpt-5", Some("p1"));
    assert!(matches!(
        hook.check(&mut c).await.unwrap(),
        HookDecision::Deny(_)
    ));
}

#[tokio::test]
async fn store_loads_from_yaml_dir() {
    let dir = std::env::temp_dir().join(format!("brpolicy-{}", uuid_like()));
    tokio::fs::create_dir_all(&dir).await.unwrap();
    tokio::fs::write(
        dir.join("team.yaml"),
        "id: team\nallowed_models: [gpt-5, claude]\nmax_spend_micro_usd: 5000\n",
    )
    .await
    .unwrap();
    let store = PolicyStore::load_dir(&dir).await.unwrap();
    assert_eq!(store.len(), 1);
    store.with_policy("team", |p| {
        let p = p.expect("team policy loaded");
        assert_eq!(p.max_spend_micro_usd, Some(5000));
        assert_eq!(p.allowed_models.as_ref().unwrap().len(), 2);
    });
    let _ = tokio::fs::remove_dir_all(&dir).await;
}

#[tokio::test]
async fn reload_re_reads_the_policy_dir() {
    let dir = std::env::temp_dir().join(format!("brpolicy-reload-{}", uuid_like()));
    tokio::fs::create_dir_all(&dir).await.unwrap();
    tokio::fs::write(
        dir.join("a.yaml"),
        "id: team-a\nmax_spend_micro_usd: 5000\n",
    )
    .await
    .unwrap();
    let store = PolicyStore::load_dir(&dir).await.unwrap();
    assert_eq!(store.len(), 1);

    // Add a second policy file and drop the first.
    tokio::fs::remove_file(dir.join("a.yaml")).await.unwrap();
    tokio::fs::write(
        dir.join("b.yaml"),
        "id: team-b\nmax_spend_micro_usd: 9000\n",
    )
    .await
    .unwrap();

    store.reload().await.unwrap();
    assert_eq!(store.len(), 1, "old policy gone, new one in");
    store.with_policy("team-a", |p| {
        assert!(p.is_none(), "deleted policy must not survive reload");
    });
    store.with_policy("team-b", |p| {
        let p = p.expect("team-b loaded");
        assert_eq!(p.max_spend_micro_usd, Some(9000));
    });
    let _ = tokio::fs::remove_dir_all(&dir).await;
}

fn uuid_like() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos() as u64
}

#[tokio::test]
async fn tool_rules_gate_requested_tools() {
    let store = Arc::new(PolicyStore::from_policies([Policy {
        id: "p1".into(),
        allowed_tools: Some(vec!["search".into()]),
        ..Default::default()
    }]));
    let hook = PolicyHook::new(store, None);

    // a request using only the allowed tool passes
    let mut ok = ctx_with_tools(&["search"], Some("p1"));
    assert!(matches!(
        hook.check(&mut ok).await.unwrap(),
        HookDecision::Allow
    ));

    // a request using a tool not in the allowlist is forbidden
    let mut nope = ctx_with_tools(&["search", "filesystem"], Some("p1"));
    match hook.check(&mut nope).await.unwrap() {
        HookDecision::Deny(reason) => {
            let err: bitrouter_sdk::BitrouterError = reason.into();
            assert_eq!(err.status(), 403);
        }
        HookDecision::Allow => panic!("disallowed tool must be forbidden"),
    }
}

#[tokio::test]
async fn spend_cap_is_enforced_via_metering_store() {
    let store = Arc::new(PolicyStore::from_policies([Policy {
        id: "p1".into(),
        max_spend_micro_usd: Some(100),
        ..Default::default()
    }]));
    let metering = fresh_metering().await;

    // Seed an existing 60µ$ row for the caller — under the cap.
    metering
        .record_request(RequestMetric {
            request_id: "r1".into(),
            user_id: "u1".into(),
            api_key_id: "k1".into(),
            launch_id: None,
            session_identity: None,
            model_id: "gpt-5".into(),
            provider_id: "openai".into(),
            prompt_tokens: 10,
            completion_tokens: 5,
            reasoning_tokens: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            uncached_input_tokens: 10,
            output_tokens: 5,
            usage_origin: Default::default(),
            raw_usage: None,
            charge_status: ChargeStatus::Computed,
            charge_evidence: test_charge_evidence(60),
            reconciliation_status: Default::default(),
            estimated_charge_micro_usd: 60,
            latency_ms: 100,
            generation_time_ms: 80,
            streamed: false,
            error: None,
        })
        .await
        .unwrap();
    let hook = PolicyHook::new(store.clone(), Some(metering.clone()));
    let mut c = ctx("gpt-5", Some("p1"));
    assert!(
        matches!(hook.check(&mut c).await.unwrap(), HookDecision::Allow),
        "60µ$ < 100µ$ cap → allow"
    );

    // Push the rolling spend over the cap.
    metering
        .record_request(RequestMetric {
            request_id: "r2".into(),
            user_id: "u1".into(),
            api_key_id: "k1".into(),
            launch_id: None,
            session_identity: None,
            model_id: "gpt-5".into(),
            provider_id: "openai".into(),
            prompt_tokens: 10,
            completion_tokens: 5,
            reasoning_tokens: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            uncached_input_tokens: 10,
            output_tokens: 5,
            usage_origin: Default::default(),
            raw_usage: None,
            charge_status: ChargeStatus::Computed,
            charge_evidence: test_charge_evidence(50),
            reconciliation_status: Default::default(),
            estimated_charge_micro_usd: 50,
            latency_ms: 100,
            generation_time_ms: 80,
            streamed: false,
            error: None,
        })
        .await
        .unwrap();
    let mut c2 = ctx("gpt-5", Some("p1"));
    match hook.check(&mut c2).await.unwrap() {
        HookDecision::Deny(reason) => {
            let err: bitrouter_sdk::BitrouterError = reason.into();
            assert_eq!(err.status(), 403);
        }
        HookDecision::Allow => panic!("110µ$ > 100µ$ cap should deny"),
    }
}

#[tokio::test]
async fn spend_cap_fails_closed_when_prior_charge_is_unknown() {
    let store = Arc::new(PolicyStore::from_policies([Policy {
        id: "p1".into(),
        max_spend_micro_usd: Some(100),
        ..Default::default()
    }]));
    let metering = fresh_metering().await;
    metering
        .record_request(RequestMetric {
            request_id: "unknown-charge".into(),
            user_id: "u1".into(),
            api_key_id: "k1".into(),
            launch_id: None,
            session_identity: None,
            model_id: "unpriced-model".into(),
            provider_id: "unknown-provider".into(),
            prompt_tokens: 10,
            completion_tokens: 5,
            reasoning_tokens: 0,
            cache_read_tokens: 0,
            cache_write_tokens: 0,
            uncached_input_tokens: 10,
            output_tokens: 5,
            usage_origin: Default::default(),
            raw_usage: None,
            charge_status: ChargeStatus::Unknown,
            charge_evidence: ChargeEvidence {
                status: ChargeStatus::Unknown,
                charge_micro_usd: None,
                normalized_usage: Default::default(),
                effective_rates: EffectivePricingRates::default(),
                pricing_source: PricingSource::Unknown,
                pricing_version: "sha256:unavailable".to_string(),
                unknown_reason: Some("pricing_not_found".to_string()),
            },
            reconciliation_status: Default::default(),
            estimated_charge_micro_usd: 0,
            latency_ms: 100,
            generation_time_ms: 80,
            streamed: false,
            error: None,
        })
        .await
        .unwrap();
    let hook = PolicyHook::new(store, Some(metering));
    let mut request = ctx("unpriced-model", Some("p1"));

    match hook.check(&mut request).await.unwrap() {
        HookDecision::Deny(reason) => {
            let error: bitrouter_sdk::BitrouterError = reason.into();
            assert_eq!(error.status(), 403);
        }
        HookDecision::Allow => panic!("unknown historical spend must fail a hard ceiling closed"),
    }
}

#[tokio::test]
async fn rate_limit_is_enforced_via_metering_store() {
    let store = Arc::new(PolicyStore::from_policies([Policy {
        id: "p1".into(),
        max_requests_per_minute: Some(2),
        ..Default::default()
    }]));
    let metering = fresh_metering().await;

    // Two requests recorded in the trailing minute (this minute) → at limit.
    for i in 0..2 {
        metering
            .record_request(RequestMetric {
                request_id: format!("r{i}"),
                user_id: "u1".into(),
                api_key_id: "k1".into(),
                launch_id: None,
                session_identity: None,
                model_id: "gpt-5".into(),
                provider_id: "openai".into(),
                prompt_tokens: 1,
                completion_tokens: 1,
                reasoning_tokens: 0,
                cache_read_tokens: 0,
                cache_write_tokens: 0,
                uncached_input_tokens: 1,
                output_tokens: 1,
                usage_origin: Default::default(),
                raw_usage: None,
                charge_status: ChargeStatus::Computed,
                charge_evidence: test_charge_evidence(0),
                reconciliation_status: Default::default(),
                estimated_charge_micro_usd: 0,
                latency_ms: 0,
                generation_time_ms: 0,
                streamed: false,
                error: None,
            })
            .await
            .unwrap();
    }
    let hook = PolicyHook::new(store, Some(metering));
    let mut c = ctx("gpt-5", Some("p1"));
    match hook.check(&mut c).await.unwrap() {
        HookDecision::Deny(reason) => {
            let err: bitrouter_sdk::BitrouterError = reason.into();
            assert_eq!(err.status(), 429);
        }
        HookDecision::Allow => panic!("at-limit request must be rate-limited"),
    }
}