-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask-api.ts
More file actions
1311 lines (1181 loc) · 50.7 KB
/
Copy pathtask-api.ts
File metadata and controls
1311 lines (1181 loc) · 50.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
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* MIT No Attribution
*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import * as path from 'path';
import { ArnFormat, Duration, RemovalPolicy, Stack } from 'aws-cdk-lib';
import * as apigw from 'aws-cdk-lib/aws-apigateway';
import * as cognito from 'aws-cdk-lib/aws-cognito';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as iam from 'aws-cdk-lib/aws-iam';
import { Runtime, Architecture, type LayerVersion } from 'aws-cdk-lib/aws-lambda';
import * as lambda from 'aws-cdk-lib/aws-lambda-nodejs';
import * as logs from 'aws-cdk-lib/aws-logs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as wafv2 from 'aws-cdk-lib/aws-wafv2';
import { NagSuppressions } from 'cdk-nag';
import { Construct } from 'constructs';
import { CEDAR_WASM_MIN_LAMBDA_MEMORY_MB } from './cedar-wasm-layer';
/** Default task-record retention used for TTL computation (days). */
const DEFAULT_TASK_RETENTION_DAYS = 90;
/** Default webhook-record retention used for TTL computation (days). */
const DEFAULT_WEBHOOK_RETENTION_DAYS = 30;
/**
* Standard API-handler Lambda timeout (seconds). Lambda's 3s default is
* not enough once cold-start TLS handshakes / SDK loads are added; 15s
* gives comfortable headroom while staying well under API Gateway's 29s
* integration cap.
*/
const API_HANDLER_TIMEOUT_SECONDS = 15;
/**
* Confirm-uploads Lambda timeout (seconds). Downloads + screens up to
* five attachments (Guardrail image scan, PDF text extraction) in one
* invocation, so it gets a much larger budget than the standard handlers.
*/
const CONFIRM_UPLOADS_TIMEOUT_SECONDS = 180;
/** Standard API-handler Lambda memory (MB). */
const API_HANDLER_MEMORY_MB = 256;
/** Memory for handlers with attachment screening or heavy SDK init (MB). */
const SCREENING_HANDLER_MEMORY_MB = 512;
/** Memory for confirm-uploads / webhook-create attachment path (MB). */
const HEAVY_ATTACHMENT_HANDLER_MEMORY_MB = 1024;
/**
* Properties for TaskApi construct.
*/
export interface TaskApiProps {
/**
* The DynamoDB task table.
*/
readonly taskTable: dynamodb.ITable;
/**
* The DynamoDB task events table.
*/
readonly taskEventsTable: dynamodb.ITable;
/**
* The DynamoDB task nudges table (Phase 2). When provided, the
* `POST /tasks/{task_id}/nudge` endpoint is created.
*/
readonly taskNudgesTable?: dynamodb.ITable;
/**
* Cedar HITL approvals table. When provided, POST /approve, POST
* /deny, and GET /pending endpoints are created. See design §7.1,
* §7.2, §7.7.
*/
readonly taskApprovalsTable?: dynamodb.ITable;
/**
* Cedar-wasm Lambda layer (CedarWasmLayer.layer). Required by the
* handlers that parse blueprint policies (`GetPoliciesFn`,
* `CreateTaskFn`). Attached only when all approval-gate plumbing
* (TaskApprovalsTable, this layer, blueprint / cedar_policies on
* RepoTable) is present.
*/
readonly cedarWasmLayer?: LayerVersion;
/**
* Per-task per-minute nudge rate limit.
* @default 10
*/
readonly nudgeRateLimitPerMinute?: number;
/**
* The DynamoDB repo config table. When provided, task creation checks
* that the target repository is onboarded before accepting the task.
*/
readonly repoTable?: dynamodb.ITable;
/**
* The DynamoDB webhook table. When provided, webhook endpoints are created.
*/
readonly webhookTable?: dynamodb.ITable;
/**
* The DynamoDB platform API key table. When provided, API key management
* endpoints are created and the webhook management endpoints accept an API
* key (with `webhooks:manage`) in addition to a Cognito JWT.
*/
readonly apiKeyTable?: dynamodb.ITable;
/**
* Number of days to retain revoked API key records before DynamoDB TTL
* deletes them.
* @default 30
*/
readonly apiKeyRetentionDays?: number;
/**
* ARN of the orchestrator Lambda alias. When set, the create-task handler
* async-invokes the orchestrator after writing the task record.
*/
readonly orchestratorFunctionArn?: string;
/**
* API Gateway stage name.
* @default 'v1'
*/
readonly stageName?: string;
/**
* Removal policy for Cognito resources.
* @default RemovalPolicy.DESTROY
*/
readonly removalPolicy?: RemovalPolicy;
/**
* Bedrock Guardrail ID for screening task input.
*/
readonly guardrailId?: string;
/**
* Bedrock Guardrail version for screening task input.
*/
readonly guardrailVersion?: string;
/**
* Number of days to retain completed task and event records before DynamoDB TTL deletes them.
* @default 90
*/
readonly taskRetentionDays?: number;
/**
* Number of days to retain revoked webhook records before DynamoDB TTL deletes them.
* @default 30
*/
readonly webhookRetentionDays?: number;
/**
* AgentCore runtime ARN for which cancel-task may call `StopRuntimeSession`.
* Also passed as `RUNTIME_ARN` to cancel-task so it can resolve the target
* runtime when a task record lacks `agent_runtime_arn`.
*/
readonly agentCoreStopSessionRuntimeArn?: string;
/**
* S3 bucket storing ``--trace`` trajectory artifacts. When provided,
* a ``GET /v1/tasks/{task_id}/trace`` route is created that issues
* short-lived presigned download URLs (design §10.1).
*/
readonly traceArtifactsBucket?: s3.IBucket;
/**
* ECS cluster ARN for cancel-task to stop ECS-backed tasks.
* When provided, the cancel Lambda gets `ECS_CLUSTER_ARN` env var and `ecs:StopTask` permission.
*/
readonly ecsClusterArn?: string;
/**
* S3 bucket for task attachments. When provided, the create-task Lambda
* gets PutObject/DeleteObject grants and the bucket name as env var.
*/
readonly attachmentsBucket?: s3.IBucket;
/**
* User concurrency table for admission control during confirm-uploads.
* Required when attachmentsBucket is provided.
*/
readonly userConcurrencyTable?: dynamodb.ITable;
}
/**
* CDK construct that creates the Task API — an API Gateway REST API backed by
* Cognito User Pool authentication and Lambda handler integrations.
*
* Exposes endpoints:
* - POST /tasks → createTask (Cognito)
* - GET /tasks → listTasks (Cognito)
* - GET /tasks/{task_id} → getTask (Cognito)
* - DELETE /tasks/{task_id} → cancelTask (Cognito)
* - GET /tasks/{task_id}/events → getTaskEvents (Cognito)
* - POST /webhooks → createWebhook (Cognito, or JWT/API-key when apiKeyTable set)
* - GET /webhooks → listWebhooks (Cognito, or JWT/API-key when apiKeyTable set)
* - DELETE /webhooks/{webhook_id} → deleteWebhook (Cognito, or JWT/API-key when apiKeyTable set)
* - POST /webhooks/tasks → webhookCreateTask (REQUEST authorizer)
* - POST /api-keys → createApiKey (Cognito)
* - GET /api-keys → listApiKeys (Cognito)
* - DELETE /api-keys/{key_id} → deleteApiKey (Cognito)
*/
export class TaskApi extends Construct {
/**
* The API Gateway REST API.
*/
public readonly api: apigw.RestApi;
/**
* The Cognito User Pool for authentication.
*/
public readonly userPool: cognito.UserPool;
/**
* The Cognito User Pool App Client.
*/
public readonly appClient: cognito.UserPoolClient;
/**
* The Cognito User Pool App Client ID.
*/
public readonly appClientId: string;
constructor(scope: Construct, id: string, props: TaskApiProps) {
super(scope, id);
const removalPolicy = props.removalPolicy ?? RemovalPolicy.DESTROY;
const stageName = props.stageName ?? 'v1';
// --- Cognito User Pool ---
this.userPool = new cognito.UserPool(this, 'UserPool', {
selfSignUpEnabled: false,
signInAliases: { email: true },
passwordPolicy: {
minLength: 12,
requireLowercase: true,
requireUppercase: true,
requireDigits: true,
requireSymbols: true,
},
removalPolicy,
});
this.appClient = this.userPool.addClient('AppClient', {
authFlows: {
userPassword: true,
userSrp: true,
},
generateSecret: false,
});
this.appClientId = this.appClient.userPoolClientId;
// Suppress Cognito rules not applicable for dev environment
NagSuppressions.addResourceSuppressions(this.userPool, [
{ id: 'AwsSolutions-COG2', reason: 'MFA not required for dev environment — CLI-based auth flow' },
{ id: 'AwsSolutions-COG3', reason: 'Advanced security mode (Plus tier) not required for dev environment' },
{ id: 'AwsSolutions-COG8', reason: 'Cognito Plus tier / feature plan not required for dev environment — same rationale as COG3 (advanced security)' },
]);
// --- REST API ---
const apiAccessLogGroup = new logs.LogGroup(this, 'ApiAccessLogs', {
removalPolicy,
retention: logs.RetentionDays.ONE_MONTH,
});
this.api = new apigw.RestApi(this, 'Api', {
restApiName: 'TaskApi',
deployOptions: {
stageName,
throttlingRateLimit: 60,
throttlingBurstLimit: 100,
accessLogDestination: new apigw.LogGroupLogDestination(apiAccessLogGroup),
accessLogFormat: apigw.AccessLogFormat.jsonWithStandardFields(),
loggingLevel: apigw.MethodLoggingLevel.INFO,
},
defaultCorsPreflightOptions: {
allowOrigins: apigw.Cors.ALL_ORIGINS,
allowMethods: apigw.Cors.ALL_METHODS,
},
});
// --- WAF Web ACL ---
const webAcl = new wafv2.CfnWebACL(this, 'WebAcl', {
defaultAction: { allow: {} },
scope: 'REGIONAL',
visibilityConfig: {
cloudWatchMetricsEnabled: true,
metricName: 'TaskApiWebAcl',
sampledRequestsEnabled: true,
},
rules: [
{
// CRS for task paths that accept large bodies (inline base64
// attachments up to 3 MB, presigned upload metadata). Excludes
// SizeRestrictions_BODY only; all other CRS rules apply. Payload
// size is bounded by API GW (10 MB) and validateAttachments().
name: 'AWSManagedRulesCommonRuleSet-TaskPaths',
priority: 1,
overrideAction: { none: {} },
statement: {
managedRuleGroupStatement: {
vendorName: 'AWS',
name: 'AWSManagedRulesCommonRuleSet',
excludedRules: [{ name: 'SizeRestrictions_BODY' }],
scopeDownStatement: {
orStatement: {
statements: [
{
byteMatchStatement: {
fieldToMatch: { uriPath: {} },
positionalConstraint: 'STARTS_WITH',
searchString: '/v1/tasks',
textTransformations: [{ priority: 0, type: 'NONE' }],
},
},
{
// Linear webhook payloads > 8 KB (HMAC-verified in Lambda,
// rate-limited by priority-4 rule below).
byteMatchStatement: {
fieldToMatch: { uriPath: {} },
positionalConstraint: 'EXACTLY',
searchString: '/v1/linear/webhook',
textTransformations: [{ priority: 0, type: 'NONE' }],
},
},
{
// Jira issue payloads include the full issue field set.
// Attachment metadata can push them over 8 KB. The
// receiver HMAC-verifies the raw body and the priority-4
// rule below still rate-limits this route.
byteMatchStatement: {
fieldToMatch: { uriPath: {} },
positionalConstraint: 'EXACTLY',
searchString: '/v1/jira/webhook',
textTransformations: [{ priority: 0, type: 'NONE' }],
},
},
{
// GitHub deployment_status webhook (preview-deploy
// screenshot pipeline). The full payload (workflow run
// history + deploy URLs + deployment metadata) exceeds
// 8 KB and trips SizeRestrictions_BODY. HMAC-verified
// in Lambda. (CloudWatch BlockedRequests metric
// confirmed: SizeRestrictions_BODY fired, not RFI —
// GenericRFI_BODY has never blocked on this WebACL.)
byteMatchStatement: {
fieldToMatch: { uriPath: {} },
positionalConstraint: 'EXACTLY',
searchString: '/v1/github/webhook',
textTransformations: [{ priority: 0, type: 'NONE' }],
},
},
],
},
},
},
},
visibilityConfig: {
cloudWatchMetricsEnabled: true,
metricName: 'CommonRuleSetTaskPaths',
sampledRequestsEnabled: true,
},
},
{
// Full CRS (including SizeRestrictions_BODY) for all other paths.
name: 'AWSManagedRulesCommonRuleSet',
priority: 2,
overrideAction: { none: {} },
statement: {
managedRuleGroupStatement: {
vendorName: 'AWS',
name: 'AWSManagedRulesCommonRuleSet',
scopeDownStatement: {
andStatement: {
statements: [
{
notStatement: {
statement: {
byteMatchStatement: {
fieldToMatch: { uriPath: {} },
positionalConstraint: 'STARTS_WITH',
searchString: '/v1/tasks',
textTransformations: [{ priority: 0, type: 'NONE' }],
},
},
},
},
{
notStatement: {
statement: {
byteMatchStatement: {
fieldToMatch: { uriPath: {} },
positionalConstraint: 'EXACTLY',
searchString: '/v1/jira/webhook',
textTransformations: [{ priority: 0, type: 'NONE' }],
},
},
},
},
{
notStatement: {
statement: {
byteMatchStatement: {
fieldToMatch: { uriPath: {} },
positionalConstraint: 'EXACTLY',
searchString: '/v1/linear/webhook',
textTransformations: [{ priority: 0, type: 'NONE' }],
},
},
},
},
{
notStatement: {
statement: {
byteMatchStatement: {
fieldToMatch: { uriPath: {} },
positionalConstraint: 'EXACTLY',
searchString: '/v1/github/webhook',
textTransformations: [{ priority: 0, type: 'NONE' }],
},
},
},
},
],
},
},
},
},
visibilityConfig: {
cloudWatchMetricsEnabled: true,
metricName: 'CommonRuleSet',
sampledRequestsEnabled: true,
},
},
{
name: 'AWSManagedRulesKnownBadInputsRuleSet',
priority: 3,
overrideAction: { none: {} },
statement: {
managedRuleGroupStatement: {
vendorName: 'AWS',
name: 'AWSManagedRulesKnownBadInputsRuleSet',
},
},
visibilityConfig: {
cloudWatchMetricsEnabled: true,
metricName: 'KnownBadInputsRuleSet',
sampledRequestsEnabled: true,
},
},
{
name: 'RateLimitRule',
priority: 4,
action: { block: {} },
statement: {
rateBasedStatement: {
limit: 1000,
aggregateKeyType: 'IP',
},
},
visibilityConfig: {
cloudWatchMetricsEnabled: true,
metricName: 'RateLimitRule',
sampledRequestsEnabled: true,
},
},
],
});
new wafv2.CfnWebACLAssociation(this, 'WebAclAssociation', {
resourceArn: this.api.deploymentStage.stageArn,
webAclArn: webAcl.attrArn,
});
// --- Cognito Authorizer ---
const cognitoAuthorizer = new apigw.CognitoUserPoolsAuthorizer(this, 'Authorizer', {
cognitoUserPools: [this.userPool],
});
const requestValidator = new apigw.RequestValidator(this, 'RequestValidator', {
restApi: this.api,
validateRequestBody: true,
validateRequestParameters: true,
});
const cognitoAuthOptions: apigw.MethodOptions = {
authorizer: cognitoAuthorizer,
authorizationType: apigw.AuthorizationType.COGNITO,
requestValidator,
};
// --- Shared Lambda configuration ---
const handlersDir = path.join(__dirname, '..', 'handlers');
const commonEnv = {
TASK_TABLE_NAME: props.taskTable.tableName,
TASK_EVENTS_TABLE_NAME: props.taskEventsTable.tableName,
TASK_RETENTION_DAYS: String(props.taskRetentionDays ?? DEFAULT_TASK_RETENTION_DAYS),
};
// The Node.js Lambda runtime ships an AWS SDK, but its pinned version
// lags current. `@aws-sdk/client-bedrock-agentcore` in particular has
// shipped new commands (e.g. StopRuntimeSessionCommand) that are not in
// the runtime's bundled SDK, so externalizing it causes Lambdas to throw
// `<Command> is not a constructor` at runtime — a silent failure mode
// because catch blocks swallow the error and log a best-effort warning.
// Bundle bedrock-agentcore explicitly; keep stable clients external to
// keep Lambda sizes small.
const commonBundling: lambda.BundlingOptions = {
externalModules: [
'@aws-sdk/client-dynamodb',
'@aws-sdk/client-ecs',
'@aws-sdk/client-lambda',
'@aws-sdk/client-bedrock-runtime',
'@aws-sdk/client-secrets-manager',
'@aws-sdk/lib-dynamodb',
'@aws-sdk/util-dynamodb',
],
};
// pdf-parse is used for PDF attachment screening (text extraction).
const attachmentScreeningBundling: lambda.BundlingOptions = {
...commonBundling,
nodeModules: ['pdf-parse'],
};
// --- Lambda handlers ---
const createTaskEnv: Record<string, string> = { ...commonEnv };
if (props.repoTable) {
createTaskEnv.REPO_TABLE_NAME = props.repoTable.tableName;
}
if (props.orchestratorFunctionArn) {
createTaskEnv.ORCHESTRATOR_FUNCTION_ARN = props.orchestratorFunctionArn;
}
if (props.guardrailId && props.guardrailVersion) {
createTaskEnv.GUARDRAIL_ID = props.guardrailId;
createTaskEnv.GUARDRAIL_VERSION = props.guardrailVersion;
}
if (props.attachmentsBucket) {
createTaskEnv.ATTACHMENTS_BUCKET_NAME = props.attachmentsBucket.bucketName;
}
const createTaskFn = new lambda.NodejsFunction(this, 'CreateTaskFn', {
entry: path.join(handlersDir, 'create-task.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: createTaskEnv,
bundling: attachmentScreeningBundling,
memorySize: SCREENING_HANDLER_MEMORY_MB,
timeout: Duration.seconds(API_HANDLER_TIMEOUT_SECONDS),
});
const getTaskFn = new lambda.NodejsFunction(this, 'GetTaskFn', {
entry: path.join(handlersDir, 'get-task.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: commonEnv,
bundling: commonBundling,
});
const listTasksFn = new lambda.NodejsFunction(this, 'ListTasksFn', {
entry: path.join(handlersDir, 'list-tasks.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: commonEnv,
bundling: commonBundling,
});
const cancelTaskEnv: Record<string, string> = { ...commonEnv };
const stopSessionArn = props.agentCoreStopSessionRuntimeArn;
if (stopSessionArn) {
cancelTaskEnv.RUNTIME_ARN = stopSessionArn;
}
if (props.ecsClusterArn) {
cancelTaskEnv.ECS_CLUSTER_ARN = props.ecsClusterArn;
}
const cancelTaskFn = new lambda.NodejsFunction(this, 'CancelTaskFn', {
entry: path.join(handlersDir, 'cancel-task.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: cancelTaskEnv,
bundling: commonBundling,
// Cancel performs: DDB GetItem + DDB UpdateItem + ECS StopTask or
// AgentCore StopRuntimeSession + DDB PutItem. The default 3s timeout
// is not enough once cold-start TLS handshakes for bedrock-agentcore
// are added. 15s gives comfortable headroom.
timeout: Duration.seconds(API_HANDLER_TIMEOUT_SECONDS),
memorySize: API_HANDLER_MEMORY_MB,
});
const getTaskEventsFn = new lambda.NodejsFunction(this, 'GetTaskEventsFn', {
entry: path.join(handlersDir, 'get-task-events.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: commonEnv,
bundling: commonBundling,
});
// Operator replay bundle (#515): aggregates TaskRecord + chronological
// TaskEvents. Reads both tables; commonEnv already carries both table names.
// Heaviest read path — GetItem + a multi-page Query loop (up to
// MAX_REPLAY_EVENTS / ~5 pages) + full-bundle serialization — so it gets the
// raised timeout/memory the other heavy handlers use rather than the 3s /
// 128MB defaults, which risk INIT-timeout 502s and OOM on long histories.
const getTaskReplayFn = new lambda.NodejsFunction(this, 'GetTaskReplayFn', {
entry: path.join(handlersDir, 'get-task-replay.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: commonEnv,
bundling: commonBundling,
timeout: Duration.seconds(API_HANDLER_TIMEOUT_SECONDS),
// 512MB (not the 256MB standard): the bundle holds up to
// MAX_REPLAY_EVENT_BYTES of events in memory during serialization.
memorySize: SCREENING_HANDLER_MEMORY_MB,
});
// --- IAM grants ---
// Read-write for create and cancel (write task + event)
props.taskTable.grantReadWriteData(createTaskFn);
props.taskEventsTable.grantReadWriteData(createTaskFn);
props.taskTable.grantReadWriteData(cancelTaskFn);
props.taskEventsTable.grantReadWriteData(cancelTaskFn);
if (stopSessionArn) {
cancelTaskFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['bedrock-agentcore:StopRuntimeSession'],
resources: [stopSessionArn, `${stopSessionArn}/*`],
}));
}
if (props.ecsClusterArn) {
cancelTaskFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['ecs:StopTask'],
resources: ['*'],
conditions: {
ArnEquals: {
'ecs:cluster': props.ecsClusterArn,
},
},
}));
}
// Repo table read for onboarding gate
if (props.repoTable) {
props.repoTable.grantReadData(createTaskFn);
}
// Read-only for get, list, and events
props.taskTable.grantReadData(getTaskFn);
props.taskTable.grantReadData(listTasksFn);
props.taskTable.grantReadData(getTaskEventsFn);
props.taskEventsTable.grantReadData(getTaskEventsFn);
// Replay reads the task record (ownership + fields) and its events.
props.taskTable.grantReadData(getTaskReplayFn);
props.taskEventsTable.grantReadData(getTaskReplayFn);
// Grant createTask permission to invoke the orchestrator
if (props.orchestratorFunctionArn) {
createTaskFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['lambda:InvokeFunction'],
resources: [props.orchestratorFunctionArn],
}));
}
// Grant createTask permission to apply the guardrail
if (props.guardrailId) {
createTaskFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['bedrock:ApplyGuardrail'],
resources: [
Stack.of(this).formatArn({
service: 'bedrock',
resource: 'guardrail',
resourceName: props.guardrailId,
}),
],
}));
}
// Grant create-task Lambda put/delete on attachments bucket for inline upload + cleanup
if (props.attachmentsBucket) {
props.attachmentsBucket.grantPut(createTaskFn);
props.attachmentsBucket.grantDelete(createTaskFn);
}
// --- Confirm-uploads Lambda (presigned upload flow) ---
let confirmUploadsFn: lambda.NodejsFunction | undefined;
if (props.attachmentsBucket && props.userConcurrencyTable) {
const confirmUploadsEnv: Record<string, string> = { ...commonEnv };
confirmUploadsEnv.ATTACHMENTS_BUCKET_NAME = props.attachmentsBucket.bucketName;
confirmUploadsEnv.USER_CONCURRENCY_TABLE_NAME = props.userConcurrencyTable.tableName;
if (props.orchestratorFunctionArn) {
confirmUploadsEnv.ORCHESTRATOR_FUNCTION_ARN = props.orchestratorFunctionArn;
}
if (props.guardrailId && props.guardrailVersion) {
confirmUploadsEnv.GUARDRAIL_ID = props.guardrailId;
confirmUploadsEnv.GUARDRAIL_VERSION = props.guardrailVersion;
}
confirmUploadsFn = new lambda.NodejsFunction(this, 'ConfirmUploadsFn', {
entry: path.join(handlersDir, 'confirm-uploads.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: confirmUploadsEnv,
bundling: attachmentScreeningBundling,
memorySize: HEAVY_ATTACHMENT_HANDLER_MEMORY_MB,
timeout: Duration.seconds(CONFIRM_UPLOADS_TIMEOUT_SECONDS),
});
// Grants: DDB read-write, S3 read-write-delete, orchestrator invoke, guardrail
props.taskTable.grantReadWriteData(confirmUploadsFn);
props.taskEventsTable.grantReadWriteData(confirmUploadsFn);
props.attachmentsBucket.grantReadWrite(confirmUploadsFn);
props.attachmentsBucket.grantDelete(confirmUploadsFn);
props.userConcurrencyTable.grantReadWriteData(confirmUploadsFn);
if (props.orchestratorFunctionArn) {
confirmUploadsFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['lambda:InvokeFunction'],
resources: [props.orchestratorFunctionArn],
}));
}
if (props.guardrailId) {
confirmUploadsFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['bedrock:ApplyGuardrail'],
resources: [
Stack.of(this).formatArn({
service: 'bedrock',
resource: 'guardrail',
resourceName: props.guardrailId,
}),
],
}));
}
}
// Collect all Lambda functions for cdk-nag suppressions
const allFunctions: lambda.NodejsFunction[] = [createTaskFn, getTaskFn, listTasksFn, cancelTaskFn, getTaskEventsFn, getTaskReplayFn];
if (confirmUploadsFn) allFunctions.push(confirmUploadsFn);
// --- API resource tree: /tasks ---
const tasks = this.api.root.addResource('tasks');
tasks.addMethod('POST', new apigw.LambdaIntegration(createTaskFn), cognitoAuthOptions);
tasks.addMethod('GET', new apigw.LambdaIntegration(listTasksFn), cognitoAuthOptions);
const taskById = tasks.addResource('{task_id}');
taskById.addMethod('GET', new apigw.LambdaIntegration(getTaskFn), cognitoAuthOptions);
taskById.addMethod('DELETE', new apigw.LambdaIntegration(cancelTaskFn), cognitoAuthOptions);
const events = taskById.addResource('events');
events.addMethod('GET', new apigw.LambdaIntegration(getTaskEventsFn), cognitoAuthOptions);
// Operator replay bundle (#515): GET /tasks/{task_id}/replay. Same Cognito
// owner-scoped auth as GET /tasks/{task_id} (cognitoAuthOptions).
const replay = taskById.addResource('replay');
replay.addMethod('GET', new apigw.LambdaIntegration(getTaskReplayFn), cognitoAuthOptions);
// --- Confirm-uploads endpoint: POST /tasks/{task_id}/confirm-uploads ---
if (confirmUploadsFn) {
const confirmUploads = taskById.addResource('confirm-uploads');
confirmUploads.addMethod('POST', new apigw.LambdaIntegration(confirmUploadsFn), cognitoAuthOptions);
}
// --- Trace URL endpoint (design §10.1): GET /tasks/{task_id}/trace ---
if (props.traceArtifactsBucket) {
const traceBucket = props.traceArtifactsBucket;
const getTraceUrlFn = new lambda.NodejsFunction(this, 'GetTraceUrlFn', {
entry: path.join(handlersDir, 'get-trace-url.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: {
...commonEnv,
TRACE_ARTIFACTS_BUCKET_NAME: traceBucket.bucketName,
},
bundling: {
...commonBundling,
// Defensive future-proofing: if ``@aws-sdk/client-s3`` or
// ``@aws-sdk/s3-request-presigner`` are ever added to
// ``commonBundling.externalModules`` (e.g. because a future
// Node runtime ships them), this filter ensures they stay
// bundled for *this* function — the Node 24 Lambda runtime
// does not ship either, and ``getSignedUrl`` will throw
// ``Cannot find module`` at cold start if it's externalized.
// Today this is a no-op (neither module is in the common
// external list); the filter exists to guard against drift.
externalModules: commonBundling.externalModules?.filter(
m => m !== '@aws-sdk/client-s3' && m !== '@aws-sdk/s3-request-presigner',
),
},
// Cold-start SDK load (s3-client + s3-request-presigner + lib-dynamodb)
// exceeds Lambda's 3s default, causing INIT timeout → 502 Bad Gateway.
timeout: Duration.seconds(API_HANDLER_TIMEOUT_SECONDS),
memorySize: SCREENING_HANDLER_MEMORY_MB,
});
props.taskTable.grantReadData(getTraceUrlFn);
// Minimal grant — the handler only needs ``s3:GetObject`` (which
// implicitly covers ``s3:HeadObject``) on trace objects to sign
// presigned URLs and HEAD-check for existence before presigning.
// ``grantRead`` would expand to ``s3:GetObject*`` + ``s3:GetBucket*``
// + ``s3:List*``; ``ListBucket`` / ``GetBucketLocation`` / etc. are
// unnecessary scope. Tightening to an explicit statement (L3 item 2).
getTraceUrlFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: [`${traceBucket.bucketArn}/*`],
}));
const trace = taskById.addResource('trace');
trace.addMethod('GET', new apigw.LambdaIntegration(getTraceUrlFn), cognitoAuthOptions);
allFunctions.push(getTraceUrlFn);
}
// --- Nudge endpoint (Phase 2): POST /tasks/{task_id}/nudge ---
if (props.taskNudgesTable) {
const nudgeTaskEnv: Record<string, string> = {
...commonEnv,
NUDGES_TABLE_NAME: props.taskNudgesTable.tableName,
NUDGE_RATE_LIMIT_PER_MINUTE: String(props.nudgeRateLimitPerMinute ?? 10),
};
if (props.guardrailId && props.guardrailVersion) {
nudgeTaskEnv.GUARDRAIL_ID = props.guardrailId;
nudgeTaskEnv.GUARDRAIL_VERSION = props.guardrailVersion;
}
const nudgeTaskFn = new lambda.NodejsFunction(this, 'NudgeTaskFn', {
entry: path.join(handlersDir, 'nudge-task.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: nudgeTaskEnv,
bundling: commonBundling,
});
// Read tasks (ownership + state), read/write nudges (persist + rate-limit counter).
props.taskTable.grantReadData(nudgeTaskFn);
props.taskNudgesTable.grantReadWriteData(nudgeTaskFn);
if (props.guardrailId) {
nudgeTaskFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['bedrock:ApplyGuardrail'],
resources: [
Stack.of(this).formatArn({
service: 'bedrock',
resource: 'guardrail',
resourceName: props.guardrailId,
}),
],
}));
}
const nudge = taskById.addResource('nudge');
nudge.addMethod('POST', new apigw.LambdaIntegration(nudgeTaskFn), cognitoAuthOptions);
allFunctions.push(nudgeTaskFn);
}
// --- Cedar HITL approval endpoints (§7.1, §7.2, §7.6, §7.7) ---
// Activated only when the approvals table is provided. The layer
// attachment on GetPoliciesFn is conditional on the cedar-wasm
// layer being supplied — without it the handler cannot parse
// policies and the route is skipped.
if (props.taskApprovalsTable) {
const approvalEnv: Record<string, string> = {
...commonEnv,
TASK_APPROVALS_TABLE_NAME: props.taskApprovalsTable.tableName,
};
// ApproveTaskFn — POST /tasks/{task_id}/approve
const approveTaskFn = new lambda.NodejsFunction(this, 'ApproveTaskFn', {
entry: path.join(handlersDir, 'approve-task.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: approvalEnv,
bundling: commonBundling,
timeout: Duration.seconds(API_HANDLER_TIMEOUT_SECONDS),
memorySize: API_HANDLER_MEMORY_MB,
});
props.taskTable.grantReadWriteData(approveTaskFn);
props.taskApprovalsTable.grantReadWriteData(approveTaskFn);
props.taskEventsTable.grantReadWriteData(approveTaskFn);
// DenyTaskFn — POST /tasks/{task_id}/deny
const denyTaskFn = new lambda.NodejsFunction(this, 'DenyTaskFn', {
entry: path.join(handlersDir, 'deny-task.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: approvalEnv,
bundling: commonBundling,
timeout: Duration.seconds(API_HANDLER_TIMEOUT_SECONDS),
memorySize: API_HANDLER_MEMORY_MB,
});
props.taskTable.grantReadWriteData(denyTaskFn);
props.taskApprovalsTable.grantReadWriteData(denyTaskFn);
props.taskEventsTable.grantReadWriteData(denyTaskFn);
// GetPendingFn — GET /pending
const getPendingFn = new lambda.NodejsFunction(this, 'GetPendingFn', {
entry: path.join(handlersDir, 'get-pending.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: approvalEnv,
bundling: commonBundling,
timeout: Duration.seconds(10),
memorySize: API_HANDLER_MEMORY_MB,
});
// Least-privilege: GetPendingFn only reads (Query on
// user_id-status-index for the user's pending rows) and writes
// a synthetic ``RATE#<user_id>#PENDING`` rate-limit row
// (UpdateItem with TTL). Full grantReadWriteData would also
// grant PutItem, BatchWrite, and DeleteItem on every approval
// record — orders of magnitude broader than needed (PR review
// S6). Pinned to the table ARN + its GSI, not the wildcard
// "/*" suffix that grantReadWriteData uses.
getPendingFn.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['dynamodb:Query'],
resources: [
props.taskApprovalsTable.tableArn,
`${props.taskApprovalsTable.tableArn}/index/*`,
],
}));
getPendingFn.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['dynamodb:UpdateItem'],
resources: [props.taskApprovalsTable.tableArn],
}));
// --- Routes ---
const approveTask = taskById.addResource('approve');
approveTask.addMethod(
'POST',
new apigw.LambdaIntegration(approveTaskFn),
cognitoAuthOptions,
);
const denyTask = taskById.addResource('deny');
denyTask.addMethod(
'POST',
new apigw.LambdaIntegration(denyTaskFn),
cognitoAuthOptions,
);
const pending = this.api.root.addResource('pending');
pending.addMethod(
'GET',
new apigw.LambdaIntegration(getPendingFn),
cognitoAuthOptions,
);
allFunctions.push(approveTaskFn, denyTaskFn, getPendingFn);
// GetPoliciesFn — GET /repos/{repo_id}/policies. Requires the
// cedar-wasm layer to parse blueprint policy text.
if (props.cedarWasmLayer && props.repoTable) {
const getPoliciesEnv: Record<string, string> = {
...approvalEnv,
REPO_TABLE_NAME: props.repoTable.tableName,
};
const getPoliciesFn = new lambda.NodejsFunction(this, 'GetPoliciesFn', {
entry: path.join(handlersDir, 'get-policies.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
environment: getPoliciesEnv,
bundling: {
...commonBundling,
// Keep cedar-wasm in the layer, not the function bundle.
// esbuild externalizes the import at build time; the layer
// provides it at runtime.
externalModules: [
...(commonBundling.externalModules ?? []),