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.

205 lines
7.1 KiB

8 years ago
  1. package webhook
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. gojira "github.com/andygrunwald/go-jira"
  8. "github.com/matrix-org/go-neb/database"
  9. "github.com/matrix-org/go-neb/realms/jira"
  10. "github.com/matrix-org/util"
  11. log "github.com/sirupsen/logrus"
  12. )
  13. type jiraWebhook struct {
  14. Name string `json:"name"`
  15. URL string `json:"url"`
  16. Events []string `json:"events"`
  17. Filter string `json:"jqlFilter"`
  18. Exclude bool `json:"excludeIssueDetails"`
  19. // These fields are populated on GET
  20. Enabled bool `json:"enabled"`
  21. }
  22. // Event represents an incoming JIRA webhook event
  23. type Event struct {
  24. WebhookEvent string `json:"webhookEvent"`
  25. Timestamp int64 `json:"timestamp"`
  26. User gojira.User `json:"user"`
  27. Issue gojira.Issue `json:"issue"`
  28. }
  29. // RegisterHook checks to see if this user is allowed to track the given projects and then tracks them.
  30. func RegisterHook(jrealm *jira.Realm, projects []string, userID, webhookEndpointURL string) error {
  31. // Tracking means that a webhook may need to be created on the remote JIRA installation.
  32. // We need to make sure that the user has permission to do this. If they don't, it may still be okay if
  33. // there is an existing webhook set up for this installation by someone else, *PROVIDED* that the projects
  34. // they wish to monitor are "public" (accessible by not logged in users).
  35. //
  36. // The methodology for this is as follows:
  37. // - If they don't have a JIRA token for the remote install, fail.
  38. // - Try to GET /webhooks. If this succeeds:
  39. // * The user is an admin (only admins can GET webhooks)
  40. // * If there is a NEB webhook already then return success.
  41. // * Else create the webhook and then return success (if creation fails then fail).
  42. // - Else:
  43. // * The user is NOT an admin.
  44. // * Are ALL the projects in the config public? If yes:
  45. // - Is there an existing config for this remote JIRA installation? If yes:
  46. // * Another user has setup a webhook. We can't check if the webhook is still alive though,
  47. // return success.
  48. // - Else:
  49. // * There is no existing NEB webhook for this JIRA installation. The user cannot create a
  50. // webhook to the JIRA installation, so fail.
  51. // * Else:
  52. // - There are private projects in the config and the user isn't an admin, so fail.
  53. logger := log.WithFields(log.Fields{
  54. "realm_id": jrealm.ID(),
  55. "jira_url": jrealm.JIRAEndpoint,
  56. "user_id": userID,
  57. })
  58. cli, err := jrealm.JIRAClient(userID, false)
  59. if err != nil {
  60. logger.WithError(err).Print("No JIRA client exists")
  61. return err // no OAuth token on this JIRA endpoint
  62. }
  63. wh, forbidden, err := getWebhook(cli, webhookEndpointURL)
  64. if err != nil {
  65. if !forbidden {
  66. logger.WithError(err).Print("Failed to GET webhook")
  67. return err
  68. }
  69. // User is not a JIRA admin (cannot GET webhooks)
  70. // The only way this is going to end well for this request is if all the projects
  71. // are PUBLIC. That is, they can be accessed directly without an access token.
  72. err = checkProjectsArePublic(jrealm, projects, userID)
  73. if err != nil {
  74. logger.WithError(err).Print("Failed to assert that all projects are public")
  75. return err
  76. }
  77. // All projects that wish to be tracked are public, but the user cannot create
  78. // webhooks. The only way this will work is if we already have a webhook for this
  79. // JIRA endpoint.
  80. if !jrealm.HasWebhook {
  81. logger.Print("No webhook exists for this realm.")
  82. return fmt.Errorf("Not authorised to create webhook: not an admin")
  83. }
  84. return nil
  85. }
  86. // The user is probably an admin (can query webhooks endpoint)
  87. if wh != nil {
  88. logger.Print("Webhook already exists")
  89. return nil // we already have a NEB webhook :D
  90. }
  91. return createWebhook(jrealm, webhookEndpointURL, userID)
  92. }
  93. // OnReceiveRequest is called when JIRA hits NEB with an update.
  94. // Returns the project key and webhook event, or an error.
  95. func OnReceiveRequest(req *http.Request) (string, *Event, *util.JSONResponse) {
  96. // extract the JIRA webhook event JSON
  97. defer req.Body.Close()
  98. var whe Event
  99. err := json.NewDecoder(req.Body).Decode(&whe)
  100. if err != nil {
  101. resErr := util.MessageResponse(400, "Failed to parse request JSON")
  102. return "", nil, &resErr
  103. }
  104. if err != nil {
  105. resErr := util.MessageResponse(400, "Failed to parse JIRA URL")
  106. return "", nil, &resErr
  107. }
  108. projKey := strings.Split(whe.Issue.Key, "-")[0]
  109. projKey = strings.ToUpper(projKey)
  110. return projKey, &whe, nil
  111. }
  112. func createWebhook(jrealm *jira.Realm, webhookEndpointURL, userID string) error {
  113. cli, err := jrealm.JIRAClient(userID, false)
  114. if err != nil {
  115. return err
  116. }
  117. req, err := cli.NewRequest("POST", "rest/webhooks/1.0/webhook", jiraWebhook{
  118. Name: "Go-NEB",
  119. URL: webhookEndpointURL,
  120. Events: []string{"jira:issue_created", "jira:issue_deleted", "jira:issue_updated"},
  121. Filter: "",
  122. Exclude: false,
  123. })
  124. if err != nil {
  125. return err
  126. }
  127. res, err := cli.Do(req, nil)
  128. if err != nil {
  129. return err
  130. }
  131. if res.StatusCode < 200 || res.StatusCode >= 300 {
  132. return fmt.Errorf("Creating webhook returned HTTP %d", res.StatusCode)
  133. }
  134. log.WithFields(log.Fields{
  135. "status_code": res.StatusCode,
  136. "realm_id": jrealm.ID(),
  137. "jira_url": jrealm.JIRAEndpoint,
  138. }).Print("Created webhook")
  139. // mark this on the realm and persist it.
  140. jrealm.HasWebhook = true
  141. _, err = database.GetServiceDB().StoreAuthRealm(jrealm)
  142. return err
  143. }
  144. // Get an existing JIRA webhook. Returns the hook if it exists, or an error along with a bool
  145. // which indicates if the request to retrieve the hook is not 2xx. If it is not 2xx, it is
  146. // forbidden (different JIRA deployments return different codes ranging from 401/403/404/500).
  147. func getWebhook(cli *gojira.Client, webhookEndpointURL string) (*jiraWebhook, bool, error) {
  148. req, err := cli.NewRequest("GET", "rest/webhooks/1.0/webhook", nil)
  149. if err != nil {
  150. return nil, false, fmt.Errorf("Failed to prepare webhook request")
  151. }
  152. var webhookList []jiraWebhook
  153. res, err := cli.Do(req, &webhookList)
  154. if err != nil {
  155. return nil, false, fmt.Errorf("Failed to query webhooks")
  156. }
  157. if res.StatusCode < 200 || res.StatusCode >= 300 {
  158. return nil, true, fmt.Errorf("Querying webhook returned HTTP %d", res.StatusCode)
  159. }
  160. log.Print("Retrieved ", len(webhookList), " webhooks")
  161. var nebWH *jiraWebhook
  162. for _, wh := range webhookList {
  163. if wh.URL == webhookEndpointURL {
  164. nebWH = &wh
  165. break
  166. }
  167. }
  168. return nebWH, false, nil
  169. }
  170. func checkProjectsArePublic(jrealm *jira.Realm, projects []string, userID string) error {
  171. publicCli, err := jrealm.JIRAClient("", true)
  172. if err != nil {
  173. return fmt.Errorf("Cannot create public JIRA client")
  174. }
  175. for _, projectKey := range projects {
  176. // check you can query this project with a public client
  177. req, err := publicCli.NewRequest("GET", "rest/api/2/project/"+projectKey, nil)
  178. if err != nil {
  179. return fmt.Errorf("Failed to create project URL for project %s", projectKey)
  180. }
  181. res, err := publicCli.Do(req, nil)
  182. if err != nil {
  183. return fmt.Errorf("Failed to query project %s", projectKey)
  184. }
  185. if res.StatusCode < 200 || res.StatusCode >= 300 {
  186. return fmt.Errorf("Project %s is not public. (HTTP %d)", projectKey, res.StatusCode)
  187. }
  188. }
  189. return nil
  190. }