You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

287 lines
9.1 KiB

  1. package webhook
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha1"
  5. "encoding/hex"
  6. "encoding/json"
  7. "fmt"
  8. "html"
  9. "io/ioutil"
  10. "net/http"
  11. "strings"
  12. "github.com/google/go-github/github"
  13. "github.com/matrix-org/go-neb/services/utils"
  14. "github.com/matrix-org/util"
  15. log "github.com/sirupsen/logrus"
  16. mevt "maunium.net/go/mautrix/event"
  17. )
  18. // OnReceiveRequest processes incoming github webhook requests and returns a
  19. // matrix message to send, along with parsed repo information.
  20. // The secretToken, if supplied, will be used to verify the request is from
  21. // Github. If it isn't, an error is returned.
  22. func OnReceiveRequest(r *http.Request, secretToken string) (string, *github.Repository, *mevt.MessageEventContent, *util.JSONResponse) {
  23. // Verify the HMAC signature if NEB was configured with a secret token
  24. eventType := r.Header.Get("X-GitHub-Event")
  25. signatureSHA1 := r.Header.Get("X-Hub-Signature")
  26. content, err := ioutil.ReadAll(r.Body)
  27. if err != nil {
  28. log.WithError(err).Print("Failed to read Github webhook body")
  29. resErr := util.MessageResponse(400, "Failed to parse body")
  30. return "", nil, nil, &resErr
  31. }
  32. // Verify request if a secret token has been supplied.
  33. if secretToken != "" {
  34. sigHex := strings.Split(signatureSHA1, "=")[1]
  35. var sigBytes []byte
  36. sigBytes, err = hex.DecodeString(sigHex)
  37. if err != nil {
  38. log.WithError(err).WithField("X-Hub-Signature", sigHex).Print(
  39. "Failed to decode signature as hex.")
  40. resErr := util.MessageResponse(400, "Failed to decode signature")
  41. return "", nil, nil, &resErr
  42. }
  43. if !checkMAC([]byte(content), sigBytes, []byte(secretToken)) {
  44. log.WithFields(log.Fields{
  45. "X-Hub-Signature": signatureSHA1,
  46. }).Print("Received Github event which failed MAC check.")
  47. resErr := util.MessageResponse(403, "Bad signature")
  48. return "", nil, nil, &resErr
  49. }
  50. }
  51. log.WithFields(log.Fields{
  52. "event_type": eventType,
  53. "signature": signatureSHA1,
  54. }).Print("Received Github event")
  55. if eventType == "ping" {
  56. // Github will send a "ping" event when the webhook is first created. We need
  57. // to return a 200 in order for the webhook to be marked as "up" (this doesn't
  58. // affect delivery, just the tick/cross status flag).
  59. res := util.MessageResponse(200, "pong")
  60. return "", nil, nil, &res
  61. }
  62. htmlStr, repo, refinedType, err := parseGithubEvent(eventType, content)
  63. if err != nil {
  64. log.WithError(err).Print("Failed to parse github event")
  65. resErr := util.MessageResponse(500, "Failed to parse github event")
  66. return "", nil, nil, &resErr
  67. }
  68. msg := utils.StrippedHTMLMessage(mevt.MsgNotice, htmlStr)
  69. return refinedType, repo, &msg, nil
  70. }
  71. // checkMAC reports whether messageMAC is a valid HMAC tag for message.
  72. func checkMAC(message, messageMAC, key []byte) bool {
  73. mac := hmac.New(sha1.New, key)
  74. mac.Write(message)
  75. expectedMAC := mac.Sum(nil)
  76. return hmac.Equal(messageMAC, expectedMAC)
  77. }
  78. // parseGithubEvent parses a github event type and JSON data and returns an explanatory
  79. // HTML string, the github repository and the refined event type, or an error.
  80. func parseGithubEvent(eventType string, data []byte) (string, *github.Repository, string, error) {
  81. if eventType == "pull_request" {
  82. var ev github.PullRequestEvent
  83. if err := json.Unmarshal(data, &ev); err != nil {
  84. return "", nil, eventType, err
  85. }
  86. refinedEventType := refineEventType(eventType, ev.Action)
  87. return pullRequestHTMLMessage(ev), ev.Repo, refinedEventType, nil
  88. } else if eventType == "issues" {
  89. var ev github.IssuesEvent
  90. if err := json.Unmarshal(data, &ev); err != nil {
  91. return "", nil, eventType, err
  92. }
  93. refinedEventType := refineEventType(eventType, ev.Action)
  94. return issueHTMLMessage(ev), ev.Repo, refinedEventType, nil
  95. } else if eventType == "push" {
  96. var ev github.PushEvent
  97. if err := json.Unmarshal(data, &ev); err != nil {
  98. return "", nil, eventType, err
  99. }
  100. // The 'push' event repository format is subtly different from normal, so munge the bits we need.
  101. fullName := *ev.Repo.Owner.Name + "/" + *ev.Repo.Name
  102. repo := github.Repository{
  103. Owner: &github.User{
  104. Login: ev.Repo.Owner.Name,
  105. },
  106. Name: ev.Repo.Name,
  107. FullName: &fullName,
  108. }
  109. return pushHTMLMessage(ev), &repo, eventType, nil
  110. } else if eventType == "issue_comment" {
  111. var ev github.IssueCommentEvent
  112. if err := json.Unmarshal(data, &ev); err != nil {
  113. return "", nil, eventType, err
  114. }
  115. return issueCommentHTMLMessage(ev), ev.Repo, eventType, nil
  116. } else if eventType == "pull_request_review_comment" {
  117. var ev github.PullRequestReviewCommentEvent
  118. if err := json.Unmarshal(data, &ev); err != nil {
  119. return "", nil, eventType, err
  120. }
  121. return prReviewCommentHTMLMessage(ev), ev.Repo, eventType, nil
  122. }
  123. return "", nil, eventType, fmt.Errorf("Unrecognized event type")
  124. }
  125. func refineEventType(eventType string, action *string) string {
  126. if action == nil {
  127. return eventType
  128. }
  129. a := *action
  130. if a == "assigned" || a == "unassigned" {
  131. return "assignments"
  132. } else if a == "milestoned" || a == "demilestoned" {
  133. return "milestones"
  134. } else if a == "labeled" || a == "unlabeled" {
  135. return "labels"
  136. }
  137. return eventType
  138. }
  139. func pullRequestHTMLMessage(p github.PullRequestEvent) string {
  140. var actionTarget string
  141. if p.PullRequest.Assignee != nil && p.PullRequest.Assignee.Login != nil {
  142. actionTarget = fmt.Sprintf(" to %s", *p.PullRequest.Assignee.Login)
  143. }
  144. return fmt.Sprintf(
  145. "[<u>%s</u>] %s %s <b>pull request #%d</b>: %s [%s]%s - %s",
  146. html.EscapeString(*p.Repo.FullName),
  147. html.EscapeString(*p.Sender.Login),
  148. html.EscapeString(*p.Action),
  149. *p.Number,
  150. html.EscapeString(*p.PullRequest.Title),
  151. html.EscapeString(*p.PullRequest.State),
  152. html.EscapeString(actionTarget),
  153. html.EscapeString(*p.PullRequest.HTMLURL),
  154. )
  155. }
  156. func issueHTMLMessage(p github.IssuesEvent) string {
  157. var actionTarget string
  158. if p.Issue.Assignee != nil && p.Issue.Assignee.Login != nil {
  159. actionTarget = fmt.Sprintf(" to %s", *p.Issue.Assignee.Login)
  160. }
  161. action := html.EscapeString(*p.Action)
  162. if p.Label != nil && (*p.Action == "labeled" || *p.Action == "unlabeled") {
  163. action = *p.Action + " [" + html.EscapeString(*p.Label.Name) + "] to"
  164. }
  165. return fmt.Sprintf(
  166. "[<u>%s</u>] %s %s <b>issue #%d</b>: %s [%s]%s - %s",
  167. html.EscapeString(*p.Repo.FullName),
  168. html.EscapeString(*p.Sender.Login),
  169. action,
  170. *p.Issue.Number,
  171. html.EscapeString(*p.Issue.Title),
  172. html.EscapeString(*p.Issue.State),
  173. html.EscapeString(actionTarget),
  174. html.EscapeString(*p.Issue.HTMLURL),
  175. )
  176. }
  177. func issueCommentHTMLMessage(p github.IssueCommentEvent) string {
  178. var kind string
  179. if p.Issue.PullRequestLinks == nil {
  180. kind = "issue"
  181. } else {
  182. kind = "pull request"
  183. }
  184. return fmt.Sprintf(
  185. "[<u>%s</u>] %s commented on %s's <b>%s #%d</b>: %s - %s",
  186. html.EscapeString(*p.Repo.FullName),
  187. html.EscapeString(*p.Comment.User.Login),
  188. html.EscapeString(*p.Issue.User.Login),
  189. kind,
  190. *p.Issue.Number,
  191. html.EscapeString(*p.Issue.Title),
  192. html.EscapeString(*p.Issue.HTMLURL),
  193. )
  194. }
  195. func prReviewCommentHTMLMessage(p github.PullRequestReviewCommentEvent) string {
  196. assignee := "None"
  197. if p.PullRequest.Assignee != nil {
  198. assignee = html.EscapeString(*p.PullRequest.Assignee.Login)
  199. }
  200. return fmt.Sprintf(
  201. "[<u>%s</u>] %s made a line comment on %s's <b>pull request #%d</b> (assignee: %s): %s - %s",
  202. html.EscapeString(*p.Repo.FullName),
  203. html.EscapeString(*p.Sender.Login),
  204. html.EscapeString(*p.PullRequest.User.Login),
  205. *p.PullRequest.Number,
  206. assignee,
  207. html.EscapeString(*p.PullRequest.Title),
  208. html.EscapeString(*p.Comment.HTMLURL),
  209. )
  210. }
  211. func pushHTMLMessage(p github.PushEvent) string {
  212. // /refs/heads/alice/branch-name => alice/branch-name
  213. branch := strings.Replace(*p.Ref, "refs/heads/", "", -1)
  214. // this branch was deleted, no HeadCommit object and deleted=true
  215. if p.HeadCommit == nil && p.Deleted != nil && *p.Deleted {
  216. return fmt.Sprintf(
  217. `[<u>%s</u>] %s <b><font color="red">deleted</font> %s</b>`,
  218. html.EscapeString(*p.Repo.FullName),
  219. html.EscapeString(*p.Pusher.Name),
  220. html.EscapeString(branch),
  221. )
  222. }
  223. if p.Commits != nil && len(p.Commits) > 1 {
  224. // multi-commit message
  225. // [<repo>] <username> pushed <num> commits to <branch>: <git.io link>
  226. // <up to 3 commits>
  227. var cList []string
  228. for _, c := range p.Commits {
  229. cList = append(cList, fmt.Sprintf(
  230. `%s: %s`,
  231. html.EscapeString(nameForAuthor(c.Author)),
  232. html.EscapeString(*c.Message),
  233. ))
  234. }
  235. return fmt.Sprintf(
  236. `[<u>%s</u>] %s pushed %d commits to <b>%s</b>: %s<br>%s`,
  237. html.EscapeString(*p.Repo.FullName),
  238. html.EscapeString(nameForAuthor(p.HeadCommit.Committer)),
  239. len(p.Commits),
  240. html.EscapeString(branch),
  241. html.EscapeString(*p.HeadCommit.URL),
  242. strings.Join(cList, "<br>"),
  243. )
  244. }
  245. // single commit message
  246. // [<repo>] <username> pushed to <branch>: <msg> - <git.io link>
  247. return fmt.Sprintf(
  248. `[<u>%s</u>] %s pushed to <b>%s</b>: %s - %s`,
  249. html.EscapeString(*p.Repo.FullName),
  250. html.EscapeString(nameForAuthor(p.HeadCommit.Committer)),
  251. html.EscapeString(branch),
  252. html.EscapeString(*p.HeadCommit.Message),
  253. html.EscapeString(*p.HeadCommit.URL),
  254. )
  255. }
  256. func nameForAuthor(a *github.CommitAuthor) string {
  257. if a == nil {
  258. return ""
  259. }
  260. if a.Login != nil { // prefer to use their GH username than the name they commited as
  261. return *a.Login
  262. }
  263. return *a.Name
  264. }