@intentius/chant 0.124.96 → 0.124.98

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 (237) hide show
  1. package/dist/audit/core.d.ts +29 -0
  2. package/dist/audit/core.d.ts.map +1 -1
  3. package/dist/audit/core.js +48 -11
  4. package/dist/audit/identity.d.ts +27 -0
  5. package/dist/audit/identity.d.ts.map +1 -0
  6. package/dist/audit/identity.js +36 -0
  7. package/dist/audit/report-html.d.ts +3 -1
  8. package/dist/audit/report-html.d.ts.map +1 -1
  9. package/dist/audit/report-html.js +1 -1
  10. package/dist/audit/report-model.d.ts +16 -0
  11. package/dist/audit/report-model.d.ts.map +1 -1
  12. package/dist/audit/report-model.js +5 -1
  13. package/dist/change-set-graph.d.ts +3 -1
  14. package/dist/change-set-graph.d.ts.map +1 -1
  15. package/dist/change-set-graph.js +7 -1
  16. package/dist/change-set.d.ts +5 -2
  17. package/dist/change-set.d.ts.map +1 -1
  18. package/dist/change-set.js +6 -3
  19. package/dist/ci-agent.d.ts +17 -0
  20. package/dist/ci-agent.d.ts.map +1 -1
  21. package/dist/ci-agent.js +32 -0
  22. package/dist/ci-comment-allow.d.ts +88 -0
  23. package/dist/ci-comment-allow.d.ts.map +1 -0
  24. package/dist/ci-comment-allow.js +178 -0
  25. package/dist/ci-comment-commands.d.ts +12 -0
  26. package/dist/ci-comment-commands.d.ts.map +1 -1
  27. package/dist/ci-comment-commands.js +22 -0
  28. package/dist/ci-control.d.ts +6 -1
  29. package/dist/ci-control.d.ts.map +1 -1
  30. package/dist/ci-control.js +6 -1
  31. package/dist/ci-product.d.ts +3 -0
  32. package/dist/ci-product.d.ts.map +1 -1
  33. package/dist/ci-product.js +3 -0
  34. package/dist/cli/commands/audit.d.ts +3 -1
  35. package/dist/cli/commands/audit.d.ts.map +1 -1
  36. package/dist/cli/commands/audit.js +23 -6
  37. package/dist/cli/commands/import.d.ts +8 -1
  38. package/dist/cli/commands/import.d.ts.map +1 -1
  39. package/dist/cli/commands/import.js +31 -6
  40. package/dist/cli/handlers/agent.d.ts.map +1 -1
  41. package/dist/cli/handlers/agent.js +12 -2
  42. package/dist/cli/handlers/pr-comment.d.ts +6 -0
  43. package/dist/cli/handlers/pr-comment.d.ts.map +1 -1
  44. package/dist/cli/handlers/pr-comment.js +12 -0
  45. package/dist/cli/handlers/promote.d.ts.map +1 -1
  46. package/dist/cli/handlers/promote.js +53 -6
  47. package/dist/cli/main.d.ts.map +1 -1
  48. package/dist/cli/main.js +29 -6
  49. package/dist/cli/parse-args.d.ts.map +1 -1
  50. package/dist/cli/parse-args.js +23 -0
  51. package/dist/cli/registry.d.ts +8 -0
  52. package/dist/cli/registry.d.ts.map +1 -1
  53. package/dist/cloud-lister/mask.d.ts +30 -1
  54. package/dist/cloud-lister/mask.d.ts.map +1 -1
  55. package/dist/cloud-lister/mask.js +66 -3
  56. package/dist/components/driver.d.ts +8 -1
  57. package/dist/components/driver.d.ts.map +1 -1
  58. package/dist/components/driver.js +1 -0
  59. package/dist/components/product-pipeline.d.ts +23 -1
  60. package/dist/components/product-pipeline.d.ts.map +1 -1
  61. package/dist/components/product-pipeline.js +40 -7
  62. package/dist/components/product-plan.d.ts +20 -0
  63. package/dist/components/product-plan.d.ts.map +1 -1
  64. package/dist/components/product-plan.js +11 -1
  65. package/dist/control/applied.d.ts +8 -1
  66. package/dist/control/applied.d.ts.map +1 -1
  67. package/dist/control/applied.js +18 -2
  68. package/dist/control/dispatch.d.ts +52 -0
  69. package/dist/control/dispatch.d.ts.map +1 -1
  70. package/dist/control/dispatch.js +140 -4
  71. package/dist/control/train.d.ts +198 -0
  72. package/dist/control/train.d.ts.map +1 -0
  73. package/dist/control/train.js +294 -0
  74. package/dist/deep-observation.js +2 -2
  75. package/dist/floor-table.data.d.ts.map +1 -1
  76. package/dist/floor-table.data.js +7 -1
  77. package/dist/graph-detail.d.ts +9 -0
  78. package/dist/graph-detail.d.ts.map +1 -1
  79. package/dist/graph-detail.js +38 -13
  80. package/dist/graph-refs.d.ts +233 -3
  81. package/dist/graph-refs.d.ts.map +1 -1
  82. package/dist/graph-refs.js +106 -15
  83. package/dist/lint/post-synth.d.ts +22 -0
  84. package/dist/lint/post-synth.d.ts.map +1 -1
  85. package/dist/lint/rules/declarable-naming-convention.d.ts +12 -0
  86. package/dist/lint/rules/declarable-naming-convention.d.ts.map +1 -1
  87. package/dist/lint/rules/declarable-naming-convention.js +38 -8
  88. package/dist/lint/rules/imported-source.d.ts +20 -0
  89. package/dist/lint/rules/imported-source.d.ts.map +1 -0
  90. package/dist/lint/rules/imported-source.js +27 -0
  91. package/dist/lint/rules/no-unused-declarable.d.ts.map +1 -1
  92. package/dist/lint/rules/no-unused-declarable.js +3 -0
  93. package/dist/op/gate.d.ts +2 -0
  94. package/dist/op/gate.d.ts.map +1 -1
  95. package/dist/op/gate.js +8 -1
  96. package/dist/pr-forge-reads.d.ts +17 -0
  97. package/dist/pr-forge-reads.d.ts.map +1 -1
  98. package/dist/pr-forge-reads.js +55 -0
  99. package/dist/reconcile.d.ts +9 -0
  100. package/dist/reconcile.d.ts.map +1 -1
  101. package/dist/release-floors.d.ts +9 -1
  102. package/dist/release-floors.d.ts.map +1 -1
  103. package/dist/release-floors.js +10 -2
  104. package/dist/repo-path.d.ts +29 -0
  105. package/dist/repo-path.d.ts.map +1 -0
  106. package/dist/repo-path.js +81 -0
  107. package/dist/sensitive-key.d.ts +23 -0
  108. package/dist/sensitive-key.d.ts.map +1 -1
  109. package/dist/sensitive-key.js +37 -0
  110. package/dist/terraform/hcl2json.d.ts +7 -0
  111. package/dist/terraform/hcl2json.d.ts.map +1 -1
  112. package/dist/terraform/hcl2json.js +7 -0
  113. package/dist/wave-runtime.mjs +352 -345
  114. package/dist/workspace/catalog-edges.d.ts +147 -0
  115. package/dist/workspace/catalog-edges.d.ts.map +1 -0
  116. package/dist/workspace/catalog-edges.js +461 -0
  117. package/dist/workspace/compose-graph.d.ts +73 -3
  118. package/dist/workspace/compose-graph.d.ts.map +1 -1
  119. package/dist/workspace/declaration.d.ts +2 -0
  120. package/dist/workspace/declaration.d.ts.map +1 -1
  121. package/dist/workspace/declaration.js +1 -0
  122. package/dist/workspace/declaration.schema.json +6 -0
  123. package/dist/workspace/discover.d.ts +134 -0
  124. package/dist/workspace/discover.d.ts.map +1 -0
  125. package/dist/workspace/discover.js +372 -0
  126. package/dist/workspace/graph-cli.d.ts +20 -0
  127. package/dist/workspace/graph-cli.d.ts.map +1 -1
  128. package/dist/workspace/graph-cli.js +178 -20
  129. package/dist/workspace/graph.schema.json +195 -2
  130. package/dist/workspace/release-train.d.ts +214 -3
  131. package/dist/workspace/release-train.d.ts.map +1 -1
  132. package/dist/workspace/release-train.js +552 -16
  133. package/dist/workspace/repo-ref.d.ts +14 -0
  134. package/dist/workspace/repo-ref.d.ts.map +1 -1
  135. package/dist/workspace/repo-ref.js +26 -1
  136. package/dist/workspace/workspace-gates.d.ts +24 -0
  137. package/dist/workspace/workspace-gates.d.ts.map +1 -1
  138. package/dist/workspace/workspace-gates.js +29 -5
  139. package/dist/workspace/workspace-ledger.d.ts +31 -5
  140. package/dist/workspace/workspace-ledger.d.ts.map +1 -1
  141. package/dist/workspace/workspace-ledger.js +2 -1
  142. package/dist/workspace/workspace-run.d.ts +14 -0
  143. package/dist/workspace/workspace-run.d.ts.map +1 -1
  144. package/dist/workspace/workspace-run.js +2 -2
  145. package/dist/yaml.d.ts.map +1 -1
  146. package/dist/yaml.js +33 -8
  147. package/package.json +1 -1
  148. package/src/audit/core.test.ts +64 -1
  149. package/src/audit/core.ts +75 -10
  150. package/src/audit/identity.test.ts +31 -0
  151. package/src/audit/identity.ts +43 -0
  152. package/src/audit/report-html.ts +4 -2
  153. package/src/audit/report-model.ts +21 -1
  154. package/src/change-set-graph.test.ts +33 -1
  155. package/src/change-set-graph.ts +7 -1
  156. package/src/change-set.ts +6 -3
  157. package/src/ci-agent.test.ts +32 -0
  158. package/src/ci-agent.ts +42 -0
  159. package/src/ci-comment-allow.test.ts +380 -0
  160. package/src/ci-comment-allow.ts +184 -0
  161. package/src/ci-comment-commands.ts +25 -0
  162. package/src/ci-control.ts +42 -0
  163. package/src/ci-product.ts +3 -0
  164. package/src/cli/commands/audit-parser-notice.test.ts +74 -0
  165. package/src/cli/commands/audit.test.ts +12 -0
  166. package/src/cli/commands/audit.ts +25 -7
  167. package/src/cli/commands/import-layout.test.ts +2 -1
  168. package/src/cli/commands/import.ts +29 -6
  169. package/src/cli/handlers/agent.ts +13 -2
  170. package/src/cli/handlers/pr-before-merge.test.ts +18 -0
  171. package/src/cli/handlers/pr-comment.ts +12 -0
  172. package/src/cli/handlers/promote.test.ts +68 -0
  173. package/src/cli/handlers/promote.ts +52 -6
  174. package/src/cli/main.test.ts +5 -0
  175. package/src/cli/main.ts +29 -6
  176. package/src/cli/parse-args.ts +18 -0
  177. package/src/cli/registry.ts +8 -0
  178. package/src/cloud-lister/kubernetes.k3d.e2e.test.ts +104 -0
  179. package/src/cloud-lister/mask-references.test.ts +132 -0
  180. package/src/cloud-lister/mask.ts +68 -3
  181. package/src/components/driver.ts +9 -1
  182. package/src/components/product-pipeline.ts +57 -7
  183. package/src/components/product-plan.ts +27 -2
  184. package/src/control/applied.ts +33 -3
  185. package/src/control/dispatch.ts +156 -5
  186. package/src/control/train.test.ts +215 -0
  187. package/src/control/train.ts +413 -0
  188. package/src/deep-observation.ts +2 -2
  189. package/src/floor-table.data.ts +7 -1
  190. package/src/graph-detail.ts +37 -12
  191. package/src/graph-refs.test.ts +45 -1
  192. package/src/graph-refs.ts +321 -14
  193. package/src/lint/post-synth.ts +20 -0
  194. package/src/lint/rules/declarable-naming-convention.test.ts +35 -1
  195. package/src/lint/rules/declarable-naming-convention.ts +35 -8
  196. package/src/lint/rules/imported-source.test.ts +22 -0
  197. package/src/lint/rules/imported-source.ts +31 -0
  198. package/src/lint/rules/no-unused-declarable.test.ts +16 -0
  199. package/src/lint/rules/no-unused-declarable.ts +7 -0
  200. package/src/op/gate.ts +10 -2
  201. package/src/pr-forge-reads.ts +62 -0
  202. package/src/reconcile.ts +9 -0
  203. package/src/release-floors.ts +14 -2
  204. package/src/repo-path.test.ts +72 -0
  205. package/src/repo-path.ts +103 -0
  206. package/src/sensitive-key.ts +38 -0
  207. package/src/terraform/hcl2json.ts +8 -0
  208. package/src/workspace/application-set.e2e.test.ts +405 -0
  209. package/src/workspace/catalog-edges.ts +507 -0
  210. package/src/workspace/ci-green-workflow.test.ts +2 -2
  211. package/src/workspace/cluster-join.e2e.test.ts +150 -0
  212. package/src/workspace/compose-graph.ts +74 -5
  213. package/src/workspace/declaration.schema.json +6 -0
  214. package/src/workspace/declaration.ts +3 -0
  215. package/src/workspace/discover.e2e.test.ts +122 -0
  216. package/src/workspace/discover.test.ts +225 -0
  217. package/src/workspace/discover.ts +406 -0
  218. package/src/workspace/drift-reader.test.ts +3 -3
  219. package/src/workspace/external-secret-catalog.e2e.test.ts +98 -0
  220. package/src/workspace/external-secret-catalog.test.ts +142 -0
  221. package/src/workspace/graph-cli.ts +207 -21
  222. package/src/workspace/graph-contract.test.ts +92 -0
  223. package/src/workspace/graph.schema.json +195 -2
  224. package/src/workspace/helm-references.e2e.test.ts +135 -0
  225. package/src/workspace/identity-annotation-catalog.e2e.test.ts +91 -0
  226. package/src/workspace/identity-annotation-catalog.test.ts +139 -0
  227. package/src/workspace/release-train-repos.test.ts +304 -0
  228. package/src/workspace/release-train.test.ts +296 -0
  229. package/src/workspace/release-train.ts +631 -16
  230. package/src/workspace/repo-ref.ts +26 -1
  231. package/src/workspace/runs-on.test.ts +45 -0
  232. package/src/workspace/workspace-gates.ts +48 -5
  233. package/src/workspace/workspace-ledger.ts +28 -5
  234. package/src/workspace/workspace-run.test.ts +1 -1
  235. package/src/workspace/workspace-run.ts +2 -2
  236. package/src/yaml.test.ts +96 -8
  237. package/src/yaml.ts +36 -8
