@intentius/chant-lexicon-aws 0.124.52 → 0.124.55

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.
Files changed (108) hide show
  1. package/dist/api/credential-chain.d.ts +3 -3
  2. package/dist/api/credential-chain.d.ts.map +1 -1
  3. package/dist/api/credential-chain.js +2 -2
  4. package/dist/api/read-client.d.ts +2 -2
  5. package/dist/api/read-client.d.ts.map +1 -1
  6. package/dist/api/read-client.js +2 -2
  7. package/dist/api/{sigv4.d.ts → signing.d.ts} +14 -34
  8. package/dist/api/signing.d.ts.map +1 -0
  9. package/dist/api/signing.js +95 -0
  10. package/dist/codegen/generate-lexicon.d.ts +2 -0
  11. package/dist/codegen/generate-lexicon.d.ts.map +1 -1
  12. package/dist/codegen/generate-lexicon.js +1 -0
  13. package/dist/components/__tests__/mock-cloud-executor.d.ts +4 -0
  14. package/dist/components/__tests__/mock-cloud-executor.d.ts.map +1 -1
  15. package/dist/components/__tests__/mock-cloud-executor.js +18 -1
  16. package/dist/components/apply.d.ts +46 -2
  17. package/dist/components/apply.d.ts.map +1 -1
  18. package/dist/components/apply.js +266 -30
  19. package/dist/components/cfn-adopt-run.d.ts +37 -0
  20. package/dist/components/cfn-adopt-run.d.ts.map +1 -0
  21. package/dist/components/cfn-adopt-run.js +104 -0
  22. package/dist/components/cfn-adopt.d.ts +99 -0
  23. package/dist/components/cfn-adopt.d.ts.map +1 -0
  24. package/dist/components/cfn-adopt.js +278 -0
  25. package/dist/components/cfn-imports.d.ts +84 -0
  26. package/dist/components/cfn-imports.d.ts.map +1 -0
  27. package/dist/components/cfn-imports.js +239 -0
  28. package/dist/components/cloud-executor.d.ts +38 -2
  29. package/dist/components/cloud-executor.d.ts.map +1 -1
  30. package/dist/components/cloud-executor.js +84 -2
  31. package/dist/health.js +1 -1
  32. package/dist/importable.d.ts +30 -0
  33. package/dist/importable.d.ts.map +1 -0
  34. package/dist/importable.js +72 -0
  35. package/dist/index-identity.d.ts +19 -0
  36. package/dist/index-identity.d.ts.map +1 -0
  37. package/dist/index-identity.js +79 -0
  38. package/dist/index-import.d.ts +25 -0
  39. package/dist/index-import.d.ts.map +1 -0
  40. package/dist/index-import.js +132 -0
  41. package/dist/index.d.ts +1 -1
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +1 -1
  44. package/dist/integrity.json +4 -4
  45. package/dist/listed-types.d.ts +11 -0
  46. package/dist/listed-types.d.ts.map +1 -0
  47. package/dist/listed-types.js +52 -0
  48. package/dist/manifest.json +1 -1
  49. package/dist/meta.json +13206 -1237
  50. package/dist/plugin.d.ts.map +1 -1
  51. package/dist/plugin.js +12 -3
  52. package/dist/reference-catalog.d.ts.map +1 -1
  53. package/dist/reference-catalog.js +62 -20
  54. package/dist/skills/chant-aws-carve-terraform.md +21 -14
  55. package/dist/spec/fetch.d.ts +5 -0
  56. package/dist/spec/fetch.d.ts.map +1 -1
  57. package/dist/spec/parse.d.ts +8 -0
  58. package/dist/spec/parse.d.ts.map +1 -1
  59. package/dist/spec/parse.js +3 -0
  60. package/package.json +2 -2
  61. package/src/api/credential-chain.ts +3 -3
  62. package/src/api/read-client.test.ts +2 -2
  63. package/src/api/read-client.ts +3 -3
  64. package/src/api/{sigv4.test.ts → signing.test.ts} +84 -96
  65. package/src/api/signing.ts +130 -0
  66. package/src/codegen/generate-lexicon.ts +3 -0
  67. package/src/components/__tests__/mock-cloud-executor.ts +20 -1
  68. package/src/components/apply.ts +288 -30
  69. package/src/components/cfn-adopt-run.test.ts +227 -0
  70. package/src/components/cfn-adopt-run.ts +141 -0
  71. package/src/components/cfn-adopt.test.ts +284 -0
  72. package/src/components/cfn-adopt.ts +340 -0
  73. package/src/components/cfn-exports-in-use.test.ts +146 -0
  74. package/src/components/cfn-imports-preview.test.ts +178 -0
  75. package/src/components/cfn-imports-three-stacks.test.ts +107 -0
  76. package/src/components/cfn-imports.test.ts +213 -0
  77. package/src/components/cfn-imports.ts +246 -0
  78. package/src/components/cfn-plan-shape-conformance.test.ts +83 -0
  79. package/src/components/cloud-executor.ts +127 -5
  80. package/src/components/demo-composed-stacks-floci.e2e.test.ts +235 -0
  81. package/src/derived-edges.test.ts +142 -0
  82. package/src/generated/lexicon-aws.json +13206 -1237
  83. package/src/health.ts +1 -1
  84. package/src/importable.test.ts +86 -0
  85. package/src/importable.ts +83 -0
  86. package/src/index-identity.test.ts +134 -0
  87. package/src/index-identity.ts +98 -0
  88. package/src/index-import.test.ts +257 -0
  89. package/src/index-import.ts +158 -0
  90. package/src/index-search.test.ts +87 -0
  91. package/src/index.ts +1 -1
  92. package/src/listed-types.test.ts +97 -0
  93. package/src/listed-types.ts +56 -0
  94. package/src/plugin.ts +13 -3
  95. package/src/reference-catalog.ts +63 -20
  96. package/src/skills/chant-aws-carve-terraform.md +21 -14
  97. package/src/spec/fetch.ts +5 -0
  98. package/src/spec/parse.test.ts +15 -0
  99. package/src/spec/parse.ts +12 -0
  100. package/src/testdata/indexed/identity.listing.json +65 -0
  101. package/src/testdata/indexed/import.listing.json +126 -0
  102. package/src/testdata/indexed/listing.json +69 -0
  103. package/src/testdata/indexed/topology.listing.json +350 -0
  104. package/src/testdata/three-cloud/dns.graph.json +336 -0
  105. package/src/three-cloud-parity.test.ts +49 -0
  106. package/dist/api/sigv4.d.ts.map +0 -1
  107. package/dist/api/sigv4.js +0 -185
  108. package/src/api/sigv4.ts +0 -243
