@intentius/chant-lexicon-aws 0.124.54 → 0.124.56

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 (48) 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/components/apply.d.ts +2 -0
  11. package/dist/components/apply.d.ts.map +1 -1
  12. package/dist/components/apply.js +6 -1
  13. package/dist/components/cfn-adopt-run.d.ts +37 -0
  14. package/dist/components/cfn-adopt-run.d.ts.map +1 -0
  15. package/dist/components/cfn-adopt-run.js +104 -0
  16. package/dist/components/cloud-executor.d.ts +7 -0
  17. package/dist/components/cloud-executor.d.ts.map +1 -1
  18. package/dist/components/cloud-executor.js +20 -0
  19. package/dist/health.js +1 -1
  20. package/dist/index-import.d.ts +8 -0
  21. package/dist/index-import.d.ts.map +1 -1
  22. package/dist/index-import.js +20 -3
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +1 -1
  26. package/dist/integrity.json +3 -3
  27. package/dist/manifest.json +1 -1
  28. package/dist/plugin.js +3 -3
  29. package/dist/skills/chant-aws-carve-terraform.md +21 -14
  30. package/package.json +2 -2
  31. package/src/api/credential-chain.ts +3 -3
  32. package/src/api/read-client.test.ts +2 -2
  33. package/src/api/read-client.ts +3 -3
  34. package/src/api/{sigv4.test.ts → signing.test.ts} +84 -96
  35. package/src/api/signing.ts +130 -0
  36. package/src/components/apply.ts +6 -1
  37. package/src/components/cfn-adopt-run.test.ts +227 -0
  38. package/src/components/cfn-adopt-run.ts +141 -0
  39. package/src/components/cloud-executor.ts +25 -0
  40. package/src/health.ts +1 -1
  41. package/src/index-import.test.ts +16 -1
  42. package/src/index-import.ts +20 -2
  43. package/src/index.ts +1 -1
  44. package/src/plugin.ts +3 -3
  45. package/src/skills/chant-aws-carve-terraform.md +21 -14
  46. package/dist/api/sigv4.d.ts.map +0 -1
  47. package/dist/api/sigv4.js +0 -185
  48. package/src/api/sigv4.ts +0 -243
