cdk-real-drift 0.4.38 → 0.4.40

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
@@ -699,6 +699,14 @@ mode: a `record` / `ignore` that would need the selection prompt refuses without
699
699
 
700
700
  After publication this shape is a backward-compatible API.
701
701
 
702
+ `revert` also **refuses to write (exit 2) when the target stack is mid-operation**
703
+ (`*_IN_PROGRESS`): it re-reads the stack status immediately before applying, so a
704
+ revert can never fight an in-flight `cdk deploy` / update by writing stale values
705
+ onto an updating stack — wait for the stack to settle, then re-run. And
706
+ `record` / `ignore` / `revert` now surface the same stack-status warning `check`
707
+ prints when a stack is mid-operation or in a failed state (a `record` mid-update
708
+ would otherwise snapshot transient values into the committed baseline).
709
+
702
710
  ## IAM permissions
703
711
 
704
712
  `check` / `record` are **read-only**: the AWS managed `ReadOnlyAccess` policy
package/dist/cli.js CHANGED
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
3
- import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
+ import { pid } from "node:process";
5
6
  import { YAMLSeq, isSeq, parse, parseDocument } from "yaml";
6
7
  import { CloudControlClient, DeleteResourceCommand, GetResourceCommand, GetResourceRequestStatusCommand, UpdateResourceCommand } from "@aws-sdk/client-cloudcontrol";
7
8
  import { homedir } from "node:os";
@@ -742,25 +743,63 @@ function appendRulesToYaml(existingRaw, added) {
742
743
  return doc.toString();
743
744
  }
744
745
  /**
746
+ * Atomically replace `dest` with `content` (same filesystem): write to a sibling temp file
747
+ * in the SAME directory, then `rename` it over `dest`. `rename` is atomic on one filesystem,
748
+ * so a concurrent reader (`loadConfig`) never observes a half-written file — it sees either
749
+ * the old bytes or the new bytes in full, never a TRUNCATED-but-still-valid YAML (issue
750
+ * #759): a crash/Ctrl-C mid-`writeFile` could otherwise leave e.g. a truncated bare-scalar
751
+ * glob `path: Api` that OVER-matches, which `loadConfig` would accept silently. The temp file
752
+ * MUST be a SIBLING (same dir) so the rename stays within one filesystem — a rename across
753
+ * filesystems is not atomic (it degrades to copy+unlink). The pid + a monotonic counter keep
754
+ * the temp name unique per concurrent writer so two racing processes don't clobber each
755
+ * other's temp file. On any failure the temp file is cleaned up so it can't accumulate.
756
+ */
757
+ let tmpCounter = 0;
758
+ async function atomicWrite(dest, content) {
759
+ const tmp = `${dest}.${pid}.${tmpCounter++}.tmp`;
760
+ try {
761
+ await writeFile(tmp, content);
762
+ await rename(tmp, dest);
763
+ } catch (e) {
764
+ await unlink(tmp).catch(() => {});
765
+ throw e;
766
+ }
767
+ }
768
+ /**
745
769
  * Append ignore rules to `.cdkrd/ignore.yaml` (cwd-relative), creating the file (and
746
770
  * the `.cdkrd/` dir) if absent. Idempotent: rules already present are reported, not
747
771
  * duplicated. Loads through `loadConfig` first so a malformed config fails fast rather
748
772
  * than being silently overwritten. Returns the path + what changed so the caller can
749
773
  * report it. The only mutating entry point for config (parallel to `writeBaseline`).
774
+ *
775
+ * The write is ATOMIC (tmp file + `rename`, see `atomicWrite`) so a crash mid-write can
776
+ * never leave a truncated-but-valid config (#759). To narrow the read-merge-write race with
777
+ * a concurrent `cdkrd` process, the on-disk config is RE-READ immediately before the write
778
+ * and the incoming rules merged against THAT fresh state — so a rule another process
779
+ * appended between our initial `loadConfig` and our write is preserved, not clobbered.
750
780
  */
