I'm coding a Webhook for GitHub, and implemented secure verification in KOA.js
as:
function sign(tok, blob) {
var hmac;
hmac = crypto
.createHmac('sha1', tok)
.update(blob)
.digest('hex');
return 'sha1=' + hmac;
}
...
key = this.request.headers['x-hub-signature'];
blob = JSON.stringify(this.request.body);
if (!key || !blob) {
this.status = 400;
this.body = 'Bad Request';
}
lock = sign(settings.api_secret, blob);
if (lock !== key) {
console.log(symbols.warning, 'Unauthorized');
this.status = 403;
this.body = 'Unauthorized';
return;
}
...
for pull_requests and create events this works ok, even pushing new branches works, but for push commits events the x-hub-signature
and the computed hash from the payload don't match, so it always get 403 unauthorized.
Update
I've noticed that for this kind of push payloads the commits and head_commit are added to the payload. I've tried removing the commits and the head_commit from the body but it didn't work.
Update
For more information please review these example payloads. I've also included url for the test repo and token info: https://gist.github.com/marcoslhc/ec581f1a5ccdd80f8b33
The default encoding of Crypto hash.update() is binary as detailed in the answer to Node JS crypto, cannot create hmac on chars with accents. This causes a problem in your push-event payload, which contains the character U+00E1
LATIN SMALL LETTER A WITH ACUTE in Hernández
four times, and GitHub services is hashing the payload as utf-8
encoded. Note that your Gist shows these incorrectly-encoded in ISO-8859-1, so also make sure that you are handling the incoming request character-encoding properly (but this should happen by-default).
To fix this you need to either use a Buffer
:
hmac = crypto.createHmac('sha1', tok).update(new Buffer(blob, 'utf-8')).digest('hex');
... or pass the encoding directly to update
:
hmac = crypto.createHmac('sha1', tok).update(blob, 'utf-8').digest('hex');
The correct hash of 7f9e6014b7bddf5533494eff6a2c71c4ec7c042d
will then be calculated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With