forked from aws/agentcore-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpre-deploy-identity.ts
More file actions
395 lines (347 loc) · 14.5 KB
/
Copy pathpre-deploy-identity.ts
File metadata and controls
395 lines (347 loc) · 14.5 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
import { SecureCredentials, readEnvFile } from '../../../lib';
import type { AgentCoreProjectSpec, Credential } from '../../../schema';
import { getCredentialProvider } from '../../aws';
import { isNoCredentialsError } from '../../errors';
import { getAwsLoginGuidance } from '../../external-requirements/checks';
import { computeDefaultCredentialEnvVarName } from '../../primitives/credential-utils';
import {
apiKeyProviderExists,
createApiKeyProvider,
createOAuth2Provider,
oAuth2ProviderExists,
setTokenVaultKmsKey,
updateApiKeyProvider,
updateOAuth2Provider,
} from '../identity';
import { BedrockAgentCoreControlClient, GetTokenVaultCommand } from '@aws-sdk/client-bedrock-agentcore-control';
import { CreateKeyCommand, KMSClient } from '@aws-sdk/client-kms';
// ─────────────────────────────────────────────────────────────────────────────
// Types
// ─────────────────────────────────────────────────────────────────────────────
export interface ApiKeyProviderSetupResult {
providerName: string;
status: 'created' | 'updated' | 'exists' | 'skipped' | 'error';
credentialProviderArn?: string;
error?: string;
}
export interface PreDeployIdentityResult {
results: ApiKeyProviderSetupResult[];
hasErrors: boolean;
kmsKeyArn?: string;
}
// ─────────────────────────────────────────────────────────────────────────────
// Main Function
// ─────────────────────────────────────────────────────────────────────────────
export interface SetupApiKeyProvidersOptions {
projectSpec: AgentCoreProjectSpec;
configBaseDir: string;
region: string;
/** Runtime credentials that override .env.local values (not persisted to disk) */
runtimeCredentials?: SecureCredentials;
/** Enable KMS encryption for the token vault (creates key if needed) */
enableKmsEncryption?: boolean;
}
/**
* Set up API key credential providers for all credentials in the project.
* Reads API keys from agentcore/.env.local and creates providers in AgentCore Identity.
* Runtime credentials (if provided) take precedence over .env.local values.
*/
export async function setupApiKeyProviders(options: SetupApiKeyProvidersOptions): Promise<PreDeployIdentityResult> {
const { projectSpec, configBaseDir, region, runtimeCredentials, enableKmsEncryption } = options;
const results: ApiKeyProviderSetupResult[] = [];
const credentials = getCredentialProvider();
const envVars = await readEnvFile(configBaseDir);
// Wrap env vars in SecureCredentials and merge with runtime credentials
const envCredentials = SecureCredentials.fromEnvVars(envVars);
const allCredentials = runtimeCredentials ? envCredentials.merge(runtimeCredentials) : envCredentials;
const client = new BedrockAgentCoreControlClient({ region, credentials });
// Configure KMS encryption for token vault if enabled
let kmsKeyArn: string | undefined;
if (enableKmsEncryption) {
const kmsResult = await setupTokenVaultKms(region, credentials, projectSpec);
if (!kmsResult.success) {
return {
results: [
{
providerName: 'TokenVault',
status: 'error',
error: `Failed to configure KMS: ${kmsResult.error}`,
},
],
hasErrors: true,
};
}
kmsKeyArn = kmsResult.keyArn;
}
// Set up each credential in the project
for (const credential of projectSpec.credentials) {
if (credential.authorizerType === 'ApiKeyCredentialProvider') {
const result = await setupApiKeyCredentialProvider(client, credential, allCredentials);
results.push(result);
}
}
return {
results,
hasErrors: results.some(r => r.status === 'error'),
kmsKeyArn,
};
}
async function setupTokenVaultKms(
region: string,
credentials: ReturnType<typeof getCredentialProvider>,
projectSpec: AgentCoreProjectSpec
): Promise<{ success: boolean; keyArn?: string; error?: string }> {
try {
const controlClient = new BedrockAgentCoreControlClient({ region, credentials });
// Check if the token vault already has a customer-managed key
try {
const vaultResponse = await controlClient.send(new GetTokenVaultCommand({}));
if (
vaultResponse.kmsConfiguration?.keyType === 'CustomerManagedKey' &&
vaultResponse.kmsConfiguration.kmsKeyArn
) {
return { success: true, keyArn: vaultResponse.kmsConfiguration.kmsKeyArn };
}
} catch {
// Vault may not exist yet or access denied — fall through to create key
}
// No CMK configured — create a new KMS key and set it on the vault
const kmsClient = new KMSClient({ region, credentials });
const response = await kmsClient.send(
new CreateKeyCommand({
Description: `AgentCore Identity encryption key for ${projectSpec.name}`,
Tags: [{ TagKey: 'agentcore:project', TagValue: projectSpec.name }],
})
);
const keyArn = response.KeyMetadata?.Arn;
if (!keyArn) {
return { success: false, error: 'Failed to create KMS key' };
}
const result = await setTokenVaultKmsKey(controlClient, keyArn);
if (!result.success) {
return { success: false, error: result.error };
}
return { success: true, keyArn };
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
}
async function setupApiKeyCredentialProvider(
client: BedrockAgentCoreControlClient,
credential: Credential,
credentials: SecureCredentials
): Promise<ApiKeyProviderSetupResult> {
const envVarName = computeDefaultCredentialEnvVarName(credential.name);
const apiKey = credentials.get(envVarName);
if (!apiKey) {
return {
providerName: credential.name,
status: 'skipped',
error: `No ${envVarName} found in agentcore/.env.local`,
};
}
try {
const exists = await apiKeyProviderExists(client, credential.name);
if (exists) {
// Always update to ensure provider has current credentials
const updateResult = await updateApiKeyProvider(client, credential.name, apiKey);
return {
providerName: credential.name,
status: updateResult.success ? 'updated' : 'error',
credentialProviderArn: updateResult.credentialProviderArn,
error: updateResult.error,
};
}
const createResult = await createApiKeyProvider(client, credential.name, apiKey);
return {
providerName: credential.name,
status: createResult.success ? 'created' : 'error',
credentialProviderArn: createResult.credentialProviderArn,
error: createResult.error,
};
} catch (error) {
// Provide clearer error message for AWS credentials issues
let errorMessage: string;
if (isNoCredentialsError(error)) {
errorMessage = `AWS credentials not found. ${await getAwsLoginGuidance()}`;
} else {
errorMessage = error instanceof Error ? error.message : String(error);
}
return {
providerName: credential.name,
status: 'error',
error: errorMessage,
};
}
}
/**
* Check if the project has any API key credentials that need setup.
*/
export function hasIdentityApiProviders(projectSpec: AgentCoreProjectSpec): boolean {
return projectSpec.credentials.some(c => c.authorizerType === 'ApiKeyCredentialProvider');
}
export interface MissingCredential {
providerName: string;
envVarName: string;
}
/**
* Get list of credentials that are missing API keys in .env.local.
*/
export async function getMissingCredentials(
projectSpec: AgentCoreProjectSpec,
configBaseDir: string
): Promise<MissingCredential[]> {
const envVars = await readEnvFile(configBaseDir);
const missing: MissingCredential[] = [];
for (const credential of projectSpec.credentials) {
if (credential.authorizerType === 'ApiKeyCredentialProvider') {
const envVarName = computeDefaultCredentialEnvVarName(credential.name);
if (!envVars[envVarName]) {
missing.push({
providerName: credential.name,
envVarName,
});
}
}
}
return missing;
}
/**
* Get list of all credentials in the project that need env vars (for manual entry prompt and runtime credential reading).
*/
export function getAllCredentials(projectSpec: AgentCoreProjectSpec): MissingCredential[] {
const credentials: MissingCredential[] = [];
for (const credential of projectSpec.credentials) {
if (credential.authorizerType === 'ApiKeyCredentialProvider') {
credentials.push({
providerName: credential.name,
envVarName: computeDefaultCredentialEnvVarName(credential.name),
});
} else if (credential.authorizerType === 'OAuthCredentialProvider') {
const nameKey = credential.name.toUpperCase().replace(/-/g, '_');
credentials.push(
{ providerName: credential.name, envVarName: `AGENTCORE_CREDENTIAL_${nameKey}_CLIENT_ID` },
{ providerName: credential.name, envVarName: `AGENTCORE_CREDENTIAL_${nameKey}_CLIENT_SECRET` }
);
}
}
return credentials;
}
// ─────────────────────────────────────────────────────────────────────────────
// OAuth2 Credential Provider Setup
// ─────────────────────────────────────────────────────────────────────────────
export interface OAuth2ProviderSetupResult {
providerName: string;
status: 'created' | 'updated' | 'skipped' | 'error';
error?: string;
credentialProviderArn?: string;
clientSecretArn?: string;
callbackUrl?: string;
}
export interface SetupOAuth2ProvidersOptions {
projectSpec: AgentCoreProjectSpec;
configBaseDir: string;
region: string;
runtimeCredentials?: SecureCredentials;
}
export interface PreDeployOAuth2Result {
results: OAuth2ProviderSetupResult[];
hasErrors: boolean;
}
/**
* Set up OAuth2 credential providers for all OAuth credentials in the project.
* Reads client credentials from agentcore/.env.local and creates providers in AgentCore Identity.
*/
export async function setupOAuth2Providers(options: SetupOAuth2ProvidersOptions): Promise<PreDeployOAuth2Result> {
const { projectSpec, configBaseDir, region, runtimeCredentials } = options;
const results: OAuth2ProviderSetupResult[] = [];
const credentials = getCredentialProvider();
const envVars = await readEnvFile(configBaseDir);
const envCredentials = SecureCredentials.fromEnvVars(envVars);
const allCredentials = runtimeCredentials ? envCredentials.merge(runtimeCredentials) : envCredentials;
const client = new BedrockAgentCoreControlClient({ region, credentials });
for (const credential of projectSpec.credentials) {
if (credential.authorizerType === 'OAuthCredentialProvider') {
const result = await setupSingleOAuth2Provider(client, credential, allCredentials);
results.push(result);
}
}
return {
results,
hasErrors: results.some(r => r.status === 'error'),
};
}
/**
* Check if the project has any OAuth credentials that need setup.
*/
export function hasIdentityOAuthProviders(projectSpec: AgentCoreProjectSpec): boolean {
return projectSpec.credentials.some(c => c.authorizerType === 'OAuthCredentialProvider');
}
async function setupSingleOAuth2Provider(
client: BedrockAgentCoreControlClient,
credential: Credential,
credentials: SecureCredentials
): Promise<OAuth2ProviderSetupResult> {
if (credential.authorizerType !== 'OAuthCredentialProvider') {
return { providerName: credential.name, status: 'error', error: 'Invalid credential type' };
}
const nameKey = credential.name.toUpperCase().replace(/-/g, '_');
const clientIdEnvVar = `AGENTCORE_CREDENTIAL_${nameKey}_CLIENT_ID`;
const clientSecretEnvVar = `AGENTCORE_CREDENTIAL_${nameKey}_CLIENT_SECRET`;
const clientId = credentials.get(clientIdEnvVar);
const clientSecret = credentials.get(clientSecretEnvVar);
if (!clientId || !clientSecret) {
return {
providerName: credential.name,
status: 'skipped',
error: `Missing ${clientIdEnvVar} or ${clientSecretEnvVar} in agentcore/.env.local`,
};
}
// Imported OAuth providers may not have a discoveryUrl (provider already exists in Identity service).
// Skip create/update since we can't build a valid config without it.
if (!credential.discoveryUrl) {
return {
providerName: credential.name,
status: 'skipped',
error: `No discoveryUrl configured for "${credential.name}". Provider already exists in Identity service — credentials in .env.local will be ignored.`,
};
}
const params = {
name: credential.name,
vendor: credential.vendor,
discoveryUrl: credential.discoveryUrl,
clientId,
clientSecret,
};
try {
const exists = await oAuth2ProviderExists(client, credential.name);
if (exists) {
const updateResult = await updateOAuth2Provider(client, params);
return {
providerName: credential.name,
status: updateResult.success ? 'updated' : 'error',
error: updateResult.error,
credentialProviderArn: updateResult.result?.credentialProviderArn,
clientSecretArn: updateResult.result?.clientSecretArn,
callbackUrl: updateResult.result?.callbackUrl,
};
}
const createResult = await createOAuth2Provider(client, params);
return {
providerName: credential.name,
status: createResult.success ? 'created' : 'error',
error: createResult.error,
credentialProviderArn: createResult.result?.credentialProviderArn,
clientSecretArn: createResult.result?.clientSecretArn,
callbackUrl: createResult.result?.callbackUrl,
};
} catch (error) {
let errorMessage: string;
if (isNoCredentialsError(error)) {
errorMessage = 'AWS credentials not found. Run `aws sso login` or set AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY.';
} else {
errorMessage = error instanceof Error ? error.message : String(error);
}
return { providerName: credential.name, status: 'error', error: errorMessage };
}
}