@ericminassian/platform-engine 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/clients.d.ts +8 -0
  2. package/dist/clients.js +22 -1
  3. package/dist/clients.js.map +1 -1
  4. package/dist/compat.d.ts +21 -9
  5. package/dist/compat.js +27 -7
  6. package/dist/compat.js.map +1 -1
  7. package/dist/drivers/appsync.d.ts +49 -0
  8. package/dist/drivers/appsync.js +155 -0
  9. package/dist/drivers/appsync.js.map +1 -0
  10. package/dist/drivers/ecr.d.ts +109 -0
  11. package/dist/drivers/ecr.js +303 -0
  12. package/dist/drivers/ecr.js.map +1 -0
  13. package/dist/drivers/ecs.d.ts +163 -0
  14. package/dist/drivers/ecs.js +447 -0
  15. package/dist/drivers/ecs.js.map +1 -0
  16. package/dist/drivers/events.d.ts +10 -0
  17. package/dist/drivers/events.js +13 -1
  18. package/dist/drivers/events.js.map +1 -1
  19. package/dist/drivers/index.d.ts +5 -0
  20. package/dist/drivers/index.js +5 -0
  21. package/dist/drivers/index.js.map +1 -1
  22. package/dist/drivers/kvs.d.ts +3 -0
  23. package/dist/drivers/kvs.js +14 -7
  24. package/dist/drivers/kvs.js.map +1 -1
  25. package/dist/drivers/lambda.d.ts +22 -0
  26. package/dist/drivers/lambda.js +74 -3
  27. package/dist/drivers/lambda.js.map +1 -1
  28. package/dist/drivers/request-function.d.ts +60 -0
  29. package/dist/drivers/request-function.js +167 -0
  30. package/dist/drivers/request-function.js.map +1 -0
  31. package/dist/drivers/s3.d.ts +5 -0
  32. package/dist/drivers/s3.js +26 -0
  33. package/dist/drivers/s3.js.map +1 -1
  34. package/dist/drivers/scheduler.d.ts +24 -0
  35. package/dist/drivers/scheduler.js +60 -5
  36. package/dist/drivers/scheduler.js.map +1 -1
  37. package/dist/drivers/ses.d.ts +77 -0
  38. package/dist/drivers/ses.js +181 -0
  39. package/dist/drivers/ses.js.map +1 -0
  40. package/dist/drivers/sqs.d.ts +11 -0
  41. package/dist/drivers/sqs.js +67 -1
  42. package/dist/drivers/sqs.js.map +1 -1
  43. package/dist/drivers/web-function.d.ts +11 -3
  44. package/dist/drivers/web-function.js +22 -5
  45. package/dist/drivers/web-function.js.map +1 -1
  46. package/dist/emulator.js.map +1 -1
  47. package/dist/images.d.ts +104 -0
  48. package/dist/images.js +182 -0
  49. package/dist/images.js.map +1 -0
  50. package/dist/index.d.ts +130 -6
  51. package/dist/index.js +11 -2
  52. package/dist/index.js.map +1 -1
  53. package/dist/local.js +222 -7
  54. package/dist/local.js.map +1 -1
  55. package/dist/policy.d.ts +47 -4
  56. package/dist/policy.js +365 -13
  57. package/dist/policy.js.map +1 -1
  58. package/dist/services.d.ts +155 -0
  59. package/dist/services.js +464 -0
  60. package/dist/services.js.map +1 -0
  61. package/dist/stage.d.ts +33 -8
  62. package/dist/stage.js +598 -124
  63. package/dist/stage.js.map +1 -1
  64. package/dist/static.d.ts +1 -1
  65. package/dist/static.js +2 -36
  66. package/dist/static.js.map +1 -1
  67. package/dist/util.d.ts +22 -0
  68. package/dist/util.js +18 -2
  69. package/dist/util.js.map +1 -1
  70. package/package.json +20 -14
  71. package/src/clients.ts +25 -1
  72. package/src/compat.ts +34 -11
  73. package/src/drivers/appsync.ts +220 -0
  74. package/src/drivers/ecr.ts +457 -0
  75. package/src/drivers/ecs.ts +661 -0
  76. package/src/drivers/events.ts +29 -2
  77. package/src/drivers/index.ts +5 -0
  78. package/src/drivers/kvs.ts +21 -12
  79. package/src/drivers/lambda.ts +103 -2
  80. package/src/drivers/request-function.ts +295 -0
  81. package/src/drivers/s3.ts +38 -0
  82. package/src/drivers/scheduler.ts +88 -5
  83. package/src/drivers/ses.ts +267 -0
  84. package/src/drivers/sqs.ts +95 -0
  85. package/src/drivers/web-function.ts +29 -9
  86. package/src/emulator.ts +3 -3
  87. package/src/images.ts +254 -0
  88. package/src/index.ts +129 -7
  89. package/src/local.ts +251 -7
  90. package/src/policy.ts +446 -24
  91. package/src/services.ts +663 -0
  92. package/src/stage.ts +753 -139
  93. package/src/static.ts +2 -37
  94. package/src/util.ts +38 -4
