meerkat-auth-core 0.7.25

Shared auth primitives for Meerkat: TokenStore backends, RefreshCoordinator impls, OAuth2 helpers, generic cloud-IAM authorizers (AWS SigV4, Google ADC, Azure AD).
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
//! OAuth 2.0 helpers.
//!
//! PKCE, authorize URL, token-exchange, loopback callback, device-code.
//! Used by per-provider OAuth runtimes in Phase 4b (OpenAI ChatGPT,
//! Anthropic Claude.ai, Google Code Assist).
//!
//! Reference-CLI parity:
//! - Codex ChatGPT OAuth: `codex-rs/login/src/server.rs`
//! - Claude Code Claude.ai OAuth: `src/services/oauth/client.ts`
//! - Gemini CLI Google OAuth: `packages/core/src/code_assist/oauth2.ts`

pub mod jwt;

#[cfg(feature = "oauth")]
pub mod callback;
#[cfg(feature = "oauth")]
pub mod device_code;
#[cfg(feature = "oauth")]
pub mod pkce;
#[cfg(feature = "oauth")]
pub mod token_exchange;

#[cfg(feature = "oauth")]
pub use callback::{
    LoopbackBinding, LoopbackHandle, LoopbackOutcome, bind_loopback_callback,
    bind_loopback_callback_with_redirect, run_loopback_callback,
};
#[cfg(feature = "oauth")]
pub use device_code::{
    DeviceCodeResponse, DevicePollOutcome, poll_device_code, request_device_code,
};
#[cfg(feature = "oauth")]
pub use pkce::{PkceChallenge, PkcePair};
#[cfg(feature = "oauth")]
pub use token_exchange::{
    exchange_authorization_code, exchange_authorization_code_with_state, exchange_refresh_token,
};

use meerkat_core::auth::{RefreshError, RefreshFailureObservation};
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Encoding expected by the provider token endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum OAuthTokenRequestFormat {
    #[default]
    FormUrlEncoded,
    Json,
}

/// OAuth endpoint configuration. Each provider's concrete runtime
/// (Phase 4b) embeds one of these with static URLs and client_id.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuthEndpoints {
    pub client_id: String,
    /// Authorization URL (browser flow).
    pub authorize_url: String,
    /// Token exchange URL.
    pub token_url: String,
    /// Device-code endpoint (optional; only for flows that support it).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub device_code_url: Option<String>,
    /// Redirect URI for loopback browser flow.
    pub redirect_uri: String,
    /// Scopes to request.
    pub scopes: Vec<String>,
    /// Provider-specific authorize-query params that are part of the public
    /// login contract, not token-exchange headers.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extra_authorize_params: Vec<(String, String)>,
    /// Provider-specific token request body encoding.
    #[serde(default)]
    pub token_request_format: OAuthTokenRequestFormat,
    /// Some providers require the browser callback state to be echoed in the
    /// authorization-code token exchange request.
    #[serde(default)]
    pub include_state_in_token_exchange: bool,
    /// Provider/resource-specific token request params.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extra_token_params: Vec<(String, String)>,
    /// Scopes to request during refresh-token exchange.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub refresh_scopes: Vec<String>,
    /// Optional "beta" or "x-" headers required during OAuth requests
    /// (e.g., Claude Code's `oauth-2025-04-20` beta header).
    #[serde(default)]
    pub extra_headers: Vec<(String, String)>,
}

impl OAuthEndpoints {
    /// Build the authorize URL with PKCE + state. Callers open this URL in
    /// the browser; the user lands on the OAuth provider's consent screen.
    #[cfg(feature = "oauth")]
    pub fn authorize_url_with_pkce(&self, pkce: &PkceChallenge, state: &str) -> String {
        let mut query = vec![
            ("response_type", "code".to_string()),
            ("client_id", self.client_id.clone()),
            ("redirect_uri", self.redirect_uri.clone()),
            ("code_challenge", pkce.code.clone()),
            ("code_challenge_method", pkce.method.to_string()),
            ("state", state.to_string()),
        ];
        if !self.scopes.is_empty() {
            query.push(("scope", self.scopes.join(" ")));
        }
        query.extend(
            self.extra_authorize_params
                .iter()
                .map(|(key, value)| (key.as_str(), value.clone())),
        );
        let qs = query
            .iter()
            .map(|(k, v)| format!("{k}={}", urlencoding::encode(v)))
            .collect::<Vec<_>>()
            .join("&");
        if self.authorize_url.contains('?') {
            format!("{}&{qs}", self.authorize_url)
        } else {
            format!("{}?{qs}", self.authorize_url)
        }
    }
}

