@intentius/chant 0.124.87 → 0.124.88

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 (342) hide show
  1. package/dist/action-pins.d.ts +1 -0
  2. package/dist/action-pins.d.ts.map +1 -1
  3. package/dist/action-pins.js +2 -0
  4. package/dist/actor.d.ts +12 -0
  5. package/dist/actor.d.ts.map +1 -0
  6. package/dist/actor.js +18 -0
  7. package/dist/bundle-check.d.ts +20 -5
  8. package/dist/bundle-check.d.ts.map +1 -1
  9. package/dist/bundle-check.js +20 -5
  10. package/dist/chant-install.d.ts +98 -0
  11. package/dist/chant-install.d.ts.map +1 -1
  12. package/dist/chant-install.js +204 -2
  13. package/dist/ci-commit.d.ts +1 -1
  14. package/dist/ci-commit.d.ts.map +1 -1
  15. package/dist/ci-commit.js +1 -2
  16. package/dist/ci-control.d.ts +1 -1
  17. package/dist/ci-control.d.ts.map +1 -1
  18. package/dist/ci-control.js +1 -1
  19. package/dist/ci-evidence-claims.d.ts +59 -0
  20. package/dist/ci-evidence-claims.d.ts.map +1 -0
  21. package/dist/ci-evidence-claims.js +87 -0
  22. package/dist/ci-evidence-from-job.d.ts +103 -0
  23. package/dist/ci-evidence-from-job.d.ts.map +1 -0
  24. package/dist/ci-evidence-from-job.js +162 -0
  25. package/dist/ci-evidence-jobs.d.ts +39 -4
  26. package/dist/ci-evidence-jobs.d.ts.map +1 -1
  27. package/dist/ci-evidence-jobs.js +38 -4
  28. package/dist/ci-handover.d.ts +12 -0
  29. package/dist/ci-handover.d.ts.map +1 -1
  30. package/dist/ci-handover.js +15 -3
  31. package/dist/ci-identity.d.ts +32 -6
  32. package/dist/ci-identity.d.ts.map +1 -1
  33. package/dist/ci-identity.js +40 -8
  34. package/dist/ci-image.d.ts +47 -9
  35. package/dist/ci-image.d.ts.map +1 -1
  36. package/dist/ci-image.js +45 -18
  37. package/dist/ci-jobs.d.ts +1 -1
  38. package/dist/ci-jobs.d.ts.map +1 -1
  39. package/dist/ci-jobs.js +7 -2
  40. package/dist/ci-login.d.ts +75 -13
  41. package/dist/ci-login.d.ts.map +1 -1
  42. package/dist/ci-login.js +89 -37
  43. package/dist/ci-product-words.d.ts +20 -1
  44. package/dist/ci-product-words.d.ts.map +1 -1
  45. package/dist/ci-product-words.js +27 -1
  46. package/dist/ci-product.d.ts +21 -2
  47. package/dist/ci-product.d.ts.map +1 -1
  48. package/dist/ci-product.js +21 -2
  49. package/dist/cli/handlers/approve-confirm.d.ts +14 -0
  50. package/dist/cli/handlers/approve-confirm.d.ts.map +1 -1
  51. package/dist/cli/handlers/approve-confirm.js +46 -0
  52. package/dist/cli/handlers/build.d.ts +1 -1
  53. package/dist/cli/handlers/build.d.ts.map +1 -1
  54. package/dist/cli/handlers/build.js +22 -1
  55. package/dist/cli/handlers/ci-check.d.ts.map +1 -1
  56. package/dist/cli/handlers/ci-check.js +21 -1
  57. package/dist/cli/handlers/ci-evidence.d.ts.map +1 -1
  58. package/dist/cli/handlers/ci-evidence.js +227 -18
  59. package/dist/cli/handlers/ci-forge-check.d.ts.map +1 -1
  60. package/dist/cli/handlers/ci-forge-check.js +34 -17
  61. package/dist/cli/handlers/generated-check.d.ts +3 -0
  62. package/dist/cli/handlers/generated-check.d.ts.map +1 -0
  63. package/dist/cli/handlers/generated-check.js +41 -0
  64. package/dist/cli/handlers/lifecycle.d.ts.map +1 -1
  65. package/dist/cli/handlers/lifecycle.js +3 -0
  66. package/dist/cli/handlers/local-chant.d.ts +13 -0
  67. package/dist/cli/handlers/local-chant.d.ts.map +1 -1
  68. package/dist/cli/handlers/local-chant.js +42 -1
  69. package/dist/cli/handlers/pr.d.ts.map +1 -1
  70. package/dist/cli/handlers/pr.js +42 -5
  71. package/dist/cli/handlers/run-wave.js +8 -0
  72. package/dist/cli/main.d.ts.map +1 -1
  73. package/dist/cli/main.js +38 -4
  74. package/dist/cli/parse-args.d.ts.map +1 -1
  75. package/dist/cli/parse-args.js +66 -0
  76. package/dist/cli/registry.d.ts +24 -0
  77. package/dist/cli/registry.d.ts.map +1 -1
  78. package/dist/components/check-hooks.d.ts +10 -0
  79. package/dist/components/check-hooks.d.ts.map +1 -1
  80. package/dist/components/check-hooks.js +18 -0
  81. package/dist/components/pr-checks.d.ts +105 -0
  82. package/dist/components/pr-checks.d.ts.map +1 -0
  83. package/dist/components/pr-checks.js +119 -0
  84. package/dist/components/pr-pipeline.d.ts +34 -0
  85. package/dist/components/pr-pipeline.d.ts.map +1 -1
  86. package/dist/components/pr-pipeline.js +14 -1
  87. package/dist/components/product-pipeline.d.ts +16 -1
  88. package/dist/components/product-pipeline.d.ts.map +1 -1
  89. package/dist/components/product-pipeline.js +17 -2
  90. package/dist/components/product-plan.d.ts +257 -4
  91. package/dist/components/product-plan.d.ts.map +1 -1
  92. package/dist/components/product-plan.js +241 -11
  93. package/dist/config.d.ts +10 -6
  94. package/dist/config.d.ts.map +1 -1
  95. package/dist/config.js +11 -6
  96. package/dist/control/consumers.d.ts +6 -0
  97. package/dist/control/consumers.d.ts.map +1 -1
  98. package/dist/control/consumers.js +6 -0
  99. package/dist/dead-guards.d.ts.map +1 -1
  100. package/dist/dead-guards.js +9 -6
  101. package/dist/discovery/files.d.ts +1 -1
  102. package/dist/discovery/files.js +1 -1
  103. package/dist/drift-issue.d.ts +20 -3
  104. package/dist/drift-issue.d.ts.map +1 -1
  105. package/dist/drift-issue.js +16 -0
  106. package/dist/drift-record.d.ts +45 -5
  107. package/dist/drift-record.d.ts.map +1 -1
  108. package/dist/drift-record.js +27 -6
  109. package/dist/floor-table.d.ts +6 -6
  110. package/dist/floor-table.d.ts.map +1 -1
  111. package/dist/floor-table.data.d.ts.map +1 -1
  112. package/dist/floor-table.data.js +58 -21
  113. package/dist/floor-table.js +10 -7
  114. package/dist/forge-check/contract.d.ts +8 -0
  115. package/dist/forge-check/contract.d.ts.map +1 -1
  116. package/dist/forge-check/contract.js +4 -1
  117. package/dist/forge-check/index.d.ts +2 -0
  118. package/dist/forge-check/index.d.ts.map +1 -1
  119. package/dist/forge-check/index.js +2 -0
  120. package/dist/forge-flags.d.ts +10 -0
  121. package/dist/forge-flags.d.ts.map +1 -1
  122. package/dist/forge-flags.js +31 -0
  123. package/dist/forge-remote.d.ts +47 -0
  124. package/dist/forge-remote.d.ts.map +1 -0
  125. package/dist/forge-remote.js +69 -0
  126. package/dist/generated-check.d.ts +74 -0
  127. package/dist/generated-check.d.ts.map +1 -0
  128. package/dist/generated-check.js +216 -0
  129. package/dist/lexicon.d.ts +16 -0
  130. package/dist/lexicon.d.ts.map +1 -1
  131. package/dist/lifecycle/publish-npm.d.ts +15 -0
  132. package/dist/lifecycle/publish-npm.d.ts.map +1 -1
  133. package/dist/lifecycle/publish-npm.js +49 -3
  134. package/dist/lifecycle/release-images.d.ts +22 -1
  135. package/dist/lifecycle/release-images.d.ts.map +1 -1
  136. package/dist/lifecycle/release-images.js +27 -3
  137. package/dist/lifecycle/release-ledger.d.ts +4 -3
  138. package/dist/lifecycle/release-ledger.d.ts.map +1 -1
  139. package/dist/lifecycle/release-ledger.js +3 -2
  140. package/dist/local-chant.d.ts +57 -3
  141. package/dist/local-chant.d.ts.map +1 -1
  142. package/dist/local-chant.js +122 -13
  143. package/dist/op/op-waves-evidence-jobs.d.ts +92 -0
  144. package/dist/op/op-waves-evidence-jobs.d.ts.map +1 -0
  145. package/dist/op/op-waves-evidence-jobs.js +112 -0
  146. package/dist/op/op-waves-evidence.d.ts +12 -1
  147. package/dist/op/op-waves-evidence.d.ts.map +1 -1
  148. package/dist/op/op-waves-evidence.js +23 -2
  149. package/dist/op/op-waves-run.d.ts +12 -1
  150. package/dist/op/op-waves-run.d.ts.map +1 -1
  151. package/dist/op/op-waves-run.js +54 -3
  152. package/dist/op/op-waves.d.ts +8 -0
  153. package/dist/op/op-waves.d.ts.map +1 -1
  154. package/dist/op/op-waves.js +10 -0
  155. package/dist/op/schedule-overdue.d.ts +39 -2
  156. package/dist/op/schedule-overdue.d.ts.map +1 -1
  157. package/dist/op/schedule-overdue.js +89 -7
  158. package/dist/pr-forge-reads.d.ts +21 -1
  159. package/dist/pr-forge-reads.d.ts.map +1 -1
  160. package/dist/pr-forge-reads.js +19 -1
  161. package/dist/pr-forge.d.ts +7 -1
  162. package/dist/pr-forge.d.ts.map +1 -1
  163. package/dist/pr-forge.js +7 -2
  164. package/dist/pr-plan-note.d.ts +24 -0
  165. package/dist/pr-plan-note.d.ts.map +1 -1
  166. package/dist/pr-plan-note.js +11 -1
  167. package/dist/pr-plan-record.d.ts +47 -0
  168. package/dist/pr-plan-record.d.ts.map +1 -0
  169. package/dist/pr-plan-record.js +89 -0
  170. package/dist/pr-post.d.ts +40 -0
  171. package/dist/pr-post.d.ts.map +1 -1
  172. package/dist/pr-post.js +79 -6
  173. package/dist/pr-requires.d.ts +8 -0
  174. package/dist/pr-requires.d.ts.map +1 -1
  175. package/dist/pr-requires.js +3 -1
  176. package/dist/ref-gate-init.d.ts +76 -0
  177. package/dist/ref-gate-init.d.ts.map +1 -0
  178. package/dist/ref-gate-init.js +144 -0
  179. package/dist/ref-gate-rules.d.ts +19 -0
  180. package/dist/ref-gate-rules.d.ts.map +1 -0
  181. package/dist/ref-gate-rules.js +17 -0
  182. package/dist/release-floors.d.ts +64 -16
  183. package/dist/release-floors.d.ts.map +1 -1
  184. package/dist/release-floors.js +65 -17
  185. package/dist/state-migration.d.ts +24 -1
  186. package/dist/state-migration.d.ts.map +1 -1
  187. package/dist/state-migration.js +39 -3
  188. package/dist/state-unlock.d.ts +32 -1
  189. package/dist/state-unlock.d.ts.map +1 -1
  190. package/dist/state-unlock.js +31 -0
  191. package/dist/wave-runtime.mjs +292 -285
  192. package/dist/workspace/ci-green-cli.d.ts.map +1 -1
  193. package/dist/workspace/ci-green-cli.js +13 -7
  194. package/dist/workspace/drift-cli.d.ts +1 -1
  195. package/dist/workspace/drift-cli.d.ts.map +1 -1
  196. package/dist/workspace/drift-cli.js +5 -12
  197. package/dist/workspace/forge-work.d.ts +3 -2
  198. package/dist/workspace/forge-work.d.ts.map +1 -1
  199. package/dist/workspace/forge-work.js +7 -17
  200. package/dist/workspace/lexicon-outputs.js +2 -2
  201. package/dist/workspace/release-workflow.d.ts +26 -3
  202. package/dist/workspace/release-workflow.d.ts.map +1 -1
  203. package/dist/workspace/release-workflow.js +48 -6
  204. package/dist/workspace/trust/check-evidence-report.d.ts +18 -0
  205. package/dist/workspace/trust/check-evidence-report.d.ts.map +1 -1
  206. package/dist/workspace/trust/check-evidence-report.js +13 -0
  207. package/dist/workspace/trust/check-evidence.d.ts +13 -1
  208. package/dist/workspace/trust/check-evidence.d.ts.map +1 -1
  209. package/dist/workspace/trust/check-evidence.js +8 -3
  210. package/dist/workspace/trust/evidence.d.ts +5 -0
  211. package/dist/workspace/trust/evidence.d.ts.map +1 -1
  212. package/dist/workspace/trust/evidence.js +5 -0
  213. package/dist/workspace/trust/open-evidence.d.ts +67 -0
  214. package/dist/workspace/trust/open-evidence.d.ts.map +1 -0
  215. package/dist/workspace/trust/open-evidence.js +92 -0
  216. package/dist/workspace/trust/ref-gate-cli.d.ts.map +1 -1
  217. package/dist/workspace/trust/ref-gate-cli.js +65 -3
  218. package/dist/workspace/trust/ref-gate.d.ts +61 -2
  219. package/dist/workspace/trust/ref-gate.d.ts.map +1 -1
  220. package/dist/workspace/trust/ref-gate.js +72 -7
  221. package/package.json +1 -1
  222. package/src/action-pins.ts +2 -0
  223. package/src/actor.test.ts +12 -0
  224. package/src/actor.ts +19 -0
  225. package/src/bundle-check.test.ts +22 -0
  226. package/src/bundle-check.ts +33 -5
  227. package/src/chant-install.test.ts +109 -1
  228. package/src/chant-install.ts +243 -2
  229. package/src/ci-commit.test.ts +51 -5
  230. package/src/ci-commit.ts +1 -2
  231. package/src/ci-control.ts +1 -0
  232. package/src/ci-evidence-claims.ts +102 -0
  233. package/src/ci-evidence-from-job.test.ts +147 -0
  234. package/src/ci-evidence-from-job.ts +195 -0
  235. package/src/ci-evidence-jobs.ts +41 -4
  236. package/src/ci-handover.ts +16 -3
  237. package/src/ci-identity.test.ts +3 -3
  238. package/src/ci-identity.ts +51 -11
  239. package/src/ci-image.test.ts +60 -10
  240. package/src/ci-image.ts +78 -19
  241. package/src/ci-jobs.ts +7 -2
  242. package/src/ci-login.test.ts +131 -3
  243. package/src/ci-login.token-drop.test.ts +204 -0
  244. package/src/ci-login.ts +137 -39
  245. package/src/ci-product-words.ts +30 -0
  246. package/src/ci-product.ts +26 -1
  247. package/src/cli/commands/__fixtures__/source-dir-root/migrations/0001-init/backfill.ts +3 -0
  248. package/src/cli/handlers/approve-confirm.test.ts +35 -0
  249. package/src/cli/handlers/approve-confirm.ts +44 -0
  250. package/src/cli/handlers/build-source-dir.test.ts +4 -0
  251. package/src/cli/handlers/build.ts +20 -2
  252. package/src/cli/handlers/ci-check.ts +19 -1
  253. package/src/cli/handlers/ci-evidence-open.test.ts +164 -0
  254. package/src/cli/handlers/ci-evidence.ts +210 -16
  255. package/src/cli/handlers/ci-forge-check.ts +22 -9
  256. package/src/cli/handlers/generated-check.ts +39 -0
  257. package/src/cli/handlers/lifecycle.test.ts +20 -0
  258. package/src/cli/handlers/lifecycle.ts +4 -0
  259. package/src/cli/handlers/local-chant.ts +39 -1
  260. package/src/cli/handlers/pr.ts +43 -5
  261. package/src/cli/handlers/run-wave.ts +7 -0
  262. package/src/cli/main.ts +38 -4
  263. package/src/cli/parse-args.ts +46 -0
  264. package/src/cli/registry.ts +24 -0
  265. package/src/components/check-hooks.ts +22 -0
  266. package/src/components/check-report-summary.test.ts +78 -0
  267. package/src/components/pr-checks.ts +159 -0
  268. package/src/components/pr-pipeline.ts +41 -1
  269. package/src/components/product-pipeline.ts +25 -3
  270. package/src/components/product-plan.test.ts +102 -1
  271. package/src/components/product-plan.ts +416 -15
  272. package/src/config.ts +13 -8
  273. package/src/control/consumers.ts +7 -0
  274. package/src/dead-guards.test.ts +27 -5
  275. package/src/dead-guards.ts +9 -6
  276. package/src/discovery/files.ts +1 -1
  277. package/src/drift-issue.test.ts +29 -1
  278. package/src/drift-issue.ts +28 -3
  279. package/src/drift-record.test.ts +25 -0
  280. package/src/drift-record.ts +55 -6
  281. package/src/floor-table.data.ts +58 -21
  282. package/src/floor-table.ts +12 -9
  283. package/src/forge-check/contract.ts +11 -1
  284. package/src/forge-check/forge-check.test.ts +8 -0
  285. package/src/forge-check/index.ts +2 -0
  286. package/src/forge-flags.test.ts +25 -1
  287. package/src/forge-flags.ts +34 -0
  288. package/src/forge-remote.test.ts +37 -0
  289. package/src/forge-remote.ts +79 -0
  290. package/src/generated-check.e2e.test.ts +98 -0
  291. package/src/generated-check.test.ts +104 -0
  292. package/src/generated-check.ts +269 -0
  293. package/src/lexicon.ts +17 -0
  294. package/src/lifecycle/publish-npm.ts +56 -3
  295. package/src/lifecycle/release-catalog.test.ts +2 -2
  296. package/src/lifecycle/release-images-dockerfile.test.ts +20 -0
  297. package/src/lifecycle/release-images.test.ts +44 -0
  298. package/src/lifecycle/release-images.ts +39 -3
  299. package/src/lifecycle/release-ledger.ts +4 -3
  300. package/src/local-chant.e2e.test.ts +81 -6
  301. package/src/local-chant.test.ts +22 -3
  302. package/src/local-chant.ts +130 -13
  303. package/src/op/op-waves-evidence-jobs.ts +134 -0
  304. package/src/op/op-waves-evidence.test.ts +36 -3
  305. package/src/op/op-waves-evidence.ts +23 -3
  306. package/src/op/op-waves-run.ts +57 -2
  307. package/src/op/op-waves.ts +11 -0
  308. package/src/op/schedule-overdue.test.ts +83 -1
  309. package/src/op/schedule-overdue.ts +107 -9
  310. package/src/pr-forge-reads-compare.test.ts +2 -1
  311. package/src/pr-forge-reads.ts +37 -1
  312. package/src/pr-forge.ts +14 -3
  313. package/src/pr-plan-note.ts +32 -3
  314. package/src/pr-plan-record.test.ts +75 -0
  315. package/src/pr-plan-record.ts +101 -0
  316. package/src/pr-post-plan-note.test.ts +60 -0
  317. package/src/pr-post.test.ts +30 -0
  318. package/src/pr-post.ts +110 -6
  319. package/src/pr-requires.test.ts +20 -0
  320. package/src/pr-requires.ts +10 -1
  321. package/src/ref-gate-init.ts +189 -0
  322. package/src/ref-gate-rules.ts +26 -0
  323. package/src/release-floors.ts +86 -17
  324. package/src/state-migration-record.test.ts +90 -0
  325. package/src/state-migration.test.ts +1 -1
  326. package/src/state-migration.ts +52 -3
  327. package/src/state-unlock.test.ts +33 -1
  328. package/src/state-unlock.ts +49 -1
  329. package/src/workspace/ci-green-cli.ts +12 -6
  330. package/src/workspace/drift-cli.ts +6 -18
  331. package/src/workspace/forge-work.ts +7 -14
  332. package/src/workspace/lexicon-outputs.ts +2 -2
  333. package/src/workspace/release-workflow.test.ts +70 -0
  334. package/src/workspace/release-workflow.ts +56 -8
  335. package/src/workspace/trust/check-evidence-report.ts +24 -0
  336. package/src/workspace/trust/check-evidence.ts +17 -5
  337. package/src/workspace/trust/evidence.ts +5 -0
  338. package/src/workspace/trust/open-evidence.ts +129 -0
  339. package/src/workspace/trust/ref-gate-cli.ts +59 -3
  340. package/src/workspace/trust/ref-gate-pieces.test.ts +175 -0
  341. package/src/workspace/trust/ref-gate.e2e.test.ts +17 -0
  342. package/src/workspace/trust/ref-gate.ts +87 -6
