-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp-stack.ts
More file actions
3739 lines (3684 loc) · 224 KB
/
Copy pathapp-stack.ts
File metadata and controls
3739 lines (3684 loc) · 224 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
import * as fs from "node:fs";
import * as path from "node:path";
import {
CfnOutput,
Duration,
Fn,
RemovalPolicy,
SecretValue,
Stack,
type StackProps,
} from "aws-cdk-lib";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import * as ecr from "aws-cdk-lib/aws-ecr";
import * as ecs from "aws-cdk-lib/aws-ecs";
import * as elbv2 from "aws-cdk-lib/aws-elasticloadbalancingv2";
import * as iam from "aws-cdk-lib/aws-iam";
import * as logs from "aws-cdk-lib/aws-logs";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as secretsmanager from "aws-cdk-lib/aws-secretsmanager";
import * as ssm from "aws-cdk-lib/aws-ssm";
import { type Construct } from "constructs";
import { type SpsEnvConfig } from "./config";
import { resolveSharedSg, resolveTierSubnets } from "./shared-vpc-subnets";
/**
* ADOT collector image, pinned by digest.
*
* `:latest` would let every new task pull a freshly-cut sidecar -- new CVEs,
* new behavior, no rollback story. The digest below is the AWS-published
* release that this stack was tested against; bumps go through a normal
* PR with the new digest captured here.
*
* Look up the current digest with:
* aws ecr-public describe-images \
* --repository-name aws-otel-collector \
* --image-ids imageTag=v0.43.3 --region us-east-1
*/
const ADOT_COLLECTOR_IMAGE =
"public.ecr.aws/aws-observability/aws-otel-collector" +
"@sha256:8aa9ea5f67b8d318f7d6af24677e3c70f7098bc0631147cb5fa91addbe980b06";
/**
* WCM SAML IdP coordinates (#466). Identical across staging and prod — WCM
* confirmed non-prod authenticates against the SAME production IdP, so these
* are IdP-global constants rather than per-env config. Source of truth is the
* IdP metadata document:
* https://login-proxy.weill.cornell.edu/idp/saml2/idp/metadata.php
* `SAML_IDP_CERT` (the signing cert) is NOT here — it is a rotatable secret
* injected from Secrets Manager (`scholars/<env>/saml/idp-cert`).
*/
const WCM_IDP_ENTITY_ID = "https://login-proxy.weill.cornell.edu/idp";
const WCM_IDP_SSO_URL = "https://login-proxy.weill.cornell.edu/idp/profile/SAML2/Redirect/SSO";
/**
* The assertion attribute carrying the bare CWID (#466). Confirmed against a
* live WCM assertion: a `CWID` attribute resolves to the un-suffixed CWID
* (e.g. `paa2013`), unlike the `@med.cornell.edu` eppn forms. node-saml keys
* attributes onto the profile by `Name`, and `extractCwid` reads
* `profile[SAML_CWID_ATTRIBUTE]`; setting it to `CWID` avoids the NameID
* fallback (which would otherwise yield the wrong identifier).
*/
const WCM_SAML_CWID_ATTRIBUTE = "CWID";
/**
* Trusted eppn scopes for the federated-login CWID fallback. The WCM-direct
* route releases the `CWID` attribute above; NYP / WCM-Q logins arrive through
* the SAML proxy WITHOUT it but WITH eppn (`<cwid>@<scope>`) — captured from a
* live `paa2013@nyp.org` assertion 2026-05-31. `extractCwidFromEppn` takes the
* eppn local-part as the CWID ONLY for these scopes, so an arbitrary domain is
* never stripped. Both are WCM-controlled domains, so allowlisting them adds no
* attack surface — only the proxy (federating these trusted upstreams) can
* assert an eppn scoped to them.
* - `nyp.org` — CONFIRMED from a live NYP assertion 2026-05-31.
* - `qatar-med.cornell.edu` — ANTICIPATED from WCM-Q's faculty email domain
* (facultyaffairs@qatar-med.cornell.edu); the proxy passes upstream eppn
* scopes through unchanged (NYP arrived as `@nyp.org`), and for NYP the
* email domain matched the eppn scope exactly. VERIFY against a live WCM-Q
* login and correct here if the real scope differs (until then a WCM-Q
* login simply no-ops this entry and fails closed — no security impact).
*/
const WCM_SAML_EPPN_TRUSTED_SCOPES = "nyp.org,qatar-med.cornell.edu";
/**
* The verified SES sender for the #160 Phase 2 "Request a change" server mailer.
* Shared by the task-role `ses:FromAddress` condition and the app `SCHOLARS_MAIL_
* FROM` env var so the IAM grant and the runtime From can never drift. Verifying
* this identity (DKIM CNAMEs) + leaving the SES sandbox are ops steps
* (docs/ses-sender-verification.md); the send stays dormant until then.
*/
const SCHOLARS_MAIL_FROM = "no-reply-scholars@weill.cornell.edu";
/** Props for {@link AppStack}. */
export interface AppStackProps extends StackProps {
/** Resolved per-environment configuration. */
readonly envConfig: SpsEnvConfig;
/** VPC every workload runs in (from NetworkStack). */
readonly vpc: ec2.IVpc;
}
/**
* AppStack — the compute and ingress plane (B05 + B06 + B09-CDK + B17).
*
* Stack 3 of the six in ADR-008. Provisions the ECR repo, the ECS Fargate
* cluster + service + task definitions, the public and internal ALBs, the
* task-execution / task / GitHub Actions deploy IAM roles, and the VPC
* endpoints the data plane uses to avoid NAT egress. Together these turn
* the running Next.js application into something AWS can actually serve
* behind a stable ALB DNS in account 665083158573.
*
* Scope deliberately clipped against the source spec (see
* `.planning/feat-infra-phase2-appstack.md § Scope clipping`):
*
* - B09 ships the CDK half only — the one-shot migration task definition
* and its log group. The deploy-workflow half (.github/workflows,
* PR template, CONTRIBUTING.md "no rollback" rule, scripts/backfills/)
* ships in a separate follow-on workstream paired with B12. Issue #108
* stays open after this row merges.
*
* - B17 places VPC endpoints in this stack rather than NetworkStack, where
* the NetworkStack header comment expects them. The COORDINATION row's
* OWNS column nails them to AppStack; touching the locked NetworkStack
* for a comment-only edit isn't worth a hot-fix workstream. The
* PRODUCTION_ADDENDUM § AppStack records the deviation from ADR-008
* Table 4.
*
* - The public ALB ships HTTP-only :80. The :443 listener + ACM cert +
* CloudFront origin-verify header check ship in B07+B14 (EdgeStack).
* Documented exposure window: one PR cycle; ALB DNS not published;
* SAML cookie's SameSite+Secure prevents it transmitting over HTTP.
*
* - The GitHub Actions OIDC deploy role is provisioned here even though
* the workflow that uses it ships in the B09/B12 follow-on. No cost; no
* functional risk; verifies the IAM scoping ahead of the workflow.
*
* Cross-stack handoff: secrets are looked up by name via
* `Secret.fromSecretNameV2(...)`. SecretsStack defines the secrets;
* AppStack reads only their ARNs. Same loose coupling NetworkStack ->
* DataStack uses; no `crossRegionReferences` needed for in-region lookups.
*/
export class AppStack extends Stack {
/** ECR repository the deploy pipeline pushes app images into. */
public readonly ecrRepository: ecr.Repository;
/**
* ECR repository for the ETL batch image (the `tsx`-based `etl/*` +
* `search:index` scripts). Kept separate from the standalone app repo so
* the two artifacts have independent lifecycle/scan and no `latest`
* collision; EtlStack pulls from here (#454).
*/
public readonly etlEcrRepository: ecr.Repository;
/** ECS Fargate cluster the app + migration tasks run in. */
public readonly ecsCluster: ecs.Cluster;
/** ECS service for the SPS application. */
public readonly ecsService: ecs.FargateService;
/** Family-only handle to the one-shot Prisma migration task definition. */
public readonly migrationTaskDefinition: ecs.FargateTaskDefinition;
public readonly dbBootstrapTaskDefinition: ecs.FargateTaskDefinition;
/** Family-only handle to the one-shot grant-equality verify task (ADR-009). */
public readonly verifyGrantsTaskDefinition: ecs.FargateTaskDefinition;
/**
* Family-only handle to the one-shot post-deploy search-eval canary task
* (#1444 remainder) — checks `scripts/search-eval/pins.json` against the
* just-deployed app, run in-VPC via `deploy.yml`'s existing OIDC role.
*/
public readonly searchEvalCanaryTaskDefinition: ecs.FargateTaskDefinition;
/** Public, internet-facing ALB. */
public readonly publicAlb: elbv2.ApplicationLoadBalancer;
/** Internal ALB — reachable only from inside the VPC. */
public readonly internalAlb: elbv2.ApplicationLoadBalancer;
/** Target group the public ALB forwards to; exposed for ObservabilityStack alarms. */
public readonly publicTargetGroup: elbv2.ApplicationTargetGroup;
/** App task CloudWatch log group; exposed for ObservabilityStack metric filters (B02 edit_authz_denied alarm). */
public readonly appLogGroup: logs.LogGroup;
/** GitHub Actions OIDC deploy role. */
public readonly deployRole: iam.Role;
/** ECS task role (application runtime identity). Exposed so AnalyticsStack can
* grant it workgroup-scoped Athena/Glue/S3 for the in-app Usage dashboard —
* the grant lives in AnalyticsStack (which owns the bucket + workgroup L2s),
* giving an Analytics→App dependency rather than importing the CFN-named
* analytics bucket into this stack. */
public readonly appTaskRole: iam.Role;
constructor(scope: Construct, id: string, props: AppStackProps) {
super(scope, id, props);
const { envConfig, vpc } = props;
const env = envConfig.envName;
// Item-3 pass 2a: import the app/etl/alb SGs by id from the SSM params
// NetworkStack publishes (pass 1) instead of the cross-stack handles — severs
// the SG `Ref` exports that would lock the useSharedVpc flip (the SGs replace
// onto the imported VPC). All uses below are `.securityGroupId` or a
// `securityGroup` reference, valid on an imported SG; the L1 id-keyed ingress
// rules survive the switch (map Q4).
const appSecurityGroup = resolveSharedSg(this, envConfig, "app", "AppSg");
const etlSecurityGroup = resolveSharedSg(this, envConfig, "etl", "EtlSg");
const albSecurityGroup = resolveSharedSg(this, envConfig, "alb", "AlbSg");
// Estate-consolidation subnet placement (plan §4.4): the app service +
// internal ALB (compute) land in the app2 tier, the optional public ALB in
// the dmz tier, when useSharedVpc is on; else the standalone Sps VPC's
// PRIVATE_WITH_EGRESS / PUBLIC tiers — byte-identical otherwise.
const appSubnets = resolveTierSubnets(this, envConfig, "app", "AppSubnet");
const albSubnets = resolveTierSubnets(this, envConfig, "alb", "PublicAlbSubnet");
// ------------------------------------------------------------------
// Secrets lookup. SecretsStack defines the full set; AppStack reads the
// twelve the app + sidecars consume (db read/write, opensearch app,
// revalidate token, session-cookie secret, SAML SP private key, ReciterDB
// connection, SAML IdP cert, SAML SP cert, db-bootstrap DSN, the New
// Relic ingest key consumed by the ADOT collector, and the read-only ED
// bind #1592). Looked up by name so the two
// stacks stay loosely coupled — no
// shared stack prop, no cross-stack export. ARNs feed both the
// task-execution role's tightly-scoped policy and the task definition's
// `secrets:` block.
// ------------------------------------------------------------------
const appRwSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"AppRwSecret",
`scholars/${env}/db/app-rw`,
);
const appRoSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"AppRoSecret",
`scholars/${env}/db/app-ro`,
);
// Least-privilege DSN for the one-shot sps-db-bootstrap task that provisions
// the scholars_audit database + the app-rw INSERT grant before migrate
// (#493). The sps_bootstrap user holds only CREATE/ALTER on scholars_audit.*
// and INSERT there WITH GRANT OPTION -- never master, nothing on `scholars`.
const bootstrapDsnSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"BootstrapDsnSecret",
`scholars/${env}/db/bootstrap`,
);
// Deploy-time-only migration DSN (ADR-009). The sps_migrate user holds the
// DDL on `scholars.*` that `prisma migrate deploy` needs; reducing app_rw to
// DML-only (Phase 3) leaves this as the only DDL-bearing credential, and it
// is injected ONLY into the one-shot migrate task -- never the 24/7 app. The
// "/migrate" tail (7 chars, no leading dash) sidesteps the Secrets Manager
// 6-char-tail partial-ARN gotcha. SecretsStack defines the stub; the
// DataStack seeder mints the user + populates this secret (Phase 1).
const migrateSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"MigrateSecret",
`scholars/${env}/db/migrate`,
);
const opensearchAppSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"OpensearchAppSecret",
`scholars/${env}/opensearch/app`,
);
// B07 CloudFront-to-ALB origin shared secret, referenced a second time
// here (as an ISecret rather than the SecretValue dynamic-ref used below
// for the ALB listener rule) so the search-eval canary task (#1444) can
// read it via its own dedicated, minimally-scoped execution role.
const originSharedSecretForCanary = secretsmanager.Secret.fromSecretNameV2(
this,
"OriginSharedSecretForCanary",
`scholars/${env}/edge/origin-shared-secret`,
);
const revalidateTokenSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"RevalidateTokenSecret",
`scholars/${env}/revalidate-token`,
);
const facultyReviewTokenSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"FacultyReviewTokenSecret",
`scholars/${env}/faculty-review-token`,
);
// Second, independent bearer for the same route -- Research Informatics
// (#2363), alongside the Faculty Review Tool's token above.
const researchInformaticsTokenSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"ResearchInformaticsTokenSecret",
`scholars/${env}/research-informatics-token`,
);
// SSO session-cookie encryption key (#100). getSessionConfig() requireEnv's
// SESSION_COOKIE_SECRET; the middleware gate and the SAML callback both read
// it, so without it the callback 500s minting the session (the gap sibling
// to the SAML_* env wiring, #466).
//
// Name is "-key", not "-secret": fromSecretNameV2 injects the *suffix-less*
// ARN into the task def's `secrets:` block, and a name ending in a 6-char
// token (like "secret") collides with the Secrets Manager random-suffix
// heuristic, making that ARN unresolvable -> GetSecretValue AccessDenied at
// task start. See SecretsStack + docs/466-saml-deploy-debrief.md.
const sessionCookieSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"SessionCookieSecret",
`scholars/${env}/session-cookie-key`,
);
const samlSpPrivateKeySecret = secretsmanager.Secret.fromSecretNameV2(
this,
"SamlSpPrivateKeySecret",
`scholars/saml-sp/${env}/private-key`,
);
// ReciterDB connection (RePORTER funding + mentoring surfaces). The app
// reads SCHOLARS_RECITERDB_* at request time; same secret + JSON keys the
// ETL task already consumes (#442). Without this the reciter-backed page
// sections fail at render and error-boundary out (#460 follow-on).
const etlReciterSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"EtlReciterSecret",
`scholars/${env}/etl/reciter`,
);
// SAML IdP signing cert — the trust anchor for assertion-signature
// verification (#466). Injected as SAML_IDP_CERT; a secret (not env) so
// the 2026-08-19 IdP cert rollover is a value rotation, not a code
// deploy. SecretsStack defines the stub; seed both rollover PEMs
// concatenated out-of-band.
const samlIdpCertSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"SamlIdpCertSecret",
`scholars/${env}/saml/idp-cert`,
);
// SP public cert — published in SP metadata (#466). node-saml's
// generateServiceProviderMetadata throws when the SP private key is set
// but no public cert is supplied, so /api/auth/saml/metadata 503s without
// this. Injected as SAML_SP_CERT; the value is public but provisioned
// out-of-band like its paired private key.
const samlSpCertSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"SamlSpCertSecret",
`scholars/saml-sp/${env}/cert`,
);
// New Relic ingest license key (B24 observability). Injected into the ADOT
// collector sidecar (NOT the app container) as NEW_RELIC_LICENSE_KEY and
// read by otel-collector-config.yaml's otlphttp/newrelic exporter via
// ${env:...}. The "-key" tail (3 chars) sidesteps the Secrets Manager
// 6-char-tail partial-ARN gotcha. SecretsStack defines the stub.
const newRelicLicenseKeySecret = secretsmanager.Secret.fromSecretNameV2(
this,
"NewRelicLicenseKeySecret",
`scholars/${env}/newrelic-license-key`,
);
// Read-only WCM Enterprise Directory (ED) bind (#1592, #1595). The SAME
// secret + JSON keys the nightly ETL consumes (cdk/lib/etl-stack.ts
// "EtlSecretEd"): SCHOLARS_LDAP_URL / _BIND_DN / _BIND_PASSWORD. The app
// injects these so lib/sources/ldap.ts openLdap() can bind for the
// SSO-gated GET /api/directory/people — both of its modes: `?cwids=`
// (unit-access-card CWID→name/title hydration) and `?q=` (the Add-admin
// DirectoryPeopleTypeahead). Without them openLdap() throws
// "SCHOLARS_LDAP_URL is not set" and BOTH surfaces fail closed.
// Read-only bind, no DDL. The "/ed" tail (2 chars) is clear of the Secrets
// Manager 6-char-tail partial-ARN gotcha.
//
// Deliberately does NOT activate the other openLdap() consumers: all three
// role checks (superuser, comms_steward, development) short-circuit on an
// empty/unset *_GROUP_CN before reaching openLdap(). See the role-flag block
// below — SCHOLARS_DEVELOPMENT_GROUP_CN is pinned "" for exactly this reason.
// ponytail: reuses the ETL's ED bind account instead of a distinct app-
// scoped read-only bind. Ceiling: the 24/7 app's larger RCE window now
// shares the SOR-critical ETL credential -- prefer a separate ED service
// account for prod (ADR-009 exposure-window logic) when one is cheap to get.
const edSecret = secretsmanager.Secret.fromSecretNameV2(
this,
"AppEtlEdSecret",
`scholars/${env}/etl/ed`,
);
// ADR-009 exec-role split -- two execution roles, two secret-ARN lists:
//
// - appConsumerSecretArns: what the 24/7 app TASK consumes (app container +
// ADOT sidecar). This is the app task-execution role's
// `secretsmanager:GetSecretValue` resource list -- exactly these, no `*`,
// and crucially NOT the migrate DSN (req 4: the DDL-capable migrate
// credential must never be readable by the internet-adjacent app role).
// `bootstrap` is also gone -- it moved to the deploy role with the
// db-bootstrap task, so the app role sheds a grant it never used.
// - deployConsumerSecretArns: what the deploy-time tasks (migrate,
// verify-grants, db-bootstrap) consume, on a separate short-lived
// execution role. The migrate DSN lives ONLY here.
//
// Both lists are asserted in app-stack.test.ts.
const appConsumerSecretArns: string[] = [
appRwSecret.secretArn,
appRoSecret.secretArn,
opensearchAppSecret.secretArn,
revalidateTokenSecret.secretArn,
samlSpPrivateKeySecret.secretArn,
etlReciterSecret.secretArn,
samlIdpCertSecret.secretArn,
samlSpCertSecret.secretArn,
sessionCookieSecret.secretArn,
// New Relic ingest key (B24): consumed by the ADOT collector sidecar,
// not the app container. Execution role still needs GetSecretValue on it.
newRelicLicenseKeySecret.secretArn,
// Read-only ED bind (#1592, #1595): the app task-execution role must
// GetSecretValue on the ED secret to inject SCHOLARS_LDAP_* into the app
// container (the SSO-gated /api/directory/people directory route).
// Read-only bind, no DDL -- same class as the other app-consumer secrets
// (ADR-009: still no migrate, no bootstrap). Lands on the EXECUTION role
// only; the task role keeps zero secretsmanager:* (asserted in tests).
edSecret.secretArn,
];
// The deploy-time tasks' DSNs (ADR-009). migrate injects only the migrate
// DSN; verify-grants injects all four role DSNs; db-bootstrap injects
// bootstrap + app-rw. The union is these four -- and the migrate DSN appears
// on no other execution role (req 4, asserted).
const deployConsumerSecretArns: string[] = [
appRoSecret.secretArn,
appRwSecret.secretArn,
bootstrapDsnSecret.secretArn,
migrateSecret.secretArn,
];
// ------------------------------------------------------------------
// ECR repository.
//
// Image-scan-on-push catches CVEs before a deploy ramps; the lifecycle
// policy keeps the last 30 tagged images (enough to bisect any recent
// regression) and expires untagged images after 7 d so failed/canceled
// builds don't accumulate.
// ------------------------------------------------------------------
this.ecrRepository = new ecr.Repository(this, "EcrRepository", {
repositoryName: `scholars-app-${env}`,
imageScanOnPush: true,
lifecycleRules: [
{
description: "Keep the last 30 tagged images",
tagStatus: ecr.TagStatus.TAGGED,
tagPatternList: ["*"],
maxImageCount: 30,
},
{
description: "Expire untagged images after 7 days",
tagStatus: ecr.TagStatus.UNTAGGED,
maxImageAge: Duration.days(7),
},
],
removalPolicy: RemovalPolicy.RETAIN,
});
// Dedicated ETL batch-image repo (#454). Same scan + lifecycle posture
// as the app repo, but a separate repository so ETL images don't share
// the app repo's 30-tag retention window or its `latest` tag. EtlStack
// pulls from here; the deploy workflow builds `--target etl` and pushes.
this.etlEcrRepository = new ecr.Repository(this, "EtlEcrRepository", {
repositoryName: `scholars-etl-${env}`,
imageScanOnPush: true,
lifecycleRules: [
{
description: "Keep the last 30 tagged images",
tagStatus: ecr.TagStatus.TAGGED,
tagPatternList: ["*"],
maxImageCount: 30,
},
{
description: "Expire untagged images after 7 days",
tagStatus: ecr.TagStatus.UNTAGGED,
maxImageAge: Duration.days(7),
},
],
removalPolicy: RemovalPolicy.RETAIN,
});
// Transitional cross-stack-export retention (#454 follow-up). EtlStack used
// to consume the app repo's ARN + name as auto-generated cross-stack
// exports; PR #455 repointed it to the dedicated ETL repo, so CDK would now
// drop those two exports. CloudFormation refuses to delete an export still
// imported by another stack, and the *currently deployed* EtlStack still
// imports them -- so an App-stack update that removes them rolls back. Pin
// them with the same auto-generated names for the transition deploy (App
// adds the ETL repo + its exports while keeping these; then EtlStack
// redeploys onto the ETL repo and stops importing them). Remove these two
// lines in a cleanup once every env's Sps-Etl-* no longer imports them.
this.exportValue(this.ecrRepository.repositoryArn);
this.exportValue(this.ecrRepository.repositoryName);
// ------------------------------------------------------------------
// CloudWatch log groups.
//
// One per task family. Retention divergence (30 d staging, 90 d prod)
// is set per env config implicitly via the AppStack-derived value —
// we use a single field that depends on env name. Both log groups are
// env-prefixed so they survive the single-account staging+prod split
// (Footgun #4).
// ------------------------------------------------------------------
const logRetention =
env === "prod" ? logs.RetentionDays.THREE_MONTHS : logs.RetentionDays.ONE_MONTH;
const appLogGroup = new logs.LogGroup(this, "AppLogGroup", {
logGroupName: `/aws/ecs/sps-app-${env}`,
retention: logRetention,
removalPolicy: RemovalPolicy.RETAIN,
});
this.appLogGroup = appLogGroup;
const migrationLogGroup = new logs.LogGroup(this, "MigrationLogGroup", {
logGroupName: `/aws/ecs/sps-migrate-${env}`,
retention: logRetention,
removalPolicy: RemovalPolicy.RETAIN,
});
// db-bootstrap task log group (#493) — distinct stream from migrate so the
// audit-provisioning output is visibly separate in CloudWatch.
const dbBootstrapLogGroup = new logs.LogGroup(this, "DbBootstrapLogGroup", {
logGroupName: `/aws/ecs/sps-db-bootstrap-${env}`,
retention: logRetention,
removalPolicy: RemovalPolicy.RETAIN,
});
// grant-equality verify task log group (ADR-009 Phase 0) — distinct stream
// so the per-role SHOW GRANTS diff output is separable from db-bootstrap.
const verifyGrantsLogGroup = new logs.LogGroup(this, "VerifyGrantsLogGroup", {
logGroupName: `/aws/ecs/sps-verify-grants-${env}`,
retention: logRetention,
removalPolicy: RemovalPolicy.RETAIN,
});
// Post-deploy search-eval canary task log group (#1444 remainder) — its
// own stream, distinct from the DB-role deploy tasks above (this one
// never touches the database at all).
const searchEvalCanaryLogGroup = new logs.LogGroup(this, "SearchEvalCanaryLogGroup", {
logGroupName: `/aws/ecs/sps-search-eval-canary-${env}`,
retention: logRetention,
removalPolicy: RemovalPolicy.RETAIN,
});
// ADOT collector sidecar log group (B24). Same retention as the app log
// group; env-prefixed per Footgun #4. Created here -- not in
// ObservabilityStack -- because the sidecar lives inside the AppStack
// task definition and its log driver references this group.
const otelLogGroup = new logs.LogGroup(this, "OtelCollectorLogGroup", {
logGroupName: `/aws/ecs/sps-otel-${env}`,
retention: logRetention,
removalPolicy: RemovalPolicy.RETAIN,
});
// ------------------------------------------------------------------
// IAM role split (B06).
//
// - **Task-execution role** (`taskExecutionRole`) is the role ECS assumes
// for the 24/7 APP task to pull the image, inject secrets, and write log
// streams. Tightly scoped: ECR auth + Batch* on the app repo only;
// secrets:GetSecretValue on the eleven app consumer ARNs only (ADR-009: no
// migrate, no bootstrap) -- the eleventh is the read-only ED bind secret
// (#1592) the app injects for the SSO-gated /api/directory/people route;
// logs on the app + ADOT-sidecar groups only.
// - **Deploy execution role** (`deployTaskExecutionRole`, ADR-009) is the
// parallel role for the short-lived deploy-time tasks (migrate,
// verify-grants, db-bootstrap). It -- and only it -- can read the migrate
// DSN, keeping the DDL-capable credential off the internet-adjacent app
// role (req 4). No `*` resource on either beyond ecr:GetAuthorizationToken.
// - **Task role** is the role the *application code* runs as. The
// running Next.js + Prisma code does not call any AWS API today;
// the task role therefore has zero attached permissions. Secrets
// are passed in by ECS via the execution role, not assumed at
// runtime — this is the documented PRODUCTION_ADDENDUM § Secrets
// pattern. Asserting "task role has zero secretsmanager:*" is the
// regression guard: any future PR that smuggles a secrets:Get*
// onto the task role goes through review.
// ------------------------------------------------------------------
const taskExecutionRole = new iam.Role(this, "TaskExecutionRole", {
roleName: `sps-task-exec-${env}`,
assumedBy: new iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
description: `SPS ECS task-execution role (${env}). Pulls images, injects secrets, writes logs.`,
});
// ECR. GetAuthorizationToken is an account-level action with no
// resource scope; everything else is scoped to the SPS repo.
taskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["ecr:GetAuthorizationToken"],
resources: ["*"],
}),
);
taskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
],
resources: [this.ecrRepository.repositoryArn],
}),
);
// Secrets -- exactly the eleven app consumer ARNs (ADR-009 split: no migrate,
// no bootstrap). Asserted in tests.
taskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["secretsmanager:GetSecretValue"],
resources: appConsumerSecretArns,
}),
);
// Logs -- the app task's own groups only (app container + ADOT sidecar).
// ADR-009: the migrate / db-bootstrap / verify-grants groups moved to the
// deploy execution role with their tasks. (awsLogs() also auto-grants the
// driving execution role write on each group; this explicit block is the
// documented, asserted scope.)
taskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["logs:CreateLogStream", "logs:PutLogEvents"],
resources: [
appLogGroup.logGroupArn,
`${appLogGroup.logGroupArn}:*`,
otelLogGroup.logGroupArn,
`${otelLogGroup.logGroupArn}:*`,
],
}),
);
// ------------------------------------------------------------------
// Deploy-time execution role (ADR-009 exec-role split).
//
// The migrate / verify-grants / db-bootstrap tasks run for seconds during a
// deploy, not 24/7. They get their OWN execution role so the migrate DSN --
// which carries `scholars.*` DDL -- is injectable into them and ONLY them.
// The app role (above) deliberately lacks it (req 4): a runtime compromise
// of the internet-adjacent app cannot even read the DDL-capable credential.
//
// Same shape as the app role: ECR auth + Batch* on BOTH repos (migrate runs
// the app image; db-bootstrap + verify-grants run the ETL image),
// GetSecretValue on the four deploy ARNs only, logs on the three deploy
// groups only. fromEcrRepository()/awsLogs() also auto-grant these; the
// explicit blocks are the documented, asserted least-privilege contract.
// ------------------------------------------------------------------
const deployTaskExecutionRole = new iam.Role(this, "DeployExecutionRole", {
roleName: `sps-deploy-exec-${env}`,
assumedBy: new iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
description: `SPS ECS deploy-time task-execution role (${env}). Migrate/verify/db-bootstrap only; the sole reader of the migrate DSN.`,
});
deployTaskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["ecr:GetAuthorizationToken"],
resources: ["*"],
}),
);
deployTaskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
],
resources: [this.ecrRepository.repositoryArn, this.etlEcrRepository.repositoryArn],
}),
);
// Secrets -- exactly the four deploy ARNs (incl. the migrate DSN, which is
// on no other role). Asserted in tests.
deployTaskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["secretsmanager:GetSecretValue"],
resources: deployConsumerSecretArns,
}),
);
// Logs -- the three deploy-task groups + their streams.
deployTaskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["logs:CreateLogStream", "logs:PutLogEvents"],
resources: [
migrationLogGroup.logGroupArn,
`${migrationLogGroup.logGroupArn}:*`,
dbBootstrapLogGroup.logGroupArn,
`${dbBootstrapLogGroup.logGroupArn}:*`,
verifyGrantsLogGroup.logGroupArn,
`${verifyGrantsLogGroup.logGroupArn}:*`,
],
}),
);
// ------------------------------------------------------------------
// search-eval canary execution role (#1444 remainder).
//
// A DEDICATED role, not a reuse of `deployTaskExecutionRole` above: that
// role's `secretsmanager:GetSecretValue` resource list is asserted to be
// exactly the four DB DSNs (ADR-009, app-stack.test.ts) — adding the
// origin-verify secret to it would both break that assertion and hand
// migrate/db-bootstrap/verify-grants a secret none of them need. This
// role reads ONLY the origin-verify shared secret and nothing else — no
// DB DSN reaches it, ever.
// ------------------------------------------------------------------
const canaryTaskExecutionRole = new iam.Role(this, "SearchEvalCanaryExecutionRole", {
roleName: `sps-search-eval-canary-exec-${env}`,
assumedBy: new iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
description: `SPS search-eval canary task-execution role (${env}). Reads only the origin-verify shared secret -- no DB DSNs (#1444).`,
});
canaryTaskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["ecr:GetAuthorizationToken"],
resources: ["*"],
}),
);
canaryTaskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
],
// Only the ETL repo -- the canary runs scripts/search-eval/canary.ts
// on the ETL image (the only one carrying tsx + the source tree).
resources: [this.etlEcrRepository.repositoryArn],
}),
);
canaryTaskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["secretsmanager:GetSecretValue"],
resources: [originSharedSecretForCanary.secretArn],
}),
);
canaryTaskExecutionRole.addToPolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["logs:CreateLogStream", "logs:PutLogEvents"],
resources: [
searchEvalCanaryLogGroup.logGroupArn,
`${searchEvalCanaryLogGroup.logGroupArn}:*`,
],
}),
);
const taskRole = new iam.Role(this, "TaskRole", {
roleName: `sps-task-${env}`,
assumedBy: new iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
description: `SPS ECS task role (${env}). Application runtime identity; X-Ray write only.`,
});
this.appTaskRole = taskRole;
// ------------------------------------------------------------------
// Shared ISR cache bucket (#1503).
//
// Backs the S3 `cacheHandler` (lib/cache/s3-cache-handler.js) that lets all
// 2–6 app tasks share one incremental-cache store, so `revalidatePath` on
// one task can't be undone by the edge refilling a stale copy from another.
// Private, SSE-S3, TLS-only; objects self-expire after 7 days (the cache is
// derived + disposable, so lifecycle is the only cleanup). Provisioned in
// every env but INERT until NEXT_ISR_CACHE_S3="on" flips the handler on —
// so enabling the feature is a flag flip, not an infra race. RETAIN matches
// the house style for every other bucket in this account.
const isrCacheBucket = new s3.Bucket(this, "IsrCacheBucket", {
encryption: s3.BucketEncryption.S3_MANAGED,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
removalPolicy: RemovalPolicy.RETAIN,
lifecycleRules: [
{ id: "expire-isr-cache", prefix: "next-isr-cache/", expiration: Duration.days(7) },
],
});
// Scoped to the app's prefix only: object CRUD on next-isr-cache/* plus
// ListBucket (the handler never touches anything else).
isrCacheBucket.grantReadWrite(taskRole, "next-isr-cache/*");
// ------------------------------------------------------------------
// X-Ray write grant (B24).
//
// The ADOT collector sidecar (added to the task definition below)
// runs under this task role and posts trace segments + telemetry
// records to X-Ray. Granted as a custom *inline* policy with exactly
// two actions, not the managed AWSXRayDaemonWriteAccess. Inline
// because:
// - The managed policy lists more than these two actions; pinning
// to two keeps the surface auditable + immunizes us against AWS
// quietly expanding the managed document later.
// - Inline documents intent in this stack rather than
// "AWS-controlled, see the console".
//
// Both actions are account-level on X-Ray and only accept
// Resource: *. The existing "task role has zero secretsmanager:*"
// assertion in app-stack.test.ts continues to hold -- the policy
// below contains neither secretsmanager nor managed-policy
// references. The plan adds the matching assertions ("exactly two
// action statements", "zero managed policies on the task role")
// in app-stack.test.ts.
// ------------------------------------------------------------------
new iam.Policy(this, "TaskRoleXrayPolicy", {
policyName: `sps-task-${env}-xray`,
roles: [taskRole],
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["xray:PutTraceSegments"],
resources: ["*"],
}),
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["xray:PutTelemetryRecords"],
resources: ["*"],
}),
],
});
// ------------------------------------------------------------------
// SES send grant (#160 Phase 2 -- "Request a change" server mailer).
//
// POST /api/edit/request-change sends one email to the office that owns
// the data. A custom *inline* policy with the single action ses:SendEmail,
// scoped by an `ses:FromAddress` condition to exactly the no-reply sender.
// Conditioning on the From (not just the identity ARN) is tighter and is
// independent of whether the sender is later verified as an email or a
// domain identity. Resource stays SES-identity-scoped -- never a bare `*`.
//
// Dormant until SELF_EDIT_REQUEST_CHANGE_SEND=on (the env var below ships
// "off") AND the identity is verified + the account is out of the SES
// sandbox (ops -- docs/ses-sender-verification.md). No EmailIdentity
// construct: a no-reply mailbox can't complete email-link verification, and
// the real path is a DKIM/domain identity owned in WCM DNS, so the resource
// is granted by ARN pattern + From condition and verified out-of-band.
//
// Contains no secretsmanager reference, so the "zero secretsmanager on the
// task role" assertion still holds; app-stack.test.ts adds the SES-scope
// assertions (single action, From condition, identity-scoped resource).
// ------------------------------------------------------------------
new iam.Policy(this, "TaskRoleSesPolicy", {
policyName: `sps-task-${env}-ses`,
roles: [taskRole],
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["ses:SendEmail"],
resources: [`arn:aws:ses:${this.region}:${this.account}:identity/*`],
conditions: {
StringEquals: { "ses:FromAddress": SCHOLARS_MAIL_FROM },
},
}),
],
});
// ------------------------------------------------------------------
// Bedrock InvokeModel grant (#742 -- overview-statement generator).
//
// The app container calls Claude on Amazon Bedrock to draft faculty
// overview statements (lib/edit/overview-generator.ts, via the AI SDK
// @ai-sdk/amazon-bedrock provider with fromNodeProviderChain()). The
// provider resolves THIS task role at runtime -- institutional AWS
// billing, no API key, no secret to seed. A custom *inline* policy with
// the single action bedrock:InvokeModel (the generator uses generateText,
// not streaming, so no InvokeModelWithResponseStream).
//
// Scoped to the Claude Opus 4.8 and Sonnet 4.x families, NOT a bare `*`:
// - the us. cross-region INFERENCE PROFILE the model id resolves to
// (account-scoped), and
// - the underlying FOUNDATION MODELs (AWS-owned, empty account field)
// the profile routes to.
// Opus 4.8 is now the DEFAULT generate model and is granted here. Sonnet
// stays granted because the verify/revise critic pass and the
// OVERVIEW_GENERATE_MODEL rollback lever still run on Sonnet.
// Region is `*` because a us. inference-profile call fans out across the
// US regions (us-east-1/-2, us-west-2); the family wildcards let an
// intra-family bump (e.g. Sonnet 4.5 -> 4.6) via OVERVIEW_GENERATE_MODEL
// skip an IAM change while still excluding Haiku and every non-Anthropic
// provider. Contains no secretsmanager reference, so the "zero
// secretsmanager on the task role" assertion still holds.
// ------------------------------------------------------------------
new iam.Policy(this, "TaskRoleBedrockPolicy", {
policyName: `sps-task-${env}-bedrock`,
roles: [taskRole],
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["bedrock:InvokeModel"],
resources: [
`arn:aws:bedrock:*:${this.account}:inference-profile/us.anthropic.claude-opus-4-8*`,
"arn:aws:bedrock:*::foundation-model/anthropic.claude-opus-4-8*",
`arn:aws:bedrock:*:${this.account}:inference-profile/us.anthropic.claude-sonnet-4-*`,
"arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-4-*",
],
}),
],
});
// ------------------------------------------------------------------
// CloudFront CreateInvalidation grant (#353 -- synchronous edge purge).
//
// The suppress / rename / revoke write paths call
// sendCloudFrontInvalidation (lib/edit/revalidation.ts) inline post-commit
// to purge the edge copy of the affected page (ADR-005 layer 1). That SDK
// call runs under THIS task role and, once SCHOLARS_CLOUDFRONT_DISTRIBUTION_ID
// is set, would AccessDenied without an explicit grant. A custom *inline*
// policy with the single action cloudfront:CreateInvalidation, scoped to a
// distribution ARN -- never a bare `*` -- the same scope the EtlStack
// background-reconciler task role (#353 PR-2) carries. CloudFront is global,
// so the ARN has no region segment.
//
// Dormant until SCHOLARS_CLOUDFRONT_DISTRIBUTION_ID is set: the invalidation
// helper no-ops while it is unset, so the grant sits unused pre-launch.
// Contains no secretsmanager reference, so the "zero secretsmanager on the
// task role" assertion still holds; app-stack.test.ts adds the CloudFront-
// scope assertions (single action, distribution-scoped resource, no `*`).
// ------------------------------------------------------------------
new iam.Policy(this, "TaskRoleCloudFrontPolicy", {
policyName: `sps-task-${env}-cloudfront`,
roles: [taskRole],
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["cloudfront:CreateInvalidation"],
resources: [`arn:aws:cloudfront::${this.account}:distribution/*`],
}),
],
});
// ------------------------------------------------------------------
// ReCiter read grant (#746 -- live "suggested articles" nudge).
//
// GET /api/edit/reciter-pending reads the self viewer's live ReCiter
// candidate publications DIRECTLY from ReCiter's own DynamoDB + S3 (no
// engine HTTP round-trip, no api-key): the GoldStandard table (the fresh
// accept/reject sets) + the Analysis table (the scored candidate list),
// falling back to s3://reciter-dynamodb/AnalysisOutput/<uid> when the
// analysis is offloaded. lib/reciter/client.ts fetchSuggestedArticles
// resolves THIS task role via the AWS SDK default chain -- institutional
// AWS, no secret to seed.
//
// A custom *inline* policy, least-privilege:
// - dynamodb:GetItem ONLY (a keyed GetItem on uid -- never Scan/Query),
// scoped to exactly the Analysis + GoldStandard tables (these are the
// account-shared ReCiter stores, NOT region/account-tokenized like the
// SPS tables, so the ARNs are pinned to us-east-1 / 665083158573 where
// ReCiter runs).
// - s3:GetObject ONLY, scoped to the AnalysisOutput/* prefix of the
// reciter-dynamodb bucket -- never a bare `*`.
// - kms:Decrypt ONLY, scoped to the single CMK that SSE-KMS-encrypts the
// reciter-dynamodb bucket. The offloaded AnalysisOutput/<uid> objects
// are encrypted with this key, so s3:GetObject ALONE returns
// AccessDenied on a prolific scholar (whose analysis is offloaded) --
// the read then silently degrades to [] and the nudge shows nothing.
// The key policy delegates to the account root (no condition), so this
// IAM grant is sufficient; the key's broad `Principal:*` Decrypt is
// conditioned to kms:ViaService=rds and does NOT cover S3 reads.
//
// Read-only by construction; the #746 reject WRITE path is the engine HTTP
// call gated separately. Contains no secretsmanager reference, so the "zero
// secretsmanager on the task role" assertion still holds; app-stack.test.ts
// adds the matching scope assertions.
// ------------------------------------------------------------------
new iam.Policy(this, "TaskRoleReciterReadPolicy", {
policyName: `sps-task-${env}-reciter-read`,
roles: [taskRole],
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["dynamodb:GetItem"],
resources: [
"arn:aws:dynamodb:us-east-1:665083158573:table/Analysis",
"arn:aws:dynamodb:us-east-1:665083158573:table/GoldStandard",
],
}),
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["s3:GetObject"],
resources: ["arn:aws:s3:::reciter-dynamodb/AnalysisOutput/*"],
}),
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["kms:Decrypt"],
resources: [
"arn:aws:kms:us-east-1:665083158573:key/6b9d182c-8abc-48a0-ac90-7c47b55c829a",
],
}),
],
});
// ------------------------------------------------------------------
// #1163 cores claim writeback -- SPS's FIRST DynamoDB *write*.
//
// When a core owner confirms/rejects a publication's core-facility usage in
// the /edit/core/[coreId] review queue, lib/cores/claim-writeback.ts mirrors
// that status onto the engine's item in the shared `reciterai` table
// (PK PUB#{pmid} / SK CORE#{coreId}) so the next pipeline_cores run sees the
// human decision. SPS `core_claim` stays the authoritative store and the
// read-merge wins regardless, so a missing/denied grant only no-ops the
// mirror (best-effort, non-throwing).
//
// A custom *inline* policy, least-privilege:
// - dynamodb:UpdateItem ONLY (the single UpdateCommand the writeback
// issues -- both create-on-first-write and update; never
// Put/Delete/BatchWrite/Scan), scoped to exactly table/reciterai. NOT
// table.grantWriteData(), which would over-grant Put/Delete/BatchWrite.
// - the same `${this.region}/${this.account}` reciterai ARN as the ETL
// read grant (EtlTaskRoleReciterAiPolicy, etl-stack.ts) -- the reciterai
// store is account-shared in THIS account. OPERATOR: if a future env
// hosts reciterai cross-account, this ARN needs a cross-account
// assume-role (same caveat as the ETL grant).
//
// Gated in code by CORE_CLAIM_WRITEBACK (default off; staging-first in the
// environment block below), so this grant can land ahead of go-live and a
// single `cdk deploy` brings grant + flag up together (no flip-before-grant
// window). Contains no secretsmanager reference, so the "zero secretsmanager
// on the task role" assertion still holds; app-stack.test.ts adds the
// matching scope assertion.
// ------------------------------------------------------------------
new iam.Policy(this, "TaskRoleCoreClaimWritebackPolicy", {
policyName: `sps-task-${env}-reciterai-writeback`,
roles: [taskRole],
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["dynamodb:UpdateItem"],
resources: [`arn:aws:dynamodb:${this.region}:${this.account}:table/reciterai`],
}),
],
});
// ------------------------------------------------------------------