Skip to content

Instantly share code, notes, and snippets.

@retgits
Created July 12, 2018 21:14
Show Gist options
  • Save retgits/66c590e26aa59730268f25a5a2077e5a to your computer and use it in GitHub Desktop.
Save retgits/66c590e26aa59730268f25a5a2077e5a to your computer and use it in GitHub Desktop.
Function to check whether a received webhook event actually comes from GitHub
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"fmt"
"strings"
"github.com/aws/aws-lambda-go/events"
)
func handler(request events.APIGatewayProxyRequest) {
// This is the secret you set when creating a Webhook in GitHub
// see https://developer.github.com/webhooks/creating/#secret for more details
secretKey := []byte("MySuperSecretKey")
// When you set a secret you'll receive the X-Hub-Signature header in the webhook POST request.
// This field is a hash signature of the payload
xhubSignature := request.Headers["X-Hub-Signature"]
// Create a SHA1 hash of the message
hash := hmac.New(sha1.New, secretKey)
message := request.Body
hash.Write([]byte(message))
// The hexit string follows a specific format of "sha1=..."
hexits := fmt.Sprintf("sha1=%s", hex.EncodeToString(hash.Sum(nil)))
// When the hexits match the xhubSignature, the event originates from GitHub,
// otherwise the event comes from somewhere else
if strings.Compare(hexits, xhubSignature) != 0 {
return
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment