返回 CodeWhale
deploy-preflight.test.ts
根目录 / web / lib / deploy-preflight.test.ts
1 import { spawnSync } from "node:child_process";
2 import { convertToWranglerConfig, loadAndParseConfig } from "@cloudflare/config";
3 import { readFileSync } from "node:fs";
4 import { fileURLToPath } from "node:url";
5 import { describe, expect, it } from "vitest";
6
7 // fileURLToPath, not `.pathname`: the latter stays percent-encoded, so a
8 // checkout under a path with non-ASCII characters spawns a filename that
9 // does not exist and every case here fails on a module-not-found exit.
10 const script = fileURLToPath(new URL("../scripts/check-cloudflare-deploy-env.mjs", import.meta.url));
11
12 function run(overrides: Record<string, string>, args: string[] = []) {
13 return spawnSync(process.execPath, [script, ...args], {
14 encoding: "utf8",
15 env: {
16 ...process.env,
17 GITHUB_ACTIONS: "",
18 GITHUB_EVENT_NAME: "",
19 GITHUB_REF: "",
20 GITHUB_SHA: "",
21 CLOUDFLARE_ACCOUNT_ID: "",
22 CLOUDFLARE_API_TOKEN: "",
23 ...overrides,
24 },
25 });
26 }
27
28 describe("Cloudflare deploy preflight", () => {
29 it("reports intentionally withheld credentials without deploying", () => {
30 const result = run({}, ["--preflight"]);
31
32 expect(result.status).toBe(0);
33 expect(result.stdout).toContain("credentialState\":\"withheld");
34 expect(result.stdout).toContain("deploymentStarted\":false");
35 });
36
37 it("rejects malformed supplied values even in credential-free preflight mode", () => {
38 const result = run(
39 {
40 CLOUDFLARE_ACCOUNT_ID: "not-an-account-id",
41 CLOUDFLARE_API_TOKEN: "not-a-token",
42 },
43 ["--preflight"],
44 );
45
46 expect(result.status).toBe(1);
47 expect(result.stderr).toContain("malformed credential placeholders");
48 expect(result.stdout).toContain("credentialState\":\"invalid");
49 });
50
51 it("keeps the normal deploy check fail-closed when credentials are missing", () => {
52 const result = run({});
53
54 expect(result.status).toBe(1);
55 expect(result.stderr).toContain("Cloudflare deploy configuration is incomplete");
56 });
57
58 it("requires an exact manual-main context inside GitHub Actions", () => {
59 const result = run({
60 GITHUB_ACTIONS: "true",
61 GITHUB_EVENT_NAME: "push",
62 GITHUB_REF: "refs/heads/main",
63 GITHUB_SHA: "a".repeat(40),
64 CLOUDFLARE_ACCOUNT_ID: "a".repeat(32),
65 CLOUDFLARE_API_TOKEN: "token-" + "b".repeat(32),
66 });
67
68 expect(result.status).toBe(1);
69 expect(result.stderr).toContain("workflow_dispatch on refs/heads/main");
70 });
71
72 it("rejects a dispatch on a non-main ref", () => {
73 const result = run({
74 GITHUB_ACTIONS: "true",
75 GITHUB_EVENT_NAME: "workflow_dispatch",
76 GITHUB_REF: "refs/heads/release",
77 GITHUB_SHA: "a".repeat(40),
78 CLOUDFLARE_ACCOUNT_ID: "a".repeat(32),
79 CLOUDFLARE_API_TOKEN: "token-" + "b".repeat(32),
80 });
81
82 expect(result.status).toBe(1);
83 expect(result.stderr).toContain("workflow_dispatch on refs/heads/main");
84 });
85
86 it("rejects a dispatch without an exact 40-hex revision", () => {
87 const result = run({
88 GITHUB_ACTIONS: "true",
89 GITHUB_EVENT_NAME: "workflow_dispatch",
90 GITHUB_REF: "refs/heads/main",
91 GITHUB_SHA: "main",
92 CLOUDFLARE_ACCOUNT_ID: "a".repeat(32),
93 CLOUDFLARE_API_TOKEN: "token-" + "b".repeat(32),
94 });
95
96 expect(result.status).toBe(1);
97 expect(result.stderr).toContain("exact SHA");
98 });
99
100 it("accepts a manual dispatch on main at an exact SHA", () => {
101 const result = run({
102 GITHUB_ACTIONS: "true",
103 GITHUB_EVENT_NAME: "workflow_dispatch",
104 GITHUB_REF: "refs/heads/main",
105 GITHUB_SHA: "a".repeat(40),
106 CLOUDFLARE_ACCOUNT_ID: "a".repeat(32),
107 CLOUDFLARE_API_TOKEN: "token-" + "b".repeat(32),
108 });
109
110 expect(result.status).toBe(0);
111 expect(result.stdout).toContain("Cloudflare deploy environment is present");
112 });
113 });
114
115 // Minimal, dependency-free reader for the two-space-indented job blocks in
116 // .github/workflows/web.yml. A real YAML parser is not a web dependency, and
117 // this file only needs the `on:` triggers plus the deploy job's `if:` guard.
118 function readWebWorkflow() {
119 const path = new URL("../../.github/workflows/web.yml", import.meta.url);
120 return readFileSync(path, "utf8");
121 }
122
123 function jobBlock(source: string, job: string) {
124 const lines = source.split("\n");
125 const start = lines.findIndex((line) => line === ` ${job}:`);
126 expect(start, `job ${job} not found in web.yml`).toBeGreaterThanOrEqual(0);
127 const rest = lines.slice(start + 1);
128 const end = rest.findIndex((line) => /^ {2}\S/.test(line));
129 return (end === -1 ? rest : rest.slice(0, end)).join("\n");
130 }
131
132 describe("web workflow deploy trigger contract", () => {
133 const workflow = readWebWorkflow();
134 const deploy = jobBlock(workflow, "deploy");
135 const deployReminder = jobBlock(workflow, "deploy-reminder");
136
137 it("runs lint only for manually requested final validation", () => {
138 const triggerBlock = workflow.slice(
139 workflow.indexOf("on:\n"),
140 workflow.indexOf("\n\npermissions:"),
141 );
142 expect(triggerBlock).toMatch(/^on:\n workflow_dispatch:(?:\n .*)*$/);
143 expect(jobBlock(workflow, "lint")).not.toContain("if:");
144 });
145
146 it("gates deploy on a manual dispatch of main only", () => {
147 const guard = deploy
148 .slice(deploy.indexOf("if:"))
149 .split("\n")
150 .slice(0, 3)
151 .join(" ")
152 .replace(/\s+/g, " ");
153
154 expect(guard).toContain("github.event_name == 'workflow_dispatch'");
155 expect(guard).toContain("github.ref == 'refs/heads/main'");
156 // The preflight script fails closed on any non-dispatch event, so a push
157 // trigger here could only ever produce a red deploy job (#4907).
158 expect(guard).not.toContain("'push'");
159 expect(deploy).toContain("needs: lint");
160 });
161
162 it("surfaces an actionable deployment reminder after a green main push", () => {
163 expect(deployReminder).toContain("needs: lint");
164 expect(deployReminder).toContain(
165 "github.event_name == 'push' && github.ref == 'refs/heads/main'",
166 );
167 expect(deployReminder).toContain("::notice title=Web deployment approval needed::");
168 expect(deployReminder).toContain("gh workflow run web.yml");
169 expect(deployReminder).not.toContain("npm run deploy");
170 });
171
172 it("checks out the exact dispatched revision before deploying", () => {
173 expect(deploy).toContain("ref: ${{ github.sha }}");
174 expect(deploy).toContain('--expected-revision "$GITHUB_SHA"');
175 });
176
177 it("verifies an optional expected_sha input right after checkout", () => {
178 expect(workflow).toMatch(
179 /^ workflow_dispatch:\n inputs:\n expected_sha:\n description: .*\n required: false\n default: ''\n type: string$/m,
180 );
181 for (const job of [jobBlock(workflow, "lint"), deploy]) {
182 expect(job).toContain("EXPECTED_SHA: ${{ inputs.expected_sha }}");
183 expect(job).toContain('actual="$(git rev-parse HEAD)"');
184 expect(job.indexOf("actions/checkout@")).toBeGreaterThanOrEqual(0);
185 expect(job.indexOf("Verify expected commit")).toBeGreaterThan(job.indexOf("actions/checkout@"));
186 expect(job.indexOf("Verify expected commit")).toBeLessThan(job.indexOf("actions/setup-node@"));
187 }
188 });
189
190 it("builds and caches one bundle before cf deploy consumes it", () => {
191 const { scripts } = JSON.parse(
192 readFileSync(new URL("../package.json", import.meta.url), "utf8"),
193 ) as { scripts: Record<string, string> };
194 const bundler = readFileSync(new URL("../wrangler.config.ts", import.meta.url), "utf8");
195 expect(scripts["build:cloudflare"].split("npm run build:opennext")).toHaveLength(2);
196 expect(scripts.deploy.indexOf("npm run build:cloudflare")).toBeLessThan(
197 scripts.deploy.indexOf("populateCache remote"),
198 );
199 expect(scripts.deploy).toMatch(/populateCache remote .* && cf deploy --prebuilt$/);
200 expect(scripts.preview).toMatch(/^npm run build:cloudflare && .*populateCache local/);
201 expect(bundler).not.toMatch(/build\s*:/);
202 expect(deploy).toContain("run: npm run deploy");
203 expect(deploy).not.toContain("npm run build");
204 });
205
206 it("preserves the website's existing storage and Worker identities in cf config", async () => {
207 const { result } = await loadAndParseConfig(
208 fileURLToPath(new URL("../cloudflare.config.ts", import.meta.url)),
209 { isPreview: false, mode: undefined },
210 );
211 if (!result.success) throw new Error(String(result.error));
212 const config = convertToWranglerConfig(result.data);
213 expect(config.name).toBe("codewhale-web");
214 expect(config.kv_namespaces).toEqual([
215 { binding: "CURATED_KV", id: "abaa6a753c9d45bfa5c0afaf26dc67b3" },
216 { binding: "NEXT_INC_CACHE_KV", id: "a2e6f324db9b4b03bbc940a4ba246985" },
217 ]);
218 expect(config.durable_objects?.bindings).toEqual([
219 { name: "DRAFT_CLAIM_LOCK", class_name: "DraftClaimLock", script_name: "codewhale-web" },
220 ]);
221 expect(config.exports).toEqual({ DraftClaimLock: { type: "durable-object", storage: "sqlite" } });
222 expect(config.routes).toEqual([
223 { pattern: "codewhale.net", custom_domain: true },
224 { pattern: "www.codewhale.net", custom_domain: true },
225 ]);
226 expect(config.services).toEqual([{ binding: "WORKER_SELF_REFERENCE", service: "codewhale-web" }]);
227 });
228 });
229
229 lines TYPESCRIPT