@@ -0,0 +1,380 @@
1
+ /**
2
+ * Comment commands limited to logins and teams (INTENTIUS/terragucci#1461):
3
+ * the decision, the team reads on GitHub's and Forgejo's request shapes, the
4
+ * comment job's hook, the re-plan's script, and the pipeline's refusals. No
5
+ * network: every read is a fake that records the requests it was asked.
6
+ */
7
+ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { describe, expect, test } from "vitest";
11
+ import { COMMENT_ALLOW_ENV, COMMENT_ALLOW_GATE_JS, TeamReadError, commentAllowFromEnv, commentAllowProblems, decideCommentAllow, type CommentAllow } from "./ci-comment-allow";
12
+ import { answerProductComment, type AnswerCommentOptions, type CommentJobs } from "./ci-comment-commands";
13
+ import { assertProductWords } from "./ci-product-words";
14
+ import { productPipelineJobs } from "./components/product-pipeline";
15
+ import { replanDecideJs } from "./components/product-plan";
16
+ import { forgeReadsFor, type ForgeReads, type PullRequestDetail } from "./pr-forge-reads";
17
+ import type { ForgeFetch } from "./pr-forge";
18
+
19
+ type Answer = { status: number; body?: unknown };
20
+
21
+ /** A fetch that answers from a table of `METHOD path` and records every request, with its Authorization header. */
22
+ function recorded(table: Record<string, Answer>) {
23
+ const seen: Array<{ url: string; auth: string | undefined }> = [];
24
+ const posts: string[] = [];
25
+ const fetch = (async (url: string, init?: { method?: string; body?: string; headers?: Record<string, string> }) => {
26
+ const path = url.replace(/^https?:\/\/[^/]+(?=\/)/, "");
27
+ if (init?.method === "POST") {
28
+ posts.push(JSON.parse(init.body ?? "{}").body);
29
+ return { ok: true, status: 201, text: async () => "{}", json: async () => ({}) };
30
+ }
31
+ seen.push({ url: path, auth: init?.headers?.Authorization ?? init?.headers?.authorization });
32
+ const a = table[path] ?? { status: 404 };
33
+ return { ok: a.status >= 200 && a.status < 300, status: a.status, text: async () => (a.body === undefined ? "" : JSON.stringify(a.body)), json: async () => a.body };
34
+ }) as unknown as ForgeFetch;
35
+ return { fetch, seen, posts };
36
+ }
37
+
38
+ /** A table whose paths sit under a prefix, as Forgejo's API root does. */
39
+ const under = (prefix: string, table: Record<string, Answer>): Record<string, Answer> => Object.fromEntries(Object.entries(table).map(([k, v]) => [prefix + k, v]));
40
+ const FJ = "/api/v1";
41
+
42
+ // What GitHub answers for a team and a membership (docs.github.com/rest/teams), cut down to the fields read.
43
+ const GH_TEAM = { id: 7, slug: "release", name: "Release" };
44
+ const GH_ACTIVE = { url: "https://api.github.com/orgs/acme/teams/release/memberships/alice", role: "member", state: "active" };
45
+ const GH_PENDING = { ...GH_ACTIVE, state: "pending" };
46
+ // Forgejo's team search is `{ ok, data: [teams] }`; a member read is 204 with no body, or 404.
47
+ const FJ_SEARCH = { ok: true, data: [{ id: 41, name: "Owners" }, { id: 42, name: "release" }] };
48
+
49
+ const github = (fetch: ForgeFetch) => forgeReadsFor({ kind: "github", apiBase: "https://api.github.com", repo: "acme/infra", token: "team-tok", host: "github.com" } as never, fetch);
50
+ const forgejo = (fetch: ForgeFetch) => forgeReadsFor({ kind: "forgejo", apiBase: "https://git.example/api/v1", repo: "acme/infra", token: "team-tok", host: "git.example" } as never, fetch);
51
+
52
+ describe("the map", () => {
53
+ test("checks commands and entries, and an empty list", () => {
54
+ expect(commentAllowProblems({ apply: ["team:acme/release", "alice"], default: ["bob"] }, "x")).toEqual([]);
55
+ expect(commentAllowProblems({ apply: [] }, "x")[0]).toMatch(/at least one entry/);
56
+ expect(commentAllowProblems({ frob: ["a"] }, "x")[0]).toMatch(/not a command/);
57
+ expect(commentAllowProblems({ apply: ["team:acme"] }, "x")[0]).toMatch(/team:<org>\/<team>/);
58
+ expect(commentAllowProblems({ apply: ["team:a/b/c"] }, "x")[0]).toMatch(/not a team/);
59
+ expect(commentAllowProblems({ apply: ["a b"] }, "x")[0]).toMatch(/not a login/);
60
+ expect(commentAllowProblems(["a"], "x")[0]).toMatch(/must be a map/);
61
+ });
62
+
63
+ test("a value that does not read never turns the limit off", () => {
64
+ expect(commentAllowFromEnv(undefined)).toBeUndefined();
65
+ expect(commentAllowFromEnv("")).toBeUndefined();
66
+ expect(commentAllowFromEnv('{"apply":["alice"]}')).toEqual({ apply: ["alice"] });
67
+ expect(() => commentAllowFromEnv("{")).toThrow(/CHANT_COMMENT_ALLOW is JSON/);
68
+ expect(() => commentAllowFromEnv('{"apply":[]}')).toThrow(/at least one entry/);
69
+ });
70
+ });
71
+
72
+ describe("decideCommentAllow", () => {
73
+ const reads = (member: boolean | Error) => ({ teamMember: async () => { if (member instanceof Error) throw member; return member; } });
74
+
75
+ test("a command with no list, and no default, is open to every writer", async () => {
76
+ expect(await decideCommentAllow({ apply: ["alice"] }, "plan", "bob", undefined)).toEqual({ ok: true });
77
+ expect(await decideCommentAllow(undefined, "apply", "bob", undefined)).toEqual({ ok: true });
78
+ });
79
+
80
+ test("a listed login needs no read, whatever its case, and default covers what is not named", async () => {
81
+ expect(await decideCommentAllow({ apply: ["Alice"] }, "apply", "alice", undefined)).toEqual({ ok: true });
82
+ const refused = await decideCommentAllow({ apply: ["alice"] }, "apply", "bob", undefined);
83
+ expect(refused).toMatchObject({ ok: false });
84
+ expect(refused.ok === false && refused.reason).toContain("bob may not run `apply`");
85
+ expect(await decideCommentAllow({ default: ["alice"] }, "agent", "bob", undefined)).toMatchObject({ ok: false });
86
+ expect(await decideCommentAllow({ default: ["alice"], agent: ["bob"] }, "agent", "bob", undefined)).toEqual({ ok: true });
87
+ });
88
+
89
+ test("a team is read until one holds the user; a user in none is refused", async () => {
90
+ const seen: string[] = [];
91
+ const r = { teamMember: async (team: string) => (seen.push(team), team === "acme/b") };
92
+ expect(await decideCommentAllow({ plan: ["team:acme/a", "team:acme/b", "team:acme/c"] }, "plan", "bob", r)).toEqual({ ok: true });
93
+ expect(seen).toEqual(["acme/a", "acme/b"]);
94
+ expect(await decideCommentAllow({ plan: ["team:acme/a"] }, "plan", "bob", reads(false))).toMatchObject({ ok: false });
95
+ });
96
+
97
+ test("a team the forge cannot answer for fails closed, with what to fix, even when another team says no", async () => {
98
+ const got = await decideCommentAllow({ apply: ["team:acme/release", "team:acme/ops"] }, "apply", "bob", { teamMember: async (t) => { if (t === "acme/release") throw new TeamReadError("GitHub team acme/release answered 404: the team does not exist, or the token cannot see it"); return false; } });
99
+ expect(got).toMatchObject({ ok: false, fail: true });
100
+ expect(got.ok === false && got.reason).toMatch(/so nothing runs \(GitHub team acme\/release answered 404.*CHANT_COMMENT_ALLOW_TOKEN/);
101
+ expect(await decideCommentAllow({ apply: ["team:acme/release"] }, "apply", "bob", undefined)).toMatchObject({ ok: false, fail: true });
102
+ await expect(decideCommentAllow({ apply: ["team:acme/release"] }, "apply", "bob", reads(new Error("boom")))).rejects.toThrow("boom");
103
+ });
104
+ });
105
+
106
+ describe("ForgeReads.teamMember on recorded shapes", () => {
107
+ test("GitHub: looks the team up, then reads the membership; active is a member, pending is not, 404 is not", async () => {
108
+ const ok = recorded({ "/orgs/acme/teams/release": { status: 200, body: GH_TEAM }, "/orgs/acme/teams/release/memberships/alice": { status: 200, body: GH_ACTIVE }, "/orgs/acme/teams/release/memberships/pat": { status: 200, body: GH_PENDING } });
109
+ const r = github(ok.fetch);
110
+ expect(await r.teamMember!("acme/release", "alice")).toBe(true);
111
+ expect(await r.teamMember!("acme/release", "pat")).toBe(false);
112
+ expect(await r.teamMember!("acme/release", "bob")).toBe(false);
113
+ expect(ok.seen[0]).toEqual({ url: "/orgs/acme/teams/release", auth: "Bearer team-tok" });
114
+ expect(ok.seen[1]!.url).toBe("/orgs/acme/teams/release/memberships/alice");
115
+ });
116
+
117
+ test("GitHub: a team the token cannot see throws a message that says what to fix, never `not a member`", async () => {
118
+ const r = github(recorded({ "/orgs/acme/teams/release": { status: 404 } }).fetch);
119
+ await expect(r.teamMember!("acme/release", "alice")).rejects.toThrow(/GitHub team acme\/release answered 404: the team does not exist, or the token cannot see it/);
120
+ await expect(r.teamMember!("acme/release", "alice")).rejects.toBeInstanceOf(TeamReadError);
121
+ const denied = github(recorded({ "/orgs/acme/teams/release": { status: 403 } }).fetch);
122
+ await expect(denied.teamMember!("acme/release", "alice")).rejects.toThrow(/answered 403/);
123
+ const noScope = github(recorded({ "/orgs/acme/teams/release": { status: 200, body: GH_TEAM }, "/orgs/acme/teams/release/memberships/alice": { status: 403 } }).fetch);
124
+ await expect(noScope.teamMember!("acme/release", "alice")).rejects.toThrow(/membership of alice answered 403/);
125
+ await expect(r.teamMember!("acme", "alice")).rejects.toThrow(/write <org>\/<team>/);
126
+ });
127
+
128
+ test("Forgejo: finds the team by name, then asks whether the login is a member", async () => {
129
+ const t = recorded(under(FJ, { "/orgs/acme/teams/search?q=release&limit=50": { status: 200, body: FJ_SEARCH }, "/teams/42/members/alice": { status: 204 }, "/teams/42/members/bob": { status: 404 } }));
130
+ const r = forgejo(t.fetch);
131
+ expect(await r.teamMember!("acme/release", "alice")).toBe(true);
132
+ expect(await r.teamMember!("acme/release", "bob")).toBe(false);
133
+ expect(t.seen[0]).toEqual({ url: `${FJ}/orgs/acme/teams/search?q=release&limit=50`, auth: "token team-tok" });
134
+ const none = forgejo(recorded(under(FJ, { "/orgs/acme/teams/search?q=ops&limit=50": { status: 200, body: FJ_SEARCH } })).fetch);
135
+ await expect(none.teamMember!("acme/ops", "alice")).rejects.toThrow(/acme has no team named ops/);
136
+ const hidden = forgejo(recorded(under(FJ, { "/orgs/acme/teams/search?q=release&limit=50": { status: 403 } })).fetch);
137
+ await expect(hidden.teamMember!("acme/release", "alice")).rejects.toThrow(/searching acme's teams answered 403/);
138
+ });
139
+ });
140
+
141
+ const tg = assertProductWords({ product: "terragucci", noun: ["root", "roots"], commands: { plan: "plan", apply: "apply", lock: "lock", unlock: "unlock", agent: "agent", action: "action" } });
142
+
143
+ function comment(body: string, allow: CommentAllow | undefined, jobs: CommentJobs, teams: ForgeReads["teamMember"] | undefined, o: { forge?: "github" | "forgejo"; user?: string } = {}) {
144
+ const posted: string[] = [];
145
+ const forge = o.forge ?? "github";
146
+ const reads = {
147
+ kind: forge,
148
+ permission: async () => "write",
149
+ pullRequest: async (n: number) => ({ number: n, title: "", body: "", state: "merged", head: "f", base: "main", sameRepo: true, mergeCommit: "a".repeat(40) }) as PullRequestDetail,
150
+ headRuns: async () => [],
151
+ runJobs: async () => [],
152
+ branchRuns: async () => [],
153
+ ...(teams ? { teamMember: teams } : {}),
154
+ } as unknown as ForgeReads;
155
+ const user = o.user ?? "bob";
156
+ const opts: AnswerCommentOptions = {
157
+ forge,
158
+ event: { action: "created", comment: { id: 7, body, user: { login: user } }, issue: { number: 12, pull_request: {} }, repository: { full_name: "acme/infra", default_branch: "main", permissions: { push: true } }, sender: { login: user } },
159
+ repo: "acme/infra",
160
+ reads,
161
+ poster: { addComment: async (_n: number, text: string) => (posted.push(text), { id: 1 } as never), commitStatuses: async () => [] as never },
162
+ runs: { rerunFailed: async () => ({}), dispatch: async () => ({}) },
163
+ words: tg,
164
+ base: "main",
165
+ jobs,
166
+ ...(allow ? { allow } : {}),
167
+ };
168
+ return { opts, posted };
169
+ }
170
+
171
+ describe("the comment job's hook", () => {
172
+ test("a writer a list leaves out gets a reply that names it, for each command the job answers", async () => {
173
+ for (const [body, jobs] of [
174
+ ["/terragucci apply", { applyOnMerge: true }],
175
+ ["/terragucci lock", {}],
176
+ ["/terragucci unlock", {}],
177
+ ["/terragucci agent fix it", {}],
178
+ ["/terragucci plan", { preview: true }],
179
+ ["/terragucci agent fix it", { agent: true }],
180
+ ] as Array<[string, CommentJobs]>) {
181
+ const s = comment(body, { default: ["alice"] }, jobs, undefined);
182
+ const got = await answerProductComment(s.opts);
183
+ expect(got, body).toMatchObject({ replied: true, ran: false });
184
+ expect(got.fail, body).toBeUndefined();
185
+ expect(s.posted, body).toEqual([expect.stringMatching(/^terragucci: bob may not run `\w+` here: it is limited to `alice`/)]);
186
+ }
187
+ });
188
+
189
+ test("a listed login, and a member of a listed team, go on to the command", async () => {
190
+ const login = comment("/terragucci lock", { lock: ["Bob"] }, {}, undefined);
191
+ expect(await answerProductComment(login.opts)).toMatchObject({ replied: true });
192
+ expect(login.posted[0]).toMatch(/lock/);
193
+ expect(login.posted[0]).not.toMatch(/may not run/);
194
+ const asked: string[] = [];
195
+ const team = comment("/terragucci apply", { apply: ["team:acme/release"] }, { applyOnMerge: true }, async (t, l) => (asked.push(`${t}:${l}`), true));
196
+ const got = await answerProductComment(team.opts);
197
+ expect(asked).toEqual(["acme/release:bob"]);
198
+ expect(team.posted.join("\n")).not.toMatch(/may not run/);
199
+ expect(got.fail).toBeUndefined();
200
+ });
201
+
202
+ test("a command with no list is open to every writer", async () => {
203
+ const s = comment("/terragucci lock", { apply: ["alice"] }, {}, undefined);
204
+ await answerProductComment(s.opts);
205
+ expect(s.posted.join("\n")).not.toMatch(/may not run/);
206
+ });
207
+
208
+ test("a team the token cannot read fails the job, with a reply that says what to fix", async () => {
209
+ const s = comment("/terragucci apply", { apply: ["team:acme/release"] }, { applyOnMerge: true }, async () => { throw new TeamReadError("GitHub team acme/release answered 403"); });
210
+ const got = await answerProductComment(s.opts);
211
+ expect(got).toMatchObject({ fail: true, replied: true, ran: false });
212
+ expect(s.posted).toEqual([expect.stringMatching(/could not read team membership for bob, so nothing runs \(GitHub team acme\/release answered 403\)/)]);
213
+ // A read that fails some other way fails the job and runs nothing.
214
+ const other = comment("/terragucci apply", { apply: ["team:acme/release"] }, { applyOnMerge: true }, async () => { throw new Error("socket closed"); });
215
+ expect(await answerProductComment(other.opts)).toMatchObject({ fail: true, ran: false });
216
+ // GitLab-shaped reads that cannot read teams fail closed too.
217
+ const none = comment("/terragucci apply", { apply: ["team:acme/release"] }, { applyOnMerge: true }, undefined);
218
+ expect(await answerProductComment(none.opts)).toMatchObject({ fail: true });
219
+ });
220
+
221
+ test("Forgejo's commenter is held to the list the same way", async () => {
222
+ const s = comment("/terragucci apply", { apply: ["alice"] }, { applyOnMerge: true }, undefined, { forge: "forgejo" });
223
+ expect(await answerProductComment(s.opts)).toMatchObject({ replied: true, ran: false });
224
+ expect(s.posted[0]).toMatch(/bob may not run `apply`/);
225
+ });
226
+
227
+ test("a commenter without write access gets no reply, before any list is read", async () => {
228
+ const s = comment("/terragucci apply", { apply: ["team:acme/release"] }, { applyOnMerge: true }, async () => { throw new Error("never read"); });
229
+ (s.opts.reads as unknown as { permission: () => Promise<string> }).permission = async () => "read";
230
+ expect(await answerProductComment(s.opts)).toMatchObject({ replied: false });
231
+ expect(s.posted).toEqual([]);
232
+ });
233
+ });
234
+
235
+ /** The gate script alone, run with a fake process and the forge's answers. */
236
+ async function gate(env: Record<string, string>, who: string, command: string, table: Record<string, Answer>) {
237
+ const t = recorded(table);
238
+ const run = new Function("process", "fetch", `${COMMENT_ALLOW_GATE_JS}; return commentAllowRefusal;`) as (p: unknown, f: unknown) => (who: string, command: string) => Promise<string | undefined>;
239
+ const refusal = run({ env }, t.fetch);
240
+ return { result: await refusal(who, command), seen: t.seen };
241
+ }
242
+
243
+ describe("the re-plan's gate script", () => {
244
+ const list = JSON.stringify({ plan: ["team:acme/release", "Carol"] });
245
+ const base = { [COMMENT_ALLOW_ENV]: list, GITHUB_API_URL: "https://api.github.com", CHANT_REPLAN_TOKEN: "job-tok" };
246
+
247
+ test("answers undefined for a listed login, with no request, and for a command with no list", async () => {
248
+ const a = await gate(base, "carol", "plan", {});
249
+ expect(a).toEqual({ result: undefined, seen: [] });
250
+ expect((await gate(base, "bob", "apply", {})).result).toBeUndefined();
251
+ });
252
+
253
+ test("makes GitHub's requests with the team token, else the job's", async () => {
254
+ const table = { "/orgs/acme/teams/release": { status: 200, body: GH_TEAM }, "/orgs/acme/teams/release/memberships/alice": { status: 200, body: GH_ACTIVE } };
255
+ const a = await gate({ ...base, CHANT_COMMENT_ALLOW_TOKEN: "team-tok" }, "alice", "plan", table);
256
+ expect(a.result).toBeUndefined();
257
+ expect(a.seen.map((s) => s.auth)).toEqual(["Bearer team-tok", "Bearer team-tok"]);
258
+ const job = await gate(base, "alice", "plan", table);
259
+ expect(job.seen[0]!.auth).toBe("Bearer job-tok");
260
+ const out = await gate(base, "bob", "plan", table);
261
+ expect(out.result).toMatch(/^bob may not run `plan` here: it is limited to `team:acme\/release`, `Carol`/);
262
+ });
263
+
264
+ test("makes Forgejo's requests, and a pending invitation is not membership", async () => {
265
+ const env = { ...base, GITHUB_API_URL: "https://git.example/api/v1", CHANT_COMMENT_ALLOW_FORGE: "forgejo" };
266
+ const table = under(FJ, { "/orgs/acme/teams/search?q=release&limit=50": { status: 200, body: FJ_SEARCH }, "/teams/42/members/alice": { status: 204 } });
267
+ expect((await gate(env, "alice", "plan", table)).result).toBeUndefined();
268
+ expect((await gate(env, "bob", "plan", table)).result).toMatch(/bob may not run/);
269
+ const pending = await gate(base, "pat", "plan", { "/orgs/acme/teams/release": { status: 200, body: GH_TEAM }, "/orgs/acme/teams/release/memberships/pat": { status: 200, body: GH_PENDING } });
270
+ expect(pending.result).toMatch(/pat may not run/);
271
+ });
272
+
273
+ test("throws when a team cannot be read, so the decision fails and nothing is planned", async () => {
274
+ await expect(gate(base, "bob", "plan", { "/orgs/acme/teams/release": { status: 404 } })).rejects.toThrow(/could not read team membership for bob, so nothing runs \(GitHub team acme\/release answered 404/);
275
+ await expect(gate({ ...base, [COMMENT_ALLOW_ENV]: "{" }, "bob", "plan", {})).rejects.toThrow(/not JSON/);
276
+ });
277
+ });
278
+
279
+ describe("the re-plan's decision with a list", () => {
280
+ /** The whole decision script, against an event file and a forge that answers from a table. */
281
+ async function decide(opts: { allow?: boolean; reply?: boolean; dispatch?: boolean }, env: Record<string, string>, who: string, table: Record<string, Answer>) {
282
+ const dir = mkdtempSync(join(tmpdir(), "chant-allow-"));
283
+ const eventFile = join(dir, "event.json");
284
+ const out = join(dir, "output");
285
+ writeFileSync(eventFile, JSON.stringify({ comment: { body: "/terragucci plan", user: { login: who } }, issue: { number: 12, pull_request: {} } }));
286
+ writeFileSync(out, "");
287
+ const t = recorded(table);
288
+ const logs: string[] = [];
289
+ let exit: number | undefined;
290
+ const proc = { env: { ...env, GITHUB_EVENT_PATH: eventFile, GITHUB_OUTPUT: out, GITHUB_REPOSITORY: "acme/infra", CHANT_REPLAN_COMMANDS: '["/terragucci plan"]' }, exit: (c: number) => { exit = c; } };
291
+ const run = new Function("process", "fetch", "require", "console", replanDecideJs(opts));
292
+ run(proc, t.fetch, (m: string) => (m === "fs" ? { readFileSync, appendFileSync: (f: string, d: string) => writeFileSync(f, readFileSync(f, "utf8") + d) } : undefined), { log: (m: string) => logs.push(m), error: (m: string) => logs.push(m) });
293
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
294
+ return { output: readFileSync(out, "utf8"), logs, exit, seen: t.seen, posts: t.posts };
295
+ }
296
+ const SHA = "c".repeat(40);
297
+ const pr = { "/repos/acme/infra/pulls/12": { status: 200, body: { state: "open", head: { sha: SHA, repo: { full_name: "acme/infra" } }, base: { sha: SHA } } } };
298
+ const team = { "/orgs/acme/teams/release": { status: 200, body: GH_TEAM }, "/orgs/acme/teams/release/memberships/alice": { status: 200, body: GH_ACTIVE } };
299
+ const env = { GITHUB_API_URL: "https://api.github.com", CHANT_REPLAN_TOKEN: "job-tok", [COMMENT_ALLOW_ENV]: JSON.stringify({ plan: ["team:acme/release"] }) };
300
+
301
+ test("a member plans, a writer outside the team does not, and neither pays for a request without a list", async () => {
302
+ const yes = await decide({ allow: true }, env, "alice", { ...pr, ...team });
303
+ expect(yes.output).toMatch(/^go=1\npr=12\n/m);
304
+ const no = await decide({ allow: true }, env, "bob", { ...pr, ...team });
305
+ expect(no.output).toBe("");
306
+ expect(no.logs.join("\n")).toMatch(/bob may not run `plan` here.*so nothing is planned again/);
307
+ const plain = await decide({}, env, "bob", pr);
308
+ expect(plain.output).toMatch(/^go=1/);
309
+ expect(plain.seen.every((s) => !s.url.startsWith("/orgs"))).toBe(true);
310
+ });
311
+
312
+ test("with reply, the re-plan posts the refusal itself, once, as the product", async () => {
313
+ const forgejoEnv = { ...env, CHANT_REPLAN_PERMISSION: "1", CHANT_REPLAN_PRODUCT: "/terragucci" };
314
+ const perm = { "/repos/acme/infra/collaborators/bob/permission": { status: 200, body: { permission: "write" } } };
315
+ const got = await decide({ allow: true, reply: true }, forgejoEnv, "bob", { ...pr, ...team, ...perm });
316
+ expect(got.output).toBe("");
317
+ expect(got.posts).toEqual([expect.stringMatching(/^terragucci: bob may not run `plan` here: it is limited to `team:acme\/release`.*, so nothing is planned again$/)]);
318
+ const quiet = await decide({ allow: true }, env, "bob", { ...pr, ...team });
319
+ expect(quiet.output).toBe("");
320
+ });
321
+
322
+ test("with reply, the check comes after the permission and holds the same", async () => {
323
+ const forgejoEnv = { ...env, CHANT_REPLAN_PERMISSION: "1" };
324
+ const perm = (p: string) => ({ "/repos/acme/infra/collaborators/bob/permission": { status: 200, body: { permission: p } }, "/repos/acme/infra/collaborators/alice/permission": { status: 200, body: { permission: "write" } } });
325
+ const no = await decide({ allow: true, reply: true }, forgejoEnv, "bob", { ...pr, ...team, ...perm("write") });
326
+ expect(no.output).toBe("");
327
+ expect(no.logs.join("\n")).toMatch(/bob may not run/);
328
+ const yes = await decide({ allow: true, reply: true }, forgejoEnv, "alice", { ...pr, ...team, ...perm("write") });
329
+ expect(yes.output).toMatch(/^go=1/);
330
+ });
331
+
332
+ test("a team that cannot be read fails the decision with a non-zero exit", async () => {
333
+ const got = await decide({ allow: true }, env, "alice", { ...pr, "/orgs/acme/teams/release": { status: 404 } });
334
+ expect(got.output).toBe("");
335
+ expect(got.exit).toBe(1);
336
+ expect(got.logs.join("\n")).toMatch(/the re-plan could not decide: could not read team membership for alice, so nothing runs/);
337
+ });
338
+
339
+ test("without the option the script is the one chant wrote before", () => {
340
+ expect(replanDecideJs({})).not.toContain("commentAllowRefusal");
341
+ expect(replanDecideJs({ allow: true })).toContain("commentAllowRefusal(asker,\"plan\")");
342
+ expect(replanDecideJs({ allow: true })).not.toContain("'");
343
+ });
344
+ });
345
+
346
+ describe("productPipelineJobs", () => {
347
+ const words = { product: "terragucci", noun: ["root", "roots"] as [string, string], commands: { plan: "plan" as const, apply: "apply" as const, lock: "lock" as const, unlock: "unlock" as const, agent: "agent" as const }, approval: "per-wave" as const, op: "tf-apply" };
348
+ const waves = { name: "tf-apply", op: "tf-apply", planWave: ["terragucci", "plan-wave", "--runs", "{runs}", "--plans", "{plans}"], applyWave: ["terragucci", "apply-wave", "--runs", "{runs}", "--plans", "{plans}"], waves: [{ name: "n", runs: [{ target: "a" }] }] };
349
+ const plan = { command: "terragucci plan --pr-report {output}", workflow: "terragucci-pr", replan: true };
350
+ const allow = { allow: { apply: ["team:acme/release"], plan: ["alice"], agent: ["team:acme/ai"] }, tokenSecret: "TG_TEAM_TOKEN" };
351
+
352
+ test("writes the map and the team token into the comment job, the re-plan and the agent", () => {
353
+ const jobs = productPipelineJobs("github", "default", { words, productPlan: plan, commentJob: true, waves, agent: true, commentAllow: allow });
354
+ expect(JSON.parse(jobs.comment!.env.CHANT_COMMENT_ALLOW!)).toEqual(allow.allow);
355
+ expect(jobs.comment!.env.CHANT_COMMENT_ALLOW_TOKEN).toBe("${{ secrets.TG_TEAM_TOKEN }}");
356
+ expect(jobs.productPlan![0]!.replan!.allow).toEqual({ list: allow.allow, tokenSecret: "TG_TEAM_TOKEN" });
357
+ expect(jobs.agent!.spec.agent).toMatchObject({ commentAllow: allow.allow, commentAllowTokenEnv: "TG_TEAM_TOKEN" });
358
+ });
359
+
360
+ test("leaves the jobs as they were without it, and the re-plan alone when the plan comment has no list", () => {
361
+ const plain = productPipelineJobs("github", "default", { words, productPlan: plan, commentJob: true, waves, agent: true });
362
+ expect(plain.comment!.env).not.toHaveProperty("CHANT_COMMENT_ALLOW");
363
+ expect(plain.productPlan![0]!.replan).not.toHaveProperty("allow");
364
+ expect(plain.agent!.spec.agent).not.toHaveProperty("commentAllow");
365
+ const applyOnly = productPipelineJobs("github", "default", { words, productPlan: plan, commentJob: true, waves, agent: true, commentAllow: { allow: { apply: ["alice"] } } });
366
+ expect(applyOnly.productPlan![0]!.replan).not.toHaveProperty("allow");
367
+ expect(applyOnly.agent!.spec.agent).not.toHaveProperty("commentAllow");
368
+ expect(applyOnly.comment!.env).not.toHaveProperty("CHANT_COMMENT_ALLOW_TOKEN");
369
+ });
370
+
371
+ test("refuses what it cannot carry: GitLab, a bad entry, a secret name, the apply before merge and the comment lock jobs", () => {
372
+ const base = { words, productPlan: plan, commentJob: true, waves };
373
+ expect(() => productPipelineJobs("gitlab", "default", { ...base, words: { ...words, commands: { plan: "plan" as const, apply: "apply" as const } }, commentJob: undefined, noteCommands: true, commentAllow: allow })).toThrow(/GitHub and Forgejo/);
374
+ expect(() => productPipelineJobs("github", "default", { ...base, commentAllow: { allow: { apply: ["team:acme"] } } })).toThrow(/team:<org>\/<team>/);
375
+ expect(() => productPipelineJobs("github", "default", { ...base, commentAllow: { allow: { apply: ["a"] }, tokenSecret: "x y" } })).toThrow(/secret's name/);
376
+ expect(() => productPipelineJobs("github", "default", { words, productPlan: plan, commentJob: true, applyBeforeMerge: true, commentAllow: { allow: { default: ["a"] } } })).toThrow(/applyBeforeMerge/);
377
+ expect(() => productPipelineJobs("github", "default", { ...base, locks: "plan", commentAllow: { allow: { lock: ["a"] } } })).toThrow(/comment lock jobs/);
378
+ expect(() => productPipelineJobs("github", "default", { ...base, locks: "plan", commentAllow: { allow: { plan: ["a"], apply: ["b"] } } })).not.toThrow();
379
+ });
380
+ });
@@ -0,0 +1,184 @@
1
+ /**
2
+ * `comment_allow` on GitHub and Forgejo (INTENTIUS/terragucci#1461): who may
3
+ * run `plan`, `apply`, `lock`, `unlock` and `agent` beyond write access.
4
+ *
5
+ * Every comment command already needs write access. A product that wants a
6
+ * narrower rule gives the pipeline a map of command to logins and teams
7
+ * (`commentAllow` in `productPipelineJobs`), and `default` for every one of
8
+ * the five it does not name:
9
+ *
10
+ * { apply: ["team:acme/release", "alice"], default: ["team:acme/engineering"] }
11
+ *
12
+ * An entry is a login, or `team:<org>/<team>`. The generator writes the map
13
+ * into the jobs that answer those commands as {@link COMMENT_ALLOW_ENV}, so
14
+ * it is read from the workflow on the default branch, which an
15
+ * `issue_comment` run uses, and a pull request cannot add its own author.
16
+ * Team membership is read from the forge with {@link COMMENT_ALLOW_TOKEN_ENV}
17
+ * when the pipeline names a secret for it, else the job's own token; when the
18
+ * forge cannot answer (a token that cannot read the team, a team that does
19
+ * not exist) nothing runs and the reply says what to fix.
20
+ *
21
+ * Where it is checked:
22
+ *
23
+ * - the comment job (./ci-comment-commands.ts), after the write-access check,
24
+ * for every command it answers: apply, lock, unlock, and plan and agent
25
+ * that other jobs run. It posts the reply, so one job speaks;
26
+ * - the product plan's re-plan decision (`replanDecideJs({ allow })`), which
27
+ * runs before the checkout with the token alone, in a script of its own
28
+ * ({@link COMMENT_ALLOW_GATE_JS}) that makes the same requests. It posts the
29
+ * refusal itself when the re-plan has `reply` (the comment job cannot be
30
+ * there beside it) and says nothing otherwise;
31
+ * - the agent's prepare step (`prepareAgentRun`).
32
+ *
33
+ * The apply before merge of the plain pull request loop and chant's comment
34
+ * lock jobs run without this check, so a list for what they answer is refused
35
+ * when the pipeline is built.
36
+ */
37
+
38
+ /** The commands a list names, besides `default`. */
39
+ export const COMMENT_ALLOW_COMMANDS = ["plan", "apply", "lock", "unlock", "agent"] as const;
40
+ export type CommentAllowCommand = (typeof COMMENT_ALLOW_COMMANDS)[number];
41
+
42
+ /** A list of logins and `team:<org>/<team>` entries per command, and `default` for the commands it does not name. */
43
+ export type CommentAllow = Partial<Record<CommentAllowCommand | "default", string[]>>;
44
+
45
+ /** The variable the jobs read the map from, as JSON ({@link CommentAllow}). */
46
+ export const COMMENT_ALLOW_ENV = "CHANT_COMMENT_ALLOW";
47
+ /** The variable team membership is read with, when the pipeline names a secret for it. Absent: the job's own token. */
48
+ export const COMMENT_ALLOW_TOKEN_ENV = "CHANT_COMMENT_ALLOW_TOKEN";
49
+ /** The forge the re-plan's script reads teams from: `github` or `forgejo`. */
50
+ export const COMMENT_ALLOW_FORGE_ENV = "CHANT_COMMENT_ALLOW_FORGE";
51
+
52
+ /** A read that could not answer: the message says what to fix. */
53
+ export class TeamReadError extends Error {}
54
+
55
+ const LOGIN_ENTRY = /^[A-Za-z0-9_][A-Za-z0-9_.@-]{0,99}$/;
56
+ const TEAM_ENTRY = /^team:([A-Za-z0-9_][A-Za-z0-9_.-]{0,99})\/([A-Za-z0-9_][A-Za-z0-9_.-]{0,99})$/;
57
+
58
+ /** Why an entry is not a login or a team, or undefined when it is one. */
59
+ export function commentAllowEntryProblem(entry: unknown): string | undefined {
60
+ if (typeof entry !== "string") return "must be a login or team:<org>/<team>";
61
+ if (entry.startsWith("team:")) return TEAM_ENTRY.test(entry) ? undefined : `${JSON.stringify(entry)} is not a team: write team:<org>/<team>`;
62
+ return LOGIN_ENTRY.test(entry) ? undefined : `${JSON.stringify(entry)} is not a login or a team: write a login, or team:<org>/<team>`;
63
+ }
64
+
65
+ /** The problems with a map, each naming its path under `where`. */
66
+ export function commentAllowProblems(v: unknown, where: string): string[] {
67
+ const names = [...COMMENT_ALLOW_COMMANDS, "default"];
68
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return [`${where} must be a map of command to a list of logins and teams (commands: ${names.join(", ")})`];
69
+ const out: string[] = [];
70
+ for (const [k, list] of Object.entries(v)) {
71
+ if (!names.includes(k)) {
72
+ out.push(`${where}.${k} is not a command this limit covers (commands: ${names.join(", ")})`);
73
+ continue;
74
+ }
75
+ if (!Array.isArray(list) || list.length === 0) {
76
+ out.push(`${where}.${k} must be a list of logins and teams with at least one entry, since an empty list would let nobody run it`);
77
+ continue;
78
+ }
79
+ list.forEach((e, i) => {
80
+ const p = commentAllowEntryProblem(e);
81
+ if (p) out.push(`${where}.${k}[${i}] ${p}`);
82
+ });
83
+ }
84
+ return out;
85
+ }
86
+
87
+ /** The map from {@link COMMENT_ALLOW_ENV}'s value, checked. Undefined when the variable is empty. Throws on a value that is not a map, so a broken value never turns the limit off. */
88
+ export function commentAllowFromEnv(raw: string | undefined): CommentAllow | undefined {
89
+ if (raw === undefined || raw.trim() === "") return undefined;
90
+ let v: unknown;
91
+ try {
92
+ v = JSON.parse(raw);
93
+ } catch {
94
+ throw new Error(`${COMMENT_ALLOW_ENV} is JSON: a map of command to a list of logins and teams`);
95
+ }
96
+ const problems = commentAllowProblems(v, COMMENT_ALLOW_ENV);
97
+ if (problems.length > 0) throw new Error(problems.join("; "));
98
+ return v as CommentAllow;
99
+ }
100
+
101
+ /** The list that governs `command`: its own, else `default`. Undefined: every writer may run it. */
102
+ export function commentAllowList(allow: CommentAllow | undefined, command: CommentAllowCommand): string[] | undefined {
103
+ const list = allow?.[command] ?? allow?.default;
104
+ return list && list.length > 0 ? list : undefined;
105
+ }
106
+
107
+ /** The commands whose list is not empty: the ones `allow` names, or all five with a `default`. */
108
+ export function commentAllowCovers(allow: CommentAllow | undefined): CommentAllowCommand[] {
109
+ return COMMENT_ALLOW_COMMANDS.filter((c) => commentAllowList(allow, c) !== undefined);
110
+ }
111
+
112
+ /** The reads a decision makes: whether a login is in a team. */
113
+ export interface CommentAllowReads {
114
+ teamMember?(team: string, login: string): Promise<boolean>;
115
+ }
116
+
117
+ export type CommentAllowDecision = { ok: true } | { ok: false; reason: string; fail?: true };
118
+
119
+ /**
120
+ * Whether `user`, who already passed the write-access check, may run
121
+ * `command`. No list for it (and no `default`): yes. A listed login needs no
122
+ * read; a team is read one at a time, stopping at the first that holds the
123
+ * user. A team the forge cannot answer for fails closed (`fail`), whatever
124
+ * the other teams say.
125
+ */
126
+ export async function decideCommentAllow(allow: CommentAllow | undefined, command: CommentAllowCommand, user: string, reads: CommentAllowReads | undefined): Promise<CommentAllowDecision> {
127
+ const list = commentAllowList(allow, command);
128
+ if (!list) return { ok: true };
129
+ const me = user.toLowerCase();
130
+ if (list.some((e) => !e.startsWith("team:") && e.toLowerCase() === me)) return { ok: true };
131
+ const teams = list.filter((e) => e.startsWith("team:")).map((e) => e.slice(5));
132
+ const refused = (): CommentAllowDecision => ({ ok: false, reason: `${user} may not run \`${command}\` here: it is limited to ${list.map((e) => `\`${e}\``).join(", ")} (the pipeline's comment limits, read from the default branch)` });
133
+ if (teams.length === 0) return refused();
134
+ if (!reads?.teamMember) return { ok: false, fail: true, reason: `could not read team membership for ${user}, so nothing runs: this forge's reads cannot answer for a team` };
135
+ let unreadable: string | undefined;
136
+ for (const team of teams) {
137
+ try {
138
+ if (await reads.teamMember(team, user)) return { ok: true };
139
+ } catch (err) {
140
+ if (!(err instanceof TeamReadError)) throw err;
141
+ unreadable ??= err.message;
142
+ }
143
+ }
144
+ if (unreadable) return { ok: false, fail: true, reason: `could not read team membership for ${user}, so nothing runs (${unreadable}). ${COMMENT_ALLOW_TOKEN_ENV}, or the job's token, must be able to read the team's members` };
145
+ return refused();
146
+ }
147
+
148
+ /**
149
+ * The script the re-plan's decision runs (`node -e`, before the checkout):
150
+ * `commentAllowRefusal(who, command)` answers undefined when `who` may run
151
+ * `command` and the refusal's text otherwise, and throws when a team cannot
152
+ * be read. It makes the requests {@link decideCommentAllow}'s reads make, from
153
+ * the same variables, with `fetch`.
154
+ */
155
+ export const COMMENT_ALLOW_GATE_JS = [
156
+ "const commentAllowRefusal=async(who,command)=>{",
157
+ `let allow;try{allow=JSON.parse(process.env.${COMMENT_ALLOW_ENV}||"null")}catch{throw new Error("${COMMENT_ALLOW_ENV} is not JSON, so nothing runs")}`,
158
+ "const list=allow&&(allow[command]||allow.default);",
159
+ "if(!Array.isArray(list)||list.length===0)return undefined;",
160
+ "const me=String(who).toLowerCase();",
161
+ 'if(list.some((e)=>!e.startsWith("team:")&&e.toLowerCase()===me))return undefined;',
162
+ 'const teams=list.filter((e)=>e.startsWith("team:")).map((e)=>e.slice(5));',
163
+ 'const refused=who+" may not run `"+command+"` here: it is limited to "+list.map((e)=>"`"+e+"`").join(", ")+" (the pipeline\\u0027s comment limits, read from the default branch)";',
164
+ "if(teams.length===0)return refused;",
165
+ `const api=String(process.env.GITHUB_API_URL||"").replace(/\\/+$/,""),tok=process.env.${COMMENT_ALLOW_TOKEN_ENV}||process.env.CHANT_REPLAN_TOKEN,forgejo=process.env.${COMMENT_ALLOW_FORGE_ENV}==="forgejo";`,
166
+ 'const hit=async(p)=>fetch(api+p,{headers:{authorization:(forgejo?"token ":"Bearer ")+tok,accept:forgejo?"application/json":"application/vnd.github+json"}});',
167
+ "const bad=(what,r)=>new Error(what+\" answered \"+r.status+(r.status===404?\": the team does not exist, or the token cannot see it\":\"\"));",
168
+ "let unreadable;",
169
+ "for(const team of teams){try{",
170
+ 'const cut=team.lastIndexOf("/"),org=encodeURIComponent(team.slice(0,cut)),slug=team.slice(cut+1);',
171
+ "if(forgejo){",
172
+ 'const s=await hit("/orgs/"+org+"/teams/search?q="+encodeURIComponent(slug)+"&limit=50");if(!s.ok)throw bad("searching "+team.slice(0,cut)+\"\\u0027s teams\",s);',
173
+ "const b=await s.json();const t=(Array.isArray(b&&b.data)?b.data:[]).find((x)=>x&&String(x.name).toLowerCase()===slug.toLowerCase());",
174
+ 'if(!t||typeof t.id!=="number")throw new Error(team.slice(0,cut)+" has no team named "+slug+", or the token cannot see it");',
175
+ 'const m=await hit("/teams/"+t.id+"/members/"+encodeURIComponent(who));if(m.status===404)continue;if(!m.ok)throw bad("team "+team+"\\u0027s member list",m);return undefined;',
176
+ "}",
177
+ 'const f=await hit("/orgs/"+org+"/teams/"+encodeURIComponent(slug));if(!f.ok)throw bad("GitHub team "+team,f);',
178
+ 'const m=await hit("/orgs/"+org+"/teams/"+encodeURIComponent(slug)+"/memberships/"+encodeURIComponent(who));if(m.status===404)continue;if(!m.ok)throw bad("team "+team+"\\u0027s membership of "+who,m);',
179
+ 'const b=await m.json();if(b&&b.state==="active")return undefined;',
180
+ "}catch(err){unreadable=unreadable||(err&&err.message?err.message:String(err))}}",
181
+ `if(unreadable)throw new Error("could not read team membership for "+who+", so nothing runs ("+unreadable+"). ${COMMENT_ALLOW_TOKEN_ENV}, or the job\\u0027s token, must be able to read the team\\u0027s members");`,
182
+ "return refused;",
183
+ "};",
184
+ ].join("");
@@ -41,6 +41,13 @@
41
41
  * takes the locks of what the reach line prints at stage apply without
42
42
  * applying, and the unlock releases the pull request's locks.
43
43
  *
44
+ * - with `allow` (INTENTIUS/terragucci#1461, ./ci-comment-allow.ts), a commenter
45
+ * a `plan`, `apply`, `lock`, `unlock` or `agent` list leaves out gets a
46
+ * reply that names the list, whichever job runs the command. The jobs that
47
+ * run `plan` and `agent` make the same check and stay silent (a re-plan
48
+ * with `reply` speaks for itself, and there is no comment job beside it),
49
+ * so one job speaks. A team the forge cannot read fails the job, with a reply.
50
+ *
44
51
  * Who asked comes first. On GitHub the commenter's permission is read from
45
52
  * the forge; Forgejo answers 403 when a job's token asks for another user's
46
53
  * permission, so there the event's `repository.permissions`, computed for
@@ -54,6 +61,7 @@
54
61
  * runs here.
55
62
  */
56
63
 
64
+ import { decideCommentAllow, COMMENT_ALLOW_COMMANDS, type CommentAllow, type CommentAllowCommand, type CommentAllowReads } from "./ci-comment-allow";
57
65
  import { commentTerms, forkReply, memberReply, notRunReply } from "./ci-comment-replies";
58
66
  import { retryApply, type ApplyRerun, type ApplyRetried, type ChantNoteJobs, type StartedRun } from "./ci-note-commands";
59
67
  import { parseProductComment, type CiProductWords, type ParsedProductComment } from "./ci-product-words";
@@ -195,6 +203,10 @@ export interface AnswerCommentOptions {
195
203
  now?: () => string;
196
204
  /** With `jobs.wavesBeforeMerge` (#4984): what the decision reads and writes with. Absent: an open pull request's apply is refused, as before. */
197
205
  beforeMerge?: CommentBeforeMerge;
206
+ /** The pipeline's comment limits (INTENTIUS/terragucci#1461), read from the workflow on the default branch. Absent: write access alone. */
207
+ allow?: CommentAllow;
208
+ /** What team membership is read with when `allow` names a team: the reads of a token that can read teams. Default `reads`. */
209
+ teams?: CommentAllowReads;
198
210
  }
199
211
 
200
212
  /** What the comment job did. */
@@ -295,6 +307,19 @@ export async function answerProductComment(o: AnswerCommentOptions): Promise<Com
295
307
  };
296
308
 
297
309
  if (parsed.kind === "refused") return reply(parsed.reason);
310
+ // INTENTIUS/terragucci#1461: the pipeline's list for the command, after the write-access check above.
311
+ if (o.allow && (COMMENT_ALLOW_COMMANDS as readonly string[]).includes(parsed.kind)) {
312
+ let decision;
313
+ try {
314
+ decision = await decideCommentAllow(o.allow, parsed.kind as CommentAllowCommand, user, o.teams ?? o.reads);
315
+ } catch (err) {
316
+ return broke(`could not check who may run \`${parsed.kind}\` (${message(err)}), so nothing runs`, command);
317
+ }
318
+ if (!decision.ok) {
319
+ const done = await reply(decision.reason);
320
+ return decision.fail ? { ...done, fail: true } : done;
321
+ }
322
+ }
298
323
  // The product plan's re-plan skips these without a word: a target that is none of its own, and a fork with forks: "skip".
299
324
  if (parsed.kind === "plan" && o.jobs.preview) {
300
325
  // #4979: the product plan's re-plan plans what its verb plans, and takes no flag the grammar reads.