forked from Dicklesworthstone/pi_agent_rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.rs
More file actions
10017 lines (9041 loc) · 360 KB
/
Copy pathauth.rs
File metadata and controls
10017 lines (9041 loc) · 360 KB
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Authentication storage and API key resolution.
//!
//! Auth file: ~/.pi/agent/auth.json
use crate::config::Config;
use crate::error::{Error, Result};
use crate::provider_metadata::{canonical_provider_id, provider_auth_env_keys, provider_metadata};
use base64::Engine as _;
use fs4::fs_std::FileExt;
use serde::{Deserialize, Serialize};
use sha2::Digest as _;
use std::collections::HashMap;
use std::fmt::Write as _;
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use tempfile::NamedTempFile;
const ANTHROPIC_OAUTH_CLIENT_ID: &str = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
const ANTHROPIC_OAUTH_AUTHORIZE_URL: &str = "https://claude.ai/oauth/authorize";
// ubs:ignore public OAuth endpoint metadata, not credential material.
const ANTHROPIC_OAUTH_TOKEN_URL: &str = "https://console.anthropic.com/v1/oauth/token";
const ANTHROPIC_OAUTH_REDIRECT_URI: &str = "https://console.anthropic.com/oauth/code/callback";
const ANTHROPIC_OAUTH_SCOPES: &str = "org:create_api_key user:profile user:inference";
// ── OpenAI Codex OAuth constants ─────────────────────────────────
const OPENAI_CODEX_OAUTH_CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
const OPENAI_CODEX_OAUTH_AUTHORIZE_URL: &str = "https://auth.openai.com/oauth/authorize";
// ubs:ignore public OAuth endpoint metadata, not credential material.
const OPENAI_CODEX_OAUTH_TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
const OPENAI_CODEX_OAUTH_REDIRECT_URI: &str = "http://localhost:1455/auth/callback";
const OPENAI_CODEX_OAUTH_SCOPES: &str = "openid profile email offline_access";
// ── Google Gemini CLI OAuth constants ────────────────────────────
const GOOGLE_GEMINI_CLI_OAUTH_CLIENT_ID: &str =
"681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com";
// ubs:ignore public installed-app OAuth client metadata, not a server-side secret.
const GOOGLE_GEMINI_CLI_OAUTH_CLIENT_SECRET: &str = "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";
const GOOGLE_GEMINI_CLI_OAUTH_REDIRECT_URI: &str = "http://localhost:8085/oauth2callback";
const GOOGLE_GEMINI_CLI_OAUTH_SCOPES: &str = "https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";
const GOOGLE_GEMINI_CLI_OAUTH_AUTHORIZE_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
// ubs:ignore public OAuth endpoint metadata, not credential material.
const GOOGLE_GEMINI_CLI_OAUTH_TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
const GOOGLE_GEMINI_CLI_CODE_ASSIST_ENDPOINT: &str = "https://cloudcode-pa.googleapis.com";
// ── Google Antigravity OAuth constants ───────────────────────────
const GOOGLE_ANTIGRAVITY_OAUTH_CLIENT_ID: &str =
"1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
// ubs:ignore public installed-app OAuth client metadata, not a server-side secret.
const GOOGLE_ANTIGRAVITY_OAUTH_CLIENT_SECRET: &str = "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";
const GOOGLE_ANTIGRAVITY_OAUTH_REDIRECT_URI: &str = "http://localhost:51121/oauth-callback";
const GOOGLE_ANTIGRAVITY_OAUTH_SCOPES: &str = "https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/cclog https://www.googleapis.com/auth/experimentsandconfigs";
const GOOGLE_ANTIGRAVITY_OAUTH_AUTHORIZE_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
// ubs:ignore public OAuth endpoint metadata, not credential material.
const GOOGLE_ANTIGRAVITY_OAUTH_TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
const GOOGLE_ANTIGRAVITY_DEFAULT_PROJECT_ID: &str = "rising-fact-p41fc";
const GOOGLE_ANTIGRAVITY_PROJECT_DISCOVERY_ENDPOINTS: [&str; 2] = [
"https://cloudcode-pa.googleapis.com",
"https://daily-cloudcode-pa.sandbox.googleapis.com",
];
/// Internal marker used to preserve OAuth-vs-API-key lane information when
/// passing Anthropic credentials through provider-agnostic key plumbing.
const ANTHROPIC_OAUTH_BEARER_MARKER: &str = "__pi_anthropic_oauth_bearer__:";
// ── GitHub / Copilot OAuth constants ──────────────────────────────
const GITHUB_OAUTH_AUTHORIZE_URL: &str = "https://github.com/login/oauth/authorize";
// ubs:ignore public OAuth endpoint metadata, not credential material.
const GITHUB_OAUTH_TOKEN_URL: &str = "https://github.com/login/oauth/access_token";
const GITHUB_DEVICE_CODE_URL: &str = "https://github.com/login/device/code";
/// Default scopes for Copilot access (read:user needed for identity).
const GITHUB_COPILOT_SCOPES: &str = "read:user";
// ── GitLab OAuth constants ────────────────────────────────────────
const GITLAB_OAUTH_AUTHORIZE_PATH: &str = "/oauth/authorize";
// ubs:ignore public OAuth endpoint path metadata, not credential material.
const GITLAB_OAUTH_TOKEN_PATH: &str = "/oauth/token";
const GITLAB_DEFAULT_BASE_URL: &str = "https://gitlab.com";
/// Default scopes for GitLab AI features.
const GITLAB_DEFAULT_SCOPES: &str = "api read_api read_user";
// ── Kimi Code OAuth constants ─────────────────────────────────────
const KIMI_CODE_OAUTH_CLIENT_ID: &str = "17e5f671-d194-4dfb-9706-5516cb48c098";
const KIMI_CODE_OAUTH_DEFAULT_HOST: &str = "https://auth.kimi.com";
const KIMI_CODE_OAUTH_HOST_ENV_KEYS: [&str; 2] = ["KIMI_CODE_OAUTH_HOST", "KIMI_OAUTH_HOST"];
const KIMI_SHARE_DIR_ENV_KEY: &str = "KIMI_SHARE_DIR";
const KIMI_CODE_DEVICE_AUTHORIZATION_PATH: &str = "/api/oauth/device_authorization";
// ubs:ignore public OAuth endpoint metadata, not credential material.
const KIMI_CODE_TOKEN_PATH: &str = "/api/oauth/token";
// ── OAuth env-var override helper ───────────────────────────────
//
// Every compiled-in OAuth constant can be overridden at runtime via an
// environment variable. This lets operators update credentials without
// rebuilding the binary if a provider rotates client IDs or URLs.
/// Read an OAuth parameter from the environment, falling back to the
/// compiled-in default when the env var is absent or empty.
fn oauth_param(env_key: &str, default: &str) -> String {
match std::env::var(env_key) {
Ok(val) if !val.is_empty() => {
tracing::debug!(env_key, "Using env override for OAuth parameter");
val
}
_ => default.to_string(),
}
}
// Accessor functions for each overridable OAuth constant. Call these
// instead of using the `const` values directly so the env-var escape
// hatch is always active.
fn anthropic_oauth_client_id() -> String {
oauth_param("PI_ANTHROPIC_OAUTH_CLIENT_ID", ANTHROPIC_OAUTH_CLIENT_ID)
}
fn anthropic_oauth_authorize_url() -> String {
oauth_param(
"PI_ANTHROPIC_OAUTH_AUTHORIZE_URL",
ANTHROPIC_OAUTH_AUTHORIZE_URL,
)
}
fn anthropic_oauth_token_url() -> String {
oauth_param("PI_ANTHROPIC_OAUTH_TOKEN_URL", ANTHROPIC_OAUTH_TOKEN_URL)
}
fn anthropic_oauth_redirect_uri() -> String {
oauth_param(
"PI_ANTHROPIC_OAUTH_REDIRECT_URI",
ANTHROPIC_OAUTH_REDIRECT_URI,
)
}
fn anthropic_oauth_scopes() -> String {
oauth_param("PI_ANTHROPIC_OAUTH_SCOPES", ANTHROPIC_OAUTH_SCOPES)
}
fn openai_codex_oauth_client_id() -> String {
oauth_param(
"PI_OPENAI_CODEX_OAUTH_CLIENT_ID",
OPENAI_CODEX_OAUTH_CLIENT_ID,
)
}
fn openai_codex_oauth_authorize_url() -> String {
oauth_param(
"PI_OPENAI_CODEX_OAUTH_AUTHORIZE_URL",
OPENAI_CODEX_OAUTH_AUTHORIZE_URL,
)
}
fn openai_codex_oauth_token_url() -> String {
oauth_param(
"PI_OPENAI_CODEX_OAUTH_TOKEN_URL",
OPENAI_CODEX_OAUTH_TOKEN_URL,
)
}
fn openai_codex_oauth_redirect_uri() -> String {
oauth_param(
"PI_OPENAI_CODEX_OAUTH_REDIRECT_URI",
OPENAI_CODEX_OAUTH_REDIRECT_URI,
)
}
fn openai_codex_oauth_scopes() -> String {
oauth_param("PI_OPENAI_CODEX_OAUTH_SCOPES", OPENAI_CODEX_OAUTH_SCOPES)
}
fn google_gemini_cli_oauth_client_id() -> String {
oauth_param(
"PI_GOOGLE_GEMINI_CLI_OAUTH_CLIENT_ID",
GOOGLE_GEMINI_CLI_OAUTH_CLIENT_ID,
)
}
fn google_gemini_cli_oauth_client_secret() -> String {
oauth_param(
"PI_GOOGLE_GEMINI_CLI_OAUTH_CLIENT_SECRET",
GOOGLE_GEMINI_CLI_OAUTH_CLIENT_SECRET,
)
}
fn google_gemini_cli_oauth_redirect_uri() -> String {
oauth_param(
"PI_GOOGLE_GEMINI_CLI_OAUTH_REDIRECT_URI",
GOOGLE_GEMINI_CLI_OAUTH_REDIRECT_URI,
)
}
fn google_antigravity_oauth_client_id() -> String {
oauth_param(
"PI_GOOGLE_ANTIGRAVITY_OAUTH_CLIENT_ID",
GOOGLE_ANTIGRAVITY_OAUTH_CLIENT_ID,
)
}
fn google_antigravity_oauth_client_secret() -> String {
oauth_param(
"PI_GOOGLE_ANTIGRAVITY_OAUTH_CLIENT_SECRET",
GOOGLE_ANTIGRAVITY_OAUTH_CLIENT_SECRET,
)
}
fn google_antigravity_oauth_redirect_uri() -> String {
oauth_param(
"PI_GOOGLE_ANTIGRAVITY_OAUTH_REDIRECT_URI",
GOOGLE_ANTIGRAVITY_OAUTH_REDIRECT_URI,
)
}
fn google_antigravity_default_project_id() -> String {
oauth_param(
"PI_GOOGLE_ANTIGRAVITY_PROJECT_ID",
GOOGLE_ANTIGRAVITY_DEFAULT_PROJECT_ID,
)
}
fn kimi_code_oauth_client_id() -> String {
oauth_param("PI_KIMI_CODE_OAUTH_CLIENT_ID", KIMI_CODE_OAUTH_CLIENT_ID)
}
/// Credentials stored in auth.json.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthCredential {
ApiKey {
key: String,
},
OAuth {
access_token: String,
refresh_token: String,
expires: i64, // Unix ms
/// Token endpoint URL for self-contained refresh (optional; backward-compatible).
#[serde(default, skip_serializing_if = "Option::is_none")]
token_url: Option<String>,
/// Client ID for self-contained refresh (optional; backward-compatible).
#[serde(default, skip_serializing_if = "Option::is_none")]
client_id: Option<String>,
},
/// AWS IAM credentials for providers like Amazon Bedrock.
///
/// Supports the standard credential chain: explicit keys → env vars → profile → container
/// credentials → web identity token.
AwsCredentials {
access_key_id: String,
secret_access_key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
session_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
region: Option<String>,
},
/// Bearer token for providers that accept `Authorization: Bearer <token>`.
///
/// Used by gateway proxies (Vercel AI Gateway, Helicone, etc.) and services
/// that issue pre-authenticated bearer tokens (e.g. `AWS_BEARER_TOKEN_BEDROCK`).
BearerToken {
token: String,
},
/// Service key credentials for providers like SAP AI Core that use
/// client-credentials OAuth (client_id + client_secret → token_url → bearer).
ServiceKey {
#[serde(default, skip_serializing_if = "Option::is_none")]
client_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
client_secret: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
token_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
service_url: Option<String>,
},
/// Preserves malformed or legacy credential entries during migration/saving
/// so that we don't drop them if the schema evolves.
#[serde(untagged)]
Unknown(serde_json::Value),
}
/// Canonical credential status for a provider in auth.json.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CredentialStatus {
Missing,
ApiKey,
OAuthValid { expires_in_ms: i64 },
OAuthExpired { expired_by_ms: i64 },
BearerToken,
AwsCredentials,
ServiceKey,
}
/// Proactive refresh: attempt refresh this many ms *before* actual expiry.
/// This avoids using a token that's about to expire during a long-running request.
const PROACTIVE_REFRESH_WINDOW_MS: i64 = 10 * 60 * 1000; // 10 minutes
type OAuthRefreshRequest = (String, String, String, Option<String>, Option<String>);
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuthFile {
#[serde(flatten)]
pub entries: HashMap<String, AuthCredential>,
}
#[derive(Serialize)]
struct AuthFileRef<'a> {
#[serde(flatten)]
entries: &'a HashMap<String, AuthCredential>,
}
/// Auth storage wrapper with file locking.
#[derive(Debug, Clone)]
pub struct AuthStorage {
path: PathBuf,
entries: HashMap<String, AuthCredential>,
}
impl AuthStorage {
fn allow_external_provider_lookup(&self) -> bool {
// External credential auto-detection is intended for Pi's global auth
// file (typically `~/.pi/agent/auth.json`). Scoping it this way keeps
// tests and custom auth sandboxes deterministic.
self.path.eq(&Config::auth_path())
}
fn entry_case_insensitive(&self, key: &str) -> Option<&AuthCredential> {
self.entries.iter().find_map(|(existing, credential)| {
existing.eq_ignore_ascii_case(key).then_some(credential)
})
}
fn credential_for_provider(&self, provider: &str) -> Option<&AuthCredential> {
if let Some(credential) = self
.entries
.get(provider)
.or_else(|| self.entry_case_insensitive(provider))
{
return Some(credential);
}
let metadata = provider_metadata(provider)?;
if let Some(credential) = self
.entries
.get(metadata.canonical_id)
.or_else(|| self.entry_case_insensitive(metadata.canonical_id))
{
return Some(credential);
}
metadata.aliases.iter().find_map(|alias| {
self.entries
.get(*alias)
.or_else(|| self.entry_case_insensitive(alias))
})
}
/// Load auth.json (creates empty if missing).
pub fn load(path: PathBuf) -> Result<Self> {
let entries = if path.exists() {
let lock_handle = open_auth_lock_file(&path)?;
let _locked = lock_file_shared(lock_handle, Duration::from_secs(30))?;
let content =
fs::read_to_string(&path).map_err(|e| Error::auth(format!("auth.json: {e}")))?;
let parsed: AuthFile = match serde_json::from_str(&content) {
Ok(file) => file,
Err(e) => {
let backup_path = path.with_extension("json.corrupt");
if let Err(backup_err) = fs::copy(&path, &backup_path) {
tracing::error!(
event = "pi.auth.backup_failed",
error = %backup_err,
backup = %backup_path.display(),
"Failed to backup corrupted auth.json"
);
}
tracing::warn!(
event = "pi.auth.parse_error",
error = %e,
backup = %backup_path.display(),
"auth.json is corrupted; backed up and starting with empty credentials"
);
AuthFile::default()
}
};
parsed.entries
} else {
HashMap::new()
};
Ok(Self { path, entries })
}
/// Load auth.json asynchronously (creates empty if missing).
pub async fn load_async(path: PathBuf) -> Result<Self> {
asupersync::runtime::spawn_blocking(move || Self::load(path)).await
}
/// Persist auth.json (atomic write + permissions).
pub fn save(&self) -> Result<()> {
let data = serde_json::to_string_pretty(&AuthFileRef {
entries: &self.entries,
})?;
Self::save_data_sync(&self.path, &data)
}
/// Persist auth.json asynchronously.
pub async fn save_async(&self) -> Result<()> {
let data = serde_json::to_string_pretty(&AuthFileRef {
entries: &self.entries,
})?;
let path = self.path.clone();
asupersync::runtime::spawn_blocking(move || Self::save_data_sync(&path, &data)).await
}
fn save_data_sync(path: &Path, data: &str) -> Result<()> {
Self::save_data_sync_with_hook(path, data, |_| Ok(()))
}
fn save_data_sync_with_hook<F>(path: &Path, data: &str, before_persist: F) -> Result<()>
where
F: FnOnce(&NamedTempFile) -> std::io::Result<()>,
{
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let lock_handle = open_auth_lock_file(path)?;
let _locked = lock_file(lock_handle, Duration::from_secs(30))?;
let parent = path.parent().unwrap_or_else(|| Path::new("."));
let mut temp = NamedTempFile::new_in(parent)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
temp.as_file()
.set_permissions(fs::Permissions::from_mode(0o600))?;
}
temp.write_all(data.as_bytes())?;
temp.as_file().sync_all()?;
before_persist(&temp)?;
temp.persist(path).map_err(|err| err.error)?;
sync_parent_dir(path)?;
Ok(())
}
/// Get raw credential.
pub fn get(&self, provider: &str) -> Option<&AuthCredential> {
self.entries.get(provider)
}
/// Insert or replace a credential for a provider.
pub fn set(&mut self, provider: impl Into<String>, credential: AuthCredential) {
self.entries.insert(provider.into(), credential);
}
/// Remove a credential for a provider.
pub fn remove(&mut self, provider: &str) -> bool {
self.entries.remove(provider).is_some()
}
/// Get API key for provider from auth.json.
///
/// For `ApiKey` and `BearerToken` variants the key/token is returned directly.
/// For `OAuth` the access token is returned only when not expired.
/// For `AwsCredentials` the access key ID is returned (callers needing the full
/// credential set should use [`get`] instead).
/// For `ServiceKey` this returns `None` because a token exchange is required first.
pub fn api_key(&self, provider: &str) -> Option<String> {
self.credential_for_provider(provider)
.and_then(api_key_from_credential)
}
/// Return the names of all providers that have stored credentials.
pub fn provider_names(&self) -> Vec<String> {
let mut providers: Vec<String> = self.entries.keys().cloned().collect();
providers.sort();
providers
}
/// Return stored credential status for a provider, including canonical alias fallback.
pub fn credential_status(&self, provider: &str) -> CredentialStatus {
let now = chrono::Utc::now().timestamp_millis();
let cred = self.credential_for_provider(provider);
let Some(cred) = cred else {
return if self.allow_external_provider_lookup()
&& resolve_external_provider_api_key(provider).is_some()
{
CredentialStatus::ApiKey
} else {
CredentialStatus::Missing
};
};
match cred {
AuthCredential::ApiKey { .. } => CredentialStatus::ApiKey,
AuthCredential::OAuth { expires, .. } if *expires > now => {
CredentialStatus::OAuthValid {
expires_in_ms: expires.saturating_sub(now),
}
}
AuthCredential::OAuth { expires, .. } => CredentialStatus::OAuthExpired {
expired_by_ms: now.saturating_sub(*expires),
},
AuthCredential::BearerToken { .. } => CredentialStatus::BearerToken,
AuthCredential::AwsCredentials { .. } => CredentialStatus::AwsCredentials,
AuthCredential::ServiceKey { .. } => CredentialStatus::ServiceKey,
AuthCredential::Unknown(_) => CredentialStatus::Missing,
}
}
/// Remove stored credentials for `provider` and any known aliases/canonical IDs.
///
/// Matching is case-insensitive to clean up legacy mixed-case auth entries.
pub fn remove_provider_aliases(&mut self, provider: &str) -> bool {
let trimmed = provider.trim();
if trimmed.is_empty() {
return false;
}
let mut targets: Vec<String> = vec![trimmed.to_ascii_lowercase()];
if let Some(metadata) = provider_metadata(trimmed) {
targets.push(metadata.canonical_id.to_ascii_lowercase());
targets.extend(
metadata
.aliases
.iter()
.map(|alias| alias.to_ascii_lowercase()),
);
}
targets.sort();
targets.dedup();
let mut removed = false;
self.entries.retain(|key, _| {
let should_remove = targets
.iter()
.any(|target| key.eq_ignore_ascii_case(target));
if should_remove {
removed = true;
}
!should_remove
});
removed
}
/// Returns true when auth.json contains a credential for `provider`
/// (including canonical alias fallback).
pub fn has_stored_credential(&self, provider: &str) -> bool {
self.credential_for_provider(provider).is_some()
}
/// Return a human-readable source label when credentials can be auto-detected
/// from other locally-installed coding CLIs.
pub fn external_setup_source(&self, provider: &str) -> Option<&'static str> {
if !self.allow_external_provider_lookup() {
return None;
}
external_setup_source(provider)
}
/// Resolve API key with precedence.
pub fn resolve_api_key(&self, provider: &str, override_key: Option<&str>) -> Option<String> {
self.resolve_api_key_with_env_lookup(provider, override_key, |var| std::env::var(var).ok())
}
fn resolve_api_key_with_env_lookup<F>(
&self,
provider: &str,
override_key: Option<&str>,
mut env_lookup: F,
) -> Option<String>
where
F: FnMut(&str) -> Option<String>,
{
if let Some(key) = override_key {
let trimmed = key.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
// Prefer explicit stored OAuth/Bearer credentials over ambient env vars.
// This prevents stale shell env keys from silently overriding successful `/login` flows.
if let Some(credential) = self.credential_for_provider(provider)
&& let Some(key) = match credential {
AuthCredential::OAuth { .. }
if canonical_provider_id(provider)
.unwrap_or(provider)
.eq("anthropic") =>
{
api_key_from_credential(credential)
.map(|token| mark_anthropic_oauth_bearer_token(&token))
}
AuthCredential::OAuth { .. } | AuthCredential::BearerToken { .. } => {
api_key_from_credential(credential)
}
_ => None,
}
{
return Some(key);
}
if let Some(key) = env_keys_for_provider(provider).iter().find_map(|var| {
env_lookup(var).and_then(|value| {
let trimmed = value.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
})
}) {
return Some(key);
}
if let Some(key) = self.api_key(provider) {
return Some(key);
}
if self.allow_external_provider_lookup() {
if let Some(key) = resolve_external_provider_api_key(provider) {
return Some(key);
}
}
canonical_provider_id(provider)
.filter(|canonical| canonical.ne(&provider))
.and_then(|canonical| {
self.api_key(canonical).or_else(|| {
self.allow_external_provider_lookup()
.then(|| resolve_external_provider_api_key(canonical))
.flatten()
})
})
}
/// Refresh any expired OAuth tokens that this binary knows how to refresh.
///
/// This keeps startup behavior predictable: models that rely on OAuth credentials remain
/// available after restart without requiring the user to re-login.
pub async fn refresh_expired_oauth_tokens(&mut self) -> Result<()> {
let client = crate::http::client::Client::new();
self.refresh_expired_oauth_tokens_with_client(&client).await
}
/// Refresh any expired OAuth tokens using the provided HTTP client.
///
/// This is primarily intended for tests and deterministic harnesses (e.g. VCR playback),
/// but is also useful for callers that want to supply a custom HTTP implementation.
#[allow(clippy::too_many_lines)]
pub async fn refresh_expired_oauth_tokens_with_client(
&mut self,
client: &crate::http::client::Client,
) -> Result<()> {
let now = chrono::Utc::now().timestamp_millis();
let proactive_deadline = now + PROACTIVE_REFRESH_WINDOW_MS;
let mut refreshes: Vec<OAuthRefreshRequest> = Vec::new();
for (provider, cred) in &self.entries {
if let AuthCredential::OAuth {
access_token,
refresh_token,
expires,
token_url,
client_id,
..
} = cred
{
// Proactive refresh: refresh if the token will expire within the
// proactive window, not just when already expired.
if *expires <= proactive_deadline {
refreshes.push((
provider.clone(),
access_token.clone(),
refresh_token.clone(),
token_url.clone(),
client_id.clone(),
));
}
}
}
let mut failed_providers = Vec::new();
let mut needs_save = false;
for (provider, access_token, refresh_token, stored_token_url, stored_client_id) in refreshes
{
let result = match provider.as_str() {
"anthropic" => {
Box::pin(refresh_anthropic_oauth_token(client, &refresh_token)).await
}
"google-gemini-cli" => match decode_project_scoped_access_token(&access_token) {
Some((_, project_id)) => {
Box::pin(refresh_google_gemini_cli_oauth_token(
client,
&refresh_token,
&project_id,
))
.await
}
None => Err(Error::auth(
"google-gemini-cli OAuth credential missing projectId payload".to_string(),
)),
},
"google-antigravity" => match decode_project_scoped_access_token(&access_token) {
Some((_, project_id)) => {
Box::pin(refresh_google_antigravity_oauth_token(
client,
&refresh_token,
&project_id,
))
.await
}
None => Err(Error::auth(
"google-antigravity OAuth credential missing projectId payload".to_string(),
)),
},
"kimi-for-coding" => {
let token_url = stored_token_url
.clone()
.unwrap_or_else(kimi_code_token_endpoint);
Box::pin(refresh_kimi_code_oauth_token(
client,
&token_url,
&refresh_token,
))
.await
}
_ => {
if let (Some(url), Some(cid)) = (&stored_token_url, &stored_client_id) {
Box::pin(refresh_self_contained_oauth_token(
client,
url,
cid,
&refresh_token,
&provider,
))
.await
} else {
// Should have been filtered out or handled by extensions logic, but safe to ignore.
continue;
}
}
};
match result {
Ok(refreshed) => {
self.entries.insert(provider, refreshed);
needs_save = true;
}
Err(e) => {
tracing::warn!("Failed to refresh OAuth token for {provider}: {e}");
failed_providers.push(format!("{provider} ({e})"));
}
}
}
if needs_save {
if let Err(e) = self.save_async().await {
tracing::warn!("Failed to save auth.json after refreshing OAuth tokens: {e}");
}
}
if !failed_providers.is_empty() {
// Return an error to signal that at least some refreshes failed,
// but only after attempting all of them.
return Err(Error::auth(format!(
"OAuth token refresh failed for: {}",
failed_providers.join(", ")
)));
}
Ok(())
}
/// Refresh expired OAuth tokens for extension-registered providers.
///
/// `extension_configs` maps provider ID to its [`OAuthConfig`](crate::models::OAuthConfig).
/// Providers already handled by `refresh_expired_oauth_tokens_with_client` (e.g. "anthropic")
/// are skipped.
pub async fn refresh_expired_extension_oauth_tokens(
&mut self,
client: &crate::http::client::Client,
extension_configs: &HashMap<String, crate::models::OAuthConfig>,
) -> Result<()> {
let now = chrono::Utc::now().timestamp_millis();
let proactive_deadline = now + PROACTIVE_REFRESH_WINDOW_MS;
let mut refreshes = Vec::new();
for (provider, cred) in &self.entries {
if let AuthCredential::OAuth {
refresh_token,
expires,
token_url,
client_id,
..
} = cred
{
// Skip built-in providers (handled by refresh_expired_oauth_tokens_with_client).
if matches!(
provider.as_str(),
"anthropic"
| "openai-codex"
| "google-gemini-cli"
| "google-antigravity"
| "kimi-for-coding"
) {
continue;
}
// Skip self-contained credentials — they are refreshed by
// refresh_expired_oauth_tokens_with_client instead.
if token_url.is_some() && client_id.is_some() {
continue;
}
if *expires <= proactive_deadline {
if let Some(config) = extension_configs.get(provider) {
refreshes.push((provider.clone(), refresh_token.clone(), config.clone()));
}
}
}
}
if !refreshes.is_empty() {
tracing::info!(
event = "pi.auth.extension_oauth_refresh.start",
count = refreshes.len(),
"Refreshing expired extension OAuth tokens"
);
}
let mut failed_providers: Vec<String> = Vec::new();
let mut needs_save = false;
for (provider, refresh_token, config) in refreshes {
let start = std::time::Instant::now(); // ubs:ignore false positive: refresh latency instrumentation, not security token generation.
match refresh_extension_oauth_token(client, &config, &refresh_token).await {
Ok(refreshed) => {
tracing::info!(
event = "pi.auth.extension_oauth_refresh.ok",
provider = %provider,
elapsed_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
"Extension OAuth token refreshed"
);
self.entries.insert(provider, refreshed);
needs_save = true;
}
Err(e) => {
tracing::warn!(
event = "pi.auth.extension_oauth_refresh.error",
provider = %provider,
error = %e,
elapsed_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
"Failed to refresh extension OAuth token; continuing with remaining providers"
);
failed_providers.push(format!("{provider} ({e})"));
}
}
}
if needs_save {
if let Err(e) = self.save_async().await {
tracing::warn!(
"Failed to save auth.json after refreshing extension OAuth tokens: {e}"
);
}
}
if failed_providers.is_empty() {
Ok(())
} else {
Err(Error::api(format!(
"Extension OAuth token refresh failed for: {}",
failed_providers.join(", ")
)))
}
}
/// Remove OAuth credentials that expired more than `max_age_ms` ago and
/// whose refresh token is no longer usable (no stored `token_url`/`client_id`
/// and no matching extension config).
///
/// Returns the list of pruned provider IDs.
pub fn prune_stale_credentials(&mut self, max_age_ms: i64) -> Vec<String> {
let now = chrono::Utc::now().timestamp_millis();
let cutoff = now - max_age_ms;
let mut pruned = Vec::new();
self.entries.retain(|provider, cred| {
if let AuthCredential::OAuth {
expires,
token_url,
client_id,
..
} = cred
{
// Only prune tokens that are well past expiry AND have no
// self-contained refresh metadata.
if *expires < cutoff && token_url.is_none() && client_id.is_none() {
tracing::info!(
event = "pi.auth.prune_stale",
provider = %provider,
expired_at = expires,
"Pruning stale OAuth credential"
);
pruned.push(provider.clone());
return false;
}
}
true
});
pruned
}
}
/// Resolve an API key string that may contain a `$ENV:VAR_NAME` or
/// `$CMD:shell command` prefix.
///
/// - Plain string → returned as-is (backward compatible literal key)
/// - `$ENV:VAR_NAME` → resolves the named environment variable at runtime
/// - `$CMD:shell command` / `$COMMAND:shell command` → runs the command and
/// uses trimmed stdout as the key
///
/// Returns `None` when the key references an env var that is unset or empty.
/// Returns `None` when the command succeeds but produces empty output.
/// Returns `Err` with a descriptive message for malformed `$ENV:` / `$CMD:`
/// references or command execution failures.
fn resolve_api_key_source(raw: &str) -> std::result::Result<Option<String>, String> {
resolve_api_key_source_with_resolvers(
raw,
|var| std::env::var(var).ok(),
run_api_key_source_command,
)
}
/// Testable version of [`resolve_api_key_source`] with injectable env lookup.
#[cfg(test)]
fn resolve_api_key_source_with_env<F>(
raw: &str,
env_lookup: F,
) -> std::result::Result<Option<String>, String>
where
F: FnOnce(&str) -> Option<String>,
{
resolve_api_key_source_with_resolvers(raw, env_lookup, |_command| {
Err("API key command resolution is not available in this test helper".to_string())
})
}
fn resolve_api_key_source_with_resolvers<F, G>(
raw: &str,
env_lookup: F,
mut command_runner: G,
) -> std::result::Result<Option<String>, String>
where
F: FnOnce(&str) -> Option<String>,
G: FnMut(&str) -> std::result::Result<Option<String>, String>,
{
if let Some(var_name) = raw.strip_prefix("$ENV:") {
if var_name.is_empty() {
return Err("$ENV: prefix requires a variable name (e.g. $ENV:MY_API_KEY)".to_string());
}
return match env_lookup(var_name) {
Some(value) if !value.trim().is_empty() => Ok(Some(value.trim().to_string())),
Some(_) => {
tracing::warn!(
event = "pi.auth.env_var_empty",
var = var_name,
"API key env var is set but empty"
);
Ok(None)
}
None => {
tracing::warn!(
event = "pi.auth.env_var_missing",
var = var_name,
"API key env var is not set"
);
Ok(None)
}
};
}
if let Some(command) = raw
.strip_prefix("$CMD:")
.or_else(|| raw.strip_prefix("$COMMAND:"))
{
let command = command.trim();
if command.is_empty() {
return Err(
"$CMD: prefix requires a shell command (e.g. $CMD:op read \"op://vault/item/field\" --no-newline)"
.to_string(),
);
}
return command_runner(command).map(|resolved| {
resolved.and_then(|value| {
let trimmed = value.trim();
(!trimmed.is_empty()).then(|| trimmed.to_string())
})
});
}
// Plain literal key — backward compatible.
Ok(Some(raw.to_string()))
}
fn run_api_key_source_command(command: &str) -> std::result::Result<Option<String>, String> {
let output = build_api_key_command_shell(command)
.output()
.map_err(|e| format!("Failed to run API key command: {e}"))?;
if !output.status.success() {