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.tsBlame320 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
146 it("sends Authorization: Bearer <secret> when GLUECRON_WEBHOOK_SECRET is set", async () => {
ea52715copilot-swe-agent[bot]147 process.env.GLUECRON_WEBHOOK_SECRET = "webhook-test-value";
43cf9b0Claude148 const calls = installFetchCapture();
149
150 await triggerCrontechDeploy(
ba93444Claude151 makeArgs({
152 owner: "acme",
153 repo: "api",
154 after,
155 before,
156 ref: "refs/heads/Main",
157 branch: "Main",
158 }),
159 { fetchImpl: fn, sleep: noSleep }
43cf9b0Claude160 );
161
ba93444Claude162 const body = JSON.parse(String(calls[0]!.init.body));
163 expect(body.event).toBe("push");
164 expect(body.repository).toEqual({ full_name: "acme/api" });
165 expect(body.ref).toBe("refs/heads/Main");
166 expect(body.after).toBe(after);
167 expect(body.before).toBe(before);
168 expect(body.pusher).toBeDefined();
169 expect(typeof body.pusher.name).toBe("string");
170 expect(typeof body.pusher.email).toBe("string");
171 expect(Array.isArray(body.commits)).toBe(true);
172 expect(typeof body.sent_at).toBe("string");
173 expect(new Date(body.sent_at).toString()).not.toBe("Invalid Date");
174 expect(body.source).toBe("gluecron");
175 });
176
177 it("signs the body with HMAC-SHA256 in X-Gluecron-Signature when secret is set", async () => {
178 process.env.GLUECRON_WEBHOOK_SECRET = "shared-vultr-secret";
179 const { calls, fn } = captureFetch();
180
181 await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
182
43cf9b0Claude183 const headers = calls[0]!.init.headers as Record<string, string>;
ba93444Claude184 const sentBody = String(calls[0]!.init.body);
185 const expected =
186 "sha256=" +
187 createHmac("sha256", "shared-vultr-secret")
188 .update(sentBody)
189 .digest("hex");
190 expect(headers["X-Gluecron-Signature"]).toBe(expected);
43cf9b0Claude191 expect(headers["Content-Type"]).toBe("application/json");
192 });
193
ba93444Claude194 it("omits X-Gluecron-Signature when no secret is configured", async () => {
195 const { calls, fn } = captureFetch();
43cf9b0Claude196
ba93444Claude197 await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
43cf9b0Claude198
199 const headers = calls[0]!.init.headers as Record<string, string>;
ba93444Claude200 expect(headers["X-Gluecron-Signature"]).toBeUndefined();
43cf9b0Claude201 });
202
ba93444Claude203 it("attaches X-Gluecron-Event=push and a non-empty X-Gluecron-Delivery id", async () => {
204 const { calls, fn } = captureFetch();
205
206 await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
207
208 const headers = calls[0]!.init.headers as Record<string, string>;
209 expect(headers["X-Gluecron-Event"]).toBe("push");
210 expect(headers["X-Gluecron-Delivery"]).toBeDefined();
211 expect(headers["X-Gluecron-Delivery"]!.length).toBeGreaterThan(0);
212 });
213
214 it("ref carries the actual case of the branch (Main, not main)", async () => {
215 const { calls, fn } = captureFetch();
43cf9b0Claude216
217 await triggerCrontechDeploy(
ba93444Claude218 makeArgs({ ref: "refs/heads/Main", branch: "Main" }),
219 { fetchImpl: fn, sleep: noSleep }
43cf9b0Claude220 );
221
222 const body = JSON.parse(String(calls[0]!.init.body));
ba93444Claude223 expect(body.ref).toBe("refs/heads/Main");
224 expect(body.ref).not.toBe("refs/heads/main");
43cf9b0Claude225 });
226
ba93444Claude227 it("retries on 5xx with provided backoff schedule, stops on first 2xx", async () => {
228 const responses = [
229 new Response("", { status: 502 }),
230 new Response("", { status: 503 }),
231 new Response("", { status: 200 }),
232 ];
233 const { calls, fn } = captureFetch((i) => responses[i]!);
234 const sleeps: number[] = [];
43cf9b0Claude235
ba93444Claude236 await triggerCrontechDeploy(makeArgs(), {
237 fetchImpl: fn,
238 sleep: async (ms) => { sleeps.push(ms); },
239 retryDelaysMs: [10, 20, 30, 40, 50],
240 });
241
242 expect(calls.length).toBe(3);
243 // Two waits — between attempt 1→2 and 2→3. None after the successful 3rd.
244 expect(sleeps).toEqual([10, 20]);
245 });
246
247 it("gives up after the configured number of attempts on persistent 5xx", async () => {
248 const { calls, fn } = captureFetch(() => new Response("", { status: 500 }));
249 const sleeps: number[] = [];
250
251 await triggerCrontechDeploy(makeArgs(), {
252 fetchImpl: fn,
253 sleep: async (ms) => { sleeps.push(ms); },
254 retryDelaysMs: [1, 2, 3, 4, 5],
255 });
256
257 // 5 delays + 1 initial = 6 total attempts (consistent with at-least-once).
258 expect(calls.length).toBe(6);
259 expect(sleeps).toEqual([1, 2, 3, 4, 5]);
260 });
261
262 it("does not retry on unrecoverable 4xx (e.g. 401 invalid signature)", async () => {
263 const { calls, fn } = captureFetch(() => new Response("", { status: 401 }));
264 const sleeps: number[] = [];
265
266 await triggerCrontechDeploy(makeArgs(), {
267 fetchImpl: fn,
268 sleep: async (ms) => { sleeps.push(ms); },
269 retryDelaysMs: [1, 2, 3, 4, 5],
270 });
43cf9b0Claude271
272 expect(calls.length).toBe(1);
ba93444Claude273 expect(sleeps).toEqual([]);
43cf9b0Claude274 });
275
ba93444Claude276 it("does retry 408 (request timeout) and 429 (rate limit)", async () => {
277 const responses = [
278 new Response("", { status: 429 }),
279 new Response("", { status: 408 }),
280 new Response("", { status: 200 }),
281 ];
282 const { calls, fn } = captureFetch((i) => responses[i]!);
283
284 await triggerCrontechDeploy(makeArgs(), {
285 fetchImpl: fn,
286 sleep: noSleep,
287 retryDelaysMs: [1, 2, 3, 4, 5],
288 });
289
290 expect(calls.length).toBe(3);
291 });
292
293 it("retries on network errors (fetch throws)", async () => {
294 let callCount = 0;
295 const fn = (async () => {
296 callCount++;
297 if (callCount < 3) throw new Error("ECONNREFUSED");
298 return new Response("", { status: 200 });
299 }) as unknown as typeof fetch;
300
301 await triggerCrontechDeploy(makeArgs(), {
302 fetchImpl: fn,
303 sleep: noSleep,
304 retryDelaysMs: [1, 2, 3, 4, 5],
305 });
306
307 expect(callCount).toBe(3);
43cf9b0Claude308 });
309
ba93444Claude310 it("does not throw when receiver responds 401 (unconfigured-secret path)", async () => {
311 const { fn } = captureFetch(() => new Response("", { status: 401 }));
43cf9b0Claude312 await expect(
ba93444Claude313 triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep })
43cf9b0Claude314 ).resolves.toBeUndefined();
ba93444Claude315 });
316
317 it("uses a default exponential-backoff schedule of 1s/4s/16s/64s/256s", () => {
318 expect(__test.RETRY_DELAYS_MS).toEqual([1_000, 4_000, 16_000, 64_000, 256_000]);
43cf9b0Claude319 });
320});