bitrouter 1.0.0-alpha.30

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
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! Cloud authentication glue and the `bitrouter cloud …` CLI entry points.
//!
//! Two daemon-side responsibilities, both keyed on the `"bitrouter"`
//! provider id:
//!
//! - [`enable_in_zero_config`] — auto-add the `bitrouter` provider to the in-memory
//!   zero-config `providers:` map when the user has signed in via
//!   `bitrouter cloud login` (an `account-credentials.json` file is present
//!   at the default path). The env-var path (`$BITROUTER_API_KEY`) is
//!   already covered by [`bitrouter_providers::zero_config`].
//! - [`register_if_configured`] — register the hosted provider applier.
//!
//! These are kept here rather than inside `bitrouter-providers` so that
//! the providers crate stays focused on reusable hosted authentication.
//!
//! The [`cli`] sub-module owns the `bitrouter cloud` subcommand surface
//! — typed wrappers around the application-owned management client.

pub mod api;
pub mod api_client;
pub mod auth;
pub mod cli;
pub mod management;
pub mod settlement;

use std::sync::Arc;

use anyhow::{Context, Result};
use bitrouter_providers::hosted::account::credentials::default_credentials_path;
use bitrouter_providers::hosted::account::manager::CredentialManager;
use bitrouter_providers::hosted::applier::{BitrouterAuthApplier, PROVIDER_ID};
use bitrouter_sdk::config::{Config, ProviderConfig};
use bitrouter_sdk::language_model::auth::AuthAppliers;
use bitrouter_telemetry::otel::TelemetryBearer;

const FIRST_PARTY_TELEMETRY_ORIGIN: &str = "https://telemetry.bitrouter.ai";
const DEFAULT_ACCOUNT_ORIGIN: &str = "https://api.bitrouter.ai";

/// Insert the `bitrouter` provider into `config.providers` when the user
/// has run `bitrouter cloud login` (i.e. the credentials file exists at the
/// default path) and the entry is not already present.
///
/// No-op when the credentials file is absent — `bitrouter_providers::zero_config`
/// already handles the `$BITROUTER_API_KEY` env-var path. Together the two
/// paths give a signed-in user the cloud provider on every fresh
/// `bitrouter serve` regardless of which credential source they chose.
pub fn enable_in_zero_config(config: &mut Config) {
    let Ok(path) = default_credentials_path() else {
        return;
    };
    enable_in_zero_config_with_path(config, &path);
}

/// Inner form taking the credentials path explicitly so unit tests can
/// drive the logic without mutating process environment.
fn enable_in_zero_config_with_path(config: &mut Config, credentials_path: &std::path::Path) {
    if config.providers.contains_key(PROVIDER_ID) {
        return;
    }
    if !credentials_path.exists() {
        return;
    }
    config.providers.insert(
        PROVIDER_ID.to_string(),
        ProviderConfig {
            auto_discover: true,
            ..ProviderConfig::default()
        },
    );
}

/// Construct the default hosted account manager without reading its store.
pub fn default_manager() -> Result<Arc<CredentialManager>> {
    let path = default_credentials_path().context("resolving BitRouter Cloud credentials path")?;
    let manager = CredentialManager::new(path)
        .map_err(|error| anyhow::anyhow!("building BitRouter Cloud credential manager: {error}"))?;
    Ok(Arc::new(manager))
}

/// One lazily constructed account manager shared by the Cloud consumers of a
/// standalone ACP invocation. Construction does not read the credential store;
/// resolution remains best-effort at each consumer boundary.
#[derive(Clone)]
pub(crate) struct StandaloneCloudCredentials {
    manager: Option<Arc<CredentialManager>>,
}

impl StandaloneCloudCredentials {
    /// Construct the invocation-scoped manager once. A path-construction
    /// failure preserves the existing best-effort fallback behavior.
    pub(crate) fn new() -> Self {
        Self {
            manager: default_manager().ok(),
        }
    }

    #[cfg(test)]
    pub(crate) fn with_manager(manager: Arc<CredentialManager>) -> Self {
        Self {
            manager: Some(manager),
        }
    }

    /// Resolve the stored account bearer for ACP routing, when available.
    pub(crate) async fn routing_fallback(&self, target_base_url: &str) -> Option<String> {
        let manager = self.manager.as_ref()?.clone();
        cloud_bearer_for_base_url_with_manager(manager, target_base_url).await
    }

