Skip to content

Commit

Permalink
fix: Enforce webhook secret in BitbucketServer event source (#1917)
Browse files Browse the repository at this point in the history
* fix: Webhook secret to be optional field in bitbucketserver es

Signed-off-by: Daniel Soifer <[email protected]>
  • Loading branch information
daniel-codefresh authored and whynowy committed May 4, 2022
1 parent 9682b13 commit f3cf34e
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions eventsources/sources/bitbucketserver/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ package bitbucketserver

import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io/ioutil"
"math/rand"
Expand Down Expand Up @@ -80,9 +83,9 @@ func (router *Router) HandleRoute(writer http.ResponseWriter, request *http.Requ
route.Metrics.EventProcessingDuration(route.EventSourceName, route.EventName, float64(time.Since(start)/time.Millisecond))
}(time.Now())

body, err := ioutil.ReadAll(request.Body)
body, err := router.parseAndValidateBitbucketServerRequest(request)
if err != nil {
logger.Errorw("failed to parse request body", zap.Error(err))
logger.Errorw("failed to parse/validate request", zap.Error(err))
common.SendErrorResponse(writer, err.Error())
route.Metrics.EventProcessingFailed(route.EventSourceName, route.EventName)
return
Expand Down Expand Up @@ -387,3 +390,27 @@ func (router *Router) createRequestBodyFromWebhook(hook bitbucketv1.Webhook) ([]

return requestBody, nil
}

func (router *Router) parseAndValidateBitbucketServerRequest(request *http.Request) ([]byte, error) {
body, err := ioutil.ReadAll(request.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to parse request body")
}

if len(router.hookSecret) != 0 {
signature := request.Header.Get("X-Hub-Signature")
if len(signature) == 0 {
return nil, errors.New("missing signature header")
}

mac := hmac.New(sha256.New, []byte(router.hookSecret))
_, _ = mac.Write(body)
expectedMAC := hex.EncodeToString(mac.Sum(nil))

if !hmac.Equal([]byte(signature[7:]), []byte(expectedMAC)) {
return nil, errors.New("hmac verification failed")
}
}

return body, nil
}

0 comments on commit f3cf34e

Please sign in to comment.