//GithubMiddleware returns a Handler that authenticates via GitHub's Authorization for //Webhooks scheme (https://developer.github.com/webhooks/securing/#validating-payloads-from-github) //Writes a http.StatusUnauthorized if authentication fails // func GithubMiddleware(secret string) gin.HandlerFunc { // Set out header value for each response return func(ctx *gin.Context) { requestSignature := ctx.Request.Header.Get("X-Hub-Signature") body, err := ioutil.ReadAll(ctx.Request.Body) if err != nil { ctx.AbortWithStatus(http.StatusUnauthorized) return } ctx.Request.Body = ioutil.NopCloser(bytes.NewReader(body)) mac := hmac.New(sha1.New, []byte(secret)) mac.Reset() mac.Write(body) calculatedSignature := fmt.Sprintf("sha1=%x", mac.Sum(nil)) if !util.SecureCompare(requestSignature, calculatedSignature) { ctx.AbortWithStatus(http.StatusUnauthorized) } else { ctx.Next() } } }
/* TravisCI returns a Handler that authenticates via Travis's Authorization for Webhooks scheme (http://docs.travis-ci.com/user/notifications/#Authorization-for-Webhooks) Writes a http.StatusUnauthorized if authentication fails */ func TravisCIMiddleware(token string) gin.HandlerFunc { return func(ctx *gin.Context) { providedAuth := ctx.Request.Header.Get("Authorization") travisRepoSlug := ctx.Request.Header.Get("Travis-Repo-Slug") calculatedAuth := fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%s%s", travisRepoSlug, token)))) if !util.SecureCompare(providedAuth, calculatedAuth) { ctx.AbortWithStatus(http.StatusUnauthorized) } ctx.Next() } }
func TestSize_SecureCompare_DifferentLength(t *testing.T) { r := util.SecureCompare("abc", "abcdef") if r { t.Fatalf("unexpected result:\n\nexp=%v\n\ngot=%v\n\n", false, r) } }
func TestSize_SecureCompare_Equal(t *testing.T) { r := util.SecureCompare("abc", "abc") if !r { t.Fatalf("unexpected result:\n\nexp=%v\n\ngot=%v\n\n", false, r) } }