    /// Build the account telemetry source from the same invocation manager.
    pub(crate) async fn telemetry_bearer(
        &self,
        endpoint: &str,
    ) -> Option<Arc<dyn TelemetryBearer>> {
        let manager = self.manager.as_ref()?.clone();
        cloud_bearer_source(manager, endpoint).await
    }
}

/// Register the BitRouter Cloud applier on `appliers` when the `bitrouter`
/// provider appears in `config.providers`. No-op otherwise.
pub fn register_if_configured(
    config: &Config,
    appliers: &mut AuthAppliers,
    manager: Arc<CredentialManager>,
) -> Result<()> {
    if !config.providers.contains_key(PROVIDER_ID) {
        return Ok(());
    }
    appliers.register(PROVIDER_ID, Arc::new(BitrouterAuthApplier::new(manager)));
    Ok(())
}

/// Live [`TelemetryBearer`] backed by the signed-in account manager.
///
/// Resolves the account bearer **on every OTLP export** (not once at startup),
/// transparently refreshing the short-lived access token through the manager,
/// which refreshes-if-near-expiry, single-flights, and writes the rotated token
/// back to disk. This is what keeps
/// account-attributed telemetry alive across token expiry without a daemon
/// restart, replacing the old startup-snapshot baked into a static header.
///
/// Best-effort: any resolution failure maps to `None`, so the export degrades to
/// anonymous rather than being dropped.
pub struct CloudBearer {
    manager: Arc<CredentialManager>,
    expected_origin: String,
}

impl std::fmt::Debug for CloudBearer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CloudBearer")
            .field("manager", &"<redacted>")
            .field("expected_origin", &self.expected_origin)
            .finish()
    }
}

#[async_trait::async_trait]
impl TelemetryBearer for CloudBearer {
    async fn bearer(&self) -> Option<String> {
        self.manager
            .resolve_bearer(None, Some(&self.expected_origin))
            .await
            .map(|credential| credential.secret().to_owned())
            .ok()
    }
}

/// Build a live telemetry-bearer source from the signed-in account, or `None`
/// when not signed in (or the AS metadata can't be fetched).
///
/// Best-effort: every failure (no credential store, no current credential,
/// metadata fetch failure) yields `None` so telemetry exports anonymously and
/// daemon startup is never broken. The caller decides whether to build a source
/// at all — `attribution: anonymous` must never call this (it would read the
/// credential store).
pub async fn cloud_bearer_source(
    manager: Arc<CredentialManager>,
    expected_origin: impl Into<String>,
) -> Option<Arc<dyn TelemetryBearer>> {
    manager.current().await.ok()??;
    let expected_origin = credential_origin_for_exporter(&expected_origin.into());
    Some(Arc::new(CloudBearer {
        manager,
        expected_origin,
    }))
}

/// Return the credential origin permitted for an OTLP exporter.
///
/// Account credentials are normally confined to the exporter's origin. The
/// sole exception is the first-party telemetry service, which accepts the
/// account credential registered at the hosted inference origin.
fn credential_origin_for_exporter(exporter: &str) -> String {
    let exporter_origin = reqwest::Url::parse(exporter)
        .ok()
        .map(|url| url.origin().ascii_serialization());
    match exporter_origin.as_deref() {
        Some(FIRST_PARTY_TELEMETRY_ORIGIN) => DEFAULT_ACCOUNT_ORIGIN.to_owned(),
        _ => exporter.to_owned(),
    }
}

/// Resolve the signed-in Cloud bearer only when `target_base_url` has the
/// exact origin recorded at login. This permits headless gateway clients to
/// reuse `bitrouter cloud login` without ever forwarding that credential to
/// an arbitrary remote host.
pub async fn cloud_bearer_for_base_url(target_base_url: &str) -> Option<String> {
    let manager = default_manager().ok()?;
    cloud_bearer_for_base_url_with_manager(manager, target_base_url).await
}

/// Resolve a hosted bearer for `target_base_url` using the supplied manager.
pub async fn cloud_bearer_for_base_url_with_manager(
    manager: Arc<CredentialManager>,
    target_base_url: &str,
) -> Option<String> {
    manager
        .resolve_bearer(None, Some(target_base_url))
        .await
        .map(|credential| credential.secret().to_owned())
        .ok()
}

