cdk-real-drift 0.2.27 → 0.2.29

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/README.md CHANGED
@@ -663,7 +663,13 @@ place, since Cloud Control has no handler for the type),
663
663
  `config:DescribeConfigRules` / `config:PutConfigRule`,
664
664
  `ecs:UpdateService` (reverts an `AWS::ECS::Service` `ServiceConnectConfiguration` /
665
665
  `VolumeConfigurations` drift — the whole writeOnly prop is re-supplied, since Cloud
666
- Control cannot sub-path patch it).
666
+ Control cannot sub-path patch it),
667
+ `apigateway:UpdateStage` (reverts an `AWS::ApiGatewayV2::Stage` — an `autoDeploy`
668
+ stage rejects the `DeploymentId` the Cloud Control handler injects, so only the
669
+ drifted stage properties are written directly, never `DeploymentId`),
670
+ `apigateway:UpdateRestApi` (reverts an `AWS::ApiGateway::RestApi` `Policy` — the
671
+ whole desired resource policy is re-serialized and replaced, since Cloud Control
672
+ holds the policy as a JSON string it cannot sub-path patch).
667
673
 
668
674
  </details>
669
675
 
package/dist/cli.js CHANGED
@@ -7,10 +7,10 @@ import { CloudControlClient, DeleteResourceCommand, GetResourceCommand, GetResou
7
7
  import { BaseCredentials, CdkAppMultiContext, NonInteractiveIoHost, Toolkit } from "@aws-cdk/toolkit-lib";
8
8
  import { CloudFormationClient, DescribeStacksCommand, DescribeTypeCommand, GetTemplateCommand, ListExportsCommand, ListStackResourcesCommand } from "@aws-sdk/client-cloudformation";
9
9
  import { KMSClient, ListAliasesCommand } from "@aws-sdk/client-kms";
10
- import { APIGatewayClient, GetAuthorizersCommand, GetGatewayResponsesCommand, GetModelsCommand, GetRequestValidatorsCommand, GetResourcesCommand, UpdateIntegrationCommand, UpdateIntegrationResponseCommand, UpdateMethodResponseCommand } from "@aws-sdk/client-api-gateway";
10
+ import { APIGatewayClient, GetAuthorizersCommand, GetGatewayResponsesCommand, GetModelsCommand, GetRequestValidatorsCommand, GetResourcesCommand, UpdateIntegrationCommand, UpdateIntegrationResponseCommand, UpdateMethodResponseCommand, UpdateRestApiCommand } from "@aws-sdk/client-api-gateway";
11
11
  import { AppConfigClient, ListConfigurationProfilesCommand, ListEnvironmentsCommand } from "@aws-sdk/client-appconfig";
12
12
  import { AppSyncClient, ListApiKeysCommand, ListDataSourcesCommand, ListFunctionsCommand, ListResolversCommand, ListTypesCommand } from "@aws-sdk/client-appsync";
13
- import { ApiGatewayV2Client, GetAuthorizersCommand as GetAuthorizersCommand$1, GetIntegrationsCommand, GetRoutesCommand, GetStagesCommand } from "@aws-sdk/client-apigatewayv2";
13
+ import { ApiGatewayV2Client, GetAuthorizersCommand as GetAuthorizersCommand$1, GetIntegrationsCommand, GetRoutesCommand, GetStagesCommand, UpdateStageCommand } from "@aws-sdk/client-apigatewayv2";
14
14
  import { CloudWatchLogsClient, DescribeMetricFiltersCommand, DescribeSubscriptionFiltersCommand, PutBearerTokenAuthenticationCommand, PutMetricFilterCommand } from "@aws-sdk/client-cloudwatch-logs";
15
15
  import { CognitoIdentityProviderClient, ListGroupsCommand, ListResourceServersCommand, ListUserPoolClientsCommand } from "@aws-sdk/client-cognito-identity-provider";
16
16
  import { DescribeAddressesCommand, DescribeClientVpnAuthorizationRulesCommand, DescribeClientVpnEndpointsCommand, DescribeClientVpnTargetNetworksCommand, DescribeLaunchTemplateVersionsCommand, DescribeNetworkAclsCommand, DescribeRouteTablesCommand, DescribeSubnetsCommand, EC2Client, ModifyClientVpnEndpointCommand } from "@aws-sdk/client-ec2";
@@ -2184,6 +2184,7 @@ const VALUE_INDEPENDENT_DEFAULT_TOPLEVEL_PATHS = {
2184
2184
  "AWS::EC2::EIP": new Set(["NetworkBorderGroup"]),
2185
2185
  "AWS::EC2::VPCEndpoint": new Set(["ServiceRegion", "DnsOptions"]),
2186
2186
  "AWS::EC2::VPCPeeringConnection": new Set(["PeerRegion"]),
2187
+ "AWS::EC2::VPCCidrBlock": new Set(["Ipv6CidrBlock", "Ipv6CidrBlockNetworkBorderGroup"]),
2187
2188
  "AWS::Grafana::Workspace": new Set(["GrafanaVersion"]),
2188
2189
  "AWS::Bedrock::AgentAlias": new Set(["RoutingConfiguration"]),
2189
2190
  "AWS::AppSync::ApiKey": new Set(["Expires"]),
@@ -8507,13 +8508,22 @@ async function loadBaseline(stackName, accountId, region) {
8507
8508
  function sortRecorded(recorded) {
8508
8509
  return [...recorded].sort((a, b) => (a.logicalId < b.logicalId ? -1 : a.logicalId > b.logicalId ? 1 : 0) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
8509
8510
  }
8511
+ /** #674: keep only physical ids for logicalIds that still carry a recorded entry, with
8512
+ * sorted keys, so the baseline JSON is byte-stable and free of dead entries. */
8513
+ function sortedPhysicalIds(ids, recorded) {
8514
+ const live = new Set(recorded.map((e) => e.logicalId));
8515
+ const out = {};
8516
+ for (const key of Object.keys(ids).sort()) if (live.has(key) && ids[key] !== void 0) out[key] = ids[key];
8517
+ return out;
8518
+ }
8510
8519
  async function writeBaselineFile(b) {
8511
8520
  const p = baselinePath(b.stackName, b.accountId, b.region);
8512
8521
  await mkdir(dirname(p), { recursive: true });
8513
8522
  const stable = {
8514
8523
  ...b,
8515
8524
  recorded: sortRecorded(b.recorded),
8516
- ...b.completeResources ? { completeResources: [...b.completeResources].sort() } : {}
8525
+ ...b.completeResources ? { completeResources: [...b.completeResources].sort() } : {},
8526
+ ...b.recordedPhysicalIds ? { recordedPhysicalIds: sortedPhysicalIds(b.recordedPhysicalIds, b.recorded) } : {}
8517
8527
  };
8518
8528
  await writeFile(p, JSON.stringify(stable, null, 2) + "\n", "utf8");
8519
8529
  return p;
@@ -8559,12 +8569,30 @@ async function writeBaseline(stackName, region, accountId, findings, rawTemplate
8559
8569
  capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
8560
8570
  templateHash: hashTemplate(rawTemplate),
8561
8571
  recorded,
8562
- completeResources: computeCompleteResources(allIds, findings, recorded, opts.previous?.completeResources ?? [])
8572
+ completeResources: computeCompleteResources(allIds, findings, recorded, opts.previous?.completeResources ?? []),
8573
+ ...buildRecordedPhysicalIds(recorded, opts.physicalIdByLogical, opts.previous)
8563
8574
  }),
8564
8575
  count: recorded.length
8565
8576
  };
8566
8577
  }
8567
8578
  /**
8579
+ * #674: build the `recordedPhysicalIds` map (logicalId -> physical id) for the entries
8580
+ * being written. Prefers the physical id resolved THIS run; falls back to the previous
8581
+ * baseline's stored id when this run did not resolve one (a resource skipped / with no
8582
+ * physical id must not lose its previously-captured id on re-record — else a later
8583
+ * replacement could not be detected). Returns `{}` (spread to nothing) when no id is
8584
+ * known, so the field stays absent on baselines with no physical ids at all.
8585
+ */
8586
+ function buildRecordedPhysicalIds(recorded, live, previous) {
8587
+ const prior = previous?.recordedPhysicalIds ?? {};
8588
+ const out = {};
8589
+ for (const e of recorded) {
8590
+ const id = live?.get(e.logicalId) ?? prior[e.logicalId];
8591
+ if (id !== void 0) out[e.logicalId] = id;
8592
+ }
8593
+ return Object.keys(out).length > 0 ? { recordedPhysicalIds: out } : {};
8594
+ }
8595
+ /**
8568
8596
  * Per-account guard (secondary defense). The baseline filename now embeds the
8569
8597
  * accountId, so a correctly-named file always matches; this guard catches a file
8570
8598
  * that was hand-copied or renamed to the wrong account's path (its `accountId`
@@ -8756,6 +8784,13 @@ function applyBaseline(findings, baseline, opts = {}) {
8756
8784
  const recorded = baseline.recorded;
8757
8785
  const complete = new Set(baseline.completeResources ?? []);
8758
8786
  const kept = [];
8787
+ const currentLogicalIds = opts.allLogicalIds === void 0 ? void 0 : Array.isArray(opts.allLogicalIds) ? new Set(opts.allLogicalIds) : opts.allLogicalIds;
8788
+ const recordedPhysIds = baseline.recordedPhysicalIds ?? {};
8789
+ const replacedLogical = /* @__PURE__ */ new Set();
8790
+ for (const [logicalId, recordedId] of Object.entries(recordedPhysIds)) {
8791
+ const liveId = opts.physicalIdByLogical?.get(logicalId);
8792
+ if (liveId !== void 0 && liveId !== recordedId) replacedLogical.add(logicalId);
8793
+ }
8759
8794
  for (const f of findings) {
8760
8795
  if (f.tier === "added") {
8761
8796
  const entry = recorded.find((a) => a.logicalId === f.logicalId && a.path === f.path);
@@ -8786,7 +8821,7 @@ function applyBaseline(findings, baseline, opts = {}) {
8786
8821
  kept.push(f);
8787
8822
  continue;
8788
8823
  }
8789
- const entry = recorded.find((a) => a.logicalId === f.logicalId && a.path === f.path);
8824
+ const entry = replacedLogical.has(f.logicalId) ? void 0 : recorded.find((a) => a.logicalId === f.logicalId && a.path === f.path);
8790
8825
  if (entry && baselineValueMatches(entry.value, f.actual)) continue;
8791
8826
  if (entry) {
8792
8827
  const delta = identityArrayDelta(canonicalizeForCompare(entry.value), f.actual);
@@ -8801,7 +8836,7 @@ function applyBaseline(findings, baseline, opts = {}) {
8801
8836
  kept.push(f);
8802
8837
  continue;
8803
8838
  }
8804
- if (complete.has(f.logicalId)) kept.push({
8839
+ if (complete.has(f.logicalId) && !replacedLogical.has(f.logicalId)) kept.push({
8805
8840
  ...f,
8806
8841
  note: f.note ? `${f.note}; appeared since record` : "appeared since record"
8807
8842
  });
@@ -8822,12 +8857,22 @@ function applyBaseline(findings, baseline, opts = {}) {
8822
8857
  }
8823
8858
  const underDeclaredDrift = (logicalId, path) => (declaredDriftByLogical.get(logicalId) ?? []).some((p) => path === p || path.startsWith(`${p}.`) || path.startsWith(`${p}[`));
8824
8859
  const promotedStale = [];
8860
+ const removedFromTemplate = [];
8861
+ const replacedStale = [];
8825
8862
  for (const a of recorded) {
8826
8863
  if (a.path === "") continue;
8864
+ if (replacedLogical.has(a.logicalId)) {
8865
+ replacedStale.push(`${a.logicalId}.${a.path}`);
8866
+ continue;
8867
+ }
8827
8868
  if (currentPaths.has(`${a.logicalId}.${a.path}`)) continue;
8828
8869
  if (skippedLogical.has(a.logicalId)) continue;
8829
8870
  if (deletedLogical.has(a.logicalId)) continue;
8830
8871
  if (underDeclaredDrift(a.logicalId, a.path)) continue;
8872
+ if (currentLogicalIds !== void 0 && !currentLogicalIds.has(a.logicalId)) {
8873
+ removedFromTemplate.push(`${a.logicalId}.${a.path}`);
8874
+ continue;
8875
+ }
8831
8876
  if (opts.declaredByLogical?.get(a.logicalId)?.has(topSegment(a.path))) {
8832
8877
  promotedStale.push(`${a.logicalId}.${a.path}`);
8833
8878
  continue;
@@ -8845,6 +8890,8 @@ function applyBaseline(findings, baseline, opts = {}) {
8845
8890
  });
8846
8891
  }
8847
8892
  if (promotedStale.length > 0) opts.warn?.(formatPromotedStaleNote(promotedStale));
8893
+ if (removedFromTemplate.length > 0) opts.warn?.(formatRemovedFromTemplateNote(removedFromTemplate));
8894
+ if (replacedStale.length > 0) opts.warn?.(formatReplacedStaleNote(replacedStale));
8848
8895
  return kept;
8849
8896
  }
8850
8897
  /**
@@ -8856,6 +8903,24 @@ function formatPromotedStaleNote(paths) {
8856
8903
  const n = paths.length;
8857
8904
  return `note: ${n === 1 ? `baseline entry (${paths[0]}) is` : `${n} baseline entries are`} now declared in the template — re-run \`cdkrd record\` to clean ${n === 1 ? "it" : "them"} up.`;
8858
8905
  }
8906
+ /**
8907
+ * #675: the folded one-line note for baseline entries whose resource is no longer in
8908
+ * the template at all (legitimately removed from IaC and deleted by the deploy). Mirror
8909
+ * of formatPromotedStaleNote. Pure + exported for unit tests.
8910
+ */
8911
+ function formatRemovedFromTemplateNote(paths) {
8912
+ const n = paths.length;
8913
+ return `note: ${n === 1 ? `baseline entry (${paths[0]}) belongs` : `${n} baseline entries belong`} to resources no longer in the template — re-run \`cdkrd record\` to clean them up.`;
8914
+ }
8915
+ /**
8916
+ * #674: the folded one-line note for baseline entries recorded against a resource that a
8917
+ * deploy has since REPLACED (new physical id). Mirror of formatPromotedStaleNote. Pure +
8918
+ * exported for unit tests.
8919
+ */
8920
+ function formatReplacedStaleNote(paths) {
8921
+ const n = paths.length;
8922
+ return `note: ${n === 1 ? `baseline entry (${paths[0]}) was` : `${n} baseline entries were`} recorded against a resource since REPLACED by a deploy — re-run \`cdkrd record\`.`;
8923
+ }
8859
8924
  /** logicalId -> set of declared top-level keys, for applyBaseline's promotion check. */
8860
8925
  function declaredKeysByLogical(resources) {
8861
8926
  return new Map(resources.map((r) => [r.logicalId, new Set(Object.keys(r.declared))]));
@@ -10337,7 +10402,49 @@ const writeKinesisVideoStreamStorage = async (ctx, ops) => {
10337
10402
  StreamStorageConfiguration: { DefaultStorageTier: target }
10338
10403
  }));
10339
10404
  };
10405
+ const APIGWV2_STAGE_UPDATE_FIELDS = new Set([
10406
+ "DefaultRouteSettings",
10407
+ "RouteSettings",
10408
+ "AccessLogSettings",
10409
+ "Description",
10410
+ "StageVariables",
10411
+ "ClientCertificateId",
10412
+ "AutoDeploy"
10413
+ ]);
10414
+ const writeApiGatewayV2Stage = async (ctx, ops) => {
10415
+ const [apiIdFromComposite, stageFromComposite] = (ctx.identifier ?? "").split("|");
10416
+ const apiId = str(apiIdFromComposite) ?? str(ctx.declared["ApiId"]);
10417
+ const stageName = str(stageFromComposite) ?? str(ctx.physicalId) ?? str(ctx.declared["StageName"]);
10418
+ if (!apiId || !stageName) throw new Error("cannot resolve ApiId|StageName for ApiGatewayV2 Stage revert");
10419
+ const desired = applyOps({ ...ctx.declared }, ops);
10420
+ const touched = new Set(ops.map((o) => o.path.replace(/^\//, "").split("/")[0]).filter((p) => !!p));
10421
+ const input = {
10422
+ ApiId: apiId,
10423
+ StageName: stageName
10424
+ };
10425
+ for (const p of touched) {
10426
+ if (!APIGWV2_STAGE_UPDATE_FIELDS.has(p)) continue;
10427
+ input[p] = desired[p];
10428
+ }
10429
+ if (Object.keys(input).length <= 2) return;
10430
+ await new ApiGatewayV2Client({ region: ctx.region }).send(new UpdateStageCommand(input));
10431
+ };
10432
+ const writeApiGatewayRestApiPolicy = async (ctx) => {
10433
+ const restApiId = str(ctx.physicalId) ?? str(ctx.declared["RestApiId"]);
10434
+ if (!restApiId) throw new Error("cannot resolve RestApiId for RestApi Policy revert");
10435
+ const declaredPolicy = ctx.declared["Policy"];
10436
+ const value = declaredPolicy === void 0 || declaredPolicy === null ? "" : typeof declaredPolicy === "string" ? declaredPolicy : JSON.stringify(declaredPolicy);
10437
+ await new APIGatewayClient({ region: ctx.region }).send(new UpdateRestApiCommand({
10438
+ restApiId,
10439
+ patchOperations: [{
10440
+ op: "replace",
10441
+ path: "/policy",
10442
+ value
10443
+ }]
10444
+ }));
10445
+ };
10340
10446
  const SDK_WRITERS = {
10447
+ "AWS::ApiGatewayV2::Stage": writeApiGatewayV2Stage,
10341
10448
  "AWS::ElasticBeanstalk::Application": writeElasticBeanstalkApplication,
10342
10449
  "AWS::ElasticBeanstalk::Environment": writeElasticBeanstalkEnvironment,
10343
10450
  "AWS::CodeBuild::ReportGroup": writeCodeBuildReportGroup,
@@ -10463,6 +10570,10 @@ const SDK_NESTED_WRITERS = {
10463
10570
  match: (p) => p.startsWith("MethodSettings["),
10464
10571
  writer: writeCloudControlIndexNested
10465
10572
  },
10573
+ "AWS::ApiGateway::RestApi": {
10574
+ match: (p) => p === "Policy" || p.startsWith("Policy.") || p.startsWith("Policy["),
10575
+ writer: writeApiGatewayRestApiPolicy
10576
+ },
10466
10577
  "AWS::Lex::Bot": {
10467
10578
  match: (p) => p === "BotLocales" || p.startsWith("BotLocales.") || p.startsWith("BotLocales["),
10468
10579
  writer: writeLexBotLocales
@@ -11220,7 +11331,8 @@ async function recordStack(p) {
11220
11331
  }
11221
11332
  const { path, count } = await writeBaseline(stackName, region, desired.accountId, findings, desired.rawTemplate, recorded, {
11222
11333
  allLogicalIds: desired.resources.map((r) => r.logicalId),
11223
- previous: existing
11334
+ previous: existing,
11335
+ physicalIdByLogical: physicalIdsByLogical(desired.resources)
11224
11336
  });
11225
11337
  console.log(style.ok(recordOutcomeMessage(stackName, path, count, refreshedOnly, !!existing)));
11226
11338
  const scopeNote = recordScopeNote(stackName, findings);
@@ -11405,7 +11517,8 @@ async function revertStack(p) {
11405
11517
  const baselineOpts = {
11406
11518
  declaredByLogical: declaredKeysByLogical(gathered.desired.resources),
11407
11519
  physicalIdByLogical: physicalIdsByLogical(gathered.desired.resources),
11408
- constructPathByLogical: constructPathsByLogical(gathered.desired.resources)
11520
+ constructPathByLogical: constructPathsByLogical(gathered.desired.resources),
11521
+ allLogicalIds: gathered.desired.resources.map((r) => r.logicalId)
11409
11522
  };
11410
11523
  const drifted = applyIgnores(applyBaseline(gathered.findings, baseline, {
11411
11524
  ...baselineOpts,
@@ -11737,6 +11850,8 @@ async function runIgnore(args) {
11737
11850
  stackName,
11738
11851
  findings: applyIgnores(applyBaseline(findings, baseline, {
11739
11852
  declaredByLogical: declaredKeysByLogical(desired.resources),
11853
+ physicalIdByLogical: physicalIdsByLogical(desired.resources),
11854
+ allLogicalIds: desired.resources.map((r) => r.logicalId),
11740
11855
  warn: console.error
11741
11856
  }), {
11742
11857
  stackName,
@@ -12292,7 +12407,8 @@ async function chooseScope(stackName, shownCount, foldedCount, yes) {
12292
12407
  const baselineOpts = (p) => ({
12293
12408
  declaredByLogical: declaredKeysByLogical(p.desired.resources),
12294
12409
  constructPathByLogical: constructPathsByLogical(p.desired.resources),
12295
- physicalIdByLogical: physicalIdsByLogical(p.desired.resources)
12410
+ physicalIdByLogical: physicalIdsByLogical(p.desired.resources),
12411
+ allLogicalIds: p.desired.resources.map((r) => r.logicalId)
12296
12412
  });
12297
12413
  /**
12298
12414
  * Re-evaluate check's exit WITHOUT re-reading AWS: reload the (possibly just-written)
@@ -12689,6 +12805,7 @@ async function runCheck(args) {
12689
12805
  declaredByLogical: declaredKeysByLogical(desired.resources),
12690
12806
  constructPathByLogical: constructPathsByLogical(desired.resources),
12691
12807
  physicalIdByLogical: physicalIdsByLogical(desired.resources),
12808
+ allLogicalIds: desired.resources.map((r) => r.logicalId),
12692
12809
  warn: (s) => {
12693
12810
  if (!a.json) console.error(s);
12694
12811
  }