@grada-run/grada 0.50.1 → 0.50.2

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/grada",
3
- "version": "0.50.1",
3
+ "version": "0.50.2",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -279,7 +279,7 @@ const ADDON_NOTIFY_ALARMS = [
279
279
  threshold: 1,
280
280
  evaluationPeriods: 1,
281
281
  period: 300,
282
- describe: () => 'the dead-letter queue holds failed messages (redrive or inspect them).',
282
+ describe: () => 'the dead-letter queue holds failed messages (redrive or inspect them). Runbook: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/alert-notifications.md#redriving-the-dlq',
283
283
  dimensions: { QueueName: 'aws_sqs_queue.dlq.name' },
284
284
  },
285
285
  {
@@ -502,7 +502,7 @@ ${aliasLine} topic_arn = aws_sns_topic.alerts.arn
502
502
  locals {
503
503
  # Length-safe forwarder name (role + function both cap at 64):
504
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"
505
+ forwarder_safe_name = length("${namePrefix}-alerts-forwarder") > 64 ? "\${trimsuffix(substr(local.app_name, 0, 64 - 1 - 5 - 17), "-")}-\${substr(md5(local.app_name), 0, 5)}-alerts-forwarder" : "${namePrefix}-alerts-forwarder"
506
506
  }
507
507
 
508
508
  variable "alerts_webhook_url" {
@@ -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, safeSuffixedName } from '../utils/resolvers.js';
11
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveLogGroup, resolveCwd, readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, resolveNamespacedProject, withWorkspaceNamespace, resolveFunctionName } 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
- : safeSuffixedName(`${namespacedProject}${readResourceSuffix(options.cwd)}`, '-fn', 64);
130
+ : resolveFunctionName(`${namespacedProject}${readResourceSuffix(options.cwd)}`);
131
131
  const runSync = options.spawnSyncImpl || spawnSync;
132
132
 
133
133
  intro(color.bgCyan(color.black(' grada diagnose 🩺 ')));
@@ -7,7 +7,7 @@ import { checkDependency } from '../utils/system.js';
7
7
  import { checkAwsCredentials, TROUBLESHOOTING_URL } from '../utils/aws.js';
8
8
  import { readLastRunMarker, isInterruptedMarker } from '../utils/terraform.js';
9
9
  import { refuseUnknownFlags } from '../utils/command.js';
10
- import { readTerraformOidcTrust } from '../utils/resolvers.js';
10
+ import { readTerraformOidcTrust, readTerraformProjectName, readResourceSuffix, resolveWorkspaceSuffix, MAX_CONFINED_PROJECT_LENGTH, MAX_CONFINED_APP_LENGTH, exceedsConfinementBound } from '../utils/resolvers.js';
11
11
  import { parseStateBucketBackend } from '../utils/terraform-metadata.js';
12
12
  import { normalizeOptions, parseFlags, normalizeArgv } from '../utils/args.js';
