meerkat 0.8.17

Modular, high-performance agent harness for LLM-powered applications
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
//! Runtime-independent interactive-auth service for native embedding hosts.
//!
//! The host owns loopback HTTP, browser launch, and UI. This service owns
//! target/owner resolution, PKCE and one-time state, token exchange,
//! coordinated persistence, AuthMachine lifecycle publication, status, and
//! logout.

use chrono::{DateTime, Utc};
use meerkat_core::connection::{WriteOwnerError, resolve_write_owner};
use meerkat_core::handles::{AUTH_LEASE_TTL_REFRESH_WINDOW_SECS, LeaseKey};
use meerkat_core::{
    AuthBindingRef, AuthStatusPhase, BindingId, Config, OAuthProviderIdentity, ProfileId, Provider,
    RealmId, ResolvedConnectionTarget,
};
use meerkat_providers::auth_oauth::{OAuthError, PkcePair, exchange_authorization_code_with_state};
use meerkat_providers::auth_store::{
    CredentialMutationError, PersistedTokens, ProviderAuthPersistence, TokenStoreError,
    credential_source_uses_persisted_store, persisted_auth_mode_is_oauth_login,
};
use meerkat_providers::oauth_flow::{
    OAuthFlowError, OAuthTargetValidationError, oauth_provider_endpoints,
    validate_oauth_login_binding,
};
use serde::{Deserialize, Serialize};

/// Exact provider binding a host wants to inspect or mutate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HostAuthTarget {
    pub provider: OAuthProviderIdentity,
    pub realm_id: RealmId,
    pub binding_id: BindingId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<ProfileId>,
}

/// Secret-free status projection for native UI.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HostAuthStatus {
    pub auth_binding: AuthBindingRef,
    pub provider: Provider,
    pub profile_id: String,
    pub phase: AuthStatusPhase,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub account_id: Option<String>,
}

/// Browser navigation data returned by [`HostAuthService::login_start`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HostAuthLoginStart {
    pub auth_binding: AuthBindingRef,
    pub authorize_url: String,
    pub state: String,
    pub redirect_uri: String,
    pub provider: OAuthProviderIdentity,
}

/// Secret-free successful login projection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HostAuthLoginComplete {
    pub auth_binding: AuthBindingRef,
    pub provider: Provider,
    pub profile_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
    pub has_refresh_token: bool,
    pub scopes: Vec<String>,
}

