cdk-real-drift 0.4.21 → 0.4.22

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
@@ -710,7 +710,10 @@ covers them. **If you never run `revert`, cdkrd needs no write permissions at al
710
710
  templates using `Fn::ImportValue`)
711
711
  - `cloudcontrol:GetResource`: Cloud Control invokes each type's own read handler,
712
712
  so it needs that type's read permissions (this is why `ReadOnlyAccess` is the
713
- simple answer)
713
+ simple answer). `revert` additionally uses `cloudcontrol:UpdateResource` /
714
+ `cloudcontrol:DeleteResource` (the latter to delete an out-of-band `added`
715
+ resource) and `cloudcontrol:GetResourceRequestStatus` to poll the async request —
716
+ see the revert section below.
714
717
  - SDK readers for the Cloud-Control-gap types: `s3:GetBucketPolicy`,
715
718
  `sns:GetTopicAttributes`, `sqs:GetQueueAttributes`, `iam:GetRolePolicy`,
716
719
  `iam:GetUserPolicy`, `iam:GetGroupPolicy`, `iam:GetPolicy`, `iam:GetPolicyVersion`,
@@ -776,9 +779,30 @@ covers them. **If you never run `revert`, cdkrd needs no write permissions at al
776
779
  full resolved option set; an out-of-band console edit to any environment option
777
780
  is otherwise invisible, and the service-filled default options fold to
778
781
  `atDefault`),
779
- `servicediscovery:GetNamespace` (reads a Cloud Map
782
+ `servicediscovery:GetNamespace` + `servicediscovery:GetService` (read a Cloud Map
780
783
  `HttpNamespace` / `PrivateDnsNamespace` / `PublicDnsNamespace` — incl. the Arn an
781
- ECS Service Connect namespace `Fn::GetAtt` resolves against)
784
+ ECS Service Connect namespace `Fn::GetAtt` resolves against — and a Cloud Map
785
+ `Service`),
786
+ `docdb:DescribeDBClusters` + `docdb:DescribeDBInstances` (read an
787
+ `AWS::DocDB::DBCluster` / `AWS::DocDB::DBInstance` — the whole DocumentDB family is
788
+ a Cloud Control read gap),
789
+ `codebuild:BatchGetProjects` (reads an `AWS::CodeBuild::Project`) +
790
+ `codebuild:BatchGetReportGroups` (reads an `AWS::CodeBuild::ReportGroup`),
791
+ `dax:DescribeClusters` + `dax:DescribeParameterGroups` + `dax:DescribeParameters` +
792
+ `dax:DescribeSubnetGroups` (read an `AWS::DAX::Cluster` / `ParameterGroup` /
793
+ `SubnetGroup` — the DynamoDB Accelerator family),
794
+ `ec2:DescribeClientVpnEndpoints` + `ec2:DescribeClientVpnAuthorizationRules` +
795
+ `ec2:DescribeClientVpnTargetNetworks` (read an `AWS::EC2::ClientVpnEndpoint` /
796
+ `ClientVpnAuthorizationRule` / `ClientVpnTargetNetworkAssociation`),
797
+ `iam:ListAccessKeys` (reads an `AWS::IAM::AccessKey`'s `Status`) +
798
+ `iam:ListEntitiesForPolicy` (enumerates a managed policy's attachments),
799
+ `appsync:ListApiKeys` (reads an `AWS::AppSync::ApiKey` — a Cloud Control gap),
800
+ `cognito-sync:GetCognitoEvents` (enriches the Cloud Control read of an
801
+ `AWS::Cognito::IdentityPool` with its writeOnly `CognitoEvents` Sync trigger),
802
+ `glue:GetClassifier` + `glue:GetWorkflow` + `glue:GetConnection`
803
+ (`glue:GetConnection` is issued with `HidePassword` so NO credential enters the
804
+ baseline — read an `AWS::Glue::Classifier` / `Workflow` / `Connection`, the rest
805
+ of the Glue family that has no Cloud Control handler)
782
806
  - Optional: `elasticloadbalancing:GetTrustStoreCaCertificatesBundle` records a
783
807
  content hash of an `AWS::ElasticLoadBalancingV2::TrustStore`'s live mTLS CA
784
808
  bundle (`CaCertificatesBundleSha256`) so an out-of-band CA-bundle swap
@@ -839,8 +863,12 @@ covers them. **If you never run `revert`, cdkrd needs no write permissions at al
839
863
  <summary>Additional write permissions (revert)</summary>
840
864
 
841
865
  `cloudcontrol:UpdateResource` (which resolves to each type's own update
842
- permissions), plus, for the SDK-written types: `s3:PutBucketPolicy` /
866
+ permissions), `cloudcontrol:DeleteResource` (to delete an out-of-band `added`
867
+ resource), and `cloudcontrol:GetResourceRequestStatus` (to poll the async Cloud
868
+ Control request to completion). Plus, for the SDK-written types:
869
+ `s3:PutBucketPolicy` /
843
870
  `s3:DeleteBucketPolicy`, `sns:SetTopicAttributes`, `sqs:SetQueueAttributes`,
871
+ `events:PutPermission` (reverts an `AWS::Events::EventBusPolicy`),
844
872
  `iam:PutRolePolicy` / `DeleteRolePolicy` / `PutUserPolicy` / `PutGroupPolicy`,
845
873
  `iam:CreatePolicyVersion` / `DeletePolicyVersion` / `ListPolicyVersions`,
846
874
  `elasticloadbalancing:ModifyLoadBalancerAttributes` / `ModifyTargetGroupAttributes`,
@@ -868,12 +896,48 @@ place, since Cloud Control has no handler for the type),
868
896
  `ecs:UpdateService` (reverts an `AWS::ECS::Service` `ServiceConnectConfiguration` /
869
897
  `VolumeConfigurations` drift — the whole writeOnly prop is re-supplied, since Cloud
870
898
  Control cannot sub-path patch it),
