@grada-run/grada 0.50.0 → 0.50.2

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/grada",
3
- "version": "0.50.0",
3
+ "version": "0.50.2",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -279,7 +279,7 @@ const ADDON_NOTIFY_ALARMS = [
279
279
  threshold: 1,
280
280
  evaluationPeriods: 1,
281
281
  period: 300,
282
- describe: () => 'the dead-letter queue holds failed messages (redrive or inspect them).',
282
+ describe: () => 'the dead-letter queue holds failed messages (redrive or inspect them). Runbook: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/alert-notifications.md#redriving-the-dlq',
283
283
  dimensions: { QueueName: 'aws_sqs_queue.dlq.name' },
284
284
  },
285
285
  {
@@ -499,6 +499,12 @@ ${aliasLine} topic_arn = aws_sns_topic.alerts.arn
499
499
  # (The archive provider constraint lives in backend.tf next to the aws
500
500
  # one — a module may declare required_providers only once.)
501
501
 
502
+ locals {
503
+ # Length-safe forwarder name (role + function both cap at 64):
504
+ # short names render byte-identically, over-cap hash-suffixes.
505
+ forwarder_safe_name = length("${namePrefix}-alerts-forwarder") > 64 ? "\${trimsuffix(substr(local.app_name, 0, 64 - 1 - 5 - 17), "-")}-\${substr(md5(local.app_name), 0, 5)}-alerts-forwarder" : "${namePrefix}-alerts-forwarder"
506
+ }
507
+
502
508
  variable "alerts_webhook_url" {
503
509
  description = "Incoming chat webhook URL for alarm notifications. Export TF_VAR_alerts_webhook_url before apply — never commit the URL to git."
504
510
  type = string
@@ -518,7 +524,7 @@ ${buildForwarderJs()} EOT
518
524
  }
519
525
 
520
526
  resource "aws_iam_role" "forwarder" {
521
- name = "${namePrefix}-alerts-forwarder"
527
+ name = local.forwarder_safe_name
522
528
  assume_role_policy = jsonencode({
523
529
  Version = "2012-10-17"
524
530
  Statement = [
@@ -537,7 +543,7 @@ resource "aws_iam_role_policy_attachment" "forwarder_logs" {
537
543
  }
538
544
 
539
545
  resource "aws_lambda_function" "forwarder" {
540
- ${aliasLine} function_name = "${namePrefix}-alerts-forwarder"
546
+ ${aliasLine} function_name = local.forwarder_safe_name
541
547
  role = aws_iam_role.forwarder.arn
542
548
  runtime = "nodejs22.x"
543
549
  handler = "index.handler"
@@ -8,7 +8,7 @@ import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized,
8
8
  import { normalizeOptions } from '../utils/args.js';
9
9
  import { truncateSpinnerText } from '../utils/spinner-text.js';
10
10
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
11
- import { resolveRegion, resolveProjectName, resolveCluster, resolveLogGroup, resolveCwd, readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, resolveNamespacedProject, withWorkspaceNamespace } from '../utils/resolvers.js';
11
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveLogGroup, resolveCwd, readTerraformComputeTarget, guardComputeTarget, readResourceSuffix, resolveNamespacedProject, withWorkspaceNamespace, resolveFunctionName } from '../utils/resolvers.js';
12
12
  import { pickNewestRunningTask } from '../utils/ecs.js';
13
13
  import { fetchLatestEvents } from './logs.js';
14
14
 
@@ -127,7 +127,7 @@ export async function runLambdaDiagnose(input = {}) {
127
127
  const namespacedProject = resolveNamespacedProject(projectName, options, options.cwd);
128
128
  const functionName = typeof options.functionName === 'string' && options.functionName.trim()
129
129
  ? options.functionName.trim()
130
- : `${namespacedProject}${readResourceSuffix(options.cwd)}-fn`;
130
+ : resolveFunctionName(`${namespacedProject}${readResourceSuffix(options.cwd)}`);
131
131
  const runSync = options.spawnSyncImpl || spawnSync;
132
132
 
133
133
  intro(color.bgCyan(color.black(' grada diagnose 🩺 ')));
@@ -7,7 +7,7 @@ import { checkDependency } from '../utils/system.js';
7
7
  import { checkAwsCredentials, TROUBLESHOOTING_URL } from '../utils/aws.js';
8
8
  import { readLastRunMarker, isInterruptedMarker } from '../utils/terraform.js';
9
9
  import { refuseUnknownFlags } from '../utils/command.js';
10
- import { readTerraformOidcTrust } from '../utils/resolvers.js';
10
+ import { readTerraformOidcTrust, readTerraformProjectName, readResourceSuffix, resolveWorkspaceSuffix, MAX_CONFINED_PROJECT_LENGTH, MAX_CONFINED_APP_LENGTH, exceedsConfinementBound } from '../utils/resolvers.js';
11
11
  import { parseStateBucketBackend } from '../utils/terraform-metadata.js';
12
12
  import { normalizeOptions, parseFlags, normalizeArgv } from '../utils/args.js';
13
13
  import { trackEvent, flushTelemetry, detectCiProvider, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
@@ -35,6 +35,7 @@ export const PROJECT_CHECKS = [
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
36
  { id: 'oidc_immutable_claims', label: 'OIDC trust formats', scope: 'project', severity: 'warn', run: checkOidcImmutableClaims, hint: () => 'Re-run npx grada-run init to upgrade the trust, or add a repo:<owner>@*/<name>@*:* entry to terraform/oidc.tf.' },
37
37
  { id: 'origin_restriction', label: 'ALB origin restriction', scope: 'project', severity: 'warn', run: checkOriginRestriction, hint: () => 'Re-run npx grada-run init to add the CloudFront origin-secret wiring, then apply.' },
38
+ { id: 'name_confinement_bound', label: 'Project name confinement bound', scope: 'project', severity: 'warn', run: checkNameConfinementBound, hint: () => 'Shorten the project name (re-scaffold into a fresh tree and migrate state) or switch to a shorter workspace; the residual and its bounds are documented in the CI/CD pipeline guide.' },
38
39
  ];
39
40
 
40
41
  const INSTALL_HINTS = {
@@ -213,6 +214,26 @@ function workspaceSuffix(lockKey) {
213
214
  // rule 403ing hits without the header). Warning-grade: the URL still
214
215
  // prints, but on unwired trees it misleads. Non-ECS targets have no
215
216
  // ALB — skip.
217
+ // Project check: names past the confinement bound hash-suffix their
218
+ // derived AWS resources, which prefix-anchored preview guardrails
219
+ // stop matching. Init refuses such names on fresh scaffolds, so a
220
+ // hit here means a grandfathered tree (or a hand-made over-long
221
+ // workspace) — warn with the remediation path, never fail.
222
+ function checkNameConfinementBound({ cwd }) {
223
+ const project = readTerraformProjectName(cwd);
224
+ if (!project) return { ok: true, skipped: 'no project name found' };
225
+ const appLen = project.length + resolveWorkspaceSuffix({}, cwd).length + (readResourceSuffix(cwd) || '').length;
226
+ if (!exceedsConfinementBound(project) && appLen <= MAX_CONFINED_APP_LENGTH) return { ok: true };
227
+ const reasons = [];
228
+ if (exceedsConfinementBound(project)) {
229
+ reasons.push(`project name is ${project.length} chars (bound: ${MAX_CONFINED_PROJECT_LENGTH}): derived AWS names hash-suffix past what the preview guardrails match`);
230
+ }
231
+ if (appLen > MAX_CONFINED_APP_LENGTH) {
232
+ reasons.push(`current app name resolves to ${appLen} chars (bound: ${MAX_CONFINED_APP_LENGTH}): the active workspace lengthens it past confinement`);
233
+ }
234
+ return { ok: false, detailLines: reasons };
235
+ }
236
+
216
237
  function checkOriginRestriction({ cwd }) {
217
238
  let mainTf;
218
239
  try {
@@ -11,7 +11,7 @@ import color from 'picocolors';
11
11
  import { intro, outro, confirm, spinner, cancel } from '@clack/prompts';
12
12
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
13
13
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
14
- import { resolveRegion, resolveProjectName, resolveCwd, isComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
14
+ import { resolveRegion, resolveProjectName, resolveCwd, isComputeTarget, readResourceSuffix, resolveFunctionName } from '../utils/resolvers.js';
15
15
  import { resolveClient } from '../utils/aws.js';
16
16
  import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseIfNonInteractive, refuseUnknownFlags, shouldAutoApprove } from '../utils/command.js';
17
17
  import { parseStateBucketBackend } from '../utils/terraform-metadata.js';
@@ -73,6 +73,13 @@ function escapeRegExp(text) {
73
73
  return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
74
74
  }
75
75
 
76
+ // Anchored snapshot-name matchers for a set of db ids and a tail
77
+ // pattern: manual safety checkpoints and per-commit pre-deploy
78
+ // snapshots share the shape, only the tail differs.
79
+ function snapshotNamePatterns(dbIds, tail) {
80
+ return dbIds.map((id) => new RegExp(`^${escapeRegExp(id)}-${tail}$`));
81
+ }
82
+
76
83
  // Grada renders exactly one ECR repo per tree: `<project><suffix>-repo`
77
84
  // (previews push tags; they never mint repos). Anything else sharing
78
85
  // the prefix is foreign — never propose it.
@@ -80,11 +87,20 @@ function projectRepoName(projectName, resourceSuffix = '') {
80
87
  return `${projectName}${resourceSuffix}-repo`;
81
88
  }
82
89
 
90
+ // Shared preview-workspace infix (`<project>-pr-<n><suffix>`), escaped
91
+ // for embedding: log-group and function liveness both match on it.
92
+ function previewPrInfix(projectName, resourceSuffix = '') {
93
+ return `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
94
+ }
95
+
83
96
  // Preview log groups carry the `-pr-<n>` workspace infix at a fixed
84
97
  // position (`<project>-pr-<n><suffix>`); anchor both ends so foreign
85
98
  // lookalikes (`myapp-evil-pr-2`) never match.
86
99
  function previewLogGroupPattern({ projectName, resourceSuffix = '', isLambda = false }) {
87
- const base = `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
100
+ const base = previewPrInfix(projectName, resourceSuffix);
101
+ // Plain-form only by design: over-cap preview names hash-suffix in
102
+ // Terraform, so they never match here — fail closed (never proposed)
103
+ // and the 30-day group retention self-cleans them instead.
88
104
  return isLambda ? new RegExp(`^/aws/lambda/${base}-fn$`) : new RegExp(`^/ecs/${base}$`);
89
105
  }
90
106
 
@@ -197,8 +213,11 @@ export async function discoverLivePreviewLogGroups({
197
213
  } = {}) {
198
214
  const live = new Set();
199
215
  try {
200
- const base = `${escapeRegExp(projectName)}-pr-\\d+${escapeRegExp(resourceSuffix)}`;
216
+ const base = previewPrInfix(projectName, resourceSuffix);
201
217
  if (isLambda) {
218
+ // Plain-form only (see previewLogGroupPattern): hashed
219
+ // over-cap functions are invisible here, and invisible to
220
+ // the orphan candidate pattern too — consistently skipped.
202
221
  const fnPattern = new RegExp(`^${base}-fn$`);
203
222
  const names = await listFunctionsImpl({ region, spawnSyncImpl });
204
223
  for (const name of names || []) {
@@ -285,12 +304,10 @@ async function discoverOldManualSnapshots({ rdsClient, dbIdentifier, dbClusterId
285
304
  const dbIds = [dbIdentifier, dbClusterIdentifier]
286
305
  .filter((id) => typeof id === 'string' && id.trim())
287
306
  .map((id) => id.trim().toLowerCase());
288
- const patterns = dbIds
289
- .map((id) => new RegExp(`^${escapeRegExp(id)}-manual-\\d{8}-\\d{6}$`));
307
+ const patterns = snapshotNamePatterns(dbIds, 'manual-\\d{8}-\\d{6}');
290
308
  // The gate's pre-deploy snapshots are per-commit, so without
291
309
  // a discovery rule they accumulate into the region snapshot quota.
292
- const predeployPatterns = dbIds
293
- .map((id) => new RegExp(`^${escapeRegExp(id)}-pre-deploy-[0-9a-f]{7,40}$`));
310
+ const predeployPatterns = snapshotNamePatterns(dbIds, 'pre-deploy-[0-9a-f]{7,40}');
294
311
  // Legacy bare pre-deploy-<sha> ids carry no db scope: retire them
295
312
  // only with a matching source-db attribute, never by name alone.
296
313
  const legacyPredeployPattern = /^pre-deploy-[0-9a-f]{7,40}$/;
@@ -740,7 +757,7 @@ async function runGcMain(input = {}) {
740
757
  // Exact match: the live group carries the suffix on suffixed
741
758
  // trees, and proposing it for deletion would be catastrophic.
742
759
  excludeLogGroup: isLambda
743
- ? `/aws/lambda/${projectName}${suffix}-fn`
760
+ ? `/aws/lambda/${resolveFunctionName(`${projectName}${suffix}`)}`
744
761
  : `/ecs/${projectName}${suffix}`,
745
762
  livePreviewGroups: liveness.groups,
746
763
  previewLivenessUnknown: liveness.unknown,
@@ -42,7 +42,7 @@ import { getTargetDirectory, getProjectConfig, promptWorkerCommand, promptGitHub
42
42
  import { resolveDjangoWsgi, handleRailsCI } from '../utils/frameworks.js';
43
43
  import { parseDockerCompose, selectComposeWebService } from '../utils/dockerCompose.js';
44
44
  import { getBaseRules, getCursorRules, injectManagedBlock } from '../utils/ai-rules.js';
45
- import { readFileSafe, COMPUTE_TARGETS, resolveHeadless, resolveInitSuffix, readTerraformProjectName, readTerraformOidcTrust, guardComputeTarget } from '../utils/resolvers.js';
45
+ import { readFileSafe, COMPUTE_TARGETS, resolveHeadless, resolveInitSuffix, readTerraformProjectName, readTerraformOidcTrust, guardComputeTarget, MAX_CONFINED_PROJECT_LENGTH, exceedsConfinementBound, safeSuffixedName } from '../utils/resolvers.js';
46
46
  import { readGitHubRepoFromRemote, isValidGitHubRepoSlug } from '../utils/git.js';
47
47
  import { parseDomainTf } from '../utils/domains.js';
48
48
  import { PLACEHOLDER_ACCOUNT_ID } from '../utils/reconcile.js';
@@ -187,6 +187,15 @@ export function buildPreviewRoleName(projectName, suffix) {
187
187
  return buildCiRoleName(projectName, suffix, 'preview');
188
188
  }
189
189
 
190
+ // Gate snapshot scope: the database identifier the pre-deploy gate
191
+ // snapshots, hashed exactly like identifier_safe_name /
192
+ // cluster_safe_name so gate snapshots match gc's pre-deploy patterns
193
+ // (and the guardrail snapshot patterns) on all name lengths.
194
+ export function buildGateDbIdentifier(projectName, suffix, isCluster) {
195
+ const base = `${projectName ?? ''}${suffix ?? ''}`;
196
+ return isCluster ? safeSuffixedName(base, '-db-cluster', 63) : safeSuffixedName(base, '-db', 63);
197
+ }
198
+
190
199
  export function buildRoleArn(accountId, roleName) {
191
200
  return `arn:aws:iam::${accountId}:role/${roleName}`;
192
201
  }
@@ -544,7 +553,7 @@ async function wireInitWorkflows({ targetDir, projectName, resourceSuffix, regio
544
553
  // Scope the gate's snapshot id to the database (aurora
545
554
  // takes the cluster prefix) so guardrails and gc can name it.
546
555
  const gateDbRefs = resolveDbEngineRefs(dbEngine);
547
- const gateDbIdentifier = `${projectName}${resourceSuffix}-db${gateDbRefs.isCluster ? '-cluster' : ''}`;
556
+ const gateDbIdentifier = buildGateDbIdentifier(projectName, resourceSuffix, gateDbRefs.isCluster);
548
557
  const gated = workflowContent ? injectMigrationGate(workflowContent, { cmd: migrationCmd, cliVersion: CLI_VERSION, dbIdentifier: gateDbIdentifier }) : null;
549
558
  if (gated) {
550
559
  atomicWriteFileSync(deployYmlPath, gated);
@@ -1351,6 +1360,36 @@ async function resolveInitWorkdir({ options, isHeadless, headlessOptions, explic
1351
1360
  trackEvent('init_project_name_reused', { projectName: sanitizedTreeName });
1352
1361
  dirConfig.actualProjectName = sanitizedTreeName;
1353
1362
  }
1363
+ // Fresh and renamed trees collapse consecutive hyphens: RDS
1364
+ // identifiers forbid `--`, and collapsing at mint time keeps every
1365
+ // derived name valid. Grandfathered trees keep their exact name
1366
+ // (collapsing there would fork live infrastructure).
1367
+ if (dirConfig.actualProjectName !== sanitizedTreeName) {
1368
+ const collapsed = dirConfig.actualProjectName.replace(/-{2,}/g, '-');
1369
+ if (collapsed !== dirConfig.actualProjectName) {
1370
+ console.log(color.dim(`Project name collapsed to "${collapsed}" (consecutive hyphens are invalid in RDS identifiers).`));
1371
+ dirConfig.actualProjectName = collapsed;
1372
+ }
1373
+ }
1374
+ // Confinement bound for NEW names only: past it, derived AWS names
1375
+ // hash-suffix and prefix-anchored preview guardrails stop matching
1376
+ // them. Grandfathered trees (existing name kept) are never refused
1377
+ // here — doctor flags them instead. Explicit renames count as new
1378
+ // names: they provision a fresh stack.
1379
+ if (dirConfig.actualProjectName !== sanitizedTreeName && exceedsConfinementBound(dirConfig.actualProjectName)) {
1380
+ return {
1381
+ refusal: await failCommand({
1382
+ message: `\n✖ Project name "${dirConfig.actualProjectName}" is ${dirConfig.actualProjectName.length} chars — past the ${MAX_CONFINED_PROJECT_LENGTH}-char confinement bound. Longer names hash-suffix their derived AWS resource names, which the prefix-anchored preview guardrails can no longer match.`,
1383
+ hint: ` Shorten to ${MAX_CONFINED_PROJECT_LENGTH} chars or fewer and re-run (existing long-name trees keep deploying; grada doctor flags them). Bound rationale: https://github.com/grada-run/grada/blob/main/apps/docs/src/content/docs/guides/cicd-pipeline.md\n`,
1384
+ useErrorStream: true,
1385
+ event: 'cli-error',
1386
+ telemetry: { step: 'project_name', error_code: 'PROJECT_NAME_OVER_CONFINEMENT_BOUND' },
1387
+ errorCode: 'PROJECT_NAME_OVER_CONFINEMENT_BOUND',
1388
+ reason: 'project-name-over-confinement-bound',
1389
+ exitCode: 1,
1390
+ }),
1391
+ };
1392
+ }
1354
1393
  return { dirConfig };
1355
1394
  }
1356
1395
 
@@ -12,7 +12,7 @@ import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveComman
12
12
  import { failCommand, failAwsError, failProjectNotInitialized, refuseIfNonInteractive, refuseUnknownFlags } from '../utils/command.js';
13
13
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
14
14
  import { isAuthError, handleAwsAuthError, resolveClient } from '../utils/aws.js';
15
- import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, withWorkspaceNamespace, resolveCwd, guardComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
15
+ import { resolveRegion, resolveProjectName, resolveCluster, resolveService, readFileSafe, withWorkspaceNamespace, resolveCwd, guardComputeTarget, readResourceSuffix, resolveFunctionName } from '../utils/resolvers.js';
16
16
  import { requireManagedTree } from '../utils/terraform-metadata.js';
17
17
  import { truncateSpinnerText } from '../utils/spinner-text.js';
18
18
  import { guardSleepingEnv, resolveSleepTarget } from '../utils/sleep-state.js';
@@ -131,7 +131,7 @@ async function runRollbackMain(input = {}) {
131
131
 
132
132
  const targetGuard = guardComputeTarget({ cwd, command: 'Rollback', supported: ['ecs'] });
133
133
  if (targetGuard) {
134
- const functionName = `${projectName}${readResourceSuffix(cwd)}-fn`;
134
+ const functionName = resolveFunctionName(`${projectName}${readResourceSuffix(cwd)}`);
135
135
  trackEvent('rollback_target_unsupported', { projectName, actual: targetGuard.actual });
136
136
  return failCommand({
137
137
  message: targetGuard.message,
@@ -9,7 +9,7 @@ import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveComman
9
9
  import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
10
10
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
11
11
  import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
12
- import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget, readResourceSuffix, resolveNamespacedProject, safeSuffixedName } from '../utils/resolvers.js';
12
+ import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget, readResourceSuffix, resolveNamespacedProject, safeSuffixedName, resolveFunctionName } from '../utils/resolvers.js';
13
13
  import { runDiagnose } from './diagnose.js';
14
14
  import { detectAlertAddonFeatures } from './alerts.js';
15
15
  import { fetchGoldenSignals } from '../utils/golden-signals.js';
@@ -135,7 +135,7 @@ export async function runLambdaStatus(input = {}) {
135
135
  const namespacedProject = resolveNamespacedProject(projectName, options, cwd);
136
136
  const functionName = typeof options.functionName === 'string' && options.functionName.trim()
137
137
  ? options.functionName.trim()
138
- : `${namespacedProject}${readResourceSuffix(cwd)}-fn`;
138
+ : resolveFunctionName(`${namespacedProject}${readResourceSuffix(cwd)}`);
139
139
  const asJson = Boolean(options.json);
140
140
  const runSync = options.spawnSyncImpl || spawnSync;
141
141
 
package/src/utils/aws.js CHANGED
@@ -112,10 +112,17 @@ export async function checkAwsCredentials(region) {
112
112
  export function formatStateBucketName(projectName, accountId) {
113
113
  const suffix = `-tfstate-${accountId}`;
114
114
  const room = Math.max(63 - suffix.length, 1);
115
- let project = sanitizeProjectName(projectName);
116
- if (project.length > room) project = project.substring(0, room).replace(/-+$/, '');
117
- if (project === '') project = 'app';
118
- return `${project}${suffix}`;
115
+ const project = sanitizeProjectName(projectName);
116
+ // Preserve a trailing resource suffix (`-a1b2c3`): truncating the
117
+ // combined string could sever it, collapsing two trees onto one
118
+ // bucket. Truncate the project part to fit around it instead.
119
+ const suffixMatch = project.match(/-[a-f0-9]{6}$/);
120
+ const resourceSuffix = suffixMatch ? suffixMatch[0] : '';
121
+ const stemRoom = Math.max(room - resourceSuffix.length, 1);
122
+ let stem = resourceSuffix ? project.slice(0, -resourceSuffix.length) : project;
123
+ if (stem.length > stemRoom) stem = stem.substring(0, stemRoom).replace(/-+$/, '');
124
+ if (stem === '') stem = 'app';
125
+ return `${stem}${resourceSuffix}${suffix}`;
119
126
  }
120
127
 
121
128
  export async function provisionStateBucket(region, projectName) {
@@ -140,6 +140,19 @@ export function injectLambdaAdapter(dockerContent, port) {
140
140
  // master-secret IAM policy (indexing an empty `master_user_secret` tuple fails
141
141
  // planning) and appends the `random_password` resource. No-op for ECS content
142
142
  // or content that was already converted.
143
+ const SAFE_NAME_KEYS = ['identifier_safe_name', 'db_name_base', 'db_name_safe_name', 'cluster_safe_name', 'instance_safe_name', 'database_name_base', 'database_name_safe_name'];
144
+
145
+ function realignSurvivingSafeNames(content) {
146
+ const present = SAFE_NAME_KEYS.filter((key) => new RegExp(`^\\s*${key}\\s*=`, 'm').test(content));
147
+ if (present.length === 0) return content;
148
+ const width = Math.max(...present.map((key) => key.length));
149
+ let out = content;
150
+ for (const key of present) {
151
+ out = out.replace(new RegExp(`^(\\s*)${key}\\s*=`, 'm'), (_, indent) => `${indent}${key}${' '.repeat(width - key.length + 1)}=`);
152
+ }
153
+ return out;
154
+ }
155
+
143
156
  export function convertDatabaseTfForLambda(databaseTfContent) {
144
157
  let content = String(databaseTfContent ?? '');
145
158
  if (!content.includes('manage_master_user_password = true')) return content;
@@ -151,6 +164,12 @@ export function convertDatabaseTfForLambda(databaseTfContent) {
151
164
  ` # Lambda targets use an explicit Terraform-managed password (see\n # random_password.db_password below) so the value can flow into the\n # function's DB_PASSWORD environment variable without a Secrets Manager\n # VPC endpoint.\n ${passwordAttr} = random_password.db_password.result`
152
165
  );
153
166
  content = content.replace('# 4. IAM Permission for RDS Master Password Secret\n', '');
167
+ // The policy's safe-name local dangles once the block below is gone —
168
+ // strip the line too or tflint flags an unused declaration. It was
169
+ // the longest key in its run, so re-pad the survivors to the new
170
+ // longest or the rendered file fails fmt -check.
171
+ content = content.replace(/^\s*secret_policy_safe_name\s*=.*\n/m, '');
172
+ content = realignSurvivingSafeNames(content);
154
173
  const resource = findResourceBlock(content, 'aws_iam_role_policy', 'rds_secret_access');
155
174
  if (resource) {
156
175
  const lineStart = content.lastIndexOf('\n', resource.headerIdx - 1) + 1;
package/src/utils/rds.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DescribeDBInstancesCommand, DescribeDBClustersCommand } from '@aws-sdk/client-rds';
2
- import { resolveProjectName, resolveWorkspaceSuffix, readResourceSuffix } from './resolvers.js';
2
+ import { resolveProjectName, resolveWorkspaceSuffix, readResourceSuffix, safeSuffixedName } from './resolvers.js';
3
3
  import { normalizeOptions } from './args.js';
4
4
 
5
5
  // Error names the RDS API returns for a missing instance across SDK shapes.
@@ -118,24 +118,26 @@ export function isValidSnapshotId(id) {
118
118
  }
119
119
 
120
120
  // Database identifier for the current project/workspace. An explicit
121
- // `--db-identifier` override wins; otherwise `<appName>-db`.
121
+ // `--db-identifier` override wins; otherwise `<appName>-db`, hash-suffixed
122
+ // past the 63-char cap exactly like identifier_safe_name in database.tf.
122
123
  export function resolveDbIdentifier(options = {}, cwd = process.cwd()) {
123
124
  const opts = normalizeOptions(options);
124
125
  if (typeof opts.dbIdentifier === 'string' && opts.dbIdentifier.trim()) {
125
126
  return opts.dbIdentifier.trim();
126
127
  }
127
128
  const base = resolveProjectName(opts, cwd);
128
- return `${base}${resolveWorkspaceSuffix(opts, cwd)}${readResourceSuffix(cwd)}-db`;
129
+ return safeSuffixedName(`${base}${resolveWorkspaceSuffix(opts, cwd)}${readResourceSuffix(cwd)}`, '-db', 63);
129
130
  }
130
131
 
131
132
  // Aurora cluster identifier for the current project/workspace. An explicit
132
133
  // `--db-identifier` override wins (tried as both kinds); otherwise
133
- // `<appName>-db-cluster`, matching the generated cluster_identifier.
134
+ // `<appName>-db-cluster`, hash-suffixed past the 63-char cap exactly
135
+ // like cluster_safe_name in database-aurora-postgresql.tf.
134
136
  export function resolveDbClusterIdentifier(options = {}, cwd = process.cwd()) {
135
137
  const opts = normalizeOptions(options);
136
138
  if (typeof opts.dbIdentifier === 'string' && opts.dbIdentifier.trim()) {
137
139
  return opts.dbIdentifier.trim();
138
140
  }
139
141
  const base = resolveProjectName(opts, cwd);
140
- return `${base}${resolveWorkspaceSuffix(opts, cwd)}${readResourceSuffix(cwd)}-db-cluster`;
142
+ return safeSuffixedName(`${base}${resolveWorkspaceSuffix(opts, cwd)}${readResourceSuffix(cwd)}`, '-db-cluster', 63);
141
143
  }
@@ -115,18 +115,47 @@ export function readTerraformRegion(cwd = process.cwd()) {
115
115
  // Length-safe AWS resource name, mirroring the template conditional
116
116
  // byte-for-byte: short names render identically; over-cap names take a
117
117
  // deterministic md5 stem (never a truncating collision). `cap` is the
118
- // service limit including suffix. Doubled hyphens at the cut point are
119
- // left alone — valid in every name pattern here, and trimming would
120
- // need identical semantics on both sides. Both sides must stay in
118
+ // service limit including suffix. Cut-point hyphens are trimmed from
119
+ // the stem (RDS forbids `--`) — the hash input stays untouched, so
120
+ // non-hyphen cuts render exactly as before. Both sides must stay in
121
121
  // sync — the parity tests below pin the shared cases.
122
122
  export function safeSuffixedName(base, suffix, cap) {
123
123
  const full = `${base}${suffix}`;
124
124
  if (full.length <= cap) return full;
125
125
  const stemLength = Math.max(cap - 1 - 5 - suffix.length, 1);
126
- const stem = base.slice(0, stemLength);
126
+ const stem = base.slice(0, stemLength).replace(/-+$/, '');
127
127
  return `${stem}-${createHash('md5').update(base, 'utf8').digest('hex').slice(0, 5)}${suffix}`;
128
128
  }
129
129
 
130
+ // Preview-confinement bound: the longest sanitized project name whose
131
+ // worst-case derived names stay plain (unhashed), so prefix-anchored
132
+ // guardrail patterns keep matching. Binding constraint is the
133
+ // scheduler role (64 - 20); worst-case app adds the preview infix
134
+ // (`-pr-` + 7 PR digits = 11) and the 7-char resource suffix, so
135
+ // project <= 64 - 20 - 11 - 7 = 26. New scaffolds past this are
136
+ // refused at init; grandfathered trees are flagged by doctor, never
137
+ // broken. Pinned honest by the parity harness in generator.test.js —
138
+ // if a template grows a longer escape-relevant suffix, recompute.
139
+ export const MAX_CONFINED_PROJECT_LENGTH = 26;
140
+ export const CONFINEMENT_WORST_ENV_SUFFIX_LENGTH = 11;
141
+ export const CONFINEMENT_RESOURCE_SUFFIX_LENGTH = 7;
142
+ // Worst-case app_name the bound admits (project + env + suffix): the
143
+ // scheduler role renders at exactly the 64-char cap here. Doctor
144
+ // evaluates the LIVE tree (real workspace + suffix) against this.
145
+ export const MAX_CONFINED_APP_LENGTH = 44;
146
+
147
+ export function exceedsConfinementBound(sanitizedProjectName) {
148
+ return String(sanitizedProjectName ?? '').length > MAX_CONFINED_PROJECT_LENGTH;
149
+ }
150
+
151
+ // Single home for the Lambda function name (`<app>-fn`, 64-char cap):
152
+ // status, diagnose, gc, rollback, and the log-group resolver all read
153
+ // through here, so the suffix and cap can't drift apart again. Short
154
+ // names render plain; over-cap names hash-suffix like fn_safe_name.
155
+ export function resolveFunctionName(appName) {
156
+ return safeSuffixedName(String(appName ?? ''), '-fn', 64);
157
+ }
158
+
130
159
  export function resolveRegion(options = {}, cwd = process.cwd()) {
131
160
  const opts = normalizeOptions(options);
132
161
  if (typeof opts.region === 'string' && opts.region.trim()) {
@@ -332,9 +361,9 @@ export function resolveLogGroup(options = {}, cwd = process.cwd()) {
332
361
  const projectName = resolveProjectName(opts, base);
333
362
  const suffixed = `${projectName}${readResourceSuffix(base)}`;
334
363
  // Lambda functions log to /aws/lambda/<fn> (see main-lambda.tf), where
335
- // the function name is `<app>-fn`.
364
+ // the function name is `<app>-fn`, hash-suffixed past 64 chars.
336
365
  if (readTerraformComputeTarget(base) === 'lambda') {
337
- return `/aws/lambda/${suffixed}-fn`;
366
+ return `/aws/lambda/${resolveFunctionName(suffixed)}`;
338
367
  }
339
368
  return `/ecs/${suffixed}`;
340
369
  }
@@ -1,7 +1,7 @@
1
1
  import fsSync from 'fs';
2
2
  import path from 'path';
3
3
  import { withProjectLock } from './file-lock.js';
4
- import { readResourceSuffix } from './resolvers.js';
4
+ import { readResourceSuffix, safeSuffixedName } from './resolvers.js';
5
5
 
6
6
  // Auxiliary sleep/wake targets driven through the AWS CLI: EventBridge
7
7
  // Scheduler pause/resume and ECS Application Auto Scaling suspend/resume.
@@ -12,11 +12,13 @@ import { readResourceSuffix } from './resolvers.js';
12
12
  // instead of adding new npm packages. Every helper degrades to a skip
13
13
  // reason; callers warn and continue so sleep/wake never fail on these.
14
14
 
15
- // cron.tf renders `name = "${local.app_name}-cron-<slug>"` inside the
16
- // schedule block. Resolves the live schedule name for an app prefix, or
17
- // null when cron isn't configured (or the file was hand-edited past
18
- // recognition). Scoped to the schedule block: the IAM role/policy above
19
- // share the `-cron-` prefix, and an unscoped first match resolves
15
+ // cron.tf renders the slug in the `schedule_full_name` local while the
16
+ // schedule block references `schedule_safe_name` (hashed past 64
17
+ // chars). Resolves the live schedule name for an app prefix, or null
18
+ // when cron isn't configured (or the file was hand-edited past
19
+ // recognition). Falls back to the legacy inline `name` for pre-hash
20
+ // trees. Scoped lookups only: the IAM role/policy share the `-cron-`
21
+ // prefix, and an unscoped first match resolves
20
22
  // `-cron-scheduler-role` — pausing a schedule that doesn't exist while
21
23
  // the real one keeps firing (and Terraform plans ENABLED -> DISABLED).
22
24
  export function readCronScheduleName(cwd, appPrefix) {
@@ -26,11 +28,16 @@ export function readCronScheduleName(cwd, appPrefix) {
26
28
  } catch {
27
29
  return null;
28
30
  }
29
- const blockStart = content.indexOf('resource "aws_scheduler_schedule"');
30
- if (blockStart < 0) return null;
31
- const match = /name\s*=\s*"\$\{local\.app_name\}-cron-([A-Za-z0-9-]+)"/.exec(content.slice(blockStart));
32
- if (!match) return null;
33
- return `${appPrefix}${readResourceSuffix(cwd)}-cron-${match[1]}`;
31
+ const fullName = /schedule_full_name\s*=\s*"\$\{local\.app_name\}-cron-([A-Za-z0-9-]+)"/.exec(content)?.[1] ?? null;
32
+ let slug = fullName;
33
+ if (!slug) {
34
+ const blockStart = content.indexOf('resource "aws_scheduler_schedule"');
35
+ if (blockStart < 0) return null;
36
+ const match = /name\s*=\s*"\$\{local\.app_name\}-cron-([A-Za-z0-9-]+)"/.exec(content.slice(blockStart));
37
+ if (!match) return null;
38
+ slug = match[1];
39
+ }
40
+ return safeSuffixedName(`${appPrefix}${readResourceSuffix(cwd)}-cron-${slug}`, '', 64);
34
41
  }
35
42
 
36
43
  export function hasCronAddon(cwd) {
@@ -15,7 +15,7 @@ concurrency:
15
15
  env:
16
16
  AWS_REGION: {{REGION}}
17
17
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
18
- LAMBDA_FUNCTION: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-fn
18
+ APP_NAME: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}
19
19
  CF_COMMENT: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-cdn
20
20
 
21
21
  permissions:
@@ -153,13 +153,26 @@ jobs:
153
153
  # `latest` is never the deploy artifact of record).
154
154
  - name: Deploy image to AWS Lambda
155
155
  run: |
156
+ # Mirror of safeSuffixedName (resolvers.js): Terraform hashes
157
+ # over-cap function names, so plain reconstruction would target
158
+ # a function that doesn't exist.
159
+ safe_name() {
160
+ local base="$1" suffix="$2" cap="$3" full="${1}${2}"
161
+ if [ "${#full}" -le "$cap" ]; then printf '%s' "$full"; return; fi
162
+ local stemlen=$((cap - 1 - 5 - ${#suffix}))
163
+ local stem=${base:0:$stemlen}
164
+ while [[ "$stem" == *- ]]; do stem=${stem%-}; done
165
+ local hash=$(printf '%s' "$base" | md5sum | cut -c1-5)
166
+ printf '%s-%s%s' "$stem" "$hash" "$suffix"
167
+ }
156
168
  IMAGE_URI=${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:${GITHUB_SHA::7}
169
+ LAMBDA_FUNCTION=$(safe_name "${{ env.APP_NAME }}" "-fn" 64)
157
170
  aws lambda update-function-code \
158
- --function-name ${{ env.LAMBDA_FUNCTION }} \
171
+ --function-name "$LAMBDA_FUNCTION" \
159
172
  --image-uri "$IMAGE_URI" \
160
173
  --region ${{ env.AWS_REGION }}
161
174
  aws lambda wait function-updated \
162
- --function-name ${{ env.LAMBDA_FUNCTION }} \
175
+ --function-name "$LAMBDA_FUNCTION" \
163
176
  --region ${{ env.AWS_REGION }}
164
177
 
165
178
  # --- 9. CACHE INVALIDATION ---
@@ -20,6 +20,7 @@ env:
20
20
  AWS_REGION: {{REGION}}
21
21
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
22
22
  WORKSPACE: pr-${{ github.event.pull_request.number }}
23
+ APP_NAME: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}
23
24
  CF_COMMENT: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}-cdn
24
25
 
25
26
  permissions:
@@ -102,12 +103,25 @@ jobs:
102
103
  # Terraform provisions the function pointing at :latest (which it
103
104
  # then ignores), so the PR-tagged image is deployed explicitly —
104
105
  # mirroring the workspace-tagged task definition on ECS targets.
106
+ # Mirror of safeSuffixedName (resolvers.js): Terraform hashes
107
+ # over-cap function names, so plain reconstruction would target
108
+ # a function that doesn't exist.
109
+ safe_name() {
110
+ local base="$1" suffix="$2" cap="$3" full="${1}${2}"
111
+ if [ "${#full}" -le "$cap" ]; then printf '%s' "$full"; return; fi
112
+ local stemlen=$((cap - 1 - 5 - ${#suffix}))
113
+ local stem=${base:0:$stemlen}
114
+ while [[ "$stem" == *- ]]; do stem=${stem%-}; done
115
+ local hash=$(printf '%s' "$base" | md5sum | cut -c1-5)
116
+ printf '%s-%s%s' "$stem" "$hash" "$suffix"
117
+ }
118
+ LAMBDA_FUNCTION=$(safe_name "${{ env.APP_NAME }}" "-fn" 64)
105
119
  aws lambda update-function-code \
106
- --function-name {{PROJECT_NAME}}-${{ env.WORKSPACE }}{{RESOURCE_SUFFIX}}-fn \
120
+ --function-name "$LAMBDA_FUNCTION" \
107
121
  --image-uri $ECR_REGISTRY/$ECR_REPOSITORY:${{ env.WORKSPACE }} \
108
122
  --region ${{ env.AWS_REGION }}
109
123
  aws lambda wait function-updated \
110
- --function-name {{PROJECT_NAME}}-${{ env.WORKSPACE }}{{RESOURCE_SUFFIX}}-fn \
124
+ --function-name "$LAMBDA_FUNCTION" \
111
125
  --region ${{ env.AWS_REGION }}
112
126
 
113
127
  - name: Read preview URL