-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathvalidate.ts
More file actions
515 lines (446 loc) · 17.7 KB
/
validate.ts
File metadata and controls
515 lines (446 loc) · 17.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
import { ConfigIO } from '../../../lib';
import {
AgentNameSchema,
BuildTypeSchema,
GatewayNameSchema,
ModelProviderSchema,
SDKFrameworkSchema,
TargetLanguageSchema,
getSupportedModelProviders,
matchEnumValue,
} from '../../../schema';
import type {
AddAgentOptions,
AddGatewayOptions,
AddGatewayTargetOptions,
AddIdentityOptions,
AddMemoryOptions,
} from './types';
import { existsSync } from 'fs';
import { extname, resolve } from 'path';
export interface ValidationResult {
valid: boolean;
error?: string;
}
// Constants
const MEMORY_OPTIONS = ['none', 'shortTerm', 'longAndShortTerm'] as const;
const OIDC_WELL_KNOWN_SUFFIX = '/.well-known/openid-configuration';
const VALID_STRATEGIES = ['SEMANTIC', 'SUMMARIZATION', 'USER_PREFERENCE'];
const VALID_STREAM_CONTENT_LEVELS = ['FULL_CONTENT', 'METADATA_ONLY'];
const VALID_DELIVERY_TYPES = ['kinesis'];
/**
* Validate that a credential name exists in the project spec.
*/
async function validateCredentialExists(credentialName: string): Promise<ValidationResult> {
try {
const configIO = new ConfigIO();
const project = await configIO.readProjectSpec();
const credentialExists = project.credentials.some(c => c.name === credentialName);
if (!credentialExists) {
const availableCredentials = project.credentials.map(c => c.name);
if (availableCredentials.length === 0) {
return {
valid: false,
error: `Credential "${credentialName}" not found. No credentials are configured. Add credentials using 'agentcore add identity'.`,
};
}
return {
valid: false,
error: `Credential "${credentialName}" not found. Available credentials: ${availableCredentials.join(', ')}`,
};
}
return { valid: true };
} catch {
return { valid: false, error: 'Failed to read project configuration' };
}
}
// Agent validation
export function validateAddAgentOptions(options: AddAgentOptions): ValidationResult {
// Normalize enum flag values (case-insensitive matching)
if (options.framework)
options.framework =
(matchEnumValue(SDKFrameworkSchema, options.framework) as typeof options.framework) ?? options.framework;
if (options.modelProvider)
options.modelProvider =
(matchEnumValue(ModelProviderSchema, options.modelProvider) as typeof options.modelProvider) ??
options.modelProvider;
if (options.language)
options.language =
(matchEnumValue(TargetLanguageSchema, options.language) as typeof options.language) ?? options.language;
if (options.build) options.build = matchEnumValue(BuildTypeSchema, options.build) ?? options.build;
if (!options.name) {
return { valid: false, error: '--name is required' };
}
const nameResult = AgentNameSchema.safeParse(options.name);
if (!nameResult.success) {
return { valid: false, error: nameResult.error.issues[0]?.message ?? 'Invalid agent name' };
}
// Validate build type if provided
if (options.build) {
const buildResult = BuildTypeSchema.safeParse(options.build);
if (!buildResult.success) {
return { valid: false, error: `Invalid build type: ${options.build}. Use CodeZip or Container` };
}
}
if (!options.framework) {
return { valid: false, error: '--framework is required' };
}
const fwResult = SDKFrameworkSchema.safeParse(options.framework);
if (!fwResult.success) {
return { valid: false, error: `Invalid framework: ${options.framework}` };
}
if (!options.modelProvider) {
return { valid: false, error: '--model-provider is required' };
}
const mpResult = ModelProviderSchema.safeParse(options.modelProvider);
if (!mpResult.success) {
return { valid: false, error: `Invalid model provider: ${options.modelProvider}` };
}
const supportedProviders = getSupportedModelProviders(options.framework);
if (!supportedProviders.includes(options.modelProvider)) {
return { valid: false, error: `${options.framework} does not support ${options.modelProvider}` };
}
if (!options.language) {
return { valid: false, error: '--language is required' };
}
const langResult = TargetLanguageSchema.safeParse(options.language);
if (!langResult.success) {
return { valid: false, error: `Invalid language: ${options.language}` };
}
const isByoPath = options.type === 'byo';
if (isByoPath) {
if (!options.codeLocation) {
return { valid: false, error: '--code-location is required for BYO path' };
}
} else {
if (options.language === 'TypeScript') {
return { valid: false, error: 'Create path only supports Python (TypeScript templates not yet available)' };
}
if (options.language === 'Other') {
return { valid: false, error: 'Create path only supports Python' };
}
if (!options.memory) {
return { valid: false, error: '--memory is required for create path' };
}
if (!MEMORY_OPTIONS.includes(options.memory as (typeof MEMORY_OPTIONS)[number])) {
return {
valid: false,
error: `Invalid memory option: ${options.memory}. Use none, shortTerm, or longAndShortTerm`,
};
}
}
return { valid: true };
}
// Gateway validation
export function validateAddGatewayOptions(options: AddGatewayOptions): ValidationResult {
if (!options.name) {
return { valid: false, error: '--name is required' };
}
const nameResult = GatewayNameSchema.safeParse(options.name);
if (!nameResult.success) {
return { valid: false, error: nameResult.error.issues[0]?.message ?? 'Invalid gateway name' };
}
if (options.authorizerType && !['NONE', 'CUSTOM_JWT'].includes(options.authorizerType)) {
return { valid: false, error: 'Invalid authorizer type. Use NONE or CUSTOM_JWT' };
}
if (options.authorizerType === 'CUSTOM_JWT') {
if (!options.discoveryUrl) {
return { valid: false, error: '--discovery-url is required for CUSTOM_JWT authorizer' };
}
try {
new URL(options.discoveryUrl);
} catch {
return { valid: false, error: 'Discovery URL must be a valid URL' };
}
if (!options.discoveryUrl.endsWith(OIDC_WELL_KNOWN_SUFFIX)) {
return { valid: false, error: `Discovery URL must end with ${OIDC_WELL_KNOWN_SUFFIX}` };
}
// allowedAudience is optional - empty means no audience validation
if (!options.allowedClients) {
return { valid: false, error: '--allowed-clients is required for CUSTOM_JWT authorizer' };
}
const clients = options.allowedClients
.split(',')
.map(s => s.trim())
.filter(Boolean);
if (clients.length === 0) {
return { valid: false, error: 'At least one client value is required' };
}
}
// Validate agent OAuth credentials
if (options.agentClientId && !options.agentClientSecret) {
return { valid: false, error: 'Both --agent-client-id and --agent-client-secret must be provided together' };
}
if (options.agentClientSecret && !options.agentClientId) {
return { valid: false, error: 'Both --agent-client-id and --agent-client-secret must be provided together' };
}
if (options.agentClientId && options.authorizerType !== 'CUSTOM_JWT') {
return { valid: false, error: 'Agent OAuth credentials are only valid with CUSTOM_JWT authorizer' };
}
return { valid: true };
}
// Gateway Target validation
export async function validateAddGatewayTargetOptions(options: AddGatewayTargetOptions): Promise<ValidationResult> {
// Normalize enum flag values (case-insensitive matching)
if (options.language)
options.language =
(matchEnumValue(TargetLanguageSchema, options.language) as typeof options.language) ?? options.language;
if (!options.name) {
return { valid: false, error: '--name is required' };
}
if (!options.type) {
return {
valid: false,
error: '--type is required. Valid options: mcp-server, api-gateway, open-api-schema, smithy-model',
};
}
const typeMap: Record<string, string> = {
'mcp-server': 'mcpServer',
'api-gateway': 'apiGateway',
'open-api-schema': 'openApiSchema',
'smithy-model': 'smithyModel',
};
const mappedType = typeMap[options.type];
if (!mappedType) {
return {
valid: false,
error: `Invalid type: ${options.type}. Valid options: mcp-server, api-gateway, open-api-schema, smithy-model`,
};
}
options.type = mappedType;
// Gateway is required — a gateway target must be attached to a gateway
if (!options.gateway) {
return {
valid: false,
error:
"--gateway is required. A gateway target must be attached to a gateway. Create a gateway first with 'agentcore add gateway'.",
};
}
// Validate the specified gateway exists
const gatewayConfigIO = new ConfigIO();
let existingGateways: string[] = [];
try {
if (gatewayConfigIO.configExists('mcp')) {
const mcpSpec = await gatewayConfigIO.readMcpSpec();
existingGateways = mcpSpec.agentCoreGateways.map(g => g.name);
}
} catch {
// If we can't read the config, treat as no gateways
}
if (existingGateways.length === 0) {
return {
valid: false,
error: "No gateways found. Create a gateway first with 'agentcore add gateway' before adding a gateway target.",
};
}
if (!existingGateways.includes(options.gateway)) {
return {
valid: false,
error: `Gateway "${options.gateway}" not found. Available gateways: ${existingGateways.join(', ')}`,
};
}
// API Gateway targets: validate early and return (skip outbound auth validation)
if (mappedType === 'apiGateway') {
if (!options.restApiId) {
return { valid: false, error: '--rest-api-id is required for api-gateway type' };
}
if (!options.stage) {
return { valid: false, error: '--stage is required for api-gateway type' };
}
if (options.endpoint) {
return { valid: false, error: '--endpoint is not applicable for api-gateway type' };
}
if (options.host) {
return { valid: false, error: '--host is not applicable for api-gateway type' };
}
if (options.language && options.language !== 'Other') {
return { valid: false, error: '--language is not applicable for api-gateway type' };
}
if (options.outboundAuthType) {
const authLower = options.outboundAuthType.toLowerCase();
if (authLower === 'oauth') {
return { valid: false, error: 'OAuth is not supported for api-gateway type' };
}
if ((authLower === 'api-key' || authLower === 'api_key') && !options.credentialName) {
return { valid: false, error: '--credential-name is required with --outbound-auth api-key' };
}
}
if (options.oauthClientId || options.oauthClientSecret || options.oauthDiscoveryUrl || options.oauthScopes) {
return { valid: false, error: 'OAuth options are not applicable for api-gateway type' };
}
options.language = 'Other';
return { valid: true };
}
// Validate outbound auth configuration
if (options.outboundAuthType && options.outboundAuthType !== 'NONE') {
const hasInlineOAuth = !!(options.oauthClientId ?? options.oauthClientSecret ?? options.oauthDiscoveryUrl);
// Reject inline OAuth fields with API_KEY auth type
if (options.outboundAuthType === 'API_KEY' && hasInlineOAuth) {
return {
valid: false,
error: 'Inline OAuth fields cannot be used with API_KEY outbound auth. Use --credential-name instead.',
};
}
if (!options.credentialName && !hasInlineOAuth) {
return {
valid: false,
error:
options.outboundAuthType === 'API_KEY'
? '--credential-name is required when outbound auth type is API_KEY'
: `--credential-name or inline OAuth fields (--oauth-client-id, --oauth-client-secret, --oauth-discovery-url) required when outbound auth type is ${options.outboundAuthType}`,
};
}
// Validate inline OAuth fields are complete
if (hasInlineOAuth) {
if (!options.oauthClientId)
return { valid: false, error: '--oauth-client-id is required for inline OAuth credential creation' };
if (!options.oauthClientSecret)
return { valid: false, error: '--oauth-client-secret is required for inline OAuth credential creation' };
if (!options.oauthDiscoveryUrl)
return { valid: false, error: '--oauth-discovery-url is required for inline OAuth credential creation' };
try {
new URL(options.oauthDiscoveryUrl);
} catch {
return { valid: false, error: '--oauth-discovery-url must be a valid URL' };
}
}
// Validate that referenced credential exists
if (options.credentialName) {
const credentialValidation = await validateCredentialExists(options.credentialName);
if (!credentialValidation.valid) {
return credentialValidation;
}
}
}
// Schema-based targets (OpenAPI / Smithy)
if (mappedType === 'openApiSchema' || mappedType === 'smithyModel') {
if (!options.schema) {
return { valid: false, error: '--schema is required for schema-based target types' };
}
if (options.endpoint) {
return { valid: false, error: `--endpoint is not applicable for ${mappedType} target type` };
}
if (options.host) {
return { valid: false, error: `--host is not applicable for ${mappedType} target type` };
}
const isS3 = options.schema.startsWith('s3://');
if (isS3) {
// Validate S3 URI format: s3://bucket/key
const s3Path = options.schema.slice(5); // strip 's3://'
if (!s3Path.includes('/') || s3Path.startsWith('/')) {
return { valid: false, error: 'Invalid S3 URI format. Expected: s3://bucket-name/key' };
}
} else {
// Local file validation
const resolvedPath = resolve(options.schema);
if (!existsSync(resolvedPath)) {
return { valid: false, error: `Schema file not found: ${options.schema}` };
}
const ext = extname(resolvedPath).toLowerCase();
if (ext !== '.json') {
return { valid: false, error: `Schema file must be a JSON file (.json), got: ${ext}` };
}
}
if (options.schemaS3Account && !isS3) {
return { valid: false, error: '--schema-s3-account is only valid with S3 URIs' };
}
options.language = 'Other';
return { valid: true };
}
if (mappedType === 'mcpServer') {
if (options.host) {
return { valid: false, error: '--host is not applicable for MCP server targets' };
}
if (!options.endpoint) {
return { valid: false, error: '--endpoint is required for mcp-server type' };
}
try {
const url = new URL(options.endpoint);
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
return { valid: false, error: 'Endpoint must use http:// or https:// protocol' };
}
} catch {
return { valid: false, error: 'Endpoint must be a valid URL (e.g. https://example.com/mcp)' };
}
// Populate defaults for fields skipped by external endpoint flow
options.language ??= 'Other';
return { valid: true };
}
if (!options.language) {
return { valid: false, error: '--language is required' };
}
if (options.language !== 'Python' && options.language !== 'TypeScript' && options.language !== 'Other') {
return { valid: false, error: 'Invalid language. Valid options: Python, TypeScript, Other' };
}
return { valid: true };
}
// Memory validation (v2: top-level resource, no owner)
export function validateAddMemoryOptions(options: AddMemoryOptions): ValidationResult {
if (!options.name) {
return { valid: false, error: '--name is required' };
}
if (options.strategies) {
const strategies = options.strategies
.split(',')
.map(s => s.trim())
.filter(Boolean);
for (const strategy of strategies) {
if (!VALID_STRATEGIES.includes(strategy)) {
return { valid: false, error: `Invalid strategy: ${strategy}. Must be one of: ${VALID_STRATEGIES.join(', ')}` };
}
}
}
if (options.streamDeliveryResources && (options.dataStreamArn || options.contentLevel)) {
return {
valid: false,
error: '--stream-delivery-resources cannot be combined with --data-stream-arn or --stream-content-level',
};
}
if (options.contentLevel && !options.dataStreamArn) {
return { valid: false, error: '--data-stream-arn is required when --stream-content-level is set' };
}
if (options.dataStreamArn && !options.dataStreamArn.startsWith('arn:')) {
return { valid: false, error: '--data-stream-arn must be a valid ARN (starts with arn:)' };
}
if (options.deliveryType && !VALID_DELIVERY_TYPES.includes(options.deliveryType)) {
return {
valid: false,
error: `Invalid delivery type. Must be one of: ${VALID_DELIVERY_TYPES.join(', ')}`,
};
}
if (options.contentLevel && !VALID_STREAM_CONTENT_LEVELS.includes(options.contentLevel)) {
return {
valid: false,
error: `Invalid content level. Must be one of: ${VALID_STREAM_CONTENT_LEVELS.join(', ')}`,
};
}
return { valid: true };
}
// Identity validation (v2: credential resource, no owner)
export function validateAddIdentityOptions(options: AddIdentityOptions): ValidationResult {
if (!options.name) {
return { valid: false, error: '--name is required' };
}
const identityType = options.type ?? 'api-key';
if (identityType === 'oauth') {
if (!options.discoveryUrl) {
return { valid: false, error: '--discovery-url is required for OAuth credentials' };
}
try {
new URL(options.discoveryUrl);
} catch {
return { valid: false, error: '--discovery-url must be a valid URL' };
}
if (!options.clientId) {
return { valid: false, error: '--client-id is required for OAuth credentials' };
}
if (!options.clientSecret) {
return { valid: false, error: '--client-secret is required for OAuth credentials' };
}
return { valid: true };
}
if (!options.apiKey) {
return { valid: false, error: '--api-key is required' };
}
return { valid: true };
}