-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgithub.ts
More file actions
608 lines (548 loc) · 18.9 KB
/
Copy pathgithub.ts
File metadata and controls
608 lines (548 loc) · 18.9 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
// GitHub webhook handler for push-event-driven incremental re-indexing.
// Fully config-driven: uses webhook.repo_sources and webhook.path_triggers
// from pathfinder.yaml to determine which pushes trigger reindexing.
import crypto from "node:crypto";
import type { Request, Response } from "express";
import { getConfig, getServerConfig } from "../config.js";
import { upsertAtlasSeedCandidate } from "../db/atlas.js";
import { recordWebhookDelivery } from "../db/queries.js";
import { isAtlasSourceConfig } from "../types.js";
import {
extractAtlasPullRequestSeedCandidates,
type AtlasPullRequestPayload,
} from "./atlas.js";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface PushCommit {
added: string[];
modified: string[];
removed: string[];
}
interface PushPayload {
ref: string;
after: string;
before: string;
repository: {
clone_url: string;
default_branch: string;
full_name: string;
};
commits: PushCommit[];
}
export interface GitHubWebhookResult {
queuedReindex: boolean;
affectedSourceNames: string[];
}
const NO_REINDEX: GitHubWebhookResult = {
queuedReindex: false,
affectedSourceNames: [],
};
type HeaderValue = string | string[] | undefined;
type NormalizedHeader =
{ ok: true; value: string | undefined } | { ok: false; reason: string };
type DuplicateHeader = Extract<NormalizedHeader, { ok: false }>;
/**
* Minimal interface for the orchestrator dependency. The full
* IndexingOrchestrator lives in ../indexing/orchestrator.ts — we only
* depend on the subset we actually call so the webhook handler can function
* independently.
*/
export interface ReindexOrchestrator {
queueIncrementalReindex(repoUrl: string): void;
queueSourceReindex(sourceName: string): void;
}
// ---------------------------------------------------------------------------
// Signature verification
// ---------------------------------------------------------------------------
function verifySignature(
rawBody: Buffer,
signatureHeader: string | undefined,
secret: string,
): boolean {
if (!signatureHeader) return false;
const expected =
"sha256=" +
crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
const signatureBuffer = Buffer.from(signatureHeader, "utf-8");
const expectedBuffer = Buffer.from(expected, "utf-8");
// timingSafeEqual requires equal byte lengths, not equal JS string lengths.
if (signatureBuffer.length !== expectedBuffer.length) return false;
return crypto.timingSafeEqual(signatureBuffer, expectedBuffer);
}
function normalizeSingleHeader(
value: HeaderValue,
headerName: string,
rawHeaders: readonly string[] | undefined,
): NormalizedHeader {
if (Array.isArray(value)) {
return {
ok: false,
reason: `duplicate ${headerName} header`,
};
}
if (countRawHeaders(rawHeaders, headerName) > 1) {
return {
ok: false,
reason: `duplicate ${headerName} header`,
};
}
return { ok: true, value };
}
function countRawHeaders(
rawHeaders: readonly string[] | undefined,
headerName: string,
): number {
if (!Array.isArray(rawHeaders)) return 0;
let count = 0;
const normalizedHeaderName = headerName.toLowerCase();
for (let i = 0; i < rawHeaders.length; i += 2) {
if (rawHeaders[i]?.toLowerCase() === normalizedHeaderName) {
count += 1;
}
}
return count;
}
// ---------------------------------------------------------------------------
// Push-event helpers
// ---------------------------------------------------------------------------
function isDefaultBranchPush(payload: PushPayload): boolean {
const branch = payload.ref.replace("refs/heads/", "");
return branch === payload.repository.default_branch;
}
function normalizePathTrigger(trigger: string): string {
return trigger.replace(/^\.?\//, "").replace(/\/+$/, "");
}
function matchesPathTrigger(filePath: string, trigger: string): boolean {
const normalizedTrigger = normalizePathTrigger(trigger);
if (normalizedTrigger.length === 0) return true;
const normalizedPath = filePath.replace(/^\.?\//, "");
return (
normalizedPath === normalizedTrigger ||
normalizedPath.startsWith(`${normalizedTrigger}/`)
);
}
/**
* Check if any committed files match any of the given path prefixes.
* An empty prefixes array means "match everything" (no path filtering).
*/
function touchesPaths(payload: PushPayload, prefixes: string[]): boolean {
if (prefixes.length === 0) return true;
for (const commit of payload.commits) {
const allPaths = [...commit.added, ...commit.modified, ...commit.removed];
if (
allPaths.some((p) =>
prefixes.some((prefix) => matchesPathTrigger(p, prefix)),
)
) {
return true;
}
}
return false;
}
function hasPathTriggers(
pathTriggers: Record<string, string[]> | undefined,
sourceName: string,
): boolean {
return (pathTriggers?.[sourceName] ?? []).length > 0;
}
function isStringArray(value: unknown): value is string[] {
return (
Array.isArray(value) && value.every((item) => typeof item === "string")
);
}
function isPushCommit(value: unknown): value is PushCommit {
if (typeof value !== "object" || value == null) return false;
const commit = value as Record<string, unknown>;
return (
isStringArray(commit.added) &&
isStringArray(commit.modified) &&
isStringArray(commit.removed)
);
}
function isPushPayload(value: unknown): value is PushPayload {
if (typeof value !== "object" || value == null) return false;
const payload = value as Record<string, unknown>;
const repository = payload.repository;
if (typeof repository !== "object" || repository == null) return false;
const repo = repository as Record<string, unknown>;
return (
typeof payload.ref === "string" &&
typeof payload.after === "string" &&
typeof payload.before === "string" &&
typeof repo.clone_url === "string" &&
typeof repo.default_branch === "string" &&
typeof repo.full_name === "string" &&
Array.isArray(payload.commits) &&
payload.commits.every(isPushCommit)
);
}
function recordPullRequestDelivery(
delivery: Parameters<typeof recordWebhookDelivery>[0],
): void {
recordGithubWebhookDelivery(delivery);
}
function recordGithubWebhookDelivery(
delivery: Parameters<typeof recordWebhookDelivery>[0],
): void {
// Delivery tracking is non-blocking audit telemetry; webhook correctness
// depends on signature validation and seed writes, not analytics persistence.
recordWebhookDelivery(delivery).catch((err) => {
console.error("[webhook] Failed to record GitHub delivery:", err);
});
}
// ---------------------------------------------------------------------------
// Factory: create a handler wired to a specific orchestrator instance
// ---------------------------------------------------------------------------
export function createWebhookHandler(orchestrator: ReindexOrchestrator) {
return async function handleGithubWebhook(
req: Request,
res: Response,
): Promise<GitHubWebhookResult> {
const cfg = getConfig();
// -- Signature verification ----------------------------------------
// The route MUST be configured with express.raw() so req.body is a
// Buffer. If it isn't, bail out — we cannot safely verify the HMAC.
const rawBody = Buffer.isBuffer(req.body) ? req.body : null;
const payloadSize = rawBody?.length;
if (!rawBody) {
console.error(
"[webhook] req.body is not a Buffer — ensure the route uses express.raw()",
);
recordGithubWebhookDelivery({
source: "github",
decision: "error",
reason: "req.body not a Buffer",
payload_size: payloadSize,
});
res
.status(500)
.json({ error: "Server misconfiguration: raw body not available" });
return NO_REINDEX;
}
if (!cfg.githubWebhookSecret?.trim()) {
console.log(
"[webhook] Rejecting request — webhook secret not configured",
);
recordGithubWebhookDelivery({
source: "github",
decision: "error",
reason: "webhook secret not configured",
payload_size: payloadSize,
});
res.status(403).json({ error: "Forbidden" });
return NO_REINDEX;
}
const signatureHeader = normalizeSingleHeader(
req.headers["x-hub-signature-256"],
"x-hub-signature-256",
req.rawHeaders,
);
const eventHeader = normalizeSingleHeader(
req.headers["x-github-event"],
"x-github-event",
req.rawHeaders,
);
const deliveryHeader = normalizeSingleHeader(
req.headers["x-github-delivery"],
"x-github-delivery",
req.rawHeaders,
);
const duplicateHeader = [signatureHeader, eventHeader, deliveryHeader].find(
(header): header is DuplicateHeader => !header.ok,
);
if (duplicateHeader) {
recordGithubWebhookDelivery({
source: "github",
decision: "error",
reason: duplicateHeader.reason,
payload_size: payloadSize,
});
res.status(400).json({
error: "Duplicate GitHub webhook header",
header: duplicateHeader.reason
.replace(/^duplicate /, "")
.replace(/ header$/, ""),
});
return NO_REINDEX;
}
const signature = signatureHeader.ok ? signatureHeader.value : undefined;
if (!verifySignature(rawBody, signature, cfg.githubWebhookSecret)) {
recordGithubWebhookDelivery({
source: "github",
decision: "error",
reason: "invalid signature",
payload_size: payloadSize,
});
res.status(401).json({ error: "Invalid or missing webhook signature" });
return NO_REINDEX;
}
// -- Event routing -------------------------------------------------
const event = eventHeader.ok ? eventHeader.value : undefined;
if (event === "pull_request") {
let payload: AtlasPullRequestPayload;
try {
payload = JSON.parse(
rawBody.toString("utf-8"),
) as AtlasPullRequestPayload;
} catch {
recordPullRequestDelivery({
source: "github",
event_type: "pull_request",
decision: "error",
reason: "malformed JSON",
payload_size: payloadSize,
});
res.status(400).json({ error: "Malformed JSON payload" });
return NO_REINDEX;
}
const repoFullName = payload.repository?.full_name;
if (typeof repoFullName !== "string" || repoFullName.length === 0) {
recordPullRequestDelivery({
source: "github",
event_type: "pull_request",
decision: "error",
reason: "missing repository.full_name",
payload_size: payloadSize,
});
res.status(400).json({ error: "Malformed Atlas pull_request payload" });
return NO_REINDEX;
}
const serverCfg = getServerConfig();
const webhookCfg = serverCfg.webhook;
const sourceNames = webhookCfg?.repo_sources?.[repoFullName] ?? [];
if (sourceNames.length === 0) {
recordPullRequestDelivery({
source: "github",
event_type: "pull_request",
repo: repoFullName,
decision: "ignored",
reason: "repo not in webhook config",
payload_size: payloadSize,
});
res
.status(200)
.json({ ignored: true, reason: "repo not in webhook config" });
return NO_REINDEX;
}
const configuredSourceNames = new Set(sourceNames);
const atlasSources = serverCfg.sources
.filter(isAtlasSourceConfig)
.filter((source) => configuredSourceNames.has(source.name));
if (atlasSources.length === 0) {
recordPullRequestDelivery({
source: "github",
event_type: "pull_request",
repo: repoFullName,
decision: "ignored",
reason: "repo has no atlas sources",
payload_size: payloadSize,
});
res
.status(200)
.json({ ignored: true, reason: "repo has no atlas sources" });
return NO_REINDEX;
}
let extraction;
try {
extraction = extractAtlasPullRequestSeedCandidates(
payload,
atlasSources,
deliveryHeader.ok ? deliveryHeader.value : undefined,
);
} catch (error) {
recordPullRequestDelivery({
source: "github",
event_type: "pull_request",
repo: repoFullName,
decision: "error",
reason:
error instanceof Error
? `malformed Atlas pull_request payload: ${error.message}`
: "malformed Atlas pull_request payload",
payload_size: payloadSize,
});
res.status(400).json({ error: "Malformed Atlas pull_request payload" });
return NO_REINDEX;
}
if (!extraction.isMergedPullRequest) {
recordPullRequestDelivery({
source: "github",
event_type: "pull_request",
repo: repoFullName,
decision: "ignored",
reason: "not a merged pull request",
payload_size: payloadSize,
});
res
.status(200)
.json({ ignored: true, reason: "not a merged pull request" });
return NO_REINDEX;
}
// Default-branch gate. The seed candidate's stored `ref` is the PR's
// BASE branch by choice (atlas.ts: `ref = baseBranch`): because this
// gate admits only baseBranch === defaultBranch deliveries, every
// upserted candidate's ref names the repo's default branch — the branch
// a downstream validator checks out. Note the extraction REQUIRES
// pull_request.base.ref unconditionally (placed BEFORE its merged-PR
// early return), so this comparison can never see an absent base ref —
// a payload without one was already rejected as malformed (400) above.
if (extraction.baseBranch !== extraction.defaultBranch) {
recordPullRequestDelivery({
source: "github",
event_type: "pull_request",
repo: repoFullName,
decision: "ignored",
reason: "not the default branch",
payload_size: payloadSize,
});
res
.status(200)
.json({ ignored: true, reason: "not the default branch" });
return NO_REINDEX;
}
for (const candidate of extraction.candidates) {
await upsertAtlasSeedCandidate(candidate);
}
recordPullRequestDelivery({
source: "github",
event_type: "pull_request",
repo: repoFullName,
decision: "queued",
payload_size: payloadSize,
});
res.status(200).json({
queued: true,
atlas_seed_candidates: extraction.candidates.length,
});
return NO_REINDEX;
}
if (event !== "push") {
recordGithubWebhookDelivery({
source: "github",
event_type: event ?? "unknown",
decision: "ignored",
reason: "not a push event",
payload_size: payloadSize,
});
res.status(200).json({ ignored: true, reason: "not a push event" });
return NO_REINDEX;
}
// -- Parse payload -------------------------------------------------
let payload: PushPayload;
try {
payload = JSON.parse(rawBody.toString("utf-8")) as PushPayload;
} catch {
recordGithubWebhookDelivery({
source: "github",
event_type: "push",
decision: "error",
reason: "malformed JSON",
payload_size: payloadSize,
});
res.status(400).json({ error: "Malformed JSON payload" });
return NO_REINDEX;
}
if (!isPushPayload(payload)) {
recordGithubWebhookDelivery({
source: "github",
event_type: "push",
decision: "error",
reason: "malformed push payload",
payload_size: payloadSize,
});
res.status(400).json({ error: "Malformed push payload" });
return NO_REINDEX;
}
if (!isDefaultBranchPush(payload)) {
recordGithubWebhookDelivery({
source: "github",
event_type: "push",
repo: payload.repository.full_name,
decision: "ignored",
reason: "not the default branch",
payload_size: payloadSize,
});
res.status(200).json({ ignored: true, reason: "not the default branch" });
return NO_REINDEX;
}
const repoFullName = payload.repository.full_name;
const repoUrl = payload.repository.clone_url;
const sha = payload.after;
// -- Config-driven dispatch ----------------------------------------
const webhookCfg = getServerConfig().webhook;
const sourceNames = webhookCfg?.repo_sources?.[repoFullName] ?? [];
if (sourceNames.length === 0) {
console.log(
`[webhook] Push to ${repoFullName} at ${sha.slice(0, 8)} — repo not in webhook config, ignoring`,
);
recordGithubWebhookDelivery({
source: "github",
event_type: "push",
repo: repoFullName,
decision: "ignored",
reason: "repo not in webhook config",
payload_size: payloadSize,
});
res
.status(200)
.json({ ignored: true, reason: "repo not in webhook config" });
return NO_REINDEX;
}
// Check path triggers for each source. If any source's triggers match
// (or it has no triggers, meaning "match all"), queue a reindex.
const affectedSourceNames: string[] = [];
for (const sourceName of sourceNames) {
const triggers = webhookCfg?.path_triggers?.[sourceName] ?? [];
if (touchesPaths(payload, triggers)) {
affectedSourceNames.push(sourceName);
}
}
if (affectedSourceNames.length === 0) {
console.log(
`[webhook] Push to ${repoFullName} at ${sha.slice(0, 8)} — ` +
`no path triggers matched, ignoring`,
);
recordGithubWebhookDelivery({
source: "github",
event_type: "push",
repo: repoFullName,
decision: "ignored",
reason: "no path triggers matched",
payload_size: payloadSize,
});
res
.status(200)
.json({ ignored: true, reason: "no path triggers matched" });
return NO_REINDEX;
}
console.log(
`[webhook] Push to ${repoFullName} ` +
`(${payload.repository.default_branch}) at ${sha.slice(0, 8)} — queuing reindex`,
);
recordGithubWebhookDelivery({
source: "github",
event_type: "push",
repo: repoFullName,
decision: "queued",
payload_size: payloadSize,
});
const shouldReindexWholeRepo =
affectedSourceNames.length === sourceNames.length ||
affectedSourceNames.some(
(sourceName) => !hasPathTriggers(webhookCfg?.path_triggers, sourceName),
);
if (shouldReindexWholeRepo) {
orchestrator.queueIncrementalReindex(repoUrl);
} else {
for (const sourceName of affectedSourceNames) {
orchestrator.queueSourceReindex(sourceName);
}
}
res.status(200).json({ queued: true });
return {
queuedReindex: true,
affectedSourceNames,
};
};
}