grada-run 0.49.1 → 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.1",
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) {
@@ -112,7 +112,7 @@ const RUNBOOKS = {
112
112
  interactive: 'Wait 5–15 minutes for the distribution to settle, then re-run the same command.',
113
113
  },
114
114
  BUCKET_NOT_EMPTY: {
115
- message: 'S3 buckets still report object versions after draining.',
115
+ message: 'Terraform destroy failed twice: an S3 bucket still holds object versions.',
116
116
  headless: 'Re-run destroy — drained buckets usually read empty within a minute; if it persists, empty the bucket by hand in the AWS Console.',
117
117
  interactive: 'Re-run destroy — drained buckets usually read empty within a minute; if it persists, empty the bucket by hand in the AWS Console.',
118
118
  },
@@ -218,9 +218,13 @@ export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}
218
218
  if (timer && typeof timer.unref === 'function') timer.unref();
219
219
  }
220
220
 
221
- child.stdout.on('data', (data) => {
222
- if (isDone) return;
223
- const lines = data.toString().split('\n').filter(line => line.trim() !== '');
221
+ // BUG-213: pipe chunks split lines at arbitrary byte offsets, so
222
+ // each chunk's trailing fragment is carried over and only
223
+ // newline-terminated lines are delivered. Splitting per chunk
224
+ // injects newlines into giant single-line JSON (show -json),
225
+ // which breaks parsing downstream.
226
+ let pendingFragment = '';
227
+ const handleLines = (lines) => {
224
228
  if (typeof onStdoutLine === 'function') {
225
229
  for (const line of lines) onStdoutLine(line);
226
230
  }
@@ -237,6 +241,21 @@ export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}
237
241
  const latestLine = lines[lines.length - 1].trim();
238
242
  emit(`${loadingPrefix} - ${color.dim(truncateSpinnerText(latestLine, { fixedOverhead: lineOverhead }))}`);
239
243
  }
244
+ };
245
+ const flushFragment = () => {
246
+ if (pendingFragment.trim() === '') {
247
+ pendingFragment = '';
248
+ return;
249
+ }
250
+ const trailing = pendingFragment;
251
+ pendingFragment = '';
252
+ handleLines([trailing]);
253
+ };
254
+ child.stdout.on('data', (data) => {
255
+ if (isDone) return;
256
+ const parts = (pendingFragment + data.toString()).split('\n');
257
+ pendingFragment = parts.pop() ?? '';
258
+ handleLines(parts.filter(line => line.trim() !== ''));
240
259
  });
241
260
 