13
13
  import { trackEvent, flushTelemetry, detectCiProvider, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
@@ -35,6 +35,7 @@ export const PROJECT_CHECKS = [
35
35
  { id: 'oidc_trust_scope', label: 'OIDC trust scope', scope: 'project', severity: 'warn', run: checkOidcTrustScope, hint: () => 'Re-scope with: npx grada-run init --github-repo owner/name (or edit the sub claim in terraform/oidc.tf).' },
36
36
  { id: 'oidc_immutable_claims', label: 'OIDC trust formats', scope: 'project', severity: 'warn', run: checkOidcImmutableClaims, hint: () => 'Re-run npx grada-run init to upgrade the trust, or add a repo:<owner>@*/<name>@*:* entry to terraform/oidc.tf.' },
37
37
  { id: 'origin_restriction', label: 'ALB origin restriction', scope: 'project', severity: 'warn', run: checkOriginRestriction, hint: () => 'Re-run npx grada-run init to add the CloudFront origin-secret wiring, then apply.' },
38
+ { id: 'name_confinement_bound', label: 'Project name confinement bound', scope: 'project', severity: 'warn', run: checkNameConfinementBound, hint: () => 'Shorten the project name (re-scaffold into a fresh tree and migrate state) or switch to a shorter workspace; the residual and its bounds are documented in the CI/CD pipeline guide.' },
38
39
  ];
39
40
 
40
41
  const INSTALL_HINTS = {
@@ -213,6 +214,26 @@ function workspaceSuffix(lockKey) {
213
214
  // rule 403ing hits without the header). Warning-grade: the URL still
214
215
  // prints, but on unwired trees it misleads. Non-ECS targets have no
215
216
  // ALB — skip.
217
+ // Project check: names past the confinement bound hash-suffix their
218
+ // derived AWS resources, which prefix-anchored preview guardrails
219
+ // stop matching. Init refuses such names on fresh scaffolds, so a
220
+ // hit here means a grandfathered tree (or a hand-made over-long
221
+ // workspace) — warn with the remediation path, never fail.
222
+ function checkNameConfinementBound({ cwd }) {
223
+ const project = readTerraformProjectName(cwd);
224
+ if (!project) return { ok: true, skipped: 'no project name found' };
225
+ const appLen = project.length + resolveWorkspaceSuffix({}, cwd).length + (readResourceSuffix(cwd) || '').length;
226
+ if (!exceedsConfinementBound(project) && appLen <= MAX_CONFINED_APP_LENGTH) return { ok: true };
227
+ const reasons = [];
228
+ if (exceedsConfinementBound(project)) {
229
+ reasons.push(`project name is ${project.length} chars (bound: ${MAX_CONFINED_PROJECT_LENGTH}): derived AWS names hash-suffix past what the preview guardrails match`);
230
+ }
231
+ if (appLen > MAX_CONFINED_APP_LENGTH) {
232
+ reasons.push(`current app name resolves to ${appLen} chars (bound: ${MAX_CONFINED_APP_LENGTH}): the active workspace lengthens it past confinement`);
233
+ }
234
+ return { ok: false, detailLines: reasons };
235
+ }
236
+
216
237
  function checkOriginRestriction({ cwd }) {
217
238
  let mainTf;
218
239
  try {
@@ -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, safeSuffixedName } from '../utils/resolvers.js';
14
+ import { resolveRegion, resolveProjectName, resolveCwd, isComputeTarget, readResourceSuffix, resolveFunctionName } 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';
@@ -73,6 +73,13 @@ function escapeRegExp(text) {
73
73
  return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
74
74
  }
75
75
 
76
+ // Anchored snapshot-name matchers for a set of db ids and a tail
77
+ // pattern: manual safety checkpoints and per-commit pre-deploy
78
+ // snapshots share the shape, only the tail differs.
79
+ function snapshotNamePatterns(dbIds, tail) {
80
+ return dbIds.map((id) => new RegExp(`^${escapeRegExp(id)}-${tail}$`));
81
+ }
82
+
76
83
  // Grada renders exactly one ECR repo per tree: `<project><suffix>-repo`
77
84
  // (previews push tags; they never mint repos). Anything else sharing
78
85
  // the prefix is foreign — never propose it.
@@ -80,11 +87,17 @@ function projectRepoName(projectName, resourceSuffix = '') {
80
87
  return `${projectName}${resourceSuffix}-repo`;
81
88
  }
82
89
 
90
+ // Shared preview-workspace infix (`<project>-pr-<n><suffix>`), escaped
91
+ // for embedding: log-group and function liveness both match on it.
92
+ function previewPrInfix(projectName, resourceSuffix = '') {
93
+ return `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
94
+ }
95
+
83
96
  // Preview log groups carry the `-pr-<n>` workspace infix at a fixed
84
97
  // position (`<project>-pr-<n><suffix>`); anchor both ends so foreign
85
98
  // lookalikes (`myapp-evil-pr-2`) never match.
86
99
  function previewLogGroupPattern({ projectName, resourceSuffix = '', isLambda = false }) {
87
- const base = `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
100
+ const base = previewPrInfix(projectName, resourceSuffix);
88
101
  // Plain-form only by design: over-cap preview names hash-suffix in
89
102
  // Terraform, so they never match here — fail closed (never proposed)
90
103
  // and the 30-day group retention self-cleans them instead.
@@ -200,7 +213,7 @@ export async function discoverLivePreviewLogGroups({
200
213
  } = {}) {
201
214
  const live = new Set();
202
215
  try {
203
- const base = `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
216
+ const base = previewPrInfix(projectName, resourceSuffix);
204
217
  if (isLambda) {
205
218
  // Plain-form only (see previewLogGroupPattern): hashed
206
219
  // over-cap functions are invisible here, and invisible to
@@ -291,12 +304,10 @@ async function discoverOldManualSnapshots({ rdsClient, dbIdentifier, dbClusterId
291
304
  const dbIds = [dbIdentifier, dbClusterIdentifier]
292
305
  .filter((id) => typeof id === 'string' && id.trim())
293
306
  .map((id) => id.trim().toLowerCase());
294
- const patterns = dbIds
295
- .map((id) => new RegExp(`^${escapeRegExp(id)}-manual-\\d{8}-\\d{6}$`));
307
+ const patterns = snapshotNamePatterns(dbIds, 'manual-\\d{8}-\\d{6}');
296
308
  // The gate's pre-deploy snapshots are per-commit, so without
297
309
  // a discovery rule they accumulate into the region snapshot quota.
298
- const predeployPatterns = dbIds
299
- .map((id) => new RegExp(`^${escapeRegExp(id)}-pre-deploy-[0-9a-f]{7,40}$`));
310
+ const predeployPatterns = snapshotNamePatterns(dbIds, 'pre-deploy-[0-9a-f]{7,40}');
300
311
  // Legacy bare pre-deploy-<sha> ids carry no db scope: retire them
301
312
  // only with a matching source-db attribute, never by name alone.
302
313
  const legacyPredeployPattern = /^pre-deploy-[0-9a-f]{7,40}$/;
@@ -746,7 +757,7 @@ async function runGcMain(input = {}) {
746
757
  // Exact match: the live group carries the suffix on suffixed
747
758
  // trees, and proposing it for deletion would be catastrophic.
748
759
  excludeLogGroup: isLambda
749
- ? `/aws/lambda/${safeSuffixedName(`${projectName}${suffix}`, '-fn', 64)}`
760
+ ? `/aws/lambda/${resolveFunctionName(`${projectName}${suffix}`)}`
750
761
  : `/ecs/${projectName}${suffix}`,
751
762
  livePreviewGroups: liveness.groups,
752
763
  previewLivenessUnknown: liveness.unknown,
@@ -42,7 +42,7 @@ import { getTargetDirectory, getProjectConfig, promptWorkerCommand, promptGitHub
42
42
  import { resolveDjangoWsgi, handleRailsCI } from '../utils/frameworks.js';
43
43
  import { parseDockerCompose, selectComposeWebService } from '../utils/dockerCompose.js';
44
44
  import { getBaseRules, getCursorRules, injectManagedBlock } from '../utils/ai-rules.js';
45
- import { readFileSafe, COMPUTE_TARGETS, resolveHeadless, resolveInitSuffix, readTerraformProjectName, readTerraformOidcTrust, guardComputeTarget } from '../utils/resolvers.js';
45
+ import { readFileSafe, COMPUTE_TARGETS, resolveHeadless, resolveInitSuffix, readTerraformProjectName, readTerraformOidcTrust, guardComputeTarget, MAX_CONFINED_PROJECT_LENGTH, exceedsConfinementBound, safeSuffixedName } from '../utils/resolvers.js';
46
46
  import { readGitHubRepoFromRemote, isValidGitHubRepoSlug } from '../utils/git.js';
47
47
  import { parseDomainTf } from '../utils/domains.js';
48
48
  import { PLACEHOLDER_ACCOUNT_ID } from '../utils/reconcile.js';
@@ -187,6 +187,15 @@ export function buildPreviewRoleName(projectName, suffix) {
187
187
  return buildCiRoleName(projectName, suffix, 'preview');
188
188
  }
189
189
 
190
+ // Gate snapshot scope: the database identifier the pre-deploy gate
191
+ // snapshots, hashed exactly like identifier_safe_name /
192
+ // cluster_safe_name so gate snapshots match gc's pre-deploy patterns
193
+ // (and the guardrail snapshot patterns) on all name lengths.
194
+ export function buildGateDbIdentifier(projectName, suffix, isCluster) {
195
+ const base = `${projectName ?? ''}${suffix ?? ''}`;
196
+ return isCluster ? safeSuffixedName(base, '-db-cluster', 63) : safeSuffixedName(base, '-db', 63);
197
+ }
198
+
190
199
  export function buildRoleArn(accountId, roleName) {
191
200
  return `arn:aws:iam::${accountId}:role/${roleName}`;
192
201
  }
@@ -544,7 +553,7 @@ async function wireInitWorkflows({ targetDir, projectName, resourceSuffix, regio
544
553
  // Scope the gate's snapshot id to the database (aurora
545
554
  // takes the cluster prefix) so guardrails and gc can name it.
546
555
  const gateDbRefs = resolveDbEngineRefs(dbEngine);
547
- const gateDbIdentifier = `${projectName}${resourceSuffix}-db${gateDbRefs.isCluster ? '-cluster' : ''}`;
556
+ const gateDbIdentifier = buildGateDbIdentifier(projectName, resourceSuffix, gateDbRefs.isCluster);
548
557
  const gated = workflowContent ? injectMigrationGate(workflowContent, { cmd: migrationCmd, cliVersion: CLI_VERSION, dbIdentifier: gateDbIdentifier }) : null;
549
558
  if (gated) {
550
559
  atomicWriteFileSync(deployYmlPath, gated);
@@ -1351,6 +1360,36 @@ async function resolveInitWorkdir({ options, isHeadless, headlessOptions, explic
1351
1360
  trackEvent('init_project_name_reused', { projectName: sanitizedTreeName });
1352
1361
  dirConfig.actualProjectName = sanitizedTreeName;
1353
1362
  }
1363
+ // Fresh and renamed trees collapse consecutive hyphens: RDS
1364
+ // identifiers forbid `--`, and collapsing at mint time keeps every
1365
+ // derived name valid. Grandfathered trees keep their exact name
1366
+ // (collapsing there would fork live infrastructure).
1367
+ if (dirConfig.actualProjectName !== sanitizedTreeName) {
1368
+ const collapsed = dirConfig.actualProjectName.replace(/-{2,}/g, '-');
1369
+ if (collapsed !== dirConfig.actualProjectName) {
1370
+ console.log(color.dim(`Project name collapsed to "${collapsed}" (consecutive hyphens are invalid in RDS identifiers).`));
1371
+ dirConfig.actualProjectName = collapsed;
1372
+ }
1373
+ }
1374
+ // Confinement bound for NEW names only: past it, derived AWS names
1375
+ // hash-suffix and prefix-anchored preview guardrails stop matching
1376
+ // them. Grandfathered trees (existing name kept) are never refused
1377
+ // here — doctor flags them instead. Explicit renames count as new
1378
+ // names: they provision a fresh stack.
1379
+ if (dirConfig.actualProjectName !== sanitizedTreeName && exceedsConfinementBound(dirConfig.actualProjectName)) {
1380
+ return {
1381
+ refusal: await failCommand({
1382
+ message: `\n✖ Project name "${dirConfig.actualProjectName}" is ${dirConfig.actualProjectName.length} chars — past the ${MAX_CONFINED_PROJECT_LENGTH}-char confinement bound. Longer names hash-suffix their derived AWS resource names, which the prefix-anchored preview guardrails can no longer match.`,
1383
+ hint: ` Shorten to ${MAX_CONFINED_PROJECT_LENGTH} chars or fewer and re-run (existing long-name trees keep deploying; grada doctor flags them). Bound rationale: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/cicd-pipeline.md\n`,
1384
+ useErrorStream: true,
1385
+ event: 'cli-error',
1386
+ telemetry: { step: 'project_name', error_code: 'PROJECT_NAME_OVER_CONFINEMENT_BOUND' },
1387
+ errorCode: 'PROJECT_NAME_OVER_CONFINEMENT_BOUND',
1388
+ reason: 'project-name-over-confinement-bound',
1389
+ exitCode: 1,
1390
+ }),
1391
+ };
1392
+ }
1354
1393
  return { dirConfig };
1355
1394
  }
1356
1395
 
@@ -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, safeSuffixedName } from '../utils/resolvers.js';
15
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, withWorkspaceNamespace, resolveCwd, guardComputeTarget, readResourceSuffix, resolveFunctionName } 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 = safeSuffixedName(`${projectName}${readResourceSuffix(cwd)}`, '-fn', 64);
134
+ const functionName = resolveFunctionName(`${projectName}${readResourceSuffix(cwd)}`);
135
135
  trackEvent('rollback_target_unsupported', { projectName, actual: targetGuard.actual });
136
136
  return failCommand({
137
137
  message: targetGuard.message,
@@ -9,7 +9,7 @@ import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveComman
9
9
  import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
10
10
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
11
11
  import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
12
- import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget, readResourceSuffix, resolveNamespacedProject, safeSuffixedName } from '../utils/resolvers.js';
12
+ import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget, readResourceSuffix, resolveNamespacedProject, safeSuffixedName, resolveFunctionName } from '../utils/resolvers.js';
13
13
  import { runDiagnose } from './diagnose.js';
14
14
  import { detectAlertAddonFeatures } from './alerts.js';
15
15
  import { fetchGoldenSignals } from '../utils/golden-signals.js';
@@ -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
- : safeSuffixedName(`${namespacedProject}${readResourceSuffix(cwd)}`, '-fn', 64);
138
+ : resolveFunctionName(`${namespacedProject}${readResourceSuffix(cwd)}`);
139
139
  const asJson = Boolean(options.json);
140
140
  const runSync = options.spawnSyncImpl || spawnSync;
141
141
 
package/src/utils/aws.js CHANGED
@@ -112,10 +112,17 @@ export async function checkAwsCredentials(region) {
112
112
  export function formatStateBucketName(projectName, accountId) {
113
113
  const suffix = `-tfstate-${accountId}`;
114
114
  const room = Math.max(63 - suffix.length, 1);
115
- let project = sanitizeProjectName(projectName);
116
- if (project.length > room) project = project.substring(0, room).replace(/-+$/, '');
117
- if (project === '') project = 'app';
118
- return `${project}${suffix}`;
115
+ const project = sanitizeProjectName(projectName);
116
+ // Preserve a trailing resource suffix (`-a1b2c3`): truncating the
117
+ // combined string could sever it, collapsing two trees onto one
118
+ // bucket. Truncate the project part to fit around it instead.
119
+ const suffixMatch = project.match(/-[a-f0-9]{6}$/);
120
+ const resourceSuffix = suffixMatch ? suffixMatch[0] : '';
121
+ const stemRoom = Math.max(room - resourceSuffix.length, 1);
122
+ let stem = resourceSuffix ? project.slice(0, -resourceSuffix.length) : project;
123
+ if (stem.length > stemRoom) stem = stem.substring(0, stemRoom).replace(/-+$/, '');
124
+ if (stem === '') stem = 'app';
125
+ return `${stem}${resourceSuffix}${suffix}`;
119
126
  }
120
127
 
121
128
  export async function provisionStateBucket(region, projectName) {
@@ -25,12 +25,6 @@ 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
- }
34
28
  return actualProjectName;
35
29
  }
36
30
 
@@ -115,18 +115,47 @@ export function readTerraformRegion(cwd = process.cwd()) {
115
115
  // Length-safe AWS resource name, mirroring the template conditional
116
116
  // byte-for-byte: short names render identically; over-cap names take a
117
117
  // deterministic md5 stem (never a truncating collision). `cap` is the
118
- // service limit including suffix. Doubled hyphens at the cut point are
119
- // left alone — valid in every name pattern here, and trimming would
120
- // need identical semantics on both sides. Both sides must stay in
118
+ // service limit including suffix. Cut-point hyphens are trimmed from
119
+ // the stem (RDS forbids `--`) — the hash input stays untouched, so
120
+ // non-hyphen cuts render exactly as before. Both sides must stay in
121
121
  // sync — the parity tests below pin the shared cases.
122
122
  export function safeSuffixedName(base, suffix, cap) {
123
123
  const full = `${base}${suffix}`;
124
124
  if (full.length <= cap) return full;
125
125
  const stemLength = Math.max(cap - 1 - 5 - suffix.length, 1);
126
- const stem = base.slice(0, stemLength);
126
+ const stem = base.slice(0, stemLength).replace(/-+$/, '');
127
127
  return `${stem}-${createHash('md5').update(base, 'utf8').digest('hex').slice(0, 5)}${suffix}`;
128
128
  }
129
129
 
130
+ // Preview-confinement bound: the longest sanitized project name whose
131
+ // worst-case derived names stay plain (unhashed), so prefix-anchored
132
+ // guardrail patterns keep matching. Binding constraint is the
133
+ // scheduler role (64 - 20); worst-case app adds the preview infix
134
+ // (`-pr-` + 7 PR digits = 11) and the 7-char resource suffix, so
135
+ // project <= 64 - 20 - 11 - 7 = 26. New scaffolds past this are
136
+ // refused at init; grandfathered trees are flagged by doctor, never
137
+ // broken. Pinned honest by the parity harness in generator.test.js —
138
+ // if a template grows a longer escape-relevant suffix, recompute.
139
+ export const MAX_CONFINED_PROJECT_LENGTH = 26;
140
+ export const CONFINEMENT_WORST_ENV_SUFFIX_LENGTH = 11;
141
+ export const CONFINEMENT_RESOURCE_SUFFIX_LENGTH = 7;
142
+ // Worst-case app_name the bound admits (project + env + suffix): the
143
+ // scheduler role renders at exactly the 64-char cap here. Doctor
144
+ // evaluates the LIVE tree (real workspace + suffix) against this.
145
+ export const MAX_CONFINED_APP_LENGTH = 44;
146
+
147
+ export function exceedsConfinementBound(sanitizedProjectName) {
148
+ return String(sanitizedProjectName ?? '').length > MAX_CONFINED_PROJECT_LENGTH;
149
+ }
150
+
151
+ // Single home for the Lambda function name (`<app>-fn`, 64-char cap):
152
+ // status, diagnose, gc, rollback, and the log-group resolver all read
153
+ // through here, so the suffix and cap can't drift apart again. Short
154
+ // names render plain; over-cap names hash-suffix like fn_safe_name.
155
+ export function resolveFunctionName(appName) {
156
+ return safeSuffixedName(String(appName ?? ''), '-fn', 64);
157
+ }
158
+
130
159
  export function resolveRegion(options = {}, cwd = process.cwd()) {
131
160
  const opts = normalizeOptions(options);
132
161
  if (typeof opts.region === 'string' && opts.region.trim()) {
@@ -334,7 +363,7 @@ export function resolveLogGroup(options = {}, cwd = process.cwd()) {
334
363
  // Lambda functions log to /aws/lambda/<fn> (see main-lambda.tf), where
335
364
  // the function name is `<app>-fn`, hash-suffixed past 64 chars.
336
365
  if (readTerraformComputeTarget(base) === 'lambda') {
337
- return `/aws/lambda/${safeSuffixedName(suffixed, '-fn', 64)}`;
366
+ return `/aws/lambda/${resolveFunctionName(suffixed)}`;
338
367
  }
339
368
  return `/ecs/${suffixed}`;
340
369
  }
@@ -1,7 +1,7 @@
1
1
  import fsSync from 'fs';
2
2
  import path from 'path';
3
3
  import { withProjectLock } from './file-lock.js';
4
- import { readResourceSuffix } from './resolvers.js';
4
+ import { readResourceSuffix, safeSuffixedName } from './resolvers.js';
5
5
 
6
6
  // Auxiliary sleep/wake targets driven through the AWS CLI: EventBridge
7
7
  // Scheduler pause/resume and ECS Application Auto Scaling suspend/resume.
@@ -12,11 +12,13 @@ import { readResourceSuffix } from './resolvers.js';
12
12
  // instead of adding new npm packages. Every helper degrades to a skip
13
13
  // reason; callers warn and continue so sleep/wake never fail on these.
14
14
 
15
- // cron.tf renders `name = "${local.app_name}-cron-<slug>"` inside the
16
- // schedule block. Resolves the live schedule name for an app prefix, or
17
- // null when cron isn't configured (or the file was hand-edited past
18
- // recognition). Scoped to the schedule block: the IAM role/policy above
19
- // share the `-cron-` prefix, and an unscoped first match resolves
15
+ // cron.tf renders the slug in the `schedule_full_name` local while the
16
+ // schedule block references `schedule_safe_name` (hashed past 64
17
+ // chars). Resolves the live schedule name for an app prefix, or null
18
+ // when cron isn't configured (or the file was hand-edited past
19
+ // recognition). Falls back to the legacy inline `name` for pre-hash
20
+ // trees. Scoped lookups only: the IAM role/policy share the `-cron-`
21
+ // prefix, and an unscoped first match resolves
20
22
  // `-cron-scheduler-role` — pausing a schedule that doesn't exist while
21
23
  // the real one keeps firing (and Terraform plans ENABLED -> DISABLED).
22
24
  export function readCronScheduleName(cwd, appPrefix) {
@@ -26,11 +28,16 @@ export function readCronScheduleName(cwd, appPrefix) {
26
28
  } catch {
27
29
  return null;
28
30
  }
29
- const blockStart = content.indexOf('resource "aws_scheduler_schedule"');
30
- if (blockStart < 0) return null;
31
- const match = /name\s*=\s*"\$\{local\.app_name\}-cron-([A-Za-z0-9-]+)"/.exec(content.slice(blockStart));
32
- if (!match) return null;
33
- return `${appPrefix}${readResourceSuffix(cwd)}-cron-${match[1]}`;
31
+ const fullName = /schedule_full_name\s*=\s*"\$\{local\.app_name\}-cron-([A-Za-z0-9-]+)"/.exec(content)?.[1] ?? null;
32
+ let slug = fullName;
33
+ if (!slug) {
34
+ const blockStart = content.indexOf('resource "aws_scheduler_schedule"');
35
+ if (blockStart < 0) return null;
36
+ const match = /name\s*=\s*"\$\{local\.app_name\}-cron-([A-Za-z0-9-]+)"/.exec(content.slice(blockStart));
37
+ if (!match) return null;
38
+ slug = match[1];
39
+ }
40
+ return safeSuffixedName(`${appPrefix}${readResourceSuffix(cwd)}-cron-${slug}`, '', 64);
34
41
  }
35
42
 
36
43
  export function hasCronAddon(cwd) {
@@ -15,7 +15,7 @@ concurrency:
15
15
  env:
16
16
  AWS_REGION: {{REGION}}
17
17
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
18
- LAMBDA_FUNCTION: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-fn
18
+ APP_NAME: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}
19
19
  CF_COMMENT: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-cdn
20
20
 
21
21
  permissions:
@@ -153,13 +153,26 @@ jobs:
153
153
  # `latest` is never the deploy artifact of record).
154
154
  - name: Deploy image to AWS Lambda
155
155
  run: |
156
+ # Mirror of safeSuffixedName (resolvers.js): Terraform hashes
157
+ # over-cap function names, so plain reconstruction would target
158
+ # a function that doesn't exist.
159
+ safe_name() {
160
+ local base="$1" suffix="$2" cap="$3" full="${1}${2}"
161
+ if [ "${#full}" -le "$cap" ]; then printf '%s' "$full"; return; fi
162
+ local stemlen=$((cap - 1 - 5 - ${#suffix}))
163
+ local stem=${base:0:$stemlen}
164
+ while [[ "$stem" == *- ]]; do stem=${stem%-}; done
165
+ local hash=$(printf '%s' "$base" | md5sum | cut -c1-5)
166
+ printf '%s-%s%s' "$stem" "$hash" "$suffix"
167
+ }
156
168
  IMAGE_URI=${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:${GITHUB_SHA::7}
169
+ LAMBDA_FUNCTION=$(safe_name "${{ env.APP_NAME }}" "-fn" 64)
157
170
  aws lambda update-function-code \
158
- --function-name ${{ env.LAMBDA_FUNCTION }} \
171
+ --function-name "$LAMBDA_FUNCTION" \
159
172
  --image-uri "$IMAGE_URI" \
160
173
  --region ${{ env.AWS_REGION }}
161
174
  aws lambda wait function-updated \
162
- --function-name ${{ env.LAMBDA_FUNCTION }} \
175
+ --function-name "$LAMBDA_FUNCTION" \
163
176
  --region ${{ env.AWS_REGION }}
164
177
 
165
178
  # --- 9. CACHE INVALIDATION ---
@@ -20,6 +20,7 @@ env:
20
20
  AWS_REGION: {{REGION}}
21
21
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
22
22
  WORKSPACE: pr-${{ github.event.pull_request.number }}
23
+ APP_NAME: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}
23
24
  CF_COMMENT: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}-cdn
24
25
 
25
26
  permissions:
@@ -102,12 +103,25 @@ jobs:
102
103
  # Terraform provisions the function pointing at :latest (which it
103
104
  # then ignores), so the PR-tagged image is deployed explicitly —
104
105
  # mirroring the workspace-tagged task definition on ECS targets.
106
+ # Mirror of safeSuffixedName (resolvers.js): Terraform hashes
107
+ # over-cap function names, so plain reconstruction would target
108
+ # a function that doesn't exist.
109
+ safe_name() {
110
+ local base="$1" suffix="$2" cap="$3" full="${1}${2}"
111
+ if [ "${#full}" -le "$cap" ]; then printf '%s' "$full"; return; fi
112
+ local stemlen=$((cap - 1 - 5 - ${#suffix}))
113
+ local stem=${base:0:$stemlen}
114
+ while [[ "$stem" == *- ]]; do stem=${stem%-}; done
115
+ local hash=$(printf '%s' "$base" | md5sum | cut -c1-5)
116
+ printf '%s-%s%s' "$stem" "$hash" "$suffix"
117
+ }
118
+ LAMBDA_FUNCTION=$(safe_name "${{ env.APP_NAME }}" "-fn" 64)
105
119
  aws lambda update-function-code \
106
- --function-name {{PROJECT_NAME}}-${{ env.WORKSPACE }}{{RESOURCE_SUFFIX}}-fn \
120
+ --function-name "$LAMBDA_FUNCTION" \
107
121
  --image-uri $ECR_REGISTRY/$ECR_REPOSITORY:${{ env.WORKSPACE }} \
108
122
  --region ${{ env.AWS_REGION }}
109
123
  aws lambda wait function-updated \
110
- --function-name {{PROJECT_NAME}}-${{ env.WORKSPACE }}{{RESOURCE_SUFFIX}}-fn \
124
+ --function-name "$LAMBDA_FUNCTION" \
111
125
  --region ${{ env.AWS_REGION }}
112
126
 
113
127
  - name: Read preview URL
@@ -69,14 +69,26 @@ jobs:
69
69
  - name: Lift preview deletion protection
70
70
  if: steps.aws-creds.outcome == 'success'
71
71
  run: |
72
+ # Mirror of safeSuffixedName (resolvers.js): Terraform hashes
73
+ # over-cap names, so plain reconstruction misses on long names
74
+ # (the describe-miss would skip the lift and fail the destroy).
75
+ safe_name() {
76
+ local base="$1" suffix="$2" cap="$3" full="${1}${2}"
77
+ if [ "${#full}" -le "$cap" ]; then printf '%s' "$full"; return; fi
78
+ local stemlen=$((cap - 1 - 5 - ${#suffix}))
79
+ local stem=${base:0:$stemlen}
80
+ while [[ "$stem" == *- ]]; do stem=${stem%-}; done
81
+ local hash=$(printf '%s' "$base" | md5sum | cut -c1-5)
82
+ printf '%s-%s%s' "$stem" "$hash" "$suffix"
83
+ }
72
84
  APP_NAME="{{PROJECT_NAME}}-${{ env.WORKSPACE }}{{RESOURCE_SUFFIX}}"
73
- DB_ID="$APP_NAME-db"
85
+ DB_ID=$(safe_name "$APP_NAME" "-db" 63)
74
86
  if aws rds describe-db-instances --db-instance-identifier "$DB_ID" --region ${{ env.AWS_REGION }} >/dev/null 2>&1; then
75
87
  echo "Lifting deletion protection on $DB_ID..."
76
88
  aws rds modify-db-instance --db-instance-identifier "$DB_ID" --no-deletion-protection --apply-immediately --region ${{ env.AWS_REGION }}
77
89
  aws rds wait db-instance-available --db-instance-identifier "$DB_ID" --region ${{ env.AWS_REGION }}
78
90
  fi
79
- CLUSTER_ID="$APP_NAME-db-cluster"
91
+ CLUSTER_ID=$(safe_name "$APP_NAME" "-db-cluster" 63)
80
92
  if aws rds describe-db-clusters --db-cluster-identifier "$CLUSTER_ID" --region ${{ env.AWS_REGION }} >/dev/null 2>&1; then
81
93
  echo "Lifting deletion protection on $CLUSTER_ID..."
82
94
  aws rds modify-db-cluster --db-cluster-identifier "$CLUSTER_ID" --no-deletion-protection --apply-immediately --region ${{ env.AWS_REGION }}
@@ -15,16 +15,19 @@ 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
18
  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"
19
+ schedule_safe_name = length(local.schedule_full_name) > 64 ? "${trimsuffix(substr(local.schedule_full_name, 0, 64 - 1 - 5), "-")}-${substr(md5(local.schedule_full_name), 0, 5)}" : local.schedule_full_name
20
+ schedule_group_safe_name = length("${local.app_name}-crons") > 64 ? "${trimsuffix(substr(local.app_name, 0, 64 - 1 - 5 - 6), "-")}-${substr(md5(local.app_name), 0, 5)}-crons" : "${local.app_name}-crons"
21
+ scheduler_policy_safe_name = length("${local.app_name}-cron-scheduler-policy") > 128 ? "${trimsuffix(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"
23
22
  }
24
23
 
25
24
  # --- IAM Role assumed by EventBridge Scheduler ---
26
25
  resource "aws_iam_role" "scheduler_cron_role" {
27
- name = local.scheduler_role_safe_name
26
+ # Deliberately unhashed: the preview guardrails carve this exact
27
+ # principal out of the task-execution deny, and a hashed name would
28
+ # silently uncarve it. Over-cap names fail the precondition below
29
+ # at plan time instead of breaking schedules silently.
30
+ name = "${local.app_name}-cron-scheduler-role"
28
31
  permissions_boundary = local.preview_boundary_arn
29
32
  assume_role_policy = jsonencode({
30
33
  Version = "2012-10-17"
@@ -38,6 +41,13 @@ resource "aws_iam_role" "scheduler_cron_role" {
38
41
  }
39
42
  ]
40
43
  })
44
+
45
+ lifecycle {
46
+ precondition {
47
+ condition = length("${local.app_name}-cron-scheduler-role") <= 64
48
+ error_message = "Project name is too long: the scheduler role name exceeds the 64-char IAM cap. Shorten the project name (max 26 chars keeps every derived name within caps)."
49
+ }
50
+ }
41
51
  }
42
52
 
43
53
  # --- Least-privilege permission to invoke the function ---
@@ -9,16 +9,19 @@ 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
12
  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"
13
+ schedule_safe_name = length(local.schedule_full_name) > 64 ? "${trimsuffix(substr(local.schedule_full_name, 0, 64 - 1 - 5), "-")}-${substr(md5(local.schedule_full_name), 0, 5)}" : local.schedule_full_name
14
+ schedule_group_safe_name = length("${local.app_name}-crons") > 64 ? "${trimsuffix(substr(local.app_name, 0, 64 - 1 - 5 - 6), "-")}-${substr(md5(local.app_name), 0, 5)}-crons" : "${local.app_name}-crons"
15
+ scheduler_policy_safe_name = length("${local.app_name}-cron-scheduler-policy") > 128 ? "${trimsuffix(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"
17
16
  }
18
17
 
19
18
  # --- IAM Role assumed by EventBridge Scheduler ---
20
19
  resource "aws_iam_role" "scheduler_cron_role" {
21
- name = local.scheduler_role_safe_name
20
+ # Deliberately unhashed: the preview guardrails carve this exact
21
+ # principal out of the task-execution deny, and a hashed name would
22
+ # silently uncarve it. Over-cap names fail the precondition below
23
+ # at plan time instead of breaking schedules silently.
24
+ name = "${local.app_name}-cron-scheduler-role"
22
25
  permissions_boundary = local.preview_boundary_arn
23
26
  assume_role_policy = jsonencode({
24
27
  Version = "2012-10-17"
@@ -32,6 +35,13 @@ resource "aws_iam_role" "scheduler_cron_role" {
32
35
  }
33
36
  ]
34
37
  })
38
+
39
+ lifecycle {
40
+ precondition {
41
+ condition = length("${local.app_name}-cron-scheduler-role") <= 64
42
+ error_message = "Project name is too long: the scheduler role name exceeds the 64-char IAM cap. Shorten the project name (max 26 chars keeps every derived name within caps)."
43
+ }
44
+ }
35
45
  }
36
46
 
37
47
  # --- Least-privilege permission to launch the scheduled task ---
@@ -14,8 +14,8 @@ locals {
14
14
  # Length-safe names: short names render byte-identically; over-cap
15
15
  # names hash-suffix instead of failing validation (config sets
16
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"
17
+ config_set_safe_name = length("${local.app_name}-ses-events") > 64 ? "${trimsuffix(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 ? "${trimsuffix(substr(local.app_name, 0, 128 - 1 - 5 - 9), "-")}-${substr(md5(local.app_name), 0, 5)}-ses-send" : "${local.app_name}-ses-send"
19
19
  }
20
20
  resource "aws_ses_domain_identity" "ses" {
21
21
  count = terraform.workspace == "default" ? 1 : 0
@@ -9,9 +9,9 @@ locals {
9
9
  # Length-safe names: short names render byte-identically; over-cap
10
10
  # names hash-suffix instead of failing validation (queues cap at
11
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"
12
+ queue_safe_name = length("${local.app_name}-queue") > 80 ? "${trimsuffix(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 ? "${trimsuffix(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 ? "${trimsuffix(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
15
  }
16
16
 
17
17
  # --- Dead-Letter Queue ---
@@ -39,11 +39,11 @@ locals {
39
39
  # names hash-suffix instead of failing validation (identifiers and
40
40
  # database names cap at 63, policies at 128). Mirrors
41
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"
42
+ cluster_safe_name = length("${local.app_name}-db-cluster") > 63 ? "${trimsuffix(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 ? "${trimsuffix(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
44
  database_name_base = replace(local.app_name, "-", "")
45
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"
46
+ secret_policy_safe_name = length("${local.app_name}-rds-secret-policy") > 128 ? "${trimsuffix(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
47
  }
48
48
 
49
49
  resource "aws_rds_cluster_parameter_group" "ssl" {
@@ -3,10 +3,10 @@
3
3
  # at 63, database names at 64, policies at 128). Mirrors
4
4
  # safeSuffixedName in resolvers.js.
5
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"
6
+ identifier_safe_name = length("${local.app_name}-db") > 63 ? "${trimsuffix(substr(local.app_name, 0, 63 - 1 - 5 - 3), "-")}-${substr(md5(local.app_name), 0, 5)}-db" : "${local.app_name}-db"
7
7
  db_name_base = replace(local.app_name, "-", "")
8
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"
9
+ secret_policy_safe_name = length("${local.app_name}-rds-secret-policy") > 128 ? "${trimsuffix(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
10
  }
11
11
 
12
12
  # 1. Database Subnet Group (isolated subnets live in network.tf, shared
@@ -3,10 +3,10 @@
3
3
  # database names cap at 63, policies at 128). Mirrors
4
4
  # safeSuffixedName in resolvers.js.
5
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"
6
+ identifier_safe_name = length("${local.app_name}-db") > 63 ? "${trimsuffix(substr(local.app_name, 0, 63 - 1 - 5 - 3), "-")}-${substr(md5(local.app_name), 0, 5)}-db" : "${local.app_name}-db"
7
7
  db_name_base = replace(local.app_name, "-", "_")
8
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"
9
+ secret_policy_safe_name = length("${local.app_name}-rds-secret-policy") > 128 ? "${trimsuffix(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
10
  }
11
11
 
12
12
  # 1. Database Subnet Group (isolated subnets live in network.tf, shared
@@ -44,10 +44,10 @@ locals {
44
44
  # Length-safe names: short names render byte-identically; over-cap
45
45
  # names hash-suffix instead of failing IAM validation. Mirrors
46
46
  # safeSuffixedName in resolvers.js.
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
- 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"
47
+ task_role_safe_name = length("${local.app_name}-task-role") > 64 ? "${trimsuffix(substr(local.app_name, 0, 64 - 1 - 5 - 10), "-")}-${substr(md5(local.app_name), 0, 5)}-task-role" : "${local.app_name}-task-role"
48
+ execution_role_safe_name = length("${local.app_name}-execution-role") > 64 ? "${trimsuffix(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 ? "${trimsuffix(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 ? "${trimsuffix(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"
51
51
  }
52
52
 
53
53
  # --- CloudWatch Logs ---
@@ -56,11 +56,11 @@ locals {
56
56
  # into collisions (ALB/TG) or failing validation (IAM). Mirrors
57
57
  # safeSuffixedName in resolvers.js — stem is always
58
58
  # cap - 1 - 5 - len(suffix). Existing trees never rename.
59
- alb_safe_name = length("${local.app_name}-alb") > 32 ? "${substr(local.app_name, 0, 32 - 1 - 5 - 4)}-${substr(md5(local.app_name), 0, 5)}-alb" : "${local.app_name}-alb"
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
- 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
- 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"
59
+ alb_safe_name = length("${local.app_name}-alb") > 32 ? "${trimsuffix(substr(local.app_name, 0, 32 - 1 - 5 - 4), "-")}-${substr(md5(local.app_name), 0, 5)}-alb" : "${local.app_name}-alb"
60
+ tg_safe_name = length("${local.app_name}-tg") > 32 ? "${trimsuffix(substr(local.app_name, 0, 32 - 1 - 5 - 3), "-")}-${substr(md5(local.app_name), 0, 5)}-tg" : "${local.app_name}-tg"
61
+ task_role_safe_name = length("${local.app_name}-task-role") > 64 ? "${trimsuffix(substr(local.app_name, 0, 64 - 1 - 5 - 10), "-")}-${substr(md5(local.app_name), 0, 5)}-task-role" : "${local.app_name}-task-role"
62
+ execution_role_safe_name = length("${local.app_name}-execution-role") > 64 ? "${trimsuffix(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 ? "${trimsuffix(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"
64
64
  }
65
65
 
66
66
  # --- CloudWatch Logs ---
@@ -49,11 +49,11 @@ 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 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.
52
+ # several exact ARNs when adding entries. Headroom is 64 chars
53
+ # at 32-char prefixes (286 at 24): the PITR/backup verbs plus
54
+ # their backup-ARN entry spent the suffix-loosening payback, with
55
+ # the verb-collapse battery covering the rest — the next addition
56
+ # re-runs the quota probe before extending.
57
57
  guardrail_compute_abuse_resources = ["*"]
58
58
  guardrail_snapshot_sharing_resources = ["*"]
59
59
  guardrail_state_destruction_resources = [
@@ -74,12 +74,18 @@ locals {
74
74
  guardrail_aurora_destruction_resources = [
75
75
  "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster:${local.prod_prefix}-db-cluster",
76
76
  ]
77
- guardrail_table_deletion_resources = [
77
+ guardrail_table_data_resources = [
78
78
  "arn:aws:dynamodb:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:table/${local.prod_prefix}-table",
79
+ # Backup ARNs authorize backup create/delete/restore-from; the table
80
+ # entry alone can't match them.
81
+ "arn:aws:dynamodb:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:table/${local.prod_prefix}-table/backup/*",
79
82
  ]
80
- guardrail_snapshot_deletion_resources = [
81
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:snapshot:${local.prod_prefix}-db-*",
82
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster-snapshot:${local.prod_prefix}-db-cluster-*",
83
+ guardrail_snapshot_data_resources = [
84
+ # Middle-wildcard: automated snapshots carry an `rds:` name prefix
85
+ # (AWS CopyDBSnapshot API reference), so prefix anchoring would
86
+ # miss them. The infix still can't match `-pr-<n>-` names.
87
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:snapshot:*${local.prod_prefix}-db*",
88
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster-snapshot:*${local.prod_prefix}-db-cluster*",
83
89
  # Legacy bare pre-deploy-<sha> ids carry no db prefix, so
84
90
  # they match no prod pattern above — deny them outright. gc never
85
91
  # runs under preview credentials, so nothing legitimate needs them.
@@ -111,20 +117,29 @@ locals {
111
117
  "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${local.prod_prefix}-*-role",
112
118
  ]
113
119
  # Data-plane confinement: prod data ARNs shared by the
114
- # DenyProdAppData twins. One statement is exact here, not
115
- # lazy — every denied action only ever matches its own service's
116
- # ARNs in a real call, so the cross-product cannot over-match.
120
+ # DenyProdAppData twins. Queue entries are suffix-anchored on
121
+ # purpose: hashed names keep their tails, so prefix anchoring
122
+ # would miss them. Preview queues match too — safe, because the
123
+ # preview role never sends/receives (pinned by test) and tasks
124
+ # stay carved out. Every denied action only ever matches its own
125
+ # service's ARNs in a real call, so the cross-product cannot
126
+ # over-match.
117
127
  guardrail_app_data_resources = [
118
128
  "arn:aws:secretsmanager:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:secret:${local.prod_prefix}-secrets-*",
119
- "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${local.prod_prefix}-*",
129
+ "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:*-queue",
130
+ "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:*-dlq",
120
131
  ]
121
132
  # Lifecycle twin of the above, deliberately carve-free: no bounded
122
- # role ever stops or reboots a database (sleep/wake and db commands
123
- # run on user credentials), and one fewer condition keeps the pair
124
- # under the 6144-char boundary quota.
133
+ # role ever stops, starts, reboots, or restores a database
134
+ # (sleep/wake and db commands run on user credentials), and one
135
+ # fewer condition keeps the pair under the 6144-char boundary
136
+ # quota. Suffix-anchored like the queues (hashed identifiers keep
137
+ # their tails); preview DBs match too, safe because no preview
138
+ # workflow calls these verbs (pinned by test) and Terraform's
139
+ # Modify calls live in the anchored destruction statements.
125
140
  guardrail_db_lifecycle_resources = [
126
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:${local.prod_prefix}-db*",
127
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster:${local.prod_prefix}-db-cluster",
141
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:*-db*",
142
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster:*-db-cluster",
128
143
  ]
129
144
  # Carve-out principal for the app-data twins: the exact prod task
130
145
  # role ARN (workers send/receive prod queues). Singular on purpose:
@@ -139,7 +154,7 @@ locals {
139
154
  # task name, and the carve-out must track the rendered name exactly
140
155
  # (a stale plain ARN would silently uncarve workers).
141
156
  guardrail_task_role_principals = [
142
- length("${local.prod_prefix}-task-role") > 64 ? "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${substr(local.prod_prefix, 0, 64 - 1 - 5 - 10)}-${substr(md5(local.prod_prefix), 0, 5)}-task-role" : "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${local.prod_prefix}-task-role",
157
+ length("${local.prod_prefix}-task-role") > 64 ? "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${trimsuffix(substr(local.prod_prefix, 0, 64 - 1 - 5 - 10), "-")}-${substr(md5(local.prod_prefix), 0, 5)}-task-role" : "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${local.prod_prefix}-task-role",
143
158
  ]
144
159
  }
145
160
 
@@ -322,7 +337,7 @@ resource "aws_iam_role_policy" "preview_guardrails" {
322
337
  {
323
338
  Sid = "DenyProdLambdaRewrite"
324
339
  Effect = "Deny"
325
- Action = ["lambda:UpdateFunctionCode", "lambda:DeleteFunction"]
340
+ Action = ["lambda:UpdateFunctionCode", "lambda:Delete*"]
326
341
  Resource = local.guardrail_lambda_rewrite_resources
327
342
  },
328
343
  {
@@ -352,8 +367,8 @@ resource "aws_iam_role_policy" "preview_guardrails" {
352
367
  # iterator dance is narrow and unactionable without table reads.
353
368
  Sid = "DenyProdTableData"
354
369
  Effect = "Deny"
355
- Action = ["dynamodb:DeleteTable", "dynamodb:Batch*", "dynamodb:*Item", "dynamodb:Query", "dynamodb:Scan", "dynamodb:Execute*", "dynamodb:Transact*"]
356
- Resource = local.guardrail_table_deletion_resources
370
+ Action = ["dynamodb:Delete*", "dynamodb:Batch*", "dynamodb:*Item", "dynamodb:Query", "dynamodb:Scan", "dynamodb:Execute*", "dynamodb:Transact*", "dynamodb:Export*", "dynamodb:Restore*", "dynamodb:CreateBackup", "dynamodb:DeleteBackup", "dynamodb:UpdateTable"]
371
+ Resource = local.guardrail_table_data_resources
357
372
  },
358
373
  {
359
374
  # Manual snapshots (grada names them
@@ -367,8 +382,8 @@ resource "aws_iam_role_policy" "preview_guardrails" {
367
382
  # export-to-attacker-bucket paths. Deletion keeps its verbs.
368
383
  Sid = "DenyProdSnapshotData"
369
384
  Effect = "Deny"
370
- Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot", "rds:Copy*", "rds:Restore*", "rds:StartExportTask"]
371
- Resource = local.guardrail_snapshot_deletion_resources
385
+ Action = ["rds:DeleteDB*Snapshot", "rds:Copy*", "rds:Restore*", "rds:StartExportTask"]
386
+ Resource = local.guardrail_snapshot_data_resources
372
387
  },
373
388
  {
374
389
  # The vault ARN carries a random suffix and static trees have no
@@ -434,7 +449,7 @@ resource "aws_iam_role_policy" "preview_guardrails" {
434
449
  # Update/DeleteService or DeleteCluster.
435
450
  Sid = "DenyProdTaskExecution"
436
451
  Effect = "Deny"
437
- Action = ["ecs:RunTask", "ecs:StopTask", "ecs:ExecuteCommand", "ecs:CreateService", "ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
452
+ Action = ["ecs:RunTask", "ecs:StopTask", "ecs:ExecuteCommand", "ecs:CreateService", "ecs:UpdateService", "ecs:Delete*"]
438
453
  Resource = local.guardrail_task_execution_resources
439
454
  # The bounded scheduler role must RunTask its task
440
455
  # definition at trigger time. A no-op on this side (the preview
@@ -449,7 +464,7 @@ resource "aws_iam_role_policy" "preview_guardrails" {
449
464
  {
450
465
  # RegisterTaskDefinition is likely resource-*-only (void half);
451
466
  # the cluster-scoped RunTask deny above is the real choke.
452
- Sid = "DenyProdTaskDefinitionRegistration"
467
+ Sid = "DenyProdTaskDefRegistration"
453
468
  Effect = "Deny"
454
469
  Action = ["ecs:RegisterTaskDefinition", "ecs:DeregisterTaskDefinition"]
455
470
  Resource = local.guardrail_task_definition_resources
@@ -551,7 +566,7 @@ resource "aws_iam_policy" "preview_boundary" {
551
566
  # weaken security instead of breaking prod tasks.
552
567
  Sid = "BoundaryDenyIAM"
553
568
  Effect = "Deny"
554
- Action = ["iam:CreateRole", "iam:DeleteRole", "iam:UpdateAssumeRolePolicy", "iam:PutRolePolicy", "iam:DeleteRolePolicy", "iam:AttachRolePolicy", "iam:DetachRolePolicy", "iam:PutRolePermissionsBoundary", "iam:DeleteRolePermissionsBoundary", "iam:CreatePolicy", "iam:DeletePolicy", "iam:CreatePolicyVersion", "iam:DeletePolicyVersion", "iam:CreateUser", "iam:DeleteUser", "iam:CreateAccessKey", "iam:DeleteAccessKey"]
569
+ Action = ["iam:CreateRole", "iam:DeleteRole", "iam:UpdateAssumeRolePolicy", "iam:PutRolePolicy", "iam:DeleteRolePolicy", "iam:AttachRolePolicy", "iam:DetachRolePolicy", "iam:*PermissionsBoundary", "iam:CreatePolicy", "iam:DeletePolicy", "iam:*PolicyVersion", "iam:CreateUser", "iam:DeleteUser", "iam:CreateAccessKey", "iam:DeleteAccessKey"]
555
570
  Resource = "*"
556
571
  },
557
572
  {
@@ -587,7 +602,7 @@ resource "aws_iam_policy" "preview_boundary" {
587
602
  {
588
603
  Sid = "BoundaryDenyLambdaRewrite"
589
604
  Effect = "Deny"
590
- Action = ["lambda:UpdateFunctionCode", "lambda:DeleteFunction"]
605
+ Action = ["lambda:UpdateFunctionCode", "lambda:Delete*"]
591
606
  Resource = local.guardrail_lambda_rewrite_resources
592
607
  },
593
608
  {
@@ -611,14 +626,14 @@ resource "aws_iam_policy" "preview_boundary" {
611
626
  {
612
627
  Sid = "BoundaryDenyTableData"
613
628
  Effect = "Deny"
614
- Action = ["dynamodb:DeleteTable", "dynamodb:Batch*", "dynamodb:*Item", "dynamodb:Query", "dynamodb:Scan", "dynamodb:Execute*", "dynamodb:Transact*"]
615
- Resource = local.guardrail_table_deletion_resources
629
+ Action = ["dynamodb:Delete*", "dynamodb:Batch*", "dynamodb:*Item", "dynamodb:Query", "dynamodb:Scan", "dynamodb:Execute*", "dynamodb:Transact*", "dynamodb:Export*", "dynamodb:Restore*", "dynamodb:CreateBackup", "dynamodb:DeleteBackup", "dynamodb:UpdateTable"]
630
+ Resource = local.guardrail_table_data_resources
616
631
  },
617
632
  {
618
633
  Sid = "BoundaryDenySnapshotData"
619
634
  Effect = "Deny"
620
- Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot", "rds:Copy*", "rds:Restore*", "rds:StartExportTask"]
621
- Resource = local.guardrail_snapshot_deletion_resources
635
+ Action = ["rds:DeleteDB*Snapshot", "rds:Copy*", "rds:Restore*", "rds:StartExportTask"]
636
+ Resource = local.guardrail_snapshot_data_resources
622
637
  },
623
638
  {
624
639
  Sid = "BoundaryDenySecretsDeletion"
@@ -637,7 +652,7 @@ resource "aws_iam_policy" "preview_boundary" {
637
652
  # economy — a separate pair would re-inline the ARNs below).
638
653
  Sid = "BoundaryDenyTaskExecution"
639
654
  Effect = "Deny"
640
- Action = ["ecs:RunTask", "ecs:StopTask", "ecs:ExecuteCommand", "ecs:CreateService", "ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
655
+ Action = ["ecs:RunTask", "ecs:StopTask", "ecs:ExecuteCommand", "ecs:CreateService", "ecs:UpdateService", "ecs:Delete*"]
641
656
  Resource = local.guardrail_task_execution_resources
642
657
  # The bounded scheduler role must RunTask its task
643
658
  # definition at trigger time; every other capped caller stays
@@ -649,7 +664,7 @@ resource "aws_iam_policy" "preview_boundary" {
649
664
  }
650
665
  },
651
666
  {
652
- Sid = "BoundaryDenyTaskDefinitionRegistration"
667
+ Sid = "BoundaryDenyTaskDefRegistration"
653
668
  Effect = "Deny"
654
669
  Action = ["ecs:RegisterTaskDefinition", "ecs:DeregisterTaskDefinition"]
655
670
  Resource = local.guardrail_task_definition_resources