/
index.ts
121 lines (98 loc) · 3.58 KB
/
index.ts
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
/* eslint-disable import/no-extraneous-dependencies */
import * as crypto from 'crypto';
import * as AWS from 'aws-sdk';
const sf = new AWS.StepFunctions();
const sm = new AWS.SecretsManager();
// TODO use @octokit/webhooks?
function verifyBody(event: any, secret: any) {
const sig = Buffer.from(event.headers['x-hub-signature-256'] || '', 'utf8');
let body = event.body;
if (event.isBase64Encoded) {
body = Buffer.from(body, 'base64');
} else {
body = Buffer.from(body || '', 'utf8');
}
const hmac = crypto.createHmac('sha256', secret);
hmac.update(body);
const expectedSig = Buffer.from(`sha256=${hmac.digest('hex')}`, 'utf8');
console.log('Calculated signature: ', expectedSig.toString());
if (sig.length !== expectedSig.length || !crypto.timingSafeEqual(sig, expectedSig)) {
throw new Error(`Signature mismatch. Expected ${expectedSig.toString()} but got ${sig.toString()}`);
}
return body;
}
exports.handler = async function (event: any) {
if (!process.env.WEBHOOK_SECRET_ARN || !process.env.STEP_FUNCTION_ARN) {
throw new Error('Missing environment variables');
}
const secret = await sm.getSecretValue({
SecretId: process.env.WEBHOOK_SECRET_ARN,
}).promise();
if (!secret.SecretString) {
throw new Error(`No SecretString in ${process.env.WEBHOOK_SECRET_ARN}`);
}
const webhookSecret = JSON.parse(secret.SecretString).webhookSecret;
let body;
try {
body = verifyBody(event, webhookSecret);
} catch (e) {
console.error(e);
return {
statusCode: 403,
body: 'Bad signature',
};
}
if (event.headers['content-type'] !== 'application/json') {
console.error(`This webhook only accepts JSON payloads, got ${event.headers['content-type']}`);
return {
statusCode: 400,
body: 'Expecting JSON payload',
};
}
if (event.headers['x-github-event'] === 'ping') {
return {
statusCode: 200,
body: 'Pong',
};
}
// if (event.headers['x-github-event'] !== 'workflow_job' && event.headers['x-github-event'] !== 'workflow_run') {
// console.error(`This webhook only accepts workflow_job and workflow_run, got ${event.headers['x-github-event']}`);
if (event.headers['x-github-event'] !== 'workflow_job') {
console.error(`This webhook only accepts workflow_job, got ${event.headers['x-github-event']}`);
return {
statusCode: 400,
body: 'Expecting workflow_job',
};
}
const payload = JSON.parse(body);
if (payload.action !== 'queued') {
console.log(`Ignoring action "${payload.action}", expecting "queued"`);
return {
statusCode: 200,
body: 'OK. No runner started.',
};
}
// it's easier to deal with maps in step functions
let labels: any = {};
payload.workflow_job.labels.forEach((l: string) => labels[l] = true);
// set execution name which is also used as runner name which are limited to 64 characters
let executionName = `${payload.repository.full_name.replace('/', '-')}-${event.headers['x-github-delivery']}`.slice(0, 64);
// start execution
const execution = await sf.startExecution({
stateMachineArn: process.env.STEP_FUNCTION_ARN,
input: JSON.stringify({
owner: payload.repository.owner.login,
repo: payload.repository.name,
runId: payload.workflow_job.run_id,
installationId: payload.installation?.id,
labels: labels,
}),
// name is not random so multiple execution of this webhook won't cause multiple builders to start
name: executionName,
}).promise();
console.log(`Started ${execution.executionArn}`);
return {
statusCode: 202,
body: executionName,
};
};