grada-run 0.41.3 → 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.3",
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,
@@ -9,7 +9,8 @@ import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveComman
9
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
+ import { ADDON_ENV_VARS, ADDON_REGISTRY } from '../utils/addons.js';
13
14
  import { requireManagedTree } from '../utils/terraform-metadata.js';
14
15
  import { truncateSpinnerText } from '../utils/spinner-text.js';
15
16
 
@@ -139,6 +140,80 @@ function resolvePullAuditArgs(projectName, options) {
139
140
  };
140
141
  }
141
142
 
143
+ // Names Grada itself injects into the runtime environment. A pushed vault
144
+ // key sharing one of these names collides in the ECS task definition
145
+ // (RegisterTaskDefinition 400: a secret name must be unique and not shared
146
+ // with any environment variable) or is silently shadowed on Lambda, where
147
+ // the same names arrive as plain environment variables.
148
+ const BASE_MANAGED_ENV = {
149
+ ecs: ['PORT', 'NODE_ENV'],
150
+ lambda: ['PORT', 'AWS_LWA_PORT', 'APP_SECRETS_ARN'],
151
+ };
152
+ const DB_MANAGED_ENV = ['DB_HOST', 'DB_PORT', 'DB_NAME', 'DB_USER', 'DB_PASSWORD'];
153
+
154
+ // Wiring-like names whose local-dev values break production when pushed:
155
+ // the migrate gate trusts a present DATABASE_URL verbatim, so a localhost
156
+ // value pushed from a dev .env would be dialed from inside the ECS task.
157
+ const WIRING_LIKE_NAMES = ['DATABASE_URL', 'DB_URL', 'REDIS_URL', 'VALKEY_URL', 'DB_HOST', 'REDIS_HOST'];
158
+ const NON_PROD_VALUE_PATTERN = /localhost|127\.0\.0\.1|0\.0\.0\.0|example\.(com|org|net)/i;
159
+
160
+ // Managed-name set for this tree: the target base set, plus DB names when
161
+ // a database file exists, plus each enabled addon's injected names
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.
165
+ export async function getManagedEnvNames(cwd = process.cwd(), target = 'ecs') {
166
+ const names = new Set(BASE_MANAGED_ENV[target] || BASE_MANAGED_ENV.ecs);
167
+ let tfFiles = [];
168
+ try {
169
+ tfFiles = await fs.readdir(path.join(cwd, 'terraform'));
170
+ } catch {
171
+ return [...names].sort();
172
+ }
173
+ const dbFile = tfFiles.find((file) => file.startsWith('database') && file.endsWith('.tf'));
174
+ if (dbFile) {
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
+ }
187
+ }
188
+ for (const [capability, entry] of Object.entries(ADDON_REGISTRY)) {
189
+ const envEntries = ADDON_ENV_VARS[capability];
190
+ if (!envEntries || !entry.file || !tfFiles.includes(entry.file)) continue;
191
+ for (const { name } of envEntries) names.add(name);
192
+ }
193
+ for (const name of readRenderedContainerEnvNames(cwd)) names.add(name);
194
+ return [...names].sort();
195
+ }
196
+
197
+ // Values that look like local-dev placeholders on wiring-like names.
198
+ // Returns [{ key, indicator }] — the matched indicator only, never the
199
+ // value itself, so warnings stay safe to print and count in telemetry.
200
+ export function findNonProdWiring(parsedSecrets = {}) {
201
+ const hits = [];
202
+ for (const [key, value] of Object.entries(parsedSecrets)) {
203
+ if (!WIRING_LIKE_NAMES.includes(key)) continue;
204
+ const match = NON_PROD_VALUE_PATTERN.exec(String(value ?? ''));
205
+ if (match) hits.push({ key, indicator: match[0] });
206
+ }
207
+ return hits;
208
+ }
209
+
210
+ // Names a few keys for confirm prompts without blowing the density
211
+ // budget: first 8 inline, remainder as a count.
212
+ function summarizeKeys(keys) {
213
+ if (keys.length <= 8) return keys.join(', ');
214
+ return `${keys.slice(0, 8).join(', ')} (+${keys.length - 8} more)`;
215
+ }
216
+
142
217
  export function diffSecretsEnvs(localSecrets = {}, remoteSecrets = {}) {
143
218
  // Own-property checks: `in` matches inherited names (toString,
144
219
  // __proto__), which would misclassify real vault keys.
@@ -301,6 +376,41 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
301
376
  return;
302
377
  }