@@ -0,0 +1,130 @@
1
+ /**
2
+ * AWS request signing for the shared read transport (#1686), through core's
3
+ * one SigV4 signer (`@intentius/chant/cloud-lister/sigv4`, #4583).
4
+ *
5
+ * This lexicon kept its own SigV4 implementation until #4583; it now holds
6
+ * only the lexicon's signing surface (`signRequest`, `resolveCredentials` and
7
+ * the credential types cedar's AVP client restates) and the header set it
8
+ * signs. Core does the canonicalization and the HMACs.
9
+ *
10
+ * ## What is signed, and what is not
11
+ *
12
+ * Header signing only. `host` is signed but never emitted: `fetch` computes
13
+ * `Host` from the URL and forbids overriding it, so the signer derives the
14
+ * same value from the URL it was given. A transport that rewrites the URL
15
+ * underneath the signer (a proxy that keeps the original `Host`, say) would
16
+ * invalidate the signature; the injectable-HTTP seam is for tests and
17
+ * emulators, not for URL rewriting.
18
+ *
19
+ * `x-amz-content-sha256` is always sent and signed. The headers in
20
+ * {@link UNSIGNED_HEADERS} are sent when a caller sets them but never signed.
21
+ *
22
+ * The canonical path is the URL's pathname as it stands (core's rule, which is
23
+ * S3's). Every caller here POSTs to `/` or reads a Route 53 path of plain
24
+ * segments, where that agrees with the twice-encoded form other services
25
+ * define; a caller with a path that needs encoding is the moment to revisit it.
26
+ */
27
+ import { signV4 } from "@intentius/chant/cloud-lister/sigv4";
28
+
29
+ /** SHA-256 of the empty string, the payload hash of every bodyless request. */
30
+ export const EMPTY_PAYLOAD_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
31
+
32
+ /**
33
+ * Headers that are never signed even when a caller sets them: `authorization`
34
+ * is the output, and the others are rewritten in transit by proxies and agents,
35
+ * so signing them produces intermittent 403s rather than security.
36
+ */
37
+ export const UNSIGNED_HEADERS: readonly string[] = ["authorization", "connection", "expect", "user-agent", "x-amzn-trace-id"];
38
+
39
+ /** A resolved credential set. `sessionToken` is present for STS/role credentials. */
40
+ export interface AwsCredentials {
41
+ accessKeyId: string;
42
+ secretAccessKey: string;
43
+ sessionToken?: string;
44
+ }
45
+
46
+ /**
47
+ * The credential injection seam: a function the caller supplies to decide, by
48
+ * whatever means it likes, what to sign with. Returning `undefined` means "this
49
+ * process has no credentials" and is respected as an answer, not overridden.
50
+ */
51
+ export type AwsCredentialResolver = () => AwsCredentials | undefined;
52
+
53
+ /** Either literal credentials or a resolver for them. */
54
+ export type AwsCredentialSource = AwsCredentials | AwsCredentialResolver;
55
+
56
+ /**
57
+ * Credentials for a request: explicit, then environment, then absent.
58
+ *
59
+ * A resolver function is authoritative: if one is injected and it declines,
60
+ * the environment is not consulted behind its back, because the point of
61
+ * injecting one is to control the answer. Literal credentials are likewise
62
+ * final. Only the no-source case falls through to `AWS_ACCESS_KEY_ID` /
63
+ * `AWS_SECRET_ACCESS_KEY` (plus `AWS_SESSION_TOKEN` when set), and a half-set
64
+ * environment (a key id with no secret) is absent rather than a signature
65
+ * that cannot verify.
66
+ *
67
+ * The shared profile files are resolved asynchronously by
68
+ * `./credential-chain.ts`, and the read transport passes its answer in as
69
+ * literal credentials (#3958), so this function stays synchronous. Not
70
+ * implemented anywhere: IMDS and the container credential endpoints.
71
+ */
72
+ export function resolveCredentials(
73
+ source?: AwsCredentialSource,
74
+ env: Record<string, string | undefined> = process.env,
75
+ ): AwsCredentials | undefined {
76
+ if (typeof source === "function") return source();
77
+ if (source) return source;
78
+ const accessKeyId = env.AWS_ACCESS_KEY_ID;
79
+ const secretAccessKey = env.AWS_SECRET_ACCESS_KEY;
80
+ if (!accessKeyId || !secretAccessKey) return undefined;
81
+ return {
82
+ accessKeyId,
83
+ secretAccessKey,
84
+ ...(env.AWS_SESSION_TOKEN ? { sessionToken: env.AWS_SESSION_TOKEN } : {}),
85
+ };
86
+ }
87
+
88
+ /** One request to sign. `headers` are the caller's; the signer adds its own. */
89
+ export interface SigV4Request {
90
+ method: string;
91
+ /** Absolute URL. Its host is signed and its path/query are canonicalized. */
92
+ url: string;
93
+ headers: Record<string, string>;
94
+ body: string;
95
+ /** Service name as it appears in the credential scope (`cloudformation`, `cloudcontrolapi`, ...). */
96
+ service: string;
97
+ region: string;
98
+ credentials: AwsCredentials;
99
+ /** Signing clock. Injected by tests; otherwise now. */
100
+ now?: Date;
101
+ }
102
+
103
+ /** The headers core's signer adds, the ones {@link signRequest} returns beside the caller's own. */
104
+ const ADDED = ["x-amz-date", "x-amz-content-sha256", "x-amz-security-token", "authorization"] as const;
105
+
106
+ /**
107
+ * The caller's headers, as given, plus everything SigV4 adds: `x-amz-date`,
108
+ * `x-amz-content-sha256`, `x-amz-security-token` when the credentials are
109
+ * temporary, and the `Authorization` header itself.
110
+ *
111
+ * `host` is signed (AWS requires it) but not returned; see the module header.
112
+ */
113
+ export function signRequest(request: SigV4Request): Record<string, string> {
114
+ const signed = signV4({
115
+ method: request.method,
116
+ url: request.url,
117
+ headers: request.headers,
118
+ body: request.body,
119
+ region: request.region,
120
+ service: request.service,
121
+ credentials: request.credentials,
122
+ now: request.now ?? new Date(),
123
+ contentSha256: true,
124
+ omitHost: true,
125
+ unsignedHeaders: UNSIGNED_HEADERS,
126
+ });
127
+ const out: Record<string, string> = { ...request.headers };
128
+ for (const name of ADDED) if (signed[name] !== undefined) out[name] = signed[name];
129
+ return out;
130
+ }
@@ -1022,6 +1022,11 @@ export function createCfnDeployCapability(
1022
1022
  }
1023
1023
  },