@@ -0,0 +1,147 @@
1
+ /**
2
+ * #4926: `chant ci evidence sign --from-job` against a fake forge. It signs
3
+ * only the checks whose steps passed, refuses a job of another commit or
4
+ * run, gives a failed policy step no `policy:` evidence whatever its claim
5
+ * file says, and each statement names the run, job and step it relied on.
6
+ * The forge's job records come through the real reads with a fake `fetch`;
7
+ * the signing is a real runner key over a local repository.
8
+ */
9
+
10
+ import { execFileSync } from "node:child_process";
11
+ import { generateKeyPairSync } from "node:crypto";
12
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import { describe, expect, test } from "vitest";
16
+ import type { ForgeFetch } from "./pr-forge";
17
+ import { githubReads, gitlabReads, type ForgeReads, type RunJob } from "./pr-forge-reads";
18
+ import { checksFromJob, signFromJob } from "./ci-evidence-from-job";
19
+ import { checkClaimFileName, parseEvidenceSources, readCheckClaimFile, writeCheckClaimFile } from "./ci-evidence-claims";
20
+ import { loadRunnerKey } from "./workspace/trust/dsse";
21
+ import { readCheckEvidence } from "./workspace/trust/check-evidence";
22
+
23
+ const SHA = "a".repeat(40);
24
+ const PLAN_STEP = "Plan, gate and apply wave 1 (dev)";
25
+ const POLICY_STEP = "Check wave 1 (dev)'s plans against the policy";
26
+ const SOURCES = { "plan:dev": { step: PLAN_STEP }, "policy:dev": { step: POLICY_STEP } };
27
+
28
+ /** A run's jobs as GitHub lists them, through the real reads. */
29
+ function githubRun(run: number, jobs: unknown[]): Pick<ForgeReads, "runJobs"> {
30
+ const fetch: ForgeFetch = async (url) => {
31
+ const u = new URL(url);
32
+ if (u.pathname !== `/repos/acme/infra/actions/runs/${run}/jobs`) return { ok: false, status: 404, text: async () => "{}" };
33
+ return { ok: true, status: 200, text: async () => JSON.stringify({ total_count: jobs.length, jobs }) };
34
+ };
35
+ return githubReads({ apiBase: "https://api.github.com", repo: "acme/infra", token: "t", fetch });
36
+ }
37
+
38
+ const step = (name: string, conclusion: string, number: number) => ({ name, status: "completed", conclusion, number });
39
+ const waveJob = (over: Record<string, unknown> = {}, steps = [step(POLICY_STEP, "success", 4), step(PLAN_STEP, "success", 5)]) => ({ id: 77, run_id: 9, name: "wave-1-dev", status: "completed", conclusion: "success", head_sha: SHA, steps, ...over });
40
+
41
+ describe("the forge's record of a job (#4926)", () => {
42
+ test("github and forgejo name the commit and the steps; gitlab names the pipeline's commit and no steps", async () => {
43
+ const [job] = await githubRun(9, [waveJob()]).runJobs(9);
44
+ expect(job).toMatchObject({ id: 77, run: 9, headSha: SHA, conclusion: "success" });
45
+ expect(job!.steps).toEqual([{ name: POLICY_STEP, number: 4, status: "completed", conclusion: "success" }, { name: PLAN_STEP, number: 5, status: "completed", conclusion: "success" }]);
46
+ const fetch: ForgeFetch = async () => ({ ok: true, status: 200, text: async () => JSON.stringify([{ id: 5, name: "wave-1-dev-policy", status: "failed", pipeline: { id: 9, sha: SHA }, commit: { id: SHA } }]) });
47
+ const [gl] = await gitlabReads({ apiBase: "https://gitlab.com/api/v4", project: "acme/infra", token: "t", fetch }).runJobs(9);
48
+ expect(gl).toEqual({ id: 5, name: "wave-1-dev-policy", status: "failed", done: true, run: 9, headSha: SHA });
49
+ });
50
+ });
51
+
52
+ describe("which checks a job's record lets the evidence job sign (#4926)", () => {
53
+ const claims = (files: Array<{ check: string; passed: boolean; claim?: string }>): string => {
54
+ const dir = mkdtempSync(join(tmpdir(), "chant-4926-claims-"));
55
+ for (const f of files) writeCheckClaimFile(dir, f);
56
+ return dir;
57
+ };
58
+
59
+ test("signs only the checks whose steps passed, each with the run, job and step it read", async () => {
60
+ const reads = githubRun(9, [waveJob({}, [step(POLICY_STEP, "failure", 4), step(PLAN_STEP, "success", 5)])]);
61
+ const got = await checksFromJob({ reads, run: 9, sha: SHA, fromJob: "wave-1-dev", checks: ["plan:dev", "policy:dev"], sources: SOURCES });
62
+ expect(got).toEqual({
63
+ sign: [{ check: "plan:dev", source: { run: 9, job: 77, step: PLAN_STEP } }],
64
+ skipped: [{ check: "policy:dev", reason: `step ${JSON.stringify(POLICY_STEP)} of job wave-1-dev concluded failure` }],
65
+ });
66
+ });
67
+
68
+ test("a failed policy step gets no policy evidence even when its claim file says it passed", async () => {
69
+ const dir = claims([{ check: "plan:dev", passed: true, claim: "sha256:1" }, { check: "policy:dev", passed: true, claim: "[]" }]);
70
+ const reads = githubRun(9, [waveJob({ conclusion: "failure" }, [step(POLICY_STEP, "failure", 4), step(PLAN_STEP, "success", 5)])]);
71
+ const got = await checksFromJob({ reads, run: 9, sha: SHA, fromJob: "wave-1-dev", checks: ["plan:dev", "policy:dev"], sources: SOURCES, claims: dir });
72
+ expect("sign" in got && got.sign.map((s) => [s.check, s.claim])).toEqual([["plan:dev", "sha256:1"]]);
73
+ });
74
+
75
+ test("a passed step whose claim file says the check did not pass, or left none, signs nothing", async () => {
76
+ const dir = claims([{ check: "policy:dev", passed: false }]);
77
+ const got = await checksFromJob({ reads: githubRun(9, [waveJob()]), run: 9, sha: SHA, fromJob: "wave-1-dev", checks: ["plan:dev", "policy:dev"], sources: SOURCES, claims: dir });
78
+ expect(got).toEqual({
79
+ sign: [],
80
+ skipped: [
81
+ { check: "plan:dev", reason: `the job left no readable ${checkClaimFileName("plan:dev")}` },
82
+ { check: "policy:dev", reason: "job wave-1-dev's claim file says policy:dev did not pass" },
83
+ ],
84
+ });
85
+ });
86
+
87
+ test("a job of another commit or another run is refused", async () => {
88
+ const other = "b".repeat(40);
89
+ expect(await checksFromJob({ reads: githubRun(9, [waveJob({ head_sha: other })]), run: 9, sha: SHA, fromJob: "wave-1-dev", checks: ["plan:dev"], sources: SOURCES })).toEqual({
90
+ refused: `job wave-1-dev (77) ran for commit ${other.slice(0, 12)}, not this run's ${SHA.slice(0, 12)}`,
91
+ });
92
+ expect(await checksFromJob({ reads: githubRun(9, [waveJob({ run_id: 8 })]), run: 9, sha: SHA, fromJob: "wave-1-dev", checks: ["plan:dev"], sources: SOURCES })).toEqual({ refused: "job wave-1-dev (77) belongs to run 8, not this run 9" });
93
+ expect(await checksFromJob({ reads: githubRun(9, []), run: 9, sha: SHA, fromJob: "wave-1-dev", checks: ["plan:dev"] })).toEqual({ refused: "run 9 has no job named wave-1-dev" });
94
+ });
95
+
96
+ test("on gitlab a check is read from its job's status, the policy from the policy job", async () => {
97
+ const jobs: RunJob[] = [
98
+ { id: 40, name: "wave-1-dev", status: "success", done: true, run: 9, headSha: SHA },
99
+ { id: 41, name: "wave-1-dev-policy", status: "failed", done: true, run: 9, headSha: SHA },
100
+ ];
101
+ const got = await checksFromJob({ reads: { runJobs: async () => jobs }, run: 9, sha: SHA, fromJob: "wave-1-dev", checks: ["plan:dev", "policy:dev"], sources: { "policy:dev": { job: "wave-1-dev-policy" } } });
102
+ expect(got).toEqual({ sign: [{ check: "plan:dev", source: { run: 9, job: 40 } }], skipped: [{ check: "policy:dev", reason: "job wave-1-dev-policy ended failed" }] });
103
+ });
104
+
105
+ test("the sources and claim files read as data", () => {
106
+ expect(parseEvidenceSources('{"plan:dev":"Plan","policy:dev":{"job":"p"}}')).toEqual({ sources: { "plan:dev": { step: "Plan" }, "policy:dev": { job: "p" } } });
107
+ expect(parseEvidenceSources("[]")).toHaveProperty("problem");
108
+ const dir = mkdtempSync(join(tmpdir(), "chant-4926-claim-"));
109
+ writeFileSync(join(dir, checkClaimFileName("policy:dev")), JSON.stringify({ check: "policy:prod", passed: true }));
110
+ expect(readCheckClaimFile(dir, "policy:dev")).toEqual({ problem: "policy-dev.json is not policy:dev's claim file" });
111
+ });
112
+ });
113
+
114
+ function git(cwd: string, ...args: string[]): string {
115
+ return execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "init.defaultBranch=main", ...args], { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
116
+ }
117
+
118
+ describe("signFromJob (#4926)", () => {
119
+ test("signs the passed checks over the run's commit, with the source in the statement, and refuses another commit", async () => {
120
+ const cwd = mkdtempSync(join(tmpdir(), "chant-4926-sign-"));
121
+ const { privateKey } = generateKeyPairSync("ed25519");
122
+ const pem = privateKey.export({ format: "pem", type: "pkcs8" }).toString();
123
+ git(cwd, "init", "--quiet");
124
+ mkdirSync(join(cwd, ".chant"));
125
+ writeFileSync(join(cwd, ".chant/trust.json"), JSON.stringify({ schema: 1, runners: [{ principal: "ci", class: "runner", key: loadRunnerKey(pem).publicKey }] }));
126
+ git(cwd, "add", ".");
127
+ git(cwd, "commit", "--quiet", "-m", "base");
128
+ const base = git(cwd, "rev-parse", "HEAD");
129
+ writeFileSync(join(cwd, "main.tf"), "# change\n");
130
+ git(cwd, "add", "main.tf");
131
+ git(cwd, "commit", "--quiet", "-m", "merge");
132
+ const head = git(cwd, "rev-parse", "HEAD");
133
+ const reads = githubRun(9, [waveJob({ head_sha: head }, [step(POLICY_STEP, "failure", 4), step(PLAN_STEP, "success", 5)])]);
134
+ const env = { GITHUB_RUN_ID: "9", GITHUB_SHA: head, CHANT_EVIDENCE_SOURCES: JSON.stringify(SOURCES) } as NodeJS.ProcessEnv;
135
+ const logs: string[] = [];
136
+ const done = await signFromJob({ repo: cwd, base, fromJob: "wave-1-dev", checks: ["plan:dev", "policy:dev"], reads, env, key: pem, push: false, log: (l) => logs.push(l) });
137
+ expect(done).toMatchObject({ signed: [{ check: "plan:dev", runner: "ci", commit: head, source: { run: 9, job: 77, step: PLAN_STEP } }] });
138
+ expect((await readCheckEvidence(cwd, head, base, ["plan:dev", "policy:dev"])).map((v) => v.status)).toEqual(["current", "missing"]);
139
+ const note = git(cwd, "notes", "--ref", "refs/notes/chant/evidence", "show", head);
140
+ const statement = JSON.parse(Buffer.from(JSON.parse(note.split("\n")[0]!).payload, "base64").toString("utf8"));
141
+ expect(statement.predicate.source).toEqual({ run: 9, job: 77, step: PLAN_STEP });
142
+ expect(logs.some((l) => l.startsWith("ci evidence: policy:dev not signed: step"))).toBe(true);
143
+ expect(await signFromJob({ repo: cwd, base, fromJob: "wave-1-dev", checks: ["plan:dev"], at: base, reads, env, key: pem, push: false, log: () => {} })).toEqual({
144
+ refused: `--at names ${base.slice(0, 12)}, and this run is for ${head.slice(0, 12)}; --from-job signs only the run's own commit`,
145
+ });
146
+ });
147
+ });
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Which checks a job outside the check's own may sign (#4926): `chant ci
3
+ * evidence sign --from-job <job>`, the evidence job after a wave job.
4
+ *
5
+ * The wave job runs the change's code, so whatever could sign in it could
6
+ * sign a check that never passed, and a wave that trades cloud credentials
7
+ * can request no signing token after the trade anyway. The evidence job runs
8
+ * none of that code. It reads the wave job's own record from the forge
9
+ * (./pr-forge-reads.ts `runJobs`) with the job token and signs a check only
10
+ * when:
11
+ *
12
+ * - the job it names ran in this run, for this commit: a job of another run
13
+ * or commit refuses the whole command;
14
+ * - the forge reports the check's step (GitHub, Forgejo) or job (GitLab,
15
+ * which reports no steps) finished with `success`. Change code can fail or
16
+ * pass its own steps, but it cannot make the forge report a passing policy
17
+ * step whose command failed;
18
+ * - with `claims`, the step's claim file (./ci-evidence-claims.ts) says the
19
+ * check passed. Its claim, such as the policy rows, is what the statement
20
+ * digests.
21
+ *
22
+ * Each check signed carries `source: { run, job, step }`, the ids it relied
23
+ * on, so a verifier can look them up.
24
+ */
25
+
26
+ import type { ForgeReads, RunJob } from "./pr-forge-reads";
27
+ import { commitAndTree, noRunnerIdentity, recordChecks, runnerEvidenceSigner, signChecks, type CheckSource } from "./workspace/trust/check-evidence";
28
+ import { EVIDENCE_SOURCES_ENV, parseEvidenceSources, readCheckClaimFile, type EvidenceSourceSpec } from "./ci-evidence-claims";
29
+
30
+ /** What {@link checksFromJob} reads. */
31
+ export interface ChecksFromJobInput {
32
+ reads: Pick<ForgeReads, "runJobs">;
33
+ /** This run's id: `GITHUB_RUN_ID`, `CI_PIPELINE_ID`. */
34
+ run: number;
35
+ /** This run's commit: `GITHUB_SHA`, `CI_COMMIT_SHA`. */
36
+ sha: string;
37
+ /** The job the checks ran in, by name. */
38
+ fromJob: string;
39
+ checks: readonly string[];
40
+ /** Each check's job and step; a check with none is read from `fromJob`'s own result. */
41
+ sources?: Readonly<Record<string, EvidenceSourceSpec>>;
42
+ /** The directory of the jobs' claim files. Without it, a check needs only its step's success and signs no claim. */
43
+ claims?: string;
44
+ }
45
+
46
+ /** What may be signed, and what not and why. */
47
+ export type ChecksFromJob =
48
+ | { sign: Array<{ check: string; claim?: string; source: CheckSource }>; skipped: Array<{ check: string; reason: string }> }
49
+ | { refused: string };
50
+
51
+ const SUCCESS = "success";
52
+
53
+ /** Whether the forge reports `job` passed: GitHub's and Forgejo's conclusion, GitLab's status. */
54
+ function jobPassed(job: RunJob): boolean {
55
+ return job.conclusion !== undefined ? job.conclusion === SUCCESS : job.status === SUCCESS;
56
+ }
57
+
58
+ /** The checks the run's record lets this job sign (#4926), or why the job it names does not count at all. */
59
+ export async function checksFromJob(input: ChecksFromJobInput): Promise<ChecksFromJob> {
60
+ const jobs = await input.reads.runJobs(input.run);
61
+ const found = new Map<string, RunJob | string>();
62
+ const jobNamed = (name: string): RunJob | string => {
63
+ const had = found.get(name);
64
+ if (had !== undefined) return had;
65
+ const named = jobs.filter((j) => j.name === name);
66
+ let got: RunJob | string;
67
+ if (named.length === 0) got = `run ${input.run} has no job named ${name}`;
68
+ else if (named.length > 1) got = `run ${input.run} has ${named.length} jobs named ${name}, so which one ran the check is not known`;
69
+ else {
70
+ const j = named[0]!;
71
+ if (j.run !== undefined && j.run !== input.run) got = `job ${name} (${j.id}) belongs to run ${j.run}, not this run ${input.run}`;
72
+ else if (j.headSha === undefined) got = `the forge names no commit for job ${name} (${j.id}), so it cannot be bound to ${input.sha.slice(0, 12)}`;
73
+ else if (j.headSha !== input.sha) got = `job ${name} (${j.id}) ran for commit ${j.headSha.slice(0, 12)}, not this run's ${input.sha.slice(0, 12)}`;
74
+ else got = j;
75
+ }
76
+ found.set(name, got);
77
+ return got;
78
+ };
79
+ const sign: Array<{ check: string; claim?: string; source: CheckSource }> = [];
80
+ const skipped: Array<{ check: string; reason: string }> = [];
81
+ for (const check of input.checks) {
82
+ const spec = input.sources?.[check] ?? {};
83
+ const name = spec.job ?? input.fromJob;
84
+ const job = jobNamed(name);
85
+ if (typeof job === "string") return { refused: job };
86
+ if (!job.done) {
87
+ skipped.push({ check, reason: `job ${name} has not finished (${job.status})` });
88
+ continue;
89
+ }
90
+ let step: string | undefined;
91
+ if (spec.step !== undefined) {
92
+ if (!job.steps) {
93
+ skipped.push({ check, reason: `the forge lists no steps for job ${name}` });
94
+ continue;
95
+ }
96
+ const s = job.steps.filter((x) => x.name === spec.step);
97
+ if (s.length !== 1) {
98
+ skipped.push({ check, reason: s.length === 0 ? `job ${name} has no step named ${JSON.stringify(spec.step)}` : `job ${name} has ${s.length} steps named ${JSON.stringify(spec.step)}` });
99
+ continue;
100
+ }
101
+ if (s[0]!.conclusion !== SUCCESS) {
102
+ skipped.push({ check, reason: `step ${JSON.stringify(spec.step)} of job ${name} concluded ${s[0]!.conclusion ?? s[0]!.status}` });
103
+ continue;
104
+ }
105
+ step = spec.step;
106
+ } else if (!jobPassed(job)) {
107
+ skipped.push({ check, reason: `job ${name} ended ${job.conclusion ?? job.status}` });
108
+ continue;
109
+ }
110
+ let claim: string | undefined;
111
+ if (input.claims !== undefined) {
112
+ const file = readCheckClaimFile(input.claims, check);
113
+ if ("problem" in file) {
114
+ skipped.push({ check, reason: file.problem });
115
+ continue;
116
+ }
117
+ if (!file.passed) {
118
+ skipped.push({ check, reason: `job ${name}'s claim file says ${check} did not pass` });
119
+ continue;
120
+ }
121
+ claim = file.claim;
122
+ }
123
+ sign.push({ check, ...(claim !== undefined ? { claim } : {}), source: { run: input.run, job: job.id, ...(step ? { step } : {}) } });
124
+ }
125
+ return { sign, skipped };
126
+ }
127
+
128
+ /** What {@link signFromJob} does in a job. */
129
+ export interface SignFromJobInput {
130
+ repo: string;
131
+ /** The commit whose `.chant/trust.json` lists the runner identities. */
132
+ base: string;
133
+ fromJob: string;
134
+ checks: readonly string[];
135
+ claims?: string;
136
+ /** The commit to sign. Default: the run's commit. It must be the run's commit. */
137
+ at?: string;
138
+ reads: Pick<ForgeReads, "runJobs">;
139
+ env?: NodeJS.ProcessEnv;
140
+ /** The runner key in place of `CHANT_RUNNER_KEY`. */
141
+ key?: string;
142
+ push?: boolean;
143
+ fetch?: typeof fetch;
144
+ log?: (line: string) => void;
145
+ }
146
+
147
+ /** What {@link signFromJob} signed and skipped, or why it refused. */
148
+ export type SignFromJobResult =
149
+ | { signed: Array<{ check: string; runner: string; commit: string; tree: string; source: CheckSource }>; skipped: Array<{ check: string; reason: string }>; pushWarning?: string }
150
+ | { refused: string };
151
+
152
+ /**
153
+ * `chant ci evidence sign --from-job` (#4926): this run's id and commit from
154
+ * the job's environment (`GITHUB_RUN_ID` and `GITHUB_SHA` on GitHub and
155
+ * Forgejo, `CI_PIPELINE_ID` and `CI_COMMIT_SHA` on GitLab), the sources from
156
+ * `CHANT_EVIDENCE_SOURCES`, the checks {@link checksFromJob} allows, signed
157
+ * with the job's runner identity and pushed. Without a runner identity it
158
+ * signs nothing and says so, as `sign` does.
159
+ */
160
+ export async function signFromJob(input: SignFromJobInput): Promise<SignFromJobResult> {
161
+ const env = input.env ?? process.env;
162
+ const log = input.log ?? ((line: string) => console.error(line));
163
+ const rawRun = env.GITHUB_RUN_ID ?? env.CI_PIPELINE_ID;
164
+ const sha = env.GITHUB_SHA ?? env.CI_COMMIT_SHA;
165
+ if (!rawRun || !/^\d+$/.test(rawRun) || !sha) return { refused: "--from-job reads this run from the job's environment: GITHUB_RUN_ID and GITHUB_SHA, or CI_PIPELINE_ID and CI_COMMIT_SHA" };
166
+ let commit: string;
167
+ try {
168
+ commit = commitAndTree(input.repo, input.at ?? sha).commit;
169
+ } catch {
170
+ return { refused: `${input.at ?? sha} is not a commit in this checkout; fetch the run's commit first` };
171
+ }
172
+ if (commit !== sha) return { refused: `--at names ${commit.slice(0, 12)}, and this run is for ${sha.slice(0, 12)}; --from-job signs only the run's own commit` };
173
+ const parsed = parseEvidenceSources(env[EVIDENCE_SOURCES_ENV]);
174
+ if ("problem" in parsed) return { refused: parsed.problem };
175
+ const decided = await checksFromJob({ reads: input.reads, run: Number(rawRun), sha, fromJob: input.fromJob, checks: input.checks, sources: parsed.sources, ...(input.claims !== undefined ? { claims: input.claims } : {}) });
176
+ if ("refused" in decided) return decided;
177
+ for (const s of decided.skipped) log(`ci evidence: ${s.check} not signed: ${s.reason}`);
178
+ if (decided.sign.length === 0) return { signed: [], skipped: decided.skipped };
179
+ const signer = await runnerEvidenceSigner(input.repo, input.base, { env, ...(input.key ? { key: input.key } : {}), ...(input.fetch ? { fetch: input.fetch } : {}) });
180
+ if (!signer) {
181
+ log(`ci evidence: ${noRunnerIdentity()}, so no check was signed`);
182
+ return { signed: [], skipped: [...decided.skipped, ...decided.sign.map((s) => ({ check: s.check, reason: noRunnerIdentity() }))] };
183
+ }
184
+ const signed = await signChecks(input.repo, commit, decided.sign, signer);
185
+ const pushed = await recordChecks(input.repo, signed, { push: input.push !== false });
186
+ const bySource = new Map(decided.sign.map((s) => [s.check, s.source]));
187
+ for (const s of signed) log(`ci evidence: signed ${s.check} at ${s.commit.slice(0, 12)} as ${s.runner}, from job ${bySource.get(s.check)!.job}${bySource.get(s.check)!.step ? ` step ${JSON.stringify(bySource.get(s.check)!.step)}` : ""} of run ${rawRun}`);
188
+ const warning = input.push !== false && !pushed.pushed ? pushed.pushWarning : undefined;
189
+ if (warning) log(`ci evidence: the evidence is attached here, and the push did not land: ${warning}`);
190
+ return {
191
+ signed: signed.map((s) => ({ check: s.check, runner: s.runner, commit: s.commit, tree: s.tree, source: bySource.get(s.check)! })),
192
+ skipped: decided.skipped,
193
+ ...(warning ? { pushWarning: warning } : {}),
194
+ };
195
+ }
@@ -14,11 +14,20 @@
14
14
  * before posting the note, which then says which checks were signed. The