#[derive(Debug, thiserror::Error)]
pub enum HostAuthError {
    #[error(transparent)]
    Target(#[from] meerkat_core::ConnectionTargetError),
    #[error(transparent)]
    WriteOwner(#[from] WriteOwnerError),
    #[error(transparent)]
    OAuthTarget(#[from] OAuthTargetValidationError),
    #[error(transparent)]
    OAuthFlow(#[from] OAuthFlowError),
    #[error("OAuth token exchange failed")]
    OAuthExchange(#[from] OAuthError),
    #[error(transparent)]
    CredentialMutation(#[from] CredentialMutationError),
    #[error(transparent)]
    TokenStore(#[from] TokenStoreError),
    #[error(transparent)]
    Factory(#[from] meerkat_client::FactoryError),
    #[error("provider auth persistence is not configured for this runtime")]
    PersistenceUnavailable,
    #[error("AuthMachine lifecycle update failed: {0}")]
    Lifecycle(String),
    #[error("credential status rehydration failed: {0}")]
    StatusRehydrate(String),
    #[error("OAuth token expiry is invalid: {0}")]
    InvalidExpiry(String),
}

/// Injectable native-host authentication facade.
#[derive(Clone)]
pub struct HostAuthService {
    persistence: ProviderAuthPersistence,
    authority: meerkat_runtime::ProviderAuthRuntimeAuthority,
    http: reqwest::Client,
}

impl HostAuthService {
    pub fn new(
        persistence: ProviderAuthPersistence,
        authority: meerkat_runtime::ProviderAuthRuntimeAuthority,
    ) -> Self {
        Self {
            persistence,
            authority,
            http: reqwest::Client::new(),
        }
    }

    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
        self.http = http;
        self
    }

    /// Construct the service from the same persistence capability an
    /// [`crate::AgentFactory`] uses for provider resolution.
    pub fn from_factory(
        factory: &crate::AgentFactory,
        authority: meerkat_runtime::ProviderAuthRuntimeAuthority,
    ) -> Result<Self, HostAuthError> {
        let persistence = factory
            .resolution_provider_auth_persistence()
            .map_err(HostAuthError::Factory)?
            .ok_or(HostAuthError::PersistenceUnavailable)?;
        Ok(Self::new(persistence, authority))
    }

    pub async fn status(
        &self,
        config: &Config,
        target: &HostAuthTarget,
    ) -> Result<HostAuthStatus, HostAuthError> {
        let resolved = resolve_target(config, target)?;
        validate_oauth_login_binding(&resolved.backend, &resolved.auth_profile, target.provider)?;
        let auth_binding = resolved.auth_binding;
        let lease_key = LeaseKey::from_auth_binding(&auth_binding);
        let now = Utc::now();
        let auth_lease = self.authority.generated_auth_lease_handle();
        auth_lease
            .observe_credential_freshness(
                &lease_key,
                now.timestamp().max(0) as u64,
                AUTH_LEASE_TTL_REFRESH_WINDOW_SECS,
            )
            .map_err(|error| HostAuthError::Lifecycle(error.to_string()))?;
        let mut snapshot = auth_lease.snapshot(&lease_key);
        let expected_mode =
            meerkat_providers::NormalizedAuthMethod::from_auth_profile(&resolved.auth_profile)
                .and_then(meerkat_providers::NormalizedAuthMethod::persisted_auth_mode);
        let source_uses_store =
            credential_source_uses_persisted_store(&resolved.auth_profile.source);
        let oauth_mode = expected_mode
            .map(persisted_auth_mode_is_oauth_login)
            .unwrap_or(false);
        let store = self.persistence.token_store();
        let mut stored = None;
        if source_uses_store {
            let phase = AuthStatusPhase::from_lease_snapshot(now, &snapshot);
            if phase.is_no_live_lease() {
                if let Some(expected_mode) = expected_mode {
                    stored = meerkat_core::rehydrate_marked_tokens_for_status(
                        store.as_ref(),
                        &auth_lease,
                        &auth_binding,
                        expected_mode,
                        now,
                    )
                    .await
                    .map_err(|error| HostAuthError::StatusRehydrate(error.to_string()))?;
                    snapshot = auth_lease.snapshot(&lease_key);
                }
            } else {
                stored = store
                    .load(&meerkat_providers::auth_store::TokenKey::from_auth_binding(
                        &auth_binding,
                    ))
                    .await?;
            }
        }
        if stored
            .as_ref()
            .is_some_and(|tokens| Some(tokens.auth_mode) != expected_mode)
        {
            stored = None;
        }
        let marker_snapshot;
        let projection_snapshot = if oauth_mode {
            marker_snapshot = stored.as_ref().and_then(|tokens| {
                meerkat_core::oauth_status_projection_snapshot_from_newer_marker(&snapshot, tokens)
            });
            marker_snapshot.as_ref().unwrap_or(&snapshot)
        } else {
            &snapshot
        };
        let projection =
            meerkat_core::project_published_auth_status(now, stored.as_ref(), projection_snapshot);
        Ok(HostAuthStatus {
            auth_binding,
            provider: target.provider.provider(),
            profile_id: resolved.auth_profile.id,
            phase: projection.phase,
            expires_at: projection.expires_at,
            account_id: projection
                .tokens
                .and_then(|tokens| tokens.account_id.clone()),
        })
    }

    pub async fn login_start(
        &self,
        config: &Config,
        target: &HostAuthTarget,
        redirect_uri: impl Into<String>,
    ) -> Result<HostAuthLoginStart, HostAuthError> {
        let redirect_uri = redirect_uri.into();
        let resolved = resolve_writable_oauth_target(config, target)?;
        let pkce = PkcePair::generate_s256();
        let lease_key = LeaseKey::from_auth_binding(&resolved.auth_binding);
        let _guard = meerkat_core::acquire_auth_login_lifecycle_guard(&lease_key).await;
        let state = self.authority.oauth_flow_authority().start(
            resolved.auth_binding.clone(),
            target.provider,
            redirect_uri.clone(),
            pkce.verifier.secret().clone(),
        )?;
        let authorize_url = oauth_provider_endpoints(target.provider, redirect_uri.clone())
            .authorize_url_with_pkce(&pkce.challenge, &state);
        Ok(HostAuthLoginStart {
            auth_binding: resolved.auth_binding,
            authorize_url,
            state,
            redirect_uri,
            provider: target.provider,
        })
    }

    pub async fn login_complete(
        &self,
        config: &Config,
        target: &HostAuthTarget,
        redirect_uri: impl Into<String>,
        state: impl Into<String>,
        code: impl AsRef<str>,
    ) -> Result<HostAuthLoginComplete, HostAuthError> {
        let redirect_uri = redirect_uri.into();
        let state = state.into();
        let resolved = resolve_writable_oauth_target(config, target)?;
        let oauth_flow_authority = self.authority.oauth_flow_authority();
        let flow = oauth_flow_authority.verify(
            &state,
            &resolved.auth_binding,
            target.provider,
            &redirect_uri,
        )?;
        let endpoints = oauth_provider_endpoints(target.provider, redirect_uri.clone());
        let exchanged = exchange_authorization_code_with_state(
            &self.http,
            &endpoints,
            code.as_ref(),
            &flow.pkce_verifier,
            target.provider.client_secret(),
            Some(&state),
        )
        .await?;
        let now = Utc::now();
        let expires_at = exchanged
            .expires_at_from(now)
            .map_err(|error| HostAuthError::InvalidExpiry(error.to_string()))?;
        let tokens = PersistedTokens {
            auth_mode: target.provider.auth_mode(),
            primary_secret: Some(exchanged.access_token),
            refresh_token: exchanged.refresh_token,
            id_token: exchanged.id_token,
            expires_at,
            last_refresh: Some(now),
            scopes: exchanged
                .scope
                .as_deref()
                .map(|scope| scope.split_whitespace().map(String::from).collect())
                .unwrap_or_default(),
            account_id: None,
            metadata: serde_json::Value::Null,
        };
        let committed =
            meerkat_providers::browser_login::save_oauth_tokens_and_consume_browser_flow(
                self.persistence.clone(),
                self.authority.generated_auth_lease_handle(),
                resolved.auth_binding.clone(),
                tokens,
                meerkat_providers::browser_login::BrowserOAuthFlowCommit {
                    authority: oauth_flow_authority,
                    state,
                    provider: target.provider,
                    redirect_uri,
                },
            )
            .await?;
        Ok(HostAuthLoginComplete {
            auth_binding: resolved.auth_binding,
            provider: target.provider.provider(),
            profile_id: resolved.auth_profile.id,
            expires_at: committed.expires_at,
            has_refresh_token: committed.refresh_token.is_some(),
            scopes: committed.scopes,
        })
    }

    pub async fn logout(
        &self,
        config: &Config,
        target: &HostAuthTarget,
    ) -> Result<AuthBindingRef, HostAuthError> {
        let resolved = resolve_writable_oauth_target(config, target)?;
        meerkat_core::clear_tokens_and_publish_lifecycle_released_coordinated(
            self.persistence.clone(),
            self.authority.generated_auth_lease_handle(),
            resolved.auth_binding.clone(),
        )
        .await?;
        Ok(resolved.auth_binding)
    }
}

fn resolve_target(
    config: &Config,
    target: &HostAuthTarget,
) -> Result<ResolvedConnectionTarget, HostAuthError> {
    Ok(meerkat_core::resolve_realm_binding_target_for_provider(
        config,
        target.provider.provider(),
        Some(&target.realm_id),
        Some(&target.binding_id),
        target.profile_id.as_ref(),
        None,
        false,
    )?)
}

fn resolve_writable_target(
    config: &Config,
    target: &HostAuthTarget,
) -> Result<ResolvedConnectionTarget, HostAuthError> {
    let resolved = resolve_target(config, target)?;
    resolve_write_owner(config, &target.realm_id, &target.binding_id)?;
    Ok(resolved)
}

fn resolve_writable_oauth_target(
    config: &Config,
    target: &HostAuthTarget,
) -> Result<ResolvedConnectionTarget, HostAuthError> {
    let resolved = resolve_writable_target(config, target)?;
    validate_oauth_login_binding(&resolved.backend, &resolved.auth_profile, target.provider)?;
    Ok(resolved)
}

#[cfg(test)]
mod tests {
    use super::*;
    use meerkat_core::{
        AuthProfileConfig, BackendProfileConfig, CredentialSourceSpec, ProviderBindingConfig,
        RealmConfigSection,
    };
    use std::sync::Arc;

    fn config_with_inherited_openai() -> Config {
        let mut config = Config::default();
        let mut global = RealmConfigSection::default();
        global.backend.insert(
            "openai".to_string(),
            BackendProfileConfig {
                provider: "openai".to_string(),
                backend_kind: "chatgpt_backend".to_string(),
                base_url: None,
                options: serde_json::Value::Null,
            },
        );
        global.auth.insert(
            "openai".to_string(),
            AuthProfileConfig {
                provider: "openai".to_string(),
                auth_method: "managed_chatgpt_oauth".to_string(),
                source: CredentialSourceSpec::ManagedStore,
                constraints: Default::default(),
                metadata_defaults: Default::default(),
            },
        );
        global.binding.insert(
            "openai".to_string(),
            ProviderBindingConfig {
                backend_profile: "openai".to_string(),
                auth_profile: "openai".to_string(),
                default_model: Some("gpt-5.4".to_string()),
                policy: Default::default(),
                provider_default: true,
            },
        );
        config.realm.insert("global".to_string(), global);
        config.realm.insert(
            "project".to_string(),
            RealmConfigSection {
                parent: Some(RealmId::global()),
                ..Default::default()
            },
        );
        config
    }

    #[test]
    fn inherited_login_target_returns_typed_owner_error() {
        let config = config_with_inherited_openai();
        let target = HostAuthTarget {
            provider: OAuthProviderIdentity::OpenAiChatGpt,
            realm_id: RealmId::parse("project").unwrap(),
            binding_id: BindingId::parse("openai").unwrap(),
            profile_id: None,
        };
        let error = resolve_writable_target(&config, &target).unwrap_err();
        assert!(matches!(
            error,
            HostAuthError::WriteOwner(WriteOwnerError::Inherited {
                ref owner,
                ..
            }) if owner == "global"
        ));
    }

    #[test]
    fn read_target_is_owner_stamped() {
        let config = config_with_inherited_openai();
        let target = HostAuthTarget {
            provider: OAuthProviderIdentity::OpenAiChatGpt,
            realm_id: RealmId::parse("project").unwrap(),
            binding_id: BindingId::parse("openai").unwrap(),
            profile_id: None,
        };
        let resolved = resolve_target(&config, &target).unwrap();
        assert_eq!(resolved.auth_binding.realm.as_str(), "global");
    }

    #[test]
    fn oauth_logout_target_rejects_non_oauth_binding() {
        let mut config = config_with_inherited_openai();
        let global = config.realm.get_mut("global").unwrap();
        global.auth.get_mut("openai").unwrap().auth_method = "api_key".to_string();
        global.backend.get_mut("openai").unwrap().backend_kind = "openai_api".to_string();
        let target = HostAuthTarget {
            provider: OAuthProviderIdentity::OpenAiChatGpt,
            realm_id: RealmId::global(),
            binding_id: BindingId::parse("openai").unwrap(),
            profile_id: None,
        };

        assert!(matches!(
            resolve_writable_oauth_target(&config, &target),
            Err(HostAuthError::OAuthTarget(_))
        ));
    }

    #[tokio::test]
    async fn absent_status_is_secret_free_and_owner_stamped() {
        let config = config_with_inherited_openai();
        let runtime = meerkat_runtime::MeerkatMachine::ephemeral();
        let persistence = ProviderAuthPersistence::new(
            Arc::new(meerkat_providers::auth_store::EphemeralTokenStore::new()),
            Arc::new(meerkat_providers::auth_store::InMemoryCoordinator::new()),
        );
        let service = HostAuthService::new(persistence, runtime.provider_auth_runtime_authority());
        let status = service
            .status(
                &config,
                &HostAuthTarget {
                    provider: OAuthProviderIdentity::OpenAiChatGpt,
                    realm_id: RealmId::parse("project").unwrap(),
                    binding_id: BindingId::parse("openai").unwrap(),
                    profile_id: None,
                },
            )
            .await
            .unwrap();

        assert_eq!(status.auth_binding.realm, RealmId::global());
        assert!(status.phase.is_no_live_lease());
        let json = serde_json::to_value(status).unwrap();
        assert!(json.get("primary_secret").is_none());
        assert!(json.get("refresh_token").is_none());
        assert!(json.get("id_token").is_none());
    }
}