1024
1024
  async run(ctx, input) {
1025
+ // #4537: `run --components <name> --adopt <file>` adopts into this stack instead of a plain deploy.
1026
+ if (ctx.adoption) {
1027
+ const { runCfnAdoption } = await import("./cfn-adopt-run");
1028
+ return runCfnAdoption(executor, ctx, input, ctx.adoption);
1029
+ }
1025
1030
  const stack = input.stack ?? ctx.component;
1026
1031
  const onReplace = input.onReplace ?? "block";
1027
1032
  const changeSet = await executor.cloudformation.createChangeSet({
@@ -1131,7 +1136,7 @@ export function createCfnDeployCapability(
1131
1136
  }
1132
1137
 
1133
1138
  /** Flatten the wired `inputs` map plus `imageRef` (already resolved by the driver) to plain string CloudFormation parameters. */
1134
- function flattenCfnInputs(input: CfnDeployInput): Record<string, string> | undefined {
1139
+ export function flattenCfnInputs(input: CfnDeployInput): Record<string, string> | undefined {
1135
1140
  const params: Record<string, string> = {};
1136
1141
  for (const [key, value] of Object.entries(input.inputs ?? {})) {
1137
1142
  params[key] = typeof value === "string" ? value : JSON.stringify(value);
@@ -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
+ }
@@ -157,6 +157,13 @@ export interface CloudFormationClient {
157
157
  * change to an export is in use, and refuses nothing.
158
158
  */
159
159
  listImports?(exportName: string): Promise<string[]>;
160
+ /**
161
+ * The logical ids of the stack's resources now (`ListStackResources`,
162
+ * #4537), sorted; empty when the stack does not exist. Adoption refuses a
163
+ * resource already in the stack. Optional: a client without it cannot
164
+ * adopt.
165
+ */
166
+ listStackResources?(stackName: string): Promise<string[]>;
160
167
  }
161
168
 
162
169
  // ── ECS ──────────────────────────────────────────────────────────────────��─
@@ -694,6 +701,24 @@ const realCloudFormation: CloudFormationClient = {
694
701
  } while (token);
695
702
  return [...new Set(stacks)].sort();
696
703
  },
704
+ async listStackResources(stackName) {
705
+ const ids: string[] = [];
706
+ let token: string | undefined;
707
+ do {
708
+ let stdout: string;
709
+ try {
710
+ ({ stdout } = await run(`aws cloudformation list-stack-resources --stack-name ${q(stackName)}${token ? ` --next-token ${q(token)}` : ""}`));
711
+ } catch (err) {
712
+ // A stack that does not exist yet holds nothing; the IMPORT change set creates it.
713
+ if (/does not exist/i.test(err instanceof Error ? err.message : String(err))) return [];
714
+ throw err;
715
+ }
716
+ const page = JSON.parse(stdout) as { StackResourceSummaries?: Array<{ LogicalResourceId: string }>; NextToken?: string };
717
+ ids.push(...(page.StackResourceSummaries ?? []).map((r) => r.LogicalResourceId));
718
+ token = page.NextToken;
719
+ } while (token);
720
+ return [...new Set(ids)].sort();
721
+ },
697
722
  async waitForStack(stackName, opts) {
698
723
  const intervalMs = opts?.intervalMs ?? 10_000;
699
724
  const deadline = opts?.timeoutMs ? Date.now() + opts.timeoutMs : undefined;
package/src/health.ts CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  xmlLeaves,
28
28
  type AwsReadClientOptions,
29
29
  } from "./api/read-client";
30
- import { resolveCredentials, signRequest } from "./api/sigv4";
30
+ import { resolveCredentials, signRequest } from "./api/signing";
31
31
  import { stackDoesNotExist } from "./stack-errors";
32
32
 
33
33
  export const AWS_HEALTH_TYPES = ["AWS::Route53::HealthCheck", "AWS::ECS::Service"] as const;
@@ -25,7 +25,7 @@ import { declaredNodes, planIndexImport, type IndexImportSelection } from "@inte
25
25
  import { typeListing, type ListingLexicon, type ListingResult } from "@intentius/chant/lifecycle/type-listing";
26
26
  import { indexImportReportJson, renderIndexImport } from "@intentius/chant/cli/commands/import-index";
27
27
  import type { LexiconPlugin } from "@intentius/chant/lexicon";
28
- import { awsImportProperties, createAwsIndexImport } from "./index-import";
28
+ import { awsImportProperties, createAwsIndexImport, isImportableAwsType } from "./index-import";
29
29
  import { awsKindForListedType } from "./listed-types";
30
30
  import { awsPlugin } from "./plugin";
31
31
  import { awsSerializer } from "./serializer";
@@ -236,6 +236,21 @@ describe("chant import --index on the aws fixture", () => {
236
236
  expect(plan.groups.map((g) => g.dir)).toEqual([""]);
237
237
  });
238
238
 
239
+ test("a type outside the AWS organization imports when the registry has it (#4538)", () => {
240
+ const rows = new Map(MANIFEST);
241
+ rows.set("Alexa::ASK::Skill", { resourceType: "Alexa::ASK::Skill", kind: "resource", attrs: {} });
242
+ const seam = createAwsIndexImport(rows);
243
+ const skill = { id: "aws:Alexa::ASK::Skill:amzn1.ask.skill.1", kind: "Alexa::ASK::Skill", lexicon: "aws", attrs: { SkillPackage: { Overrides: {} } } };
244
+ expect(seam.resource(skill)).toMatchObject({ type: "Alexa::ASK::Skill", properties: { SkillPackage: { Overrides: {} } } });
245
+ expect(isImportableAwsType("Alexa::ASK::Skill", rows)).toBe(true);
246
+ // Not in the registry, or not a CloudFormation type at all: refused.
247
+ expect(seam.resource({ ...skill, kind: "Alexa::ASK::Other" })).toEqual({ unsupported: expect.stringMatching(/not a CloudFormation resource type/) });
248
+ expect(isImportableAwsType("AWS::S3", rows)).toBe(false);
249
+ // With no registry, the listed-type rule's shape check alone decides.
250
+ expect(isImportableAwsType("Alexa::ASK::Skill", new Map())).toBe(true);
251
+ expect(isImportableAwsType("not-a-type", new Map())).toBe(false);
252
+ });
253
+
239
254
  test("the plugin declares the seam", () => {
240
255
  expect(awsPlugin.indexImport).toBeDefined();
241
256
  });
@@ -24,6 +24,7 @@ import { moduleSourceUrl } from "@intentius/chant/module-source";
24
24
  import type { IRNode } from "@intentius/chant/graph-ir";
25
25
  import type { IndexImportCodegen, IndexImportTarget } from "@intentius/chant/lifecycle/index-import";
26
26
  import type { ParameterIR } from "@intentius/chant/import/parser";
27
+ import { awsKindForListedType } from "./listed-types";
27
28
 
28
29
  const require = createRequire(moduleSourceUrl(import.meta.url));
29
30
 
@@ -49,7 +50,24 @@ function defaultManifest(): ReadonlyMap<string, ImportManifestEntry> {
49
50
  return cachedManifest;
50
51
  }
51
52
 
52
- const CFN_TYPE = /^AWS::[A-Za-z0-9]+::[A-Za-z0-9]+$/;
53
+ /**
54
+ * Whether `type` is a resource type this lexicon can write: the listed-type
55
+ * rule (./listed-types.ts) against the registry's kinds. The organization
56
+ * segment is not pinned to `AWS`, so `Alexa::ASK::Skill` imports. With no
57
+ * registry (a checkout that has not generated) every well-formed
58
+ * CloudFormation type does, as the listed-type mapping assumes.
59
+ */
60
+ export function isImportableAwsType(type: string, manifest: ReadonlyMap<string, ImportManifestEntry> = defaultManifest()): boolean {
61
+ return awsKindForListedType(type, manifest.size > 0 ? manifestKinds(manifest) : null) !== undefined;
62
+ }
63
+
64
+ const kindSets = new WeakMap<ReadonlyMap<string, ImportManifestEntry>, ReadonlySet<string>>();
65
+
66
+ function manifestKinds(manifest: ReadonlyMap<string, ImportManifestEntry>): ReadonlySet<string> {
67
+ let kinds = kindSets.get(manifest);
68
+ if (!kinds) kindSets.set(manifest, (kinds = new Set(manifest.keys())));
69
+ return kinds;
70
+ }
53
71
 
54
72
  function isRecord(v: unknown): v is Record<string, unknown> {
55
73
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -113,7 +131,7 @@ export function createAwsIndexImport(manifest?: ReadonlyMap<string, ImportManife
113
131
  const m = () => manifest ?? defaultManifest();
114
132
  return {
115
133
  resource(node: IRNode) {
116
- if (!CFN_TYPE.test(node.kind)) return { unsupported: `${node.kind} is not a CloudFormation resource type` };
134
+ if (!isImportableAwsType(node.kind, m())) return { unsupported: `${node.kind} is not a CloudFormation resource type the aws lexicon generates` };
117
135
  // Retain on every imported resource until a person changes it in source
118
136
  // (#4536, ruled on choudoufu#2284 Q4): CloudFormation deletes at stack
119
137
  // level and reads no per-resource marker, so an adopted object is never
package/src/index.ts CHANGED
@@ -99,7 +99,7 @@ export {
99
99
  resolveCredentials,
100
100
  EMPTY_PAYLOAD_SHA256,
101
101
  type SigV4Request,
102
- } from "./api/sigv4";
102
+ } from "./api/signing";
103
103
 
104
104
  // Intrinsics
105
105
  export {