@niwa-labs/forge 0.0.0-stage → 0.0.0

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.
package/src/targets.ts ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The targets of forge actions, as the rules of a grant name them.
3
+ *
4
+ * A target is segments between `/`: `<host>/<path>` for a repository, `<host>/<path>/pr/<n>` for a
5
+ * pull request and `<host>/<path>/ref/<ref>` for a branch or a tag. A rule may end in `/*`, so
6
+ * `forge.pr.merge@gitlab.example.com/acme/billing/pr/*` covers every pull request of one project and
7
+ * nothing else. A template fills the repository from the input of a run:
8
+ * `forge.pr.merge@{repo.host}/{repo.path}/pr/*`.
9
+ */
10
+
11
+ import { callTarget } from "@niwa-labs/core";
12
+ import { z } from "zod";
13
+
14
+ /**
15
+ * The name of a GitLab server as a target names it: a DNS name, lower case, without a scheme or a
16
+ * port. A target segment cannot hold `:`, so a server on a port is configured by its URL and named
17
+ * here by its host alone.
18
+ */
19
+ export const ForgeHost = z
20
+ .string()
21
+ .regex(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/, "a host name, lower case, without a scheme or a port");
22
+ export type ForgeHost = z.infer<typeof ForgeHost>;
23
+
24
+ /** One segment of a project path: what GitLab allows in a group or project name. */
25
+ const PATH_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
26
+
27
+ /** The full path of a project, `group/subgroup/project`. */
28
+ export const ProjectPath = z
29
+ .string()
30
+ .refine((path) => path.split("/").length >= 2 && path.split("/").every((segment) => PATH_SEGMENT.test(segment) && !segment.endsWith(".git")), {
31
+ message: "a project path is its groups and its name between \"/\", such as acme/billing",
32
+ });
33
+ export type ProjectPath = z.infer<typeof ProjectPath>;
34
+
35
+ /** A repository as a caller names it: the server and the path of the project. */
36
+ export const RepoName = z.strictObject({ host: ForgeHost, path: ProjectPath });
37
+ export type RepoName = z.infer<typeof RepoName>;
38
+
39
+ /**
40
+ * A branch or a tag, as GitLab names it. It may hold `/` (`feature/login`); it may not be empty,
41
+ * hold whitespace, `*`, `@`, `:` or braces, or have an empty segment: the target it makes must name
42
+ * one place and widen nothing.
43
+ */
44
+ export const RefName = z
45
+ .string()
46
+ .min(1)
47
+ .refine((ref) => ref.split("/").every((segment) => segment.length > 0 && !/[\s*@:{}]/.test(segment)), {
48
+ message: "a ref is segments between \"/\", none empty, without whitespace, \"*\", \"@\", \":\" or braces",
49
+ });
50
+
51
+ /** The target of a repository: `<host>/<path>`. */
52
+ export function repoTarget(repo: RepoName): string {
53
+ return callTarget(`${repo.host}/${repo.path}`);
54
+ }
55
+
56
+ /**
57
+ * The target of a pull request: `<host>/<path>/pr/<n>`. A pull request that does not exist yet has
58
+ * the number `new`, which a rule `…/pr/*` covers.
59
+ */
60
+ export function prTarget(repo: RepoName, number: number | "new"): string {
61
+ return callTarget(`${repoTarget(repo)}/pr/${String(number)}`);
62
+ }
63
+
64
+ /** The target of a branch or a tag: `<host>/<path>/ref/<ref>`. */
65
+ export function refTarget(repo: RepoName, ref: string): string {
66
+ return callTarget(`${repoTarget(repo)}/ref/${ref}`);
67
+ }
68
+
69
+ /** The template of a rule on the pull requests of the repository a run is given as `repo`. */
70
+ export function prRule(action: string): string {
71
+ return `${action}@{repo.host}/{repo.path}/pr/*`;
72
+ }
73
+
74
+ /** The template of a rule on the refs of the repository a run is given as `repo`. */
75
+ export function refRule(action: string): string {
76
+ return `${action}@{repo.host}/{repo.path}/ref/*`;
77
+ }
78
+
79
+ /** The template of a rule on the repository a run is given as `repo`. */
80
+ export function repoRule(action: string): string {
81
+ return `${action}@{repo.host}/{repo.path}`;
82
+ }
@@ -0,0 +1,59 @@
1
+ // What a push to a branch of a watched repository means for the worktrees niwa keeps: a built-in
2
+ // workflow of the forge module, on the forge's own `forge.push`, that reads the git module's
3
+ // worktrees. It lives here, as a workflow of the two, and not in the git module, so local git has no
4
+ // hidden need of a forge.
5
+ //
6
+ // A worktree belongs to the repository that was pushed to when the remote its base pushes to, as
7
+ // `git.worktree.list` shows it, is that repository. The owner may also name local checkouts
8
+ // (`forge({ pushReaction: { checkouts } })`) for clones whose remote the git module does not verify.
9
+ // A push to a branch that such worktrees were made from leaves them behind it, unless their head is
10
+ // already the pushed commit; the run answers which, for a composition to act on.
11
+
12
+ /** What the push record holds, as much of it as the script reads. */
13
+ interface Push {
14
+ repo: { host: string; path: string };
15
+ ref: string;
16
+ refType: "branch" | "tag";
17
+ after?: string;
18
+ }
19
+
20
+ /** One worktree as `git.worktree.list` shows it. */
21
+ interface Listed {
22
+ id: string;
23
+ state: "ok" | "missing" | "orphan";
24
+ repo?: string;
25
+ base?: string;
26
+ head?: string;
27
+ remote?: { name: string; host: string; path: string };
28
+ }
29
+
30
+ declare const call: (name: string, input: unknown, opts?: { label?: string }) => Promise<any>;
31
+ declare const workflow: (
32
+ declaration: { on: Array<string | { type: string; filter?: Record<string, unknown> }>; uses: string[]; output: unknown },
33
+ run: (trigger: { data: Push }) => Promise<{ ref: string; behind: string[] }>,
34
+ ) => unknown;
35
+ declare const z: { object(shape: Record<string, unknown>): unknown; string(): unknown; array(of: unknown): { optional(): unknown } & object };
36
+
37
+ export default workflow(
38
+ {
39
+ on: [{ type: "forge.push", filter: { refType: "branch" } }],
40
+ uses: ["forge.push.config", "git.worktree.list"],
41
+ output: z.object({ ref: z.string(), behind: z.array(z.string()) }),
42
+ },
43
+ async ({ data }) => {
44
+ if (data.after === undefined) return { ref: data.ref, behind: [] };
45
+ const { checkouts } = (await call("forge.push.config", {}, { label: "config" })) as { checkouts: Record<string, string[]> };
46
+ const local = checkouts[`${data.repo.host}/${data.repo.path}`] ?? [];
47
+ const { items } = (await call("git.worktree.list", {}, { label: "worktrees" })) as { items: Listed[] };
48
+ const behind = items
49
+ .filter(
50
+ (item) =>
51
+ item.state === "ok" &&
52
+ item.base === data.ref &&
53
+ item.head !== data.after &&
54
+ ((item.remote?.host === data.repo.host && item.remote.path === data.repo.path) || (item.repo !== undefined && local.includes(item.repo))),
55
+ )
56
+ .map((item) => item.id);
57
+ return { ref: data.ref, behind };
58
+ },
59
+ );
@@ -0,0 +1,235 @@
1
+ // The actions of the forge module against a fake server: what they read and change there, the class
2
+ // each declares, the grants that let them through, and the token that never reaches the journal.
3
+
4
+ import { afterEach, expect, test } from "bun:test";
5
+
6
+ import { forgeCommentCreate, forgeCommentRead, forgeJobLog, forgeJobRun, forgePipelineRead, forgePipelineRetry, forgePipelineTrigger, forgePrClose, forgePrEnsure, forgePrMerge, forgePrRead, forgeRepoList, forgeRepoWatch, secret } from "../src/index.ts";
7
+ import { sha } from "./fake-gitlab.ts";
8
+ import { BILLING, forgeHost, openMr } from "./support.ts";
9
+ import type { ForgeHost } from "./support.ts";
10
+
11
+ const hosts: ForgeHost[] = [];
12
+ afterEach(async () => {
13
+ for (const host of hosts.splice(0)) await host.stop();
14
+ });
15
+
16
+ async function served(opts: Parameters<typeof forgeHost>[0] = {}): Promise<ForgeHost> {
17
+ const host = await forgeHost(opts);
18
+ hosts.push(host);
19
+ return host;
20
+ }
21
+
22
+ test("a pull request is read with the token of the host's secret file", async () => {
23
+ const host = await served();
24
+ openMr(host);
25
+ const pr = await host.niwa.call(forgePrRead, { repo: BILLING, number: 7 });
26
+ expect(pr).toMatchObject({ pr: { repo: { ...BILLING, projectId: 42 }, number: 7 }, state: "open", branch: "topic", base: "main", head: sha("topic-1") });
27
+ expect(host.server.requests.every((one) => one.headers["PRIVATE-TOKEN"] === host.server.token)).toBe(true);
28
+ });
29
+
30
+ test("a token file others can read is refused, and the variable of the environment is taken when there is no file", async () => {
31
+ const unsafe = await served({ tokenMode: 0o644 });
32
+ openMr(unsafe);
33
+ await expect(unsafe.niwa.call(forgePrRead, { repo: BILLING, number: 7 })).rejects.toThrow(/0600/);
34
+ expect(unsafe.server.requests).toHaveLength(0);
35
+
36
+ const fromEnv = await served({ tokenMode: false, env: { NIWA_SECRET_GITLAB_TOKEN: "glpat-test-token" } });
37
+ openMr(fromEnv);
38
+ expect((await fromEnv.niwa.call(forgePrRead, { repo: BILLING, number: 7 })).state).toBe("open");
39
+ expect(fromEnv.server.requests.at(-1)?.headers["PRIVATE-TOKEN"]).toBe("glpat-test-token");
40
+ });
41
+
42
+ test("neither the token nor a secret variable is written to the journal, on success or on failure", async () => {
43
+ const host = await served({ env: { NIWA_SECRET_DEPLOY_KEY: "s3cr3t-deploy-value" } });
44
+ openMr(host);
45
+ await host.niwa.call(forgeRepoWatch, { repo: BILLING });
46
+ await host.niwa.call(forgePipelineTrigger, { repo: BILLING, ref: "main", variables: { DEPLOY_KEY: secret("DEPLOY_KEY"), MODE: "dry" } });
47
+ const pipeline = [...host.billing.variables.values()][0];
48
+ expect(pipeline).toEqual([
49
+ { key: "DEPLOY_KEY", value: "s3cr3t-deploy-value" },
50
+ { key: "MODE", value: "dry" },
51
+ ]);
52
+ host.server.token = "glpat-rotated";
53
+ await expect(host.niwa.call(forgePrRead, { repo: BILLING, number: 7 })).rejects.toThrow(/401/);
54
+ const journal = JSON.stringify(await host.records());
55
+ expect(journal).toContain("forge.repo.watched");
56
+ expect(journal).not.toContain("glpat-test-token");
57
+ expect(journal).not.toContain("s3cr3t-deploy-value");
58
+ });
59
+
60
+ test("each action declares its class: reads read, merging and pipelines are irreversible, watching writes niwa's own records", async () => {
61
+ const host = await served();
62
+ const described = new Map((await host.niwa.describe()).actions.map((one) => [one.name as string, one]));
63
+ expect(described.get("forge.pr.merge")).toMatchObject({ effect: "irreversible", world: "external", recovery: "do-not-repeat" });
64
+ expect(described.get("forge.pr.read")).toMatchObject({ effect: "read", world: "external" });
65
+ expect(described.get("forge.pr.ensure")).toMatchObject({ effect: "write", world: "external", idempotent: true });
66
+ expect(described.get("forge.comment.create")).toMatchObject({ effect: "write", world: "external", recovery: "do-not-repeat" });
67
+ expect(described.get("forge.repo.watch")).toMatchObject({ effect: "record", world: "niwa" });
68
+ for (const name of ["forge.pipeline.trigger", "forge.pipeline.retry", "forge.pipeline.cancel", "forge.job.retry", "forge.job.cancel", "forge.job.run"]) {
69
+ expect(described.get(name)).toMatchObject({ effect: "irreversible", world: "external" });
70
+ }
71
+ });
72
+
73
+ test("a mask lets a caller write on pull requests but never merge or touch a pipeline; a rule that names merge on one project does", async () => {
74
+ const host = await served();
75
+ openMr(host);
76
+ host.server.mr(host.payroll, { iid: 7, source_branch: "topic", sha: sha("payroll") });
77
+ const masked = await host.as(["forge.*"]);
78
+ expect(await masked.call(forgePrClose, { repo: BILLING, number: 7 })).toMatchObject({ closed: true });
79
+ await expect(masked.call(forgePrMerge, { repo: BILLING, number: 7, expectHead: sha("topic-1"), method: "merge" })).rejects.toThrow(/grant/);
80
+ await expect(masked.call(forgePipelineRetry, { repo: BILLING, ref: "main", pipeline: 1 })).rejects.toThrow(/grant/);
81
+
82
+ host.billing.mrs.get(7)!.state = "opened";
83
+ const named = await host.as(["forge.pr.merge@gitlab.example.com/acme/billing/pr/*"]);
84
+ expect(await named.call(forgePrMerge, { repo: BILLING, number: 7, expectHead: sha("topic-1"), method: "merge" })).toMatchObject({ outcome: "merged" });
85
+ const payroll = { host: BILLING.host, path: "acme/payroll" };
86
+ await expect(named.call(forgePrMerge, { repo: payroll, number: 7, expectHead: sha("payroll"), method: "merge" })).rejects.toThrow(/grant/);
87
+ expect(host.payroll.mrs.get(7)?.state).toBe("opened");
88
+ });
89
+
90
+ test("a read is granted on the repository, a write on the pull request it changes", async () => {
91
+ const host = await served();
92
+ openMr(host);
93
+ const reader = await host.as(["forge.pr.read@gitlab.example.com/acme/billing", "forge.comment.*@gitlab.example.com/acme/billing/pr/7"]);
94
+ expect((await reader.call(forgePrRead, { repo: BILLING, number: 7 })).state).toBe("open");
95
+ expect(await reader.call(forgeCommentCreate, { repo: BILLING, number: 7, body: "Looks good" })).toMatchObject({ discussion: expect.any(String) });
96
+ await expect(reader.call(forgeCommentCreate, { repo: BILLING, number: 8, body: "No" })).rejects.toThrow(/grant/);
97
+ await expect(reader.call(forgePrRead, { repo: { ...BILLING, path: "acme/payroll" }, number: 7 })).rejects.toThrow(/grant/);
98
+ });
99
+
100
+ test("ensure opens a pull request of a branch once, finds it again, and updates it by its number", async () => {
101
+ const host = await served();
102
+ host.billing.branches.set("feature/login", sha("login-1"));
103
+ const first = await host.niwa.call(forgePrEnsure, { repo: BILLING, branch: "feature/login", base: "main", title: "Login" });
104
+ expect(first).toMatchObject({ created: true, head: sha("login-1") });
105
+ const same = await host.niwa.call(forgePrEnsure, { repo: BILLING, branch: "feature/login", base: "main", title: "Login" });
106
+ expect(same).toMatchObject({ created: false, pr: { number: first.pr.number } });
107
+ const again = await host.niwa.call(forgePrEnsure, { repo: BILLING, number: first.pr.number, branch: "feature/login", base: "develop", title: "Login, again", draft: true });
108
+ expect(again).toMatchObject({ created: false, pr: { number: first.pr.number } });
109
+ expect(host.billing.mrs.get(first.pr.number)).toMatchObject({ title: "Draft: Login, again", target_branch: "develop" });
110
+ expect(host.billing.mrs.size).toBe(1);
111
+ });
112
+
113
+ test("ensure with a number reopens a closed pull request and updates it, so the answer is an open one", async () => {
114
+ const host = await served();
115
+ openMr(host);
116
+ host.billing.mrs.get(7)!.state = "closed";
117
+ const owner = await host.as(["forge.pr.ensure@gitlab.example.com/acme/billing/pr/7"]);
118
+ expect(await owner.call(forgePrEnsure, { repo: BILLING, number: 7, branch: "topic", base: "main", title: "Back again" })).toMatchObject({ created: false, pr: { number: 7 } });
119
+ expect(host.billing.mrs.get(7)).toMatchObject({ state: "opened", title: "Back again" });
120
+ expect(host.server.seen("PUT", /merge_requests\/7$/)[0]?.body).toMatchObject({ state_event: "reopen" });
121
+ });
122
+
123
+ test("ensure with a number refuses a pull request that is merged or locked, and changes nothing", async () => {
124
+ const host = await served();
125
+ openMr(host);
126
+ const owner = await host.as(["forge.pr.ensure@gitlab.example.com/acme/billing/pr/7"]);
127
+ const ensure = () => owner.call(forgePrEnsure, { repo: BILLING, number: 7, branch: "topic", base: "main", title: "Renamed" }).catch((caught: unknown) => caught) as Promise<Error>;
128
+ host.billing.mrs.get(7)!.state = "merged";
129
+ expect(await ensure()).toMatchObject({ message: expect.stringContaining("is merged") });
130
+ host.billing.mrs.get(7)!.state = "locked";
131
+ expect(await ensure()).toMatchObject({ message: expect.stringContaining("is locked") });
132
+ expect(host.server.requests.filter((one) => one.method === "PUT")).toHaveLength(0);
133
+ expect(host.billing.mrs.get(7)?.title).toBe("MR 7");
134
+ });
135
+
136
+ test("comments are read with their text from the server, and the text is the step's, not a record's", async () => {
137
+ const host = await served();
138
+ openMr(host);
139
+ await host.niwa.call(forgeCommentCreate, { repo: BILLING, number: 7, body: "Please rename the field" });
140
+ const { items } = await host.niwa.call(forgeCommentRead, { repo: BILLING, number: 7 });
141
+ expect(items).toEqual([expect.objectContaining({ body: "Please rename the field", author: "niwa", resolved: false })]);
142
+ });
143
+
144
+ test("a pipeline or a job of another ref than the one the call names is refused before anything changes", async () => {
145
+ const host = await served();
146
+ const release = host.server.pipeline(host.billing, { sha: sha("v1"), ref: "release", status: "failed" });
147
+ const manual = host.server.job(host.billing, { pipeline: release.id, ref: "release", status: "manual" });
148
+ await expect(host.niwa.call(forgePipelineRetry, { repo: BILLING, ref: "feature/x", pipeline: release.id })).rejects.toThrow(/release/);
149
+ await expect(host.niwa.call(forgeJobRun, { repo: BILLING, ref: "feature/x", job: manual.id })).rejects.toThrow(/release/);
150
+ expect(host.server.requests.filter((one) => one.method === "POST")).toHaveLength(0);
151
+ expect(await host.niwa.call(forgePipelineRetry, { repo: BILLING, ref: "release", pipeline: release.id })).toMatchObject({ state: "running" });
152
+ expect(await host.niwa.call(forgeJobRun, { repo: BILLING, ref: "release", job: manual.id })).toMatchObject({ state: "pending" });
153
+ });
154
+
155
+ test("a watched repository is listed with its project id, and watching it again changes nothing", async () => {
156
+ const host = await served();
157
+ await host.niwa.call(forgeRepoWatch, { repo: BILLING });
158
+ await host.niwa.call(forgeRepoWatch, { repo: BILLING });
159
+ expect(await host.niwa.call(forgeRepoList, {})).toEqual({ items: [{ ...BILLING, projectId: 42 }] });
160
+ expect(await host.records(["forge.repo.watched"])).toHaveLength(1);
161
+ });
162
+
163
+ test("ensure without a number changes no open pull request: a grant on pr/new cannot rewrite pull request 7", async () => {
164
+ const host = await served();
165
+ openMr(host);
166
+ const creator = await host.as(["forge.pr.ensure@gitlab.example.com/acme/billing/pr/new"]);
167
+ await expect(creator.call(forgePrEnsure, { repo: BILLING, branch: "topic", base: "develop", title: "Hijacked" })).rejects.toThrow(/number/);
168
+ expect(host.billing.mrs.get(7)).toMatchObject({ title: "MR 7", target_branch: "main" });
169
+ expect(await creator.call(forgePrEnsure, { repo: BILLING, branch: "topic", base: "main", title: "MR 7" })).toMatchObject({ created: false, pr: { number: 7 } });
170
+ const owner = await host.as(["forge.pr.ensure@gitlab.example.com/acme/billing/pr/7"]);
171
+ expect(await owner.call(forgePrEnsure, { repo: BILLING, number: 7, branch: "topic", base: "develop", title: "Renamed" })).toMatchObject({ created: false });
172
+ expect(host.billing.mrs.get(7)).toMatchObject({ title: "Renamed", target_branch: "develop" });
173
+ });
174
+
175
+ test("a secret value the server repeats in an error is not in the error, nor in the journal", async () => {
176
+ const host = await served({ env: { NIWA_SECRET_DEPLOY_KEY: "s3cr3t-deploy-value" } });
177
+ host.server.queue("POST", /\/pipeline$/, 400, { message: { variables: ["DEPLOY_KEY=s3cr3t-deploy-value is not allowed"] } });
178
+ const error = await host.niwa.call(forgePipelineTrigger, { repo: BILLING, ref: "main", variables: { DEPLOY_KEY: secret("DEPLOY_KEY") } }).catch((caught: unknown) => caught);
179
+ expect(String((error as Error).message)).toContain("is not allowed");
180
+ expect(String((error as Error).message)).not.toContain("s3cr3t-deploy-value");
181
+ expect(JSON.stringify(await host.records())).not.toContain("s3cr3t-deploy-value");
182
+ });
183
+
184
+ test("the pipelines of a commit include a merge result however many pipelines the project ran since", async () => {
185
+ const host = await served();
186
+ openMr(host);
187
+ const mergeSha = sha("merge-result-1");
188
+ host.billing.commits.set(mergeSha, [sha("main-1"), sha("topic-1")]);
189
+ const result = host.server.pipeline(host.billing, { sha: mergeSha, ref: "refs/merge-requests/7/merge", source: "merge_request_event", status: "success" });
190
+ for (let at = 0; at < 60; at += 1) host.server.pipeline(host.billing, { sha: sha(`other-${String(at)}`), ref: "main" });
191
+ const found = await host.niwa.call(forgePipelineRead, { repo: BILLING, sha: sha("topic-1"), kind: "merge-result" });
192
+ expect(found.items.map((one) => [one.pipeline, one.sourceSha, one.mergeSha])).toEqual([[result.id, sha("topic-1"), mergeSha]]);
193
+ });
194
+
195
+ test("a job log counts the bytes the server sent, and a tail that starts inside a character starts after it", async () => {
196
+ const host = await served();
197
+ const pipeline = host.server.pipeline(host.billing, { sha: sha("main"), ref: "main" });
198
+ const bad = new Uint8Array([0xff, 0xfe, 0xff]);
199
+ const text = new TextEncoder().encode(`${"é".repeat(40)}end\n`);
200
+ const trace = new Uint8Array([...bad, ...text]);
201
+ const job = host.server.job(host.billing, { pipeline: pipeline.id, ref: "main", trace });
202
+ const whole = await host.niwa.call(forgeJobLog, { repo: BILLING, job: job.id });
203
+ expect(whole).toMatchObject({ truncated: false, size: trace.length });
204
+ const tail = await host.niwa.call(forgeJobLog, { repo: BILLING, job: job.id, bytes: 7 });
205
+ expect(tail).toMatchObject({ truncated: true, size: trace.length });
206
+ expect(tail.log).toBe("éend\n");
207
+ });
208
+
209
+ test("a secret value that crosses the bound of the error message is taken out before the message is cut", async () => {
210
+ const host = await served({ env: { NIWA_SECRET_DEPLOY_KEY: "s3cr3t-deploy-value" } });
211
+ host.server.queue("POST", /\/pipeline$/, 400, { message: `${"x".repeat(480)}DEPLOY_KEY=s3cr3t-deploy-value is not allowed` });
212
+ const error = (await host.niwa.call(forgePipelineTrigger, { repo: BILLING, ref: "main", variables: { DEPLOY_KEY: secret("DEPLOY_KEY") } }).catch((caught: unknown) => caught)) as Error;
213
+ expect(error.message).not.toContain("s3cr3t");
214
+ expect(error.message).toContain("DEPLOY_KEY=");
215
+ expect(JSON.stringify(await host.records())).not.toContain("s3cr3t");
216
+ });
217
+
218
+ test("the token of the host is taken out of what the server says, even when it is cut by the bound", async () => {
219
+ const host = await served();
220
+ host.server.queue("GET", /\/merge_requests\/7$/, 400, { message: `${"y".repeat(494)}${host.server.token}` });
221
+ const error = (await host.niwa.call(forgePrRead, { repo: BILLING, number: 7 }).catch((caught: unknown) => caught)) as Error;
222
+ expect(error.message).not.toContain("glpat");
223
+ expect(error.message).toContain("yyyy");
224
+ });
225
+
226
+ test("a job log is read up to a bound that keeps the step's outcome small", async () => {
227
+ const host = await served();
228
+ const pipeline = host.server.pipeline(host.billing, { sha: sha("main"), ref: "main" });
229
+ const job = host.server.job(host.billing, { pipeline: pipeline.id, ref: "main", trace: `start\n${"x".repeat(70_000)}\nend\n` });
230
+ const log = await host.niwa.call(forgeJobLog, { repo: BILLING, job: job.id });
231
+ expect(log).toMatchObject({ truncated: true, size: 70_011 });
232
+ expect(log.log.endsWith("end\n")).toBe(true);
233
+ expect(Buffer.byteLength(log.log)).toBe(65_536);
234
+ expect(forgeJobLog.input.safeParse({ repo: BILLING, job: job.id, bytes: 65_537 }).success).toBe(false);
235
+ });
@@ -0,0 +1,55 @@
1
+ // The copy of the forge actions the cockpit module keeps reads what the host answers and sends what it takes,
2
+ // and the merge it shows can be called off with what the host gave.
3
+
4
+ import { afterEach, expect, test } from "bun:test";
5
+ import { actionName } from "@niwa-labs/core";
6
+ import { unreadable, unsendable } from "@niwa-labs/testing";
7
+
8
+ import { forgePrList, forgePrMerge, forgePrMergeCancel, forgePrMergePending, forgeRepoList, forgeRepoSync, forgeRepoWatch } from "../src/index.ts";
9
+ import { cancelMergeAction, pendingAction, prListAction, repoListAction, repoSyncAction } from "../src/cockpit/actions.ts";
10
+ import { cancelInput } from "../src/cockpit/pulls.ts";
11
+ import { sha } from "./fake-gitlab.ts";
12
+ import { BILLING, forgeHost, openMr } from "./support.ts";
13
+ import type { ForgeHost } from "./support.ts";
14
+
15
+ const hosts: ForgeHost[] = [];
16
+ afterEach(async () => {
17
+ for (const host of hosts.splice(0)) await host.stop();
18
+ });
19
+
20
+ test.each([
21
+ ["forge.repo.list", repoListAction, forgeRepoList],
22
+ ["forge.repo.sync", repoSyncAction, forgeRepoSync],
23
+ ["forge.pr.list", prListAction, forgePrList],
24
+ ["forge.pr.merge.pending", pendingAction, forgePrMergePending],
25
+ ["forge.pr.merge.cancel", cancelMergeAction, forgePrMergeCancel],
26
+ ] as const)("%s is sent as the host takes it and its answer is read", (name, copy, real) => {
27
+ expect(String(copy.name)).toBe(name);
28
+ expect(String(real.name)).toBe(name);
29
+ expect(unsendable(copy.input, real.input)).toEqual([]);
30
+ expect(unreadable(copy.output, real.output)).toEqual([]);
31
+ });
32
+
33
+ test("the plugin offers its page to the cockpit", async () => {
34
+ const host = await forgeHost();
35
+ hosts.push(host);
36
+ const catalog = (await host.niwa.call(actionName("niwa.cockpit.catalog"), {})) as { modules: Array<{ id: string; plugin: string }> };
37
+ expect(catalog.modules).toContainEqual(expect.objectContaining({ id: "forge", plugin: "forge" }));
38
+ });
39
+
40
+ test("an armed merge is called off with the input the host gave with it", async () => {
41
+ const host = await forgeHost();
42
+ hosts.push(host);
43
+ await host.niwa.call(forgeRepoWatch, { repo: BILLING });
44
+ openMr(host);
45
+ await host.niwa.call(forgePrMerge, { repo: BILLING, number: 7, expectHead: sha("topic-1"), method: "merge", when: "pipeline" });
46
+ const [armed] = (await host.niwa.call(forgePrMergePending, {})).items;
47
+ if (armed === undefined) throw new Error("the merge was not armed");
48
+
49
+ const input = cancelInput(armed);
50
+ expect(input).toEqual({ repo: BILLING, number: 7 });
51
+ // What the page sends is what the host's own schema takes, the nested repository included.
52
+ expect(forgePrMergeCancel.input.safeParse(input).success).toBe(true);
53
+ expect(await host.niwa.call(forgePrMergeCancel, input!)).toEqual({ cancelled: true });
54
+ expect((await host.niwa.call(forgePrMergePending, {})).items).toEqual([]);
55
+ });
@@ -0,0 +1,58 @@
1
+ // The forge page: how pull requests and pipelines are named and grouped, and which merges the page may call off.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import type { ObservedPr, PendingMerge, PrPipeline, PrRef } from "../src/cockpit/actions.ts";
6
+ import { armedBy, byRepo, cancelInput, pipelineText, prKey, prLabel, repoLabel } from "../src/cockpit/pulls.ts";
7
+
8
+ const A = "a".repeat(40);
9
+ const B = "b".repeat(40);
10
+
11
+ const ref = (path: string, projectId: number, number: number): PrRef => ({ repo: { host: "gitlab.example.com", path, projectId }, number });
12
+
13
+ const entry = (pr: PrRef): ObservedPr => ({ pr, state: "open", title: "t", branch: "topic", base: "main", draft: false, checks: "none", pipelines: [] });
14
+
15
+ const pending = (pr: PrRef, action = "forge.pr.merge.cancel"): PendingMerge => ({
16
+ pr,
17
+ mode: "auto-merge",
18
+ externalId: `${pr.repo.host}/${pr.repo.path}!${String(pr.number)}`,
19
+ expectHead: A,
20
+ cancel: { action, input: { repo: { host: pr.repo.host, path: pr.repo.path }, number: pr.number } },
21
+ });
22
+
23
+ test("a pull request is named as the server names it", () => {
24
+ expect(prLabel(ref("acme/billing", 42, 7))).toBe("acme/billing!7");
25
+ expect(repoLabel({ host: "gitlab.example.com", path: "acme/billing" })).toBe("gitlab.example.com/acme/billing");
26
+ });
27
+
28
+ test("a renamed project keeps its pull requests apart from another project's of the same number", () => {
29
+ expect(prKey(ref("acme/billing", 42, 7))).toBe(prKey(ref("acme/invoicing", 42, 7)));
30
+ expect(prKey(ref("acme/billing", 42, 7))).not.toBe(prKey(ref("acme/billing", 43, 7)));
31
+ });
32
+
33
+ test("a pipeline is told by its number, what it ran on, and for a merge result the pair of commits", () => {
34
+ const head: PrPipeline = { pipeline: 5, kind: "head", state: "running", sourceSha: A };
35
+ expect(pipelineText(head)).toBe("#5 коммит aaaaaaaa");
36
+ expect(pipelineText({ pipeline: 6, kind: "merge-result", state: "success", sourceSha: A, targetSha: B, mergeSha: A })).toBe("#6 результат слияния aaaaaaaa → bbbbbbbb");
37
+ expect(pipelineText({ pipeline: 7, kind: "train", state: "success", sourceSha: A, targetSha: B })).toBe("#7 очередь слияния aaaaaaaa → bbbbbbbb");
38
+ });
39
+
40
+ test("pull requests are grouped by project and keep the order they came in", () => {
41
+ const groups = byRepo([entry(ref("acme/billing", 42, 9)), entry(ref("acme/payroll", 43, 1)), entry(ref("acme/billing", 42, 7))]);
42
+ expect(groups.map((group) => [group.repo.path, group.prs.map((one) => one.pr.number)])).toEqual([
43
+ ["acme/billing", [9, 7]],
44
+ ["acme/payroll", [1]],
45
+ ]);
46
+ });
47
+
48
+ test("the merges the server holds are found by the pull request they are for", () => {
49
+ const held = pending(ref("acme/billing", 42, 7));
50
+ const map = armedBy([held]);
51
+ expect(map.get(prKey(ref("acme/billing", 42, 7)))).toBe(held);
52
+ expect(map.get(prKey(ref("acme/billing", 42, 8)))).toBeUndefined();
53
+ });
54
+
55
+ test("a merge is called off with the host's own input, and only through the action the page knows", () => {
56
+ expect(cancelInput(pending(ref("acme/billing", 42, 7)))).toEqual({ repo: { host: "gitlab.example.com", path: "acme/billing" }, number: 7 });
57
+ expect(cancelInput(pending(ref("acme/billing", 42, 7), "forge.pr.merge.dequeue"))).toBeUndefined();
58
+ });