|
| 1 | +import type { GetSecretValueCommandOutput } from '@aws-sdk/client-secrets-manager' |
| 2 | +import { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-secrets-manager' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { getErrorMessage } from '@sim/utils/errors' |
| 5 | +import { sleep } from '@sim/utils/helpers' |
| 6 | +import { backoffWithJitter } from '@sim/utils/retry' |
| 7 | + |
| 8 | +const logger = createLogger('RuntimeSecrets') |
| 9 | + |
| 10 | +/** Plaintext env var (set in the ECS task definition) naming the secret to ingest. */ |
| 11 | +const SECRET_ID_ENV = 'SIM_ENV_SECRET_ID' |
| 12 | + |
| 13 | +const MAX_ATTEMPTS = 3 |
| 14 | + |
| 15 | +/** |
| 16 | + * Fetches the combined `/{env}/sim/env-vars` secret once at container boot and |
| 17 | + * hydrates `process.env`, so secrets no longer have to be fanned out into the |
| 18 | + * ECS task definition (which is approaching the 64 KB rendered-document limit). |
| 19 | + * |
| 20 | + * Must run before any application module that reads env at import time. No-ops |
| 21 | + * when {@link SECRET_ID_ENV} is unset (local dev / self-hosted keep using their |
| 22 | + * own env). Existing `process.env` keys are never overwritten, so explicit |
| 23 | + * task-definition `environment` entries win. Throws on any fetch/parse failure |
| 24 | + * so a misconfigured container crashes instead of booting without its config. |
| 25 | + */ |
| 26 | +export async function loadRuntimeSecrets(): Promise<void> { |
| 27 | + const secretId = process.env[SECRET_ID_ENV] |
| 28 | + if (!secretId) { |
| 29 | + logger.info(`${SECRET_ID_ENV} not set; skipping runtime secret ingestion`) |
| 30 | + return |
| 31 | + } |
| 32 | + |
| 33 | + const client = new SecretsManagerClient( |
| 34 | + process.env.AWS_REGION ? { region: process.env.AWS_REGION } : {} |
| 35 | + ) |
| 36 | + |
| 37 | + const secretString = await fetchSecretString(client, secretId) |
| 38 | + const entries = parseSecretJson(secretString) |
| 39 | + |
| 40 | + let loaded = 0 |
| 41 | + let skipped = 0 |
| 42 | + for (const [key, value] of Object.entries(entries)) { |
| 43 | + if (key in process.env) { |
| 44 | + skipped++ |
| 45 | + continue |
| 46 | + } |
| 47 | + process.env[key] = typeof value === 'string' ? value : JSON.stringify(value) |
| 48 | + loaded++ |
| 49 | + } |
| 50 | + |
| 51 | + logger.info('Runtime secrets ingested', { secretId, loaded, skipped }) |
| 52 | +} |
| 53 | + |
| 54 | +async function fetchSecretString(client: SecretsManagerClient, secretId: string): Promise<string> { |
| 55 | + let lastError: unknown |
| 56 | + for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { |
| 57 | + try { |
| 58 | + const response: GetSecretValueCommandOutput = await client.send( |
| 59 | + new GetSecretValueCommand({ SecretId: secretId }) |
| 60 | + ) |
| 61 | + if (!response.SecretString) { |
| 62 | + throw new Error('Secret has no SecretString (binary secrets are not supported)') |
| 63 | + } |
| 64 | + return response.SecretString |
| 65 | + } catch (error) { |
| 66 | + lastError = error |
| 67 | + if (attempt < MAX_ATTEMPTS) { |
| 68 | + const delay = backoffWithJitter(attempt, null, { baseMs: 200, maxMs: 2000 }) |
| 69 | + logger.warn( |
| 70 | + `Failed to fetch runtime secrets (attempt ${attempt}/${MAX_ATTEMPTS}), retrying`, |
| 71 | + { error: getErrorMessage(error) } |
| 72 | + ) |
| 73 | + await sleep(delay) |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + throw new Error(`Failed to fetch runtime secrets from ${secretId}: ${getErrorMessage(lastError)}`) |
| 78 | +} |
| 79 | + |
| 80 | +function parseSecretJson(secretString: string): Record<string, unknown> { |
| 81 | + let parsed: unknown |
| 82 | + try { |
| 83 | + parsed = JSON.parse(secretString) |
| 84 | + } catch (error) { |
| 85 | + throw new Error(`Runtime secret is not valid JSON: ${getErrorMessage(error)}`) |
| 86 | + } |
| 87 | + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { |
| 88 | + throw new Error('Runtime secret must be a JSON object of key/value pairs') |
| 89 | + } |
| 90 | + return parsed as Record<string, unknown> |
| 91 | +} |
0 commit comments