meerkat-core 0.8.4

Core agent logic for Meerkat (no I/O deps)
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
//! TokenStore trait + PersistedTokens/TokenKey types + RefreshCoordinator.
//!
//! Moved from `meerkat-providers::auth_store` (B2 split, 2026-04-18) so
//! the trait surface is reachable without heavy-IO dependencies.
//! Concrete backends (File/Keyring/Auto/Ephemeral/InMemory/FileLock)
//! live in `meerkat-auth-core::auth_store`.

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures::future::BoxFuture;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use std::sync::Arc;

use crate::connection::{AuthBindingRef, BindingId, IdentityError, ProfileId, RealmId};

/// Key for a persisted token bundle: realm + binding + optional auth profile override.
///
/// Wave-c C-12 / C-1 follow-up: `realm_id: String` / `binding_id: String`
/// retyped to `realm: RealmId` / `binding: BindingId` to match the typed-atom
/// rename C-1 did on `AuthBindingRef`. Consumers that need the flat string
/// form use `.realm.as_str()` / `.binding.as_str()` at the exact site that
/// needs it (path segments, log lines, keyring account keys).
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize, Ord, PartialOrd)]
pub struct TokenKey {
    pub realm: RealmId,
    pub binding: BindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile: Option<ProfileId>,
}

impl TokenKey {
    /// Construct a token key from already-typed atoms. The primary
    /// constructor — call sites that have the typed forms (e.g. from
    /// `AuthBindingRef.realm` / `AuthBindingRef.binding`) use this
    /// directly. Raw-string call sites build the atoms at their CLI /
    /// wire boundary via `RealmId::parse` / `BindingId::parse` and
    /// fold the resulting `Result<TokenKey, IdentityError>` into their
    /// ambient error handling.
    pub fn new(realm: RealmId, binding: BindingId) -> Self {
        Self {
            realm,
            binding,
            profile: None,
        }
    }

    pub fn new_with_profile(
        realm: RealmId,
        binding: BindingId,
        profile: Option<ProfileId>,
    ) -> Self {
        Self {
            realm,
            binding,
            profile,
        }
    }

    pub fn from_auth_binding(auth_binding: &AuthBindingRef) -> Self {
        Self::new_with_profile(
            auth_binding.realm.clone(),
            auth_binding.binding.clone(),
            auth_binding.profile.clone(),
        )
    }

    /// Construct a token key from raw strings, validating each component
    /// against the slug grammar enforced by
    /// `meerkat_core::connection::{RealmId,BindingId}::parse`. This is
    /// the right entry point for callers that only have flat-string
    /// input — the CLI `--auth-binding` parser, wire-layer handlers,
    /// test fixtures.
    pub fn parse(realm: impl AsRef<str>, binding: impl AsRef<str>) -> Result<Self, IdentityError> {
        Self::parse_with_profile(realm, binding, None::<&str>)
    }

    pub fn parse_with_profile(
        realm: impl AsRef<str>,
        binding: impl AsRef<str>,
        profile: Option<impl AsRef<str>>,
    ) -> Result<Self, IdentityError> {
        Ok(Self {
            realm: RealmId::parse(realm.as_ref())?,
            binding: BindingId::parse(binding.as_ref())?,
            profile: profile
                .map(|profile| ProfileId::parse(profile.as_ref()))
                .transpose()?,
        })
    }

    /// The flat account identifier used by OS keyrings.
    ///
    /// Default binding credentials preserve the legacy format:
    /// `<realm>:<binding>`. Profile override credentials include the
    /// canonical override atom: `<realm>:<binding>:<profile>`.
    ///
    /// The default credential format stays identical to the pre-profile-key
    /// output; this method is the source of truth for the keyring
    /// `service:account` convention, so the default branch must preserve that
    /// output byte-for-byte to keep existing OAuth credentials reachable.
    pub fn keyring_account(&self) -> String {
        match &self.profile {
            Some(profile) => format!("{}:{}:{}", self.realm, self.binding, profile),
            None => format!("{}:{}", self.realm, self.binding),
        }
    }
}

