CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 | /**
* BLK-016 — Crontech deploy webhook sender.
*
* Asserts that `triggerCrontechDeploy` (in `src/hooks/post-receive.ts`)
* matches the wire contract documented at the top of that helper, which
* is the inbound contract for Crontech's
* `apps/api/src/webhooks/gluecron-push.ts` receiver:
*
* POST https://crontech.ai/api/webhooks/gluecron-push
* Content-Type: application/json
* X-Gluecron-Signature: sha256=<hex(hmac-sha256(body, secret))>
*
* body = {
* event: "push",
* repository: { full_name },
* ref, after, before,
* pusher: { name, email },
* commits: [...]
* }
*
* Plus at-least-once delivery: 5 attempts on 5xx with exponential backoff,
* stop on first 2xx or unrecoverable 4xx.
*
* The helper swallows DB errors, so these tests work without a real DB.
*/
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
import { createHmac } from "crypto";
import { __test } from "../hooks/post-receive";
const { triggerCrontechDeploy, signBody } = __test;
interface CapturedCall {
url: string;
init: RequestInit;
}
const origSecret = process.env.GLUECRON_WEBHOOK_SECRET;
const origUrl = process.env.CRONTECH_DEPLOY_URL;
const origRepo = process.env.CRONTECH_REPO;
const NULL_REPO_ID = "00000000-0000-0000-0000-000000000000";
const ZERO_SHA = "0000000000000000000000000000000000000000";
function makeArgs(overrides: Partial<{
owner: string;
repo: string;
before: string;
after: string;
ref: string;
branch: string;
repositoryId: string;
}> = {}) {
return {
owner: "ccantynz-alt",
repo: "crontech",
before: ZERO_SHA,
after: "a".repeat(40),
ref: "refs/heads/Main",
branch: "Main",
repositoryId: NULL_REPO_ID,
...overrides,
};
}
function captureFetch(
responder: (callIdx: number) => Response | Promise<Response> = () =>
new Response(
JSON.stringify({ ok: true, deploymentId: "d1" }),
{ status: 200, headers: { "Content-Type": "application/json" } }
)
): { calls: CapturedCall[]; fn: typeof fetch } {
const calls: CapturedCall[] = [];
const fn = (async (
input: RequestInfo | URL,
init: RequestInit = {}
): Promise<Response> => {
const i = calls.length;
calls.push({ url: String(input), init });
return responder(i);
}) as unknown as typeof fetch;
return { calls, fn };
}
const noSleep = async (_ms: number) => {};
describe("hooks/post-receive — signBody", () => {
it("returns null when no secret", () => {
expect(signBody("any body", "")).toBeNull();
});
it("produces sha256=<hex hmac>", () => {
const body = '{"event":"push"}';
const secret = "topsecret";
const expected =
"sha256=" + createHmac("sha256", secret).update(body).digest("hex");
expect(signBody(body, secret)).toBe(expected);
});
it("is deterministic for the same input", () => {
const a = signBody("body", "k");
const b = signBody("body", "k");
expect(a).toBe(b);
});
it("changes when the body changes", () => {
const a = signBody("body1", "k");
const b = signBody("body2", "k");
expect(a).not.toBe(b);
});
});
describe("hooks/post-receive — triggerCrontechDeploy (BLK-016 sender)", () => {
beforeEach(() => {
delete process.env.GLUECRON_WEBHOOK_SECRET;
delete process.env.CRONTECH_DEPLOY_URL;
delete process.env.CRONTECH_REPO;
});
afterEach(() => {
if (origSecret === undefined) delete process.env.GLUECRON_WEBHOOK_SECRET;
else process.env.GLUECRON_WEBHOOK_SECRET = origSecret;
if (origUrl === undefined) delete process.env.CRONTECH_DEPLOY_URL;
else process.env.CRONTECH_DEPLOY_URL = origUrl;
if (origRepo === undefined) delete process.env.CRONTECH_REPO;
else process.env.CRONTECH_REPO = origRepo;
});
it("is exported from __test", () => {
expect(typeof triggerCrontechDeploy).toBe("function");
});
it("POSTs to /api/webhooks/gluecron-push (matches Crontech receiver path)", async () => {
const { calls, fn } = captureFetch();
await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
expect(calls.length).toBe(1);
expect(calls[0]!.url).toBe(
"https://crontech.ai/api/webhooks/gluecron-push"
);
expect(calls[0]!.url).not.toContain("/api/hooks/gluecron/push");
expect(calls[0]!.init.method).toBe("POST");
});
it("sends Authorization: Bearer <secret> when GLUECRON_WEBHOOK_SECRET is set", async () => {
process.env.GLUECRON_WEBHOOK_SECRET = "webhook-test-value";
const calls = installFetchCapture();
await triggerCrontechDeploy(
makeArgs({
owner: "acme",
repo: "api",
after,
before,
ref: "refs/heads/Main",
branch: "Main",
}),
{ fetchImpl: fn, sleep: noSleep }
);
const body = JSON.parse(String(calls[0]!.init.body));
expect(body.event).toBe("push");
expect(body.repository).toEqual({ full_name: "acme/api" });
expect(body.ref).toBe("refs/heads/Main");
expect(body.after).toBe(after);
expect(body.before).toBe(before);
expect(body.pusher).toBeDefined();
expect(typeof body.pusher.name).toBe("string");
expect(typeof body.pusher.email).toBe("string");
expect(Array.isArray(body.commits)).toBe(true);
expect(typeof body.sent_at).toBe("string");
expect(new Date(body.sent_at).toString()).not.toBe("Invalid Date");
expect(body.source).toBe("gluecron");
});
it("signs the body with HMAC-SHA256 in X-Gluecron-Signature when secret is set", async () => {
process.env.GLUECRON_WEBHOOK_SECRET = "shared-vultr-secret";
const { calls, fn } = captureFetch();
await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
const headers = calls[0]!.init.headers as Record<string, string>;
const sentBody = String(calls[0]!.init.body);
const expected =
"sha256=" +
createHmac("sha256", "shared-vultr-secret")
.update(sentBody)
.digest("hex");
expect(headers["X-Gluecron-Signature"]).toBe(expected);
expect(headers["Content-Type"]).toBe("application/json");
});
it("omits X-Gluecron-Signature when no secret is configured", async () => {
const { calls, fn } = captureFetch();
await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
const headers = calls[0]!.init.headers as Record<string, string>;
expect(headers["X-Gluecron-Signature"]).toBeUndefined();
});
it("attaches X-Gluecron-Event=push and a non-empty X-Gluecron-Delivery id", async () => {
const { calls, fn } = captureFetch();
await triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep });
const headers = calls[0]!.init.headers as Record<string, string>;
expect(headers["X-Gluecron-Event"]).toBe("push");
expect(headers["X-Gluecron-Delivery"]).toBeDefined();
expect(headers["X-Gluecron-Delivery"]!.length).toBeGreaterThan(0);
});
it("ref carries the actual case of the branch (Main, not main)", async () => {
const { calls, fn } = captureFetch();
await triggerCrontechDeploy(
makeArgs({ ref: "refs/heads/Main", branch: "Main" }),
{ fetchImpl: fn, sleep: noSleep }
);
const body = JSON.parse(String(calls[0]!.init.body));
expect(body.ref).toBe("refs/heads/Main");
expect(body.ref).not.toBe("refs/heads/main");
});
it("retries on 5xx with provided backoff schedule, stops on first 2xx", async () => {
const responses = [
new Response("", { status: 502 }),
new Response("", { status: 503 }),
new Response("", { status: 200 }),
];
const { calls, fn } = captureFetch((i) => responses[i]!);
const sleeps: number[] = [];
await triggerCrontechDeploy(makeArgs(), {
fetchImpl: fn,
sleep: async (ms) => { sleeps.push(ms); },
retryDelaysMs: [10, 20, 30, 40, 50],
});
expect(calls.length).toBe(3);
// Two waits — between attempt 1→2 and 2→3. None after the successful 3rd.
expect(sleeps).toEqual([10, 20]);
});
it("gives up after the configured number of attempts on persistent 5xx", async () => {
const { calls, fn } = captureFetch(() => new Response("", { status: 500 }));
const sleeps: number[] = [];
await triggerCrontechDeploy(makeArgs(), {
fetchImpl: fn,
sleep: async (ms) => { sleeps.push(ms); },
retryDelaysMs: [1, 2, 3, 4, 5],
});
// 5 delays + 1 initial = 6 total attempts (consistent with at-least-once).
expect(calls.length).toBe(6);
expect(sleeps).toEqual([1, 2, 3, 4, 5]);
});
it("does not retry on unrecoverable 4xx (e.g. 401 invalid signature)", async () => {
const { calls, fn } = captureFetch(() => new Response("", { status: 401 }));
const sleeps: number[] = [];
await triggerCrontechDeploy(makeArgs(), {
fetchImpl: fn,
sleep: async (ms) => { sleeps.push(ms); },
retryDelaysMs: [1, 2, 3, 4, 5],
});
expect(calls.length).toBe(1);
expect(sleeps).toEqual([]);
});
it("does retry 408 (request timeout) and 429 (rate limit)", async () => {
const responses = [
new Response("", { status: 429 }),
new Response("", { status: 408 }),
new Response("", { status: 200 }),
];
const { calls, fn } = captureFetch((i) => responses[i]!);
await triggerCrontechDeploy(makeArgs(), {
fetchImpl: fn,
sleep: noSleep,
retryDelaysMs: [1, 2, 3, 4, 5],
});
expect(calls.length).toBe(3);
});
it("retries on network errors (fetch throws)", async () => {
let callCount = 0;
const fn = (async () => {
callCount++;
if (callCount < 3) throw new Error("ECONNREFUSED");
return new Response("", { status: 200 });
}) as unknown as typeof fetch;
await triggerCrontechDeploy(makeArgs(), {
fetchImpl: fn,
sleep: noSleep,
retryDelaysMs: [1, 2, 3, 4, 5],
});
expect(callCount).toBe(3);
});
it("does not throw when receiver responds 401 (unconfigured-secret path)", async () => {
const { fn } = captureFetch(() => new Response("", { status: 401 }));
await expect(
triggerCrontechDeploy(makeArgs(), { fetchImpl: fn, sleep: noSleep })
).resolves.toBeUndefined();
});
it("uses a default exponential-backoff schedule of 1s/4s/16s/64s/256s", () => {
expect(__test.RETRY_DELAYS_MS).toEqual([1_000, 4_000, 16_000, 64_000, 256_000]);
});
});
|