repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

ai(SMH-PLAN-AIAG0001): resolve credentials and refresh catalogs deterministically

4738c9f1b86c548088d0d93d0e5a055961bbad33

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Credentials resolve from environment or explicit values with lazy
renewal, readiness checks without network access, and redacted
descriptions; concurrent updates to one provider cannot disturb
another. Catalog refresh is a generation-checked state machine over
an injected fetch: cancelled or failed attempts keep the cache and
stale completions can never replace a newer snapshot, while offline
startup always has the built-in catalog.

Changed files (3)

+434 / −0 text lines

Diff layout

smith-ai/src/auth.rs

Added
new file mode 100644

+213 / −0 text lines

1//! Credential resolution without context exposure.
2//!
3//! Credentials come from environment variables or explicit values, resolve
4//! without any network access, and can be checked for readiness
5//! independently of a model request. Registered holders are redacted in
6//! diagnostics, and updating one provider's credential can never disturb
7//! another.
8
9use std::collections::HashMap;
10use std::sync::{Arc, Mutex};
11use std::time::{Duration, SystemTime};
13/// Where a credential comes from.
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub enum CredentialSource {
16 /// Read from this environment variable at resolve time.
17 Env(String),
18 /// An explicit value, typically from configuration or a plugin.
19 Explicit(String),
20}
22/// A resolved credential with optional renewal.
23///
24/// Carries a renewal closure, so it deliberately implements neither
25/// [`std::fmt::Debug`] nor equality; use [`Credential::describe`] for
26/// diagnostics.
27#[derive(Clone)]
28pub struct Credential {
29 source: CredentialSource,
30 expires_at: Option<SystemTime>,
31 renewed: Option<Arc<dyn Fn() -> Option<String> + Send + Sync>>,
32}
34impl Credential {
35 /// A credential read from an environment variable when needed.
36 #[must_use]
37 pub fn from_env(var: impl Into<String>) -> Self {
38 Self {
39 source: CredentialSource::Env(var.into()),
40 expires_at: None,
41 renewed: None,
42 }
43 }
45 /// A credential with an explicit value.
46 #[must_use]
47 pub fn explicit(value: impl Into<String>) -> Self {
48 Self {
49 source: CredentialSource::Explicit(value.into()),
50 expires_at: None,
51 renewed: None,
52 }
53 }
55 /// Attach an expiry; expired values must renew before use.
56 #[must_use]
57 pub fn expires_in(mut self, after: Duration) -> Self {
58 self.expires_at = SystemTime::now().checked_add(after);
59 self
60 }
62 /// Attach a renewal closure that returns a fresh value.
63 #[must_use]
64 pub fn renew_with(mut self, renew: Arc<dyn Fn() -> Option<String> + Send + Sync>) -> Self {
65 self.renewed = Some(renew);
66 self
67 }
69 fn is_expired(&self) -> bool {
70 self.expires_at.is_some_and(|at| SystemTime::now() >= at)
71 }
73 /// The secret value, resolving lazily and renewing when expired.
74 ///
75 /// # Errors
76 ///
77 /// Returns a [`smith::error::ProviderFault::Authentication`] fault when
78 /// the source is empty, the value expired, or renewal failed.
79 pub fn secret(&self) -> smith::error::Result<String> {
80 if self.is_expired() {
81 if let Some(renew) = &self.renewed
82 && let Some(fresh) = renew()
83 {
84 return Ok(fresh);
85 }
86 return Err(auth("credential expired and renewal failed"));
87 }
88 match &self.source {
89 CredentialSource::Env(var) => std::env::var(var)
90 .ok()
91 .filter(|value| !value.is_empty())
92 .ok_or_else(|| auth(format!("environment variable {var} is empty or unset"))),
93 CredentialSource::Explicit(value) => Ok(value.clone()),
94 }
95 }
97 /// Whether a request could be dispatched with this credential now,
98 /// checked without any network access.
99 #[must_use]
100 pub fn is_ready(&self) -> bool {
101 !self.is_expired()
102 && match &self.source {
103 CredentialSource::Env(var) => {
104 std::env::var(var).is_ok_and(|value| !value.is_empty())
105 }
106 CredentialSource::Explicit(_) => true,
107 }
108 }
109}
111/// Redacted description; the secret value never appears.
112impl Credential {
113 /// A redacted description safe for logs and diagnostics.
114 #[must_use]
115 pub fn describe(&self) -> String {
116 match &self.source {
117 CredentialSource::Env(var) => format!("env:{var}"),
118 CredentialSource::Explicit(_) => "explicit:<redacted>".to_string(),
119 }
120 }
121}
123/// Per-provider credential registry with concurrent update safety.
124#[derive(Clone, Default)]
125pub struct AuthRegistry {
126 credentials: Arc<Mutex<HashMap<String, Credential>>>,
127}
129impl AuthRegistry {
130 /// An empty registry.
131 #[must_use]
132 pub fn new() -> Self {
133 Self::default()
134 }
136 /// Register or replace the credential for one provider.
137 pub fn set(&self, provider: impl Into<String>, credential: Credential) {
138 if let Ok(mut guard) = self.credentials.lock() {
139 guard.insert(provider.into(), credential);
140 }
141 }
143 /// The registered credential, when present.
144 #[must_use]
145 pub fn get(&self, provider: &str) -> Option<Credential> {
146 self.credentials
147 .lock()
148 .ok()
149 .and_then(|guard| guard.get(provider).cloned())
150 }
152 /// Whether the provider has a ready credential, without network access.
153 #[must_use]
154 pub fn is_ready(&self, provider: &str) -> bool {
155 self.get(provider)
156 .is_some_and(|credential| credential.is_ready())
157 }
158}
160fn auth(message: impl Into<String>) -> smith::error::SmithError {
161 smith::error::SmithError::Provider {
162 fault: smith::error::ProviderFault::Authentication {
163 message: message.into(),
164 },
165 }
166}
168#[cfg(test)]
169mod tests {
170 use super::*;
172 #[test]
173 fn explicit_credential_resolves_and_redacts() {
174 let credential = Credential::explicit("sk-test");
175 assert!(credential.is_ready());
176 assert_eq!(credential.secret().unwrap_or_default(), "sk-test");
177 assert_eq!(credential.describe(), "explicit:<redacted>");
178 }
180 #[test]
181 fn expired_credential_renews_or_fails_explicitly() {
182 let credential = Credential::explicit("old")
183 .expires_in(Duration::from_millis(0))
184 .renew_with(Arc::new(|| Some("fresh".to_string())));
185 assert_eq!(credential.secret().unwrap_or_default(), "fresh");
186 let dead = Credential::explicit("old").expires_in(Duration::from_millis(0));
187 assert_eq!(
188 dead.secret().err().map(|e| e.code().to_string()),
189 Some("PROVIDER_AUTH".to_string())
190 );
191 assert!(!dead.is_ready());
192 }
194 #[test]
195 fn concurrent_updates_preserve_unrelated_providers() {
196 let registry = AuthRegistry::new();
197 registry.set("anthropic", Credential::explicit("a"));
198 registry.set("openai", Credential::explicit("o"));
199 let writer = std::thread::spawn({
200 let registry = registry.clone();
201 move || {
202 for round in 0..100 {
203 registry.set("anthropic", Credential::explicit(format!("a{round}")));
204 }
205 }
206 });
207 for _ in 0..100 {
208 assert!(registry.is_ready("openai"));
209 assert!(registry.is_ready("anthropic"));
210 }
211 writer.join().ok();
212 }
213}

