Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
Blame · Line-by-line history

crontech-deploy.test.ts

Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.

crontech-deploy.test.tsBlame322 lines · 2 contributors
43cf9b0Claude1/**
ba93444Claude2 * BLK-016 — Crontech deploy webhook sender.
43cf9b0Claude3 *
ba93444Claude4 * Asserts that `triggerCrontechDeploy` (in `src/hooks/post-receive.ts`)
5 * matches the wire contract documented at the top of that helper, which
6 * is the inbound contract for Crontech's
7 * `apps/api/src/webhooks/gluecron-push.ts` receiver:
43cf9b0Claude8 *
ba93444Claude9 * POST https://crontech.ai/api/webhooks/gluecron-push
43cf9b0Claude10 * Content-Type: application/json
ba93444Claude11 * X-Gluecron-Signature: sha256=<hex(hmac-sha256(body, secret))>
12 *
13 * body = {
14 * event: "push",
15 * repository: { full_name },
16 * ref, after, before,
17 * pusher: { name, email },
18 * commits: [...]
19 * }
20 *
21 * Plus at-least-once delivery: 5 attempts on 5xx with exponential backoff,
22 * stop on first 2xx or unrecoverable 4xx.
43cf9b0Claude23 *
24 * The helper swallows DB errors, so these tests work without a real DB.
25 */
26
27import { afterEach, beforeEach, describe, expect, it } from "bun:test";
ba93444Claude28import { createHmac } from "crypto";
43cf9b0Claude29import { __test } from "../hooks/post-receive";
30
ba93444Claude31const { triggerCrontechDeploy, signBody } = __test;
43cf9b0Claude32
33interface CapturedCall {
34 url: string;
35 init: RequestInit;
36}
37
38const origSecret = process.env.GLUECRON_WEBHOOK_SECRET;
39const origUrl = process.env.CRONTECH_DEPLOY_URL;
ba93444Claude40const origRepo = process.env.CRONTECH_REPO;
41
42const NULL_REPO_ID = "00000000-0000-0000-0000-000000000000";
43const ZERO_SHA = "0000000000000000000000000000000000000000";
43cf9b0Claude44
ba93444Claude45function makeArgs(overrides: Partial<{
46 owner: string;
47 repo: string;
48 before: string;
49 after: string;
50 ref: string;
51 branch: string;
52 repositoryId: string;
53}> = {}) {
54 return {
55 owner: "ccantynz-alt",
56 repo: "crontech",
57 before: ZERO_SHA,
58 after: "a".repeat(40),
59 ref: "refs/heads/Main",
60 branch: "Main",
61 repositoryId: NULL_REPO_ID,
62 ...overrides,
63 };
64}
43cf9b0Claude65
ba93444Claude66function captureFetch(
67 responder: (callIdx: number) => Response | Promise<Response> = () =>
43cf9b0Claude68 new Response(
ba93444Claude69 JSON.stringify({ ok: true, deploymentId: "d1" }),
43cf9b0Claude70 { status: 200, headers: { "Content-Type": "application/json" } }
71 )
ba93444Claude72): { calls: CapturedCall[]; fn: typeof fetch } {
43cf9b0Claude73 const calls: CapturedCall[] = [];
ba93444Claude74 const fn = (async (
43cf9b0Claude75 input: RequestInfo | URL,
76 init: RequestInit = {}
77 ): Promise<Response> => {
ba93444Claude78 const i = calls.length;
43cf9b0Claude79 calls.push({ url: String(input), init });
ba93444Claude80 return responder(i);
81 }) as unknown as typeof fetch;
82 return { calls, fn };
43cf9b0Claude83}
84
ba93444Claude85const noSleep = async (_ms: number) => {};
86
87describe("hooks/post-receive — signBody", () => {
88 it("returns null when no secret", () => {
89 expect(signBody("any body", "")).toBeNull();
90 });
91
92 it("produces sha256=<hex hmac>", () => {
93 const body = '{"event":"push"}';
94 const secret = "topsecret";
95 const expected =
96 "sha256=" + createHmac("sha256", secret).update(body).digest("hex");
97 expect(signBody(body, secret)).toBe(expected);
98 });
99
100 it("is deterministic for the same input", () => {
101 const a = signBody("body", "k");
102 const b = signBody("body", "k");
103 expect(a).toBe(b);
104 });
43cf9b0Claude105
ba93444Claude106 it("changes when the body changes", () => {
107 const a = signBody("body1", "k");
108 const b = signBody("body2", "k");
109 expect(a).not.toBe(b);
110 });
111});
43cf9b0Claude112
ba93444Claude113describe("hooks/post-receive — triggerCrontechDeploy (BLK-016 sender)", () => {
43cf9b0Claude114 beforeEach(() => {
115 delete process.env.GLUECRON_WEBHOOK_SECRET;
116 delete process.env.CRONTECH_DEPLOY_URL;
ba93444Claude117 delete process.env.CRONTECH_REPO;
43cf9b0Claude118 });
119
120 afterEach(() => {
121 if (origSecret === undefined) delete process.env.GLUECRON_WEBHOOK_SECRET;
122 else process.env.GLUECRON_WEBHOOK_SECRET = origSecret;
123 if (origUrl === undefined) delete process.env.CRONTECH_DEPLOY_URL;
124 else process.env.CRONTECH_DEPLOY_URL = origUrl;
ba93444Claude125 if (origRepo === undefined) delete process.env.CRONTECH_REPO;
126 else process.env.CRONTECH_REPO = origRepo;
43cf9b0Claude127 });
128
129 it("is exported from __test", () => {
130 expect(typeof triggerCrontechDeploy).toBe("function");
131 });
132
ba93444Claude133 it("POSTs to /api/webhooks/gluecron-push (matches Crontech receiver path)", async () => {
134 const { calls, fn } = captureFetch();
43cf9b0Claude135
ba93444Claude136 await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
43cf9b0Claude137
138 expect(calls.length).toBe(1);
139 expect(calls[0]!.url).toBe(
ba93444Claude140 "https://crontech.ai/api/webhooks/gluecron-push"
43cf9b0Claude141 );
ba93444Claude142 expect(calls[0]!.url).not.toContain("/api/hooks/gluecron/push");
43cf9b0Claude143 expect(calls[0]!.init.method).toBe("POST");
144 });
145
2316901Claude146 it("sends the GitHub-style push payload (event/repo/ref/sha/pusher/commits)", async () => {
ea52715copilot-swe-agent[bot]147 process.env.GLUECRON_WEBHOOK_SECRET = "webhook-test-value";
2316901Claude148 const { calls, fn } = captureFetch();
149 const after = "b".repeat(40);
150 const before = "c".repeat(40);
43cf9b0Claude151
152 await triggerCrontechDeploy(
ba93444Claude153 makeArgs({
154 owner: "acme",
155 repo: "api",
156 after,
157 before,
158 ref: "refs/heads/Main",
159 branch: "Main",
160 }),
161 { fetchImpl: fn, sleep: noSleep }
43cf9b0Claude162 );
163
ba93444Claude164 const body = JSON.parse(String(calls[0]!.init.body));
165 expect(body.event).toBe("push");
166 expect(body.repository).toEqual({ full_name: "acme/api" });
167 expect(body.ref).toBe("refs/heads/Main");
168 expect(body.after).toBe(after);
169 expect(body.before).toBe(before);
170 expect(body.pusher).toBeDefined();
171 expect(typeof body.pusher.name).toBe("string");
172 expect(typeof body.pusher.email).toBe("string");
173 expect(Array.isArray(body.commits)).toBe(true);
174 expect(typeof body.sent_at).toBe("string");
175 expect(new Date(body.sent_at).toString()).not.toBe("Invalid Date");
176 expect(body.source).toBe("gluecron");
177 });
178
179 it("signs the body with HMAC-SHA256 in X-Gluecron-Signature when secret is set", async () => {
180 process.env.GLUECRON_WEBHOOK_SECRET = "shared-vultr-secret";
181 const { calls, fn } = captureFetch();
182
183 await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
184
43cf9b0Claude185 const headers = calls[0]!.init.headers as Record<string, string>;
ba93444Claude186 const sentBody = String(calls[0]!.init.body);
187 const expected =
188 "sha256=" +
189 createHmac("sha256", "shared-vultr-secret")
190 .update(sentBody)
191 .digest("hex");
192 expect(headers["X-Gluecron-Signature"]).toBe(expected);
43cf9b0Claude193 expect(headers["Content-Type"]).toBe("application/json");
194 });
195
ba93444Claude196 it("omits X-Gluecron-Signature when no secret is configured", async () => {
197 const { calls, fn } = captureFetch();
43cf9b0Claude198
ba93444Claude199 await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
43cf9b0Claude200
201 const headers = calls[0]!.init.headers as Record<string, string>;
ba93444Claude202 expect(headers["X-Gluecron-Signature"]).toBeUndefined();
43cf9b0Claude203 });
204
ba93444Claude205 it("attaches X-Gluecron-Event=push and a non-empty X-Gluecron-Delivery id", async () => {
206 const { calls, fn } = captureFetch();
207
208 await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
209
210 const headers = calls[0]!.init.headers as Record<string, string>;
211 expect(headers["X-Gluecron-Event"]).toBe("push");
212 expect(headers["X-Gluecron-Delivery"]).toBeDefined();
213 expect(headers["X-Gluecron-Delivery"]!.length).toBeGreaterThan(0);
214 });
215
216 it("ref carries the actual case of the branch (Main, not main)", async () => {
217 const { calls, fn } = captureFetch();
43cf9b0Claude218
219 await triggerCrontechDeploy(
ba93444Claude220 makeArgs({ ref: "refs/heads/Main", branch: "Main" }),
221 { fetchImpl: fn, sleep: noSleep }
43cf9b0Claude222 );
223
224 const body = JSON.parse(String(calls[0]!.init.body));
ba93444Claude225 expect(body.ref).toBe("refs/heads/Main");
226 expect(body.ref).not.toBe("refs/heads/main");
43cf9b0Claude227 });
228
ba93444Claude229 it("retries on 5xx with provided backoff schedule, stops on first 2xx", async () => {
230 const responses = [
231 new Response("", { status: 502 }),
232 new Response("", { status: 503 }),
233 new Response("", { status: 200 }),
234 ];
235 const { calls, fn } = captureFetch((i) => responses[i]!);
236 const sleeps: number[] = [];
43cf9b0Claude237
ba93444Claude238 await triggerCrontechDeploy(makeArgs(), {
239 fetchImpl: fn,
240 sleep: async (ms) => { sleeps.push(ms); },
241 retryDelaysMs: [10, 20, 30, 40, 50],
242 });
243
244 expect(calls.length).toBe(3);
245 // Two waits — between attempt 1→2 and 2→3. None after the successful 3rd.
246 expect(sleeps).toEqual([10, 20]);
247 });
248
249 it("gives up after the configured number of attempts on persistent 5xx", async () => {
250 const { calls, fn } = captureFetch(() => new Response("", { status: 500 }));
251 const sleeps: number[] = [];
252
253 await triggerCrontechDeploy(makeArgs(), {
254 fetchImpl: fn,
255 sleep: async (ms) => { sleeps.push(ms); },
256 retryDelaysMs: [1, 2, 3, 4, 5],
257 });
258
259 // 5 delays + 1 initial = 6 total attempts (consistent with at-least-once).
260 expect(calls.length).toBe(6);
261 expect(sleeps).toEqual([1, 2, 3, 4, 5]);
262 });
263
264 it("does not retry on unrecoverable 4xx (e.g. 401 invalid signature)", async () => {
265 const { calls, fn } = captureFetch(() => new Response("", { status: 401 }));
266 const sleeps: number[] = [];
267
268 await triggerCrontechDeploy(makeArgs(), {
269 fetchImpl: fn,
270 sleep: async (ms) => { sleeps.push(ms); },
271 retryDelaysMs: [1, 2, 3, 4, 5],
272 });
43cf9b0Claude273
274 expect(calls.length).toBe(1);
ba93444Claude275 expect(sleeps).toEqual([]);
43cf9b0Claude276 });
277
ba93444Claude278 it("does retry 408 (request timeout) and 429 (rate limit)", async () => {
279 const responses = [
280 new Response("", { status: 429 }),
281 new Response("", { status: 408 }),
282 new Response("", { status: 200 }),
283 ];
284 const { calls, fn } = captureFetch((i) => responses[i]!);
285
286 await triggerCrontechDeploy(makeArgs(), {
287 fetchImpl: fn,
288 sleep: noSleep,
289 retryDelaysMs: [1, 2, 3, 4, 5],
290 });
291
292 expect(calls.length).toBe(3);
293 });
294
295 it("retries on network errors (fetch throws)", async () => {
296 let callCount = 0;
297 const fn = (async () => {
298 callCount++;
299 if (callCount < 3) throw new Error("ECONNREFUSED");
300 return new Response("", { status: 200 });
301 }) as unknown as typeof fetch;
302
303 await triggerCrontechDeploy(makeArgs(), {
304 fetchImpl: fn,
305 sleep: noSleep,
306 retryDelaysMs: [1, 2, 3, 4, 5],
307 });
308
309 expect(callCount).toBe(3);
43cf9b0Claude310 });
311
ba93444Claude312 it("does not throw when receiver responds 401 (unconfigured-secret path)", async () => {
313 const { fn } = captureFetch(() => new Response("", { status: 401 }));
43cf9b0Claude314 await expect(
ba93444Claude315 triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep })
43cf9b0Claude316 ).resolves.toBeUndefined();
ba93444Claude317 });
318
319 it("uses a default exponential-backoff schedule of 1s/4s/16s/64s/256s", () => {
320 expect(__test.RETRY_DELAYS_MS).toEqual([1_000, 4_000, 16_000, 64_000, 256_000]);
43cf9b0Claude321 });
322});