@intentius/chant-lexicon-aws 0.124.54 → 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 (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
package/src/plugin.ts CHANGED
@@ -596,7 +596,7 @@ aws cloudformation wait stack-update-complete --stack-name my-app-prod`,
596
596
  {
597
597
  file: "chant-aws-carve-terraform.md",
598
598
  name: "chant-aws-carve-terraform",
599
- description: "Demo carving a resource out of Terraform into native chant — advise, emit, audit, bridge, apply — fully offline",
599
+ description: "Demo moving one Terraform resource to native CloudFormation, fully offline (advise, emit, audit, bridge, apply); Terraform keeps the rest",
600
600
  triggers: [
601
601
  { type: "context", value: "terraform" },
602
602
  { type: "context", value: "carve" },
@@ -620,12 +620,12 @@ aws cloudformation wait stack-update-complete --stack-name my-app-prod`,
620
620
  {
621
621
  title: "Run the offline demo",
622
622
  description: "Demo the full advise → emit → bridge → apply loop with no cloud",
623
- input: "Show me how chant carves a resource out of Terraform",
623
+ input: "Show me how chant moves one resource from Terraform to CloudFormation",
624
624
  output: "cd examples/terraform-carve-out && ./demo.sh",
625
625
  },
626
626
  {
627
627
  title: "Adopt a resource from state",
628
- description: "Emit native chant source for a Terraform-managed resource, offline",
628
+ description: "Emit chant source for the AWS lexicon from a Terraform-managed resource, offline",
629
629
  input: "Adopt aws_s3_bucket.assets into chant",
630
630
  output: "chant carve emit --from ./terraform --select aws_s3_bucket.assets --state ./terraform/terraform.tfstate",
631
631
  },
@@ -1,20 +1,26 @@
1
1
  ---
2
2
  skill: chant-aws-carve-terraform
3
- description: Demo carving a resource out of Terraform into native chant — advise, emit, audit, bridge, apply — fully offline
3
+ description: Demo moving one Terraform resource to native CloudFormation, fully offline (advise, emit, audit, bridge, apply); Terraform keeps the rest
4
4
  user-invocable: true
5
5
  ---
6
6
 
7
- # Carve a resource out of Terraform (demo)
7
+ # Move one Terraform resource to CloudFormation (demo)
8
8
 
9
- Use this skill to cleanly demonstrate chant's Terraform carve-out flow for
10
- someone. The whole demo runs **offline** — no cloud account, no Terraform
11
- binary, no state backend. It carves an AWS S3 bucket out of a small Terraform
12
- estate into native chant source, patches the survivors, and plans the
13
- graduation.
9
+ Use this skill to demonstrate chant's carve flow, which moves one resource
10
+ from a Terraform estate to chant source for the AWS lexicon. The whole demo
11
+ runs **offline**, with no cloud account, Terraform binary or state backend. It
12
+ moves an S3 bucket from a small Terraform estate to chant source, patches the
13
+ resources that stay in Terraform, and plans the graduation.
14
14
 
15
15
  ## When to use
16
16
 
17
- - Someone asks "how does chant move things off Terraform?"
17
+ - Someone asks how chant can manage one resource from a Terraform root as
18
+ native CloudFormation.
19
+ - Someone on Terraform or OpenTofu asks how to get chant's ownership markers
20
+ on their resources. Point them at choudoufu instead
21
+ (`terraform.binary: "choudoufu"`, see
22
+ https://intentius.io/chant/lexicons/terraform/ops/#choudoufu). Their roots
23
+ stay in OpenTofu.
18
24
  - You want to show the advise → emit → audit → bridge → apply loop end to end.
19
25
  - You are evaluating whether a Terraform estate is worth carving.
20
26
 
@@ -40,12 +46,12 @@ Walk the person through the output. That is the whole demo.
40
46
 
41
47
  From `examples/terraform-carve-out`, with `TF=./terraform`:
42
48
 
43
- 1. **Advise — what is cheap to carve.**
49
+ 1. **Advise: rank the resources.**
44
50
  ```bash
45
51
  chant carve advise --from ./terraform
46
52
  ```
47
53
  Point out the three bands: clean leaves (carve now), carvable with edits,
48
- and leave-in-Terraform. `aws_s3_bucket.assets` is a clean leaf held back one
54
+ and stays in Terraform (`leave in Terraform` in the JSON). `aws_s3_bucket.assets` is a clean leaf held back one
49
55
  notch by the Lambda that reads it; `random_pet` has no native mapping.
50
56
 
51
57
  2. **Emit — adopt the bucket into chant source, offline, from state.**
@@ -68,9 +74,9 @@ From `examples/terraform-carve-out`, with `TF=./terraform`:
68
74
  chant build ./carveout/src --lexicon aws
69
75
  ```
70
76
  The first build fails, deliberately: the post-synth audit refuses the
71
- adopted bucket because Terraform managed it without a public-access block or
72
- a TLS-only policy. This is a feature of carving: chant immediately tells the
73
- person what is wrong with what they adopted. Show the fix (add
77
+ adopted bucket because it has no public-access block or TLS-only policy.
78
+ This is a feature of carving: chant tells the person which settings the
79
+ adopted resource is missing. Show the fix (add
74
80
  `PublicAccessBlockConfiguration` and a companion `S3BucketPolicy` with an
75
81
  `aws:SecureTransport = false` Deny — the tutorial page has the exact code),
76
82
  then re-run the build and show the valid CloudFormation template.
@@ -96,7 +102,8 @@ From `examples/terraform-carve-out`, with `TF=./terraform`:
96
102
 
97
103
  - Nothing is destroyed or applied; every step before graduation is reversible
98
104
  with `terraform import`.
99
- - You carve one resource at a time. The gnarly long tail stays in Terraform.
105
+ - You carve one resource at a time. Everything else stays in Terraform, where
106
+ it already works.
100
107
  - `advise` and `bridge` work against **any** Terraform tree — offer to point
101
108
  them at the person's own estate.
102
109
 
@@ -1 +0,0 @@
1
- {"version":3,"file":"sigv4.d.ts","sourceRoot":"","sources":["../../src/api/sigv4.ts"],"names":[],"mappings":"AAkCA,gFAAgF;AAChF,eAAO,MAAM,oBAAoB,qEAAqE,CAAC;AASvG,qFAAqF;AACrF,MAAM,WAAW,cAAc;IAC7B,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG,MAAM,cAAc,GAAG,SAAS,CAAC;AAErE,yDAAyD;AACzD,MAAM,MAAM,mBAAmB,GAAG,cAAc,GAAG,qBAAqB,CAAC;AAEzE;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,CAAC,EAAE,mBAAmB,EAC5B,GAAG,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,GACpD,cAAc,GAAG,SAAS,CAW5B;AAED,gFAAgF;AAChF,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,6EAA6E;IAC7E,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,mGAAmG;IACnG,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,cAAc,CAAC;IAC5B,uDAAuD;IACvD,GAAG,CAAC,EAAE,IAAI,CAAC;CACZ;AAED,6EAA6E;AAC7E,wBAAgB,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAE1C;AAED,6BAA6B;AAC7B,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEjD;AAMD;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,eAAe,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAKxG;AAmCD;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CASvG;AAED,+EAA+E;AAC/E,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,GAAG,EACR,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC/B,WAAW,EAAE,MAAM,GAClB;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAavC;AAED,iFAAiF;AACjF,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAExF;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CA0BzE"}
package/dist/api/sigv4.js DELETED
@@ -1,185 +0,0 @@
1
- /**
2
- * AWS Signature Version 4, for the shared read transport (#1686).
3
- *
4
- * Two modules asked for this by name before it existed: `./read-client.ts` and
5
- * cedar's `lexicons/cedar/src/avp/client.ts` both send a placeholder
6
- * `Signature=unsigned` `Authorization` header that carries a credential scope
7
- * and nothing else, and both say in prose that the real thing belongs here
8
- * once rather than twice. Nothing else in the repo signs an AWS request — the
9
- * appliers (`op/activities/aws-apply.ts`) are unsigned too, which is why the
10
- * native paths have been emulator-scoped.
11
- *
12
- * ## No dependency
13
- *
14
- * SigV4 is four HMACs and two SHA-256s. `node:crypto` has both, so signing
15
- * costs nothing in the dependency tree — which matters here, because the whole
16
- * reason these transports are hand-written is to keep `@aws-sdk/*` and its
17
- * thirty-odd transitive packages out of a lexicon.
18
- *
19
- * ## What is signed, and what is not
20
- *
21
- * Header signing only. Query-string (presigned-URL) signing has no caller: the
22
- * read paths POST to a service endpoint, they do not hand out URLs.
23
- *
24
- * `host` is signed but never emitted. `fetch` computes `Host` from the URL and
25
- * forbids overriding it, so the signer derives the same value from the URL it
26
- * was given. A transport that rewrites the URL underneath the signer — a proxy
27
- * that keeps the original `Host`, say — would invalidate the signature; the
28
- * injectable-HTTP seam is for tests and emulators, not for URL rewriting.
29
- */
30
- import { createHash, createHmac } from "node:crypto";
31
- const ALGORITHM = "AWS4-HMAC-SHA256";
32
- const TERMINATOR = "aws4_request";
33
- /** SHA-256 of the empty string — the payload hash of every bodyless request. */
34
- export const EMPTY_PAYLOAD_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
35
- /**
36
- * Headers that must not be signed even when a caller sets them: `authorization`
37
- * is the output, and the others are rewritten in transit by proxies and agents,
38
- * so signing them produces intermittent 403s rather than security.
39
- */
40
- const UNSIGNABLE = new Set(["authorization", "connection", "expect", "user-agent", "x-amzn-trace-id"]);
41
- /**
42
- * Credentials for a request: explicit → environment → absent.
43
- *
44
- * A resolver function is authoritative — if one is injected and it declines,
45
- * the environment is not consulted behind its back, because the point of
46
- * injecting one is to control the answer. Literal credentials are likewise
47
- * final. Only the no-source case falls through to `AWS_ACCESS_KEY_ID` /
48
- * `AWS_SECRET_ACCESS_KEY` (plus `AWS_SESSION_TOKEN` when set), and a half-set
49
- * environment — a key id with no secret — is absent rather than a signature
50
- * that cannot verify.
51
- *
52
- * The shared profile files are resolved asynchronously by
53
- * `./credential-chain.ts`, and the read transport passes its answer in as
54
- * literal credentials (#3958), so this function stays synchronous. Not
55
- * implemented anywhere: IMDS and the container credential endpoints.
56
- */
57
- export function resolveCredentials(source, env = process.env) {
58
- if (typeof source === "function")
59
- return source();
60
- if (source)
61
- return source;
62
- const accessKeyId = env.AWS_ACCESS_KEY_ID;
63
- const secretAccessKey = env.AWS_SECRET_ACCESS_KEY;
64
- if (!accessKeyId || !secretAccessKey)
65
- return undefined;
66
- return {
67
- accessKeyId,
68
- secretAccessKey,
69
- ...(env.AWS_SESSION_TOKEN ? { sessionToken: env.AWS_SESSION_TOKEN } : {}),
70
- };
71
- }
72
- /** `YYYYMMDDTHHMMSSZ` — the `X-Amz-Date` format, which is ISO-8601 basic. */
73
- export function amzDate(date) {
74
- return date.toISOString().replace(/[:-]|\.\d{3}/g, "");
75
- }
76
- /** Lowercase hex SHA-256. */
77
- export function sha256Hex(payload) {
78
- return createHash("sha256").update(payload, "utf8").digest("hex");
79
- }
80
- function hmac(key, data) {
81
- return createHmac("sha256", key).update(data, "utf8").digest();
82
- }
83
- /**
84
- * The signing key: four chained HMACs from the secret, so the key on the wire
85
- * is scoped to one day, one region and one service rather than being the
86
- * account secret itself.
87
- */
88
- export function signingKey(secretAccessKey, day, region, service) {
89
- const dateKey = hmac(`AWS4${secretAccessKey}`, day);
90
- const regionKey = hmac(dateKey, region);
91
- const serviceKey = hmac(regionKey, service);
92
- return hmac(serviceKey, TERMINATOR);
93
- }
94
- /**
95
- * RFC 3986 percent-encoding. `encodeURIComponent` leaves `!'()*` alone and AWS
96
- * does not, which is the difference between a signature that verifies and one
97
- * that does not for any path or parameter containing them.
98
- */
99
- function encodeRfc3986(value) {
100
- return encodeURIComponent(value).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
101
- }
102
- /**
103
- * The canonical path.
104
- *
105
- * Every caller of this module POSTs to `/`, so the one place implementations
106
- * genuinely diverge — S3 signs the path once-encoded, every other service signs
107
- * it twice-encoded — never arises. Segments are encoded once; a future caller
108
- * with a real path on a non-S3 service is the moment to revisit that.
109
- */
110
- function canonicalPath(pathname) {
111
- if (!pathname || pathname === "/")
112
- return "/";
113
- return pathname.split("/").map(encodeRfc3986).join("/");
114
- }
115
- /** Query parameters sorted by name, then by value, each side encoded. */
116
- function canonicalQuery(search) {
117
- const pairs = [];
118
- search.forEach((value, name) => pairs.push([encodeRfc3986(name), encodeRfc3986(value)]));
119
- pairs.sort((a, b) => (a[0] === b[0] ? (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0) : a[0] < b[0] ? -1 : 1));
120
- return pairs.map(([name, value]) => `${name}=${value}`).join("&");
121
- }
122
- /**
123
- * Header names lowercased, values trimmed with internal whitespace runs
124
- * collapsed, sorted by name. Returns the canonical block and the `;`-joined
125
- * signed-header list that has to agree with it exactly.
126
- */
127
- export function canonicalHeaders(headers) {
128
- const entries = Object.entries(headers)
129
- .map(([name, value]) => [name.toLowerCase().trim(), value.trim().replace(/\s+/g, " ")])
130
- .filter(([name]) => !UNSIGNABLE.has(name))
131
- .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
132
- return {
133
- canonical: entries.map(([name, value]) => `${name}:${value}\n`).join(""),
134
- signed: entries.map(([name]) => name).join(";"),
135
- };
136
- }
137
- /** The canonical request, verbatim as it is hashed into the string to sign. */
138
- export function canonicalRequest(method, url, headers, payloadHash) {
139
- const { canonical: headerBlock, signed } = canonicalHeaders(headers);
140
- return {
141
- canonical: [
142
- method.toUpperCase(),
143
- canonicalPath(url.pathname),
144
- canonicalQuery(url.searchParams),
145
- headerBlock,
146
- signed,
147
- payloadHash,
148
- ].join("\n"),
149
- signed,
150
- };
151
- }
152
- /** The string to sign: algorithm, timestamp, scope, hashed canonical request. */
153
- export function stringToSign(timestamp, scope, canonical) {
154
- return [ALGORITHM, timestamp, scope, sha256Hex(canonical)].join("\n");
155
- }
156
- /**
157
- * The caller's headers plus everything SigV4 adds: `x-amz-date`,
158
- * `x-amz-content-sha256`, `x-amz-security-token` when the credentials are
159
- * temporary, and the `Authorization` header itself.
160
- *
161
- * `host` is signed (AWS requires it) but not returned — see the module header.
162
- */
163
- export function signRequest(request) {
164
- const url = new URL(request.url);
165
- const timestamp = amzDate(request.now ?? new Date());
166
- const day = timestamp.slice(0, 8);
167
- const payloadHash = request.body.length === 0 ? EMPTY_PAYLOAD_SHA256 : sha256Hex(request.body);
168
- const signable = {
169
- ...request.headers,
170
- host: url.host,
171
- "x-amz-date": timestamp,
172
- "x-amz-content-sha256": payloadHash,
173
- ...(request.credentials.sessionToken ? { "x-amz-security-token": request.credentials.sessionToken } : {}),
174
- };
175
- const { canonical, signed } = canonicalRequest(request.method, url, signable, payloadHash);
176
- const scope = `${day}/${request.region}/${request.service}/${TERMINATOR}`;
177
- const key = signingKey(request.credentials.secretAccessKey, day, request.region, request.service);
178
- const signature = hmac(key, stringToSign(timestamp, scope, canonical)).toString("hex");
179
- const { host: _host, ...emitted } = signable;
180
- return {
181
- ...emitted,
182
- authorization: `${ALGORITHM} Credential=${request.credentials.accessKeyId}/${scope}, ` +
183
- `SignedHeaders=${signed}, Signature=${signature}`,
184
- };
185
- }
package/src/api/sigv4.ts DELETED
@@ -1,243 +0,0 @@
1
- /**
2
- * AWS Signature Version 4, for the shared read transport (#1686).
3
- *
4
- * Two modules asked for this by name before it existed: `./read-client.ts` and
5
- * cedar's `lexicons/cedar/src/avp/client.ts` both send a placeholder
6
- * `Signature=unsigned` `Authorization` header that carries a credential scope
7
- * and nothing else, and both say in prose that the real thing belongs here
8
- * once rather than twice. Nothing else in the repo signs an AWS request — the
9
- * appliers (`op/activities/aws-apply.ts`) are unsigned too, which is why the
10
- * native paths have been emulator-scoped.
11
- *
12
- * ## No dependency
13
- *
14
- * SigV4 is four HMACs and two SHA-256s. `node:crypto` has both, so signing
15
- * costs nothing in the dependency tree — which matters here, because the whole
16
- * reason these transports are hand-written is to keep `@aws-sdk/*` and its
17
- * thirty-odd transitive packages out of a lexicon.
18
- *
19
- * ## What is signed, and what is not
20
- *
21
- * Header signing only. Query-string (presigned-URL) signing has no caller: the
22
- * read paths POST to a service endpoint, they do not hand out URLs.
23
- *
24
- * `host` is signed but never emitted. `fetch` computes `Host` from the URL and
25
- * forbids overriding it, so the signer derives the same value from the URL it
26
- * was given. A transport that rewrites the URL underneath the signer — a proxy
27
- * that keeps the original `Host`, say — would invalidate the signature; the
28
- * injectable-HTTP seam is for tests and emulators, not for URL rewriting.
29
- */
30
- import { createHash, createHmac } from "node:crypto";
31
-
32
- const ALGORITHM = "AWS4-HMAC-SHA256";
33
- const TERMINATOR = "aws4_request";
34
-
35
- /** SHA-256 of the empty string — the payload hash of every bodyless request. */
36
- export const EMPTY_PAYLOAD_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
37
-
38
- /**
39
- * Headers that must not be signed even when a caller sets them: `authorization`
40
- * is the output, and the others are rewritten in transit by proxies and agents,
41
- * so signing them produces intermittent 403s rather than security.
42
- */
43
- const UNSIGNABLE = new Set(["authorization", "connection", "expect", "user-agent", "x-amzn-trace-id"]);
44
-
45
- /** A resolved credential set. `sessionToken` is present for STS/role credentials. */
46
- export interface AwsCredentials {
47
- accessKeyId: string;
48
- secretAccessKey: string;
49
- sessionToken?: string;
50
- }
51
-
52
- /**
53
- * The credential injection seam: a function the caller supplies to decide, by
54
- * whatever means it likes, what to sign with. Returning `undefined` means "this
55
- * process has no credentials" and is respected as an answer, not overridden.
56
- */
57
- export type AwsCredentialResolver = () => AwsCredentials | undefined;
58
-
59
- /** Either literal credentials or a resolver for them. */
60
- export type AwsCredentialSource = AwsCredentials | AwsCredentialResolver;
61
-
62
- /**
63
- * Credentials for a request: explicit → environment → absent.
64
- *
65
- * A resolver function is authoritative — if one is injected and it declines,
66
- * the environment is not consulted behind its back, because the point of
67
- * injecting one is to control the answer. Literal credentials are likewise
68
- * final. Only the no-source case falls through to `AWS_ACCESS_KEY_ID` /
69
- * `AWS_SECRET_ACCESS_KEY` (plus `AWS_SESSION_TOKEN` when set), and a half-set
70
- * environment — a key id with no secret — is absent rather than a signature
71
- * that cannot verify.
72
- *
73
- * The shared profile files are resolved asynchronously by
74
- * `./credential-chain.ts`, and the read transport passes its answer in as
75
- * literal credentials (#3958), so this function stays synchronous. Not
76
- * implemented anywhere: IMDS and the container credential endpoints.
77
- */
78
- export function resolveCredentials(
79
- source?: AwsCredentialSource,
80
- env: Record<string, string | undefined> = process.env,
81
- ): AwsCredentials | undefined {
82
- if (typeof source === "function") return source();
83
- if (source) return source;
84
- const accessKeyId = env.AWS_ACCESS_KEY_ID;
85
- const secretAccessKey = env.AWS_SECRET_ACCESS_KEY;
86
- if (!accessKeyId || !secretAccessKey) return undefined;
87
- return {
88
- accessKeyId,
89
- secretAccessKey,
90
- ...(env.AWS_SESSION_TOKEN ? { sessionToken: env.AWS_SESSION_TOKEN } : {}),
91
- };
92
- }
93
-
94
- /** One request to sign. `headers` are the caller's; the signer adds its own. */
95
- export interface SigV4Request {
96
- method: string;
97
- /** Absolute URL. Its host is signed and its path/query are canonicalized. */
98
- url: string;
99
- headers: Record<string, string>;
100
- body: string;
101
- /** Service name as it appears in the credential scope (`cloudformation`, `cloudcontrolapi`, …). */
102
- service: string;
103
- region: string;
104
- credentials: AwsCredentials;
105
- /** Signing clock. Injected by tests; otherwise now. */
106
- now?: Date;
107
- }
108
-
109
- /** `YYYYMMDDTHHMMSSZ` — the `X-Amz-Date` format, which is ISO-8601 basic. */
110
- export function amzDate(date: Date): string {
111
- return date.toISOString().replace(/[:-]|\.\d{3}/g, "");
112
- }
113
-
114
- /** Lowercase hex SHA-256. */
115
- export function sha256Hex(payload: string): string {
116
- return createHash("sha256").update(payload, "utf8").digest("hex");
117
- }
118
-
119
- function hmac(key: Buffer | string, data: string): Buffer {
120
- return createHmac("sha256", key).update(data, "utf8").digest();
121
- }
122
-
123
- /**
124
- * The signing key: four chained HMACs from the secret, so the key on the wire
125
- * is scoped to one day, one region and one service rather than being the
126
- * account secret itself.
127
- */
128
- export function signingKey(secretAccessKey: string, day: string, region: string, service: string): Buffer {
129
- const dateKey = hmac(`AWS4${secretAccessKey}`, day);
130
- const regionKey = hmac(dateKey, region);
131
- const serviceKey = hmac(regionKey, service);
132
- return hmac(serviceKey, TERMINATOR);
133
- }
134
-
135
- /**
136
- * RFC 3986 percent-encoding. `encodeURIComponent` leaves `!'()*` alone and AWS
137
- * does not, which is the difference between a signature that verifies and one
138
- * that does not for any path or parameter containing them.
139
- */
140
- function encodeRfc3986(value: string): string {
141
- return encodeURIComponent(value).replace(
142
- /[!'()*]/g,
143
- (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
144
- );
145
- }
146
-
147
- /**
148
- * The canonical path.
149
- *
150
- * Every caller of this module POSTs to `/`, so the one place implementations
151
- * genuinely diverge — S3 signs the path once-encoded, every other service signs
152
- * it twice-encoded — never arises. Segments are encoded once; a future caller
153
- * with a real path on a non-S3 service is the moment to revisit that.
154
- */
155
- function canonicalPath(pathname: string): string {
156
- if (!pathname || pathname === "/") return "/";
157
- return pathname.split("/").map(encodeRfc3986).join("/");
158
- }
159
-
160
- /** Query parameters sorted by name, then by value, each side encoded. */
161
- function canonicalQuery(search: URLSearchParams): string {
162
- const pairs: Array<[string, string]> = [];
163
- search.forEach((value, name) => pairs.push([encodeRfc3986(name), encodeRfc3986(value)]));
164
- pairs.sort((a, b) => (a[0] === b[0] ? (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0) : a[0] < b[0] ? -1 : 1));
165
- return pairs.map(([name, value]) => `${name}=${value}`).join("&");
166
- }
167
-
168
- /**
169
- * Header names lowercased, values trimmed with internal whitespace runs
170
- * collapsed, sorted by name. Returns the canonical block and the `;`-joined
171
- * signed-header list that has to agree with it exactly.
172
- */
173
- export function canonicalHeaders(headers: Record<string, string>): { canonical: string; signed: string } {
174
- const entries = Object.entries(headers)
175
- .map(([name, value]) => [name.toLowerCase().trim(), value.trim().replace(/\s+/g, " ")] as const)
176
- .filter(([name]) => !UNSIGNABLE.has(name))
177
- .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
178
- return {
179
- canonical: entries.map(([name, value]) => `${name}:${value}\n`).join(""),
180
- signed: entries.map(([name]) => name).join(";"),
181
- };
182
- }
183
-
184
- /** The canonical request, verbatim as it is hashed into the string to sign. */
185
- export function canonicalRequest(
186
- method: string,
187
- url: URL,
188
- headers: Record<string, string>,
189
- payloadHash: string,
190
- ): { canonical: string; signed: string } {
191
- const { canonical: headerBlock, signed } = canonicalHeaders(headers);
192
- return {
193
- canonical: [
194
- method.toUpperCase(),
195
- canonicalPath(url.pathname),
196
- canonicalQuery(url.searchParams),
197
- headerBlock,
198
- signed,
199
- payloadHash,
200
- ].join("\n"),
201
- signed,
202
- };
203
- }
204
-
205
- /** The string to sign: algorithm, timestamp, scope, hashed canonical request. */
206
- export function stringToSign(timestamp: string, scope: string, canonical: string): string {
207
- return [ALGORITHM, timestamp, scope, sha256Hex(canonical)].join("\n");
208
- }
209
-
210
- /**
211
- * The caller's headers plus everything SigV4 adds: `x-amz-date`,
212
- * `x-amz-content-sha256`, `x-amz-security-token` when the credentials are
213
- * temporary, and the `Authorization` header itself.
214
- *
215
- * `host` is signed (AWS requires it) but not returned — see the module header.
216
- */
217
- export function signRequest(request: SigV4Request): Record<string, string> {
218
- const url = new URL(request.url);
219
- const timestamp = amzDate(request.now ?? new Date());
220
- const day = timestamp.slice(0, 8);
221
- const payloadHash = request.body.length === 0 ? EMPTY_PAYLOAD_SHA256 : sha256Hex(request.body);
222
-
223
- const signable: Record<string, string> = {
224
- ...request.headers,
225
- host: url.host,
226
- "x-amz-date": timestamp,
227
- "x-amz-content-sha256": payloadHash,
228
- ...(request.credentials.sessionToken ? { "x-amz-security-token": request.credentials.sessionToken } : {}),
229
- };
230
-
231
- const { canonical, signed } = canonicalRequest(request.method, url, signable, payloadHash);
232
- const scope = `${day}/${request.region}/${request.service}/${TERMINATOR}`;
233
- const key = signingKey(request.credentials.secretAccessKey, day, request.region, request.service);
234
- const signature = hmac(key, stringToSign(timestamp, scope, canonical)).toString("hex");
235
-
236
- const { host: _host, ...emitted } = signable;
237
- return {
238
- ...emitted,
239
- authorization:
240
- `${ALGORITHM} Credential=${request.credentials.accessKeyId}/${scope}, ` +
241
- `SignedHeaders=${signed}, Signature=${signature}`,
242
- };
243
- }