cdk-real-drift 0.2.76 → 0.2.78

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
@@ -345,7 +345,7 @@ CI (with `--yes`).
345
345
 
346
346
  | option | meaning |
347
347
  | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
348
- | `--region <r>` | AWS region (or `$AWS_REGION` / `$AWS_DEFAULT_REGION`); else `env.region` per stack, else the `--profile`'s region |
348
+ | `--region <r>` | a stack's own `env.region` ALWAYS wins; for an env-AGNOSTIC stack (no `env`) it falls back to `--region` (or `$AWS_REGION` / `$AWS_DEFAULT_REGION`), else the `--profile`'s region |
349
349
  | `--profile <p>` | AWS profile (or `$AWS_PROFILE`) |
350
350
  | `-a, --app <cmd\|cdk.out>` | CDK app command or pre-synthesized assembly dir (or `$CDKRD_APP` / cdk.json `"app"`); stack auto-discovery + construct paths |
351
351
  | `-c, --context key=value` | context for synth (repeatable; cdk.json is the base layer) |
@@ -353,14 +353,14 @@ CI (with `--yes`).
353
353
  | `--json` | machine-readable output (see [JSON contract](#json-output-contract)) |
354
354
  | `--fail` | (check) exit 1 on drift and never prompt; for scripts/CI. Without it, check reports drift but exits 0 |
355
355
  | `--strict` | (check) exit 1 when coverage is incomplete. A coverage gap is always surfaced loudly; `--strict` makes it CI-failing. Orthogonal to `--fail` |
356
- | `--show-all` | inventory mode: show all current undeclared state, ignoring the baseline |
357
- | `--verbose` / `-v` | (check) expand the `info:` footer tiers / (revert) expand the per-reason not-revertable summary to full lists |
356
+ | `--show-all` | (check) inventory mode: show all current undeclared state, ignoring the baseline |
357
+ | `--verbose` / `-v` | (check) expand the `info:` footer tiers / (revert) expand the not-revertable summary to full lists; (record) itemizes nested sub-keys in the multiselect |
358
358
  | `--pre-deploy` | (check) compare live vs the LOCAL synth template: the declared drift your next `cdk deploy` would silently overwrite |
359
359
  | `--undeclared-only` | (check) undeclared drift only: pair cdkrd with `cdk drift` for the declared side |
360
360
  | `--declared-only` | (check) declared drift vs the deployed template only (undeclared tier skipped; baseline untouched). Not `--pre-deploy` |
361
361
  | `--dry-run` | (revert) print the plan; make no changes |
362
362
  | `--wait[=DURATION]` | (revert) on a transient "resource is mid-update" error (e.g. Route53Resolver `RSLVR-00705`) keep retrying until it settles, up to DURATION (default `10m`; e.g. `--wait=5m`, `--wait=90s`) |
363
- | `--remove-unrecorded` | (revert) REMOVE unrecorded values + DELETE unrecorded added resources in a no-prompt run (`--yes`/CI); an interactive revert already lists them |
363
+ | `--remove-unrecorded` | (revert, and check for its inline revert) REMOVE unrecorded values + DELETE unrecorded added resources in a no-prompt run (`--yes`/CI); an interactive revert already lists them |
364
364
  | `--yes` / `-y` | skip confirmations (revert apply; record records all without the multiselect) |
365
365
 
366
366
  Unknown options (`--apq`) and options missing their value (`--app` at the end of
@@ -371,8 +371,10 @@ the line) are errors (exit `2`): a typo'd flag never silently becomes a stack na
371
371
  Every option runs exactly the same code as the standalone commands. Prompts are
372
372
  skipped under `--json`, `--show-all`, `--pre-deploy`, and `--fail`. A non-TTY run
373
373
  never prompts: a required write decision without `--yes` errors with exit 2 (the
374
- safe side); `--yes` alone in a TTY auto-approves confirmations only (select prompts
375
- still show).
374
+ safe side); `--yes` in a TTY skips the write confirmation AND each verb's selection
375
+ multiselect — `record` records ALL, `ignore` ignores ALL, `revert` applies the full
376
+ plan. Only `check`'s action menu (Record / Revert / Ignore / …) still shows under
377
+ `--yes`.
376
378
 
377
379
  - **`check` with drift** offers `Record / Revert / Ignore / Decide per finding /
378
380
  Nothing` (see [The model](#the-model-one-verb-you-run-three-it-offers)). Each
@@ -577,7 +579,9 @@ valid JSON value nor JSONL; multi-stack `--json` was unparseable — issue #755.
577
579
  A **stack that errored or was skipped** before it could be checked still appears as an
578
580
  element so a consumer sees which stacks ran: it carries `"error": "<reason>"` alongside
579
581
  `"drifted": 0` and an empty `"findings": []`. (`error` is absent on a
580
- successfully-checked stack.)
582
+ successfully-checked stack.) Its `stack` is `"<name> (<region>)"` as usual, EXCEPT
583
+ when the failure is that no region could be resolved for the stack — then `stack`
584
+ is the bare `"<name>"` (no ` (<region>)` suffix), since there is no region to name.
581
585
 
582
586
  A **stack deleted out of band** — its committed baseline proves it was once deployed but
583
587
  it is now gone from CloudFormation — is the strongest drift, so it carries
@@ -625,6 +629,17 @@ Optional per-finding fields, present only when they apply:
625
629
  - `modelReadFailed` (`true`) — an `added` resource whose full live model could not be
626
630
  read this run (`actual` is only the enumerator's identity snippet); it exists but is
627
631
  not change-watchable until the next check.
632
+ - `wholeArrayRevert` (`{ path, value }`) — **internal, revert-only** metadata on a
633
+ `declared` per-element finding inside an unordered object-array (a set the
634
+ service reorders — SecurityGroup rules, PrefixList entries, …): it carries the
635
+ WHOLE declared array so `revert` replaces the array as a unit instead of
636
+ index-patching a sorted position that does not map to the live index.
637
+ Display-only for the report; a consumer can ignore it.
638
+ - `siblingPolicyNames` (`"unresolved"`) — **internal, revert-only** sentinel on a
639
+ `declared` IAM Role `Policies` finding whose sibling `AWS::IAM::Policy` names
640
+ could not be resolved; `revert` reads it and refuses to act (a per-entry revert
641
+ could delete a managed inline policy). The only emitted value is the
642
+ `"unresolved"` string; a consumer can ignore it.
628
643
  - On an `added` finding, `desired` carries the **recorded baseline model** and `actual`
629
644
  the live one (so a recorded `added` resource that changed shows the delta), and
630
645
  `unrecorded` marks a never-recorded one as potential drift.
package/dist/cli.js CHANGED
@@ -816,6 +816,29 @@ var QuietIoHost = class extends NonInteractiveIoHost {
816
816
  }
817
817
  };
818
818
 
819
+ //#endregion
820
+ //#region src/synth/missing-context.ts
821
+ /** Unique, sorted missing-context keys (dedup by key). Empty array when nothing is missing. */
822
+ function missingContextKeys(missing) {
823
+ if (!missing || missing.length === 0) return [];
824
+ return [...new Set(missing.map((m) => m.key))].sort();
825
+ }
826
+ /**
827
+ * Build the stderr message body (no `warning:`/`error:` prefix — the caller adds it) for an
828
+ * assembly synthesized with unresolved context lookups. Returns `null` when `keys` is empty
829
+ * (a clean assembly — behavior unchanged). Under `preDeploy` the wording escalates to an
830
+ * explicit REFUSAL: the placeholders are the declared source there, so proceeding on
831
+ * fabricated values (false drift, a bad `--fail`, a revert that writes dummies back) is worse
832
+ * than stopping — the user must supply the context or deploy so the lookups resolve.
833
+ */
834
+ function missingContextWarning(keys, opts = {}) {
835
+ if (keys.length === 0) return null;
836
+ const lead = `the CDK app synthesized with ${keys.length} unresolved context lookup(s): ${keys.join(", ")}`;
837
+ const why = "CDK filled these with placeholder dummy values (e.g. vpc-12345), so the synthesized template does not reflect real infrastructure.";
838
+ if (opts.preDeploy) return `${lead}\n${why}\n(--pre-deploy) refusing: those placeholders are the DECLARED source, so every check would report fabricated declared drift and a revert would write the dummy values back to AWS. Provide the context (commit cdk.context.json, pass -c key=value, or deploy so the lookups resolve) and re-run.`;
839
+ return `${lead}\n${why}`;
840
+ }
841
+
819
842
  //#endregion
820
843
  //#region src/synth/synth.ts
821
844
  const CONCRETE_REGION = /^[a-z]{2}(-[a-z]+)+-\d+$/;
@@ -847,6 +870,12 @@ async function synthApp(app, opts = {}) {
847
870
  }
848
871
  const cached = await toolkit.synth(source);
849
872
  try {
873
+ const missingKeys = missingContextKeys(cached.cloudAssembly.manifest.missing);
874
+ if (missingKeys.length > 0) {
875
+ const msg = missingContextWarning(missingKeys, { preDeploy: opts.preDeploy });
876
+ if (opts.preDeploy) throw new Error(msg ?? "unresolved CDK context lookups");
877
+ console.error(`warning: ${msg}`);
878
+ }
850
879
  return cached.cloudAssembly.stacksRecursively.map((s) => ({
851
880
  stackName: s.stackName,
852
881
  region: CONCRETE_REGION.test(s.environment.region) ? s.environment.region : void 0,
@@ -1383,6 +1412,20 @@ const KNOWN_DEFAULTS = {
1383
1412
  BucketKeyEnabled: true,
1384
1413
  ServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" }
1385
1414
  }] } },
1415
+ "AWS::S3::AccessPoint": { PublicAccessBlockConfiguration: {
1416
+ RestrictPublicBuckets: true,
1417
+ BlockPublicPolicy: true,
1418
+ BlockPublicAcls: true,
1419
+ IgnorePublicAcls: true
1420
+ } },
1421
+ "AWS::ImageBuilder::InfrastructureConfiguration": { TerminateInstanceOnFailure: true },
1422
+ "AWS::ImageBuilder::ImagePipeline": {
1423
+ EnhancedImageMetadataEnabled: true,
1424
+ ImageTestsConfiguration: {
1425
+ ImageTestsEnabled: true,
1426
+ TimeoutMinutes: 720
1427
+ }
1428
+ },
1386
1429
  "AWS::S3Tables::TableBucket": {
1387
1430
  StorageClassConfiguration: { StorageClass: "STANDARD" },
1388
1431
  MetricsConfiguration: { Status: "Disabled" },
@@ -2323,7 +2366,8 @@ const CONTEXT_ARN_DEFAULTS = {
2323
2366
  "AWS::ResourceExplorer2::View": { Scope: "arn:{partition}:iam::{accountId}:root" },
2324
2367
  "AWS::KinesisVideo::Stream": { KmsKeyId: "arn:{partition}:kms:{region}:{accountId}:alias/aws/kinesisvideo" },
2325
2368
  "AWS::AutoScaling::AutoScalingGroup": { ServiceLinkedRoleARN: "arn:{partition}:iam::{accountId}:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling" },
2326
- "AWS::LakeFormation::Tag": { CatalogId: "{accountId}" }
2369
+ "AWS::LakeFormation::Tag": { CatalogId: "{accountId}" },
2370
+ "AWS::S3::AccessPoint": { BucketAccountId: "{accountId}" }
2327
2371
  };
2328
2372
  const ENGINE_DEFAULTS = {
2329
2373
  "AWS::RDS::DBInstance": {
@@ -2788,7 +2832,10 @@ const CASE_INSENSITIVE_PATHS = {
2788
2832
  "AWS::RDS::DBCluster": new Set(["DBClusterIdentifier"]),
2789
2833
  "AWS::DMS::Endpoint": new Set(["EndpointType"]),
2790
2834
  "AWS::WAFv2::LoggingConfiguration": new Set(["RedactedFields.*.SingleHeader.Name"]),
2791
- "AWS::ElasticLoadBalancing::LoadBalancer": new Set(["Listeners.*.Protocol", "Listeners.*.InstanceProtocol"])
2835
+ "AWS::ElasticLoadBalancing::LoadBalancer": new Set(["Listeners.*.Protocol", "Listeners.*.InstanceProtocol"]),
2836
+ "AWS::EC2::SecurityGroup": new Set(["SecurityGroupIngress.*.IpProtocol", "SecurityGroupEgress.*.IpProtocol"]),
2837
+ "AWS::EC2::SecurityGroupIngress": new Set(["IpProtocol"]),
2838
+ "AWS::EC2::SecurityGroupEgress": new Set(["IpProtocol"])
2792
2839
  };
2793
2840
  function isCaseInsensitiveScalarEqual(a, b) {
2794
2841
  return typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();
@@ -2934,7 +2981,10 @@ function isPropertiesFileEqual(a, b) {
2934
2981
  for (const [k, v] of ma) if (mb.get(k) !== v) return false;
2935
2982
  return true;
2936
2983
  }
2937
- const CASE_INSENSITIVE_ARRAY_PATHS = { "AWS::ApiGatewayV2::Api": new Set(["CorsConfiguration.AllowHeaders", "CorsConfiguration.ExposeHeaders"]) };
2984
+ const CASE_INSENSITIVE_ARRAY_PATHS = {
2985
+ "AWS::ApiGatewayV2::Api": new Set(["CorsConfiguration.AllowHeaders", "CorsConfiguration.ExposeHeaders"]),
2986
+ "AWS::Lambda::Url": new Set(["Cors.AllowHeaders", "Cors.ExposeHeaders"])
2987
+ };
2938
2988
  function isCaseInsensitiveEqualScalarSet(a, b) {
2939
2989
  if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
2940
2990
  if (!a.every((v) => typeof v === "string") || !b.every((v) => typeof v === "string")) return false;
@@ -4104,7 +4154,8 @@ const MEANINGFUL_WHEN_OFF = {
4104
4154
  "AWS::EC2::Instance": { SourceDestCheck: () => true },
4105
4155
  "AWS::EC2::NetworkInterface": { SourceDestCheck: () => true },
4106
4156
  "AWS::Cognito::UserPoolClient": { EnableTokenRevocation: () => true },
4107
- "AWS::CloudWatch::CompositeAlarm": { ActionsEnabled: () => true }
4157
+ "AWS::CloudWatch::CompositeAlarm": { ActionsEnabled: () => true },
4158
+ "AWS::ApplicationInsights::Application": { CWEMonitorEnabled: () => true }
4108
4159
  };
4109
4160
  const stripCognitoAttrPrefix = (id) => id.replace(/^(custom|dev):/, "");
4110
4161
  const IDENTITY_KEYED_SUBSET_ARRAYS = {
@@ -4917,7 +4968,10 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
4917
4968
  if (LATEST_SENTINEL_PATHS[resourceType]?.has(d.path) && isLatestSentinelMatch(d.stateValue, d.awsValue)) continue;
4918
4969
  if (INTELLIGENT_TIERING_PATHS[resourceType]?.has(d.path) && isIntelligentTieringMatch(d.stateValue, d.awsValue)) continue;
4919
4970
  if ((UNORDERED_ARRAY_PROPS[resourceType]?.has(d.path) || UNORDERED_ARRAY_PROPS[resourceType]?.has(d.path.replace(/\.\d+(?=\.|$)/g, ".*")) || schema.unorderedScalarPaths?.includes(d.path)) && isEqualUnorderedScalarSet(d.stateValue, d.awsValue)) continue;
4920
- if (isTrivialEmpty(d.stateValue) && d.path in knownDef && deepEqual(d.awsValue, knownDef[d.path])) continue;
4971
+ if (isTrivialEmpty(d.stateValue) && d.path in knownDef && deepEqual(d.awsValue, knownDef[d.path]) && !(MEANINGFUL_WHEN_OFF[resourceType]?.[d.path]?.({
4972
+ declared,
4973
+ live
4974
+ }) ?? false)) continue;
4921
4975
  const unorderedExtra = unorderedObjArray && Array.isArray(declaredVal) && declaredRemapSource ? {
4922
4976
  path: remapSortedIndexToDeclared(d.path, k, declaredVal, declaredRemapSource),
4923
4977
  wholeArrayRevert: {
@@ -8798,6 +8852,7 @@ function parseSchema(schemaJson) {
8798
8852
  const defaultPaths = collectDefaultPaths(schema.definitions ?? {}, schema.properties ?? {});
8799
8853
  const unorderedArrayPaths = collectUnorderedArrayPaths(schema.definitions ?? {}, schema.properties ?? {});
8800
8854
  const freeFormMapPaths = collectFreeFormMapPaths(schema.definitions ?? {}, schema.properties ?? {});
8855
+ const updatable = schema.handlers === void 0 ? void 0 : Object.hasOwn(schema.handlers, "update");
8801
8856
  return {
8802
8857
  readOnly: topLevel(readOnlyPaths),
8803
8858
  writeOnly: topLevel(writeOnlyPaths),
@@ -8809,7 +8864,8 @@ function parseSchema(schemaJson) {
8809
8864
  defaultPaths,
8810
8865
  unorderedScalarPaths: unorderedArrayPaths.scalar,
8811
8866
  unorderedObjectArrayPaths: unorderedArrayPaths.object,
8812
- freeFormMapPaths
8867
+ freeFormMapPaths,
8868
+ updatable
8813
8869
  };
8814
8870
  }
8815
8871
 
@@ -9367,8 +9423,11 @@ async function loadBaseline(stackName, accountId, region) {
9367
9423
  throw new Error(`baseline file ${path} is not valid JSON (corrupt or partially written)`);
9368
9424
  }
9369
9425
  if (parsed === null || typeof parsed !== "object") throw new Error(`baseline file ${path} is malformed: root is not an object`);
9426
+ if (parsed.stackName && parsed.stackName !== stackName) throw new Error(`baseline file ${path} was captured for stack ${parsed.stackName}, but it was loaded as stack ${stackName} (the file was likely copied or renamed to the wrong path, or a case-insensitive filesystem collided two stacks onto one file). Baselines are per-stack — run \`cdkrd record\` to write this stack's own baseline file, or restore the correct file from git.`);
9427
+ if (parsed.region && parsed.region !== region) throw new Error(`baseline file ${path} was captured in region ${parsed.region}, but the current region is ${region} (the file was likely copied or renamed to the wrong region path). Baselines are per-region — run \`cdkrd record\` to write this region's own baseline file, or restore the correct file from git.`);
9370
9428
  if (parsed.recorded === void 0 && parsed.accepted !== void 0) parsed.recorded = parsed.accepted;
9371
9429
  delete parsed.accepted;
9430
+ if (parsed.schemaVersion !== void 0 && typeof parsed.schemaVersion !== "number") throw new Error(`baseline file ${path} has a non-numeric schemaVersion (${JSON.stringify(parsed.schemaVersion)}); it is malformed (corrupt or hand-edited)`);
9372
9431
  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`);
9373
9432
  if (!Array.isArray(parsed.recorded)) throw new Error(`baseline file ${path} is malformed: \`recorded\` is missing or not an array`);
9374
9433
  parsed.recorded.forEach((entry, i) => validateRecordedEntry(entry, i, path));
@@ -11866,6 +11925,15 @@ function buildRevertPlan(findings, baseline, opts = {}) {
11866
11925
  });
11867
11926
  continue;
11868
11927
  }
11928
+ if (schema?.updatable === false && !SDK_WRITERS[f.resourceType] && !propScoped && !nestedScoped) {
11929
+ notRevertable.push({
11930
+ displayId,
11931
+ resourceType: f.resourceType,
11932
+ path: f.path,
11933
+ reason: "type has no update handler — detect/record only"
11934
+ });
11935
+ continue;
11936
+ }
11869
11937
  const kind = SDK_WRITERS[f.resourceType] || propScoped || nestedScoped ? "sdk" : "cc";
11870
11938
  let toRevert = f;
11871
11939
  const sgSide = f.tier === "declared" && f.resourceType === "AWS::EC2::SecurityGroup" ? SG_REVERT_SIDE[f.path] : void 0;
@@ -12349,6 +12417,7 @@ function revertSelectMessage(stackName) {
12349
12417
  async function recordStack(p) {
12350
12418
  const { stackName, region, desired, findings, yes, interactive, preselectedKeys, expandNested } = p;
12351
12419
  const existing = await loadBaseline(stackName, desired.accountId, region);
12420
+ if (existing) checkBaselineAccount(existing, desired.accountId, stackName);
12352
12421
  if (!yes && existing) console.error(`note: ${stackName}: will overwrite the existing baseline file on confirm (nothing written yet; it is git-tracked — review the diff afterwards). Pass --yes to silence.`);
12353
12422
  let recorded = carryForwardUnreadable(buildRecorded(findings), existing, findings);
12354
12423
  let refreshedOnly = false;
@@ -13909,11 +13978,19 @@ async function runCheck(args) {
13909
13978
  emitEmptyJsonOnError();
13910
13979
  return 2;
13911
13980
  }
13912
- const synthed = await synthApp(app, {
13913
- region: a.region,
13914
- profile: a.profile,
13915
- context: a.context
13916
- });
13981
+ let synthed;
13982
+ try {
13983
+ synthed = await synthApp(app, {
13984
+ region: a.region,
13985
+ profile: a.profile,
13986
+ context: a.context,
13987
+ preDeploy: true
13988
+ });
13989
+ } catch (e) {
13990
+ console.error(`error: ${e.message}`);
13991
+ emitEmptyJsonOnError();
13992
+ return 2;
13993
+ }
13917
13994
  synthTemplates = new Map(synthed.map((s) => [synthKey(s.stackName, s.region ?? a.region), s.template]));
13918
13995
  console.error("(--pre-deploy) comparing live state against the LOCAL synth template");
13919
13996
  }
@@ -14199,8 +14276,10 @@ OPTIONS
14199
14276
  --remove-unrecorded (revert) REMOVE unrecorded values + DELETE unrecorded
14200
14277
  added resources (never recorded; default: refuse —
14201
14278
  record the ones that are right)
14202
- --yes, -y skip confirmation (revert) / overwrite notice (record) /
14203
- ignore ALL shown drift without the multiselect (ignore)
14279
+ --yes, -y skip the write confirm AND the op multiselect — apply the
14280
+ FULL plan (revert) / skip the selection multiselect +
14281
+ overwrite notice, record ALL (record) / ignore ALL shown
14282
+ drift without the multiselect (ignore)
14204
14283
  --help, -h --version, -v
14205
14284
 
14206
14285
  Automation: check --fail / record --yes / ignore --yes / revert --yes (or