/// Kind of credential material persisted.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PersistedAuthMode {
    ApiKey,
    StaticBearer,
    ChatgptOauth,
    ClaudeAiOauth,
    OauthToApiKey,
    GoogleOauth,
    Adc,
    ComputeAdc,
    Bedrock,
    Vertex,
    Foundry,
    McpOauth,
    ExternalTokens,
    ExternalAuthorizer,
    Command,
}

/// Serializable token bundle.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PersistedTokens {
    pub auth_mode: PersistedAuthMode,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub primary_secret: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub refresh_token: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub id_token: Option<String>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        with = "chrono::serde::ts_seconds_option"
    )]
    pub expires_at: Option<DateTime<Utc>>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        with = "chrono::serde::ts_seconds_option"
    )]
    pub last_refresh: Option<DateTime<Utc>>,
    #[serde(default)]
    pub scopes: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub account_id: Option<String>,
    #[serde(default)]
    pub metadata: serde_json::Value,
}

impl PersistedTokens {
    pub fn api_key(secret: impl Into<String>) -> Self {
        Self {
            auth_mode: PersistedAuthMode::ApiKey,
            primary_secret: Some(secret.into()),
            refresh_token: None,
            id_token: None,
            expires_at: None,
            last_refresh: None,
            scopes: Vec::new(),
            account_id: None,
            metadata: serde_json::Value::Null,
        }
    }

    pub fn static_bearer(token: impl Into<String>) -> Self {
        Self {
            auth_mode: PersistedAuthMode::StaticBearer,
            primary_secret: Some(token.into()),
            refresh_token: None,
            id_token: None,
            expires_at: None,
            last_refresh: None,
            scopes: Vec::new(),
            account_id: None,
            metadata: serde_json::Value::Null,
        }
    }
}

/// Errors from the token-store layer.
#[derive(Debug, Error)]
pub enum TokenStoreError {
    #[error("io error: {0}")]
    Io(String),
    #[error("serialization error: {0}")]
    Serde(String),
    #[error("keyring backend unavailable: {0}")]
    KeyringUnavailable(String),
    #[error("no credentials found for {realm}:{binding}")]
    NotFound { realm: String, binding: String },
    #[error("permission denied: {0}")]
    PermissionDenied(String),
    #[error("backend unavailable: {0}")]
    Unavailable(String),
}

#[cfg(not(target_arch = "wasm32"))]
impl From<std::io::Error> for TokenStoreError {
    fn from(e: std::io::Error) -> Self {
        match e.kind() {
            std::io::ErrorKind::PermissionDenied => Self::PermissionDenied(e.to_string()),
            std::io::ErrorKind::NotFound => Self::Io(e.to_string()),
            _ => Self::Io(e.to_string()),
        }
    }
}

impl From<serde_json::Error> for TokenStoreError {
    fn from(e: serde_json::Error) -> Self {
        Self::Serde(e.to_string())
    }
}

/// Cross-process-safe persistence for tokens.
///
/// # Vault property: the durable lifecycle marker is the proof-of-acquisition
///
/// `TokenStore` persists credential *material*; the AuthMachine lease owns the
/// credential *lifecycle*. The bridge between the two is the durable lifecycle
/// marker embedded in [`PersistedTokens::metadata`] by
/// `mark_tokens_lifecycle_published_for_transition`: it is stamped from an
/// AuthMachine acquisition transition and is the only durable proof that the
/// machine recorded the acquisition.
///
/// Writers MUST follow acquire-first ordering: acquire the AuthMachine lease
/// (`publish_token_lifecycle_acquired`), stamp the marker from the returned
/// transition, then perform a single `save` of the marked tokens. Unmarked
/// token bytes must never be persisted — on a crash the durable record either
/// carries the marker or does not exist, so no orphan window is
/// representable.
///
/// Readers MUST only use persisted tokens after marker validation through the
/// lifecycle restore path (`restore_marked_token_lifecycle` /
/// `rehydrate_marked_tokens_for_status`) and the AuthMachine admission gate
/// (`resolve_credential_use_admission` in the resolver). A persisted token
/// without a valid marker is dead data: no acquisition was recorded for it,
/// and it must be rejected, never silently adopted.
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait TokenStore: Send + Sync {
    async fn load(&self, key: &TokenKey) -> Result<Option<PersistedTokens>, TokenStoreError>;
    async fn save(&self, key: &TokenKey, tokens: &PersistedTokens) -> Result<(), TokenStoreError>;
    async fn clear(&self, key: &TokenKey) -> Result<(), TokenStoreError>;
    async fn list(&self) -> Result<Vec<TokenKey>, TokenStoreError>;
    fn backend_name(&self) -> &'static str;
}

