@intentius/chant 0.124.76 → 0.124.77
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/dist/__fixtures__/agent-guard/plywood.d.ts +8 -0
- package/dist/__fixtures__/agent-guard/plywood.d.ts.map +1 -0
- package/dist/__fixtures__/agent-guard/plywood.js +19 -0
- package/dist/__fixtures__/agent-guard/terragucci.d.ts +8 -0
- package/dist/__fixtures__/agent-guard/terragucci.d.ts.map +1 -0
- package/dist/__fixtures__/agent-guard/terragucci.js +30 -0
- package/dist/__fixtures__/gated-ledger.d.ts +10 -0
- package/dist/__fixtures__/gated-ledger.d.ts.map +1 -0
- package/dist/__fixtures__/gated-ledger.js +51 -0
- package/dist/agent-guard.d.ts +143 -0
- package/dist/agent-guard.d.ts.map +1 -0
- package/dist/agent-guard.js +456 -0
- package/dist/ci-commit.d.ts +54 -3
- package/dist/ci-commit.d.ts.map +1 -1
- package/dist/ci-commit.js +69 -7
- package/dist/ci-own-jobs.d.ts +81 -0
- package/dist/ci-own-jobs.d.ts.map +1 -0
- package/dist/ci-own-jobs.js +234 -0
- package/dist/ci-product.d.ts +39 -0
- package/dist/ci-product.d.ts.map +1 -1
- package/dist/ci-product.js +40 -0
- package/dist/cli/handlers/approve.d.ts +5 -1
- package/dist/cli/handlers/approve.d.ts.map +1 -1
- package/dist/cli/handlers/approve.js +17 -11
- package/dist/cli/handlers/build.d.ts +1 -1
- package/dist/cli/handlers/build.d.ts.map +1 -1
- package/dist/cli/handlers/build.js +88 -2
- package/dist/cli/handlers/commit.d.ts.map +1 -1
- package/dist/cli/handlers/commit.js +3 -1
- package/dist/cli/handlers/notify-relay.d.ts +18 -1
- package/dist/cli/handlers/notify-relay.d.ts.map +1 -1
- package/dist/cli/handlers/notify-relay.js +90 -14
- package/dist/cli/handlers/pr.d.ts.map +1 -1
- package/dist/cli/handlers/pr.js +3 -1
- package/dist/cli/handlers/release.d.ts +5 -1
- package/dist/cli/handlers/release.d.ts.map +1 -1
- package/dist/cli/handlers/release.js +17 -5
- package/dist/cli/handlers/run-generate.d.ts.map +1 -1
- package/dist/cli/handlers/run-generate.js +2 -1
- package/dist/cli/main.d.ts.map +1 -1
- package/dist/cli/main.js +21 -1
- package/dist/cli/parse-args.d.ts.map +1 -1
- package/dist/cli/parse-args.js +60 -4
- package/dist/cli/registry.d.ts +16 -0
- package/dist/cli/registry.d.ts.map +1 -1
- package/dist/components/pr-env-components.d.ts +65 -0
- package/dist/components/pr-env-components.d.ts.map +1 -0
- package/dist/components/pr-env-components.js +163 -0
- package/dist/components/pr-policy.d.ts +15 -0
- package/dist/components/pr-policy.d.ts.map +1 -1
- package/dist/components/pr-policy.js +24 -1
- package/dist/components/release-compile.d.ts +15 -3
- package/dist/components/release-compile.d.ts.map +1 -1
- package/dist/components/release-compile.js +66 -15
- package/dist/gate-policy.d.ts +14 -1
- package/dist/gate-policy.d.ts.map +1 -1
- package/dist/gate-policy.js +16 -6
- package/dist/lexicon.d.ts +17 -1
- package/dist/lexicon.d.ts.map +1 -1
- package/dist/lexicon.js +1 -0
- package/dist/lifecycle/gated-op.d.ts +95 -0
- package/dist/lifecycle/gated-op.d.ts.map +1 -0
- package/dist/lifecycle/gated-op.js +96 -0
- package/dist/lifecycle/git.d.ts.map +1 -1
- package/dist/lifecycle/git.js +83 -2
- package/dist/notify-relay-repo.d.ts +131 -0
- package/dist/notify-relay-repo.d.ts.map +1 -0
- package/dist/notify-relay-repo.js +202 -0
- package/dist/notify-relay.d.ts +25 -1
- package/dist/notify-relay.d.ts.map +1 -1
- package/dist/notify-relay.js +28 -2
- package/dist/op/op-waves-capability.js +2 -2
- package/dist/policy-engine.d.ts +95 -0
- package/dist/policy-engine.d.ts.map +1 -0
- package/dist/policy-engine.js +158 -0
- package/dist/release-floors.d.ts +1 -1
- package/dist/release-floors.js +1 -1
- package/dist/state-export.d.ts +126 -0
- package/dist/state-export.d.ts.map +1 -0
- package/dist/state-export.js +157 -0
- package/dist/state-migration.d.ts +148 -0
- package/dist/state-migration.d.ts.map +1 -0
- package/dist/state-migration.js +147 -0
- package/dist/state-unlock.d.ts +167 -0
- package/dist/state-unlock.d.ts.map +1 -0
- package/dist/state-unlock.js +197 -0
- package/dist/wave-runtime.mjs +329 -329
- package/dist/workspace/declaration.schema.json +1 -1
- package/dist/workspace/release-workflow.d.ts +10 -0
- package/dist/workspace/release-workflow.d.ts.map +1 -1
- package/dist/workspace/release-workflow.js +8 -3
- package/package.json +1 -1
- package/src/__fixtures__/agent-guard/plywood.ts +27 -0
- package/src/__fixtures__/agent-guard/terragucci.ts +39 -0
- package/src/__fixtures__/gated-ledger.ts +58 -0
- package/src/agent-guard.test.ts +320 -0
- package/src/agent-guard.ts +548 -0
- package/src/ci-commit.test.ts +50 -2
- package/src/ci-commit.ts +93 -9
- package/src/ci-own-jobs.test.ts +109 -0
- package/src/ci-own-jobs.ts +253 -0
- package/src/ci-product.ts +81 -0
- package/src/cli/handlers/approve-cwd.test.ts +112 -0
- package/src/cli/handlers/approve.ts +22 -11
- package/src/cli/handlers/build-own-jobs.test.ts +80 -0
- package/src/cli/handlers/build-pr-loop-control.test.ts +88 -0
- package/src/cli/handlers/build-run-group.test.ts +60 -0
- package/src/cli/handlers/build.ts +83 -3
- package/src/cli/handlers/commit.ts +3 -0
- package/src/cli/handlers/notify-relay.ts +99 -17
- package/src/cli/handlers/pr.ts +3 -1
- package/src/cli/handlers/release.ts +15 -5
- package/src/cli/handlers/run-generate.ts +2 -1
- package/src/cli/main.ts +21 -1
- package/src/cli/parse-args.ts +45 -3
- package/src/cli/registry.ts +16 -0
- package/src/components/pr-env-components.test.ts +138 -0
- package/src/components/pr-env-components.ts +214 -0
- package/src/components/pr-policy.test.ts +41 -1
- package/src/components/pr-policy.ts +25 -1
- package/src/components/release-compile.test.ts +47 -0
- package/src/components/release-compile.ts +70 -13
- package/src/gate-policy-bundle.test.ts +14 -0
- package/src/gate-policy.test.ts +7 -0
- package/src/gate-policy.ts +22 -7
- package/src/lexicon.ts +18 -1
- package/src/lifecycle/gated-op.ts +158 -0
- package/src/lifecycle/git.test.ts +92 -0
- package/src/lifecycle/git.ts +71 -2
- package/src/notify-relay-repo.test.ts +284 -0
- package/src/notify-relay-repo.ts +234 -0
- package/src/notify-relay.test.ts +12 -0
- package/src/notify-relay.ts +30 -3
- package/src/op/op-waves-capability.ts +2 -2
- package/src/policy-engine.test.ts +163 -0
- package/src/policy-engine.ts +201 -0
- package/src/release-floors.ts +1 -1
- package/src/state-export.test.ts +125 -0
- package/src/state-export.ts +228 -0
- package/src/state-migration.test.ts +134 -0
- package/src/state-migration.ts +237 -0
- package/src/state-unlock.test.ts +166 -0
- package/src/state-unlock.ts +294 -0
- package/src/workspace/declaration.schema.json +1 -1
- package/src/workspace/release-workflow.test.ts +34 -0
- package/src/workspace/release-workflow.ts +17 -3
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #4759: `chant notify relay --repo <url> --token-env <VAR>` checks its token
|
|
3
|
+
* and clones the repo itself. The forge is a loopback server that answers the
|
|
4
|
+
* forge's REST calls and serves a local bare repository over git's smart
|
|
5
|
+
* HTTP protocol (`git http-backend`), so the clone, the fetch before each
|
|
6
|
+
* click and the ledger push all carry the token as a header. No real forge.
|
|
7
|
+
*/
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
10
|
+
import { createServer, type IncomingMessage, type Server } from "node:http";
|
|
11
|
+
import type { AddressInfo } from "node:net";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { afterAll, afterEach, describe, expect, test } from "vitest";
|
|
14
|
+
import { CHANT_WORDS } from "./ci-product-words";
|
|
15
|
+
import { checkoutRelayDeps } from "./cli/handlers/notify-relay";
|
|
16
|
+
import { parseArgs } from "./cli/parse-args";
|
|
17
|
+
import { relayToken } from "./notify";
|
|
18
|
+
import { decideRelayClick } from "./notify-relay";
|
|
19
|
+
import { checkRelayToken, prepareRelayCheckout, relayGitAuthEnv, relayRepo, type RelayRepo } from "./notify-relay-repo";
|
|
20
|
+
import { cleanScratch, git, scratchDir, writeFiles } from "./workspace/__fixtures__/contract-repo";
|
|
21
|
+
|
|
22
|
+
afterAll(cleanScratch);
|
|
23
|
+
|
|
24
|
+
const KEY = "AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl";
|
|
25
|
+
const TOKEN = "relay-token-for-tests";
|
|
26
|
+
const RELAY_KEY = "relay-key-for-tests";
|
|
27
|
+
const D = `jcs1-sha256:${"a".repeat(64)}`;
|
|
28
|
+
|
|
29
|
+
/** A route's answer: the JSON body, and any response headers. */
|
|
30
|
+
type Route = { body: unknown; headers?: Record<string, string> };
|
|
31
|
+
|
|
32
|
+
interface LoopbackForge {
|
|
33
|
+
url: string;
|
|
34
|
+
/** REST routes by path, as the client asks them (encoded). Anything else answers 404. */
|
|
35
|
+
routes: Map<string, Route>;
|
|
36
|
+
/** Every request's method, path and Authorization header. */
|
|
37
|
+
seen: Array<{ method: string; path: string; auth: string | undefined }>;
|
|
38
|
+
close(): Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const readBody = (req: IncomingMessage): Promise<Buffer> =>
|
|
42
|
+
new Promise((done) => {
|
|
43
|
+
const chunks: Buffer[] = [];
|
|
44
|
+
req.on("data", (c: Buffer) => chunks.push(c));
|
|
45
|
+
req.on("end", () => done(Buffer.concat(chunks)));
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
/** One loopback server: the forge's REST API, and `<owner>/<name>.git` from `gitRoot` through git http-backend. */
|
|
49
|
+
async function loopbackForge(gitRoot?: string): Promise<LoopbackForge> {
|
|
50
|
+
const routes = new Map<string, Route>();
|
|
51
|
+
const seen: LoopbackForge["seen"] = [];
|
|
52
|
+
const server: Server = createServer((req, res) => {
|
|
53
|
+
void (async () => {
|
|
54
|
+
const [path, query = ""] = (req.url ?? "/").split("?");
|
|
55
|
+
seen.push({ method: req.method ?? "GET", path: path!, auth: req.headers.authorization });
|
|
56
|
+
const body = await readBody(req);
|
|
57
|
+
if (gitRoot && /\.git\//.test(path!)) {
|
|
58
|
+
const cgi = spawn("git", ["http-backend"], {
|
|
59
|
+
env: {
|
|
60
|
+
...process.env,
|
|
61
|
+
GIT_PROJECT_ROOT: gitRoot,
|
|
62
|
+
GIT_HTTP_EXPORT_ALL: "1",
|
|
63
|
+
// http-backend serves a push only to an authenticated user.
|
|
64
|
+
REMOTE_USER: "relay",
|
|
65
|
+
PATH_INFO: decodeURIComponent(path!),
|
|
66
|
+
QUERY_STRING: query,
|
|
67
|
+
REQUEST_METHOD: req.method ?? "GET",
|
|
68
|
+
CONTENT_TYPE: req.headers["content-type"] ?? "",
|
|
69
|
+
CONTENT_LENGTH: String(body.length),
|
|
70
|
+
...(req.headers["git-protocol"] ? { GIT_PROTOCOL: String(req.headers["git-protocol"]) } : {}),
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
const out: Buffer[] = [];
|
|
74
|
+
cgi.stdout.on("data", (c: Buffer) => out.push(c));
|
|
75
|
+
cgi.stdin.end(body);
|
|
76
|
+
await new Promise((done) => cgi.on("close", done));
|
|
77
|
+
const all = Buffer.concat(out);
|
|
78
|
+
const split = all.indexOf("\r\n\r\n");
|
|
79
|
+
const head = all.subarray(0, split).toString("utf-8");
|
|
80
|
+
const headers: Record<string, string> = {};
|
|
81
|
+
let status = 200;
|
|
82
|
+
for (const line of head.split("\r\n")) {
|
|
83
|
+
const at = line.indexOf(":");
|
|
84
|
+
const name = line.slice(0, at).trim();
|
|
85
|
+
const value = line.slice(at + 1).trim();
|
|
86
|
+
if (name.toLowerCase() === "status") status = Number(value.split(" ")[0]);
|
|
87
|
+
else headers[name] = value;
|
|
88
|
+
}
|
|
89
|
+
res.writeHead(status, headers);
|
|
90
|
+
res.end(all.subarray(split + 4));
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const hit = routes.get(path!);
|
|
94
|
+
res.writeHead(hit ? 200 : 404, { "content-type": "application/json", ...(hit?.headers ?? {}) });
|
|
95
|
+
res.end(JSON.stringify(hit ? hit.body : { message: "Not Found" }));
|
|
96
|
+
})();
|
|
97
|
+
});
|
|
98
|
+
await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
|
|
99
|
+
return {
|
|
100
|
+
url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
|
|
101
|
+
routes,
|
|
102
|
+
seen,
|
|
103
|
+
close: () => new Promise<void>((done) => server.close(() => done())),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const forges: LoopbackForge[] = [];
|
|
108
|
+
afterEach(async () => {
|
|
109
|
+
for (const f of forges.splice(0)) await f.close();
|
|
110
|
+
});
|
|
111
|
+
async function forge(routes: Record<string, Route | unknown> = {}, gitRoot?: string): Promise<LoopbackForge> {
|
|
112
|
+
const f = await loopbackForge(gitRoot);
|
|
113
|
+
for (const [p, r] of Object.entries(routes)) f.routes.set(p, r && typeof r === "object" && "body" in r ? (r as Route) : { body: r });
|
|
114
|
+
forges.push(f);
|
|
115
|
+
return f;
|
|
116
|
+
}
|
|
117
|
+
const repoAt = (f: LoopbackForge, kind: "github" | "gitlab" | "forgejo"): RelayRepo => {
|
|
118
|
+
const r = relayRepo(`${f.url}/acme/infra.git`, kind);
|
|
119
|
+
if ("error" in r) throw new Error(r.error);
|
|
120
|
+
return r;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
describe("the relay's token (#4759)", () => {
|
|
124
|
+
test("on Forgejo, takes a token whose user neither administers the repo nor may push to the default branch, and pushes as that user", async () => {
|
|
125
|
+
const ok = await forge({ "/api/v1/user": { login: "relay-bot" }, "/api/v1/repos/acme/infra": { permissions: { admin: false, push: true } }, "/api/v1/repos/acme/infra/branches/main": { user_can_push: false } });
|
|
126
|
+
expect(await checkRelayToken(repoAt(ok, "forgejo"), TOKEN, "main")).toEqual({ user: "relay-bot" });
|
|
127
|
+
expect(ok.seen.every((s) => s.auth === `token ${TOKEN}`)).toBe(true);
|
|
128
|
+
const admin = await forge({ "/api/v1/user": { login: "root" }, "/api/v1/repos/acme/infra": { permissions: { admin: true } }, "/api/v1/repos/acme/infra/branches/main": { user_can_push: true } });
|
|
129
|
+
expect(await checkRelayToken(repoAt(admin, "forgejo"), TOKEN, "main")).toEqual({ error: "the token's user administers acme/infra" });
|
|
130
|
+
const pusher = await forge({ "/api/v1/user": { login: "dev" }, "/api/v1/repos/acme/infra": { permissions: { admin: false } }, "/api/v1/repos/acme/infra/branches/main": { user_can_push: true } });
|
|
131
|
+
expect(await checkRelayToken(repoAt(pusher, "forgejo"), TOKEN, "main")).toMatchObject({ error: expect.stringMatching(/may push to main/) });
|
|
132
|
+
// A branch read that does not say counts as a push.
|
|
133
|
+
const silent = await forge({ "/api/v1/user": { login: "dev" }, "/api/v1/repos/acme/infra": { permissions: { admin: false } }, "/api/v1/repos/acme/infra/branches/main": {} });
|
|
134
|
+
expect(await checkRelayToken(repoAt(silent, "forgejo"), TOKEN, "main")).toMatchObject({ error: expect.stringMatching(/may push to main/) });
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test("on GitHub, refuses a classic token, an admin, and an unprotected default branch", async () => {
|
|
138
|
+
const routes = { "/api/v3/repos/acme/infra": { permissions: { admin: false, push: true } }, "/api/v3/repos/acme/infra/branches/main": { protected: true } };
|
|
139
|
+
const ok = await forge(routes);
|
|
140
|
+
expect(await checkRelayToken(repoAt(ok, "github"), TOKEN, "main")).toEqual({ user: "x-access-token" });
|
|
141
|
+
expect(ok.seen.every((s) => s.auth === `Bearer ${TOKEN}`)).toBe(true);
|
|
142
|
+
const classic = await forge({ ...routes, "/api/v3/repos/acme/infra": { body: { permissions: { admin: false } }, headers: { "x-oauth-scopes": "repo" } } });
|
|
143
|
+
expect(await checkRelayToken(repoAt(classic, "github"), TOKEN, "main")).toMatchObject({ error: expect.stringMatching(/classic token/) });
|
|
144
|
+
const admin = await forge({ ...routes, "/api/v3/repos/acme/infra": { permissions: { admin: true } } });
|
|
145
|
+
expect(await checkRelayToken(repoAt(admin, "github"), TOKEN, "main")).toEqual({ error: "the token's account administers acme/infra" });
|
|
146
|
+
const open = await forge({ ...routes, "/api/v3/repos/acme/infra/branches/main": { protected: false } });
|
|
147
|
+
expect(await checkRelayToken(repoAt(open, "github"), TOKEN, "main")).toMatchObject({ error: expect.stringMatching(/not protected/) });
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test("on GitLab, refuses the api scope, a Maintainer, an unprotected branch, and a push level the user holds", async () => {
|
|
151
|
+
const base = {
|
|
152
|
+
"/api/v4/personal_access_tokens/self": { scopes: ["write_repository", "read_api"] },
|
|
153
|
+
"/api/v4/projects/acme%2Finfra": { permissions: { project_access: { access_level: 30 } } },
|
|
154
|
+
"/api/v4/projects/acme%2Finfra/protected_branches/main": { push_access_levels: [{ access_level: 40 }] },
|
|
155
|
+
};
|
|
156
|
+
const ok = await forge(base);
|
|
157
|
+
expect(await checkRelayToken(repoAt(ok, "gitlab"), TOKEN, "main")).toEqual({ user: "oauth2" });
|
|
158
|
+
expect(ok.seen.length).toBe(3);
|
|
159
|
+
const api = await forge({ ...base, "/api/v4/personal_access_tokens/self": { scopes: ["api"] } });
|
|
160
|
+
expect(await checkRelayToken(repoAt(api, "gitlab"), TOKEN, "main")).toMatchObject({ error: expect.stringMatching(/scopes api/) });
|
|
161
|
+
const maintainer = await forge({ ...base, "/api/v4/projects/acme%2Finfra": { permissions: { project_access: { access_level: 30 }, group_access: { access_level: 40 } } } });
|
|
162
|
+
expect(await checkRelayToken(repoAt(maintainer, "gitlab"), TOKEN, "main")).toMatchObject({ error: expect.stringMatching(/Maintainer/) });
|
|
163
|
+
const unprotected = await forge({ "/api/v4/personal_access_tokens/self": base["/api/v4/personal_access_tokens/self"], "/api/v4/projects/acme%2Finfra": base["/api/v4/projects/acme%2Finfra"] });
|
|
164
|
+
expect(await checkRelayToken(repoAt(unprotected, "gitlab"), TOKEN, "main")).toMatchObject({ error: expect.stringMatching(/not a protected branch/) });
|
|
165
|
+
const developers = await forge({ ...base, "/api/v4/projects/acme%2Finfra/protected_branches/main": { push_access_levels: [{ access_level: 30 }] } });
|
|
166
|
+
expect(await checkRelayToken(repoAt(developers, "gitlab"), TOKEN, "main")).toMatchObject({ error: expect.stringMatching(/may push to main/) });
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
test("a forge that will not answer refuses the token", async () => {
|
|
170
|
+
const none = await forge();
|
|
171
|
+
expect(await checkRelayToken(repoAt(none, "github"), TOKEN, "main")).toMatchObject({ error: expect.stringMatching(/could not be read with the token .*answered 404/) });
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
test("refuses a clone address that carries a credential or names no forge, and keeps the token out of every file", () => {
|
|
175
|
+
expect(relayRepo("https://bot:t@github.com/acme/infra.git")).toMatchObject({ error: expect.stringMatching(/must not carry a credential/) });
|
|
176
|
+
expect(relayRepo("git@github.com:acme/infra.git")).toMatchObject({ error: expect.stringMatching(/https clone address/) });
|
|
177
|
+
expect(relayRepo("https://git.example.com/acme/infra.git")).toMatchObject({ error: expect.stringMatching(/pass --forge/) });
|
|
178
|
+
expect(relayRepo("https://gitlab.com/acme/platform/infra.git")).toMatchObject({ forge: "gitlab", path: "acme/platform/infra", apiBase: "https://gitlab.com/api/v4" });
|
|
179
|
+
expect(relayRepo("https://github.com/acme/infra")).toMatchObject({ forge: "github", path: "acme/infra", apiBase: "https://api.github.com" });
|
|
180
|
+
const basic = `Authorization: Basic ${Buffer.from("relay-bot:tok").toString("base64")}`;
|
|
181
|
+
expect(relayGitAuthEnv("relay-bot", "tok")).toEqual({ GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "http.extraHeader", GIT_CONFIG_VALUE_0: basic, GIT_TERMINAL_PROMPT: "0" });
|
|
182
|
+
// Entries the environment already has are kept.
|
|
183
|
+
expect(relayGitAuthEnv("relay-bot", "tok", { GIT_CONFIG_COUNT: "2" })).toEqual({ GIT_CONFIG_COUNT: "3", GIT_CONFIG_KEY_2: "http.extraHeader", GIT_CONFIG_VALUE_2: basic, GIT_TERMINAL_PROMPT: "0" });
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
describe("the relay's flags (#4759)", () => {
|
|
188
|
+
test("--repo takes a clone address for the relay and owner/name for ci serve", () => {
|
|
189
|
+
expect(parseArgs(["notify", "relay", "--repo", "https://github.com/acme/infra.git", "--token-env", "RELAY_TOKEN", "--host", "0.0.0.0", "--port", "8080"])).toMatchObject({ repoUrl: "https://github.com/acme/infra.git", tokenEnv: "RELAY_TOKEN", host: "0.0.0.0", port: ["8080"] });
|
|
190
|
+
expect(parseArgs(["ci", "serve", "--repo", "acme/infra"])).toMatchObject({ ciRepo: "acme/infra" });
|
|
191
|
+
expect(() => parseArgs(["notify", "relay", "--token-env", "not a name"])).toThrow(/--token-env needs a variable's name/);
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
describe("the relay's own checkout (#4759)", () => {
|
|
196
|
+
const SIGNERS = `alice@acme.com,slack:T1/U1 ssh-ed25519 ${KEY}\nbob@acme.com ssh-ed25519 ${KEY}\n`;
|
|
197
|
+
const T = (h: number): string => new Date(Date.now() - 3600_000 + h * 3600_000).toISOString();
|
|
198
|
+
const pending = { version: 1, kind: "pending", op: "tf-apply", gate: "wave-1", timestamp: T(1), expiresAt: T(49), planDigest: D };
|
|
199
|
+
|
|
200
|
+
/** A bare `acme/infra.git` under a scratch root: main with the signers file, and chant/lifecycle with one pending fact. */
|
|
201
|
+
function bareRepo(): { root: string; bare: string; work: string } {
|
|
202
|
+
const root = scratchDir("chant-relay-forge-");
|
|
203
|
+
const bare = join(root, "acme", "infra.git");
|
|
204
|
+
git(root, "init", "-q", "--bare", "-b", "main", bare);
|
|
205
|
+
const work = join(root, "work");
|
|
206
|
+
git(root, "init", "-q", "-b", "main", work);
|
|
207
|
+
writeFiles(work, { ".chant/allowed_signers": SIGNERS });
|
|
208
|
+
git(work, "add", "-A");
|
|
209
|
+
git(work, "commit", "-q", "-m", "main");
|
|
210
|
+
git(work, "push", "-q", bare, "main");
|
|
211
|
+
git(work, "checkout", "-q", "--orphan", "chant/lifecycle");
|
|
212
|
+
git(work, "rm", "-rq", "--cached", ".");
|
|
213
|
+
writeFiles(work, { "_gates/tf-apply.jsonl": `${JSON.stringify(pending)}\n` });
|
|
214
|
+
git(work, "add", "_gates");
|
|
215
|
+
git(work, "commit", "-q", "-m", "ledger");
|
|
216
|
+
git(work, "push", "-q", bare, "chant/lifecycle");
|
|
217
|
+
git(work, "checkout", "-q", "-f", "main");
|
|
218
|
+
return { root, bare, work };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const githubRoutes = { "/api/v3/repos/acme/infra": { permissions: { admin: false, push: true } }, "/api/v3/repos/acme/infra/branches/main": { protected: true } };
|
|
222
|
+
|
|
223
|
+
test("refuses an over-scoped token before it clones anything", async () => {
|
|
224
|
+
const { root } = bareRepo();
|
|
225
|
+
const f = await forge({ ...githubRoutes, "/api/v3/repos/acme/infra/branches/main": { protected: false } }, root);
|
|
226
|
+
const parent = scratchDir();
|
|
227
|
+
const made = await prepareRelayCheckout({ url: `${f.url}/acme/infra.git`, token: TOKEN, forge: "github", parent });
|
|
228
|
+
expect(made).toMatchObject({ error: expect.stringMatching(/^the relay holds only an approve-only token, and this one is more: main is not protected/) });
|
|
229
|
+
// Only the default branch was asked (ls-remote); nothing was cloned.
|
|
230
|
+
expect(readdirSync(parent)).toEqual([]);
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
test("clones the default branch with the token as a header only, reads a signer added since at the tip, and pushes the approval", async () => {
|
|
234
|
+
const { root, bare, work } = bareRepo();
|
|
235
|
+
const f = await forge(githubRoutes, root);
|
|
236
|
+
const made = await prepareRelayCheckout({ url: `${f.url}/acme/infra.git`, token: TOKEN, forge: "github", env: { ...process.env, GIT_CONFIG_COUNT: "0" }, parent: scratchDir() });
|
|
237
|
+
if ("error" in made) throw new Error(made.error);
|
|
238
|
+
expect(made).toMatchObject({ branch: "main", user: "x-access-token" });
|
|
239
|
+
// Every git request carried the token as Basic auth; the checkout's files do not hold it.
|
|
240
|
+
const gitCalls = f.seen.filter((s) => s.path.includes(".git/"));
|
|
241
|
+
expect(gitCalls.length).toBeGreaterThan(0);
|
|
242
|
+
expect(gitCalls.every((s) => s.auth === `Basic ${Buffer.from(`x-access-token:${TOKEN}`).toString("base64")}`)).toBe(true);
|
|
243
|
+
expect(readFileSync(join(made.dir, ".git", "config"), "utf-8")).not.toContain(TOKEN);
|
|
244
|
+
expect(readFileSync(join(made.dir, ".git", "config"), "utf-8")).not.toContain(Buffer.from(`x-access-token:${TOKEN}`).toString("base64"));
|
|
245
|
+
expect(git(made.dir, "remote", "get-url", "origin")).toBe(`${f.url}/acme/infra.git`);
|
|
246
|
+
|
|
247
|
+
// A signer added on main after the clone.
|
|
248
|
+
writeFiles(work, { ".chant/allowed_signers": `${SIGNERS}carol@acme.com,slack:T1/U3 ssh-ed25519 ${KEY}\n` });
|
|
249
|
+
git(work, "commit", "-qam", "add carol");
|
|
250
|
+
git(work, "push", "-q", bare, "main");
|
|
251
|
+
|
|
252
|
+
const prev = { env: { ...process.env }, cwd: process.cwd() };
|
|
253
|
+
Object.assign(process.env, made.gitEnv, { GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" });
|
|
254
|
+
// As chant notify relay runs it: in the checkout, since chant approve writes the ledger of the process's directory (#4760).
|
|
255
|
+
process.chdir(made.dir);
|
|
256
|
+
try {
|
|
257
|
+
const deps = checkoutRelayDeps(made.dir, "chant-relay");
|
|
258
|
+
expect(deps.words).toEqual(CHANT_WORDS);
|
|
259
|
+
const click = (user: string) => ({ app: "slack" as const, chatUser: user, display: user, action: "approve" as const, token: relayToken(RELAY_KEY, { id: "e1", source: "chant", at: new Date().toISOString(), gate: "wave-1", digest: D }) });
|
|
260
|
+
const a = await decideRelayClick(click("slack:T1/U3"), { key: RELAY_KEY }, deps);
|
|
261
|
+
expect(a).toMatchObject({ ok: true, outcome: "approved", principal: "carol@acme.com" });
|
|
262
|
+
const ledger = git(root, "--git-dir", bare, "show", "chant/lifecycle:_gates/tf-apply.jsonl");
|
|
263
|
+
expect(ledger).toMatch(/"resolvedBy":"carol@acme\.com"/);
|
|
264
|
+
expect(ledger).toMatch(/"relayedBy":"chant-relay"/);
|
|
265
|
+
} finally {
|
|
266
|
+
process.chdir(prev.cwd);
|
|
267
|
+
for (const k of Object.keys(process.env)) if (!(k in prev.env)) delete process.env[k];
|
|
268
|
+
Object.assign(process.env, prev.env);
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
test("a click whose fetch of the default branch fails records nothing", async () => {
|
|
273
|
+
const { root } = bareRepo();
|
|
274
|
+
const f = await forge(githubRoutes, root);
|
|
275
|
+
const made = await prepareRelayCheckout({ url: `${f.url}/acme/infra.git`, token: TOKEN, forge: "github", parent: scratchDir() });
|
|
276
|
+
if ("error" in made) throw new Error(made.error);
|
|
277
|
+
// Without the header, the loopback forge still serves git, so point origin somewhere that answers nothing.
|
|
278
|
+
git(made.dir, "remote", "set-url", "origin", "http://127.0.0.1:9/acme/infra.git");
|
|
279
|
+
const deps = checkoutRelayDeps(made.dir, "chant-relay");
|
|
280
|
+
const token = relayToken(RELAY_KEY, { id: "e1", source: "chant", at: new Date().toISOString(), gate: "wave-1", digest: D });
|
|
281
|
+
const a = await decideRelayClick({ app: "slack", chatUser: "slack:T1/U1", display: "alice", action: "approve", token }, { key: RELAY_KEY }, deps);
|
|
282
|
+
expect(a).toMatchObject({ ok: false, outcome: "refused", text: expect.stringMatching(/^Not recorded: cannot fetch main to read the signers at its tip/) });
|
|
283
|
+
});
|
|
284
|
+
});
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `chant notify relay --repo <url> --token-env <VAR>` (#4759): the relay
|
|
3
|
+
* clones the repository itself, so a product's relay container needs no
|
|
4
|
+
* entrypoint of its own.
|
|
5
|
+
*
|
|
6
|
+
* Before it serves, the relay:
|
|
7
|
+
*
|
|
8
|
+
* 1. refuses a token that is more than approve-only. An approve-only token
|
|
9
|
+
* reads the repo and pushes `chant/lifecycle`: it neither administers the
|
|
10
|
+
* repo nor may push to the default branch, and on GitLab it carries no
|
|
11
|
+
* scope beyond `read_api`, `read_repository` and `write_repository`
|
|
12
|
+
* ({@link relayTokenVerdict}). The forge is read with a few GETs of its
|
|
13
|
+
* own ({@link readTokenReach}), kept out of `./pr-forge.ts` so the forge
|
|
14
|
+
* client's bundles do not grow for the relay;
|
|
15
|
+
* 2. clones the repo into a checkout of its default branch. The token goes
|
|
16
|
+
* to git as an `http.extraHeader` in the environment
|
|
17
|
+
* (`GIT_CONFIG_COUNT`/`KEY`/`VALUE`), for this process's git calls only,
|
|
18
|
+
* and is never written to a file or into the remote's address.
|
|
19
|
+
*
|
|
20
|
+
* Each click then fetches the default branch before it reads the signers
|
|
21
|
+
* (`../cli/handlers/notify-relay.ts`), so a signer added since start counts
|
|
22
|
+
* without a restart.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { execFile } from "node:child_process";
|
|
26
|
+
import { mkdtempSync } from "node:fs";
|
|
27
|
+
import { tmpdir } from "node:os";
|
|
28
|
+
import { join } from "node:path";
|
|
29
|
+
import type { ForgeFetch, ForgeKind } from "./pr-forge";
|
|
30
|
+
|
|
31
|
+
/** The repository the relay clones, read from its clone address. */
|
|
32
|
+
export interface RelayRepo {
|
|
33
|
+
forge: ForgeKind;
|
|
34
|
+
/** Lower-cased, with the port when there is one. */
|
|
35
|
+
host: string;
|
|
36
|
+
/** `<scheme>://<host>[:port]`. */
|
|
37
|
+
web: string;
|
|
38
|
+
/** `owner/name`, or GitLab's `group/subgroup/name`. */
|
|
39
|
+
path: string;
|
|
40
|
+
/** The clone address as given. */
|
|
41
|
+
url: string;
|
|
42
|
+
/** The forge's REST base. */
|
|
43
|
+
apiBase: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The relay's clone address and forge, or why they do not name a repository. */
|
|
47
|
+
export function relayRepo(url: string, forge?: string): RelayRepo | { error: string } {
|
|
48
|
+
const u = url.trim();
|
|
49
|
+
if (!/^https?:\/\//.test(u)) return { error: `--repo is the repository's https clone address, such as https://github.com/acme/infra.git (got ${JSON.stringify(url)})` };
|
|
50
|
+
if (/^https?:\/\/[^/]*@/.test(u)) return { error: "--repo must not carry a credential; the token goes in the variable --token-env names" };
|
|
51
|
+
const m = /^(https?):\/\/([^/:]+)(:\d+)?\/(.+?)(?:\.git)?\/?$/.exec(u);
|
|
52
|
+
if (!m || !m[4]!.includes("/")) return { error: `--repo names no owner/name: ${u}` };
|
|
53
|
+
const host = m[2]!.toLowerCase();
|
|
54
|
+
const kind: ForgeKind | undefined = forge === "github" || forge === "gitlab" || forge === "forgejo" ? forge : host === "github.com" ? "github" : host === "gitlab.com" ? "gitlab" : undefined;
|
|
55
|
+
if (forge !== undefined && forge !== "" && kind !== forge) return { error: `--forge is github, gitlab or forgejo (got ${JSON.stringify(forge)})` };
|
|
56
|
+
if (!kind) return { error: `${host} is not github.com or gitlab.com; pass --forge github, gitlab or forgejo` };
|
|
57
|
+
const web = `${m[1]}://${host}${m[3] ?? ""}`;
|
|
58
|
+
const apiBase = kind === "gitlab" ? `${web}/api/v4` : kind === "forgejo" ? `${web}/api/v1` : host === "github.com" ? "https://api.github.com" : `${web}/api/v3`;
|
|
59
|
+
return { forge: kind, host: `${host}${m[3] ?? ""}`, web, path: m[4]!, url: u, apiBase };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* What a token may do in a repository, as {@link readTokenReach} reads it.
|
|
64
|
+
*
|
|
65
|
+
* - GitHub: whether it is a classic token (GitHub sends `x-oauth-scopes` for
|
|
66
|
+
* one), whether its account administers the repository, and whether the
|
|
67
|
+
* default branch is protected.
|
|
68
|
+
* - GitLab: the token's scopes, its user's access level on the project
|
|
69
|
+
* (project or group, the higher), and the push access levels of the
|
|
70
|
+
* default branch's protection, or null when it is not protected.
|
|
71
|
+
* - Forgejo: its user's login, whether that user administers the
|
|
72
|
+
* repository, and whether it may push to the default branch.
|
|
73
|
+
*/
|
|
74
|
+
export type TokenReach =
|
|
75
|
+
| { kind: "github"; classic: boolean; admin: boolean; branchProtected: boolean }
|
|
76
|
+
| { kind: "gitlab"; scopes: string[]; accessLevel: number; pushLevels: number[] | null }
|
|
77
|
+
| { kind: "forgejo"; login: string; admin: boolean; canPush: boolean };
|
|
78
|
+
|
|
79
|
+
const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
80
|
+
|
|
81
|
+
/** The header the forge takes a token in, as chant's forge clients send it. */
|
|
82
|
+
function authHeaders(forge: ForgeKind, token: string): Record<string, string> {
|
|
83
|
+
if (forge === "gitlab") return { "PRIVATE-TOKEN": token, Accept: "application/json" };
|
|
84
|
+
if (forge === "forgejo") return { Authorization: `token ${token}`, Accept: "application/json" };
|
|
85
|
+
return { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json" };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Read what `token` reaches in `repo`, with GETs against the forge's REST base. Throws when a read the check needs is refused. */
|
|
89
|
+
export async function readTokenReach(repo: RelayRepo, token: string, branch: string, fetchImpl: ForgeFetch = globalThis.fetch as unknown as ForgeFetch): Promise<TokenReach> {
|
|
90
|
+
const headers = authHeaders(repo.forge, token);
|
|
91
|
+
const get = async (path: string, missing?: "null"): Promise<{ body: unknown; header: (n: string) => string | null }> => {
|
|
92
|
+
const url = `${repo.apiBase}${path}`;
|
|
93
|
+
const res = await fetchImpl(url, { method: "GET", headers });
|
|
94
|
+
const text = await res.text();
|
|
95
|
+
const header = (n: string): string | null => (res as { headers?: { get(n: string): string | null } }).headers?.get(n) ?? null;
|
|
96
|
+
if (res.status === 404 && missing) return { body: null, header };
|
|
97
|
+
if (!res.ok) throw new Error(`GET ${path} answered ${res.status}`);
|
|
98
|
+
return { body: text ? JSON.parse(text) : null, header };
|
|
99
|
+
};
|
|
100
|
+
const enc = (b: string): string => b.split("/").map(encodeURIComponent).join("/");
|
|
101
|
+
if (repo.forge === "gitlab") {
|
|
102
|
+
const project = `/projects/${encodeURIComponent(repo.path)}`;
|
|
103
|
+
const self = (await get("/personal_access_tokens/self")).body;
|
|
104
|
+
const scopes = isObject(self) && Array.isArray(self.scopes) ? self.scopes.filter((x): x is string => typeof x === "string") : [];
|
|
105
|
+
const got = (await get(project)).body;
|
|
106
|
+
const perms = isObject(got) && isObject(got.permissions) ? got.permissions : {};
|
|
107
|
+
const level = (k: string): number => {
|
|
108
|
+
const v = perms[k];
|
|
109
|
+
return isObject(v) && typeof v.access_level === "number" ? v.access_level : 0;
|
|
110
|
+
};
|
|
111
|
+
const accessLevel = Math.max(level("project_access"), level("group_access"));
|
|
112
|
+
const pb = (await get(`${project}/protected_branches/${encodeURIComponent(branch)}`, "null")).body;
|
|
113
|
+
if (pb === null) return { kind: "gitlab", scopes, accessLevel, pushLevels: null };
|
|
114
|
+
const push = isObject(pb) && Array.isArray(pb.push_access_levels) ? pb.push_access_levels : [];
|
|
115
|
+
const pushLevels = push.map((p) => (isObject(p) && typeof p.access_level === "number" ? p.access_level : undefined)).filter((n): n is number => n !== undefined);
|
|
116
|
+
return { kind: "gitlab", scopes, accessLevel, pushLevels };
|
|
117
|
+
}
|
|
118
|
+
const at = `/repos/${repo.path}`;
|
|
119
|
+
const adminOf = (v: unknown): boolean => isObject(v) && isObject(v.permissions) && v.permissions.admin === true;
|
|
120
|
+
if (repo.forge === "forgejo") {
|
|
121
|
+
const me = (await get("/user")).body;
|
|
122
|
+
const r = (await get(at)).body;
|
|
123
|
+
const b = (await get(`${at}/branches/${enc(branch)}`)).body;
|
|
124
|
+
// Anything but an explicit false counts as a push: a Forgejo that does not say is not trusted.
|
|
125
|
+
return { kind: "forgejo", login: isObject(me) && typeof me.login === "string" ? me.login : "", admin: adminOf(r), canPush: !(isObject(b) && b.user_can_push === false) };
|
|
126
|
+
}
|
|
127
|
+
const r = await get(at);
|
|
128
|
+
const b = (await get(`${at}/branches/${enc(branch)}`)).body;
|
|
129
|
+
return { kind: "github", classic: Boolean(r.header("x-oauth-scopes")), admin: adminOf(r.body), branchProtected: isObject(b) && b.protected === true };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The scopes an approve-only GitLab token may carry. */
|
|
133
|
+
export const RELAY_GITLAB_SCOPES: readonly string[] = ["read_api", "read_repository", "write_repository"];
|
|
134
|
+
/** GitLab's Maintainer access level. */
|
|
135
|
+
const GITLAB_MAINTAINER = 40;
|
|
136
|
+
|
|
137
|
+
/** The git user a token pushes as over https, before the forge names one. */
|
|
138
|
+
export const relayGitUser = (forge: ForgeKind): string => (forge === "github" ? "x-access-token" : "oauth2");
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Why a token reaching `reach` is more than approve-only, or the git user
|
|
142
|
+
* name it pushes as.
|
|
143
|
+
*/
|
|
144
|
+
export function relayTokenVerdict(reach: TokenReach, repoPath: string, branch: string): { user: string } | { error: string } {
|
|
145
|
+
if (reach.kind === "gitlab") {
|
|
146
|
+
const extra = reach.scopes.filter((s) => !RELAY_GITLAB_SCOPES.includes(s));
|
|
147
|
+
if (extra.length > 0) return { error: `the token has the scopes ${extra.join(", ")}; an approve-only token has write_repository and read_api only` };
|
|
148
|
+
if (reach.accessLevel >= GITLAB_MAINTAINER) return { error: `the token's user is a Maintainer or Owner of ${repoPath}; give the relay a Developer` };
|
|
149
|
+
if (reach.pushLevels === null) return { error: `${branch} is not a protected branch, so the token could push to it` };
|
|
150
|
+
if (reach.pushLevels.some((l) => l > 0 && l <= reach.accessLevel)) return { error: `the token's user may push to ${branch}` };
|
|
151
|
+
return { user: relayGitUser("gitlab") };
|
|
152
|
+
}
|
|
153
|
+
if (reach.kind === "github") {
|
|
154
|
+
if (reach.classic) return { error: "a classic token reaches every repo its account can; give the relay a fine-grained token for this repo with Contents: Read and write, and nothing else" };
|
|
155
|
+
if (reach.admin) return { error: `the token's account administers ${repoPath}` };
|
|
156
|
+
if (!reach.branchProtected) return { error: `${branch} is not protected, so the token could push to it` };
|
|
157
|
+
return { user: relayGitUser("github") };
|
|
158
|
+
}
|
|
159
|
+
if (reach.admin) return { error: `the token's user administers ${repoPath}` };
|
|
160
|
+
if (reach.canPush) return { error: `the token's user may push to ${branch}; protect it so only reviewed merges reach it` };
|
|
161
|
+
return { user: reach.login || relayGitUser("forgejo") };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Read what the token reaches through chant's forge client, and judge it. Never throws. */
|
|
165
|
+
export async function checkRelayToken(repo: RelayRepo, token: string, branch: string, fetchImpl?: ForgeFetch): Promise<{ user: string } | { error: string }> {
|
|
166
|
+
try {
|
|
167
|
+
return relayTokenVerdict(await readTokenReach(repo, token, branch, fetchImpl), repo.path, branch);
|
|
168
|
+
} catch (e) {
|
|
169
|
+
return { error: `the forge could not be read with the token (${(e as Error).message})` };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The git config that carries the token as a header, appended after any
|
|
175
|
+
* `GIT_CONFIG_*` entries `env` already has. Nothing is written to a file.
|
|
176
|
+
*/
|
|
177
|
+
export function relayGitAuthEnv(user: string, token: string, env: NodeJS.ProcessEnv = {}): Record<string, string> {
|
|
178
|
+
const n = Number(env.GIT_CONFIG_COUNT ?? "0");
|
|
179
|
+
const at = Number.isInteger(n) && n > 0 ? n : 0;
|
|
180
|
+
return {
|
|
181
|
+
GIT_CONFIG_COUNT: String(at + 1),
|
|
182
|
+
[`GIT_CONFIG_KEY_${at}`]: "http.extraHeader",
|
|
183
|
+
[`GIT_CONFIG_VALUE_${at}`]: `Authorization: Basic ${Buffer.from(`${user}:${token}`).toString("base64")}`,
|
|
184
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Run git without blocking the process, so a forge served by the same process (a test's) can answer. */
|
|
189
|
+
const runGit = (args: string[], env: NodeJS.ProcessEnv): Promise<{ ok: boolean; stdout: string; stderr: string }> =>
|
|
190
|
+
new Promise((done) => {
|
|
191
|
+
execFile("git", args, { encoding: "utf-8", env, maxBuffer: 16 * 1024 * 1024 }, (err, stdout, stderr) => done({ ok: !err, stdout: stdout ?? "", stderr: stderr ?? "" }));
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
/** The default branch the remote at `url` names, or why it could not be read. */
|
|
195
|
+
export async function relayDefaultBranch(url: string, env: NodeJS.ProcessEnv): Promise<{ branch: string } | { error: string }> {
|
|
196
|
+
const ls = await runGit(["ls-remote", "--symref", url, "HEAD"], env);
|
|
197
|
+
const branch = /^ref: refs\/heads\/(\S+)\s+HEAD/m.exec(ls.stdout)?.[1];
|
|
198
|
+
return branch ? { branch } : { error: ls.stderr.trim() || "the remote names no default branch" };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** A checkout of `branch` of the repo at `url`, in a new directory under `parent` (default the system's temporary one). */
|
|
202
|
+
export async function relayCheckout(url: string, branch: string, env: NodeJS.ProcessEnv, parent: string = tmpdir()): Promise<{ dir: string } | { error: string }> {
|
|
203
|
+
const dir = mkdtempSync(join(parent, "chant-relay-"));
|
|
204
|
+
const r = await runGit(["clone", "-q", "--branch", branch, url, dir], env);
|
|
205
|
+
return r.ok ? { dir } : { error: `cannot clone ${url}: ${r.stderr.trim()}` };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** What {@link prepareRelayCheckout} made: the checkout, its default branch, and the git config every later git call needs. */
|
|
209
|
+
export interface RelayCheckout {
|
|
210
|
+
dir: string;
|
|
211
|
+
branch: string;
|
|
212
|
+
repo: RelayRepo;
|
|
213
|
+
user: string;
|
|
214
|
+
gitEnv: Record<string, string>;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Check the token and clone the repo, in that order: a token that is more
|
|
219
|
+
* than approve-only is refused before anything is cloned with it.
|
|
220
|
+
*/
|
|
221
|
+
export async function prepareRelayCheckout(o: { url: string; token: string; forge?: string; env?: NodeJS.ProcessEnv; fetch?: ForgeFetch; parent?: string }): Promise<RelayCheckout | { error: string }> {
|
|
222
|
+
const env = o.env ?? process.env;
|
|
223
|
+
const repo = relayRepo(o.url, o.forge);
|
|
224
|
+
if ("error" in repo) return repo;
|
|
225
|
+
if (!o.token) return { error: "the token is empty: the relay pushes approvals with an approve-only token" };
|
|
226
|
+
const probe = await relayDefaultBranch(repo.url, { ...env, ...relayGitAuthEnv(relayGitUser(repo.forge), o.token, env) });
|
|
227
|
+
if ("error" in probe) return { error: `cannot read ${repo.path} with the token: ${probe.error}` };
|
|
228
|
+
const checked = await checkRelayToken(repo, o.token, probe.branch, o.fetch);
|
|
229
|
+
if ("error" in checked) return { error: `the relay holds only an approve-only token, and this one is more: ${checked.error}` };
|
|
230
|
+
const gitEnv = relayGitAuthEnv(checked.user, o.token, env);
|
|
231
|
+
const cloned = await relayCheckout(repo.url, probe.branch, { ...env, ...gitEnv }, o.parent);
|
|
232
|
+
if ("error" in cloned) return cloned;
|
|
233
|
+
return { dir: cloned.dir, branch: probe.branch, repo, user: checked.user, gitEnv };
|
|
234
|
+
}
|
package/src/notify-relay.test.ts
CHANGED
|
@@ -165,6 +165,18 @@ describe("chant notify relay (#4611)", () => {
|
|
|
165
165
|
expect(approvals).toEqual([]);
|
|
166
166
|
});
|
|
167
167
|
|
|
168
|
+
test("a click on a link button on the same message is acknowledged and ignored (#4759)", async () => {
|
|
169
|
+
const { deps, approvals } = memoryDeps();
|
|
170
|
+
const r = await relay(deps);
|
|
171
|
+
const payload = { type: "block_actions", user: { id: "UANA", team_id: "T1" }, actions: [{ action_id: "replan", url: "https://ci.example.com/run/7", value: "x" }], response_url: "https://hooks.slack.com/actions/1" };
|
|
172
|
+
const out = await r.slack(new URLSearchParams({ payload: JSON.stringify(payload) }).toString());
|
|
173
|
+
expect(out).toEqual({ status: 200, text: "" });
|
|
174
|
+
expect(r.posted).toEqual([]);
|
|
175
|
+
expect(approvals).toEqual([]);
|
|
176
|
+
// A button that is neither chant's nor a link is still refused.
|
|
177
|
+
expect((await r.slack(slackBody("UANA", "other", "x"))).status).toBe(400);
|
|
178
|
+
});
|
|
179
|
+
|
|
168
180
|
test("only the three paths answer", async () => {
|
|
169
181
|
const r = await relay(memoryDeps().deps);
|
|
170
182
|
expect((await fetch(`${r.url}/healthz`)).status).toBe(200);
|
package/src/notify-relay.ts
CHANGED
|
@@ -47,6 +47,7 @@ import { createServer, type IncomingMessage, type Server } from "node:http";
|
|
|
47
47
|
import type { CiProductWords } from "./ci-product-words";
|
|
48
48
|
import type { GatedRequest } from "./lifecycle/gated-request-digest";
|
|
49
49
|
import { readRelayToken, RELAY_APPROVE_ACTION, RELAY_DECLINE_ACTION, type RelayRef } from "./notify";
|
|
50
|
+
import { NEXT_RELEASE } from "./release-floors";
|
|
50
51
|
|
|
51
52
|
/**
|
|
52
53
|
* The first chant whose relay answers a gate's decision point and whose
|
|
@@ -56,6 +57,16 @@ import { readRelayToken, RELAY_APPROVE_ACTION, RELAY_DECLINE_ACTION, type RelayR
|
|
|
56
57
|
*/
|
|
57
58
|
export const NOTIFY_RELAY_POINTS_FLOOR = "0.124.72";
|
|
58
59
|
|
|
60
|
+
/**
|
|
61
|
+
* The first chant whose `chant notify relay --repo <url> --token-env <VAR>`
|
|
62
|
+
* refuses a token that is more than approve-only and clones the repo itself,
|
|
63
|
+
* whose `--host` listens where asked, which acknowledges a Slack link button's
|
|
64
|
+
* click, and which reads the signers at the default branch's current tip
|
|
65
|
+
* (#4759). A product whose relay container ran its own entrypoint for these
|
|
66
|
+
* feature-detects on it.
|
|
67
|
+
*/
|
|
68
|
+
export const NOTIFY_RELAY_CLONE_FLOOR = NEXT_RELEASE;
|
|
69
|
+
|
|
59
70
|
/** The relay's settings, by environment variable. */
|
|
60
71
|
export const RELAY_ENV = {
|
|
61
72
|
/** The key the notify buttons are signed with: the variable `notify.relay` names on the sending side. */
|
|
@@ -72,6 +83,16 @@ export const RELAY_ENV = {
|
|
|
72
83
|
slackResponse: "CHANT_RELAY_SLACK_RESPONSE",
|
|
73
84
|
} as const;
|
|
74
85
|
|
|
86
|
+
/** The variables that stand in for `--repo`, the default `--token-env`, and `--forge` (#4759). */
|
|
87
|
+
export const RELAY_REPO_ENV = {
|
|
88
|
+
/** The repository's https clone address. */
|
|
89
|
+
repo: "CHANT_RELAY_REPO",
|
|
90
|
+
/** The variable `--token-env` reads by default: the approve-only token. */
|
|
91
|
+
token: "CHANT_RELAY_TOKEN",
|
|
92
|
+
/** github, gitlab or forgejo, for a host other than github.com and gitlab.com. */
|
|
93
|
+
forge: "CHANT_RELAY_FORGE",
|
|
94
|
+
} as const;
|
|
95
|
+
|
|
75
96
|
/** Slack's own reply hosts: hooks.slack.com, and GovSlack's. */
|
|
76
97
|
export const SLACK_RESPONSE_PREFIXES = ["https://hooks.slack.com/", "https://hooks.slack-gov.com/"];
|
|
77
98
|
const SLACK_WINDOW_S = 5 * 60;
|
|
@@ -129,8 +150,13 @@ export interface RelayClick {
|
|
|
129
150
|
thread?: string;
|
|
130
151
|
}
|
|
131
152
|
|
|
132
|
-
/**
|
|
133
|
-
|
|
153
|
+
/**
|
|
154
|
+
* A Slack `block_actions` payload (the form field `payload`), or why the
|
|
155
|
+
* relay does not read it. `ignore` is set for a click on a link button (one
|
|
156
|
+
* with a `url`, such as a product's Re-plan link on the same message): Slack
|
|
157
|
+
* posts it too, and the relay acknowledges it and does nothing (#4759).
|
|
158
|
+
*/
|
|
159
|
+
export function slackRelayClick(raw: string): RelayClick | { error: string; ignore?: true } {
|
|
134
160
|
let p: any;
|
|
135
161
|
try {
|
|
136
162
|
p = JSON.parse(new URLSearchParams(raw).get("payload") ?? "");
|
|
@@ -143,6 +169,7 @@ export function slackRelayClick(raw: string): RelayClick | { error: string } {
|
|
|
143
169
|
if (typeof team !== "string" || typeof user !== "string") return { error: "the click names no Slack user" };
|
|
144
170
|
const a = Array.isArray(p.actions) ? p.actions[0] : undefined;
|
|
145
171
|
const action = a?.action_id === RELAY_APPROVE_ACTION ? "approve" : a?.action_id === RELAY_DECLINE_ACTION ? "decline" : undefined;
|
|
172
|
+
if (!action && typeof a?.url === "string") return { error: `the button ${String(a?.action_id)} is a link`, ignore: true };
|
|
146
173
|
if (!action) return { error: `the button ${String(a?.action_id)} is not chant's` };
|
|
147
174
|
if (typeof a.value !== "string" || !a.value) return { error: "the button carries no reference" };
|
|
148
175
|
const thread = p.container?.message_ts ?? p.message?.ts;
|
|
@@ -369,7 +396,7 @@ export async function handleRelayRequest(
|
|
|
369
396
|
return plain(401, refused);
|
|
370
397
|
}
|
|
371
398
|
const click = slackRelayClick(req.body);
|
|
372
|
-
if ("error" in click) return plain(400, click.error);
|
|
399
|
+
if ("error" in click) return click.ignore ? plain(200, "") : plain(400, click.error);
|
|
373
400
|
const answer = await decideRelayClick(click, settings, deps);
|
|
374
401
|
log(`slack: ${click.chatUser} ${click.action}: ${answer.outcome}: ${answer.text}`);
|
|
375
402
|
if (click.responseUrl) {
|
|
@@ -270,8 +270,8 @@ export async function opWavePolicyVerdicts(
|
|
|
270
270
|
at: { spec: Pick<OpWavesSpec, "name">; gate: string; env: string; base: string; head: string; cwd: string; exec?: GatePolicyExec },
|
|
271
271
|
parts: ReadonlyMap<string, ChangeSetPart>,
|
|
272
272
|
): Promise<{ verdicts: Map<string, OpWaveRunVerdict>; source?: ResolvedGatePolicySource } | { note: string }> {
|
|
273
|
-
const { prLoopPolicyAt, runPrPolicy } = await import("../components/pr-policy");
|
|
274
|
-
const read = prLoopPolicyAt(at.cwd, at.base);
|
|
273
|
+
const { prLoopPolicyAt, preparePrPolicyEngine, runPrPolicy } = await import("../components/pr-policy");
|
|
274
|
+
const read = await preparePrPolicyEngine(prLoopPolicyAt(at.cwd, at.base));
|
|
275
275
|
if (!read.settings) return { note: read.note ?? `holds.policy: the declaration at ${at.base.slice(0, 12)} names no ci.policy, so no policy runs` };
|
|
276
276
|
const verdicts = new Map<string, OpWaveRunVerdict>();
|
|
277
277
|
for (const [target, part] of parts) {
|