242
261
  child.stderr.on('data', (data) => {
@@ -247,6 +266,7 @@ export function runTerraformCommand(args, cwd, spin, loadingPrefix, options = {}
247
266
  if (isDone) return;
248
267
  isDone = true;
249
268
  cleanup();
269
+ flushFragment();
250
270
  if (code === 0) {
251
271
  settleMarker('completed', { exitCode: code });
252
272
  resolve();
@@ -34,9 +34,10 @@ WORKDIR /app
34
34
  RUN addgroup -g 1001 appgroup && \
35
35
  adduser -u 1001 -G appgroup -s /bin/sh -D appuser
36
36
 
37
- # Runtime libraries only (native wheels arrive inside the venv)
37
+ # Runtime libraries only (native wheels arrive inside the venv), plus a
38
+ # CA bundle: without it no verified TLS egress works (RDS, AWS APIs).
38
39
  RUN apk update && apk upgrade --no-cache && \
39
- apk add --no-cache libpq
40
+ apk add --no-cache libpq ca-certificates
40
41
 
41
42
  # Strip the base image's system pip (the venv already ships without one)
42
43
  RUN /usr/local/bin/python -m pip uninstall -y setuptools wheel pip && \
@@ -10,6 +10,10 @@ RUN CGO_ENABLED=0 GOOS=linux go build -o /main .
10
10
  FROM alpine:3.20@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc
11
11
  WORKDIR /app
12
12
 
13
+ # Ship a CA bundle: without it the static binary cannot verify any TLS
14
+ # egress (RDS, AWS APIs, webhooks).
15
+ RUN apk add --no-cache ca-certificates
16
+
13
17
  # Create unprivileged user
14
18
  RUN addgroup -g 1001 -S appgroup && \
15
19
  adduser -S appuser -u 1001 -G appgroup
@@ -9,8 +9,10 @@ RUN npm run build
9
9
  # --- Stage 2: Production ---
10
10
  FROM node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914
11
11
 
12
- # 1. DevSecOps: Patch Alpine OS
13
- RUN apk update && apk upgrade --no-cache
12
+ # 1. DevSecOps: Patch Alpine OS, and ship a CA bundle: without it no
13
+ # verified TLS egress works (RDS, AWS APIs, webhooks) from runtimes
14
+ # using the system store.
15
+ RUN apk update && apk upgrade --no-cache && apk add --no-cache ca-certificates
14
16
 
15
17
  ENV NODE_ENV=production
16
18
  WORKDIR /app
@@ -24,6 +24,7 @@ WORKDIR /app
24
24
  # FIX 2: Upgrade Alpine packages and absolutely destroy npm, yarn, and corepack
25
25
  # to eliminate all remaining Critical/High container vulnerabilities.
26
26
  RUN apk upgrade --no-cache && \
27
+ apk add --no-cache ca-certificates && \
27
28
  rm -rf /usr/local/lib/node_modules/npm \
28
29
  /usr/local/bin/npm \
29
30
  /usr/local/bin/npx \
@@ -9,8 +9,10 @@ RUN npm ci --omit=dev && npm cache clean --force && mkdir -p node_modules
9
9
  # --- Stage 2: Production runner (no package managers) ---
10
10
  FROM node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS runner
11
11
 
12
- # 1. DevSecOps: Patch underlying Alpine OS vulnerabilities
13
- RUN apk update && apk upgrade --no-cache
12
+ # 1. DevSecOps: Patch underlying Alpine OS vulnerabilities, and ship a
13
+ # CA bundle: without it no verified TLS egress works (RDS, AWS APIs,
14
+ # webhooks) from runtimes using the system store.
15
+ RUN apk update && apk upgrade --no-cache && apk add --no-cache ca-certificates
14
16
 
15
17
  # 2. Set production environment (optimizes Node and prevents dev dependencies)
16
18
  ENV NODE_ENV=production
@@ -26,6 +26,7 @@ ENV NITRO_HOST="0.0.0.0"
26
26
  # 1. Upgrade Alpine OS packages to clear OpenSSL/crypto CVEs
27
27
  # 2. Vaporize Node package managers (npm, yarn, corepack) to clear ghost CVEs
28
28
  RUN apk update && apk upgrade --no-cache && \
29
+ apk add --no-cache ca-certificates && \
29
30
  rm -rf /usr/local/lib/node_modules \
30
31
  /usr/local/bin/npm \
31
32
  /usr/local/bin/npx \
@@ -34,9 +34,10 @@ WORKDIR /app
34
34
  RUN addgroup -S appgroup && \
35
35
  adduser -S appuser -G appgroup -D -s /bin/sh
36
36
 
37
- # Runtime libraries only (native wheels arrive inside the venv)
37
+ # Runtime libraries only (native wheels arrive inside the venv), plus a
38
+ # CA bundle: without it no verified TLS egress works (RDS, AWS APIs).
38
39
  RUN apk update && apk upgrade --no-cache && \
39
- apk add --no-cache libpq
40
+ apk add --no-cache libpq ca-certificates
40
41
 
41
42
  # Strip the base image's system pip (the venv already ships without one)
42
43
  RUN /usr/local/bin/python -m pip uninstall -y setuptools wheel pip && \
@@ -33,7 +33,7 @@ ENV RAILS_ENV=production \
33
33
  # Upgrade Alpine OS to patch system CVEs and install runtime libs
34
34
  # Explicitly patch Ruby's default gems and remove their legacy gemspecs so Trivy ignores them
35
35
  RUN apk update && apk upgrade --no-cache && \
36
- apk add --no-cache postgresql-libs tzdata && \
36
+ apk add --no-cache postgresql-libs tzdata ca-certificates && \
37
37
  apk add --no-cache --virtual .build-deps build-base zlib-dev && \
38
38
  gem install erb net-imap resolv rexml uri zlib && \
39
39
  rm -f /usr/local/lib/ruby/gems/*/specifications/default/erb-*.gemspec \
@@ -26,8 +26,10 @@ RUN GRADA_BYPASS=true npm run build
26
26
  # ==========================================
27
27
  FROM node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914
28
28
 
29
- # 1. DevSecOps: Patch underlying Alpine OS vulnerabilities
30
- RUN apk update && apk upgrade --no-cache
29
+ # 1. DevSecOps: Patch underlying Alpine OS vulnerabilities, and ship a
30
+ # CA bundle: without it no verified TLS egress works (RDS, AWS APIs,
31
+ # webhooks) from runtimes using the system store.
32
+ RUN apk update && apk upgrade --no-cache && apk add --no-cache ca-certificates
31
33
 
32
34
  # 2. Set production environment
33
35
  ENV NODE_ENV=production
@@ -13,7 +13,8 @@
13
13
 
14
14
  # --- IAM Role assumed by EventBridge Scheduler ---
15
15
  resource "aws_iam_role" "scheduler_cron_role" {
16
- name = "${local.app_name}-cron-scheduler-role"
16
+ name = "${local.app_name}-cron-scheduler-role"
17
+ permissions_boundary = local.preview_boundary_arn
17
18
  assume_role_policy = jsonencode({
18
19
  Version = "2012-10-17"
19
20
  Statement = [
@@ -7,7 +7,8 @@
7
7
 
8
8
  # --- IAM Role assumed by EventBridge Scheduler ---
9
9
  resource "aws_iam_role" "scheduler_cron_role" {
10
- name = "${local.app_name}-cron-scheduler-role"
10
+ name = "${local.app_name}-cron-scheduler-role"
11
+ permissions_boundary = local.preview_boundary_arn
11
12
  assume_role_policy = jsonencode({
12
13
  Version = "2012-10-17"
13
14
  Statement = [
@@ -85,8 +85,9 @@ data "aws_iam_policy_document" "ecs_trust" {
85
85
  }
86
86
 
87
87
  resource "aws_iam_role" "execution_role" {
88
- name = "${local.app_name}-execution-role"
89
- assume_role_policy = data.aws_iam_policy_document.ecs_trust.json
88
+ name = "${local.app_name}-execution-role"
89
+ assume_role_policy = data.aws_iam_policy_document.ecs_trust.json
90
+ permissions_boundary = local.preview_boundary_arn
90
91
  }
91
92
 
92
93
  resource "aws_iam_role_policy_attachment" "execution_role_policy" {
@@ -109,8 +110,9 @@ data "aws_iam_policy_document" "lambda_task_trust" {
109
110
  }
110
111
 
111
112
  resource "aws_iam_role" "task_role" {
112
- name = "${local.app_name}-task-role"
113
- assume_role_policy = data.aws_iam_policy_document.lambda_task_trust.json
113
+ name = "${local.app_name}-task-role"
114
+ assume_role_policy = data.aws_iam_policy_document.lambda_task_trust.json
115
+ permissions_boundary = local.preview_boundary_arn
114
116
  }
115
117
 
116
118
  # VPC ENI management plus CloudWatch Logs delivery (this single managed
@@ -94,8 +94,9 @@ data "aws_iam_policy_document" "ecs_trust" {
94
94
  }
95
95
 
96
96
  resource "aws_iam_role" "execution_role" {
97
- name = "${local.app_name}-execution-role"
98
- assume_role_policy = data.aws_iam_policy_document.ecs_trust.json
97
+ name = "${local.app_name}-execution-role"
98
+ assume_role_policy = data.aws_iam_policy_document.ecs_trust.json
99
+ permissions_boundary = local.preview_boundary_arn
99
100
  }
100
101
 
101
102
  resource "aws_iam_role_policy_attachment" "execution_role_policy" {
@@ -106,8 +107,9 @@ resource "aws_iam_role_policy_attachment" "execution_role_policy" {
106
107
  # --- IAM: Task Role ---
107
108
  # Allows your application code running INSIDE the container to access AWS services
108
109
  resource "aws_iam_role" "task_role" {
109
- name = "${local.app_name}-task-role"
110
- assume_role_policy = data.aws_iam_policy_document.ecs_trust.json
110
+ name = "${local.app_name}-task-role"
111
+ assume_role_policy = data.aws_iam_policy_document.ecs_trust.json
112
+ permissions_boundary = local.preview_boundary_arn
111
113
  }
112
114
 
113
115
  # --- IAM: ECS Exec (SSM) permissions for the task role ---
@@ -36,6 +36,81 @@ locals {
36
36
  # (not local.app_name): app_name carries the workspace suffix in preview
37
37
  # workspaces, while these denies must always name production.
38
38
  prod_prefix = "{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}"
39
+ # Boundary ARN resolving in every workspace: created in default, read
40
+ # everywhere else (mirrors the secrets-vault pattern). Consumed by the
41
+ # task/execution/cron roles, which static trees lack.
42
+ # tflint-ignore: terraform_unused_declarations
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
+ ]
39
114
  }
40
115
 
41
116
  # Deploy role FIRST: readTerraformOidcTrust anchors on this block so re-init
@@ -170,7 +245,7 @@ resource "aws_iam_role_policy" "preview_guardrails" {
170
245
  Sid = "DenyComputeAbuse"
171
246
  Effect = "Deny"
172
247
  Action = ["ec2:RunInstances"]
173
- Resource = "*"
248
+ Resource = local.guardrail_compute_abuse_resources
174
249
  },
175
250
  {
176
251
  Sid = "DenyIAMBackdoors"
@@ -198,111 +273,347 @@ resource "aws_iam_role_policy" "preview_guardrails" {
198
273
  Sid = "DenySnapshotSharing"
199
274
  Effect = "Deny"
200
275
  Action = ["rds:ModifyDBSnapshotAttribute"]
201
- Resource = "*"
276
+ Resource = local.guardrail_snapshot_sharing_resources
202
277
  },
203
278
  {
204
- Sid = "DenyProdStateDestruction"
205
- Effect = "Deny"
206
- Action = ["s3:DeleteBucket", "s3:DeleteObjectVersion"]
207
- Resource = [
208
- "arn:aws:s3:::{{STATE_BUCKET}}",
209
- "arn:aws:s3:::{{STATE_BUCKET}}/*",
210
- ]
279
+ Sid = "DenyProdStateDestruction"
280
+ Effect = "Deny"
281
+ Action = ["s3:DeleteBucket", "s3:DeleteObjectVersion"]
282
+ Resource = local.guardrail_state_destruction_resources
211
283
  },
212
284
  {
213
- Sid = "DenyProdECSShutdown"
214
- Effect = "Deny"
215
- Action = ["ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
216
- Resource = [
217
- "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster/${local.prod_prefix}-cluster",
218
- "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-cluster/${local.prod_prefix}-service",
219
- "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",
220
- ]
285
+ Sid = "DenyProdECSShutdown"
286
+ Effect = "Deny"
287
+ Action = ["ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
288
+ Resource = local.guardrail_ecs_shutdown_resources
221
289
  },
222
290
  {
223
- Sid = "DenyProdImageDeletion"
224
- Effect = "Deny"
225
- Action = ["ecr:BatchDeleteImage"]
226
- Resource = [
227
- "arn:aws:ecr:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:repository/${local.prod_prefix}-repo",
228
- ]
291
+ Sid = "DenyProdImageDeletion"
292
+ Effect = "Deny"
293
+ Action = ["ecr:BatchDeleteImage"]
294
+ Resource = local.guardrail_image_deletion_resources
229
295
  },
230
296
  {
231
- Sid = "DenyProdLambdaRewrite"
232
- Effect = "Deny"
233
- Action = ["lambda:UpdateFunctionCode", "lambda:DeleteFunction"]
234
- Resource = [
235
- "arn:aws:lambda:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:function:${local.prod_prefix}-fn",
236
- ]
297
+ Sid = "DenyProdLambdaRewrite"
298
+ Effect = "Deny"
299
+ Action = ["lambda:UpdateFunctionCode", "lambda:DeleteFunction"]
300
+ Resource = local.guardrail_lambda_rewrite_resources
237
301
  },
238
302
  {
239
- Sid = "DenyProdQueueDestruction"
240
- Effect = "Deny"
241
- Action = ["sqs:PurgeQueue", "sqs:DeleteQueue"]
242
- Resource = [
243
- "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${local.prod_prefix}-queue",
244
- "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${local.prod_prefix}-dlq",
245
- ]
303
+ Sid = "DenyProdQueueDestruction"
304
+ Effect = "Deny"
305
+ Action = ["sqs:PurgeQueue", "sqs:DeleteQueue"]
306
+ Resource = local.guardrail_queue_destruction_resources
246
307
  },
247
308
  {
248
- Sid = "DenyProdDatabaseDestruction"
249
- Effect = "Deny"
250
- Action = ["rds:DeleteDBInstance", "rds:ModifyDBInstance"]
251
- Resource = [
252
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:${local.prod_prefix}-db",
253
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:${local.prod_prefix}-db-instance-1",
254
- ]
309
+ Sid = "DenyProdDatabaseDestruction"
310
+ Effect = "Deny"
311
+ Action = ["rds:DeleteDBInstance", "rds:ModifyDBInstance"]
312
+ Resource = local.guardrail_database_destruction_resources
255
313
  },
256
314
  {
257
- Sid = "DenyProdAuroraDestruction"
258
- Effect = "Deny"
259
- Action = ["rds:DeleteDBCluster", "rds:ModifyDBCluster"]
260
- Resource = [
261
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster:${local.prod_prefix}-db-cluster",
262
- ]
315
+ Sid = "DenyProdAuroraDestruction"
316
+ Effect = "Deny"
317
+ Action = ["rds:DeleteDBCluster", "rds:ModifyDBCluster"]
318
+ Resource = local.guardrail_aurora_destruction_resources
263
319
  },
264
320
  {
265
- Sid = "DenyProdTableDeletion"
266
- Effect = "Deny"
267
- Action = ["dynamodb:DeleteTable"]
268
- Resource = [
269
- "arn:aws:dynamodb:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:table/${local.prod_prefix}-table",
270
- ]
321
+ Sid = "DenyProdTableDeletion"
322
+ Effect = "Deny"
323
+ Action = ["dynamodb:DeleteTable"]
324
+ Resource = local.guardrail_table_deletion_resources
271
325
  },
272
326
  {
273
327
  # BUG-208: manual snapshots (grada names them
274
- # <db-identifier>-manual-<stamp>) are directly deletable;
328
+ # <db-identifier>-manual-<stamp> and
329
+ # <db-identifier>-pre-deploy-<sha>) are directly deletable;
275
330
  # automated snapshots can only go away via retention changes or
276
331
  # instance deletion, both already denied above.
277
- Sid = "DenyProdSnapshotDeletion"
278
- Effect = "Deny"
279
- Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot"]
280
- Resource = [
281
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:snapshot:${local.prod_prefix}-db-*",
282
- "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster-snapshot:${local.prod_prefix}-db-cluster-*",
283
- ]
332
+ Sid = "DenyProdSnapshotDeletion"
333
+ Effect = "Deny"
334
+ Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot"]
335
+ Resource = local.guardrail_snapshot_deletion_resources
284
336
  },
285
337
  {
286
338
  # The vault ARN carries a random suffix and static trees have no
287
339
  # vault at all (no secrets.tf), so match the tight name prefix —
288
340
  # on static it simply matches nothing.
289
- Sid = "DenyProdSecretsDeletion"
290
- Effect = "Deny"
291
- Action = ["secretsmanager:DeleteSecret"]
292
- Resource = [
293
- "arn:aws:secretsmanager:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:secret:${local.prod_prefix}-secrets-*",
294
- ]
341
+ Sid = "DenyProdSecretsDeletion"
342
+ Effect = "Deny"
343
+ Action = ["secretsmanager:DeleteSecret"]
344
+ Resource = local.guardrail_secrets_deletion_resources
295
345
  },
296
346
  {
297
347
  # Web and worker containers share one log group; deleting it
298
348
  # wipes the audit trail for both.
299
- Sid = "DenyProdLogDeletion"
349
+ Sid = "DenyProdLogDeletion"
350
+ Effect = "Deny"
351
+ Action = ["logs:DeleteLogGroup"]
352
+ Resource = local.guardrail_log_deletion_resources
353
+ },
354
+ {
355
+ # BUG-212: every role preview credentials create must carry the
356
+ # boundary — a missing key fails StringNotEquals, so unbounded
357
+ # creation is denied and born-capped roles cannot escalate.
358
+ Sid = "DenyRoleWithoutBoundary"
359
+ Effect = "Deny"
360
+ Action = ["iam:CreateRole"]
361
+ Resource = "*"
362
+ Condition = {
363
+ StringNotEquals = {
364
+ "iam:PermissionsBoundary" = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/${local.prod_prefix}-preview-boundary"
365
+ }
366
+ }
367
+ },
368
+ {
369
+ # The boundary cannot be swapped or removed after creation:
370
+ # legitimate Terraform never touches it (stable ARN, and
371
+ # deleting a role needs no boundary call).
372
+ Sid = "DenyBoundarySwap"
373
+ Effect = "Deny"
374
+ Action = ["iam:PutRolePermissionsBoundary", "iam:DeleteRolePermissionsBoundary"]
375
+ Resource = "*"
376
+ },
377
+ {
378
+ # The boundary policy itself cannot be neutered (preview
379
+ # Terraform never manages it: this file is
380
+ # default-workspace-only).
381
+ Sid = "DenyBoundaryMutation"
300
382
  Effect = "Deny"
301
- Action = ["logs:DeleteLogGroup"]
383
+ Action = ["iam:*"]
302
384
  Resource = [
303
- "arn:aws:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/ecs/${local.prod_prefix}",
385
+ "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/${local.prod_prefix}-preview-boundary",
304
386
  ]
305
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
+ },
306
423
  ]
307
424
  })
308
425
  }
426
+
427
+ # BUG-212: permissions boundary capping every role preview credentials
428
+ # can create. The guardrail above denies CreateRole unless the request
429
+ # carries this boundary, so a backdoor role is born capped: its
430
+ # effective permissions are its own policies intersected with this one.
431
+ # Deny-list shape (default-allow) on purpose: a missing entry weakens
432
+ # security instead of breaking prod tasks. Twin pairs share their
433
+ # resource lists via the locals above, so one-sided edits fail loudly.
434
+ resource "aws_iam_policy" "preview_boundary" {
435
+ count = terraform.workspace == "default" ? 1 : 0
436
+ name = "${local.prod_prefix}-preview-boundary"
437
+ description = "Permissions boundary capping roles created by preview CI runs"
438
+
439
+ policy = jsonencode({
440
+ Version = "2012-10-17"
441
+ Statement = [
442
+ {
443
+ Sid = "BoundaryBaseAllow"
444
+ Effect = "Allow"
445
+ Action = "*"
446
+ Resource = "*"
447
+ },
448
+ {
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 = "*"
456
+ },
457
+ {
458
+ Sid = "BoundaryDenyAuditBilling"
459
+ Effect = "Deny"
460
+ Action = ["cloudtrail:*", "organizations:*", "aws-portal:*", "billing:*"]
461
+ Resource = "*"
462
+ },
463
+ {
464
+ Sid = "BoundaryDenyComputeAbuse"
465
+ Effect = "Deny"
466
+ Action = ["ec2:RunInstances"]
467
+ Resource = local.guardrail_compute_abuse_resources
468
+ },
469
+ {
470
+ Sid = "BoundaryDenySnapshotSharing"
471
+ Effect = "Deny"
472
+ Action = ["rds:ModifyDBSnapshotAttribute"]
473
+ Resource = local.guardrail_snapshot_sharing_resources
474
+ },
475
+ {
476
+ Sid = "BoundaryDenyStateDestruction"
477
+ Effect = "Deny"
478
+ Action = ["s3:DeleteBucket", "s3:DeleteObjectVersion"]
479
+ Resource = local.guardrail_state_destruction_resources
480
+ },
481
+ {
482
+ Sid = "BoundaryDenyECSShutdown"
483
+ Effect = "Deny"
484
+ Action = ["ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
485
+ Resource = local.guardrail_ecs_shutdown_resources
486
+ },
487
+ {
488
+ Sid = "BoundaryDenyImageDeletion"
489
+ Effect = "Deny"
490
+ Action = ["ecr:BatchDeleteImage"]
491
+ Resource = local.guardrail_image_deletion_resources
492
+ },
493
+ {
494
+ Sid = "BoundaryDenyLambdaRewrite"
495
+ Effect = "Deny"
496
+ Action = ["lambda:UpdateFunctionCode", "lambda:DeleteFunction"]
497
+ Resource = local.guardrail_lambda_rewrite_resources
498
+ },
499
+ {
500
+ Sid = "BoundaryDenyQueueDestruction"
501
+ Effect = "Deny"
502
+ Action = ["sqs:PurgeQueue", "sqs:DeleteQueue"]
503
+ Resource = local.guardrail_queue_destruction_resources
504
+ },
505
+ {
506
+ Sid = "BoundaryDenyDatabaseDestruction"
507
+ Effect = "Deny"
508
+ Action = ["rds:DeleteDBInstance", "rds:ModifyDBInstance"]
509
+ Resource = local.guardrail_database_destruction_resources
510
+ },
511
+ {
512
+ Sid = "BoundaryDenyAuroraDestruction"
513
+ Effect = "Deny"
514
+ Action = ["rds:DeleteDBCluster", "rds:ModifyDBCluster"]
515
+ Resource = local.guardrail_aurora_destruction_resources
516
+ },
517
+ {
518
+ Sid = "BoundaryDenyTableDeletion"
519
+ Effect = "Deny"
520
+ Action = ["dynamodb:DeleteTable"]
521
+ Resource = local.guardrail_table_deletion_resources
522
+ },
523
+ {
524
+ Sid = "BoundaryDenySnapshotDeletion"
525
+ Effect = "Deny"
526
+ Action = ["rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot"]
527
+ Resource = local.guardrail_snapshot_deletion_resources
528
+ },
529
+ {
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
546
+ },
547
+ {
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"
586
+ Effect = "Deny"
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
+ }
608
+ },
609
+ ]
610
+ })
611
+ }
612
+
613
+ # Preview workspaces create pr-suffixed roles through the same templates,
614
+ # so they read the default workspace's boundary instead of creating one
615
+ # (IAM names are account-global).
616
+ data "aws_iam_policy" "preview_boundary" {
617
+ count = terraform.workspace == "default" ? 0 : 1
618
+ name = "${local.prod_prefix}-preview-boundary"
619
+ }