/// Errors raised by the refresh coordinator.
#[derive(Clone, Debug, Error)]
pub enum RefreshError {
    #[error("refresh function failed: {0}")]
    Refresh(String),
    #[error("refresh function failed: {message}")]
    Observed {
        message: String,
        observation: RefreshFailureObservation,
    },
    #[error("refresh function failed: {message}")]
    Classified {
        message: String,
        observation: RefreshFailureObservation,
        disposition: RefreshFailureDisposition,
    },
    #[error("refresh requires interactive reauthorization: {0}")]
    ReauthRequired(String),
    #[error("refresh in progress was cancelled")]
    Cancelled,
    #[error("cross-process lock acquisition failed: {0}")]
    LockFailed(String),
    #[error("durable credential terminal commit failed: {message}")]
    DurableTerminalCommit {
        message: String,
        observation: RefreshFailureObservation,
        disposition: RefreshFailureDisposition,
    },
}

/// Machine-issued classification of a typed refresh-failure observation.
///
/// AuthMachine is the semantic owner of this verdict. Provider and persistence
/// shells may mirror it for durable ordering and public error projection, but
/// must never construct it by re-evaluating raw HTTP or OAuth fields.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RefreshFailureDisposition {
    /// The refresh may be retried after returning the lease to Expiring.
    Transient,
    /// The credential is terminally unusable and interactive authorization is
    /// required.
    ReauthRequired,
}

/// Typed boundary evidence reported to AuthMachine after a refresh failure.
///
/// This is not a lifecycle classification.  It records facts the provider
/// boundary actually observed; AuthMachine owns the semantic permanent vs.
/// transient transition decision.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RefreshFailureObservation {
    pub http_status: Option<u64>,
    pub oauth_error_code: Option<String>,
    pub local_credential_unusable: bool,
}

impl RefreshFailureObservation {
    pub fn transient() -> Self {
        Self::default()
    }

    pub fn http_status(status: u16) -> Self {
        Self {
            http_status: Some(u64::from(status)),
            ..Self::default()
        }
    }

    pub fn oauth_token_endpoint(status: u16, oauth_error_code: Option<String>) -> Self {
        Self {
            http_status: Some(u64::from(status)),
            oauth_error_code,
            ..Self::default()
        }
    }

    pub fn oauth_error_code(code: impl Into<String>) -> Self {
        Self {
            oauth_error_code: Some(code.into()),
            ..Self::default()
        }
    }

    pub fn local_credential_unusable() -> Self {
        Self {
            local_credential_unusable: true,
            ..Self::default()
        }
    }
}

impl RefreshError {
    pub fn observation(&self) -> RefreshFailureObservation {
        match self {
            Self::Observed { observation, .. }
            | Self::Classified { observation, .. }
            | Self::DurableTerminalCommit { observation, .. } => observation.clone(),
            Self::ReauthRequired(_) => RefreshFailureObservation::local_credential_unusable(),
            Self::Refresh(_) | Self::Cancelled | Self::LockFailed(_) => {
                RefreshFailureObservation::transient()
            }
        }
    }

    /// Return only a disposition issued by AuthMachine's generated classifier.
    /// Unclassified provider errors deliberately return `None` rather than
    /// re-deriving policy from their observation fields.
    pub fn refresh_failure_disposition(&self) -> Option<RefreshFailureDisposition> {
        match self {
            Self::Classified { disposition, .. }
            | Self::DurableTerminalCommit { disposition, .. } => Some(*disposition),
            Self::Refresh(_)
            | Self::Observed { .. }
            | Self::ReauthRequired(_)
            | Self::Cancelled
            | Self::LockFailed(_) => None,
        }
    }
}

