cdk-real-drift 0.7.3 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1051,6 +1051,10 @@ function buildStackSelector(patterns) {
1051
1051
  };
1052
1052
  }
1053
1053
  const CONCRETE_REGION = /^[a-z]{2}(-[a-z]+)+-\d+$/;
1054
+ const CONCRETE_ACCOUNT = /^\d{12}$/;
1055
+ function concreteAccount(raw) {
1056
+ return raw && CONCRETE_ACCOUNT.test(raw) ? raw : void 0;
1057
+ }
1054
1058
  /**
1055
1059
  * Build the stderr message body (no `warning:` prefix — the caller adds it) for the case where
1056
1060
  * `--app` points at a pre-synthesized cloud-assembly DIRECTORY (`cdk.out`) yet the user also
@@ -1145,17 +1149,23 @@ async function synthApp(app, opts = {}) {
1145
1149
  return cached.cloudAssembly.stacksRecursively.map((s) => ({
1146
1150
  stackName: s.stackName,
1147
1151
  region: CONCRETE_REGION.test(s.environment.region) ? s.environment.region : void 0,
1152
+ account: concreteAccount(s.environment.account),
1148
1153
  template: s.template
1149
1154
  }));
1150
1155
  } finally {
1151
1156
  await cached.dispose();
1152
1157
  }
1153
1158
  }
1154
- /** Synth and return each stack's name + its own (concrete) region + template, for discovery. */
1159
+ /**
1160
+ * Synth and return each stack's name + its own (concrete) region + account + template, for
1161
+ * discovery. The account (#740) lets check distinguish a stack pinned to another account from
1162
+ * a never-deployed one.
1163
+ */
1155
1164
  async function discoverStacks(app, opts = {}) {
1156
1165
  return (await synthApp(app, opts)).map((s) => ({
1157
1166
  stackName: s.stackName,
1158
1167
  region: s.region,
1168
+ account: s.account,
1159
1169
  template: s.template
1160
1170
  }));
1161
1171
  }