303
378
 
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
383
+ // any AWS or keys-file write. The spinner stops once for all
384
+ // pre-write output and restarts when the push proceeds.
385
+ const pushTarget = readTerraformComputeTarget(process.cwd());
386
+ const managedNames = await getManagedEnvNames(process.cwd(), pushTarget);
387
+ const collisions = Object.keys(parsedSecrets).filter((key) => managedNames.includes(key));
388
+ const wiringHits = findNonProdWiring(parsedSecrets);
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');
397
+ if (needsPreWriteOutput) s.stop('Pre-flight checks done.');
398
+ for (const { key, indicator } of wiringHits) {
399
+ console.log(color.yellow(`⚠️ Warning: "${key}" looks like a local-dev value (contains "${indicator}") — pushed as-is, production wiring would dial it.`));
400
+ }
401
+ if (collisions.length > 0 && pushTarget === 'lambda') {
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.`));
403
+ }
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;
411
+ }
412
+ if (needsPreWriteOutput) s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
413
+
304
414
  // 2. Resolve the region (explicit flag > env > backend.tf > default)
305
415
  // so the AWS client is never constructed without one.
306
416
  const targetRegion = await resolveSecretsRegion(opts);
@@ -331,20 +441,54 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
331
441
  }
332
442
  }
333
443
 
444
+ // BUG-80: push is full-replace, so vault keys absent from .env are
445
+ // deleted by the update below. Name every victim before writing;
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.
450
+ const removed = (existingKeys ?? []).filter((key) => !Object.hasOwn(parsedSecrets, key));
451
+ if (removed.length > 0) {
452
+ s.stop('Pre-flight checks done.');
453
+ console.log(color.yellow(`⚠️ ${removed.length} vault ${removed.length === 1 ? 'key' : 'keys'} not in ${resolvedFilePath} will be deleted:`));
454
+ for (const key of removed) console.log(color.red(`- ${key} (removed from the vault)`));
455
+ const headlessPush = opts.isHeadless || opts.headless || process.env.CI;
456
+ const removalApproved = [opts.autoApprove, opts.yes].some((flag) => flag === true || flag === 'true');
457
+ if (!headlessPush && !removalApproved) {
458
+ const refusedRemoval = await refuseIfNonInteractive(opts, {
459
+ message: `\n✖ secrets push needs approval before deleting ${removed.length} vault ${removed.length === 1 ? 'key' : 'keys'} missing from ${resolvedFilePath}.`,
460
+ hint: ' Re-run with --headless to delete non-interactively (removals are named above), or run interactively to decide.\n',
461
+ event: 'secrets_pushed',
462
+ telemetry: { projectName: resolvedProjectName, removed_count: removed.length },
463
+ errorCode: 'SECRETS_NON_INTERACTIVE',
464
+ });
465
+ if (refusedRemoval) return refusedRemoval;
466
+ const proceed = await confirm({
467
+ message: `Delete ${summarizeKeys(removed)} from the vault?`,
468
+ initialValue: false,
469
+ });
470
+ if (isCancel(proceed) || proceed !== true) {
471
+ console.log(color.dim('Secrets push cancelled. The vault and secret_keys.json are unchanged.'));
472
+ return;
473
+ }
474
+ }
475
+ s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
476
+ }
477
+
334
478
  // 5. Update the secret string in AWS
335
479
  const command = new UpdateSecretCommand({
336
480
  SecretId: `${secretVaultId(resolvedProjectName)}`,
337
- SecretString: JSON.stringify(parsedSecrets),
481
+ SecretString: JSON.stringify(pushableSecrets),
338
482
  });
339
483
 
340
484
  await client.send(command);
341
485
 
342
- const keys = Object.keys(parsedSecrets);
486
+ const keys = Object.keys(pushableSecrets);
343
487
  const keysFilePath = path.join(process.cwd(), 'terraform', 'secret_keys.json');
344
488
 
345
489
  await atomicWriteFile(keysFilePath, JSON.stringify(keys, null, 2));
346
490
 
347
- 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'})!`);
348
492
 
349
493
  const sortedExisting = [...(existingKeys ?? [])].sort();
350
494
  const sortedNew = [...keys].sort();
@@ -363,11 +507,14 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
363
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')}`));
364
508
  await trackSuccess('secrets_pushed', {
365
509
  projectName: resolvedProjectName,
366
- secret_count: Object.keys(parsedSecrets).length,
510
+ secret_count: Object.keys(pushableSecrets).length,
367
511
  keys_changed: false,
368
- ecs_restart: false
512
+ ecs_restart: false,
513
+ removed_count: removed.length,
514
+ managed_collisions: collisions.length,
515
+ skipped_count: skipped.length
369
516
  });
370
- return { keysChanged: false, restarted: false };
517
+ return { keysChanged: false, restarted: false, skipped };
371
518
  }
372
519
  // Automated runs cannot answer prompts: skip the restart (fresh
373
520
  // deploys pick up the values) instead of hanging on confirm.
