README Source History Refs Reviews Compare Notes Search Review guide ai(SMH-PLAN-AIAG0001): resolve credentials and refresh catalogs deterministically 4738c9f1b86c548088d0d93d0e5a055961bbad33
Oliver Jan Krylow <oliver@bugabinga.net > · 11 Sep 2026
unsigned
Browse files Compare 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) Diff layout Auto Unified Split
smith-ai/src/auth.rs Added new file mode 100644+213 / −0 text lines
9 + use std::collections::HashMap;10 + use std::sync::{Arc, Mutex};11 + use std::time::{Duration, SystemTime};14 + #[derive(Clone, Debug, PartialEq, Eq)]15 + pub enum CredentialSource {28 + pub struct Credential {29 + source: CredentialSource,30 + expires_at: Option <SystemTime>,31 + renewed: Option <Arc<dyn Fn () -> Option <String > + Send + Sync >>,37 + pub fn from_env (var: impl Into <String >) -> Self {39 + source: CredentialSource::Env(var.into ()),47 + pub fn explicit (value: impl Into <String >) -> Self {49 + source: CredentialSource::Explicit(value.into ()),57 + pub fn expires_in (mut self, after: Duration) -> Self {58 + self.expires_at = SystemTime::now().checked_add (after);64 + pub fn renew_with (mut self, renew: Arc<dyn Fn () -> Option <String > + Send + Sync >) -> Self {65 + self.renewed = Some (renew);69 + fn is_expired (& self) -> bool {70 + self.expires_at.is_some_and (|at| SystemTime::now() >= at)79 + pub fn secret (& self) -> smith::error::Result <String > {80 + if self.is_expired () {81 + if let Some (renew) = & self.renewed82 + && let Some (fresh) = renew ()86 + return Err (auth ("credential expired and renewal failed" ));89 + CredentialSource::Env(var) => std::env::var(var)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 ()),100 + pub fn is_ready (& self) -> bool {102 + && match & self.source {103 + CredentialSource::Env(var) => {104 + std::env::var(var).is_ok_and (|value| ! value.is_empty ())106 + CredentialSource::Explicit(_ ) => true ,115 + pub fn describe (& self) -> String {116 + match & self.source {117 + CredentialSource::Env(var) => format! ("env:{var}" ),118 + CredentialSource::Explicit(_ ) => "explicit:<redacted>" .to_string (),124 + #[derive(Clone, Default)]125 + pub struct AuthRegistry {126 + credentials: Arc<Mutex<HashMap<String , Credential>>>,132 + pub fn new () -> Self {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);145 + pub fn get (& self, provider: &str ) -> Option <Credential> {149 + .and_then (|guard| guard.get (provider).cloned ())154 + pub fn is_ready (& self, provider: &str ) -> bool {156 + .is_some_and (|credential| credential.is_ready ())160 + fn auth (message: impl Into <String >) -> smith::error::SmithError {161 + smith::error::SmithError::Provider {162 + fault: smith::error::ProviderFault::Authentication {163 + message: message.into (),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>" );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 ));188 + dead.secret ().err ().map (|e| e.code ().to_string ()),189 + Some ("PROVIDER_AUTH" .to_string ())191 + assert! (! dead.is_ready ());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 ();202 + for round in 0 .. 100 {203 + registry.set ("anthropic" , Credential::explicit(format! ("a{round}" )));208 + assert! (registry.is_ready ("openai" ));209 + assert! (registry.is_ready ("anthropic" ));smith-ai/src/lib.rs Modified +6 / −0 text lines
11 11 pub mod anthropic ;pub mod anthropic ;13 15 pub mod conformance ;pub mod conformance ;17 19 pub mod models ;pub mod models ;19 21 pub mod openai ;pub mod openai ;21 25 pub use anthropic::AnthropicDecoder;pub use anthropic::AnthropicDecoder;
26 + pub use auth::{AuthRegistry, Credential, CredentialSource};22 27 pub use conformance::{Expected, Fixture, StreamDecoder};pub use conformance::{Expected, Fixture, StreamDecoder};23 28 pub use gemini::GeminiDecoder;pub use gemini::GeminiDecoder;24 29 pub use models::{Catalog, ModelCapabilities, ModelEntry, ProviderKind};pub use models::{Catalog, ModelCapabilities, ModelEntry, ProviderKind};25 30 pub use openai::OpenAiDecoder;pub use openai::OpenAiDecoder;
31 + pub use refresh::{CatalogSnapshot, CatalogState, RefreshOutcome, refresh};smith-ai/src/refresh.rs Added new file mode 100644+215 / −0 text lines
8 + use crate ::models::Catalog;9 + use smith::tool::CancelHandle;10 + use std::sync::{Arc, Mutex};11 + use std::time::SystemTime;14 + #[derive(Clone, Debug, PartialEq, Eq)]15 + pub struct CatalogSnapshot {17 + pub catalog: Catalog,21 + pub published_at: Option <SystemTime>,25 + #[derive(Clone, Debug)]26 + pub struct CatalogState {27 + inner: Arc<Mutex<CatalogSnapshot>>,36 + pub fn with_builtin () -> smith::error::Result <Self > {38 + inner: Arc::new(Mutex::new(CatalogSnapshot {39 + catalog: Catalog::builtin()? ,48 + pub fn from_snapshot (snapshot: CatalogSnapshot) -> Self {50 + inner: Arc::new(Mutex::new(snapshot)),56 + pub fn snapshot (& self) -> CatalogSnapshot {57 + match self.inner.lock () {58 + Ok (guard) => guard.clone (),59 + Err (poisoned) => poisoned.into_inner ().clone (),65 + #[derive(Clone, Copy, Debug, PartialEq, Eq)]66 + pub enum RefreshOutcome {91 + pub type Fetch = dyn Fn (u64 , & CancelHandle) -> smith::error::Result <(u64 , Catalog)>;100 + state: & CatalogState,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);108 + let attempt = fetch (started_generation, cancel);109 + if cancel.is_cancelled () {110 + return Ok (RefreshOutcome::Cancelled);112 + let Ok ((fetched_generation, catalog)) = attempt else {113 + return Ok (RefreshOutcome::KeptCache);115 + let published = state.snapshot ().generation;116 + if fetched_generation <= published {117 + return Ok (RefreshOutcome::StaleDiscarded);119 + let mut guard = match state.inner.lock () {122 + return Err (smith::error::SmithError::Session {123 + code: "CATALOG_LOCK_POISONED" .to_string (),124 + message: "catalog state lock poisoned" .to_string (),129 + if fetched_generation <= guard.generation {130 + return Ok (RefreshOutcome::StaleDiscarded);132 + guard.generation = fetched_generation;133 + guard.catalog = catalog;134 + guard.published_at = Some (SystemTime::now());135 + Ok (RefreshOutcome::Published {136 + generation: fetched_generation,142 + clippy::unwrap_used,143 + reason = "refresh tests assert on fixed generations" 148 + fn snapshot (generation: u64 ) -> CatalogSnapshot {150 + catalog: Catalog::builtin().unwrap (),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 );164 + fn newer_publication_wins_and_stale_work_is_discarded () {165 + let state = CatalogState::from_snapshot(snapshot (0 ));166 + let cancel = CancelHandle::new();168 + let outcome = refresh (170 + &| _gen, _cancel| Ok ((5 , Catalog::builtin().unwrap ())),174 + assert_eq! (outcome, RefreshOutcome::Published { generation: 5 });177 + let outcome = refresh (179 + &| _gen, _cancel| Ok ((2 , Catalog::builtin().unwrap ())),183 + assert_eq! (outcome, RefreshOutcome::StaleDiscarded);184 + assert_eq! (state.snapshot ().generation, 5 );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 (195 + &| _gen, _cancel| Ok ((9 , Catalog::builtin().unwrap ())),199 + assert_eq! (outcome, RefreshOutcome::Cancelled);200 + let outcome = refresh (203 + Err (smith::error::SmithError::Provider {204 + fault: smith::error::ProviderFault::Transient {205 + message: "offline" .to_string (),212 + assert_eq! (outcome, RefreshOutcome::KeptCache);213 + assert_eq! (state.snapshot ().generation, 3 );