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.tsBlame321 lines · 1 contributor
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
5164fabClaude146 it("posts a GitHub-shaped push payload (event, repository, ref, before/after, pusher, commits, sent_at, source)", async () => {
147 const after = "b".repeat(40);
148 const before = "c".repeat(40);
149 const { calls, fn } = captureFetch();
43cf9b0Claude150
151 await triggerCrontechDeploy(
ba93444Claude152 makeArgs({
153 owner: "acme",
154 repo: "api",
155 after,
156 before,
157 ref: "refs/heads/Main",
158 branch: "Main",
159 }),
160 { fetchImpl: fn, sleep: noSleep }
43cf9b0Claude161 );
162
ba93444Claude163 const body = JSON.parse(String(calls[0]!.init.body));
164 expect(body.event).toBe("push");
165 expect(body.repository).toEqual({ full_name: "acme/api" });
166 expect(body.ref).toBe("refs/heads/Main");
167 expect(body.after).toBe(after);
168 expect(body.before).toBe(before);
169 expect(body.pusher).toBeDefined();
170 expect(typeof body.pusher.name).toBe("string");
171 expect(typeof body.pusher.email).toBe("string");
172 expect(Array.isArray(body.commits)).toBe(true);
173 expect(typeof body.sent_at).toBe("string");
174 expect(new Date(body.sent_at).toString()).not.toBe("Invalid Date");
175 expect(body.source).toBe("gluecron");
176 });
177
178 it("signs the body with HMAC-SHA256 in X-Gluecron-Signature when secret is set", async () => {
179 process.env.GLUECRON_WEBHOOK_SECRET = "shared-vultr-secret";
180 const { calls, fn } = captureFetch();
181
182 await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
183
43cf9b0Claude184 const headers = calls[0]!.init.headers as Record<string, string>;
ba93444Claude185 const sentBody = String(calls[0]!.init.body);
186 const expected =
187 "sha256=" +
188 createHmac("sha256", "shared-vultr-secret")
189 .update(sentBody)
190 .digest("hex");
191 expect(headers["X-Gluecron-Signature"]).toBe(expected);
43cf9b0Claude192 expect(headers["Content-Type"]).toBe("application/json");
193 });
194
ba93444Claude195 it("omits X-Gluecron-Signature when no secret is configured", async () => {
196 const { calls, fn } = captureFetch();
43cf9b0Claude197
ba93444Claude198 await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
43cf9b0Claude199
200 const headers = calls[0]!.init.headers as Record<string, string>;
ba93444Claude201 expect(headers["X-Gluecron-Signature"]).toBeUndefined();
43cf9b0Claude202 });
203
ba93444Claude204 it("attaches X-Gluecron-Event=push and a non-empty X-Gluecron-Delivery id", async () => {
205 const { calls, fn } = captureFetch();
206
207 await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
208
209 const headers = calls[0]!.init.headers as Record<string, string>;
210 expect(headers["X-Gluecron-Event"]).toBe("push");
211 expect(headers["X-Gluecron-Delivery"]).toBeDefined();
212 expect(headers["X-Gluecron-Delivery"]!.length).toBeGreaterThan(0);
213 });
214
215 it("ref carries the actual case of the branch (Main, not main)", async () => {
216 const { calls, fn } = captureFetch();
43cf9b0Claude217
218 await triggerCrontechDeploy(
ba93444Claude219 makeArgs({ ref: "refs/heads/Main", branch: "Main" }),
220 { fetchImpl: fn, sleep: noSleep }
43cf9b0Claude221 );
222
223 const body = JSON.parse(String(calls[0]!.init.body));
ba93444Claude224 expect(body.ref).toBe("refs/heads/Main");
225 expect(body.ref).not.toBe("refs/heads/main");
43cf9b0Claude226 });
227
ba93444Claude228 it("retries on 5xx with provided backoff schedule, stops on first 2xx", async () => {
229 const responses = [
230 new Response("", { status: 502 }),
231 new Response("", { status: 503 }),
232 new Response("", { status: 200 }),
233 ];
234 const { calls, fn } = captureFetch((i) => responses[i]!);
235 const sleeps: number[] = [];
43cf9b0Claude236
ba93444Claude237 await triggerCrontechDeploy(makeArgs(), {
238 fetchImpl: fn,
239 sleep: async (ms) => { sleeps.push(ms); },
240 retryDelaysMs: [10, 20, 30, 40, 50],
241 });
242
243 expect(calls.length).toBe(3);
244 // Two waits — between attempt 1→2 and 2→3. None after the successful 3rd.
245 expect(sleeps).toEqual([10, 20]);
246 });
247
248 it("gives up after the configured number of attempts on persistent 5xx", async () => {
249 const { calls, fn } = captureFetch(() => new Response("", { status: 500 }));
250 const sleeps: number[] = [];
251
252 await triggerCrontechDeploy(makeArgs(), {
253 fetchImpl: fn,
254 sleep: async (ms) => { sleeps.push(ms); },
255 retryDelaysMs: [1, 2, 3, 4, 5],
256 });
257
258 // 5 delays + 1 initial = 6 total attempts (consistent with at-least-once).
259 expect(calls.length).toBe(6);
260 expect(sleeps).toEqual([1, 2, 3, 4, 5]);
261 });
262
263 it("does not retry on unrecoverable 4xx (e.g. 401 invalid signature)", async () => {
264 const { calls, fn } = captureFetch(() => new Response("", { status: 401 }));
265 const sleeps: number[] = [];
266
267 await triggerCrontechDeploy(makeArgs(), {
268 fetchImpl: fn,
269 sleep: async (ms) => { sleeps.push(ms); },
270 retryDelaysMs: [1, 2, 3, 4, 5],
271 });
43cf9b0Claude272
273 expect(calls.length).toBe(1);
ba93444Claude274 expect(sleeps).toEqual([]);
43cf9b0Claude275 });
276
ba93444Claude277 it("does retry 408 (request timeout) and 429 (rate limit)", async () => {
278 const responses = [
279 new Response("", { status: 429 }),
280 new Response("", { status: 408 }),
281 new Response("", { status: 200 }),
282 ];
283 const { calls, fn } = captureFetch((i) => responses[i]!);
284
285 await triggerCrontechDeploy(makeArgs(), {
286 fetchImpl: fn,
287 sleep: noSleep,
288 retryDelaysMs: [1, 2, 3, 4, 5],
289 });
290
291 expect(calls.length).toBe(3);
292 });
293
294 it("retries on network errors (fetch throws)", async () => {
295 let callCount = 0;
296 const fn = (async () => {
297 callCount++;
298 if (callCount < 3) throw new Error("ECONNREFUSED");
299 return new Response("", { status: 200 });
300 }) as unknown as typeof fetch;
301
302 await triggerCrontechDeploy(makeArgs(), {
303 fetchImpl: fn,
304 sleep: noSleep,
305 retryDelaysMs: [1, 2, 3, 4, 5],
306 });
307
308 expect(callCount).toBe(3);
43cf9b0Claude309 });
310
ba93444Claude311 it("does not throw when receiver responds 401 (unconfigured-secret path)", async () => {
312 const { fn } = captureFetch(() => new Response("", { status: 401 }));
43cf9b0Claude313 await expect(
ba93444Claude314 triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep })
43cf9b0Claude315 ).resolves.toBeUndefined();
ba93444Claude316 });
317
318 it("uses a default exponential-backoff schedule of 1s/4s/16s/64s/256s", () => {
319 expect(__test.RETRY_DELAYS_MS).toEqual([1_000, 4_000, 16_000, 64_000, 256_000]);
43cf9b0Claude320 });
321});