@intentius/chant 0.124.40 → 0.124.42

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 (346) hide show
  1. package/dist/__fixtures__/oidc-emulator.d.ts +49 -0
  2. package/dist/__fixtures__/oidc-emulator.d.ts.map +1 -0
  3. package/dist/__fixtures__/oidc-emulator.js +89 -0
  4. package/dist/ci-handover.d.ts +117 -0
  5. package/dist/ci-handover.d.ts.map +1 -0
  6. package/dist/ci-handover.js +217 -0
  7. package/dist/ci-identity.d.ts +190 -0
  8. package/dist/ci-identity.d.ts.map +1 -0
  9. package/dist/ci-identity.js +219 -0
  10. package/dist/cli/handlers/approve.d.ts +2 -1
  11. package/dist/cli/handlers/approve.d.ts.map +1 -1
  12. package/dist/cli/handlers/approve.js +20 -6
  13. package/dist/cli/handlers/build.d.ts.map +1 -1
  14. package/dist/cli/handlers/build.js +18 -1
  15. package/dist/cli/handlers/fan-out.d.ts.map +1 -1
  16. package/dist/cli/handlers/fan-out.js +42 -5
  17. package/dist/cli/handlers/gate-resume.d.ts +3 -0
  18. package/dist/cli/handlers/gate-resume.d.ts.map +1 -1
  19. package/dist/cli/handlers/gate-resume.js +15 -2
  20. package/dist/cli/handlers/lock.d.ts +8 -0
  21. package/dist/cli/handlers/lock.d.ts.map +1 -0
  22. package/dist/cli/handlers/lock.js +197 -0
  23. package/dist/cli/handlers/pr-env.d.ts +34 -0
  24. package/dist/cli/handlers/pr-env.d.ts.map +1 -0
  25. package/dist/cli/handlers/pr-env.js +436 -0
  26. package/dist/cli/handlers/pr.d.ts +76 -0
  27. package/dist/cli/handlers/pr.d.ts.map +1 -1
  28. package/dist/cli/handlers/pr.js +615 -55
  29. package/dist/cli/handlers/promote.d.ts.map +1 -1
  30. package/dist/cli/handlers/promote.js +9 -0
  31. package/dist/cli/handlers/query.d.ts +6 -0
  32. package/dist/cli/handlers/query.d.ts.map +1 -0
  33. package/dist/cli/handlers/query.js +80 -0
  34. package/dist/cli/handlers/run.d.ts.map +1 -1
  35. package/dist/cli/handlers/run.js +11 -0
  36. package/dist/cli/main.d.ts.map +1 -1
  37. package/dist/cli/main.js +49 -4
  38. package/dist/cli/parse-args.d.ts.map +1 -1
  39. package/dist/cli/parse-args.js +46 -2
  40. package/dist/cli/registry.d.ts +31 -2
  41. package/dist/cli/registry.d.ts.map +1 -1
  42. package/dist/components/capability.d.ts +47 -0
  43. package/dist/components/capability.d.ts.map +1 -1
  44. package/dist/components/capability.js +44 -0
  45. package/dist/components/cli-support.d.ts +6 -0
  46. package/dist/components/cli-support.d.ts.map +1 -1
  47. package/dist/components/cli-support.js +8 -1
  48. package/dist/components/driver.d.ts +10 -0
  49. package/dist/components/driver.d.ts.map +1 -1
  50. package/dist/components/driver.js +52 -2
  51. package/dist/components/fan-out-run.d.ts +37 -0
  52. package/dist/components/fan-out-run.d.ts.map +1 -1
  53. package/dist/components/fan-out-run.js +44 -4
  54. package/dist/components/gate-plan.d.ts +2 -0
  55. package/dist/components/gate-plan.d.ts.map +1 -1
  56. package/dist/components/gate-plan.js +1 -0
  57. package/dist/components/pr-environment.d.ts +298 -0
  58. package/dist/components/pr-environment.d.ts.map +1 -0
  59. package/dist/components/pr-environment.js +406 -0
  60. package/dist/components/pr-hooks.d.ts +66 -0
  61. package/dist/components/pr-hooks.d.ts.map +1 -0
  62. package/dist/components/pr-hooks.js +119 -0
  63. package/dist/components/pr-pipeline.d.ts +92 -2
  64. package/dist/components/pr-pipeline.d.ts.map +1 -1
  65. package/dist/components/pr-pipeline.js +150 -21
  66. package/dist/components/pr-policy.d.ts +109 -0
  67. package/dist/components/pr-policy.d.ts.map +1 -0
  68. package/dist/components/pr-policy.js +150 -0
  69. package/dist/components/pr-run.d.ts +6 -0
  70. package/dist/components/pr-run.d.ts.map +1 -1
  71. package/dist/components/pr-run.js +8 -3
  72. package/dist/components/wave-plan.d.ts +14 -1
  73. package/dist/components/wave-plan.d.ts.map +1 -1
  74. package/dist/components/wave-plan.js +34 -2
  75. package/dist/gate-decision.d.ts +15 -2
  76. package/dist/gate-decision.d.ts.map +1 -1
  77. package/dist/gate-decision.js +17 -2
  78. package/dist/gate-policy.d.ts +140 -0
  79. package/dist/gate-policy.d.ts.map +1 -0
  80. package/dist/gate-policy.js +242 -0
  81. package/dist/lifecycle/gate-checkpoint.d.ts +1 -1
  82. package/dist/lifecycle/gate-checkpoint.js +1 -1
  83. package/dist/{workspace/trust → lifecycle}/gate-seal.d.ts +1 -1
  84. package/dist/lifecycle/gate-seal.d.ts.map +1 -0
  85. package/dist/lifecycle/query.d.ts +68 -0
  86. package/dist/lifecycle/query.d.ts.map +1 -0
  87. package/dist/lifecycle/query.js +246 -0
  88. package/dist/lifecycle/run-ledger.d.ts +13 -0
  89. package/dist/lifecycle/run-ledger.d.ts.map +1 -1
  90. package/dist/lifecycle/run-ledger.js +16 -0
  91. package/dist/lifecycle/target-lock.d.ts +97 -0
  92. package/dist/lifecycle/target-lock.d.ts.map +1 -0
  93. package/dist/lifecycle/target-lock.js +286 -0
  94. package/dist/op/activities/activity-contracts.d.ts +30 -0
  95. package/dist/op/activities/activity-contracts.d.ts.map +1 -1
  96. package/dist/op/activities/activity-contracts.js +26 -0
  97. package/dist/op/activities/index.d.ts +2 -0
  98. package/dist/op/activities/index.d.ts.map +1 -1
  99. package/dist/op/activities/index.js +4 -0
  100. package/dist/op/activities/pr-refs.d.ts +10 -0
  101. package/dist/op/activities/pr-refs.d.ts.map +1 -0
  102. package/dist/op/activities/pr-refs.js +26 -0
  103. package/dist/op/activities/predict-behaviour.d.ts +2 -4
  104. package/dist/op/activities/predict-behaviour.d.ts.map +1 -1
  105. package/dist/op/activities/predict-behaviour.js +2 -21
  106. package/dist/op/activities/review-agent.d.ts +137 -0
  107. package/dist/op/activities/review-agent.d.ts.map +1 -0
  108. package/dist/op/activities/review-agent.js +266 -0
  109. package/dist/op/builders.d.ts +9 -0
  110. package/dist/op/builders.d.ts.map +1 -1
  111. package/dist/op/builders.js +11 -0
  112. package/dist/op/cron.d.ts +8 -0
  113. package/dist/op/cron.d.ts.map +1 -1
  114. package/dist/op/cron.js +51 -0
  115. package/dist/op/gate-approval.d.ts +20 -13
  116. package/dist/op/gate-approval.d.ts.map +1 -1
  117. package/dist/op/gate-approval.js +13 -18
  118. package/dist/op/gate-quorum.d.ts +131 -0
  119. package/dist/op/gate-quorum.d.ts.map +1 -0
  120. package/dist/op/gate-quorum.js +183 -0
  121. package/dist/op/gate-resume.d.ts +4 -2
  122. package/dist/op/gate-resume.d.ts.map +1 -1
  123. package/dist/op/gate-resume.js +5 -4
  124. package/dist/op/gate-review.js +1 -1
  125. package/dist/op/gate.d.ts +32 -4
  126. package/dist/op/gate.d.ts.map +1 -1
  127. package/dist/op/gate.js +40 -24
  128. package/dist/op/index.d.ts +6 -4
  129. package/dist/op/index.d.ts.map +1 -1
  130. package/dist/op/index.js +4 -3
  131. package/dist/op/local-executor.d.ts.map +1 -1
  132. package/dist/op/local-executor.js +9 -3
  133. package/dist/op/op-waves-run.d.ts +28 -43
  134. package/dist/op/op-waves-run.d.ts.map +1 -1
  135. package/dist/op/op-waves-run.js +170 -120
  136. package/dist/op/op-waves.d.ts +55 -3
  137. package/dist/op/op-waves.d.ts.map +1 -1
  138. package/dist/op/op-waves.js +63 -8
  139. package/dist/op/schedule-overdue.d.ts +57 -0
  140. package/dist/op/schedule-overdue.d.ts.map +1 -0
  141. package/dist/op/schedule-overdue.js +138 -0
  142. package/dist/op/stage-hooks.d.ts +132 -0
  143. package/dist/op/stage-hooks.d.ts.map +1 -0
  144. package/dist/op/stage-hooks.js +142 -0
  145. package/dist/override-gate.d.ts +2 -2
  146. package/dist/override-gate.d.ts.map +1 -1
  147. package/dist/override-gate.js +1 -1
  148. package/dist/pr-forge.d.ts +64 -0
  149. package/dist/pr-forge.d.ts.map +1 -1
  150. package/dist/pr-forge.js +331 -44
  151. package/dist/pr-loop.d.ts +107 -1
  152. package/dist/pr-loop.d.ts.map +1 -1
  153. package/dist/pr-loop.js +84 -3
  154. package/dist/pr-post.d.ts +72 -0
  155. package/dist/pr-post.d.ts.map +1 -0
  156. package/dist/pr-post.js +134 -0
  157. package/dist/pr-requires.d.ts +38 -0
  158. package/dist/pr-requires.d.ts.map +1 -0
  159. package/dist/pr-requires.js +48 -0
  160. package/dist/wave-blocked.d.ts +79 -0
  161. package/dist/wave-blocked.d.ts.map +1 -0
  162. package/dist/wave-blocked.js +245 -0
  163. package/dist/wave-engine.d.ts +6 -0
  164. package/dist/wave-engine.d.ts.map +1 -1
  165. package/dist/wave-engine.js +2 -0
  166. package/dist/wave-runtime.mjs +243 -243
  167. package/dist/workspace/__fixtures__/two-member-workspace.d.ts +1 -0
  168. package/dist/workspace/__fixtures__/two-member-workspace.d.ts.map +1 -1
  169. package/dist/workspace/__fixtures__/two-member-workspace.js +1 -1
  170. package/dist/workspace/checks/ci-workflow.d.ts.map +1 -1
  171. package/dist/workspace/checks/ci-workflow.js +19 -4
  172. package/dist/workspace/ci-branches.d.ts +51 -0
  173. package/dist/workspace/ci-branches.d.ts.map +1 -0
  174. package/dist/workspace/ci-branches.js +69 -0
  175. package/dist/workspace/ci-cloud-identity.d.ts +11 -0
  176. package/dist/workspace/ci-cloud-identity.d.ts.map +1 -0
  177. package/dist/workspace/ci-cloud-identity.js +24 -0
  178. package/dist/workspace/ci-init.d.ts.map +1 -1
  179. package/dist/workspace/ci-init.js +5 -4
  180. package/dist/workspace/ci-locks.d.ts +12 -0
  181. package/dist/workspace/ci-locks.d.ts.map +1 -0
  182. package/dist/workspace/ci-locks.js +6 -0
  183. package/dist/workspace/ci-run.d.ts +17 -1
  184. package/dist/workspace/ci-run.d.ts.map +1 -1
  185. package/dist/workspace/ci-run.js +66 -4
  186. package/dist/workspace/ci-workflow-at.d.ts +14 -0
  187. package/dist/workspace/ci-workflow-at.d.ts.map +1 -0
  188. package/dist/workspace/ci-workflow-at.js +17 -0
  189. package/dist/workspace/ci-workflow.d.ts +11 -3
  190. package/dist/workspace/ci-workflow.d.ts.map +1 -1
  191. package/dist/workspace/ci-workflow.js +10 -2
  192. package/dist/workspace/declaration.d.ts +69 -3
  193. package/dist/workspace/declaration.d.ts.map +1 -1
  194. package/dist/workspace/declaration.js +72 -1
  195. package/dist/workspace/declaration.schema.json +149 -2
  196. package/dist/workspace/identity-gate-rule.d.ts +1 -1
  197. package/dist/workspace/identity-gate-rule.d.ts.map +1 -1
  198. package/dist/workspace/identity-gate-rule.js +1 -1
  199. package/dist/workspace/identity.d.ts +1 -1
  200. package/dist/workspace/identity.d.ts.map +1 -1
  201. package/dist/workspace/lineage-upgrade.d.ts.map +1 -1
  202. package/dist/workspace/lineage-upgrade.js +8 -5
  203. package/dist/workspace/member-pipeline.d.ts +6 -0
  204. package/dist/workspace/member-pipeline.d.ts.map +1 -1
  205. package/dist/workspace/member-pipeline.js +23 -0
  206. package/dist/workspace/pr-report.schema.json +94 -3
  207. package/dist/workspace/reason-codes.d.ts +1 -1
  208. package/dist/workspace/reason-codes.d.ts.map +1 -1
  209. package/dist/workspace/reason-codes.js +1 -1
  210. package/dist/workspace/security.d.ts.map +1 -1
  211. package/dist/workspace/security.js +4 -0
  212. package/dist/workspace/status-gates.d.ts +3 -2
  213. package/dist/workspace/status-gates.d.ts.map +1 -1
  214. package/dist/workspace/status-gates.js +8 -7
  215. package/dist/workspace/status.d.ts.map +1 -1
  216. package/dist/workspace/status.js +4 -1
  217. package/dist/workspace/trust/seal.d.ts +2 -2
  218. package/dist/workspace/trust/seal.d.ts.map +1 -1
  219. package/dist/workspace/trust/seal.js +2 -2
  220. package/package.json +1 -1
  221. package/src/__fixtures__/oidc-emulator.ts +118 -0
  222. package/src/ci-handover.test.ts +209 -0
  223. package/src/ci-handover.ts +237 -0
  224. package/src/ci-identity.test.ts +201 -0
  225. package/src/ci-identity.ts +310 -0
  226. package/src/cli/handlers/approve.ts +18 -5
  227. package/src/cli/handlers/build.ts +18 -1
  228. package/src/cli/handlers/fan-out.ts +43 -6
  229. package/src/cli/handlers/gate-resume.ts +16 -2
  230. package/src/cli/handlers/lock.test.ts +98 -0
  231. package/src/cli/handlers/lock.ts +202 -0
  232. package/src/cli/handlers/operator.test.ts +3 -1
  233. package/src/cli/handlers/pr-before-merge.test.ts +276 -0
  234. package/src/cli/handlers/pr-env.ts +462 -0
  235. package/src/cli/handlers/pr-waves-blocked.test.ts +247 -0
  236. package/src/cli/handlers/pr.test.ts +184 -0
  237. package/src/cli/handlers/pr.ts +605 -61
  238. package/src/cli/handlers/promote.ts +9 -0
  239. package/src/cli/handlers/query.ts +78 -0
  240. package/src/cli/handlers/run.ts +10 -0
  241. package/src/cli/main.ts +49 -4
  242. package/src/cli/parse-args.ts +34 -2
  243. package/src/cli/registry.ts +31 -2
  244. package/src/components/capability-targets.test.ts +162 -0
  245. package/src/components/capability.ts +71 -0
  246. package/src/components/cli-support.ts +14 -1
  247. package/src/components/driver.ts +54 -3
  248. package/src/components/fan-out-run.ts +58 -3
  249. package/src/components/fan-out-waves.test.ts +45 -1
  250. package/src/components/gate-plan.ts +3 -0
  251. package/src/components/pr-environment.test.ts +249 -0
  252. package/src/components/pr-environment.ts +538 -0
  253. package/src/components/pr-hooks.test.ts +118 -0
  254. package/src/components/pr-hooks.ts +157 -0
  255. package/src/components/pr-pipeline.ts +194 -21
  256. package/src/components/pr-policy.test.ts +145 -0
  257. package/src/components/pr-policy.ts +211 -0
  258. package/src/components/pr-run.ts +14 -2
  259. package/src/components/wave-plan.ts +38 -3
  260. package/src/gate-decision-bundle.test.ts +4 -3
  261. package/src/gate-decision.ts +39 -2
  262. package/src/gate-policy-bundle.test.ts +28 -0
  263. package/src/gate-policy.test.ts +162 -0
  264. package/src/gate-policy.ts +298 -0
  265. package/src/lifecycle/gate-checkpoint.ts +1 -1
  266. package/src/{workspace/trust → lifecycle}/gate-seal.ts +1 -1
  267. package/src/lifecycle/query.test.ts +91 -0
  268. package/src/lifecycle/query.ts +315 -0
  269. package/src/lifecycle/run-ledger.ts +18 -0
  270. package/src/lifecycle/target-lock.test.ts +195 -0
  271. package/src/lifecycle/target-lock.ts +347 -0
  272. package/src/op/activities/activity-contracts.ts +31 -0
  273. package/src/op/activities/index.ts +6 -0
  274. package/src/op/activities/pr-refs.ts +28 -0
  275. package/src/op/activities/predict-behaviour.ts +3 -23
  276. package/src/op/activities/review-agent.test.ts +240 -0
  277. package/src/op/activities/review-agent.ts +355 -0
  278. package/src/op/builders.ts +13 -0
  279. package/src/op/cron.ts +44 -0
  280. package/src/op/gate-alias.test.ts +2 -2
  281. package/src/op/gate-approval.test.ts +30 -9
  282. package/src/op/gate-approval.ts +23 -26
  283. package/src/op/gate-quorum.test.ts +139 -0
  284. package/src/op/gate-quorum.ts +248 -0
  285. package/src/op/gate-resume.ts +6 -3
  286. package/src/op/gate-review.ts +1 -1
  287. package/src/op/gate.ts +64 -23
  288. package/src/op/index.ts +13 -1
  289. package/src/op/local-executor.ts +9 -2
  290. package/src/op/op-waves-hook-targets.test.ts +126 -0
  291. package/src/op/op-waves-policy-hold.test.ts +66 -0
  292. package/src/op/op-waves-quorum.test.ts +101 -0
  293. package/src/op/op-waves-run.ts +197 -183
  294. package/src/op/op-waves.ts +83 -10
  295. package/src/op/schedule-overdue.test.ts +220 -0
  296. package/src/op/schedule-overdue.ts +161 -0
  297. package/src/op/stage-hooks.ts +251 -0
  298. package/src/override-gate-bundle.test.ts +1 -1
  299. package/src/override-gate.ts +2 -2
  300. package/src/pr-forge-bundle.test.ts +2 -2
  301. package/src/pr-forge.test.ts +33 -0
  302. package/src/pr-forge.ts +347 -35
  303. package/src/pr-loop-bundle.test.ts +2 -2
  304. package/src/pr-loop.test.ts +58 -0
  305. package/src/pr-loop.ts +170 -4
  306. package/src/pr-post.test.ts +141 -0
  307. package/src/pr-post.ts +159 -0
  308. package/src/pr-requires.test.ts +184 -0
  309. package/src/pr-requires.ts +79 -0
  310. package/src/review-agent-bundle.test.ts +35 -0
  311. package/src/stage-hooks-bundle.test.ts +38 -0
  312. package/src/wave-blocked-bundle.test.ts +25 -0
  313. package/src/wave-blocked.test.ts +146 -0
  314. package/src/wave-blocked.ts +271 -0
  315. package/src/wave-engine.ts +8 -0
  316. package/src/workspace/__fixtures__/two-member-workspace.ts +2 -2
  317. package/src/workspace/checks/ci-workflow.test.ts +9 -0
  318. package/src/workspace/checks/ci-workflow.ts +18 -4
  319. package/src/workspace/ci-branches.test.ts +62 -0
  320. package/src/workspace/ci-branches.ts +79 -0
  321. package/src/workspace/ci-cloud-identity.test.ts +53 -0
  322. package/src/workspace/ci-cloud-identity.ts +23 -0
  323. package/src/workspace/ci-init.ts +5 -4
  324. package/src/workspace/ci-locks.ts +16 -0
  325. package/src/workspace/ci-run-index.test.ts +2 -1
  326. package/src/workspace/ci-run.test.ts +107 -8
  327. package/src/workspace/ci-run.ts +74 -5
  328. package/src/workspace/ci-workflow-at.ts +23 -0
  329. package/src/workspace/ci-workflow.ts +13 -2
  330. package/src/workspace/declaration.schema.json +149 -2
  331. package/src/workspace/declaration.test.ts +76 -0
  332. package/src/workspace/declaration.ts +140 -5
  333. package/src/workspace/identity-gate-rule.ts +1 -1
  334. package/src/workspace/identity.ts +1 -1
  335. package/src/workspace/lineage-upgrade.ts +11 -8
  336. package/src/workspace/member-pipeline.test.ts +29 -0
  337. package/src/workspace/member-pipeline.ts +30 -0
  338. package/src/workspace/pr-report.schema.json +94 -3
  339. package/src/workspace/reason-codes.ts +1 -1
  340. package/src/workspace/security.ts +4 -0
  341. package/src/workspace/status-gates.ts +9 -6
  342. package/src/workspace/status.ts +4 -1
  343. package/src/workspace/trust/gate-seal.test.ts +1 -1
  344. package/src/workspace/trust/seal.ts +2 -2
  345. package/dist/workspace/trust/gate-seal.d.ts.map +0 -1
  346. /package/dist/{workspace/trust → lifecycle}/gate-seal.js +0 -0
