@intentius/chant 0.124.85 → 0.124.86

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 (254) hide show
  1. package/dist/bundle-check.d.ts +102 -0
  2. package/dist/bundle-check.d.ts.map +1 -0
  3. package/dist/bundle-check.js +310 -0
  4. package/dist/chant-install.d.ts +100 -0
  5. package/dist/chant-install.d.ts.map +1 -0
  6. package/dist/chant-install.js +158 -0
  7. package/dist/ci-commit.d.ts +19 -6
  8. package/dist/ci-commit.d.ts.map +1 -1
  9. package/dist/ci-commit.js +23 -4
  10. package/dist/ci-evidence-jobs.d.ts +54 -0
  11. package/dist/ci-evidence-jobs.d.ts.map +1 -0
  12. package/dist/ci-evidence-jobs.js +55 -0
  13. package/dist/ci-image.d.ts +274 -0
  14. package/dist/ci-image.d.ts.map +1 -0
  15. package/dist/ci-image.js +635 -0
  16. package/dist/ci-login.d.ts +150 -0
  17. package/dist/ci-login.d.ts.map +1 -0
  18. package/dist/ci-login.js +240 -0
  19. package/dist/ci-product.d.ts +16 -0
  20. package/dist/ci-product.d.ts.map +1 -1
  21. package/dist/ci-product.js +17 -0
  22. package/dist/cli/commands/import-index.js +2 -2
  23. package/dist/cli/handlers/build.d.ts +8 -0
  24. package/dist/cli/handlers/build.d.ts.map +1 -1
  25. package/dist/cli/handlers/build.js +22 -4
  26. package/dist/cli/handlers/ci-check.d.ts.map +1 -1
  27. package/dist/cli/handlers/ci-check.js +57 -2
  28. package/dist/cli/handlers/ci-evidence.d.ts +3 -0
  29. package/dist/cli/handlers/ci-evidence.d.ts.map +1 -0
  30. package/dist/cli/handlers/ci-evidence.js +171 -0
  31. package/dist/cli/handlers/components.js +3 -3
  32. package/dist/cli/handlers/dead-guards.d.ts +3 -0
  33. package/dist/cli/handlers/dead-guards.d.ts.map +1 -0
  34. package/dist/cli/handlers/dead-guards.js +35 -0
  35. package/dist/cli/handlers/graph.js +4 -4
  36. package/dist/cli/handlers/lifecycle.d.ts +2 -1
  37. package/dist/cli/handlers/lifecycle.d.ts.map +1 -1
  38. package/dist/cli/handlers/lifecycle.js +5 -4
  39. package/dist/cli/handlers/local-chant.d.ts +16 -0
  40. package/dist/cli/handlers/local-chant.d.ts.map +1 -0
  41. package/dist/cli/handlers/local-chant.js +109 -0
  42. package/dist/cli/handlers/operator.js +2 -2
  43. package/dist/cli/handlers/search.js +5 -5
  44. package/dist/cli/main.d.ts.map +1 -1
  45. package/dist/cli/main.js +38 -0
  46. package/dist/cli/parse-args.d.ts.map +1 -1
  47. package/dist/cli/parse-args.js +28 -0
  48. package/dist/cli/registry.d.ts +16 -0
  49. package/dist/cli/registry.d.ts.map +1 -1
  50. package/dist/components/check-hooks.d.ts +49 -0
  51. package/dist/components/check-hooks.d.ts.map +1 -1
  52. package/dist/components/check-hooks.js +64 -4
  53. package/dist/components/check-steps.d.ts +17 -0
  54. package/dist/components/check-steps.d.ts.map +1 -1
  55. package/dist/components/check-steps.js +37 -5
  56. package/dist/components/product-pipeline.d.ts +23 -0
  57. package/dist/components/product-pipeline.d.ts.map +1 -1
  58. package/dist/components/product-pipeline.js +6 -2
  59. package/dist/components/product-plan.d.ts +137 -0
  60. package/dist/components/product-plan.d.ts.map +1 -0
  61. package/dist/components/product-plan.js +143 -0
  62. package/dist/components/release-compile.d.ts.map +1 -1
  63. package/dist/components/release-compile.js +2 -2
  64. package/dist/config.d.ts +39 -1
  65. package/dist/config.d.ts.map +1 -1
  66. package/dist/config.js +35 -3
  67. package/dist/dead-guards.d.ts +82 -0
  68. package/dist/dead-guards.d.ts.map +1 -0
  69. package/dist/dead-guards.js +436 -0
  70. package/dist/discovery/files.d.ts +3 -1
  71. package/dist/discovery/files.d.ts.map +1 -1
  72. package/dist/discovery/files.js +5 -3
  73. package/dist/drift-issue.d.ts +152 -0
  74. package/dist/drift-issue.d.ts.map +1 -0
  75. package/dist/drift-issue.js +167 -0
  76. package/dist/floor-table.d.ts +30 -0
  77. package/dist/floor-table.d.ts.map +1 -0
  78. package/dist/floor-table.data.d.ts +3 -0
  79. package/dist/floor-table.data.d.ts.map +1 -0
  80. package/dist/floor-table.data.js +178 -0
  81. package/dist/floor-table.js +56 -0
  82. package/dist/forge-flags.d.ts +90 -0
  83. package/dist/forge-flags.d.ts.map +1 -0
  84. package/dist/forge-flags.js +184 -0
  85. package/dist/lexicon.d.ts +69 -0
  86. package/dist/lexicon.d.ts.map +1 -1
  87. package/dist/lifecycle/gated-op.d.ts +7 -1
  88. package/dist/lifecycle/gated-op.d.ts.map +1 -1
  89. package/dist/lifecycle/gated-op.js +7 -4
  90. package/dist/local-chant.d.ts +98 -0
  91. package/dist/local-chant.d.ts.map +1 -0
  92. package/dist/local-chant.js +307 -0
  93. package/dist/op/activities/predict-behaviour.js +2 -2
  94. package/dist/op/op-waves-evidence-spec.d.ts +13 -0
  95. package/dist/op/op-waves-evidence-spec.d.ts.map +1 -0
  96. package/dist/op/op-waves-evidence-spec.js +21 -0
  97. package/dist/op/op-waves-evidence.d.ts +38 -0
  98. package/dist/op/op-waves-evidence.d.ts.map +1 -0
  99. package/dist/op/op-waves-evidence.js +57 -0
  100. package/dist/op/op-waves-run.d.ts +4 -0
  101. package/dist/op/op-waves-run.d.ts.map +1 -1
  102. package/dist/op/op-waves-run.js +24 -1
  103. package/dist/op/op-waves.d.ts +17 -1
  104. package/dist/op/op-waves.d.ts.map +1 -1
  105. package/dist/op/op-waves.js +23 -0
  106. package/dist/op/schedule-overdue.d.ts +41 -9
  107. package/dist/op/schedule-overdue.d.ts.map +1 -1
  108. package/dist/op/schedule-overdue.js +154 -25
  109. package/dist/plan-summary.d.ts +25 -0
  110. package/dist/plan-summary.d.ts.map +1 -1
  111. package/dist/plan-summary.js +31 -0
  112. package/dist/pr-plan-note.d.ts +35 -0
  113. package/dist/pr-plan-note.d.ts.map +1 -1
  114. package/dist/pr-plan-note.js +10 -0
  115. package/dist/pr-post.d.ts +23 -0
  116. package/dist/pr-post.d.ts.map +1 -1
  117. package/dist/pr-post.js +125 -3
  118. package/dist/release-floors.d.ts +31 -1
  119. package/dist/release-floors.d.ts.map +1 -1
  120. package/dist/release-floors.js +31 -1
  121. package/dist/state-migration.d.ts +24 -0
  122. package/dist/state-migration.d.ts.map +1 -1
  123. package/dist/state-migration.js +100 -5
  124. package/dist/wave-runtime.mjs +305 -298
  125. package/dist/workspace/lexicon-outputs.d.ts.map +1 -1
  126. package/dist/workspace/lexicon-outputs.js +21 -7
  127. package/dist/workspace/reason-codes.d.ts +3 -0
  128. package/dist/workspace/reason-codes.d.ts.map +1 -1
  129. package/dist/workspace/reason-codes.js +4 -0
  130. package/dist/workspace/ref-gate.schema.json +85 -0
  131. package/dist/workspace/search-contract.d.ts +1 -1
  132. package/dist/workspace/search-contract.d.ts.map +1 -1
  133. package/dist/workspace/trust/check-evidence-report.d.ts +51 -0
  134. package/dist/workspace/trust/check-evidence-report.d.ts.map +1 -0
  135. package/dist/workspace/trust/check-evidence-report.js +102 -0
  136. package/dist/workspace/trust/check-evidence.d.ts +126 -0
  137. package/dist/workspace/trust/check-evidence.d.ts.map +1 -0
  138. package/dist/workspace/trust/check-evidence.js +237 -0
  139. package/dist/workspace/trust/local-evidence.d.ts +120 -0
  140. package/dist/workspace/trust/local-evidence.d.ts.map +1 -0
  141. package/dist/workspace/trust/local-evidence.js +259 -0
  142. package/dist/workspace/trust/policy.d.ts +84 -0
  143. package/dist/workspace/trust/policy.d.ts.map +1 -1
  144. package/dist/workspace/trust/policy.js +94 -1
  145. package/dist/workspace/trust/ref-gate-cli.d.ts +33 -0
  146. package/dist/workspace/trust/ref-gate-cli.d.ts.map +1 -0
  147. package/dist/workspace/trust/ref-gate-cli.js +234 -0
  148. package/dist/workspace/trust/ref-gate-fixture.d.ts +38 -0
  149. package/dist/workspace/trust/ref-gate-fixture.d.ts.map +1 -0
  150. package/dist/workspace/trust/ref-gate-fixture.js +97 -0
  151. package/dist/workspace/trust/ref-gate.d.ts +187 -0
  152. package/dist/workspace/trust/ref-gate.d.ts.map +1 -0
  153. package/dist/workspace/trust/ref-gate.js +430 -0
  154. package/dist/workspace/trust/trust-files.d.ts.map +1 -1
  155. package/dist/workspace/trust/trust-files.js +18 -1
  156. package/package.json +1 -1
  157. package/src/bundle-check.test.ts +140 -0
  158. package/src/bundle-check.ts +352 -0
  159. package/src/chant-install.test.ts +112 -0
  160. package/src/chant-install.ts +179 -0
  161. package/src/ci-commit.test.ts +45 -0
  162. package/src/ci-commit.ts +38 -4
  163. package/src/ci-evidence-jobs.ts +67 -0
  164. package/src/ci-image.test.ts +506 -0
  165. package/src/ci-image.ts +822 -0
  166. package/src/ci-login.test.ts +235 -0
  167. package/src/ci-login.ts +307 -0
  168. package/src/ci-product.ts +18 -0
  169. package/src/cli/commands/__fixtures__/source-dir-include/chant.config.json +1 -0
  170. package/src/cli/commands/__fixtures__/source-dir-include/infra.ts +1 -0
  171. package/src/cli/commands/__fixtures__/source-dir-include/scripts/run-on-load.ts +3 -0
  172. package/src/cli/commands/__fixtures__/source-dir-root/chant.config.json +1 -0
  173. package/src/cli/commands/__fixtures__/source-dir-root/infra.test.ts +1 -0
  174. package/src/cli/commands/__fixtures__/source-dir-root/infra.ts +1 -0
  175. package/src/cli/commands/__fixtures__/source-dir-root/scripts/run-on-load.ts +3 -0
  176. package/src/cli/commands/__fixtures__/source-dir-scoped/app.ts +3 -0
  177. package/src/cli/commands/__fixtures__/source-dir-scoped/chant.config.json +1 -0
  178. package/src/cli/commands/__fixtures__/source-dir-scoped/infra/net.ts +1 -0
  179. package/src/cli/commands/__fixtures__/source-dir-scoped/scripts/run-on-load.ts +3 -0
  180. package/src/cli/commands/import-index.ts +2 -2
  181. package/src/cli/handlers/build-source-dir.test.ts +64 -0
  182. package/src/cli/handlers/build.ts +21 -4
  183. package/src/cli/handlers/ci-check.ts +56 -3
  184. package/src/cli/handlers/ci-evidence.ts +162 -0
  185. package/src/cli/handlers/components.ts +3 -3
  186. package/src/cli/handlers/dead-guards.ts +37 -0
  187. package/src/cli/handlers/graph.ts +4 -4
  188. package/src/cli/handlers/lifecycle.ts +5 -4
  189. package/src/cli/handlers/local-chant.ts +106 -0
  190. package/src/cli/handlers/operator.ts +2 -2
  191. package/src/cli/handlers/search.ts +5 -5
  192. package/src/cli/main.test.ts +7 -0
  193. package/src/cli/main.ts +38 -0
  194. package/src/cli/parse-args.ts +21 -0
  195. package/src/cli/registry.ts +16 -0
  196. package/src/components/check-evidence-stage.test.ts +80 -0
  197. package/src/components/check-hooks.ts +84 -4
  198. package/src/components/check-local-evidence-stage.test.ts +141 -0
  199. package/src/components/check-steps.ts +56 -6
  200. package/src/components/product-pipeline.ts +28 -3
  201. package/src/components/product-plan.test.ts +87 -0
  202. package/src/components/product-plan.ts +226 -0
  203. package/src/components/release-compile.ts +2 -2
  204. package/src/config.ts +44 -3
  205. package/src/dead-guards.test.ts +206 -0
  206. package/src/dead-guards.ts +446 -0
  207. package/src/discovery/files.ts +5 -3
  208. package/src/drift-issue-bundle.test.ts +31 -0
  209. package/src/drift-issue.test.ts +206 -0
  210. package/src/drift-issue.ts +274 -0
  211. package/src/fit-note.test.ts +44 -0
  212. package/src/floor-table.data.ts +180 -0
  213. package/src/floor-table.ts +77 -0
  214. package/src/forge-flags.test.ts +110 -0
  215. package/src/forge-flags.ts +208 -0
  216. package/src/gate-decision-bundle.test.ts +1 -0
  217. package/src/lexicon.ts +68 -0
  218. package/src/lifecycle/gated-op.ts +10 -5
  219. package/src/local-chant.e2e.test.ts +94 -0
  220. package/src/local-chant.test.ts +162 -0
  221. package/src/local-chant.ts +341 -0
  222. package/src/op/activities/predict-behaviour.ts +2 -2
  223. package/src/op/op-waves-evidence-spec.ts +24 -0
  224. package/src/op/op-waves-evidence.test.ts +130 -0
  225. package/src/op/op-waves-evidence.ts +57 -0
  226. package/src/op/op-waves-run.ts +25 -1
  227. package/src/op/op-waves.ts +31 -1
  228. package/src/op/schedule-overdue.test.ts +85 -0
  229. package/src/op/schedule-overdue.ts +162 -26
  230. package/src/plan-summary.ts +40 -0
  231. package/src/pr-plan-note.ts +34 -0
  232. package/src/pr-post-plan-note.test.ts +146 -0
  233. package/src/pr-post.ts +127 -3
  234. package/src/release-floors.ts +44 -1
  235. package/src/stage-hooks-bundle.test.ts +1 -0
  236. package/src/state-migration.test.ts +52 -1
  237. package/src/state-migration.ts +107 -5
  238. package/src/workspace/lexicon-outputs.ts +23 -6
  239. package/src/workspace/reason-codes.test.ts +3 -0
  240. package/src/workspace/reason-codes.ts +4 -0
  241. package/src/workspace/ref-gate.schema.json +85 -0
  242. package/src/workspace/trust/check-evidence-report.ts +106 -0
  243. package/src/workspace/trust/check-evidence.test.ts +133 -0
  244. package/src/workspace/trust/check-evidence.ts +257 -0
  245. package/src/workspace/trust/local-evidence.test.ts +127 -0
  246. package/src/workspace/trust/local-evidence.ts +266 -0
  247. package/src/workspace/trust/policy.ts +134 -1
  248. package/src/workspace/trust/ref-gate-cli.ts +244 -0
  249. package/src/workspace/trust/ref-gate-fixture.ts +125 -0
  250. package/src/workspace/trust/ref-gate.e2e.test.ts +76 -0
  251. package/src/workspace/trust/ref-gate.test.ts +247 -0
  252. package/src/workspace/trust/ref-gate.ts +538 -0
  253. package/src/workspace/trust/trust-files.test.ts +16 -0
  254. package/src/workspace/trust/trust-files.ts +41 -1