@@ -1240,17 +1250,19 @@ async function resolveStacks(a) {
1240
1250
  if (a.all || a.stackNames.length === 0) return discovered.map((s) => ({
1241
1251
  stackName: s.stackName,
1242
1252
  region: s.region ?? fallbackRegion,
1253
+ account: s.account,
1243
1254
  template: s.template
1244
1255
  }));
1245
1256
  const seen = /* @__PURE__ */ new Set();
1246
1257
  const out = [];
1247
- const add = (stackName, region, template) => {
1258
+ const add = (stackName, region, account, template) => {
1248
1259
  const key = `${stackName}\0${region ?? ""}`;
1249
1260
  if (seen.has(key)) return;
1250
1261
  seen.add(key);
1251
1262
  out.push({
1252
1263
  stackName,
1253
1264
  region,
1265
+ account,
1254
1266
  template
1255
1267
  });
1256
1268
  };
@@ -1259,13 +1271,13 @@ async function resolveStacks(a) {
1259
1271
  let matched = 0;
1260
1272
  for (const s of discovered) if (matchesGlob(name, s.stackName)) {
1261
1273
  matched++;
1262
- add(s.stackName, s.region ?? fallbackRegion, s.template);
1274
+ add(s.stackName, s.region ?? fallbackRegion, s.account, s.template);
1263
1275
  }
1264
1276
  if (matched === 0) throw new Error(`glob "${name}" matched no stacks defined by the CDK app (found: ${known()})`);
1265
1277
  } else {
1266
1278
  const hits = discovered.filter((s) => s.stackName === name);
1267
1279
  if (hits.length === 0) throw new Error(`stack "${name}" is not defined by the CDK app (found: ${known()})`);
1268
- for (const hit of hits) add(hit.stackName, hit.region ?? fallbackRegion, hit.template);
1280
+ for (const hit of hits) add(hit.stackName, hit.region ?? fallbackRegion, hit.account, hit.template);
1269
1281
  }
1270
1282
  if (out.length === 0) throw new Error(`no stacks match ${a.stackNames.join(", ")} (found: ${known()})`);
1271
1283
  return out;
@@ -4011,7 +4023,7 @@ function partitionForRegion(region) {
4011
4023
  urlSuffix: "amazonaws.com"
4012
4024
  };
4013
4025
  }
4014
- function buildResolverContext(template, stackParams, physIds, region, accountId, stackName, stackId) {
4026
+ function buildResolverContext(template, stackParams, physIds, region, accountId, stackName, stackId, preDeploy = false) {
4015
4027
  const paramDefs = template.Parameters ?? {};
4016
4028
  const isList = (k) => {
4017
4029
  const t = paramDefs[k]?.Type ?? "";
@@ -4024,7 +4036,9 @@ function buildResolverContext(template, stackParams, physIds, region, accountId,
4024
4036
  if ((def?.Type ?? "").includes("::Parameter::Value<")) continue;
4025
4037
  if (def && "Default" in def) params[k] = toParam(k, String(def.Default));
4026
4038
  }
4027
- for (const [k, v] of Object.entries(stackParams)) params[k] = toParam(k, v);
4039
+ if (preDeploy) {
4040
+ for (const [k, v] of Object.entries(stackParams)) if (!(k in params)) params[k] = toParam(k, v);
4041
+ } else for (const [k, v] of Object.entries(stackParams)) params[k] = toParam(k, v);
4028
4042
  const templateResources = template.Resources ?? {};
4029
4043
  const typeOf = {};
4030
4044
  const declaredRawProps = {};
@@ -4120,7 +4134,7 @@ async function loadDesired(client, stackName, region, templateOverride, recovery
4120
4134
  const replaceInfo = typeChangeReplaceInfo([...typeChanged].sort(), templateResourcesForTypeCheck, deployedTypeOf, stackName);
4121
4135
  if (replaceInfo) console.error(replaceInfo);
4122
4136
  }
4123
- const ctx = buildResolverContext(template, stackParams, physIds, region, accountId, stackName, stackId);
4137
+ const ctx = buildResolverContext(template, stackParams, physIds, region, accountId, stackName, stackId, !!templateOverride);
4124
4138
  const notificationArns = stack?.NotificationARNs ?? [];
4125
4139
  if (notificationArns.length > 0) ctx.params["AWS::NotificationARNs"] = notificationArns;
4126
4140
  if (JSON.stringify(template).includes("Fn::ImportValue")) try {
@@ -4840,6 +4854,27 @@ const CLUSTER_ECHO_CHILD = {
4840
4854
  };
4841
4855
  const isKeyValueEntry = (t) => !!t && typeof t === "object" && typeof t.Key === "string" && "Value" in t;
4842
4856
  const REFLECTED_CHILD_PROPS = { "AWS::SNS::Topic": "Subscription" };
4857
+ const EVENT_BUS_TYPE = "AWS::Events::EventBus";
4858
+ const EVENT_BUS_POLICY_PROP = "Policy";
4859
+ function subtractSiblingEventBusStatements(live, siblingStatements) {
4860
+ const policy = live[EVENT_BUS_POLICY_PROP];
4861
+ if (!policy || typeof policy !== "object") return;
4862
+ const arr = policy.Statement;
4863
+ if (!Array.isArray(arr) || siblingStatements.length === 0) return;
4864
+ for (const sib of siblingStatements) {
4865
+ if (!sib || typeof sib !== "object") continue;
4866
+ const sub = sib;
4867
+ const sibSid = sub.Sid;
4868
+ const i = arr.findIndex((el) => {
4869
+ if (el === null || typeof el !== "object") return false;
4870
+ const e = el;
4871
+ if (typeof sibSid === "string" && sibSid) return e.Sid === sibSid;
4872
+ return Object.entries(sub).every(([k, v]) => v === UNRESOLVED || deepEqual(e[k], v));
4873
+ });
4874
+ if (i >= 0) arr.splice(i, 1);
4875
+ }
4876
+ if (arr.length === 0) delete live[EVENT_BUS_POLICY_PROP];
4877
+ }
4843
4878
  const IAM_PRINCIPAL_POLICY_TYPES = new Set([
4844
4879
  "AWS::IAM::Role",
4845
4880
  "AWS::IAM::User",
@@ -5230,6 +5265,11 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
5230
5265
  const declared = canonicalizeForCompare(rewriteOaiPrincipalsDeep(declaredForCompare, oaiMap), resourceType);
5231
5266
  const reflected = REFLECTED_CHILD_PROPS[resourceType];
5232
5267
  if (reflected && !(reflected in declared)) delete live[reflected];
5268
+ if (resourceType === EVENT_BUS_TYPE && !(EVENT_BUS_POLICY_PROP in declared)) {
5269
+ const busKey = physicalId ?? resource.declared.Name;
5270
+ const sibStatements = typeof busKey === "string" ? opts.siblingEventBusPolicies?.[busKey] : void 0;
5271
+ if (sibStatements) subtractSiblingEventBusStatements(live, sibStatements);
5272
+ }
5233
5273
  if (resourceType === "AWS::ECS::Cluster" && resource.hasSiblingCapacityProviders) {
5234
5274
  for (const p of ["CapacityProviders", "DefaultCapacityProviderStrategy"]) if (!(p in declared)) delete live[p];
5235
5275
  }
@@ -10219,6 +10259,28 @@ function buildSiblingSgRules(desired) {
10219
10259
  }
10220
10260
  return map;
10221
10261
  }
10262
+ const EVENT_BUS_POLICY_TYPE = "AWS::Events::EventBusPolicy";
10263
+ const DEFAULT_EVENT_BUS = "default";
10264
+ function buildSiblingEventBusPolicies(desired) {
10265
+ const map = {};
10266
+ for (const r of desired.resources) {
10267
+ if (r.resourceType !== EVENT_BUS_POLICY_TYPE) continue;
10268
+ const decl = r.declared;
10269
+ if (!decl || typeof decl !== "object") continue;
10270
+ const d = decl;
10271
+ const busName = d.EventBusName;
10272
+ let busKey;
10273
+ if (busName === void 0) busKey = DEFAULT_EVENT_BUS;
10274
+ else if (typeof busName === "string" && busName) busKey = busName;
10275
+ else continue;
10276
+ const stmt = d.Statement;
10277
+ if (!stmt || typeof stmt !== "object") continue;
10278
+ const statement = { ...stmt };
10279
+ if (statement.Sid === void 0 && typeof d.StatementId === "string" && d.StatementId) statement.Sid = d.StatementId;
10280
+ (map[busKey] ??= []).push(statement);
10281
+ }
10282
+ return map;
10283
+ }
10222
10284
  const S3_NOTIFICATIONS_CR_TYPE = "Custom::S3BucketNotifications";
10223
10285
  function buildBucketNotificationManaged(desired) {
10224
10286
  const byLogicalId = /* @__PURE__ */ new Map();
@@ -10389,6 +10451,7 @@ async function gatherFindings(stackName, region, templateOverride, recoveryTempl
10389
10451
  kmsAliasTargets,
10390
10452
  oaiCanonicalIds,
10391
10453
  siblingSgRules: buildSiblingSgRules(desired),
10454
+ siblingEventBusPolicies: buildSiblingEventBusPolicies(desired),
10392
10455
  bucketNotificationManaged: buildBucketNotificationManaged(desired),
10393
10456
  clusterEchoModel: buildClusterEchoModels(desired)
10394
10457
  };
@@ -10447,6 +10510,7 @@ async function regatherTouched(gathered, touched, region) {
10447
10510
  kmsAliasTargets,
10448
10511
  oaiCanonicalIds,
10449
10512
  siblingSgRules: buildSiblingSgRules(desired),
10513
+ siblingEventBusPolicies: buildSiblingEventBusPolicies(desired),
10450
10514
  bucketNotificationManaged: buildBucketNotificationManaged(desired),
10451
10515
  clusterEchoModel: buildClusterEchoModels(desired)
10452
10516
  };
@@ -13565,12 +13629,26 @@ function buildRevertPlan(findings, baseline, opts = {}) {
13565
13629
  notRevertable
13566
13630
  };
13567
13631
  }
13632
+ function coerceDeclaredScalar(desired, live) {
13633
+ if (typeof desired !== "string") return desired;
13634
+ if (typeof live === "number") {
13635
+ const n = Number(desired);
13636
+ if (Number.isFinite(n) && desired.trim() !== "") return n;
13637
+ return desired;
13638
+ }
13639
+ if (typeof live === "boolean") {
13640
+ if (desired === "true") return true;
13641
+ if (desired === "false") return false;
13642
+ return desired;
13643
+ }
13644
+ return desired;
13645
+ }
13568
13646
  function revertOp(f, recorded) {
13569
13647
  const pointer = toPointer(f.path);
13570
13648
  if (f.tier === "declared") return {
13571
13649
  op: "add",
13572
13650
  path: pointer,
13573
- value: f.desired,
13651
+ value: coerceDeclaredScalar(f.desired, f.actual),
13574
13652
  prior: f.actual,
13575
13653
  ...f.attributeKey !== void 0 && { attributeKey: f.attributeKey },
13576
13654
  human: `${f.path}${f.attributeKey ? `[${f.attributeKey}]` : ""} -> deployed-template value`
@@ -15970,6 +16048,36 @@ async function resolveCallerAccount(region) {
15970
16048
  return;
15971
16049
  }
15972
16050
  }
16051
+ /**
16052
+ * #740: decide whether a stack must be SKIPPED because it is pinned (via `env.account`) to a
16053
+ * different AWS account than the active credentials are for.
16054
+ *
16055
+ * A CDK app with dev+prod stacks in DIFFERENT accounts (the CDK Pipelines / multi-env staple)
16056
+ * is checked one account at a time — the caller runs `check --all` per account with that
16057
+ * account's credentials. A stack whose `env.account` names an OTHER account cannot be read
16058
+ * with the current creds: `DescribeStacks` throws "does not exist" (the stack IS deployed, just
16059
+ * in its own account), which `isStackNotDeployed` mistakes for "never deployed yet — skipped"
16060
+ * — a misleading green pass that hides an UNCHECKED stack. Worse, if a SAME-NAMED stack happens
16061
+ * to exist in the reachable account, cdkrd would silently compare intent against the WRONG
16062
+ * account's live resources. Detecting the mismatch UP FRONT lets check skip accurately without
16063
+ * reading the wrong account.
16064
+ *
16065
+ * Rule: skip ONLY when BOTH accounts are known (concrete) AND they differ — a proven mismatch.
16066
+ * When either is undefined (an env-agnostic stack with no account pin, or STS could not resolve
16067
+ * the caller) we CANNOT prove a mismatch, so we do NOT skip — behavior is identical to today
16068
+ * (the stack is read; a real "not deployed" still surfaces as before). Pure (no AWS) + exported
16069
+ * for unit tests.
16070
+ */
16071
+ function classifyAccountMismatch(declaredAccount, callerAccount) {
16072
+ if (declaredAccount && callerAccount && declaredAccount !== callerAccount) return {
16073
+ skip: true,
16074
+ message: `stack is pinned to account ${declaredAccount} but the active credentials are for account ${callerAccount} — skipped (run with account-${declaredAccount} credentials to check it)`
16075
+ };
16076
+ return {
16077
+ skip: false,
16078
+ message: ""
16079
+ };
16080
+ }
15973
16081
  function safeStringifyJson(value) {
15974
16082
  const seen = /* @__PURE__ */ new WeakSet();
15975
16083
  const replacer = (_key, v) => {
@@ -16058,7 +16166,14 @@ async function runCheck(args) {
16058
16166
  const showProgress = !a.json && isInteractive();
16059
16167
  let callerAccount;
16060
16168
  let callerAccountResolved = false;
16061
- for (const [idx, { stackName, region, template }] of stacks.entries()) {
16169
+ const ensureCallerAccount = async (region) => {
16170
+ if (!callerAccountResolved) {
16171
+ callerAccount = await resolveCallerAccount(region);
16172
+ callerAccountResolved = true;
16173
+ }
16174
+ return callerAccount;
16175
+ };
16176
+ for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
16062
16177
  if (!region) {
16063
16178
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
16064
16179
  console.error(`error: ${stackName}: ${msg}`);
@@ -16068,6 +16183,13 @@ async function runCheck(args) {
16068
16183
  }
16069
16184
  const posPrefix = a.json ? "" : positionPrefix(idx, stacks.length);
16070
16185
  try {
16186
+ const mismatch = classifyAccountMismatch(account, await ensureCallerAccount(region));
16187
+ if (mismatch.skip) {
16188
+ console.error(`note: ${stackName}: ${mismatch.message}`);
16189
+ jsonError(stackName, region, mismatch.message);
16190
+ worst = Math.max(worst, a.strict ? 1 : 0);
16191
+ continue;
16192
+ }
16071
16193
  const sKey = synthKey(stackName, region);
16072
16194
  if (synthTemplates && !synthTemplates.has(sKey)) {
16073
16195
  console.error(`note: ${stackName}: not in the synth output — skipped (--pre-deploy)`);
@@ -16078,6 +16200,13 @@ async function runCheck(args) {
16078
16200
  const gathered = await gatherWithProgress(showProgress, progressLabel(idx, stacks.length, stackName, region), () => gatherFindings(stackName, region, synthTemplates?.get(sKey), template));
16079
16201
  const { desired, schemas, liveByLogical } = gathered;
16080
16202
  let findings = gathered.findings;
16203
+ if (account && desired.accountId !== account) {
16204
+ const msg = `compared against account ${desired.accountId} but the stack is pinned to ${account} — skipped (run with account-${account} credentials to check it)`;
16205
+ console.error(`note: ${stackName}: ${msg}`);
16206
+ jsonError(stackName, region, msg);
16207
+ worst = Math.max(worst, a.strict ? 1 : 0);
16208
+ continue;
16209
+ }
16081
16210
  const nestedWarn = nestedStackWarning(desired.resources, stackName);
16082
16211
  if (nestedWarn) console.error(nestedWarn);
16083
16212
  if (a.json) {
@@ -16178,10 +16307,7 @@ async function runCheck(args) {
16178
16307
  worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources));
16179
16308
  } catch (e) {
16180
16309
  if (isStackNotDeployed(e)) {
16181
- if (!callerAccountResolved) {
16182
- callerAccount = await resolveCallerAccount(region);
16183
- callerAccountResolved = true;
16184
- }
16310
+ await ensureCallerAccount(region);
16185
16311
  if (hasBaselineForStack(stackName, region, callerAccount)) {
16186
16312
  const msg = "deployed baseline exists but the stack is gone — deleted out of band";
16187
16313
  const label = `${stackName} (${region})`;