github.com/google/go-github/v52@v52.0.0/github/messages.go (about)

     1  // Copyright 2016 The go-github AUTHORS. All rights reserved.
     2  //
     3  // Use of this source code is governed by a BSD-style
     4  // license that can be found in the LICENSE file.
     5  
     6  // This file provides functions for validating payloads from GitHub Webhooks.
     7  // GitHub API docs: https://developer.github.com/webhooks/securing/#validating-payloads-from-github
     8  
     9  package github
    10  
    11  import (
    12  	"crypto/hmac"
    13  	"crypto/sha1"
    14  	"crypto/sha256"
    15  	"crypto/sha512"
    16  	"encoding/hex"
    17  	"encoding/json"
    18  	"errors"
    19  	"fmt"
    20  	"hash"
    21  	"io"
    22  	"mime"
    23  	"net/http"
    24  	"net/url"
    25  	"strings"
    26  )
    27  
    28  const (
    29  	// sha1Prefix is the prefix used by GitHub before the HMAC hexdigest.
    30  	sha1Prefix = "sha1"
    31  	// sha256Prefix and sha512Prefix are provided for future compatibility.
    32  	sha256Prefix = "sha256"
    33  	sha512Prefix = "sha512"
    34  	// SHA1SignatureHeader is the GitHub header key used to pass the HMAC-SHA1 hexdigest.
    35  	SHA1SignatureHeader = "X-Hub-Signature"
    36  	// SHA256SignatureHeader is the GitHub header key used to pass the HMAC-SHA256 hexdigest.
    37  	SHA256SignatureHeader = "X-Hub-Signature-256"
    38  	// EventTypeHeader is the GitHub header key used to pass the event type.
    39  	EventTypeHeader = "X-Github-Event"
    40  	// DeliveryIDHeader is the GitHub header key used to pass the unique ID for the webhook event.
    41  	DeliveryIDHeader = "X-Github-Delivery"
    42  )
    43  
    44  var (
    45  	// eventTypeMapping maps webhooks types to their corresponding go-github struct types.
    46  	eventTypeMapping = map[string]string{
    47  		"branch_protection_rule":         "BranchProtectionRuleEvent",
    48  		"check_run":                      "CheckRunEvent",
    49  		"check_suite":                    "CheckSuiteEvent",
    50  		"code_scanning_alert":            "CodeScanningAlertEvent",
    51  		"commit_comment":                 "CommitCommentEvent",
    52  		"content_reference":              "ContentReferenceEvent",
    53  		"create":                         "CreateEvent",
    54  		"delete":                         "DeleteEvent",
    55  		"deploy_key":                     "DeployKeyEvent",
    56  		"deployment":                     "DeploymentEvent",
    57  		"deployment_status":              "DeploymentStatusEvent",
    58  		"discussion":                     "DiscussionEvent",
    59  		"discussion_comment":             "DiscussionCommentEvent",
    60  		"fork":                           "ForkEvent",
    61  		"github_app_authorization":       "GitHubAppAuthorizationEvent",
    62  		"gollum":                         "GollumEvent",
    63  		"installation":                   "InstallationEvent",
    64  		"installation_repositories":      "InstallationRepositoriesEvent",
    65  		"issue_comment":                  "IssueCommentEvent",
    66  		"issues":                         "IssuesEvent",
    67  		"label":                          "LabelEvent",
    68  		"marketplace_purchase":           "MarketplacePurchaseEvent",
    69  		"member":                         "MemberEvent",
    70  		"membership":                     "MembershipEvent",
    71  		"merge_group":                    "MergeGroupEvent",
    72  		"meta":                           "MetaEvent",
    73  		"milestone":                      "MilestoneEvent",
    74  		"organization":                   "OrganizationEvent",
    75  		"org_block":                      "OrgBlockEvent",
    76  		"package":                        "PackageEvent",
    77  		"page_build":                     "PageBuildEvent",
    78  		"ping":                           "PingEvent",
    79  		"project":                        "ProjectEvent",
    80  		"project_card":                   "ProjectCardEvent",
    81  		"project_column":                 "ProjectColumnEvent",
    82  		"public":                         "PublicEvent",
    83  		"pull_request":                   "PullRequestEvent",
    84  		"pull_request_review":            "PullRequestReviewEvent",
    85  		"pull_request_review_comment":    "PullRequestReviewCommentEvent",
    86  		"pull_request_review_thread":     "PullRequestReviewThreadEvent",
    87  		"pull_request_target":            "PullRequestTargetEvent",
    88  		"push":                           "PushEvent",
    89  		"repository":                     "RepositoryEvent",
    90  		"repository_dispatch":            "RepositoryDispatchEvent",
    91  		"repository_import":              "RepositoryImportEvent",
    92  		"repository_vulnerability_alert": "RepositoryVulnerabilityAlertEvent",
    93  		"release":                        "ReleaseEvent",
    94  		"secret_scanning_alert":          "SecretScanningAlertEvent",
    95  		"star":                           "StarEvent",
    96  		"status":                         "StatusEvent",
    97  		"team":                           "TeamEvent",
    98  		"team_add":                       "TeamAddEvent",
    99  		"user":                           "UserEvent",
   100  		"watch":                          "WatchEvent",
   101  		"workflow_dispatch":              "WorkflowDispatchEvent",
   102  		"workflow_job":                   "WorkflowJobEvent",
   103  		"workflow_run":                   "WorkflowRunEvent",
   104  	}
   105  )
   106  
   107  // genMAC generates the HMAC signature for a message provided the secret key
   108  // and hashFunc.
   109  func genMAC(message, key []byte, hashFunc func() hash.Hash) []byte {
   110  	mac := hmac.New(hashFunc, key)
   111  	mac.Write(message)
   112  	return mac.Sum(nil)
   113  }
   114  
   115  // checkMAC reports whether messageMAC is a valid HMAC tag for message.
   116  func checkMAC(message, messageMAC, key []byte, hashFunc func() hash.Hash) bool {
   117  	expectedMAC := genMAC(message, key, hashFunc)
   118  	return hmac.Equal(messageMAC, expectedMAC)
   119  }
   120  
   121  // messageMAC returns the hex-decoded HMAC tag from the signature and its
   122  // corresponding hash function.
   123  func messageMAC(signature string) ([]byte, func() hash.Hash, error) {
   124  	if signature == "" {
   125  		return nil, nil, errors.New("missing signature")
   126  	}
   127  	sigParts := strings.SplitN(signature, "=", 2)
   128  	if len(sigParts) != 2 {
   129  		return nil, nil, fmt.Errorf("error parsing signature %q", signature)
   130  	}
   131  
   132  	var hashFunc func() hash.Hash
   133  	switch sigParts[0] {
   134  	case sha1Prefix:
   135  		hashFunc = sha1.New
   136  	case sha256Prefix:
   137  		hashFunc = sha256.New
   138  	case sha512Prefix:
   139  		hashFunc = sha512.New
   140  	default:
   141  		return nil, nil, fmt.Errorf("unknown hash type prefix: %q", sigParts[0])
   142  	}
   143  
   144  	buf, err := hex.DecodeString(sigParts[1])
   145  	if err != nil {
   146  		return nil, nil, fmt.Errorf("error decoding signature %q: %v", signature, err)
   147  	}
   148  	return buf, hashFunc, nil
   149  }
   150  
   151  // ValidatePayloadFromBody validates an incoming GitHub Webhook event request body
   152  // and returns the (JSON) payload.
   153  // The Content-Type header of the payload can be "application/json" or "application/x-www-form-urlencoded".
   154  // If the Content-Type is neither then an error is returned.
   155  // secretToken is the GitHub Webhook secret token.
   156  // If your webhook does not contain a secret token, you can pass an empty secretToken.
   157  // Webhooks without a secret token are not secure and should be avoided.
   158  //
   159  // Example usage:
   160  //
   161  //	func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   162  //	  // read signature from request
   163  //	  signature := ""
   164  //	  payload, err := github.ValidatePayloadFromBody(r.Header.Get("Content-Type"), r.Body, signature, s.webhookSecretKey)
   165  //	  if err != nil { ... }
   166  //	  // Process payload...
   167  //	}
   168  func ValidatePayloadFromBody(contentType string, readable io.Reader, signature string, secretToken []byte) (payload []byte, err error) {
   169  	var body []byte // Raw body that GitHub uses to calculate the signature.
   170  
   171  	switch contentType {
   172  	case "application/json":
   173  		var err error
   174  		if body, err = io.ReadAll(readable); err != nil {
   175  			return nil, err
   176  		}
   177  
   178  		// If the content type is application/json,
   179  		// the JSON payload is just the original body.
   180  		payload = body
   181  
   182  	case "application/x-www-form-urlencoded":
   183  		// payloadFormParam is the name of the form parameter that the JSON payload
   184  		// will be in if a webhook has its content type set to application/x-www-form-urlencoded.
   185  		const payloadFormParam = "payload"
   186  
   187  		var err error
   188  		if body, err = io.ReadAll(readable); err != nil {
   189  			return nil, err
   190  		}
   191  
   192  		// If the content type is application/x-www-form-urlencoded,
   193  		// the JSON payload will be under the "payload" form param.
   194  		form, err := url.ParseQuery(string(body))
   195  		if err != nil {
   196  			return nil, err
   197  		}
   198  		payload = []byte(form.Get(payloadFormParam))
   199  
   200  	default:
   201  		return nil, fmt.Errorf("webhook request has unsupported Content-Type %q", contentType)
   202  	}
   203  
   204  	// Validate the signature if present or if one is expected (secretToken is non-empty).
   205  	if len(secretToken) > 0 || len(signature) > 0 {
   206  		if err := ValidateSignature(signature, body, secretToken); err != nil {
   207  			return nil, err
   208  		}
   209  	}
   210  
   211  	return payload, nil
   212  }
   213  
   214  // ValidatePayload validates an incoming GitHub Webhook event request
   215  // and returns the (JSON) payload.
   216  // The Content-Type header of the payload can be "application/json" or "application/x-www-form-urlencoded".
   217  // If the Content-Type is neither then an error is returned.
   218  // secretToken is the GitHub Webhook secret token.
   219  // If your webhook does not contain a secret token, you can pass nil or an empty slice.
   220  // This is intended for local development purposes only and all webhooks should ideally set up a secret token.
   221  //
   222  // Example usage:
   223  //
   224  //	func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   225  //	  payload, err := github.ValidatePayload(r, s.webhookSecretKey)
   226  //	  if err != nil { ... }
   227  //	  // Process payload...
   228  //	}
   229  func ValidatePayload(r *http.Request, secretToken []byte) (payload []byte, err error) {
   230  	signature := r.Header.Get(SHA256SignatureHeader)
   231  	if signature == "" {
   232  		signature = r.Header.Get(SHA1SignatureHeader)
   233  	}
   234  
   235  	contentType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
   236  	if err != nil {
   237  		return nil, err
   238  	}
   239  
   240  	return ValidatePayloadFromBody(contentType, r.Body, signature, secretToken)
   241  }
   242  
   243  // ValidateSignature validates the signature for the given payload.
   244  // signature is the GitHub hash signature delivered in the X-Hub-Signature header.
   245  // payload is the JSON payload sent by GitHub Webhooks.
   246  // secretToken is the GitHub Webhook secret token.
   247  //
   248  // GitHub API docs: https://developer.github.com/webhooks/securing/#validating-payloads-from-github
   249  func ValidateSignature(signature string, payload, secretToken []byte) error {
   250  	messageMAC, hashFunc, err := messageMAC(signature)
   251  	if err != nil {
   252  		return err
   253  	}
   254  	if !checkMAC(payload, messageMAC, secretToken, hashFunc) {
   255  		return errors.New("payload signature check failed")
   256  	}
   257  	return nil
   258  }
   259  
   260  // WebHookType returns the event type of webhook request r.
   261  //
   262  // GitHub API docs: https://docs.github.com/en/developers/webhooks-and-events/events/github-event-types
   263  func WebHookType(r *http.Request) string {
   264  	return r.Header.Get(EventTypeHeader)
   265  }
   266  
   267  // DeliveryID returns the unique delivery ID of webhook request r.
   268  //
   269  // GitHub API docs: https://docs.github.com/en/developers/webhooks-and-events/events/github-event-types
   270  func DeliveryID(r *http.Request) string {
   271  	return r.Header.Get(DeliveryIDHeader)
   272  }
   273  
   274  // ParseWebHook parses the event payload. For recognized event types, a
   275  // value of the corresponding struct type will be returned (as returned
   276  // by Event.ParsePayload()). An error will be returned for unrecognized event
   277  // types.
   278  //
   279  // Example usage:
   280  //
   281  //	func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   282  //	  payload, err := github.ValidatePayload(r, s.webhookSecretKey)
   283  //	  if err != nil { ... }
   284  //	  event, err := github.ParseWebHook(github.WebHookType(r), payload)
   285  //	  if err != nil { ... }
   286  //	  switch event := event.(type) {
   287  //	  case *github.CommitCommentEvent:
   288  //	      processCommitCommentEvent(event)
   289  //	  case *github.CreateEvent:
   290  //	      processCreateEvent(event)
   291  //	  ...
   292  //	  }
   293  //	}
   294  func ParseWebHook(messageType string, payload []byte) (interface{}, error) {
   295  	eventType, ok := eventTypeMapping[messageType]
   296  	if !ok {
   297  		return nil, fmt.Errorf("unknown X-Github-Event in message: %v", messageType)
   298  	}
   299  
   300  	event := Event{
   301  		Type:       &eventType,
   302  		RawPayload: (*json.RawMessage)(&payload),
   303  	}
   304  	return event.ParsePayload()
   305  }