package/src/policy.ts CHANGED
@@ -1,9 +1,15 @@
1
1
  import {
2
+ type EmailRuntimeConfig,
3
+ emailFromAddress,
4
+ type ContainersRuntimeConfig,
2
5
  IAM_APP_PATH,
3
6
  names,
7
+ ownFunctionHandlers,
4
8
  type PlatformRuntimeConfig,
5
9
  platformNames,
10
+ publicStores,
6
11
  type ResolvedManifest,
12
+ telemetryKeys,
7
13
  } from '@ericminassian/platform-core';
8
14
  import { type PolicyDocument, type PolicyStatement, policy } from './util.ts';
9
15
 
@@ -13,14 +19,37 @@ export interface StagePolicyInput {
13
19
  region: string;
14
20
  accountId: string;
15
21
  manifest: ResolvedManifest;
16
- platform: Pick<PlatformRuntimeConfig, 'storageBucket'>;
22
+ platform: Pick<PlatformRuntimeConfig, 'storageBucket' | 'telemetryTable' | 'realtime' | 'email'>;
17
23
  }
18
24
 
19
- /** Trust for per-stage roles: the worker and Web Function (Lambda) and schedules (Scheduler). */
25
+ /** A channel namespace's ARN in the platform's Event API. */
26
+ export function channelNamespaceArn(
27
+ region: string,
28
+ accountId: string,
29
+ apiId: string,
30
+ namespace: string,
31
+ ): string {
32
+ return `arn:aws:appsync:${region}:${accountId}:apis/${apiId}/channelNamespace/${namespace}`;
33
+ }
34
+
35
+ /** An SES configuration set's ARN (each stage's is `names.emailTenant`). */
36
+ export function configurationSetArn(region: string, accountId: string, name: string): string {
37
+ return `arn:aws:ses:${region}:${accountId}:configuration-set/${name}`;
38
+ }
39
+
40
+ /** An SES identity's ARN (the platform's is its mail domain). */
41
+ export function emailIdentityArn(region: string, accountId: string, identity: string): string {
42
+ return `arn:aws:ses:${region}:${accountId}:identity/${identity}`;
43
+ }
44
+
45
+ /**
46
+ * Trust for per-stage roles: the worker and Web Function (Lambda), schedules
47
+ * (Scheduler) and long-running services (ECS tasks).
48
+ */
20
49
  export function stageTrustPolicy(): PolicyDocument {
21
50
  return policy({
22
51
  Effect: 'Allow',
23
- Principal: { Service: ['lambda.amazonaws.com', 'scheduler.amazonaws.com'] },
52
+ Principal: { Service: ['lambda.amazonaws.com', 'scheduler.amazonaws.com', 'ecs-tasks.amazonaws.com'] },
24
53
  Action: 'sts:AssumeRole',
25
54
  });
26
55
  }
@@ -68,20 +97,39 @@ export function stageRolePolicy(input: StagePolicyInput): PolicyDocument {
68
97
  });
69
98
  }
70
99
 
