grada-run 0.50.0 → 0.50.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grada-run",
3
- "version": "0.50.0",
3
+ "version": "0.50.1",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -499,6 +499,12 @@ ${aliasLine} topic_arn = aws_sns_topic.alerts.arn
499
499
  # (The archive provider constraint lives in backend.tf next to the aws
500
500
  # one — a module may declare required_providers only once.)
501
501
 
502
+ locals {
503
+ # Length-safe forwarder name (role + function both cap at 64):
504
+ # short names render byte-identically, over-cap hash-suffixes.
505
+ forwarder_safe_name = length("${namePrefix}-alerts-forwarder") > 64 ? "\${substr(local.app_name, 0, 64 - 1 - 5 - 17)}-\${substr(md5(local.app_name), 0, 5)}-alerts-forwarder" : "${namePrefix}-alerts-forwarder"
506
+ }
507
+
502
508
  variable "alerts_webhook_url" {
503
509
  description = "Incoming chat webhook URL for alarm notifications. Export TF_VAR_alerts_webhook_url before apply — never commit the URL to git."
504
510
  type = string
@@ -518,7 +524,7 @@ ${buildForwarderJs()} EOT
518
524
  }
519
525
 
520
526
  resource "aws_iam_role" "forwarder" {
521
- name = "${namePrefix}-alerts-forwarder"
527
+ name = local.forwarder_safe_name
522
528
  assume_role_policy = jsonencode({
523
529
  Version = "2012-10-17"
524
530
  Statement = [
@@ -537,7 +543,7 @@ resource "aws_iam_role_policy_attachment" "forwarder_logs" {
537
543
  }
538
544
 
539
545
  resource "aws_lambda_function" "forwarder" {
540
- ${aliasLine} function_name = "${namePrefix}-alerts-forwarder"
546
+ ${aliasLine} function_name = local.forwarder_safe_name
541
547
  role = aws_iam_role.forwarder.arn
542
548
  runtime = "nodejs22.x"
543
549
  handler = "index.handler"
@@ -8,7 +8,7 @@ import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized,
8
8
  import { normalizeOptions } from '../utils/args.js';
9
9
  import { truncateSpinnerText } from '../utils/spinner-text.js';
10
10
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
11
- import { resolveRegion, resolveProjectName, resolveCluster, resolveLogGroup, resolveCwd, readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, resolveNamespacedProject, withWorkspaceNamespace } from '../utils/resolvers.js';
11
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveLogGroup, resolveCwd, readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, resolveNamespacedProject, withWorkspaceNamespace, safeSuffixedName } from '../utils/resolvers.js';
12
12
  import { pickNewestRunningTask } from '../utils/ecs.js';
13
13
  import { fetchLatestEvents } from './logs.js';
14
14
 
@@ -127,7 +127,7 @@ export async function runLambdaDiagnose(input = {}) {
127
127
  const namespacedProject = resolveNamespacedProject(projectName, options, options.cwd);
128
128
  const functionName = typeof options.functionName === 'string' && options.functionName.trim()
129
129
  ? options.functionName.trim()
130
- : `${namespacedProject}${readResourceSuffix(options.cwd)}-fn`;
130
+ : safeSuffixedName(`${namespacedProject}${readResourceSuffix(options.cwd)}`, '-fn', 64);
131
131
  const runSync = options.spawnSyncImpl || spawnSync;
132
132
 
133
133
  intro(color.bgCyan(color.black(' grada diagnose 🩺 ')));
@@ -11,7 +11,7 @@ import color from 'picocolors';
11
11
  import { intro, outro, confirm, spinner, cancel } from '@clack/prompts';
12
12
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
13
13
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
14
- import { resolveRegion, resolveProjectName, resolveCwd, isComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
14
+ import { resolveRegion, resolveProjectName, resolveCwd, isComputeTarget, readResourceSuffix, safeSuffixedName } from '../utils/resolvers.js';
15
15
  import { resolveClient } from '../utils/aws.js';
16
16
  import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseIfNonInteractive, refuseUnknownFlags, shouldAutoApprove } from '../utils/command.js';
17
17
  import { parseStateBucketBackend } from '../utils/terraform-metadata.js';
@@ -85,6 +85,9 @@ function projectRepoName(projectName, resourceSuffix = '') {
85
85
  // lookalikes (`myapp-evil-pr-2`) never match.
86
86
  function previewLogGroupPattern({ projectName, resourceSuffix = '', isLambda = false }) {
87
87
  const base = `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
88
+ // Plain-form only by design: over-cap preview names hash-suffix in
89
+ // Terraform, so they never match here — fail closed (never proposed)
90
+ // and the 30-day group retention self-cleans them instead.
88
91
  return isLambda ? new RegExp(`^/aws/lambda/${base}-fn$`) : new RegExp(`^/ecs/${base}$`);
89
92
  }
90
93
 
@@ -199,6 +202,9 @@ export async function discoverLivePreviewLogGroups({
199
202
  try {
200
203
  const base = `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
201
204
  if (isLambda) {
205
+ // Plain-form only (see previewLogGroupPattern): hashed
206
+ // over-cap functions are invisible here, and invisible to
207
+ // the orphan candidate pattern too — consistently skipped.
202
208
  const fnPattern = new RegExp(`^${base}-fn$`);
203
209
  const names = await listFunctionsImpl({ region, spawnSyncImpl });
204
210
  for (const name of names || []) {
@@ -740,7 +746,7 @@ async function runGcMain(input = {}) {
740
746
  // Exact match: the live group carries the suffix on suffixed
741
747
  // trees, and proposing it for deletion would be catastrophic.
742
748
  excludeLogGroup: isLambda
743
- ? `/aws/lambda/${projectName}${suffix}-fn`
749
+ ? `/aws/lambda/${safeSuffixedName(`${projectName}${suffix}`, '-fn', 64)}`
744
750
  : `/ecs/${projectName}${suffix}`,
745
751
  livePreviewGroups: liveness.groups,
746
752
  previewLivenessUnknown: liveness.unknown,
@@ -12,7 +12,7 @@ import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveComman
12
12
  import { failCommand, failAwsError, failProjectNotInitialized, refuseIfNonInteractive, refuseUnknownFlags } from '../utils/command.js';
13
13
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
14
14
  import { isAuthError, handleAwsAuthError, resolveClient } from '../utils/aws.js';
15
- import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, withWorkspaceNamespace, resolveCwd, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
15
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, withWorkspaceNamespace, resolveCwd, guardComputeTarget, readResourceSuffix, safeSuffixedName } from '../utils/resolvers.js';
16
16
  import { requireManagedTree } from '../utils/terraform-metadata.js';
17
17
  import { truncateSpinnerText } from '../utils/spinner-text.js';
18
18
  import { guardSleepingEnv, resolveSleepTarget } from '../utils/sleep-state.js';
@@ -131,7 +131,7 @@ async function runRollbackMain(input = {}) {
131
131
 
132
132
  const targetGuard = guardComputeTarget({ cwd, command: 'Rollback', supported: ['ecs'] });
133
133
  if (targetGuard) {
134
- const functionName = `${projectName}${readResourceSuffix(cwd)}-fn`;
134
+ const functionName = safeSuffixedName(`${projectName}${readResourceSuffix(cwd)}`, '-fn', 64);
135
135
  trackEvent('rollback_target_unsupported', { projectName, actual: targetGuard.actual });
136
136
  return failCommand({
137
137
  message: targetGuard.message,
@@ -135,7 +135,7 @@ export async function runLambdaStatus(input = {}) {
135
135
  const namespacedProject = resolveNamespacedProject(projectName, options, cwd);
136
136
  const functionName = typeof options.functionName === 'string' && options.functionName.trim()
137
137
  ? options.functionName.trim()
138
- : `${namespacedProject}${readResourceSuffix(cwd)}-fn`;
138
+ : safeSuffixedName(`${namespacedProject}${readResourceSuffix(cwd)}`, '-fn', 64);
139
139
  const asJson = Boolean(options.json);
140
140
  const runSync = options.spawnSyncImpl || spawnSync;
141
141
 
@@ -140,6 +140,19 @@ export function injectLambdaAdapter(dockerContent, port) {
140
140
  // master-secret IAM policy (indexing an empty `master_user_secret` tuple fails
141
141
  // planning) and appends the `random_password` resource. No-op for ECS content
142
142
  // or content that was already converted.
143
+ const SAFE_NAME_KEYS = ['identifier_safe_name', 'db_name_base', 'db_name_safe_name', 'cluster_safe_name', 'instance_safe_name', 'database_name_base', 'database_name_safe_name'];
144
+
145
+ function realignSurvivingSafeNames(content) {
146
+ const present = SAFE_NAME_KEYS.filter((key) => new RegExp(`^\\s*${key}\\s*=`, 'm').test(content));
147
+ if (present.length === 0) return content;
148
+ const width = Math.max(...present.map((key) => key.length));
149
+ let out = content;
150
+ for (const key of present) {
151
+ out = out.replace(new RegExp(`^(\\s*)${key}\\s*=`, 'm'), (_, indent) => `${indent}${key}${' '.repeat(width - key.length + 1)}=`);
152
+ }
153
+ return out;
154
+ }
155
+
143
156
  export function convertDatabaseTfForLambda(databaseTfContent) {
144
157
  let content = String(databaseTfContent ?? '');
145
158
  if (!content.includes('manage_master_user_password = true')) return content;
@@ -151,6 +164,12 @@ export function convertDatabaseTfForLambda(databaseTfContent) {
151
164
  ` # Lambda targets use an explicit Terraform-managed password (see\n # random_password.db_password below) so the value can flow into the\n # function's DB_PASSWORD environment variable without a Secrets Manager\n # VPC endpoint.\n ${passwordAttr} = random_password.db_password.result`
152
165
  );
153
166
  content = content.replace('# 4. IAM Permission for RDS Master Password Secret\n', '');
167
+ // The policy's safe-name local dangles once the block below is gone —
168
+ // strip the line too or tflint flags an unused declaration. It was
169
+ // the longest key in its run, so re-pad the survivors to the new
170
+ // longest or the rendered file fails fmt -check.
171
+ content = content.replace(/^\s*secret_policy_safe_name\s*=.*\n/m, '');
172
+ content = realignSurvivingSafeNames(content);
154
173
  const resource = findResourceBlock(content, 'aws_iam_role_policy', 'rds_secret_access');
155
174
  if (resource) {
156
175
  const lineStart = content.lastIndexOf('\n', resource.headerIdx - 1) + 1;
@@ -25,6 +25,12 @@ function resolveActualProjectName(rawName) {
25
25
  if (actualProjectName !== String(rawName ?? '').trim()) {
26
26
  console.log(color.dim(`Project name sanitized to "${actualProjectName}" for AWS resource compatibility.`));
27
27
  }
28
+ // Downstream truncation is silent (CI role heads keep ~29 chars,
29
+ // the state bucket ~42) with uniqueness preserved via the
30
+ // resource suffix — say so once at decision time instead.
31
+ if (actualProjectName.length > 29) {
32
+ console.log(color.yellow(`⚠️ "${actualProjectName}" is ${actualProjectName.length} chars: CI role names truncate to the first ~29 and the state bucket to the first ~42 (uniqueness preserved via the suffix). Shorter names stay fully readable.`));
33
+ }
28
34
  return actualProjectName;
29
35
  }
30
36
 
package/src/utils/rds.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DescribeDBInstancesCommand, DescribeDBClustersCommand } from '@aws-sdk/client-rds';
2
- import { resolveProjectName, resolveWorkspaceSuffix, readResourceSuffix } from './resolvers.js';
2
+ import { resolveProjectName, resolveWorkspaceSuffix, readResourceSuffix, safeSuffixedName } from './resolvers.js';
3
3
  import { normalizeOptions } from './args.js';
4
4
 
5
5
  // Error names the RDS API returns for a missing instance across SDK shapes.
@@ -118,24 +118,26 @@ export function isValidSnapshotId(id) {
118
118
  }
119
119
 
120
120
  // Database identifier for the current project/workspace. An explicit
121
- // `--db-identifier` override wins; otherwise `<appName>-db`.
121
+ // `--db-identifier` override wins; otherwise `<appName>-db`, hash-suffixed
122
+ // past the 63-char cap exactly like identifier_safe_name in database.tf.
122
123
  export function resolveDbIdentifier(options = {}, cwd = process.cwd()) {
123
124
  const opts = normalizeOptions(options);
124
125
  if (typeof opts.dbIdentifier === 'string' && opts.dbIdentifier.trim()) {
125
126
  return opts.dbIdentifier.trim();
126
127
  }
127
128
  const base = resolveProjectName(opts, cwd);
128
- return `${base}${resolveWorkspaceSuffix(opts, cwd)}${readResourceSuffix(cwd)}-db`;
129
+ return safeSuffixedName(`${base}${resolveWorkspaceSuffix(opts, cwd)}${readResourceSuffix(cwd)}`, '-db', 63);
129
130
  }
130
131
 
131
132
  // Aurora cluster identifier for the current project/workspace. An explicit
132
133
  // `--db-identifier` override wins (tried as both kinds); otherwise
133
- // `<appName>-db-cluster`, matching the generated cluster_identifier.
134
+ // `<appName>-db-cluster`, hash-suffixed past the 63-char cap exactly
135
+ // like cluster_safe_name in database-aurora-postgresql.tf.
134
136
  export function resolveDbClusterIdentifier(options = {}, cwd = process.cwd()) {
135
137
  const opts = normalizeOptions(options);
136
138
  if (typeof opts.dbIdentifier === 'string' && opts.dbIdentifier.trim()) {
137
139
  return opts.dbIdentifier.trim();
138
140
  }
139
141
  const base = resolveProjectName(opts, cwd);
140
- return `${base}${resolveWorkspaceSuffix(opts, cwd)}${readResourceSuffix(cwd)}-db-cluster`;
142
+ return safeSuffixedName(`${base}${resolveWorkspaceSuffix(opts, cwd)}${readResourceSuffix(cwd)}`, '-db-cluster', 63);
141
143
  }
@@ -332,9 +332,9 @@ export function resolveLogGroup(options = {}, cwd = process.cwd()) {
332
332
  const projectName = resolveProjectName(opts, base);
333
333
  const suffixed = `${projectName}${readResourceSuffix(base)}`;
334
334
  // Lambda functions log to /aws/lambda/<fn> (see main-lambda.tf), where
335
- // the function name is `<app>-fn`.
335
+ // the function name is `<app>-fn`, hash-suffixed past 64 chars.
336
336
  if (readTerraformComputeTarget(base) === 'lambda') {
337
- return `/aws/lambda/${suffixed}-fn`;
337
+ return `/aws/lambda/${safeSuffixedName(suffixed, '-fn', 64)}`;
338
338
  }
339
339
  return `/ecs/${suffixed}`;
340
340
  }
@@ -24,6 +24,8 @@ env:
24
24
  PREVIEW_CLUSTER: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}-cluster
25
25
  PREVIEW_SERVICE: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}-service
26
26
  PREVIEW_TASK_FAMILY: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}-task
27
+ PREVIEW_WORKER_SERVICE: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}-worker-service
28
+ PREVIEW_WORKER_TASK_FAMILY: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}-worker-task
27
29
 
28
30
  permissions:
29
31
  id-token: write
@@ -168,6 +170,66 @@ jobs:
168
170
  exit 1
169
171
  fi
170
172
 
173
+ # The worker ships the same static :pr-N image as web, so it gets
174
+ # the same digest-pinned treatment — otherwise it would run the
175
+ # first push's code forever while web moves on. Skipped on
176
+ # workerless projects (deploy-workflow guard).
177
+ - name: Register preview worker task definition revision
178
+ id: register-preview-worker-task-def
179
+ if: hashFiles('terraform/worker.tf') != '' && steps.aws-creds.outcome == 'success'
180
+ env:
181
+ ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
182
+ run: |
183
+ DIGEST=$(aws ecr describe-images \
184
+ --repository-name ${{ env.ECR_REPOSITORY }} \
185
+ --image-ids imageTag=${{ env.WORKSPACE }} \
186
+ --query 'imageDetails[0].imageDigest' \
187
+ --output text \
188
+ --region ${{ env.AWS_REGION }})
189
+ IMAGE_URI=${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}@${DIGEST}
190
+ TASK_DEF=$(aws ecs describe-task-definition \
191
+ --task-definition ${{ env.PREVIEW_WORKER_TASK_FAMILY }} \
192
+ --region ${{ env.AWS_REGION }} \
193
+ --query 'taskDefinition' \
194
+ --output json)
195
+ NEW_TASK_DEF=$(echo "$TASK_DEF" | jq \
196
+ --arg IMAGE "$IMAGE_URI" \
197
+ '.containerDefinitions[0].image = $IMAGE | del(.taskDefinitionArn, .revision, .status, .requiresAttributes, .compatibilities, .registeredAt, .registeredBy, .deregisteredAt)')
198
+ NEW_TASK_ARN=$(aws ecs register-task-definition \
199
+ --region ${{ env.AWS_REGION }} \
200
+ --cli-input-json "$NEW_TASK_DEF" \
201
+ --query 'taskDefinition.taskDefinitionArn' \
202
+ --output text)
203
+ echo "task-arn=$NEW_TASK_ARN" >> $GITHUB_OUTPUT
204
+
205
+ - name: Force preview worker deployment
206
+ if: hashFiles('terraform/worker.tf') != '' && steps.aws-creds.outcome == 'success'
207
+ run: |
208
+ aws ecs update-service \
209
+ --cluster ${{ env.PREVIEW_CLUSTER }} \
210
+ --service ${{ env.PREVIEW_WORKER_SERVICE }} \
211
+ --task-definition ${{ steps.register-preview-worker-task-def.outputs.task-arn }} \
212
+ --force-new-deployment \
213
+ --region ${{ env.AWS_REGION }}
214
+
215
+ - name: Wait for preview worker rollout
216
+ if: hashFiles('terraform/worker.tf') != '' && steps.aws-creds.outcome == 'success'
217
+ run: |
218
+ aws ecs wait services-stable \
219
+ --cluster ${{ env.PREVIEW_CLUSTER }} \
220
+ --services ${{ env.PREVIEW_WORKER_SERVICE }} \
221
+ --region ${{ env.AWS_REGION }}
222
+ PRIMARY_TD=$(aws ecs describe-services \
223
+ --cluster ${{ env.PREVIEW_CLUSTER }} \
224
+ --services ${{ env.PREVIEW_WORKER_SERVICE }} \
225
+ --query 'services[0].deployments[?status==`PRIMARY`].taskDefinition' \
226
+ --output text \
227
+ --region ${{ env.AWS_REGION }})
228
+ if [ "$PRIMARY_TD" != "${{ steps.register-preview-worker-task-def.outputs.task-arn }}" ]; then
229
+ echo "Preview worker rollout of ${{ steps.register-preview-worker-task-def.outputs.task-arn }} did not stick (PRIMARY runs $PRIMARY_TD) — the deployment failed or rolled back." >&2
230
+ exit 1
231
+ fi
232
+
171
233
  # Every push redeploys the preview: clear its CDN so new HTML shows
172
234
  # immediately instead of serving stale pages until TTL expiry.
173
235
  - name: Invalidate CloudFront
@@ -15,10 +15,11 @@ locals {
15
15
  # Length-safe names: short names render byte-identically; over-cap
16
16
  # names hash-suffix instead of failing validation. Mirrors
17
17
  # safeSuffixedName in resolvers.js.
18
- scheduler_role_safe_name = length("${local.app_name}-cron-scheduler-role") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 20)}-${substr(md5(local.app_name), 0, 5)}-cron-scheduler-role" : "${local.app_name}-cron-scheduler-role"
19
- schedule_full_name = "${local.app_name}-cron-{{CRON_NAME}}"
20
- schedule_safe_name = length(local.schedule_full_name) > 64 ? "${substr(local.schedule_full_name, 0, 64 - 1 - 5)}-${substr(md5(local.schedule_full_name), 0, 5)}" : local.schedule_full_name
21
- schedule_group_safe_name = length("${local.app_name}-crons") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 6)}-${substr(md5(local.app_name), 0, 5)}-crons" : "${local.app_name}-crons"
18
+ scheduler_role_safe_name = length("${local.app_name}-cron-scheduler-role") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 20)}-${substr(md5(local.app_name), 0, 5)}-cron-scheduler-role" : "${local.app_name}-cron-scheduler-role"
19
+ schedule_full_name = "${local.app_name}-cron-{{CRON_NAME}}"
20
+ schedule_safe_name = length(local.schedule_full_name) > 64 ? "${substr(local.schedule_full_name, 0, 64 - 1 - 5)}-${substr(md5(local.schedule_full_name), 0, 5)}" : local.schedule_full_name
21
+ schedule_group_safe_name = length("${local.app_name}-crons") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 6)}-${substr(md5(local.app_name), 0, 5)}-crons" : "${local.app_name}-crons"
22
+ scheduler_policy_safe_name = length("${local.app_name}-cron-scheduler-policy") > 128 ? "${substr(local.app_name, 0, 128 - 1 - 5 - 22)}-${substr(md5(local.app_name), 0, 5)}-cron-scheduler-policy" : "${local.app_name}-cron-scheduler-policy"
22
23
  }
23
24
 
24
25
  # --- IAM Role assumed by EventBridge Scheduler ---
@@ -41,7 +42,7 @@ resource "aws_iam_role" "scheduler_cron_role" {
41
42
 
42
43
  # --- Least-privilege permission to invoke the function ---
43
44
  resource "aws_iam_role_policy" "scheduler_cron_policy" {
44
- name = "${local.app_name}-cron-scheduler-policy"
45
+ name = local.scheduler_policy_safe_name
45
46
  role = aws_iam_role.scheduler_cron_role.id
46
47
  policy = jsonencode({
47
48
  Version = "2012-10-17"
@@ -9,10 +9,11 @@ locals {
9
9
  # Length-safe names: short names render byte-identically; over-cap
10
10
  # names hash-suffix instead of failing validation. Mirrors
11
11
  # safeSuffixedName in resolvers.js.
12
- scheduler_role_safe_name = length("${local.app_name}-cron-scheduler-role") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 20)}-${substr(md5(local.app_name), 0, 5)}-cron-scheduler-role" : "${local.app_name}-cron-scheduler-role"
13
- schedule_full_name = "${local.app_name}-cron-{{CRON_NAME}}"
14
- schedule_safe_name = length(local.schedule_full_name) > 64 ? "${substr(local.schedule_full_name, 0, 64 - 1 - 5)}-${substr(md5(local.schedule_full_name), 0, 5)}" : local.schedule_full_name
15
- schedule_group_safe_name = length("${local.app_name}-crons") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 6)}-${substr(md5(local.app_name), 0, 5)}-crons" : "${local.app_name}-crons"
12
+ scheduler_role_safe_name = length("${local.app_name}-cron-scheduler-role") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 20)}-${substr(md5(local.app_name), 0, 5)}-cron-scheduler-role" : "${local.app_name}-cron-scheduler-role"
13
+ schedule_full_name = "${local.app_name}-cron-{{CRON_NAME}}"
14
+ schedule_safe_name = length(local.schedule_full_name) > 64 ? "${substr(local.schedule_full_name, 0, 64 - 1 - 5)}-${substr(md5(local.schedule_full_name), 0, 5)}" : local.schedule_full_name
15
+ schedule_group_safe_name = length("${local.app_name}-crons") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 6)}-${substr(md5(local.app_name), 0, 5)}-crons" : "${local.app_name}-crons"
16
+ scheduler_policy_safe_name = length("${local.app_name}-cron-scheduler-policy") > 128 ? "${substr(local.app_name, 0, 128 - 1 - 5 - 22)}-${substr(md5(local.app_name), 0, 5)}-cron-scheduler-policy" : "${local.app_name}-cron-scheduler-policy"
16
17
  }
