forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
2002 lines (1784 loc) · 63.9 KB
/
auth.ts
File metadata and controls
2002 lines (1784 loc) · 63.9 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
import chalk from 'chalk'
import { exec } from 'child_process'
import { execa } from 'execa'
import { mkdir, stat } from 'fs/promises'
import memoize from 'lodash-es/memoize.js'
import { join } from 'path'
import { CLAUDE_AI_PROFILE_SCOPE } from 'src/constants/oauth.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from 'src/services/analytics/index.js'
import { getModelStrings } from 'src/utils/model/modelStrings.js'
import { getAPIProvider } from 'src/utils/model/providers.js'
import {
getIsNonInteractiveSession,
preferThirdPartyAuthentication,
} from '../bootstrap/state.js'
import {
getMockSubscriptionType,
shouldUseMockSubscription,
} from '../services/mockRateLimits.js'
import {
isOAuthTokenExpired,
refreshOAuthToken,
shouldUseClaudeAIAuth,
} from '../services/oauth/client.js'
import { getOauthProfileFromOauthToken } from '../services/oauth/getOauthProfile.js'
import type { OAuthTokens, SubscriptionType } from '../services/oauth/types.js'
import {
getApiKeyFromFileDescriptor,
getOAuthTokenFromFileDescriptor,
} from './authFileDescriptor.js'
import {
maybeRemoveApiKeyFromMacOSKeychainThrows,
normalizeApiKeyForConfig,
} from './authPortable.js'
import {
checkStsCallerIdentity,
clearAwsIniCache,
isValidAwsStsOutput,
} from './aws.js'
import { AwsAuthStatusManager } from './awsAuthStatusManager.js'
import { clearBetasCaches } from './betas.js'
import {
type AccountInfo,
checkHasTrustDialogAccepted,
getGlobalConfig,
saveGlobalConfig,
} from './config.js'
import { logAntError, logForDebugging } from './debug.js'
import {
getClaudeConfigHomeDir,
isBareMode,
isEnvTruthy,
isRunningOnHomespace,
} from './envUtils.js'
import { errorMessage } from './errors.js'
import { execSyncWithDefaults_DEPRECATED } from './execFileNoThrow.js'
import * as lockfile from './lockfile.js'
import { logError } from './log.js'
import { memoizeWithTTLAsync } from './memoize.js'
import { getSecureStorage } from './secureStorage/index.js'
import {
clearLegacyApiKeyPrefetch,
getLegacyApiKeyPrefetchResult,
} from './secureStorage/keychainPrefetch.js'
import {
clearKeychainCache,
getMacOsKeychainStorageServiceName,
getUsername,
} from './secureStorage/macOsKeychainHelpers.js'
import {
getSettings_DEPRECATED,
getSettingsForSource,
} from './settings/settings.js'
import { sleep } from './sleep.js'
import { jsonParse } from './slowOperations.js'
import { clearToolSchemaCache } from './toolSchemaCache.js'
/** Default TTL for API key helper cache in milliseconds (5 minutes) */
const DEFAULT_API_KEY_HELPER_TTL = 5 * 60 * 1000
/**
* CCR and Claude Desktop spawn the CLI with OAuth and should never fall back
* to the user's ~/.claude/settings.json API-key config (apiKeyHelper,
* env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN). Those settings exist for
* the user's terminal CLI, not managed sessions. Without this guard, a user
* who runs `claude` in their terminal with an API key sees every CCD session
* also use that key — and fail if it's stale/wrong-org.
*/
function isManagedOAuthContext(): boolean {
return (
isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) ||
process.env.CLAUDE_CODE_ENTRYPOINT === 'claude-desktop'
)
}
/** Whether we are supporting direct 1P auth. */
// this code is closely related to getAuthTokenSource
export function isAnthropicAuthEnabled(): boolean {
// --bare: API-key-only, never OAuth.
if (isBareMode()) return false
// `claude ssh` remote: ANTHROPIC_UNIX_SOCKET tunnels API calls through a
// local auth-injecting proxy. The launcher sets CLAUDE_CODE_OAUTH_TOKEN as a
// placeholder iff the local side is a subscriber (so the remote includes the
// oauth-2025 beta header to match what the proxy will inject). The remote's
// ~/.claude settings (apiKeyHelper, settings.env.ANTHROPIC_API_KEY) MUST NOT
// flip this — they'd cause a header mismatch with the proxy and a bogus
// "invalid x-api-key" from the API. See src/ssh/sshAuthProxy.ts.
if (process.env.ANTHROPIC_UNIX_SOCKET) {
return !!process.env.CLAUDE_CODE_OAUTH_TOKEN
}
const is3P =
isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) ||
isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) ||
isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY)
// Check if user has configured an external API key source
// This allows externally-provided API keys to work (without requiring proxy configuration)
const settings = getSettings_DEPRECATED() || {}
const apiKeyHelper = settings.apiKeyHelper
const hasExternalAuthToken =
process.env.ANTHROPIC_AUTH_TOKEN ||
apiKeyHelper ||
process.env.CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR
// Check if API key is from an external source (not managed by /login)
const { source: apiKeySource } = getAnthropicApiKeyWithSource({
skipRetrievingKeyFromApiKeyHelper: true,
})
const hasExternalApiKey =
apiKeySource === 'ANTHROPIC_API_KEY' || apiKeySource === 'apiKeyHelper'
// Disable Anthropic auth if:
// 1. Using 3rd party services (Bedrock/Vertex/Foundry)
// 2. User has an external API key (regardless of proxy configuration)
// 3. User has an external auth token (regardless of proxy configuration)
// this may cause issues if users have complex proxy / gateway "client-side creds" auth scenarios,
// e.g. if they want to set X-Api-Key to a gateway key but use Anthropic OAuth for the Authorization
// if we get reports of that, we should probably add an env var to force OAuth enablement
const shouldDisableAuth =
is3P ||
(hasExternalAuthToken && !isManagedOAuthContext()) ||
(hasExternalApiKey && !isManagedOAuthContext())
return !shouldDisableAuth
}
/** Where the auth token is being sourced from, if any. */
// this code is closely related to isAnthropicAuthEnabled
export function getAuthTokenSource() {
// --bare: API-key-only. apiKeyHelper (from --settings) is the only
// bearer-token-shaped source allowed. OAuth env vars, FD tokens, and
// keychain are ignored.
if (isBareMode()) {
if (getConfiguredApiKeyHelper()) {
return { source: 'apiKeyHelper' as const, hasToken: true }
}
return { source: 'none' as const, hasToken: false }
}
if (process.env.ANTHROPIC_AUTH_TOKEN && !isManagedOAuthContext()) {
return { source: 'ANTHROPIC_AUTH_TOKEN' as const, hasToken: true }
}
if (process.env.CLAUDE_CODE_OAUTH_TOKEN) {
return { source: 'CLAUDE_CODE_OAUTH_TOKEN' as const, hasToken: true }
}
// Check for OAuth token from file descriptor (or its CCR disk fallback)
const oauthTokenFromFd = getOAuthTokenFromFileDescriptor()
if (oauthTokenFromFd) {
// getOAuthTokenFromFileDescriptor has a disk fallback for CCR subprocesses
// that can't inherit the pipe FD. Distinguish by env var presence so the
// org-mismatch message doesn't tell the user to unset a variable that
// doesn't exist. Call sites fall through correctly — the new source is
// !== 'none' (cli/handlers/auth.ts → oauth_token) and not in the
// isEnvVarToken set (auth.ts:1844 → generic re-login message).
if (process.env.CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR) {
return {
source: 'CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR' as const,
hasToken: true,
}
}
return {
source: 'CCR_OAUTH_TOKEN_FILE' as const,
hasToken: true,
}
}
// Check if apiKeyHelper is configured without executing it
// This prevents security issues where arbitrary code could execute before trust is established
const apiKeyHelper = getConfiguredApiKeyHelper()
if (apiKeyHelper && !isManagedOAuthContext()) {
return { source: 'apiKeyHelper' as const, hasToken: true }
}
const oauthTokens = getClaudeAIOAuthTokens()
if (shouldUseClaudeAIAuth(oauthTokens?.scopes) && oauthTokens?.accessToken) {
return { source: 'claude.ai' as const, hasToken: true }
}
return { source: 'none' as const, hasToken: false }
}
export type ApiKeySource =
| 'ANTHROPIC_API_KEY'
| 'apiKeyHelper'
| '/login managed key'
| 'none'
export function getAnthropicApiKey(): null | string {
const { key } = getAnthropicApiKeyWithSource()
return key
}
export function hasAnthropicApiKeyAuth(): boolean {
const { key, source } = getAnthropicApiKeyWithSource({
skipRetrievingKeyFromApiKeyHelper: true,
})
return key !== null && source !== 'none'
}
export function getAnthropicApiKeyWithSource(
opts: { skipRetrievingKeyFromApiKeyHelper?: boolean } = {},
): {
key: null | string
source: ApiKeySource
} {
// --bare: hermetic auth. Only ANTHROPIC_API_KEY env or apiKeyHelper from
// the --settings flag. Never touches keychain, config file, or approval
// lists. 3P (Bedrock/Vertex/Foundry) uses provider creds, not this path.
if (isBareMode()) {
if (process.env.ANTHROPIC_API_KEY) {
return { key: process.env.ANTHROPIC_API_KEY, source: 'ANTHROPIC_API_KEY' }
}
if (getConfiguredApiKeyHelper()) {
return {
key: opts.skipRetrievingKeyFromApiKeyHelper
? null
: getApiKeyFromApiKeyHelperCached(),
source: 'apiKeyHelper',
}
}
return { key: null, source: 'none' }
}
// On homespace, don't use ANTHROPIC_API_KEY (use Console key instead)
// https://anthropic.slack.com/archives/C08428WSLKV/p1747331773214779
const apiKeyEnv = isRunningOnHomespace()
? undefined
: process.env.ANTHROPIC_API_KEY
// Always check for direct environment variable when the user ran claude --print.
// This is useful for CI, etc.
if (preferThirdPartyAuthentication() && apiKeyEnv) {
return {
key: apiKeyEnv,
source: 'ANTHROPIC_API_KEY',
}
}
if (isEnvTruthy(process.env.CI) || process.env.NODE_ENV === 'test') {
// Check for API key from file descriptor first
const apiKeyFromFd = getApiKeyFromFileDescriptor()
if (apiKeyFromFd) {
return {
key: apiKeyFromFd,
source: 'ANTHROPIC_API_KEY',
}
}
if (
!apiKeyEnv &&
!process.env.CLAUDE_CODE_OAUTH_TOKEN &&
!process.env.CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR
) {
throw new Error(
'ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN env var is required',
)
}
if (apiKeyEnv) {
return {
key: apiKeyEnv,
source: 'ANTHROPIC_API_KEY',
}
}
// OAuth token is present but this function returns API keys only
return {
key: null,
source: 'none',
}
}
// Check for ANTHROPIC_API_KEY before checking the apiKeyHelper or /login-managed key
if (
apiKeyEnv &&
getGlobalConfig().customApiKeyResponses?.approved?.includes(
normalizeApiKeyForConfig(apiKeyEnv),
)
) {
return {
key: apiKeyEnv,
source: 'ANTHROPIC_API_KEY',
}
}
// Check for API key from file descriptor
const apiKeyFromFd = getApiKeyFromFileDescriptor()
if (apiKeyFromFd) {
return {
key: apiKeyFromFd,
source: 'ANTHROPIC_API_KEY',
}
}
// Check for apiKeyHelper — use sync cache, never block
const apiKeyHelperCommand = getConfiguredApiKeyHelper()
if (apiKeyHelperCommand) {
if (opts.skipRetrievingKeyFromApiKeyHelper) {
return {
key: null,
source: 'apiKeyHelper',
}
}
// Cache may be cold (helper hasn't finished yet). Return null with
// source='apiKeyHelper' rather than falling through to keychain —
// apiKeyHelper must win. Callers needing a real key must await
// getApiKeyFromApiKeyHelper() first (client.ts, useApiKeyVerification do).
return {
key: getApiKeyFromApiKeyHelperCached(),
source: 'apiKeyHelper',
}
}
const apiKeyFromConfigOrMacOSKeychain = getApiKeyFromConfigOrMacOSKeychain()
if (apiKeyFromConfigOrMacOSKeychain) {
return apiKeyFromConfigOrMacOSKeychain
}
return {
key: null,
source: 'none',
}
}
/**
* Get the configured apiKeyHelper from settings.
* In bare mode, only the --settings flag source is consulted — apiKeyHelper
* from ~/.claude/settings.json or project settings is ignored.
*/
export function getConfiguredApiKeyHelper(): string | undefined {
if (isBareMode()) {
return getSettingsForSource('flagSettings')?.apiKeyHelper
}
const mergedSettings = getSettings_DEPRECATED() || {}
return mergedSettings.apiKeyHelper
}
/**
* Check if the configured apiKeyHelper comes from project settings (projectSettings or localSettings)
*/
function isApiKeyHelperFromProjectOrLocalSettings(): boolean {
const apiKeyHelper = getConfiguredApiKeyHelper()
if (!apiKeyHelper) {
return false
}
const projectSettings = getSettingsForSource('projectSettings')
const localSettings = getSettingsForSource('localSettings')
return (
projectSettings?.apiKeyHelper === apiKeyHelper ||
localSettings?.apiKeyHelper === apiKeyHelper
)
}
/**
* Get the configured awsAuthRefresh from settings
*/
function getConfiguredAwsAuthRefresh(): string | undefined {
const mergedSettings = getSettings_DEPRECATED() || {}
return mergedSettings.awsAuthRefresh
}
/**
* Check if the configured awsAuthRefresh comes from project settings
*/
export function isAwsAuthRefreshFromProjectSettings(): boolean {
const awsAuthRefresh = getConfiguredAwsAuthRefresh()
if (!awsAuthRefresh) {
return false
}
const projectSettings = getSettingsForSource('projectSettings')
const localSettings = getSettingsForSource('localSettings')
return (
projectSettings?.awsAuthRefresh === awsAuthRefresh ||
localSettings?.awsAuthRefresh === awsAuthRefresh
)
}
/**
* Get the configured awsCredentialExport from settings
*/
function getConfiguredAwsCredentialExport(): string | undefined {
const mergedSettings = getSettings_DEPRECATED() || {}
return mergedSettings.awsCredentialExport
}
/**
* Check if the configured awsCredentialExport comes from project settings
*/
export function isAwsCredentialExportFromProjectSettings(): boolean {
const awsCredentialExport = getConfiguredAwsCredentialExport()
if (!awsCredentialExport) {
return false
}
const projectSettings = getSettingsForSource('projectSettings')
const localSettings = getSettingsForSource('localSettings')
return (
projectSettings?.awsCredentialExport === awsCredentialExport ||
localSettings?.awsCredentialExport === awsCredentialExport
)
}
/**
* Calculate TTL in milliseconds for the API key helper cache
* Uses CLAUDE_CODE_API_KEY_HELPER_TTL_MS env var if set and valid,
* otherwise defaults to 5 minutes
*/
export function calculateApiKeyHelperTTL(): number {
const envTtl = process.env.CLAUDE_CODE_API_KEY_HELPER_TTL_MS
if (envTtl) {
const parsed = parseInt(envTtl, 10)
if (!Number.isNaN(parsed) && parsed >= 0) {
return parsed
}
logForDebugging(
`Found CLAUDE_CODE_API_KEY_HELPER_TTL_MS env var, but it was not a valid number. Got ${envTtl}`,
{ level: 'error' },
)
}
return DEFAULT_API_KEY_HELPER_TTL
}
// Async API key helper with sync cache for non-blocking reads.
// Epoch bumps on clearApiKeyHelperCache() — orphaned executions check their
// captured epoch before touching module state so a settings-change or 401-retry
// mid-flight can't clobber the newer cache/inflight.
let _apiKeyHelperCache: { value: string; timestamp: number } | null = null
let _apiKeyHelperInflight: {
promise: Promise<string | null>
// Only set on cold launches (user is waiting); null for SWR background refreshes.
startedAt: number | null
} | null = null
let _apiKeyHelperEpoch = 0
export function getApiKeyHelperElapsedMs(): number {
const startedAt = _apiKeyHelperInflight?.startedAt
return startedAt ? Date.now() - startedAt : 0
}
export async function getApiKeyFromApiKeyHelper(
isNonInteractiveSession: boolean,
): Promise<string | null> {
if (!getConfiguredApiKeyHelper()) return null
const ttl = calculateApiKeyHelperTTL()
if (_apiKeyHelperCache) {
if (Date.now() - _apiKeyHelperCache.timestamp < ttl) {
return _apiKeyHelperCache.value
}
// Stale — return stale value now, refresh in the background.
// `??=` banned here by eslint no-nullish-assign-object-call (bun bug).
if (!_apiKeyHelperInflight) {
_apiKeyHelperInflight = {
promise: _runAndCache(
isNonInteractiveSession,
false,
_apiKeyHelperEpoch,
),
startedAt: null,
}
}
return _apiKeyHelperCache.value
}
// Cold cache — deduplicate concurrent calls
if (_apiKeyHelperInflight) return _apiKeyHelperInflight.promise
_apiKeyHelperInflight = {
promise: _runAndCache(isNonInteractiveSession, true, _apiKeyHelperEpoch),
startedAt: Date.now(),
}
return _apiKeyHelperInflight.promise
}
async function _runAndCache(
isNonInteractiveSession: boolean,
isCold: boolean,
epoch: number,
): Promise<string | null> {
try {
const value = await _executeApiKeyHelper(isNonInteractiveSession)
if (epoch !== _apiKeyHelperEpoch) return value
if (value !== null) {
_apiKeyHelperCache = { value, timestamp: Date.now() }
}
return value
} catch (e) {
if (epoch !== _apiKeyHelperEpoch) return ' '
const detail = e instanceof Error ? e.message : String(e)
// biome-ignore lint/suspicious/noConsole: user-configured script failed; must be visible without --debug
console.error(chalk.red(`apiKeyHelper failed: ${detail}`))
logForDebugging(`Error getting API key from apiKeyHelper: ${detail}`, {
level: 'error',
})
// SWR path: a transient failure shouldn't replace a working key with
// the ' ' sentinel — keep serving the stale value and bump timestamp
// so we don't hammer-retry every call.
if (!isCold && _apiKeyHelperCache && _apiKeyHelperCache.value !== ' ') {
_apiKeyHelperCache = { ..._apiKeyHelperCache, timestamp: Date.now() }
return _apiKeyHelperCache.value
}
// Cold cache or prior error — cache ' ' so callers don't fall back to OAuth
_apiKeyHelperCache = { value: ' ', timestamp: Date.now() }
return ' '
} finally {
if (epoch === _apiKeyHelperEpoch) {
_apiKeyHelperInflight = null
}
}
}
async function _executeApiKeyHelper(
isNonInteractiveSession: boolean,
): Promise<string | null> {
const apiKeyHelper = getConfiguredApiKeyHelper()
if (!apiKeyHelper) {
return null
}
if (isApiKeyHelperFromProjectOrLocalSettings()) {
const hasTrust = checkHasTrustDialogAccepted()
if (!hasTrust && !isNonInteractiveSession) {
const error = new Error(
`Security: apiKeyHelper executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`,
)
logAntError('apiKeyHelper invoked before trust check', error)
logEvent('tengu_apiKeyHelper_missing_trust11', {})
return null
}
}
const result = await execa(apiKeyHelper, {
shell: true,
timeout: 10 * 60 * 1000,
reject: false,
})
if (result.failed) {
// reject:false — execa resolves on exit≠0/timeout, stderr is on result
const why = result.timedOut ? 'timed out' : `exited ${result.exitCode}`
const stderr = result.stderr?.trim()
throw new Error(stderr ? `${why}: ${stderr}` : why)
}
const stdout = result.stdout?.trim()
if (!stdout) {
throw new Error('did not return a value')
}
return stdout
}
/**
* Sync cache reader — returns the last fetched apiKeyHelper value without executing.
* Returns stale values to match SWR semantics of the async reader.
* Returns null only if the async fetch hasn't completed yet.
*/
export function getApiKeyFromApiKeyHelperCached(): string | null {
return _apiKeyHelperCache?.value ?? null
}
export function clearApiKeyHelperCache(): void {
_apiKeyHelperEpoch++
_apiKeyHelperCache = null
_apiKeyHelperInflight = null
}
export function prefetchApiKeyFromApiKeyHelperIfSafe(
isNonInteractiveSession: boolean,
): void {
// Skip if trust not yet accepted — the inner _executeApiKeyHelper check
// would catch this too, but would fire a false-positive analytics event.
if (
isApiKeyHelperFromProjectOrLocalSettings() &&
!checkHasTrustDialogAccepted()
) {
return
}
void getApiKeyFromApiKeyHelper(isNonInteractiveSession)
}
/** Default STS credentials are one hour. We manually manage invalidation, so not too worried about this being accurate. */
const DEFAULT_AWS_STS_TTL = 60 * 60 * 1000
/**
* Run awsAuthRefresh to perform interactive authentication (e.g., aws sso login)
* Streams output in real-time for user visibility
*/
async function runAwsAuthRefresh(): Promise<boolean> {
const awsAuthRefresh = getConfiguredAwsAuthRefresh()
if (!awsAuthRefresh) {
return false // Not configured, treat as success
}
// SECURITY: Check if awsAuthRefresh is from project settings
if (isAwsAuthRefreshFromProjectSettings()) {
// Check if trust has been established for this project
const hasTrust = checkHasTrustDialogAccepted()
if (!hasTrust && !getIsNonInteractiveSession()) {
const error = new Error(
`Security: awsAuthRefresh executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`,
)
logAntError('awsAuthRefresh invoked before trust check', error)
logEvent('tengu_awsAuthRefresh_missing_trust', {})
return false
}
}
try {
logForDebugging('Fetching AWS caller identity for AWS auth refresh command')
await checkStsCallerIdentity()
logForDebugging(
'Fetched AWS caller identity, skipping AWS auth refresh command',
)
return false
} catch {
// only actually do the refresh if caller-identity calls
return refreshAwsAuth(awsAuthRefresh)
}
}
// Timeout for AWS auth refresh command (3 minutes).
// Long enough for browser-based SSO flows, short enough to prevent indefinite hangs.
const AWS_AUTH_REFRESH_TIMEOUT_MS = 3 * 60 * 1000
export function refreshAwsAuth(awsAuthRefresh: string): Promise<boolean> {
logForDebugging('Running AWS auth refresh command')
// Start tracking authentication status
const authStatusManager = AwsAuthStatusManager.getInstance()
authStatusManager.startAuthentication()
return new Promise(resolve => {
const refreshProc = exec(awsAuthRefresh, {
timeout: AWS_AUTH_REFRESH_TIMEOUT_MS,
})
refreshProc.stdout!.on('data', data => {
const output = data.toString().trim()
if (output) {
// Add output to status manager for UI display
authStatusManager.addOutput(output)
// Also log for debugging
logForDebugging(output, { level: 'debug' })
}
})
refreshProc.stderr!.on('data', data => {
const error = data.toString().trim()
if (error) {
authStatusManager.setError(error)
logForDebugging(error, { level: 'error' })
}
})
refreshProc.on('close', (code, signal) => {
if (code === 0) {
logForDebugging('AWS auth refresh completed successfully')
authStatusManager.endAuthentication(true)
void resolve(true)
} else {
const timedOut = signal === 'SIGTERM'
const message = timedOut
? chalk.red(
'AWS auth refresh timed out after 3 minutes. Run your auth command manually in a separate terminal.',
)
: chalk.red(
'Error running awsAuthRefresh (in settings or ~/.claude.json):',
)
// biome-ignore lint/suspicious/noConsole:: intentional console output
console.error(message)
authStatusManager.endAuthentication(false)
void resolve(false)
}
})
})
}
/**
* Run awsCredentialExport to get credentials and set environment variables
* Expects JSON output containing AWS credentials
*/
async function getAwsCredsFromCredentialExport(): Promise<{
accessKeyId: string
secretAccessKey: string
sessionToken: string
} | null> {
const awsCredentialExport = getConfiguredAwsCredentialExport()
if (!awsCredentialExport) {
return null
}
// SECURITY: Check if awsCredentialExport is from project settings
if (isAwsCredentialExportFromProjectSettings()) {
// Check if trust has been established for this project
const hasTrust = checkHasTrustDialogAccepted()
if (!hasTrust && !getIsNonInteractiveSession()) {
const error = new Error(
`Security: awsCredentialExport executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`,
)
logAntError('awsCredentialExport invoked before trust check', error)
logEvent('tengu_awsCredentialExport_missing_trust', {})
return null
}
}
try {
logForDebugging(
'Fetching AWS caller identity for credential export command',
)
await checkStsCallerIdentity()
logForDebugging(
'Fetched AWS caller identity, skipping AWS credential export command',
)
return null
} catch {
// only actually do the export if caller-identity calls
try {
logForDebugging('Running AWS credential export command')
const result = await execa(awsCredentialExport, {
shell: true,
reject: false,
})
if (result.exitCode !== 0 || !result.stdout) {
throw new Error('awsCredentialExport did not return a valid value')
}
// Parse the JSON output from aws sts commands
const awsOutput = jsonParse(result.stdout.trim())
if (!isValidAwsStsOutput(awsOutput)) {
throw new Error(
'awsCredentialExport did not return valid AWS STS output structure',
)
}
logForDebugging('AWS credentials retrieved from awsCredentialExport')
return {
accessKeyId: awsOutput.Credentials.AccessKeyId,
secretAccessKey: awsOutput.Credentials.SecretAccessKey,
sessionToken: awsOutput.Credentials.SessionToken,
}
} catch (e) {
const message = chalk.red(
'Error getting AWS credentials from awsCredentialExport (in settings or ~/.claude.json):',
)
if (e instanceof Error) {
// biome-ignore lint/suspicious/noConsole:: intentional console output
console.error(message, e.message)
} else {
// biome-ignore lint/suspicious/noConsole:: intentional console output
console.error(message, e)
}
return null
}
}
}
/**
* Refresh AWS authentication and get credentials with cache clearing
* This combines runAwsAuthRefresh, getAwsCredsFromCredentialExport, and clearAwsIniCache
* to ensure fresh credentials are always used
*/
export const refreshAndGetAwsCredentials = memoizeWithTTLAsync(
async (): Promise<{
accessKeyId: string
secretAccessKey: string
sessionToken: string
} | null> => {
// First run auth refresh if needed
const refreshed = await runAwsAuthRefresh()
// Get credentials from export
const credentials = await getAwsCredsFromCredentialExport()
// Clear AWS INI cache to ensure fresh credentials are used
if (refreshed || credentials) {
await clearAwsIniCache()
}
return credentials
},
DEFAULT_AWS_STS_TTL,
)
export function clearAwsCredentialsCache(): void {
refreshAndGetAwsCredentials.cache.clear()
}
/**
* Get the configured gcpAuthRefresh from settings
*/
function getConfiguredGcpAuthRefresh(): string | undefined {
const mergedSettings = getSettings_DEPRECATED() || {}
return mergedSettings.gcpAuthRefresh
}
/**
* Check if the configured gcpAuthRefresh comes from project settings
*/
export function isGcpAuthRefreshFromProjectSettings(): boolean {
const gcpAuthRefresh = getConfiguredGcpAuthRefresh()
if (!gcpAuthRefresh) {
return false
}
const projectSettings = getSettingsForSource('projectSettings')
const localSettings = getSettingsForSource('localSettings')
return (
projectSettings?.gcpAuthRefresh === gcpAuthRefresh ||
localSettings?.gcpAuthRefresh === gcpAuthRefresh
)
}
/** Short timeout for the GCP credentials probe. Without this, when no local
* credential source exists (no ADC file, no env var), google-auth-library falls
* through to the GCE metadata server which hangs ~12s outside GCP. */
const GCP_CREDENTIALS_CHECK_TIMEOUT_MS = 5_000
/**
* Check if GCP credentials are currently valid by attempting to get an access token.
* This uses the same authentication chain that the Vertex SDK uses.
*/
export async function checkGcpCredentialsValid(): Promise<boolean> {
try {
// Dynamically import to avoid loading google-auth-library unnecessarily
const { GoogleAuth } = await import('google-auth-library')
const auth = new GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
})
const probe = (async () => {
const client = await auth.getClient()
await client.getAccessToken()
})()
const timeout = sleep(GCP_CREDENTIALS_CHECK_TIMEOUT_MS).then(() => {
throw new GcpCredentialsTimeoutError('GCP credentials check timed out')
})
await Promise.race([probe, timeout])
return true
} catch {
return false
}
}
/** Default GCP credential TTL - 1 hour to match typical ADC token lifetime */
const DEFAULT_GCP_CREDENTIAL_TTL = 60 * 60 * 1000
/**
* Run gcpAuthRefresh to perform interactive authentication (e.g., gcloud auth application-default login)
* Streams output in real-time for user visibility
*/
async function runGcpAuthRefresh(): Promise<boolean> {
const gcpAuthRefresh = getConfiguredGcpAuthRefresh()
if (!gcpAuthRefresh) {
return false // Not configured, treat as success
}
// SECURITY: Check if gcpAuthRefresh is from project settings
if (isGcpAuthRefreshFromProjectSettings()) {
// Check if trust has been established for this project
// Pass true to indicate this is a dangerous feature that requires trust
const hasTrust = checkHasTrustDialogAccepted()
if (!hasTrust && !getIsNonInteractiveSession()) {
const error = new Error(
`Security: gcpAuthRefresh executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`,
)
logAntError('gcpAuthRefresh invoked before trust check', error)
logEvent('tengu_gcpAuthRefresh_missing_trust', {})
return false
}
}
try {
logForDebugging('Checking GCP credentials validity for auth refresh')
const isValid = await checkGcpCredentialsValid()
if (isValid) {
logForDebugging(
'GCP credentials are valid, skipping auth refresh command',
)
return false
}
} catch {
// Credentials check failed, proceed with refresh
}
return refreshGcpAuth(gcpAuthRefresh)
}
// Timeout for GCP auth refresh command (3 minutes).
// Long enough for browser-based auth flows, short enough to prevent indefinite hangs.
const GCP_AUTH_REFRESH_TIMEOUT_MS = 3 * 60 * 1000
export function refreshGcpAuth(gcpAuthRefresh: string): Promise<boolean> {
logForDebugging('Running GCP auth refresh command')
// Start tracking authentication status. AwsAuthStatusManager is cloud-provider-agnostic
// despite the name — print.ts emits its updates as generic SDK 'auth_status' messages.
const authStatusManager = AwsAuthStatusManager.getInstance()
authStatusManager.startAuthentication()
return new Promise(resolve => {
const refreshProc = exec(gcpAuthRefresh, {
timeout: GCP_AUTH_REFRESH_TIMEOUT_MS,
})
refreshProc.stdout!.on('data', data => {
const output = data.toString().trim()
if (output) {
// Add output to status manager for UI display
authStatusManager.addOutput(output)
// Also log for debugging
logForDebugging(output, { level: 'debug' })
}
})
refreshProc.stderr!.on('data', data => {
const error = data.toString().trim()
if (error) {
authStatusManager.setError(error)
logForDebugging(error, { level: 'error' })
}
})
refreshProc.on('close', (code, signal) => {
if (code === 0) {
logForDebugging('GCP auth refresh completed successfully')
authStatusManager.endAuthentication(true)
void resolve(true)
} else {
const timedOut = signal === 'SIGTERM'
const message = timedOut
? chalk.red(
'GCP auth refresh timed out after 3 minutes. Run your auth command manually in a separate terminal.',
)
: chalk.red(
'Error running gcpAuthRefresh (in settings or ~/.claude.json):',
)
// biome-ignore lint/suspicious/noConsole:: intentional console output
console.error(message)
authStatusManager.endAuthentication(false)
void resolve(false)
}
})
})
}
/**
* Refresh GCP authentication if needed.
* This function checks if credentials are valid and runs the refresh command if not.
* Memoized with TTL to avoid excessive refresh attempts.
*/
export const refreshGcpCredentialsIfNeeded = memoizeWithTTLAsync(
async (): Promise<boolean> => {
// Run auth refresh if needed
const refreshed = await runGcpAuthRefresh()
return refreshed
},
DEFAULT_GCP_CREDENTIAL_TTL,
)
export function clearGcpCredentialsCache(): void {
refreshGcpCredentialsIfNeeded.cache.clear()
}
/**
* Prefetches GCP credentials only if workspace trust has already been established.
* This allows us to start the potentially slow GCP commands early for trusted workspaces
* while maintaining security for untrusted ones.
*
* Returns void to prevent misuse - use refreshGcpCredentialsIfNeeded() to actually refresh.
*/
export function prefetchGcpCredentialsIfSafe(): void {
// Check if gcpAuthRefresh is configured
const gcpAuthRefresh = getConfiguredGcpAuthRefresh()
if (!gcpAuthRefresh) {
return
}