@ericminassian/platform-engine 0.2.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 (98) 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 +7 -0
  32. package/dist/drivers/s3.js +31 -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/ssm.d.ts +1 -0
  44. package/dist/drivers/ssm.js +23 -3
  45. package/dist/drivers/ssm.js.map +1 -1
  46. package/dist/drivers/web-function.d.ts +41 -11
  47. package/dist/drivers/web-function.js +62 -8
  48. package/dist/drivers/web-function.js.map +1 -1
  49. package/dist/emulator.js.map +1 -1
  50. package/dist/images.d.ts +104 -0
  51. package/dist/images.js +182 -0
  52. package/dist/images.js.map +1 -0
  53. package/dist/index.d.ts +132 -7
  54. package/dist/index.js +11 -2
  55. package/dist/index.js.map +1 -1
  56. package/dist/local.js +222 -7
  57. package/dist/local.js.map +1 -1
  58. package/dist/policy.d.ts +47 -4
  59. package/dist/policy.js +369 -15
  60. package/dist/policy.js.map +1 -1
  61. package/dist/services.d.ts +155 -0
  62. package/dist/services.js +464 -0
  63. package/dist/services.js.map +1 -0
  64. package/dist/stage.d.ts +44 -4
  65. package/dist/stage.js +681 -138
  66. package/dist/stage.js.map +1 -1
  67. package/dist/static.d.ts +1 -1
  68. package/dist/static.js +2 -36
  69. package/dist/static.js.map +1 -1
  70. package/dist/util.d.ts +22 -0
  71. package/dist/util.js +18 -2
  72. package/dist/util.js.map +1 -1
  73. package/package.json +20 -14
  74. package/src/clients.ts +25 -1
  75. package/src/compat.ts +34 -11
  76. package/src/drivers/appsync.ts +220 -0
  77. package/src/drivers/ecr.ts +457 -0
  78. package/src/drivers/ecs.ts +661 -0
  79. package/src/drivers/events.ts +29 -2
  80. package/src/drivers/index.ts +5 -0
  81. package/src/drivers/kvs.ts +21 -12
  82. package/src/drivers/lambda.ts +103 -2
  83. package/src/drivers/request-function.ts +295 -0
  84. package/src/drivers/s3.ts +46 -0
  85. package/src/drivers/scheduler.ts +88 -5
  86. package/src/drivers/ses.ts +267 -0
  87. package/src/drivers/sqs.ts +95 -0
  88. package/src/drivers/ssm.ts +23 -2
  89. package/src/drivers/web-function.ts +108 -17
  90. package/src/emulator.ts +3 -3
  91. package/src/images.ts +254 -0
  92. package/src/index.ts +131 -8
  93. package/src/local.ts +251 -7
  94. package/src/policy.ts +450 -26
  95. package/src/services.ts +663 -0
  96. package/src/stage.ts +839 -153
  97. package/src/static.ts +2 -37
  98. 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
  }
@@ -35,10 +64,12 @@ export function stageRolePolicy(input: StagePolicyInput): PolicyDocument {
35
64
  const base = names.base(app, stage);
36
65
  const statements: PolicyStatement[] = [];
37
66
 
67
+ // No logs:CreateLogGroup: the engine creates the stage's groups. With it, logs still in flight
68
+ // when a stage is destroyed recreate the groups right after destroy deletes them.
38
69
  statements.push({
39
70
  Sid: 'Logs',
40
71
  Effect: 'Allow',
41
- Action: ['logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents'],
72
+ Action: ['logs:CreateLogStream', 'logs:PutLogEvents'],
42
73
  Resource: [
43
74
  `arn:aws:logs:${region}:${acct}:log-group:${names.logGroupPrefix(app, stage)}*`,
44
75
  `arn:aws:logs:${region}:${acct}:log-group:${names.logGroupPrefix(app, stage)}*:log-stream:*`,
@@ -66,20 +97,39 @@ export function stageRolePolicy(input: StagePolicyInput): PolicyDocument {
66
97
  });
67
98
  }
68
99
 
69
- if (Object.keys(manifest.queues).length > 0) {
70
- statements.push({
71
- Sid: 'Queues',
72
- Effect: 'Allow',
73
- Action: [
74
- 'sqs:SendMessage',
75
- 'sqs:ReceiveMessage',
76
- 'sqs:DeleteMessage',
77
- 'sqs:GetQueueAttributes',
78
- 'sqs:GetQueueUrl',
79
- 'sqs:ChangeMessageVisibility',
80
- ],
81
- Resource: `arn:aws:sqs:${region}:${acct}:${base}--*`,
82
- });
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
+ );
83
133
  }
84
134
 
85
135
  statements.push({
@@ -90,20 +140,21 @@ export function stageRolePolicy(input: StagePolicyInput): PolicyDocument {
90
140
  });
91
141
 
92
142
  if (manifest.storage.length > 0) {
93
- 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));
94
145
  statements.push(
95
146
  {
96
147
  Sid: 'StorageObjects',
97
148
  Effect: 'Allow',
98
149
  Action: ['s3:GetObject', 's3:PutObject', 's3:DeleteObject'],
99
- Resource: `arn:aws:s3:::${input.platform.storageBucket}/${prefix}*`,
150
+ Resource: prefixes.map((prefix) => `arn:aws:s3:::${input.platform.storageBucket}/${prefix}*`),
100
151
  },
101
152
  {
102
153
  Sid: 'StorageList',
103
154
  Effect: 'Allow',
104
155
  Action: 's3:ListBucket',
105
156
  Resource: `arn:aws:s3:::${input.platform.storageBucket}`,
106
- Condition: { StringLike: { 's3:prefix': [`${prefix}*`] } },
157
+ Condition: { StringLike: { 's3:prefix': prefixes.map((prefix) => `${prefix}*`) } },
107
158
  },
108
159
  );
109
160
  }