/// Resolve only a static inference API key for an exact Cloud origin. OAuth
/// access tokens use `Authorization: Bearer`; settlement receipts are scoped
/// by `x-api-key`, so silently coercing OAuth into that header is invalid.
pub async fn cloud_api_key_for_base_url(target_base_url: &str) -> Option<String> {
    let manager = default_manager().ok()?;
    manager
        .resolve_api_key(None, Some(target_base_url))
        .await
        .map(|credential| credential.secret().to_owned())
        .ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use bitrouter_providers::hosted::account::credentials::{Credentials, StoredCredential};
    use bitrouter_providers::hosted::account::manager::CredentialManager;
    use bitrouter_providers::hosted::applier::BitrouterAuthApplier;
    use bitrouter_sdk::language_model::AuthApplier;
    use bitrouter_sdk::language_model::types::{ApiProtocol, RoutingTarget};
    use chrono::{Duration, Utc};
    use serde_json::json;
    use wiremock::matchers::{body_string_contains, method, path as wm_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn fresh_tmp_creds_path(
        label: &str,
    ) -> anyhow::Result<(tempfile::TempDir, std::path::PathBuf)> {
        let directory = tempfile::Builder::new()
            .prefix(&format!("bitrouter-cloud-glue-{label}-"))
            .tempdir()?;
        let path = directory.path().join("account-credentials.json");
        Ok((directory, path))
    }

    fn target_for_origin(origin: &str) -> RoutingTarget {
        RoutingTarget {
            provider_name: bitrouter_providers::hosted::applier::PROVIDER_ID.to_owned(),
            service_id: "gpt-4o".to_owned(),
            api_base: origin.to_owned(),
            api_key: String::new(),
            api_protocol: ApiProtocol::ChatCompletions,
            chat_token_limit_field: None,
            chat_supports_store: None,
            chat_supports_stream_options: None,
            reasoning_effort: None,
            account_label: None,
            api_key_override: None,
            api_base_override: None,
            auth_scheme: Default::default(),
        }
    }

    #[tokio::test]
    async fn shared_manager_single_flights_oauth_refresh_for_auth_and_telemetry()
    -> anyhow::Result<()> {
        let server = MockServer::start().await;
        let origin = server.uri();
        Mock::given(method("GET"))
            .and(wm_path("/.well-known/oauth-authorization-server"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "issuer": origin,
                "device_authorization_endpoint": format!("{origin}/oauth/device_authorization"),
                "token_endpoint": format!("{origin}/oauth/token"),
            })))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(wm_path("/oauth/token"))
            .and(body_string_contains("grant_type=refresh_token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "access_token": "rotated-access",
                "token_type": "Bearer",
                "expires_in": 3600,
                "refresh_token": "rotated-refresh",
                "scope": "inference:invoke",
            })))
            .mount(&server)
            .await;

        let (_directory, path) = fresh_tmp_creds_path("shared-refresh")?;
        let manager = Arc::new(CredentialManager::with_client(
            path.clone(),
            reqwest::Client::new(),
        ));
        manager
            .save(
                bitrouter_providers::hosted::account::credentials::StoredCredential::from(
                    bitrouter_providers::hosted::account::credentials::Credentials {
                        access_token: "stale-access".to_owned(),
                        refresh_token: Some("original-refresh".to_owned()),
                        expires_at: Utc::now() + Duration::seconds(10),
                        refresh_token_expires_at: None,
                        token_type: "Bearer".to_owned(),
                        scope: "inference:invoke".to_owned(),
                        client_id: "bitrouter-cli".to_owned(),
                        authorization_server: origin.clone(),
                        namespace_id: Some("ns-test".to_owned()),
                        subject: None,
                    },
                ),
            )
            .await?;

        let applier = BitrouterAuthApplier::new(Arc::clone(&manager));
        let telemetry = CloudBearer {
            manager: Arc::clone(&manager),
            expected_origin: origin.clone(),
        };
        let request = reqwest::Client::new().post(&origin).build()?;
        let target = target_for_origin(&origin);
        let (applied, bearer) = tokio::join!(applier.apply(request, &target), telemetry.bearer(),);
        assert_eq!(
            applied?.headers()[reqwest::header::AUTHORIZATION],
            "Bearer rotated-access"
        );
        assert_eq!(bearer.as_deref(), Some("rotated-access"));
        let current = manager
            .current()
            .await?
            .ok_or_else(|| anyhow::anyhow!("rotated credential was not persisted"))?;
        let oauth = current
            .oauth()
            .ok_or_else(|| anyhow::anyhow!("rotated credential is not OAuth"))?;
        assert_eq!(oauth.refresh_token.as_deref(), Some("rotated-refresh"));
        let refreshes = server
            .received_requests()
            .await
            .ok_or_else(|| anyhow::anyhow!("wiremock did not record requests"))?
            .into_iter()
            .filter(|request| request.method == "POST")
            .count();
        assert_eq!(refreshes, 1);
        Ok(())
    }

    #[test]
    fn enable_in_zero_config_noop_when_no_credentials_file() -> anyhow::Result<()> {
        let (_directory, path) = fresh_tmp_creds_path("noop")?;
        // path's parent exists; the file itself does not.
        let mut config = Config::default();
        enable_in_zero_config_with_path(&mut config, &path);
        assert!(!config.providers.contains_key(PROVIDER_ID));
        Ok(())
    }

    #[test]
    fn enable_in_zero_config_inserts_when_credentials_file_present() -> anyhow::Result<()> {
        let (_directory, path) = fresh_tmp_creds_path("inserts")?;
        std::fs::write(&path, "{}")?;
        let mut config = Config::default();
        enable_in_zero_config_with_path(&mut config, &path);
        let provider = match config.providers.get(PROVIDER_ID) {
            Some(provider) => provider,
            None => anyhow::bail!("bitrouter provider was not auto-enabled"),
        };
        assert!(
            provider.auto_discover,
            "auto_discover should be true so /models populates the routable list"
        );
        Ok(())
    }

    #[test]
    fn enable_in_zero_config_noop_when_already_configured() -> anyhow::Result<()> {
        let (_directory, path) = fresh_tmp_creds_path("already")?;
        std::fs::write(&path, "{}")?;
        let mut config = Config::default();
        // Pre-populate with a sentinel `api_base` so we can prove we didn't
        // overwrite the existing entry.
        config.providers.insert(
            PROVIDER_ID.to_string(),
            ProviderConfig {
                api_base: "https://example.invalid".to_string(),
                ..ProviderConfig::default()
            },
        );
        enable_in_zero_config_with_path(&mut config, &path);
        let provider = match config.providers.get(PROVIDER_ID) {
            Some(provider) => provider,
            None => anyhow::bail!("configured bitrouter provider disappeared"),
        };
        assert_eq!(provider.api_base, "https://example.invalid");
        Ok(())
    }

    #[tokio::test]
    async fn cloud_bearer_source_none_when_not_signed_in() -> anyhow::Result<()> {
        let (_directory, path) = fresh_tmp_creds_path("absent")?;
        let manager = Arc::new(CredentialManager::with_client(path, reqwest::Client::new()));
        assert!(
            cloud_bearer_source(manager, "https://telemetry.bitrouter.ai")
                .await
                .is_none()
        );
        Ok(())
    }

    #[tokio::test]
    async fn cloud_bearer_source_uses_custom_exporter_same_origin_api_key() -> anyhow::Result<()> {
        let (_directory, path) = fresh_tmp_creds_path("api-key-bearer")?;
        let manager = Arc::new(CredentialManager::with_client(path, reqwest::Client::new()));
        manager
            .save(StoredCredential::api_key(
                "brk_telemetry.secret".to_owned(),
                "https://collector.example".to_owned(),
            ))
            .await?;
        let source = match cloud_bearer_source(manager, "https://collector.example/v1/traces").await
        {
            Some(source) => source,
            None => anyhow::bail!("stored API key did not produce a telemetry source"),
        };
        assert_eq!(
            source.bearer().await.as_deref(),
            Some("brk_telemetry.secret")
        );
        Ok(())
    }

    #[tokio::test]
    async fn default_first_party_exporter_uses_default_account_credential() -> anyhow::Result<()> {
        let (_directory, path) = fresh_tmp_creds_path("default-telemetry-origin")?;
        let manager = Arc::new(CredentialManager::with_client(path, reqwest::Client::new()));
        manager
            .save(StoredCredential::api_key(
                "brk_default-account.secret".to_owned(),
                "https://api.bitrouter.ai".to_owned(),
            ))
            .await?;
        let source = match cloud_bearer_source(manager, "https://telemetry.bitrouter.ai/v1/traces")
            .await
        {
            Some(source) => source,
            None => anyhow::bail!("default account credential did not produce telemetry source"),
        };
        assert_eq!(
            source.bearer().await.as_deref(),
            Some("brk_default-account.secret")
        );
        Ok(())
    }

    #[tokio::test]
    async fn custom_exporter_cannot_receive_default_account_credential() -> anyhow::Result<()> {
        let (_directory, path) = fresh_tmp_creds_path("custom-telemetry-origin")?;
        let manager = Arc::new(CredentialManager::with_client(path, reqwest::Client::new()));
        manager
            .save(StoredCredential::api_key(
                "brk_default-account.secret".to_owned(),
                "https://api.bitrouter.ai".to_owned(),
            ))
            .await?;
        let source = match cloud_bearer_source(manager, "https://collector.example/v1/traces").await
        {
            Some(source) => source,
            None => anyhow::bail!("stored credential did not produce telemetry source"),
        };
        assert!(source.bearer().await.is_none());
        Ok(())
    }

    #[tokio::test]
    async fn cloud_gateway_bearer_is_scoped_to_the_login_origin() -> anyhow::Result<()> {
        let (_directory, path) = fresh_tmp_creds_path("gateway-origin")?;
        let manager = Arc::new(CredentialManager::with_client(path, reqwest::Client::new()));
        manager
            .save(StoredCredential::api_key(
                "brk_gateway.secret".to_owned(),
                "https://api.bitrouter.ai".to_owned(),
            ))
            .await?;

        assert_eq!(
            cloud_bearer_for_base_url_with_manager(
                Arc::clone(&manager),
                "https://api.bitrouter.ai/v1/responses",
            )
            .await
            .as_deref(),
            Some("brk_gateway.secret")
        );
        assert!(
            cloud_bearer_for_base_url_with_manager(manager, "https://api.bitrouter.ai.evil/v1")
                .await
                .is_none()
        );
        Ok(())
    }

    #[tokio::test]
    async fn settlement_resolver_rejects_oauth_but_accepts_same_origin_api_key()
    -> anyhow::Result<()> {
        let (_oauth_directory, oauth_path) = fresh_tmp_creds_path("settlement-oauth")?;
        let oauth = Arc::new(CredentialManager::with_client(
            oauth_path,
            reqwest::Client::new(),
        ));
        oauth
            .save(StoredCredential::from(Credentials {
                access_token: "oauth-access-token".to_owned(),
                refresh_token: Some("oauth-refresh-token".to_owned()),
                expires_at: Utc::now() + Duration::minutes(10),
                refresh_token_expires_at: None,
                token_type: "Bearer".to_owned(),
                scope: "inference:invoke".to_owned(),
                client_id: "bitrouter-cli".to_owned(),
                authorization_server: "https://api.bitrouter.ai".to_owned(),
                namespace_id: Some("ns-test".to_owned()),
                subject: None,
            }))
            .await?;
        assert!(
            oauth
                .resolve_api_key(None, Some("https://api.bitrouter.ai"))
                .await
                .is_err()
        );
        let (_api_key_directory, api_key_path) = fresh_tmp_creds_path("settlement-api-key")?;
        let api_key = Arc::new(CredentialManager::with_client(
            api_key_path,
            reqwest::Client::new(),
        ));
        api_key
            .save(StoredCredential::api_key(
                "brk_gateway.secret".to_owned(),
                "https://api.bitrouter.ai".to_owned(),
            ))
            .await?;
        let resolved = api_key
            .resolve_api_key(None, Some("https://api.bitrouter.ai/v1"))
            .await?;
        assert_eq!(resolved.secret(), "brk_gateway.secret");
        Ok(())
    }

    #[test]
    fn cloud_bearer_debug_redacts_manager() -> anyhow::Result<()> {
        let (_directory, path) = fresh_tmp_creds_path("dbg")?;
        let manager = Arc::new(CredentialManager::with_client(path, reqwest::Client::new()));
        let bearer = CloudBearer {
            manager,
            expected_origin: "https://telemetry.bitrouter.ai".to_owned(),
        };
        let rendered = format!("{bearer:?}");
        assert!(rendered.contains("<redacted>"));
        Ok(())
    }

    #[tokio::test]
    async fn malformed_credentials_file_is_swallowed_as_anonymous() -> anyhow::Result<()> {
        let (_directory, path) = fresh_tmp_creds_path("malformed")?;
        std::fs::write(&path, "{ not valid json")?;
        let manager = Arc::new(CredentialManager::with_client(path, reqwest::Client::new()));
        assert!(
            cloud_bearer_source(manager, "https://telemetry.bitrouter.ai")
                .await
                .is_none()
        );
        Ok(())
    }
}