17
18
 
18
19
  # --- IAM Role assumed by EventBridge Scheduler ---
@@ -35,7 +36,7 @@ resource "aws_iam_role" "scheduler_cron_role" {
35
36
 
36
37
  # --- Least-privilege permission to launch the scheduled task ---
37
38
  resource "aws_iam_role_policy" "scheduler_cron_policy" {
38
- name = "${local.app_name}-cron-scheduler-policy"
39
+ name = local.scheduler_policy_safe_name
39
40
  role = aws_iam_role.scheduler_cron_role.id
40
41
  policy = jsonencode({
41
42
  Version = "2012-10-17"
@@ -10,6 +10,13 @@
10
10
  # --- SES Domain Identity ---
11
11
  # Account-wide singletons per domain/region: scoped to the default
12
12
  # (production) workspace so PR preview teardowns never delete them.
13
+ locals {
14
+ # Length-safe names: short names render byte-identically; over-cap
15
+ # names hash-suffix instead of failing validation (config sets
16
+ # cap at 64, policies at 128). Mirrors safeSuffixedName.
17
+ config_set_safe_name = length("${local.app_name}-ses-events") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 11)}-${substr(md5(local.app_name), 0, 5)}-ses-events" : "${local.app_name}-ses-events"
18
+ send_policy_safe_name = length("${local.app_name}-ses-send") > 128 ? "${substr(local.app_name, 0, 128 - 1 - 5 - 9)}-${substr(md5(local.app_name), 0, 5)}-ses-send" : "${local.app_name}-ses-send"
19
+ }
13
20
  resource "aws_ses_domain_identity" "ses" {
14
21
  count = terraform.workspace == "default" ? 1 : 0
15
22
  domain = "{{SES_DOMAIN}}"
@@ -34,7 +41,7 @@ resource "aws_ses_domain_mail_from" "ses" {
34
41
  # under the verified domain above verify automatically.
35
42
  resource "aws_ses_configuration_set" "main" {
36
43
  count = terraform.workspace == "default" ? 1 : 0
37
- name = "${local.app_name}-ses-events"
44
+ name = local.config_set_safe_name
38
45
  reputation_metrics_enabled = true
39
46
  sending_enabled = true
40
47
  }
@@ -62,7 +69,7 @@ resource "aws_sesv2_email_identity" "sender" {
62
69
  {{SES_ROUTE53_RECORDS_BLOCK}}
63
70
  # --- Least-Privilege IAM Policy for the ECS Task Role ---
64
71
  resource "aws_iam_role_policy" "ses_send" {
65
- name = "${local.app_name}-ses-send"
72
+ name = local.send_policy_safe_name
66
73
  role = aws_iam_role.task_role.id
67
74
  policy = jsonencode({
68
75
  Version = "2012-10-17"
@@ -5,16 +5,25 @@
5
5
  # Billing: no fixed hourly instance cost (usage-billed). The first 1M SQS
6
6
  # requests/mo are free, then $0.40 per million requests.
7
7
 
8
+ locals {
9
+ # Length-safe names: short names render byte-identically; over-cap
10
+ # names hash-suffix instead of failing validation (queues cap at
11
+ # 80, policies at 128). Mirrors safeSuffixedName in resolvers.js.
12
+ queue_safe_name = length("${local.app_name}-queue") > 80 ? "${substr(local.app_name, 0, 80 - 1 - 5 - 6)}-${substr(md5(local.app_name), 0, 5)}-queue" : "${local.app_name}-queue"
13
+ dlq_safe_name = length("${local.app_name}-dlq") > 80 ? "${substr(local.app_name, 0, 80 - 1 - 5 - 4)}-${substr(md5(local.app_name), 0, 5)}-dlq" : "${local.app_name}-dlq"
14
+ queue_policy_safe_name = length("${local.app_name}-queue-sqs-access") > 128 ? "${substr(local.app_name, 0, 128 - 1 - 5 - 17)}-${substr(md5(local.app_name), 0, 5)}-queue-sqs-access" : "${local.app_name}-queue-sqs-access"
15
+ }
16
+
8
17
  # --- Dead-Letter Queue ---
9
18
  resource "aws_sqs_queue" "dlq" {
10
- name = "${local.app_name}-dlq"
19
+ name = local.dlq_safe_name
11
20
  message_retention_seconds = 1209600
12
21
  sqs_managed_sse_enabled = true
13
22
  }
14
23
 
15
24
  # --- Primary Queue ---
16
25
  resource "aws_sqs_queue" "main" {
17
- name = "${local.app_name}-queue"
26
+ name = local.queue_safe_name
18
27
  visibility_timeout_seconds = 30
19
28
  message_retention_seconds = 345600
20
29
  receive_wait_time_seconds = 20
@@ -27,7 +36,7 @@ resource "aws_sqs_queue" "main" {
27
36
 
28
37
  # --- Least-Privilege IAM Policy for the ECS Task Role ---
29
38
  resource "aws_iam_role_policy" "queue_sqs_access" {
30
- name = "${local.app_name}-queue-sqs-access"
39
+ name = local.queue_policy_safe_name
31
40
  role = aws_iam_role.task_role.id
32
41
  policy = jsonencode({
33
42
  Version = "2012-10-17"
@@ -19,21 +19,54 @@ resource "aws_security_group" "rds" {
19
19
  }
20
20
  }
21
21
 
22
- # 2b. No SSL parameter group yet: this template floats its engine
23
- # version by design, and a cluster parameter group family must match
24
- # it exactly — forcing a family would pin the engine by side effect.
25
- # Deferred until the engine-version decision; the instance engines
26
- # already enforce TLS via their own groups.
22
+ # 2b. TLS enforcement: the cluster floats its engine version by
23
+ # design, so resolve the regional default at plan time and derive
24
+ # the matching family — no pin, no mismatch, ever. (default_only
25
+ # spans every major's default, so latest pins the lookup down to
26
+ # one; if AWS ever defaults new clusters elsewhere, the family
27
+ # mismatch fails loud at apply instead of enforcing silently
28
+ # wrong.) Pending reboot like the instance groups.
29
+ data "aws_rds_engine_version" "default" {
30
+ engine = "aurora-postgresql"
31
+ default_only = true
32
+ latest = true
33
+ }
34
+
35
+ locals {
36
+ aurora_major = split(".", data.aws_rds_engine_version.default.version_actual)[0]
37
+
38
+ # Length-safe names: short names render byte-identically; over-cap
39
+ # names hash-suffix instead of failing validation (identifiers and
40
+ # database names cap at 63, policies at 128). Mirrors
41
+ # safeSuffixedName in resolvers.js.
42
+ cluster_safe_name = length("${local.app_name}-db-cluster") > 63 ? "${substr(local.app_name, 0, 63 - 1 - 5 - 11)}-${substr(md5(local.app_name), 0, 5)}-db-cluster" : "${local.app_name}-db-cluster"
43
+ instance_safe_name = length("${local.app_name}-db-instance-1") > 63 ? "${substr(local.app_name, 0, 63 - 1 - 5 - 14)}-${substr(md5(local.app_name), 0, 5)}-db-instance-1" : "${local.app_name}-db-instance-1"
44
+ database_name_base = replace(local.app_name, "-", "")
45
+ database_name_safe_name = length(local.database_name_base) > 63 ? "${substr(local.database_name_base, 0, 58)}${substr(md5(local.database_name_base), 0, 5)}" : local.database_name_base
46
+ secret_policy_safe_name = length("${local.app_name}-rds-secret-policy") > 128 ? "${substr(local.app_name, 0, 128 - 1 - 5 - 18)}-${substr(md5(local.app_name), 0, 5)}-rds-secret-policy" : "${local.app_name}-rds-secret-policy"
47
+ }
48
+
49
+ resource "aws_rds_cluster_parameter_group" "ssl" {
50
+ name = "${local.app_name}-aurorapg${local.aurora_major}"
51
+ family = "aurora-postgresql${local.aurora_major}"
52
+
53
+ parameter {
54
+ name = "rds.force_ssl"
55
+ value = "1"
56
+ apply_method = "pending-reboot"
57
+ }
58
+ }
59
+
27
60
  # 3. The Aurora PostgreSQL Serverless v2 Cluster (scale-to-zero)
28
61
  resource "aws_rds_cluster" "postgres" {
29
- cluster_identifier = "${local.app_name}-db-cluster"
62
+ cluster_identifier = local.cluster_safe_name
30
63
  engine = "aurora-postgresql"
31
64
 
32
65
  # engine_version is intentionally omitted: AWS retires Aurora minor versions
33
66
  # (e.g. 16.4 in us-east-2), so new clusters take the regional default.
34
67
  # Strip dashes for the database name: Aurora database_name must begin with a
35
68
  # letter and contain only alphanumeric characters (e.g. my-project -> myproject)
36
- database_name = replace(local.app_name, "-", "")
69
+ database_name = local.database_name_safe_name
37
70
  master_username = "dbadmin"
38
71
 
39
72
  # AWS automatically creates and manages the secret in Secrets Manager!
@@ -42,6 +75,10 @@ resource "aws_rds_cluster" "postgres" {
42
75
  db_subnet_group_name = aws_db_subnet_group.main.name
43
76
  vpc_security_group_ids = [aws_security_group.rds.id]
44
77
 
78
+ # TLS enforcement (see the parameter group above). In-place update,
79
+ # never a replacement.
80
+ db_cluster_parameter_group_name = aws_rds_cluster_parameter_group.ssl.name
81
+
45
82
  skip_final_snapshot = true
46
83
  storage_encrypted = true
47
84
 
@@ -78,7 +115,7 @@ variable "grada_allow_data_loss" {
78
115
  }
79
116
 
80
117
  resource "aws_rds_cluster_instance" "postgres" {
81
- identifier = "${local.app_name}-db-instance-1"
118
+ identifier = local.instance_safe_name
82
119
  cluster_identifier = aws_rds_cluster.postgres.id
83
120
  instance_class = "db.serverless"
84
121
  engine = aws_rds_cluster.postgres.engine
@@ -89,7 +126,7 @@ resource "aws_rds_cluster_instance" "postgres" {
89
126
 
90
127
  # 4. IAM Permission for RDS Master Password Secret
91
128
  resource "aws_iam_role_policy" "rds_secret_access" {
92
- name = "${local.app_name}-rds-secret-policy"
129
+ name = local.secret_policy_safe_name
93
130
  role = aws_iam_role.execution_role.id
94
131
  policy = jsonencode({
95
132
  Version = "2012-10-17"
@@ -1,3 +1,14 @@
1
+ # 0. Length-safe names: short names render byte-identically; over-cap
2
+ # names hash-suffix instead of failing validation (identifiers cap
3
+ # at 63, database names at 64, policies at 128). Mirrors
4
+ # safeSuffixedName in resolvers.js.
5
+ locals {
6
+ identifier_safe_name = length("${local.app_name}-db") > 63 ? "${substr(local.app_name, 0, 63 - 1 - 5 - 3)}-${substr(md5(local.app_name), 0, 5)}-db" : "${local.app_name}-db"
7
+ db_name_base = replace(local.app_name, "-", "")
8
+ db_name_safe_name = length(local.db_name_base) > 64 ? "${substr(local.db_name_base, 0, 59)}${substr(md5(local.db_name_base), 0, 5)}" : local.db_name_base
9
+ secret_policy_safe_name = length("${local.app_name}-rds-secret-policy") > 128 ? "${substr(local.app_name, 0, 128 - 1 - 5 - 18)}-${substr(md5(local.app_name), 0, 5)}-rds-secret-policy" : "${local.app_name}-rds-secret-policy"
10
+ }
11
+
1
12
  # 1. Database Subnet Group (isolated subnets live in network.tf, shared
2
13
  # with ElastiCache so every data-plane group stays off public subnets)
3
14
  resource "aws_db_subnet_group" "main" {
@@ -36,7 +47,7 @@ resource "aws_db_parameter_group" "ssl" {
36
47
 
37
48
  # 3. The MySQL Instance
38
49
  resource "aws_db_instance" "postgres" {
39
- identifier = "${local.app_name}-db"
50
+ identifier = local.identifier_safe_name
40
51
  engine = "mysql"
41
52
  engine_version = "8.0"
42
53
  instance_class = "db.t4g.micro"
@@ -56,7 +67,7 @@ resource "aws_db_instance" "postgres" {
56
67
 
57
68
  # Strip dashes for the database name: RDS MySQL db_name must begin with a
58
69
  # letter and contain only alphanumeric characters (e.g. my-project -> myproject)
59
- db_name = replace(local.app_name, "-", "")
70
+ db_name = local.db_name_safe_name
60
71
  username = "dbadmin"
61
72
 
62
73
  # AWS automatically creates and manages the secret in Secrets Manager!
@@ -84,7 +95,7 @@ variable "grada_allow_data_loss" {
84
95
 
85
96
  # 4. IAM Permission for RDS Master Password Secret
86
97
  resource "aws_iam_role_policy" "rds_secret_access" {
87
- name = "${local.app_name}-rds-secret-policy"
98
+ name = local.secret_policy_safe_name
88
99
  role = aws_iam_role.execution_role.id
89
100
  policy = jsonencode({
90
101
  Version = "2012-10-17"
@@ -1,3 +1,14 @@
1
+ # 0. Length-safe names: short names render byte-identically; over-cap
2
+ # names hash-suffix instead of failing validation (identifiers and
3
+ # database names cap at 63, policies at 128). Mirrors
4
+ # safeSuffixedName in resolvers.js.
5
+ locals {
6
+ identifier_safe_name = length("${local.app_name}-db") > 63 ? "${substr(local.app_name, 0, 63 - 1 - 5 - 3)}-${substr(md5(local.app_name), 0, 5)}-db" : "${local.app_name}-db"
7
+ db_name_base = replace(local.app_name, "-", "_")
8
+ db_name_safe_name = length(local.db_name_base) > 63 ? "${substr(local.db_name_base, 0, 57)}_${substr(md5(local.db_name_base), 0, 5)}" : local.db_name_base
9
+ secret_policy_safe_name = length("${local.app_name}-rds-secret-policy") > 128 ? "${substr(local.app_name, 0, 128 - 1 - 5 - 18)}-${substr(md5(local.app_name), 0, 5)}-rds-secret-policy" : "${local.app_name}-rds-secret-policy"
10
+ }
11
+
1
12
  # 1. Database Subnet Group (isolated subnets live in network.tf, shared
2
13
  # with ElastiCache so every data-plane group stays off public subnets)
3
14
  resource "aws_db_subnet_group" "main" {
@@ -36,7 +47,7 @@ resource "aws_db_parameter_group" "ssl" {
36
47
 
37
48
  # 3. The PostgreSQL Instance
38
49
  resource "aws_db_instance" "postgres" {
39
- identifier = "${local.app_name}-db"
50
+ identifier = local.identifier_safe_name
40
51
  engine = "postgres"
41
52
  engine_version = "16"
42
53
  instance_class = "db.t4g.micro"
@@ -55,7 +66,7 @@ resource "aws_db_instance" "postgres" {
55
66
  parameter_group_name = aws_db_parameter_group.ssl.name
56
67
 
57
68
  # Clean up dashes for the database name (e.g. my-project -> my_project)
58
- db_name = replace(local.app_name, "-", "_")
69
+ db_name = local.db_name_safe_name
59
70
  username = "dbadmin"
60
71
 
61
72
  # AWS automatically creates and manages the secret in Secrets Manager!
@@ -83,7 +94,7 @@ variable "grada_allow_data_loss" {
83
94
 
84
95
  # 4. IAM Permission for RDS Master Password Secret
85
96
  resource "aws_iam_role_policy" "rds_secret_access" {
86
- name = "${local.app_name}-rds-secret-policy"
97
+ name = local.secret_policy_safe_name
87
98
  role = aws_iam_role.execution_role.id
88
99
  policy = jsonencode({
89
100
  Version = "2012-10-17"
@@ -46,11 +46,13 @@ locals {
46
46
  # safeSuffixedName in resolvers.js.
47
47
  task_role_safe_name = length("${local.app_name}-task-role") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 10)}-${substr(md5(local.app_name), 0, 5)}-task-role" : "${local.app_name}-task-role"
48
48
  execution_role_safe_name = length("${local.app_name}-execution-role") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 16)}-${substr(md5(local.app_name), 0, 5)}-execution-role" : "${local.app_name}-execution-role"
49
+ fn_safe_name = length("${local.app_name}-fn") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 3)}-${substr(md5(local.app_name), 0, 5)}-fn" : "${local.app_name}-fn"
50
+ secrets_policy_safe_name = length("${local.app_name}-app-secrets-policy") > 128 ? "${substr(local.app_name, 0, 128 - 1 - 5 - 19)}-${substr(md5(local.app_name), 0, 5)}-app-secrets-policy" : "${local.app_name}-app-secrets-policy"
49
51
  }
50
52
 
51
53
  # --- CloudWatch Logs ---
52
54
  resource "aws_cloudwatch_log_group" "app" {
53
- name = "/aws/lambda/${local.app_name}-fn"
55
+ name = "/aws/lambda/${local.fn_safe_name}"
54
56
  retention_in_days = 30
55
57
  }
56
58
 
@@ -133,7 +135,7 @@ resource "aws_iam_role_policy_attachment" "lambda_vpc_access" {
133
135
  # reach Secrets Manager directly; VPC-attached functions should prefer
134
136
  # plain environment variables injected with `grada add`).
135
137
  resource "aws_iam_role_policy" "app_secrets_access" {
136
- name = "${local.app_name}-app-secrets-policy"
138
+ name = local.secrets_policy_safe_name
137
139
  role = aws_iam_role.task_role.id
138
140
  policy = jsonencode({
139
141
  Version = "2012-10-17"
@@ -149,7 +151,7 @@ resource "aws_iam_role_policy" "app_secrets_access" {
149
151
 
150
152
  # --- Lambda Function (container image + Web Adapter) ---
151
153
  resource "aws_lambda_function" "app" {
152
- function_name = "${local.app_name}-fn"
154
+ function_name = local.fn_safe_name
153
155
  role = aws_iam_role.task_role.arn
154
156
  package_type = "Image"
155
157
  # Lambda requires an image in a private same-account ECR repository.
@@ -60,6 +60,7 @@ locals {
60
60
  tg_safe_name = length("${local.app_name}-tg") > 32 ? "${substr(local.app_name, 0, 32 - 1 - 5 - 3)}-${substr(md5(local.app_name), 0, 5)}-tg" : "${local.app_name}-tg"
61
61
  task_role_safe_name = length("${local.app_name}-task-role") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 10)}-${substr(md5(local.app_name), 0, 5)}-task-role" : "${local.app_name}-task-role"
62
62
  execution_role_safe_name = length("${local.app_name}-execution-role") > 64 ? "${substr(local.app_name, 0, 64 - 1 - 5 - 16)}-${substr(md5(local.app_name), 0, 5)}-execution-role" : "${local.app_name}-execution-role"
63
+ exec_policy_safe_name = length("${local.app_name}-ecs-exec-policy") > 128 ? "${substr(local.app_name, 0, 128 - 1 - 5 - 16)}-${substr(md5(local.app_name), 0, 5)}-ecs-exec-policy" : "${local.app_name}-ecs-exec-policy"
63
64
  }
64
65
 
65
66
  # --- CloudWatch Logs ---
@@ -125,7 +126,7 @@ resource "aws_iam_role" "task_role" {
125
126
  # --- IAM: ECS Exec (SSM) permissions for the task role ---
126
127
  # Required for `npx grada-run exec` — lets Fargate open an SSM session.
127
128
  resource "aws_iam_role_policy" "ecs_exec" {
128
- name = "${local.app_name}-ecs-exec-policy"
129
+ name = local.exec_policy_safe_name
129
130
  role = aws_iam_role.task_role.id
130
131
  policy = jsonencode({
131
132
  Version = "2012-10-17"
@@ -49,18 +49,16 @@ locals {
49
49
  # ${prod_prefix}-* pattern matches prod only. Anchoring also keeps
50
50
  # the boundary under the 6144-char managed-policy quota that broke
51
51
  # tier1 E2E at a 24-char prefix — prefer one anchored wildcard over
52
- # several exact ARNs when adding entries. Headroom is now single
53
- # digits at 32-char prefixes: the next IAM addition must economize
54
- # (shorter Sids, fewer verbs, or slimmer patterns) before extending.
52
+ # several exact ARNs when adding entries. Headroom is 78 chars
53
+ # at 32-char prefixes (316 at 24): the shutdown-into-execution
54
+ # merger paid for the lifecycle/snapshot/table data verbs, so
55
+ # additions still fit — but the next one re-runs the quota probe
56
+ # before extending.
55
57
  guardrail_compute_abuse_resources = ["*"]
56
58
  guardrail_snapshot_sharing_resources = ["*"]
57
59
  guardrail_state_destruction_resources = [
58
60
  "arn:aws:s3:::{{STATE_BUCKET}}*",
59
61
  ]
60
- guardrail_ecs_shutdown_resources = [
61
- "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster/${local.prod_prefix}-cluster",
62
- "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-cluster/*",
63
- ]
64
62
  guardrail_image_deletion_resources = [
65
63
  "arn:aws:ecr:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:repository/${local.prod_prefix}-repo",
66
64
  ]
@@ -306,7 +304,7 @@ resource "aws_iam_role_policy" "preview_guardrails" {
306
304
  {
307
305
  Sid = "DenySnapshotSharing"
308
306
  Effect = "Deny"
309
- Action = ["rds:ModifyDBSnapshotAttribute"]
307
+ Action = ["rds:Modify*SnapshotAttribute"]
310
308
  Resource = local.guardrail_snapshot_sharing_resources
311
309
  },
312
310
  {
@@ -315,12 +313,6 @@ resource "aws_iam_role_policy" "preview_guardrails" {
315
313
  Action = ["s3:DeleteBucket", "s3:DeleteObjectVersion"]
316
314
  Resource = local.guardrail_state_destruction_resources
317
315
  },
318
- {
319
- Sid = "DenyProdECSShutdown"
320
- Effect = "Deny"
321
- Action = ["ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
322
- Resource = local.guardrail_ecs_shutdown_resources
323
- },
324
316
  {
325
317
  Sid = "DenyProdImageDeletion"
326
318
  Effect = "Deny"
@@ -352,9 +344,15 @@ resource "aws_iam_role_policy" "preview_guardrails" {
352
344
  Resource = local.guardrail_aurora_destruction_resources
353
345
  },
354
346
  {
355
- Sid = "DenyProdTableDeletion"
347
+ # Item data joins the table deny: preview apps use preview
348
+ # tables, so no bounded role ever reads prod items — and the
349
+ # wildcard set below leaves Describe*/List* (plan refresh) and
350
+ # control verbs alone. Streams stay out of reach of this
351
+ # pattern (stream ARNs carry a /stream suffix): accepted, the
352
+ # iterator dance is narrow and unactionable without table reads.
353
+ Sid = "DenyProdTableData"
356
354
  Effect = "Deny"
357
- Action = ["dynamodb:DeleteTable"]
355
+ Action = ["dynamodb:DeleteTable", "dynamodb:Batch*", "dynamodb:*Item", "dynamodb:Query", "dynamodb:Scan", "dynamodb:Execute*", "dynamodb:Transact*"]
358
356
  Resource = local.guardrail_table_deletion_resources
359
357
  },
360
358
  {
@@ -363,9 +361,13 @@ resource "aws_iam_role_policy" "preview_guardrails" {
363
361
  # <db-identifier>-pre-deploy-<sha>) are directly deletable;
364
362
  # automated snapshots can only go away via retention changes or
365
363
  # instance deletion, both already denied above.
366
- Sid = "DenyProdSnapshotDeletion"
364
+ # Copies, snapshot-based restores, and S3 exports authorize
365
+ # the source snapshot (service authorization reference), so
366
+ # denying them here closes the copy-then-read and
367
+ # export-to-attacker-bucket paths. Deletion keeps its verbs.
368
+ Sid = "DenyProdSnapshotData"
367
369
  Effect = "Deny"
368
- Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot"]
370
+ Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot", "rds:Copy*", "rds:Restore*", "rds:StartExportTask"]
369
371
  Resource = local.guardrail_snapshot_deletion_resources
370
372
  },
371
373
  {
@@ -424,9 +426,15 @@ resource "aws_iam_role_policy" "preview_guardrails" {
424
426
  # ARNs while pr-* stays allowed. No describes: plan.yml
425
427
  # refreshes prod state with preview credentials, so describing
426
428
  # prod is legitimate traffic.
429
+ # Service shutdown verbs live here (not in a separate
430
+ # statement): they share the cluster+service resources below,
431
+ # and a twin pair of their own would re-inline ~280 chars of
432
+ # ARNs against the boundary quota. The scheduler carve-out is
433
+ # a no-op for them — the scheduler role can never call
434
+ # Update/DeleteService or DeleteCluster.
427
435
  Sid = "DenyProdTaskExecution"
428
436
  Effect = "Deny"
429
- Action = ["ecs:RunTask", "ecs:StopTask", "ecs:ExecuteCommand", "ecs:CreateService"]
437
+ Action = ["ecs:RunTask", "ecs:StopTask", "ecs:ExecuteCommand", "ecs:CreateService", "ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
430
438
  Resource = local.guardrail_task_execution_resources
431
439
  # The bounded scheduler role must RunTask its task
432
440
  # definition at trigger time. A no-op on this side (the preview
@@ -475,9 +483,14 @@ resource "aws_iam_role_policy" "preview_guardrails" {
475
483
  # is never a task role) so the twins stay identical.
476
484
  # Accepted residual: GetSecretValue + prod state reads (plan
477
485
  # refresh requires both; state additionally exposes adopted
478
- # live values), snapshot export/restore, Bedrock/SES spend
479
- # verbs, DynamoDB data verbs, and RDS Start — follow-ups, not
480
- # oversights.
486
+ # live values), Bedrock/SES spend verbs (denying would gut
487
+ # preview fidelity for AI/email apps — previews are full
488
+ # copies; same-repo guard + PR review are the controls), and
489
+ # DynamoDB stream reads (narrow iterator dance, unactionable
490
+ # without the table reads denied below). Snapshot copy/
491
+ # restore/export, point-in-time restore, DynamoDB item data,
492
+ # and RDS Start all landed as denies; DeleteMessage stays
493
+ # unreachable with Receive denied.
481
494
  Sid = "DenyProdAppData"
482
495
  Effect = "Deny"
483
496
  Action = [
@@ -492,12 +505,13 @@ resource "aws_iam_role_policy" "preview_guardrails" {
492
505
  }
493
506
  },
494
507
  {
495
- # ...nor stop or reboot prod databases. Deliberately
496
- # carve-free: no bounded role ever calls these (sleep/wake
497
- # and db commands run on user credentials).
508
+ # ...nor stop, start, reboot, or point-in-time-restore prod
509
+ # databases. Deliberately carve-free: no bounded role ever
510
+ # calls these (sleep/wake and db commands run on user
511
+ # credentials).
498
512
  Sid = "DenyProdDbLifecycle"
499
513
  Effect = "Deny"
500
- Action = ["rds:Stop*", "rds:Reboot*"]
514
+ Action = ["rds:Stop*", "rds:Reboot*", "rds:Start*", "rds:Restore*"]
501
515
  Resource = local.guardrail_db_lifecycle_resources
502
516
  },
503
517
  ]
@@ -555,7 +569,7 @@ resource "aws_iam_policy" "preview_boundary" {
555
569
  {
556
570
  Sid = "BoundaryDenySnapshotSharing"
557
571
  Effect = "Deny"
558
- Action = ["rds:ModifyDBSnapshotAttribute"]
572
+ Action = ["rds:Modify*SnapshotAttribute"]
559
573
  Resource = local.guardrail_snapshot_sharing_resources
560
574
  },
561
575
  {
@@ -564,12 +578,6 @@ resource "aws_iam_policy" "preview_boundary" {
564
578
  Action = ["s3:DeleteBucket", "s3:DeleteObjectVersion"]
565
579
  Resource = local.guardrail_state_destruction_resources
566
580
  },
567
- {
568
- Sid = "BoundaryDenyECSShutdown"
569
- Effect = "Deny"
570
- Action = ["ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
571
- Resource = local.guardrail_ecs_shutdown_resources
572
- },
573
581
  {
574
582
  Sid = "BoundaryDenyImageDeletion"
575
583
  Effect = "Deny"
@@ -601,15 +609,15 @@ resource "aws_iam_policy" "preview_boundary" {
601
609
  Resource = local.guardrail_aurora_destruction_resources
602
610
  },
603
611
  {
604
- Sid = "BoundaryDenyTableDeletion"
612
+ Sid = "BoundaryDenyTableData"
605
613
  Effect = "Deny"
606
- Action = ["dynamodb:DeleteTable"]
614
+ Action = ["dynamodb:DeleteTable", "dynamodb:Batch*", "dynamodb:*Item", "dynamodb:Query", "dynamodb:Scan", "dynamodb:Execute*", "dynamodb:Transact*"]
607
615
  Resource = local.guardrail_table_deletion_resources
608
616
  },
609
617
  {
610
- Sid = "BoundaryDenySnapshotDeletion"
618
+ Sid = "BoundaryDenySnapshotData"
611
619
  Effect = "Deny"
612
- Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot"]
620
+ Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot", "rds:Copy*", "rds:Restore*", "rds:StartExportTask"]
613
621
  Resource = local.guardrail_snapshot_deletion_resources
614
622
  },
615
623
  {
@@ -625,9 +633,11 @@ resource "aws_iam_policy" "preview_boundary" {
625
633
  Resource = local.guardrail_log_deletion_resources
626
634
  },
627
635
  {
636
+ # Shutdown verbs merged here; see the twin's comment (quota
637
+ # economy — a separate pair would re-inline the ARNs below).
628
638
  Sid = "BoundaryDenyTaskExecution"
629
639
  Effect = "Deny"
630
- Action = ["ecs:RunTask", "ecs:StopTask", "ecs:ExecuteCommand", "ecs:CreateService"]
640
+ Action = ["ecs:RunTask", "ecs:StopTask", "ecs:ExecuteCommand", "ecs:CreateService", "ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
631
641
  Resource = local.guardrail_task_execution_resources
632
642
  # The bounded scheduler role must RunTask its task
633
643
  # definition at trigger time; every other capped caller stays
@@ -674,7 +684,7 @@ resource "aws_iam_policy" "preview_boundary" {
674
684
  {
675
685
  Sid = "BoundaryDenyDbLifecycle"
676
686
  Effect = "Deny"
677
- Action = ["rds:Stop*", "rds:Reboot*"]
687
+ Action = ["rds:Stop*", "rds:Reboot*", "rds:Start*", "rds:Restore*"]
678
688
  Resource = local.guardrail_db_lifecycle_resources
679
689
  },
680
690
  {