cdk-real-drift 0.0.1 → 0.1.0

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
@@ -1,45 +1,667 @@
1
- # cdk-real-drift
1
+ # cdk-real-drift (`cdkrd`)
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
3
+ [![npm](https://img.shields.io/npm/v/cdk-real-drift)](https://www.npmjs.com/package/cdk-real-drift)
4
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
4
5
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
6
+ Drift detection for AWS CDK that sees what your template can't, including the
7
+ **properties you never declared**. **Detect** it, **record** it, or **revert** it.
6
8
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
9
+ **In a nutshell:**
8
10
 
9
- ## Purpose
11
+ ```text
12
+ live AWS state vs ( CFn template + AWS defaults + .cdkrd baseline )
13
+ ```
10
14
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `cdk-real-drift`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
+ `cdkrd` compares your real deployed resources against your intent, which is three
16
+ things combined:
15
17
 
16
- ## What is OIDC Trusted Publishing?
18
+ - **CFn template** — the properties you **declared**.
19
+ - **AWS defaults** — undeclared properties still sitting at their AWS default,
20
+ subtracted automatically (you maintain nothing here).
21
+ - **.cdkrd baseline** — a small committed file recording the **undeclared** values
22
+ that actually differ from the default and you've accepted.
17
23
 
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
24
+ The baseline is **optional**: with just the first two, `cdkrd` already catches
25
+ drift on your declared properties and undeclared properties that drift away from
26
+ their AWS default (plus out-of-band deletes) — no setup required. The baseline
27
+ only adds one more thing: confirming drift on undeclared values that were
28
+ non-default from the start, which your template never mentions.
19
29
 
20
- ## Setup Instructions
30
+ ## Why
21
31
 
22
- To properly configure OIDC trusted publishing for this package:
32
+ Someone tweaks one of your resources from the console: an extra inline policy on a
33
+ role, a bucket setting you never declared. CloudFormation drift detection only
34
+ compares properties that **appear in your template**, so it reports nothing:
23
35
 
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
36
+ ```bash
37
+ $ npx cdk drift
38
+ ✨ Number of resources with drift: 0
39
+ ```
28
40
 
29
- ## DO NOT USE THIS PACKAGE
41
+ `cdkrd` reads the **full** live resource model and subtracts everything
42
+ explainable, so the same change shows up:
30
43
 
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
44
+ ```console
45
+ $ npx cdkrd check
46
+ === check: ApiStack (us-east-1) ===
47
+ [CFn-Undeclared Drift: 1] (live-only (not in your CloudFormation template), changed from your .cdkrd baseline — the differentiator)
48
+ ApiRole.Policies (AWS::IAM::Role) — appeared since record
49
+ actual =[{"PolicyName":"manual-debug-access", ...}]
36
50
 
37
- ## More Information
51
+ ─────────────────────────────────
52
+ result: 1 drift(s) (undeclared=1)
53
+ ─────────────────────────────────
54
+ ```
38
55
 
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
56
+ ![cdkrd finds an out-of-band inline policy that `cdk drift` reports as zero](demo/demo.gif)
42
57
 
43
- ---
58
+ | Capability | `cdkrd` | `cdk drift` / CFn drift detection |
59
+ | -------------------------------------------------------------- | :-----: | :-------------------------------: |
60
+ | Drift on **declared** properties (+ out-of-band deletes) | ✅ | ✅ |
61
+ | Drift on **undeclared** properties | ✅ | ❌ |
62
+ | **Added** out-of-band resources (not in template) | ✅ | ❌ |
63
+ | **Revert** declared drift | ✅ | ✅ `cdk deploy --revert-drift` |
64
+ | **Revert** undeclared drift | ✅ | ❌ |
65
+ | **Ignore / accept** a drift, incl. a **declared** one | ✅ | ❌ |
66
+ | **Record** undeclared / added state as a reviewed git baseline | ✅ | ❌ |
44
67
 
45
- **Maintained for OIDC setup purposes only**
68
+ ## Quick start
69
+
70
+ ```bash
71
+ npm install -D cdk-real-drift # in your CDK project
72
+ npx cdkrd check # checks every stack your app defines
73
+ ```
74
+
75
+ `check` is the only command you run by hand, with nothing to set up first: it
76
+ finds drift and offers **Record**, **Revert**, and **Ignore** inline on what it
77
+ turns up.
78
+
79
+ ## How to use
80
+
81
+ ### Your first run needs no baseline
82
+
83
+ The first time you run `check` on a stack, before recording anything:
84
+
85
+ ```console
86
+ === check: ApiStack (us-east-1) ===
87
+ No baseline yet — live-only values can't be confirmed as drift, but declared drift and out-of-band deletes always can.
88
+
89
+ [CFn-Declared Drift: 1] (declared in your CloudFormation template — the live value differs)
90
+ Topic.DisplayName (AWS::SNS::Topic)
91
+ desired="prod-alerts"
92
+ actual ="test"
93
+
94
+ [Potential Drift: 2] (live-only and not yet in your .cdkrd baseline, so cdkrd can't tell whether it's intended or an out-of-band change — Record to accept it, or Revert to remove it)
95
+ Queue.RedrivePolicy (AWS::SQS::Queue)
96
+ actual ={"maxReceiveCount":5}
97
+ Role.Policies (AWS::IAM::Role)
98
+ actual =[{"PolicyName":"adhoc", ...}]
99
+
100
+ ─────────────────────────────────────────────────────────────
101
+ result: 3 findings — 1 drift (declared=1) + 2 potential drift
102
+ ─────────────────────────────────────────────────────────────
103
+
104
+ ApiStack: drift found — what do you want to do?
105
+ ❯ Nothing (decide later)
106
+ Record undeclared (live-only) — snapshot into the .cdkrd baseline (keeps watching)
107
+ Revert — write the desired values back to AWS
108
+ Ignore — stop reporting it (writes .cdkrd/ignore.yaml)
109
+ Decide per finding — assign a different action to each
110
+ ```
111
+
112
+ Each block above is one kind of finding, and neither needed a baseline:
113
+
114
+ - **`[CFn-Declared Drift]`**: a property you declared changed out of band, so it's
115
+ confirmed against your template right away (deletes of declared resources are
116
+ confirmed the same way).
117
+ - **`[Potential Drift]`**: settings that live only on the real resource, not in
118
+ your template. cdkrd detects these too: it strips the obvious noise (AWS
119
+ defaults, auto-generated names) so what's left is the values most likely to be
120
+ real drift. They're only _potential_ because there's no baseline yet — and,
121
+ being an unconfirmed best-effort guess, this is the one tier that **can include
122
+ false positives** (an AWS-managed default or noise the fold tables didn't yet
123
+ strip). Confirmed `[CFn-Declared Drift]` never guesses. If a potential-drift
124
+ value is really noise, [please report it](https://github.com/go-to-k/cdk-real-drift/issues)
125
+ so it becomes a fold-table fix.
126
+
127
+ At the prompt you act on each finding: **record** it (accept and watch),
128
+ **revert** it (undo the change), or **ignore** it (stop reporting).
129
+
130
+ ### Recording
131
+
132
+ Recording snapshots those live-only values into a git-committed `.cdkrd` baseline,
133
+ so from then on any later out-of-band change to them is confirmed drift. That's the
134
+ day-to-day loop: run `check`, record what's intended, commit the baseline, and the
135
+ next out-of-band change stands out on its own.
136
+
137
+ With `Role.Policies` recorded, an inline policy added later out of band now
138
+ surfaces as **`[CFn-Undeclared Drift]`**: confirmed drift on a value that isn't in
139
+ your CloudFormation template, the kind `cdk drift` can't see:
140
+
141
+ ```console
142
+ === check: ApiStack (us-east-1) ===
143
+ [CFn-Undeclared Drift: 1] (live-only (not in your CloudFormation template), changed from your .cdkrd baseline — the differentiator)
144
+ Role.Policies (AWS::IAM::Role) — changed since record
145
+ actual =[{"PolicyName":"adhoc", ...}, {"PolicyName":"manual-debug-access", ...}]
146
+
147
+ ─────────────────────────────────
148
+ result: 1 drift(s) (undeclared=1)
149
+ ─────────────────────────────────
150
+ ```
151
+
152
+ `record` covers live-only state only, not a `[CFn-Declared Drift]`; the other
153
+ verbs are in [The model](#the-model-one-verb-you-run-three-it-offers).
154
+
155
+ ### In CI
156
+
157
+ Run `npx cdkrd check --fail`. It's read-only, never prompts, and exits 1 on drift;
158
+ it never writes a baseline (you record locally and commit the file).
159
+
160
+ ## The model: one verb you run, three it offers
161
+
162
+ `cdkrd check` is the entry point: on a TTY it finds drift and offers the other
163
+ three as inline actions.
164
+
165
+ All four are also standalone commands for non-TTY use (scripting / CI). Here's what
166
+ each does, run on its own:
167
+
168
+ | verb | meaning | writes |
169
+ | -------------- | -------------------------------------------------------------------- | ----------------------------------- |
170
+ | `cdkrd check` | find drift (the one you run) | nothing; the 3 below do the writing |
171
+ | `cdkrd record` | "this undeclared / added state is the norm; tell me if it _changes_" | a git file (baseline) |
172
+ | `cdkrd ignore` | "stop reporting this property, ever" | a git file (`ignore.yaml`) |
173
+ | `cdkrd revert` | "this state is wrong"; write the desired value back | AWS (plan + confirm) |
174
+
175
+ The scopes differ: `record` is **undeclared / added only**, while `ignore` works on
176
+ **any** tier. It's the only in-tool way to accept a **declared** drift without
177
+ editing code or reverting.
178
+
179
+ `check`, `record`, and `ignore` never write to AWS. `revert` is the one mutating
180
+ verb and always confirms first (`--dry-run` to preview, `--yes` to skip the
181
+ prompt). Baselines stay a reviewed, git-committed artifact either way; CI never
182
+ writes one. It re-reads each touched resource afterward to verify it converged:
183
+
184
+ ```console
185
+ === revert: ApiStack (us-east-1) ===
186
+
187
+ ApiRole (AWS::IAM::Role)
188
+ - Policies -> remove (undeclared, not in baseline)
189
+
190
+ Apply 1 revert op(s) to ApiStack? This WRITES to AWS. · yes
191
+ reverted: ApiRole
192
+
193
+ verifying convergence (re-reading 1 resource(s))...
194
+ ApiStack: CLEAN after revert.
195
+ ```
196
+
197
+ Picking an action lets you choose **which** findings it touches; after a Record or
198
+ Ignore the prompt re-offers anything still drifting, so you finish in one run. Full
199
+ prompt mechanics (multiselect, Decide per finding, key bindings) are under
200
+ [Interactive prompts](#interactive-prompts-tty-only-ci-is-never-prompted).
201
+
202
+ ## How drift is judged
203
+
204
+ cdkrd compares the **live AWS resource** against your deployed **CloudFormation
205
+ template** (or your local synth with `--pre-deploy`). It's reality vs intent,
206
+ **not** a line-by-line diff of your CDK source the way `cdk diff` works, so
207
+ undeployed code changes don't show up as drift by default. `--pre-deploy` inverts
208
+ that, checking live state against the freshly synthesized template (see
209
+ [`--pre-deploy`](#--pre-deploy)).
210
+
211
+ ### The kinds of drift
212
+
213
+ Named so "declared" is never ambiguous (`CFn-declared` means **in the deployed
214
+ template**, not your CDK code and not your `.cdkrd` baseline):
215
+
216
+ | term | source | how it's judged |
217
+ | ------------------------------ | ------------------------------------ | ----------------------------------------------------------------------- |
218
+ | **CFn-declared** | in the deployed template | vs the deployed template; drift from the first run, no baseline needed |
219
+ | **CFn-undeclared** (live-only) | on the resource, not in the template | vs your `.cdkrd` baseline; the key differentiator |
220
+ | **Added resource** | a whole resource not in the template | reconciled against the baseline like an undeclared property (see below) |
221
+ | **Deleted** | in the template, gone live | the most blatant drift; always fails `--fail` |
222
+
223
+ (`CFn-undeclared` is a template axis; `recorded` / `unrecorded` is a separate
224
+ baseline-file axis: whether you've snapshotted that value yet.)
225
+
226
+ The mechanics:
227
+
228
+ - **Until a stack's first `record`, undeclared / added state is `unrecorded`:**
229
+ informational, CLEAN, never fails `--fail`.
230
+ [Recording](#recording) is what arms detection,
231
+ turning a later out-of-band change into failing drift. The baseline is a
232
+ git-committed JSON file at `.cdkrd/baselines/<stack>.<accountId>.<region>.json`
233
+ (reviewable; account id + region in the name prevent cross-account collisions).
234
+ - **There is no watch-list to maintain.** Every `check` snapshots the full live
235
+ model (Cloud Control API + SDK readers for the gap types) and subtracts everything
236
+ explainable: schema read-only/write-only/defaults, AWS-managed fields, `aws:*`
237
+ tags, policy-document and ordering noise. What survives is signal.
238
+ - **Anything not confidently comparable is reported honestly** (`readGap` /
239
+ `unresolved` / `skipped`), never guessed, so no false drift.
240
+
241
+ ### Added out-of-band resources
242
+
243
+ A whole child resource that exists live but isn't in your template (e.g. an API
244
+ Gateway `ANY` method added on `/` via the console) is the resource-level sibling
245
+ of an undeclared property, and is reconciled the same way against your baseline:
246
+
247
+ | state | reported as |
248
+ | --------------------------- | ---------------------------------------------- |
249
+ | added, **not** recorded | **Potential Drift** (no baseline, unconfirmed) |
250
+ | recorded, unchanged | suppressed |
251
+ | recorded, **changed** since | failing drift |
252
+
253
+ `cdk drift` / CFn drift detection compare only template-declared resources, so an
254
+ out-of-band addition is invisible to them. Decide it like any finding: `record`
255
+ snapshots its full live model and watches it, `ignore` accepts it, or `revert`
256
+ **deletes** it (Cloud Control `DeleteResource`, behind the usual confirm /
257
+ `--dry-run` / picker; an unrecorded one needs `--remove-unrecorded`).
258
+
259
+ <details>
260
+ <summary>Covered parent types (the <code>CHILD_ENUMERATORS</code> registry, growing per type)</summary>
261
+
262
+ - **API Gateway REST**: resources, methods, authorizers, models, request
263
+ validators, gateway responses
264
+ - **API Gateway V2** (HTTP / WebSocket): routes, integrations, authorizers, stages
265
+ - **SNS**: topic subscriptions
266
+ - **Lambda**: event source mappings, function URLs, aliases, versions
267
+ - **EventBridge**: bus rules
268
+ - **Cognito**: user pool clients, groups, resource servers
269
+ - **AppSync**: data sources, resolvers, functions
270
+ - **CloudWatch Logs**: metric filters, subscription filters
271
+ - **ELBv2**: listeners, listener rules
272
+ - **EC2**: VPC subnets, route table routes
273
+ - **ECS**: cluster services
274
+ - **KMS**: key aliases
275
+ - **AppConfig**: application environments, configuration profiles
276
+ - **EFS**: file system mount targets
277
+ - **RDS**: database cluster instances
278
+
279
+ </details>
280
+
281
+ Full design and rationale: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
282
+
283
+ ## Selecting stacks
284
+
285
+ | invocation | what is checked |
286
+ | --------------------- | ------------------------------------------------------------- |
287
+ | `cdkrd check` | every stack the CDK app defines, each in its own `env.region` |
288
+ | `cdkrd check 'Dev*'` | glob, matched against the app's stack names |
289
+ | `cdkrd check MyStack` | one stack, selected by name from the app |
290
+
291
+ cdkrd resolves your CDK app to discover which stacks exist and to label findings by
292
+ construct path. The app comes from `cdk.json` (when run in the project directory) or
293
+ from `--app`: a command (`--app "node bin/app.js"`) or a pre-synthesized assembly
294
+ (`--app cdk.out`, read not executed); `$CDKRD_APP` also works. The drift
295
+ comparison still reads each stack's **deployed** template + live state from AWS;
296
+ synth only tells cdkrd which stacks to look at.
297
+
298
+ ## Commands & options
299
+
300
+ | command | does |
301
+ | --------------------------- | ---------------------------------------------------------------------- |
302
+ | `cdkrd check [<stack>...]` | compare live state vs template (declared) + baseline (undeclared) |
303
+ | `cdkrd record [<stack>...]` | snapshot undeclared + added state into the baseline (CI: `--yes`) |
304
+ | `cdkrd ignore [<stack>...]` | stop reporting chosen drift via `.cdkrd/ignore.yaml` (CI: `--yes`) |
305
+ | `cdkrd revert [<stack>...]` | write the desired value back to AWS (confirms; `--dry-run` to preview) |
306
+
307
+ Day to day you run only `cdkrd check` and act from its prompt; the standalone
308
+ `record` / `ignore` / `revert` are the **same actions** for scripting / non-TTY /
309
+ CI (with `--yes`).
310
+
311
+ ### Exit codes
312
+
313
+ - `check` is **report-only by default**: drift prints but exits `0` (a note names
314
+ the flag).
315
+ - **`--fail`** (the `cdk diff --fail` / `cdk drift --fail` convention) exits `1` on
316
+ drift and suppresses all prompts. It's the one flag for scripts and CI.
317
+ - **`--strict`** is the orthogonal **coverage** axis: it exits `1` when a run was
318
+ incomplete (any resource skipped, or a nested stack not recursed into). The gap
319
+ is always surfaced regardless (as the `skipped=N` footer line or a loud
320
+ `warning:`); `--strict` only decides whether it fails the build.
321
+ - Errors always exit `2`; `revert` exits `1` when drift remains after it.
322
+
323
+ ```yaml
324
+ - run: npm ci # cdkrd resolves the CDK app, so its deps must be installed
325
+ - run: npx cdkrd check --fail --region us-east-1 # fails the job on drift
326
+ # or point at a prebuilt assembly artifact instead of synthesizing:
327
+ # - run: npx cdkrd check --fail --app cdk.out --region us-east-1
328
+ ```
329
+
330
+ ### Options
331
+
332
+ | option | meaning |
333
+ | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
334
+ | `--region <r>` | AWS region (or `$AWS_REGION` / `$AWS_DEFAULT_REGION`); else `env.region` per stack, else the `--profile`'s region |
335
+ | `--profile <p>` | AWS profile (or `$AWS_PROFILE`) |
336
+ | `-a, --app <cmd\|cdk.out>` | CDK app command or pre-synthesized assembly dir (or `$CDKRD_APP` / cdk.json `"app"`); stack auto-discovery + construct paths |
337
+ | `-c, --context key=value` | context for synth (repeatable; cdk.json is the base layer) |
338
+ | `--all` | target every stack the app defines (the default when no `<stack>` is named; overrides any positional names) |
339
+ | `--json` | machine-readable output (see [JSON contract](#json-output-contract)) |
340
+ | `--fail` | (check) exit 1 on drift and never prompt; for scripts/CI. Without it, check reports drift but exits 0 |
341
+ | `--strict` | (check) exit 1 when coverage is incomplete. A coverage gap is always surfaced loudly; `--strict` makes it CI-failing. Orthogonal to `--fail` |
342
+ | `--show-all` | inventory mode: show all current undeclared state, ignoring the baseline |
343
+ | `--verbose` / `-v` | (check) expand the `info:` footer tiers / (revert) expand the per-reason not-revertable summary to full lists |
344
+ | `--pre-deploy` | (check) compare live vs the LOCAL synth template: the declared drift your next `cdk deploy` would silently overwrite |
345
+ | `--undeclared-only` | (check) undeclared drift only: pair cdkrd with `cdk drift` for the declared side |
346
+ | `--declared-only` | (check) declared drift vs the deployed template only (undeclared tier skipped; baseline untouched). Not `--pre-deploy` |
347
+ | `--dry-run` | (revert) print the plan; make no changes |
348
+ | `--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`) |
349
+ | `--remove-unrecorded` | (revert) REMOVE unrecorded values + DELETE unrecorded added resources in a no-prompt run (`--yes`/CI); an interactive revert already lists them |
350
+ | `--yes` / `-y` | skip confirmations (revert apply; record records all without the multiselect) |
351
+
352
+ Unknown options (`--apq`) and options missing their value (`--app` at the end of
353
+ the line) are errors (exit `2`): a typo'd flag never silently becomes a stack name.
354
+
355
+ ### Interactive prompts (TTY only, CI is never prompted)
356
+
357
+ Every option runs exactly the same code as the standalone commands. Prompts are
358
+ skipped under `--json`, `--show-all`, `--pre-deploy`, and `--fail`. A non-TTY run
359
+ never prompts: a required write decision without `--yes` errors with exit 2 (the
360
+ safe side); `--yes` alone in a TTY auto-approves confirmations only (select prompts
361
+ still show).
362
+
363
+ - **`check` with drift** offers `Record / Revert / Ignore / Decide per finding /
364
+ Nothing` (see [The model](#the-model-one-verb-you-run-three-it-offers)). Each
365
+ option appears only when it applies (no Revert if nothing is revertable; "Decide per finding" only
366
+ with >1 finding). Aborting the Revert confirmation writes nothing.
367
+ - **`revert`** shows the plan, then a multiselect of the op(s) to write. **Every op
368
+ starts unselected**: it's the one command that writes to AWS, so you opt in to
369
+ each write. REMOVE ops (deleting a live value not in your template) are labeled
370
+ `(REMOVE)`. **space** toggles · **→** selects all · **←** clears all · **enter**
371
+ confirms. `--yes` applies the full plan.
372
+ - **`record`** shows a multiselect of only the **delta** from the existing baseline
373
+ (new + changed values, pre-selected); already-recorded unchanged values are
374
+ auto-kept. Deselect a suspicious one and it stays reported by `check`. Nested
375
+ undeclared sub-keys (a value inside an object you _did_ declare) are listed in
376
+ full alongside the top-level ones — a non-default one is a real out-of-band
377
+ setting, so it is surfaced, not hidden. `record` writes only undeclared + added
378
+ state; any declared /
379
+ deleted drift is not written and `record` prints a note that it still stands
380
+ (resolve with `revert` or `cdk deploy`).
381
+ - **`Decide per finding`** assigns a different action to each finding. On a busy
382
+ stack, **just start typing to filter** the rows (↑↓ move · space cycles a row's
383
+ actions · → applies the focused action to every visible row · enter applies).
384
+ - **Folded inventory**: if `check` folded undeclared values out of the report,
385
+ Ignore / Decide first ask whether to act on just the shown drift (default) or the
386
+ folded values too, so the picker never lists values you never saw.
387
+
388
+ ### `--pre-deploy`
389
+
390
+ Normal `check` asks "did reality drift from what I deployed?". `--pre-deploy` asks
391
+ the inverse, **right before a deploy**: "which LIVE values would my local code
392
+ overwrite?" It compares live state against your **local synth** template, so a
393
+ console hot-fix made during an incident shows up before `cdk deploy` silently
394
+ reverts it:
395
+
396
+ ```console
397
+ $ npx cdkrd check --pre-deploy
398
+ (--pre-deploy) comparing live state against the LOCAL synth template
399
+ === check: ApiStack (us-east-1) ===
400
+ [CFn-Declared Drift: 1]
401
+ Api/Handler.MemorySize (AWS::Lambda::Function)
402
+ desired=1024
403
+ actual =2048
404
+
405
+ ───────────────────────────────
406
+ result: 1 drift(s) (declared=1)
407
+ ───────────────────────────────
408
+ ```
409
+
410
+ `desired` is what your local code is about to set; `actual` is live now: someone
411
+ bumped memory to 2048 out of band. Port it into code (or decide it should go away)
412
+ before deploying. As a pipeline gate:
413
+
414
+ ```yaml
415
+ - run: npx cdkrd check --pre-deploy --fail # block the deploy on clobber risk
416
+ - run: npx cdk deploy --all --require-approval never
417
+ ```
418
+
419
+ `--pre-deploy` reports **declared** drift only (the undeclared tier is defined
420
+ against the _deployed_ template) and never touches the baseline.
421
+
422
+ ### Ignoring externally-managed properties
423
+
424
+ Some properties are _legitimately_ rewritten by another system, such as Application
425
+ Auto Scaling moving an ECS Service `DesiredCount`, or autoscaled DynamoDB capacity.
426
+ A recorded snapshot would re-flag every move. Run **`cdkrd ignore`** to pick the
427
+ drift to suppress, or hand-edit the git-committed `.cdkrd/ignore.yaml`. It is a
428
+ hand-edited policy file (the `.gitignore` / `.dockerignore` / `.trivyignore`
429
+ family), so it is YAML rather than JSON: the single most valuable hand-edit is a
430
+ `#` comment recording **why** a property is ignored, and YAML can carry it where
431
+ JSON cannot. (The companion baseline stays JSON because it is the opposite —
432
+ machine-generated, wholesale-rewritten data, not human policy.)
433
+
434
+ ```yaml
435
+ # cdkrd ignore rules — properties cdkrd should stop reporting as drift.
436
+ ignore:
437
+ # DesiredCount is managed by Application Auto Scaling
438
+ - path: '*.DesiredCount'
439
+ # the common case: scope a rule to one stack
440
+ - path: '*.DesiredCount'
441
+ stack: Prod*
442
+ # narrow further to a single account and/or region when the same stack
443
+ # name is deployed to several (a property may legitimately drift in only one)
444
+ - path: Fn*.ReservedConcurrentExecutions
445
+ stack: Prod*
446
+ account: '111111111111'
447
+ region: ap-northeast-1
448
+ ```
449
+
450
+ - Every rule is a mapping `{ path, stack?, account?, region? }`. `cdkrd ignore`
451
+ writes the unscoped form (and is **comment-preserving and append-only**: it keeps
452
+ your existing comments and layout, and appends new rules at the end — you own the
453
+ order). `path` is an exact `<constructPath>.<path>` — the construct path WITHIN the
454
+ stack (the stack/Stage prefix stripped), byte-identical to what `cdkrd check` prints, so
455
+ you can copy what you see (or `<logicalId>.<path>` on a non-CDK stack). Rules written with
456
+ the older full `<stack>/<constructPath>.<path>` form still match. The optional `stack` /
457
+ `account` / `region` scopes are a hand-edit.
458
+ - All four fields accept the same `*` / `?` glob, and a parent `path` covers child
459
+ paths. The three scope axes — **stack, account, region** — are exactly the
460
+ baseline file's identity axes. **Account** keeps a `stack: "Prod*"` rule from
461
+ leaking into a same-named stack in another account (stack-name uniqueness only
462
+ holds within one account / App); **region** is independent the same way — the same
463
+ stack in several accounts or regions may drift in only one.
464
+ - Matching findings move to the informational `ignored` tier: visible under
465
+ `--verbose`, never exit-affecting, excluded from `revert` and `record`. A
466
+ **deleted resource is never ignorable**.
467
+
468
+ ## Output
469
+
470
+ Two parts: the **drift sections** in full detail, then a one-line `info:` footer
471
+ that folds everything informational.
472
+
473
+ ```console
474
+ === check: ApiStack (us-east-1) ===
475
+ [CFn-Declared Drift: 1]
476
+ UploadBucket.VersioningConfiguration.Status (AWS::S3::Bucket)
477
+ desired="Enabled"
478
+ actual ="Suspended"
479
+
480
+ ───────────────────────────────
481
+ result: 1 drift(s) (declared=1)
482
+ ───────────────────────────────
483
+ info:
484
+ - readGap=1 (declared but unverifiable — AWS doesn't return them on read, not drift: 1 write-only)
485
+ - skipped=2 (custom resource 2)
486
+ run with --verbose for the list
487
+ ```
488
+
489
+ - **Drift tiers** (`deleted` / `declared` / `undeclared`) are always listed in
490
+ full and drive the `--fail` exit. They are the point.
491
+ - **`[Potential Drift: N]`**: undeclared values with no baseline yet; cdkrd
492
+ can't tell an intentional setting from an out-of-band change, so they're listed
493
+ in full as _potential_ (unconfirmed) drift and don't drive the `--fail` exit;
494
+ `result:` points you at `cdkrd record` to accept them (or `revert` to remove).
495
+ Once a resource is fully snapshotted, a value that _appears_ later is real drift
496
+ (`appeared since record`).
497
+ - **`↳` origin hint**: when a finding's live value has a recognizable external
498
+ source — e.g. the CloudWatch Application Signals / Lambda Insights
499
+ auto-instrumentation footprint (an added Insights layer + tracer execution
500
+ policy, typically enabled account-wide, not per-resource) — a `↳` line names
501
+ the likely source. It's an explanation only: the finding is still real drift and
502
+ still drives the exit, so an unexpected account-wide enablement is never hidden.
503
+ - **`info:` footer** folds the informational tiers to per-reason counts
504
+ (`--verbose` expands them):
505
+
506
+ | tier | what it folds |
507
+ | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
508
+ | `atDefault` | an undeclared value sitting at a known AWS default (e.g. Lambda `TracingConfig: PassThrough`). Equality-gated, so a change away from it re-surfaces; never recorded. |
509
+ | `generated` | an undeclared value AWS/CDK minted, like an auto `TopicName`. Equality-gated; never recorded. |
510
+ | `nested` | an undeclared sub-key inside a property you _did_ declare (e.g. a CloudFront origin gaining `ConnectionTimeout`, or an API Gateway method's `Integration.PassthroughBehavior`). Surfaced in full like a top-level undeclared value — a non-default nested value is a real out-of-band setting — and recordable. (Catalogued AWS defaults are folded upstream as `atDefault`/`generated`, so only genuine settings remain.) |
511
+ | `readGap` / `unresolved` / `skipped` / `ignored` | values cdkrd can't confidently compare, reported honestly rather than guessed (never false drift). |
512
+
513
+ `^result:` is the greppable verdict, framed by a horizontal rule when there is
514
+ drift so it stands out from the findings above (a CLEAN stack stays compact).
515
+ Colorized on a TTY (`NO_COLOR` respected): red/yellow/green for the verdicts and
516
+ tiers, while explanatory prose (tier notes, the `↳` hint, the `info:` footer) uses
517
+ your terminal's default foreground so it stays legible on any theme — dim/gray is
518
+ reserved for picker rows you aren't on. Piped / CI / `--json` output is plain text.
519
+
520
+ ### JSON output contract
521
+
522
+ `--json` emits
523
+ `{ "stack": "<name> (<region>)", "drifted": <n>, "findings": [...] }`.
524
+ Each finding has a stable shape: `tier` (`deleted` | `declared` | `undeclared` |
525
+ `readGap` | `unresolved` | `skipped` | `ignored`), `logicalId`, `resourceType`,
526
+ `path`, `desired`, `actual`, `note`, `physicalId`, `constructPath`. An unrecorded
527
+ value keeps `tier: "undeclared"` and carries `"unrecorded": true`; `drifted`
528
+ excludes it. The output always carries every finding regardless of `--verbose`.
529
+ After publication this shape is a backward-compatible API.
530
+
531
+ ## IAM permissions
532
+
533
+ `check` / `record` are **read-only**: the AWS managed `ReadOnlyAccess` policy
534
+ covers them. **If you never run `revert`, cdkrd needs no write permissions at all.**
535
+
536
+ <details>
537
+ <summary>Minimal read permissions (check / record)</summary>
538
+
539
+ - `cloudformation:GetTemplate`, `ListStackResources`, `DescribeStacks`,
540
+ `DescribeType`; `ListExports` (only for templates using `Fn::ImportValue`)
541
+ - `cloudcontrol:GetResource`: Cloud Control invokes each type's own read handler,
542
+ so it needs that type's read permissions (this is why `ReadOnlyAccess` is the
543
+ simple answer)
544
+ - SDK readers for the Cloud-Control-gap types: `s3:GetBucketPolicy`,
545
+ `sns:GetTopicAttributes`, `sqs:GetQueueAttributes`, `iam:GetRolePolicy`,
546
+ `iam:GetUserPolicy`, `iam:GetGroupPolicy`, `iam:GetPolicy`, `iam:GetPolicyVersion`,
547
+ `lambda:GetPolicy`, `budgets:ViewBudget`, `ec2:DescribeAddresses`,
548
+ `ec2:DescribeLaunchTemplateVersions`, `ec2:DescribeNetworkAcls`,
549
+ `route53:ListResourceRecordSets`,
550
+ `ses:DescribeReceiptRuleSet`, `ses:DescribeReceiptRule`, `ses:ListReceiptFilters`
551
+ (the SES inbound receipt-rule family — `ReceiptRuleSet` / `ReceiptRule` /
552
+ `ReceiptFilter` — has no Cloud Control handlers),
553
+ `glue:GetTable`, `logs:DescribeMetricFilters`, `scheduler:GetSchedule`,
554
+ `cloudwatch:DescribeAnomalyDetectors` (reads an
555
+ `AWS::CloudWatch::AnomalyDetector` — NON_PROVISIONABLE, no Cloud Control
556
+ handlers),
557
+ `dlm:GetLifecyclePolicy` (reads an `AWS::DLM::LifecyclePolicy` — a Data
558
+ Lifecycle Manager EBS-snapshot / AMI backup-schedule policy, NON_PROVISIONABLE
559
+ with no Cloud Control handlers; the physical id IS the policy id),
560
+ `dms:DescribeEndpoints` + `dms:DescribeReplicationSubnetGroups` (read an
561
+ `AWS::DMS::Endpoint` / `AWS::DMS::ReplicationSubnetGroup` — the classic DMS
562
+ migration/CDC family, NON_PROVISIONABLE with no Cloud Control handlers),
563
+ `mediaconvert:GetQueue` + `mediaconvert:GetJobTemplate` (read an
564
+ `AWS::MediaConvert::Queue` / `AWS::MediaConvert::JobTemplate` — a video-pipeline
565
+ staple, NON_PROVISIONABLE with no Cloud Control handlers; the physical id IS the
566
+ resource name),
567
+ `ssm:DescribeParameters` (supplements the Cloud Control read of an
568
+ `AWS::SSM::Parameter` with its writeOnly `Description` / `AllowedPattern`),
569
+ `elasticache:DescribeReplicationGroups` + `elasticache:DescribeCacheClusters`
570
+ (supplement an `AWS::ElastiCache::ReplicationGroup` with its writeOnly
571
+ `PreferredMaintenanceWindow` / `NotificationTopicArn` / `EngineVersion`, read
572
+ from the member cache cluster), `ecs:DescribeServices` (supplements an
573
+ `AWS::ECS::Service` with its writeOnly `ServiceConnectConfiguration` /
574
+ `VolumeConfigurations`, read from the PRIMARY deployment),
575
+ `elasticache:DescribeUsers` + `memorydb:DescribeUsers` (supplement an
576
+ `AWS::ElastiCache::User` / `AWS::MemoryDB::User` with its writeOnly
577
+ `AccessString` — the Redis/Valkey ACL; an out-of-band permission grant is
578
+ otherwise invisible to the Cloud Control read),
579
+ `redshift-serverless:GetWorkgroup` (supplements an
580
+ `AWS::RedshiftServerless::Workgroup` with its writeOnly `ConfigParameters` /
581
+ `SecurityGroupIds` / `SubnetIds`, which the Cloud Control read returns only
582
+ inside its read-only echo attribute — an out-of-band security-group swap or
583
+ config-parameter change is otherwise invisible),
584
+ `kafka:DescribeConfiguration` + `kafka:DescribeConfigurationRevision`
585
+ (supplement an `AWS::MSK::Configuration` with its writeOnly `ServerProperties`
586
+ Kafka blob — an out-of-band `update-configuration` revision is otherwise
587
+ invisible),
588
+ `servicediscovery:GetNamespace` (reads a Cloud Map
589
+ `HttpNamespace` / `PrivateDnsNamespace` / `PublicDnsNamespace` — incl. the Arn an
590
+ ECS Service Connect namespace `Fn::GetAtt` resolves against)
591
+ - Optional: `elasticloadbalancing:GetTrustStoreCaCertificatesBundle` records a
592
+ content hash of an `AWS::ElasticLoadBalancingV2::TrustStore`'s live mTLS CA
593
+ bundle (`CaCertificatesBundleSha256`) so an out-of-band CA-bundle swap
594
+ re-surfaces as drift — otherwise invisible (the bundle location is write-only).
595
+ It fetches the presigned S3 URL the API returns; without the permission (or on
596
+ any fetch failure) the signal is skipped, never false-flagged.
597
+ - Optional: `kms:ListAliases` enables strict verification that a declared
598
+ `alias/aws/*` key was not swapped for a customer-managed key. Without it that case
599
+ is conservatively suppressed AND cdkrd prints a one-line warning per region (the
600
+ swap would otherwise go undetected), so the reduced coverage is never silent.
601
+
602
+ </details>
603
+
604
+ <details>
605
+ <summary>Additional write permissions (revert)</summary>
606
+
607
+ `cloudcontrol:UpdateResource` (which resolves to each type's own update
608
+ permissions), plus, for the SDK-written types: `s3:PutBucketPolicy` /
609
+ `s3:DeleteBucketPolicy`, `sns:SetTopicAttributes`, `sqs:SetQueueAttributes`,
610
+ `iam:PutRolePolicy` / `DeleteRolePolicy` / `PutUserPolicy` / `PutGroupPolicy`,
611
+ `iam:CreatePolicyVersion` / `DeletePolicyVersion` / `ListPolicyVersions`,
612
+ `elasticloadbalancing:ModifyLoadBalancerAttributes` / `ModifyTargetGroupAttributes`,
613
+ `glue:UpdateTable`, `glue:UpdateConnection` (reverts an `AWS::Glue::Connection` —
614
+ the whole `ConnectionInput` is re-supplied; a connection with an inline password
615
+ is refused, never overwritten, so the un-read credential is never cleared),
616
+ `logs:PutMetricFilter`, `route53:ChangeResourceRecordSets`,
617
+ `ses:UpdateReceiptRule` (reverts an `AWS::SES::ReceiptRule` — the whole rule is
618
+ re-supplied in place, since Cloud Control has no handler for the type),
619
+ `cloudwatch:PutAnomalyDetector` (reverts an `AWS::CloudWatch::AnomalyDetector`
620
+ `Configuration` drift — an upsert keyed on the detector's createOnly identity),
621
+ `dlm:UpdateLifecyclePolicy` (reverts an `AWS::DLM::LifecyclePolicy` — the same
622
+ Description / State / ExecutionRoleArn / PolicyDetails shape is re-supplied in
623
+ place, since Cloud Control has no handler for the type),
624
+ `docdb:ModifyDBCluster` / `ModifyDBInstance`,
625
+ `config:DescribeConfigRules` / `config:PutConfigRule`,
626
+ `ecs:UpdateService` (reverts an `AWS::ECS::Service` `ServiceConnectConfiguration` /
627
+ `VolumeConfigurations` drift — the whole writeOnly prop is re-supplied, since Cloud
628
+ Control cannot sub-path patch it).
629
+
630
+ </details>
631
+
632
+ ## Limitations
633
+
634
+ `cdkrd` is **fail-closed**: anything it can't confidently compare is reported as
635
+ informational, never guessed (zero false drift). For the full list of what it does
636
+ not do (revert's boundaries, nested stacks, per-type read gaps, stack-state
637
+ handling), see [docs/limitations.md](docs/limitations.md).
638
+
639
+ The exception to zero-false-drift is the **`[Potential Drift]`** tier: with no
640
+ baseline yet, cdkrd can't confirm those live-only values, so it strips the noise
641
+ it recognizes and shows the rest as a best-effort guess — which can occasionally
642
+ surface an AWS-managed default or noise it hasn't catalogued (a false positive).
643
+
644
+ ## Reporting issues
645
+
646
+ Found a false positive in `[Potential Drift]` (an AWS-managed default or noise
647
+ that should have been folded), a missed detection, or any other bug? Please
648
+ [open an issue](https://github.com/go-to-k/cdk-real-drift/issues) — noise reports
649
+ turn directly into fold-table fixes and make the next run quieter for everyone.
650
+
651
+ ## FAQ
652
+
653
+ How `cdkrd` differs from `cdk deploy --revert-drift`, why the baseline is a
654
+ committed file, why `ignore` rules live in `.cdkrd/ignore.yaml`, and more:
655
+ [docs/faq.md](docs/faq.md).
656
+
657
+ ## Contributing
658
+
659
+ ```bash
660
+ pnpm install
661
+ vp run test # unit tests vp run typecheck
662
+ vp run check # lint + format vp run build
663
+ ```
664
+
665
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Integration tests (real AWS, self-cleaning)
666
+ live under [tests/integration/](tests/integration/README.md). Design rationale:
667
+ [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) · [DESIGN.md](DESIGN.md).