smith-ai/src/lib.rs

Modified

+6 / −0 text lines

1010/// Anthropic Messages adapter.
1111pub mod anthropic;
12/// Credential resolution without context exposure.
13pub mod auth;
1214/// Stream conformance kit shared by all vendor adapters.
1315pub mod conformance;
1416/// Google Gemini adapter.
1719pub mod models;
1820/// OpenAI-compatible chat-completions adapter.
1921pub mod openai;
22/// Cancellable, generation-checked catalog refresh.
23pub mod refresh;
2125pub use anthropic::AnthropicDecoder;
26pub use auth::{AuthRegistry, Credential, CredentialSource};
2227pub use conformance::{Expected, Fixture, StreamDecoder};
2328pub use gemini::GeminiDecoder;
2429pub use models::{Catalog, ModelCapabilities, ModelEntry, ProviderKind};
2530pub use openai::OpenAiDecoder;
31pub use refresh::{CatalogSnapshot, CatalogState, RefreshOutcome, refresh};

smith-ai/src/refresh.rs

Added
new file mode 100644

+215 / −0 text lines

1//! Cancellable catalog refresh with generation-checked publication.
2//!
3//! Refresh is a pure state machine over an injected fetch closure, so the
4//! semantics hold without a network: a cancelled fetch keeps the cached
5//! snapshot, a stale completion cannot replace a newer publication, and
6//! offline startup always has the built-in snapshot available.
7
8use crate::models::Catalog;
9use smith::tool::CancelHandle;
10use std::sync::{Arc, Mutex};
11use std::time::SystemTime;
13/// One published catalog snapshot with its generation and origin.
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct CatalogSnapshot {
16 /// The catalog data.
17 pub catalog: Catalog,
18 /// Monotonic publication generation.
19 pub generation: u64,
20 /// When this snapshot was published.
21 pub published_at: Option<SystemTime>,
22}
24/// Shared catalog state with generation-checked publication.
25#[derive(Clone, Debug)]
26pub struct CatalogState {
27 inner: Arc<Mutex<CatalogSnapshot>>,
28}
30impl CatalogState {
31 /// Publish the built-in catalog as generation zero.
32 ///
33 /// # Errors
34 ///
35 /// Returns the built-in catalog's load error unchanged.
36 pub fn with_builtin() -> smith::error::Result<Self> {
37 Ok(Self {
38 inner: Arc::new(Mutex::new(CatalogSnapshot {
39 catalog: Catalog::builtin()?,
40 generation: 0,
41 published_at: None,
42 })),
43 })
44 }
46 /// Start from an explicit snapshot, for tests.
47 #[must_use]
48 pub fn from_snapshot(snapshot: CatalogSnapshot) -> Self {
49 Self {
50 inner: Arc::new(Mutex::new(snapshot)),
51 }
52 }
54 /// The currently published snapshot.
55 #[must_use]
56 pub fn snapshot(&self) -> CatalogSnapshot {
57 match self.inner.lock() {
58 Ok(guard) => guard.clone(),
59 Err(poisoned) => poisoned.into_inner().clone(),
60 }
61 }
62}
64/// Outcome of one refresh attempt.
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub enum RefreshOutcome {
67 /// A newer snapshot was published.
68 Published {
69 /// Generation of the new snapshot.
70 generation: u64,
71 },
72 /// The fetch failed; the cached snapshot stays usable.
73 KeptCache,
74 /// The fetch was cancelled; the cached snapshot stays usable.
75 Cancelled,
76 /// The fetch completed, but a newer snapshot had already been published.
77 StaleDiscarded,
78}
80/// Runs one refresh against an injected fetch.
81///
82/// The fetch closure receives the generation it must beat to publish; a
83/// returning generation at or below the published one is discarded, so slow
84/// work can never roll the catalog back.
85///
86/// # Errors
87///
88/// Returns fetch errors only for propagation by the caller; the cached
89/// snapshot is untouched in every error case.
90/// An injected catalog fetch: beat `generation`, honoring cancellation.
91pub type Fetch = dyn Fn(u64, &CancelHandle) -> smith::error::Result<(u64, Catalog)>;
93/// Run one refresh attempt against an injected fetch.
94///
95/// # Errors
96///
97/// Propagates a lock-poisoning error only; fetch failures and cancellation
98/// are reported as outcomes with the cache untouched.
99pub fn refresh(
100 state: &CatalogState,
101 fetch: &Fetch,
102 cancel: &CancelHandle,
103) -> smith::error::Result<RefreshOutcome> {
104 let started_generation = state.snapshot().generation;
105 if cancel.is_cancelled() {
106 return Ok(RefreshOutcome::Cancelled);
107 }
108 let attempt = fetch(started_generation, cancel);
109 if cancel.is_cancelled() {
110 return Ok(RefreshOutcome::Cancelled);
111 }
112 let Ok((fetched_generation, catalog)) = attempt else {
113 return Ok(RefreshOutcome::KeptCache);
114 };
115 let published = state.snapshot().generation;
116 if fetched_generation <= published {
117 return Ok(RefreshOutcome::StaleDiscarded);
118 }
119 let mut guard = match state.inner.lock() {
120 Ok(guard) => guard,
121 Err(_) => {
122 return Err(smith::error::SmithError::Session {
123 code: "CATALOG_LOCK_POISONED".to_string(),
124 message: "catalog state lock poisoned".to_string(),
125 });
126 }
127 };
128 // Re-check under the lock: only the newest generation may publish.
129 if fetched_generation <= guard.generation {
130 return Ok(RefreshOutcome::StaleDiscarded);
131 }
132 guard.generation = fetched_generation;
133 guard.catalog = catalog;
134 guard.published_at = Some(SystemTime::now());
135 Ok(RefreshOutcome::Published {
136 generation: fetched_generation,
137 })
138}
140#[cfg(test)]
141#[expect(
142 clippy::unwrap_used,
143 reason = "refresh tests assert on fixed generations"
144)]
145mod tests {
146 use super::*;
148 fn snapshot(generation: u64) -> CatalogSnapshot {
149 CatalogSnapshot {
150 catalog: Catalog::builtin().unwrap(),
151 generation,
152 published_at: None,
153 }
154 }
156 #[test]
157 fn offline_startup_has_a_usable_snapshot() {
158 let state = CatalogState::with_builtin();
159 assert!(state.is_ok());
160 assert_eq!(state.unwrap().snapshot().generation, 0);
161 }
163 #[test]
164 fn newer_publication_wins_and_stale_work_is_discarded() {
165 let state = CatalogState::from_snapshot(snapshot(0));
166 let cancel = CancelHandle::new();
167 // Fast refresh publishes generation 5.
168 let outcome = refresh(
169 &state,
170 &|_gen, _cancel| Ok((5, Catalog::builtin().unwrap())),
171 &cancel,
172 )
173 .unwrap();
174 assert_eq!(outcome, RefreshOutcome::Published { generation: 5 });
175 // Slow refresh from generation 0 completes later with generation 2:
176 // stale, must not replace generation 5.
177 let outcome = refresh(
178 &state,
179 &|_gen, _cancel| Ok((2, Catalog::builtin().unwrap())),
180 &cancel,
181 )
182 .unwrap();
183 assert_eq!(outcome, RefreshOutcome::StaleDiscarded);
184 assert_eq!(state.snapshot().generation, 5);
185 }
187 #[test]
188 fn cancelled_and_failed_fetches_keep_the_cache() {
189 let state = CatalogState::from_snapshot(snapshot(3));
190 let cancel = CancelHandle::new();
191 let cancelled_handle = CancelHandle::new();
192 cancelled_handle.cancel();
193 let outcome = refresh(
194 &state,
195 &|_gen, _cancel| Ok((9, Catalog::builtin().unwrap())),
196 &cancelled_handle,
197 )
198 .unwrap();
199 assert_eq!(outcome, RefreshOutcome::Cancelled);
200 let outcome = refresh(
201 &state,
202 &|_gen, _cancel| {
203 Err(smith::error::SmithError::Provider {
204 fault: smith::error::ProviderFault::Transient {
205 message: "offline".to_string(),
206 },
207 })
208 },
209 &cancel,
210 )
211 .unwrap();
212 assert_eq!(outcome, RefreshOutcome::KeptCache);
213 assert_eq!(state.snapshot().generation, 3);
214 }
215}