@grada-run/grada 0.41.3 → 0.41.4
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 +1 -1
- package/src/commands/secrets.js +177 -6
- package/templates/terraform/main.tf +4 -2
package/package.json
CHANGED
package/src/commands/secrets.js
CHANGED
|
@@ -6,10 +6,11 @@ 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, refuseIfNonInteractive } from '../utils/command.js';
|
|
9
|
+
import { failCommand, isProgrammaticCall, refuseIfNonInteractive } from '../utils/command.js';
|
|
10
10
|
import { atomicWriteFile } from '../utils/atomic-write.js';
|
|
11
11
|
import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
|
|
12
12
|
import { readTerraformComputeTarget, guardComputeTarget, readResourceSuffix } 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,65 @@ 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_ENGINE', '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/). Sorted for stable output.
|
|
163
|
+
export async function getManagedEnvNames(cwd = process.cwd(), target = 'ecs') {
|
|
164
|
+
const names = new Set(BASE_MANAGED_ENV[target] || BASE_MANAGED_ENV.ecs);
|
|
165
|
+
let tfFiles = [];
|
|
166
|
+
try {
|
|
167
|
+
tfFiles = await fs.readdir(path.join(cwd, 'terraform'));
|
|
168
|
+
} catch {
|
|
169
|
+
return [...names].sort();
|
|
170
|
+
}
|
|
171
|
+
if (tfFiles.some((file) => file.startsWith('database') && file.endsWith('.tf'))) {
|
|
172
|
+
for (const name of DB_MANAGED_ENV) names.add(name);
|
|
173
|
+
}
|
|
174
|
+
for (const [capability, entry] of Object.entries(ADDON_REGISTRY)) {
|
|
175
|
+
const envEntries = ADDON_ENV_VARS[capability];
|
|
176
|
+
if (!envEntries || !entry.file || !tfFiles.includes(entry.file)) continue;
|
|
177
|
+
for (const { name } of envEntries) names.add(name);
|
|
178
|
+
}
|
|
179
|
+
return [...names].sort();
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Values that look like local-dev placeholders on wiring-like names.
|
|
183
|
+
// Returns [{ key, indicator }] — the matched indicator only, never the
|
|
184
|
+
// value itself, so warnings stay safe to print and count in telemetry.
|
|
185
|
+
export function findNonProdWiring(parsedSecrets = {}) {
|
|
186
|
+
const hits = [];
|
|
187
|
+
for (const [key, value] of Object.entries(parsedSecrets)) {
|
|
188
|
+
if (!WIRING_LIKE_NAMES.includes(key)) continue;
|
|
189
|
+
const match = NON_PROD_VALUE_PATTERN.exec(String(value ?? ''));
|
|
190
|
+
if (match) hits.push({ key, indicator: match[0] });
|
|
191
|
+
}
|
|
192
|
+
return hits;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Names a few keys for confirm prompts without blowing the density
|
|
196
|
+
// budget: first 8 inline, remainder as a count.
|
|
197
|
+
function summarizeKeys(keys) {
|
|
198
|
+
if (keys.length <= 8) return keys.join(', ');
|
|
199
|
+
return `${keys.slice(0, 8).join(', ')} (+${keys.length - 8} more)`;
|
|
200
|
+
}
|
|
201
|
+
|
|
142
202
|
export function diffSecretsEnvs(localSecrets = {}, remoteSecrets = {}) {
|
|
143
203
|
// Own-property checks: `in` matches inherited names (toString,
|
|
144
204
|
// __proto__), which would misclassify real vault keys.
|
|
@@ -301,6 +361,63 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
|
|
|
301
361
|
return;
|
|
302
362
|
}
|
|
303
363
|
|
|
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
|
|
367
|
+
// any AWS or keys-file write. The spinner stops once for all
|
|
368
|
+
// pre-write output and restarts when the push proceeds.
|
|
369
|
+
const pushTarget = readTerraformComputeTarget(process.cwd());
|
|
370
|
+
const managedNames = await getManagedEnvNames(process.cwd(), pushTarget);
|
|
371
|
+
const collisions = Object.keys(parsedSecrets).filter((key) => managedNames.includes(key));
|
|
372
|
+
const wiringHits = findNonProdWiring(parsedSecrets);
|
|
373
|
+
const needsPreWriteOutput = collisions.length > 0 || wiringHits.length > 0;
|
|
374
|
+
if (needsPreWriteOutput) s.stop('Pre-flight checks done.');
|
|
375
|
+
for (const { key, indicator } of wiringHits) {
|
|
376
|
+
console.log(color.yellow(`⚠️ Warning: "${key}" looks like a local-dev value (contains "${indicator}") — pushed as-is, production wiring would dial it.`));
|
|
377
|
+
}
|
|
378
|
+
if (collisions.length > 0 && pushTarget === 'lambda') {
|
|
379
|
+
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
|
+
}
|
|
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
|
+
}
|
|
418
|
+
}
|
|
419
|
+
if (needsPreWriteOutput) s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
|
|
420
|
+
|
|
304
421
|
// 2. Resolve the region (explicit flag > env > backend.tf > default)
|
|
305
422
|
// so the AWS client is never constructed without one.
|
|
306
423
|
const targetRegion = await resolveSecretsRegion(opts);
|
|
@@ -331,6 +448,37 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
|
|
|
331
448
|
}
|
|
332
449
|
}
|
|
333
450
|
|
|
451
|
+
// BUG-80: push is full-replace, so vault keys absent from .env are
|
|
452
|
+
// deleted by the update below. Name every victim before writing;
|
|
453
|
+
// interactive runs confirm first, headless proceeds loudly.
|
|
454
|
+
const removed = (existingKeys ?? []).filter((key) => !Object.hasOwn(parsedSecrets, key));
|
|
455
|
+
if (removed.length > 0) {
|
|
456
|
+
s.stop('Pre-flight checks done.');
|
|
457
|
+
console.log(color.yellow(`⚠️ ${removed.length} vault ${removed.length === 1 ? 'key' : 'keys'} not in ${resolvedFilePath} will be deleted:`));
|
|
458
|
+
for (const key of removed) console.log(color.red(`- ${key} (removed from the vault)`));
|
|
459
|
+
const headlessPush = opts.isHeadless || opts.headless || process.env.CI;
|
|
460
|
+
const removalApproved = [opts.autoApprove, opts.yes].some((flag) => flag === true || flag === 'true');
|
|
461
|
+
if (!headlessPush && !removalApproved) {
|
|
462
|
+
const refusedRemoval = await refuseIfNonInteractive(opts, {
|
|
463
|
+
message: `\n✖ secrets push needs approval before deleting ${removed.length} vault ${removed.length === 1 ? 'key' : 'keys'} missing from ${resolvedFilePath}.`,
|
|
464
|
+
hint: ' Re-run with --headless to delete non-interactively (removals are named above), or run interactively to decide.\n',
|
|
465
|
+
event: 'secrets_pushed',
|
|
466
|
+
telemetry: { projectName: resolvedProjectName, removed_count: removed.length },
|
|
467
|
+
errorCode: 'SECRETS_NON_INTERACTIVE',
|
|
468
|
+
});
|
|
469
|
+
if (refusedRemoval) return refusedRemoval;
|
|
470
|
+
const proceed = await confirm({
|
|
471
|
+
message: `Delete ${summarizeKeys(removed)} from the vault?`,
|
|
472
|
+
initialValue: false,
|
|
473
|
+
});
|
|
474
|
+
if (isCancel(proceed) || proceed !== true) {
|
|
475
|
+
console.log(color.dim('Secrets push cancelled. The vault and secret_keys.json are unchanged.'));
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`));
|
|
480
|
+
}
|
|
481
|
+
|
|
334
482
|
// 5. Update the secret string in AWS
|
|
335
483
|
const command = new UpdateSecretCommand({
|
|
336
484
|
SecretId: `${secretVaultId(resolvedProjectName)}`,
|
|
@@ -365,7 +513,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
|
|
|
365
513
|
projectName: resolvedProjectName,
|
|
366
514
|
secret_count: Object.keys(parsedSecrets).length,
|
|
367
515
|
keys_changed: false,
|
|
368
|
-
ecs_restart: false
|
|
516
|
+
ecs_restart: false,
|
|
517
|
+
removed_count: removed.length,
|
|
518
|
+
managed_collisions: collisions.length
|
|
369
519
|
});
|
|
370
520
|
return { keysChanged: false, restarted: false };
|
|
371
521
|
}
|
|
@@ -378,7 +528,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
|
|
|
378
528
|
projectName: resolvedProjectName,
|
|
379
529
|
secret_count: Object.keys(parsedSecrets).length,
|
|
380
530
|
keys_changed: false,
|
|
381
|
-
ecs_restart: false
|
|
531
|
+
ecs_restart: false,
|
|
532
|
+
removed_count: removed.length,
|
|
533
|
+
managed_collisions: collisions.length
|
|
382
534
|
});
|
|
383
535
|
return { keysChanged: false, restarted: false };
|
|
384
536
|
}
|
|
@@ -416,7 +568,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
|
|
|
416
568
|
projectName: resolvedProjectName,
|
|
417
569
|
secret_count: Object.keys(parsedSecrets).length,
|
|
418
570
|
keys_changed: false,
|
|
419
|
-
ecs_restart: true
|
|
571
|
+
ecs_restart: true,
|
|
572
|
+
removed_count: removed.length,
|
|
573
|
+
managed_collisions: collisions.length
|
|
420
574
|
});
|
|
421
575
|
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
576
|
return { keysChanged: false, restarted: true, cluster, service };
|
|
@@ -427,7 +581,9 @@ async function pushSecretsMain(envFilePath, projectName, options = {}) {
|
|
|
427
581
|
await trackSuccess('secrets_pushed', {
|
|
428
582
|
projectName: resolvedProjectName,
|
|
429
583
|
secret_count: Object.keys(parsedSecrets).length,
|
|
430
|
-
keys_changed: keysChanged
|
|
584
|
+
keys_changed: keysChanged,
|
|
585
|
+
removed_count: removed.length,
|
|
586
|
+
managed_collisions: collisions.length
|
|
431
587
|
});
|
|
432
588
|
return { keysChanged };
|
|
433
589
|
|
|
@@ -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,
|
|
@@ -27,8 +27,10 @@ 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
|
-
|
|
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"))) : []
|
|
32
34
|
|
|
33
35
|
# Workspace suffix for PR preview environments (e.g., "-pr-123"). Empty for production.
|
|
34
36
|
env_suffix = terraform.workspace == "default" ? "" : "-${terraform.workspace}"
|