import { buildState } from "./buildkite"; import { isObject, string } from "./xrpc"; const maxBodyBytes = 1024 * 1024; const maxClockSkewSeconds = 300; async function verified( secret: string | undefined, signature: string, signed: Uint8Array, ): Promise { if (secret === undefined || secret === "") { return false; } const key = await crypto.subtle.importKey( "raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"], ); return await crypto.subtle.verify("HMAC", key, Uint8Array.fromHex(signature), signed); } export async function buildkiteWebhook( request: Request, env: Env, ctx: ExecutionContext, ): Promise { const header = request.headers.get("X-Buildkite-Signature") ?? ""; const [, timestamp = "", signature = ""] = /^timestamp=(\d+),signature=([0-9a-f]{64})$/.exec(header) ?? []; const ts = Number(timestamp); if (signature === "" || Math.abs(Date.now() / 1000 - ts) > maxClockSkewSeconds) { return new Response("invalid signature", { status: 401 }); } const length = Number(request.headers.get("Content-Length") ?? Number.NaN); if (!Number.isInteger(length) || length > maxBodyBytes) { return new Response("body needs a length of at most 1 MiB", { status: 413 }); } const body = new Uint8Array(await request.arrayBuffer()); const prefix = new TextEncoder().encode(`${timestamp}.`); const signed = new Uint8Array(prefix.length + body.length); signed.set(prefix); signed.set(body, prefix.length); if (!(await verified(env.BUILDKITE_WEBHOOK_SECRET, signature, signed))) { return new Response("invalid signature", { status: 401 }); } let payload: unknown; try { payload = JSON.parse(new TextDecoder().decode(body)); } catch { return new Response("invalid JSON", { status: 400 }); } if (!isObject(payload)) { return new Response(null); } const { build, pipeline, job } = payload; const event = request.headers.get("X-Buildkite-Event") ?? ""; const isBuild = event.startsWith("build."); if (!isObject(build) || !(isBuild || event.startsWith("job."))) { return new Response(null); } const state = buildState(build); const meta = isObject(build["meta_data"]) ? build["meta_data"] : {}; const run = string(meta["treadle:pipeline"]); const workflow = string(meta["treadle:workflow"]); if (isBuild && state !== undefined) { await ctx.exports.Store.getByName("main").updateBuild({ ...state, ts, pipeline: run, workflow, slug: isObject(pipeline) ? string(pipeline["slug"]) : undefined, commit: string(build["commit"]), }); } const number = build["number"]; // The Logs object drops events of other builds and events nobody watches. if (run !== undefined && workflow !== undefined && typeof number === "number") { const logs = ctx.exports.Logs.getByName(`${run}/${workflow}`); ctx.waitUntil( logs .update(number, isBuild ? state?.status : undefined, isBuild ? undefined : job) .catch((error: unknown) => { console.warn("log stream update failed", { run, workflow, error: String(error), }); }), ); } return new Response(null); }