grada-run 0.41.4 → 0.41.5

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.41.4",
3
+ "version": "0.41.5",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -478,6 +478,21 @@ resource "aws_subnet" "db_isolated" {
478
478
  }
479
479
  }`;
480
480
 
481
+ // Merges names into the `managed_env_names` collision-guard list in
482
+ // main.tf content. Sorted + deduplicated for deterministic output;
483
+ // idempotent reruns return the content identical. Returns content
484
+ // unchanged when the block is absent (pre-list trees fail open — the
485
+ // CLI preflight still guards local applies).
486
+ export function upsertManagedEnvNames(tfContent, names = []) {
487
+ const content = String(tfContent ?? '');
488
+ const match = /managed_env_names\s*=\s*\[([^\]]*)\]/.exec(content);
489
+ if (!match) return content;
490
+ const existing = [...match[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]);
491
+ const merged = [...new Set([...existing, ...names])].sort();
492
+ if (merged.length === existing.length && merged.every((name, i) => name === existing[i])) return content;
493
+ return content.replace(match[0], `managed_env_names = [${merged.map((name) => JSON.stringify(name)).join(', ')}]`);
494
+ }
495
+
481
496
  // Idempotently appends the isolated-subnet block to network.tf content.
482
497
  // Returns the content unchanged when the block already exists. Uses the
483
498
  // line-anchored lookup so a `#` comment quoting the header never
@@ -1552,6 +1567,8 @@ async function scaffoldDatabaseInner(engine, projectDir, refs) {
1552
1567
  const withVpc = ensureLambdaVpcConfig(updated);
1553
1568
  vpcInjected = withVpc !== updated;
1554
1569
  updated = withVpc;
1570
+ } else {
1571
+ updated = upsertManagedEnvNames(updated, [...env.map((entry) => entry.name), ...secrets.map((entry) => entry.name)]);
1555
1572
  }
1556
1573
  const envInjected = updated !== mainTfContent;
1557
1574
  if (envInjected) await atomicWriteFile(mainTfPath, normalizeBlankLines(updated));
