Sandra Schlichting
Sandra Schlichting

Reputation: 26026

Why does my Github secret fail (change on each event)?

I am trying to verify the Github webhook secret, but each time I trigger an event in Github, the value of req.headers['x-hub-signature']) changes, which doesn't make sense.

NodeJs: sha1=b57ad18e45f71ac069d15618f6ca547ed75bb2e9
Github: sha1=0b6ff08d557b240dbadedb2a0c1054ce69f2d93e    <----

NodeJs: sha1=b57ad18e45f71ac069d15618f6ca547ed75bb2e9
Github: sha1=15e3d5edae00951abb180e9eaea9a6278d8f8d0b    <----

Notice the secret that comes from Githit hub is different each time!

I have found others that verify the secret, but I don't see how their code is different from mine.

Question

Can anyone figure out why I get different secrets from Github on each event? Or am I doing something wrong?

const express = require("express");
const bodyParser = require("body-parser");
const crypto = require('crypto');
const secret = "x";

const app = express();
const PORT = 8080;

app.use(bodyParser.json());

app.post("/", (req, res) => {

let sig = "sha1=" + crypto.createHmac('sha1', secret).digest('hex');

  console.log('NodeJs: ' + sig);
  console.log('Github: ' + req.headers['x-hub-signature']);
    
  res.status(200).end();
});

app.listen(PORT, () => console.log(`Github wekhook listening on port ${PORT}`));

Upvotes: 1

Views: 273

Answers (1)

d2xdt2
d2xdt2

Reputation: 371

req.headers['x-hub-signature']) is not a hash of the secret, but req.body signed with the secret. That is why it is different on each event.

const express = require("express");
const bodyParser = require("body-parser");
const crypto = require('crypto');
const secret = "x";

const app = express();
const PORT = 8080;

app.use(bodyParser.json());

function isSigOk(request, secret) {
    // calculate the signature
    const expectedSignature = "sha1=" +
        crypto.createHmac("sha1", secret)
            .update(JSON.stringify(request.body))
            .digest("hex");

    // compare the signature against the one in the request
    const signature = request.headers["x-hub-signature"];
    if (signature !== expectedSignature) {
        throw new Error("Invalid signature.");
    };
};

app.post("/", (req, res) => {
  // will throw an error if not ok
  isSigOk(req, secret);

  // Do stuff here

  res.status(200).end();
});

app.listen(PORT, () => console.log(`Github wekhook listening on port ${PORT}`));

Upvotes: 0

Related Questions