@intentius/chant 0.124.29 → 0.124.31
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/cli/handlers/build.d.ts.map +1 -1
- package/dist/cli/handlers/build.js +4 -1
- package/dist/cli/handlers/fan-out.d.ts.map +1 -1
- package/dist/cli/handlers/fan-out.js +27 -5
- package/dist/cli/handlers/pr.d.ts.map +1 -1
- package/dist/cli/main.d.ts.map +1 -1
- package/dist/cli/main.js +64 -0
- package/dist/cli/parse-args.d.ts.map +1 -1
- package/dist/cli/parse-args.js +99 -0
- package/dist/cli/registry.d.ts +35 -1
- package/dist/cli/registry.d.ts.map +1 -1
- package/dist/components/pr-pipeline.d.ts +24 -0
- package/dist/components/pr-pipeline.d.ts.map +1 -1
- package/dist/components/pr-pipeline.js +16 -0
- package/dist/components/pr-run.d.ts +20 -2
- package/dist/components/pr-run.d.ts.map +1 -1
- package/dist/components/pr-run.js +26 -13
- package/dist/components/wave-plan.d.ts +11 -0
- package/dist/components/wave-plan.d.ts.map +1 -1
- package/dist/components/wave-plan.js +26 -0
- package/dist/lifecycle/release-ledger.d.ts +8 -3
- package/dist/lifecycle/release-ledger.d.ts.map +1 -1
- package/dist/lifecycle/release-ledger.js +2 -0
- package/dist/lifecycle/run-ledger.d.ts +1 -1
- package/dist/lifecycle/run-ledger.d.ts.map +1 -1
- package/dist/lifecycle/run-ledger.js +9 -0
- package/dist/op/activities/activity-contracts.d.ts +1 -0
- package/dist/op/activities/activity-contracts.d.ts.map +1 -1
- package/dist/op/activities/activity-contracts.js +1 -0
- package/dist/op/activities/shell.d.ts +6 -0
- package/dist/op/activities/shell.d.ts.map +1 -1
- package/dist/op/activities/shell.js +1 -1
- package/dist/op/local-executor.d.ts +35 -1
- package/dist/op/local-executor.d.ts.map +1 -1
- package/dist/op/local-executor.js +31 -6
- package/dist/op/redact.d.ts +34 -0
- package/dist/op/redact.d.ts.map +1 -0
- package/dist/op/redact.js +94 -0
- package/dist/op/runtime.d.ts +27 -0
- package/dist/op/runtime.d.ts.map +1 -1
- package/dist/op/runtime.js +20 -0
- package/dist/op/step-console.d.ts +2 -0
- package/dist/op/step-console.d.ts.map +1 -1
- package/dist/op/step-console.js +5 -2
- package/dist/pr-forge.d.ts +40 -0
- package/dist/pr-forge.d.ts.map +1 -1
- package/dist/pr-forge.js +56 -6
- package/dist/pr-loop.d.ts +10 -0
- package/dist/pr-loop.d.ts.map +1 -1
- package/dist/pr-loop.js +7 -0
- package/dist/pr-report-url.d.ts +8 -0
- package/dist/pr-report-url.d.ts.map +1 -1
- package/dist/pr-report-url.js +47 -1
- package/dist/run-event-stream.d.ts +2 -2
- package/dist/run-event-stream.d.ts.map +1 -1
- package/dist/run-event-stream.js +2 -2
- package/dist/run-event.d.ts +15 -0
- package/dist/run-event.d.ts.map +1 -1
- package/dist/run-event.js +2 -0
- package/dist/wave-runtime.mjs +171 -171
- package/dist/workspace/ci-green-forge.d.ts +2 -0
- package/dist/workspace/ci-green-forge.d.ts.map +1 -1
- package/dist/workspace/ci-green.d.ts +2 -0
- package/dist/workspace/ci-green.d.ts.map +1 -1
- package/dist/workspace/ci-green.js +4 -2
- package/dist/workspace/ci-run-index.d.ts +96 -0
- package/dist/workspace/ci-run-index.d.ts.map +1 -0
- package/dist/workspace/ci-run-index.js +162 -0
- package/dist/workspace/ci-run-index.schema.json +50 -0
- package/dist/workspace/ci-run.d.ts +299 -0
- package/dist/workspace/ci-run.d.ts.map +1 -0
- package/dist/workspace/ci-run.js +691 -0
- package/dist/workspace/ci-runner-key.d.ts +120 -0
- package/dist/workspace/ci-runner-key.d.ts.map +1 -0
- package/dist/workspace/ci-runner-key.js +217 -0
- package/dist/workspace/ci-secrets.d.ts +65 -0
- package/dist/workspace/ci-secrets.d.ts.map +1 -0
- package/dist/workspace/ci-secrets.js +211 -0
- package/dist/workspace/ci-serve.d.ts +227 -0
- package/dist/workspace/ci-serve.d.ts.map +1 -0
- package/dist/workspace/ci-serve.js +468 -0
- package/dist/workspace/pr-report.schema.json +5 -0
- package/dist/workspace/reason-codes.d.ts +6 -2
- package/dist/workspace/reason-codes.d.ts.map +1 -1
- package/dist/workspace/reason-codes.js +7 -2
- package/dist/workspace/run-event.schema.json +14 -3
- package/dist/workspace/status-stewards.d.ts +2 -0
- package/dist/workspace/status-stewards.d.ts.map +1 -1
- package/dist/workspace/status-stewards.js +1 -0
- package/dist/workspace/status.schema.json +12 -1
- package/dist/workspace/trust/trust-write.d.ts +109 -0
- package/dist/workspace/trust/trust-write.d.ts.map +1 -0
- package/dist/workspace/trust/trust-write.js +320 -0
- package/dist/workspace/trust-write.schema.json +265 -0
- package/package.json +1 -1
- package/src/cli/handlers/build.test.ts +15 -0
- package/src/cli/handlers/build.ts +4 -1
- package/src/cli/handlers/fan-out.test.ts +82 -0
- package/src/cli/handlers/fan-out.ts +34 -5
- package/src/cli/handlers/pr.ts +5 -0
- package/src/cli/main.test.ts +1 -0
- package/src/cli/main.ts +64 -0
- package/src/cli/parse-args.ts +71 -0
- package/src/cli/registry.ts +35 -1
- package/src/components/pr-pipeline.ts +32 -0
- package/src/components/pr-run.test.ts +127 -0
- package/src/components/pr-run.ts +32 -12
- package/src/components/wave-plan.ts +30 -0
- package/src/lifecycle/release-ledger.ts +9 -3
- package/src/lifecycle/run-ledger.ts +7 -1
- package/src/op/activities/activity-contracts.ts +1 -0
- package/src/op/activities/shell.ts +7 -1
- package/src/op/local-executor.ts +58 -7
- package/src/op/redact.ts +93 -0
- package/src/op/runtime.ts +42 -0
- package/src/op/step-console.ts +7 -2
- package/src/pr-forge.test.ts +54 -0
- package/src/pr-forge.ts +92 -6
- package/src/pr-loop.test.ts +13 -1
- package/src/pr-loop.ts +16 -0
- package/src/pr-report-url.ts +53 -1
- package/src/run-event-stream.ts +4 -3
- package/src/run-event.ts +17 -0
- package/src/workspace/ci-green-forge.ts +2 -0
- package/src/workspace/ci-green.ts +6 -2
- package/src/workspace/ci-run-index.schema.json +50 -0
- package/src/workspace/ci-run-index.test.ts +353 -0
- package/src/workspace/ci-run-index.ts +192 -0
- package/src/workspace/ci-run.test.ts +716 -0
- package/src/workspace/ci-run.ts +833 -0
- package/src/workspace/ci-runner-key.test.ts +166 -0
- package/src/workspace/ci-runner-key.ts +250 -0
- package/src/workspace/ci-secrets.test.ts +106 -0
- package/src/workspace/ci-secrets.ts +213 -0
- package/src/workspace/ci-serve.test.ts +367 -0
- package/src/workspace/ci-serve.ts +574 -0
- package/src/workspace/pr-report.schema.json +5 -0
- package/src/workspace/reason-codes.test.ts +2 -0
- package/src/workspace/reason-codes.ts +7 -2
- package/src/workspace/run-event.schema.json +14 -3
- package/src/workspace/status-stewards.ts +3 -0
- package/src/workspace/status.schema.json +12 -1
- package/src/workspace/trust/trust-write.test.ts +179 -0
- package/src/workspace/trust/trust-write.ts +377 -0
- package/src/workspace/trust-write.schema.json +265 -0
|
@@ -0,0 +1,716 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #4094: `chant ci run plan|apply` runs one pull-request job as a pipeline
|
|
3
|
+
* Op in a fresh worktree with a clean environment, records it as `pr-plan`
|
|
4
|
+
* or `pr-apply` on `chant/lifecycle` signed by a runner key, and `ci tick
|
|
5
|
+
* --source runs` then tags the commit.
|
|
6
|
+
*
|
|
7
|
+
* Every test works in its own temp repository with a bare origin, and the
|
|
8
|
+
* runner key is a throwaway one. The job's `chant` is a stub script outside
|
|
9
|
+
* the repository that records the arguments, environment and directory it
|
|
10
|
+
* was run with. Nothing is written in process.cwd().
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { execFileSync } from "node:child_process";
|
|
14
|
+
import { createPublicKey, generateKeyPairSync } from "node:crypto";
|
|
15
|
+
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { afterAll, beforeAll, describe, expect, test } from "vitest";
|
|
18
|
+
import { cleanScratch, declaration, git, repoFixture, scratchDir, writeFiles } from "./__fixtures__/contract-repo";
|
|
19
|
+
import { checkRunEventLines } from "./__fixtures__/run-event-check";
|
|
20
|
+
import { ciJobCommand, ciJobEnv, ciJobFailure, ciJobOp, ciRun, CiRunError, ciStatusContext, ciStatusFromEnv, ciStatusUrl, formatCiRun } from "./ci-run";
|
|
21
|
+
import type { CommitStatus } from "../pr-forge";
|
|
22
|
+
import { ciTick, evaluateCommit, readOpRunSource, revokedAnnotation } from "./ci-green";
|
|
23
|
+
import type { StepRecord } from "../op/local-executor";
|
|
24
|
+
import { sshFromEd25519 } from "./trust/dsse";
|
|
25
|
+
import { verifyOpRunStatement } from "./trust/op-run-statement";
|
|
26
|
+
import { readRunLedger } from "../lifecycle/run-ledger";
|
|
27
|
+
import { prLoopJobs, PR_LOOP_SETUP } from "../components/pr-pipeline";
|
|
28
|
+
import { parseArgs } from "../cli/parse-args";
|
|
29
|
+
import { ciSecretsFor, readCiSecrets } from "./ci-secrets";
|
|
30
|
+
import { runEventFileName, runEventsDir } from "../run-event-store";
|
|
31
|
+
|
|
32
|
+
afterAll(cleanScratch);
|
|
33
|
+
|
|
34
|
+
const NOW = new Date("2026-10-18T12:00:00Z");
|
|
35
|
+
const hoursAgo = (h: number) => new Date(NOW.getTime() - h * 3_600_000).toISOString();
|
|
36
|
+
|
|
37
|
+
function runnerKey(): { pem: string; ssh: string } {
|
|
38
|
+
const { privateKey } = generateKeyPairSync("ed25519");
|
|
39
|
+
const jwk = createPublicKey(privateKey).export({ format: "jwk" }) as { x: string };
|
|
40
|
+
return { pem: privateKey.export({ type: "pkcs8", format: "pem" }).toString(), ssh: sshFromEd25519(Buffer.from(jwk.x, "base64url")) };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const BOT = runnerKey();
|
|
44
|
+
const RUNNERS = [{ principal: "chant-runner", class: "runner" as const, key: BOT.ssh }];
|
|
45
|
+
const GREEN = { branch: "main", phases: { plan: ["pr-plan"], apply: ["pr-apply"] }, require: ["plan", "apply"], source: "runs" };
|
|
46
|
+
|
|
47
|
+
function commitAt(root: string, hours: number, file: string): string {
|
|
48
|
+
writeFiles(root, { [file]: `${file} ${hours}\n` });
|
|
49
|
+
const date = hoursAgo(hours);
|
|
50
|
+
const env = { ...process.env, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date };
|
|
51
|
+
for (const args of [["add", "-A"], ["commit", "-q", "-m", file]]) {
|
|
52
|
+
execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false", ...args], { cwd: root, env, stdio: "ignore" });
|
|
53
|
+
}
|
|
54
|
+
return git(root, "rev-parse", "HEAD");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A checkout on main with a bare origin: member `app`, `ci.green` from runs, and BOT as the runner `chant-runner`.
|
|
59
|
+
* The history is two commits, `base` and then `sha`, which changes app/a.txt, and both are pushed to origin.
|
|
60
|
+
*/
|
|
61
|
+
const workspaceTemplate = repoFixture(() => {
|
|
62
|
+
const top = scratchDir("chant-ci-run-template-");
|
|
63
|
+
const origin = join(top, "origin");
|
|
64
|
+
const root = join(top, "root");
|
|
65
|
+
mkdirSync(origin);
|
|
66
|
+
mkdirSync(root);
|
|
67
|
+
git(origin, "init", "-q", "--bare");
|
|
68
|
+
git(root, "init", "-q");
|
|
69
|
+
git(root, "symbolic-ref", "HEAD", "refs/heads/main");
|
|
70
|
+
git(root, "config", "user.name", "t");
|
|
71
|
+
git(root, "config", "user.email", "t@example.com");
|
|
72
|
+
writeFiles(root, {
|
|
73
|
+
"chant.workspace.json": declaration([{ name: "app", dir: "app", kind: "other", because: "the app" }], { ci: { green: GREEN } }),
|
|
74
|
+
".chant/trust.json": JSON.stringify({ schema: 1, runners: [{ principal: "chant-runner", class: "runner", key: BOT.ssh }], roles: { runner: ["chant-runner"] } }),
|
|
75
|
+
".gitignore": ".chant/pr/\n",
|
|
76
|
+
"app/a.txt": "a\n",
|
|
77
|
+
});
|
|
78
|
+
git(root, "remote", "add", "origin", origin);
|
|
79
|
+
commitAt(root, 23, "app/init.txt");
|
|
80
|
+
commitAt(root, 2, "app/a.txt");
|
|
81
|
+
git(root, "push", "-q", "origin", "main");
|
|
82
|
+
return top;
|
|
83
|
+
}, "chant-ci-run-");
|
|
84
|
+
|
|
85
|
+
/** A copy of the template repository, its origin pointed at the copy of the bare one. */
|
|
86
|
+
function workspace(): { root: string; app: string; base: string; sha: string } {
|
|
87
|
+
const top = workspaceTemplate();
|
|
88
|
+
const root = join(top, "root");
|
|
89
|
+
git(root, "remote", "set-url", "origin", join(top, "origin"));
|
|
90
|
+
return { root, app: join(root, "app"), base: git(root, "rev-parse", "HEAD~1"), sha: git(root, "rev-parse", "HEAD") };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* A stand-in for `chant` outside the repository. It keeps the arguments,
|
|
95
|
+
* the environment and the directory it ran in as files under `.chant/pr`,
|
|
96
|
+
* where the real commands write their reports, and exits `$FAKE_EXIT`.
|
|
97
|
+
*/
|
|
98
|
+
function fakeChant(): string {
|
|
99
|
+
const file = join(scratchDir("chant-ci-run-bin-"), "chant");
|
|
100
|
+
writeFileSync(
|
|
101
|
+
file,
|
|
102
|
+
[
|
|
103
|
+
"#!/bin/sh",
|
|
104
|
+
'stage="$2"',
|
|
105
|
+
"mkdir -p .chant/pr",
|
|
106
|
+
'echo "chant $1${2:+ $2}" >> .chant/pr/order',
|
|
107
|
+
'printf "%s\\n" "$@" > ".chant/pr/$stage.args"',
|
|
108
|
+
'env | sort > ".chant/pr/$stage.env"',
|
|
109
|
+
'pwd -P > ".chant/pr/$stage.pwd"',
|
|
110
|
+
// FAKE_REPORT, when the job is given it, is the pr report the command writes.
|
|
111
|
+
'if [ -n "$FAKE_REPORT" ]; then printf "%s" "$FAKE_REPORT" > ".chant/pr/$stage.json"; else echo "{\\"stage\\": \\"$stage\\"}" > ".chant/pr/$stage.json"; fi',
|
|
112
|
+
'echo "fake $stage ran"',
|
|
113
|
+
'exit "${FAKE_EXIT:-0}"',
|
|
114
|
+
"",
|
|
115
|
+
].join("\n"),
|
|
116
|
+
);
|
|
117
|
+
chmodSync(file, 0o755);
|
|
118
|
+
return file;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// A job image of its own, so the jobs get no setup lines: the default image's
|
|
122
|
+
// OpenTofu install would download from the network on a runner without tofu.
|
|
123
|
+
const JOB_IMAGE = "chant-ci-run-test:local";
|
|
124
|
+
|
|
125
|
+
const HOST = {
|
|
126
|
+
PATH: process.env.PATH,
|
|
127
|
+
HOME: process.env.HOME,
|
|
128
|
+
GITHUB_TOKEN: "forge-token",
|
|
129
|
+
GITHUB_REPOSITORY: "acme/estate",
|
|
130
|
+
GITHUB_SERVER_URL: "http://forgejo.localhost",
|
|
131
|
+
GITHUB_API_URL: "http://forgejo.localhost/api/v1",
|
|
132
|
+
AWS_ACCESS_KEY_ID: "floci",
|
|
133
|
+
NOT_FOR_JOBS: "leak",
|
|
134
|
+
CHANT_RUNNER_KEY: BOT.pem,
|
|
135
|
+
GITHUB_RUN_ID: "999",
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const envFile = (dir: string, stage: string): Record<string, string> =>
|
|
139
|
+
Object.fromEntries(
|
|
140
|
+
readFileSync(join(dir, `${stage}.env`), "utf-8")
|
|
141
|
+
.split("\n")
|
|
142
|
+
.filter(Boolean)
|
|
143
|
+
.map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]),
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
describe("the job as an Op (#4094)", () => {
|
|
147
|
+
test("the job's variables come from flags, literals and the runner's tokens, and nothing else of the runner's", () => {
|
|
148
|
+
const [plan, apply] = prLoopJobs("forgejo", "prod", { events: true });
|
|
149
|
+
const env = ciJobEnv(plan!, { forge: "forgejo", env: "prod", values: { base: "b".repeat(40), pr: 7, commit: "c".repeat(40) }, hostEnv: HOST, passEnv: ["AWS_ACCESS_KEY_ID"] });
|
|
150
|
+
expect(env).toMatchObject({
|
|
151
|
+
BASE_SHA: "b".repeat(40),
|
|
152
|
+
PR_NUMBER: "7",
|
|
153
|
+
GITHUB_TOKEN: "forge-token",
|
|
154
|
+
GITHUB_REPOSITORY: "acme/estate",
|
|
155
|
+
GITHUB_SHA: "c".repeat(40),
|
|
156
|
+
CHANT_ENV: "prod",
|
|
157
|
+
CHANT_RUN_EVENTS_DIR: ".chant/pr/run-events",
|
|
158
|
+
AWS_ACCESS_KEY_ID: "floci",
|
|
159
|
+
});
|
|
160
|
+
for (const name of ["NOT_FOR_JOBS", "CHANT_RUNNER_KEY", "GITHUB_RUN_ID"]) expect(env).not.toHaveProperty(name);
|
|
161
|
+
// No `${{ ... }}` expression reaches a job.
|
|
162
|
+
expect(Object.values(env).some((v) => v.includes("${{"))).toBe(false);
|
|
163
|
+
|
|
164
|
+
expect(() => ciJobEnv(plan!, { forge: "forgejo", env: "prod", values: { base: "b".repeat(40), commit: "c".repeat(40) }, hostEnv: {} })).toThrow(CiRunError);
|
|
165
|
+
expect(() => ciJobEnv(apply!, { forge: "forgejo", env: "prod", values: { commit: "c".repeat(40) }, hostEnv: {} })).toThrow(/pass --base <sha>/);
|
|
166
|
+
|
|
167
|
+
const [, gitlabApply] = prLoopJobs("gitlab", "prod");
|
|
168
|
+
const gl = ciJobEnv(gitlabApply!, { forge: "gitlab", env: "prod", values: { base: "b".repeat(40), commit: "c".repeat(40) }, hostEnv: {} });
|
|
169
|
+
expect(gl).toEqual({ BASE_SHA: "b".repeat(40), CHANT_ENV: "prod", CI_COMMIT_SHA: "c".repeat(40) });
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test("the Op runs the generated job's command, after its setup and build lines, each a clean shell step", () => {
|
|
173
|
+
const [plan] = prLoopJobs("github", "prod", {}, "app");
|
|
174
|
+
const op = ciJobOp({ job: plan!, env: "prod", cwd: "/w/app", jobEnv: { BASE_SHA: "b" }, setup: PR_LOOP_SETUP, build: ["npm ci"], chant: "npx chant" });
|
|
175
|
+
expect(op.name).toBe("pr-plan");
|
|
176
|
+
expect(op.labels).toMatchObject({ Env: "prod" });
|
|
177
|
+
expect(op.phases.map((p) => [p.name, p.steps.length])).toEqual([["setup", 1], ["build", 1], ["plan", 1]]);
|
|
178
|
+
const last = op.phases[2]!.steps[0] as { fn: string; args: Record<string, unknown> };
|
|
179
|
+
expect(last.fn).toBe("shellCmd");
|
|
180
|
+
expect(last.args).toEqual({ cmd: `npx chant${plan!.command.slice("chant".length)}`, cwd: "/w/app", env: { BASE_SHA: "b" }, inheritEnv: false });
|
|
181
|
+
expect(plan!.command).toContain("--member app");
|
|
182
|
+
|
|
183
|
+
// No setup or build lines: the job's phase alone. GitLab's apply keeps its base fallback in the command's shell.
|
|
184
|
+
const [, gitlabApply] = prLoopJobs("gitlab", "prod");
|
|
185
|
+
const bare = ciJobOp({ job: gitlabApply!, env: "prod", cwd: "/w", jobEnv: {}, setup: [], build: [] });
|
|
186
|
+
expect(bare.phases.map((p) => p.name)).toEqual(["apply"]);
|
|
187
|
+
expect(ciJobCommand(gitlabApply!)).toBe(`${gitlabApply!.setup![0]}\n${gitlabApply!.command}`);
|
|
188
|
+
|
|
189
|
+
// #4088's build and lint lines follow --before-script, with chant replaced in each.
|
|
190
|
+
const [built] = prLoopJobs("forgejo", "prod", { build: true });
|
|
191
|
+
expect(built!.build).toEqual(["chant build --env prod", "chant lint"]);
|
|
192
|
+
const withBuild = ciJobOp({ job: built!, env: "prod", cwd: "/w", jobEnv: {}, setup: [], build: ["npm ci", ...built!.build!], chant: "npx chant" });
|
|
193
|
+
expect(withBuild.phases[0]!.steps.map((st) => ((st as unknown as { args: { cmd: string } }).args.cmd))).toEqual(["npm ci", "npx chant build --env prod", "npx chant lint"]);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test("the command line takes the job and the forge's values as flags", () => {
|
|
197
|
+
const args = parseArgs(["ci", "run", "apply", "--env", "prod", "--base", "abc", "--commit", "def", "--pass-env", "AWS_PROFILE", "--pass-env", "AWS_REGION", "--chant", "npx chant", "--key", "k.pem", "--pr-build", "--pr-build-command", "npm run build"]);
|
|
198
|
+
expect(args).toMatchObject({ prBuild: true, prBuildCommand: "npm run build" });
|
|
199
|
+
expect(args).toMatchObject({ command: "ci", path: "run", extraPositional: "apply", env: "prod", base: "abc", commit: "def", passEnv: ["AWS_PROFILE", "AWS_REGION"], ciChant: "npx chant", key: "k.pem" });
|
|
200
|
+
expect(() => parseArgs(["ci", "run", "plan", "--commit"])).toThrow(/--commit needs/);
|
|
201
|
+
});
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
describe("chant ci run, then ci tick from runs (#4094)", () => {
|
|
205
|
+
// The plan and the apply run once, in beforeAll, and the tests below read what they left. A job
|
|
206
|
+
// takes a few hundred milliseconds here and several times that on a loaded runner, so two jobs and
|
|
207
|
+
// a tick in one test came close to the unit budget (#2817). A file's beforeAll is not counted in it.
|
|
208
|
+
let w: ReturnType<typeof workspace>;
|
|
209
|
+
let worktrees: string;
|
|
210
|
+
let chant: string;
|
|
211
|
+
let reports: string;
|
|
212
|
+
let events: string[];
|
|
213
|
+
let plan: Awaited<ReturnType<typeof ciRun>>;
|
|
214
|
+
let apply: Awaited<ReturnType<typeof ciRun>>;
|
|
215
|
+
|
|
216
|
+
beforeAll(async () => {
|
|
217
|
+
w = workspace();
|
|
218
|
+
worktrees = git(w.root, "worktree", "list", "--porcelain");
|
|
219
|
+
chant = fakeChant();
|
|
220
|
+
reports = scratchDir("chant-ci-run-reports-");
|
|
221
|
+
events = [];
|
|
222
|
+
plan = await ciRun({ image: JOB_IMAGE,
|
|
223
|
+
cwd: w.app,
|
|
224
|
+
job: "plan",
|
|
225
|
+
env: "prod",
|
|
226
|
+
forge: "forgejo",
|
|
227
|
+
base: w.base,
|
|
228
|
+
pr: 7,
|
|
229
|
+
chant,
|
|
230
|
+
hostEnv: HOST,
|
|
231
|
+
passEnv: ["AWS_ACCESS_KEY_ID"],
|
|
232
|
+
runnerKey: BOT.pem,
|
|
233
|
+
output: join(reports, "plan"),
|
|
234
|
+
runId: "chant-plan-1",
|
|
235
|
+
runEvents: (line) => events.push(line),
|
|
236
|
+
});
|
|
237
|
+
apply = await ciRun({ image: JOB_IMAGE, cwd: w.app, job: "apply", env: "prod", forge: "forgejo", base: w.base, chant, hostEnv: HOST, runnerKey: BOT.pem, output: join(reports, "apply") });
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
test("the plan runs in a fresh worktree, in the member's directory, with a clean environment", () => {
|
|
241
|
+
const { root, base, sha } = w;
|
|
242
|
+
expect(plan.status).toBe("ok");
|
|
243
|
+
expect(plan.warnings).toEqual([]);
|
|
244
|
+
expect(plan.signer).toBe("chant-runner");
|
|
245
|
+
expect(plan.pushed).toBe(true);
|
|
246
|
+
|
|
247
|
+
// The job ran the generated command, in the member's directory of a checkout outside the repository.
|
|
248
|
+
const out = join(reports, "plan");
|
|
249
|
+
const [job] = prLoopJobs("forgejo", "prod", {}, "app");
|
|
250
|
+
const argv = readFileSync(join(out, "pr-plan.args"), "utf-8").trimEnd().split("\n");
|
|
251
|
+
expect(argv).toEqual(["components", "pr-plan", "--base", base, "--pr", "7", "--env", "prod", "--gate", "pr-apply", "--output", ".chant/pr", "--forge", "forgejo", "--member", "app"]);
|
|
252
|
+
expect(job!.command.split(" ").slice(1).map((a) => a.replace(/"/g, ""))).toEqual(argv.map((a) => (a === base ? "$BASE_SHA" : a === "7" ? "$PR_NUMBER" : a)));
|
|
253
|
+
const pwd = readFileSync(join(out, "pr-plan.pwd"), "utf-8").trim();
|
|
254
|
+
expect(pwd).toBe(join(plan.checkout, "app"));
|
|
255
|
+
expect(pwd.startsWith(realpathSync(root))).toBe(false);
|
|
256
|
+
expect(existsSync(plan.checkout)).toBe(false);
|
|
257
|
+
expect(git(root, "worktree", "list", "--porcelain")).toBe(worktrees);
|
|
258
|
+
expect(JSON.parse(readFileSync(join(out, "pr-plan.json"), "utf-8"))).toEqual({ stage: "pr-plan" });
|
|
259
|
+
|
|
260
|
+
// The environment is clean: the job's variables and the few the runner hands on. The copied
|
|
261
|
+
// report shows the values of the variables whose names look secret as *** (#4096).
|
|
262
|
+
const env = envFile(out, "pr-plan");
|
|
263
|
+
expect(env).toMatchObject({ BASE_SHA: base, PR_NUMBER: "7", GITHUB_SHA: sha, CHANT_ENV: "prod", GITHUB_TOKEN: "***", AWS_ACCESS_KEY_ID: "***" });
|
|
264
|
+
for (const name of ["NOT_FOR_JOBS", "CHANT_RUNNER_KEY", "GITHUB_RUN_ID"]) expect(env).not.toHaveProperty(name);
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
test("the plan and the apply are recorded signed, with a pipeline run's events", async () => {
|
|
268
|
+
const { app, base, sha } = w;
|
|
269
|
+
// The record: Op pr-plan at the commit, run by chant, with a statement that verifies.
|
|
270
|
+
expect(plan.record).toMatchObject({ op: "pr-plan", env: "prod", status: "ok", gitSha: sha, runOrigin: { forge: "chant" }, id: "chant-plan-1" });
|
|
271
|
+
const stored = (await readRunLedger("prod", "pr-plan", { cwd: app })).records.at(-1)!;
|
|
272
|
+
expect(stored.statement).toEqual(plan.record.statement);
|
|
273
|
+
expect(verifyOpRunStatement(stored, RUNNERS, { runner: ["chant-runner"] })).toMatchObject({ status: "signed", signer: "chant-runner" });
|
|
274
|
+
expect(stored.phases.map((p) => [p.name, p.status])).toEqual([["plan", "ok"]]);
|
|
275
|
+
|
|
276
|
+
// The events: a pipeline run, on the chant runner.
|
|
277
|
+
const stream = checkRunEventLines(events);
|
|
278
|
+
expect(stream[0]).toMatchObject({ kind: "pipeline", runtime: "ci", name: "pr-plan", runId: "chant-plan-1", gitSha: sha, runOrigin: { forge: "chant" } });
|
|
279
|
+
expect(stream.at(-1)).toMatchObject({ type: "run-settle", status: "ok" });
|
|
280
|
+
|
|
281
|
+
expect(apply.status).toBe("ok");
|
|
282
|
+
const applyArgs = readFileSync(join(reports, "apply", "pr-apply.args"), "utf-8").trimEnd().split("\n");
|
|
283
|
+
expect(applyArgs).toEqual(["components", "pr-apply", "--base", base, "--env", "prod", "--gate", "pr-apply", "--output", ".chant/pr", "--forge", "forgejo", "--member", "app", "--require-review", "--resume", ".chant/pr-resume/pr-apply.json"]);
|
|
284
|
+
expect(formatCiRun(apply)).toContain("signed by chant-runner");
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
test("the records reached origin, and a tick from runs tags the commit green with no forge", async () => {
|
|
288
|
+
const { root, app, sha } = w;
|
|
289
|
+
expect(git(root, "ls-remote", "origin", "chant/lifecycle")).toContain(git(root, "rev-parse", "chant/lifecycle"));
|
|
290
|
+
const tick = await ciTick({ cwd: app, now: NOW, runnerKey: BOT.pem });
|
|
291
|
+
expect(tick.source).toBe("runs");
|
|
292
|
+
expect(tick.made).toEqual([`ci/green/${sha}`]);
|
|
293
|
+
const note = git(root, "tag", "-l", "--format=%(contents)", `ci/green/${sha}`);
|
|
294
|
+
const record = JSON.parse(note.slice(note.indexOf("{"))) as { phases: Record<string, { name: string; opRun: { id: string; signer: string } }[]> };
|
|
295
|
+
expect(record.phases.plan![0]).toMatchObject({ name: "pr-plan", opRun: { id: "chant-plan-1", signer: "chant-runner" } });
|
|
296
|
+
expect(record.phases.apply![0]).toMatchObject({ name: "pr-apply", opRun: { id: apply.record.id, signer: "chant-runner" } });
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
test("a failing job is recorded failed, and a key from the environment that trust.json does not list leaves it unsigned", async () => {
|
|
300
|
+
const { app, base } = workspace();
|
|
301
|
+
const stranger = runnerKey();
|
|
302
|
+
const lines: string[] = [];
|
|
303
|
+
const r = await ciRun({ image: JOB_IMAGE,
|
|
304
|
+
cwd: app,
|
|
305
|
+
job: "apply",
|
|
306
|
+
env: "prod",
|
|
307
|
+
forge: "github",
|
|
308
|
+
base,
|
|
309
|
+
chant: fakeChant(),
|
|
310
|
+
hostEnv: { ...HOST, FAKE_EXIT: "3" },
|
|
311
|
+
passEnv: ["FAKE_EXIT"],
|
|
312
|
+
runnerKey: stranger.pem,
|
|
313
|
+
runnerKeyFromEnv: true,
|
|
314
|
+
output: join(scratchDir("chant-ci-run-out-"), "pr"),
|
|
315
|
+
push: false,
|
|
316
|
+
stepOutput: (line) => lines.push(line),
|
|
317
|
+
});
|
|
318
|
+
expect(r.status).toBe("fail");
|
|
319
|
+
expect(r.record.status).toBe("fail");
|
|
320
|
+
expect(r.record.statement).toBeUndefined();
|
|
321
|
+
expect(r.signer).toBeNull();
|
|
322
|
+
expect(r.warnings[0]).toMatch(/CHANT_RUNNER_KEY is set, and the run will not be signed: .*lists no runner with this key/);
|
|
323
|
+
expect(r.failure).toMatchObject({ phase: "apply", error: expect.stringContaining("command exited 3") });
|
|
324
|
+
// The report says nothing about a failure, so the record names the command.
|
|
325
|
+
expect(r.record.failure).toMatchObject({ code: "command-failed", phase: "apply", exitCode: 3, reason: expect.stringContaining("command exited 3") });
|
|
326
|
+
expect(lines.some((l) => l.includes("fake pr-apply ran"))).toBe(true);
|
|
327
|
+
expect(r.report).not.toBeNull();
|
|
328
|
+
expect(formatCiRun(r)).toContain("unsigned, so ci tick from runs does not count it");
|
|
329
|
+
|
|
330
|
+
// The same key given with --key refuses the run before anything runs.
|
|
331
|
+
await expect(ciRun({ image: JOB_IMAGE, cwd: app, job: "apply", env: "prod", forge: "github", base, chant: fakeChant(), hostEnv: HOST, runnerKey: stranger.pem, push: false })).rejects.toThrow(/would not be signed/);
|
|
332
|
+
expect((await readRunLedger("prod", "pr-apply", { cwd: app })).records).toHaveLength(1);
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
test("--pr-build runs the job's build and lint lines after --before-script and before the command, and a failing build fails the job", async () => {
|
|
336
|
+
const { root, app, base, sha } = workspace();
|
|
337
|
+
const chant = fakeChant();
|
|
338
|
+
const out = join(scratchDir("chant-ci-run-build-"), "pr");
|
|
339
|
+
const ok = await ciRun({ image: JOB_IMAGE,
|
|
340
|
+
cwd: app,
|
|
341
|
+
job: "plan",
|
|
342
|
+
env: "prod",
|
|
343
|
+
forge: "forgejo",
|
|
344
|
+
base,
|
|
345
|
+
pr: 3,
|
|
346
|
+
chant,
|
|
347
|
+
hostEnv: HOST,
|
|
348
|
+
beforeScript: ["mkdir -p .chant/pr && echo before-script >> .chant/pr/order"],
|
|
349
|
+
loop: { buildCommand: "echo build >> .chant/pr/order" },
|
|
350
|
+
push: false,
|
|
351
|
+
output: out,
|
|
352
|
+
});
|
|
353
|
+
expect(ok.status).toBe("ok");
|
|
354
|
+
expect(readFileSync(join(out, "order"), "utf-8").trimEnd().split("\n")).toEqual(["before-script", "build", "chant lint", "chant components pr-plan"]);
|
|
355
|
+
expect(ok.record.phases.map((p) => [p.name, p.status, p.steps.length])).toEqual([["build", "ok", 3], ["plan", "ok", 1]]);
|
|
356
|
+
|
|
357
|
+
const failed = await ciRun({ image: JOB_IMAGE,
|
|
358
|
+
cwd: app,
|
|
359
|
+
job: "apply",
|
|
360
|
+
env: "prod",
|
|
361
|
+
forge: "forgejo",
|
|
362
|
+
base,
|
|
363
|
+
chant,
|
|
364
|
+
hostEnv: HOST,
|
|
365
|
+
loop: { buildCommand: "mkdir -p .chant/pr && echo build >> .chant/pr/order && exit 4" },
|
|
366
|
+
runnerKey: BOT.pem,
|
|
367
|
+
push: false,
|
|
368
|
+
output: join(scratchDir("chant-ci-run-build-"), "pr"),
|
|
369
|
+
});
|
|
370
|
+
expect(failed.status).toBe("fail");
|
|
371
|
+
expect(failed.failure).toMatchObject({ phase: "build", error: expect.stringContaining("command exited 4") });
|
|
372
|
+
expect(failed.record).toMatchObject({ op: "pr-apply", status: "fail", gitSha: sha, runOrigin: { forge: "chant" } });
|
|
373
|
+
expect(failed.record.phases.map((p) => [p.name, p.status])).toEqual([["build", "fail"]]);
|
|
374
|
+
// The command never ran: the report holds the build's line alone.
|
|
375
|
+
expect(readFileSync(join(failed.report!, "order"), "utf-8").trimEnd().split("\n")).toEqual(["build"]);
|
|
376
|
+
const stored = (await readRunLedger("prod", "pr-apply", { cwd: app })).records.at(-1)!;
|
|
377
|
+
expect(stored.status).toBe("fail");
|
|
378
|
+
expect(stored.failure).toEqual({ code: "build-failed", phase: "build", exitCode: 4, reason: "mkdir -p .chant/pr && echo build >> .chant/pr/order && exit 4 exited 4" });
|
|
379
|
+
expect(verifyOpRunStatement(stored, RUNNERS, { runner: ["chant-runner"] })).toMatchObject({ status: "signed" });
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
test("a failed job's record and settle event say why from its pr report, signed, and a revoke note names the code", async () => {
|
|
383
|
+
const { root, app, base, sha } = workspace();
|
|
384
|
+
const refusedReport = { stage: "apply", status: "refused", refusal: "not-a-reviewer", message: "ana approved the plan, and ana has not approved the pull request on the forge" };
|
|
385
|
+
const extra = { FAKE_EXIT: "3", FAKE_REPORT: JSON.stringify(refusedReport) };
|
|
386
|
+
const events: string[] = [];
|
|
387
|
+
const refused = await ciRun({
|
|
388
|
+
image: JOB_IMAGE,
|
|
389
|
+
cwd: app,
|
|
390
|
+
job: "apply",
|
|
391
|
+
env: "prod",
|
|
392
|
+
forge: "forgejo",
|
|
393
|
+
base,
|
|
394
|
+
chant: fakeChant(),
|
|
395
|
+
hostEnv: { ...HOST, ...extra },
|
|
396
|
+
passEnv: Object.keys(extra),
|
|
397
|
+
runnerKey: BOT.pem,
|
|
398
|
+
push: false,
|
|
399
|
+
output: join(scratchDir("chant-ci-run-why-"), "pr"),
|
|
400
|
+
runEvents: (line) => events.push(line),
|
|
401
|
+
});
|
|
402
|
+
expect(refused.status).toBe("fail");
|
|
403
|
+
const why = { code: "not-a-reviewer", reason: refusedReport.message, phase: "apply", exitCode: 3 };
|
|
404
|
+
expect(refused.record.failure).toEqual(why);
|
|
405
|
+
expect(formatCiRun(refused)).toContain("failure: not-a-reviewer in apply, exit 3: ana approved the plan");
|
|
406
|
+
const stored = (await readRunLedger("prod", "pr-apply", { cwd: app })).records.at(-1)!;
|
|
407
|
+
expect(stored.failure).toEqual(why);
|
|
408
|
+
// The failure is signed with the rest of the record.
|
|
409
|
+
expect(verifyOpRunStatement(stored, RUNNERS, { runner: ["chant-runner"] })).toMatchObject({ status: "signed" });
|
|
410
|
+
// The settle event carries it, and validates against run-event.schema.json.
|
|
411
|
+
expect(checkRunEventLines(events).at(-1)).toMatchObject({ type: "run-settle", status: "failed", kind: "pipeline", failure: why });
|
|
412
|
+
|
|
413
|
+
// A tick from runs reads the code, and the revoke note names it.
|
|
414
|
+
const runs = (await readOpRunSource(app, root, git(root, "rev-parse", "HEAD"))).checkRuns(sha);
|
|
415
|
+
expect(runs).toEqual([expect.objectContaining({ name: "pr-apply", conclusion: "failure", failureCode: "not-a-reviewer" })]);
|
|
416
|
+
const green = { branch: "main", window: "7d", phases: [{ name: "apply", runs: ["pr-apply"] }], require: ["apply"], source: "runs" } as unknown as Parameters<typeof evaluateCommit>[0];
|
|
417
|
+
const verdict = evaluateCommit(green, runs);
|
|
418
|
+
expect(revokedAnnotation(green, sha, verdict.failure!, NOW).split("\n")[0]).toBe("ci: phase apply failed in pr-apply (failure, not-a-reviewer)");
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
test("the failure code comes from the report's refusal, its status and failed members, or the command", () => {
|
|
422
|
+
const op = ciJobOp({ job: prLoopJobs("forgejo", "prod")[1]!, env: "prod", cwd: "/w", jobEnv: {}, setup: [], build: ["npm ci"] });
|
|
423
|
+
const dir = scratchDir("chant-ci-run-report-");
|
|
424
|
+
const fail = (phase: string, code: number) => ({ phase, fn: "shellCmd", status: "fail", durationMs: 1, error: `command exited ${code} (expected 0): Command failed: x\nnoise` }) as unknown as StepRecord;
|
|
425
|
+
const ok = (phase: string) => ({ phase, fn: "shellCmd", status: "ok", durationMs: 1 }) as unknown as StepRecord;
|
|
426
|
+
const at = (records: StepRecord[]) => ciJobFailure({ job: "apply", op, records, reportDir: dir });
|
|
427
|
+
|
|
428
|
+
expect(at([ok("build"), ok("apply")])).toBeUndefined();
|
|
429
|
+
expect(at([fail("build", 2)])).toEqual({ code: "build-failed", reason: "npm ci exited 2", phase: "build", exitCode: 2 });
|
|
430
|
+
expect(at([ok("build"), fail("apply", 1)])).toEqual({ code: "command-failed", reason: "command exited 1 (expected 0): Command failed: x", phase: "apply", exitCode: 1 });
|
|
431
|
+
|
|
432
|
+
writeFileSync(join(dir, "pr-apply.json"), JSON.stringify({ status: "failed", members: [
|
|
433
|
+
{ member: "network", status: "applied" },
|
|
434
|
+
{ member: "cluster-a", status: "failed", error: "stack CREATE_FAILED\nmore" },
|
|
435
|
+
{ member: "cluster-b", status: "failed" },
|
|
436
|
+
{ member: "app-01", status: "blocked" },
|
|
437
|
+
] }));
|
|
438
|
+
expect(at([ok("build"), fail("apply", 1)])).toEqual({ code: "failed", reason: "members cluster-a failed (stack CREATE_FAILED), cluster-b failed", phase: "apply", exitCode: 1 });
|
|
439
|
+
writeFileSync(join(dir, "pr-apply.json"), JSON.stringify({ status: "refused", refusal: "plan-changed", message: "the plan changed after review\nsecond line" }));
|
|
440
|
+
expect(at([ok("build"), fail("apply", 3)])).toEqual({ code: "plan-changed", reason: "the plan changed after review", phase: "apply", exitCode: 3 });
|
|
441
|
+
// A report that says the job did its work leaves the command's failure.
|
|
442
|
+
writeFileSync(join(dir, "pr-apply.json"), JSON.stringify({ status: "applied", members: [] }));
|
|
443
|
+
expect(at([ok("build"), fail("apply", 1)])!.code).toBe("command-failed");
|
|
444
|
+
});
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
describe("a commit status per job (#4097)", () => {
|
|
448
|
+
/** A fake forge client: it records each status, and fails on the states in `refuse`. */
|
|
449
|
+
function fakeForge(refuse: string[] = []): { client: { setCommitStatus(sha: string, status: CommitStatus): Promise<void> }; posts: { sha: string; status: CommitStatus }[] } {
|
|
450
|
+
const posts: { sha: string; status: CommitStatus }[] = [];
|
|
451
|
+
return {
|
|
452
|
+
posts,
|
|
453
|
+
client: {
|
|
454
|
+
async setCommitStatus(sha, status) {
|
|
455
|
+
if (refuse.includes(status.state)) throw new Error(`POST /statuses/${sha} answered 500`);
|
|
456
|
+
posts.push({ sha, status });
|
|
457
|
+
},
|
|
458
|
+
},
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
async function job(over: Record<string, unknown>) {
|
|
463
|
+
const { root, app, base, sha } = workspace();
|
|
464
|
+
const r = await ciRun({ image: JOB_IMAGE, cwd: app, job: "plan", env: "prod", forge: "forgejo", base, pr: 7, chant: fakeChant(), hostEnv: HOST, push: false, output: join(scratchDir("chant-ci-status-"), "pr"), ...over } as Parameters<typeof ciRun>[0]);
|
|
465
|
+
return { r, sha };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
test("a good job posts pending, then success, at its commit", async () => {
|
|
469
|
+
const forge = fakeForge();
|
|
470
|
+
const { r, sha } = await job({ status: { client: forge.client } });
|
|
471
|
+
expect(r.status).toBe("ok");
|
|
472
|
+
expect(r.warnings).toEqual([]);
|
|
473
|
+
expect(forge.posts.map((p) => [p.sha, p.status.context, p.status.state])).toEqual([[sha, "chant/pr-plan", "pending"], [sha, "chant/pr-plan", "success"]]);
|
|
474
|
+
expect(forge.posts[0]!.status.description).toBe("pr-plan running");
|
|
475
|
+
expect(forge.posts[1]!.status.description).toMatch(/^pr-plan passed in \d+s$/);
|
|
476
|
+
expect(forge.posts[1]!.status).not.toHaveProperty("targetUrl");
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
test("a failed job posts pending, then failure with the run record's code and reason", async () => {
|
|
480
|
+
const forge = fakeForge();
|
|
481
|
+
const report = JSON.stringify({ stage: "apply", status: "refused", refusal: "not-approved", message: "no reviewer approved this plan" });
|
|
482
|
+
const { r } = await job({ job: "apply", pr: undefined, hostEnv: { ...HOST, FAKE_EXIT: "1", FAKE_REPORT: report }, passEnv: ["FAKE_EXIT", "FAKE_REPORT"], status: { client: forge.client } });
|
|
483
|
+
expect(r.status).toBe("fail");
|
|
484
|
+
expect(forge.posts.map((p) => [p.status.context, p.status.state])).toEqual([["chant/pr-apply", "pending"], ["chant/pr-apply", "failure"]]);
|
|
485
|
+
expect(r.record.failure!.code).toBe("not-approved");
|
|
486
|
+
expect(forge.posts[1]!.status.description).toBe("not-approved: no reviewer approved this plan");
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
test("a long failure reason is cut to the forge's 140 characters", async () => {
|
|
490
|
+
const forge = fakeForge();
|
|
491
|
+
const report = JSON.stringify({ stage: "apply", status: "refused", refusal: "plan-changed", message: "y".repeat(400) });
|
|
492
|
+
await job({ job: "apply", pr: undefined, hostEnv: { ...HOST, FAKE_EXIT: "1", FAKE_REPORT: report }, passEnv: ["FAKE_EXIT", "FAKE_REPORT"], status: { client: forge.client } });
|
|
493
|
+
const d = forge.posts[1]!.status.description;
|
|
494
|
+
expect(d).toHaveLength(140);
|
|
495
|
+
expect(d.startsWith("plan-changed: yyy")).toBe(true);
|
|
496
|
+
expect(d.endsWith("...")).toBe(true);
|
|
497
|
+
});
|
|
498
|
+
|
|
499
|
+
test("a renamed gate names the apply's context", async () => {
|
|
500
|
+
const forge = fakeForge();
|
|
501
|
+
await job({ job: "apply", pr: undefined, loop: { gate: "prod-approval" }, status: { client: forge.client } });
|
|
502
|
+
expect(forge.posts.map((p) => p.status.context)).toEqual(["chant/prod-approval", "chant/prod-approval"]);
|
|
503
|
+
expect(ciStatusContext("plan", "prod-approval")).toBe("chant/pr-plan");
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
// One job per test: each runs a whole Op in a worktree, and three in one test went over the unit budget.
|
|
507
|
+
test("target_url is an https --report-url with the key", async () => {
|
|
508
|
+
const https = fakeForge();
|
|
509
|
+
const { sha } = await job({ loop: { reportUrl: "https://host/reports/" }, status: { client: https.client } });
|
|
510
|
+
const key = `7/${sha}/app`;
|
|
511
|
+
expect(https.posts.map((p) => p.status.targetUrl)).toEqual([`https://host/reports/${key}/`, `https://host/reports/${key}/`]);
|
|
512
|
+
});
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* An `aws` stand-in first on PATH for the test. The run index of an s3 --report-url is read and
|
|
516
|
+
* written with the AWS CLI, and the real one reaches for credentials and the network: seconds on a
|
|
517
|
+
* runner that has it. The stub takes a put and answers a get with a missing object.
|
|
518
|
+
*/
|
|
519
|
+
function withStubAws(): () => void {
|
|
520
|
+
const dir = scratchDir("chant-ci-run-aws-");
|
|
521
|
+
const file = join(dir, "aws");
|
|
522
|
+
writeFileSync(file, ['#!/bin/sh', 'if [ "$3" = "-" ]; then cat > /dev/null; exit 0; fi', 'echo "An error occurred (404) when calling the HeadObject operation: Key not found" >&2', "exit 1", ""].join("\n"));
|
|
523
|
+
chmodSync(file, 0o755);
|
|
524
|
+
const saved = process.env.PATH;
|
|
525
|
+
process.env.PATH = `${dir}:${saved}`;
|
|
526
|
+
return () => {
|
|
527
|
+
process.env.PATH = saved;
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
test("target_url is the --status-url template for an s3 --report-url", async () => {
|
|
532
|
+
const s3 = fakeForge();
|
|
533
|
+
const restore = withStubAws();
|
|
534
|
+
try {
|
|
535
|
+
const mapped = await job({ loop: { reportUrl: "s3://bucket/prefix" }, status: { client: s3.client, urlTemplate: "https://host/reports/{key}" } });
|
|
536
|
+
expect(s3.posts.map((p) => p.status.targetUrl)).toEqual([`https://host/reports/7/${mapped.sha}/app`, `https://host/reports/7/${mapped.sha}/app`]);
|
|
537
|
+
} finally {
|
|
538
|
+
restore();
|
|
539
|
+
}
|
|
540
|
+
});
|
|
541
|
+
|
|
542
|
+
test("an s3 or file --report-url with no --status-url gives no target_url", async () => {
|
|
543
|
+
const bare = fakeForge();
|
|
544
|
+
const restore = withStubAws();
|
|
545
|
+
try {
|
|
546
|
+
await job({ loop: { reportUrl: "s3://bucket/prefix" }, status: { client: bare.client } });
|
|
547
|
+
} finally {
|
|
548
|
+
restore();
|
|
549
|
+
}
|
|
550
|
+
expect(bare.posts.every((p) => p.status.targetUrl === undefined)).toBe(true);
|
|
551
|
+
expect(ciStatusUrl({ reportUrl: "file:///tmp/r", commit: "abc" })).toBeUndefined();
|
|
552
|
+
});
|
|
553
|
+
|
|
554
|
+
test("--no-status, a missing token and GitLab give no client; a bad --status-url is refused", () => {
|
|
555
|
+
const env = { GITHUB_TOKEN: "t", GITHUB_REPOSITORY: "acme/estate", GITHUB_SERVER_URL: "http://forgejo.localhost", GITHUB_API_URL: "http://forgejo.localhost/api/v1" };
|
|
556
|
+
expect(ciStatusFromEnv({ forge: "forgejo", hostEnv: env, noStatus: true })).toEqual({});
|
|
557
|
+
expect(ciStatusFromEnv({ forge: "forgejo", hostEnv: { GITHUB_REPOSITORY: "acme/estate" } })).toEqual({});
|
|
558
|
+
expect(ciStatusFromEnv({ forge: "gitlab", hostEnv: { ...env, GITLAB_TOKEN: "t" } })).toEqual({});
|
|
559
|
+
expect(ciStatusFromEnv({ forge: "forgejo", hostEnv: env }).status?.client.setCommitStatus).toBeTypeOf("function");
|
|
560
|
+
expect(ciStatusFromEnv({ forge: "forgejo", hostEnv: env, statusUrl: "https://h/{key}" }).status?.urlTemplate).toBe("https://h/{key}");
|
|
561
|
+
expect(ciStatusFromEnv({ forge: "forgejo", hostEnv: { GITHUB_TOKEN: "t" } }).warning).toMatch(/no commit status/);
|
|
562
|
+
expect(() => ciStatusFromEnv({ forge: "forgejo", hostEnv: env, statusUrl: "s3://b/{key}" })).toThrow(/--status-url takes an http or https URL/);
|
|
563
|
+
const flags = parseArgs(["ci", "run", "plan", "--no-status", "--status-url", "https://h/{key}"]);
|
|
564
|
+
expect(flags).toMatchObject({ noStatus: true, statusUrl: "https://h/{key}" });
|
|
565
|
+
});
|
|
566
|
+
|
|
567
|
+
test("a status the forge refuses is a warning, and the job stays ok", async () => {
|
|
568
|
+
const forge = fakeForge(["pending", "success"]);
|
|
569
|
+
const { r } = await job({ status: { client: forge.client } });
|
|
570
|
+
expect(r.status).toBe("ok");
|
|
571
|
+
expect(r.record.status).toBe("ok");
|
|
572
|
+
expect(r.warnings).toHaveLength(2);
|
|
573
|
+
expect(r.warnings[0]).toMatch(/could not set the chant\/pr-plan status: POST \/statuses\/[0-9a-f]+ answered 500/);
|
|
574
|
+
});
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
/** A secrets file only its owner can read, as `--secrets` takes it. */
|
|
578
|
+
function secretsFile(text: string, name = "secrets.env"): string {
|
|
579
|
+
const file = join(scratchDir("chant-ci-run-secrets-"), name);
|
|
580
|
+
writeFileSync(file, text, { mode: 0o600 });
|
|
581
|
+
chmodSync(file, 0o600);
|
|
582
|
+
return file;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** Every file under `dir`, with its text. */
|
|
586
|
+
function filesUnder(dir: string): Record<string, string> {
|
|
587
|
+
const out: Record<string, string> = {};
|
|
588
|
+
for (const entry of readdirSync(dir, { recursive: true, withFileTypes: true })) {
|
|
589
|
+
if (!entry.isFile()) continue;
|
|
590
|
+
const path = join(entry.parentPath, entry.name);
|
|
591
|
+
out[path] = readFileSync(path, "utf-8");
|
|
592
|
+
}
|
|
593
|
+
return out;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
describe("the job's secrets from the host (#4096)", () => {
|
|
597
|
+
test("a secret reaches the step, and the file's allowlist keeps one from the plan", async () => {
|
|
598
|
+
const { app, base } = workspace();
|
|
599
|
+
const secrets = readCiSecrets(
|
|
600
|
+
secretsFile(JSON.stringify({ secrets: { DB_PASSWORD: "hunter22-db", DEPLOY_KEY: "deploy-key-value" }, jobs: { plan: ["DB_PASSWORD"] } }), "secrets.json"),
|
|
601
|
+
);
|
|
602
|
+
const out = join(scratchDir("chant-ci-run-secret-"), "pr");
|
|
603
|
+
const r = await ciRun({
|
|
604
|
+
image: JOB_IMAGE,
|
|
605
|
+
cwd: app,
|
|
606
|
+
job: "plan",
|
|
607
|
+
env: "prod",
|
|
608
|
+
forge: "forgejo",
|
|
609
|
+
base,
|
|
610
|
+
pr: 5,
|
|
611
|
+
chant: fakeChant(),
|
|
612
|
+
hostEnv: HOST,
|
|
613
|
+
secrets,
|
|
614
|
+
// The step checks the value it got, and that the plan got no DEPLOY_KEY.
|
|
615
|
+
beforeScript: ['test "$DB_PASSWORD" = "hunter22-db" && test -z "${DEPLOY_KEY+set}" && mkdir -p .chant/pr && echo reached > .chant/pr/reached'],
|
|
616
|
+
push: false,
|
|
617
|
+
output: out,
|
|
618
|
+
});
|
|
619
|
+
expect(r.status).toBe("ok");
|
|
620
|
+
expect(readFileSync(join(out, "reached"), "utf-8").trim()).toBe("reached");
|
|
621
|
+
const env = envFile(out, "pr-plan");
|
|
622
|
+
// The value reached the command too, and the copied report shows it as ***.
|
|
623
|
+
expect(env.DB_PASSWORD).toBe("***");
|
|
624
|
+
expect(env).not.toHaveProperty("DEPLOY_KEY");
|
|
625
|
+
expect(env).not.toHaveProperty("CHANT_RUNNER_KEY");
|
|
626
|
+
|
|
627
|
+
// The apply is not in the allowlist, so it gets every secret.
|
|
628
|
+
const [, apply] = prLoopJobs("forgejo", "prod");
|
|
629
|
+
const applyEnv = ciJobEnv(apply!, { forge: "forgejo", env: "prod", values: { base, commit: base }, hostEnv: HOST, secrets: ciSecretsFor(secrets, "apply") });
|
|
630
|
+
expect(applyEnv).toMatchObject({ DB_PASSWORD: "hunter22-db", DEPLOY_KEY: "deploy-key-value" });
|
|
631
|
+
// A secret can replace a forge token, and never the variables the runner sets.
|
|
632
|
+
const over = ciJobEnv(apply!, { forge: "forgejo", env: "prod", values: { base, commit: base }, hostEnv: HOST, secrets: { GITHUB_TOKEN: "from-file", BASE_SHA: "x", CHANT_RUNNER_KEY: "k" } });
|
|
633
|
+
expect(over).toMatchObject({ GITHUB_TOKEN: "from-file", BASE_SHA: base });
|
|
634
|
+
expect(over).not.toHaveProperty("CHANT_RUNNER_KEY");
|
|
635
|
+
expect(() => ciJobEnv(apply!, { forge: "forgejo", env: "prod", values: { base, commit: base }, hostEnv: HOST, passEnv: ["CHANT_RUNNER_KEY"] })).toThrow(/never passed to a job/);
|
|
636
|
+
});
|
|
637
|
+
|
|
638
|
+
test("a secret the job prints, writes in its report or fails with is *** in the events, the signed record, the copied report and the output", async () => {
|
|
639
|
+
const { app, base } = workspace();
|
|
640
|
+
const SECRET = "s3cret pass#1";
|
|
641
|
+
const TOKEN = "tok-abc123";
|
|
642
|
+
const secrets = readCiSecrets(secretsFile(`# the host's secrets\nDB_PASSWORD="${SECRET}"\nexport PIN=abc\n`));
|
|
643
|
+
expect(secrets.values).toEqual({ DB_PASSWORD: SECRET, PIN: "abc" });
|
|
644
|
+
|
|
645
|
+
const leaky = join(scratchDir("chant-ci-run-bin-"), "chant");
|
|
646
|
+
writeFileSync(
|
|
647
|
+
leaky,
|
|
648
|
+
[
|
|
649
|
+
"#!/bin/sh",
|
|
650
|
+
"mkdir -p .chant/pr",
|
|
651
|
+
'env | sort > .chant/pr/pr-apply.env',
|
|
652
|
+
'printf \'{"stage":"apply","status":"refused","refusal":"not-approved","message":"the deploy failed with %s"}\' "$DB_PASSWORD" > .chant/pr/pr-apply.json',
|
|
653
|
+
'printf \'{\\n "entries": [\\n { "password": "%s" }\\n ]\\n}\\n\' "$DB_PASSWORD" > .chant/pr/change-set.json',
|
|
654
|
+
'echo "connecting with $DB_PASSWORD and $MY_API_TOKEN, pin $PIN"',
|
|
655
|
+
'echo "login refused for $DB_PASSWORD" >&2',
|
|
656
|
+
"exit 3",
|
|
657
|
+
"",
|
|
658
|
+
].join("\n"),
|
|
659
|
+
);
|
|
660
|
+
chmodSync(leaky, 0o755);
|
|
661
|
+
|
|
662
|
+
const events: string[] = [];
|
|
663
|
+
const lines: string[] = [];
|
|
664
|
+
const out = join(scratchDir("chant-ci-run-leak-"), "pr");
|
|
665
|
+
const r = await ciRun({
|
|
666
|
+
image: JOB_IMAGE,
|
|
667
|
+
cwd: app,
|
|
668
|
+
job: "apply",
|
|
669
|
+
env: "prod",
|
|
670
|
+
forge: "forgejo",
|
|
671
|
+
base,
|
|
672
|
+
chant: leaky,
|
|
673
|
+
hostEnv: { ...HOST, MY_API_TOKEN: TOKEN },
|
|
674
|
+
passEnv: ["MY_API_TOKEN"],
|
|
675
|
+
secrets,
|
|
676
|
+
runnerKey: BOT.pem,
|
|
677
|
+
push: false,
|
|
678
|
+
output: out,
|
|
679
|
+
runId: "chant-leak-1",
|
|
680
|
+
runEvents: (line) => events.push(line),
|
|
681
|
+
stepOutput: (line) => lines.push(line),
|
|
682
|
+
});
|
|
683
|
+
expect(r.status).toBe("fail");
|
|
684
|
+
const leaks = (text: string): boolean => text.includes(SECRET) || text.includes(TOKEN);
|
|
685
|
+
|
|
686
|
+
// The events, as written and as kept on this host, still valid lines.
|
|
687
|
+
expect(events.some(leaks)).toBe(false);
|
|
688
|
+
const stream = checkRunEventLines(events);
|
|
689
|
+
expect(stream.at(-1)).toMatchObject({ type: "run-settle", status: "failed", failure: { code: "not-approved", reason: "the deploy failed with ***" } });
|
|
690
|
+
const kept = readFileSync(join((await runEventsDir(app))!, runEventFileName("chant-leak-1")), "utf-8");
|
|
691
|
+
expect(leaks(kept)).toBe(false);
|
|
692
|
+
expect(kept).toContain("***");
|
|
693
|
+
|
|
694
|
+
// The record: the step's error and failure.reason redacted, and the statement still verifies.
|
|
695
|
+
expect(leaks(JSON.stringify(r.record))).toBe(false);
|
|
696
|
+
expect(r.record.failure).toMatchObject({ code: "not-approved", reason: "the deploy failed with ***", exitCode: 3 });
|
|
697
|
+
const stored = (await readRunLedger("prod", "pr-apply", { cwd: app })).records.at(-1)!;
|
|
698
|
+
expect(leaks(JSON.stringify(stored))).toBe(false);
|
|
699
|
+
expect(stored.phases.at(-1)!.steps[0]!.error).toContain("login refused for ***");
|
|
700
|
+
expect(verifyOpRunStatement(stored, RUNNERS, { runner: ["chant-runner"] })).toMatchObject({ status: "signed", signer: "chant-runner" });
|
|
701
|
+
|
|
702
|
+
// The copied report and change set: redacted, and still JSON in the layout the job wrote.
|
|
703
|
+
const files = filesUnder(out);
|
|
704
|
+
expect(Object.values(files).some(leaks)).toBe(false);
|
|
705
|
+
expect(JSON.parse(files[join(out, "pr-apply.json")]!)).toMatchObject({ message: "the deploy failed with ***" });
|
|
706
|
+
expect(files[join(out, "change-set.json")]).toBe('{\n "entries": [\n {\n "password": "***"\n }\n ]\n}\n');
|
|
707
|
+
expect(envFile(out, "pr-apply")).toMatchObject({ DB_PASSWORD: "***", MY_API_TOKEN: "***" });
|
|
708
|
+
|
|
709
|
+
// What ci run prints: the step's lines, the result's failure and the summary. A value under 4 characters is kept.
|
|
710
|
+
expect(lines.some(leaks)).toBe(false);
|
|
711
|
+
expect(lines.some((l) => l.endsWith("| connecting with *** and ***, pin abc"))).toBe(true);
|
|
712
|
+
expect(leaks(r.failure!.error)).toBe(false);
|
|
713
|
+
expect(leaks(formatCiRun(r))).toBe(false);
|
|
714
|
+
expect(formatCiRun(r)).toContain("not-approved in apply, exit 3: the deploy failed with ***");
|
|
715
|
+
});
|
|
716
|
+
});
|