forked from aws/agentcore-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPolicyEnginePrimitive.ts
More file actions
362 lines (328 loc) · 12.6 KB
/
Copy pathPolicyEnginePrimitive.ts
File metadata and controls
362 lines (328 loc) · 12.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
import { findConfigRoot } from '../../lib';
import type { AgentCoreProjectSpec, PolicyEngine } from '../../schema';
import { PolicyEngineModeSchema, PolicyEngineSchema } from '../../schema';
import { getErrorMessage } from '../errors';
import type { RemovalPreview, RemovalResult, SchemaChange } from '../operations/remove/types';
import { BasePrimitive } from './BasePrimitive';
import { SOURCE_CODE_NOTE } from './constants';
import type { AddResult, AddScreenComponent, RemovableResource } from './types';
import type { Command } from '@commander-js/extra-typings';
export interface AddPolicyEngineOptions {
name: string;
description?: string;
encryptionKeyArn?: string;
}
export class PolicyEnginePrimitive extends BasePrimitive<AddPolicyEngineOptions, RemovableResource> {
readonly kind = 'policy-engine' as const;
readonly label = 'Policy Engine';
readonly primitiveSchema = PolicyEngineSchema;
async add(options: AddPolicyEngineOptions): Promise<AddResult<{ engineName: string }>> {
try {
const project = await this.readProjectSpec();
this.checkDuplicate(project.policyEngines, options.name);
const engine: PolicyEngine = {
name: options.name,
...(options.description && { description: options.description }),
...(options.encryptionKeyArn && { encryptionKeyArn: options.encryptionKeyArn }),
policies: [],
};
project.policyEngines.push(engine);
await this.writeProjectSpec(project);
return { success: true, engineName: engine.name };
} catch (err) {
return { success: false, error: getErrorMessage(err) };
}
}
async remove(engineName: string): Promise<RemovalResult> {
try {
const project = await this.readProjectSpec();
const index = project.policyEngines.findIndex(e => e.name === engineName);
if (index === -1) {
return { success: false, error: `Policy engine "${engineName}" not found.` };
}
project.policyEngines.splice(index, 1);
await this.writeProjectSpec(project);
// Clean up any gateway references to this engine in agentcore.json
let changed = false;
for (const gw of project.agentCoreGateways) {
if (gw.policyEngineConfiguration?.policyEngineName === engineName) {
delete gw.policyEngineConfiguration;
changed = true;
}
}
if (changed) {
await this.writeProjectSpec(project);
}
return { success: true };
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown error';
return { success: false, error: message };
}
}
async previewRemove(engineName: string): Promise<RemovalPreview> {
const project = await this.readProjectSpec();
const engine = project.policyEngines.find(e => e.name === engineName);
if (!engine) {
throw new Error(`Policy engine "${engineName}" not found.`);
}
const summary: string[] = [`Removing policy engine: ${engineName}`];
if (engine.policies.length > 0) {
summary.push(`Note: ${engine.policies.length} policy(ies) within this engine will also be removed`);
}
const schemaChanges: SchemaChange[] = [];
const afterSpec: AgentCoreProjectSpec = {
...project,
policyEngines: project.policyEngines.filter(e => e.name !== engineName),
};
schemaChanges.push({
file: 'agentcore/agentcore.json',
before: project,
after: afterSpec,
});
// Show changes if any gateways reference this engine
const affectedGateways = project.agentCoreGateways.filter(
gw => gw.policyEngineConfiguration?.policyEngineName === engineName
);
if (affectedGateways.length > 0) {
summary.push(
`Note: ${affectedGateways.length} gateway(s) referencing this engine will have policyEngineConfiguration removed`
);
summary.push(
'Warning: this may grant agents escalated permissions to invoke gateway tools that were previously restricted'
);
}
return { summary, directoriesToDelete: [], schemaChanges };
}
async getRemovable(): Promise<RemovableResource[]> {
try {
const project = await this.readProjectSpec();
return project.policyEngines.map(e => ({ name: e.name }));
} catch {
return [];
}
}
async getExistingEngines(): Promise<string[]> {
try {
const project = await this.readProjectSpec();
return project.policyEngines.map(e => e.name);
} catch {
return [];
}
}
/**
* Get gateway names that don't have a policy engine attached.
*/
async getUnprotectedGateways(): Promise<string[]> {
try {
const project = await this.readProjectSpec();
return project.agentCoreGateways.filter(gw => !gw.policyEngineConfiguration).map(gw => gw.name);
} catch {
return [];
}
}
/**
* Attach a policy engine to the specified gateways in agentcore.json.
*/
async attachToGateways(engineName: string, gatewayNames: string[], mode: 'LOG_ONLY' | 'ENFORCE'): Promise<void> {
if (gatewayNames.length === 0) return;
const project = await this.readProjectSpec();
const nameSet = new Set(gatewayNames);
for (const gw of project.agentCoreGateways) {
if (nameSet.has(gw.name)) {
gw.policyEngineConfiguration = { policyEngineName: engineName, mode };
}
}
await this.writeProjectSpec(project);
}
async getDeployedEngineId(engineName: string): Promise<string | null> {
try {
const deployedState = await this.configIO.readDeployedState();
for (const target of Object.values(deployedState.targets)) {
const engineState = target.resources?.policyEngines?.[engineName];
if (engineState) {
return engineState.policyEngineId;
}
}
return null;
} catch {
return null;
}
}
async getDeployedGatewayArn(): Promise<string | null> {
const gateways = await this.getDeployedGateways();
const firstArn = Object.values(gateways)[0];
return firstArn ?? null;
}
async getDeployedGateways(): Promise<Record<string, string>> {
try {
const deployedState = await this.configIO.readDeployedState();
const result: Record<string, string> = {};
for (const target of Object.values(deployedState.targets)) {
const gateways = target.resources?.mcp?.gateways;
if (gateways) {
for (const [name, gw] of Object.entries(gateways)) {
if (gw?.gatewayArn) {
result[name] = gw.gatewayArn;
}
}
}
}
return result;
} catch {
return {};
}
}
registerCommands(addCmd: Command, removeCmd: Command): void {
addCmd
.command('policy-engine')
.description('Add a policy engine to the project')
.option('--name <name>', 'Policy engine name [non-interactive]')
.option('--description <desc>', 'Policy engine description [non-interactive]')
.option('--encryption-key-arn <arn>', 'KMS encryption key ARN [non-interactive]')
.option(
'--attach-to-gateways <gateways>',
'Comma-separated gateway names to attach this engine to [non-interactive]'
)
.option('--attach-mode <mode>', 'Enforcement mode for attached gateways: LOG_ONLY or ENFORCE [non-interactive]')
.option('--json', 'Output as JSON [non-interactive]')
.action(
async (cliOptions: {
name?: string;
description?: string;
encryptionKeyArn?: string;
attachToGateways?: string;
attachMode?: string;
json?: boolean;
}) => {
try {
if (!findConfigRoot()) {
console.error('No agentcore project found. Run `agentcore create` first.');
process.exit(1);
}
if (cliOptions.name || cliOptions.description || cliOptions.encryptionKeyArn || cliOptions.json) {
if (!cliOptions.name) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error: '--name is required' }));
} else {
console.error('--name is required');
}
process.exit(1);
}
const result = await this.add({
name: cliOptions.name,
description: cliOptions.description,
encryptionKeyArn: cliOptions.encryptionKeyArn,
});
// Attach to gateways if requested
if (result.success && cliOptions.attachToGateways) {
const mode = PolicyEngineModeSchema.parse(cliOptions.attachMode ?? 'LOG_ONLY');
const gateways = cliOptions.attachToGateways
.split(',')
.map(s => s.trim())
.filter(Boolean);
await this.attachToGateways(cliOptions.name, gateways, mode);
}
if (cliOptions.json) {
console.log(JSON.stringify(result));
} else if (result.success) {
console.log(`Added policy engine '${result.engineName}'`);
} else {
console.error(result.error);
}
process.exit(result.success ? 0 : 1);
} else {
const [{ render }, { default: React }, { AddFlow }] = await Promise.all([
import('ink'),
import('react'),
import('../tui/screens/add/AddFlow'),
]);
const { clear, unmount } = render(
React.createElement(AddFlow, {
isInteractive: false,
onExit: () => {
clear();
unmount();
process.exit(0);
},
})
);
}
} catch (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error: getErrorMessage(error) }));
} else {
console.error(`Error: ${getErrorMessage(error)}`);
}
process.exit(1);
}
}
);
removeCmd
.command('policy-engine')
.description('Remove a policy engine from the project')
.option('--name <name>', 'Name of resource to remove [non-interactive]')
.option('-y, --yes', 'Skip confirmation prompt [non-interactive]')
.option('--json', 'Output as JSON [non-interactive]')
.action(async (cliOptions: { name?: string; yes?: boolean; json?: boolean }) => {
try {
if (!findConfigRoot()) {
console.error('No agentcore project found. Run `agentcore create` first.');
process.exit(1);
}
if (cliOptions.name || cliOptions.yes || cliOptions.json) {
if (!cliOptions.name) {
console.log(JSON.stringify({ success: false, error: '--name is required' }));
process.exit(1);
}
const result = await this.remove(cliOptions.name);
if (cliOptions.json) {
console.log(
JSON.stringify({
success: result.success,
resourceType: this.kind,
resourceName: cliOptions.name,
message: result.success ? `Removed policy engine '${cliOptions.name}'` : undefined,
note: result.success ? SOURCE_CODE_NOTE : undefined,
error: !result.success ? result.error : undefined,
})
);
} else if (result.success) {
console.log(`Removed policy engine '${cliOptions.name}'`);
} else {
console.error(result.error);
}
process.exit(result.success ? 0 : 1);
} else {
const [{ render }, { default: React }, { RemoveFlow }] = await Promise.all([
import('ink'),
import('react'),
import('../tui/screens/remove'),
]);
const { clear, unmount } = render(
React.createElement(RemoveFlow, {
isInteractive: false,
force: cliOptions.yes,
initialResourceType: this.kind,
initialResourceName: cliOptions.name,
onExit: () => {
clear();
unmount();
process.exit(0);
},
})
);
}
} catch (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error: getErrorMessage(error) }));
} else {
console.error(`Error: ${getErrorMessage(error)}`);
}
process.exit(1);
}
});
}
addScreen(): AddScreenComponent {
return null;
}
}