@@ -0,0 +1,201 @@
1
+ /**
2
+ * #4296: the plan and apply cloud identities, and the OIDC trade. The trade
3
+ * tests run the generated `node -e` line with `sh`, as a forge step runs
4
+ * it, against a local emulator of the forge's token URL, AWS STS, Google's
5
+ * STS and IAM credentials, and Entra (./__fixtures__/oidc-emulator.ts).
6
+ * Test values only; no cloud is reached.
7
+ */
8
+
9
+ import { execFile } from "node:child_process";
10
+ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { promisify } from "node:util";
14
+ import { afterAll, beforeAll, describe, expect, test } from "vitest";
15
+ import {
16
+ cloudIdentityProblems,
17
+ gitlabTradeIdTokens,
18
+ gitlabTradeLines,
19
+ idTokenVar,
20
+ OIDC_REQUEST_VARS,
21
+ resolveCloudIdentity,
22
+ TRADE_JS,
23
+ TRADE_SPEC_ENV,
24
+ tradeLine,
25
+ type CloudIdentityDeclaration,
26
+ type CloudTradeSpec,
27
+ } from "./ci-identity";
28
+ import { emulatedCredentials, EMULATED_JWT_PREFIX, startOidcEmulator, type OidcEmulator } from "./__fixtures__/oidc-emulator";
29
+ import { dropForgeTokens } from "./ci-handover";
30
+
31
+ const run = promisify(execFile);
32
+
33
+ const DECL: CloudIdentityDeclaration = {
34
+ aws: {
35
+ region: "eu-west-1",
36
+ rules: [
37
+ { environments: ["prod"], members: ["net"], plan: "arn:aws:iam::111111111111:role/net-prod-plan", apply: "arn:aws:iam::111111111111:role/net-prod-apply" },
38
+ { environments: ["prod"], plan: "arn:aws:iam::111111111111:role/prod-plan", apply: "arn:aws:iam::111111111111:role/prod-apply" },
39
+ { environments: ["staging-*"], plan: "arn:aws:iam::222222222222:role/staging-plan", apply: "arn:aws:iam::222222222222:role/staging-apply" },
40
+ ],
41
+ },
42
+ gcp: {
43
+ provider: "projects/123/locations/global/workloadIdentityPools/ci/providers/forge",
44
+ rules: [{ plan: "plan@test-project.iam.gserviceaccount.com", apply: "apply@test-project.iam.gserviceaccount.com" }],
45
+ },
46
+ azure: { tenantId: "00000000-0000-0000-0000-00000000tena", rules: [{ members: ["app"], plan: "plan-client-id", apply: "apply-client-id" }] },
47
+ };
48
+
49
+ describe("which identities a pipeline takes (#4296)", () => {
50
+ test("the first rule whose environments and members match wins, per cloud", () => {
51
+ const net = resolveCloudIdentity(DECL, "prod", "net")!;
52
+ expect(net.plan.aws!.role).toBe("arn:aws:iam::111111111111:role/net-prod-plan");
53
+ expect(net.apply.aws!.role).toBe("arn:aws:iam::111111111111:role/net-prod-apply");
54
+ expect(resolveCloudIdentity(DECL, "prod", "web")!.plan.aws!.role).toBe("arn:aws:iam::111111111111:role/prod-plan");
55
+ expect(resolveCloudIdentity(DECL, "staging-eu", "net")!.apply.aws!.role).toBe("arn:aws:iam::222222222222:role/staging-apply");
56
+ expect(net.plan.aws).toMatchObject({ region: "eu-west-1", audience: "sts.amazonaws.com" });
57
+ });
58
+
59
+ test("a cloud no rule covers is left out, and so is a pipeline no rule covers", () => {
60
+ expect(resolveCloudIdentity(DECL, "prod", "net")!.plan.azure).toBeUndefined();
61
+ expect(resolveCloudIdentity(DECL, "prod", "app")!.plan.azure).toMatchObject({ clientId: "plan-client-id", audience: "api://AzureADTokenExchange" });
62
+ expect(resolveCloudIdentity({ aws: DECL.aws }, "dev", "net")).toBeUndefined();
63
+ expect(resolveCloudIdentity(undefined, "prod")).toBeUndefined();
64
+ });
65
+
66
+ test("a rule with members never matches a pipeline outside a member", () => {
67
+ expect(resolveCloudIdentity(DECL, "prod")!.plan.aws!.role).toBe("arn:aws:iam::111111111111:role/prod-plan");
68
+ });
69
+
70
+ test("GCP's default audience names the provider", () => {
71
+ expect(resolveCloudIdentity(DECL, "prod")!.plan.gcp!.audience).toBe("https://iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/ci/providers/forge");
72
+ });
73
+
74
+ test("a rule may not plan as an identity it or another rule applies as", () => {
75
+ expect(cloudIdentityProblems(DECL)).toEqual([]);
76
+ const same = cloudIdentityProblems({ aws: { rules: [{ plan: "r", apply: "r" }] } });
77
+ expect(same).toEqual([{ pointer: "/ci/identity/cloud/aws/rules/0", message: expect.stringContaining("plans and applies as r") }]);
78
+ const crossed = cloudIdentityProblems({ gcp: { provider: "p", rules: [{ plan: "a", apply: "b" }, { plan: "b", apply: "c" }] } });
79
+ expect(crossed).toEqual([{ pointer: "/ci/identity/cloud/gcp/rules/1", message: expect.stringContaining("plans as b, which another rule applies as") }]);
80
+ });
81
+ });
82
+
83
+ describe("the trade script stays inside one shell word", () => {
84
+ test("it holds no single quote, so tradeLine can quote it", () => {
85
+ expect(TRADE_JS).not.toContain("'");
86
+ });
87
+ test("GitLab's lines trade, unset the token variables and the extra ones, then source the credentials", () => {
88
+ const [trade, unset, source] = gitlabTradeLines(["CHANT_FORGE_TOKEN"]);
89
+ expect(trade).toContain("node -e");
90
+ expect(unset).toBe(`unset CHANT_FORGE_TOKEN ${OIDC_REQUEST_VARS.join(" ")}`);
91
+ expect(source).toMatch(/^\. "\$\{TMPDIR:-\/tmp\}\/chant-cloud-\$CI_JOB_ID\.sh" && rm -f /);
92
+ expect(gitlabTradeIdTokens(resolveCloudIdentity(DECL, "prod", "app")!.plan)).toEqual({
93
+ CHANT_ID_TOKEN_AWS: { aud: "sts.amazonaws.com" },
94
+ CHANT_ID_TOKEN_GCP: { aud: "https://iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/ci/providers/forge" },
95
+ CHANT_ID_TOKEN_AZURE: { aud: "api://AzureADTokenExchange" },
96
+ });
97
+ });
98
+ });
99
+
100
+ const dirs: string[] = [];
101
+ let emu: OidcEmulator;
102
+ beforeAll(async () => {
103
+ emu = await startOidcEmulator();
104
+ });
105
+ afterAll(async () => {
106
+ await emu.close();
107
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
108
+ });
109
+
110
+ const BASE = { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: process.env.HOME ?? "/tmp" };
111
+
112
+ /** Run the trade line as a step does, with `spec` pointed at the emulator. */
113
+ async function trade(spec: CloudTradeSpec, format: "github-env" | "sh", env: Record<string, string> = emu.requestEnv): Promise<{ out: string; stdout: string; stderr: string; code: number; file: string }> {
114
+ const dir = mkdtempSync(join(tmpdir(), "chant-trade-"));
115
+ dirs.push(dir);
116
+ const file = join(dir, format === "sh" ? "cloud.sh" : "github-env");
117
+ if (format === "github-env") writeFileSync(file, "EARLIER=1\n");
118
+ try {
119
+ const r = await run("sh", ["-c", tradeLine(file, format)], { env: { ...BASE, ...env, [TRADE_SPEC_ENV]: JSON.stringify(emu.pointAt(spec)) } });
120
+ return { out: existsSync(file) ? readFileSync(file, "utf-8") : "", stdout: r.stdout, stderr: r.stderr, code: 0, file };
121
+ } catch (e) {
122
+ const err = e as { stdout: string; stderr: string; code: number };
123
+ return { out: existsSync(file) ? readFileSync(file, "utf-8") : "", stdout: err.stdout, stderr: err.stderr, code: err.code, file };
124
+ }
125
+ }
126
+
127
+ describe("the trade, run against the emulator (#4296)", () => {
128
+ const prodApp = () => resolveCloudIdentity(DECL, "prod", "app")!;
129
+
130
+ test("it trades one minted token per cloud for the plan identity alone, and writes the credentials to GITHUB_ENV", async () => {
131
+ const before = { minted: emu.log.minted.length, assumed: emu.log.assumed.length };
132
+ const r = await trade(prodApp().plan, "github-env");
133
+ expect(r.stderr).not.toContain("failed");
134
+ expect(r.code).toBe(0);
135
+ const aws = emulatedCredentials("arn:aws:iam::111111111111:role/prod-plan");
136
+ expect(r.out).toContain("EARLIER=1\n");
137
+ expect(r.out).toContain(`AWS_ACCESS_KEY_ID=${aws.accessKeyId}\n`);
138
+ expect(r.out).toContain(`AWS_SESSION_TOKEN=${aws.token}\n`);
139
+ expect(r.out).toContain("AWS_REGION=eu-west-1\n");
140
+ expect(r.out).toMatch(/^GOOGLE_OAUTH_ACCESS_TOKEN=ya29\.session-/m);
141
+ expect(r.out).toMatch(/^AZURE_ACCESS_TOKEN=azure\.session-/m);
142
+ expect(r.out).toContain("AZURE_CLIENT_ID=plan-client-id\n");
143
+ // The minted token itself is in no line the later steps get, and no apply identity was asked for.
144
+ expect(r.out).not.toContain(EMULATED_JWT_PREFIX);
145
+ expect(r.stdout + r.stderr).not.toContain(EMULATED_JWT_PREFIX);
146
+ expect(emu.log.minted.slice(before.minted)).toEqual(["sts.amazonaws.com", "https://iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/ci/providers/forge", "api://AzureADTokenExchange"]);
147
+ expect(emu.log.assumed.slice(before.assumed).map((a) => a.role)).toEqual(["arn:aws:iam::111111111111:role/prod-plan"]);
148
+ expect(emu.log.impersonated.at(-1)).toBe("plan@test-project.iam.gserviceaccount.com");
149
+ expect(emu.log.clients.at(-1)!.clientId).toBe("plan-client-id");
150
+ // GitHub masks each secret in every later step's log.
151
+ expect(r.stdout).toContain(`::add-mask::${aws.secret}`);
152
+ expect(r.stdout).toContain(`::add-mask::${aws.token}`);
153
+ });
154
+
155
+ test("the sh format writes export lines a GitLab script sources, mode 0600", async () => {
156
+ const r = await trade({ aws: prodApp().apply.aws }, "sh");
157
+ expect(r.code).toBe(0);
158
+ expect(statSync(r.file).mode & 0o777).toBe(0o600);
159
+ const probe = await run("sh", ["-c", `. "${r.file}"; echo "$AWS_ACCESS_KEY_ID"`], { env: BASE });
160
+ expect(probe.stdout.trim()).toBe(emulatedCredentials("arn:aws:iam::111111111111:role/prod-apply").accessKeyId);
161
+ });
162
+
163
+ test("on GitLab the token comes from the job's id_tokens variable, and no request URL is needed", async () => {
164
+ const before = emu.log.minted.length;
165
+ const jwt = `${EMULATED_JWT_PREFIX}.gitlab.1`;
166
+ const r = await trade({ aws: prodApp().plan.aws }, "sh", { [idTokenVar("aws")]: jwt });
167
+ expect(r.code).toBe(0);
168
+ expect(emu.log.minted.length).toBe(before);
169
+ expect(emu.log.assumed.at(-1)).toEqual({ role: "arn:aws:iam::111111111111:role/prod-plan", token: jwt });
170
+ expect(r.out).not.toContain(jwt);
171
+ });
172
+
173
+ test("a job that can request no token fails the step and writes nothing", async () => {
174
+ const r = await trade({ aws: prodApp().plan.aws }, "sh", {});
175
+ expect(r.code).not.toBe(0);
176
+ expect(r.stderr).toContain("the job can request no OIDC token for aws");
177
+ expect(r.out).toBe("");
178
+ });
179
+
180
+ test("an answer that would add a line of its own to GITHUB_ENV is refused", async () => {
181
+ const r = await trade({ aws: { ...prodApp().plan.aws!, region: "eu-west-1\nNODE_OPTIONS=--require=/tmp/x" } }, "github-env");
182
+ expect(r.code).not.toBe(0);
183
+ expect(r.out).toBe("EARLIER=1\n");
184
+ });
185
+ });
186
+
187
+ describe("after the trade, a step that runs the change's code cannot request a token (#4296)", () => {
188
+ test("the drop line with the OIDC request variables leaves none of them, and a request from the step fails", async () => {
189
+ const dir = mkdtempSync(join(tmpdir(), "chant-trade-drop-"));
190
+ dirs.push(dir);
191
+ const file = join(dir, "step.sh");
192
+ const ask = `node -e 'const u=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,k=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(!u||!k){console.log("no-request-vars");process.exit(0)}fetch(u+"&audience=sts.amazonaws.com",{headers:{authorization:"bearer "+k}}).then(r=>r.text()).then(t=>console.log("minted:"+t))'`;
193
+ writeFileSync(file, `${dropForgeTokens("sh", OIDC_REQUEST_VARS)}\nenv\n${ask}\n`);
194
+ const before = emu.log.minted.length;
195
+ const r = await run("sh", ["-e", file], { cwd: dir, env: { ...BASE, ...emu.requestEnv, [idTokenVar("aws")]: `${EMULATED_JWT_PREFIX}.x.y`, [TRADE_SPEC_ENV]: "{}" } });
196
+ expect(r.stdout).toContain("no-request-vars");
197
+ expect(r.stdout).not.toContain(EMULATED_JWT_PREFIX);
198
+ for (const v of OIDC_REQUEST_VARS) expect(r.stdout).not.toMatch(new RegExp(`^${v}=`, "m"));
199
+ expect(emu.log.minted.length).toBe(before);
200
+ });
201
+ });
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Plan and apply cloud identities (#4296): the pull-request jobs plan with
3
+ * one identity and apply with another, per cloud, and the plan job trades
4
+ * its OIDC token before the change's code is checked out.
5
+ *
6
+ * The workspace declaration's `ci.identity.cloud` gives each cloud a list of
7
+ * rules. A rule names environment globs and member globs, and a plan and an
8
+ * apply identity: an AWS role, a GCP service account or an Azure client id.
9
+ * The first rule whose globs match the pipeline's environment and member is
10
+ * the pipeline's ({@link resolveCloudIdentity}). A workspace generates one
11
+ * pull-request pipeline per member and environment, so each member's apply
12
+ * jobs hold that member's apply identity and no other.
13
+ *
14
+ * The plan job runs the pull request's code. Its first step, before the
15
+ * checkout, runs {@link tradeJs} with `node -e`: it asks the forge for an
16
+ * OIDC token, trades it for the plan identity's own credentials, and leaves
17
+ * those credentials for the later steps. Each later step then starts again
18
+ * without the variables a token is requested with ({@link OIDC_REQUEST_VARS},
19
+ * through `dropForgeTokens` in ./ci-handover.ts), so the change's code holds
20
+ * no OIDC token and cannot request one. The plan job's file names no apply
21
+ * identity. The record job plans the merged commit with the plan identity,
22
+ * and the apply jobs trade for the apply identity.
23
+ *
24
+ * The trade is terragucci's `oidc-trade.ts` (INTENTIUS/terragucci e6cb431,
25
+ * packages/terragucci/src/oidc-trade.ts) with these clients:
26
+ *
27
+ * AWS STS AssumeRoleWithWebIdentity, as session keys in
28
+ * AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN
29
+ * GCP Google's STS token exchange, then IAM generateAccessToken for the
30
+ * service account, in GOOGLE_OAUTH_ACCESS_TOKEN and
31
+ * CLOUDSDK_AUTH_ACCESS_TOKEN
32
+ * Azure Entra's client credentials grant with the token as the client
33
+ * assertion, as an ARM access token in AZURE_ACCESS_TOKEN, with
34
+ * AZURE_CLIENT_ID and AZURE_TENANT_ID (and ARM_ spellings)
35
+ *
36
+ * terragucci leaves Azure untraded because the azurerm provider takes only
37
+ * the OIDC token. chant trades it, so the change's code never holds a token
38
+ * another client could be traded for; a tool that needs the OIDC token
39
+ * itself cannot plan under this block.
40
+ */
41
+
42
+ // @ts-ignore: picomatch has no types declaration
43
+ import picomatch from "picomatch";
44
+
45
+ /** The clouds `ci.identity.cloud` names. */
46
+ export const CLOUDS = ["aws", "gcp", "azure"] as const;
47
+ export type Cloud = (typeof CLOUDS)[number];
48
+
49
+ /** One rule: the environments and members it covers, and their two identities. */
50
+ export interface CloudIdentityRule {
51
+ /** Environment-name globs. Absent: every environment. */
52
+ environments?: string[];
53
+ /** Member-name globs. Absent: every member, and a pipeline outside a workspace member. */
54
+ members?: string[];
55
+ /** The identity the plan and record jobs take. */
56
+ plan: string;
57
+ /** The identity the apply jobs take. */
58
+ apply: string;
59
+ }
60
+
61
+ export interface AwsCloudIdentity {
62
+ /** The STS region. Default `us-east-1`. */
63
+ region?: string;
64
+ /** The OIDC token's audience. Default `sts.amazonaws.com`. */
65
+ audience?: string;
66
+ /** The STS endpoint, for an emulator. Default the region's, or `AWS_ENDPOINT_URL_STS` in the job. */
67
+ endpoint?: string;
68
+ rules: CloudIdentityRule[];
69
+ }
70
+
71
+ export interface GcpCloudIdentity {
72
+ /** The workload identity provider: `projects/<number>/locations/global/workloadIdentityPools/<pool>/providers/<provider>`. */
73
+ provider: string;
74
+ /** The OIDC token's audience. Default `https://iam.googleapis.com/<provider>`. */
75
+ audience?: string;
76
+ /** Google's STS, for an emulator. Default `https://sts.googleapis.com`. */
77
+ stsEndpoint?: string;
78
+ /** IAM credentials, for an emulator. Default `https://iamcredentials.googleapis.com`. */
79
+ iamEndpoint?: string;
80
+ rules: CloudIdentityRule[];
81
+ }
82
+
83
+ export interface AzureCloudIdentity {
84
+ /** The Entra tenant. */
85
+ tenantId: string;
86
+ /** Set as AZURE_SUBSCRIPTION_ID and ARM_SUBSCRIPTION_ID when given. */
87
+ subscriptionId?: string;
88
+ /** The OIDC token's audience. Default `api://AzureADTokenExchange`. */
89
+ audience?: string;
90
+ /** The Entra authority host, for an emulator. Default `https://login.microsoftonline.com`. */
91
+ authority?: string;
92
+ rules: CloudIdentityRule[];
93
+ }
94
+
95
+ /** `ci.identity.cloud` as the declaration holds it. */
96
+ export interface CloudIdentityDeclaration {
97
+ aws?: AwsCloudIdentity;
98
+ gcp?: GcpCloudIdentity;
99
+ azure?: AzureCloudIdentity;
100
+ }
101
+
102
+ /** What one job trades for: per cloud, the one identity and where to trade it. */
103
+ export interface CloudTradeSpec {
104
+ aws?: { role: string; region: string; audience: string; endpoint?: string };
105
+ gcp?: { serviceAccount: string; provider: string; audience: string; stsEndpoint?: string; iamEndpoint?: string };
106
+ azure?: { clientId: string; tenantId: string; audience: string; subscriptionId?: string; authority?: string };
107
+ }
108
+
109
+ /** A pipeline's two trades: the plan and record jobs', and the apply jobs'. */
110
+ export interface PipelineCloudIdentity {
111
+ plan: CloudTradeSpec;
112
+ apply: CloudTradeSpec;
113
+ }
114
+
115
+ const matches = (globs: readonly string[] | undefined, name: string | undefined): boolean =>
116
+ globs === undefined || (name !== undefined && globs.some((g) => (picomatch(g) as (s: string) => boolean)(name)));
117
+
118
+ /** The first rule that covers `env` and `member`, or undefined. */
119
+ export function ruleFor(rules: readonly CloudIdentityRule[], env: string, member?: string): CloudIdentityRule | undefined {
120
+ return rules.find((r) => matches(r.environments, env) && matches(r.members, member));
121
+ }
122
+
123
+ /** The provider's resource name without the `//iam.googleapis.com/` prefix. */
124
+ const providerPath = (p: string): string => p.replace(/^(https:)?\/\/iam\.googleapis\.com\//, "");
125
+
126
+ /**
127
+ * The plan and apply trades of the pipeline for `env` and `member`, or
128
+ * undefined when no rule of any cloud covers them. A cloud no rule covers
129
+ * is left out of both.
130
+ */
131
+ export function resolveCloudIdentity(decl: CloudIdentityDeclaration | undefined, env: string, member?: string): PipelineCloudIdentity | undefined {
132
+ if (!decl) return undefined;
133
+ const plan: CloudTradeSpec = {};
134
+ const apply: CloudTradeSpec = {};
135
+ const aws = decl.aws && ruleFor(decl.aws.rules, env, member);
136
+ if (decl.aws && aws) {
137
+ const at = { region: decl.aws.region ?? "us-east-1", audience: decl.aws.audience ?? "sts.amazonaws.com", ...(decl.aws.endpoint ? { endpoint: decl.aws.endpoint } : {}) };
138
+ plan.aws = { role: aws.plan, ...at };
139
+ apply.aws = { role: aws.apply, ...at };
140
+ }
141
+ const gcp = decl.gcp && ruleFor(decl.gcp.rules, env, member);
142
+ if (decl.gcp && gcp) {
143
+ const provider = providerPath(decl.gcp.provider);
144
+ const at = {
145
+ provider,
146
+ audience: decl.gcp.audience ?? `https://iam.googleapis.com/${provider}`,
147
+ ...(decl.gcp.stsEndpoint ? { stsEndpoint: decl.gcp.stsEndpoint } : {}),
148
+ ...(decl.gcp.iamEndpoint ? { iamEndpoint: decl.gcp.iamEndpoint } : {}),
149
+ };
150
+ plan.gcp = { serviceAccount: gcp.plan, ...at };
151
+ apply.gcp = { serviceAccount: gcp.apply, ...at };
152
+ }
153
+ const azure = decl.azure && ruleFor(decl.azure.rules, env, member);
154
+ if (decl.azure && azure) {
155
+ const at = {
156
+ tenantId: decl.azure.tenantId,
157
+ audience: decl.azure.audience ?? "api://AzureADTokenExchange",
158
+ ...(decl.azure.subscriptionId ? { subscriptionId: decl.azure.subscriptionId } : {}),
159
+ ...(decl.azure.authority ? { authority: decl.azure.authority } : {}),
160
+ };
161
+ plan.azure = { clientId: azure.plan, ...at };
162
+ apply.azure = { clientId: azure.apply, ...at };
163
+ }
164
+ return Object.keys(plan).length > 0 ? { plan, apply } : undefined;
165
+ }
166
+
167
+ /** The clouds a trade covers, in {@link CLOUDS} order. */
168
+ export function tradedClouds(spec: CloudTradeSpec): Cloud[] {
169
+ return CLOUDS.filter((c) => spec[c] !== undefined);
170
+ }
171
+
172
+ /** Every identity a trade names: the role, the service account, the client id. */
173
+ export function tradeIdentities(spec: CloudTradeSpec): string[] {
174
+ return [spec.aws?.role, spec.gcp?.serviceAccount, spec.azure?.clientId].filter((v): v is string => v !== undefined);
175
+ }
176
+
177
+ /**
178
+ * The problems of a declared `ci.identity.cloud`, each with its JSON
179
+ * pointer: a rule whose plan and apply are one identity, or a plan identity
180
+ * that is another rule's apply identity. Either would let the plan job,
181
+ * which runs the change's code, act as an apply identity.
182
+ */
183
+ export function cloudIdentityProblems(decl: CloudIdentityDeclaration): Array<{ pointer: string; message: string }> {
184
+ const out: Array<{ pointer: string; message: string }> = [];
185
+ for (const cloud of CLOUDS) {
186
+ const rules = decl[cloud]?.rules ?? [];
187
+ const applies = new Set(rules.map((r) => r.apply));
188
+ rules.forEach((r, i) => {
189
+ const pointer = `/ci/identity/cloud/${cloud}/rules/${i}`;
190
+ if (r.plan === r.apply) out.push({ pointer, message: `ci.identity.cloud.${cloud}.rules[${i}] plans and applies as ${r.plan}; the plan runs the pull request's code, so give it an identity of its own` });
191
+ else if (applies.has(r.plan)) out.push({ pointer, message: `ci.identity.cloud.${cloud}.rules[${i}] plans as ${r.plan}, which another rule applies as; the plan runs the pull request's code, so give it an identity no rule applies as` });
192
+ });
193
+ }
194
+ return out;
195
+ }
196
+
197
+ /** The variable the trade step reads its {@link CloudTradeSpec} from, as JSON. */
198
+ export const TRADE_SPEC_ENV = "CHANT_CLOUD_TRADE";
199
+
200
+ /** The GitLab `id_tokens` variable a cloud's token comes in: `CHANT_ID_TOKEN_AWS`, `_GCP`, `_AZURE`. */
201
+ export function idTokenVar(cloud: Cloud): string {
202
+ return `CHANT_ID_TOKEN_${cloud.toUpperCase()}`;
203
+ }
204
+
205
+ /**
206
+ * The variables a GitHub or Forgejo step requests an OIDC token with, and
207
+ * the GitLab `id_tokens` variables the trade reads. A step that runs the
208
+ * change's code starts without them, once the trade is done.
209
+ */
210
+ export const OIDC_REQUEST_VARS = ["ACTIONS_ID_TOKEN_REQUEST_TOKEN", "ACTIONS_ID_TOKEN_REQUEST_URL", ...CLOUDS.map(idTokenVar), TRADE_SPEC_ENV] as const;
211
+
212
+ /** The variables the trade sets, per cloud. */
213
+ export const TRADED_VARS: Record<Cloud, readonly string[]> = {
214
+ aws: ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_REGION", "AWS_DEFAULT_REGION"],
215
+ gcp: ["GOOGLE_OAUTH_ACCESS_TOKEN", "CLOUDSDK_AUTH_ACCESS_TOKEN"],
216
+ azure: ["AZURE_ACCESS_TOKEN", "AZURE_CLIENT_ID", "AZURE_TENANT_ID", "ARM_CLIENT_ID", "ARM_TENANT_ID", "AZURE_SUBSCRIPTION_ID", "ARM_SUBSCRIPTION_ID"],
217
+ };
218
+
219
+ /**
220
+ * How the trade leaves what it got. `github-env`: `NAME=value` lines
221
+ * appended to the file argv 1 names (`$GITHUB_ENV`), and an `::add-mask::`
222
+ * line for each secret, so every later step of the job has them. `sh`: a
223
+ * file of `export` lines a GitLab script sources, mode 0600.
224
+ */
225
+ export type TradeFormat = "github-env" | "sh";
226
+
227
+ /**
228
+ * The trade, a script for `node -e` with no dependency, so it runs before
229
+ * the checkout and reads none of the change's files. argv 1 is the file it
230
+ * writes and argv 2 its {@link TradeFormat}; {@link TRADE_SPEC_ENV} is the
231
+ * spec. The token comes from a cloud's {@link idTokenVar} when the job has
232
+ * it (GitLab's `id_tokens`), else from the forge's request URL with the
233
+ * cloud's audience. A value that holds anything but printable ASCII with no
234
+ * space is refused, so no answer can add a line of its own to the file. The
235
+ * script never prints a token.
236
+ */
237
+ export const TRADE_JS = [
238
+ 'const fs=require("fs");',
239
+ "const [out,format]=process.argv.slice(1);",
240
+ "const Q=String.fromCharCode(39);",
241
+ 'const fail=(m)=>{console.error("chant: the OIDC trade failed: "+m);process.exit(1)};',
242
+ `let spec;try{spec=JSON.parse(process.env.${TRADE_SPEC_ENV}||"")}catch{fail("${TRADE_SPEC_ENV} is not JSON")}`,
243
+ 'const clean=(v)=>typeof v==="string"&&/^[\\x21-\\x7e]+$/.test(v);',
244
+ 'const trim=(u)=>String(u).replace(/\\/+$/,"");',
245
+ 'const post=async(url,headers,body)=>{const r=await fetch(url,{method:"POST",headers,body});const t=await r.text();if(!r.ok)throw new Error(url+" answered "+r.status+": "+t.slice(0,200).replace(/\\s+/g," "));return t};',
246
+ 'const json=(t,what)=>{try{return JSON.parse(t)}catch{throw new Error(what+" answered with no JSON")}};',
247
+ "const idToken=async(cloud,aud)=>{",
248
+ 'const named=process.env["CHANT_ID_TOKEN_"+cloud.toUpperCase()];if(named)return named;',
249
+ "const u=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,k=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;",
250
+ 'if(!u||!k)throw new Error("the job can request no OIDC token for "+cloud+": it needs id-token: write, and a pull request from a fork gets none");',
251
+ 'const r=await fetch(u+(u.includes("?")?"&":"?")+"audience="+encodeURIComponent(aud),{headers:{authorization:"bearer "+k,accept:"application/json"}});',
252
+ 'if(!r.ok)throw new Error("the OIDC token request answered "+r.status);',
253
+ 'const v=json(await r.text(),"the OIDC token request").value;if(!clean(v))throw new Error("the OIDC token request gave no token");return v};',
254
+ "const vars={},secrets=[],said=[];",
255
+ "const run=async()=>{",
256
+ "if(spec.aws){const a=spec.aws;const tok=await idToken(\"aws\",a.audience);",
257
+ 'const ep=trim(a.endpoint||process.env.AWS_ENDPOINT_URL_STS||("https://sts."+a.region+".amazonaws.com"+(a.region.startsWith("cn-")?".cn":"")));',
258
+ 'const t=await post(ep+"/",{"content-type":"application/x-www-form-urlencoded",accept:"application/xml"},new URLSearchParams({Action:"AssumeRoleWithWebIdentity",Version:"2011-06-15",RoleArn:a.role,RoleSessionName:"chant-"+(process.env.GITHUB_RUN_ID||process.env.CI_JOB_ID||"job"),WebIdentityToken:tok}).toString());',
259
+ 'const g=(k)=>{const m=new RegExp("<"+k+">([^<]+)</"+k+">").exec(t);return m?m[1].trim():undefined};',
260
+ 'const id=g("AccessKeyId"),key=g("SecretAccessKey"),st=g("SessionToken");if(!clean(id)||!clean(key)||!clean(st))throw new Error("STS gave no credentials for "+a.role);',
261
+ 'Object.assign(vars,{AWS_ACCESS_KEY_ID:id,AWS_SECRET_ACCESS_KEY:key,AWS_SESSION_TOKEN:st,AWS_REGION:a.region,AWS_DEFAULT_REGION:a.region});secrets.push(key,st);said.push(a.role)}',
262
+ "if(spec.gcp){const c=spec.gcp;const tok=await idToken(\"gcp\",c.audience);",
263
+ 'const sts=trim(c.stsEndpoint||"https://sts.googleapis.com"),iam=trim(c.iamEndpoint||"https://iamcredentials.googleapis.com");',
264
+ 'const fed=json(await post(sts+"/v1/token",{"content-type":"application/json"},JSON.stringify({grantType:"urn:ietf:params:oauth:grant-type:token-exchange",audience:"//iam.googleapis.com/"+c.provider,scope:"https://www.googleapis.com/auth/cloud-platform",requestedTokenType:"urn:ietf:params:oauth:token-type:access_token",subjectToken:tok,subjectTokenType:"urn:ietf:params:oauth:token-type:jwt"})),"Google STS").access_token;',
265
+ 'if(!clean(fed))throw new Error("Google STS gave no token");',
266
+ 'const at=json(await post(iam+"/v1/projects/-/serviceAccounts/"+encodeURIComponent(c.serviceAccount)+":generateAccessToken",{"content-type":"application/json",authorization:"Bearer "+fed},JSON.stringify({scope:["https://www.googleapis.com/auth/cloud-platform"]})),"IAM credentials").accessToken;',
267
+ 'if(!clean(at))throw new Error("IAM credentials gave no token for "+c.serviceAccount);',
268
+ "Object.assign(vars,{GOOGLE_OAUTH_ACCESS_TOKEN:at,CLOUDSDK_AUTH_ACCESS_TOKEN:at});secrets.push(at);said.push(c.serviceAccount)}",
269
+ "if(spec.azure){const z=spec.azure;const tok=await idToken(\"azure\",z.audience);",
270
+ 'const host=trim(z.authority||"https://login.microsoftonline.com");',
271
+ 'const at=json(await post(host+"/"+encodeURIComponent(z.tenantId)+"/oauth2/v2.0/token",{"content-type":"application/x-www-form-urlencoded"},new URLSearchParams({client_id:z.clientId,scope:"https://management.azure.com/.default",grant_type:"client_credentials",client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:tok}).toString()),"Entra").access_token;',
272
+ 'if(!clean(at))throw new Error("Entra gave no token for "+z.clientId);',
273
+ "Object.assign(vars,{AZURE_ACCESS_TOKEN:at,AZURE_CLIENT_ID:z.clientId,AZURE_TENANT_ID:z.tenantId,ARM_CLIENT_ID:z.clientId,ARM_TENANT_ID:z.tenantId});",
274
+ "if(z.subscriptionId)Object.assign(vars,{AZURE_SUBSCRIPTION_ID:z.subscriptionId,ARM_SUBSCRIPTION_ID:z.subscriptionId});secrets.push(at);said.push(z.clientId)}",
275
+ 'for(const [k,v] of Object.entries(vars))if(!clean(v))throw new Error(k+" is not a value the job can hold");',
276
+ 'if(format==="github-env"){for(const s of secrets)console.log("::add-mask::"+s);fs.appendFileSync(out,Object.entries(vars).map(([k,v])=>k+"="+v+"\\n").join(""))}',
277
+ 'else fs.writeFileSync(out,Object.entries(vars).map(([k,v])=>"export "+k+"="+Q+v.split(Q).join(Q+"\\\\"+Q+Q)+Q+"\\n").join(""),{mode:0o600});',
278
+ 'for(const s of said)console.error("chant: traded the job\\u0027s OIDC token for "+s)};',
279
+ "run().catch((e)=>fail(e&&e.message?e.message:String(e)));",
280
+ ].join("");
281
+
282
+ /**
283
+ * The shell line of a trade step: `node -e` from `/`, so no file of the
284
+ * checkout (a `package.json`, an `.npmrc`) is in reach, writing `out` in
285
+ * `format`.
286
+ */
287
+ export function tradeLine(out: string, format: TradeFormat): string {
288
+ return `(cd / && node -e '${TRADE_JS}' "${out}" ${format})`;
289
+ }
290
+
291
+ /** The GitLab file the trade writes and the plan script sources, outside the project directory. */
292
+ export const GITLAB_TRADE_FILE = "${TMPDIR:-/tmp}/chant-cloud-$CI_JOB_ID.sh";
293
+
294
+ /**
295
+ * The lines a GitLab job's script starts with when it trades: the trade,
296
+ * the unset of the token variables (and, with `extraUnset`, the forge
297
+ * tokens'), and the source of what the trade wrote, which it then deletes.
298
+ */
299
+ export function gitlabTradeLines(extraUnset: readonly string[] = []): string[] {
300
+ return [
301
+ tradeLine(GITLAB_TRADE_FILE, "sh"),
302
+ `unset ${[...extraUnset, ...OIDC_REQUEST_VARS].join(" ")}`,
303
+ `. "${GITLAB_TRADE_FILE}" && rm -f "${GITLAB_TRADE_FILE}"`,
304
+ ];
305
+ }
306
+
307
+ /** GitLab's `id_tokens:` for a trade: one per cloud, with the cloud's audience. */
308
+ export function gitlabTradeIdTokens(spec: CloudTradeSpec): Record<string, { aud: string }> {
309
+ return Object.fromEntries(tradedClouds(spec).map((c) => [idTokenVar(c), { aud: spec[c]!.audience }]));
310
+ }
@@ -21,6 +21,7 @@ import {
21
21
  type GateApprover, type GatePolicyDecision, type GatePolicyEvaluator, type ResolvedGateApproval,
22
22
  } from "../../op/gate-approval";
23
23
  import { approverOf, humanQuorumSince, tallyGateApprovals } from "../../op/gate";
24
+ import { quorumRuleLine, quorumRules, trustQuorumJudge, UNPROVEN_JUDGE, type GateQuorumJudge } from "../../op/gate-quorum";
24
25
  import { FAN_OUT_GATE_OP, OVERRIDE_GATE_OP, RELEASE_GATE_OP, WORKSPACE_UPGRADE_GATE_OP } from "../../op/gate-name";
25
26
  import { PR_GATE_OP } from "../../pr-loop";
26
27
  import { pushLifecycleReport, requireLifecycleLedger } from "../../lifecycle/git";
@@ -680,7 +681,9 @@ export async function recordGateApproval(
680
681
  ));
