1use 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
31const OPENROUTER_AUTH_URL: &str = "https://openrouter.ai/auth";
33const OPENROUTER_KEYS_URL: &str = "https://openrouter.ai/api/v1/auth/keys";
34
35const DEFAULT_CALLBACK_PORT: u16 = 8484;
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
40#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
41#[serde(default)]
42pub struct OpenRouterOAuthConfig {
43 use_oauth: bool,
45 pub callback_port: u16,
47 auto_refresh: bool,
49 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#[derive(Clone, Serialize, Deserialize)]
66pub struct OpenRouterToken {
67 pub api_key: String,
69 pub obtained_at: u64,
71 pub expires_at: Option<u64>,
73 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 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
103pub 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
122pub 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 return Err(token_exchange_error(status));
158 }
159
160 let body =
162 vtcode_commons::http_body::read_text_limited(response, vtcode_commons::http_body::CONTROL_BODY_LIMIT_BYTES)
163 .await
164 .context("Failed to read response body")?;
165 let response_json: serde_json::Value = serde_json::from_str(&body).context("Failed to parse token response")?;
166
167 let api_key = response_json
168 .get("key")
169 .and_then(|v| v.as_str())
170 .ok_or_else(|| anyhow!("Response missing 'key' field"))?
171 .to_string();
172
173 Ok(api_key)
174}
175
176fn token_exchange_error(status: reqwest::StatusCode) -> anyhow::Error {
177 match status.as_u16() {
178 400 => anyhow!("Invalid code_challenge_method. Ensure you're using the same method (S256) in both steps."),
179 403 => anyhow!("Invalid code or code_verifier. The authorization code may have expired."),
180 405 => anyhow!("Method not allowed. Ensure you're using POST over HTTPS."),
181 _ => anyhow!("Token exchange failed (HTTP {status})"),
182 }
183}
184
185pub fn save_oauth_token_with_mode(token: &OpenRouterToken, mode: AuthCredentialsStoreMode) -> Result<()> {
191 OpenRouterTokenStorage::new().save(token, mode)
192}
193
194pub fn save_oauth_token(token: &OpenRouterToken) -> Result<()> {
198 save_oauth_token_with_mode(token, AuthCredentialsStoreMode::default())
199}
200
201pub fn load_oauth_token_with_mode(mode: AuthCredentialsStoreMode) -> Result<Option<OpenRouterToken>> {
205 let storage = OpenRouterTokenStorage::new();
206 let Some(token) = storage.load(mode)? else {
207 return Ok(None);
208 };
209
210 if token.is_expired() {
211 tracing::warn!("OpenRouter OAuth token has expired, removing it");
212 storage.clear(mode)?;
213 return Ok(None);
214 }
215
216 Ok(Some(token))
217}
218
219pub fn load_oauth_token() -> Result<Option<OpenRouterToken>> {
224 let storage = OpenRouterTokenStorage::new();
225 for mode in [AuthCredentialsStoreMode::Keyring, AuthCredentialsStoreMode::File] {
226 let token = match storage.load(mode) {
227 Ok(token) => token,
228 Err(error) if mode == AuthCredentialsStoreMode::Keyring => {
229 tracing::debug!(%error, "optional keyring token lookup unavailable; trying file storage");
230 continue;
231 }
232 Err(error) => return Err(error),
233 };
234 let Some(token) = token else {
235 continue;
236 };
237
238 if token.is_expired() {
239 tracing::warn!("OpenRouter OAuth token has expired, removing it");
240 storage.clear(mode)?;
241 continue;
242 }
243
244 return Ok(Some(token));
245 }
246
247 Ok(None)
248}
249
250pub fn clear_oauth_token_with_mode(mode: AuthCredentialsStoreMode) -> Result<()> {
252 OpenRouterTokenStorage::new().clear(mode)
253}
254
255pub fn clear_oauth_token() -> Result<()> {
257 OpenRouterTokenStorage::new().clear_all()
258}
259
260pub fn get_auth_status_with_mode(mode: AuthCredentialsStoreMode) -> Result<AuthStatus> {
262 match load_oauth_token_with_mode(mode)? {
263 Some(token) => {
264 let now = std::time::SystemTime::now()
265 .duration_since(std::time::UNIX_EPOCH)
266 .map(|d| d.as_secs())
267 .unwrap_or(0);
268
269 let age_seconds = now.saturating_sub(token.obtained_at);
270
271 Ok(AuthStatus::Authenticated {
272 label: token.label,
273 age_seconds,
274 expires_in: token.expires_at.map(|e| e.saturating_sub(now)),
275 })
276 }
277 None => Ok(AuthStatus::NotAuthenticated),
278 }
279}
280
281pub fn get_auth_status() -> Result<AuthStatus> {
282 match load_oauth_token()? {
283 Some(token) => {
284 let now = std::time::SystemTime::now()
285 .duration_since(std::time::UNIX_EPOCH)
286 .map(|d| d.as_secs())
287 .unwrap_or(0);
288
289 let age_seconds = now.saturating_sub(token.obtained_at);
290
291 Ok(AuthStatus::Authenticated {
292 label: token.label,
293 age_seconds,
294 expires_in: token.expires_at.map(|e| e.saturating_sub(now)),
295 })
296 }
297 None => Ok(AuthStatus::NotAuthenticated),
298 }
299}
300
301#[derive(Debug, Clone)]
303pub enum AuthStatus {
304 Authenticated {
306 label: Option<String>,
308 age_seconds: u64,
310 expires_in: Option<u64>,
312 },
313 NotAuthenticated,
315}
316
317impl AuthStatus {
318 pub fn is_authenticated(&self) -> bool {
320 matches!(self, AuthStatus::Authenticated { .. })
321 }
322
323 fn display_string(&self) -> String {
325 match self {
326 AuthStatus::Authenticated { label, age_seconds, expires_in } => {
327 let label_str = label.as_ref().map(|l| format!(" ({l})")).unwrap_or_default();
328 let age_str = format!("{} ago", vtcode_commons::formatting::humanize_duration_compact(*age_seconds));
329 let expiry_str = expires_in
330 .map(|e| format!(", expires in {}", vtcode_commons::formatting::humanize_duration_compact(e)))
331 .unwrap_or_default();
332 format!("Authenticated{label_str}, obtained {age_str}{expiry_str}")
333 }
334 AuthStatus::NotAuthenticated => "Not authenticated".to_string(),
335 }
336 }
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342 use assert_fs::TempDir;
343 use serial_test::serial;
344 use std::fs;
345 use std::path::PathBuf;
346
347 struct TestAuthDirGuard {
348 temp_dir: Option<TempDir>,
349 previous: Option<PathBuf>,
350 }
351
352 impl TestAuthDirGuard {
353 fn new() -> Self {
354 let temp_dir = TempDir::new().expect("create temp auth dir");
355 let previous = crate::storage_paths::auth_storage_dir_override_for_tests().expect("read auth dir override");
356 crate::storage_paths::set_auth_storage_dir_override_for_tests(Some(temp_dir.path().to_path_buf()))
357 .expect("set temp auth dir override");
358 Self { temp_dir: Some(temp_dir), previous }
359 }
360 }
361
362 impl Drop for TestAuthDirGuard {
363 fn drop(&mut self) {
364 crate::storage_paths::set_auth_storage_dir_override_for_tests(self.previous.clone())
365 .expect("restore auth dir override");
366 if let Some(temp_dir) = self.temp_dir.take() {
367 temp_dir.close().expect("remove temp auth dir");
368 }
369 }
370 }
371
372 #[test]
373 fn test_auth_url_generation() {
374 let challenge = PkceChallenge {
375 code_verifier: "test_verifier".to_string(),
376 code_challenge: "test_challenge".to_string(),
377 code_challenge_method: "S256".to_string(),
378 };
379
380 let url = get_auth_url(&challenge, 8484);
381
382 assert!(url.starts_with("https://openrouter.ai/auth"));
383 assert!(url.contains("callback_url="));
384 assert!(url.contains("code_challenge=test_challenge"));
385 assert!(url.contains("code_challenge_method=S256"));
386 }
387
388 #[test]
389 fn debug_impl_redacts_api_key() {
390 let token = OpenRouterToken {
391 api_key: "sk-openrouter-secret".to_string(),
392 obtained_at: 123,
393 expires_at: Some(456),
394 label: Some("test token".to_string()),
395 };
396
397 let debug = format!("{token:?}");
398
399 assert!(!debug.contains("sk-openrouter-secret"), "api key leaked: {debug}");
400 assert!(debug.contains("<redacted>"), "api key should be redacted: {debug}");
401 assert!(debug.contains("test token"), "non-secret metadata should remain visible: {debug}");
402 }
403
404 #[test]
405 fn token_exchange_errors_do_not_include_response_bodies() {
406 let error = token_exchange_error(reqwest::StatusCode::INTERNAL_SERVER_ERROR);
407 let message = error.to_string();
408
409 assert_eq!(message, "Token exchange failed (HTTP 500 Internal Server Error)");
410 assert!(!message.contains("sk-openrouter-secret"));
411 }
412
413 #[test]
414 fn test_token_expiry_check() {
415 let now = std::time::SystemTime::now()
416 .duration_since(std::time::UNIX_EPOCH)
417 .unwrap()
418 .as_secs();
419
420 let token = OpenRouterToken {
422 api_key: "test".to_string(),
423 obtained_at: now,
424 expires_at: Some(now + 3600),
425 label: None,
426 };
427 assert!(!token.is_expired());
428
429 let expired_token = OpenRouterToken {
431 api_key: "test".to_string(),
432 obtained_at: now - 7200,
433 expires_at: Some(now - 3600),
434 label: None,
435 };
436 assert!(expired_token.is_expired());
437
438 let no_expiry_token = OpenRouterToken {
440 api_key: "test".to_string(),
441 obtained_at: now,
442 expires_at: None,
443 label: None,
444 };
445 assert!(!no_expiry_token.is_expired());
446 }
447
448 #[test]
449 fn test_encryption_roundtrip() {
450 let token = OpenRouterToken {
451 api_key: "sk-test-key-12345".to_string(),
452 obtained_at: 1234567890,
453 expires_at: Some(1234567890 + 86400),
454 label: Some("Test Token".to_string()),
455 };
456
457 let encrypted = encrypt_token(&token).unwrap();
458 let decrypted = decrypt_token(&encrypted).unwrap();
459
460 assert_eq!(decrypted.api_key, token.api_key);
461 assert_eq!(decrypted.obtained_at, token.obtained_at);
462 assert_eq!(decrypted.expires_at, token.expires_at);
463 assert_eq!(decrypted.label, token.label);
464 }
465
466 #[test]
467 fn test_auth_status_display() {
468 let status = AuthStatus::Authenticated {
469 label: Some("My App".to_string()),
470 age_seconds: 3700,
471 expires_in: Some(86000),
472 };
473
474 let display = status.display_string();
475 assert!(display.contains("Authenticated"));
476 assert!(display.contains("My App"));
477 }
478
479 #[test]
480 #[serial]
481 fn file_storage_round_trips_without_plaintext() {
482 let _guard = TestAuthDirGuard::new();
483 let now = std::time::SystemTime::now()
484 .duration_since(std::time::UNIX_EPOCH)
485 .unwrap()
486 .as_secs();
487 let token = OpenRouterToken {
488 api_key: "sk-test-key-12345".to_string(),
489 obtained_at: now,
490 expires_at: Some(now + 86400),
491 label: Some("Test Token".to_string()),
492 };
493
494 save_oauth_token_with_mode(&token, AuthCredentialsStoreMode::File).expect("save token");
495 let loaded = load_oauth_token_with_mode(AuthCredentialsStoreMode::File).expect("load token");
496 assert_eq!(loaded.as_ref().map(|value| &value.api_key), Some(&token.api_key));
497
498 let stored = fs::read_to_string(OpenRouterTokenStorage::new().current_file_path().expect("token path"))
499 .expect("read token file");
500 assert!(!stored.contains(&token.api_key));
501 }
502
503 #[test]
504 #[serial]
505 fn default_loader_falls_back_to_shared_file_storage() {
506 let _guard = TestAuthDirGuard::new();
507 let token = OpenRouterToken {
508 api_key: "sk-default-file-token".to_string(),
509 obtained_at: 1,
510 expires_at: None,
511 label: Some("default file fallback".to_string()),
512 };
513
514 save_oauth_token_with_mode(&token, AuthCredentialsStoreMode::File).expect("save token");
515
516 let loaded = load_oauth_token()
517 .expect("load default token")
518 .expect("token should be present");
519 assert_eq!(loaded.api_key, token.api_key);
520 }
521
522 #[test]
523 #[serial]
524 fn explicit_keyring_reports_unavailability_while_default_falls_back() {
525 let _guard = TestAuthDirGuard::new();
526 let env = vtcode_commons::env_lock::lock();
527 let previous = std::env::var_os("VTCODE_DISABLE_KEYRING");
528 env.set_var("VTCODE_DISABLE_KEYRING", "1");
529 let default_load = load_oauth_token();
530 let exact_load = load_oauth_token_with_mode(AuthCredentialsStoreMode::Keyring);
531 let exact_clear = clear_oauth_token_with_mode(AuthCredentialsStoreMode::Keyring);
532 match previous {
533 Some(value) => env.set_var("VTCODE_DISABLE_KEYRING", value),
534 None => env.remove_var("VTCODE_DISABLE_KEYRING"),
535 }
536 assert!(matches!(default_load, Ok(None)), "default lookup may fall back to file storage");
537 assert!(exact_load.is_err());
538 assert!(exact_clear.is_err());
539 }
540
541 #[test]
542 #[serial]
543 fn legacy_file_token_migrates_to_shared_storage() {
544 let _guard = TestAuthDirGuard::new();
545 let token = OpenRouterToken {
546 api_key: "sk-legacy-token".to_string(),
547 obtained_at: 1,
548 expires_at: None,
549 label: Some("legacy".to_string()),
550 };
551 let encrypted = encrypt_token(&token).expect("encrypt legacy token");
552 let legacy_path = get_token_path().expect("legacy token path");
553 fs::write(&legacy_path, serde_json::to_vec(&encrypted).expect("serialize legacy token"))
554 .expect("write legacy token");
555
556 let loaded = load_oauth_token_with_mode(AuthCredentialsStoreMode::File)
557 .expect("load migrated token")
558 .expect("token should be present");
559
560 assert_eq!(loaded.api_key, token.api_key);
561 assert!(legacy_path.exists(), "legacy token should remain as a rollback source after migration");
562 assert!(
563 OpenRouterTokenStorage::new()
564 .current_file_path()
565 .expect("shared token path")
566 .exists()
567 );
568 }
569
570 #[test]
571 #[serial]
572 #[cfg(unix)]
573 fn file_storage_uses_private_permissions() {
574 use std::os::unix::fs::PermissionsExt;
575
576 let _guard = TestAuthDirGuard::new();
577 let now = std::time::SystemTime::now()
578 .duration_since(std::time::UNIX_EPOCH)
579 .unwrap()
580 .as_secs();
581 let token = OpenRouterToken {
582 api_key: "sk-test-key-12345".to_string(),
583 obtained_at: now,
584 expires_at: Some(now + 86400),
585 label: Some("Test Token".to_string()),
586 };
587
588 save_oauth_token_with_mode(&token, AuthCredentialsStoreMode::File).expect("save token");
589
590 let metadata = fs::metadata(OpenRouterTokenStorage::new().current_file_path().expect("token path"))
591 .expect("read token metadata");
592 assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
593 }
594}