/// Boxed refresh closure.
pub type RefreshFn =
    Box<dyn FnOnce() -> BoxFuture<'static, Result<PersistedTokens, RefreshError>> + Send + 'static>;

/// Errors raised while serializing one durable credential mutation.
///
/// Refresh classification remains AuthMachine-owned. This error only describes
/// the mechanics of entering and completing the shared mutation transaction
/// used by refresh and interactive credential replacement.
#[derive(Clone, Debug, Error)]
pub enum CredentialMutationError {
    #[error("credential mutation failed: {0}")]
    Operation(String),
    #[error("credential token-store mutation failed: {0}")]
    TokenStore(String),
    #[error("credential lifecycle mutation failed: {0}")]
    AuthLifecycle(String),
    #[error("credential mutation was cancelled")]
    Cancelled,
    #[error("cross-process credential mutation lock acquisition failed: {0}")]
    LockFailed(String),
}

/// Typed durable result of one exclusive credential mutation.
///
/// Refresh and credential replacement publish the exact persisted token bytes;
/// logout/profile deletion publish the absence of durable credentials. Keeping
/// both outcomes in the coordinator contract lets every mutation share the
/// same per-key cross-process transaction without inventing sentinel tokens or
/// a second locking seam.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CredentialMutationOutcome {
    Persisted(PersistedTokens),
    Cleared,
}

/// Boxed non-coalescing credential mutation closure.
pub type CredentialMutationFn = Box<
    dyn FnOnce() -> BoxFuture<'static, Result<CredentialMutationOutcome, CredentialMutationError>>
        + Send
        + 'static,
>;

/// Coordinator for token-refresh calls. Implementations coalesce
/// concurrent calls for the same `TokenKey`.
#[async_trait]
pub trait RefreshCoordinator: Send + Sync {
    /// Run one per-key credential mutation under the coordinator's in-process
    /// and, when configured, cross-process exclusion boundary.
    ///
    /// Unlike refresh calls, distinct mutations are never coalesced: every
    /// closure runs exactly once after the prior transaction releases the key.
    async fn with_exclusive_mutation(
        &self,
        key: TokenKey,
        mutation_fn: CredentialMutationFn,
    ) -> Result<CredentialMutationOutcome, CredentialMutationError>;

    async fn with_refresh(
        &self,
        key: TokenKey,
        refresh_fn: RefreshFn,
    ) -> Result<PersistedTokens, RefreshError>;

    async fn with_forced_refresh(
        &self,
        key: TokenKey,
        refresh_fn: RefreshFn,
    ) -> Result<PersistedTokens, RefreshError> {
        self.with_refresh(key, refresh_fn).await
    }
}

/// Complete provider-auth persistence capability.
///
/// Rotating provider credentials are only safe when their vault and mutation
/// authority agree. Keeping the [`TokenStore`] and [`RefreshCoordinator`] in
/// one value makes that pairing an invariant of provider-resolution and
/// factory composition instead of a convention reconstructed by each caller.
/// Native persisted backends construct this value from one backend decision;
/// ephemeral hosts and tests must pair their process-local store and
/// coordinator explicitly through [`Self::new`].
#[derive(Clone)]
pub struct ProviderAuthPersistence {
    token_store: Arc<dyn TokenStore>,
    refresh_coordinator: Arc<dyn RefreshCoordinator>,
}

impl ProviderAuthPersistence {
    /// Pair one token vault with the authority that serializes its mutations.
    pub fn new(
        token_store: Arc<dyn TokenStore>,
        refresh_coordinator: Arc<dyn RefreshCoordinator>,
    ) -> Self {
        Self {
            token_store,
            refresh_coordinator,
        }
    }

    pub fn token_store(&self) -> Arc<dyn TokenStore> {
        Arc::clone(&self.token_store)
    }

    pub fn refresh_coordinator(&self) -> Arc<dyn RefreshCoordinator> {
        Arc::clone(&self.refresh_coordinator)
    }
}