cdk-real-drift 0.0.1 → 0.1.1

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