cdk-real-drift 0.3.8 → 0.3.10

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
@@ -744,12 +744,23 @@ function parseIgnoreRule(entry) {
744
744
  * structured property covers its leaves, including array / identity-keyed elements), and a
745
745
  * rule "MyApi/Res" covers its whole construct-path subtree "MyApi/Res/Method.Prop".
746
746
  * Parent matching walks ancestors at each `.`, `[`, OR `/` boundary, combined with the glob.
747
+ *
748
+ * `wholeResource` marks an atomic, whole-resource target (an `added` finding — empty property
749
+ * path, so the target is just `<parentLogicalId>/<CC-identifier>`). Such a target has NO
750
+ * property subtree: the `.` / `[` inside it are DATA within the CC identifier
751
+ * (`example.com`, an ARN, `a[0]`), never property separators. Trimming there would walk into
752
+ * a DIFFERENT sibling resource whose identifier is this one extended by `.` / `[`
753
+ * (`MyApi/a` wrongly swallowing `MyApi/a.b`, `MyApi/a[0]`) — a silent over-suppression of the
754
+ * `added` out-of-band feature (issue #990). So in this mode the ancestor walk trims ONLY at
755
+ * `/` boundaries, which alone mark a resource boundary: a bare PARENT-resource rule (`MyLb`)
756
+ * still covers its added children across `/` (e.g. a listener child whose id is an ARN full
757
+ * of `/`, issue #903), while a rule for one whole resource can no longer reach a sibling.
747
758
  */
748
- function pathMatches(pattern, target) {
759
+ function pathMatches(pattern, target, wholeResource = false) {
749
760
  if (matchesPathGlob(pattern, target)) return true;
750
761
  let t = target;
751
762
  while (true) {
752
- const cut = Math.max(t.lastIndexOf("."), t.lastIndexOf("["), t.lastIndexOf("/"));
763
+ const cut = wholeResource ? t.lastIndexOf("/") : Math.max(t.lastIndexOf("."), t.lastIndexOf("["), t.lastIndexOf("/"));
753
764
  if (cut <= 0) break;
754
765
  t = t.slice(0, cut);
755
766
  if (matchesPathGlob(pattern, t)) return true;
@@ -763,12 +774,13 @@ function applyIgnores(findings, scope, config) {
763
774
  return findings.map((f) => {
764
775
  if (f.tier !== "declared" && f.tier !== "undeclared" && f.tier !== "added") return f;
765
776
  const suffix = f.path ? `.${f.path}` : "";
777
+ const wholeResource = f.tier === "added";
766
778
  const targets = [`${f.logicalId}${suffix}`];
767
779
  if (f.constructPath) {
768
780
  targets.push(`${withinStackPath(f.constructPath, stackName)}${suffix}`);
769
781
  targets.push(`${f.constructPath}${suffix}`);
770
782
  }
771
- const hit = rules.find((r) => (r.stackGlob === void 0 || matchesGlob(r.stackGlob, stackName)) && (r.accountGlob === void 0 || matchesGlob(r.accountGlob, accountId)) && (r.regionGlob === void 0 || matchesGlob(r.regionGlob, region)) && targets.some((t) => pathMatches(r.pathPattern, t)));
783
+ const hit = rules.find((r) => (r.stackGlob === void 0 || matchesGlob(r.stackGlob, stackName)) && (r.accountGlob === void 0 || matchesGlob(r.accountGlob, accountId)) && (r.regionGlob === void 0 || matchesGlob(r.regionGlob, region)) && targets.some((t) => pathMatches(r.pathPattern, t, wholeResource)));
772
784
  if (!hit) return f;
773
785
  const { unrecorded: _unrecorded, ...rest } = f;
774
786
  return {
@@ -2640,7 +2652,7 @@ const VALUE_INDEPENDENT_DEFAULT_TOPLEVEL_PATHS = {
2640
2652
  "AWS::EKS::AccessEntry": new Set(["Username"]),
2641
2653
  "AWS::Glue::Job": new Set(["MaxCapacity", "AllocatedCapacity"]),
2642
2654
  "AWS::EC2::SecurityGroupIngress": new Set(["SourceSecurityGroupName"]),
2643
- "AWS::EC2::SecurityGroupEgress": new Set(["SourceSecurityGroupName"]),
2655
+ "AWS::EC2::SecurityGroupEgress": new Set(["DestinationSecurityGroupName"]),
2644
2656
  "AWS::DocDB::DBCluster": new Set(["PreferredMaintenanceWindow", "PreferredBackupWindow"]),
2645
2657
  "AWS::DocDB::DBInstance": new Set(["PreferredMaintenanceWindow"]),
2646
2658
  "AWS::Neptune::DBCluster": new Set(["PreferredMaintenanceWindow", "PreferredBackupWindow"]),
@@ -4385,8 +4397,13 @@ function stripInjectedJsonStringDefaults(declared, live, defaults) {
4385
4397
  return stripObject(declared, live);
4386
4398
  }
4387
4399
  function isCfnGeneratedName(value, constructPath, physicalId, logicalId) {
4388
- if (typeof value !== "string" || !constructPath || value === physicalId) return false;
4400
+ if (typeof value !== "string" || value === physicalId) return false;
4389
4401
  if (logicalId && value === logicalId) return true;
4402
+ if (logicalId && CFN_RANDOM_SUFFIX.test(value)) {
4403
+ const base = value.replace(CFN_RANDOM_SUFFIX, "");
4404
+ if (base.length > logicalId.length && base.endsWith(`-${logicalId}`)) return true;
4405
+ }
4406
+ if (!constructPath) return false;
4390
4407
  const stackName = constructPath.split("/")[0];
4391
4408
  if (!stackName || !CFN_RANDOM_SUFFIX.test(value)) return false;
4392
4409
  if (value.startsWith(`${stackName}-`)) return true;
@@ -7084,7 +7101,7 @@ const readIamAccessKey = async ({ declared, physicalId, region }) => {
7084
7101
  region,
7085
7102
  ...READ_RETRY
7086
7103
  }).send(new ListAccessKeysCommand({ UserName: userName }))).AccessKeyMetadata ?? []).find((m) => m.AccessKeyId === physicalId);
7087
- if (!meta) return void 0;
7104
+ if (!meta) throw new ResourceGoneError(`AccessKey ${physicalId} absent from user ${userName}`);
7088
7105
  return {
7089
7106
  UserName: userName,
7090
7107
  Status: meta.Status
@@ -8112,8 +8129,12 @@ const readAppSyncApiKey = async ({ physicalId, declared, region }) => {
8112
8129
  if (keyId) k = keys.find((x) => x.id === keyId);
8113
8130
  nextToken = r.nextToken;
8114
8131
  } while (!k && nextToken);
8115
- if (!keyId) k = keys[0];
8116
- if (!k) return void 0;
8132
+ if (keyId) {
8133
+ if (!k) throw new ResourceGoneError(`AppSync ApiKey ${keyId} absent from API ${apiId}`);
8134
+ } else {
8135
+ k = keys[0];
8136
+ if (!k) return void 0;
8137
+ }
8117
8138
  const model = { ApiId: apiId };
8118
8139
  if (k.description !== void 0 && k.description !== "") model.Description = k.description;
8119
8140
  if (k.expires !== void 0) model.Expires = k.expires;
@@ -9017,7 +9038,16 @@ const CC_IDENTIFIER_ADAPTERS = {
9017
9038
  const integrationId = declared.IntegrationId;
9018
9039
  return typeof apiId === "string" && apiId.length > 0 && typeof integrationId === "string" && integrationId.length > 0 ? `${apiId}|${integrationId}|${pid}` : void 0;
9019
9040
  },
9020
- "AWS::GuardDuty::Filter": compositeWith("DetectorId")
9041
+ "AWS::GuardDuty::Filter": compositeWith("DetectorId"),
9042
+ "AWS::Events::Rule": (pid, declared, region, account) => {
9043
+ const bar = pid.lastIndexOf("|");
9044
+ if (bar < 0) return pid;
9045
+ const busName = pid.slice(0, bar);
9046
+ const ruleName = pid.slice(bar + 1);
9047
+ const busArn = declared.EventBusName;
9048
+ if (typeof busArn === "string" && busArn.includes(":event-bus/")) return `${busArn.replace(":event-bus/", ":rule/")}/${ruleName}`;
9049
+ if (region && account) return `arn:${region.startsWith("cn-") ? "aws-cn" : region.startsWith("us-gov-") ? "aws-us-gov" : "aws"}:events:${region}:${account}:rule/${busName}/${ruleName}`;
9050
+ }
9021
9051
  };
9022
9052
  function scalingPolicyComposite(pid, declared) {
9023
9053
  if (pid.includes("|")) return pid;
@@ -9060,7 +9090,7 @@ async function readLive(cc, resource, region, accountId) {
9060
9090
  return { skippedReason: `SDK override (${resourceType}): ${e.name}` };
9061
9091
  }
9062
9092
  try {
9063
- const identifier = CC_IDENTIFIER_ADAPTERS[resourceType]?.(physicalId ?? "", declared) ?? physicalId ?? "";
9093
+ const identifier = CC_IDENTIFIER_ADAPTERS[resourceType]?.(physicalId ?? "", declared, region, accountId) ?? physicalId ?? "";
9064
9094
  const g = await cc.send(new GetResourceCommand({
9065
9095
  TypeName: resourceType,
9066
9096
  Identifier: identifier
@@ -10399,10 +10429,11 @@ const writeDocDbCluster = async (ctx, ops) => {
10399
10429
  let any = false;
10400
10430
  for (const op of ops) {
10401
10431
  const top = op.path.replace(/^\//, "").split("/")[0];
10402
- if (top && DOCDB_CLUSTER_MODIFY_PARAMS.has(top) && desired[top] !== void 0) {
10403
- input[top] = desired[top];
10404
- any = true;
10405
- }
10432
+ if (!top || !DOCDB_CLUSTER_MODIFY_PARAMS.has(top)) continue;
10433
+ if (desired[top] !== void 0) input[top] = desired[top];
10434
+ else if (top === "DeletionProtection") input.DeletionProtection = false;
10435
+ else throw new Error(`DocDB DBCluster ${top} cannot be cleared via ModifyDBCluster (its unset state is AWS-assigned/required, not expressible in a selective modify); update it manually`);
10436
+ any = true;
10406
10437
  }
10407
10438
  if (!any) return;
10408
10439
  await new DocDBClient({ region: ctx.region }).send(new ModifyDBClusterCommand(input));
@@ -10424,10 +10455,11 @@ const writeDocDbInstance = async (ctx, ops) => {
10424
10455
  let any = false;
10425
10456
  for (const op of ops) {
10426
10457
  const top = op.path.replace(/^\//, "").split("/")[0];
10427
- if (top && DOCDB_INSTANCE_MODIFY_PARAMS.has(top) && desired[top] !== void 0) {
10428
- input[top] = desired[top];
10429
- any = true;
10430
- }
10458
+ if (!top || !DOCDB_INSTANCE_MODIFY_PARAMS.has(top)) continue;
10459
+ if (desired[top] !== void 0) input[top] = desired[top];
10460
+ else if (top === "EnablePerformanceInsights") input.EnablePerformanceInsights = false;
10461
+ else throw new Error(`DocDB DBInstance ${top} cannot be cleared via ModifyDBInstance (its unset state is AWS-assigned/required, not expressible in a selective modify); update it manually`);
10462
+ any = true;
10431
10463
  }
10432
10464
  if (!any) return;
10433
10465
  await new DocDBClient({ region: ctx.region }).send(new ModifyDBInstanceCommand(input));
@@ -11070,12 +11102,23 @@ const writeEc2ClientVpnEndpoint = async (ctx, ops) => {
11070
11102
  const input = { ClientVpnEndpointId: id };
11071
11103
  let any = false;
11072
11104
  const tops = new Set(ops.map((op) => op.path.replace(/^\//, "").split("/")[0] ?? ""));
11073
- for (const top of tops) if (CLIENT_VPN_SCALAR_PARAMS.has(top) && desired[top] !== void 0) {
11074
- input[top] = desired[top];
11075
- any = true;
11076
- } else if (top === "ConnectionLogOptions" && desired.ConnectionLogOptions !== void 0) {
11077
- input.ConnectionLogOptions = desired.ConnectionLogOptions;
11078
- any = true;
11105
+ const removed = (field) => ops.some((o) => o.op === "remove" && (o.path.replace(/^\//, "").split("/")[0] ?? "") === field);
11106
+ for (const top of tops) if (CLIENT_VPN_SCALAR_PARAMS.has(top)) {
11107
+ if (desired[top] !== void 0) {
11108
+ input[top] = desired[top];
11109
+ any = true;
11110
+ } else if (removed(top)) {
11111
+ if (top === "Description") input.Description = "";
11112
+ else if (top === "SplitTunnel") input.SplitTunnel = false;
11113
+ else if (top === "DisconnectOnSessionTimeout") input.DisconnectOnSessionTimeout = false;
11114
+ else throw new Error(`EC2 ClientVpnEndpoint ${top} cannot be cleared via ModifyClientVpnEndpoint (its unset state is not expressible in a selective modify); update it manually`);
11115
+ any = true;
11116
+ }
11117
+ } else if (top === "ConnectionLogOptions") {
11118
+ if (desired.ConnectionLogOptions !== void 0) {
11119
+ input.ConnectionLogOptions = desired.ConnectionLogOptions;
11120
+ any = true;
11121
+ } else if (removed("ConnectionLogOptions")) throw new Error("EC2 ClientVpnEndpoint ConnectionLogOptions cannot be cleared via ModifyClientVpnEndpoint (its unset state is not expressible in a selective modify); update it manually");
11079
11122
  } else if (top === "DnsServers") {
11080
11123
  const list = desired.DnsServers;
11081
11124
  input.DnsServers = Array.isArray(list) && list.length > 0 ? {
@@ -11090,7 +11133,7 @@ const writeEc2ClientVpnEndpoint = async (ctx, ops) => {
11090
11133
  input.SecurityGroupIds = list;
11091
11134
  input.VpcId = vpcId;
11092
11135
  any = true;
11093
- }
11136
+ } else if (removed("SecurityGroupIds")) throw new Error("EC2 ClientVpnEndpoint SecurityGroupIds cannot be cleared via ModifyClientVpnEndpoint (an endpoint cannot revert to no security group in a selective modify); update it manually");
11094
11137
  }
11095
11138
  if (!any) return;
11096
11139
  await new EC2Client({ region: ctx.region }).send(new ModifyClientVpnEndpointCommand(input));
@@ -14068,17 +14111,26 @@ function finalCheckExit(code, fail) {
14068
14111
  return fail || code !== 1 ? code : 0;
14069
14112
  }
14070
14113
  /**
14071
- * #781: does a committed baseline exist for this stack, under ANY account/region axis?
14072
- * When a stack is gone (a DescribeStacks "does not exist"), we do NOT know the
14073
- * account/region it was deployed to, so we cannot construct the exact baseline path.
14114
+ * #781: does a committed baseline exist for this stack IN THE REGION being checked?
14074
14115
  * A committed baseline is named `<stackName>.<accountId>.<region>.json` under
14075
- * `.cdkrd/baselines/`, so match by the `<stackName>.` filename prefix across the whole
14076
- * directory — a prior baseline is PROOF the stack was once deployed, which distinguishes
14077
- * "deleted out of band" (real drift) from "never deployed yet" (a benign skip). The
14078
- * baselines directory is derived from `baselinePath` so the layout stays single-sourced.
14116
+ * `.cdkrd/baselines/`. The gone stack's ACCOUNT is unknown without an STS call, so it
14117
+ * stays wildcarded; but the REGION being checked IS known (the loop's `region`), and a
14118
+ * baseline recorded for THIS stack in THIS region carries exactly that region in its
14119
+ * filename — so we require the `.<region>.json` suffix. A prior baseline in this region
14120
+ * is PROOF the stack was once deployed THERE, which distinguishes "deleted out of band"
14121
+ * (real drift) from "never deployed yet" (a benign skip). Without the region gate, a
14122
+ * same-named stack that was never deployed in region B but has a baseline in region A is
14123
+ * falsely reported "deleted out of band" (#942).
14124
+ *
14125
+ * #986: the match is CASE-INSENSITIVE (both sides lowercased) so it answers consistently
14126
+ * with `loadBaseline`, whose `readFile` opens the file case-insensitively on macOS/Windows.
14127
+ * A case-sensitive `readdirSync` prefix would MISS a baseline committed as `mystack.….json`
14128
+ * when checking `MyStack`, silently downgrading a genuinely deleted stack to a benign skip.
14129
+ *
14130
+ * The baselines directory is derived from `baselinePath` so the layout stays single-sourced.
14079
14131
  * Pure (filesystem-only, no AWS) + exported for unit tests. Missing dir → false.
14080
14132
  */
14081
- function hasBaselineForStack(stackName) {
14133
+ function hasBaselineForStack(stackName, region) {
14082
14134
  const dir = dirname(baselinePath(stackName, "a", "r"));
14083
14135
  let entries;
14084
14136
  try {
@@ -14087,7 +14139,11 @@ function hasBaselineForStack(stackName) {
14087
14139
  return false;
14088
14140
  }
14089
14141
  const prefix = `${stackName}.`.toLowerCase();
14090
- return entries.some((f) => f.toLowerCase().startsWith(prefix) && f.endsWith(".json"));
14142
+ const suffix = `.${region}.json`.toLowerCase();
14143
+ return entries.some((f) => {
14144
+ const lower = f.toLowerCase();
14145
+ return lower.startsWith(prefix) && lower.endsWith(suffix);
14146
+ });
14091
14147
  }
14092
14148
  async function runCheck(args) {
14093
14149
  const a = parseCommonArgs(args, "check");
@@ -14268,7 +14324,7 @@ async function runCheck(args) {
14268
14324
  worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources));
14269
14325
  } catch (e) {
14270
14326
  if (isStackNotDeployed(e)) {
14271
- if (hasBaselineForStack(stackName)) {
14327
+ if (hasBaselineForStack(stackName, region)) {
14272
14328
  const msg = "deployed baseline exists but the stack is gone — deleted out of band";
14273
14329
  const label = `${stackName} (${region})`;
14274
14330
  console.error(`[Drift] ${label}: ${msg}`);