871
- `apigateway:UpdateStage` (reverts an `AWS::ApiGatewayV2::Stage` — an `autoDeploy`
872
- stage rejects the `DeploymentId` the Cloud Control handler injects, so only the
873
- drifted stage properties are written directly, never `DeploymentId`),
874
- `apigateway:UpdateRestApi` (reverts an `AWS::ApiGateway::RestApi` `Policy` — the
875
- whole desired resource policy is re-serialized and replaced, since Cloud Control
876
- holds the policy as a JSON string it cannot sub-path patch).
899
+ `elasticbeanstalk:UpdateApplication` / `elasticbeanstalk:UpdateEnvironment`
900
+ (revert an `AWS::ElasticBeanstalk::Application` / `Environment`),
901
+ `codebuild:UpdateReportGroup` (reverts an `AWS::CodeBuild::ReportGroup`),
902
+ `dax:UpdateCluster` / `dax:UpdateParameterGroup` (revert an `AWS::DAX::Cluster` /
903
+ `ParameterGroup`),
904
+ `ec2:ModifyClientVpnEndpoint` (reverts an `AWS::EC2::ClientVpnEndpoint`),
905
+ `opensearch:UpdateDomainConfig` (reverts an `AWS::OpenSearchService::Domain`),
906
+ `cloudfront:GetDistributionConfig` / `cloudfront:UpdateDistribution` (revert an
907
+ `AWS::CloudFront::Distribution`),
908
+ `wafv2:GetWebACL` / `wafv2:UpdateWebACL` (revert an `AWS::WAFv2::WebACL`),
909
+ `glue:UpdateJob` / `glue:UpdateClassifier` / `glue:UpdateWorkflow` (revert an
910
+ `AWS::Glue::Job` / `Classifier` / `Workflow`),
911
+ `servicediscovery:UpdateHttpNamespace` (reverts an
912
+ `AWS::ServiceDiscovery::HttpNamespace` `Description`),
913
+ `cognito-sync:SetCognitoEvents` (reverts an `AWS::Cognito::IdentityPool`'s
914
+ writeOnly `CognitoEvents`),
915
+ `kinesisvideo:UpdateDataRetention` / `kinesisvideo:UpdateSignalingChannel` /
916
+ `kinesisvideo:UpdateStreamStorageConfiguration` (revert an `AWS::KinesisVideo::Stream`
917
+ `DataRetentionInHours` / `StreamStorageConfiguration` and an
918
+ `AWS::KinesisVideo::SignalingChannel` `MessageTtlSeconds`),
919
+ `kafka:UpdateConfiguration` (reverts an `AWS::MSK::Configuration` `ServerProperties`
920
+ — append-only, a new revision carrying the desired properties),
921
+ `logs:PutBearerTokenAuthentication` (reverts an `AWS::Logs::LogGroup`
922
+ `BearerTokenAuthenticationEnabled`),
923
+ `iam:AttachRolePolicy` / `DetachRolePolicy` / `AttachUserPolicy` /
924
+ `DetachUserPolicy` /
925
+ `AttachGroupPolicy` / `DetachGroupPolicy` / `ListEntitiesForPolicy` (revert an
926
+ `AWS::IAM::ManagedPolicy`'s attachments alongside the `CreatePolicyVersion` above),
927
+ the `lexv2models:*` write family
928
+ (`CreateIntent` / `UpdateIntent` / `DeleteIntent`, `CreateSlot` / `UpdateSlot` /
929
+ `DeleteSlot`, `CreateSlotType` / `UpdateSlotType` / `DeleteSlotType`,
930
+ `UpdateBotLocale` / `BuildBotLocale`, plus the `Describe*` / `List*` reads they
931
+ build on) to revert an `AWS::Lex::Bot` `BotLocales` drift,
932
+ `apigateway:PATCH` (the single IAM action API Gateway maps its update operations
933
+ to — reverts an `AWS::ApiGatewayV2::Stage`, where an `autoDeploy` stage rejects the
934
+ `DeploymentId` the Cloud Control handler injects so only the drifted stage
935
+ properties are written directly, and an `AWS::ApiGateway::RestApi` `Policy`, where
936
+ the whole desired resource policy is re-serialized and replaced since Cloud Control
937
+ holds the policy as a JSON string it cannot sub-path patch, and an
938
+ `AWS::ApiGateway::Method`'s
939
+ nested integration/response knobs) plus `apigateway:DELETE` (clearing a stage's
940
+ access-log / route settings back to unset).
877
941
 
878
942
  </details>
879
943
 
package/dist/cli.js CHANGED
@@ -1787,7 +1787,6 @@ const KNOWN_DEFAULTS = {
1787
1787
  EncryptionOptions: { UseAwsOwnedKey: true },
1788
1788
  DataReplicationMode: "NONE"
1789
1789
  },
1790
- "AWS::Chatbot::SlackChannelConfiguration": { GuardrailPolicies: ["arn:aws:iam::aws:policy/AdministratorAccess"] },
1791
1790
  "AWS::CloudTrail::Trail": { EventSelectors: [{
1792
1791
  IncludeManagementEvents: true,
1793
1792
  ReadWriteType: "All",
@@ -2663,7 +2662,8 @@ const CONTEXT_ARN_DEFAULTS = {
2663
2662
  "AWS::KinesisVideo::Stream": { KmsKeyId: "arn:{partition}:kms:{region}:{accountId}:alias/aws/kinesisvideo" },
2664
2663
  "AWS::AutoScaling::AutoScalingGroup": { ServiceLinkedRoleARN: "arn:{partition}:iam::{accountId}:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling" },
2665
2664
  "AWS::LakeFormation::Tag": { CatalogId: "{accountId}" },
2666
- "AWS::S3::AccessPoint": { BucketAccountId: "{accountId}" }
2665
+ "AWS::S3::AccessPoint": { BucketAccountId: "{accountId}" },
2666
+ "AWS::Chatbot::SlackChannelConfiguration": { GuardrailPolicies: ["arn:{partition}:iam::aws:policy/AdministratorAccess"] }
2667
2667
  };
2668
2668
  const ENGINE_DEFAULTS = {
2669
2669
  "AWS::RDS::DBInstance": {
@@ -5495,9 +5495,12 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
5495
5495
  }
5496
5496
  }
5497
5497
  const ctxArnTemplate = CONTEXT_ARN_DEFAULTS[resourceType]?.[k];
5498
- if (ctxArnTemplate !== void 0 && opts.region !== void 0 && opts.accountId !== void 0 && typeof v === "string") {
5498
+ if (ctxArnTemplate !== void 0 && opts.region !== void 0 && opts.accountId !== void 0) {
5499
5499
  const partition = partitionForRegion(opts.region).partition;
5500
- if (v === ctxArnTemplate.replace("{partition}", partition).replace("{region}", opts.region).replace("{accountId}", opts.accountId)) {
5500
+ const region = opts.region;
5501
+ const accountId = opts.accountId;
5502
+ const substitute = (t) => t.replace("{partition}", partition).replace("{region}", region).replace("{accountId}", accountId);
5503
+ if (Array.isArray(ctxArnTemplate) ? deepEqual(v, ctxArnTemplate.map(substitute)) : typeof v === "string" && v === substitute(ctxArnTemplate)) {
5501
5504
  findings.push({
5502
5505
  tier: "atDefault",
5503
5506
  logicalId,
@@ -7132,7 +7135,8 @@ async function enumerateVpcChildren(ctx) {
7132
7135
  });
7133
7136
  }
7134
7137
  function diffRouteTableChildren(input) {
7135
- const { routeTableId, declaredCidrs, liveRoutes } = input;
7138
+ const { routeTableId, declaredCidrs, liveRoutes, hasUnresolvedDeclaredRoute } = input;
7139
+ if (hasUnresolvedDeclaredRoute) return [];
7136
7140
  const declared = new Set(declaredCidrs);
7137
7141
  const added = [];
7138
7142
  for (const route of liveRoutes) {
@@ -7160,14 +7164,21 @@ async function enumerateRouteTableChildren(ctx) {
7160
7164
  const routeTableId = parent.physicalId;
7161
7165
  if (!routeTableId) return [];
7162
7166
  const declaredCidrs = [];
7163
- for (const r of desired.resources) if (r.resourceType === "AWS::EC2::Route" && parentRefMatches(r.declared.RouteTableId, routeTableId) && typeof r.declared.DestinationCidrBlock === "string") declaredCidrs.push(r.declared.DestinationCidrBlock);
7167
+ let hasUnresolvedDeclaredRoute = false;
7168
+ for (const r of desired.resources) {
7169
+ if (r.resourceType !== "AWS::EC2::Route" || !parentRefMatches(r.declared.RouteTableId, routeTableId)) continue;
7170
+ const cidr = r.declared.DestinationCidrBlock;
7171
+ if (typeof cidr === "string") declaredCidrs.push(cidr);
7172
+ else if (cidr === UNRESOLVED || hasUnresolved(cidr)) hasUnresolvedDeclaredRoute = true;
7173
+ }
7164
7174
  return diffRouteTableChildren({
7165
7175
  routeTableId,
7166
7176
  declaredCidrs,
7167
7177
  liveRoutes: (await describeRouteTable(new EC2Client({
7168
7178
  region,
7169
7179
  ...READ_RETRY
7170
- }), routeTableId)).filter(isEnumerableRoute).map((route) => ({ cidr: route.DestinationCidrBlock }))
7180
+ }), routeTableId)).filter(isEnumerableRoute).map((route) => ({ cidr: route.DestinationCidrBlock })),
7181
+ hasUnresolvedDeclaredRoute
7171
7182
  });
7172
7183
  }
7173
7184
  function diffEcsClusterChildren(input) {
@@ -7622,7 +7633,10 @@ const readLambdaPermission = async ({ declared, physicalId, region }) => {
7622
7633
  region,
7623
7634
  ...READ_RETRY
7624
7635
  }).send(new GetPolicyCommand({ FunctionName: fn }))).Policy)?.Statement ?? [];
7625
- const byId = physicalId ? stmts.find((s) => s.Sid === physicalId) : void 0;
7636
+ const sid = str$1(physicalId);
7637
+ const byId = sid ? stmts.find((s) => s.Sid === sid) : void 0;
7638
+ const policyKeysBySid = stmts.some((s) => str$1(s.Sid) !== void 0);
7639
+ if (sid && !byId && policyKeysBySid) throw new ResourceGoneError(`Lambda Permission Sid ${sid} absent from function ${fn}'s policy`);
7626
7640
  const want = {
7627
7641
  action: str$1(declared.Action),
7628
7642
  principal: str$1(declared.Principal)
@@ -9323,24 +9337,45 @@ async function fetch$1(client, resourceType) {
9323
9337
  };
9324
9338
  }
9325
9339
  }
9340
+ function resolveRefNode(node, definitions) {
9341
+ if (!node || typeof node !== "object") return void 0;
9342
+ let n = node;
9343
+ const seen = /* @__PURE__ */ new Set();
9344
+ while (n?.$ref) {
9345
+ const name = n.$ref.replace("#/definitions/", "");
9346
+ if (seen.has(name)) return void 0;
9347
+ seen.add(name);
9348
+ n = definitions[name];
9349
+ }
9350
+ return n;
9351
+ }
9326
9352
  function pointerToDotted$1(p) {
9327
9353
  return p.replace(/^\/properties\//, "").replace(/\/properties\//g, "/").replace(/\/properties$/, "").replace(/\//g, ".");
9328
9354
  }
9355
+ function variantBranches(node) {
9356
+ return [
9357
+ ...node.oneOf ?? [],
9358
+ ...node.anyOf ?? [],
9359
+ ...node.allOf ?? []
9360
+ ];
9361
+ }
9362
+ const MAX_VARIANT_DEPTH = 30;
9329
9363
  function collectDefaultPaths(definitions, properties) {
9330
9364
  const out = {};
9331
- const walk = (node, path, seen) => {
9332
- if (!node || typeof node !== "object") return;
9365
+ const walk = (node, path, seen, depth) => {
9366
+ if (!node || typeof node !== "object" || depth > MAX_VARIANT_DEPTH) return;
9333
9367
  if (node.$ref) {
9334
9368
  const name = node.$ref.replace("#/definitions/", "");
9335
9369
  if (seen.has(name)) return;
9336
- walk(definitions[name], path, new Set(seen).add(name));
9370
+ walk(definitions[name], path, new Set(seen).add(name), depth);
9337
9371
  return;
9338
9372
  }
9339
9373
  if ("default" in node && path) out[path] = node.default;
9340
- if (node.properties) for (const [k, child] of Object.entries(node.properties)) walk(child, path ? `${path}.${k}` : k, seen);
9341
- if (node.items) walk(node.items, path ? `${path}.*` : "*", seen);
9374
+ if (node.properties) for (const [k, child] of Object.entries(node.properties)) walk(child, path ? `${path}.${k}` : k, seen, depth);
9375
+ if (node.items) walk(node.items, path ? `${path}.*` : "*", seen, depth);
9376
+ for (const branch of variantBranches(node)) walk(branch, path, seen, depth + 1);
9342
9377
  };
9343
- for (const [k, child] of Object.entries(properties)) walk(child, k, /* @__PURE__ */ new Set());
9378
+ for (const [k, child] of Object.entries(properties)) walk(child, k, /* @__PURE__ */ new Set(), 0);
9344
9379
  return out;
9345
9380
  }
9346
9381
  const SCALAR_TYPES = new Set([
@@ -9382,7 +9417,8 @@ function collectUnorderedArrayPaths(definitions, properties) {
9382
9417
  if (propKeys.length === 0) return false;
9383
9418
  return !propKeys.some((k) => ITEM_IDENTITY_FIELDS.includes(k));
9384
9419
  };
9385
- const walk = (node, path, seen) => {
9420
+ const walk = (node, path, seen, depth) => {
9421
+ if (depth > MAX_VARIANT_DEPTH) return;
9386
9422
  const n = resolve(node, seen);
9387
9423
  if (!n) return;
9388
9424
  const nextSeen = node?.$ref ? new Set(seen).add(node.$ref.replace("#/definitions/", "")) : seen;
@@ -9392,11 +9428,12 @@ function collectUnorderedArrayPaths(definitions, properties) {
9392
9428
  if (isScalarItems(it)) scalar.push(path);
9393
9429
  else if (isNonIdentityObjectItems(it)) object.push(path);
9394
9430
  }
9395
- if (n.items) walk(n.items, path ? `${path}.*` : "*", nextSeen);
9431
+ if (n.items) walk(n.items, path ? `${path}.*` : "*", nextSeen, depth);
9396
9432
  }
9397
- if (n.properties) for (const [k, child] of Object.entries(n.properties)) walk(child, path ? `${path}.${k}` : k, nextSeen);
9433
+ if (n.properties) for (const [k, child] of Object.entries(n.properties)) walk(child, path ? `${path}.${k}` : k, nextSeen, depth);
9434
+ for (const branch of variantBranches(n)) walk(branch, path, nextSeen, depth + 1);
9398
9435
  };
9399
- for (const [k, child] of Object.entries(properties)) walk(child, k, /* @__PURE__ */ new Set());
9436
+ for (const [k, child] of Object.entries(properties)) walk(child, k, /* @__PURE__ */ new Set(), 0);
9400
9437
  return {
9401
9438
  scalar: [...new Set(scalar)].sort(),
9402
9439
  object: [...new Set(object)].sort()
@@ -9405,22 +9442,23 @@ function collectUnorderedArrayPaths(definitions, properties) {
9405
9442
  function collectFreeFormMapPaths(definitions, properties) {
9406
9443
  const out = [];
9407
9444
  const isObjectSchema = (v) => typeof v === "object" && v !== null;
9408
- const walk = (node, path, seen) => {
9409
- if (!node || typeof node !== "object") return;
9445
+ const walk = (node, path, seen, depth) => {
9446
+ if (!node || typeof node !== "object" || depth > MAX_VARIANT_DEPTH) return;
9410
9447
  if (node.$ref) {
9411
9448
  const name = node.$ref.replace("#/definitions/", "");
9412
9449
  if (seen.has(name)) return;
9413
- walk(definitions[name], path, new Set(seen).add(name));
9450
+ walk(definitions[name], path, new Set(seen).add(name), depth);
9414
9451
  return;
9415
9452
  }
9416
9453
  const hasFixedProps = node.properties && Object.keys(node.properties).length > 0;
9417
9454
  const isMap = node.type === "object" && !hasFixedProps && (node.patternProperties && Object.keys(node.patternProperties).length > 0 || isObjectSchema(node.additionalProperties));
9418
9455
  const lastSeg = path.split(".").at(-1);
9419
9456
  if (isMap && path && lastSeg !== "Tags") out.push(path);
9420
- if (node.properties) for (const [k, child] of Object.entries(node.properties)) walk(child, path ? `${path}.${k}` : k, seen);
9421
- if (node.items) walk(node.items, path ? `${path}.*` : "*", seen);
9457
+ if (node.properties) for (const [k, child] of Object.entries(node.properties)) walk(child, path ? `${path}.${k}` : k, seen, depth);
9458
+ if (node.items) walk(node.items, path ? `${path}.*` : "*", seen, depth);
9459
+ for (const branch of variantBranches(node)) walk(branch, path, seen, depth + 1);
9422
9460
  };
9423
- for (const [k, child] of Object.entries(properties)) walk(child, k, /* @__PURE__ */ new Set());
9461
+ for (const [k, child] of Object.entries(properties)) walk(child, k, /* @__PURE__ */ new Set(), 0);
9424
9462
  return [...new Set(out)].sort();
9425
9463
  }
9426
9464
  /** Exported for unit testing without an AWS call. */
@@ -9431,11 +9469,15 @@ function parseSchema(schemaJson) {
9431
9469
  const readOnlyPaths = dotted(schema.readOnlyProperties);
9432
9470
  const writeOnlyPaths = dotted(schema.writeOnlyProperties);
9433
9471
  const createOnlyPaths = dotted(schema.createOnlyProperties);
9472
+ const definitions = schema.definitions ?? {};
9434
9473
  const defaults = {};
9435
- for (const [k, def] of Object.entries(schema.properties ?? {})) if (def && typeof def === "object" && "default" in def) defaults[k] = def.default;
9436
- const defaultPaths = collectDefaultPaths(schema.definitions ?? {}, schema.properties ?? {});
9437
- const unorderedArrayPaths = collectUnorderedArrayPaths(schema.definitions ?? {}, schema.properties ?? {});
9438
- const freeFormMapPaths = collectFreeFormMapPaths(schema.definitions ?? {}, schema.properties ?? {});
9474
+ for (const [k, def] of Object.entries(schema.properties ?? {})) {
9475
+ const resolved = resolveRefNode(def, definitions);
9476
+ if (resolved && "default" in resolved) defaults[k] = resolved.default;
9477
+ }
9478
+ const defaultPaths = collectDefaultPaths(definitions, schema.properties ?? {});
9479
+ const unorderedArrayPaths = collectUnorderedArrayPaths(definitions, schema.properties ?? {});
9480
+ const freeFormMapPaths = collectFreeFormMapPaths(definitions, schema.properties ?? {});
9439
9481
  const updatable = schema.handlers === void 0 ? void 0 : Object.hasOwn(schema.handlers, "update");
9440
9482
  const propertyTransforms = {};
9441
9483
  for (const [ptr, expr] of Object.entries(schema.propertyTransform ?? {})) if (typeof expr === "string") propertyTransforms[pointerToDotted$1(ptr)] = expr;
@@ -10042,6 +10084,7 @@ async function loadBaseline(stackName, accountId, region) {
10042
10084
  if (typeof parsed.schemaVersion === "number" && parsed.schemaVersion > 2) throw new Error(`baseline file ${path} was written by a newer cdkrd (schemaVersion ${parsed.schemaVersion}); upgrade cdkrd`);
10043
10085
  if (!Array.isArray(parsed.recorded)) throw new Error(`baseline file ${path} is malformed: \`recorded\` is missing or not an array`);
10044
10086
  parsed.recorded.forEach((entry, i) => validateRecordedEntry(entry, i, path));
10087
+ validateRecordedUniqueness(parsed.recorded, path);
10045
10088
  validateCompleteResources(parsed.completeResources, path);
10046
10089
  validateRecordedPhysicalIds(parsed.recordedPhysicalIds, path);
10047
10090
  return parsed;
@@ -10066,6 +10109,34 @@ function validateRecordedEntry(entry, index, path) {
10066
10109
  ]) if (typeof obj[k] !== "string") throw new Error(`${at}: "${k}" is required and must be a string`);
10067
10110
  }
10068
10111
  /**
10112
+ * #1047: reject duplicate `recorded` identity keys at load. The baseline is git-committed,
10113
+ * hand-editable, and merge-conflictable, so a bad merge / hand-edit can leave TWO entries
10114
+ * sharing the SAME identity — `(logicalId, path, resourceType)` — with DIFFERENT values. The
10115
+ * #794 shape validation above proves each element is well-FORMED but never cross-checks
10116
+ * identity, so such a file loads cleanly and then misbehaves: every match site
10117
+ * (`recorded.find(...)` in applyBaseline / splitRecordedByBaseline) silently first-wins — so
10118
+ * if LIVE equals the SECOND duplicate the finding is NOT suppressed and false-surfaces as
10119
+ * confirmed drift — AND the removed-since-record loop iterates ALL entries, emitting TWO
10120
+ * identical "baseline value removed since record" findings for the one path (an inflated
10121
+ * drift count). The identity here is exactly the one the match sites compare on (see
10122
+ * `entryMatches` / splitRecordedByBaseline's `.find`), so a collision is genuinely
10123
+ * ambiguous — the file is corrupt. Fail LOUDLY (naming the duplicated identity) rather than
10124
+ * silently pick the first, mirroring #794's loud-vs-silent principle. Entries are all
10125
+ * shape-validated by this point, so `logicalId`/`resourceType`/`path` are known strings.
10126
+ */
10127
+ function validateRecordedUniqueness(recorded, path) {
10128
+ const seen = /* @__PURE__ */ new Set();
10129
+ recorded.forEach((entry, i) => {
10130
+ const key = JSON.stringify([
10131
+ entry.logicalId,
10132
+ entry.path,
10133
+ entry.resourceType
10134
+ ]);
10135
+ if (seen.has(key)) throw new Error(`baseline file ${path}: \`recorded\`[${i}] is a duplicate of an earlier entry with the same identity (logicalId=${JSON.stringify(entry.logicalId)}, path=${JSON.stringify(entry.path)}, resourceType=${JSON.stringify(entry.resourceType)}). Two recorded entries with the same identity are ambiguous (a bad merge or hand-edit) — remove the stale one, or restore the correct file from git.`);
10136
+ seen.add(key);
10137
+ });
10138
+ }
10139
+ /**
10069
10140
  * #794: validate `completeResources` (optional; absent on v1 files). When present it must
10070
10141
  * be an array of strings — a bare string would have `new Set(...)` iterate its CHARACTERS
10071
10142
  * (silently mis-scoping completeness), and a number would crash with an opaque
@@ -14315,10 +14386,15 @@ function sanitizeForTerminal(s) {
14315
14386
  let out = "";
14316
14387
  for (const ch of s) {
14317
14388
  const code = ch.charCodeAt(0);
14318
- out += code < 32 || code === 127 ? `\\x${code.toString(16).padStart(2, "0")}` : ch;
14389
+ if (code < 32 || code === 127) out += `\\x${code.toString(16).padStart(2, "0")}`;
14390
+ else if (isBidiOrZeroWidth(code)) out += `\\u{${code.toString(16).toUpperCase()}}`;
14391
+ else out += ch;
14319
14392
  }
14320
14393
  return out;
14321
14394
  }
14395
+ function isBidiOrZeroWidth(code) {
14396
+ return code >= 8234 && code <= 8238 || code >= 8294 && code <= 8297 || code >= 8203 && code <= 8207 || code === 65279;
14397
+ }
14322
14398
  function jPair(a, b) {
14323
14399
  const as = JSON.stringify(a) ?? String(a);
14324
14400
  const bs = JSON.stringify(b) ?? String(b);
@@ -14927,6 +15003,23 @@ function hasBaselineForStack(stackName, region) {
14927
15003
  return lower.startsWith(prefix) && lower.endsWith(suffix);
14928
15004
  });
14929
15005
  }
15006
+ function safeStringifyJson(value) {
15007
+ const seen = /* @__PURE__ */ new WeakSet();
15008
+ const replacer = (_key, v) => {
15009
+ if (typeof v === "bigint") return v.toString();
15010
+ if (typeof v === "object" && v !== null) {
15011
+ if (seen.has(v)) return "[Circular]";
15012
+ seen.add(v);
15013
+ }
15014
+ return v;
15015
+ };
15016
+ try {
15017
+ return JSON.stringify(value, replacer, 2);
15018
+ } catch (e) {
15019
+ console.error(`error: could not serialize --json output: ${e.message} — emitting [] instead`);
15020
+ return "[]";
15021
+ }
15022
+ }
14930
15023
  async function runCheck(args) {
14931
15024
  const a = parseCommonArgs(args, "check");
14932
15025
  if (a.profile) process.env.AWS_PROFILE = a.profile;
@@ -15135,7 +15228,7 @@ async function runCheck(args) {
15135
15228
  worst = Math.max(worst, 2);
15136
15229
  }
15137
15230
  }
15138
- if (a.json) console.log(JSON.stringify(jsonReports, null, 2));
15231
+ if (a.json) console.log(safeStringifyJson(jsonReports));
15139
15232
  if (anyDrift && !a.fail && !a.json) console.error("note: drift found — exit 0 (report-only). Pass --fail to make drift fail this command.");
15140
15233
  return worst;
15141
15234
  }