/// Successful OAuth token exchange result.
#[derive(Debug, Clone)]
pub struct OAuthTokenResult {
    pub access_token: String,
    pub refresh_token: Option<String>,
    pub id_token: Option<String>,
    pub expires_in_secs: Option<u64>,
    pub scope: Option<String>,
}

impl OAuthTokenResult {
    pub fn expires_at_from(
        &self,
        now: chrono::DateTime<chrono::Utc>,
    ) -> Result<Option<chrono::DateTime<chrono::Utc>>, OAuthError> {
        let Some(expires_in_secs) = self.expires_in_secs else {
            return Ok(None);
        };
        let signed_seconds = i64::try_from(expires_in_secs)
            .map_err(|_| OAuthError::TokenExpiryOutOfRange { expires_in_secs })?;
        let lifetime = chrono::Duration::try_seconds(signed_seconds)
            .ok_or(OAuthError::TokenExpiryOutOfRange { expires_in_secs })?;
        now.checked_add_signed(lifetime)
            .map(Some)
            .ok_or(OAuthError::TokenExpiryOutOfRange { expires_in_secs })
    }
}

/// OAuth flow errors.
#[derive(Debug, Error)]
pub enum OAuthError {
    #[error("user denied authorization")]
    UserDenied,
    #[error("callback parse error: {0}")]
    CallbackParse(String),
    #[error("token endpoint error: status={status} body={body}")]
    TokenEndpoint { status: u16, body: String },
    #[error("token expires_in is out of range: {expires_in_secs}")]
    TokenExpiryOutOfRange { expires_in_secs: u64 },
    #[error("network error: {0}")]
    Network(String),
    #[error("timeout")]
    Timeout,
    #[error("invalid configuration: {0}")]
    InvalidConfig(String),
    #[error("state mismatch (possible CSRF)")]
    StateMismatch,
    #[error("device flow still pending (poll again)")]
    AuthorizationPending,
    #[error("device flow slow down (increase poll interval)")]
    SlowDown,
    #[error("device flow access denied")]
    AccessDenied,
    #[error("device flow expired")]
    ExpiredToken,
}

/// Typed permanence verdict for an OAuth token-endpoint / refresh failure,
/// derived **structurally** from the HTTP status code and the typed
/// [`OAuthError`] variant — never from free-text body inspection by callers.
///
/// This is the single typed owner of the permanence shape on `OAuthError`:
/// a `400`/`401`/`403`/`422` token-endpoint failure (and the structurally
/// terminal OAuth variants) resolve to [`ReauthRequired`](Self::ReauthRequired);
/// `5xx`, network, timeout, and decode failures resolve to
/// [`Transient`](Self::Transient). The catch-all credential-unusable terminal
/// variants resolve to [`Permanent`](Self::Permanent). Callers that need the
/// reauth-vs-retry boundary classification still route through
/// [`oauth_refresh_observation`] + [`RefreshFailureObservation::requires_reauth`]
/// (which the AuthMachine mirrors); this method gives a typed structural verdict
/// so no caller has to re-parse `OAuthError::TokenEndpoint { body, .. }` text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OAuthRefreshPermanence {
    /// The credential is permanently unusable as observed at this boundary
    /// (e.g. callback parse failure, state mismatch / CSRF, malformed expiry).
    Permanent,
    /// The failure is transient; a later retry of the same credential may
    /// succeed (5xx, network, timeout, decode).
    Transient,
    /// Interactive user reauthorization is required (the authorization grant
    /// or client is no longer valid: 400/401/403/422 at the token endpoint,
    /// user-denied, expired authorization).
    ReauthRequired,
}