@@ -376,11 +523,14 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
376
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')}`));
377
524
  await trackSuccess('secrets_pushed', {
378
525
  projectName: resolvedProjectName,
379
- secret_count: Object.keys(parsedSecrets).length,
526
+ secret_count: Object.keys(pushableSecrets).length,
380
527
  keys_changed: false,
381
- ecs_restart: false
528
+ ecs_restart: false,
529
+ removed_count: removed.length,
530
+ managed_collisions: collisions.length,
531
+ skipped_count: skipped.length
382
532
  });
383
- return { keysChanged: false, restarted: false };
533
+ return { keysChanged: false, restarted: false, skipped };
384
534
  }
385
535
  const refused = await refuseIfNonInteractive(opts, {
386
536
  message: `\n✖ secrets push needs approval before triggering the ECS restart.`,
@@ -414,22 +564,28 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
414
564
  }
415
565
  await trackSuccess('secrets_pushed', {
416
566
  projectName: resolvedProjectName,
417
- secret_count: Object.keys(parsedSecrets).length,
567
+ secret_count: Object.keys(pushableSecrets).length,
418
568
  keys_changed: false,
419
- ecs_restart: true
569
+ ecs_restart: true,
570
+ removed_count: removed.length,
571
+ managed_collisions: collisions.length,
572
+ skipped_count: skipped.length
420
573
  });
421
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')}`));
422
- return { keysChanged: false, restarted: true, cluster, service };
575
+ return { keysChanged: false, restarted: true, cluster, service, skipped };
423
576
  }
424
577
  }
425
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')}`));
426
579
 
427
580
  await trackSuccess('secrets_pushed', {
428
581
  projectName: resolvedProjectName,
429
- secret_count: Object.keys(parsedSecrets).length,
430
- keys_changed: keysChanged
582
+ secret_count: Object.keys(pushableSecrets).length,
583
+ keys_changed: keysChanged,
584
+ removed_count: removed.length,
585
+ managed_collisions: collisions.length,
586
+ skipped_count: skipped.length
431
587
  });
432
- return { keysChanged };
588
+ return { keysChanged, skipped };
433
589
 
434
590
  } catch (error) {
435
591
  return handleSecretsCatch({
@@ -660,15 +816,30 @@ async function auditSecretsMain(envFilePath, projectName, options = {}) {
660
816
  }
661
817
  }
662
818
 
819
+ // BUG-79: flag both limbs — keys colliding with Grada-managed
820
+ // environment names (fatal on ECS, shadowing on Lambda) and
821
+ // wiring-like values that look like local-dev placeholders.
822
+ const auditTarget = readTerraformComputeTarget(process.cwd());
823
+ const auditManaged = await getManagedEnvNames(process.cwd(), auditTarget);
824
+ const auditedKeys = [...new Set([...Object.keys(localSecrets), ...Object.keys(remoteSecrets)])];
825
+ const collisions = auditedKeys.filter((key) => auditManaged.includes(key));
826
+ for (const key of collisions) {
827
+ console.log(color.red(`! ${key} (collides with a Grada-managed environment name)`));
828
+ }
829
+ for (const { key, indicator } of findNonProdWiring(remoteSecrets)) {
830
+ console.log(color.yellow(`⚠️ ${key} looks like a local-dev value (contains "${indicator}") — production wiring would dial it.`));
831
+ }
832
+
663
833
  outro(`Audit complete. ${driftCount} drifted variable(s) found.`);
664
834
 
665
835
  trackEvent('secrets_audit', {
666
836
  projectName: resolvedProjectName,
667
837
  driftCount,
838
+ collision_count: collisions.length,
668
839
  });
669
840
  await flushTelemetry();
670
841
 
671
- return { missingLocally, mismatched, untrackedLocally, driftCount };
842
+ return { missingLocally, mismatched, untrackedLocally, driftCount, collisions };
672
843
  } catch (error) {
673
844
  return handleSecretsCatch({
674
845
  error,
@@ -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
@@ -27,8 +27,18 @@ provider "aws" {
27
27
  }
28
28
 
29
29
  locals {
30
- # Safely read the keys generated by the CLI, default to empty list if file doesn't exist
31
- secret_keys = fileexists("${path.module}/secret_keys.json") ? jsondecode(file("${path.module}/secret_keys.json")) : []
30
+ # Safely read the keys generated by the CLI, default to empty list if file doesn't exist.
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}}
32
42
 
33
43
  # Workspace suffix for PR preview environments (e.g., "-pr-123"). Empty for production.
34
44
  env_suffix = terraform.workspace == "default" ? "" : "-${terraform.workspace}"
@@ -137,6 +147,13 @@ resource "aws_ecs_task_definition" "app" {
137
147
  execution_role_arn = aws_iam_role.execution_role.arn
138
148
  task_role_arn = aws_iam_role.task_role.arn
139
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
+
140
157
  container_definitions = jsonencode([
141
158
  {
142
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"