@@ -1735,10 +1752,11 @@ async function scaffoldAddonInner(capability, resolvedOpts, { cwd, region } = {}
1735
1752
  // ElastiCache lives inside the VPC: attach the function on first Redis
1736
1753
  // provisioning when the project was generated without a database.
1737
1754
  const withVpc = capability === 'db:redis' ? ensureLambdaVpcConfig(updated) : updated;
1738
- const envInjected = withVpc !== mainTfContent;
1755
+ const withManaged = isLambda ? withVpc : upsertManagedEnvNames(withVpc, envVars.map((entry) => entry.name));
1756
+ const envInjected = withManaged !== mainTfContent;
1739
1757
  const vpcInjected = withVpc !== updated;
1740
1758
  if (envInjected) {
1741
- await atomicWriteFile(mainTfPath, normalizeBlankLines(withVpc));
1759
+ await atomicWriteFile(mainTfPath, normalizeBlankLines(withManaged));
1742
1760
  }
1743
1761
 
1744
1762
  let workerEnvInjected = false;
@@ -12,7 +12,7 @@ import { runTerraformCommand, getTerraformOutputs, readLastRunMarker, isInterrup
12
12
  import { classifyTerraformError, countRecreateCollisions, getRunbook, ERROR_CODES } from '../utils/terraform-errors.js';
13
13
  import { readInitManifest, recordAppliedTarget } from '../utils/backup.js';
14
14
  import { requireManagedTree, parseStateBucketBackend, upsertAutoTfvar } from '../utils/terraform-metadata.js';
15
- import { readTerraformComputeTarget, resolveRegion } from '../utils/resolvers.js';
15
+ import { readTerraformComputeTarget, resolveRegion, readRenderedContainerEnvNames } from '../utils/resolvers.js';
16
16
  import { requireAwakeEnvironment, resolveSleepTarget, guardSleepingEnv } from '../utils/sleep-state.js';
17
17
  import { promptStateBucketRecovery, recreateStateBucket } from '../utils/recovery.js';
18
18
  import { resolveProjectName, readResourceSuffix } from '../utils/resolvers.js';
@@ -339,6 +339,34 @@ async function enforceTargetSwitchGate({ options, targetDir, tfDir, runTerraform
339
339
 
340
340
  // Programmatic entry wrapper: stamps cli_command for telemetry on every
341
341
  // invocation path, including direct imports that bypass bin/cli.js and MCP.
342
+ // Intersects secret_keys.json with the RENDERED container env names so
343
+ // stale, confirmed-through, or hand-edited keys files fail here instead
344
+ // of late on the raw ECS 400. Returns null when clean or inapplicable
345
+ // (non-ECS target, unreadable inputs — those surface through their own
346
+ // errors), else { kind, keys, detail? } for the failCommand call site.
347
+ function preflightSecretEnvCollisions({ targetDir }) {
348
+ if (readTerraformComputeTarget(targetDir) !== 'ecs') return null;
349
+ let keysRaw;
350
+ try {
351
+ keysRaw = fs.readFileSync(path.join(targetDir, 'terraform', 'secret_keys.json'), 'utf-8');
352
+ } catch {
353
+ return null;
354
+ }
355
+ let keys;
356
+ try {
357
+ keys = JSON.parse(keysRaw);
358
+ } catch {
359
+ return { kind: 'malformed', keys: [], detail: 'is not valid JSON.' };
360
+ }
361
+ if (!Array.isArray(keys) || keys.some((key) => typeof key !== 'string' || key === '')) {
362
+ return { kind: 'malformed', keys: [], detail: 'must be a JSON array of non-empty key names.' };
363
+ }
364
+ const rendered = readRenderedContainerEnvNames(targetDir);
365
+ const collisions = [...new Set(keys.filter((key) => rendered.includes(key)))];
366
+ if (collisions.length === 0) return null;
367
+ return { kind: 'collision', keys: collisions };
368
+ }
369
+
342
370
  export async function applyStack(input = {}) {
343
371
  setActiveCommandName('apply');
344
372
  try {
@@ -426,6 +454,34 @@ async function applyStackMain(input = {}) {
426
454
  if (!sleepGuard.proceed) return sleepGuard.result;
427
455
  }
428
456
 
457
+ // 1d. Preflight secret/env collisions (BUG-81): stale,
458
+ // confirmed-through, or hand-edited keys files would die late on
459
+ // the raw ECS 400 — fail here naming the key and the fix. ECS-only
460
+ // (Lambda maps no secrets into env), unconditional (a collision is
461
+ // deterministic breakage no flag can fix), and fail-open on
462
+ // unreadable inputs. Runs on dry runs too: previews should
463
+ // surface deterministic breakage, not hide it.
464
+ const secretPreflight = preflightSecretEnvCollisions({ targetDir });
465
+ if (secretPreflight !== null) {
466
+ const shown = secretPreflight.keys.length <= 8
467
+ ? secretPreflight.keys.join(', ')
468
+ : `${secretPreflight.keys.slice(0, 8).join(', ')} (+${secretPreflight.keys.length - 8} more)`;
469
+ const isCollision = secretPreflight.kind === 'collision';
470
+ return failCommand({
471
+ noExit: isProgrammaticCall(options),
472
+ message: isCollision
473
+ ? `\n✖ ${secretPreflight.keys.length} secret ${secretPreflight.keys.length === 1 ? 'key' : 'keys'} in terraform/secret_keys.json ${secretPreflight.keys.length === 1 ? 'collides' : 'collide'} with container environment names: ${shown}.\n`
474
+ : `\n✖ terraform/secret_keys.json ${secretPreflight.detail}\n`,
475
+ hint: isCollision
476
+ ? ' ECS rejects task definitions where a secret shares a name with an environment variable. Remove the key(s) from .env and re-push (colliding keys are skipped automatically), then re-run apply.\n'
477
+ : ' Re-push your secrets to regenerate it: npx grada-run secrets push .env\n',
478
+ event: 'infrastructure_applied',
479
+ telemetry: { projectName: path.basename(targetDir), collision_count: secretPreflight.keys.length },
480
+ errorCode: 'SECRETS_ENV_COLLISION',
481
+ reason: isCollision ? 'secrets-env-collision' : 'malformed-keys-file',
482
+ });
483
+ }
484
+
429
485
  // 2. Read the actual AWS configuration from disk (CPU, Memory, Region, Database)
430
486
  const detectedConfig = parseTerraformConfig(tfDir);
431
487
  detectedConfig.projectName = path.basename(process.cwd());
@@ -33,6 +33,7 @@ export const PROJECT_CHECKS = [
33
33
  { id: 'state_lock', label: 'Terraform state lock', scope: 'project', severity: 'fail', run: checkStateLock, hint: () => 'If no apply is running, release it with: terraform force-unlock <lock-id> (find the holder via grada doctor --deep).' },
34
34
  { id: 'interrupted_run', label: 'Interrupted Terraform run', scope: 'project', severity: 'warn', run: checkInterruptedRun, hint: () => 'Review the last apply/destroy output before trusting applied state; the next run overwrites the marker.' },
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
+ { id: 'oidc_immutable_claims', label: 'OIDC trust formats', scope: 'project', severity: 'warn', run: checkOidcImmutableClaims, hint: () => 'Re-run setup to upgrade the trust, or add a repo:<owner>@*/<name>@*:* entry to terraform/oidc.tf.' },
36
37
  ];
37
38
 
38
39
  const INSTALL_HINTS = {
@@ -220,6 +221,26 @@ function checkOidcTrustScope({ cwd }) {
220
221
  };
221
222
  }
222
223
 
224
+ // Project check: a trust covering classic subject claims only rejects
225
+ // every repo created after 2026-07-15 (immutable `repo:<owner>@<id>/`
226
+ // `<name>@<id>:...` subjects). Warning-grade like the scope check: the
227
+ // open trust matches all formats, and any `@*`/`@<id>` entry counts as
228
+ // immutable coverage.
229
+ function checkOidcImmutableClaims({ cwd }) {
230
+ const trust = readTerraformOidcTrust(cwd);
231
+ if (trust === null) return { ok: true, skipped: 'no oidc.tf trust found' };
232
+ if (trust.kind === 'unparseable') {
233
+ return { ok: true, skipped: 'trust value not parseable (non-literal claim — review by hand)' };
234
+ }
235
+ const entries = trust.kind === 'list' ? trust.entries : [trust.value];
236
+ const covered = entries.some((entry) => entry === 'repo:*' || /@(\*|\d)/.test(entry));
237
+ if (covered) return { ok: true };
238
+ return {
239
+ ok: false,
240
+ detailLines: ['CI trust covers classic subject claims only — workflows in repos created after 2026-07-15 use immutable claims this trust rejects, failing every deploy with an OIDC assume-role error.'],
241
+ };
242
+ }
243
+
223
244
  // Project check: a leftover interrupted/running marker means the last
224
245
  // Terraform run never settled. Warning-grade (apply proceeds with its own
225
246
  // warning): surfaces yellow without flipping the verdict red.
@@ -82,15 +82,49 @@ export async function mainStack(input = {}) {
82
82
  }
83
83
  }
84
84
 
85
+ // Scoped classic claim shape: `repo:<owner>/<name>[:<suffix>]`. Owner and
86
+ // name exclude `@` (GitHub names cannot contain it), so immutable-format
87
+ // entries never match and pass through untouched.
88
+ const SCOPED_SUB_RE = /^repo:([^/@]+)\/([^/@:]+)(?::(.*))?$/;
89
+
90
+ // Builds the immutable-claim companion for a classic entry, or null when
91
+ // the entry is not classic-shaped (open trust, immutable entries, and
92
+ // anything exotic stay single).
93
+ export function immutableCompanion(classicSub) {
94
+ if (typeof classicSub !== 'string') return null;
95
+ const match = SCOPED_SUB_RE.exec(classicSub);
96
+ if (!match) return null;
97
+ const [, owner, name, rest] = match;
98
+ const suffix = rest === undefined ? '*' : rest;
99
+ return `repo:${owner}@*/${name}@*:${suffix}`;
100
+ }
101
+
102
+ // Renders the OIDC sub claim as an HCL value fragment: scoped trusts gain
103
+ // the immutable-claim companion (repos created after 2026-07-15 emit
104
+ // `repo:<owner>@<id>/<name>@<id>:...`, which classic patterns reject),
105
+ // while the open trust (matching every format) and non-classic literals
106
+ // render verbatim.
107
+ export function renderOidcSubClaim(sub) {
108
+ const companion = immutableCompanion(sub);
109
+ if (companion === null) return `"${sub}"`;
110
+ return `["${sub}", "${companion}"]`;
111
+ }
112
+
85
113
  // Classifies an existing tree's OIDC claim for re-init: a bare string (or
86
- // single-entry list, IAM-identical) renders verbatim; anything richer is
87
- // described for warnings and guarded against silent widening.
114
+ // single-entry list, IAM-identical) renders verbatim; our own canonical
115
+ // dual-format pair resolves back to its classic entry so re-init stays
116
+ // stable; anything richer is described for warnings and guarded against
117
+ // silent widening.
88
118
  function classifyTreeTrust(claim) {
89
119
  if (!claim) return { trust: null, complex: null };
90
120
  if (claim.kind === 'string') return { trust: claim.value, complex: null };
91
121
  if (claim.kind === 'list' && claim.entries.length === 1) {
92
122
  return { trust: claim.entries[0], complex: null };
93
123
  }
124
+ if (claim.kind === 'list' && claim.entries.length === 2
125
+ && immutableCompanion(claim.entries[0]) === claim.entries[1]) {
126
+ return { trust: claim.entries[0], complex: null };
127
+ }
94
128
  if (claim.kind === 'list') {
95
129
  const entries = claim.entries.length > 0 ? ` (${claim.entries.join(', ')})` : '';
96
130
  return { trust: null, complex: `${claim.entries.length}-entry list${entries}` };
@@ -780,7 +814,7 @@ async function mainStackMain(input = {}) {
780
814
  HEALTH_CHECK_PATH: config.healthCheckPath,
781
815
  DESIRED_COUNT: config.desiredCount,
782
816
  DEPLOY_BRANCH: config.branch,
783
- GITHUB_REPO_SUB: oidcTrustSub,
817
+ GITHUB_REPO_SUB: renderOidcSubClaim(oidcTrustSub),
784
818
  BUILD_DIR: buildDir,
785
819
  finalFramework: config.framework,
786
820
  NEEDS_DATABASE: config.needsDatabase,
@@ -6,10 +6,10 @@ import { spinner, confirm, outro, isCancel } from '@clack/prompts';
6
6
  import color from 'picocolors';
7
7
  import path from 'path';
8
8
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
9
- import { failCommand, isProgrammaticCall, refuseIfNonInteractive } from '../utils/command.js';
9
+ import { failCommand, refuseIfNonInteractive } from '../utils/command.js';
10
10
  import { atomicWriteFile } from '../utils/atomic-write.js';
11
11
  import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
12
- import { readTerraformComputeTarget, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
12
+ import { readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, readRenderedContainerEnvNames } from '../utils/resolvers.js';
13
13
  import { ADDON_ENV_VARS, ADDON_REGISTRY } from '../utils/addons.js';
14
14
  import { requireManagedTree } from '../utils/terraform-metadata.js';
15
15
  import { truncateSpinnerText } from '../utils/spinner-text.js';
@@ -149,7 +149,7 @@ const BASE_MANAGED_ENV = {
149
149
  ecs: ['PORT', 'NODE_ENV'],
150
150
  lambda: ['PORT', 'AWS_LWA_PORT', 'APP_SECRETS_ARN'],
151
151
  };
152
- const DB_MANAGED_ENV = ['DB_HOST', 'DB_PORT', 'DB_NAME', 'DB_ENGINE', 'DB_USER', 'DB_PASSWORD'];
152
+ const DB_MANAGED_ENV = ['DB_HOST', 'DB_PORT', 'DB_NAME', 'DB_USER', 'DB_PASSWORD'];
153
153
 
154
154
  // Wiring-like names whose local-dev values break production when pushed:
155
155
  // the migrate gate trusts a present DATABASE_URL verbatim, so a localhost
@@ -159,7 +159,9 @@ const NON_PROD_VALUE_PATTERN = /localhost|127\.0\.0\.1|0\.0\.0\.0|example\.(com|
159
159
 
160
160
  // Managed-name set for this tree: the target base set, plus DB names when
161
161
  // a database file exists, plus each enabled addon's injected names
162
- // (capability file present under terraform/). Sorted for stable output.
162
+ // (capability file present under terraform/), plus every name in the
163
+ // RENDERED task definitions (covers compose-injected and hand-added env
164
+ // the maps cannot predict). Sorted for stable output.
163
165
  export async function getManagedEnvNames(cwd = process.cwd(), target = 'ecs') {
164
166
  const names = new Set(BASE_MANAGED_ENV[target] || BASE_MANAGED_ENV.ecs);
165
167
  let tfFiles = [];
@@ -168,14 +170,27 @@ export async function getManagedEnvNames(cwd = process.cwd(), target = 'ecs') {
168
170
  } catch {
169
171
  return [...names].sort();
170
172
  }
171
- if (tfFiles.some((file) => file.startsWith('database') && file.endsWith('.tf'))) {
173
+ const dbFile = tfFiles.find((file) => file.startsWith('database') && file.endsWith('.tf'));
174
+ if (dbFile) {
172
175
  for (const name of DB_MANAGED_ENV) names.add(name);
176
+ // DB_ENGINE is rendered only for non-postgres engines: including
177
+ // it blindly would auto-skip a legitimate custom key on postgres
178
+ // trees with a false "injected by Grada" notice. Unparseable
179
+ // files exclude it — the preflights still catch real collisions.
180
+ try {
181
+ const dbContent = await fs.readFile(path.join(cwd, 'terraform', dbFile), 'utf-8');
182
+ const engine = /engine\s*=\s*"([^"]+)"/.exec(dbContent)?.[1];
183
+ if (engine && engine !== 'postgres') names.add('DB_ENGINE');
184
+ } catch {
185
+ // Fall through with the base DB set.
186
+ }
173
187
  }
174
188
  for (const [capability, entry] of Object.entries(ADDON_REGISTRY)) {
175
189
  const envEntries = ADDON_ENV_VARS[capability];
176
190
  if (!envEntries || !entry.file || !tfFiles.includes(entry.file)) continue;
177
191
  for (const { name } of envEntries) names.add(name);
178
192
  }
193
+ for (const name of readRenderedContainerEnvNames(cwd)) names.add(name);
179
194
  return [...names].sort();
180
195
  }
181
196
 
@@ -361,16 +376,24 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
361
376
  return;
362
377
  }
363
378
 
364
- // Pre-write guards (BUG-79): collisions brick ECS deploys with a
365
- // RegisterTaskDefinition 400, and local-dev wiring values get
366
- // trusted verbatim by the migrate gate — both must surface before
379
+ // Pre-write guards (BUG-79/81): colliding keys are auto-skipped
380
+ // on ECS — pushing them can only brick the deploy, so excluding
381
+ // them with a loud notice beats refusing and demanding a hand
382
+ // edit. Local-dev wiring values warn. Everything surfaces before
367
383
  // any AWS or keys-file write. The spinner stops once for all
368
384
  // pre-write output and restarts when the push proceeds.
369
385
  const pushTarget = readTerraformComputeTarget(process.cwd());
370
386
  const managedNames = await getManagedEnvNames(process.cwd(), pushTarget);
371
387
  const collisions = Object.keys(parsedSecrets).filter((key) => managedNames.includes(key));
372
388
  const wiringHits = findNonProdWiring(parsedSecrets);
373
- const needsPreWriteOutput = collisions.length > 0 || wiringHits.length > 0;
389
+ // Explicit --yes/--auto-approve pushes everything (vault-storage
390
+ // escape hatch); the apply preflight still backstops deploys.
391
+ const skipBypassed = [opts.autoApprove, opts.yes].some((flag) => flag === true || flag === 'true');
392
+ const skipped = (collisions.length > 0 && pushTarget !== 'lambda' && !skipBypassed) ? collisions : [];
393
+ const skippedSet = new Set(skipped);
394
+ const pushableSecrets = Object.fromEntries(Object.entries(parsedSecrets).filter(([key]) => !skippedSet.has(key)));
395
+ const needsPreWriteOutput = skipped.length > 0 || wiringHits.length > 0
396
+ || (collisions.length > 0 && pushTarget === 'lambda');
374
397
  if (needsPreWriteOutput) s.stop('Pre-flight checks done.');
375
398
  for (const { key, indicator } of wiringHits) {
376
399
  console.log(color.yellow(`⚠️ Warning: "${key}" looks like a local-dev value (contains "${indicator}") — pushed as-is, production wiring would dial it.`));
@@ -378,43 +401,13 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
378
401
  if (collisions.length > 0 && pushTarget === 'lambda') {
379
402
  console.log(color.yellow(`⚠️ Warning: ${summarizeKeys(collisions)} ${collisions.length === 1 ? 'is' : 'are'} also injected by Grada as plain environment variables — the pushed vault value may be shadowed at runtime.`));
380
403
  }
381
- if (collisions.length > 0 && pushTarget !== 'lambda') {
382
- console.log(color.yellow(`⚠️ Warning: ${summarizeKeys(collisions)} ${collisions.length === 1 ? 'collides' : 'collide'} with names Grada injects into the container — the next deploy would fail with an ECS task-definition error.`));
383
- // Explicit --yes/--auto-approve acknowledges the collision and
384
- // proceeds; every other non-interactive caller refuses loudly
385
- // (a colliding push guarantees a broken deploy, so proceeding
386
- // silently is never the safe default).
387
- const explicitlyApproved = [opts.autoApprove, opts.yes].some((flag) => flag === true || flag === 'true');
388
- if (!explicitlyApproved) {
389
- if (opts.isHeadless || opts.headless || process.env.CI) {
390
- return failCommand({
391
- noExit: isProgrammaticCall(opts),
392
- message: `\n✖ secrets push refuses to push ${summarizeKeys(collisions)}: Grada-managed environment names cannot also be vault secrets on ECS targets.`,
393
- hint: ' Rename the key in your .env file, or re-run with --yes to acknowledge the collision and push anyway.\n',
394
- event: 'secrets_pushed',
395
- telemetry: { projectName: resolvedProjectName, managed_collisions: collisions.length },
396
- errorCode: 'SECRETS_MANAGED_KEY_COLLISION',
397
- reason: 'managed-key-collision',
398
- exitCode: 1,
399
- });
400
- }
401
- const refusedCollision = await refuseIfNonInteractive(opts, {
402
- message: `\n✖ secrets push needs approval before pushing ${summarizeKeys(collisions)}: Grada-managed environment names cannot also be vault secrets on ECS targets.`,
403
- hint: ' Re-run with --yes to acknowledge the collision non-interactively, or run interactively to decide.\n',
404
- event: 'secrets_pushed',
405
- telemetry: { projectName: resolvedProjectName, managed_collisions: collisions.length },
406
- errorCode: 'SECRETS_MANAGED_KEY_COLLISION',
407
- });
408
- if (refusedCollision) return refusedCollision;
409
- const proceed = await confirm({
410
- message: `Push ${collisions.length === 1 ? 'this colliding key' : 'these colliding keys'} anyway? Deploys will fail until the collision is removed.`,
411
- initialValue: false,
412
- });
413
- if (isCancel(proceed) || proceed !== true) {
414
- console.log(color.dim('Secrets push cancelled. The vault and secret_keys.json are unchanged.'));
415
- return;
416
- }
417
- }
404
+ if (skipped.length > 0) {
405
+ console.log(color.yellow(`⚠️ Skipping ${skipped.length} colliding ${skipped.length === 1 ? 'key' : 'keys'} (injected by Grada — remove from .env to silence this):`));
406
+ for (const key of skipped) console.log(color.yellow(`- ${key} (skipped — Grada-managed name)`));
407
+ }
408
+ if (Object.keys(pushableSecrets).length === 0) {
409
+ console.log(color.dim('Nothing left to push — the vault and secret_keys.json are unchanged.'));
410
+ return;
418
411
  }
419
412
  if (needsPreWriteOutput) s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
420
413
 
@@ -451,6 +444,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
451
444
  // BUG-80: push is full-replace, so vault keys absent from .env are
452
445
  // deleted by the update below. Name every victim before writing;
453
446
  // interactive runs confirm first, headless proceeds loudly.
447
+ // Skipped keys are present in .env, so they never land here — their
448
+ // exclusion from the vault write is covered by the skip notice
449
+ // above, not by this confirm.
454
450
  const removed = (existingKeys ?? []).filter((key) => !Object.hasOwn(parsedSecrets, key));
455
451
  if (removed.length > 0) {
456
452
  s.stop('Pre-flight checks done.');
@@ -482,17 +478,17 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
482
478
  // 5. Update the secret string in AWS
483
479
  const command = new UpdateSecretCommand({
484
480
  SecretId: `${secretVaultId(resolvedProjectName)}`,
485
- SecretString: JSON.stringify(parsedSecrets),
481
+ SecretString: JSON.stringify(pushableSecrets),
486
482
  });
487
483
 
488
484
  await client.send(command);
489
485
 
490
- const keys = Object.keys(parsedSecrets);
486
+ const keys = Object.keys(pushableSecrets);
491
487
  const keysFilePath = path.join(process.cwd(), 'terraform', 'secret_keys.json');
492
488
 
493
489
  await atomicWriteFile(keysFilePath, JSON.stringify(keys, null, 2));
494
490
 
495
- s.stop(`✅ Successfully pushed ${Object.keys(parsedSecrets).length} secrets to AWS (${targetRegion || 'default region'})!`);
491
+ s.stop(`✅ Successfully pushed ${Object.keys(pushableSecrets).length} secrets to AWS (${targetRegion || 'default region'})!`);
496
492
 
497
493
  const sortedExisting = [...(existingKeys ?? [])].sort();
498
494
  const sortedNew = [...keys].sort();
@@ -511,13 +507,14 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
511
507
  console.log(color.blue(`\n📘 Learn how secrets reach your app: ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/secrets-management.md')}`));
512
508
  await trackSuccess('secrets_pushed', {
513
509
  projectName: resolvedProjectName,
514
- secret_count: Object.keys(parsedSecrets).length,
510
+ secret_count: Object.keys(pushableSecrets).length,
515
511
  keys_changed: false,
516
512
  ecs_restart: false,
517
513
  removed_count: removed.length,
518
- managed_collisions: collisions.length
514
+ managed_collisions: collisions.length,
515
+ skipped_count: skipped.length
519
516
  });
520
- return { keysChanged: false, restarted: false };
517
+ return { keysChanged: false, restarted: false, skipped };
521
518
  }
522
519
  // Automated runs cannot answer prompts: skip the restart (fresh
523
520
  // deploys pick up the values) instead of hanging on confirm.
@@ -526,13 +523,14 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
526
523
  console.log(color.blue(`\n📘 Learn how secrets reach your app: ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/secrets-management.md')}`));
527
524
  await trackSuccess('secrets_pushed', {
528
525
  projectName: resolvedProjectName,
529
- secret_count: Object.keys(parsedSecrets).length,
526
+ secret_count: Object.keys(pushableSecrets).length,
530
527
  keys_changed: false,
531
528
  ecs_restart: false,
532
529
  removed_count: removed.length,
533
- managed_collisions: collisions.length
530
+ managed_collisions: collisions.length,
531
+ skipped_count: skipped.length
534
532
  });
535
- return { keysChanged: false, restarted: false };
533
+ return { keysChanged: false, restarted: false, skipped };
536
534
  }
537
535
  const refused = await refuseIfNonInteractive(opts, {
538
536
  message: `\n✖ secrets push needs approval before triggering the ECS restart.`,
@@ -566,26 +564,28 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
566
564
  }
567
565
  await trackSuccess('secrets_pushed', {
568
566
  projectName: resolvedProjectName,
569
- secret_count: Object.keys(parsedSecrets).length,
567
+ secret_count: Object.keys(pushableSecrets).length,
570
568
  keys_changed: false,
571
569
  ecs_restart: true,
572
570
  removed_count: removed.length,
573
- managed_collisions: collisions.length
571
+ managed_collisions: collisions.length,
572
+ skipped_count: skipped.length
574
573
  });
575
574
  console.log(color.blue(`\n📘 Learn how secrets reach your app: ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/secrets-management.md')}`));
576
- return { keysChanged: false, restarted: true, cluster, service };
575
+ return { keysChanged: false, restarted: true, cluster, service, skipped };
577
576
  }
578
577
  }
579
578
  console.log(color.blue(`\n📘 Learn how secrets reach your app: ${color.underline('https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/secrets-management.md')}`));
580
579
 
581
580
  await trackSuccess('secrets_pushed', {
582
581
  projectName: resolvedProjectName,
583
- secret_count: Object.keys(parsedSecrets).length,
582
+ secret_count: Object.keys(pushableSecrets).length,
584
583
  keys_changed: keysChanged,
585
584
  removed_count: removed.length,
586
- managed_collisions: collisions.length
585
+ managed_collisions: collisions.length,
586
+ skipped_count: skipped.length
587
587
  });
588
- return { keysChanged };
588
+ return { keysChanged, skipped };
589
589
 
590
590
  } catch (error) {
591
591
  return handleSecretsCatch({
@@ -305,6 +305,12 @@ export async function generateTemplates(targetDir, config) {
305
305
  // 3. Configure Compute Commands & Environment Variables
306
306
  let secretsArray = [];
307
307
 
308
+ // Exact container env + static-secret names for the managed_env_names
309
+ // collision-guard list (union over rendered task definitions). Each
310
+ // section below appends what IT renders, so the list tracks the
311
+ // environment by construction instead of parallel knowledge.
312
+ const managedEnvNames = ['PORT'];
313
+
308
314
  // 3.1. Format the ECS Task Command (Heroku Procfile Support)
309
315
  // If a Procfile exists and has a 'web' process, override the Docker CMD
310
316
  if (config.PROCFILE && config.PROCFILE.web) {
@@ -338,6 +344,10 @@ export async function generateTemplates(targetDir, config) {
338
344
  } else {
339
345
  config.WORKER_COMMAND = '';
340
346
  }
347
+ // Worker-only static env joins the union only when worker.tf renders —
348
+ // otherwise a pushed NODE_ENV would trip the app precondition though
349
+ // nothing would collide.
350
+ if (config.WORKER_COMMAND !== '') managedEnvNames.push('NODE_ENV');
341
351
 
342
352
  // 3.2. Inject Managed Database Variables. Static targets have no
343
353
  // compute to connect, so a database is never generated for them (init
@@ -374,6 +384,9 @@ export async function generateTemplates(targetDir, config) {
374
384
 
375
385
  secretsArray.push(`{ "name" : "DB_USER", "valueFrom" : "\${${dbRef}.master_user_secret[0].secret_arn}:username::" }`);
376
386
  secretsArray.push(`{ "name" : "DB_PASSWORD", "valueFrom" : "\${${dbRef}.master_user_secret[0].secret_arn}:password::" }`);
387
+ managedEnvNames.push('DB_HOST', 'DB_PORT', 'DB_NAME');
388
+ if (dbEngine !== 'postgres') managedEnvNames.push('DB_ENGINE');
389
+ managedEnvNames.push('DB_USER', 'DB_PASSWORD');
377
390
  }
378
391
 
379
392
  // VPC-attached functions reach RDS/ElastiCache over the VPC subnets;
@@ -412,6 +425,7 @@ export async function generateTemplates(targetDir, config) {
412
425
  composeWebEnvVars.push(` ${key} = "${String(val).replace(/"/g, '\\"')}"`);
413
426
  } else {
414
427
  composeWebEnvVars.push(`{ "name" : "${key}", "value" : "${String(val).replace(/"/g, '\\"')}" }`);
428
+ managedEnvNames.push(key);
415
429
  }
416
430
  }
417
431
 
@@ -481,6 +495,8 @@ export async function generateTemplates(targetDir, config) {
481
495
  if (config.finalFramework === 'rails') {
482
496
  secretsArray.push(`{ "name" : "RAILS_MASTER_KEY", "valueFrom" : "\${local.secret_arn}:RAILS_MASTER_KEY::" }`);
483
497
 
498
+ if (!isLambda) managedEnvNames.push('RAILS_MASTER_KEY');
499
+
484
500
  let initialMasterKey = "1234567890abcdef1234567890abcdef"; // Dummy fallback for CI/CD
485
501
  const masterKeyPath = path.join(targetDir, 'config', 'master.key');
486
502
 
@@ -501,6 +517,9 @@ export async function generateTemplates(targetDir, config) {
501
517
  console.log(color.yellow('⚠️ RAILS_MASTER_KEY is not auto-injected on Lambda targets: set it as a function environment variable after provisioning.'));
502
518
  }
503
519
  config.TASK_SECRETS = isLambda ? '' : secretsArray.join(',\n ');
520
+ // Collision-guard list for the task-definition precondition. Unused on
521
+ // Lambda/static targets (their templates carry no task definitions).
522
+ config.MANAGED_ENV_NAMES = `[${[...new Set(managedEnvNames)].map((name) => JSON.stringify(name)).join(', ')}]`;
504
523
  config.INITIAL_SECRET_MAP = initialSecretMap;
505
524
 
506
525
  config.SAFE_ALB_NAME = config.PROJECT_NAME.length > 27
@@ -148,6 +148,31 @@ export function readTerraformOidcTrust(cwd = process.cwd()) {
148
148
  return { kind: 'string', value: raw.slice(1, -1) };
149
149
  }
150
150
 
151
+ // Reads container environment + static-secret names from the rendered
152
+ // task definitions (main.tf + worker.tf). Covers every injection path —
153
+ // scaffold DB/compose entries (`{ "name" : "X" }`), addon entries
154
+ // (`{ name = "X" }`), static secrets (`valueFrom`) — because it reads
155
+ // what Terraform will actually submit, not what the maps predict. The
156
+ // dynamic `for key in local.secret_keys` loop carries an unquoted key
157
+ // reference, so it never matches; the shape filter drops resource names
158
+ // (`${...}`, hyphens, paths). Sorted, deduplicated, [] when unreadable.
159
+ export function readRenderedContainerEnvNames(cwd = process.cwd()) {
160
+ const base = resolveCwd({}, cwd);
161
+ const names = new Set();
162
+ const patterns = [/"name"\s*:\s*"([^"]+)"/g, /\bname\s*=\s*"([^"]+)"/g];
163
+ const shape = /^[A-Za-z_][A-Za-z0-9_]*$/;
164
+ for (const file of ['main.tf', 'worker.tf']) {
165
+ const content = readFileSafe(path.join(base, 'terraform', file));
166
+ if (!content) continue;
167
+ for (const pattern of patterns) {
168
+ for (const match of content.matchAll(pattern)) {
169
+ if (shape.test(match[1])) names.add(match[1]);
170
+ }
171
+ }
172
+ }
173
+ return [...names].sort();
174
+ }
175
+
151
176
  // Collision-resistant naming: init mints a `-a1b2c3` suffix per project,
152
177
  // rendered into `grada_resource_suffix` in terraform/main.tf. AWS-name
153
178
  // builders append it to whatever base they assemble (bare or
@@ -28,9 +28,17 @@ provider "aws" {
28
28
 
29
29
  locals {
30
30
  # Safely read the keys generated by the CLI, default to empty list if file doesn't exist.
31
- # toset() collapses hand-duplicated entries: duplicate secrets render the
32
- # same RegisterTaskDefinition 400 as a name collision (BUG-79).
33
- secret_keys = fileexists("${path.module}/secret_keys.json") ? toset(jsondecode(file("${path.module}/secret_keys.json"))) : []
31
+ # distinct() collapses hand-duplicated entries (duplicates render the
32
+ # same RegisterTaskDefinition 400 as a name collision) while preserving
33
+ # file order, so upgrading trees get no task-definition churn (BUG-81).
34
+ secret_keys = fileexists("${path.module}/secret_keys.json") ? distinct(jsondecode(file("${path.module}/secret_keys.json"))) : []
35
+
36
+ # Exact container env + static-secret names (union over app and worker
37
+ # task definitions), maintained by the CLI at scaffold/add time. The
38
+ # app task-definition precondition below intersects it with
39
+ # secret_keys.json so CI fails plan with a named error instead of
40
+ # dying late on the raw ECS 400.
41
+ managed_env_names = {{MANAGED_ENV_NAMES}}
34
42
 
35
43
  # Workspace suffix for PR preview environments (e.g., "-pr-123"). Empty for production.
36
44
  env_suffix = terraform.workspace == "default" ? "" : "-${terraform.workspace}"
@@ -139,6 +147,13 @@ resource "aws_ecs_task_definition" "app" {
139
147
  execution_role_arn = aws_iam_role.execution_role.arn
140
148
  task_role_arn = aws_iam_role.task_role.arn
141
149
 
150
+ lifecycle {
151
+ precondition {
152
+ condition = length(setintersection(toset(local.secret_keys), toset(local.managed_env_names))) == 0
153
+ error_message = "secret_keys.json collides with container environment: ${join(", ", setintersection(toset(local.secret_keys), toset(local.managed_env_names)))}. Remove the key(s) from .env and re-push (push skips them automatically)."
154
+ }
155
+ }
156
+
142
157
  container_definitions = jsonencode([
143
158
  {
144
159
  name = "${local.app_name}-container"
@@ -47,7 +47,10 @@ resource "aws_iam_role" "github_actions" {
47
47
  # CI trust, scoped at scaffold time from --github-repo, the git
48
48
  # remote, or the setup prompt. "repo:*" means any GitHub repo's
49
49
  # Actions can assume this role — re-scope before going live.
50
- "token.actions.githubusercontent.com:sub" : "{{GITHUB_REPO_SUB}}"
50
+ # Scoped trusts render both subject-claim formats: the classic
51
+ # `repo:<owner>/<name>:*` plus the immutable-claim companion
52
+ # `repo:<owner>@*/<name>@*:*` (repos created after 2026-07-15).
53
+ "token.actions.githubusercontent.com:sub" : {{GITHUB_REPO_SUB}}
51
54
  }
52
55
  StringEquals = {
53
56
  "token.actions.githubusercontent.com:aud" : "sts.amazonaws.com"