import { SecretsManagerClient, UpdateSecretCommand, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager"; import { ECSClient, UpdateServiceCommand } from "@aws-sdk/client-ecs"; import dotenv from "dotenv"; import fs from 'fs/promises'; import { spinner, confirm, outro, isCancel } from '@clack/prompts'; import color from 'picocolors'; import path from 'path'; import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js'; import { failCommand, refuseIfNonInteractive } from '../utils/command.js'; import { atomicWriteFile } from '../utils/atomic-write.js'; import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js'; import { readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, readRenderedContainerEnvNames, readTerraformProjectName } from '../utils/resolvers.js'; import { ADDON_ENV_VARS, ADDON_REGISTRY } from '../utils/addons.js'; import { requireManagedTree } from '../utils/terraform-metadata.js'; import { truncateSpinnerText } from '../utils/spinner-text.js'; import { withProjectLock } from '../utils/file-lock.js'; // Static sites provision no secrets vault, so push/pull/audit would fail // obscurely against a Secrets Manager secret that can never exist. One // shared guard keeps the three entry points consistent. function secretsTargetGuard(subcommand) { return guardComputeTarget({ cwd: process.cwd(), command: `secrets ${subcommand}`, supported: ['ecs', 'lambda'], hint: 'Static sites provision no secrets vault — static sites needing secrets need an API backend.', }); } function failUnsupportedTarget(guard, event, projectName) { return failCommand({ message: guard.message, hint: guard.hint, event, telemetry: { projectName }, errorCode: guard.errorCode, reason: guard.reason, }); } // Ejected trees are user-owned: push/pull/audit refuse unless --force. // Returns the refusal result, or null when the caller may proceed. async function secretsManagedTreeGuard(subcommand, event, projectName, options = {}) { const managedTree = await requireManagedTree({ cwd: process.cwd(), command: `secrets ${subcommand}`, options, event, projectName: resolveSecretsProject(projectName), }); if (!managedTree.proceed) return managedTree.result; return null; } function resolveSecretsFile(envFilePath) { let resolvedFilePath = (typeof envFilePath === 'string' && envFilePath.trim()) ? envFilePath.trim() : '.env'; if (!resolvedFilePath.includes('.env') && !resolvedFilePath.includes('txt') && !resolvedFilePath.includes('json')) { console.log(color.yellow(`⚠️ Warning: "${resolvedFilePath}" does not look like a standard secrets file. Defaulting to ".env"`)); resolvedFilePath = '.env'; } return resolvedFilePath; } function resolveSecretsProject(projectName) { // The terraform project name (what provisioned the vault) // outranks the directory basename — a renamed directory otherwise // silently aims at a missing vault. if (typeof projectName === 'string' && projectName.trim()) return projectName.trim(); return readTerraformProjectName(process.cwd()) || path.basename(process.cwd()); } // Vault identifiers carry the tree's resource suffix (matching the // Terraform secret name); telemetry keeps the bare project name. function secretVaultId(projectName) { return `${projectName}${readResourceSuffix()}-secrets`; } export async function resolveSecretsRegion(options = {}) { const fromOptions = typeof options.region === 'string' ? options.region.trim() : ''; if (fromOptions) return fromOptions; for (const key of ['AWS_REGION', 'AWS_DEFAULT_REGION']) { const value = typeof process.env[key] === 'string' ? process.env[key].trim() : ''; if (value) return value; } try { const backendTfPath = path.join(process.cwd(), 'terraform', 'backend.tf'); const backendTfContent = await fs.readFile(backendTfPath, 'utf-8'); // Scan line-wise skipping comments — the old whole-file // regex resolved commented-out regions (or legacy lines) as live. for (const rawLine of backendTfContent.split('\n')) { const line = rawLine.trim(); if (line === '' || line.startsWith('#')) continue; const regionMatch = line.match(/region\s*=\s*"([^"]+)"/); if (regionMatch && !regionMatch[1].includes('{{')) { return regionMatch[1]; } } } catch { // Fall through to the product default region if the file is missing or unreadable } return 'us-east-2'; } // Quote one value so `dotenv.parse` reads it back byte-identical. Plain // values keep the legacy double-quote style; values holding a double // quote switch to a literal style (single or backtick) because dotenv // keeps `\"` verbatim instead of unescaping it. Returns null when no // style round-trips — the caller must refuse to write rather than // corrupt the file. export function quoteEnvValue(value) { const text = String(value ?? ''); const hasSingle = text.includes("'"); const hasDouble = text.includes('"'); const hasBacktick = text.includes('`'); if (hasDouble) { if (hasSingle && hasBacktick) return null; if (hasSingle) return `\`${text}\``; return `'${text}'`; } if (hasSingle) { // Literal backslash-n/r sequences are indistinguishable from escaped // newlines inside double quotes, so they force the literal styles. if (/\\[nr]/.test(text)) return hasBacktick ? null : `\`${text}\``; return `"${text.replace(/\n/g, '\\n').replace(/\r/g, '\\r')}"`; } if (text.includes('\\')) return `'${text}'`; return `"${text.replace(/\n/g, '\\n').replace(/\r/g, '\\r')}"`; } function serializeEnv(orderedKeys, values) { return orderedKeys.map((key) => `${key}=${quoteEnvValue(values[key])}`).join('\n') + '\n'; } function normalizeSecretsArgs(projectName, options) { // Supports (file, project, opts) and (file, opts) call shapes. if (projectName !== null && typeof projectName === 'object' && !Array.isArray(projectName)) { return { projectName: undefined, options: projectName }; } return { projectName, options: options && typeof options === 'object' ? options : {} }; } function resolvePullAuditArgs(projectName, options) { const normalized = normalizeSecretsArgs(projectName, options); return { resolvedProjectName: resolveSecretsProject(normalized.projectName), opts: normalized.options, }; } // Names Grada itself injects into the runtime environment. A pushed vault // key sharing one of these names collides in the ECS task definition // (RegisterTaskDefinition 400: a secret name must be unique and not shared // with any environment variable) or is silently shadowed on Lambda, where // the same names arrive as plain environment variables. const BASE_MANAGED_ENV = { ecs: ['PORT', 'NODE_ENV'], lambda: ['PORT', 'AWS_LWA_PORT', 'APP_SECRETS_ARN'], }; const DB_MANAGED_ENV = ['DB_HOST', 'DB_PORT', 'DB_NAME', 'DB_USER', 'DB_PASSWORD']; // Wiring-like names whose local-dev values break production when pushed: // the migrate gate trusts a present DATABASE_URL verbatim, so a localhost // value pushed from a dev .env would be dialed from inside the ECS task. const WIRING_LIKE_NAMES = ['DATABASE_URL', 'DB_URL', 'REDIS_URL', 'VALKEY_URL', 'DB_HOST', 'REDIS_HOST']; const NON_PROD_VALUE_PATTERN = /localhost|127\.0\.0\.1|0\.0\.0\.0|example\.(com|org|net)/i; // Managed-name set for this tree: the target base set, plus DB names when // a database file exists, plus each enabled addon's injected names // (capability file present under terraform/), plus every name in the // RENDERED task definitions (covers compose-injected and hand-added env // the maps cannot predict). Sorted for stable output. export async function getManagedEnvNames(cwd = process.cwd(), target = 'ecs') { const names = new Set(BASE_MANAGED_ENV[target] || BASE_MANAGED_ENV.ecs); let tfFiles = []; try { tfFiles = await fs.readdir(path.join(cwd, 'terraform')); } catch { return [...names].sort(); } // NODE_ENV is injected only when the worker renders (the generator // scopes it to worker trees): on workerless trees it is a legitimate // custom key and must not auto-skip. Unreadable dirs keep // the base set above (fail-closed; the TF precondition backstops // real collisions there). if (!tfFiles.includes('worker.tf')) names.delete('NODE_ENV'); const dbFiles = tfFiles.filter((file) => file.startsWith('database') && file.endsWith('.tf')); if (dbFiles.length > 0) { for (const name of DB_MANAGED_ENV) names.add(name); // DB_ENGINE is rendered only for non-postgres engines: including // it blindly would auto-skip a legitimate custom key on postgres // trees with a false "injected by Grada" notice. Every database // file is sniffed — a stale database.tf sorting before the live // database-mysql.tf must not hide the engine. Unparseable // files exclude it — the preflights still catch real collisions. try { const contents = await Promise.all( dbFiles.map((dbFile) => fs.readFile(path.join(cwd, 'terraform', dbFile), 'utf-8')) ); const engines = contents.map((dbContent) => /engine\s*=\s*"([^"]+)"/.exec(dbContent)?.[1]); if (engines.some((engine) => engine && engine !== 'postgres')) names.add('DB_ENGINE'); } catch { // Fall through with the base DB set. } } for (const [capability, entry] of Object.entries(ADDON_REGISTRY)) { const envEntries = ADDON_ENV_VARS[capability]; if (!envEntries || !entry.file || !tfFiles.includes(entry.file)) continue; for (const { name } of envEntries) names.add(name); } for (const name of readRenderedContainerEnvNames(cwd)) names.add(name); return [...names].sort(); } // Values that look like local-dev placeholders on wiring-like names. // Returns [{ key, indicator }] — the matched indicator only, never the // value itself, so warnings stay safe to print and count in telemetry. export function findNonProdWiring(parsedSecrets = {}) { const hits = []; for (const [key, value] of Object.entries(parsedSecrets)) { if (!WIRING_LIKE_NAMES.includes(key)) continue; const match = NON_PROD_VALUE_PATTERN.exec(String(value ?? '')); if (match) hits.push({ key, indicator: match[0] }); } return hits; } // Names a few keys for confirm prompts without blowing the density // budget: first 8 inline, remainder as a count. function summarizeKeys(keys) { if (keys.length <= 8) return keys.join(', '); return `${keys.slice(0, 8).join(', ')} (+${keys.length - 8} more)`; } export function diffSecretsEnvs(localSecrets = {}, remoteSecrets = {}) { // Own-property checks: `in` matches inherited names (toString, // __proto__), which would misclassify real vault keys. const missingLocally = Object.keys(remoteSecrets).filter((k) => !Object.hasOwn(localSecrets, k)); const untrackedLocally = Object.keys(localSecrets).filter((k) => !Object.hasOwn(remoteSecrets, k)); const mismatched = Object.keys(remoteSecrets).filter( (k) => Object.hasOwn(localSecrets, k) && String(localSecrets[k]) !== String(remoteSecrets[k]) ); return { missingLocally, mismatched, untrackedLocally }; } // Names the shape of a non-object vault payload for refusal messages. function vaultPayloadShape(parsed) { if (parsed === null) return 'null'; if (Array.isArray(parsed)) return 'array'; return typeof parsed; } // Validates a GetSecretValue response into the managed JSON object. // Refuses binary payloads (They read as "empty" and a push // would full-replace them away without the removal confirm) and // non-object/non-string payloads (Phantom `0,1` removals, // garbage pull keys, TypeError crashes). A response carrying neither // field means an empty/new vault — live AWS never returns that shape // for a valued secret. function vaultPayloadObject(resp, secretId) { if (resp.SecretBinary != null) { const binaryError = new Error(`Refusing to operate on "${secretId}": the vault payload is binary, not the JSON object secrets commands manage. Migrate it to a JSON string payload first.`); binaryError.code = 'REMOTE_SECRET_BINARY'; throw binaryError; } if (resp.SecretString == null) return {}; let parsed; try { parsed = JSON.parse(resp.SecretString); } catch { const jsonError = new Error('Remote secret payload is not valid JSON.'); jsonError.code = 'REMOTE_SECRET_MALFORMED'; throw jsonError; } const valuesOk = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) && Object.values(parsed).every((value) => typeof value === 'string'); if (!valuesOk) { const shapeError = new Error(`Remote secret payload must be a JSON object of string values, found ${vaultPayloadShape(parsed)}.`); shapeError.code = 'REMOTE_SECRET_MALFORMED'; throw shapeError; } return parsed; } // Lenient key-attempt extractor for drop accounting: what key did this // line TRY to define? Calibrated against the real dotenv parse — a line // is dropped only when its attempted key is absent from it. const ATTEMPTED_KEY_RE = /^\s*([^=:#\s][^=:]*?)\s*[=:]/; // Finds .env input lines dotenv silently dropped plus duplicate keys //. Multiline double-quoted values span lines — continuation // lines are value text, not dropped lines. Pure and unit-tested via // push output. function analyzeEnvLines(envContent, parsedSecrets) { const dropped = []; const seen = new Map(); const lines = String(envContent ?? '').split('\n'); let continuation = false; lines.forEach((rawLine, index) => { const line = rawLine.replace(/\r$/, ''); const wasContinuation = continuation; // Track unescaped double quotes across lines (backslash escapes). let open = continuation; for (let i = 0; i < line.length; i += 1) { if (line[i] === '\\') { i += 1; } else if (line[i] === '"') { open = !open; } } continuation = open; if (wasContinuation) return; const trimmed = line.trim(); if (trimmed === '' || trimmed.startsWith('#')) return; const effective = line.replace(/^\s*export\s+/, ''); const match = ATTEMPTED_KEY_RE.exec(effective); if (!match) { dropped.push({ line: index + 1, content: trimmed }); return; } const attempted = match[1].trim(); if (!Object.hasOwn(parsedSecrets, attempted)) { dropped.push({ line: index + 1, content: trimmed }); return; } if (!seen.has(attempted)) seen.set(attempted, []); seen.get(attempted).push(index + 1); }); const duplicates = []; for (const [key, dupLines] of seen) { if (dupLines.length > 1) duplicates.push({ key, lines: dupLines }); } return { dropped, duplicates }; } // Shared failure tail for push/pull/audit: identical telemetry stamps, // not-found guidance, auth branch, and spinner/exit routing, so the // three subcommands cannot drift apart again. async function handleSecretsCatch({ error, event, verb, s, opts, projectName, notFoundMessage, notFoundGuidance, spinnerStopped = false, stackTraceOnTypeError = false, postVaultStep = null, }) { await trackFailure(event, { projectName, error_code: error.code || error.name || 'UNKNOWN', error_message: error.message, ...(stackTraceOnTypeError ? { stack_trace: error.name === 'TypeError' ? error.stack : undefined } : {}), }); if (error.name === 'ResourceNotFoundException') { s.stop(color.red(notFoundMessage)); console.log(color.yellow('\n💡 Next Step:')); for (const line of notFoundGuidance) console.log(line); } else if (handleAuthErrorBranch(error, s, opts)) { return; } // Failures after the vault write (keys file, ECS restart) // must report the vault as updated with the recovery step — a bare // "Failed to push" lies about what succeeded. const postVaultHints = { 'secret_keys.json write': ' Re-run the push to regenerate terraform/secret_keys.json — the vault already holds the new values.\n', 'ECS restart': ' Re-run the push to retry the restart (or trigger it by hand: aws ecs update-service --force-new-deployment) — the vault already holds the new values.\n', }; const failureMessage = postVaultStep === null ? `❌ Failed to ${verb} secrets: ${error.message}` : `❌ Vault updated, but the ${postVaultStep} failed: ${error.message}`; const failureHint = postVaultStep === null ? null : (postVaultHints[postVaultStep] ?? null); if (spinnerStopped) { // The spinner already stopped, so its stop is a no-op — // route the message through the failure stamp instead. return failCommand({ message: failureMessage, hint: failureHint, exitCode: 1 }); } s.stop(failureMessage); if (failureHint) console.log(color.dim(failureHint)); return failCommand({ exitCode: 1 }); } export function resolveEcsCluster(projectName, options = {}) { if (typeof options.cluster === 'string' && options.cluster.trim()) return options.cluster.trim(); if (typeof process.env.ECS_CLUSTER === 'string' && process.env.ECS_CLUSTER.trim()) { return process.env.ECS_CLUSTER.trim(); } return `${projectName}-cluster`; } export function resolveEcsService(projectName, options = {}) { for (const key of ['service', 'serviceName']) { if (typeof options[key] === 'string' && options[key].trim()) return options[key].trim(); } if (typeof process.env.ECS_SERVICE === 'string' && process.env.ECS_SERVICE.trim()) { return process.env.ECS_SERVICE.trim(); } return `${projectName}-service`; } // Programmatic entry wrapper: stamps cli_command for telemetry on every // invocation path, including direct imports that bypass bin/cli.js and MCP. export async function pushSecrets(envFilePath, projectName, options = {}) { setActiveCommandName('secrets_push'); try { return await pushSecretsMain(envFilePath, projectName, options); } finally { resetActiveCommandName(); } } async function pushSecretsMain(envFilePath, projectName, options = {}) { // Push is read-modify-full-replace — serialize local // concurrent pushes like every other mutating family (the re-read // before UpdateSecret below covers cross-machine second writers). return withProjectLock(process.cwd(), () => pushSecretsInner(envFilePath, projectName, options)); } // Builds the secrets_pushed success payload shared by the full-push and // all-skipped early-return paths, so the two can never skew key names. function pushSuccessTelemetry({ projectName, pushableSecrets, keysChanged, removed, collisions, skipped, staleSkipped }) { return { projectName, secret_count: Object.keys(pushableSecrets).length, keys_changed: keysChanged, removed_count: removed.length, managed_collisions: collisions.length, skipped_count: skipped.length, stale_skipped_count: staleSkipped.length, }; } async function pushSecretsInner(envFilePath, projectName, options = {}) { const refused = await secretsManagedTreeGuard('push', 'secrets_pushed', projectName, options); if (refused) return refused; const pushGuard = secretsTargetGuard('push'); if (pushGuard) { return failUnsupportedTarget(pushGuard, 'secrets_pushed', typeof projectName === 'string' ? projectName : path.basename(process.cwd())); } const normalized = normalizeSecretsArgs(projectName, options); const opts = normalized.options; const explicitProjectName = normalized.projectName; // Ensure envFilePath is a valid string, defaulting to '.env' if undefined or an object let resolvedFilePath = (typeof envFilePath === 'string' && envFilePath.trim()) ? envFilePath.trim() : '.env'; // Guard against CI injection bugs where "event" or "push" gets passed as the file name if (!resolvedFilePath.includes('.env') && !resolvedFilePath.includes('txt') && !resolvedFilePath.includes('json')) { console.log(color.yellow(`⚠️ Warning: "${resolvedFilePath}" does not look like a standard secrets file. Defaulting to ".env"`)); resolvedFilePath = '.env'; } // Shared helper — the terraform project name outranks the // directory basename (a renamed directory must not aim at a phantom). const resolvedProjectName = resolveSecretsProject(explicitProjectName); const s = spinner(); s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`)); // Write progress for the catch below — names the post-vault // follow-up step when one fails, so the report says the vault is // updated instead of misreporting a failed push. let postVaultStep = null; try { // 1. Read and parse the local .env file const envPath = path.resolve(process.cwd(), resolvedFilePath); let envContent; try { envContent = await fs.readFile(envPath, 'utf-8'); } catch (fsError) { if (fsError.code !== 'ENOENT') throw fsError; s.stop('No .env file found.'); if (opts.isHeadless || process.env.CI) { return failCommand({ message: 'No .env file found. In automated environments, please ensure the file is generated before running secrets push.', event: 'secrets_pushed', telemetry: { projectName: resolvedProjectName, error_code: 'ENV_FILE_MISSING', reason: 'missing_env_headless', }, }); } const refused = await refuseIfNonInteractive(opts, { message: `\n✖ secrets push needs an .env file before pushing.`, hint: ' Generate the .env file before pushing, or run interactively to create an empty one.\n', event: 'secrets_pushed', telemetry: { projectName: resolvedProjectName }, errorCode: 'SECRETS_NON_INTERACTIVE', }); if (refused) return refused; const confirmed = await confirm({ message: `Would you like to create an empty ${resolvedFilePath} file now to get started?`, }); if (isCancel(confirmed)) { console.log(color.dim('Secrets push cancelled. No file was created.')); return; } if (confirmed) { await fs.mkdir(path.dirname(envPath), { recursive: true }); await fs.writeFile(envPath, '# Add your environment variables here\n'); console.log(color.green(`Created empty ${resolvedFilePath}. Add your variables to it, then re-run secrets push.`)); await trackFailure('secrets_pushed', { projectName: resolvedProjectName, reason: 'created_empty_file', }); return; } console.log(color.dim('Secrets push cancelled. No file was created.')); return; } const parsedSecrets = dotenv.parse(envContent); // Dotenv silently drops lines it cannot parse (and // last-wins duplicates) — name them so the success count below // reconciles with the file. Runs before the empty early-return // so an all-dropped file explains itself. const { dropped: droppedLines, duplicates: duplicateKeys } = analyzeEnvLines(envContent, parsedSecrets); if (droppedLines.length > 0 || duplicateKeys.length > 0) { s.stop('Pre-flight checks done.'); if (droppedLines.length > 0) { console.log(color.yellow(`⚠️ Warning: ${droppedLines.length} ${droppedLines.length === 1 ? 'line' : 'lines'} in ${resolvedFilePath} could not be parsed and ${droppedLines.length === 1 ? 'was' : 'were'} ignored:`)); for (const { line, content } of droppedLines) console.log(color.yellow(`- line ${line}: ${content}`)); } for (const { key, lines } of duplicateKeys) { console.log(color.yellow(`⚠️ Warning: duplicate key "${key}" (lines ${lines.join(', ')}) — last value wins.`)); } s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`)); } if (Object.keys(parsedSecrets).length === 0) { s.stop('No secrets found in file.'); return; } // Pre-write guards: colliding keys are auto-skipped // on ECS — pushing them can only brick the deploy, so excluding // them with a loud notice beats refusing and demanding a hand // edit. Local-dev wiring values warn. Everything surfaces before // any AWS or keys-file write. The spinner stops once for all // pre-write output and restarts when the push proceeds. const pushTarget = readTerraformComputeTarget(process.cwd()); const managedNames = await getManagedEnvNames(process.cwd(), pushTarget); const collisions = Object.keys(parsedSecrets).filter((key) => managedNames.includes(key)); const wiringHits = findNonProdWiring(parsedSecrets); // Explicit --yes/--auto-approve pushes everything (vault-storage // escape hatch); the apply preflight still backstops deploys. const skipBypassed = [opts.autoApprove, opts.yes].some((flag) => flag === true || flag === 'true'); const skipped = (collisions.length > 0 && pushTarget !== 'lambda' && !skipBypassed) ? collisions : []; const skippedSet = new Set(skipped); const pushableSecrets = Object.fromEntries(Object.entries(parsedSecrets).filter(([key]) => !skippedSet.has(key))); const needsPreWriteOutput = skipped.length > 0 || wiringHits.length > 0 || (collisions.length > 0 && (pushTarget === 'lambda' || skipBypassed)); if (needsPreWriteOutput) s.stop('Pre-flight checks done.'); for (const { key, indicator } of wiringHits) { console.log(color.yellow(`⚠️ Warning: "${key}" looks like a local-dev value (contains "${indicator}") — pushed as-is, production wiring would dial it.`)); } if (collisions.length > 0 && pushTarget === 'lambda') { 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.`)); } if (collisions.length > 0 && skipBypassed && pushTarget !== 'lambda') { console.log(color.yellow(`⚠️ Warning: pushing ${summarizeKeys(collisions)} anyway (--yes) though Grada injects ${collisions.length === 1 ? 'it' : 'them'} — the apply preflight refuses until conflicting keys leave .env.`)); } if (skipped.length > 0) { console.log(color.yellow(`⚠️ Skipping ${skipped.length} colliding ${skipped.length === 1 ? 'key' : 'keys'} (injected by Grada — remove from .env to silence this):`)); for (const key of skipped) console.log(color.yellow(`- ${key} (skipped — Grada-managed name)`)); } if (Object.keys(pushableSecrets).length === 0) { console.log(color.dim('Nothing left to push — the vault and secret_keys.json are unchanged.')); await trackSuccess('secrets_pushed', pushSuccessTelemetry({ projectName: resolvedProjectName, pushableSecrets, keysChanged: [], removed: [], collisions, skipped, staleSkipped: [], })); return; } if (needsPreWriteOutput) s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`)); // 2. Resolve the region (explicit flag > env > backend.tf > default) // so the AWS client is never constructed without one. const targetRegion = await resolveSecretsRegion(opts); // 3. Initialize the AWS Client locked to the correct region const client = resolveClient(opts.client, SecretsManagerClient, targetRegion ? { region: targetRegion } : {}); // 4. Fetch the existing secret payload to detect key changes (safe on new vaults) let existingKeys = null; let firstSecretString = null; const vaultId = `${secretVaultId(resolvedProjectName)}`; try { const existingResp = await client.send(new GetSecretValueCommand({ SecretId: vaultId, })); firstSecretString = existingResp.SecretString ?? null; existingKeys = Object.keys(vaultPayloadObject(existingResp, vaultId)); } catch (fetchError) { if (fetchError && fetchError.name === 'ResourceNotFoundException') { existingKeys = []; } else { throw fetchError; } } // Push is full-replace, so vault keys absent from .env are // deleted by the update below. Name every victim before writing; // interactive runs confirm first, headless proceeds loudly. // Skipped keys are present in .env, so they never land here — their // exclusion from the vault write is covered by the skip notice // above, not by this confirm. const removed = (existingKeys ?? []).filter((key) => !Object.hasOwn(parsedSecrets, key)); // Skipped keys are present in .env (so they never land in // `removed`) but excluded from the vault write — a stale vault // value for a skipped key is wiped by the full-replace update. // Name every such victim loudly. The skip notice above is the // acknowledgment, so unlike true removals these never confirm. const staleSkipped = skipped.filter((key) => (existingKeys ?? []).includes(key)); if (staleSkipped.length > 0) { console.log(color.yellow(`⚠️ ${staleSkipped.length} skipped ${staleSkipped.length === 1 ? 'key' : 'keys'} still ${staleSkipped.length === 1 ? 'has' : 'have'} a stale vault value that this push deletes (no longer pushed):`)); for (const key of staleSkipped) console.log(color.red(`- ${key} (stale vault value deleted — key is skipped)`)); } if (removed.length > 0) { s.stop('Pre-flight checks done.'); console.log(color.yellow(`⚠️ ${removed.length} vault ${removed.length === 1 ? 'key' : 'keys'} not in ${resolvedFilePath} will be deleted:`)); for (const key of removed) console.log(color.red(`- ${key} (removed from the vault)`)); const headlessPush = opts.isHeadless || opts.headless || process.env.CI; const removalApproved = [opts.autoApprove, opts.yes].some((flag) => flag === true || flag === 'true'); if (!headlessPush && !removalApproved) { const refusedRemoval = await refuseIfNonInteractive(opts, { message: `\n✖ secrets push needs approval before deleting ${removed.length} vault ${removed.length === 1 ? 'key' : 'keys'} missing from ${resolvedFilePath}.`, hint: ' Re-run with --headless to delete non-interactively (removals are named above), or run interactively to decide.\n', event: 'secrets_pushed', telemetry: { projectName: resolvedProjectName, removed_count: removed.length }, errorCode: 'SECRETS_NON_INTERACTIVE', }); if (refusedRemoval) return refusedRemoval; const proceed = await confirm({ message: `Delete ${summarizeKeys(removed)} from the vault?`, initialValue: false, }); if (isCancel(proceed) || proceed !== true) { console.log(color.dim('Secrets push cancelled. The vault and secret_keys.json are unchanged.')); return; } } s.start(truncateSpinnerText(`Reading ${envFilePath} and pushing to AWS Secrets Manager...`)); } // The confirm above can wait unboundedly — re-read the // vault immediately before the full-replace write and abort when // a second writer moved the payload since the first read. let rereadSecretString = null; let rereadBinary = false; try { const rereadResp = await client.send(new GetSecretValueCommand({ SecretId: vaultId })); rereadSecretString = rereadResp.SecretString ?? null; rereadBinary = rereadResp.SecretBinary != null; } catch (rereadError) { if (!rereadError || rereadError.name !== 'ResourceNotFoundException') throw rereadError; } if (rereadBinary || rereadSecretString !== firstSecretString) { s.stop('Pre-flight checks done.'); return failCommand({ message: `\n✖ The vault changed while this push was waiting (a second writer updated it) — refusing to overwrite. Re-run the push to merge with the latest vault content.\n`, event: 'secrets_pushed', telemetry: { projectName: resolvedProjectName, error_code: 'SECRETS_VAULT_CHANGED' }, errorCode: 'SECRETS_VAULT_CHANGED', reason: 'secrets-vault-changed', }); } // 5. Update the secret string in AWS const command = new UpdateSecretCommand({ SecretId: vaultId, SecretString: JSON.stringify(pushableSecrets), }); await client.send(command); const keys = Object.keys(pushableSecrets); const keysFilePath = path.join(process.cwd(), 'terraform', 'secret_keys.json'); // Skip the write when the file is already byte-identical // so unchanged pushes don't dirty `git status`. const nextKeysContent = JSON.stringify(keys, null, 2); let keysUnchanged = false; try { keysUnchanged = (await fs.readFile(keysFilePath, 'utf-8')) === nextKeysContent; } catch { keysUnchanged = false; } if (!keysUnchanged) { postVaultStep = 'secret_keys.json write'; await atomicWriteFile(keysFilePath, nextKeysContent); } s.stop(`✅ Successfully pushed ${Object.keys(pushableSecrets).length} secrets to AWS (${targetRegion || 'default region'})!`); const sortedExisting = [...(existingKeys ?? [])].sort(); const sortedNew = [...keys].sort(); const keysChanged = sortedExisting.length !== sortedNew.length || sortedExisting.some((key, index) => key !== sortedNew[index]); if (keysChanged) { console.log(color.cyan(`\nUpdated ${keysFilePath}`)); console.log(color.green('Commit this file and push to GitHub to trigger a deployment with your new variables.')); } else { console.log(color.cyan(`\nUpdated ${keysFilePath}`)); // Lambda functions read secrets at invocation time, so new values // apply to fresh execution environments with no restart to trigger. if (readTerraformComputeTarget(process.cwd()) === 'lambda') { console.log(color.dim('Lambda target detected: new secret values apply to fresh invocations automatically — no restart needed.')); 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')}`)); await trackSuccess('secrets_pushed', { projectName: resolvedProjectName, secret_count: Object.keys(pushableSecrets).length, keys_changed: false, ecs_restart: false, removed_count: removed.length, managed_collisions: collisions.length, skipped_count: skipped.length, stale_skipped_count: staleSkipped.length }); return { keysChanged: false, restarted: false, skipped }; } // Automated runs cannot answer prompts: skip the restart (fresh // deploys pick up the values) instead of hanging on confirm. if (opts.isHeadless || process.env.CI) { console.log(color.dim('Headless environment detected: skipping the ECS restart prompt — new values apply on the next deployment or restart.')); 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')}`)); await trackSuccess('secrets_pushed', { projectName: resolvedProjectName, secret_count: Object.keys(pushableSecrets).length, keys_changed: false, ecs_restart: false, removed_count: removed.length, managed_collisions: collisions.length, skipped_count: skipped.length, stale_skipped_count: staleSkipped.length }); return { keysChanged: false, restarted: false, skipped }; } const refused = await refuseIfNonInteractive(opts, { message: `\n✖ secrets push needs approval before triggering the ECS restart.`, hint: ' Re-run with --headless to skip the restart non-interactively (values apply on the next deployment), or run interactively to decide.\n', event: 'secrets_pushed', telemetry: { projectName: resolvedProjectName }, errorCode: 'SECRETS_NON_INTERACTIVE', }); if (refused) return refused; const shouldRestart = await confirm({ message: 'Keys are unchanged. Trigger a rolling ECS restart to apply new values immediately?', initialValue: false, }); if (shouldRestart === true) { const cluster = resolveEcsCluster(resolvedProjectName, opts); const service = resolveEcsService(resolvedProjectName, opts); const ecsClient = resolveClient(opts.ecsClient ?? opts.ecs, ECSClient, targetRegion ? { region: targetRegion } : {}); const restartSpinner = spinner(); restartSpinner.start('Triggering rolling ECS restart...'); try { postVaultStep = 'ECS restart'; await ecsClient.send(new UpdateServiceCommand({ cluster, service, forceNewDeployment: true, })); restartSpinner.stop('✅ ECS rolling restart triggered.'); outro(`Rolling restart initiated for ${service} in ${cluster}. ECS will roll tasks with the new secret values.`); } catch (ecsError) { restartSpinner.stop(`❌ Failed to trigger ECS restart: ${ecsError.message}`); throw ecsError; } await trackSuccess('secrets_pushed', { projectName: resolvedProjectName, secret_count: Object.keys(pushableSecrets).length, keys_changed: false, ecs_restart: true, removed_count: removed.length, managed_collisions: collisions.length, skipped_count: skipped.length, stale_skipped_count: staleSkipped.length }); 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')}`)); return { keysChanged: false, restarted: true, cluster, service, skipped }; } } 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')}`)); await trackSuccess('secrets_pushed', pushSuccessTelemetry({ projectName: resolvedProjectName, pushableSecrets, keysChanged, removed, collisions, skipped, staleSkipped, })); return { keysChanged, skipped }; } catch (error) { return handleSecretsCatch({ error, event: 'secrets_pushed', verb: 'push', s, opts, projectName: resolvedProjectName, postVaultStep, notFoundMessage: `❌ Secrets Vault "${secretVaultId(resolvedProjectName)}" does not exist in AWS yet.`, notFoundGuidance: [ `Run ${color.cyan('npx --yes grada-run apply')} first to provision the infrastructure and Secrets Manager vault.`, `Once applied, run ${color.cyan(`npx grada-run secrets push ${resolvedFilePath}`)} to upload your environment variables.\n`, ], stackTraceOnTypeError: true, }); } } // Programmatic entry wrapper: stamps cli_command for telemetry on every // invocation path, including direct imports that bypass bin/cli.js and MCP. export async function pullSecrets(envFilePath, projectName, options = {}) { setActiveCommandName('secrets_pull'); try { return await pullSecretsMain(envFilePath, projectName, options); } finally { resetActiveCommandName(); } } async function pullSecretsMain(envFilePath, projectName, options = {}) { const refused = await secretsManagedTreeGuard('pull', 'secrets_pull', projectName, options); if (refused) return refused; const pullGuard = secretsTargetGuard('pull'); if (pullGuard) { return failUnsupportedTarget(pullGuard, 'secrets_pull', typeof projectName === 'string' ? projectName : path.basename(process.cwd())); } const { resolvedProjectName, opts } = resolvePullAuditArgs(projectName, options); const resolvedFilePath = resolveSecretsFile(envFilePath); const { isHeadless = false, client: injectedClient } = opts; const s = spinner(); s.start('Fetching secrets from AWS...'); let remoteFetched = false; try { const targetRegion = await resolveSecretsRegion(opts); const client = resolveClient(injectedClient, SecretsManagerClient, targetRegion ? { region: targetRegion } : {}); const resp = await client.send(new GetSecretValueCommand({ SecretId: `${secretVaultId(resolvedProjectName)}`, })); const remoteSecrets = vaultPayloadObject(resp, `${secretVaultId(resolvedProjectName)}`); const remoteKeys = Object.keys(remoteSecrets); s.stop('Remote secrets fetched.'); remoteFetched = true; const envPath = path.resolve(process.cwd(), resolvedFilePath); let localSecrets = {}; let localExists = true; let envContent = null; try { envContent = await fs.readFile(envPath, 'utf-8'); localSecrets = dotenv.parse(envContent); } catch (fsError) { if (fsError.code === 'ENOENT') { localExists = false; localSecrets = {}; } else { throw fsError; } } const { mismatched } = diffSecretsEnvs(localSecrets, remoteSecrets); let overwrite = true; if (localExists && mismatched.length > 0) { if (isHeadless) { overwrite = true; } else { const refused = await refuseIfNonInteractive(opts, { message: `\n✖ secrets pull needs approval before overwriting local values.`, hint: ' Re-run with --headless to overwrite non-interactively, or run interactively to review conflicts.\n', event: 'secrets_pull', telemetry: { projectName: resolvedProjectName }, errorCode: 'SECRETS_NON_INTERACTIVE', }); if (refused) return refused; const answer = await confirm({ message: 'Conflicting variables found. Overwrite local values with remote?', initialValue: false, }); overwrite = answer === true; } } // Null-prototype map: a `__proto__` vault key lands as an own data // property instead of mutating the merge target's prototype. const merged = Object.assign(Object.create(null), localSecrets); for (const [key, value] of Object.entries(remoteSecrets)) { if (!Object.hasOwn(merged, key) || overwrite) { merged[key] = String(value); } } const orderedKeys = [ ...Object.keys(localSecrets), ...remoteKeys.filter((k) => !Object.hasOwn(localSecrets, k)), ]; // The merge appends remote-only keys (reviving local deletions) // — name what came back instead of syncing silently. const appended = localExists ? remoteKeys.filter((k) => !Object.hasOwn(localSecrets, k)) : []; if (appended.length > 0) { console.log(color.yellow(`⚠️ Pulled ${appended.length} key${appended.length === 1 ? '' : 's'} not present locally (revived deletions?): ${appended.join(', ')}`)); } // Only keys being added/overwritten can block the write: a // local-only exotic value must not abort an unrelated sync. const writtenKeys = remoteKeys.filter((key) => !Object.hasOwn(localSecrets, key) || overwrite); const unrepresentable = writtenKeys.filter((key) => key === '__proto__' || quoteEnvValue(merged[key]) === null ); if (unrepresentable.length > 0) { const abort = new Error( `Refusing to write ${resolvedFilePath}: ${unrepresentable.length} entr${unrepresentable.length === 1 ? 'y' : 'ies'} ` + `cannot round-trip through .env quoting (${unrepresentable.join(', ')}). ` + 'Rename or re-encode them in the vault and retry.' ); abort.code = 'SECRETS_PULL_UNREPRESENTABLE_VALUE'; throw abort; } // Skip the write when the merge changes nothing semantically. // Byte comparison always differs on commented files // (serializeEnv emits canonical lines), so compare parsed // content instead: same keys + same values means the file — // comments and all — already holds exactly this state. const localKeys = Object.keys(localSecrets); const semanticallyEqual = localExists && localKeys.length === orderedKeys.length && orderedKeys.every((key) => Object.hasOwn(localSecrets, key) && String(localSecrets[key]) === String(merged[key])); if (!semanticallyEqual) { await fs.writeFile(envPath, serializeEnv(orderedKeys, merged)); } outro(`Successfully synced ${remoteKeys.length} secrets to ${resolvedFilePath}`); trackEvent('secrets_pull', { projectName: resolvedProjectName, variablesCount: remoteKeys.length, }); await flushTelemetry(); return { synced: remoteKeys.length, file: resolvedFilePath, overwritten: overwrite, conflicts: mismatched, appended }; } catch (error) { return handleSecretsCatch({ error, event: 'secrets_pull', verb: 'pull', s, opts, projectName: resolvedProjectName, notFoundMessage: `❌ No remote secrets found for "${secretVaultId(resolvedProjectName)}".`, notFoundGuidance: [ `Run ${color.cyan(`npx grada-run secrets push ${resolvedFilePath}`)} first to upload your environment variables.\n`, ], spinnerStopped: remoteFetched, }); } } // Programmatic entry wrapper: stamps cli_command for telemetry on every // invocation path, including direct imports that bypass bin/cli.js and MCP. export async function auditSecrets(envFilePath, projectName, options = {}) { setActiveCommandName('secrets_audit'); try { return await auditSecretsMain(envFilePath, projectName, options); } finally { resetActiveCommandName(); } } async function auditSecretsMain(envFilePath, projectName, options = {}) { const refused = await secretsManagedTreeGuard('audit', 'secrets_audit', projectName, options); if (refused) return refused; const auditGuard = secretsTargetGuard('audit'); if (auditGuard) { return failUnsupportedTarget(auditGuard, 'secrets_audit', typeof projectName === 'string' ? projectName : path.basename(process.cwd())); } const { resolvedProjectName, opts } = resolvePullAuditArgs(projectName, options); const resolvedFilePath = resolveSecretsFile(envFilePath); const { client: injectedClient } = opts; const s = spinner(); s.start('Auditing local environment against AWS...'); try { const targetRegion = await resolveSecretsRegion(opts); const client = resolveClient(injectedClient, SecretsManagerClient, targetRegion ? { region: targetRegion } : {}); const resp = await client.send(new GetSecretValueCommand({ SecretId: `${secretVaultId(resolvedProjectName)}`, })); const remoteSecrets = vaultPayloadObject(resp, `${secretVaultId(resolvedProjectName)}`); const envPath = path.resolve(process.cwd(), resolvedFilePath); let localSecrets = {}; try { const envContent = await fs.readFile(envPath, 'utf-8'); localSecrets = dotenv.parse(envContent); } catch (fsError) { if (fsError.code !== 'ENOENT') throw fsError; localSecrets = {}; } s.stop('Audit complete.'); const { missingLocally, mismatched, untrackedLocally } = diffSecretsEnvs(localSecrets, remoteSecrets); const driftCount = missingLocally.length + mismatched.length + untrackedLocally.length; if (driftCount === 0) { console.log(color.green('No drift detected. Local and remote secrets are in sync.')); } else { for (const key of missingLocally) { console.log(color.green(`+ ${key} (Missing locally)`)); } for (const key of mismatched) { console.log(color.yellow(`~ ${key} (Mismatched value)`)); } for (const key of untrackedLocally) { console.log(color.dim(`- ${key} (Not tracked in AWS)`)); } } // Flag both limbs — keys colliding with Grada-managed // environment names (fatal on ECS, shadowing on Lambda) and // wiring-like values that look like local-dev placeholders. const auditTarget = readTerraformComputeTarget(process.cwd()); const auditManaged = await getManagedEnvNames(process.cwd(), auditTarget); const auditedKeys = [...new Set([...Object.keys(localSecrets), ...Object.keys(remoteSecrets)])]; const collisions = auditedKeys.filter((key) => auditManaged.includes(key)); for (const key of collisions) { console.log(color.red(`! ${key} (collides with a Grada-managed environment name)`)); } for (const { key, indicator } of findNonProdWiring(remoteSecrets)) { console.log(color.yellow(`⚠️ ${key} looks like a local-dev value (contains "${indicator}") — production wiring would dial it.`)); } outro(`Audit complete. ${driftCount} drifted variable(s) found.`); trackEvent('secrets_audit', { projectName: resolvedProjectName, driftCount, collision_count: collisions.length, }); await flushTelemetry(); return { missingLocally, mismatched, untrackedLocally, driftCount, collisions }; } catch (error) { return handleSecretsCatch({ error, event: 'secrets_audit', verb: 'audit', s, opts, projectName: resolvedProjectName, notFoundMessage: `❌ No remote secrets found for "${secretVaultId(resolvedProjectName)}".`, notFoundGuidance: [ `Run ${color.cyan(`npx grada-run secrets push ${resolvedFilePath}`)} first to upload your environment variables.\n`, ], }); } }