我正在对Webhook for GitHub进行编码,并在KOA.js
中实施了安全验证:
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;
}
...
对于pull_requests和create事件,这项工作正常,即使推送新分支也可以,但对于推送提交事件,x-hub-signature
和来自有效负载的计算哈希不匹配,因此它总是获得403未授权。
更新
我注意到,对于这种推送有效载荷,提交和head_commit被添加到有效载荷中。我已经尝试从机体中移除提交和head_commit,但它没有工作。
更新
有关详细信息,请查看这些示例有效负载。我还包含了测试仓库和令牌信息的网址:https://gist.github.com/marcoslhc/ec581f1a5ccdd80f8b33
答案 0 :(得分:11)
default encoding of Crypto hash.update() is binary的答案中详述的Node JS crypto, cannot create hmac on chars with accents。这会导致push事件有效负载出现问题,该问题在U+00E1
中包含Hernández
LATIN SMALL LETTER A WITH ACUTE 四次,而GitHub服务将有效负载散列为utf-8
编码。请注意,您的Gist在ISO-8859-1中显示了这些错误编码,因此还要确保正确处理传入的请求字符编码(但这应该默认情况下发生)。
要解决此问题,您需要使用Buffer
:
hmac = crypto.createHmac('sha1', tok).update(new Buffer(blob, 'utf-8')).digest('hex');
...或直接将编码传递给update
:
hmac = crypto.createHmac('sha1', tok).update(blob, 'utf-8').digest('hex');
然后将计算7f9e6014b7bddf5533494eff6a2c71c4ec7c042d
的正确哈希值。