@@ -0,0 +1,235 @@
1
+ /**
2
+ * #4788: cloud login steps from the OIDC token file, per forge and cloud.
3
+ * The shell tests run the rendered step's lines with bash, as a forge runs
4
+ * a step, against the local emulator of the forge's token URL
5
+ * (./__fixtures__/oidc-emulator.ts). The login calls no cloud: the cloud's
6
+ * own tools trade the token file later, so the tests check the files and
7
+ * variables those tools read. Test values only; no cloud is reached.
8
+ */
9
+
10
+ import { execFile } from "node:child_process";
11
+ import { chmodSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { promisify } from "node:util";
15
+ import { afterAll, beforeAll, describe, expect, test } from "vitest";
16
+ import { cloudLogin, forgejoCloudLogin, githubCloudLogin, gitlabCloudLogin, LOGIN_JS, LOGIN_SPEC_ENV, type CloudLoginSpec, type LoginForge } from "./ci-login";
17
+ import { CLOUD_TARGETS_ENV, resolveCloudIdentity, targetCloudEnv, type CloudIdentityDeclaration } from "./ci-identity";
18
+ import { EMULATED_JWT_PREFIX, startOidcEmulator, type OidcEmulator } from "./__fixtures__/oidc-emulator";
19
+
20
+ const run = promisify(execFile);
21
+
22
+ const PROVIDER = "projects/123/locations/global/workloadIdentityPools/ci/providers/forge";
23
+ const TENANT = "00000000-0000-0000-0000-000000000001";
24
+ const SPEC: CloudLoginSpec = {
25
+ aws: { role: "arn:aws:iam::111111111111:role/plan", region: "eu-west-1", sessionName: "terragucci-plan" },
26
+ gcp: { serviceAccount: "plan@proj.iam.gserviceaccount.com", provider: PROVIDER },
27
+ azure: { clientId: "11111111-1111-1111-1111-111111111111", tenantId: TENANT, subscriptionId: "22222222-2222-2222-2222-222222222222" },
28
+ };
29
+ const AUD = { aws: "sts.amazonaws.com", gcp: `https://iam.googleapis.com/${PROVIDER}`, azure: "api://AzureADTokenExchange" };
30
+ const FORGES: LoginForge[] = ["github", "gitlab", "forgejo"];
31
+
32
+ describe("the rendered login (#4788)", () => {
33
+ test("one function per forge, each one step that runs the login from / and names its clouds", () => {
34
+ expect(githubCloudLogin(SPEC)).toEqual(cloudLogin("github", SPEC));
35
+ expect(forgejoCloudLogin(SPEC)).toEqual(cloudLogin("forgejo", SPEC));
36
+ expect(gitlabCloudLogin(SPEC)).toEqual(cloudLogin("gitlab", SPEC));
37
+ for (const forge of FORGES) {
38
+ const { steps } = cloudLogin(forge, SPEC);
39
+ expect(steps).toHaveLength(1);
40
+ expect(steps[0]!.name).toBe("Cloud login (chant ci-login: aws, gcp, azure)");
41
+ expect(steps[0]!.run[0]).toMatch(new RegExp(`^export ${LOGIN_SPEC_ENV}='\\{`));
42
+ expect(steps[0]!.run[1]).toMatch(new RegExp(`\\(cd / && node -e '.*' ".*" (github-env|sh) ${forge}\\)"?$`));
43
+ }
44
+ expect(githubCloudLogin(SPEC).steps[0]!.run[1]).toContain('"$GITHUB_ENV" github-env github');
45
+ expect(forgejoCloudLogin(SPEC).steps[0]!.run[1]).toContain('"$GITHUB_ENV" github-env forgejo');
46
+ const gitlab = gitlabCloudLogin(SPEC).steps[0]!.run;
47
+ expect(gitlab[1]).toMatch(/^CHANT_CLOUD_LOGIN_VARS="\$\(cd \/ && node -e '.*' "-" sh gitlab\)"$/);
48
+ expect(gitlab.slice(2)).toEqual(['eval "$CHANT_CLOUD_LOGIN_VARS"', `unset CHANT_CLOUD_LOGIN_VARS ${LOGIN_SPEC_ENV} CHANT_ID_TOKEN_AWS CHANT_ID_TOKEN_GCP CHANT_ID_TOKEN_AZURE`]);
49
+ });
50
+
51
+ test.each(["aws", "gcp", "azure"] as const)("%s: each forge's job requests the cloud's token with the cloud's audience", (cloud) => {
52
+ for (const forge of FORGES) {
53
+ expect(cloudLogin(forge, { [cloud]: SPEC[cloud] }).idTokens).toEqual({ [`CHANT_ID_TOKEN_${cloud.toUpperCase()}`]: AUD[cloud] });
54
+ expect(cloudLogin(forge, { [cloud]: { ...SPEC[cloud], audience: "custom" } }).idTokens).toEqual({ [`CHANT_ID_TOKEN_${cloud.toUpperCase()}`]: "custom" });
55
+ }
56
+ });
57
+
58
+ test("a cloud with a tokenFile the runner provides requests no token", () => {
59
+ expect(forgejoCloudLogin({ aws: { ...SPEC.aws!, tokenFile: "$RUNNER_TEMP/aws-token" }, gcp: SPEC.gcp }).idTokens).toEqual({ CHANT_ID_TOKEN_GCP: AUD.gcp });
60
+ });
61
+
62
+ test("no cloud, no step", () => {
63
+ for (const forge of FORGES) expect(cloudLogin(forge, {})).toEqual({ steps: [], idTokens: {} });
64
+ });
65
+
66
+ test("the script has no single quote, so it sits in one shell word", () => {
67
+ expect(LOGIN_JS).not.toContain("'");
68
+ });
69
+
70
+ test("a stage's identities come from resolveCloudIdentity, as the trade's do", () => {
71
+ const decl: CloudIdentityDeclaration = { aws: { region: "eu-west-1", rules: [{ plan: "arn:aws:iam::1:role/p", apply: "arn:aws:iam::1:role/a" }] } };
72
+ const both = resolveCloudIdentity(decl, "prod")!;
73
+ expect(JSON.parse(githubCloudLogin(both.plan).steps[0]!.run[0]!.slice(`export ${LOGIN_SPEC_ENV}=`.length).slice(1, -1))).toEqual({ aws: { role: "arn:aws:iam::1:role/p", region: "eu-west-1", audience: "sts.amazonaws.com" } });
74
+ expect(githubCloudLogin(both.apply).steps[0]!.run[0]).toContain("role/a");
75
+ });
76
+
77
+ test("what a login cannot do is refused", () => {
78
+ expect(() => githubCloudLogin({ pulumi: { organization: "o", audience: "a", token: "team:x" } } as unknown as CloudLoginSpec)).toThrow(/Pulumi Cloud\) is traded/);
79
+ expect(() => githubCloudLogin({ azure: { ...SPEC.azure!, database: true } } as unknown as CloudLoginSpec)).toThrow(/no database token/);
80
+ expect(() => githubCloudLogin({ aws: { role: "arn:aws:iam::1:role/a b" } })).toThrow(/role is .*printable ASCII with no space/);
81
+ expect(() => githubCloudLogin({ aws: {} })).toThrow(/names no identity/);
82
+ expect(() => githubCloudLogin({ aws: { role: "r", sessionName: "x" } })).toThrow(/sessionName/);
83
+ expect(() => githubCloudLogin({ aws: { role: "r", tokenFile: "$(id)" } })).toThrow(/tokenFile/);
84
+ expect(() => githubCloudLogin({ azure: { tenantId: TENANT, targets: [{ targets: ["a"], clientId: "c" }], cli: true } })).toThrow(/needs clientId/);
85
+ });
86
+ });
87
+
88
+ describe("the login, run (#4788)", () => {
89
+ let emu: OidcEmulator;
90
+ beforeAll(async () => {
91
+ emu = await startOidcEmulator();
92
+ });
93
+ afterAll(async () => {
94
+ await emu.close();
95
+ });
96
+
97
+ const parseEnvFile = (text: string): Record<string, string> => Object.fromEntries(text.trim().split("\n").filter(Boolean).map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]));
98
+
99
+ /** Runs an Actions step's lines with bash -e, as a GitHub or Forgejo step; gives $GITHUB_ENV's variables. */
100
+ async function actionsStep(forge: "github" | "forgejo", spec: CloudLoginSpec, env: Record<string, string> = emu.requestEnv) {
101
+ const dir = mkdtempSync(join(tmpdir(), "chant-login-"));
102
+ const githubEnv = join(dir, "github-env");
103
+ writeFileSync(githubEnv, "");
104
+ const step = cloudLogin(forge, spec).steps[0]!;
105
+ const out = await run("bash", ["-e", "-c", step.run.join("\n")], { env: { PATH: process.env.PATH!, GITHUB_ENV: githubEnv, RUNNER_TEMP: dir, ...env } }).catch((e: { stderr: string; code: number }) => ({ stderr: e.stderr, failed: e.code }));
106
+ return { dir, vars: parseEnvFile(readFileSync(githubEnv, "utf-8")), out };
107
+ }
108
+
109
+ test.each(["github", "forgejo"] as const)("%s: every cloud's token in a file, and the variables its tools read", async (forge) => {
110
+ const before = emu.log.minted.length;
111
+ const { dir, vars, out } = await actionsStep(forge, SPEC);
112
+ expect(out).not.toHaveProperty("failed");
113
+ expect(emu.log.minted.slice(before)).toEqual([AUD.aws, AUD.gcp, AUD.azure]);
114
+ // AWS: the SDKs' web identity provider.
115
+ expect(vars).toMatchObject({ AWS_ROLE_ARN: SPEC.aws!.role, AWS_ROLE_SESSION_NAME: "terragucci-plan", AWS_REGION: "eu-west-1", AWS_DEFAULT_REGION: "eu-west-1" });
116
+ expect(vars.AWS_WEB_IDENTITY_TOKEN_FILE!.startsWith(`${dir}/chant-oidc-aws-`)).toBe(true);
117
+ expect(readFileSync(vars.AWS_WEB_IDENTITY_TOKEN_FILE!, "utf-8")).toBe(`${EMULATED_JWT_PREFIX}.${Buffer.from(AUD.aws).toString("base64url")}.${before + 1}`);
118
+ expect(statSync(vars.AWS_WEB_IDENTITY_TOKEN_FILE!).mode & 0o777).toBe(0o600);
119
+ // GCP: an external_account file over the GCP token, for the libraries and gcloud.
120
+ expect(vars.CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE).toBe(vars.GOOGLE_APPLICATION_CREDENTIALS);
121
+ const cred = JSON.parse(readFileSync(vars.GOOGLE_APPLICATION_CREDENTIALS!, "utf-8"));
122
+ expect(cred).toEqual({
123
+ type: "external_account",
124
+ audience: `//iam.googleapis.com/${PROVIDER}`,
125
+ subject_token_type: "urn:ietf:params:oauth:token-type:jwt",
126
+ token_url: "https://sts.googleapis.com/v1/token",
127
+ service_account_impersonation_url: "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/plan@proj.iam.gserviceaccount.com:generateAccessToken",
128
+ credential_source: { file: expect.stringContaining(`${dir}/chant-oidc-gcp-`) },
129
+ });
130
+ expect(readFileSync(cred.credential_source.file, "utf-8")).toContain(Buffer.from(AUD.gcp).toString("base64url"));
131
+ // Azure: the SDKs' workload identity and azurerm's OIDC, over one file.
132
+ expect(vars).toMatchObject({
133
+ AZURE_CLIENT_ID: SPEC.azure!.clientId,
134
+ AZURE_TENANT_ID: TENANT,
135
+ ARM_USE_OIDC: "true",
136
+ ARM_CLIENT_ID: SPEC.azure!.clientId,
137
+ ARM_TENANT_ID: TENANT,
138
+ AZURE_SUBSCRIPTION_ID: SPEC.azure!.subscriptionId,
139
+ ARM_SUBSCRIPTION_ID: SPEC.azure!.subscriptionId,
140
+ });
141
+ expect(vars.ARM_OIDC_TOKEN_FILE_PATH).toBe(vars.AZURE_FEDERATED_TOKEN_FILE);
142
+ expect(readFileSync(vars.ARM_OIDC_TOKEN_FILE_PATH!, "utf-8")).toContain(Buffer.from(AUD.azure).toString("base64url"));
143
+ // Nothing a token: the variables name files.
144
+ for (const v of Object.values(vars)) expect(v).not.toContain(EMULATED_JWT_PREFIX);
145
+ });
146
+
147
+ test("an emulator's endpoints reach the variables and the credential file", async () => {
148
+ const { vars } = await actionsStep("github", { aws: { ...SPEC.aws!, endpoint: `${emu.url}/aws/` }, gcp: { ...SPEC.gcp!, stsEndpoint: `${emu.url}/gsts/`, iamEndpoint: `${emu.url}/giam` }, azure: { ...SPEC.azure!, authority: `${emu.url}/entra/` } });
149
+ expect(vars.AWS_ENDPOINT_URL_STS).toBe(`${emu.url}/aws`);
150
+ expect(vars.AZURE_AUTHORITY_HOST).toBe(`${emu.url}/entra`);
151
+ const cred = JSON.parse(readFileSync(vars.GOOGLE_APPLICATION_CREDENTIALS!, "utf-8"));
152
+ expect(cred.token_url).toBe(`${emu.url}/gsts/v1/token`);
153
+ expect(cred.service_account_impersonation_url).toBe(`${emu.url}/giam/v1/projects/-/serviceAccounts/plan@proj.iam.gserviceaccount.com:generateAccessToken`);
154
+ });
155
+
156
+ test.each([
157
+ ["github", /the job can request no OIDC token for aws: it needs permissions: id-token: write/],
158
+ ["forgejo", /Forgejo serves one from version 15, with Forgejo Runner 12.5 or later, to a job with enable-openid-connect: true/],
159
+ ] as const)("%s: a job served no token stops, saying what it needs", async (forge, said) => {
160
+ const { vars, out } = await actionsStep(forge, { aws: SPEC.aws }, {});
161
+ expect(out).toMatchObject({ failed: 1, stderr: expect.stringMatching(said) });
162
+ expect(vars).toEqual({});
163
+ });
164
+
165
+ test("forgejo: a runner's token file is used where it is, and no token is requested", async () => {
166
+ const dir = mkdtempSync(join(tmpdir(), "chant-login-runner-"));
167
+ writeFileSync(join(dir, "token"), "eyJrunner.token.1\n");
168
+ const before = emu.log.minted.length;
169
+ const { vars, out } = await actionsStep("forgejo", { aws: { ...SPEC.aws!, tokenFile: "$RUNNER_TOKENS/token" }, azure: { ...SPEC.azure!, tokenFile: "${RUNNER_TOKENS}/token" } }, { RUNNER_TOKENS: dir });
170
+ expect(out).not.toHaveProperty("failed");
171
+ expect(emu.log.minted.length).toBe(before);
172
+ expect(vars.AWS_WEB_IDENTITY_TOKEN_FILE).toBe(join(dir, "token"));
173
+ expect(vars.ARM_OIDC_TOKEN_FILE_PATH).toBe(join(dir, "token"));
174
+ const missing = await actionsStep("forgejo", { aws: { ...SPEC.aws!, tokenFile: "$RUNNER_TOKENS/none" } }, { RUNNER_TOKENS: dir });
175
+ expect(missing.out).toMatchObject({ failed: 1, stderr: expect.stringContaining(`aws's tokenFile ${dir}/none cannot be read`) });
176
+ });
177
+
178
+ test("gitlab: the id_tokens tokens go to files, the variables are sourced, and the tokens and spec are unset", async () => {
179
+ const dir = mkdtempSync(join(tmpdir(), "chant-login-gl-"));
180
+ const { steps, idTokens } = gitlabCloudLogin(SPEC);
181
+ const tokens = Object.fromEntries(Object.keys(idTokens).map((k) => [k, `eyJgitlab.${k}.1`]));
182
+ // GitLab runs the script's lines in one shell that stops at the first failure.
183
+ const script = [...steps[0]!.run, "env"].join("\n");
184
+ const { stdout } = await run("sh", ["-e", "-c", script], { env: { PATH: process.env.PATH!, TMPDIR: dir, CI_JOB_ID: "77", ...tokens } });
185
+ const env = parseEnvFile(stdout);
186
+ for (const k of [...Object.keys(idTokens), LOGIN_SPEC_ENV, "CHANT_CLOUD_LOGIN_VARS"]) expect(env[k]).toBeUndefined();
187
+ expect(readFileSync(env.AWS_WEB_IDENTITY_TOKEN_FILE!, "utf-8")).toBe("eyJgitlab.CHANT_ID_TOKEN_AWS.1");
188
+ expect(readFileSync(env.AZURE_FEDERATED_TOKEN_FILE!, "utf-8")).toBe("eyJgitlab.CHANT_ID_TOKEN_AZURE.1");
189
+ expect(readFileSync(JSON.parse(readFileSync(env.GOOGLE_APPLICATION_CREDENTIALS!, "utf-8")).credential_source.file, "utf-8")).toBe("eyJgitlab.CHANT_ID_TOKEN_GCP.1");
190
+ expect(env).toMatchObject({ AWS_ROLE_ARN: SPEC.aws!.role, ARM_CLIENT_ID: SPEC.azure!.clientId });
191
+ // The variables were never written to a file: the directory holds the token files and the credential file alone.
192
+ expect(readdirSync(dir).every((f) => /^chant-(oidc|gcp)-/.test(f))).toBe(true);
193
+ });
194
+
195
+ test("gitlab: a job without the cloud's id_tokens stops, naming the entry it needs", async () => {
196
+ const step = gitlabCloudLogin({ gcp: SPEC.gcp }).steps[0]!;
197
+ const failed = await run("sh", ["-e", "-c", step.run.join("\n")], { env: { PATH: process.env.PATH!, TMPDIR: tmpdir(), CI_JOB_ID: "78" } }).catch((e: { stderr: string }) => e);
198
+ expect((failed as { stderr: string }).stderr).toContain(`the job has no CHANT_ID_TOKEN_GCP: it needs id_tokens: CHANT_ID_TOKEN_GCP: aud: ${AUD.gcp}`);
199
+ });
200
+
201
+ test("per target: each identity's variables in the targets file, and targetCloudEnv hands each root its own", async () => {
202
+ const spec: CloudLoginSpec = {
203
+ aws: { role: "arn:aws:iam::1:role/default", targets: [{ targets: ["envs/prod/**"], role: "arn:aws:iam::1:role/prod" }], region: "eu-west-1" },
204
+ gcp: { serviceAccount: "default@p.iam.gserviceaccount.com", targets: [{ targets: ["envs/prod/**"], serviceAccount: "prod@p.iam.gserviceaccount.com" }], provider: PROVIDER },
205
+ azure: { tenantId: TENANT, targets: [{ targets: ["envs/prod/**"], clientId: "prod-client" }] },
206
+ };
207
+ const { vars } = await actionsStep("github", spec);
208
+ expect(vars[CLOUD_TARGETS_ENV]).toBeDefined();
209
+ // Static keys in the job's environment would win over the role, so a root with another role starts without them.
210
+ const job = { ...vars, AWS_ACCESS_KEY_ID: "static" };
211
+ const prod = targetCloudEnv(job, "envs/prod/net");
212
+ expect(prod.AWS_ROLE_ARN).toBe("arn:aws:iam::1:role/prod");
213
+ expect(prod.AWS_ACCESS_KEY_ID).toBeUndefined();
214
+ expect(prod.AWS_WEB_IDENTITY_TOKEN_FILE).toBe(vars.AWS_WEB_IDENTITY_TOKEN_FILE);
215
+ expect(JSON.parse(readFileSync(prod.GOOGLE_APPLICATION_CREDENTIALS!, "utf-8")).service_account_impersonation_url).toContain("/serviceAccounts/prod@p.iam.gserviceaccount.com:");
216
+ expect(prod).toMatchObject({ ARM_CLIENT_ID: "prod-client", AZURE_CLIENT_ID: "prod-client", ARM_OIDC_TOKEN_FILE_PATH: expect.stringContaining("/chant-oidc-azure-") });
217
+ const other = targetCloudEnv(job, "envs/dev/net");
218
+ expect(other.AWS_ROLE_ARN).toBe("arn:aws:iam::1:role/default");
219
+ expect(other.GOOGLE_APPLICATION_CREDENTIALS).toBe(vars.GOOGLE_APPLICATION_CREDENTIALS);
220
+ // Azure has no job identity here, so a root no glob takes holds none.
221
+ expect(other.ARM_CLIENT_ID).toBeUndefined();
222
+ });
223
+
224
+ test("azure cli: az logs in as the job's client with the token, and sets the subscription", async () => {
225
+ const bin = mkdtempSync(join(tmpdir(), "chant-login-az-"));
226
+ const calls = join(bin, "calls");
227
+ writeFileSync(join(bin, "az"), `#!/bin/sh\necho "$*" >> "${calls}"\n`);
228
+ chmodSync(join(bin, "az"), 0o755);
229
+ const { out } = await actionsStep("github", { azure: { ...SPEC.azure!, cli: true } }, { ...emu.requestEnv, PATH: `${bin}:${process.env.PATH}` });
230
+ expect(out).not.toHaveProperty("failed");
231
+ const lines = readFileSync(calls, "utf-8").trim().split("\n");
232
+ expect(lines[0]).toMatch(new RegExp(`^login --service-principal --username ${SPEC.azure!.clientId} --tenant ${TENANT} --federated-token ${EMULATED_JWT_PREFIX}\\.\\S+ --allow-no-subscriptions --output none$`));
233
+ expect(lines[1]).toBe(`account set --subscription ${SPEC.azure!.subscriptionId}`);
234
+ });
235
+ });
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Cloud login steps from the OIDC token file (#4788): a CI job's step that
3
+ * writes the forge's OIDC token to a file and points each cloud's own tools
4
+ * at it, for AWS, GCP and Azure, on GitHub, GitLab and Forgejo.
5
+ *
6
+ * ./ci-identity.ts trades the token for short-lived credentials before the
7
+ * checkout. This is the other way a CI product logs in: the job keeps the
8
+ * token in a file and the cloud's SDK, command line or Terraform provider
9
+ * trades it itself, again whenever its credentials run out. That is what
10
+ * the AWS SDKs' web identity provider, Google's `external_account`
11
+ * credentials and the azurerm provider's OIDC read, and what terragucci's
12
+ * `oidcScript`, `gcpScript` and `azureScript` and SQL Yodeler's Forgejo
13
+ * login wrote for themselves.
14
+ *
15
+ * The step runs {@link LOGIN_JS} with `node -e` from `/`, so it reads none
16
+ * of the checkout's files and needs nothing installed. Per cloud it takes
17
+ * the token from, in order: the cloud's `tokenFile`, a file the runner
18
+ * provides (left where it is, so a runner that refreshes it keeps the job
19
+ * logged in); the GitLab `id_tokens` variable {@link idTokenVar}; the forge's
20
+ * token request URL with the cloud's audience (GitHub, and Forgejo 15 with
21
+ * Forgejo Runner 12.5 and `enable-openid-connect: true`). A token it got
22
+ * goes to a file of its own under `RUNNER_TEMP` (else `TMPDIR`, else
23
+ * `/tmp`), mode 0600. Then it sets:
24
+ *
25
+ * AWS AWS_ROLE_ARN, AWS_WEB_IDENTITY_TOKEN_FILE, AWS_ROLE_SESSION_NAME,
26
+ * AWS_REGION, AWS_DEFAULT_REGION (and AWS_ENDPOINT_URL_STS with
27
+ * `endpoint`)
28
+ * GCP GOOGLE_APPLICATION_CREDENTIALS and
29
+ * CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE, an `external_account`
30
+ * file per service account that trades the token at Google's STS
31
+ * and impersonates the account
32
+ * Azure AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_FEDERATED_TOKEN_FILE
33
+ * (the Azure SDKs), ARM_USE_OIDC, ARM_CLIENT_ID, ARM_TENANT_ID,
34
+ * ARM_OIDC_TOKEN_FILE_PATH (azurerm), the subscription in
35
+ * AZURE_SUBSCRIPTION_ID and ARM_SUBSCRIPTION_ID, and with `cli`
36
+ * `az login --federated-token` for the `az` command line
37
+ *
38
+ * gcloud reads CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE, so it needs no
39
+ * `gcloud auth login`. On GitHub and Forgejo the variables go to
40
+ * `$GITHUB_ENV`; on GitLab the script evaluates the `export` lines the
41
+ * login prints, which name files and hold no token, then unsets the token
42
+ * variables and the spec. No file of variables is left to delete.
43
+ *
44
+ * Per target and per stage: the spec is a {@link CloudTradeSpec} without
45
+ * Pulumi, the plan or apply side of what `resolveCloudIdentity` gives, so a
46
+ * product passes the stage's own. A cloud's `targets` name the identities
47
+ * other targets take (#4332). The step then writes the
48
+ * {@link CLOUD_TARGETS_ENV} file the trade writes, each identity's
49
+ * variables in it, and a product hands each target's tool its own with
50
+ * `targetCloudEnv`, as after the trade.
51
+ *
52
+ * The functions return {@link OpWaveRunStep}s and the job's `idTokens`, the
53
+ * shape `OpWavesPipelineOptions.waveJobs[].before` and `recordPlans` take
54
+ * (#4791), so a product passes the login to chant's generators instead of
55
+ * writing it into their files.
56
+ */
57
+
58
+ import {
59
+ CLOUD_TARGETS_ENV,
60
+ IDENTITY_KEY,
61
+ idTokenVar,
62
+ type Cloud,
63
+ type CloudTradeSpec,
64
+ } from "./ci-identity";
65
+ import type { OpWaveRunStep } from "./lexicon";
66
+
67
+ /** The variable the login step reads its {@link CloudLoginSpec} from, as JSON. */
68
+ export const LOGIN_SPEC_ENV = "CHANT_CLOUD_LOGIN";
69
+
70
+ /** The forges a login step is rendered for. */
71
+ export type LoginForge = "github" | "gitlab" | "forgejo";
72
+
73
+ /** What a cloud's login may add to its trade spec: a token file the runner provides. */
74
+ interface TokenFileOption {
75
+ /**
76
+ * A file holding the job's OIDC token for this cloud, which the runner
77
+ * provides, such as a Forgejo runner's own. A leading `$NAME` or
78
+ * `${NAME}` is the job's variable. The job then requests no token for
79
+ * this cloud.
80
+ */
81
+ tokenFile?: string;
82
+ }
83
+
84
+ /** One job's login, per cloud: a {@link CloudTradeSpec}'s AWS, GCP and Azure parts, with defaults, and the login's own options. */
85
+ export interface CloudLoginSpec {
86
+ aws?: Omit<NonNullable<CloudTradeSpec["aws"]>, "region" | "audience"> &
87
+ TokenFileOption & {
88
+ /** Default `us-east-1`. */
89
+ region?: string;
90
+ /** The token's audience. Default `sts.amazonaws.com`. */
91
+ audience?: string;
92
+ /** AWS_ROLE_SESSION_NAME, 2 to 64 of letters, digits and `+=,.@_-`. Default `chant`. */
93
+ sessionName?: string;
94
+ };
95
+ gcp?: Omit<NonNullable<CloudTradeSpec["gcp"]>, "audience"> &
96
+ TokenFileOption & {
97
+ /** The token's audience. Default `https://iam.googleapis.com/<provider>`. */
98
+ audience?: string;
99
+ };
100
+ azure?: Omit<NonNullable<CloudTradeSpec["azure"]>, "audience" | "database"> &
101
+ TokenFileOption & {
102
+ /** The token's audience. Default `api://AzureADTokenExchange`. */
103
+ audience?: string;
104
+ /** Also `az login --service-principal --federated-token` as the job's own client, for the `az` command line. Default false. */
105
+ cli?: boolean;
106
+ };
107
+ }
108
+
109
+ /** A job's login: its steps, and the OIDC tokens the job requests. */
110
+ export interface CloudLoginSteps {
111
+ /**
112
+ * The steps, in order. GitHub and Forgejo: each one `run:` step, its lines
113
+ * joined by newlines. GitLab: their lines in the job's script.
114
+ */
115
+ steps: OpWaveRunStep[];
116
+ /**
117
+ * The tokens the job requests, `{ <variable>: <audience> }`, as
118
+ * `recordPlans.idTokens` and a wave's `idTokens` take them: GitLab
119
+ * `id_tokens:`, and on GitHub and Forgejo the job's `id-token: write`
120
+ * (Forgejo `enable-openid-connect: true`). Empty when every cloud names a
121
+ * `tokenFile`.
122
+ */
123
+ idTokens: Record<string, string>;
124
+ }
125
+
126
+ const LOGIN_CLOUDS = ["aws", "gcp", "azure"] as const satisfies readonly Cloud[];
127
+
128
+ /** The provider's resource name without the `//iam.googleapis.com/` prefix, as ci-identity reads it. */
129
+ const providerPath = (p: string): string => p.replace(/^(https:)?\/\/iam\.googleapis\.com\//, "");
130
+
131
+ /** A value the login writes to a job's environment: printable ASCII with no space or quote. */
132
+ const SAFE = /^[\x21-\x7e]+$/;
133
+ const SESSION_NAME = /^[\w+=,.@-]{2,64}$/;
134
+ const TOKEN_FILE = /^(\$\{?[A-Za-z_][A-Za-z0-9_]*\}?)?[\w./-]+$/;
135
+
136
+ /** `spec` with every default filled, as the login script reads it, refused when a value cannot be held by the job. */
137
+ export function cloudLoginSpec(spec: CloudLoginSpec): CloudLoginSpec {
138
+ const extra = Object.keys(spec).filter((k) => !(LOGIN_CLOUDS as readonly string[]).includes(k));
139
+ if (extra.length > 0) throw new Error(`a cloud login covers ${LOGIN_CLOUDS.join(", ")}; ${extra.join(", ")} ${extra.includes("pulumi") ? "(Pulumi Cloud) is traded, with ci-identity's trade step" : "is no cloud it knows"}`);
140
+ if ((spec.azure as { database?: unknown } | undefined)?.database) throw new Error("a cloud login gives Azure no database token: trade the token with ci-identity's trade step for azure.database");
141
+ const out: CloudLoginSpec = {};
142
+ if (spec.aws) out.aws = { ...spec.aws, region: spec.aws.region ?? "us-east-1", audience: spec.aws.audience ?? "sts.amazonaws.com" };
143
+ if (spec.gcp) {
144
+ const provider = providerPath(spec.gcp.provider);
145
+ out.gcp = { ...spec.gcp, provider, audience: spec.gcp.audience ?? `https://iam.googleapis.com/${provider}` };
146
+ }
147
+ if (spec.azure) out.azure = { ...spec.azure, audience: spec.azure.audience ?? "api://AzureADTokenExchange" };
148
+ for (const cloud of LOGIN_CLOUDS) {
149
+ const c = out[cloud] as (Record<string, unknown> & { targets?: Array<Record<string, unknown>> }) | undefined;
150
+ if (!c) continue;
151
+ const key = IDENTITY_KEY[cloud];
152
+ const ids = [c[key], ...(c.targets ?? []).map((t) => t[key])].filter((v) => v !== undefined);
153
+ if (ids.length === 0) throw new Error(`the ${cloud} login names no identity: give it ${key}, or targets`);
154
+ for (const [k, v] of Object.entries(c)) {
155
+ if (typeof v === "string" && !SAFE.test(v)) throw new Error(`the ${cloud} login's ${k} is ${JSON.stringify(v)}; a job holds printable ASCII with no space`);
156
+ }
157
+ for (const id of ids) if (typeof id !== "string" || !SAFE.test(id)) throw new Error(`the ${cloud} login's identity ${JSON.stringify(id)} is not one a job can hold`);
158
+ if (c.tokenFile !== undefined && !TOKEN_FILE.test(String(c.tokenFile))) throw new Error(`the ${cloud} login's tokenFile ${JSON.stringify(c.tokenFile)} is not a file path`);
159
+ }
160
+ if (out.aws?.sessionName !== undefined && !SESSION_NAME.test(out.aws.sessionName)) throw new Error(`the aws login's sessionName ${JSON.stringify(out.aws.sessionName)} is not 2 to 64 of letters, digits and +=,.@_-`);
161
+ if (out.azure?.cli && !out.azure.clientId) throw new Error("the azure login's cli logs the az command line in as the job's own client, so it needs clientId");
162
+ return out;
163
+ }
164
+
165
+ /**
166
+ * The login, a script for `node -e` with no dependency. argv 1 is the file
167
+ * it writes, argv 2 its format (`github-env` appends `NAME=value` lines to
168
+ * the file; `sh` prints `export` lines, and argv 1 is `-`), argv 3 the forge, for what a job
169
+ * with no token is told. {@link LOGIN_SPEC_ENV} is the spec, defaults filled
170
+ * ({@link cloudLoginSpec}). It never prints a token.
171
+ */
172
+ export const LOGIN_JS = [
173
+ 'const fs=require("fs"),crypto=require("crypto");',
174
+ "const [out,format,forge]=process.argv.slice(1);",
175
+ "const Q=String.fromCharCode(39);",
176
+ 'const fail=(m)=>{console.error("chant: the cloud login failed: "+m);process.exit(1)};',
177
+ `let spec;try{spec=JSON.parse(process.env.${LOGIN_SPEC_ENV}||"")}catch{fail("${LOGIN_SPEC_ENV} is not JSON")}`,
178
+ 'const clean=(v)=>typeof v==="string"&&/^[\\x21-\\x7e]+$/.test(v);',
179
+ 'const trim=(u)=>String(u).replace(/\\/+$/,"");',
180
+ 'const tmp=trim(process.env.RUNNER_TEMP||process.env.TMPDIR||"/tmp");',
181
+ 'const rand=()=>crypto.randomBytes(8).toString("hex");',
182
+ 'const NO={github:"it needs permissions: id-token: write, and a pull request from a fork gets none",forgejo:"Forgejo serves one from version 15, with Forgejo Runner 12.5 or later, to a job with enable-openid-connect: true; on an older Forgejo give the cloud a tokenFile the runner provides"};',
183
+ // A cloud's token: the runner's file, else GitLab's id_tokens variable, else the forge's request URL, into a file of its own.
184
+ "const tokenFile=async(cloud,s)=>{",
185
+ 'if(s.tokenFile){const f=s.tokenFile.replace(/^\\$\\{?([A-Za-z_][A-Za-z0-9_]*)\\}?/,(m,v)=>process.env[v]||"");let t;try{t=fs.readFileSync(f,"utf8").trim()}catch{throw new Error(cloud+"\\u0027s tokenFile "+f+" cannot be read")}if(!t)throw new Error(cloud+"\\u0027s tokenFile "+f+" is empty");return f}',
186
+ 'const name="CHANT_ID_TOKEN_"+cloud.toUpperCase();let v=process.env[name];',
187
+ 'if(!v){if(forge==="gitlab")throw new Error("the job has no "+name+": it needs id_tokens: "+name+": aud: "+s.audience);',
188
+ "const u=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,k=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;",
189
+ 'if(!u||!k)throw new Error("the job can request no OIDC token for "+cloud+": "+(NO[forge]||NO.github));',
190
+ 'const r=await fetch(u+(u.includes("?")?"&":"?")+"audience="+encodeURIComponent(s.audience),{headers:{authorization:"bearer "+k,accept:"application/json"}});',
191
+ 'if(!r.ok)throw new Error("the OIDC token request answered "+r.status);',
192
+ 'try{v=JSON.parse(await r.text()).value}catch{throw new Error("the OIDC token request answered with no JSON")}}',
193
+ 'if(!clean(v))throw new Error("the job\\u0027s OIDC token for "+cloud+" is not a token");',
194
+ 'const f=tmp+"/chant-oidc-"+cloud+"-"+rand();fs.writeFileSync(f,v,{mode:0o600,flag:"wx"});return f};',
195
+ `const KEY=${JSON.stringify(IDENTITY_KEY)};`,
196
+ 'const ids=(c)=>{const s=spec[c],l=[];if(s[KEY[c]])l.push(s[KEY[c]]);for(const t of s.targets||[])if(!l.includes(t[KEY[c]]))l.push(t[KEY[c]]);return l};',
197
+ "const vars={},said=[],by={};",
198
+ "const run=async()=>{",
199
+ 'if(spec.aws){const a=spec.aws;const f=await tokenFile("aws",a);by.aws={};',
200
+ 'for(const role of ids("aws")){by.aws[role]={AWS_ROLE_ARN:role,AWS_WEB_IDENTITY_TOKEN_FILE:f,AWS_ROLE_SESSION_NAME:a.sessionName||"chant",AWS_REGION:a.region,AWS_DEFAULT_REGION:a.region,...(a.endpoint?{AWS_ENDPOINT_URL_STS:trim(a.endpoint)}:{})};said.push(role)}',
201
+ "if(a.role)Object.assign(vars,by.aws[a.role])}",
202
+ 'if(spec.gcp){const c=spec.gcp;const f=await tokenFile("gcp",c);by.gcp={};',
203
+ 'const sts=trim(c.stsEndpoint||"https://sts.googleapis.com"),iam=trim(c.iamEndpoint||"https://iamcredentials.googleapis.com");',
204
+ 'for(const sa of ids("gcp")){const cf=tmp+"/chant-gcp-"+rand()+".json";',
205
+ 'fs.writeFileSync(cf,JSON.stringify({type:"external_account",audience:"//iam.googleapis.com/"+c.provider,subject_token_type:"urn:ietf:params:oauth:token-type:jwt",token_url:sts+"/v1/token",service_account_impersonation_url:iam+"/v1/projects/-/serviceAccounts/"+sa+":generateAccessToken",credential_source:{file:f}})+"\\n",{mode:0o600,flag:"wx"});',
206
+ "by.gcp[sa]={GOOGLE_APPLICATION_CREDENTIALS:cf,CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE:cf};said.push(sa)}",
207
+ "if(c.serviceAccount)Object.assign(vars,by.gcp[c.serviceAccount])}",
208
+ 'if(spec.azure){const z=spec.azure;const f=await tokenFile("azure",z);by.azure={};',
209
+ "for(const cid of ids(\"azure\")){by.azure[cid]={AZURE_CLIENT_ID:cid,AZURE_TENANT_ID:z.tenantId,AZURE_FEDERATED_TOKEN_FILE:f,ARM_USE_OIDC:\"true\",ARM_CLIENT_ID:cid,ARM_TENANT_ID:z.tenantId,ARM_OIDC_TOKEN_FILE_PATH:f,...(z.subscriptionId?{AZURE_SUBSCRIPTION_ID:z.subscriptionId,ARM_SUBSCRIPTION_ID:z.subscriptionId}:{}),...(z.authority?{AZURE_AUTHORITY_HOST:trim(z.authority)}:{})};said.push(cid)}",
210
+ "if(z.clientId)Object.assign(vars,by.azure[z.clientId]);",
211
+ // The az command line keeps a login of its own; the token goes on its argv, as `az login` takes it.
212
+ 'if(z.cli){const r=require("child_process").spawnSync("az",["login","--service-principal","--username",z.clientId,"--tenant",z.tenantId,"--federated-token",fs.readFileSync(f,"utf8").trim(),"--allow-no-subscriptions","--output","none"],{stdio:["ignore","ignore","inherit"]});',
213
+ 'if(r.error)throw new Error("az login could not run: "+r.error.message);if(r.status!==0)throw new Error("az login exited "+r.status);',
214
+ 'if(z.subscriptionId){const s=require("child_process").spawnSync("az",["account","set","--subscription",z.subscriptionId],{stdio:["ignore","ignore","inherit"]});if(s.status!==0)throw new Error("az account set exited "+s.status)}}}',
215
+ // #4332: with targets, every identity's variables go in the trade's targets file, which targetCloudEnv reads.
216
+ 'const clouds=Object.keys(by);if(clouds.some((c)=>(spec[c].targets||[]).length>0)){',
217
+ 'const doc={version:1,clouds:{}};for(const c of clouds){const s=spec[c];doc.clouds[c]={...(s[KEY[c]]?{default:s[KEY[c]]}:{}),targets:(s.targets||[]).map((t)=>({targets:t.targets,identity:t[KEY[c]]})),vars:by[c]}}',
218
+ `const tf=tmp+"/chant-cloud-targets-"+rand()+".json";fs.writeFileSync(tf,JSON.stringify(doc),{mode:0o600,flag:"wx"});vars.${CLOUD_TARGETS_ENV}=tf}`,
219
+ 'for(const [k,v] of Object.entries(vars))if(!clean(v))throw new Error(k+" is not a value the job can hold");',
220
+ 'if(format==="github-env")fs.appendFileSync(out,Object.entries(vars).map(([k,v])=>k+"="+v+"\\n").join(""));',
221
+ 'else process.stdout.write(Object.entries(vars).map(([k,v])=>"export "+k+"="+Q+v.split(Q).join(Q+"\\\\"+Q+Q)+Q+"\\n").join(""));',
222
+ 'for(const s of said)console.error("chant: logged in from the OIDC token file as "+s)};',
223
+ "run().catch((e)=>fail(e&&e.message?e.message:String(e)));",
224
+ ].join("");
225
+
226
+ const sh = (s: string): string => `'${s.split("'").join(`'\\''`)}'`;
227
+
228
+ /** The tokens a login's job requests: one per cloud with no `tokenFile`, with the cloud's audience. */
229
+ function loginIdTokens(spec: CloudLoginSpec): Record<string, string> {
230
+ return Object.fromEntries(LOGIN_CLOUDS.filter((c) => spec[c] && spec[c]!.tokenFile === undefined).map((c) => [idTokenVar(c), spec[c]!.audience!]));
231
+ }
232
+
233
+ /** The step's name: which clouds it logs in to. */
234
+ const stepName = (spec: CloudLoginSpec): string => `Cloud login (chant ci-login: ${LOGIN_CLOUDS.filter((c) => spec[c]).join(", ")})`;
235
+
236
+ /** The shell line that runs the login from `/`, writing `out` in `format`. */
237
+ export function loginLine(out: string, format: "github-env" | "sh", forge: LoginForge): string {
238
+ return `(cd / && node -e '${LOGIN_JS}' "${out}" ${format} ${forge})`;
239
+ }
240
+
241
+ /** A GitHub Actions or Forgejo Actions login: one step that appends the variables to `$GITHUB_ENV`. */
242
+ function actionsLogin(forge: "github" | "forgejo", given: CloudLoginSpec): CloudLoginSteps {
243
+ const spec = cloudLoginSpec(given);
244
+ if (Object.keys(spec).length === 0) return { steps: [], idTokens: {} };
245
+ return {
246
+ steps: [{ name: stepName(spec), run: [`export ${LOGIN_SPEC_ENV}=${sh(JSON.stringify(spec))}`, loginLine("$GITHUB_ENV", "github-env", forge)] }],
247
+ idTokens: loginIdTokens(spec),
248
+ };
249
+ }
250
+
251
+ /**
252
+ * A GitHub Actions job's cloud login (#4788): one step that requests the
253
+ * OIDC token per cloud, writes each to a file and appends the clouds'
254
+ * variables to `$GITHUB_ENV`, so every later step has them. The job needs
255
+ * `id-token: write`, which `idTokens` asks chant's generators for.
256
+ */
257
+ export function githubCloudLogin(spec: CloudLoginSpec): CloudLoginSteps {
258
+ return actionsLogin("github", spec);
259
+ }
260
+
261
+ /**
262
+ * A Forgejo Actions job's cloud login (#4788), as on GitHub. Forgejo 15 with
263
+ * Forgejo Runner 12.5 serves the token to a job with
264
+ * `enable-openid-connect: true`, which the forgejo lexicon sets for a job
265
+ * that asks for `id-token: write`. On an older Forgejo, give each cloud a
266
+ * `tokenFile` the runner provides; the job then requests none.
267
+ */
268
+ export function forgejoCloudLogin(spec: CloudLoginSpec): CloudLoginSteps {
269
+ return actionsLogin("forgejo", spec);
270
+ }
271
+
272
+ /** The GitLab variable the login's `export` lines are kept in until the script evaluates them. */
273
+ export const GITLAB_LOGIN_VARS = "CHANT_CLOUD_LOGIN_VARS";
274
+
275
+ /**
276
+ * A GitLab CI job's cloud login (#4788): script lines that write each
277
+ * cloud's `id_tokens` token to a file, evaluate the clouds' variables, and
278
+ * unset the token variables and the spec, so later lines hold the token
279
+ * only in its file. The job's `id_tokens:` are `idTokens`, each
280
+ * `{ aud: <audience> }`.
281
+ */
282
+ export function gitlabCloudLogin(given: CloudLoginSpec): CloudLoginSteps {
283
+ const spec = cloudLoginSpec(given);
284
+ if (Object.keys(spec).length === 0) return { steps: [], idTokens: {} };
285
+ const idTokens = loginIdTokens(spec);
286
+ return {
287
+ steps: [
288
+ {
289
+ name: stepName(spec),
290
+ run: [
291
+ `export ${LOGIN_SPEC_ENV}=${sh(JSON.stringify(spec))}`,
292
+ // An assignment's status is its command substitution's, so a failed login stops the script.
293
+ `${GITLAB_LOGIN_VARS}="$${loginLine("-", "sh", "gitlab")}"`,
294
+ `eval "$${GITLAB_LOGIN_VARS}"`,
295
+ `unset ${[GITLAB_LOGIN_VARS, LOGIN_SPEC_ENV, ...Object.keys(idTokens)].join(" ")}`,
296
+ ],
297
+ },
298
+ ],
299
+ idTokens,
300
+ };
301
+ }
302
+
303
+ /** A job's cloud login on `forge` (#4788): {@link githubCloudLogin}, {@link gitlabCloudLogin} or {@link forgejoCloudLogin}. */
304
+ export function cloudLogin(forge: LoginForge, spec: CloudLoginSpec): CloudLoginSteps {
305
+ return forge === "gitlab" ? gitlabCloudLogin(spec) : actionsLogin(forge, spec);
306
+ }
307
+
package/src/ci-product.ts CHANGED
@@ -13,6 +13,7 @@ import type { CiProductWords, CiProductWordsInput } from "./ci-product-words";
13
13
  import type { ProductMcpHook } from "./cli/mcp/product-tools";
14
14
  import type { ProductWaveHook } from "./op/op-waves-after-plan";
15
15
  import { OTLP_EXPORTER_FLOOR } from "./otlp";
16
+ import { NEXT_RELEASE } from "./release-floors";
16
17
 
17
18
  /**
18
19
  * The first chant with the product pipeline (#4550): the words, the
@@ -117,6 +118,23 @@ export {
117
118
  } from "./components/product-pipeline";
118
119
  export { prActionJob, PR_ACTION_JOB, prApplyComment, prCommentLockJobs, prCommentPreviewJob, prLoopSetup, engineSetupLines, withProductBin, type PrActionJob, type PrActionJobOptions, type PrCommentLockJob, type PrCommentPreviewJob } from "./components/pr-pipeline";
119
120
 
121
+ /**
122
+ * The product plan (#4799): `productPipelineJobs(forge, env, { words,
123
+ * productPlan })` runs the product's plan verb in place of `pr-plan`, one
124
+ * plan job and one plan-note job per target, each with only its target's
125
+ * variables and secrets and an optional write probe, and `pr-post` posts the
126
+ * plan note hand-off the verb wrote (`planNoteHandoff`, `PR_PLAN_NOTE_FILE`
127
+ * in `@intentius/chant/pr-plan-note`). The forge lexicons render the
128
+ * workflow in process with no component graph: `generateProductPlanPipeline`
129
+ * (github), `generateForgejoProductPlanPipeline` (forgejo) and
130
+ * `generateGitlabProductPlanPipeline` (gitlab), each under
131
+ * `components/product-plan-pipeline`. A product feature-detects on this
132
+ * floor.
133
+ */
134
+ export const PRODUCT_PLAN_FLOOR = NEXT_RELEASE;
135
+ export { productPlanJobs, PR_PLAN_NOTE_WORDS_ENV, type ProductPlanJob, type ProductPlanOptions, type ProductPlanTarget } from "./components/product-plan";
136
+ export { planNoteHandoff, PR_PLAN_NOTE_FILE, type PrPlanNoteHandoff } from "./pr-plan-note";
137
+
120
138
  /**
121
139
  * Day-2 actions in the product pipeline (#4654): the `action` comment
122
140
  * command counted as answered by the product's own workflow
@@ -0,0 +1 @@
1
+ { "lexicons": [], "include": ["scripts"] }
@@ -0,0 +1 @@
1
+ export const infra = "declared";
@@ -0,0 +1,3 @@
1
+ // A script that runs on load: a build that loads it fails (#4794).
2
+ export const script = "ran";
3
+ throw new Error("scripts/run-on-load.ts was loaded");
@@ -0,0 +1 @@
1
+ export const infraTest = "test";
@@ -0,0 +1 @@
1
+ export const infra = "declared";
@@ -0,0 +1,3 @@
1
+ // A script that runs on load: a build that loads it fails (#4794).
2
+ export const script = "ran";
3
+ throw new Error("scripts/run-on-load.ts was loaded");
@@ -0,0 +1,3 @@
1
+ // Outside sourceDir: a build of the project that loads it fails (#4794).
2
+ export const app = "app";
3
+ throw new Error("app.ts was loaded");
@@ -0,0 +1 @@
1
+ { "lexicons": [], "sourceDir": "infra" }
@@ -0,0 +1 @@
1
+ export const net = "declared";
@@ -0,0 +1,3 @@
1
+ // Outside sourceDir.
2
+ export const script = "ran";
3
+ throw new Error("scripts/run-on-load.ts was loaded");