grada-run 0.49.2 → 0.49.3

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.49.2",
3
+ "version": "0.49.3",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -25,6 +25,31 @@ const SNAPSHOT_ALREADY_EXISTS_NAMES = new Set([
25
25
  // wastes the timeout and misreports.
26
26
  const TERMINAL_SNAPSHOT_STATUSES = new Set(['failed', 'deleted', 'deleting']);
27
27
 
28
+ // Source database of a described snapshot, by kind. Missing attributes
29
+ // read as undefined (never equal to the target): ownership callers fail
30
+ // closed on unattributed snapshots.
31
+ function snapshotSourceDb(snapshot, isCluster) {
32
+ if (!snapshot) return undefined;
33
+ return isCluster ? snapshot.DBClusterIdentifier : snapshot.DBInstanceIdentifier;
34
+ }
35
+
36
+ // BUG-204 failure: the reused id names another database's snapshot.
37
+ // Shared by the wait and no-wait paths (they differ only in `waited`).
38
+ function failSnapshotMismatch({ spinnerHandle, snapshotId, foreignDb, targetId, projectName, waited, dbIdentifier, region }) {
39
+ spinnerHandle.stop(color.red('❌ Snapshot belongs to another database.'));
40
+ return failCommand({
41
+ print: () => {
42
+ console.log(color.red(`\n✖ Snapshot ${snapshotId} belongs to ${foreignDb ?? 'an unknown database'}, not ${targetId} — refusing to adopt it.`));
43
+ console.log(' Pass a different --id, or delete the foreign snapshot first.\n');
44
+ },
45
+ event: 'db_backup_run',
46
+ telemetry: { projectName, waited },
47
+ errorCode: 'SNAPSHOT_MISMATCH',
48
+ reason: 'snapshot-mismatch',
49
+ resultExtra: { dbIdentifier, region, snapshotId },
50
+ });
51
+ }
52
+
28
53
  export function parseDbBackupArgs(argv = []) {
29
54
  const args = normalizeArgv(argv);
30
55
  if (args[0] === 'db') args.shift();
@@ -177,6 +202,31 @@ async function runDbBackupMain(input = {}) {
177
202
 
178
203
  if (noWait) {
179
204
  if (reusedExisting) {
205
+ // BUG-204: verify ownership even when not waiting — one
206
+ // describe, fail closed on a foreign snapshot. A
207
+ // not-found here is transient (eventual consistency),
208
+ // so only proceed past it.
209
+ let ownedSnapshot = null;
210
+ try {
211
+ if (isCluster) {
212
+ const resp = await rdsClient.send(
213
+ new DescribeDBClusterSnapshotsCommand({ DBClusterSnapshotIdentifier: snapshotId })
214
+ );
215
+ ownedSnapshot = resp.DBClusterSnapshots?.[0] ?? null;
216
+ } else {
217
+ const resp = await rdsClient.send(
218
+ new DescribeDBSnapshotsCommand({ DBSnapshotIdentifier: snapshotId })
219
+ );
220
+ ownedSnapshot = resp.DBSnapshots?.[0] ?? null;
221
+ }
222
+ } catch (error) {
223
+ const notFoundNames = isCluster ? CLUSTER_SNAPSHOT_NOT_FOUND_NAMES : SNAPSHOT_NOT_FOUND_NAMES;
224
+ if (!(error && notFoundNames.has(error.name))) throw error;
225
+ }
226
+ const foreignDb = snapshotSourceDb(ownedSnapshot, isCluster);
227
+ if (ownedSnapshot && foreignDb !== target.id) {
228
+ return failSnapshotMismatch({ spinnerHandle: s, snapshotId, foreignDb, targetId: target.id, projectName, waited: false, dbIdentifier, region });
229
+ }
180
230
  s.stop(color.green('Snapshot already exists.'));
181
231
  console.log(`\n Snapshot ${color.cyan(snapshotId)} already exists — reusing it.`);
182
232
  } else {
@@ -218,6 +268,16 @@ async function runDbBackupMain(input = {}) {
218
268
  throw error;
219
269
  }
220
270
  const snapshot = snapshots[0] || null;
271
+ // BUG-204: an explicit --id can name another database's
272
+ // snapshot (AlreadyExists proves existence, not
273
+ // ownership) — fail closed instead of adopting a
274
+ // foreign snapshot as our safety backup. Checked
275
+ // before status handling so a foreign snapshot fails
276
+ // fast instead of burning the timeout.
277
+ const foreignDb = snapshotSourceDb(snapshot, isCluster);
278
+ if (snapshot && foreignDb !== target.id) {
279
+ return { done: true, value: { sourceMismatch: true, sourceDb: foreignDb } };
280
+ }
221
281
  if (snapshot && snapshot.Status === 'available') {
222
282
  return { done: true, value: snapshot };
223
283
  }
@@ -232,6 +292,10 @@ async function runDbBackupMain(input = {}) {
232
292
  },
233
293
  });
234
294
 
295
+ if (outcome.value?.sourceMismatch) {
296
+ return failSnapshotMismatch({ spinnerHandle: s, snapshotId, foreignDb: outcome.value.sourceDb, targetId: target.id, projectName, waited: true, dbIdentifier, region });
297
+ }
298
+
235
299
  if (outcome.value?.terminalFailure) {
236
300
  const failedStatus = outcome.value.status;
237
301
  s.stop(color.red(`❌ Snapshot ${failedStatus}.`));
@@ -16,7 +16,9 @@ import {
16
16
  resolveHeadless,
17
17
  resolveCwd,
18
18
  readTerraformComputeTarget,
19
+ readTerraformDbKind,
19
20
  } from '../../utils/resolvers.js';
21
+ import { resolveDbIdentifier, resolveDbClusterIdentifier } from '../../utils/rds.js';
20
22
  import { detectMigrationCommand } from '../../utils/detector.js';
21
23
  import { resolveContainer } from '../../utils/ecs.js';
22
24
  import { runEphemeralEcsTask, buildRunnerCommand, parseRunnerTimeout, guardNpmStrippedRunner, reportRunnerOutcome } from '../../utils/ecs-runner.js';
@@ -144,15 +146,20 @@ function injectGateBlock(content, { steps, anchor }) {
144
146
 
145
147
  // Idempotently injects (or refreshes) the migration gate block into a
146
148
  // deploy.yml document. Returns the updated content, or null when neither
147
- // anchor step is present. Pure and unit-tested.
148
- export function injectMigrationGate(workflowContent, { cmd, cliVersion } = {}) {
149
+ // anchor step is present. Pure and unit-tested. The snapshot id embeds
150
+ // the database identifier (BUG-205): bare pre-deploy-<sha> ids match no
151
+ // guardrail or gc name pattern, so they were never protected or retired.
152
+ export function injectMigrationGate(workflowContent, { cmd, cliVersion, dbIdentifier } = {}) {
153
+ if (typeof dbIdentifier !== 'string' || dbIdentifier.trim() === '') {
154
+ throw new Error('injectMigrationGate requires dbIdentifier for the snapshot id');
155
+ }
149
156
  const taskDefRef = '${{ steps.register-task-def.outputs.task-arn }}';
150
157
  const runner = buildRunnerInvocation(cliVersion);
151
158
  return injectGateBlock(workflowContent, {
152
159
  steps: [
153
160
  {
154
161
  stepName: 'Take pre-migration database snapshot',
155
- runLine: `${runner} db backup --id "pre-deploy-\${{ github.sha }}" --headless`,
162
+ runLine: `${runner} db backup --id "${dbIdentifier.trim()}-pre-deploy-\${{ github.sha }}" --headless`,
156
163
  },
157
164
  {
158
165
  stepName: 'Pre-Deploy Database Migration',
@@ -321,7 +328,14 @@ async function runDbMigrateMain(input = {}) {
321
328
  resultExtra: { cluster, service, region },
322
329
  });
323
330
  }
324
- const updated = injectMigrationGate(workflowContent, { cmd: resolvedCmd, cliVersion: getCliVersion() });
331
+ // BUG-205: the gate always targets production (deploy.yml), so
332
+ // resolve the prod db id even with a preview workspace checked
333
+ // out locally. Aurora needs the cluster prefix: cluster
334
+ // snapshots named with the instance prefix would miss the
335
+ // cluster-snapshot guardrail pattern.
336
+ const setupDbResolver = readTerraformDbKind(cwd) === 'cluster' ? resolveDbClusterIdentifier : resolveDbIdentifier;
337
+ const setupDbIdentifier = setupDbResolver({ projectName, workspace: 'default' }, cwd);
338
+ const updated = injectMigrationGate(workflowContent, { cmd: resolvedCmd, cliVersion: getCliVersion(), dbIdentifier: setupDbIdentifier });
325
339
  if (updated === null) {
326
340
  return failCommand({
327
341
  message: '\n✖ Could not find the task-definition registration or ECS deployment step in .github/workflows/deploy.yml to anchor the migration gate.\n',
@@ -273,7 +273,8 @@ async function discoverUnattachedEips({ ec2Client, projectName }) {
273
273
 
274
274
  // Standard target discovery: pre-destroy manual snapshots older than
275
275
  // the age threshold. Scoped by the exact `<db>-manual-<stamp>` naming
276
- // pattern destroy writes (instance AND cluster snapshots) — foreign,
276
+ // pattern destroy writes plus the `<db>-pre-deploy-<sha>` pattern the
277
+ // migration gate writes (instance AND cluster snapshots) — foreign,
277
278
  // automated, non-available, and young snapshots are never proposed.
278
279
  // Tolerant of missing clients/identifiers (programmatic callers without
279
280
  // RDS context discover nothing instead of throwing).
@@ -281,22 +282,37 @@ async function discoverOldManualSnapshots({ rdsClient, dbIdentifier, dbClusterId
281
282
  if (!rdsClient || (!dbIdentifier && !dbClusterIdentifier)) return [];
282
283
  const maxAgeDays = Number(snapshotMaxAgeDays ?? DEFAULT_SNAPSHOT_MAX_AGE_DAYS);
283
284
  const cutoffMs = Date.now() - (Number.isFinite(maxAgeDays) ? maxAgeDays : DEFAULT_SNAPSHOT_MAX_AGE_DAYS) * 86400000;
284
- const patterns = [dbIdentifier, dbClusterIdentifier]
285
+ const dbIds = [dbIdentifier, dbClusterIdentifier]
285
286
  .filter((id) => typeof id === 'string' && id.trim())
286
- .map((id) => new RegExp(`^${escapeRegExp(id.trim().toLowerCase())}-manual-\\d{8}-\\d{6}$`));
287
+ .map((id) => id.trim().toLowerCase());
288
+ const patterns = dbIds
289
+ .map((id) => new RegExp(`^${escapeRegExp(id)}-manual-\\d{8}-\\d{6}$`));
290
+ // BUG-205: the gate's pre-deploy snapshots are per-commit, so without
291
+ // a discovery rule they accumulate into the region snapshot quota.
292
+ const predeployPatterns = dbIds
293
+ .map((id) => new RegExp(`^${escapeRegExp(id)}-pre-deploy-[0-9a-f]{7,40}$`));
294
+ // Legacy bare pre-deploy-<sha> ids carry no db scope: retire them
295
+ // only with a matching source-db attribute, never by name alone.
296
+ const legacyPredeployPattern = /^pre-deploy-[0-9a-f]{7,40}$/;
297
+ const knownSourceDbs = new Set(dbIds);
287
298
  if (patterns.length === 0) return [];
288
- const isRetirable = (snapshotId, status, type, createTime) => {
299
+ const isRetirable = (snapshotId, status, type, createTime, sourceDb) => {
289
300
  if (status !== 'available' || type !== 'manual') return false;
290
301
  const createdMs = createTime ? new Date(createTime).getTime() : NaN;
291
302
  if (!Number.isFinite(createdMs) || createdMs > cutoffMs) return false;
292
- return patterns.some((pattern) => pattern.test(String(snapshotId).toLowerCase()));
303
+ const name = String(snapshotId).toLowerCase();
304
+ if (patterns.some((pattern) => pattern.test(name))) return true;
305
+ if (predeployPatterns.some((pattern) => pattern.test(name))) return true;
306
+ return legacyPredeployPattern.test(name)
307
+ && typeof sourceDb === 'string'
308
+ && knownSourceDbs.has(sourceDb.toLowerCase());
293
309
  };
294
310
  const snapshots = [];
295
311
  let marker;
296
312
  do {
297
313
  const resp = await rdsClient.send(new DescribeDBSnapshotsCommand({ Marker: marker, MaxRecords: 100 }));
298
314
  for (const snap of resp.DBSnapshots || []) {
299
- if (isRetirable(snap.DBSnapshotIdentifier, snap.Status, snap.SnapshotType, snap.SnapshotCreateTime)) {
315
+ if (isRetirable(snap.DBSnapshotIdentifier, snap.Status, snap.SnapshotType, snap.SnapshotCreateTime, snap.DBInstanceIdentifier)) {
300
316
  snapshots.push({ id: snap.DBSnapshotIdentifier, kind: 'instance', createTime: snap.SnapshotCreateTime });
301
317
  }
302
318
  }
@@ -306,7 +322,7 @@ async function discoverOldManualSnapshots({ rdsClient, dbIdentifier, dbClusterId
306
322
  do {
307
323
  const resp = await rdsClient.send(new DescribeDBClusterSnapshotsCommand({ Marker: marker, MaxRecords: 100 }));
308
324
  for (const snap of resp.DBClusterSnapshots || []) {
309
- if (isRetirable(snap.DBClusterSnapshotIdentifier, snap.Status, snap.SnapshotType, snap.SnapshotCreateTime)) {
325
+ if (isRetirable(snap.DBClusterSnapshotIdentifier, snap.Status, snap.SnapshotType, snap.SnapshotCreateTime, snap.DBClusterIdentifier)) {
310
326
  snapshots.push({ id: snap.DBClusterSnapshotIdentifier, kind: 'cluster', createTime: snap.SnapshotCreateTime });
311
327
  }
312
328
  }
@@ -33,7 +33,7 @@ import { trackEvent, flushTelemetry, getCliVersion, setActiveCommandName, resetA
33
33
  import { failCommand } from '../utils/command.js';
34
34
  import { getFrameworkWarning } from '../utils/warnings.js';
35
35
  import { provisionStateBucket, formatStateBucketName, isAuthError, printAwsAuthGuidance } from '../utils/aws.js';
36
- import { generateTemplates } from '../utils/generator.js';
36
+ import { generateTemplates, resolveDbEngineRefs } from '../utils/generator.js';
37
37
  import { planExistingFiles, executeBackup, preserveManagedFiles, restoreManagedFiles, refusalResultForPlan, writeInitManifest } from '../utils/backup.js';
38
38
  import { checkStateAdoption } from '../utils/state-adoption.js';
39
39
  import { atomicWriteFileSync } from '../utils/atomic-write.js';
@@ -1025,7 +1025,11 @@ async function mainStackMain(input = {}) {
1025
1025
  if (migrationGateEnabled && migrationCmd) {
1026
1026
  const deployYmlPath = path.join(dirConfig.targetDir, '.github', 'workflows', 'deploy.yml');
1027
1027
  const workflowContent = readFileSafe(deployYmlPath);
1028
- const gated = workflowContent ? injectMigrationGate(workflowContent, { cmd: migrationCmd, cliVersion: CLI_VERSION }) : null;
1028
+ // BUG-205: scope the gate's snapshot id to the database (aurora
1029
+ // takes the cluster prefix) so guardrails and gc can name it.
1030
+ const gateDbRefs = resolveDbEngineRefs(config.dbEngine);
1031
+ const gateDbIdentifier = `${dirConfig.actualProjectName}${resourceSuffix}-db${gateDbRefs.isCluster ? '-cluster' : ''}`;
1032
+ const gated = workflowContent ? injectMigrationGate(workflowContent, { cmd: migrationCmd, cliVersion: CLI_VERSION, dbIdentifier: gateDbIdentifier }) : null;
1029
1033
  if (gated) {
1030
1034
  atomicWriteFileSync(deployYmlPath, gated);
1031
1035
  console.log(color.green('✅ Wired the pre-deploy database migration gate into .github/workflows/deploy.yml (snapshot first, then migrate)'));
@@ -45,6 +45,21 @@ export function readTerraformComputeTarget(cwd = process.cwd()) {
45
45
  return detectComputeTargetFromMainTf(readFileSafe(path.join(base, 'terraform', 'main.tf')));
46
46
  }
47
47
 
48
+ // Offline database-kind detection for `--setup-ci` (no AWS calls): the
49
+ // generator copies exactly one database template, so the aurora file's
50
+ // presence means cluster snapshots. Unknown/absent means instance — the
51
+ // runtime backup resolves the live kind anyway; the id prefix only
52
+ // name-scopes the snapshot for guardrails + gc.
53
+ export function readTerraformDbKind(cwd = process.cwd()) {
54
+ const base = resolveCwd({}, cwd);
55
+ try {
56
+ if (fsSync.existsSync(path.join(base, 'terraform', 'database-aurora-postgresql.tf'))) return 'cluster';
57
+ } catch {
58
+ // Fall through to the instance default
59
+ }
60
+ return 'instance';
61
+ }
62
+
48
63
  // Predicate form of the target check for commands that adapt (rather
49
64
  // than refuse) per target: `isComputeTarget(cwd, 'lambda')`.
50
65
  export function isComputeTarget(cwd = process.cwd(), ...targets) {
@@ -41,6 +41,76 @@ locals {
41
41
  # task/execution/cron roles, which static trees lack.
42
42
  # tflint-ignore: terraform_unused_declarations
43
43
  preview_boundary_arn = terraform.workspace == "default" ? aws_iam_policy.preview_boundary[0].arn : data.aws_iam_policy.preview_boundary[0].arn
44
+ # Shared twin resource lists: every Deny*/BoundaryDeny* pair consumes
45
+ # one list, so a one-sided resource edit is impossible. New pairs add
46
+ # their list here and reference it from both sides.
47
+ guardrail_compute_abuse_resources = ["*"]
48
+ guardrail_snapshot_sharing_resources = ["*"]
49
+ guardrail_state_destruction_resources = [
50
+ "arn:aws:s3:::{{STATE_BUCKET}}",
51
+ "arn:aws:s3:::{{STATE_BUCKET}}/*",
52
+ ]
53
+ guardrail_ecs_shutdown_resources = [
54
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster/${local.prod_prefix}-cluster",
55
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-cluster/${local.prod_prefix}-service",
56
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-cluster/${local.prod_prefix}-worker-service",
57
+ ]
58
+ guardrail_image_deletion_resources = [
59
+ "arn:aws:ecr:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:repository/${local.prod_prefix}-repo",
60
+ ]
61
+ guardrail_lambda_rewrite_resources = [
62
+ "arn:aws:lambda:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:function:${local.prod_prefix}-fn",
63
+ ]
64
+ guardrail_queue_destruction_resources = [
65
+ "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${local.prod_prefix}-queue",
66
+ "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${local.prod_prefix}-dlq",
67
+ ]
68
+ guardrail_database_destruction_resources = [
69
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:${local.prod_prefix}-db",
70
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:${local.prod_prefix}-db-instance-1",
71
+ ]
72
+ guardrail_aurora_destruction_resources = [
73
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster:${local.prod_prefix}-db-cluster",
74
+ ]
75
+ guardrail_table_deletion_resources = [
76
+ "arn:aws:dynamodb:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:table/${local.prod_prefix}-table",
77
+ ]
78
+ guardrail_snapshot_deletion_resources = [
79
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:snapshot:${local.prod_prefix}-db-*",
80
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster-snapshot:${local.prod_prefix}-db-cluster-*",
81
+ # BUG-205: legacy bare pre-deploy-<sha> ids carry no db prefix, so
82
+ # they match no prod pattern above — deny them outright. gc never
83
+ # runs under preview credentials, so nothing legitimate needs them.
84
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:snapshot:pre-deploy-*",
85
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster-snapshot:pre-deploy-*",
86
+ ]
87
+ guardrail_secrets_deletion_resources = [
88
+ "arn:aws:secretsmanager:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:secret:${local.prod_prefix}-secrets-*",
89
+ ]
90
+ guardrail_log_deletion_resources = [
91
+ "arn:aws:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/ecs/${local.prod_prefix}",
92
+ ]
93
+ guardrail_task_execution_resources = [
94
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster/${local.prod_prefix}-cluster",
95
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-cluster/${local.prod_prefix}-service",
96
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-cluster/${local.prod_prefix}-worker-service",
97
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:task/${local.prod_prefix}-cluster/*",
98
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:task-definition/${local.prod_prefix}-task:*",
99
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:task-definition/${local.prod_prefix}-worker-task:*",
100
+ ]
101
+ guardrail_task_definition_resources = [
102
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:task-definition/${local.prod_prefix}-task:*",
103
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:task-definition/${local.prod_prefix}-worker-task:*",
104
+ ]
105
+ # String-built (not HCL refs): static trees define no IAM roles, so
106
+ # refs would dangle and fail validate. ECS and Lambda use identical
107
+ # physical role names, so one pattern covers both and matches
108
+ # nothing on static.
109
+ guardrail_app_role_resources = [
110
+ "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${local.prod_prefix}-task-role",
111
+ "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${local.prod_prefix}-execution-role",
112
+ "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${local.prod_prefix}-cron-scheduler-role",
113
+ ]
44
114
  }
45
115
 
46
116
  # Deploy role FIRST: readTerraformOidcTrust anchors on this block so re-init
@@ -175,7 +245,7 @@ resource "aws_iam_role_policy" "preview_guardrails" {
175
245
  Sid = "DenyComputeAbuse"
176
246
  Effect = "Deny"
177
247
  Action = ["ec2:RunInstances"]
178
- Resource = "*"
248
+ Resource = local.guardrail_compute_abuse_resources
179
249
  },
180
250
  {
181
251
  Sid = "DenyIAMBackdoors"
@@ -203,110 +273,83 @@ resource "aws_iam_role_policy" "preview_guardrails" {
203
273
  Sid = "DenySnapshotSharing"
204
274
  Effect = "Deny"
205
275
  Action = ["rds:ModifyDBSnapshotAttribute"]
206
- Resource = "*"
276
+ Resource = local.guardrail_snapshot_sharing_resources
207
277
  },
208
278
  {
209
- Sid = "DenyProdStateDestruction"
210
- Effect = "Deny"
211
- Action = ["s3:DeleteBucket", "s3:DeleteObjectVersion"]
212
- Resource = [
213
- "arn:aws:s3:::{{STATE_BUCKET}}",
214
- "arn:aws:s3:::{{STATE_BUCKET}}/*",
215
- ]
279
+ Sid = "DenyProdStateDestruction"
280
+ Effect = "Deny"
281
+ Action = ["s3:DeleteBucket", "s3:DeleteObjectVersion"]
282
+ Resource = local.guardrail_state_destruction_resources
216
283
  },
217
284
  {
218
- Sid = "DenyProdECSShutdown"
219
- Effect = "Deny"
220
- Action = ["ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
221
- Resource = [
222
- "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster/${local.prod_prefix}-cluster",
223
- "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-cluster/${local.prod_prefix}-service",
224
- "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-cluster/${local.prod_prefix}-worker-service",
225
- ]
285
+ Sid = "DenyProdECSShutdown"
286
+ Effect = "Deny"
287
+ Action = ["ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
288
+ Resource = local.guardrail_ecs_shutdown_resources
226
289
  },
227
290
  {
228
- Sid = "DenyProdImageDeletion"
229
- Effect = "Deny"
230
- Action = ["ecr:BatchDeleteImage"]
231
- Resource = [
232
- "arn:aws:ecr:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:repository/${local.prod_prefix}-repo",
233
- ]
291
+ Sid = "DenyProdImageDeletion"
292
+ Effect = "Deny"
293
+ Action = ["ecr:BatchDeleteImage"]
294
+ Resource = local.guardrail_image_deletion_resources
234
295
  },
235
296
  {
236
- Sid = "DenyProdLambdaRewrite"
237
- Effect = "Deny"
238
- Action = ["lambda:UpdateFunctionCode", "lambda:DeleteFunction"]
239
- Resource = [
240
- "arn:aws:lambda:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:function:${local.prod_prefix}-fn",
241
- ]
297
+ Sid = "DenyProdLambdaRewrite"
298
+ Effect = "Deny"
299
+ Action = ["lambda:UpdateFunctionCode", "lambda:DeleteFunction"]
300
+ Resource = local.guardrail_lambda_rewrite_resources
242
301
  },
243
302
  {
244
- Sid = "DenyProdQueueDestruction"
245
- Effect = "Deny"
246
- Action = ["sqs:PurgeQueue", "sqs:DeleteQueue"]
247
- Resource = [
248
- "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${local.prod_prefix}-queue",
249
- "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${local.prod_prefix}-dlq",
250
- ]
303
+ Sid = "DenyProdQueueDestruction"
304
+ Effect = "Deny"
305
+ Action = ["sqs:PurgeQueue", "sqs:DeleteQueue"]
306
+ Resource = local.guardrail_queue_destruction_resources
251
307
  },
252
308
  {
253
- Sid = "DenyProdDatabaseDestruction"
254
- Effect = "Deny"
255
- Action = ["rds:DeleteDBInstance", "rds:ModifyDBInstance"]
256
- Resource = [
257
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:${local.prod_prefix}-db",
258
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:${local.prod_prefix}-db-instance-1",
259
- ]
309
+ Sid = "DenyProdDatabaseDestruction"
310
+ Effect = "Deny"
311
+ Action = ["rds:DeleteDBInstance", "rds:ModifyDBInstance"]
312
+ Resource = local.guardrail_database_destruction_resources
260
313
  },
261
314
  {
262
- Sid = "DenyProdAuroraDestruction"
263
- Effect = "Deny"
264
- Action = ["rds:DeleteDBCluster", "rds:ModifyDBCluster"]
265
- Resource = [
266
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster:${local.prod_prefix}-db-cluster",
267
- ]
315
+ Sid = "DenyProdAuroraDestruction"
316
+ Effect = "Deny"
317
+ Action = ["rds:DeleteDBCluster", "rds:ModifyDBCluster"]
318
+ Resource = local.guardrail_aurora_destruction_resources
268
319
  },
269
320
  {
270
- Sid = "DenyProdTableDeletion"
271
- Effect = "Deny"
272
- Action = ["dynamodb:DeleteTable"]
273
- Resource = [
274
- "arn:aws:dynamodb:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:table/${local.prod_prefix}-table",
275
- ]
321
+ Sid = "DenyProdTableDeletion"
322
+ Effect = "Deny"
323
+ Action = ["dynamodb:DeleteTable"]
324
+ Resource = local.guardrail_table_deletion_resources
276
325
  },
277
326
  {
278
327
  # BUG-208: manual snapshots (grada names them
279
- # <db-identifier>-manual-<stamp>) are directly deletable;
328
+ # <db-identifier>-manual-<stamp> and
329
+ # <db-identifier>-pre-deploy-<sha>) are directly deletable;
280
330
  # automated snapshots can only go away via retention changes or
281
331
  # instance deletion, both already denied above.
282
- Sid = "DenyProdSnapshotDeletion"
283
- Effect = "Deny"
284
- Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot"]
285
- Resource = [
286
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:snapshot:${local.prod_prefix}-db-*",
287
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster-snapshot:${local.prod_prefix}-db-cluster-*",
288
- ]
332
+ Sid = "DenyProdSnapshotDeletion"
333
+ Effect = "Deny"
334
+ Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot"]
335
+ Resource = local.guardrail_snapshot_deletion_resources
289
336
  },
290
337
  {
291
338
  # The vault ARN carries a random suffix and static trees have no
292
339
  # vault at all (no secrets.tf), so match the tight name prefix —
293
340
  # on static it simply matches nothing.
294
- Sid = "DenyProdSecretsDeletion"
295
- Effect = "Deny"
296
- Action = ["secretsmanager:DeleteSecret"]
297
- Resource = [
298
- "arn:aws:secretsmanager:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:secret:${local.prod_prefix}-secrets-*",
299
- ]
341
+ Sid = "DenyProdSecretsDeletion"
342
+ Effect = "Deny"
343
+ Action = ["secretsmanager:DeleteSecret"]
344
+ Resource = local.guardrail_secrets_deletion_resources
300
345
  },
301
346
  {
302
347
  # Web and worker containers share one log group; deleting it
303
348
  # wipes the audit trail for both.
304
- Sid = "DenyProdLogDeletion"
305
- Effect = "Deny"
306
- Action = ["logs:DeleteLogGroup"]
307
- Resource = [
308
- "arn:aws:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/ecs/${local.prod_prefix}",
309
- ]
349
+ Sid = "DenyProdLogDeletion"
350
+ Effect = "Deny"
351
+ Action = ["logs:DeleteLogGroup"]
352
+ Resource = local.guardrail_log_deletion_resources
310
353
  },
311
354
  {
312
355
  # BUG-212: every role preview credentials create must carry the
@@ -342,6 +385,41 @@ resource "aws_iam_role_policy" "preview_guardrails" {
342
385
  "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/${local.prod_prefix}-preview-boundary",
343
386
  ]
344
387
  },
388
+ {
389
+ # BUG-215: close by target — deny the execution APIs on exact
390
+ # prod ARNs while pr-* stays allowed. No describes: plan.yml
391
+ # refreshes prod state with preview credentials, so describing
392
+ # prod is legitimate traffic.
393
+ Sid = "DenyProdTaskExecution"
394
+ Effect = "Deny"
395
+ Action = ["ecs:RunTask", "ecs:StopTask", "ecs:ExecuteCommand", "ecs:CreateService"]
396
+ Resource = local.guardrail_task_execution_resources
397
+ },
398
+ {
399
+ # RegisterTaskDefinition is likely resource-*-only (void half);
400
+ # the cluster-scoped RunTask deny above is the real choke.
401
+ Sid = "DenyProdTaskDefinitionRegistration"
402
+ Effect = "Deny"
403
+ Action = ["ecs:RegisterTaskDefinition", "ecs:DeregisterTaskDefinition"]
404
+ Resource = local.guardrail_task_definition_resources
405
+ },
406
+ {
407
+ Sid = "DenyProdPassRole"
408
+ Effect = "Deny"
409
+ Action = ["iam:PassRole"]
410
+ Resource = local.guardrail_app_role_resources
411
+ },
412
+ {
413
+ # Trust writes close the assume-it-directly bypass (re-trusting
414
+ # the prod task role would defeat every execution deny);
415
+ # DeleteRole guards the roles themselves. UpdateRole and
416
+ # tagging stay allowed (cosmetic — description, session
417
+ # duration within AWS bounds, tags).
418
+ Sid = "DenyProdAppRoleMutation"
419
+ Effect = "Deny"
420
+ Action = ["iam:AttachRolePolicy", "iam:DetachRolePolicy", "iam:PutRolePolicy", "iam:DeleteRolePolicy", "iam:UpdateAssumeRolePolicy", "iam:DeleteRole"]
421
+ Resource = local.guardrail_app_role_resources
422
+ },
345
423
  ]
346
424
  })
347
425
  }
@@ -351,8 +429,8 @@ resource "aws_iam_role_policy" "preview_guardrails" {
351
429
  # carries this boundary, so a backdoor role is born capped: its
352
430
  # effective permissions are its own policies intersected with this one.
353
431
  # Deny-list shape (default-allow) on purpose: a missing entry weakens
354
- # security instead of breaking prod tasks. Keep the data denies in sync
355
- # with preview_guardrails above.
432
+ # security instead of breaking prod tasks. Twin pairs share their
433
+ # resource lists via the locals above, so one-sided edits fail loudly.
356
434
  resource "aws_iam_policy" "preview_boundary" {
357
435
  count = terraform.workspace == "default" ? 1 : 0
358
436
  name = "${local.prod_prefix}-preview-boundary"
@@ -368,10 +446,13 @@ resource "aws_iam_policy" "preview_boundary" {
368
446
  Resource = "*"
369
447
  },
370
448
  {
371
- Sid = "BoundaryDenyIAM"
372
- Effect = "Deny"
373
- Action = ["iam:*"]
374
- Resource = "*"
449
+ # BUG-214: capped roles must pass their task roles to ECS (the
450
+ # scheduler role passes at invocation time), so PassRole is
451
+ # carved out here and re-gated on service + target below.
452
+ Sid = "BoundaryDenyIAM"
453
+ Effect = "Deny"
454
+ NotAction = ["iam:PassRole"]
455
+ Resource = "*"
375
456
  },
376
457
  {
377
458
  Sid = "BoundaryDenyAuditBilling"
@@ -383,107 +464,147 @@ resource "aws_iam_policy" "preview_boundary" {
383
464
  Sid = "BoundaryDenyComputeAbuse"
384
465
  Effect = "Deny"
385
466
  Action = ["ec2:RunInstances"]
386
- Resource = "*"
467
+ Resource = local.guardrail_compute_abuse_resources
387
468
  },
388
469
  {
389
470
  Sid = "BoundaryDenySnapshotSharing"
390
471
  Effect = "Deny"
391
472
  Action = ["rds:ModifyDBSnapshotAttribute"]
392
- Resource = "*"
473
+ Resource = local.guardrail_snapshot_sharing_resources
393
474
  },
394
475
  {
395
- Sid = "BoundaryDenyStateDestruction"
396
- Effect = "Deny"
397
- Action = ["s3:DeleteBucket", "s3:DeleteObjectVersion"]
398
- Resource = [
399
- "arn:aws:s3:::{{STATE_BUCKET}}",
400
- "arn:aws:s3:::{{STATE_BUCKET}}/*",
401
- ]
476
+ Sid = "BoundaryDenyStateDestruction"
477
+ Effect = "Deny"
478
+ Action = ["s3:DeleteBucket", "s3:DeleteObjectVersion"]
479
+ Resource = local.guardrail_state_destruction_resources
402
480
  },
403
481
  {
404
- Sid = "BoundaryDenyECSShutdown"
405
- Effect = "Deny"
406
- Action = ["ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
407
- Resource = [
408
- "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster/${local.prod_prefix}-cluster",
409
- "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-cluster/${local.prod_prefix}-service",
410
- "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-cluster/${local.prod_prefix}-worker-service",
411
- ]
482
+ Sid = "BoundaryDenyECSShutdown"
483
+ Effect = "Deny"
484
+ Action = ["ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
485
+ Resource = local.guardrail_ecs_shutdown_resources
412
486
  },
413
487
  {
414
- Sid = "BoundaryDenyImageDeletion"
415
- Effect = "Deny"
416
- Action = ["ecr:BatchDeleteImage"]
417
- Resource = [
418
- "arn:aws:ecr:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:repository/${local.prod_prefix}-repo",
419
- ]
488
+ Sid = "BoundaryDenyImageDeletion"
489
+ Effect = "Deny"
490
+ Action = ["ecr:BatchDeleteImage"]
491
+ Resource = local.guardrail_image_deletion_resources
420
492
  },
421
493
  {
422
- Sid = "BoundaryDenyLambdaRewrite"
423
- Effect = "Deny"
424
- Action = ["lambda:UpdateFunctionCode", "lambda:DeleteFunction"]
425
- Resource = [
426
- "arn:aws:lambda:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:function:${local.prod_prefix}-fn",
427
- ]
494
+ Sid = "BoundaryDenyLambdaRewrite"
495
+ Effect = "Deny"
496
+ Action = ["lambda:UpdateFunctionCode", "lambda:DeleteFunction"]
497
+ Resource = local.guardrail_lambda_rewrite_resources
428
498
  },
429
499
  {
430
- Sid = "BoundaryDenyQueueDestruction"
431
- Effect = "Deny"
432
- Action = ["sqs:PurgeQueue", "sqs:DeleteQueue"]
433
- Resource = [
434
- "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${local.prod_prefix}-queue",
435
- "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${local.prod_prefix}-dlq",
436
- ]
500
+ Sid = "BoundaryDenyQueueDestruction"
501
+ Effect = "Deny"
502
+ Action = ["sqs:PurgeQueue", "sqs:DeleteQueue"]
503
+ Resource = local.guardrail_queue_destruction_resources
437
504
  },
438
505
  {
439
- Sid = "BoundaryDenyDatabaseDestruction"
440
- Effect = "Deny"
441
- Action = ["rds:DeleteDBInstance", "rds:ModifyDBInstance"]
442
- Resource = [
443
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:${local.prod_prefix}-db",
444
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:${local.prod_prefix}-db-instance-1",
445
- ]
506
+ Sid = "BoundaryDenyDatabaseDestruction"
507
+ Effect = "Deny"
508
+ Action = ["rds:DeleteDBInstance", "rds:ModifyDBInstance"]
509
+ Resource = local.guardrail_database_destruction_resources
446
510
  },
447
511
  {
448
- Sid = "BoundaryDenyAuroraDestruction"
449
- Effect = "Deny"
450
- Action = ["rds:DeleteDBCluster", "rds:ModifyDBCluster"]
451
- Resource = [
452
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster:${local.prod_prefix}-db-cluster",
453
- ]
512
+ Sid = "BoundaryDenyAuroraDestruction"
513
+ Effect = "Deny"
514
+ Action = ["rds:DeleteDBCluster", "rds:ModifyDBCluster"]
515
+ Resource = local.guardrail_aurora_destruction_resources
454
516
  },
455
517
  {
456
- Sid = "BoundaryDenyTableDeletion"
457
- Effect = "Deny"
458
- Action = ["dynamodb:DeleteTable"]
459
- Resource = [
460
- "arn:aws:dynamodb:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:table/${local.prod_prefix}-table",
461
- ]
518
+ Sid = "BoundaryDenyTableDeletion"
519
+ Effect = "Deny"
520
+ Action = ["dynamodb:DeleteTable"]
521
+ Resource = local.guardrail_table_deletion_resources
462
522
  },
463
523
  {
464
- Sid = "BoundaryDenySnapshotDeletion"
465
- Effect = "Deny"
466
- Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot"]
467
- Resource = [
468
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:snapshot:${local.prod_prefix}-db-*",
469
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster-snapshot:${local.prod_prefix}-db-cluster-*",
470
- ]
524
+ Sid = "BoundaryDenySnapshotDeletion"
525
+ Effect = "Deny"
526
+ Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot"]
527
+ Resource = local.guardrail_snapshot_deletion_resources
471
528
  },
472
529
  {
473
- Sid = "BoundaryDenySecretsDeletion"
474
- Effect = "Deny"
475
- Action = ["secretsmanager:DeleteSecret"]
476
- Resource = [
477
- "arn:aws:secretsmanager:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:secret:${local.prod_prefix}-secrets-*",
478
- ]
530
+ Sid = "BoundaryDenySecretsDeletion"
531
+ Effect = "Deny"
532
+ Action = ["secretsmanager:DeleteSecret"]
533
+ Resource = local.guardrail_secrets_deletion_resources
534
+ },
535
+ {
536
+ Sid = "BoundaryDenyLogDeletion"
537
+ Effect = "Deny"
538
+ Action = ["logs:DeleteLogGroup"]
539
+ Resource = local.guardrail_log_deletion_resources
540
+ },
541
+ {
542
+ Sid = "BoundaryDenyTaskExecution"
543
+ Effect = "Deny"
544
+ Action = ["ecs:RunTask", "ecs:StopTask", "ecs:ExecuteCommand", "ecs:CreateService"]
545
+ Resource = local.guardrail_task_execution_resources
479
546
  },
480
547
  {
481
- Sid = "BoundaryDenyLogDeletion"
548
+ Sid = "BoundaryDenyTaskDefinitionRegistration"
549
+ Effect = "Deny"
550
+ Action = ["ecs:RegisterTaskDefinition", "ecs:DeregisterTaskDefinition"]
551
+ Resource = local.guardrail_task_definition_resources
552
+ },
553
+ {
554
+ Sid = "BoundaryDenyPassRole"
555
+ Effect = "Deny"
556
+ Action = ["iam:PassRole"]
557
+ Resource = local.guardrail_app_role_resources
558
+ },
559
+ {
560
+ Sid = "BoundaryDenyAppRoleMutation"
561
+ Effect = "Deny"
562
+ Action = ["iam:AttachRolePolicy", "iam:DetachRolePolicy", "iam:PutRolePolicy", "iam:DeleteRolePolicy", "iam:UpdateAssumeRolePolicy", "iam:DeleteRole"]
563
+ Resource = local.guardrail_app_role_resources
564
+ },
565
+ {
566
+ # BUG-214: carved PassRole may only pass to the ECS tasks
567
+ # service (mirrors the scheduler policy's own condition).
568
+ Sid = "BoundaryDenyPassRoleOffService"
569
+ Effect = "Deny"
570
+ Action = ["iam:PassRole"]
571
+ Resource = "*"
572
+ Condition = {
573
+ StringNotEquals = {
574
+ "iam:PassedToService" = "ecs-tasks.amazonaws.com"
575
+ }
576
+ }
577
+ },
578
+ {
579
+ # ... and only task roles: preview patterns plus the prod pair
580
+ # (shared local, so renames flow). Preview app names put the
581
+ # workspace between the project and the collision suffix
582
+ # (<project>-pr-<n>-<suffix>), so the preview patterns key off
583
+ # {{PROJECT_NAME}}, not prod_prefix. Prod roles stay
584
+ # scheduler-only via the statement below.
585
+ Sid = "BoundaryDenyPassRoleOffTarget"
482
586
  Effect = "Deny"
483
- Action = ["logs:DeleteLogGroup"]
484
- Resource = [
485
- "arn:aws:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/ecs/${local.prod_prefix}",
486
- ]
587
+ Action = ["iam:PassRole"]
588
+ NotResource = concat([
589
+ "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/{{PROJECT_NAME}}-pr-*-task-role",
590
+ "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/{{PROJECT_NAME}}-pr-*-execution-role",
591
+ ], local.guardrail_app_role_resources)
592
+ },
593
+ {
594
+ # Prod task roles pass only by the prod scheduler role, which
595
+ # passes them at invocation time (its own policy allows only
596
+ # those two roles, so the boundary stays a backstop). Every
597
+ # other capped caller stays denied, and the scheduler itself
598
+ # cannot pass anything outside the four roles above.
599
+ Sid = "BoundaryDenyProdPassRoleOffScheduler"
600
+ Effect = "Deny"
601
+ Action = ["iam:PassRole"]
602
+ Resource = local.guardrail_app_role_resources
603
+ Condition = {
604
+ StringNotEquals = {
605
+ "aws:PrincipalArn" = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${local.prod_prefix}-cron-scheduler-role"
606
+ }
607
+ }
487
608
  },
488
609
  ]
489
610
  })