cdk-preflight 0.0.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/AGENTS.md ADDED
@@ -0,0 +1,60 @@
1
+ # AGENTS.md — cdk-preflight
2
+
3
+ Guide for AI agents (and humans) working on this repository.
4
+
5
+ ## What this package is
6
+
7
+ A data-first OSS: the product is the **rule pack** (`rules/`), not the loader. Rules are Rego documents evaluated by `@aws/cloudformation-validate` (the engine bundled inside `aws-cdk-lib` >= 2.267.0). The loader (`src/index.ts`) only selects rules and registers them with the CDK validation machinery.
8
+
9
+ Scope: **deploy-failure prevention only.** Security/compliance policies (cdk-nag, Control Tower proactive controls) are out of scope. A rule belongs here only if violating it makes an actual deployment fail.
10
+
11
+ ## Design principles (do not violate)
12
+
13
+ 1. **No duplication of the engine.** If the bundled engine already reports a constraint as ERROR/FATAL (schema check or built-in rule), we must not re-implement it. `test/rules.test.ts` enforces this mechanically ("does not duplicate a built-in blocker"). If that test fails for a new rule, the rule is unnecessary — delete it and record why in the PR.
14
+ 2. **Every rule ships with proof.** `templates/fail.template.json` must violate exactly this rule; `templates/pass.template.json` must be clean. `meta.yaml#repro` records how the deploy-time failure was verified (`real-deploy` / `research-case` / `doc-only` — the last one requires an explanation in `evidence`).
15
+ 3. **Rules graduate upstream.** Constraints expressible in schemas or generic engine rules should be PRed to [cloudformation-validate](https://github.com/aws-cloudformation/cloudformation-validate) (open an issue first). Track status in `meta.yaml#upstream` (`none` / `pending-engine` / `engine-pr` / `retired`). Shrinking this pack is success, not failure.
16
+ 4. **Tests are the contract.** Never merge with a red test; never weaken an assertion to make it pass. New behavior needs a new test first.
17
+
18
+ ## Repository layout
19
+
20
+ ```
21
+ rules/<service>/<rule-id>/
22
+ rule.rego # package cdk_preflight / import rego.v1 / violation contains make_diag_full(...)
23
+ meta.yaml # id, service, resourceTypes, severity, title, constraintSource, upstream, repro
24
+ templates/fail.template.json
25
+ templates/pass.template.json
26
+ src/index.ts # Preflight.apply / PreflightOptions (jsii surface — keep minimal)
27
+ src/private/enforce.ts # enforce-mode plugin (calls the engine directly)
28
+ src/rules.generated.ts # GENERATED from rules/ — never edit; run `npx projen bundle-rules`
29
+ scripts/bundle-rules.ts # generator + structural validation
30
+ test/ # 4 layers: rules / loader / structure / cli
31
+ bench/ # real-deploy verification (needs an AWS account; not part of CI)
32
+ ```
33
+
34
+ ## Adding a rule (the pipeline)
35
+
36
+ 1. Identify a constraint that fails only at deploy time (doc page, API error message, war story).
37
+ 2. Create `rules/<service>/<rule-id>/` with all four files. Rego conventions:
38
+ - `package cdk_preflight`, `import rego.v1`
39
+ - Emit via `make_diag_full("<rule-id>", "ERROR", name, <property-path>, <message with actual value>, <fix>, <doc url>)`
40
+ - Use the engine builtins (`resources_of_type`, `resolve`, `flatten_list`, `object.get`); guard numbers with `to_number` — it is undefined for non-numeric input, which safely skips tokens/refs.
41
+ - The standard OPA `walk` builtin is NOT available in this engine. Write explicit traversals.
42
+ - Helper rules must use a unique `_pf_<rule>_...` prefix (all rules share one package).
43
+ 3. `npx projen bundle-rules` then `npx jest test/rules.test.ts test/structure.test.ts` — the duplication guard and fixture checks run here.
44
+ 4. **Real-deploy gate**: `bash bench/verify-rule.sh <rule-id>` deploys the fail template (expects CREATE to fail; records the service error message) and, where cheap, the pass template (expects success, then deletes). Paste the observed error into `meta.yaml#repro.evidence` with the date. Only `doc-only` rules may skip this, with justification.
45
+ 5. Update nothing else by hand — `docs/rules.md` and `src/rules.generated.ts` are generated.
46
+
47
+ ## Commands
48
+
49
+ | Task | Command |
50
+ |---|---|
51
+ | Regenerate bundle + docs | `npx projen bundle-rules` |
52
+ | Unit tests | `npx jest` |
53
+ | Full build (jsii, lint, tests, package) | `npx projen build` |
54
+ | Real-deploy verification for one rule | `bash bench/verify-rule.sh <rule-id>` |
55
+
56
+ ## Known engine facts (verified 2026-09-01, engine 1.7.0-beta)
57
+
58
+ - Custom rule diagnostics carry `source: "CUSTOM"`; schema checks are `SCHEMA` (e.g. `F3034`), cfn-lint-derived rules are `CFN_LINT`.
59
+ - The engine's bundled schemas are *patched* (e.g. SQS numeric ranges exist even though the raw registry schema lacks them). Always check what the engine already catches before writing a rule.
60
+ - The CDK plugin path downgrades every finding to a warning; `@aws-cdk/core:validateAgainstDefaultRules` does not promote them (confirmed inert in aws-cdk-lib 2.267.0). This is why `enforce` mode exists.
package/API.md ADDED
@@ -0,0 +1,152 @@
1
+ # API Reference <a name="API Reference" id="api-reference"></a>
2
+
3
+
4
+ ## Structs <a name="Structs" id="Structs"></a>
5
+
6
+ ### PreflightOptions <a name="PreflightOptions" id="cdk-preflight.PreflightOptions"></a>
7
+
8
+ Options for {@link Preflight.apply}.
9
+
10
+ #### Initializer <a name="Initializer" id="cdk-preflight.PreflightOptions.Initializer"></a>
11
+
12
+ ```typescript
13
+ import { PreflightOptions } from 'cdk-preflight'
14
+
15
+ const preflightOptions: PreflightOptions = { ... }
16
+ ```
17
+
18
+ #### Properties <a name="Properties" id="Properties"></a>
19
+
20
+ | **Name** | **Type** | **Description** |
21
+ | --- | --- | --- |
22
+ | <code><a href="#cdk-preflight.PreflightOptions.property.enforce">enforce</a></code> | <code>boolean</code> | Fail synthesis (instead of reporting warnings) when a bundled rule is violated. |
23
+ | <code><a href="#cdk-preflight.PreflightOptions.property.exclude">exclude</a></code> | <code>string[]</code> | Rule ids to disable (see `Preflight.ruleIds()` or docs/rules.md). |
24
+ | <code><a href="#cdk-preflight.PreflightOptions.property.includeUpstreamPending">includeUpstreamPending</a></code> | <code>boolean</code> | Include rules that are marked `pending-engine` (candidates that have been proposed to the upstream cloudformation-validate engine but are not merged yet). |
25
+ | <code><a href="#cdk-preflight.PreflightOptions.property.strict">strict</a></code> | <code>boolean</code> | In enforce mode, additionally fail synthesis on error-class findings (severity ERROR/FATAL) of the built-in validation engine itself, e.g. schema violations like `F3034`. This is the workaround for the CDK behavior where all built-in findings are downgraded to warnings. |
26
+
27
+ ---
28
+
29
+ ##### `enforce`<sup>Optional</sup> <a name="enforce" id="cdk-preflight.PreflightOptions.property.enforce"></a>
30
+
31
+ ```typescript
32
+ public readonly enforce: boolean;
33
+ ```
34
+
35
+ - *Type:* boolean
36
+ - *Default:* false
37
+
38
+ Fail synthesis (instead of reporting warnings) when a bundled rule is violated.
39
+
40
+ In the default (warn) mode, findings are reported through the CDK built-in
41
+ CloudFormation validator and surface as synth warnings with construct traces.
42
+ With `enforce: true`, cdk-preflight evaluates its rules with its own
43
+ validation plugin and a violation makes `cdk synth` fail.
44
+
45
+ ---
46
+
47
+ ##### `exclude`<sup>Optional</sup> <a name="exclude" id="cdk-preflight.PreflightOptions.property.exclude"></a>
48
+
49
+ ```typescript
50
+ public readonly exclude: string[];
51
+ ```
52
+
53
+ - *Type:* string[]
54
+ - *Default:* all bundled rules are enabled
55
+
56
+ Rule ids to disable (see `Preflight.ruleIds()` or docs/rules.md).
57
+
58
+ ---
59
+
60
+ ##### `includeUpstreamPending`<sup>Optional</sup> <a name="includeUpstreamPending" id="cdk-preflight.PreflightOptions.property.includeUpstreamPending"></a>
61
+
62
+ ```typescript
63
+ public readonly includeUpstreamPending: boolean;
64
+ ```
65
+
66
+ - *Type:* boolean
67
+ - *Default:* true
68
+
69
+ Include rules that are marked `pending-engine` (candidates that have been proposed to the upstream cloudformation-validate engine but are not merged yet).
70
+
71
+ Disable this if you run a newer engine that already covers them.
72
+
73
+ ---
74
+
75
+ ##### `strict`<sup>Optional</sup> <a name="strict" id="cdk-preflight.PreflightOptions.property.strict"></a>
76
+
77
+ ```typescript
78
+ public readonly strict: boolean;
79
+ ```
80
+
81
+ - *Type:* boolean
82
+ - *Default:* false
83
+
84
+ In enforce mode, additionally fail synthesis on error-class findings (severity ERROR/FATAL) of the built-in validation engine itself, e.g. schema violations like `F3034`. This is the workaround for the CDK behavior where all built-in findings are downgraded to warnings.
85
+
86
+ Only effective together with `enforce: true`.
87
+
88
+ ---
89
+
90
+ ## Classes <a name="Classes" id="Classes"></a>
91
+
92
+ ### Preflight <a name="Preflight" id="cdk-preflight.Preflight"></a>
93
+
94
+ cdk-preflight: catch deploy-time CloudFormation failures at synth time.
95
+
96
+ Injects a curated Rego rule pack (constraints that resource provider schemas
97
+ do not express: doc-only value limits, cross-property and cross-resource
98
+ rules) into the AWS CDK built-in CloudFormation validator.
99
+
100
+ *Example*
101
+
102
+ ```typescript
103
+ declare const app: App;
104
+ Preflight.apply(app);
105
+ ```
106
+
107
+
108
+
109
+ #### Static Functions <a name="Static Functions" id="Static Functions"></a>
110
+
111
+ | **Name** | **Description** |
112
+ | --- | --- |
113
+ | <code><a href="#cdk-preflight.Preflight.apply">apply</a></code> | Register the cdk-preflight rules on an App or Stage. |
114
+ | <code><a href="#cdk-preflight.Preflight.ruleIds">ruleIds</a></code> | The ids of all bundled rules. |
115
+
116
+ ---
117
+
118
+ ##### `apply` <a name="apply" id="cdk-preflight.Preflight.apply"></a>
119
+
120
+ ```typescript
121
+ import { Preflight } from 'cdk-preflight'
122
+
123
+ Preflight.apply(scope: IConstruct, options?: PreflightOptions)
124
+ ```
125
+
126
+ Register the cdk-preflight rules on an App or Stage.
127
+
128
+ ###### `scope`<sup>Required</sup> <a name="scope" id="cdk-preflight.Preflight.apply.parameter.scope"></a>
129
+
130
+ - *Type:* constructs.IConstruct
131
+
132
+ ---
133
+
134
+ ###### `options`<sup>Optional</sup> <a name="options" id="cdk-preflight.Preflight.apply.parameter.options"></a>
135
+
136
+ - *Type:* <a href="#cdk-preflight.PreflightOptions">PreflightOptions</a>
137
+
138
+ ---
139
+
140
+ ##### `ruleIds` <a name="ruleIds" id="cdk-preflight.Preflight.ruleIds"></a>
141
+
142
+ ```typescript
143
+ import { Preflight } from 'cdk-preflight'
144
+
145
+ Preflight.ruleIds()
146
+ ```
147
+
148
+ The ids of all bundled rules.
149
+
150
+
151
+
152
+
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # cdk-preflight
2
+
3
+ **Catch deploy-time CloudFormation failures at `cdk synth` time.**
4
+
5
+ Some CloudFormation constraints are not expressed in resource provider schemas — they live only in documentation, in service API validation, or across multiple properties. Templates that violate them pass `cdk synth`, pass CloudFormation pre-deployment validation, and then fail minutes into a deployment, burning a rollback cycle.
6
+
7
+ cdk-preflight is a curated [Rego rule pack](docs/rules.md) for exactly those constraints. It injects the rules into the AWS CDK built-in CloudFormation validator (`aws-cdk-lib` >= 2.267.0), so violations surface at synth with construct-level traces — before you deploy.
8
+
9
+ Every bundled rule is backed by a `fail`/`pass` template pair, and the failure has been reproduced against real AWS (or is explicitly marked `doc-only`). Rules that the built-in validation engine already covers are deliberately **not** duplicated — a test suite enforces this.
10
+
11
+ ## Quick start
12
+
13
+ ```bash
14
+ npm i -D cdk-preflight
15
+ npx cdk-preflight init # inserts Preflight.apply(app) into your CDK app
16
+ ```
17
+
18
+ or add one line yourself:
19
+
20
+ ```ts
21
+ import { Preflight } from 'cdk-preflight';
22
+
23
+ const app = new App();
24
+ Preflight.apply(app);
25
+ ```
26
+
27
+ `cdk synth` then reports violations like:
28
+
29
+ ```text
30
+ WARNING idle_timeout.timeout_seconds is 5000 but must be between 1 and 4000 seconds (CloudFormation Validate)
31
+ MyStack/Alb (Alb) aws-cdk-lib.aws_elasticloadbalancingv2.CfnLoadBalancer
32
+ Acknowledge with 'CloudFormation-Validate::pf-elbv2-lb-idle-timeout-range'
33
+ ```
34
+
35
+ ## Failing the build
36
+
37
+ By default findings are warnings (matching the CDK built-in validator behavior). To make violations fail `cdk synth`:
38
+
39
+ ```ts
40
+ Preflight.apply(app, { enforce: true });
41
+ ```
42
+
43
+ | Option | Default | Effect |
44
+ |---|---|---|
45
+ | `enforce` | `false` | Violations of bundled rules fail synthesis instead of warning |
46
+ | `strict` | `false` | With `enforce`: also fail on error-class findings (`ERROR`/`FATAL`, e.g. `F3034`) of the built-in validation engine itself, which the CDK currently downgrades to warnings |
47
+ | `exclude` | `[]` | Rule ids to disable |
48
+ | `includeUpstreamPending` | `true` | Include rules already proposed to the upstream engine but not yet merged |
49
+
50
+ Individual findings can also be suppressed with the CDK acknowledge mechanism shown in the warning text.
51
+
52
+ ## Bundled rules
53
+
54
+ See [docs/rules.md](docs/rules.md) for the generated rule table. Highlights:
55
+
56
+ - **ELBv2**: `idle_timeout` / `deregistration_delay` / `slow_start` attribute ranges (stringly-typed Key/Value attributes are invisible to schema validation)
57
+ - **IAM**: managed (6,144 chars) and inline (role/group/user) policy document size limits
58
+ - **CloudFront**: `MinTTL <= DefaultTTL <= MaxTTL` ordering, ACM certificates must live in `us-east-1`
59
+ - **Step Functions**: `StartAt`/`Next`/`Default`/`Choices` must reference defined states
60
+ - **EC2**: security group TCP/UDP port ranges and `FromPort <= ToPort`
61
+
62
+ ## For AI agents
63
+
64
+ To add cdk-preflight to a CDK app:
65
+
66
+ 1. `npm i -D cdk-preflight`
67
+ 2. `npx cdk-preflight init` (finds the entry point via `cdk.json` and inserts `Preflight.apply(app)`; use `--dry-run` to preview)
68
+ 3. Run `cdk synth` and read the warnings; each carries a rule id, a suggested fix, and a construct trace
69
+ 4. If the user wants synthesis to fail on violations, change the call to `Preflight.apply(app, { enforce: true })`
70
+
71
+ The machine-readable findings are written to `cdk.out/validation-report.json` when synthesizing with `-c @aws-cdk/core:validationReportJson=true`.
72
+
73
+ ## How it works
74
+
75
+ `Preflight.apply()` registers the rules with the CDK built-in `CloudFormationValidatePlugin` (the [cloudformation-validate](https://github.com/aws-cloudformation/cloudformation-validate) Rust/WASM engine that ships inside `aws-cdk-lib`). No extra binaries, no network access at synth time. In `enforce` mode the same engine is invoked through a dedicated validation plugin so that violations fail synthesis.
76
+
77
+ Constraints that *can* be expressed in schemas or generic engine rules are contributed upstream instead of living here; each rule's `meta.yaml` tracks its upstream status, and rules retire once the engine covers them.
78
+
79
+ ## Requirements
80
+
81
+ - `aws-cdk-lib` >= 2.267.0 (the first release that bundles the built-in CloudFormation validator)
82
+
83
+ ## Contributing
84
+
85
+ Rule authoring, the verification gates (including real-deploy reproduction), and the test layout are documented in [AGENTS.md](AGENTS.md) — written for AI coding agents and humans alike.
86
+
87
+ ## License
88
+
89
+ Apache-2.0
package/docs/rules.md ADDED
@@ -0,0 +1,15 @@
1
+ # Bundled rules
2
+
3
+ <!-- Generated by scripts/bundle-rules.ts. Do not edit by hand. -->
4
+
5
+ | Rule | Resource types | Constraint | Upstream status |
6
+ |---|---|---|---|
7
+ | `pf-cloudfront-acm-cert-region` | AWS::CloudFront::Distribution | CloudFront viewer certificates must live in us-east-1 | none |
8
+ | `pf-cloudfront-ttl-order` | AWS::CloudFront::Distribution | Cache behavior TTLs must satisfy MinTTL <= DefaultTTL <= MaxTTL | none |
9
+ | `pf-ec2-sg-port-range` | AWS::EC2::SecurityGroup<br>AWS::EC2::SecurityGroupIngress<br>AWS::EC2::SecurityGroupEgress | Security group TCP/UDP ports must be within 0-65535 and FromPort <= ToPort | none |
10
+ | `pf-elbv2-lb-idle-timeout-range` | AWS::ElasticLoadBalancingV2::LoadBalancer | ALB idle_timeout.timeout_seconds must be between 1 and 4000 | none |
11
+ | `pf-elbv2-tg-deregistration-delay-range` | AWS::ElasticLoadBalancingV2::TargetGroup | Target group deregistration_delay.timeout_seconds must be between 0 and 3600 | none |
12
+ | `pf-elbv2-tg-slow-start-range` | AWS::ElasticLoadBalancingV2::TargetGroup | Target group slow_start.duration_seconds must be 0 or between 30 and 900 | none |
13
+ | `pf-iam-inline-policy-size` | AWS::IAM::Policy<br>AWS::IAM::RolePolicy<br>AWS::IAM::UserPolicy<br>AWS::IAM::GroupPolicy | Inline policy documents are limited per identity (role 10240 / group 5120 / user 2048 characters) | none |
14
+ | `pf-iam-managed-policy-size` | AWS::IAM::ManagedPolicy | Managed policy documents are limited to 6144 characters (whitespace excluded) | none |
15
+ | `pf-sfn-asl-missing-state` | AWS::StepFunctions::StateMachine | ASL StartAt/Next/Default/Choices must reference a defined state (top-level states) | none |
package/lib/cli.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI 本体。テストから直接呼べるよう exit せず終了コードを返す。
4
+ */
5
+ export declare function runCli(args: string[]): number;
package/lib/cli.js ADDED
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.runCli = runCli;
38
+ /**
39
+ * `npx cdk-preflight init` — 既存 CDK アプリに Preflight.apply(app) を挿入する codemod。
40
+ * 人間にも AI エージェントにも同じ入口を提供する。
41
+ */
42
+ const fs = __importStar(require("fs"));
43
+ const path = __importStar(require("path"));
44
+ /* eslint-disable no-console */
45
+ const USAGE = [
46
+ 'Usage: cdk-preflight init [--dry-run] [--dir <path>]',
47
+ '',
48
+ 'Inserts `Preflight.apply(app)` into the CDK app entry point found via cdk.json.',
49
+ ].join('\n');
50
+ /**
51
+ * CLI 本体。テストから直接呼べるよう exit せず終了コードを返す。
52
+ */
53
+ function runCli(args) {
54
+ const cmd = args[0];
55
+ if (cmd === undefined || cmd === '--help' || cmd === '-h') {
56
+ console.log(USAGE);
57
+ return 0;
58
+ }
59
+ if (cmd !== 'init') {
60
+ console.error(`cdk-preflight: unknown command "${cmd}"\n\n${USAGE}`);
61
+ return 1;
62
+ }
63
+ const dry = args.includes('--dry-run');
64
+ const dirIdx = args.indexOf('--dir');
65
+ const cwd = dirIdx >= 0 && args[dirIdx + 1] ? path.resolve(args[dirIdx + 1]) : process.cwd();
66
+ const cdkJsonPath = path.join(cwd, 'cdk.json');
67
+ if (!fs.existsSync(cdkJsonPath)) {
68
+ console.error(`cdk-preflight: no cdk.json found in ${cwd} (run inside a CDK app, or pass --dir)`);
69
+ return 1;
70
+ }
71
+ const appCmd = JSON.parse(fs.readFileSync(cdkJsonPath, 'utf8')).app ?? '';
72
+ const entryMatch = appCmd.match(/(\S+\.(?:ts|mts|cts|js|mjs|cjs))\b/);
73
+ if (!entryMatch) {
74
+ console.error(`cdk-preflight: could not locate an entry file in cdk.json "app": ${appCmd}`);
75
+ return 1;
76
+ }
77
+ const entry = path.join(cwd, entryMatch[1]);
78
+ if (!fs.existsSync(entry)) {
79
+ console.error(`cdk-preflight: entry file not found: ${entry}`);
80
+ return 1;
81
+ }
82
+ const src = fs.readFileSync(entry, 'utf8');
83
+ if (src.includes('cdk-preflight')) {
84
+ console.log(`cdk-preflight: ${entry} already references cdk-preflight — nothing to do`);
85
+ return 0;
86
+ }
87
+ const appLineMatch = src.match(/^.*\bnew\s+(?:cdk\.)?App\s*\([^;\n]*\)\s*;?[^\S\n]*$/m);
88
+ if (!appLineMatch) {
89
+ console.error([
90
+ `cdk-preflight: could not find \`new App(...)\` in ${entry}. Add manually:`,
91
+ " import { Preflight } from 'cdk-preflight';",
92
+ ' Preflight.apply(app);',
93
+ ].join('\n'));
94
+ return 1;
95
+ }
96
+ const appLine = appLineMatch[0];
97
+ const varMatch = appLine.match(/(?:const|let|var)\s+(\w+)\s*=/);
98
+ const appVar = varMatch ? varMatch[1] : 'app';
99
+ let updated = src.replace(appLine, `${appLine}\nPreflight.apply(${appVar});`);
100
+ updated = `import { Preflight } from 'cdk-preflight';\n${updated}`;
101
+ if (dry) {
102
+ console.log(`--- ${entry} (dry run) ---\n${updated}`);
103
+ }
104
+ else {
105
+ fs.writeFileSync(entry, updated);
106
+ console.log(`cdk-preflight: updated ${entry}`);
107
+ }
108
+ console.log([
109
+ '',
110
+ 'Next steps:',
111
+ ' 1. npm i -D cdk-preflight (if not installed yet)',
112
+ ' 2. cdk synth (violations appear as warnings with construct traces)',
113
+ ' 3. Optional: Preflight.apply(app, { enforce: true }) to fail synth on violations',
114
+ ].join('\n'));
115
+ return 0;
116
+ }
117
+ /* istanbul ignore next */
118
+ if (require.main === module) {
119
+ process.exit(runCli(process.argv.slice(2)));
120
+ }
121
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2xpLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2NsaS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFtQkEsd0JBa0VDO0FBcEZEOzs7R0FHRztBQUNILHVDQUF5QjtBQUN6QiwyQ0FBNkI7QUFFN0IsK0JBQStCO0FBRS9CLE1BQU0sS0FBSyxHQUFHO0lBQ1osc0RBQXNEO0lBQ3RELEVBQUU7SUFDRixpRkFBaUY7Q0FDbEYsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFD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