681
682
  }
682
683
  if (approval) {
683
- for (const line of describeApprovalProgress(approval, record, ledger.resolutions, standingForOrigin, ledger.pending)) {
684
+ // #4290: the rules count roles from .chant/trust.json at base, for a proven approver.
685
+ const judge = trustQuorumJudge({ signers: scope.policy, roles: scope.policy.roles });
686
+ for (const line of describeApprovalProgress(approval, record, ledger.resolutions, standingForOrigin, ledger.pending, judge)) {
684
687
  console.error(formatInfo(line));
685
688
  }
686
689
  }
@@ -699,6 +702,7 @@ export function describeApprovalProgress(
699
702
  prior: GateResolutionRecord[],
700
703
  standing: PendingGateRecord | undefined,
701
704
  pending: readonly PendingGateRecord[] = standing ? [standing] : [],
705
+ judge: GateQuorumJudge = UNPROVEN_JUDGE,
702
706
  ): string[] {
703
707
  const lines: string[] = [];
704
708
  const decision = record.policyDecision;
@@ -717,15 +721,24 @@ export function describeApprovalProgress(
717
721
  const since = standing?.timestamp ?? new Date(0).toISOString();
718
722
  // #3206: count the humans the way the run will, back past facts re-recorded for this plan.
719
723
  const humansSince = standing && samePlanDigest(standing.planDigest, record.planDigest) ? humanQuorumSince(pending, standing) : since;
720
- const tally = tallyGateApprovals([...prior, record], record.gate, since, record.planDigest, approval, humansSince);
721
- const roles = approval.quorum?.roles ? ` with role ${approval.quorum.roles.join(" or ")}` : "";
724
+ const tally = tallyGateApprovals([...prior, record], record.gate, since, record.planDigest, approval, humansSince, judge);
722
725
  const who = tally.counted.map((r) => r.resolvedBy).join(", ") || "none yet";
723
- lines.push(`Quorum: ${tally.counted.length} of ${tally.need} human approval(s)${roles} for this plan (${who}).`);
726
+ if (!Array.isArray(approval.quorum)) {
727
+ const one = quorumRules(approval.quorum)[0];
728
+ const roles = one?.roles ? ` with role ${one.roles.join(" or ")}` : "";
729
+ lines.push(`Quorum: ${tally.counted.length} of ${tally.need} human approval(s)${roles} for this plan (${who}).`);
730
+ } else {
731
+ // #4290: one line per approval rule the gate takes.
732
+ for (const p of tally.rules ?? []) lines.push(`Quorum: ${quorumRuleLine(p)}.`);
733
+ }
724
734
  if (!tally.counted.includes(record)) {
735
+ const roles = quorumRules(approval.quorum).flatMap((r) => r.roles ?? []);
725
736
  lines.push(
726
737
  approverOf(record).kind === "agent"
727
738
  ? "An agent's approval does not count toward the quorum."
728
- : `This approval does not count toward the quorum: the approver claims none of its roles (${approval.quorum?.roles?.join(", ")}).`,
739
+ : judge(record).proven
740
+ ? `This approval does not count toward the quorum: .chant/trust.json at base gives ${record.resolvedBy} none of its roles (${[...new Set(roles)].join(", ")}).`
741
+ : `This approval does not count toward the quorum: its roles are read from .chant/trust.json at base, and only for an approval sealed by a signer listed at base (chant approve --sign).`,
729
742
  );
730
743
  }
731
744
  return lines;
@@ -21,6 +21,9 @@ import type { PrLoopPipelineOptions } from "../../components/pr-pipeline";
21
21
  * `review-rules` security group (#4168); off otherwise. `requireRunnerStart`
22
22
  * is `--require-runner-start`, or the `isolated-runners` group. `--apply-on-merge`
23
23
  * (#4168) writes the apply job on merge in place of the record job.
24
+ * `--pr-env` (#4298) adds the jobs of a pull request's environment.
25
+ * `--apply-before-merge` (#4301) writes the apply job that applies an open
26
+ * pull request before it merges, beside the record job.
24
27
  */
25
28
  function prLoopOption(args: CommandContext["args"], reportUrl: string | undefined, requireReview = false, requireRunnerStart = false): PrLoopPipelineOptions {
26
29
  return {
@@ -33,6 +36,8 @@ function prLoopOption(args: CommandContext["args"], reportUrl: string | undefine
33
36
  ...(args.requireReview === true || requireReview ? { requireReview: true } : {}),
34
37
  ...(args.requireRunnerStart === true || requireRunnerStart ? { requireRunnerStart: true } : {}),
35
38
  ...(args.applyOnMerge ? { applyOnMerge: true } : {}),
39
+ ...(args.prEnv ? { prEnvironment: true } : {}),
40
+ ...(args.applyBeforeMerge ? { applyBeforeMerge: true } : {}),
36
41
  };
37
42
  }
38
43
 
@@ -141,6 +146,17 @@ async function runGenerateComponents(ctx: CommandContext): Promise<number> {
141
146
  }
142
147
  }
143
148
 
149
+ // #4296: the plan and apply cloud identities ci.identity.cloud gives this pipeline's environment and member.
150
+ let identity: import("../../ci-identity").PipelineCloudIdentity | undefined;
151
+ if (found && args.prLoop) {
152
+ try {
153
+ identity = await (await import("../../workspace/ci-cloud-identity")).declaredCloudIdentity(resolve(args.path), args.env ?? "production", plan?.member.name);
154
+ } catch (err) {
155
+ console.error(formatError({ message: err instanceof Error ? err.message : String(err) }));
156
+ return 1;
157
+ }
158
+ }
159
+
144
160
  // Which lexicons support generate mode is a property of the loaded lexicon
145
161
  // plugins (those implementing `generateComponentPipeline`, #688), not a
146
162
  // hard-coded core list — `generateComponentsPipeline` returns a descriptive
@@ -161,7 +177,8 @@ async function runGenerateComponents(ctx: CommandContext): Promise<number> {
161
177
  ? { gatedWaves: { gate: args.waveGate, ...(args.canary?.length ? { canary: args.canary } : {}), ...(args.base ? { base: args.base } : {}) } }
162
178
  : {}),
163
179
  // #3183: a plan job per pull request and an apply job per merge.
164
- ...(args.prLoop ? { prLoop: prLoopOption(args, reportUrl, reviewRules, isolatedRunners) } : {}),
180
+ // #4292: on the branch ci.branches routes the member to, when it routes it.
181
+ ...(args.prLoop ? { prLoop: { ...prLoopOption(args, reportUrl, reviewRules, isolatedRunners), ...(plan?.branch ? { branch: plan.branch } : {}), ...(identity ? { identity } : {}) } } : {}),
165
182
  // #4002: the job image and the lines that install what it lacks, chant itself included.
166
183
  ...(args.image ? { image: args.image } : {}),
167
184
  ...(args.beforeScript?.length ? { beforeScript: args.beforeScript } : {}),