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.

206 lines
9.0 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package travisci
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "net/http/httptest"
  9. "strings"
  10. "testing"
  11. "github.com/matrix-org/go-neb/database"
  12. "github.com/matrix-org/go-neb/testutils"
  13. "github.com/matrix-org/go-neb/types"
  14. "github.com/matrix-org/gomatrix"
  15. )
  16. const travisOrgPEMPublicKey = (`-----BEGIN PUBLIC KEY-----
  17. MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvtjdLkS+FP+0fPC09j25
  18. y/PiuYDDivIT86COVedvlElk99BBYTrqNaJybxjXbIZ1Q6xFNhOY+iTcBr4E1zJu
  19. tizF3Xi0V9tOuP/M8Wn4Y/1lCWbQKlWrNQuqNBmhovF4K3mDCYswVbpgTmp+JQYu
  20. Bm9QMdieZMNry5s6aiMA9aSjDlNyedvSENYo18F+NYg1J0C0JiPYTxheCb4optr1
  21. 5xNzFKhAkuGs4XTOA5C7Q06GCKtDNf44s/CVE30KODUxBi0MCKaxiXw/yy55zxX2
  22. /YdGphIyQiA5iO1986ZmZCLLW8udz9uhW5jUr3Jlp9LbmphAC61bVSf4ou2YsJaN
  23. 0QIDAQAB
  24. -----END PUBLIC KEY-----`)
  25. const travisComPEMPublicKey = (`-----BEGIN PUBLIC KEY-----
  26. MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnQU2j9lnRtyuW36arNOc
  27. dzCzyKVirLUi3/aLh6UfnTVXzTnx8eHUnBn1ZeQl7Eh3J3qqdbIKl6npS27ONzCy
  28. 3PIcfjpLPaVyGagIL8c8XgDEvB45AesC0osVP5gkXQkPUM3B2rrUmp1AZzG+Fuo0
  29. SAeNnS71gN63U3brL9fN/MTCXJJ6TvMt3GrcJUq5uq56qNeJTsiowK6eiiWFUSfh
  30. e1qapOdMFmcEs9J/R1XQ/scxbAnLcWfl8lqH/MjMdCMe0j3X2ZYMTqOHsb3cQGSS
  31. dMPwZGeLWV+OaxjJ7TrJ+riqMANOgqCBGpvWUnUfo046ACOx7p6u4fFc3aRiuqYK
  32. VQIDAQAB
  33. -----END PUBLIC KEY-----`)
  34. const exampleSignature = ("pW0CDpmcAeWw3qf2Ufx8UvzfrZRUpYx30HBl9nJcDkh2v9FrF1GjJVsrcqx7ly0FPjb7dkfMJ/d0Q3JpDb1EL4p509cN4Vy8+HpfINw35Wg6JqzOQqTa" +
  35. "TidwoDLXo0NgL78zfiL3dra7ZwOGTA+LmnLSuNp38ROxn70u26uqJzWprGSdVNbRu1LkF1QKLa61NZegfxK7RZn1PlIsznWIyTS0qj81mg2sXMDLH1J4" +
  36. "pHxjEpzydjSb5b8tCjrN+vFLDdAtP5RjU8NwvQM4LRRGbLDIlRsO77HDwfXrPgUE3DjPIqVpHhMcCusygp0ClH2b1J1O3LkhxSS9ol5w99Hkpg==")
  37. const exampleBody = ("payload=%7B%22id%22%3A176075135%2C%22repository%22%3A%7B%22id%22%3A6461770%2C%22name%22%3A%22flow-jsdoc%22%2C%22owner_" +
  38. "name%22%3A%22Kegsay%22%2C%22url%22%3Anull%7D%2C%22number%22%3A%2218%22%2C%22config%22%3A%7B%22notifications%22%3A%7B%22web" +
  39. "hooks%22%3A%5B%22http%3A%2F%2F7abbe705.ngrok.io%22%5D%7D%2C%22language%22%3A%22node_js%22%2C%22node_js%22%3A%5B%224.1%22%5D%2C%22.resu" +
  40. "lt%22%3A%22configured%22%2C%22group%22%3A%22stable%22%2C%22dist%22%3A%22precise%22%7D%2C%22status%22%3A0%2C%22result%22%3A0%2C%22status_" +
  41. "message%22%3A%22Passed%22%2C%22result_message%22%3A%22Passed%22%2C%22started_at%22%3A%222016-11-15T15%3A10%3A22Z%22%2C%22finished_" +
  42. "at%22%3A%222016-11-15T15%3A10%3A54Z%22%2C%22duration%22%3A32%2C%22build_url%22%3A%22https%3A%2F%2Ftravis-ci.org%2FKegsay%2Fflow-js" +
  43. "doc%2Fbuilds%2F176075135%22%2C%22commit_id%22%3A50222535%2C%22commit%22%3A%223a092c3a6032ebb50384c99b445f947e9ce86e2a%22%2C%22base_com" +
  44. "mit%22%3Anull%2C%22head_commit%22%3Anull%2C%22branch%22%3A%22master%22%2C%22message%22%3A%22Test+Travis+webhook+support%22%2C%22compare_" +
  45. "url%22%3A%22https%3A%2F%2Fgithub.com%2FKegsay%2Fflow-jsdoc%2Fcompare%2F9f9d459ba082...3a092c3a6032%22%2C%22committed_at%22%3A%222016-1" +
  46. "1-15T15%3A08%3A16Z%22%2C%22author_name%22%3A%22Kegan+Dougal%22%2C%22author_email%22%3A%22kegan%40matrix.org%22%2C%22committer_" +
  47. "name%22%3A%22Kegan+Dougal%22%2C%22committer_email%22%3A%22kegan%40matrix.org%22%2C%22matrix%22%3A%5B%7B%22id%22%3A176075137%2C%22reposit" +
  48. "ory_id%22%3A6461770%2C%22parent_id%22%3A176075135%2C%22number%22%3A%2218.1%22%2C%22state%22%3A%22finished%22%2C%22config%22%3A%7B%22notifi" +
  49. "cations%22%3A%7B%22webhooks%22%3A%5B%22http%3A%2F%2F7abbe705.ngrok.io%22%5D%7D%2C%22language%22%3A%22node_js%22%2C%22node_" +
  50. "js%22%3A%224.1%22%2C%22.result%22%3A%22configured%22%2C%22group%22%3A%22stable%22%2C%22dist%22%3A%22precise%22%2C%22os%22%3A%22li" +
  51. "nux%22%7D%2C%22status%22%3A0%2C%22result%22%3A0%2C%22commit%22%3A%223a092c3a6032ebb50384c99b445f947e9ce86e2a%22%2C%22branch%22%3A%22mas" +
  52. "ter%22%2C%22message%22%3A%22Test+Travis+webhook+support%22%2C%22compare_url%22%3A%22https%3A%2F%2Fgithub.com%2FKegsay%2Fflow-jsdoc%2Fcomp" +
  53. "are%2F9f9d459ba082...3a092c3a6032%22%2C%22started_at%22%3A%222016-11-15T15%3A10%3A22Z%22%2C%22finished_at%22%3A%222016-11-" +
  54. "15T15%3A10%3A54Z%22%2C%22committed_at%22%3A%222016-11-15T15%3A08%3A16Z%22%2C%22author_name%22%3A%22Kegan+Dougal%22%2C%22author_ema" +
  55. "il%22%3A%22kegan%40matrix.org%22%2C%22committer_name%22%3A%22Kegan+Dougal%22%2C%22committer_email%22%3A%22kegan%40matrix.org%22%2C%22allow_f" +
  56. "ailure%22%3Afalse%7D%5D%2C%22type%22%3A%22push%22%2C%22state%22%3A%22passed%22%2C%22pull_request%22%3Afalse%2C%22pull_request_number%22%3Anu" +
  57. "ll%2C%22pull_request_title%22%3Anull%2C%22tag%22%3Anull%7D")
  58. var travisTests = []struct {
  59. Signature string
  60. ValidSignature bool
  61. Body string
  62. Template string
  63. ExpectedOutput string
  64. }{
  65. {
  66. exampleSignature, true, exampleBody,
  67. "%{repository}#%{build_number} (%{branch} - %{commit} : %{author}): %{message}",
  68. "Kegsay/flow-jsdoc#18 (master - 3a092c3a60 : Kegan Dougal): Passed",
  69. },
  70. {
  71. "obviously_invalid_signature", false, exampleBody,
  72. "%{repository}#%{build_number} (%{branch} - %{commit} : %{author}): %{message}",
  73. "Kegsay/flow-jsdoc#18 (master - 3a092c3a60 : Kegan Dougal): Passed",
  74. },
  75. {
  76. // Payload is valid but doesn't match signature now
  77. exampleSignature, false, strings.TrimSuffix(exampleBody, "%7D") + "%2C%22EXTRA_KEY%22%3Anull%7D",
  78. "%{repository}#%{build_number} (%{branch} - %{commit} : %{author}): %{message}",
  79. "Kegsay/flow-jsdoc#18 (master - 3a092c3a60 : Kegan Dougal): Passed",
  80. },
  81. {
  82. exampleSignature, true, exampleBody,
  83. "%{repository}#%{build_number} %{duration}",
  84. "Kegsay/flow-jsdoc#18 32s",
  85. },
  86. }
  87. func TestTravisCI(t *testing.T) {
  88. database.SetServiceDB(&database.NopStorage{})
  89. // When the service tries to get Travis' public key, return the constant
  90. urlToKey := make(map[string]string)
  91. urlToKey["https://api.travis-ci.org/config"] = travisOrgPEMPublicKey
  92. urlToKey["https://api.travis-ci.com/config"] = travisComPEMPublicKey
  93. travisTransport := testutils.NewRoundTripper(func(req *http.Request) (*http.Response, error) {
  94. if key := urlToKey[req.URL.String()]; key != "" {
  95. escKey, _ := json.Marshal(key)
  96. return &http.Response{
  97. StatusCode: 200,
  98. Body: ioutil.NopCloser(bytes.NewBufferString(
  99. `{"config":{"notifications":{"webhook":{"public_key":` + string(escKey) + `}}}}`,
  100. )),
  101. }, nil
  102. }
  103. return nil, fmt.Errorf("Unhandled URL %s", req.URL.String())
  104. })
  105. // clobber the http client that the service uses to talk to Travis
  106. httpClient = &http.Client{Transport: travisTransport}
  107. // Intercept message sending to Matrix and mock responses
  108. msgs := []gomatrix.TextMessage{}
  109. matrixTrans := struct{ testutils.MockTransport }{}
  110. matrixTrans.RT = func(req *http.Request) (*http.Response, error) {
  111. if !strings.Contains(req.URL.String(), "/send/m.room.message") {
  112. return nil, fmt.Errorf("Unhandled URL: %s", req.URL.String())
  113. }
  114. var msg gomatrix.TextMessage
  115. if err := json.NewDecoder(req.Body).Decode(&msg); err != nil {
  116. return nil, fmt.Errorf("Failed to decode request JSON: %s", err)
  117. }
  118. msgs = append(msgs, msg)
  119. return &http.Response{
  120. StatusCode: 200,
  121. Body: ioutil.NopCloser(bytes.NewBufferString(`{"event_id":"$yup:event"}`)),
  122. }, nil
  123. }
  124. matrixCli, _ := gomatrix.NewClient("https://hyrule", "@travisci:hyrule", "its_a_secret")
  125. matrixCli.Client = &http.Client{Transport: matrixTrans}
  126. // BEGIN running the Travis-CI table tests
  127. // ---------------------------------------
  128. for _, test := range travisTests {
  129. msgs = []gomatrix.TextMessage{} // reset sent messages
  130. mockWriter := httptest.NewRecorder()
  131. travis := makeService(t, test.Template)
  132. if travis == nil {
  133. t.Error("TestTravisCI Failed to create service")
  134. continue
  135. }
  136. if err := travis.Register(nil, matrixCli); err != nil {
  137. t.Errorf("TestTravisCI Failed to Register(): %s", err)
  138. continue
  139. }
  140. req, err := http.NewRequest(
  141. "POST", "https://neb.endpoint/travis-ci-service", bytes.NewBufferString(test.Body),
  142. )
  143. if err != nil {
  144. t.Errorf("TestTravisCI Failed to create webhook request: %s", err)
  145. continue
  146. }
  147. req.Header.Set("Signature", test.Signature)
  148. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  149. travis.OnReceiveWebhook(mockWriter, req, matrixCli)
  150. if test.ValidSignature {
  151. if !assertResponse(t, mockWriter, msgs, 200, 1) {
  152. continue
  153. }
  154. if msgs[0].Body != test.ExpectedOutput {
  155. t.Errorf("TestTravisCI want matrix body '%s', got '%s'", test.ExpectedOutput, msgs[0].Body)
  156. }
  157. } else {
  158. assertResponse(t, mockWriter, msgs, 403, 0)
  159. }
  160. }
  161. }
  162. func assertResponse(t *testing.T, w *httptest.ResponseRecorder, msgs []gomatrix.TextMessage, expectCode int, expectMsgLength int) bool {
  163. if w.Code != expectCode {
  164. t.Errorf("TestTravisCI OnReceiveWebhook want HTTP code %d, got %d", expectCode, w.Code)
  165. return false
  166. }
  167. if len(msgs) != expectMsgLength {
  168. t.Errorf("TestTravisCI want %d sent messages, got %d ", expectMsgLength, len(msgs))
  169. return false
  170. }
  171. return true
  172. }
  173. func makeService(t *testing.T, template string) *Service {
  174. srv, err := types.CreateService("id", ServiceType, "@travisci:hyrule", []byte(
  175. `{
  176. "rooms":{
  177. "!ewfug483gsfe:localhost": {
  178. "repos": {
  179. "Kegsay/flow-jsdoc": {
  180. "template": "`+template+`"
  181. }
  182. }
  183. }
  184. }
  185. }`,
  186. ))
  187. if err != nil {
  188. t.Error("Failed to create Travis-CI service: ", err)
  189. return nil
  190. }
  191. return srv.(*Service)
  192. }