71
- if (Object.keys(manifest.queues).length > 0) {
72
- statements.push({
73
- Sid: 'Queues',
74
- Effect: 'Allow',
75
- Action: [
76
- 'sqs:SendMessage',
77
- 'sqs:ReceiveMessage',
78
- 'sqs:DeleteMessage',
79
- 'sqs:GetQueueAttributes',
80
- 'sqs:GetQueueUrl',
81
- 'sqs:ChangeMessageVisibility',
82
- ],
83
- Resource: `arn:aws:sqs:${region}:${acct}:${base}--*`,
84
- });
100
+ if (manifest.worker) {
101
+ // Jobs (core jobs.ts): the dead-letter queue takes failed jobs from the SDK, Lambda's on-failure
102
+ // destination and Scheduler, all as this role. Receiving is for queues from before 0.4.0,
103
+ // which drain through their event source mappings (also this role) before they go.
104
+ statements.push(
105
+ {
106
+ Sid: 'Jobs',
107
+ Effect: 'Allow',
108
+ Action: [
109
+ 'sqs:SendMessage',
110
+ 'sqs:ReceiveMessage',
111
+ 'sqs:DeleteMessage',
112
+ 'sqs:GetQueueAttributes',
113
+ 'sqs:ChangeMessageVisibility',
114
+ ],
115
+ Resource: `arn:aws:sqs:${region}:${acct}:${base}--*`,
116
+ },
117
+ {
118
+ // Retries and delayed sends are one-shot schedules in the stage's group, invoking the
119
+ // stage's functions as this role.
120
+ Sid: 'JobSchedules',
121
+ Effect: 'Allow',
122
+ Action: 'scheduler:CreateSchedule',
123
+ Resource: `arn:aws:scheduler:${region}:${acct}:schedule/${names.scheduleGroup(app, stage)}/_*`,
124
+ },
125
+ {
126
+ Sid: 'JobSchedulesRole',
127
+ Effect: 'Allow',
128
+ Action: 'iam:PassRole',
129
+ Resource: `arn:aws:iam::${acct}:role${IAM_APP_PATH}${names.role(app, stage)}`,
130
+ Condition: { StringEquals: { 'iam:PassedToService': 'scheduler.amazonaws.com' } },
131
+ },
132
+ );
85
133
  }
86
134
 
87
135
  statements.push({
@@ -92,20 +140,21 @@ export function stageRolePolicy(input: StagePolicyInput): PolicyDocument {
92
140
  });
93
141
 
94
142
  if (manifest.storage.length > 0) {
95
- const prefix = names.storagePrefix(app, stage);
143
+ const prefixes = [names.storagePrefix(app, stage)];
144
+ if (publicStores(manifest).length > 0) prefixes.push(names.publicStoragePrefix(app, stage));
96
145
  statements.push(
97
146
  {
98
147
  Sid: 'StorageObjects',
99
148
  Effect: 'Allow',
100
149
  Action: ['s3:GetObject', 's3:PutObject', 's3:DeleteObject'],
101
- Resource: `arn:aws:s3:::${input.platform.storageBucket}/${prefix}*`,
150
+ Resource: prefixes.map((prefix) => `arn:aws:s3:::${input.platform.storageBucket}/${prefix}*`),
102
151
  },
103
152
  {
104
153
  Sid: 'StorageList',
105
154
  Effect: 'Allow',
106
155
  Action: 's3:ListBucket',
107
156
  Resource: `arn:aws:s3:::${input.platform.storageBucket}`,
108
- Condition: { StringLike: { 's3:prefix': [`${prefix}*`] } },
157
+ Condition: { StringLike: { 's3:prefix': prefixes.map((prefix) => `${prefix}*`) } },
109
158
  },
110
159
  );
111
160
  }
@@ -130,12 +179,66 @@ export function stageRolePolicy(input: StagePolicyInput): PolicyDocument {
130
179
  },
131
180
  );
132
181
 
182
+ // Publishing only (HTTP, IAM-signed), and only to this stage's namespace:
183
+ // namespaces are per stage so IAM, not handler code, keeps stages apart.
184
+ const realtimeApi = input.platform.realtime?.apiId;
185
+ if (manifest.realtime && realtimeApi) {
186
+ statements.push({
187
+ Sid: 'Realtime',
188
+ Effect: 'Allow',
189
+ Action: 'appsync:EventPublish',
190
+ Resource: channelNamespaceArn(region, acct, realtimeApi, names.realtimeNamespace(app, stage)),
191
+ });
192
+ }
193
+
194
+ // Sending only as this stage: its address, its tenant (whose reputation policy can pause it, a
195
+ // backstop app code can't get around) and its configuration set. SES v1 shares the action
196
+ // name, so `ses:ApiVersion` keeps the grant to SESv2, the API the SDK sends with. The SDK names
197
+ // the tenant and the configuration set on every send; IAM checks the identity and the
198
+ // configuration set as resources.
199
+ const email = input.platform.email;
200
+ if (manifest.email && email) {
201
+ const tenant = names.emailTenant(app, stage);
202
+ statements.push(
203
+ {
204
+ Sid: 'Email',
205
+ Effect: 'Allow',
206
+ Action: 'ses:SendEmail',
207
+ Resource: [email.identityArn, configurationSetArn(region, acct, tenant)],
208
+ Condition: {
209
+ StringEquals: {
210
+ 'ses:FromAddress': emailFromAddress(app, stage, email.domain),
211
+ 'ses:TenantName': tenant,
212
+ 'ses:ApiVersion': '2',
213
+ },
214
+ },
215
+ },
216
+ {
217
+ // The daily limit's counter: one row per UTC day in the platform's telemetry table,
218
+ // under this stage's own partition key only.
219
+ Sid: 'EmailUsage',
220
+ Effect: 'Allow',
221
+ Action: 'dynamodb:UpdateItem',
222
+ Resource: `arn:aws:dynamodb:${region}:${acct}:table/${input.platform.telemetryTable}`,
223
+ Condition: {
224
+ 'ForAllValues:StringEquals': { 'dynamodb:LeadingKeys': [telemetryKeys.email(app, stage)] },
225
+ },
226
+ },
227
+ );
228
+ }
229
+
230
+ // The SDK sends queue messages and `invokeJob` to the worker's function and handlers' own, and
231
+ // Scheduler (crons, retries, delayed sends) calls them as this role.
133
232
  if (manifest.worker) {
233
+ const functions = [
234
+ names.workerFunction(app, stage),
235
+ ...ownFunctionHandlers(manifest).map((h) => names.handlerFunction(app, stage, h.kind, h.name)),
236
+ ].map((fn) => `arn:aws:lambda:${region}:${acct}:function:${fn}`);
134
237
  statements.push({
135
238
  Sid: 'InvokeWorker',
136
239
  Effect: 'Allow',
137
240
  Action: 'lambda:InvokeFunction',
138
- Resource: `arn:aws:lambda:${region}:${acct}:function:${names.workerFunction(app, stage)}`,
241
+ Resource: functions.length === 1 ? functions[0]! : functions,
139
242
  });
140
243
  }
141
244
 
@@ -152,8 +255,48 @@ export function boundaryPolicy(input: {
152
255
  region: string;
153
256
  accountId: string;
154
257
  storageBucket: string;
258
+ /** The platform's Event API; stage roles may publish to its stage namespaces. */
259
+ realtimeApiId?: string;
260
+ /**
261
+ * The platform's mail domain and the table holding usage counters; stage roles may send as
262
+ * a stage tenant and count what they send.
263
+ */
264
+ email?: { identityArn: string; usageTable: string };
155
265
  }): PolicyDocument {
156
266
  const { region, accountId: acct } = input;
267
+ const email: PolicyStatement[] = input.email
268
+ ? [
269
+ {
270
+ Sid: 'StageEmail',
271
+ Effect: 'Allow',
272
+ Action: 'ses:SendEmail',
273
+ // Tenants and their configuration sets are `<app>--<stage>`.
274
+ Resource: [input.email.identityArn, configurationSetArn(region, acct, '*--*')],
275
+ Condition: { StringLike: { 'ses:TenantName': '*--*' } },
276
+ },
277
+ {
278
+ Sid: 'StageEmailUsage',
279
+ Effect: 'Allow',
280
+ Action: 'dynamodb:UpdateItem',
281
+ Resource: `arn:aws:dynamodb:${region}:${acct}:table/${input.email.usageTable}`,
282
+ Condition: {
283
+ 'ForAllValues:StringLike': { 'dynamodb:LeadingKeys': [telemetryKeys.email('*', '*')] },
284
+ },
285
+ },
286
+ ]
287
+ : [];
288
+ const realtime: PolicyStatement[] = input.realtimeApiId
289
+ ? [
290
+ {
291
+ Sid: 'StageRealtime',
292
+ Effect: 'Allow',
293
+ Action: 'appsync:EventPublish',
294
+ // Stage namespaces are `<app>--<stage>` (or that, hashed, when long); `--` never
295
+ // appears in an app or stage name.
296
+ Resource: channelNamespaceArn(region, acct, input.realtimeApiId, '*--*'),
297
+ },
298
+ ]
299
+ : [];
157
300
  return policy(
158
301
  {
159
302
  Sid: 'StageLogs',
@@ -189,6 +332,21 @@ export function boundaryPolicy(input: {
189
332
  Action: 'events:PutEvents',
190
333
  Resource: `arn:aws:events:${region}:${acct}:event-bus/*--*`,
191
334
  },
335
+ {
336
+ // Jobs' retries and delayed sends (`_`-prefixed one-shot schedules in a stage's group), run as
337
+ // a stage role.
338
+ Sid: 'StageJobSchedules',
339
+ Effect: 'Allow',
340
+ Action: 'scheduler:CreateSchedule',
341
+ Resource: `arn:aws:scheduler:${region}:${acct}:schedule/*--*/_*`,
342
+ },
343
+ {
344
+ Sid: 'StageJobSchedulesRole',
345
+ Effect: 'Allow',
346
+ Action: 'iam:PassRole',
347
+ Resource: `arn:aws:iam::${acct}:role${IAM_APP_PATH}*`,
348
+ Condition: { StringEquals: { 'iam:PassedToService': 'scheduler.amazonaws.com' } },
349
+ },
192
350
  {
193
351
  Sid: 'StageStorage',
194
352
  Effect: 'Allow',
@@ -205,11 +363,15 @@ export function boundaryPolicy(input: {
205
363
  ],
206
364
  },
207
365
  {
366
+ // Workers are `<app>--<stage>--worker`; handlers' own functions are `…--worker--<handler>`,
367
+ // hashed when long, so all that's sure to remain is a second `--`.
208
368
  Sid: 'StageWorkers',
209
369
  Effect: 'Allow',
210
370
  Action: 'lambda:InvokeFunction',
211
- Resource: `arn:aws:lambda:${region}:${acct}:function:*--*--worker`,
371
+ Resource: `arn:aws:lambda:${region}:${acct}:function:*--*--*`,
212
372
  },
373
+ ...realtime,
374
+ ...email,
213
375
  );
214
376
  }
215
377
 
@@ -230,7 +392,15 @@ export function controlPlanePolicy(input: {
230
392
  | 'userPoolId'
231
393
  | 'boundaryPolicyArn'
232
394
  | 'alertsTopicArn'
233
- >;
395
+ | 'distributionArn'
396
+ > & {
397
+ realtime?: Pick<NonNullable<PlatformRuntimeConfig['realtime']>, 'apiId'>;
398
+ email?: Pick<EmailRuntimeConfig, 'identityArn'>;
399
+ containers?: Pick<
400
+ ContainersRuntimeConfig,
401
+ 'cluster' | 'repository' | 'executionRoleArn' | 'schedulerRoleArn'
402
+ >;
403
+ };
234
404
  }): PolicyDocument {
235
405
  const { region, accountId: acct, runtime } = input;
236
406
  const appRoles = `arn:aws:iam::${acct}:role${IAM_APP_PATH}*`;
@@ -290,6 +460,8 @@ export function controlPlanePolicy(input: {
290
460
  'lambda:CreateEventSourceMapping',
291
461
  'lambda:ListFunctions',
292
462
  'lambda:ListWebFunctions',
463
+ // Whether `auto` may run a server in request mode (core `requestModeBlocked`).
464
+ 'lambda:GetAccountSettings',
293
465
  ],
294
466
  Resource: '*',
295
467
  },
@@ -321,9 +493,17 @@ export function controlPlanePolicy(input: {
321
493
  ]),
322
494
  },
323
495
  {
496
+ // PutParameter with Tags (secrets are created tagged) is also authorized
497
+ // as ssm:AddTagsToResource, which `*Parameter*` doesn't match.
324
498
  Sid: 'Parameters',
325
499
  Effect: 'Allow',
326
- Action: ['ssm:*Parameter*', 'kms:Decrypt', 'kms:Encrypt', 'kms:GenerateDataKey'],
500
+ Action: [
501
+ 'ssm:*Parameter*',
502
+ 'ssm:AddTagsToResource',
503
+ 'kms:Decrypt',
504
+ 'kms:Encrypt',
505
+ 'kms:GenerateDataKey',
506
+ ],
327
507
  Resource: [`arn:aws:ssm:${region}:${acct}:parameter/platform/*`, `arn:aws:kms:${region}:${acct}:key/*`],
328
508
  },
329
509
  {
@@ -348,6 +528,50 @@ export function controlPlanePolicy(input: {
348
528
  Resource: runtime.kvsArn,
349
529
  });
350
530
  }
531
+ if (runtime.distributionArn) {
532
+ // The edge floor (control plane edge-floor.ts): its web ACL exists only while it's on, so the
533
+ // control plane creates, attaches, detaches and deletes it. Granted with or without
534
+ // `limits.edgeFloorAt`, so a floor that was on when the setting went can still be taken down.
535
+ // UpdateDistribution can change the whole router config, as writing the route store can
536
+ // already route any host anywhere.
537
+ const webAcl = `arn:aws:wafv2:us-east-1:${acct}:global/webacl/${platformNames.edgeWebAcl}/*`;
538
+ statements.push(
539
+ {
540
+ Sid: 'EdgeFloorDistribution',
541
+ Effect: 'Allow',
542
+ Action: ['cloudfront:GetDistributionConfig', 'cloudfront:UpdateDistribution'],
543
+ Resource: runtime.distributionArn,
544
+ },
545
+ {
546
+ // GetWebACL is also what CloudFront checks when a distribution is pointed at a web ACL.
547
+ Sid: 'EdgeFloorWebAcl',
548
+ Effect: 'Allow',
549
+ Action: [
550
+ 'wafv2:CreateWebACL',
551
+ 'wafv2:GetWebACL',
552
+ 'wafv2:UpdateWebACL',
553
+ 'wafv2:DeleteWebACL',
554
+ 'wafv2:TagResource',
555
+ 'wafv2:GetSampledRequests',
556
+ ],
557
+ Resource: webAcl,
558
+ },
559
+ {
560
+ // Finds the web ACL's id and lock token by name; the action takes no resource.
561
+ Sid: 'EdgeFloorLookup',
562
+ Effect: 'Allow',
563
+ Action: 'wafv2:ListWebACLs',
564
+ Resource: '*',
565
+ },
566
+ {
567
+ // The alarm on the router's requests per minute that turns it on (foundation stack).
568
+ Sid: 'EdgeFloorAlarm',
569
+ Effect: 'Allow',
570
+ Action: 'cloudwatch:DescribeAlarms',
571
+ Resource: `arn:aws:cloudwatch:${region}:${acct}:alarm:${platformNames.edgeFloorAlarm}`,
572
+ },
573
+ );
574
+ }
351
575
  if (runtime.userPoolId) {
352
576
  statements.push({
353
577
  Sid: 'AppClients',
@@ -361,6 +585,155 @@ export function controlPlanePolicy(input: {
361
585
  Resource: `arn:aws:cognito-idp:${region}:${acct}:userpool/${runtime.userPoolId}`,
362
586
  });
363
587
  }
588
+ if (runtime.realtime) {
589
+ const api = `arn:aws:appsync:${region}:${acct}:apis/${runtime.realtime.apiId}`;
590
+ statements.push({
591
+ // Stage namespaces (deploy, destroy) and the public subscribe key (nightly extension).
592
+ Sid: 'Realtime',
593
+ Effect: 'Allow',
594
+ Action: [
595
+ 'appsync:CreateChannelNamespace',
596
+ 'appsync:UpdateChannelNamespace',
597
+ 'appsync:DeleteChannelNamespace',
598
+ 'appsync:GetChannelNamespace',
599
+ 'appsync:ListChannelNamespaces',
600
+ 'appsync:CreateApiKey',
601
+ 'appsync:UpdateApiKey',
602
+ 'appsync:ListApiKeys',
603
+ 'appsync:TagResource',
604
+ 'appsync:ListTagsForResource',
605
+ ],
606
+ Resource: [api, `${api}/*`],
607
+ });
608
+ statements.push({
609
+ // listStageResources finds the API by name, like every other resource.
610
+ Sid: 'RealtimeLookup',
611
+ Effect: 'Allow',
612
+ Action: 'appsync:ListApis',
613
+ Resource: '*',
614
+ });
615
+ }
616
+ if (runtime.email) {
617
+ const ses = `arn:aws:ses:${region}:${acct}`;
618
+ statements.push(
619
+ {
620
+ // Stage tenants and their configuration sets: the engine creates, associates and deletes
621
+ // them; the control plane reads their status, pauses and resumes sending, and manages
622
+ // their suppression lists. Tenant ARNs are `tenant/<name>/<id>`, so `*--*` covers both.
623
+ Sid: 'Email',
624
+ Effect: 'Allow',
625
+ Action: [
626
+ 'ses:CreateConfigurationSet',
627
+ 'ses:GetConfigurationSet',
628
+ 'ses:DeleteConfigurationSet',
629
+ 'ses:PutConfigurationSetReputationOptions',
630
+ 'ses:CreateTenant',
631
+ 'ses:GetTenant',
632
+ 'ses:DeleteTenant',
633
+ 'ses:PutTenantSuppressionAttributes',
634
+ 'ses:CreateTenantResourceAssociation',
635
+ 'ses:DeleteTenantResourceAssociation',
636
+ 'ses:ListTenantResources',
637
+ 'ses:TagResource',
638
+ 'ses:ListTagsForResource',
639
+ 'ses:GetReputationEntity',
640
+ 'ses:UpdateReputationEntityCustomerManagedStatus',
641
+ 'ses:ListSuppressedDestinations',
642
+ 'ses:GetSuppressedDestination',
643
+ 'ses:DeleteSuppressedDestination',
644
+ ],
645
+ Resource: [`${ses}:tenant/*--*`, `${ses}:configuration-set/*--*`],
646
+ },
647
+ {
648
+ // An association is authorized against the associated resource too: here, the domain.
649
+ Sid: 'EmailDomain',
650
+ Effect: 'Allow',
651
+ Action: ['ses:CreateTenantResourceAssociation', 'ses:DeleteTenantResourceAssociation'],
652
+ Resource: runtime.email.identityArn,
653
+ },
654
+ {
655
+ // A tenant's ARN ends in an id SES assigns, so a lookup by name of a tenant that doesn't
656
+ // exist (every deploy and destroy of a stage without email) is authorized against `*`.
657
+ Sid: 'EmailTenantLookup',
658
+ Effect: 'Allow',
659
+ Action: ['ses:GetTenant', 'ses:ListTenantResources'],
660
+ Resource: '*',
661
+ },
662
+ );
663
+ }
664
+ if (runtime.containers) {
665
+ const { cluster, repository, executionRoleArn, schedulerRoleArn } = runtime.containers;
666
+ statements.push(
667
+ {
668
+ // Stage services (deploy, destroy, start/stop/restart).
669
+ Sid: 'ContainerServices',
670
+ Effect: 'Allow',
671
+ Action: [
672
+ 'ecs:CreateService',
673
+ 'ecs:UpdateService',
674
+ 'ecs:DeleteService',
675
+ 'ecs:DescribeServices',
676
+ 'ecs:TagResource',
677
+ 'ecs:UntagResource',
678
+ 'ecs:ListTagsForResource',
679
+ ],
680
+ Resource: `arn:aws:ecs:${region}:${acct}:service/${cluster}/*`,
681
+ },
682
+ {
683
+ // Task definitions, and the cluster's tasks and service listing, take no narrower resource.
684
+ Sid: 'ContainerTasks',
685
+ Effect: 'Allow',
686
+ Action: [
687
+ 'ecs:RegisterTaskDefinition',
688
+ 'ecs:DeregisterTaskDefinition',
689
+ 'ecs:DeleteTaskDefinitions',
690
+ 'ecs:DescribeTaskDefinition',
691
+ 'ecs:ListTaskDefinitions',
692
+ 'ecs:ListTaskDefinitionFamilies',
693
+ 'ecs:TagResource',
694
+ 'ecs:ListTagsForResource',
695
+ 'ecs:ListServices',
696
+ 'ecs:ListTasks',
697
+ 'ecs:DescribeTasks',
698
+ 'ecs:StopTask',
699
+ ],
700
+ Resource: '*',
701
+ },
702
+ {
703
+ // Images are built through the registry API (no Docker), so pushes are IAM calls.
704
+ Sid: 'ContainerImages',
705
+ Effect: 'Allow',
706
+ Action: [
707
+ 'ecr:BatchCheckLayerAvailability',
708
+ 'ecr:InitiateLayerUpload',
709
+ 'ecr:UploadLayerPart',
710
+ 'ecr:CompleteLayerUpload',
711
+ 'ecr:PutImage',
712
+ 'ecr:BatchGetImage',
713
+ 'ecr:GetDownloadUrlForLayer',
714
+ 'ecr:DescribeImages',
715
+ 'ecr:ListImages',
716
+ 'ecr:BatchDeleteImage',
717
+ ],
718
+ Resource: `arn:aws:ecr:${region}:${acct}:repository/${repository}`,
719
+ },
720
+ {
721
+ Sid: 'ContainerRoles',
722
+ Effect: 'Allow',
723
+ Action: 'iam:PassRole',
724
+ Resource: [executionRoleArn, schedulerRoleArn],
725
+ },
726
+ {
727
+ // ECS manages task network interfaces through its service-linked role, which it creates on
728
+ // first use. A young account doesn't have it yet, so the first CreateService makes it.
729
+ Sid: 'ContainerServiceLinkedRole',
730
+ Effect: 'Allow',
731
+ Action: 'iam:CreateServiceLinkedRole',
732
+ Resource: `arn:aws:iam::${acct}:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS`,
733
+ Condition: { StringEquals: { 'iam:AWSServiceName': 'ecs.amazonaws.com' } },
734
+ },
735
+ );
736
+ }
364
737
  if (runtime.alertsTopicArn) {
365
738
  statements.push({
366
739
  Sid: 'Alerts',
@@ -372,6 +745,55 @@ export function controlPlanePolicy(input: {
372
745
  return policy(...statements);
373
746
  }
374
747
 
748
+ /**
749
+ * What ECS needs to start a platform container: pull its image and ship its
750
+ * logs to the stage's service log groups (created by the engine). The app's
751
+ * own code runs as the stage role, never as this one.
752
+ */
753
+ export function containerExecutionPolicy(input: {
754
+ region: string;
755
+ accountId: string;
756
+ repository: string;
757
+ }): PolicyDocument {
758
+ const { region, accountId: acct } = input;
759
+ return policy(
760
+ {
761
+ Sid: 'PullImages',
762
+ Effect: 'Allow',
763
+ Action: ['ecr:BatchGetImage', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchCheckLayerAvailability'],
764
+ Resource: `arn:aws:ecr:${region}:${acct}:repository/${input.repository}`,
765
+ },
766
+ { Sid: 'RegistryAuth', Effect: 'Allow', Action: 'ecr:GetAuthorizationToken', Resource: '*' },
767
+ {
768
+ Sid: 'ContainerLogs',
769
+ Effect: 'Allow',
770
+ Action: ['logs:CreateLogStream', 'logs:PutLogEvents'],
771
+ Resource: [
772
+ `arn:aws:logs:${region}:${acct}:log-group:/platform/apps/*/*/services/*`,
773
+ `arn:aws:logs:${region}:${acct}:log-group:/platform/apps/*/*/services/*:log-stream:*`,
774
+ ],
775
+ },
776
+ );
777
+ }
778
+
779
+ /**
780
+ * Assumed by EventBridge Scheduler for the one-shot schedules that stop a
781
+ * preview's services. It can only change a stage service's desired count
782
+ * (the schedule's input is fixed by the engine); app code never holds it.
783
+ */
784
+ export function containerSchedulerPolicy(input: {
785
+ region: string;
786
+ accountId: string;
787
+ cluster: string;
788
+ }): PolicyDocument {
789
+ return policy({
790
+ Sid: 'ScaleStageServices',
791
+ Effect: 'Allow',
792
+ Action: 'ecs:UpdateService',
793
+ Resource: `arn:aws:ecs:${input.region}:${input.accountId}:service/${input.cluster}/*--*`,
794
+ });
795
+ }
796
+
375
797
  export function serviceTrustPolicy(...services: string[]): PolicyDocument {
376
798
  return policy({ Effect: 'Allow', Principal: { Service: services }, Action: 'sts:AssumeRole' });
377
799
  }