-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathpost-deploy-http-gateways.ts
More file actions
628 lines (568 loc) · 20.7 KB
/
Copy pathpost-deploy-http-gateways.ts
File metadata and controls
628 lines (568 loc) · 20.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
import type { AgentCoreProjectSpec, DeployedResourceState, HttpGatewayDeployedState } from '../../../schema';
import { getCredentialProvider } from '../../aws/account';
import {
createHttpGateway,
createHttpGatewayTarget,
deleteHttpGateway,
deleteHttpGatewayTarget,
getHttpGatewayTarget,
listAllHttpGateways,
listHttpGatewayTargets,
waitForGatewayReady,
waitForTargetReady,
} from '../../aws/agentcore-http-gateways';
import {
CreateRoleCommand,
DeleteRoleCommand,
DeleteRolePolicyCommand,
GetRoleCommand,
IAMClient,
PutRolePolicyCommand,
} from '@aws-sdk/client-iam';
import { createHash } from 'node:crypto';
// ============================================================================
// Types
// ============================================================================
export interface SetupHttpGatewaysOptions {
region: string;
projectName: string;
projectSpec: AgentCoreProjectSpec;
existingHttpGateways?: Record<string, HttpGatewayDeployedState>;
deployedResources?: DeployedResourceState;
}
export interface HttpGatewaySetupResult {
gatewayName: string;
status: 'created' | 'skipped' | 'deleted' | 'error';
gatewayId?: string;
gatewayArn?: string;
error?: string;
}
export interface SetupHttpGatewaysResult {
results: HttpGatewaySetupResult[];
httpGateways: Record<string, HttpGatewayDeployedState>;
hasErrors: boolean;
}
// ============================================================================
// Constants
// ============================================================================
const HTTP_GATEWAY_ROLE_POLICY_NAME = 'HttpGatewayExecutionPolicy';
// ============================================================================
// Implementation
// ============================================================================
/**
* Create or delete HTTP gateways post-deploy.
*
* Pattern:
* 1. For each httpGateway in project spec -> resolve runtime ARN, create or skip
* 2. For each httpGateway in deployed-state but NOT in project spec -> delete (reconciliation)
* 3. Return updated deployed state entries
*/
export async function setupHttpGateways(options: SetupHttpGatewaysOptions): Promise<SetupHttpGatewaysResult> {
const { region, projectName, projectSpec, existingHttpGateways, deployedResources } = options;
const results: HttpGatewaySetupResult[] = [];
const httpGateways: Record<string, HttpGatewayDeployedState> = {};
// Defensive: Zod .default([]) only fires on undefined, not null.
// If someone has "httpGateways": null in their JSON, it passes through as null.
const httpGatewaySpecs = projectSpec.httpGateways ?? [];
// Create or skip gateways from the spec
for (const gwSpec of httpGatewaySpecs) {
let resolvedRoleArn: string | undefined;
let roleCreatedByCli = false;
try {
const existingGateway = existingHttpGateways?.[gwSpec.name];
if (existingGateway) {
// Already deployed
// Create or update targets from httpGateways[].targets (for target-based AB testing)
if (gwSpec.targets && gwSpec.targets.length > 0) {
// List existing targets to avoid unnecessary create calls
const existingTargetsByName = new Map<string, { targetId: string }>();
try {
const existingTargets = await listHttpGatewayTargets({
region,
gatewayId: existingGateway.gatewayId,
});
for (const t of existingTargets.targets) {
existingTargetsByName.set(t.name, { targetId: t.targetId });
}
} catch {
// If list fails, fall through and let create handle 409s
}
for (const tgt of gwSpec.targets) {
const existingTarget = existingTargetsByName.get(tgt.name);
if (existingTarget) {
// Target exists by name — check if qualifier matches
try {
const targetDetails = await getHttpGatewayTarget({
region,
gatewayId: existingGateway.gatewayId,
targetId: existingTarget.targetId,
});
const httpConfig = (
targetDetails.targetConfiguration as
| {
http?: {
agentcoreRuntime?: { qualifier?: string };
runtimeTargetConfiguration?: { qualifier?: string };
};
}
| undefined
)?.http;
const existingQualifier =
httpConfig?.agentcoreRuntime?.qualifier ?? httpConfig?.runtimeTargetConfiguration?.qualifier;
const specQualifier = tgt.qualifier ?? 'DEFAULT';
if (existingQualifier === specQualifier) {
// Qualifier matches — skip
continue;
}
// Qualifier differs — delete old target and recreate
await deleteHttpGatewayTarget({
region,
gatewayId: existingGateway.gatewayId,
targetId: existingTarget.targetId,
});
} catch {
// If get/delete fails, fall through to create which will handle conflicts
}
}
try {
const tgtRuntime = deployedResources?.runtimes?.[tgt.runtimeRef];
if (!tgtRuntime) continue;
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: existingGateway.gatewayId,
targetName: tgt.name,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
await waitForTargetReady({
region,
gatewayId: existingGateway.gatewayId,
targetId: tgtResult.targetId,
});
} catch (tgtErr) {
if (tgtErr instanceof Error && tgtErr.message.includes('409')) continue;
// Non-fatal
}
}
}
httpGateways[gwSpec.name] = existingGateway;
results.push({
gatewayName: gwSpec.name,
status: 'skipped',
gatewayId: existingGateway.gatewayId,
gatewayArn: existingGateway.gatewayArn,
});
continue;
}
// Try to find by name via list (handles re-creation after state loss)
const existingByName = await findHttpGatewayByName(region, gwSpec.name);
if (existingByName) {
console.warn(
`Warning: HTTP gateway "${gwSpec.name}" found by name but local state was lost. Target and role state may be incomplete — consider re-deploying.`
);
httpGateways[gwSpec.name] = {
gatewayId: existingByName.gatewayId,
gatewayArn: existingByName.gatewayArn,
// targetId, roleArn, roleCreatedByCli unknown after state-loss recovery
};
results.push({
gatewayName: gwSpec.name,
status: 'skipped',
gatewayId: existingByName.gatewayId,
gatewayArn: existingByName.gatewayArn,
});
continue;
}
// Resolve runtime ARN from deployed state
const runtimeState = deployedResources?.runtimes?.[gwSpec.runtimeRef];
if (!runtimeState) {
results.push({
gatewayName: gwSpec.name,
status: 'error',
error: `Runtime "${gwSpec.runtimeRef}" not found in deployed resources. Deploy the runtime before creating an HTTP gateway.`,
});
continue;
}
const runtimeArn = runtimeState.runtimeArn;
if (gwSpec.roleArn) {
resolvedRoleArn = gwSpec.roleArn;
} else {
resolvedRoleArn = await getOrCreateHttpGatewayRole({
region,
projectName,
gatewayName: gwSpec.name,
runtimeArn,
});
roleCreatedByCli = true;
}
// Create gateway and wait for it to become READY before adding targets
// Creating HTTP gateway for runtime
const createResult = await createHttpGateway({
region,
name: gwSpec.name,
roleArn: resolvedRoleArn,
});
const readyGateway = await waitForGatewayReady({
region,
gatewayId: createResult.gatewayId,
});
// Create target pointing to the runtime
let targetId: string | undefined;
try {
const targetResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: gwSpec.runtimeRef,
runtimeArn,
});
targetId = targetResult.targetId;
// Wait for target to become ready
// Waiting for gateway target to become ready
await waitForTargetReady({
region,
gatewayId: createResult.gatewayId,
targetId: targetResult.targetId,
});
} catch (targetErr) {
// Rollback: delete target (if created), wait for deletion, then delete gateway
try {
if (targetId) {
await deleteHttpGatewayTarget({ region, gatewayId: createResult.gatewayId, targetId });
}
} catch {
// Best-effort target cleanup
}
try {
await deleteHttpGateway({ region, gatewayId: createResult.gatewayId });
} catch {
// Best-effort gateway rollback
}
// Always clean up auto-created role on target failure, regardless of gateway rollback result
if (roleCreatedByCli && resolvedRoleArn) {
try {
await deleteHttpGatewayRole(region, resolvedRoleArn);
} catch {
// Best-effort role cleanup
}
}
results.push({
gatewayName: gwSpec.name,
status: 'error',
error: `Target creation failed, gateway rolled back: ${targetErr instanceof Error ? targetErr.message : String(targetErr)}`,
});
continue;
}
// Create additional targets from httpGateways[].targets (for target-based AB testing)
if (gwSpec.targets && gwSpec.targets.length > 0) {
for (const tgt of gwSpec.targets) {
try {
const tgtRuntime = deployedResources?.runtimes?.[tgt.runtimeRef];
if (!tgtRuntime) {
// Runtime not deployed, skip this target
continue;
}
const tgtResult = await createHttpGatewayTarget({
region,
gatewayId: createResult.gatewayId,
targetName: tgt.name,
runtimeArn: tgtRuntime.runtimeArn,
qualifier: tgt.qualifier,
});
await waitForTargetReady({
region,
gatewayId: createResult.gatewayId,
targetId: tgtResult.targetId,
});
} catch (tgtErr) {
// 409 = already exists, skip
if (tgtErr instanceof Error && tgtErr.message.includes('409')) continue;
// Non-fatal: log but continue
}
}
}
httpGateways[gwSpec.name] = {
gatewayId: createResult.gatewayId,
gatewayArn: createResult.gatewayArn,
gatewayUrl: readyGateway.gatewayUrl,
targetId,
roleArn: resolvedRoleArn,
roleCreatedByCli,
};
results.push({
gatewayName: gwSpec.name,
status: 'created',
gatewayId: createResult.gatewayId,
gatewayArn: createResult.gatewayArn,
});
} catch (err) {
// If we auto-created a role, clean it up on failure
if (roleCreatedByCli && resolvedRoleArn) {
try {
await deleteHttpGatewayRole(region, resolvedRoleArn);
} catch {
// Best-effort role cleanup
}
}
results.push({
gatewayName: gwSpec.name,
status: 'error',
error: err instanceof Error ? err.message : String(err),
});
}
}
// Orphaned gateways are deleted by deleteOrphanedHttpGateways() which runs
// as a separate pre-pass. No deletion loop here.
return {
results,
httpGateways,
hasErrors: results.some(r => r.status === 'error'),
};
}
// ============================================================================
// Shared Gateway Deletion
// ============================================================================
/**
* Delete an HTTP gateway and all its targets. Best-effort — target failures
* are warned but don't prevent gateway deletion attempt.
*
* Order: targets → gateway → role
*/
export async function deleteHttpGatewayWithTargets(options: {
region: string;
gatewayId: string;
gatewayName: string;
knownTargetId?: string;
roleArn?: string;
roleCreatedByCli?: boolean;
}): Promise<{ success: boolean; error?: string }> {
const { region, gatewayId, gatewayName, knownTargetId, roleArn, roleCreatedByCli } = options;
const targetIds: string[] = [];
if (knownTargetId) {
targetIds.push(knownTargetId);
}
try {
const targets = await listHttpGatewayTargets({ region, gatewayId, maxResults: 100 });
for (const t of targets.targets) {
if (!targetIds.includes(t.targetId)) {
targetIds.push(t.targetId);
}
}
} catch {
// Best-effort — proceed with whatever IDs we have
}
for (const targetId of targetIds) {
try {
await deleteHttpGatewayTarget({ region, gatewayId, targetId });
} catch (err) {
console.warn(
`Warning: Failed to delete target ${targetId} on gateway "${gatewayName}": ${err instanceof Error ? err.message : String(err)}`
);
}
}
const deleteResult = await deleteHttpGateway({ region, gatewayId });
if (!deleteResult.success) {
return { success: false, error: deleteResult.error };
}
if (roleCreatedByCli && roleArn) {
try {
await deleteHttpGatewayRole(region, roleArn);
} catch {
// Best-effort role cleanup
}
}
return { success: true };
}
/**
* Delete orphaned HTTP gateways (in deployed-state but removed from spec).
* Call before setupHttpGateways.
*/
export async function deleteOrphanedHttpGateways(options: {
region: string;
projectSpec: AgentCoreProjectSpec;
existingHttpGateways?: Record<string, HttpGatewayDeployedState>;
}): Promise<{ results: HttpGatewaySetupResult[]; hasErrors: boolean }> {
const { region, projectSpec, existingHttpGateways } = options;
if (!existingHttpGateways) return { results: [], hasErrors: false };
const specGatewayNames = new Set((projectSpec.httpGateways ?? []).map(g => g.name));
const results: HttpGatewaySetupResult[] = [];
for (const [gwName, gwState] of Object.entries(existingHttpGateways)) {
if (!specGatewayNames.has(gwName)) {
try {
const result = await deleteHttpGatewayWithTargets({
region,
gatewayId: gwState.gatewayId,
gatewayName: gwName,
knownTargetId: gwState.targetId,
roleArn: gwState.roleArn,
roleCreatedByCli: gwState.roleCreatedByCli,
});
results.push({
gatewayName: gwName,
status: result.success ? 'deleted' : 'error',
error: result.error,
});
} catch (err) {
results.push({
gatewayName: gwName,
status: 'error',
error: err instanceof Error ? err.message : String(err),
});
}
}
}
return {
results,
hasErrors: results.some(r => r.status === 'error'),
};
}
// ============================================================================
// Gateway Trace Delivery
// ============================================================================
// ============================================================================
// Helpers
// ============================================================================
async function findHttpGatewayByName(
region: string,
name: string
): Promise<{ gatewayId: string; gatewayArn: string } | undefined> {
try {
const gateways = await listAllHttpGateways({ region });
return gateways.find(gw => gw.name === name);
} catch (err) {
console.warn(
`Warning: Could not list HTTP gateways to check for existing "${name}": ${err instanceof Error ? err.message : String(err)}`
);
return undefined;
}
}
// ============================================================================
// IAM Role Management
// ============================================================================
/**
* Generate a project-scoped role name following the CDK pattern:
* AgentCore-{ProjectName}-HttpGw{GatewayName}-{Hash}
*/
function generateRoleName(projectName: string, gatewayName: string): string {
const base = `AgentCore-${projectName}-HttpGw${gatewayName}`;
// Use deterministic hash so retries produce the same role name
const hash = createHash('sha256').update(`${projectName}:${gatewayName}`).digest('hex').slice(0, 8);
// IAM role names max 64 chars
return `${base.slice(0, 55)}-${hash}`;
}
/**
* Extract role name from ARN: arn:aws:iam::123456789012:role/RoleName -> RoleName
*/
function roleNameFromArn(roleArn: string): string {
const parts = roleArn.split('/');
return parts[parts.length - 1] ?? roleArn;
}
interface CreateHttpGatewayRoleOptions {
region: string;
projectName: string;
gatewayName: string;
runtimeArn: string;
}
async function getOrCreateHttpGatewayRole(options: CreateHttpGatewayRoleOptions): Promise<string> {
const { region, projectName, gatewayName } = options;
const credentials = getCredentialProvider();
const iamClient = new IAMClient({ region, credentials });
const roleName = generateRoleName(projectName, gatewayName);
const trustPolicy = JSON.stringify({
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: { Service: 'bedrock-agentcore.amazonaws.com' },
Action: 'sts:AssumeRole',
},
],
});
const policy = JSON.stringify({
Version: '2012-10-17',
Statement: [
{
Sid: 'InvokeRuntimeStatement',
Effect: 'Allow',
Action: [
'bedrock-agentcore:InvokeRuntime',
'bedrock-agentcore:InvokeAgent',
'bedrock-agentcore:InvokeAgentRuntime',
],
// Resource must be '*' because the gateway service invokes runtimes using
// a resource identifier that doesn't match the deployed runtime ARN format.
// This matches the A/B testing guide's gateway role policy.
Resource: '*',
},
],
});
let roleArn: string;
let needsPropagationWait = false;
try {
const createResult = await iamClient.send(
new CreateRoleCommand({
RoleName: roleName,
AssumeRolePolicyDocument: trustPolicy,
Description: `Auto-created execution role for AgentCore HTTP gateway: ${gatewayName}`,
Tags: [
{ Key: 'agentcore:created-by', Value: 'agentcore-cli' },
{ Key: 'agentcore:project-name', Value: projectName },
{ Key: 'agentcore:http-gateway-name', Value: gatewayName },
],
})
);
roleArn = createResult.Role?.Arn ?? '';
if (!roleArn) {
throw new Error(`IAM CreateRole succeeded but returned no role ARN for "${roleName}"`);
}
needsPropagationWait = true;
} catch (err: unknown) {
// Handle retry after a previous failed deploy left the role behind
const errName = (err as { name?: string }).name;
if (errName === 'EntityAlreadyExistsException') {
// IAM role already exists — reusing
const existing = await iamClient.send(new GetRoleCommand({ RoleName: roleName }));
roleArn = existing.Role?.Arn ?? '';
if (!roleArn) {
throw new Error(`Role "${roleName}" already exists but ARN could not be retrieved`);
}
} else {
throw new Error(
`Failed to create IAM role "${roleName}" for HTTP gateway "${gatewayName}": ${err instanceof Error ? err.message : String(err)}`
);
}
}
// Re-apply the inline policy (idempotent — covers both new and recovered roles)
await iamClient.send(
new PutRolePolicyCommand({
RoleName: roleName,
PolicyName: HTTP_GATEWAY_ROLE_POLICY_NAME,
PolicyDocument: policy,
})
);
if (needsPropagationWait) {
// Waiting for IAM role propagation (~15s)
await new Promise(resolve => setTimeout(resolve, 15_000));
}
return roleArn;
}
export async function deleteHttpGatewayRole(region: string, roleArn: string): Promise<void> {
const credentials = getCredentialProvider();
const iamClient = new IAMClient({ region, credentials });
const roleName = roleNameFromArn(roleArn);
try {
// Must delete inline policies before deleting the role
await iamClient.send(
new DeleteRolePolicyCommand({
RoleName: roleName,
PolicyName: HTTP_GATEWAY_ROLE_POLICY_NAME,
})
);
} catch {
// Policy may not exist
}
try {
await iamClient.send(new DeleteRoleCommand({ RoleName: roleName }));
} catch {
// Role may already be deleted or in use -- best effort
}
}