Skip to content

Commit

Permalink
make it generic , to work on different git providers (#2)
Browse files Browse the repository at this point in the history
parse signature sha256 for github


fix gitlab too
  • Loading branch information
Kos-M authored Mar 6, 2024
1 parent 5552531 commit 2b1201e
Showing 1 changed file with 27 additions and 15 deletions.
42 changes: 27 additions & 15 deletions routes/signatureVerify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,45 @@ import { Request, Response, NextFunction } from 'express';
import crypto from 'crypto';

const secret: string | undefined = process.env.SECRET;
const sigHeaderName: string = 'x-gitea-signature';
const sigHeaderNames: string[] = ['x-gitea-signature', 'X-Gitlab-Token', 'X-Hub-Signature-256'];
const sigHashAlg: string = 'sha256';


function VerifySignature(req: Request, res: Response, next: NextFunction): void {
if (!req.body || !req.rawBody) {
res.setHeader('Content-Type', 'application/json');
res.status(400).json({ error: 'Request body empty' });
return;
}
const headerSignature: Buffer = Buffer.from(req.get(sigHeaderName) || '', 'utf8');
if (!secret) {
res.status(500).json({ error: 'Internal Server Error', reason: 'Secret is not defined' });
return;
}

const hmac: crypto.Hmac = crypto.createHmac(sigHashAlg, secret);
const digest: Buffer = Buffer.from(`${hmac.update(req.rawBody).digest('hex')}`, 'utf8');

if (headerSignature.length !== digest.length || !crypto.timingSafeEqual(digest, headerSignature)) {
res.status(400).json({
error: 'Data validation failed',
reason: `Request body digest (${digest}) did not match ${sigHeaderName} (${headerSignature})`
});
return;
}
next();
const rawBody: string = req.rawBody || '';
let matchProvider: boolean =false;
sigHeaderNames.forEach((headerKey) => {
let headerSignature: Buffer = Buffer.from(req.get(headerKey) || '', 'utf8');
if (headerKey === 'X-Hub-Signature-256'){
const githubSignature = req.get(headerKey)?.replace('sha256=', '');
headerSignature = Buffer.from(githubSignature || '', 'utf8');
}else if ( headerKey === 'X-Gitlab-Token' && secret != null && secret !== '' && secret !== undefined){ // plain secret format for Gitlab
if( secret === req.get(headerKey) ){
matchProvider = true;
next();
}
}
const hmac: crypto.Hmac = crypto.createHmac(sigHashAlg, secret);
const digest: Buffer = Buffer.from(`${hmac.update(rawBody).digest('hex')}`, 'utf8');

if (headerSignature.length == digest.length && crypto.timingSafeEqual(digest, headerSignature)) {
matchProvider = true
next();
}
});
if ( matchProvider) return;
res.status(400).json({
error: 'Data validation failed',
reason: `Secret validation failed, supported signature headers:${sigHeaderNames}`,
});
}

export { VerifySignature };

0 comments on commit 2b1201e

Please sign in to comment.