@@ -0,0 +1,227 @@
1
+ /**
2
+ * #4537: `cfn-deploy` under `run --components <name> --adopt <file>`, over a
3
+ * fake CloudFormation client. The step plans the adoption against its built
4
+ * template and the stack's resources, sends each change set through the
5
+ * review core hands it, refuses what the library refuses before any change
6
+ * set exists, and says what to do when the marker step stops after a good
7
+ * import. Nothing reaches a cloud; the floci run is a maintainer run.
8
+ */
9
+ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { describe, expect, test } from "vitest";
13
+ import type { AdoptionReviewRequest, DeployAdoption } from "@intentius/chant/components/adoption";
14
+ import type { DeployContext } from "@intentius/chant/components/capability";
15
+ import { indexDocumentDigest, indexScopeKey, indexVersionName, type CloudIndexScope, type IndexDocument } from "@intentius/chant/lifecycle/index-document";
16
+ import type { ImportabilityManifestEntry } from "../importable";
17
+ import { createCfnDeployCapability } from "./apply";
18
+ import { runCfnAdoption } from "./cfn-adopt-run";
19
+ import type { CfnChange, CfnChangeSet, CloudExecutor, CloudFormationClient } from "./cloud-executor";
20
+
21
+ const SCOPE: CloudIndexScope = { kind: "cloud", substrate: "aws", scopeId: "000000000000", locations: ["us-east-1"], types: "*" };
22
+ const BUCKET = "aws/000000000000/us-east-1/AWS::S3::Bucket/web-logs";
23
+ const graph = {
24
+ version: 1 as const,
25
+ nodes: [{ id: BUCKET, kind: "AWS::S3::Bucket", lexicon: "aws", attrs: { BucketName: "web-logs" }, listedType: "AWS::S3::Bucket", location: "us-east-1", nativeId: "web-logs" }],
26
+ edges: [],
27
+ groups: {},
28
+ };
29
+ const INDEX: IndexDocument = {
30
+ index: "v1",
31
+ stamp: { source: { kind: "cloud", name: "behold-lister" }, scope: SCOPE, scopeKey: indexScopeKey(SCOPE), observedAt: "2026-10-26T12:00:00Z", digest: indexDocumentDigest({ graph, coverage: [] }) },
32
+ coverage: [],
33
+ graph,
34
+ };
35
+ const MANIFEST = new Map<string, ImportabilityManifestEntry>([
36
+ [
37
+ "AWS::S3::Bucket",
38
+ {
39
+ resourceType: "AWS::S3::Bucket",
40
+ kind: "resource",
41
+ handlers: ["create", "delete", "list", "read", "update"],
42
+ primaryIdentifier: ["BucketName"],
43
+ tagging: { taggable: true, tagUpdatable: true, tagProperty: "Tags", tagShape: "list" },
44
+ },
45
+ ],
46
+ ]);
47
+
48
+ function templateFile(extra: Record<string, unknown> = {}): string {
49
+ const dir = mkdtempSync(join(tmpdir(), "cfn-adopt-run-test-"));
50
+ const path = join(dir, "web.template.json");
51
+ writeFileSync(
52
+ path,
53
+ JSON.stringify({
54
+ AWSTemplateFormatVersion: "2010-09-09",
55
+ Metadata: { "chant:ownership": { "chant:managed-by": "chant", "chant:stack": "web", "chant:env": "prod" } },
56
+ Resources: {
57
+ BucketWebLogs: {
58
+ Type: "AWS::S3::Bucket",
59
+ DeletionPolicy: "Retain",
60
+ UpdateReplacePolicy: "Retain",
61
+ Properties: {
62
+ BucketName: "web-logs",
63
+ Tags: [
64
+ { Key: "chant:managed-by", Value: "chant" },
65
+ { Key: "chant:stack", Value: "web" },
66
+ { Key: "chant:env", Value: "prod" },
67
+ ],
68
+ },
69
+ },
70
+ ...extra,
71
+ },
72
+ }),
73
+ );
74
+ return path;
75
+ }
76
+
77
+ function adoptionOf(seen: AdoptionReviewRequest[], answer: (r: AdoptionReviewRequest) => boolean = () => true): DeployAdoption {
78
+ return {
79
+ file: "adopt.json",
80
+ adoption: {
81
+ adopt: "v1",
82
+ index: { scopeKey: INDEX.stamp.scopeKey, version: indexVersionName(INDEX.stamp.observedAt, INDEX.stamp.digest), digest: INDEX.stamp.digest },
83
+ select: [{ node: BUCKET, as: "BucketWebLogs", type: "AWS::S3::Bucket" }],
84
+ },
85
+ index: INDEX,
86
+ review: async (r) => {
87
+ seen.push(r);
88
+ return answer(r);
89
+ },
90
+ };
91
+ }
92
+
93
+ function fake(opts: { existing?: string[]; noList?: boolean; markerChanges?: CfnChange[] } = {}) {
94
+ const calls: string[] = [];
95
+ let status = "REVIEW_IN_PROGRESS";
96
+ let pending: "IMPORT" | "UPDATE" | undefined;
97
+ const cs = (name: string, changes: CfnChange[], extra: Partial<CfnChangeSet> = {}): CfnChangeSet => ({ changeSetName: name, stackName: "web", status: "CREATE_COMPLETE", isCreate: false, changes, ...extra });
98
+ const cfn: CloudFormationClient = {
99
+ async listStackResources() {
100
+ calls.push("listStackResources");
101
+ return opts.existing ?? [];
102
+ },
103
+ async createImportChangeSet(args) {
104
+ calls.push("createImportChangeSet");
105
+ expect(readFileSync(args.templatePath, "utf8")).not.toContain("chant:");
106
+ pending = "IMPORT";
107
+ return cs(
108
+ "cs-import",
109
+ args.resourcesToImport.map((r) => ({ action: "Import" as const, logicalResourceId: r.logicalResourceId, resourceType: r.resourceType, replacement: false })),
110
+ { changeSetType: "IMPORT" },
111
+ );
112
+ },
113
+ async createChangeSet() {
114
+ calls.push("createChangeSet");
115
+ pending = "UPDATE";
116
+ return cs("cs-markers", opts.markerChanges ?? [{ action: "Modify", logicalResourceId: "BucketWebLogs", resourceType: "AWS::S3::Bucket", replacement: false, replacementMode: "False", details: ["Tags"] }]);
117
+ },
118
+ async executeChangeSet(args) {
119
+ calls.push(`execute:${args.changeSetName}`);
120
+ status = pending === "IMPORT" ? "IMPORT_COMPLETE" : "UPDATE_COMPLETE";
121
+ },
122
+ async deleteChangeSet(args) {
123
+ calls.push(`delete:${args.changeSetName}`);
124
+ },
125
+ async waitForStack() {
126
+ return { stackStatus: status, outputs: {} };
127
+ },
128
+ async describeStack() {
129
+ return { stackStatus: status, outputs: { BucketName: "web-logs" } };
130
+ },
131
+ async rollbackStack() {
132
+ calls.push("rollbackStack");
133
+ },
134
+ };
135
+ if (opts.noList) delete cfn.listStackResources;
136
+ return { executor: { cloudformation: cfn } as unknown as CloudExecutor, calls };
137
+ }
138
+
139
+ const ctx = (adoption?: DeployAdoption): DeployContext => ({ env: "prod", component: "web", ...(adoption ? { adoption } : {}) });
140
+
141
+ describe("runCfnAdoption (#4537)", () => {
142
+ test("IMPORT then the marker UPDATE, each through the review, and the outcome says what was adopted", async () => {
143
+ const { executor, calls } = fake();
144
+ const seen: AdoptionReviewRequest[] = [];
145
+ const adoption = adoptionOf(seen);
146
+ const out = await runCfnAdoption(executor, ctx(adoption), { stack: "web", template: templateFile() }, adoption, { manifest: MANIFEST });
147
+ expect(out).toEqual({ stackStatus: "UPDATE_COMPLETE", outputs: { BucketName: "web-logs" } });
148
+ expect(calls).toEqual(["listStackResources", "createImportChangeSet", "execute:cs-import", "createChangeSet", "execute:cs-markers"]);
149
+ expect(seen.map((r) => [r.step, r.changeSet])).toEqual([
150
+ ["import", "cs-import"],
151
+ ["markers", "cs-markers"],
152
+ ]);
153
+ expect(seen[0]!.entries).toMatchObject([{ address: "BucketWebLogs", action: "no-op", importing: true }]);
154
+ expect(seen[1]!.lines).toEqual(["marker write, tags only: BucketWebLogs (AWS::S3::Bucket) Tags += chant:env=prod, chant:managed-by=chant, chant:stack=web"]);
155
+ expect(adoption.outcome).toMatchObject({ member: "web", status: "adopted" });
156
+ expect(adoption.outcome!.lines[0]).toBe("imported BucketWebLogs (AWS::S3::Bucket) BucketName=web-logs, DeletionPolicy Retain");
157
+ });
158
+
159
+ test("a declined marker review after a good import says a plain deploy writes the markers", async () => {
160
+ const { executor, calls } = fake();
161
+ const adoption = adoptionOf([], (r) => r.step === "import");
162
+ await expect(runCfnAdoption(executor, ctx(adoption), { stack: "web", template: templateFile() }, adoption, { manifest: MANIFEST })).rejects.toThrow(/declined at the markers step/);
163
+ expect(calls).toEqual(["listStackResources", "createImportChangeSet", "execute:cs-import", "createChangeSet", "delete:cs-markers"]);
164
+ expect(adoption.outcome).toMatchObject({ status: "declined", step: "markers" });
165
+ expect(adoption.outcome!.lines.join("\n")).toMatch(
166
+ /imported into web and carry no chant markers yet\. A plain deploy of the same template writes them: chant run --components web --env prod, without --adopt\./,
167
+ );
168
+ });
169
+
170
+ test("a marker change set that is not tags only is refused, with the same way out", async () => {
171
+ const { executor, calls } = fake({ markerChanges: [{ action: "Modify", logicalResourceId: "BucketWebLogs", resourceType: "AWS::S3::Bucket", replacement: false, details: ["Tags", "VersioningConfiguration"] }] });
172
+ const adoption = adoptionOf([]);
173
+ await expect(runCfnAdoption(executor, ctx(adoption), { stack: "web", template: templateFile() }, adoption, { manifest: MANIFEST })).rejects.toThrow(/refused at the markers step/);
174
+ expect(calls.at(-1)).toBe("delete:cs-markers");
175
+ expect(adoption.outcome!.lines.join("\n")).toMatch(/not only its tags/);
176
+ expect(adoption.outcome!.lines.join("\n")).toMatch(/A plain deploy of the same template writes them/);
177
+ });
178
+
179
+ test("a declined IMPORT review imports nothing and deletes the change set", async () => {
180
+ const { executor, calls } = fake();
181
+ const adoption = adoptionOf([], () => false);
182
+ await expect(runCfnAdoption(executor, ctx(adoption), { stack: "web", template: templateFile() }, adoption, { manifest: MANIFEST })).rejects.toThrow(/declined at the import step/);
183
+ expect(calls).toEqual(["listStackResources", "createImportChangeSet", "delete:cs-import"]);
184
+ expect(adoption.outcome!.lines).toContain("Nothing was imported.");
185
+ });
186
+
187
+ test("what the library refuses is refused before any change set: a resource already in the stack, an extra resource", async () => {
188
+ const { executor, calls } = fake({ existing: ["BucketWebLogs"] });
189
+ const adoption = adoptionOf([]);
190
+ await expect(
191
+ runCfnAdoption(executor, ctx(adoption), { stack: "web", template: templateFile({ NewQueue: { Type: "AWS::SQS::Queue", Properties: {} } }) }, adoption, { manifest: MANIFEST }),
192
+ ).rejects.toThrow(/adoption refused/);
193
+ expect(calls).toEqual(["listStackResources"]);
194
+ expect(adoption.outcome).toMatchObject({ status: "refused", step: "plan" });
195
+ const lines = adoption.outcome!.lines.join("\n");
196
+ expect(lines).toMatch(/BucketWebLogs is already in the stack/);
197
+ expect(lines).toMatch(/the template also creates NewQueue/);
198
+ });
199
+
200
+ test("a client that cannot list the stack's resources, and an unreadable template, are refused", async () => {
201
+ const noList = fake({ noList: true });
202
+ const a = adoptionOf([]);
203
+ await expect(runCfnAdoption(noList.executor, ctx(a), { stack: "web", template: templateFile() }, a, { manifest: MANIFEST })).rejects.toThrow(/cannot list the stack's resources/);
204
+ expect(noList.calls).toEqual([]);
205
+ const archived = fake();
206
+ const b = adoptionOf([]);
207
+ await expect(runCfnAdoption(archived.executor, ctx(b), { stack: "web", template: "archive:web.template.json" }, b, { manifest: MANIFEST })).rejects.toThrow(/cannot be read here/);
208
+ expect(archived.calls).toEqual([]);
209
+ });
210
+
211
+ test("an adoption already taken by another step is refused", async () => {
212
+ const { executor, calls } = fake();
213
+ const adoption = adoptionOf([]);
214
+ adoption.outcome = { member: "other", status: "adopted", lines: [] };
215
+ await expect(runCfnAdoption(executor, ctx(adoption), { stack: "web", template: templateFile() }, adoption, { manifest: MANIFEST })).rejects.toThrow(/already taken by other/);
216
+ expect(calls).toEqual([]);
217
+ });
218
+
219
+ test("cfn-deploy's run takes DeployContext.adoption instead of a plain deploy", async () => {
220
+ const { executor, calls } = fake({ existing: ["BucketWebLogs"] });
221
+ const adoption = adoptionOf([]);
222
+ const capability = createCfnDeployCapability(executor);
223
+ await expect(capability.run(ctx(adoption), { stack: "web", template: templateFile() })).rejects.toThrow(/adoption refused/);
224
+ expect(calls).toEqual(["listStackResources"]);
225
+ expect(adoption.outcome).toMatchObject({ member: "web", status: "refused" });
226
+ });
227
+ });
@@ -0,0 +1,141 @@
1
+ /**
2
+ * `cfn-deploy` under `chant run --components <name> --env <env> --adopt
3
+ * <adoption-file>` (#4537): the step adopts the file's resources into its
4
+ * stack with ./cfn-adopt.ts instead of deploying the template plainly.
5
+ *
6
+ * Core hands the step the adoption file, the index version it names and the
7
+ * review on `DeployContext.adoption` (packages/core/src/components/adoption.ts).
8
+ * This step plans the adoption against the step's built template and the
9
+ * stack's resources now, then runs the IMPORT change set and the marker
10
+ * UPDATE, each through that review. Everything the library refuses is
11
+ * refused here, by name, before any change set is made, and the change set a
12
+ * refusal or a declined review leaves is deleted.
13
+ *
14
+ * When the marker step stops after a good import, the resources are in the
15
+ * stack, with the template's DeletionPolicy (Retain from `chant import
16
+ * --index`) and without chant's markers. A plain deploy of the same template
17
+ * writes them, and the outcome says so.
18
+ */
19
+ import type { DeployContext } from "@intentius/chant/components/capability";
20
+ import type { AdoptionReviewRequest, DeployAdoption, DeployAdoptionOutcome } from "@intentius/chant/components/adoption";
21
+ import { cfnChangeEntry, flattenCfnInputs, type CfnDeployInput, type CfnDeployOutput } from "./apply";
22
+ import { adoptIntoStack, cfnImportReview, cfnMarkerReview, planCfnAdoption, type CfnAdoptionOutcome, type CfnAdoptionPlan, type CfnTemplate } from "./cfn-adopt";
23
+ import { readCfnTemplate } from "./cfn-imports";
24
+ import type { CloudExecutor } from "./cloud-executor";
25
+ import type { ImportabilityManifestEntry } from "../importable";
26
+
27
+ /** What to do when the marker step stops after a good import. */
28
+ export function markerStepHint(stack: string, component: string, env: string): string {
29
+ return (
30
+ `The resources are imported into ${stack} and carry no chant markers yet. ` +
31
+ `A plain deploy of the same template writes them: chant run --components ${component} --env ${env}, without --adopt.`
32
+ );
33
+ }
34
+
35
+ /** The outcome lines and status for one adoption result. */
36
+ export function adoptionOutcome(
37
+ stack: string,
38
+ ctx: Pick<DeployContext, "component" | "env">,
39
+ plan: CfnAdoptionPlan | undefined,
40
+ result: CfnAdoptionOutcome,
41
+ ): DeployAdoptionOutcome {
42
+ const member = stack;
43
+ switch (result.status) {
44
+ case "adopted":
45
+ return {
46
+ member,
47
+ status: "adopted",
48
+ lines: [
49
+ ...(plan ? cfnImportReview(plan).map((l) => l.replace(/^import /, "imported ")) : []),
50
+ ...(plan ? cfnMarkerReview(plan) : []),
51
+ ...(result.markerChangeSet ? [] : ["the marker change set had nothing to write"]),
52
+ ],
53
+ };
54
+ case "refused": {
55
+ const after = result.step === "markers" ? [markerStepHint(stack, ctx.component, ctx.env)] : ["Nothing was imported."];
56
+ return { member, status: "refused", step: result.step, lines: [...result.refusals.map((r) => `refused: ${r}`), ...after] };
57
+ }
58
+ case "declined":
59
+ return {
60
+ member,
61
+ status: "declined",
62
+ step: result.step,
63
+ lines: [
64
+ `the ${result.step === "import" ? "IMPORT" : "marker"} change set was not approved and was deleted`,
65
+ result.step === "markers" ? markerStepHint(stack, ctx.component, ctx.env) : "Nothing was imported.",
66
+ ],
67
+ };
68
+ case "failed":
69
+ return {
70
+ member,
71
+ status: "failed",
72
+ step: result.step,
73
+ lines: [
74
+ `the ${result.step === "import" ? "IMPORT" : "marker"} change set executed and the stack reached ${result.stackStatus}; read the stack events for the resource that failed`,
75
+ ...(result.step === "markers" ? [markerStepHint(stack, ctx.component, ctx.env)] : []),
76
+ ],
77
+ };
78
+ }
79
+ }
80
+
81
+ /** Run the adoption in place of the step's deploy, and report its outcome on `adoption.outcome`. Throws unless it adopted. */
82
+ export async function runCfnAdoption(
83
+ executor: CloudExecutor,
84
+ ctx: DeployContext,
85
+ input: CfnDeployInput,
86
+ adoption: DeployAdoption,
87
+ opts: { manifest?: ReadonlyMap<string, ImportabilityManifestEntry>; waitOptions?: { intervalMs?: number; timeoutMs?: number } } = {},
88
+ ): Promise<CfnDeployOutput> {
89
+ const stack = input.stack ?? ctx.component;
90
+ if (adoption.outcome) {
91
+ throw new Error(`cfn-deploy "${stack}": the adoption is already taken by ${adoption.outcome.member}; --adopt adopts into one stack, so a component with two cfn-deploy steps cannot take it`);
92
+ }
93
+ const finish = (plan: CfnAdoptionPlan | undefined, result: CfnAdoptionOutcome): DeployAdoptionOutcome => {
94
+ adoption.outcome = adoptionOutcome(stack, ctx, plan, result);
95
+ return adoption.outcome;
96
+ };
97
+ const refuse = (refusals: string[]): never => {
98
+ const outcome = finish(undefined, { status: "refused", step: "plan", refusals });
99
+ throw new Error(`cfn-deploy "${stack}": adoption refused: ${outcome.lines.join(" ")}`);
100
+ };
101
+
102
+ const template = readCfnTemplate(input.template);
103
+ if (!template || typeof template.Resources !== "object" || template.Resources === null) {
104
+ refuse([`the template ${input.template} cannot be read here as a CloudFormation JSON template; adoption plans from the built template`]);
105
+ }
106
+ const cfn = executor.cloudformation;
107
+ if (!cfn.listStackResources) refuse(["this CloudFormation client cannot list the stack's resources, so it cannot tell which are already in the stack"]);
108
+ let existing: string[];
109
+ try {
110
+ existing = await cfn.listStackResources!(stack);
111
+ } catch (err) {
112
+ return refuse([`could not list the resources of ${stack}: ${err instanceof Error ? err.message : String(err)}`]);
113
+ }
114
+ const plan = planCfnAdoption({ template: template as unknown as CfnTemplate, adoption: adoption.adoption, index: adoption.index, existing: new Set(existing), ...(opts.manifest ? { manifest: opts.manifest } : {}) });
115
+ if (plan.refusals.length > 0) refuse(plan.refusals);
116
+
117
+ const parameters = flattenCfnInputs(input);
118
+ const result = await adoptIntoStack({
119
+ cfn,
120
+ stackName: stack,
121
+ plan,
122
+ ...(parameters ? { parameters } : {}),
123
+ ...(opts.waitOptions ? { waitOptions: opts.waitOptions } : {}),
124
+ review: (step, changeSet, lines) => {
125
+ const request: AdoptionReviewRequest = {
126
+ member: stack,
127
+ step,
128
+ changeSet: changeSet.changeSetName,
129
+ entries: changeSet.changes.map((c) => cfnChangeEntry(stack, c)),
130
+ lines,
131
+ };
132
+ return adoption.review(request);
133
+ },
134
+ });
135
+ const outcome = finish(plan, result);
136
+ if (result.status !== "adopted") {
137
+ throw new Error(`cfn-deploy "${stack}": adoption ${outcome.status}${outcome.step ? ` at the ${outcome.step} step` : ""}: ${outcome.lines.join(" ")}`);
138
+ }
139
+ const { stackStatus, outputs } = await cfn.describeStack(stack);
140
+ return { stackStatus, outputs };
141
+ }
@@ -0,0 +1,284 @@
1
+ /**
2
+ * #4536: CloudFormation adoption over a fake CloudFormation client. The
3
+ * IMPORT change set carries no markers and no stack tags, the UPDATE adds
4
+ * them and must be tags only, each change set goes through the review, and
5
+ * the plan refuses create-only tags, a type CloudFormation cannot import, a
6
+ * resource with no DeletionPolicy, an extra resource and a stale adoption
7
+ * file. Nothing reaches a cloud; the floci run is a maintainer run.
8
+ */
9
+ import { readFileSync } from "node:fs";
10
+ import { describe, expect, test } from "vitest";
11
+ import { indexDocumentDigest, indexScopeKey, indexVersionName, type CloudIndexScope, type IndexDocument } from "@intentius/chant/lifecycle/index-document";
12
+ import type { AdoptionFile } from "@intentius/chant/lifecycle/adoption-file";
13
+ import type { ImportabilityManifestEntry } from "../importable";
14
+ import {
15
+ adoptIntoStack,
16
+ cfnMarkerReview,
17
+ cfnResourceIdentifier,
18
+ markerChangeSetProblems,
19
+ planCfnAdoption,
20
+ type CfnAdoptionReview,
21
+ type CfnTemplate,
22
+ } from "./cfn-adopt";
23
+ import type { CfnChange, CfnChangeSet, CfnCreateChangeSetArgs, CfnCreateImportChangeSetArgs, CloudFormationClient } from "./cloud-executor";
24
+
25
+ const SCOPE: CloudIndexScope = { kind: "cloud", substrate: "aws", scopeId: "000000000000", locations: ["us-east-1"], types: "*" };
26
+ const BUCKET = "aws/000000000000/us-east-1/AWS::S3::Bucket/web-logs";
27
+ const KEYPAIR = "aws/000000000000/us-east-1/AWS::EC2::KeyPair/deploy";
28
+ const ROUTE = "aws/000000000000/us-east-1/AWS::EC2::Route/rtb-1|0.0.0.0/0";
29
+ const graph = {
30
+ version: 1 as const,
31
+ nodes: [
32
+ { id: BUCKET, kind: "AWS::S3::Bucket", lexicon: "aws", attrs: { BucketName: "web-logs" }, listedType: "AWS::S3::Bucket", location: "us-east-1", nativeId: "web-logs" },
33
+ { id: KEYPAIR, kind: "AWS::EC2::KeyPair", lexicon: "aws", attrs: { KeyName: "deploy" }, listedType: "AWS::EC2::KeyPair", location: "us-east-1", nativeId: "deploy" },
34
+ { id: ROUTE, kind: "AWS::EC2::Route", lexicon: "aws", attrs: {}, listedType: "AWS::EC2::Route", location: "us-east-1", nativeId: "rtb-1|0.0.0.0/0" },
35
+ ],
36
+ edges: [],
37
+ groups: {},
38
+ };
39
+ const INDEX: IndexDocument = {
40
+ index: "v1",
41
+ stamp: { source: { kind: "cloud", name: "behold-lister" }, scope: SCOPE, scopeKey: indexScopeKey(SCOPE), observedAt: "2026-10-26T12:00:00Z", digest: indexDocumentDigest({ graph, coverage: [] }) },
42
+ coverage: [],
43
+ graph,
44
+ };
45
+ const ALL = ["create", "delete", "list", "read", "update"];
46
+ const MANIFEST = new Map<string, ImportabilityManifestEntry>([
47
+ ["AWS::S3::Bucket", { resourceType: "AWS::S3::Bucket", kind: "resource", handlers: ALL, primaryIdentifier: ["BucketName"], tagging: { taggable: true, tagUpdatable: true, tagProperty: "Tags", tagShape: "list" } }],
48
+ ["AWS::EC2::KeyPair", { resourceType: "AWS::EC2::KeyPair", kind: "resource", handlers: ALL, primaryIdentifier: ["KeyName"], tagging: { taggable: true, tagUpdatable: false, tagProperty: "Tags", tagShape: "list" } }],
49
+ ["AWS::EC2::Route", { resourceType: "AWS::EC2::Route", kind: "resource", handlers: ALL, primaryIdentifier: ["RouteTableId", "DestinationCidrBlock"] }],
50
+ ["AWS::IAM::Policy", { resourceType: "AWS::IAM::Policy", kind: "resource", handlers: ["create", "delete", "update"], primaryIdentifier: ["Id"] }],
51
+ ]);
52
+ const MARKERS = [
53
+ { Key: "chant:managed-by", Value: "chant" },
54
+ { Key: "chant:stack", Value: "web" },
55
+ { Key: "chant:env", Value: "prod" },
56
+ ];
57
+
58
+ const adoption = (select: AdoptionFile["select"]): AdoptionFile => ({
59
+ adopt: "v1",
60
+ index: { scopeKey: INDEX.stamp.scopeKey, version: indexVersionName(INDEX.stamp.observedAt, INDEX.stamp.digest), digest: INDEX.stamp.digest },
61
+ select,
62
+ });
63
+ const template = (): CfnTemplate => ({
64
+ AWSTemplateFormatVersion: "2010-09-09",
65
+ Metadata: { "chant:ownership": { "chant:managed-by": "chant", "chant:stack": "web", "chant:env": "prod" } },
66
+ Resources: {
67
+ BucketWebLogs: {
68
+ Type: "AWS::S3::Bucket",
69
+ DeletionPolicy: "Retain",
70
+ UpdateReplacePolicy: "Retain",
71
+ Properties: { BucketName: "web-logs", Tags: [{ Key: "team", Value: "shop" }, ...MARKERS] },
72
+ },
73
+ },
74
+ });
75
+ const bucketOnly = () => adoption([{ node: BUCKET, as: "BucketWebLogs", type: "AWS::S3::Bucket" }]);
76
+
77
+ interface Fake {
78
+ cfn: CloudFormationClient;
79
+ calls: string[];
80
+ templates: Record<string, unknown>;
81
+ imports: CfnCreateImportChangeSetArgs[];
82
+ }
83
+
84
+ function fakeCfn(opts: { importChanges?: CfnChange[]; markerChanges?: CfnChange[]; markerNoop?: boolean; noImport?: boolean } = {}): Fake {
85
+ const calls: string[] = [];
86
+ const templates: Record<string, unknown> = {};
87
+ const imports: CfnCreateImportChangeSetArgs[] = [];
88
+ let status = "REVIEW_IN_PROGRESS";
89
+ let pending: "IMPORT" | "UPDATE" | undefined;
90
+ const cs = (name: string, changes: CfnChange[], extra: Partial<CfnChangeSet> = {}): CfnChangeSet => ({ changeSetName: name, stackName: "web", status: "CREATE_COMPLETE", isCreate: false, changes, ...extra });
91
+ const cfn: CloudFormationClient = {
92
+ async createImportChangeSet(args) {
93
+ calls.push("createImportChangeSet");
94
+ imports.push(args);
95
+ templates.import = JSON.parse(readFileSync(args.templatePath, "utf8"));
96
+ pending = "IMPORT";
97
+ const changes = opts.importChanges ?? args.resourcesToImport.map((r) => ({ action: "Import" as const, logicalResourceId: r.logicalResourceId, resourceType: r.resourceType, replacement: false }));
98
+ return cs("cs-import", changes, { changeSetType: "IMPORT" });
99
+ },
100
+ async createChangeSet(args: CfnCreateChangeSetArgs) {
101
+ calls.push("createChangeSet");
102
+ templates.markers = JSON.parse(readFileSync(args.templatePath, "utf8"));
103
+ pending = "UPDATE";
104
+ if (opts.markerNoop) return cs("cs-markers", [], { status: "FAILED", statusReason: "The submitted information didn't contain changes." });
105
+ return cs("cs-markers", opts.markerChanges ?? [{ action: "Modify", logicalResourceId: "BucketWebLogs", resourceType: "AWS::S3::Bucket", replacement: false, replacementMode: "False", details: ["Tags"] }]);
106
+ },
107
+ async executeChangeSet(args) {
108
+ calls.push(`execute:${args.changeSetName}`);
109
+ status = pending === "IMPORT" ? "IMPORT_COMPLETE" : "UPDATE_COMPLETE";
110
+ },
111
+ async deleteChangeSet(args) {
112
+ calls.push(`delete:${args.changeSetName}`);
113
+ },
114
+ async waitForStack() {
115
+ calls.push("waitForStack");
116
+ return { stackStatus: status, outputs: {} };
117
+ },
118
+ async describeStack() {
119
+ return { stackStatus: status, outputs: {} };
120
+ },
121
+ async rollbackStack() {},
122
+ };
123
+ if (opts.noImport) delete cfn.createImportChangeSet;
124
+ return { cfn, calls, templates, imports };
125
+ }
126
+
127
+ const approveAll = (seen: Array<{ step: string; lines: string[] }> = []): CfnAdoptionReview => async (step, _cs, lines) => {
128
+ seen.push({ step, lines });
129
+ return true;
130
+ };
131
+
132
+ describe("planCfnAdoption (#4536)", () => {
133
+ test("the IMPORT template drops the markers and the stack tags; the marker template keeps them", () => {
134
+ const plan = planCfnAdoption({ template: template(), adoption: bucketOnly(), index: INDEX, manifest: MANIFEST });
135
+ expect(plan.refusals).toEqual([]);
136
+ expect(plan.resources).toEqual([
137
+ {
138
+ node: BUCKET,
139
+ logicalId: "BucketWebLogs",
140
+ type: "AWS::S3::Bucket",
141
+ identifier: { BucketName: "web-logs" },
142
+ deletionPolicy: "Retain",
143
+ tagProperty: "Tags",
144
+ markers: { "chant:managed-by": "chant", "chant:stack": "web", "chant:env": "prod" },
145
+ },
146
+ ]);
147
+ expect(plan.importTemplate.Resources.BucketWebLogs!.Properties!.Tags).toEqual([{ Key: "team", Value: "shop" }]);
148
+ expect(plan.importTemplate.Metadata).toBeUndefined();
149
+ expect(plan.importTemplate.Resources.BucketWebLogs!.DeletionPolicy).toBe("Retain");
150
+ expect(plan.markerTemplate).toEqual(template());
151
+ });
152
+
153
+ test("a tag list of markers only is dropped from the IMPORT template", () => {
154
+ const t = template();
155
+ t.Resources.BucketWebLogs!.Properties!.Tags = [...MARKERS];
156
+ const plan = planCfnAdoption({ template: t, adoption: bucketOnly(), index: INDEX, manifest: MANIFEST });
157
+ expect(plan.importTemplate.Resources.BucketWebLogs!.Properties!.Tags).toBeUndefined();
158
+ });
159
+
160
+ test("create-only tags are refused by name, never replaced to mark them", () => {
161
+ const t = template();
162
+ t.Resources.KeyPairDeploy = { Type: "AWS::EC2::KeyPair", DeletionPolicy: "Retain", Properties: { KeyName: "deploy" } };
163
+ const plan = planCfnAdoption({
164
+ template: t,
165
+ adoption: adoption([{ node: BUCKET, as: "BucketWebLogs" }, { node: KEYPAIR, as: "KeyPairDeploy" }]),
166
+ index: INDEX,
167
+ manifest: MANIFEST,
168
+ });
169
+ expect(plan.refusals).toEqual(["KeyPairDeploy: AWS::EC2::KeyPair's tags can only be set at create, so writing chant's markers would replace it"]);
170
+ });
171
+
172
+ test("a resource with no DeletionPolicy, one already in the stack, and an extra resource are refused", () => {
173
+ const t = template();
174
+ delete t.Resources.BucketWebLogs!.DeletionPolicy;
175
+ t.Resources.NewQueue = { Type: "AWS::SQS::Queue", Properties: {} };
176
+ const plan = planCfnAdoption({ template: t, adoption: bucketOnly(), index: INDEX, manifest: MANIFEST, existing: new Set(["BucketWebLogs"]) });
177
+ expect(plan.refusals.join("\n")).toMatch(/BucketWebLogs declares no DeletionPolicy/);
178
+ expect(plan.refusals.join("\n")).toMatch(/BucketWebLogs is already in the stack/);
179
+ expect(plan.refusals.join("\n")).toMatch(/the template also creates NewQueue/);
180
+ });
181
+
182
+ test("a stale adoption file, a missing logical id and a type mismatch are refused", () => {
183
+ const stale = bucketOnly();
184
+ stale.index = { ...stale.index, digest: "0".repeat(64), version: indexVersionName(INDEX.stamp.observedAt, "0".repeat(64)) };
185
+ expect(planCfnAdoption({ template: template(), adoption: stale, index: INDEX, manifest: MANIFEST }).refusals.join("\n")).toMatch(/digest does not match/);
186
+ const missing = adoption([{ node: BUCKET, as: "Elsewhere" }]);
187
+ expect(planCfnAdoption({ template: template(), adoption: missing, index: INDEX, manifest: MANIFEST }).refusals.join("\n")).toMatch(/declares no resource Elsewhere/);
188
+ const wrongType = adoption([{ node: BUCKET, as: "BucketWebLogs", type: "aws_s3_bucket" }]);
189
+ expect(planCfnAdoption({ template: template(), adoption: wrongType, index: INDEX, manifest: MANIFEST }).refusals.join("\n")).toMatch(/names type aws_s3_bucket/);
190
+ });
191
+
192
+ test("a composite identifier splits on |", () => {
193
+ expect(cfnResourceIdentifier(["RouteTableId", "DestinationCidrBlock"], "rtb-1|0.0.0.0/0")).toEqual({ RouteTableId: "rtb-1", DestinationCidrBlock: "0.0.0.0/0" });
194
+ expect(cfnResourceIdentifier(["A", "B"], "only-one")).toBeUndefined();
195
+ });
196
+
197
+ test("the marker review lists each marker write as tags only", () => {
198
+ const plan = planCfnAdoption({ template: template(), adoption: bucketOnly(), index: INDEX, manifest: MANIFEST });
199
+ expect(cfnMarkerReview(plan)).toEqual(["marker write, tags only: BucketWebLogs (AWS::S3::Bucket) Tags += chant:env=prod, chant:managed-by=chant, chant:stack=web"]);
200
+ });
201
+ });
202
+
203
+ describe("adoptIntoStack (#4536)", () => {
204
+ test("IMPORT then the marker UPDATE, each reviewed before it executes", async () => {
205
+ const fake = fakeCfn();
206
+ const seen: Array<{ step: string; lines: string[] }> = [];
207
+ const plan = planCfnAdoption({ template: template(), adoption: bucketOnly(), index: INDEX, manifest: MANIFEST });
208
+ const out = await adoptIntoStack({ cfn: fake.cfn, stackName: "web", plan, review: approveAll(seen) });
209
+ expect(out).toMatchObject({ status: "adopted", importChangeSet: "cs-import", markerChangeSet: "cs-markers" });
210
+ expect(fake.calls).toEqual(["createImportChangeSet", "execute:cs-import", "waitForStack", "createChangeSet", "execute:cs-markers", "waitForStack"]);
211
+ expect(fake.imports[0]!.resourcesToImport).toEqual([{ resourceType: "AWS::S3::Bucket", logicalResourceId: "BucketWebLogs", resourceIdentifier: { BucketName: "web-logs" } }]);
212
+ expect(JSON.stringify(fake.templates.import)).not.toContain("chant:");
213
+ expect(JSON.stringify(fake.templates.markers)).toContain("chant:managed-by");
214
+ expect(seen.map((s) => s.step)).toEqual(["import", "markers"]);
215
+ expect(seen[0]!.lines).toEqual(["import BucketWebLogs (AWS::S3::Bucket) BucketName=web-logs, DeletionPolicy Retain"]);
216
+ expect(seen[1]!.lines[0]).toMatch(/^marker write, tags only: BucketWebLogs/);
217
+ });
218
+
219
+ test("a plan with refusals makes no change set", async () => {
220
+ const fake = fakeCfn();
221
+ const t = template();
222
+ t.Resources.KeyPairDeploy = { Type: "AWS::EC2::KeyPair", DeletionPolicy: "Retain", Properties: { KeyName: "deploy" } };
223
+ const plan = planCfnAdoption({ template: t, adoption: adoption([{ node: BUCKET, as: "BucketWebLogs" }, { node: KEYPAIR, as: "KeyPairDeploy" }]), index: INDEX, manifest: MANIFEST });
224
+ const out = await adoptIntoStack({ cfn: fake.cfn, stackName: "web", plan, review: approveAll() });
225
+ expect(out.status).toBe("refused");
226
+ expect(fake.calls).toEqual([]);
227
+ });
228
+
229
+ test("a declined import review deletes the change set and executes nothing", async () => {
230
+ const fake = fakeCfn();
231
+ const plan = planCfnAdoption({ template: template(), adoption: bucketOnly(), index: INDEX, manifest: MANIFEST });
232
+ const out = await adoptIntoStack({ cfn: fake.cfn, stackName: "web", plan, review: async () => false });
233
+ expect(out).toEqual({ status: "declined", step: "import" });
234
+ expect(fake.calls).toEqual(["createImportChangeSet", "delete:cs-import"]);
235
+ });
236
+
237
+ test("an IMPORT change set that would touch another resource is refused and deleted", async () => {
238
+ const fake = fakeCfn({
239
+ importChanges: [
240
+ { action: "Import", logicalResourceId: "BucketWebLogs", resourceType: "AWS::S3::Bucket", replacement: false },
241
+ { action: "Add", logicalResourceId: "Other", resourceType: "AWS::SQS::Queue", replacement: false },
242
+ ],
243
+ });
244
+ const plan = planCfnAdoption({ template: template(), adoption: bucketOnly(), index: INDEX, manifest: MANIFEST });
245
+ const out = await adoptIntoStack({ cfn: fake.cfn, stackName: "web", plan, review: approveAll() });
246
+ expect(out).toMatchObject({ status: "refused", step: "import" });
247
+ expect(fake.calls).toEqual(["createImportChangeSet", "delete:cs-import"]);
248
+ });
249
+
250
+ test("a marker UPDATE that changes more than tags, or replaces, is refused before it executes", async () => {
251
+ for (const change of [
252
+ { action: "Modify" as const, logicalResourceId: "BucketWebLogs", resourceType: "AWS::S3::Bucket", replacement: false, details: ["Tags", "VersioningConfiguration"] },
253
+ { action: "Modify" as const, logicalResourceId: "BucketWebLogs", resourceType: "AWS::S3::Bucket", replacement: true, replacementMode: "True" as const, details: ["Tags"] },
254
+ { action: "Add" as const, logicalResourceId: "Other", resourceType: "AWS::SQS::Queue", replacement: false },
255
+ ]) {
256
+ const fake = fakeCfn({ markerChanges: [change] });
257
+ const plan = planCfnAdoption({ template: template(), adoption: bucketOnly(), index: INDEX, manifest: MANIFEST });
258
+ const out = await adoptIntoStack({ cfn: fake.cfn, stackName: "web", plan, review: approveAll() });
259
+ expect(out).toMatchObject({ status: "refused", step: "markers" });
260
+ expect(fake.calls.slice(-2)).toEqual(["createChangeSet", "delete:cs-markers"]);
261
+ expect(fake.calls).not.toContain("execute:cs-markers");
262
+ }
263
+ });
264
+
265
+ test("a marker UPDATE with nothing to change ends the adoption without executing it", async () => {
266
+ const fake = fakeCfn({ markerNoop: true });
267
+ const plan = planCfnAdoption({ template: template(), adoption: bucketOnly(), index: INDEX, manifest: MANIFEST });
268
+ const out = await adoptIntoStack({ cfn: fake.cfn, stackName: "web", plan, review: approveAll() });
269
+ expect(out).toMatchObject({ status: "adopted", importChangeSet: "cs-import" });
270
+ expect(fake.calls).toEqual(["createImportChangeSet", "execute:cs-import", "waitForStack", "createChangeSet", "delete:cs-markers"]);
271
+ });
272
+
273
+ test("a client that cannot create an IMPORT change set is refused", async () => {
274
+ const fake = fakeCfn({ noImport: true });
275
+ const plan = planCfnAdoption({ template: template(), adoption: bucketOnly(), index: INDEX, manifest: MANIFEST });
276
+ expect(await adoptIntoStack({ cfn: fake.cfn, stackName: "web", plan, review: approveAll() })).toMatchObject({ status: "refused", step: "plan" });
277
+ });
278
+
279
+ test("markerChangeSetProblems accepts a tags-only Modify on an imported resource", () => {
280
+ const plan = planCfnAdoption({ template: template(), adoption: bucketOnly(), index: INDEX, manifest: MANIFEST });
281
+ const cs: CfnChangeSet = { changeSetName: "x", stackName: "web", status: "CREATE_COMPLETE", isCreate: false, changes: [{ action: "Modify", logicalResourceId: "BucketWebLogs", resourceType: "AWS::S3::Bucket", replacement: false, details: ["Tags"] }] };
282
+ expect(markerChangeSetProblems(cs, plan)).toEqual([]);
283
+ });
284
+ });