15
15
  * key is in that one step, in a job that runs none of the change's code.
16
16
  * GitLab posts its notes from a target-branch pipeline that reads every
17
- * open merge request, so there a job of its own after each plan job
18
- * (`<plan job>-evidence`) signs from the plan job's artifact.
17
+ * open merge request, so there a job of its own in that pipeline, before
18
+ * the note job (`<plan job>-evidence`), signs from each merge request's
19
+ * plan job artifact (#4914): a merge request pipeline is built from the
20
+ * change's own files, so no job in it may hold the key. The signing job
21
+ * names the environment {@link GITLAB_EVIDENCE_ENVIRONMENT}, which the
22
+ * key's variable is scoped to, protected; the jobs that run the change
23
+ * name none, so GitLab never hands them the key.
19
24
  * - A wave job (the waves pipeline) gets the key on its `chant run wave`
20
25
  * step, and signs `plan:<wave>` and `policy:<wave>` once the wave is
21
- * planned (../op/op-waves-evidence.ts).
26
+ * planned (../op/op-waves-evidence.ts). A wave with a policy runs it as a
27
+ * step of its own and a `<wave job>-evidence` job signs `policy:<wave>`
28
+ * from that step's result; a wave that trades cloud credentials and signs
29
+ * keyless signs `plan:<wave>` there too (#4926,
30
+ * ./op/op-waves-evidence-jobs.ts).
22
31
  * - A product's check job runs `chant ci check` with the key in
23
32
  * `CHANT_RUNNER_KEY`; the check runner signs each hook (./components/check-steps.ts).
24
33
  *
@@ -45,7 +54,35 @@ export const EVIDENCE_ID_TOKEN_VAR = "CHANT_ID_TOKEN_SIGSTORE";
45
54
  /** The audience a keyless signing job's token is requested for unless told: sigstore's. */
46
55
  export const EVIDENCE_DEFAULT_AUDIENCE = "sigstore";
47
56
 
48
- export { CHECK_EVIDENCE_FLOOR, KEYLESS_EVIDENCE_FLOOR, LOCAL_EVIDENCE_FLOOR } from "./release-floors";
57
+ export { CHECK_EVIDENCE_FLOOR, CHECK_JOB_FLOOR, GITLAB_OPEN_EVIDENCE_FLOOR, KEYLESS_EVIDENCE_FLOOR, LOCAL_EVIDENCE_FLOOR, PR_LOOP_EVIDENCE_FLOOR, REF_GATE_STATUS_JOB_FLOOR, WAVE_EVIDENCE_JOB_FLOOR } from "./release-floors";
58
+
59
+ /**
60
+ * The GitLab environment every signing job names (#4914), with `action:
61
+ * access`, so it creates no deployment. Scope the runner key's CI/CD
62
+ * variable to it and protect it: GitLab then hands the key only to the
63
+ * signing jobs of a protected branch's pipeline, and to none of the jobs
64
+ * that run a merge request's code.
65
+ */
66
+ export const GITLAB_EVIDENCE_ENVIRONMENT = "chant-evidence";
67
+
68
+ /** Where a GitLab signing job keeps what it signed for each merge request (#4914): `.chant/evidence/<job>/<iid>/evidence.json`. */
69
+ export function gitlabOpenEvidenceDir(job: string): string {
70
+ return `.chant/evidence/${job}`;
71
+ }
72
+
73
+ /**
74
+ * The lines of a GitLab signing job in the target branch's plan notes
75
+ * pipeline (#4914): `chant ci evidence sign --open` finds every open merge
76
+ * request's newest `job`, reads its report from the job's artifact at
77
+ * `dir`, fetches the head and signs it against the policy at the branch's
78
+ * commit, and keeps each merge request's `evidence.json` under `out`.
79
+ * With `noForks`, a merge request from a fork is not signed for, as a
80
+ * product plan with `forks: "skip"` plans none.
81
+ */
82
+ export function openEvidenceLines(opts: { job: string; dir: string; out: string; bin?: string; noForks?: boolean }): string[] {
83
+ const chant = opts.bin ?? "chant";
84
+ return [`${chant} ci evidence sign --open --job ${opts.job} --from-report ${opts.dir} --base "$CI_COMMIT_SHA" --output ${opts.out}${opts.noForks ? " --no-forks" : ""}`];
85
+ }
49
86
 
50
87
  /**
51
88
  * A pipeline's runner identity (#4870): a runner key's secret, or (#4869)
@@ -77,10 +77,23 @@ export const NO_FORGE_TOKEN_MARKER = "CHANT_NO_FORGE_TOKEN";
77
77
  * `$0` is that file. terragucci's `restartWithout` (render.ts:1826).
78
78
  */
79
79
  export function dropForgeTokens(shell: "sh" | "bash" = "sh", extra: readonly string[] = []): string {
80
- const again = shell === "bash" ? 'bash --noprofile --norc -e -o pipefail "$0"' : 'sh -e "$0"';
81
- const marker = NO_FORGE_TOKEN_MARKER;
82
80
  // #4296: a plan job that traded its OIDC token drops the variables a token is requested with too.
83
- const vars = [...FORGE_TOKEN_VARS, ...extra];
81
+ return restartWithout(shell, [...FORGE_TOKEN_VARS, ...extra], NO_FORGE_TOKEN_MARKER);
82
+ }
83
+
84
+ /**
85
+ * The line that restarts the step's shell once without `vars` in its
86
+ * process environment, setting `marker` so the restarted shell does not
87
+ * restart again, or, when it cannot restart, unsets them (#4912). The
88
+ * restart runs the step's script file (`$0`) again from its first line,
89
+ * with every exported variable but `vars`, so the line goes at the top of
90
+ * the step. It needs that file, `env` and the shell on the PATH; without
91
+ * them (a script given to `sh -c`, GitLab's piped script) the shell unsets
92
+ * `vars` and runs on. {@link dropForgeTokens} and ci-login's `restart` use
93
+ * it. terragucci's `restartWithout` (render.ts:2101).
94
+ */
95
+ export function restartWithout(shell: "sh" | "bash", vars: readonly string[], marker: string): string {
96
+ const again = shell === "bash" ? 'bash --noprofile --norc -e -o pipefail "$0"' : 'sh -e "$0"';
84
97
  const can = `[ -z "\${${marker}:-}" ] && [ "\${0#*/}" != "$0" ] && [ -f "$0" ] && ! { [ "\${0##*/}" = sh ] || [ "\${0##*/}" = bash ] || [ "\${0##*/}" = dash ]; } && command -v env >/dev/null 2>&1 && command -v ${shell} >/dev/null 2>&1`;
85
98
  return `if ${can}; then exec env ${vars.map((v) => `-u ${v}`).join(" ")} ${marker}=1 ${again}; fi; unset ${vars.join(" ")}`;
86
99
  }
@@ -84,11 +84,11 @@ describe("the trade script stays inside one shell word", () => {
84
84
  test("it holds no single quote, so tradeLine can quote it", () => {
85
85
  expect(TRADE_JS).not.toContain("'");
86
86
  });
87
- test("GitLab's lines trade, unset the token variables and the extra ones, then source the credentials", () => {
87
+ test("GitLab's lines trade into a shell variable, unset the token variables and the extra ones, then evaluate the credentials (#4912)", () => {
88
88
  const [trade, unset, source] = gitlabTradeLines(["CHANT_FORGE_TOKEN"]);
89
- expect(trade).toContain("node -e");
89
+ expect(trade).toMatch(/^CHANT_CLOUD_TRADE_VARS="\$\(cd \/ && node -e '.*' "-" sh\)"$/);
90
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 /);
91
+ expect(source).toBe('eval "$CHANT_CLOUD_TRADE_VARS"; unset CHANT_CLOUD_TRADE_VARS');
92
92
  expect(gitlabTradeIdTokens(resolveCloudIdentity(DECL, "prod", "app")!.plan)).toEqual({
93
93
  CHANT_ID_TOKEN_AWS: { aud: "sts.amazonaws.com" },
94
94
  CHANT_ID_TOKEN_GCP: { aud: "https://iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/ci/providers/forge" },
@@ -124,7 +124,12 @@ export interface GcpCloudIdentity {
124
124
  provider: string;
125
125
  /** The OIDC token's audience. Default `https://iam.googleapis.com/<provider>`. */
126
126
  audience?: string;
127
- /** Google's STS, for an emulator. Default `https://sts.googleapis.com`. */
127
+ /**
128
+ * Google's STS, for a regional endpoint or an emulator: its base URL, to
129
+ * which `/v1/token` is added, or its full token URL, one that ends in
130
+ * `/token` (#4912, terragucci's `token_url`). Default
131
+ * `https://sts.googleapis.com`.
132
+ */
128
133
  stsEndpoint?: string;
129
134
  /** IAM credentials, for an emulator. Default `https://iamcredentials.googleapis.com`. */
130
135
  iamEndpoint?: string;
@@ -569,8 +574,9 @@ export const TRADED_VARS: Record<IdentityCloud, readonly string[]> = {
569
574
  /**
570
575
  * How the trade leaves what it got. `github-env`: `NAME=value` lines
571
576
  * appended to the file argv 1 names (`$GITHUB_ENV`), and an `::add-mask::`
572
- * line for each secret, so every later step of the job has them. `sh`: a
573
- * file of `export` lines a GitLab script sources, mode 0600.
577
+ * line for each secret, so every later step of the job has them. `sh`:
578
+ * `export` lines, printed when argv 1 is `-` (GitLab's script captures and
579
+ * evaluates them, #4912), else written to that file, mode 0600.
574
580
  */
575
581
  export type TradeFormat = "github-env" | "sh";
576
582
 
@@ -582,6 +588,22 @@ export type TradeFormat = "github-env" | "sh";
582
588
  */
583
589
  export const CLOUD_TARGETS_ENV = "CHANT_CLOUD_TARGETS";
584
590
 
591
+ /**
592
+ * The variable the trade sets (#4930): the clouds it traded the job's
593
+ * token for, comma-separated (`aws,gcp`). The trade and ci-login's login
594
+ * both write a {@link CLOUD_TARGETS_ENV} file, so a product that hands a
595
+ * target traded credentials (terragucci's re-plan) reads this, not the
596
+ * file, to know the job traded. The login never sets it.
597
+ */
598
+ export const CLOUD_TRADED_ENV = "CHANT_CLOUD_TRADED";
599
+
600
+ /** The clouds the job's trade traded for, from {@link CLOUD_TRADED_ENV}: none when the job did not trade, such as after ci-login's login (#4930). */
601
+ export function cloudsTraded(env: Readonly<Record<string, string | undefined>>): IdentityCloud[] {
602
+ const v = env[CLOUD_TRADED_ENV];
603
+ if (!v) return [];
604
+ return v.split(",").filter((c): c is IdentityCloud => (IDENTITY_CLOUDS as readonly string[]).includes(c));
605
+ }
606
+
585
607
  /** The file {@link CLOUD_TARGETS_ENV} names: per cloud, the job's own identity, the targets that take another, and each identity's variables. */
586
608
  export interface CloudTargetsFile {
587
609
  version: 1;
@@ -633,7 +655,8 @@ export const TRADE_JS = [
633
655
  "if(a.role)Object.assign(vars,by.aws[a.role])}",
634
656
  'if(spec.gcp){const c=spec.gcp;const tok=await idToken("gcp",c.audience);by.gcp={};',
635
657
  'const sts=trim(c.stsEndpoint||"https://sts.googleapis.com"),iam=trim(c.iamEndpoint||"https://iamcredentials.googleapis.com");',
636
- '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;',
658
+ // #4912: stsEndpoint is Google's STS, or its full token URL (terragucci's `token_url`).
659
+ 'const fed=json(await post(/\\/token$/.test(sts)?sts: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;',
637
660
  'if(!clean(fed))throw new Error("Google STS gave no token");',
638
661
  'for(const sa of ids("gcp")){',
639
662
  'const at=json(await post(iam+"/v1/projects/-/serviceAccounts/"+encodeURIComponent(sa)+":generateAccessToken",{"content-type":"application/json",authorization:"Bearer "+fed},JSON.stringify({scope:["https://www.googleapis.com/auth/cloud-platform"]})),"IAM credentials").accessToken;',
@@ -665,9 +688,11 @@ export const TRADE_JS = [
665
688
  '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]}}',
666
689
  'const tf=trim(process.env.RUNNER_TEMP||process.env.TMPDIR||"/tmp")+"/chant-cloud-targets-"+require("crypto").randomBytes(8).toString("hex")+".json";',
667
690
  `fs.writeFileSync(tf,JSON.stringify(doc),{mode:0o600,flag:"wx"});vars.${CLOUD_TARGETS_ENV}=tf}`,
691
+ // #4930: which clouds this job traded, so a product tells the trade's targets file from a login's.
692
+ `if(clouds.length)vars.${CLOUD_TRADED_ENV}=clouds.join(",");`,
668
693
  'for(const [k,v] of Object.entries(vars))if(!clean(v))throw new Error(k+" is not a value the job can hold");',
669
694
  '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(""))}',
670
- '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});',
695
+ 'else{const sh=Object.entries(vars).map(([k,v])=>"export "+k+"="+Q+v.split(Q).join(Q+"\\\\"+Q+Q)+Q+"\\n").join("");if(out==="-")process.stdout.write(sh);else fs.writeFileSync(out,sh,{mode:0o600})}',
671
696
  'for(const s of said)console.error("chant: traded the job\\u0027s OIDC token for "+s)};',
672
697
  "run().catch((e)=>fail(e&&e.message?e.message:String(e)));",
673
698
  ].join("");
@@ -681,19 +706,30 @@ export function tradeLine(out: string, format: TradeFormat): string {
681
706
  return `(cd / && node -e '${TRADE_JS}' "${out}" ${format})`;
682
707
  }
683
708
 
684
- /** The GitLab file the trade writes and the plan script sources, outside the project directory. */
709
+ /**
710
+ * The file GitLab's trade wrote and sourced before #4912. `gitlabTradeLines`
711
+ * writes none now; kept for a product that names it.
712
+ * @deprecated `gitlabTradeLines` captures the trade's `export` lines in {@link GITLAB_TRADE_VARS}.
713
+ */
685
714
  export const GITLAB_TRADE_FILE = "${TMPDIR:-/tmp}/chant-cloud-$CI_JOB_ID.sh";
686
715
 
716
+ /** The shell variable GitLab's script holds the trade's `export` lines in until it evaluates them (#4912), as ci-login's `CHANT_CLOUD_LOGIN_VARS`. Not exported, so no child sees it. */
717
+ export const GITLAB_TRADE_VARS = "CHANT_CLOUD_TRADE_VARS";
718
+
687
719
  /**
688
720
  * The lines a GitLab job's script starts with when it trades: the trade,
689
- * the unset of the token variables (and, with `extraUnset`, the forge
690
- * tokens'), and the source of what the trade wrote, which it then deletes.
721
+ * its `export` lines captured in {@link GITLAB_TRADE_VARS}, the unset of
722
+ * the token variables (and, with `extraUnset`, the forge tokens'), and the
723
+ * evaluation of what the trade printed, then the unset of the variable
724
+ * that held it. No file of credentials is written (#4912), as ci-login's
725
+ * `gitlabCloudLogin`. An assignment's status is its command substitution's,
726
+ * so a failed trade stops the script.
691
727
  */
692
728
  export function gitlabTradeLines(extraUnset: readonly string[] = []): string[] {
693
729
  return [
694
- tradeLine(GITLAB_TRADE_FILE, "sh"),
730
+ `${GITLAB_TRADE_VARS}="$${tradeLine("-", "sh")}"`,
695
731
  `unset ${[...extraUnset, ...OIDC_REQUEST_VARS].join(" ")}`,
696
- `. "${GITLAB_TRADE_FILE}" && rm -f "${GITLAB_TRADE_FILE}"`,
732
+ `eval "$${GITLAB_TRADE_VARS}"; unset ${GITLAB_TRADE_VARS}`,
697
733
  ];
698
734
  }
699
735
 
@@ -702,6 +738,9 @@ export function gitlabTradeIdTokens(spec: CloudTradeSpec): Record<string, { aud:
702
738
  return Object.fromEntries(tradedClouds(spec).map((c) => [idTokenVar(c), { aud: spec[c]!.audience }]));
703
739
  }
704
740
 
741
+ /** The AWS region variables, which {@link targetCloudEnv} replaces only when the target's identity sets them. */
742
+ const JOB_REGION_VARS: ReadonlySet<string> = new Set(["AWS_REGION", "AWS_DEFAULT_REGION"]);
743
+
705
744
  /**
706
745
  * `env` for one target's tool (#4332): the job's environment with each
707
746
  * cloud's credentials replaced by those of the identity `target` takes, as
@@ -722,7 +761,8 @@ export function targetCloudEnv(env: Readonly<Record<string, string | undefined>>
722
761
  if (id === undefined || id === c.default) continue;
723
762
  const vars = c.vars[id];
724
763
  if (!vars) throw new Error(`${CLOUD_TARGETS_ENV} (${path}) holds no ${cloud} credentials for ${id}`);
725
- for (const k of TRADED_VARS[cloud]) delete out[k];
764
+ // The region is the job's, not the identity's: a login that names none (#4930) leaves the job's in place, and a trade's identity sets its own.
765
+ for (const k of TRADED_VARS[cloud]) if (!JOB_REGION_VARS.has(k)) delete out[k];
726
766
  Object.assign(out, vars);
727
767
  }
728
768
  return out;