costroid_connect/lib.rs
1//! Costroid's network + credential boundary — **the only crate allowed to make a
2//! network call or touch a secret**. Everything else in the workspace is provably
3//! local-only; this crate is the single, deliberate exception, and it is **off by
4//! default** (compiled in only behind a consumer's `connect` Cargo feature — today
5//! `apps/cli`'s, off by default).
6//!
7//! # Status: connections shipped (T8 keychain · T9a client · T9b adapters · T10a/T10c callers)
8//!
9//! This crate carries the keychain-backed store for the user's own usage/billing
10//! API keys ([`CredentialStore`]), a *non-secret* on-disk index of which vendors are
11//! linked ([`ConnectionRegistry`]), the **generic authorized-host HTTPS client**
12//! ([`AuthorizedClient`]): blocking `ureq` + `rustls`, OS-native trust roots, bound to
13//! one explicitly authorized host, redirects disabled, GET-only — and the per-provider
14//! usage-API adapters ([`AnthropicAdapter`]/[`OpenAiAdapter`]; Gemini = first-class
15//! unavailable). Its callers are the `apps/cli` `connect`/`disconnect`/`connections`
16//! CLI (T10a) and the `reconcile` display (T10c): a network call occurs **only** on an
17//! explicit, user-initiated `connect` / `connections --check` / `reconcile` action.
18//!
19//! ## What lives here
20//!
21//! * [`CredentialStore`] — `store` / `retrieve` / `delete` an API key in the OS
22//! keychain via the [`keyring`] crate. Secrets are wrapped in
23//! [`secrecy::SecretString`] in memory and are **never** written to disk, config,
24//! or logs — only the keychain holds them.
25//! * [`ConnectionRegistry`] — the *non-secret* answer to "what is linked?", a small
26//! JSON index at `${XDG_STATE_HOME:-~/.local/state}/costroid/connections.json`. The
27//! OS keychain is not portably enumerable, so this records the connected vendors
28//! (slugs only — zero secret material) for T10's Connections view to read.
29//! * [`ApiVendor`] — the *billing-vendor* axis (whose usage/billing API a key calls):
30//! Anthropic / OpenAI / Gemini. This is deliberately distinct from
31//! `costroid-providers::ProviderId` (the *tool* axis: Claude Code / Codex / Cursor)
32//! — Cursor has no key, and "Anthropic" is not the Claude-Code tool — so this crate
33//! stays free of a `costroid-core`/`costroid-focus` dependency (T9a kept it that
34//! way: the generic client needs no internal type; they arrive with T9b if needed).
35//! * [`AuthorizedClient`] (+ [`AuthHeader`], [`HttpResponse`], [`RequestLimits`]) —
36//! the client described above (in `src/http.rs`): it can only talk to the one host
37//! it was constructed over (off-host requests are a typed error **before any I/O**),
38//! classifies failures (redirect / timeout / 429 / 5xx / other-4xx / transport /
39//! body-too-large) and leaves retry *policy* to its caller, and never lets a
40//! secret-valued header reach logs, `Debug`, or error text.
41//!
42//! # The gate
43//!
44//! `costroid-connect` is compiled into a binary **only** when that binary opts in via
45//! its `connect` Cargo feature. A default `cargo build` of the `costroid` binary never
46//! links it, so the shipped local-only build contains no keychain/HTTP/TLS code at
47//! all. Two tests keep that honest:
48//!
49//! * `apps/cli/tests/offline.rs` — the default build links none of the sanctioned
50//! trio (`keyring`/`ureq`/`rustls`); with `connect` on, exactly that trio is
51//! permitted (and asserted present, since T9a) while async runtimes, OpenSSL,
52//! other HTTP clients, and all telemetry stay forbidden.
53//! * `scripts/offline_acceptance.sh` — the default build runs every command under
54//! network isolation and proves no outbound IP traffic is attempted; its
55//! feature-on baseline proves a normal `--features connect` run attempts none
56//! either, and a network-namespace fail-closed check proves the `connect` action
57//! cannot reach the host (and leaves no `$HOME` residue) when no network exists.
58//!
59//! ## Why the *sync* Secret Service backend (Linux)
60//!
61//! [`keyring`] is configured with the **`sync-secret-service`** backend (blocking
62//! C libdbus, via `dbus-secret-service`) plus pure-Rust crypto (`crypto-rust`), **not**
63//! the `async-secret-service` (zbus) path. That choice keeps **no async runtime** in
64//! the dependency graph — `async-io`/`tokio` stay globally forbidden even under
65//! `--features connect` — at the cost of the C build-deps `libdbus-1-dev` +
66//! `libsecret-1-dev` (installed in CI; ARCHITECTURE). macOS uses the Security
67//! framework (`apple-native`) and Windows the Credential Manager (`windows-native`).
68//!
69//! # The auth source ladder (the rule the future code must obey)
70//!
71//! Every datum is sourced by descending an explicit ladder, most-sanctioned first —
72//! **only tiers 0–3 are ever built** (ARCHITECTURE):
73//!
74//! 0. Local artifacts — provider logs on disk (today's default, *not* this crate).
75//! 1. Sanctioned push/hook — e.g. Claude's `statusLine` capture (also not this crate).
76//! 2. Sanctioned OAuth (first-party; system browser + loopback redirect, PKCE) — T9+.
77//! 3. The user's own API key — official provider *usage* APIs, the user's own key.
78//! 4. **Never** reuse any credential, session, or cookie against a non-sanctioned,
79//! undocumented, or internal endpoint — that datum stays "unavailable", never
80//! fetched.
81//!
82//! No telemetry — ever. Network occurs only on an explicit, user-initiated `connect`
83//! action to a provider endpoint the user authorized (T9/T10).
84//!
85//! [`keyring`]: https://crates.io/crates/keyring
86
87use std::collections::{BTreeMap, BTreeSet};
88use std::fmt;
89use std::fs;
90use std::io;
91use std::path::{Path, PathBuf};
92use std::str::FromStr;
93
94use keyring::{Entry, Error as KeyringError};
95use serde::{Deserialize, Serialize};
96
97mod anthropic;
98mod fetch;
99mod http;
100mod openai;
101/// A `cfg(test)`/`feature = "test-support"`-only loopback HTTP harness (see the module).
102/// `pub` only under the opt-in `test-support` feature so a dependent crate's tests can
103/// drive the connect path against a local `TcpListener` + an in-memory keychain; never
104/// part of the shipping `--features connect` surface.
105#[cfg(any(test, feature = "test-support"))]
106pub mod test_support;
107
108pub use anthropic::{AnthropicAdapter, OrgValidation};
109pub use http::{AuthHeader, AuthorizedClient, HttpResponse, RequestLimits};
110pub use openai::OpenAiAdapter;
111
112// Re-export `secrecy`'s `SecretString` + `ExposeSecret` so the first caller (the T10a
113// `connect` CLI) can wrap a pasted key in the keychain's secret type — and inspect only
114// its non-secret class prefix — without itself depending on `secrecy`. The key is a
115// `SecretString` from the moment it leaves stdin until it lands in the keychain.
116pub use secrecy::{ExposeSecret, SecretString};
117
118// Re-export the core vendor-report vocabulary that appears in the adapters' public
119// signatures, so a `costroid-connect` consumer need not also import from
120// `costroid-core` for the return types. The shapes themselves are owned by
121// `costroid-core::vendor_report` (T9b type-placement pin: connect → core).
122pub use costroid_core::vendor_report::{
123 CostReportOutcome, DateRange, UsageReportOutcome, VendorReportUnavailable,
124};
125
126/// Gemini has **no sanctioned static-key usage API**, so there is no adapter: both
127/// report kinds resolve to a first-class [`VendorReportUnavailable::NoSanctionedStaticKeyApi`]
128/// carrying the pinned reason string (`docs/ROADMAP.md`). T10
129/// renders it; nothing here ever performs a network call for Gemini.
130pub fn gemini_cost_report() -> CostReportOutcome {
131 CostReportOutcome::Unavailable(VendorReportUnavailable::NoSanctionedStaticKeyApi)
132}
133
134/// The usage-report counterpart of [`gemini_cost_report`].
135pub fn gemini_usage_report() -> UsageReportOutcome {
136 UsageReportOutcome::Unavailable(VendorReportUnavailable::NoSanctionedStaticKeyApi)
137}
138
139/// The OS-keychain *service* name under which every Costroid secret is filed. Stable
140/// (changing it would orphan stored keys); the per-secret *account* namespaces the
141/// kind (`apikey:<vendor>` today; `oauth:<vendor>` reserved for the deferred tier-2
142/// OAuth in T9/T10).
143const KEYCHAIN_SERVICE: &str = "costroid";
144
145/// The keychain `service` the real [`CredentialStore`] uses, exposed for the
146/// `test_support` mock-invariant probe so its throwaway `Entry` matches the production
147/// identifiers (one source of truth — no magic string in the guard). Available only to the
148/// in-crate tests and the opt-in `test-support` harness; never part of the production API.
149#[cfg(any(test, feature = "test-support"))]
150pub(crate) fn keychain_service() -> &'static str {
151 KEYCHAIN_SERVICE
152}
153
154/// The keychain account for a vendor's own usage/billing **API key**.
155fn apikey_account(vendor: ApiVendor) -> String {
156 format!("apikey:{}", vendor.slug())
157}
158
159// ---------------------------------------------------------------------------
160// ApiVendor — the billing-vendor axis
161// ---------------------------------------------------------------------------
162
163/// The billing-API vendor a stored key authenticates against — i.e. *whose*
164/// usage/billing API the key calls.
165///
166/// This is the **billing-vendor** axis, deliberately distinct from
167/// `costroid-providers::ProviderId` (the *tool* axis: Claude Code / Codex / Cursor):
168/// Cursor exposes no individual API key, and "Anthropic" is the billing vendor behind
169/// the Claude-Code *tool*, not the tool itself. Keeping them separate is what lets
170/// `costroid-connect` stay free of a providers/core dependency in T8.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
172#[serde(rename_all = "lowercase")]
173pub enum ApiVendor {
174 /// Anthropic (the Claude usage/billing API).
175 Anthropic,
176 /// OpenAI (the Codex/GPT usage/billing API).
177 OpenAI,
178 /// Google Gemini (the Gemini usage/billing API).
179 Gemini,
180}
181
182impl ApiVendor {
183 /// Every vendor T8 can store a key for, in a stable order.
184 pub const ALL: [ApiVendor; 3] = [ApiVendor::Anthropic, ApiVendor::OpenAI, ApiVendor::Gemini];
185
186 /// The stable lowercase slug used in the keychain account and the registry file.
187 /// Must never change (it is part of the on-disk/keychain key).
188 pub fn slug(self) -> &'static str {
189 match self {
190 ApiVendor::Anthropic => "anthropic",
191 ApiVendor::OpenAI => "openai",
192 ApiVendor::Gemini => "gemini",
193 }
194 }
195
196 /// Dense index into a per-vendor array (mirrors [`ApiVendor::ALL`]).
197 fn index(self) -> usize {
198 match self {
199 ApiVendor::Anthropic => 0,
200 ApiVendor::OpenAI => 1,
201 ApiVendor::Gemini => 2,
202 }
203 }
204}
205
206impl fmt::Display for ApiVendor {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 f.write_str(self.slug())
209 }
210}
211
212/// Returned by [`ApiVendor::from_str`] for an unrecognized vendor slug.
213#[derive(Debug, thiserror::Error)]
214#[error("unknown API vendor {0:?} (expected one of: anthropic, openai, gemini)")]
215pub struct ParseVendorError(String);
216
217impl FromStr for ApiVendor {
218 type Err = ParseVendorError;
219
220 fn from_str(s: &str) -> Result<Self, Self::Err> {
221 match s {
222 "anthropic" => Ok(ApiVendor::Anthropic),
223 "openai" => Ok(ApiVendor::OpenAI),
224 "gemini" => Ok(ApiVendor::Gemini),
225 other => Err(ParseVendorError(other.to_string())),
226 }
227 }
228}
229
230// ---------------------------------------------------------------------------
231// Errors
232// ---------------------------------------------------------------------------
233
234/// Anything that can go wrong reaching the OS keychain, the connection registry, or
235/// (since T9a) the authorized host. Library-crate errors are propagated, never
236/// `unwrap`/`panic`, and **no variant ever carries secret material** in its fields,
237/// `Debug`, or `Display` text (pinned by tests).
238#[derive(Debug, thiserror::Error)]
239pub enum ConnectError {
240 /// The OS keychain backend reported an error (other than "no such entry", which
241 /// the store maps to `None`/`Ok` so callers never special-case it). Built only via
242 /// the scrubbing `From<KeyringError>` below — never construct it with an
243 /// unscrubbed `BadEncoding`.
244 #[error("OS keychain error: {0}")]
245 Keyring(#[source] KeyringError),
246
247 /// Reading or writing the non-secret connection registry failed.
248 #[error("connection registry I/O at {path}: {source}")]
249 RegistryIo {
250 /// The path being read or written.
251 path: PathBuf,
252 /// The underlying I/O error.
253 source: io::Error,
254 },
255
256 /// The connection registry file exists but is not valid JSON of the expected shape.
257 #[error("connection registry is corrupt ({path}): {source}")]
258 RegistryFormat {
259 /// The registry path.
260 path: PathBuf,
261 /// The parse/serialize error.
262 source: serde_json::Error,
263 },
264
265 /// Neither `$XDG_STATE_HOME` nor `$HOME` resolves a base directory, so the default
266 /// registry path cannot be computed.
267 #[error("no state directory: set $HOME or $XDG_STATE_HOME")]
268 NoStateDir,
269
270 // ---- the T9a HTTP-client taxonomy (ARCHITECTURE pins) ----------
271 //
272 /// The request URL is not on the client's single authorized host. Raised
273 /// **before any I/O** — the authorized-host guarantee lives in the type.
274 #[error("refusing request to {requested:?}: not the authorized host {authorized:?}")]
275 UnauthorizedHost {
276 /// The (normalized) host the request asked for.
277 requested: String,
278 /// The one host this client is authorized to talk to.
279 authorized: String,
280 },
281
282 /// The authorized host given at construction is not a bare hostname.
283 #[error("invalid authorized host: {reason}")]
284 InvalidHost {
285 /// Why the host was rejected (never echoes secret material).
286 reason: String,
287 },
288
289 /// The request URL could not be validated (not absolute, wrong scheme,
290 /// userinfo, or invalid host characters). Raised before any I/O.
291 #[error("invalid request URL: {reason}")]
292 InvalidUrl {
293 /// Why the URL was rejected (never echoes secret material).
294 reason: String,
295 },
296
297 /// The authorized host answered with a redirect. Redirects are disabled
298 /// entirely — following one could leave the authorized host — so any 3xx is
299 /// refused, never followed.
300 #[error("redirect response (HTTP {status}) — redirects are disabled, refusing to follow")]
301 Redirect {
302 /// The 3xx status received.
303 status: u16,
304 },
305
306 /// The connect or overall deadline elapsed ([`RequestLimits`]).
307 #[error("request timed out")]
308 Timeout,
309
310 /// HTTP 429 — the vendor is rate-limiting. Backoff *policy* is the caller's;
311 /// the parsed `Retry-After` seconds (when present) support it.
312 #[error("rate limited by the authorized host (HTTP 429)")]
313 RateLimited {
314 /// `Retry-After` in seconds, when the response carried the seconds form.
315 retry_after_seconds: Option<u64>,
316 },
317
318 /// HTTP 5xx — the vendor's side failed; degrade, don't fabricate.
319 #[error("server error from the authorized host (HTTP {status})")]
320 ServerError {
321 /// The 5xx status received.
322 status: u16,
323 },
324
325 /// HTTP 4xx other than 429 — wrong key class, missing permission, bad request.
326 /// Carries the (bounded, best-effort UTF-8) response body so a provider adapter can
327 /// classify the cause — e.g. distinguish Anthropic's individual-account 403 from a
328 /// role 403. The body is a vendor **error message**, never a secret: the API key
329 /// rides only in a request header and never appears in a response (pinned by test).
330 #[error("client error from the authorized host (HTTP {status})")]
331 ClientError {
332 /// The 4xx status received.
333 status: u16,
334 /// The response body as UTF-8 text, when present and decodable (else `None`).
335 body: Option<String>,
336 },
337
338 /// A transport-level failure: DNS, TCP connect, TLS, or protocol. The message
339 /// comes from the transport stack and never contains header values.
340 #[error("transport error: {message}")]
341 Transport {
342 /// The transport stack's (secret-free) description.
343 message: String,
344 },
345
346 /// The response body exceeded [`RequestLimits::max_body_bytes`].
347 #[error("response body exceeds the {limit_bytes}-byte limit")]
348 BodyTooLarge {
349 /// The configured cap that was exceeded.
350 limit_bytes: u64,
351 },
352
353 /// The OS-native trust store could not be loaded (or yielded no certificates),
354 /// so an HTTPS client cannot be built.
355 #[error("could not load OS-native TLS roots: {detail}")]
356 NativeRoots {
357 /// The trust-store loader's (secret-free) description.
358 detail: String,
359 },
360
361 /// A 2xx response body did not match the documented schema (a usage-API adapter
362 /// could not parse it, or a money amount was malformed). The detail describes the
363 /// JSON/parse problem and never contains a secret — the API key rides only in a
364 /// request header, never in a response (T9b adapters).
365 #[error("could not parse the vendor response: {detail}")]
366 ResponseFormat {
367 /// The (secret-free) parse-failure description.
368 detail: String,
369 },
370}
371
372impl From<KeyringError> for ConnectError {
373 /// Scrub the one keyring variant that carries secret material: `BadEncoding`
374 /// attaches the RAW stored secret bytes ("available for examination in the attached
375 /// value"), which a `Debug` render of this error would otherwise transit into a
376 /// message or log. The payload is emptied at this boundary — keyring's `Display` is
377 /// already redacted; this keeps `Debug` (and any future serialization) safe too.
378 fn from(err: KeyringError) -> Self {
379 match err {
380 KeyringError::BadEncoding(_) => {
381 ConnectError::Keyring(KeyringError::BadEncoding(Vec::new()))
382 }
383 other => ConnectError::Keyring(other),
384 }
385 }
386}
387
388// ---------------------------------------------------------------------------
389// CredentialStore — secrets, keychain only
390// ---------------------------------------------------------------------------
391
392/// A keychain-backed store for the user's own usage/billing API keys.
393///
394/// Secrets live **only** in the OS keychain (service `costroid`, account
395/// `apikey:<vendor>`); nothing is written to disk, config, or logs. In memory a secret
396/// is always a [`SecretString`], so it cannot be accidentally `Debug`-printed or logged.
397///
398/// The store owns one [`keyring::Entry`] per vendor. Caching the entries (rather than
399/// rebuilding one per call) is what lets the platform-independent **mock** backend —
400/// which persists a secret only inside its own `Entry` — round-trip in tests; for the
401/// real OS backends it is a harmless, cheap handle reuse.
402pub struct CredentialStore {
403 entries: [Entry; 3],
404}
405
406impl CredentialStore {
407 /// Open the keychain store. Fails only if the OS keychain rejects the
408 /// (service, account) identifiers, which the fixed constants never do in practice.
409 pub fn new() -> Result<Self, ConnectError> {
410 Ok(Self {
411 entries: [
412 Entry::new(KEYCHAIN_SERVICE, &apikey_account(ApiVendor::Anthropic))?,
413 Entry::new(KEYCHAIN_SERVICE, &apikey_account(ApiVendor::OpenAI))?,
414 Entry::new(KEYCHAIN_SERVICE, &apikey_account(ApiVendor::Gemini))?,
415 ],
416 })
417 }
418
419 fn entry(&self, vendor: ApiVendor) -> &Entry {
420 &self.entries[vendor.index()]
421 }
422
423 /// Store (or overwrite) the API key for `vendor` in the OS keychain.
424 pub fn store(&self, vendor: ApiVendor, secret: &SecretString) -> Result<(), ConnectError> {
425 self.entry(vendor).set_password(secret.expose_secret())?;
426 Ok(())
427 }
428
429 /// Retrieve the API key for `vendor`, or `None` if none is stored.
430 pub fn retrieve(&self, vendor: ApiVendor) -> Result<Option<SecretString>, ConnectError> {
431 match self.entry(vendor).get_password() {
432 Ok(password) => Ok(Some(SecretString::from(password))),
433 Err(KeyringError::NoEntry) => Ok(None),
434 Err(err) => Err(err.into()),
435 }
436 }
437
438 /// Delete the API key for `vendor`. Deleting a key that is not present is a no-op
439 /// (`Ok`), so `disconnect` is idempotent.
440 pub fn delete(&self, vendor: ApiVendor) -> Result<(), ConnectError> {
441 match self.entry(vendor).delete_credential() {
442 Ok(()) | Err(KeyringError::NoEntry) => Ok(()),
443 Err(err) => Err(err.into()),
444 }
445 }
446}
447
448impl fmt::Debug for CredentialStore {
449 /// Deliberately opaque: never render the entries, whose mock backend would hold a
450 /// secret in memory. The real backends hold no secret here, but a redacting `Debug`
451 /// keeps the no-leak guarantee true regardless of backend.
452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
453 f.debug_struct("CredentialStore").finish_non_exhaustive()
454 }
455}
456
457// ---------------------------------------------------------------------------
458// ConnectionRegistry — the non-secret "what is linked?" index
459// ---------------------------------------------------------------------------
460
461/// A **non-secret** organization label captured at connect time (Anthropic `me`'s
462/// `name`/`id`), stored beside the vendor in the [`ConnectionRegistry`] so the
463/// Connections view can show it offline. Carries **zero** secret material — the API key
464/// itself never leaves the OS keychain.
465#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
466pub struct OrgLabel {
467 /// The organization's display name (e.g. Anthropic `me.name`).
468 pub name: String,
469 /// The organization id, when the vendor returns one (Anthropic `me.id`).
470 #[serde(default, skip_serializing_if = "Option::is_none")]
471 pub id: Option<String>,
472}
473
474impl OrgLabel {
475 /// Build a label from **untrusted, server-provided** text, stripping every control
476 /// character (C0, DEL, and C1 — anything [`char::is_control`], incl. `ESC`/CSI). A
477 /// malicious or buggy org name must not be able to inject a terminal escape sequence
478 /// when the label is later printed, nor smuggle a control byte into the on-disk
479 /// registry. Printable non-ASCII (e.g. an accented org name) is preserved here; the
480 /// `--plain` ASCII floor is enforced separately at the render boundary.
481 pub fn from_server(name: impl AsRef<str>, id: Option<String>) -> Self {
482 OrgLabel {
483 name: strip_control_chars(name.as_ref()),
484 id: id.map(|value| strip_control_chars(&value)),
485 }
486 }
487}
488
489/// Remove control characters from untrusted label text — defense against terminal-escape
490/// injection from a server-controlled string.
491fn strip_control_chars(value: &str) -> String {
492 value.chars().filter(|ch| !ch.is_control()).collect()
493}
494
495/// On-disk shape of the connection registry. Holds **only** vendor slugs and non-secret
496/// org labels — never any secret material. A `BTreeSet`/`BTreeMap` keep it deduplicated
497/// and deterministically ordered (so the file is stable across writes).
498#[derive(Debug, Default, Serialize, Deserialize)]
499struct RegistryFile {
500 connected: BTreeSet<ApiVendor>,
501 /// Optional non-secret org labels, keyed by vendor. Skipped when empty so a
502 /// label-free registry still serializes to exactly `{"connected": [...]}` (the T8
503 /// shape), and so a registry written by an older build round-trips.
504 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
505 labels: BTreeMap<ApiVendor, OrgLabel>,
506}
507
508/// Resolve the default registry path
509/// `${XDG_STATE_HOME:-$HOME/.local/state}/costroid/connections.json`. `None` when
510/// neither `$XDG_STATE_HOME` nor `$HOME` resolves a base directory. (Mirrors the
511/// `claude_rate_limits_cache_path` convention in `costroid-providers`.)
512pub fn default_registry_path() -> Option<PathBuf> {
513 let base = std::env::var_os("XDG_STATE_HOME")
514 .map(PathBuf::from)
515 .filter(|path| !path.as_os_str().is_empty())
516 .or_else(|| {
517 std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".local").join("state"))
518 })?;
519 Some(base.join("costroid").join("connections.json"))
520}
521
522/// A *non-secret* record of which [`ApiVendor`]s are currently linked.
523///
524/// The OS keychain cannot be enumerated portably, so this small JSON index answers
525/// "what is connected?" for the Connections view (T10). It stores vendor slugs only —
526/// **no secret ever lands here**; the keys themselves live solely in the keychain.
527/// Writes are atomic (temp file + rename) so a concurrent reader never sees a torn file,
528/// and the file is written `0600` (owner-only) on Unix as defense in depth for the
529/// non-secret org label.
530///
531/// Concurrency: each mutation is a load → modify → save with **no inter-process lock**, so
532/// two `connect`/`disconnect` actions racing in parallel could lose one update (a
533/// connected-mark or label in this *non-secret* index — never a key, which lives in the
534/// keychain). That is acceptable: connect/disconnect are interactive, one-at-a-time human
535/// actions, and the keychain (the secret's source of truth) plus the presence gate
536/// (`is_connected && key present`) self-heal any stale mark. Do not drive concurrent
537/// mutations from a script; if that ever becomes a need, take an advisory file lock here.
538pub struct ConnectionRegistry {
539 path: PathBuf,
540}
541
542impl ConnectionRegistry {
543 /// Open the registry at its default path (see [`default_registry_path`]).
544 pub fn open() -> Result<Self, ConnectError> {
545 Ok(Self {
546 path: default_registry_path().ok_or(ConnectError::NoStateDir)?,
547 })
548 }
549
550 /// Open the registry at an explicit path — the testable seam (no env access).
551 pub fn at(path: PathBuf) -> Self {
552 Self { path }
553 }
554
555 /// The vendors currently marked connected, in deterministic order.
556 pub fn list(&self) -> Result<Vec<ApiVendor>, ConnectError> {
557 Ok(self.load()?.connected.into_iter().collect())
558 }
559
560 /// Whether `vendor` is currently marked connected.
561 pub fn is_connected(&self, vendor: ApiVendor) -> Result<bool, ConnectError> {
562 Ok(self.load()?.connected.contains(&vendor))
563 }
564
565 /// Mark `vendor` connected (idempotent). Leaves any existing org label untouched.
566 pub fn mark_connected(&self, vendor: ApiVendor) -> Result<(), ConnectError> {
567 let mut file = self.load()?;
568 file.connected.insert(vendor);
569 self.save(&file)
570 }
571
572 /// Mark `vendor` connected and set (or, with `None`, clear) its non-secret org label
573 /// in one atomic write (idempotent). The label carries no secret material.
574 pub fn mark_connected_with_label(
575 &self,
576 vendor: ApiVendor,
577 label: Option<OrgLabel>,
578 ) -> Result<(), ConnectError> {
579 let mut file = self.load()?;
580 file.connected.insert(vendor);
581 match label {
582 Some(label) => {
583 file.labels.insert(vendor, label);
584 }
585 None => {
586 file.labels.remove(&vendor);
587 }
588 }
589 self.save(&file)
590 }
591
592 /// Mark `vendor` disconnected (idempotent; removing an absent vendor is a no-op).
593 /// Also drops any stored org label, so disconnect leaves no residue.
594 pub fn mark_disconnected(&self, vendor: ApiVendor) -> Result<(), ConnectError> {
595 let mut file = self.load()?;
596 file.connected.remove(&vendor);
597 file.labels.remove(&vendor);
598 self.save(&file)
599 }
600
601 /// The non-secret org label recorded for `vendor`, if any.
602 pub fn label(&self, vendor: ApiVendor) -> Result<Option<OrgLabel>, ConnectError> {
603 Ok(self.load()?.labels.get(&vendor).cloned())
604 }
605
606 /// Read the registry file. A missing file is an empty registry (not an error); a
607 /// present-but-malformed file is a [`ConnectError::RegistryFormat`].
608 fn load(&self) -> Result<RegistryFile, ConnectError> {
609 match fs::read(&self.path) {
610 Ok(bytes) => {
611 serde_json::from_slice(&bytes).map_err(|source| ConnectError::RegistryFormat {
612 path: self.path.clone(),
613 source,
614 })
615 }
616 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(RegistryFile::default()),
617 Err(source) => Err(ConnectError::RegistryIo {
618 path: self.path.clone(),
619 source,
620 }),
621 }
622 }
623
624 /// Atomically write the registry: temp file in the same directory, then rename.
625 fn save(&self, file: &RegistryFile) -> Result<(), ConnectError> {
626 if let Some(parent) = self.path.parent() {
627 fs::create_dir_all(parent).map_err(|source| ConnectError::RegistryIo {
628 path: parent.to_path_buf(),
629 source,
630 })?;
631 }
632 let bytes =
633 serde_json::to_vec_pretty(file).map_err(|source| ConnectError::RegistryFormat {
634 path: self.path.clone(),
635 source,
636 })?;
637 let tmp = tmp_sibling(&self.path);
638 fs::write(&tmp, &bytes).map_err(|source| ConnectError::RegistryIo {
639 path: tmp.clone(),
640 source,
641 })?;
642 // Defense in depth: the registry is non-secret, but tighten it to owner-only on Unix
643 // (the org label is mildly sensitive) before the rename, which preserves the mode.
644 #[cfg(unix)]
645 {
646 use std::os::unix::fs::PermissionsExt;
647 fs::set_permissions(&tmp, fs::Permissions::from_mode(0o600)).map_err(|source| {
648 ConnectError::RegistryIo {
649 path: tmp.clone(),
650 source,
651 }
652 })?;
653 }
654 fs::rename(&tmp, &self.path).map_err(|source| ConnectError::RegistryIo {
655 path: self.path.clone(),
656 source,
657 })?;
658 Ok(())
659 }
660}
661
662/// A unique `<path>.<pid>.<n>.tmp` sibling for atomic writes (same directory, so the
663/// rename stays atomic). A FIXED temp name would let two concurrent writers interleave
664/// truncate/write/rename and publish a torn registry file.
665fn tmp_sibling(path: &Path) -> PathBuf {
666 use std::sync::atomic::{AtomicU64, Ordering};
667 static COUNTER: AtomicU64 = AtomicU64::new(0);
668 let serial = COUNTER.fetch_add(1, Ordering::Relaxed);
669 let mut tmp = path.as_os_str().to_owned();
670 tmp.push(format!(".{}.{serial}.tmp", std::process::id()));
671 PathBuf::from(tmp)
672}
673
674#[cfg(test)]
675mod tests {
676 use super::*;
677 use std::sync::Once;
678
679 // The workspace forbids `.unwrap()`/`.expect()` even in tests, so these
680 // panic-on-failure helpers stand in (panics are allowed; cf. apps/cli/tests/offline.rs).
681 #[track_caller]
682 fn ok<T, E: std::fmt::Debug>(result: Result<T, E>) -> T {
683 match result {
684 Ok(value) => value,
685 Err(err) => panic!("expected Ok, got Err: {err:?}"),
686 }
687 }
688 #[track_caller]
689 fn some<T>(value: Option<T>) -> T {
690 match value {
691 Some(value) => value,
692 None => panic!("expected Some, got None"),
693 }
694 }
695
696 // The mock keychain is process-global and must be installed before any `Entry` is
697 // created. A `Once` does it exactly once; each test then builds its own
698 // `CredentialStore`, whose owned entries give it an isolated in-memory store (the
699 // mock persists a secret only inside its own `Entry`), so keychain tests are
700 // independent and parallel-safe without touching any real OS keychain.
701 static MOCK_KEYCHAIN: Once = Once::new();
702 fn use_mock_keychain() {
703 MOCK_KEYCHAIN.call_once(|| {
704 keyring::set_default_credential_builder(keyring::mock::default_credential_builder());
705 });
706 // Enforce the M6 T3 mock invariant locally too: if the install ever fails to take
707 // effect, fail loudly before any `Entry` could reach a real OS keychain.
708 crate::test_support::assert_mock_keychain_active();
709 }
710
711 // ---- The keychain mock invariant (M6 T3 — enforced, not just documented) ----
712
713 /// The non-optional keychain guard (Hazard 1): after `install_mock_keychain()` the
714 /// active backend MUST be the in-memory mock, so no test — here or in any dependent
715 /// crate, on any CI runner OS — can construct a `CredentialStore`/`Entry` that reaches a
716 /// real OS keychain. This asserts the enforcement mechanism actually discriminates: the
717 /// probe downcasts to `MockCredential` only when the mock is live. If a future refactor
718 /// breaks the mock install, this test fails loudly instead of silently hitting the
719 /// runner's keychain. (The check inspects the built backend type only — no keychain I/O.)
720 #[test]
721 fn keychain_mock_invariant_is_enforced() {
722 use_mock_keychain();
723 // The public enforcement entry point: panics loudly unless the mock is active.
724 crate::test_support::assert_mock_keychain_active();
725
726 // And prove it discriminates: a freshly built real store's entries are all the
727 // in-memory mock backend (never an OS-native credential) once the mock is installed.
728 let store = ok(CredentialStore::new());
729 for entry in &store.entries {
730 assert!(
731 entry
732 .get_credential()
733 .downcast_ref::<keyring::mock::MockCredential>()
734 .is_some(),
735 "CredentialStore entry is not the in-memory mock — a real OS keychain backend \
736 is active; the mock invariant is broken"
737 );
738 }
739 }
740
741 /// A unique, auto-cleaned temp directory (no `tempfile` dep — keeps the dev-dep
742 /// graph clean for the offline forbidden-crates check).
743 struct TempDir {
744 path: PathBuf,
745 }
746 impl TempDir {
747 fn new(tag: &str) -> Self {
748 static COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
749 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
750 let path = std::env::temp_dir()
751 .join(format!("costroid-connect-{tag}-{}-{n}", std::process::id()));
752 let _ = fs::remove_dir_all(&path);
753 ok(fs::create_dir_all(&path));
754 Self { path }
755 }
756 }
757 impl Drop for TempDir {
758 fn drop(&mut self) {
759 let _ = fs::remove_dir_all(&self.path);
760 }
761 }
762
763 // ---- ApiVendor -------------------------------------------------------
764
765 #[test]
766 fn vendor_slug_display_and_parse_round_trip() {
767 for vendor in ApiVendor::ALL {
768 assert_eq!(vendor.to_string(), vendor.slug());
769 assert_eq!(ok(vendor.slug().parse::<ApiVendor>()), vendor);
770 }
771 assert!("cursor".parse::<ApiVendor>().is_err());
772 assert!("".parse::<ApiVendor>().is_err());
773 }
774
775 #[test]
776 fn vendor_serializes_as_lowercase_slug() {
777 assert_eq!(ok(serde_json::to_string(&ApiVendor::OpenAI)), "\"openai\"");
778 assert_eq!(
779 ok(serde_json::from_str::<ApiVendor>("\"gemini\"")),
780 ApiVendor::Gemini
781 );
782 }
783
784 #[test]
785 fn gemini_reports_are_first_class_unavailable_with_the_pinned_string() {
786 // No Gemini adapter exists; both report kinds resolve to the pinned unavailable
787 // reason — never a network call, never an error.
788 assert!(matches!(
789 gemini_cost_report(),
790 CostReportOutcome::Unavailable(VendorReportUnavailable::NoSanctionedStaticKeyApi)
791 ));
792 assert!(matches!(
793 gemini_usage_report(),
794 UsageReportOutcome::Unavailable(VendorReportUnavailable::NoSanctionedStaticKeyApi)
795 ));
796 assert_eq!(
797 VendorReportUnavailable::NoSanctionedStaticKeyApi.message(),
798 costroid_core::vendor_report::GEMINI_UNAVAILABLE_MESSAGE
799 );
800 }
801
802 // ---- CredentialStore (mock backend) ---------------------------------
803
804 #[test]
805 fn store_retrieve_delete_round_trips() {
806 use_mock_keychain();
807 let store = ok(CredentialStore::new());
808
809 assert!(ok(store.retrieve(ApiVendor::Anthropic)).is_none());
810
811 let secret = SecretString::from("sk-ant-secret-123".to_string());
812 ok(store.store(ApiVendor::Anthropic, &secret));
813 let got = some(ok(store.retrieve(ApiVendor::Anthropic)));
814 assert_eq!(got.expose_secret(), "sk-ant-secret-123");
815
816 ok(store.delete(ApiVendor::Anthropic));
817 assert!(ok(store.retrieve(ApiVendor::Anthropic)).is_none());
818 // delete is idempotent
819 ok(store.delete(ApiVendor::Anthropic));
820 }
821
822 #[test]
823 fn store_overwrites_existing_key() {
824 use_mock_keychain();
825 let store = ok(CredentialStore::new());
826 ok(store.store(ApiVendor::OpenAI, &SecretString::from("old".to_string())));
827 ok(store.store(ApiVendor::OpenAI, &SecretString::from("new".to_string())));
828 assert_eq!(
829 some(ok(store.retrieve(ApiVendor::OpenAI))).expose_secret(),
830 "new"
831 );
832 }
833
834 #[test]
835 fn vendors_are_independent_slots() {
836 use_mock_keychain();
837 let store = ok(CredentialStore::new());
838 ok(store.store(ApiVendor::Anthropic, &SecretString::from("a".to_string())));
839 ok(store.store(ApiVendor::Gemini, &SecretString::from("g".to_string())));
840 assert_eq!(
841 some(ok(store.retrieve(ApiVendor::Anthropic))).expose_secret(),
842 "a"
843 );
844 assert!(ok(store.retrieve(ApiVendor::OpenAI)).is_none());
845 assert_eq!(
846 some(ok(store.retrieve(ApiVendor::Gemini))).expose_secret(),
847 "g"
848 );
849 }
850
851 #[test]
852 fn credential_store_debug_is_redacted() {
853 use_mock_keychain();
854 let store = ok(CredentialStore::new());
855 ok(store.store(
856 ApiVendor::Anthropic,
857 &SecretString::from("top-secret-xyz".to_string()),
858 ));
859 let rendered = format!("{store:?}");
860 assert!(
861 !rendered.contains("top-secret-xyz"),
862 "CredentialStore Debug must not leak a stored secret, got: {rendered}"
863 );
864 }
865
866 /// The secret-residue guarantee at the unit level: a store→retrieve→delete
867 /// round-trip writes **nothing** to the filesystem (the secret lives only in the
868 /// keychain — here, the in-memory mock). Mirrors the offline-acceptance script's
869 /// "no secret written to disk/config/logs" check, with no real keychain touched.
870 #[test]
871 fn credential_round_trip_writes_nothing_to_disk() {
872 use_mock_keychain();
873 let dir = TempDir::new("residue");
874 let store = ok(CredentialStore::new());
875 ok(store.store(ApiVendor::Gemini, &SecretString::from("k".to_string())));
876 let _ = ok(store.retrieve(ApiVendor::Gemini));
877 ok(store.delete(ApiVendor::Gemini));
878 let entries: Vec<_> = ok(fs::read_dir(&dir.path)).collect();
879 assert!(
880 entries.is_empty(),
881 "the keychain round-trip must write nothing to disk, found: {entries:?}"
882 );
883 }
884
885 // ---- ConnectionRegistry (non-secret, on disk) -----------------------
886
887 #[test]
888 fn registry_missing_file_is_empty() {
889 let dir = TempDir::new("reg-empty");
890 let reg = ConnectionRegistry::at(dir.path.join("connections.json"));
891 assert!(ok(reg.list()).is_empty());
892 assert!(!ok(reg.is_connected(ApiVendor::Anthropic)));
893 }
894
895 #[test]
896 fn registry_marks_lists_and_unmarks() {
897 let dir = TempDir::new("reg-mark");
898 let reg = ConnectionRegistry::at(dir.path.join("connections.json"));
899 ok(reg.mark_connected(ApiVendor::Anthropic));
900 ok(reg.mark_connected(ApiVendor::OpenAI));
901 ok(reg.mark_connected(ApiVendor::Anthropic)); // idempotent
902 assert_eq!(
903 ok(reg.list()),
904 vec![ApiVendor::Anthropic, ApiVendor::OpenAI]
905 );
906 assert!(ok(reg.is_connected(ApiVendor::OpenAI)));
907
908 ok(reg.mark_disconnected(ApiVendor::Anthropic));
909 ok(reg.mark_disconnected(ApiVendor::Gemini)); // absent → no-op
910 assert_eq!(ok(reg.list()), vec![ApiVendor::OpenAI]);
911 }
912
913 #[test]
914 fn registry_persists_only_vendor_slugs_no_secret() {
915 let dir = TempDir::new("reg-content");
916 let path = dir.path.join("connections.json");
917 let reg = ConnectionRegistry::at(path.clone());
918 ok(reg.mark_connected(ApiVendor::Anthropic));
919 ok(reg.mark_connected(ApiVendor::Gemini));
920 let raw = ok(fs::read_to_string(&path));
921 // Exactly the vendor slugs, under a `connected` key — and nothing else.
922 let parsed: serde_json::Value = ok(serde_json::from_str(&raw));
923 assert_eq!(
924 parsed["connected"],
925 serde_json::json!(["anthropic", "gemini"])
926 );
927 assert_eq!(some(parsed.as_object()).len(), 1);
928 }
929
930 #[test]
931 fn registry_stores_and_clears_non_secret_org_labels() {
932 let dir = TempDir::new("reg-label");
933 let path = dir.path.join("connections.json");
934 let reg = ConnectionRegistry::at(path.clone());
935
936 // A label-free connect keeps the T8 shape (only `connected`).
937 ok(reg.mark_connected(ApiVendor::OpenAI));
938 let raw = ok(fs::read_to_string(&path));
939 let parsed: serde_json::Value = ok(serde_json::from_str(&raw));
940 assert_eq!(
941 some(parsed.as_object()).len(),
942 1,
943 "labels skipped when empty"
944 );
945
946 // Connect with a label → it is stored and readable, alongside the slug.
947 let label = OrgLabel {
948 name: "Erens Org".to_string(),
949 id: Some("org-123".to_string()),
950 };
951 ok(reg.mark_connected_with_label(ApiVendor::Anthropic, Some(label.clone())));
952 assert_eq!(some(ok(reg.label(ApiVendor::Anthropic))), label);
953 assert!(ok(reg.label(ApiVendor::OpenAI)).is_none());
954
955 // The file holds the label but no secret-shaped material.
956 let raw = ok(fs::read_to_string(&path));
957 assert!(raw.contains("Erens Org") && raw.contains("org-123"));
958 assert!(
959 !raw.contains("sk-"),
960 "no key material in the registry: {raw}"
961 );
962
963 // Disconnect drops both the slug and the label (no residue).
964 ok(reg.mark_disconnected(ApiVendor::Anthropic));
965 assert!(!ok(reg.is_connected(ApiVendor::Anthropic)));
966 assert!(ok(reg.label(ApiVendor::Anthropic)).is_none());
967 }
968
969 #[test]
970 fn org_label_from_server_strips_control_chars_keeps_printable() {
971 // Untrusted server text: ESC/CSI, tab, newline, DEL are stripped; printable
972 // (incl. non-ASCII) is preserved — so neither the terminal nor connections.json can
973 // carry an injected escape sequence.
974 let label = OrgLabel::from_server(
975 "\u{1b}[2J\tEvil\nCorp Café",
976 Some("org-\u{7f}42".to_string()),
977 );
978 assert_eq!(label.name, "[2JEvilCorp Café");
979 assert!(!label.name.chars().any(|c| c.is_control()));
980 assert_eq!(label.id.as_deref(), Some("org-42"));
981
982 // Persisted to disk, the registry file carries no escape byte.
983 let dir = TempDir::new("reg-label-sanitize");
984 let path = dir.path.join("connections.json");
985 let reg = ConnectionRegistry::at(path.clone());
986 ok(reg.mark_connected_with_label(ApiVendor::Anthropic, Some(label)));
987 let raw = ok(fs::read_to_string(&path));
988 assert!(
989 !raw.contains('\u{1b}'),
990 "no escape byte in registry: {raw:?}"
991 );
992 assert!(
993 raw.contains("[2JEvilCorp"),
994 "sanitized name persisted: {raw}"
995 );
996 }
997
998 #[test]
999 fn registry_rejects_corrupt_file() {
1000 let dir = TempDir::new("reg-corrupt");
1001 let path = dir.path.join("connections.json");
1002 ok(fs::write(&path, b"{ this is not json"));
1003 let reg = ConnectionRegistry::at(path);
1004 assert!(matches!(
1005 reg.list(),
1006 Err(ConnectError::RegistryFormat { .. })
1007 ));
1008 }
1009
1010 #[test]
1011 fn keyring_bad_encoding_payload_is_scrubbed_at_the_boundary() {
1012 // keyring's BadEncoding attaches the RAW stored secret bytes; the From
1013 // conversion must empty that payload so no Debug render of ConnectError can
1014 // ever carry secret material.
1015 let err: ConnectError = KeyringError::BadEncoding(b"super-secret-key".to_vec()).into();
1016 match &err {
1017 ConnectError::Keyring(KeyringError::BadEncoding(bytes)) => {
1018 assert!(bytes.is_empty(), "payload must be scrubbed, got {bytes:?}");
1019 }
1020 other => panic!("expected a scrubbed BadEncoding, got {other:?}"),
1021 }
1022 let rendered = format!("{err:?} / {err}");
1023 assert!(
1024 !rendered.contains("super-secret-key"),
1025 "no render may carry the secret: {rendered}"
1026 );
1027 }
1028
1029 #[test]
1030 fn registry_tmp_siblings_never_collide() {
1031 // A FIXED temp name would let two concurrent writers tear the registry; the
1032 // unique sibling keeps the temp in the same directory (atomic rename).
1033 let path = Path::new("/tmp/example/connections.json");
1034 let first = tmp_sibling(path);
1035 let second = tmp_sibling(path);
1036 assert_ne!(first, second);
1037 assert_eq!(first.parent(), path.parent());
1038 }
1039}