impl OAuthError {
    /// Classify this OAuth failure's permanence **structurally** from the typed
    /// variant and HTTP status code, without inspecting any response body text.
    ///
    /// Token-endpoint statuses `400`/`401`/`403`/`422` and the structurally
    /// terminal authorization variants (`UserDenied`, `AccessDenied`,
    /// `ExpiredToken`) require reauth. `5xx` and the transient transport/decode
    /// variants (`Network`, `Timeout`, `CallbackParse`, `TokenExpiryOutOfRange`,
    /// `InvalidConfig`, device-flow pending/slow-down) are transient. A
    /// `StateMismatch` (possible CSRF) is a permanently unusable local
    /// credential.
    pub fn refresh_permanence(&self) -> OAuthRefreshPermanence {
        match self {
            OAuthError::TokenEndpoint { status, .. } => match status {
                400 | 401 | 403 | 422 => OAuthRefreshPermanence::ReauthRequired,
                500..=599 => OAuthRefreshPermanence::Transient,
                // Other 4xx (e.g. 429 rate-limit, 408 request timeout) are
                // transient: the same credential may succeed on retry.
                _ => OAuthRefreshPermanence::Transient,
            },
            OAuthError::UserDenied | OAuthError::AccessDenied | OAuthError::ExpiredToken => {
                OAuthRefreshPermanence::ReauthRequired
            }
            OAuthError::StateMismatch => OAuthRefreshPermanence::Permanent,
            OAuthError::CallbackParse(_)
            | OAuthError::TokenExpiryOutOfRange { .. }
            | OAuthError::Network(_)
            | OAuthError::Timeout
            | OAuthError::InvalidConfig(_)
            | OAuthError::AuthorizationPending
            | OAuthError::SlowDown => OAuthRefreshPermanence::Transient,
        }
    }
}

#[derive(Debug, Deserialize)]
struct OAuthTokenEndpointErrorBody {
    error: Option<String>,
}

pub fn oauth_token_endpoint_error_code(body: &str) -> Option<String> {
    let parsed: OAuthTokenEndpointErrorBody = serde_json::from_str(body).ok()?;
    parsed.error.map(|value| value.to_ascii_lowercase())
}

pub fn oauth_refresh_observation(error: &OAuthError) -> RefreshFailureObservation {
    match error {
        OAuthError::TokenEndpoint { status, body } => {
            RefreshFailureObservation::oauth_token_endpoint(
                *status,
                oauth_token_endpoint_error_code(body),
            )
        }
        OAuthError::UserDenied | OAuthError::AccessDenied => {
            RefreshFailureObservation::oauth_error_code("access_denied")
        }
        OAuthError::ExpiredToken => RefreshFailureObservation::oauth_error_code("expired_token"),
        OAuthError::StateMismatch => RefreshFailureObservation::local_credential_unusable(),
        OAuthError::CallbackParse(_)
        | OAuthError::TokenExpiryOutOfRange { .. }
        | OAuthError::Network(_)
        | OAuthError::Timeout
        | OAuthError::InvalidConfig(_) => RefreshFailureObservation::transient(),
        OAuthError::AuthorizationPending => {
            RefreshFailureObservation::oauth_error_code("authorization_pending")
        }
        OAuthError::SlowDown => RefreshFailureObservation::oauth_error_code("slow_down"),
    }
}

pub fn oauth_refresh_error(error: OAuthError) -> RefreshError {
    let message = error.to_string();
    let observation = oauth_refresh_observation(&error);
    RefreshError::Observed {
        message,
        observation,
    }
}