@@ -128,12 +179,66 @@ export function stageRolePolicy(input: StagePolicyInput): PolicyDocument {
128
179
  },
129
180
  );
130
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.
131
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}`);
132
237
  statements.push({
133
238
  Sid: 'InvokeWorker',
134
239
  Effect: 'Allow',
135
240
  Action: 'lambda:InvokeFunction',
136
- Resource: `arn:aws:lambda:${region}:${acct}:function:${names.workerFunction(app, stage)}`,
241
+ Resource: functions.length === 1 ? functions[0]! : functions,
137
242
  });
138
243
  }
139
244
 
@@ -150,13 +255,53 @@ export function boundaryPolicy(input: {
150
255
  region: string;
151
256
  accountId: string;
152
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 };
153
265
  }): PolicyDocument {
154
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
+ : [];
155
300
  return policy(
156
301
  {
157
302
  Sid: 'StageLogs',
158
303
  Effect: 'Allow',
159
- Action: ['logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents'],
304
+ Action: ['logs:CreateLogStream', 'logs:PutLogEvents'],
160
305
  Resource: `arn:aws:logs:${region}:${acct}:log-group:/platform/apps/*`,
161
306
  },
162
307
  {
@@ -187,6 +332,21 @@ export function boundaryPolicy(input: {
187
332
  Action: 'events:PutEvents',
188
333
  Resource: `arn:aws:events:${region}:${acct}:event-bus/*--*`,
189
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
+ },
190
350
  {
191
351
  Sid: 'StageStorage',
192
352
  Effect: 'Allow',
@@ -203,11 +363,15 @@ export function boundaryPolicy(input: {
203
363
  ],
204
364
  },
205
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 `--`.
206
368
  Sid: 'StageWorkers',
207
369
  Effect: 'Allow',
208
370
  Action: 'lambda:InvokeFunction',
209
- Resource: `arn:aws:lambda:${region}:${acct}:function:*--*--worker`,
371
+ Resource: `arn:aws:lambda:${region}:${acct}:function:*--*--*`,
210
372
  },
373
+ ...realtime,
374
+ ...email,
211
375
  );
212
376
  }
213
377
 
@@ -228,7 +392,15 @@ export function controlPlanePolicy(input: {
228
392
  | 'userPoolId'
229
393
  | 'boundaryPolicyArn'
230
394
  | 'alertsTopicArn'
231
- >;
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
+ };
232
404
  }): PolicyDocument {
233
405
  const { region, accountId: acct, runtime } = input;
234
406
  const appRoles = `arn:aws:iam::${acct}:role${IAM_APP_PATH}*`;
@@ -288,6 +460,8 @@ export function controlPlanePolicy(input: {
288
460
  'lambda:CreateEventSourceMapping',
289
461
  'lambda:ListFunctions',
290
462
  'lambda:ListWebFunctions',
463
+ // Whether `auto` may run a server in request mode (core `requestModeBlocked`).
464
+ 'lambda:GetAccountSettings',
291
465
  ],
292
466
  Resource: '*',
293
467
  },
@@ -319,9 +493,17 @@ export function controlPlanePolicy(input: {
319
493
  ]),
320
494
  },
321
495
  {
496
+ // PutParameter with Tags (secrets are created tagged) is also authorized
497
+ // as ssm:AddTagsToResource, which `*Parameter*` doesn't match.
322
498
  Sid: 'Parameters',
323
499
  Effect: 'Allow',
324
- 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
+ ],
325
507
  Resource: [`arn:aws:ssm:${region}:${acct}:parameter/platform/*`, `arn:aws:kms:${region}:${acct}:key/*`],
326
508
  },
327
509
  {
@@ -346,6 +528,50 @@ export function controlPlanePolicy(input: {
346
528
  Resource: runtime.kvsArn,
347
529
  });
348
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
+ }
349
575
  if (runtime.userPoolId) {
350
576
  statements.push({
351
577
  Sid: 'AppClients',
@@ -359,6 +585,155 @@ export function controlPlanePolicy(input: {
359
585
  Resource: `arn:aws:cognito-idp:${region}:${acct}:userpool/${runtime.userPoolId}`,
360
586
  });
361
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
+ }
362
737
  if (runtime.alertsTopicArn) {
363
738
  statements.push({
364
739
  Sid: 'Alerts',
@@ -370,6 +745,55 @@ export function controlPlanePolicy(input: {
370
745
  return policy(...statements);
371
746
  }
372
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
+
373
797
  export function serviceTrustPolicy(...services: string[]): PolicyDocument {
374
798
  return policy({ Effect: 'Allow', Principal: { Service: services }, Action: 'sts:AssumeRole' });
375
799
  }