751
781
  async function addIgnoreRules(newRules) {
752
- const { added, alreadyPresent } = mergeIgnoreRules((await loadConfig()).ignore, newRules);
753
- added.forEach((rule, i) => validateIgnoreEntry(rule, i));
754
- if (added.length > 0) {
755
- let existingRaw;
756
- try {
757
- existingRaw = await readFile(CONFIG_PATH, "utf8");
758
- } catch (e) {
759
- if (e.code !== "ENOENT") throw e;
760
- }
761
- await mkdir(dirname(CONFIG_PATH), { recursive: true });
762
- await writeFile(CONFIG_PATH, appendRulesToYaml(existingRaw, added));
782
+ const firstPass = mergeIgnoreRules((await loadConfig()).ignore, newRules);
783
+ firstPass.added.forEach((rule, i) => validateIgnoreEntry(rule, i));
784
+ if (firstPass.added.length === 0) return {
785
+ path: CONFIG_PATH,
786
+ added: firstPass.added,
787
+ alreadyPresent: firstPass.alreadyPresent
788
+ };
789
+ await mkdir(dirname(CONFIG_PATH), { recursive: true });
790
+ let existingRaw;
791
+ try {
792
+ existingRaw = await readFile(CONFIG_PATH, "utf8");
793
+ } catch (e) {
794
+ if (e.code !== "ENOENT") throw e;
763
795
  }
796
+ const { added, alreadyPresent } = mergeIgnoreRules(existingRaw !== void 0 && existingRaw.trim() !== "" ? (await loadConfig()).ignore : [], newRules);
797
+ if (added.length === 0) return {
798
+ path: CONFIG_PATH,
799
+ added,
800
+ alreadyPresent
801
+ };
802
+ await atomicWrite(CONFIG_PATH, appendRulesToYaml(existingRaw, added));
764
803
  return {
765
804
  path: CONFIG_PATH,
766
805
  added,
@@ -4333,6 +4372,14 @@ function canonicalizeStatement(s) {
4333
4372
  }
4334
4373
  return out;
4335
4374
  }
4375
+ const AWS_LOG_DELIVERY_ALLOWED_ACTIONS = new Set([
4376
+ "s3:PutObject",
4377
+ "s3:GetBucketAcl",
4378
+ "logs:CreateLogStream",
4379
+ "logs:PutLogEvents",
4380
+ "firehose:PutRecord",
4381
+ "firehose:PutRecordBatch"
4382
+ ]);
4336
4383
  function isAwsManagedLogDeliveryStatement(s) {
4337
4384
  if (!isObj(s)) return false;
4338
4385
  const sid = s.Sid;
@@ -4340,7 +4387,12 @@ function isAwsManagedLogDeliveryStatement(s) {
4340
4387
  const principal = s.Principal;
4341
4388
  if (!isObj(principal)) return false;
4342
4389
  const svc = principal.Service;
4343
- return (Array.isArray(svc) ? svc : [svc]).includes("delivery.logs.amazonaws.com");
4390
+ if (!(Array.isArray(svc) ? svc : [svc]).includes("delivery.logs.amazonaws.com")) return false;
4391
+ if (s.Effect !== "Allow") return false;
4392
+ const actionRaw = s.Action;
4393
+ const actions = Array.isArray(actionRaw) ? actionRaw : [actionRaw];
4394
+ if (actions.length === 0) return false;
4395
+ return actions.every((a) => typeof a === "string" && AWS_LOG_DELIVERY_ALLOWED_ACTIONS.has(a));
4344
4396
  }
4345
4397
  function canonicalizePrincipal(v) {
4346
4398
  if (isObj(v)) {
@@ -9350,21 +9402,30 @@ const failureWarned = /* @__PURE__ */ new Set();
9350
9402
  function describeTypeFailedWarning(resourceType, region) {
9351
9403
  return `warning: ${region}: cloudformation:DescribeType failed for ${resourceType} — schema-based drift suppression is degraded for this type. Undeclared read-only attributes may surface as [Potential Drift] and declared write-only properties may report false drift. Grant cloudformation:DescribeType (and retry if throttled) for full coverage.`;
9352
9404
  }
9353
- async function getSchemaInfo(client, resourceType) {
9405
+ async function getSchemaInfoResult(client, resourceType) {
9354
9406
  const region = await client.config.region();
9355
9407
  const cacheKey = `${region}\0${resourceType}`;
9356
9408
  const cached = cache.get(cacheKey);
9357
- if (cached) return cached;
9409
+ if (cached) return {
9410
+ info: cached,
9411
+ failed: false
9412
+ };
9358
9413
  const result = await fetch$1(client, resourceType);
9359
9414
  if (result.ok) {
9360
9415
  cache.set(cacheKey, result.info);
9361
- return result.info;
9416
+ return {
9417
+ info: result.info,
9418
+ failed: false
9419
+ };
9362
9420
  }
9363
9421
  if (!failureWarned.has(cacheKey)) {
9364
9422
  failureWarned.add(cacheKey);
9365
9423
  console.error(describeTypeFailedWarning(resourceType, region));
9366
9424
  }
9367
- return result.info;
9425
+ return {
9426
+ info: result.info,
9427
+ failed: true
9428
+ };
9368
9429
  }
9369
9430
  const OVERRIDE_READABLE_WRITEONLY = {
9370
9431
  "AWS::EC2::LaunchTemplate": ["LaunchTemplateData"],
@@ -9834,8 +9895,12 @@ async function readAddedModel(cc, cfn, c, schemas, oaiCanonicalIds) {
9834
9895
  Identifier: c.identifier
9835
9896
  }));
9836
9897
  const raw = JSON.parse(g.ResourceDescription?.Properties ?? "{}");
9837
- const schema = schemas.get(c.resourceType) ?? await getSchemaInfo(cfn, c.resourceType);
9838
- schemas.set(c.resourceType, schema);
9898
+ let schema = schemas.get(c.resourceType);
9899
+ if (!schema) {
9900
+ const res = await getSchemaInfoResult(cfn, c.resourceType);
9901
+ schema = res.info;
9902
+ if (!res.failed) schemas.set(c.resourceType, schema);
9903
+ }
9839
9904
  return {
9840
9905
  model: normalizeLiveModel(raw, schema, {
9841
9906
  oaiCanonicalIds,
@@ -9985,8 +10050,12 @@ async function classifyRead(cfn, r, read, schemas, classifyOpts) {
9985
10050
  path: "",
9986
10051
  note: read?.skippedReason ?? "not readable"
9987
10052
  }];
9988
- const schema = schemas.get(r.resourceType) ?? await getSchemaInfo(cfn, r.resourceType);
9989
- schemas.set(r.resourceType, schema);
10053
+ let schema = schemas.get(r.resourceType);
10054
+ if (!schema) {
10055
+ const res = await getSchemaInfoResult(cfn, r.resourceType);
10056
+ schema = res.info;
10057
+ if (!res.failed) schemas.set(r.resourceType, schema);
10058
+ }
9990
10059
  return classifyResource(r, read.live, schema, classifyOpts);
9991
10060
  }
9992
10061
  async function gatherFindings(stackName, region, templateOverride, recoveryTemplate) {
@@ -10501,9 +10570,33 @@ function carryForwardUnreadable(recorded, existing, findings) {
10501
10570
  * cleanly with #767's identity-sort case). Idempotency of the pipeline means an
10502
10571
  * already-canonical live value is unchanged, so this never weakens real change
10503
10572
  * detection: two values that differ after canonicalization still compare unequal.
10573
+ *
10574
+ * #767: `canonicalizeForCompare` only IDENTITY-sorts object arrays (by
10575
+ * Key/Id/Name/…), but the live model reaches a DIFFERENT total order — classify's
10576
+ * `sortUnorderedSetProps` runs `sortUnorderedObjectArray` (a full CANONICAL-JSON
10577
+ * sort) over unordered object-array props, and for an IDENTITY-LESS array the
10578
+ * identity-sort is a no-op, so the live `f.actual` lands in canonical-JSON order
10579
+ * while the recorded raw baseline stays in template order. `deepEqual` is
10580
+ * positional, so those two never converge — a permanent "changed since record" that
10581
+ * re-recording can't clear. Re-applying the SAME canonical-JSON sort (deeply) to
10582
+ * BOTH sides here drives them to one total order, restoring reflexivity
10583
+ * (`baselineValueMatches(v, v)` is true for identity-less arrays too). It is
10584
+ * SYMMETRIC and only REORDERS (never merges/drops elements), so two genuinely
10585
+ * different values still differ — change detection is preserved. Baseline compare is
10586
+ * type-agnostic over UNDECLARED snapshot fragments, which never carry an
10587
+ * order-significant declared array, so an order-insensitive sort is safe here.
10504
10588
  */
10505
10589
  function baselineValueMatches(baselineValue, currentCanonicalValue) {
10506
- return deepEqual(canonicalizeForCompare(baselineValue), canonicalizeForCompare(currentCanonicalValue));
10590
+ return deepEqual(sortObjectArraysDeep(canonicalizeForCompare(baselineValue)), sortObjectArraysDeep(canonicalizeForCompare(currentCanonicalValue)));
10591
+ }
10592
+ function sortObjectArraysDeep(v) {
10593
+ if (Array.isArray(v)) return sortUnorderedObjectArray(v.map(sortObjectArraysDeep));
10594
+ if (v && typeof v === "object") {
10595
+ const out = {};
10596
+ for (const [k, val] of Object.entries(v)) out[k] = sortObjectArraysDeep(val);
10597
+ return out;
10598
+ }
10599
+ return v;
10507
10600
  }
10508
10601
  const DELTA_IDENTITY_FIELDS = [
10509
10602
  "Key",
@@ -13410,6 +13503,41 @@ function stackLabel$1(stackName, region) {
13410
13503
  return `${stackName} (${region})`;
13411
13504
  }
13412
13505
  /**
13506
+ * Print the stack-state warning (#786) — a stack that is mid-operation (`*_IN_PROGRESS`)
13507
+ * or in a failed state (`*_FAILED`) carries a `stackStatusWarning` from `loadDesired`
13508
+ * (via `classifyStackStatus`). `check` prints it (`check.ts`), but the standalone
13509
+ * `record` / `ignore` / `revert` verbs never consumed it — so a `record` mid-`cdk deploy`
13510
+ * would snapshot transient values into the git baseline, and a `revert` would fight the
13511
+ * in-flight deploy, all silently. This centralizes the SAME wording/stderr routing check
13512
+ * uses so every verb surfaces the warning identically. No-op when the stack is stable.
13513
+ */
13514
+ function warnStackStatus(stackName, warning) {
13515
+ if (warning) console.error(`warning: ${stackName}: ${warning}`);
13516
+ }
13517
+ /**
13518
+ * TOCTOU guard (#786): re-read the stack's live `StackStatus` immediately before a
13519
+ * revert's Cloud Control / SDK write and REFUSE when it is mid-operation
13520
+ * (`*_IN_PROGRESS`). A stack stable at gather time can enter a `cdk deploy` while the
13521
+ * revert confirm prompt sits open — writing OLD values onto an updating stack fights the
13522
+ * deploy. `revert` is the one AWS-mutating verb, so the gate must be right before the
13523
+ * write, not only at gather time. Returns a refusal reason string when the write must be
13524
+ * refused, or `undefined` when it is safe to proceed. A DescribeStacks read error is NOT
13525
+ * treated as a refusal (fail-open: the gather already succeeded, so a transient re-read
13526
+ * failure should not block a legitimate revert) — only a confirmed in-progress state does.
13527
+ */
13528
+ async function stackInProgressRefusal(stackName, region) {
13529
+ let status;
13530
+ try {
13531
+ status = (await new CloudFormationClient({
13532
+ region,
13533
+ ...CLIENT_TIMEOUTS
13534
+ }).send(new DescribeStacksCommand({ StackName: stackName }))).Stacks?.[0]?.StackStatus;
13535
+ } catch {
13536
+ return;
13537
+ }
13538
+ if (status?.endsWith("_IN_PROGRESS")) return `refusing to write to AWS — ${stackName} is mid-operation (${status}). A revert now would fight the in-flight deploy/update. Wait for the stack to settle, then re-run.`;
13539
+ }
13540
+ /**
13413
13541
  * The revert confirm message (R52). When NOT-revertable findings exist (e.g. a
13414
13542
  * no-baseline first check with one declared drift and 100+ undeclared values),
13415
13543
  * users read "This WRITES to AWS" as "everything I just saw gets written" —
@@ -13903,6 +14031,15 @@ async function revertStack(p) {
13903
14031
  };
13904
14032
  }
13905
14033
  }
14034
+ const inProgress = await stackInProgressRefusal(stackName, region);
14035
+ if (inProgress) {
14036
+ console.error("\n" + inProgress);
14037
+ return {
14038
+ exit: 2,
14039
+ aborted: false,
14040
+ refusedReason: inProgress
14041
+ };
14042
+ }
13906
14043
  const cc = new CloudControlClient({
13907
14044
  region,
13908
14045
  ...CLIENT_TIMEOUTS
@@ -14125,6 +14262,7 @@ async function runRecord(args) {
14125
14262
  }
14126
14263
  try {
14127
14264
  const { desired, findings } = await gatherWithProgress(showProgress, progressLabel(idx, stacks.length, stackName, region), () => gatherFindings(stackName, region, void 0, template));
14265
+ warnStackStatus(stackName, desired.stackStatusWarning);
14128
14266
  const result = await recordStack({
14129
14267
  stackName,
14130
14268
  region,
@@ -14233,6 +14371,7 @@ async function runIgnore(args) {
14233
14371
  }
14234
14372
  try {
14235
14373
  const { desired, findings } = await gatherWithProgress(showProgress, progressLabel(idx, stacks.length, stackName, region), () => gatherFindings(stackName, region, void 0, template));
14374
+ warnStackStatus(stackName, desired.stackStatusWarning);
14236
14375
  const baseline = await loadBaseline(stackName, desired.accountId, region);
14237
14376
  if (baseline) checkBaselineAccount(baseline, desired.accountId, stackName);
14238
14377
  const result = await ignoreStack({
@@ -15550,6 +15689,7 @@ async function runRevert(args) {
15550
15689
  const gathered = await gatherWithProgress(showProgress, progressLabel(idx, stacks.length, stackName, region), () => gatherFindings(stackName, region, void 0, template));
15551
15690
  const baseline = await loadBaseline(stackName, gathered.desired.accountId, region);
15552
15691
  if (baseline) checkBaselineAccount(baseline, gathered.desired.accountId, stackName);
15692
+ warnStackStatus(stackName, gathered.desired.stackStatusWarning);
15553
15693
  const outcome = await revertStack({
15554
15694
  stackName,
15555
15695
  region,