forked from aws/aws-toolkit-vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiamProfileSelection.ts
More file actions
1335 lines (1174 loc) · 51.7 KB
/
iamProfileSelection.ts
File metadata and controls
1335 lines (1174 loc) · 51.7 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
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import * as vscode from 'vscode'
import * as path from 'path'
import * as os from 'os'
import { getLogger } from '../../../shared/logger/logger'
import { ToolkitError } from '../../../shared/errors'
import { loadSharedCredentialsProfiles, parseIni } from '../../../auth/credentials/sharedCredentials'
import { getCredentialsFilename, getConfigFilename } from '../../../auth/credentials/sharedCredentialsFile'
import { SmusErrorCodes, DataZoneServiceId } from '../../shared/smusUtils'
import globals from '../../../shared/extensionGlobals'
import fs from '../../../shared/fs/fs'
/**
* Actions available in the credential management dialog
*/
enum CredentialManagementAction {
EditCredentialsFile = 'EDIT_CREDENTIALS_FILE',
EditConfigFile = 'EDIT_CONFIG_FILE',
AddNewProfile = 'ADD_NEW_PROFILE',
}
/**
* Actions available in the profile selection dialog
*/
enum ProfileSelectionAction {
SelectProfile = 'SELECT_PROFILE',
ManageCredentials = 'MANAGE_CREDENTIALS',
}
/**
* Actions available in the session token input dialog
*/
enum SessionTokenAction {
Skip = 'SKIP',
UseToken = 'USE_TOKEN',
Warning = 'WARNING',
}
/**
* Result of IAM profile selection
*/
export interface IamProfileSelection {
profileName: string
region: string
}
/**
* Result indicating user chose to edit credential files
*/
export interface IamProfileEditingInProgress {
isEditing: true
message: string
}
/**
* Result indicating user chose to go back
*/
export interface IamProfileBackNavigation {
isBack: true
message: string
}
/**
* IAM profile selection interface for SMUS
*/
export class SmusIamProfileSelector {
private static readonly logger = getLogger('smus')
// Validation regex patterns (based on AWS STS API specifications)
// Reference: https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html
private static readonly profileNamePattern = /^[a-zA-Z0-9_-]+$/
// AWS AccessKeyId: 16-128 chars, pattern [\w]* (alphanumeric + underscore)
private static readonly accessKeyIdPattern = /^[a-zA-Z0-9_]*$/
// AWS SecretAccessKey and SessionToken: Required per STS API, but no pattern/length constraints specified
private static readonly regionLinePattern = /^region\s*=.*$/m
/**
* Creates a QuickPick with common settings for input dialogs
* @param title Title for the QuickPick
* @param placeholder Placeholder text
* @returns Configured QuickPick instance
*/
private static createInputQuickPick(title: string, placeholder: string): vscode.QuickPick<vscode.QuickPickItem> {
const quickPick = vscode.window.createQuickPick()
quickPick.title = title
quickPick.placeholder = placeholder
quickPick.canSelectMany = false
quickPick.ignoreFocusOut = true
quickPick.buttons = [vscode.QuickInputButtons.Back]
return quickPick
}
/**
* Shows the IAM profile selection dialog matching the Figma design
* @returns Promise resolving to the selected profile and region, editing status, or back navigation
*/
public static async showIamProfileSelection(): Promise<
IamProfileSelection | IamProfileEditingInProgress | IamProfileBackNavigation
> {
const logger = this.logger
try {
// Load available credential profiles
const profiles = await loadSharedCredentialsProfiles()
const profileNames = Object.keys(profiles)
// Create QuickPick items for profiles
const profileItems: (vscode.QuickPickItem & {
action: ProfileSelectionAction
profileName: string
region: string
})[] = profileNames.map((profileName) => {
const profile = profiles[profileName]
const region = profile.region || 'not-set'
return {
label: `$(key) ${profileName}`,
description: `IAM Credentials, configured locally (${region})`,
detail: `Profile: ${profileName} | Region: ${region}`,
action: ProfileSelectionAction.SelectProfile,
profileName,
region,
}
})
// Add "Add or edit credentials" option
const addCredentialsItem: vscode.QuickPickItem & { action: ProfileSelectionAction } = {
label: '$(add) Add or edit credentials',
description: 'Manage AWS credential profiles',
detail: 'Add new profiles or edit existing credential files',
action: ProfileSelectionAction.ManageCredentials,
}
const options = [...profileItems, addCredentialsItem]
const quickPick = vscode.window.createQuickPick()
quickPick.title = 'Select an IAM Profile'
quickPick.placeholder = 'Choose an AWS credential profile to authenticate with SageMaker Unified Studio'
quickPick.items = options
quickPick.canSelectMany = false
quickPick.ignoreFocusOut = true
// Add back button
const backButton = vscode.QuickInputButtons.Back
quickPick.buttons = [backButton]
return new Promise((resolve, reject) => {
let isCompleted = false
quickPick.onDidAccept(() => {
const selectedItem = quickPick.selectedItems[0]
if (!selectedItem) {
quickPick.dispose()
reject(
new ToolkitError('No profile selected', {
code: SmusErrorCodes.UserCancelled,
cancelled: true,
})
)
return
}
isCompleted = true
quickPick.dispose()
const itemWithAction = selectedItem as vscode.QuickPickItem & {
action: ProfileSelectionAction
profileName?: string
region?: string
}
// Check if user selected "Add or edit credentials"
if (itemWithAction.action === ProfileSelectionAction.ManageCredentials) {
// Handle the async credential management flow
void (async () => {
try {
const managementResult = await SmusIamProfileSelector.showCredentialManagement()
// Check if a new profile was created (returns IamProfileSelection)
if (typeof managementResult === 'object' && 'profileName' in managementResult) {
// User created a new profile, use it directly
logger.debug(
`SMUS Auth: Using newly created profile: ${managementResult.profileName}`
)
resolve(managementResult)
} else if (managementResult === true) {
// User wants to restart profile selection (e.g., clicked back)
const result = await SmusIamProfileSelector.showIamProfileSelection()
resolve(result)
} else {
// User chose to edit files, return a special result indicating this
resolve({
isEditing: true,
message:
'User chose to edit credential files. Please complete setup and try again.',
})
}
} catch (error) {
// Handle user cancellation gracefully
if (error instanceof ToolkitError && error.code === SmusErrorCodes.UserCancelled) {
resolve({
isEditing: true,
message: 'User cancelled credential management.',
})
} else {
reject(error)
}
}
})()
return
}
// User selected an existing profile
// Ensure we have profile data (should always be present for SelectProfile action)
if (!itemWithAction.profileName || !itemWithAction.region) {
reject(new ToolkitError('Invalid profile selection', { code: 'InvalidProfileSelection' }))
return
}
const profileName = itemWithAction.profileName
const profileRegion = itemWithAction.region
logger.debug(`User selected profile: ${profileName}`)
// Check if region is not set and prompt for region selection
if (profileRegion === 'not-set') {
void (async () => {
try {
const selectedRegion = await SmusIamProfileSelector.showRegionSelection()
// Check if user clicked back on region selection
if (selectedRegion === 'BACK') {
resolve({
isBack: true,
message: 'User chose to go back from region selection.',
})
return
}
// Update the profile with the selected region
await SmusIamProfileSelector.updateProfileRegion(profileName, selectedRegion)
resolve({
profileName: profileName,
region: selectedRegion,
})
} catch (error) {
reject(error)
}
})()
} else {
resolve({
profileName: profileName,
region: profileRegion,
})
}
})
quickPick.onDidTriggerButton((button) => {
if (button === vscode.QuickInputButtons.Back) {
isCompleted = true
quickPick.dispose()
resolve({
isBack: true,
message: 'User chose to go back to authentication method selection.',
})
}
})
quickPick.onDidHide(() => {
if (!isCompleted) {
quickPick.dispose()
reject(
new ToolkitError('Profile selection cancelled', {
code: SmusErrorCodes.UserCancelled,
cancelled: true,
})
)
}
})
quickPick.show()
})
} catch (error) {
// Don't log or chain user cancellation as an error
if (error instanceof ToolkitError && error.code === SmusErrorCodes.UserCancelled) {
throw error
}
logger.error('Failed to show IAM profile selection: %s', error)
throw ToolkitError.chain(error, 'Failed to show IAM profile selection')
}
}
/**
* Shows region selection dialog for IAM authentication
* @param options Configuration options for the region selection dialog
* @returns Promise resolving to the selected region or 'BACK' if user wants to go back
*/
public static async showRegionSelection(options?: {
defaultRegion?: string
title?: string
placeholder?: string
returnBackOnCancel?: boolean
}): Promise<string> {
const logger = this.logger
// Get regions where DataZone service is available
const allRegions = globals.regionProvider.getRegions()
const dataZoneRegions = allRegions.filter((region) =>
globals.regionProvider.isServiceInRegion(DataZoneServiceId, region.id)
)
// If no regions found with DataZone service, fall back to all regions
const regions = dataZoneRegions.length > 0 ? dataZoneRegions : allRegions
const regionItems: vscode.QuickPickItem[] = regions.map(
(region) =>
({
label: region.name,
description: region.id,
detail: `AWS Region: ${region.id}`,
regionCode: region.id,
}) as vscode.QuickPickItem & { regionCode: string }
)
const quickPick = this.createInputQuickPick(
options?.title ?? 'Select AWS Region',
options?.placeholder ?? 'Choose the AWS region for SageMaker Unified Studio'
)
quickPick.items = regionItems
// Allow users to find matches by typing in the region code (e.g., us-east-1)
quickPick.matchOnDescription = true
// Pre-select default region if provided
if (options?.defaultRegion) {
const defaultItem = regionItems.find((item) => (item as any).regionCode === options.defaultRegion)
if (defaultItem) {
quickPick.activeItems = [defaultItem]
}
}
return new Promise((resolve, reject) => {
let isCompleted = false
quickPick.onDidAccept(() => {
const selectedItem = quickPick.selectedItems[0]
if (!selectedItem) {
if (options?.returnBackOnCancel) {
quickPick.dispose()
resolve('BACK')
} else {
quickPick.dispose()
reject(
new ToolkitError('No region selected', {
code: SmusErrorCodes.UserCancelled,
cancelled: true,
})
)
}
return
}
isCompleted = true
quickPick.dispose()
const regionItem = selectedItem as vscode.QuickPickItem & { regionCode: string }
logger.debug(`User selected region: ${regionItem.regionCode}`)
resolve(regionItem.regionCode)
})
quickPick.onDidTriggerButton((button) => {
if (button === vscode.QuickInputButtons.Back) {
isCompleted = true
quickPick.dispose()
resolve('BACK')
}
})
quickPick.onDidHide(() => {
if (!isCompleted) {
quickPick.dispose()
if (options?.returnBackOnCancel) {
resolve('BACK')
} else {
reject(
new ToolkitError('Region selection cancelled', {
code: SmusErrorCodes.UserCancelled,
cancelled: true,
})
)
}
}
})
quickPick.show()
})
}
/**
* Shows credential management options (Add/Edit credentials)
* @returns Promise resolving to boolean indicating if profile selection should restart, or profile data if a new profile was created
*/
public static async showCredentialManagement(): Promise<boolean | IamProfileSelection> {
const logger = this.logger
logger.debug('Showing credential management options')
const options: (vscode.QuickPickItem & { action: CredentialManagementAction })[] = [
{
label: '$(file-text) Edit AWS Credentials File',
description: 'Open ~/.aws/credentials file for editing',
detail: 'Edit existing credential profiles or add new ones',
action: CredentialManagementAction.EditCredentialsFile,
},
{
label: '$(file-text) Edit AWS Config File',
description: 'Open ~/.aws/config file for editing',
detail: 'Edit AWS configuration settings and profiles',
action: CredentialManagementAction.EditConfigFile,
},
{
label: '$(add) Add New Profile',
description: 'Create a new AWS credential profile',
detail: 'Interactive setup for a new credential profile',
action: CredentialManagementAction.AddNewProfile,
},
]
const quickPick = vscode.window.createQuickPick()
quickPick.title = 'Manage AWS Credentials'
quickPick.placeholder = 'Choose how you want to manage your AWS credentials'
quickPick.items = options
quickPick.canSelectMany = false
quickPick.ignoreFocusOut = true
// Add back button
const backButton = vscode.QuickInputButtons.Back
quickPick.buttons = [backButton]
return new Promise((resolve, reject) => {
let isCompleted = false
quickPick.onDidAccept(() => {
const selectedItem = quickPick.selectedItems[0]
if (!selectedItem) {
quickPick.dispose()
reject(
new ToolkitError('No option selected', { code: SmusErrorCodes.UserCancelled, cancelled: true })
)
return
}
isCompleted = true
quickPick.dispose()
// Handle the async operations after disposing the quick pick
void (async () => {
try {
const itemWithAction = selectedItem as vscode.QuickPickItem & {
action: CredentialManagementAction
}
switch (itemWithAction.action) {
case CredentialManagementAction.EditCredentialsFile: {
const result = await this.openAwsFile('credentials')
// If user clicked "Select Profile", restart profile selection
resolve(result === 'RESTART_PROFILE_SELECTION')
break
}
case CredentialManagementAction.EditConfigFile: {
const result = await this.openAwsFile('config')
// If user clicked "Select Profile", restart profile selection
resolve(result === 'RESTART_PROFILE_SELECTION')
break
}
case CredentialManagementAction.AddNewProfile: {
const newProfile = await this.addNewProfile()
// Return the newly created profile data to use it directly
resolve(newProfile)
break
}
}
} catch (error) {
if (error instanceof ToolkitError && error.code === SmusErrorCodes.UserCancelled) {
// User cancelled, don't treat as error
reject(error)
} else {
reject(error)
}
}
})()
})
quickPick.onDidTriggerButton((button) => {
if (button === vscode.QuickInputButtons.Back) {
isCompleted = true
quickPick.dispose()
// User wants to go back to profile selection
resolve(true)
}
})
quickPick.onDidHide(() => {
if (!isCompleted) {
quickPick.dispose()
reject(
new ToolkitError('Credential management cancelled', {
code: SmusErrorCodes.UserCancelled,
cancelled: true,
})
)
}
})
quickPick.show()
})
}
/**
* Opens the AWS credentials file in VS Code editor
*/
/**
* Opens an AWS configuration file in VS Code editor
* @param fileType Type of file to open ('credentials' or 'config')
*/
private static async openAwsFile(fileType: 'credentials' | 'config'): Promise<void | 'RESTART_PROFILE_SELECTION'> {
const logger = this.logger
const isCredentials = fileType === 'credentials'
try {
const filePath = isCredentials ? getCredentialsFilename() : getConfigFilename()
const fileLabel = isCredentials ? 'credentials' : 'config'
logger.debug(`Opening ${fileLabel} file: ${filePath}`)
// Ensure the .aws directory exists
await this.ensureAwsDirectoryExists()
// Create the file if it doesn't exist
if (!(await fs.existsFile(filePath))) {
await fs.writeFile(filePath, '')
logger.debug(`Created new ${fileLabel} file`)
}
// Open the file in VS Code
const document = await vscode.workspace.openTextDocument(filePath)
await vscode.window.showTextDocument(document)
logger.debug(`${fileLabel} file opened successfully`)
} catch (error) {
const fileLabel = isCredentials ? 'credentials' : 'config'
logger.error(`Failed to open ${fileLabel} file: %s`, error)
throw new ToolkitError(`Failed to open AWS ${fileLabel} file: ${(error as Error).message}`, {
code: isCredentials ? 'CredentialsFileError' : 'ConfigFileError',
})
}
}
/**
* Interactive flow to add a new AWS credential profile with back navigation
* @returns Promise resolving to the newly created profile data
*/
private static async addNewProfile(): Promise<IamProfileSelection> {
const logger = this.logger
try {
logger.debug('Starting add new profile flow')
const profileData = await this.collectProfileData()
if (profileData === 'BACK') {
// User navigated back, throw error to go back to credential management
throw new ToolkitError('User navigated back', { code: SmusErrorCodes.UserCancelled, cancelled: true })
}
// Add the profile to credentials file
await this.addProfileToCredentialsFile(
profileData.profileName,
profileData.accessKeyId,
profileData.secretAccessKey,
profileData.sessionToken,
profileData.region
)
// Show success message
void vscode.window.showInformationMessage(
`AWS profile '${profileData.profileName}' has been added successfully and will be used for authentication.`
)
logger.debug(`Successfully added new profile: ${profileData.profileName}`)
// Return the profile data to use it directly
return {
profileName: profileData.profileName,
region: profileData.region,
}
} catch (error) {
// Only log actual errors, not user cancellations
if (error instanceof ToolkitError && error.code === SmusErrorCodes.UserCancelled) {
logger.debug('User cancelled add new profile flow')
throw error // Re-throw for telemetry but don't log as error
}
logger.error('Failed to add new profile: %s', error)
throw new ToolkitError(`Failed to add new profile: ${(error as Error).message}`, {
code: 'AddProfileError',
})
}
}
/**
* Collects profile data through a multi-step flow with back navigation
*/
private static async collectProfileData(): Promise<
| {
profileName: string
accessKeyId: string
secretAccessKey: string
sessionToken?: string
region: string
}
| 'BACK'
> {
let currentStep = 1
let profileName = ''
let accessKeyId = ''
let secretAccessKey = ''
let sessionToken = ''
let region = ''
while (currentStep <= 5) {
switch (currentStep) {
case 1: {
// Step 1: Profile Name
const result = await this.getProfileNameInput()
if (result === 'BACK') {
return 'BACK' // User wants to go back - exit to credential management menu
}
profileName = result
currentStep = 2
break
}
case 2: {
// Step 2: Access Key ID
const result = await this.getAccessKeyIdInput()
if (result === 'BACK') {
currentStep = 1 // Go back to step 1
} else {
accessKeyId = result
currentStep = 3
}
break
}
case 3: {
// Step 3: Secret Access Key
const result = await this.getSecretAccessKeyInput()
if (result === 'BACK') {
currentStep = 2 // Go back to step 2
} else {
secretAccessKey = result
currentStep = 4
}
break
}
case 4: {
// Step 4: Session Token (optional)
const result = await this.getSessionTokenInput()
if (result === 'BACK') {
currentStep = 3 // Go back to step 3
} else {
sessionToken = result
currentStep = 5
}
break
}
case 5: {
// Step 5: Region
const result = await this.showRegionSelection({
title: 'Add New AWS Profile - Step 5 of 5',
placeholder: 'Select a default region',
returnBackOnCancel: true,
})
if (result === 'BACK') {
currentStep = 4 // Go back to step 4
} else {
region = result
currentStep = 6 // Exit the loop
}
break
}
}
}
return {
profileName,
accessKeyId,
secretAccessKey,
sessionToken: sessionToken || undefined,
region, // Region is always set since step 5 is required
}
}
/**
* Gets profile name input with back navigation and existing profile validation
*/
private static async getProfileNameInput(): Promise<string | 'BACK'> {
return new Promise((resolve) => {
const quickPick = this.createInputQuickPick(
'Add New AWS Profile - Step 1 of 5',
'Type a profile name (e.g., my-profile, dev, prod)'
)
quickPick.items = []
let isCompleted = false
quickPick.onDidTriggerButton((button) => {
if (button === vscode.QuickInputButtons.Back) {
isCompleted = true
quickPick.dispose()
resolve('BACK')
}
})
quickPick.onDidChangeValue(async (value) => {
// Show placeholder when empty
if (!value) {
quickPick.items = [
{
label: '$(edit) Enter profile name',
description: 'e.g., my-profile, dev, prod',
detail: 'Profile names can contain letters, numbers, hyphens, and underscores',
},
]
return
}
// Validate input as user types
if (value.includes(' ')) {
quickPick.items = [
{
label: `${value}`,
description: '$(error) Cannot contain spaces',
detail: 'Valid characters: letters, numbers, hyphens, underscores',
},
]
} else if (!this.profileNamePattern.test(value)) {
quickPick.items = [
{
label: `${value}`,
description: '$(error) Invalid characters',
detail: 'Profile names can only contain letters, numbers, hyphens, and underscores',
},
]
} else if (value.length < 2) {
quickPick.items = [
{
label: `${value}`,
description: `$(info) Too short (${value.length}/2 min)`,
detail: 'Profile names should be at least 2 characters long',
},
]
} else {
// Check if profile already exists
try {
const profiles = await loadSharedCredentialsProfiles()
const profileExists = profiles[value] !== undefined
if (profileExists) {
quickPick.items = [
{
label: `${value}`,
description: '$(warning) Profile exists - will be overwritten',
detail: 'Press Enter to overwrite the existing profile',
},
]
} else {
quickPick.items = [
{
label: `${value}`,
description: `$(check) Valid (${value.length} characters)`,
detail: 'Press Enter to use this profile name',
},
]
}
} catch (error) {
// If we can't load profiles, just show as valid
quickPick.items = [
{
label: `${value}`,
description: `$(check) Valid (${value.length} characters)`,
detail: 'Press Enter to use this profile name',
},
]
}
}
})
quickPick.onDidAccept(async () => {
const value = quickPick.value.trim()
// Validate final input
if (!value || value.length < 2) {
return // Don't accept empty or too short input
}
if (value.includes(' ')) {
return // Don't accept names with spaces
}
if (!this.profileNamePattern.test(value)) {
return // Don't accept invalid characters
}
// Check if profile exists and ask for confirmation
try {
const profiles = await loadSharedCredentialsProfiles()
const profileExists = profiles[value] !== undefined
if (profileExists) {
isCompleted = true
quickPick.dispose()
// Ask for confirmation to overwrite
const overwrite = await vscode.window.showWarningMessage(
`Profile '${value}' already exists. Do you want to overwrite it?`,
{ modal: true },
'Overwrite'
)
if (overwrite === 'Overwrite') {
resolve(value)
} else {
// User cancelled, restart the input
const result = await this.getProfileNameInput()
resolve(result)
}
return
}
} catch (error) {
// If we can't load profiles, just continue
}
isCompleted = true
quickPick.dispose()
resolve(value)
})
quickPick.onDidHide(() => {
if (!isCompleted) {
quickPick.dispose()
resolve('BACK')
}
})
quickPick.show()
})
}
/**
* Gets access key ID input with back navigation
*/
private static async getAccessKeyIdInput(): Promise<string | 'BACK'> {
return new Promise((resolve) => {
const quickPick = this.createInputQuickPick(
'Add New AWS Profile - Step 2 of 5',
'Type your AWS Access Key ID (e.g., AKIAIOSFODNN7EXAMPLE)'
)
quickPick.items = []
let isCompleted = false
quickPick.onDidTriggerButton((button) => {
if (button === vscode.QuickInputButtons.Back) {
isCompleted = true
quickPick.dispose()
resolve('BACK')
}
})
quickPick.onDidChangeValue((value) => {
// Show placeholder when empty
if (!value) {
quickPick.items = [
{
label: '$(key) Enter AWS Access Key ID',
description: 'e.g., AKIAIOSFODNN7EXAMPLE',
detail: 'Access Key IDs are typically 16-32 characters long',
},
]
return
}
// Validate input as user types (AWS STS API: 16-128 chars, pattern [\w]*)
// Reference: https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html
if (!this.accessKeyIdPattern.test(value)) {
quickPick.items = [
{
label: `${value}`,
description: '$(error) Invalid characters',
detail: 'Access Key IDs can only contain letters, numbers, and underscores',
},
]
} else if (value.length < 16) {
quickPick.items = [
{
label: `${value}`,
description: `$(info) Too short (${value.length}/16 min)`,
detail: 'AWS Access Key IDs must be 16-128 characters long',
},
]
} else if (value.length > 128) {
quickPick.items = [
{
label: `${value}`,
description: `$(error) Too long (${value.length}/128 max)`,
detail: 'AWS Access Key IDs must be 16-128 characters long',
},
]
} else {
quickPick.items = [
{
label: `${value}`,
description: `$(check) Valid (${value.length} characters)`,
detail: 'Press Enter to use this Access Key ID',
},
]
}
})
quickPick.onDidAccept(() => {
const value = quickPick.value.trim()
// Validate final input (AWS STS API: 16-128 chars, pattern [\w]*)
// Reference: https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html
if (!value) {
return // Don't accept empty input
}
if (!this.accessKeyIdPattern.test(value)) {
return // Don't accept invalid characters
}
if (value.length < 16 || value.length > 128) {
return // Don't accept invalid length
}
isCompleted = true
quickPick.dispose()
resolve(value)
})
quickPick.onDidHide(() => {
if (!isCompleted) {
quickPick.dispose()
resolve('BACK')
}
})
quickPick.show()
})
}
/**
* Gets secret access key input with back navigation
*/
private static async getSecretAccessKeyInput(): Promise<string | 'BACK'> {
return new Promise((resolve) => {
const quickPick = this.createInputQuickPick(
'Add New AWS Profile - Step 3 of 5',
'Type your AWS Secret Access Key (will be hidden when typing)'
)
quickPick.items = []
let isCompleted = false
quickPick.onDidTriggerButton((button) => {
if (button === vscode.QuickInputButtons.Back) {
isCompleted = true
quickPick.dispose()
resolve('BACK')
}
})
quickPick.onDidChangeValue((value) => {
// Show placeholder when empty
if (!value) {
quickPick.items = [
{
label: '$(lock) Enter AWS Secret Access Key',
description: 'Required field',
detail: 'Enter your AWS Secret Access Key',
},
]
return
}
// AWS STS API: Required, no specific pattern/length constraints in docs
// Reference: https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html