#[cfg(feature = "oauth")]
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    #[test]
    fn authorize_url_includes_pkce_and_state() {
        let ep = OAuthEndpoints {
            client_id: "cid".into(),
            authorize_url: "https://example.com/oauth/authorize".into(),
            token_url: "https://example.com/oauth/token".into(),
            device_code_url: None,
            redirect_uri: "http://127.0.0.1:8777/callback".into(),
            scopes: vec!["read".into(), "write".into()],
            extra_authorize_params: Vec::new(),
            token_request_format: OAuthTokenRequestFormat::FormUrlEncoded,
            include_state_in_token_exchange: false,
            extra_token_params: Vec::new(),
            refresh_scopes: Vec::new(),
            extra_headers: Vec::new(),
        };
        let pkce = PkcePair::generate_s256();
        let url = ep.authorize_url_with_pkce(&pkce.challenge, "state-abc");
        assert!(url.starts_with("https://example.com/oauth/authorize?"));
        assert!(url.contains("response_type=code"));
        assert!(url.contains("client_id=cid"));
        assert!(url.contains(&format!("code_challenge={}", pkce.challenge.code)));
        assert!(url.contains("code_challenge_method=S256"));
        assert!(url.contains("state=state-abc"));
        assert!(url.contains("scope=read%20write"));
        // redirect_uri is URL-encoded.
        assert!(url.contains("redirect_uri=http%3A%2F%2F127.0.0.1%3A8777%2Fcallback"));
    }

    #[test]
    fn authorize_url_preserves_existing_query() {
        let ep = OAuthEndpoints {
            client_id: "cid".into(),
            authorize_url: "https://example.com/authorize?prompt=consent".into(),
            token_url: "https://example.com/token".into(),
            device_code_url: None,
            redirect_uri: "http://localhost/cb".into(),
            scopes: vec![],
            extra_authorize_params: Vec::new(),
            token_request_format: OAuthTokenRequestFormat::FormUrlEncoded,
            include_state_in_token_exchange: false,
            extra_token_params: Vec::new(),
            refresh_scopes: Vec::new(),
            extra_headers: Vec::new(),
        };
        let pkce = PkcePair::generate_s256();
        let url = ep.authorize_url_with_pkce(&pkce.challenge, "x");
        assert!(url.contains("prompt=consent&response_type=code"));
    }

    #[test]
    fn authorize_url_includes_extra_authorize_params() {
        let ep = OAuthEndpoints {
            client_id: "cid".into(),
            authorize_url: "https://example.com/oauth/authorize".into(),
            token_url: "https://example.com/oauth/token".into(),
            device_code_url: None,
            redirect_uri: "http://localhost:1455/auth/callback".into(),
            scopes: vec!["openid".into()],
            extra_authorize_params: vec![
                ("id_token_add_organizations".into(), "true".into()),
                ("codex_cli_simplified_flow".into(), "true".into()),
                ("originator".into(), "codex_cli_rs".into()),
            ],
            token_request_format: OAuthTokenRequestFormat::FormUrlEncoded,
            include_state_in_token_exchange: false,
            extra_token_params: Vec::new(),
            refresh_scopes: Vec::new(),
            extra_headers: Vec::new(),
        };
        let pkce = PkcePair::generate_s256();
        let url = ep.authorize_url_with_pkce(&pkce.challenge, "state-abc");

        assert!(url.contains("id_token_add_organizations=true"));
        assert!(url.contains("codex_cli_simplified_flow=true"));
        assert!(url.contains("originator=codex_cli_rs"));
    }

    fn token_result(expires_in_secs: Option<u64>) -> OAuthTokenResult {
        OAuthTokenResult {
            access_token: "access-token".to_string(),
            refresh_token: None,
            id_token: None,
            expires_in_secs,
            scope: None,
        }
    }

    #[test]
    fn refresh_permanence_is_structural_not_body_text() {
        // Row #111 gate: token-endpoint permanence is derived from the typed
        // status code, never from free-text body inspection. A 400/401
        // token-endpoint failure must classify as ReauthRequired; a 5xx /
        // network failure must classify as Transient. The body strings here are
        // deliberately misleading ("transient" inside a 400, "invalid_grant"
        // inside a 503) to prove the verdict ignores body text.
        let bad_request = OAuthError::TokenEndpoint {
            status: 400,
            body: "this body literally says transient but is permanent".into(),
        };
        assert_eq!(
            bad_request.refresh_permanence(),
            OAuthRefreshPermanence::ReauthRequired
        );
        let unauthorized = OAuthError::TokenEndpoint {
            status: 401,
            body: String::new(),
        };
        assert_eq!(
            unauthorized.refresh_permanence(),
            OAuthRefreshPermanence::ReauthRequired
        );
        let server_error = OAuthError::TokenEndpoint {
            status: 503,
            body: r#"{"error":"invalid_grant"}"#.into(),
        };
        assert_eq!(
            server_error.refresh_permanence(),
            OAuthRefreshPermanence::Transient
        );
        assert_eq!(
            OAuthError::Network("connection reset".into()).refresh_permanence(),
            OAuthRefreshPermanence::Transient
        );
        assert_eq!(
            OAuthError::Timeout.refresh_permanence(),
            OAuthRefreshPermanence::Transient
        );
        assert_eq!(
            OAuthError::StateMismatch.refresh_permanence(),
            OAuthRefreshPermanence::Permanent
        );
        assert_eq!(
            OAuthError::AccessDenied.refresh_permanence(),
            OAuthRefreshPermanence::ReauthRequired
        );
    }

    #[test]
    fn token_expiry_rejects_lifetime_that_cannot_fit_signed_duration() {
        let result = token_result(Some(u64::MAX));
        let err = result
            .expires_at_from(chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap())
            .expect_err("oversized expires_in must not wrap negative");

        assert!(matches!(
            err,
            OAuthError::TokenExpiryOutOfRange {
                expires_in_secs: u64::MAX
            }
        ));
    }

    #[test]
    fn token_expiry_rejects_timestamp_overflow() {
        let result = token_result(Some(1));
        let err = result
            .expires_at_from(chrono::DateTime::<chrono::Utc>::MAX_UTC)
            .expect_err("expires_in must not overflow DateTime bounds");

        assert!(matches!(
            err,
            OAuthError::TokenExpiryOutOfRange { expires_in_secs: 1 }
        ));
    }
}