-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathplugin.ts
More file actions
768 lines (695 loc) · 26.6 KB
/
plugin.ts
File metadata and controls
768 lines (695 loc) · 26.6 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
import {
type Resolver, type PluginCacheAccessor, plugin, resolveCacheTtl,
} from 'varlock/plugin-lib';
import {
SecretsManagerClient,
GetSecretValueCommand,
type GetSecretValueCommandOutput,
} from '@aws-sdk/client-secrets-manager';
import {
SSMClient,
GetParameterCommand,
type GetParameterCommandOutput,
} from '@aws-sdk/client-ssm';
import { fromIni } from '@aws-sdk/credential-providers';
const { ValidationError, SchemaError, ResolutionError } = plugin.ERRORS;
const AWS_ICON = 'skill-icons:aws-dark';
plugin.name = 'aws';
const { debug } = plugin;
debug('init - version =', plugin.version);
plugin.icon = AWS_ICON;
// capture cache accessor while the plugin proxy context is active
// (the `plugin` proxy is only valid during module initialization, not during resolve())
let pluginCache: PluginCacheAccessor | undefined;
try {
pluginCache = plugin.cache;
} catch {
// cache not available (e.g., no encryption key)
}
plugin.standardVars = {
initDecorator: '@initAws',
params: {
region: { key: ['AWS_REGION', 'AWS_DEFAULT_REGION'] },
accessKeyId: { key: 'AWS_ACCESS_KEY_ID', dataType: 'awsAccessKey' },
secretAccessKey: { key: 'AWS_SECRET_ACCESS_KEY', dataType: 'awsSecretKey' },
},
};
const FIX_AUTH_TIP = [
'Verify your AWS credentials are configured correctly. Use one of the following options:',
' 1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables',
' 2. Configure ~/.aws/credentials file (run: aws configure)',
' 3. Provide credentials explicitly via @initAws(accessKeyId=..., secretAccessKey=...)',
' 4. Use IAM roles (if running on AWS infrastructure)',
].join('\n');
class AwsPluginInstance {
private region?: string;
private accessKeyId?: string;
private secretAccessKey?: string;
private sessionToken?: string;
private profile?: string;
private namePrefix?: string;
/** optional cache TTL - when set, resolved values are cached */
cacheTtl?: string | number;
constructor(
readonly id: string,
) {
}
setAuth(
region?: any,
accessKeyId?: any,
secretAccessKey?: any,
sessionToken?: any,
profile?: any,
namePrefix?: any,
) {
this.region = region ? String(region) : undefined;
this.accessKeyId = accessKeyId ? String(accessKeyId) : undefined;
this.secretAccessKey = secretAccessKey ? String(secretAccessKey) : undefined;
this.sessionToken = sessionToken ? String(sessionToken) : undefined;
this.profile = profile;
this.namePrefix = namePrefix ? String(namePrefix) : undefined;
debug(
'aws instance',
this.id,
'set auth - region:',
this.region,
'profile:',
this.profile,
'hasAccessKey:',
!!this.accessKeyId,
'hasSecretKey:',
!!this.secretAccessKey,
'namePrefix:',
this.namePrefix,
);
}
applyNamePrefix(name: string): string {
if (this.namePrefix) {
return this.namePrefix + name;
}
return name;
}
private secretsManagerClientPromise: Promise<SecretsManagerClient> | undefined;
async initSecretsManagerClient() {
if (this.secretsManagerClientPromise) return this.secretsManagerClientPromise;
this.secretsManagerClientPromise = (async () => {
try {
const clientConfig: any = {
region: this.region,
};
if (this.accessKeyId && this.secretAccessKey) {
// Use explicit credentials
clientConfig.credentials = {
accessKeyId: this.accessKeyId,
secretAccessKey: this.secretAccessKey,
sessionToken: this.sessionToken,
};
debug('Using explicit AWS credentials');
} else if (this.profile) {
// Use named profile from ~/.aws/credentials
clientConfig.credentials = fromIni({ profile: this.profile });
debug('Using AWS profile:', this.profile);
} else {
// Use default AWS credential chain (env vars, ~/.aws/credentials, IAM roles)
debug('Using default AWS credential chain');
}
const client = new SecretsManagerClient(clientConfig);
debug('AWS Secrets Manager client initialized for instance', this.id);
return client;
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
throw new SchemaError(`Failed to initialize AWS Secrets Manager client: ${errorMsg}`, {
tip: FIX_AUTH_TIP,
});
}
})();
return this.secretsManagerClientPromise;
}
private ssmClientPromise: Promise<SSMClient> | undefined;
async initSSMClient() {
if (this.ssmClientPromise) return this.ssmClientPromise;
this.ssmClientPromise = (async () => {
try {
const clientConfig: any = {
region: this.region,
};
if (this.accessKeyId && this.secretAccessKey) {
// Use explicit credentials
clientConfig.credentials = {
accessKeyId: this.accessKeyId,
secretAccessKey: this.secretAccessKey,
sessionToken: this.sessionToken,
};
debug('Using explicit AWS credentials');
} else if (this.profile) {
// Use named profile from ~/.aws/credentials
clientConfig.credentials = fromIni({ profile: this.profile });
debug('Using AWS profile:', this.profile);
} else {
// Use default AWS credential chain (env vars, ~/.aws/credentials, IAM roles)
debug('Using default AWS credential chain');
}
const client = new SSMClient(clientConfig);
debug('AWS SSM client initialized for instance', this.id);
return client;
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
throw new SchemaError(`Failed to initialize AWS SSM client: ${errorMsg}`, {
tip: FIX_AUTH_TIP,
});
}
})();
return this.ssmClientPromise;
}
async getSecret(secretId: string, jsonKey?: string): Promise<string> {
const client = await this.initSecretsManagerClient();
if (!client) throw new Error('Expected AWS Secrets Manager client to be initialized');
try {
const command = new GetSecretValueCommand({ SecretId: secretId });
const response: GetSecretValueCommandOutput = await client.send(command);
// Return SecretString if available, otherwise decode SecretBinary
let secretValue: string;
if (response.SecretString) {
secretValue = response.SecretString;
} else if (response.SecretBinary) {
// Decode binary secret
const buff = Buffer.from(response.SecretBinary);
secretValue = buff.toString('utf-8');
} else {
throw new ResolutionError('Secret data is empty');
}
// If a JSON key is specified, parse and extract it
if (jsonKey) {
try {
const parsed = JSON.parse(secretValue);
if (!(jsonKey in parsed)) {
throw new ResolutionError(`Key "${jsonKey}" not found in secret JSON`, {
tip: `Available keys: ${Object.keys(parsed).join(', ')}`,
});
}
return String(parsed[jsonKey]);
} catch (err) {
if (err instanceof ResolutionError) throw err;
throw new ResolutionError(`Failed to parse secret as JSON: ${err instanceof Error ? err.message : String(err)}`, {
tip: 'Ensure the secret value is valid JSON when extracting a specific key',
});
}
}
return secretValue;
} catch (err: any) {
// Re-throw ResolutionError as-is
if (err instanceof ResolutionError) {
throw err;
}
let errorMessage = 'Failed to fetch secret';
let errorTip: string | undefined;
// Handle common AWS Secrets Manager errors
const errorName = err.name || err.__type || '';
const errorCode = err.$metadata?.httpStatusCode;
if (errorName === 'ResourceNotFoundException' || errorCode === 404) {
errorMessage = `Secret "${secretId}" not found`;
errorTip = [
'Verify the secret exists in AWS Secrets Manager',
`AWS Console: https://console.aws.amazon.com/secretsmanager/home?region=${this.region || 'us-east-1'}`,
].join('\n');
} else if (errorName === 'AccessDeniedException' || errorCode === 403) {
errorMessage = `Permission denied accessing secret "${secretId}"`;
errorTip = [
'Ensure your IAM user/role has the required permissions',
'Required IAM policy:',
'{',
' "Effect": "Allow",',
' "Action": ["secretsmanager:GetSecretValue"],',
` "Resource": "arn:aws:secretsmanager:${this.region || '*'}:*:secret:*"`,
'}',
].join('\n');
} else if (errorName === 'InvalidRequestException') {
errorMessage = `Invalid request for secret "${secretId}"`;
errorTip = [
'Check the secret ID format:',
' - Name: "my-secret"',
' - ARN: "arn:aws:secretsmanager:region:account-id:secret:name-AbCdEf"',
' - Partial ARN: "name-AbCdEf"',
].join('\n');
} else if (
errorName.includes('Credential')
|| errorMessage.includes('credentials')
|| errorCode === 401
) {
// Check if we're using explicit credentials or default chain
if (!this.accessKeyId && !this.profile) {
errorMessage = 'Authentication failed';
errorTip = [
err.message,
FIX_AUTH_TIP,
].join('\n');
} else {
errorMessage = 'Authentication failed with provided credentials';
errorTip = 'Verify that your AWS credentials are valid and have the required permissions';
}
} else if (err.message) {
errorMessage = `AWS Secrets Manager error: ${err.message}`;
}
throw new ResolutionError(errorMessage, {
tip: errorTip,
});
}
}
async getParameter(name: string, jsonKey?: string): Promise<string> {
const client = await this.initSSMClient();
if (!client) throw new Error('Expected AWS SSM client to be initialized');
// Validate parameter name format before making the AWS call
if (!name.startsWith('/')) {
throw new ResolutionError(`Invalid AWS SSM parameter name: "${name}"`, {
tip: `SSM parameter names must start with "/"\n Try: "/${name}"`,
});
}
// AWS reserves the /ssm prefix (case-insensitive)
if (/^\/ssm(\/|$)/i.test(name)) {
throw new ResolutionError(`Invalid AWS SSM parameter name: "${name}"`, {
tip: 'SSM parameter names cannot start with "/ssm" (AWS reserved prefix, case-insensitive)',
});
}
// Validate parameter name characters (letters, numbers, and . - _ / are allowed)
if (!/^[a-zA-Z0-9/._-]+$/.test(name)) {
const invalidChars = [...new Set(name.match(/[^a-zA-Z0-9/._-]/g) || [])].join('');
throw new ResolutionError(`Invalid AWS SSM parameter name: "${name}"`, {
tip: `SSM parameter names can only contain letters, numbers, and the symbols / . - _\n Invalid character(s): ${invalidChars}`,
});
}
try {
const command = new GetParameterCommand({
Name: name,
WithDecryption: true,
});
const response: GetParameterCommandOutput = await client.send(command);
if (!response.Parameter?.Value) {
throw new ResolutionError('Parameter value is empty');
}
const paramValue = response.Parameter.Value;
// If a JSON key is specified, parse and extract it
if (jsonKey) {
try {
const parsed = JSON.parse(paramValue);
if (!(jsonKey in parsed)) {
throw new ResolutionError(`Key "${jsonKey}" not found in parameter JSON`, {
tip: `Available keys: ${Object.keys(parsed).join(', ')}`,
});
}
return String(parsed[jsonKey]);
} catch (err) {
if (err instanceof ResolutionError) throw err;
throw new ResolutionError(`Failed to parse parameter as JSON: ${err instanceof Error ? err.message : String(err)}`, {
tip: 'Ensure the parameter value is valid JSON when using the # syntax for key extraction',
});
}
}
return paramValue;
} catch (err: any) {
// Re-throw ResolutionError as-is
if (err instanceof ResolutionError) {
throw err;
}
let errorMessage = 'Failed to fetch parameter';
let errorTip: string | undefined;
// Handle common AWS Parameter Store errors
const errorName = err.name || err.__type || '';
const errorCode = err.$metadata?.httpStatusCode;
if (errorName === 'ParameterInvalidException' || errorName === 'ValidationException') {
errorMessage = `Invalid AWS SSM parameter name: "${name}"`;
errorTip = 'Parameter names must start with "/" and can only contain letters, numbers, and the symbols / . - _';
} else if (errorName === 'ParameterNotFound' || errorCode === 404) {
errorMessage = `Parameter "${name}" not found`;
errorTip = [
'Verify the parameter exists in AWS Systems Manager Parameter Store',
`AWS Console: https://console.aws.amazon.com/systems-manager/parameters?region=${this.region || 'us-east-1'}`,
].join('\n');
} else if (errorName === 'AccessDeniedException' || errorCode === 403) {
errorMessage = `Permission denied accessing parameter "${name}"`;
errorTip = [
'Ensure your IAM user/role has the required permissions',
'Required IAM policy:',
'{',
' "Effect": "Allow",',
' "Action": ["ssm:GetParameter"],',
` "Resource": "arn:aws:ssm:${this.region || '*'}:*:parameter/*"`,
'}',
].join('\n');
} else if (
errorName.includes('Credential')
|| errorMessage.includes('credentials')
|| errorCode === 401
) {
// Check if we're using explicit credentials or default chain
if (!this.accessKeyId && !this.profile) {
errorMessage = 'Authentication failed';
errorTip = [
err.message,
FIX_AUTH_TIP,
].join('\n');
} else {
errorMessage = 'Authentication failed with provided credentials';
errorTip = 'Verify that your AWS credentials are valid and have the required permissions';
}
} else if (err.message) {
errorMessage = `AWS Parameter Store error: ${err.message}`;
}
throw new ResolutionError(errorMessage, {
tip: errorTip,
});
}
}
}
const pluginInstances: Record<string, AwsPluginInstance> = {};
plugin.registerRootDecorator({
name: 'initAws',
description: 'Initialize an AWS plugin instance for awsSecret() and awsParam() resolvers',
isFunction: true,
async process(argsVal) {
const objArgs = argsVal.objArgs;
if (!objArgs) throw new SchemaError('Expected some args');
// Validate id is static
if (objArgs.id && !objArgs.id.isStatic) {
throw new SchemaError('Expected id to be static');
}
const id = String(objArgs?.id?.staticValue || '_default');
if (pluginInstances[id]) {
throw new SchemaError(`Instance with id "${id}" already initialized`);
}
// Region is required
if (!objArgs.region) {
throw new SchemaError('Region parameter is required');
}
pluginInstances[id] = new AwsPluginInstance(id);
return {
id,
profileResolver: objArgs.profile,
regionResolver: objArgs.region,
accessKeyIdResolver: objArgs.accessKeyId,
secretAccessKeyResolver: objArgs.secretAccessKey,
sessionTokenResolver: objArgs.sessionToken,
namePrefixResolver: objArgs.namePrefix,
cacheTtlResolver: objArgs.cacheTtl,
};
},
async execute({
id,
profileResolver,
regionResolver,
accessKeyIdResolver,
secretAccessKeyResolver,
sessionTokenResolver,
namePrefixResolver,
cacheTtlResolver,
}) {
const region = await regionResolver.resolve();
const accessKeyId = await accessKeyIdResolver?.resolve();
const secretAccessKey = await secretAccessKeyResolver?.resolve();
const sessionToken = await sessionTokenResolver?.resolve();
const profile = await profileResolver?.resolve();
const namePrefix = await namePrefixResolver?.resolve();
pluginInstances[id].setAuth(region, accessKeyId, secretAccessKey, sessionToken, profile, namePrefix);
const cacheTtl = await resolveCacheTtl(cacheTtlResolver);
if (cacheTtl !== undefined) {
pluginInstances[id].cacheTtl = cacheTtl;
}
},
});
plugin.registerDataType({
name: 'awsAccessKey',
sensitive: false,
typeDescription: 'AWS access key ID for IAM authentication',
icon: AWS_ICON,
docs: [
{
description: 'Managing access keys for IAM users',
url: 'https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html',
},
],
async validate(val): Promise<true> {
// AWS access keys are typically 20 characters and alphanumeric
if (!/^[A-Z0-9]{20}$/.test(val)) {
throw new ValidationError('Must be a 20-character alphanumeric string (typically starts with AKIA)');
}
return true;
},
});
plugin.registerDataType({
name: 'awsSecretKey',
sensitive: true,
typeDescription: 'AWS secret access key for IAM authentication',
icon: AWS_ICON,
docs: [
{
description: 'Managing access keys for IAM users',
url: 'https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html',
},
],
async validate(val): Promise<true> {
// AWS secret keys are typically 40 characters
if (val.length !== 40) {
throw new ValidationError('Must be exactly 40 characters long');
}
return true;
},
});
plugin.registerResolverFunction({
name: 'awsSecret',
label: 'Fetch secret from AWS Secrets Manager',
icon: AWS_ICON,
argsSchema: {
type: 'mixed',
arrayMinLength: 0,
},
process() {
let instanceId: string;
let secretIdResolver: Resolver | undefined;
let inferredSecretName: string | undefined;
let keyResolver: Resolver | undefined;
// Check for named 'key' parameter
if (this.objArgs?.key) {
keyResolver = this.objArgs.key;
}
// No args - auto-infer from parent config item key
if (!this.arrArgs || this.arrArgs.length === 0) {
instanceId = '_default';
const parent = (this as any).parent;
const itemKey = parent?.key || '';
if (!itemKey) {
throw new SchemaError('Could not infer secret name - no parent config item key found', {
tip: 'Either provide a secret name as an argument, or ensure this is used within a config item',
});
}
// Use item key as-is (AWS allows underscores and mixed case)
inferredSecretName = itemKey;
} else if (this.arrArgs.length === 1) {
instanceId = '_default';
secretIdResolver = this.arrArgs[0];
} else if (this.arrArgs.length === 2) {
if (!(this.arrArgs[0].isStatic)) {
throw new SchemaError('Expected instance id to be a static value');
} else {
instanceId = String(this.arrArgs[0].staticValue);
}
secretIdResolver = this.arrArgs[1];
} else {
throw new SchemaError('Expected 0, 1, or 2 args');
}
if (!Object.values(pluginInstances).length) {
throw new SchemaError('No AWS plugin instances found', {
tip: 'Initialize at least one AWS plugin instance using the @initAws root decorator',
});
}
// Make sure instance id is valid
const selectedInstance = pluginInstances[instanceId];
if (!selectedInstance) {
if (instanceId === '_default') {
throw new SchemaError('AWS plugin instance (without id) not found', {
tip: [
'Either remove the `id` param from your @initAws call',
'or use `awsSecret(id, secretId)` to select an instance by id.',
`Possible ids are: ${Object.keys(pluginInstances).join(', ')}`,
].join('\n'),
});
} else {
throw new SchemaError(`AWS plugin instance id "${instanceId}" not found`, {
tip: [`Valid ids are: ${Object.keys(pluginInstances).join(', ')}`].join('\n'),
});
}
}
return {
instanceId, secretIdResolver, inferredSecretName, keyResolver,
};
},
async resolve({
instanceId, secretIdResolver, inferredSecretName, keyResolver,
}) {
const selectedInstance = pluginInstances[instanceId];
let secretIdWithKey: string;
if (inferredSecretName) {
secretIdWithKey = inferredSecretName;
} else if (secretIdResolver) {
const secretId = await secretIdResolver.resolve();
if (typeof secretId !== 'string') {
throw new SchemaError('Expected secret ID to resolve to a string');
}
secretIdWithKey = secretId;
} else {
throw new SchemaError('No secret ID provided or inferred');
}
// Parse the secret ID for JSON key extraction (using # syntax)
let secretId: string;
let jsonKey: string | undefined;
const hashIndex = secretIdWithKey.indexOf('#');
if (hashIndex !== -1) {
secretId = secretIdWithKey.substring(0, hashIndex);
jsonKey = secretIdWithKey.substring(hashIndex + 1);
} else {
secretId = secretIdWithKey;
}
// Named 'key' parameter takes precedence over # syntax
if (keyResolver) {
const keyValue = await keyResolver.resolve();
if (typeof keyValue !== 'string') {
throw new SchemaError('Expected key parameter to resolve to a string');
}
jsonKey = keyValue;
}
// Apply namePrefix
const finalSecretId = selectedInstance.applyNamePrefix(secretId);
// check cache if cacheTtl is configured and cache is available
if (selectedInstance.cacheTtl !== undefined && pluginCache) {
const cacheKey = `awsSecret:${instanceId}:${finalSecretId}`;
const cached = await pluginCache.get(cacheKey);
if (cached !== undefined) {
debug('cache hit for %s', cacheKey);
return cached;
}
const secretValue = await selectedInstance.getSecret(finalSecretId, jsonKey);
await pluginCache.set(cacheKey, secretValue, selectedInstance.cacheTtl);
return secretValue;
}
const secretValue = await selectedInstance.getSecret(finalSecretId, jsonKey);
return secretValue;
},
});
plugin.registerResolverFunction({
name: 'awsParam',
label: 'Fetch parameter from AWS Systems Manager Parameter Store',
icon: AWS_ICON,
argsSchema: {
type: 'mixed',
arrayMinLength: 0,
},
process() {
let instanceId: string;
let parameterNameResolver: Resolver | undefined;
let inferredParamName: string | undefined;
let keyResolver: Resolver | undefined;
// Check for named 'key' parameter
if (this.objArgs?.key) {
keyResolver = this.objArgs.key;
}
// No args - auto-infer from parent config item key
if (!this.arrArgs || this.arrArgs.length === 0) {
instanceId = '_default';
const parent = (this as any).parent;
const itemKey = parent?.key || '';
if (!itemKey) {
throw new SchemaError('Could not infer parameter name - no parent config item key found', {
tip: 'Either provide a parameter name as an argument, or ensure this is used within a config item',
});
}
// Use item key as-is (AWS allows underscores and mixed case)
inferredParamName = itemKey;
} else if (this.arrArgs.length === 1) {
instanceId = '_default';
parameterNameResolver = this.arrArgs[0];
} else if (this.arrArgs.length === 2) {
if (!(this.arrArgs[0].isStatic)) {
throw new SchemaError('Expected instance id to be a static value');
} else {
instanceId = String(this.arrArgs[0].staticValue);
}
parameterNameResolver = this.arrArgs[1];
} else {
throw new SchemaError('Expected 0, 1, or 2 args');
}
if (!Object.values(pluginInstances).length) {
throw new SchemaError('No AWS plugin instances found', {
tip: 'Initialize at least one AWS plugin instance using the @initAws root decorator',
});
}
// Make sure instance id is valid
const selectedInstance = pluginInstances[instanceId];
if (!selectedInstance) {
if (instanceId === '_default') {
throw new SchemaError('AWS plugin instance (without id) not found', {
tip: [
'Either remove the `id` param from your @initAws call',
'or use `awsParam(id, parameterName)` to select an instance by id.',
`Possible ids are: ${Object.keys(pluginInstances).join(', ')}`,
].join('\n'),
});
} else {
throw new SchemaError(`AWS plugin instance id "${instanceId}" not found`, {
tip: [`Valid ids are: ${Object.keys(pluginInstances).join(', ')}`].join('\n'),
});
}
}
return {
instanceId, parameterNameResolver, inferredParamName, keyResolver,
};
},
async resolve({
instanceId, parameterNameResolver, inferredParamName, keyResolver,
}) {
const selectedInstance = pluginInstances[instanceId];
let paramNameWithKey: string;
if (inferredParamName) {
paramNameWithKey = inferredParamName;
} else if (parameterNameResolver) {
const paramName = await parameterNameResolver.resolve();
if (typeof paramName !== 'string') {
throw new SchemaError('Expected parameter name to resolve to a string');
}
paramNameWithKey = paramName;
} else {
throw new SchemaError('No parameter name provided or inferred');
}
// Parse the parameter name for JSON key extraction (using # syntax)
let parameterName: string;
let jsonKey: string | undefined;
const hashIndex = paramNameWithKey.indexOf('#');
if (hashIndex !== -1) {
parameterName = paramNameWithKey.substring(0, hashIndex);
jsonKey = paramNameWithKey.substring(hashIndex + 1);
} else {
parameterName = paramNameWithKey;
}
// Named 'key' parameter takes precedence over # syntax
if (keyResolver) {
const keyValue = await keyResolver.resolve();
if (typeof keyValue !== 'string') {
throw new SchemaError('Expected key parameter to resolve to a string');
}
jsonKey = keyValue;
}
// Apply namePrefix
const finalParameterName = selectedInstance.applyNamePrefix(parameterName);
// check cache if cacheTtl is configured and cache is available
if (selectedInstance.cacheTtl !== undefined && pluginCache) {
const cacheKey = `awsParam:${instanceId}:${finalParameterName}`;
const cached = await pluginCache.get(cacheKey);
if (cached !== undefined) {
debug('cache hit for %s', cacheKey);
return cached;
}
const parameterValue = await selectedInstance.getParameter(finalParameterName, jsonKey);
await pluginCache.set(cacheKey, parameterValue, selectedInstance.cacheTtl);
return parameterValue;
}
const parameterValue = await selectedInstance.getParameter(finalParameterName, jsonKey);
return parameterValue;
},
});