Skip to main content

vtcode_auth/
openrouter_oauth.rs

1//! OpenRouter OAuth PKCE authentication flow.
2//!
3//! This module implements the OAuth PKCE flow for OpenRouter, allowing users
4//! to authenticate with their OpenRouter account securely.
5//!
6//! ## Security Model
7//!
8//! Tokens use the shared credential storage boundary: OS keyring when selected
9//! and AES-256-GCM encrypted files as the fallback backend.
10//!
11//! ### Keyring Storage (Default)
12//! Uses the platform-native credential store:
13//! - **macOS**: Keychain (accessible only to the user)
14//! - **Windows**: Credential Manager (encrypted with user's credentials)
15//! - **Linux**: Secret Service API / libsecret (requires a keyring daemon)
16//!
17//! Existing `openrouter.json` files are decrypted and migrated when loaded.
18
19use anyhow::{Context, Result, anyhow};
20use serde::{Deserialize, Serialize};
21use std::fmt;
22
23pub use super::credentials::AuthCredentialsStoreMode;
24use super::pkce::PkceChallenge;
25use crate::openrouter_token_storage::OpenRouterTokenStorage;
26#[cfg(test)]
27use crate::openrouter_token_storage::{
28    decrypt_legacy_token as decrypt_token, encrypt_legacy_token as encrypt_token, legacy_token_path as get_token_path,
29};
30
31/// OpenRouter API endpoints
32const OPENROUTER_AUTH_URL: &str = "https://openrouter.ai/auth";
33const OPENROUTER_KEYS_URL: &str = "https://openrouter.ai/api/v1/auth/keys";
34
35/// Default callback port for localhost OAuth server
36const DEFAULT_CALLBACK_PORT: u16 = 8484;
37
38/// Configuration for OpenRouter OAuth authentication.
39#[derive(Debug, Clone, Serialize, Deserialize)]
40#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
41#[serde(default)]
42pub struct OpenRouterOAuthConfig {
43    /// Whether to use OAuth instead of API key
44    use_oauth: bool,
45    /// Port for the local callback server
46    pub callback_port: u16,
47    /// Whether to automatically refresh tokens
48    auto_refresh: bool,
49    /// Timeout in seconds for completing the OAuth browser flow.
50    pub flow_timeout_secs: u64,
51}
52
53impl Default for OpenRouterOAuthConfig {
54    fn default() -> Self {
55        Self {
56            use_oauth: false,
57            callback_port: DEFAULT_CALLBACK_PORT,
58            auto_refresh: true,
59            flow_timeout_secs: 300,
60        }
61    }
62}
63
64/// Stored OAuth token with metadata.
65#[derive(Clone, Serialize, Deserialize)]
66pub struct OpenRouterToken {
67    /// The API key obtained via OAuth
68    pub api_key: String,
69    /// When the token was obtained (Unix timestamp)
70    pub obtained_at: u64,
71    /// Optional expiry time (Unix timestamp)
72    pub expires_at: Option<u64>,
73    /// User-friendly label for the token
74    pub label: Option<String>,
75}
76
77impl fmt::Debug for OpenRouterToken {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        f.debug_struct("OpenRouterToken")
80            .field("api_key", &"<redacted>")
81            .field("obtained_at", &self.obtained_at)
82            .field("expires_at", &self.expires_at)
83            .field("label", &self.label)
84            .finish()
85    }
86}
87
88impl OpenRouterToken {
89    /// Check if the token has expired.
90    fn is_expired(&self) -> bool {
91        if let Some(expires_at) = self.expires_at {
92            let now = std::time::SystemTime::now()
93                .duration_since(std::time::UNIX_EPOCH)
94                .map(|d| d.as_secs())
95                .unwrap_or(0);
96            now >= expires_at
97        } else {
98            false
99        }
100    }
101}
102
103/// Generate the OAuth authorization URL.
104///
105/// # Arguments
106/// * `challenge` - PKCE challenge containing the code_challenge
107/// * `callback_port` - Port for the localhost callback server
108///
109/// # Returns
110/// The full authorization URL to redirect the user to.
111pub fn get_auth_url(challenge: &PkceChallenge, callback_port: u16) -> String {
112    let callback_url = format!("http://localhost:{callback_port}/callback");
113    format!(
114        "{}?callback_url={}&code_challenge={}&code_challenge_method={}",
115        OPENROUTER_AUTH_URL,
116        urlencoding::encode(&callback_url),
117        urlencoding::encode(&challenge.code_challenge),
118        challenge.code_challenge_method
119    )
120}
121
122/// Exchange an authorization code for an API key.
123///
124/// This makes a POST request to OpenRouter's token endpoint with the
125/// authorization code and PKCE verifier.
126///
127/// # Arguments
128/// * `code` - The authorization code from the callback URL
129/// * `challenge` - The PKCE challenge used during authorization
130///
131/// # Returns
132/// The obtained API key on success.
133pub async fn exchange_code_for_token(code: &str, challenge: &PkceChallenge) -> Result<String> {
134    let client = vtcode_commons::http::create_default_client_without_redirects()
135        .context("failed to build openrouter token client")?;
136
137    let payload = serde_json::json!({
138        "code": code,
139        "code_verifier": challenge.code_verifier,
140        "code_challenge_method": challenge.code_challenge_method
141    });
142
143    let response = vtcode_commons::http::send_with_retry_transport_only(&crate::oauth_token_retry_policy(), || {
144        client
145            .post(OPENROUTER_KEYS_URL)
146            .header("Content-Type", "application/json")
147            .json(&payload)
148            .send()
149    })
150    .await
151    .context("Failed to send token exchange request")?;
152
153    let status = response.status();
154    if !status.is_success() {
155        // Never expose the raw response body: OAuth providers may echo codes,
156        // tokens, or other sensitive diagnostics in an error payload.
157        return Err(token_exchange_error(status));
158    }
159
160    // Parse the response to extract the key
161    let body = response.text().await.context("Failed to read response body")?;
162    let response_json: serde_json::Value = serde_json::from_str(&body).context("Failed to parse token response")?;
163
164    let api_key = response_json
165        .get("key")
166        .and_then(|v| v.as_str())
167        .ok_or_else(|| anyhow!("Response missing 'key' field"))?
168        .to_string();
169
170    Ok(api_key)
171}
172
173fn token_exchange_error(status: reqwest::StatusCode) -> anyhow::Error {
174    match status.as_u16() {
175        400 => anyhow!("Invalid code_challenge_method. Ensure you're using the same method (S256) in both steps."),
176        403 => anyhow!("Invalid code or code_verifier. The authorization code may have expired."),
177        405 => anyhow!("Method not allowed. Ensure you're using POST over HTTPS."),
178        _ => anyhow!("Token exchange failed (HTTP {status})"),
179    }
180}
181
182/// Save an OAuth token to encrypted storage with specified mode.
183///
184/// # Arguments
185/// * `token` - The OAuth token to save
186/// * `mode` - The storage mode to use
187pub fn save_oauth_token_with_mode(token: &OpenRouterToken, mode: AuthCredentialsStoreMode) -> Result<()> {
188    OpenRouterTokenStorage::new().save(token, mode)
189}
190
191/// Save an OAuth token to encrypted storage using the default mode.
192///
193/// Uses the configured default credential storage mode.
194pub fn save_oauth_token(token: &OpenRouterToken) -> Result<()> {
195    save_oauth_token_with_mode(token, AuthCredentialsStoreMode::default())
196}
197
198/// Load an OAuth token from storage with specified mode.
199///
200/// Returns `None` if no token exists or the token has expired.
201pub fn load_oauth_token_with_mode(mode: AuthCredentialsStoreMode) -> Result<Option<OpenRouterToken>> {
202    let storage = OpenRouterTokenStorage::new();
203    let Some(token) = storage.load(mode)? else {
204        return Ok(None);
205    };
206
207    if token.is_expired() {
208        tracing::warn!("OpenRouter OAuth token has expired, removing it");
209        storage.clear(mode)?;
210        return Ok(None);
211    }
212
213    Ok(Some(token))
214}
215
216/// Load an OAuth token from storage using the default mode.
217///
218/// This function checks the selected secure backend and migrates the legacy
219/// encrypted file format when necessary.
220pub fn load_oauth_token() -> Result<Option<OpenRouterToken>> {
221    let storage = OpenRouterTokenStorage::new();
222    for mode in [AuthCredentialsStoreMode::Keyring, AuthCredentialsStoreMode::File] {
223        let token = match storage.load(mode) {
224            Ok(token) => token,
225            Err(error) if mode == AuthCredentialsStoreMode::Keyring => {
226                tracing::debug!(%error, "optional keyring token lookup unavailable; trying file storage");
227                continue;
228            }
229            Err(error) => return Err(error),
230        };
231        let Some(token) = token else {
232            continue;
233        };
234
235        if token.is_expired() {
236            tracing::warn!("OpenRouter OAuth token has expired, removing it");
237            storage.clear(mode)?;
238            continue;
239        }
240
241        return Ok(Some(token));
242    }
243
244    Ok(None)
245}
246
247/// Clear the stored OAuth token using the selected storage mode.
248pub fn clear_oauth_token_with_mode(mode: AuthCredentialsStoreMode) -> Result<()> {
249    OpenRouterTokenStorage::new().clear(mode)
250}
251
252/// Clear the token from both shared backends and the legacy file format.
253pub fn clear_oauth_token() -> Result<()> {
254    OpenRouterTokenStorage::new().clear_all()
255}
256
257/// Get the current OAuth authentication status.
258pub fn get_auth_status_with_mode(mode: AuthCredentialsStoreMode) -> Result<AuthStatus> {
259    match load_oauth_token_with_mode(mode)? {
260        Some(token) => {
261            let now = std::time::SystemTime::now()
262                .duration_since(std::time::UNIX_EPOCH)
263                .map(|d| d.as_secs())
264                .unwrap_or(0);
265
266            let age_seconds = now.saturating_sub(token.obtained_at);
267
268            Ok(AuthStatus::Authenticated {
269                label: token.label,
270                age_seconds,
271                expires_in: token.expires_at.map(|e| e.saturating_sub(now)),
272            })
273        }
274        None => Ok(AuthStatus::NotAuthenticated),
275    }
276}
277
278pub fn get_auth_status() -> Result<AuthStatus> {
279    match load_oauth_token()? {
280        Some(token) => {
281            let now = std::time::SystemTime::now()
282                .duration_since(std::time::UNIX_EPOCH)
283                .map(|d| d.as_secs())
284                .unwrap_or(0);
285
286            let age_seconds = now.saturating_sub(token.obtained_at);
287
288            Ok(AuthStatus::Authenticated {
289                label: token.label,
290                age_seconds,
291                expires_in: token.expires_at.map(|e| e.saturating_sub(now)),
292            })
293        }
294        None => Ok(AuthStatus::NotAuthenticated),
295    }
296}
297
298/// OAuth authentication status.
299#[derive(Debug, Clone)]
300pub enum AuthStatus {
301    /// User is authenticated with OAuth
302    Authenticated {
303        /// Optional label for the token
304        label: Option<String>,
305        /// How long ago the token was obtained (seconds)
306        age_seconds: u64,
307        /// Time until expiry (seconds), if known
308        expires_in: Option<u64>,
309    },
310    /// User is not authenticated via OAuth
311    NotAuthenticated,
312}
313
314impl AuthStatus {
315    /// Check if the user is authenticated.
316    pub fn is_authenticated(&self) -> bool {
317        matches!(self, AuthStatus::Authenticated { .. })
318    }
319
320    /// Get a human-readable status string.
321    fn display_string(&self) -> String {
322        match self {
323            AuthStatus::Authenticated { label, age_seconds, expires_in } => {
324                let label_str = label.as_ref().map(|l| format!(" ({l})")).unwrap_or_default();
325                let age_str = format!("{} ago", vtcode_commons::formatting::humanize_duration_compact(*age_seconds));
326                let expiry_str = expires_in
327                    .map(|e| format!(", expires in {}", vtcode_commons::formatting::humanize_duration_compact(e)))
328                    .unwrap_or_default();
329                format!("Authenticated{label_str}, obtained {age_str}{expiry_str}")
330            }
331            AuthStatus::NotAuthenticated => "Not authenticated".to_string(),
332        }
333    }
334}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339    use assert_fs::TempDir;
340    use serial_test::serial;
341    use std::fs;
342    use std::path::PathBuf;
343
344    struct TestAuthDirGuard {
345        temp_dir: Option<TempDir>,
346        previous: Option<PathBuf>,
347    }
348
349    impl TestAuthDirGuard {
350        fn new() -> Self {
351            let temp_dir = TempDir::new().expect("create temp auth dir");
352            let previous = crate::storage_paths::auth_storage_dir_override_for_tests().expect("read auth dir override");
353            crate::storage_paths::set_auth_storage_dir_override_for_tests(Some(temp_dir.path().to_path_buf()))
354                .expect("set temp auth dir override");
355            Self { temp_dir: Some(temp_dir), previous }
356        }
357    }
358
359    impl Drop for TestAuthDirGuard {
360        fn drop(&mut self) {
361            crate::storage_paths::set_auth_storage_dir_override_for_tests(self.previous.clone())
362                .expect("restore auth dir override");
363            if let Some(temp_dir) = self.temp_dir.take() {
364                temp_dir.close().expect("remove temp auth dir");
365            }
366        }
367    }
368
369    #[test]
370    fn test_auth_url_generation() {
371        let challenge = PkceChallenge {
372            code_verifier: "test_verifier".to_string(),
373            code_challenge: "test_challenge".to_string(),
374            code_challenge_method: "S256".to_string(),
375        };
376
377        let url = get_auth_url(&challenge, 8484);
378
379        assert!(url.starts_with("https://openrouter.ai/auth"));
380        assert!(url.contains("callback_url="));
381        assert!(url.contains("code_challenge=test_challenge"));
382        assert!(url.contains("code_challenge_method=S256"));
383    }
384
385    #[test]
386    fn debug_impl_redacts_api_key() {
387        let token = OpenRouterToken {
388            api_key: "sk-openrouter-secret".to_string(),
389            obtained_at: 123,
390            expires_at: Some(456),
391            label: Some("test token".to_string()),
392        };
393
394        let debug = format!("{token:?}");
395
396        assert!(!debug.contains("sk-openrouter-secret"), "api key leaked: {debug}");
397        assert!(debug.contains("<redacted>"), "api key should be redacted: {debug}");
398        assert!(debug.contains("test token"), "non-secret metadata should remain visible: {debug}");
399    }
400
401    #[test]
402    fn token_exchange_errors_do_not_include_response_bodies() {
403        let error = token_exchange_error(reqwest::StatusCode::INTERNAL_SERVER_ERROR);
404        let message = error.to_string();
405
406        assert_eq!(message, "Token exchange failed (HTTP 500 Internal Server Error)");
407        assert!(!message.contains("sk-openrouter-secret"));
408    }
409
410    #[test]
411    fn test_token_expiry_check() {
412        let now = std::time::SystemTime::now()
413            .duration_since(std::time::UNIX_EPOCH)
414            .unwrap()
415            .as_secs();
416
417        // Non-expired token
418        let token = OpenRouterToken {
419            api_key: "test".to_string(),
420            obtained_at: now,
421            expires_at: Some(now + 3600),
422            label: None,
423        };
424        assert!(!token.is_expired());
425
426        // Expired token
427        let expired_token = OpenRouterToken {
428            api_key: "test".to_string(),
429            obtained_at: now - 7200,
430            expires_at: Some(now - 3600),
431            label: None,
432        };
433        assert!(expired_token.is_expired());
434
435        // No expiry
436        let no_expiry_token = OpenRouterToken {
437            api_key: "test".to_string(),
438            obtained_at: now,
439            expires_at: None,
440            label: None,
441        };
442        assert!(!no_expiry_token.is_expired());
443    }
444
445    #[test]
446    fn test_encryption_roundtrip() {
447        let token = OpenRouterToken {
448            api_key: "sk-test-key-12345".to_string(),
449            obtained_at: 1234567890,
450            expires_at: Some(1234567890 + 86400),
451            label: Some("Test Token".to_string()),
452        };
453
454        let encrypted = encrypt_token(&token).unwrap();
455        let decrypted = decrypt_token(&encrypted).unwrap();
456
457        assert_eq!(decrypted.api_key, token.api_key);
458        assert_eq!(decrypted.obtained_at, token.obtained_at);
459        assert_eq!(decrypted.expires_at, token.expires_at);
460        assert_eq!(decrypted.label, token.label);
461    }
462
463    #[test]
464    fn test_auth_status_display() {
465        let status = AuthStatus::Authenticated {
466            label: Some("My App".to_string()),
467            age_seconds: 3700,
468            expires_in: Some(86000),
469        };
470
471        let display = status.display_string();
472        assert!(display.contains("Authenticated"));
473        assert!(display.contains("My App"));
474    }
475
476    #[test]
477    #[serial]
478    fn file_storage_round_trips_without_plaintext() {
479        let _guard = TestAuthDirGuard::new();
480        let now = std::time::SystemTime::now()
481            .duration_since(std::time::UNIX_EPOCH)
482            .unwrap()
483            .as_secs();
484        let token = OpenRouterToken {
485            api_key: "sk-test-key-12345".to_string(),
486            obtained_at: now,
487            expires_at: Some(now + 86400),
488            label: Some("Test Token".to_string()),
489        };
490
491        save_oauth_token_with_mode(&token, AuthCredentialsStoreMode::File).expect("save token");
492        let loaded = load_oauth_token_with_mode(AuthCredentialsStoreMode::File).expect("load token");
493        assert_eq!(loaded.as_ref().map(|value| &value.api_key), Some(&token.api_key));
494
495        let stored = fs::read_to_string(OpenRouterTokenStorage::new().current_file_path().expect("token path"))
496            .expect("read token file");
497        assert!(!stored.contains(&token.api_key));
498    }
499
500    #[test]
501    #[serial]
502    fn default_loader_falls_back_to_shared_file_storage() {
503        let _guard = TestAuthDirGuard::new();
504        let token = OpenRouterToken {
505            api_key: "sk-default-file-token".to_string(),
506            obtained_at: 1,
507            expires_at: None,
508            label: Some("default file fallback".to_string()),
509        };
510
511        save_oauth_token_with_mode(&token, AuthCredentialsStoreMode::File).expect("save token");
512
513        let loaded = load_oauth_token()
514            .expect("load default token")
515            .expect("token should be present");
516        assert_eq!(loaded.api_key, token.api_key);
517    }
518
519    #[test]
520    #[serial]
521    fn explicit_keyring_reports_unavailability_while_default_falls_back() {
522        let _guard = TestAuthDirGuard::new();
523        let env = vtcode_commons::env_lock::lock();
524        let previous = std::env::var_os("VTCODE_DISABLE_KEYRING");
525        env.set_var("VTCODE_DISABLE_KEYRING", "1");
526        let default_load = load_oauth_token();
527        let exact_load = load_oauth_token_with_mode(AuthCredentialsStoreMode::Keyring);
528        let exact_clear = clear_oauth_token_with_mode(AuthCredentialsStoreMode::Keyring);
529        match previous {
530            Some(value) => env.set_var("VTCODE_DISABLE_KEYRING", value),
531            None => env.remove_var("VTCODE_DISABLE_KEYRING"),
532        }
533        assert!(matches!(default_load, Ok(None)), "default lookup may fall back to file storage");
534        assert!(exact_load.is_err());
535        assert!(exact_clear.is_err());
536    }
537
538    #[test]
539    #[serial]
540    fn legacy_file_token_migrates_to_shared_storage() {
541        let _guard = TestAuthDirGuard::new();
542        let token = OpenRouterToken {
543            api_key: "sk-legacy-token".to_string(),
544            obtained_at: 1,
545            expires_at: None,
546            label: Some("legacy".to_string()),
547        };
548        let encrypted = encrypt_token(&token).expect("encrypt legacy token");
549        let legacy_path = get_token_path().expect("legacy token path");
550        fs::write(&legacy_path, serde_json::to_vec(&encrypted).expect("serialize legacy token"))
551            .expect("write legacy token");
552
553        let loaded = load_oauth_token_with_mode(AuthCredentialsStoreMode::File)
554            .expect("load migrated token")
555            .expect("token should be present");
556
557        assert_eq!(loaded.api_key, token.api_key);
558        assert!(legacy_path.exists(), "legacy token should remain as a rollback source after migration");
559        assert!(
560            OpenRouterTokenStorage::new()
561                .current_file_path()
562                .expect("shared token path")
563                .exists()
564        );
565    }
566
567    #[test]
568    #[serial]
569    #[cfg(unix)]
570    fn file_storage_uses_private_permissions() {
571        use std::os::unix::fs::PermissionsExt;
572
573        let _guard = TestAuthDirGuard::new();
574        let now = std::time::SystemTime::now()
575            .duration_since(std::time::UNIX_EPOCH)
576            .unwrap()
577            .as_secs();
578        let token = OpenRouterToken {
579            api_key: "sk-test-key-12345".to_string(),
580            obtained_at: now,
581            expires_at: Some(now + 86400),
582            label: Some("Test Token".to_string()),
583        };
584
585        save_oauth_token_with_mode(&token, AuthCredentialsStoreMode::File).expect("save token");
586
587        let metadata = fs::metadata(OpenRouterTokenStorage::new().current_file_path().expect("token path"))
588            .expect("read token metadata");
589        assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
590    }
591}