webhook.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "crypto/tls"
  7. "encoding/json"
  8. "fmt"
  9. "io/ioutil"
  10. "strings"
  11. "time"
  12. "github.com/go-xorm/xorm"
  13. gouuid "github.com/satori/go.uuid"
  14. log "gopkg.in/clog.v1"
  15. api "github.com/gogits/go-gogs-client"
  16. "github.com/gogits/gogs/modules/httplib"
  17. "github.com/gogits/gogs/modules/setting"
  18. "github.com/gogits/gogs/modules/sync"
  19. )
  20. var HookQueue = sync.NewUniqueQueue(setting.Webhook.QueueLength)
  21. type HookContentType int
  22. const (
  23. JSON HookContentType = iota + 1
  24. FORM
  25. )
  26. var hookContentTypes = map[string]HookContentType{
  27. "json": JSON,
  28. "form": FORM,
  29. }
  30. // ToHookContentType returns HookContentType by given name.
  31. func ToHookContentType(name string) HookContentType {
  32. return hookContentTypes[name]
  33. }
  34. func (t HookContentType) Name() string {
  35. switch t {
  36. case JSON:
  37. return "json"
  38. case FORM:
  39. return "form"
  40. }
  41. return ""
  42. }
  43. // IsValidHookContentType returns true if given name is a valid hook content type.
  44. func IsValidHookContentType(name string) bool {
  45. _, ok := hookContentTypes[name]
  46. return ok
  47. }
  48. type HookEvents struct {
  49. Create bool `json:"create"`
  50. Push bool `json:"push"`
  51. PullRequest bool `json:"pull_request"`
  52. }
  53. // HookEvent represents events that will delivery hook.
  54. type HookEvent struct {
  55. PushOnly bool `json:"push_only"`
  56. SendEverything bool `json:"send_everything"`
  57. ChooseEvents bool `json:"choose_events"`
  58. HookEvents `json:"events"`
  59. }
  60. type HookStatus int
  61. const (
  62. HOOK_STATUS_NONE = iota
  63. HOOK_STATUS_SUCCEED
  64. HOOK_STATUS_FAILED
  65. )
  66. // Webhook represents a web hook object.
  67. type Webhook struct {
  68. ID int64 `xorm:"pk autoincr"`
  69. RepoID int64
  70. OrgID int64
  71. URL string `xorm:"url TEXT"`
  72. ContentType HookContentType
  73. Secret string `xorm:"TEXT"`
  74. Events string `xorm:"TEXT"`
  75. *HookEvent `xorm:"-"`
  76. IsSSL bool `xorm:"is_ssl"`
  77. IsActive bool
  78. HookTaskType HookTaskType
  79. Meta string `xorm:"TEXT"` // store hook-specific attributes
  80. LastStatus HookStatus // Last delivery status
  81. Created time.Time `xorm:"-"`
  82. CreatedUnix int64
  83. Updated time.Time `xorm:"-"`
  84. UpdatedUnix int64
  85. }
  86. func (w *Webhook) BeforeInsert() {
  87. w.CreatedUnix = time.Now().Unix()
  88. w.UpdatedUnix = w.CreatedUnix
  89. }
  90. func (w *Webhook) BeforeUpdate() {
  91. w.UpdatedUnix = time.Now().Unix()
  92. }
  93. func (w *Webhook) AfterSet(colName string, _ xorm.Cell) {
  94. var err error
  95. switch colName {
  96. case "events":
  97. w.HookEvent = &HookEvent{}
  98. if err = json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
  99. log.Error(3, "Unmarshal [%d]: %v", w.ID, err)
  100. }
  101. case "created_unix":
  102. w.Created = time.Unix(w.CreatedUnix, 0).Local()
  103. case "updated_unix":
  104. w.Updated = time.Unix(w.UpdatedUnix, 0).Local()
  105. }
  106. }
  107. func (w *Webhook) GetSlackHook() *SlackMeta {
  108. s := &SlackMeta{}
  109. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  110. log.Error(2, "GetSlackHook [%d]: %v", w.ID, err)
  111. }
  112. return s
  113. }
  114. // History returns history of webhook by given conditions.
  115. func (w *Webhook) History(page int) ([]*HookTask, error) {
  116. return HookTasks(w.ID, page)
  117. }
  118. // UpdateEvent handles conversion from HookEvent to Events.
  119. func (w *Webhook) UpdateEvent() error {
  120. data, err := json.Marshal(w.HookEvent)
  121. w.Events = string(data)
  122. return err
  123. }
  124. // HasCreateEvent returns true if hook enabled create event.
  125. func (w *Webhook) HasCreateEvent() bool {
  126. return w.SendEverything ||
  127. (w.ChooseEvents && w.HookEvents.Create)
  128. }
  129. // HasPushEvent returns true if hook enabled push event.
  130. func (w *Webhook) HasPushEvent() bool {
  131. return w.PushOnly || w.SendEverything ||
  132. (w.ChooseEvents && w.HookEvents.Push)
  133. }
  134. // HasPullRequestEvent returns true if hook enabled pull request event.
  135. func (w *Webhook) HasPullRequestEvent() bool {
  136. return w.SendEverything ||
  137. (w.ChooseEvents && w.HookEvents.PullRequest)
  138. }
  139. func (w *Webhook) EventsArray() []string {
  140. events := make([]string, 0, 3)
  141. if w.HasCreateEvent() {
  142. events = append(events, "create")
  143. }
  144. if w.HasPushEvent() {
  145. events = append(events, "push")
  146. }
  147. if w.HasPullRequestEvent() {
  148. events = append(events, "pull_request")
  149. }
  150. return events
  151. }
  152. // CreateWebhook creates a new web hook.
  153. func CreateWebhook(w *Webhook) error {
  154. _, err := x.Insert(w)
  155. return err
  156. }
  157. // getWebhook uses argument bean as query condition,
  158. // ID must be specified and do not assign unnecessary fields.
  159. func getWebhook(bean *Webhook) (*Webhook, error) {
  160. has, err := x.Get(bean)
  161. if err != nil {
  162. return nil, err
  163. } else if !has {
  164. return nil, ErrWebhookNotExist{bean.ID}
  165. }
  166. return bean, nil
  167. }
  168. // GetWebhookByID returns webhook by given ID.
  169. // Use this function with caution of accessing unauthorized webhook,
  170. // which means should only be used in non-user interactive functions.
  171. func GetWebhookByID(id int64) (*Webhook, error) {
  172. return getWebhook(&Webhook{
  173. ID: id,
  174. })
  175. }
  176. // GetWebhookOfRepoByID returns webhook of repository by given ID.
  177. func GetWebhookOfRepoByID(repoID, id int64) (*Webhook, error) {
  178. return getWebhook(&Webhook{
  179. ID: id,
  180. RepoID: repoID,
  181. })
  182. }
  183. // GetWebhookByOrgID returns webhook of organization by given ID.
  184. func GetWebhookByOrgID(orgID, id int64) (*Webhook, error) {
  185. return getWebhook(&Webhook{
  186. ID: id,
  187. OrgID: orgID,
  188. })
  189. }
  190. // GetActiveWebhooksByRepoID returns all active webhooks of repository.
  191. func GetActiveWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  192. webhooks := make([]*Webhook, 0, 5)
  193. return webhooks, x.Where("repo_id = ?", repoID).And("is_active = ?", true).Find(&webhooks)
  194. }
  195. // GetWebhooksByRepoID returns all webhooks of a repository.
  196. func GetWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  197. webhooks := make([]*Webhook, 0, 5)
  198. return webhooks, x.Find(&webhooks, &Webhook{RepoID: repoID})
  199. }
  200. // UpdateWebhook updates information of webhook.
  201. func UpdateWebhook(w *Webhook) error {
  202. _, err := x.Id(w.ID).AllCols().Update(w)
  203. return err
  204. }
  205. // deleteWebhook uses argument bean as query condition,
  206. // ID must be specified and do not assign unnecessary fields.
  207. func deleteWebhook(bean *Webhook) (err error) {
  208. sess := x.NewSession()
  209. defer sessionRelease(sess)
  210. if err = sess.Begin(); err != nil {
  211. return err
  212. }
  213. if _, err = sess.Delete(bean); err != nil {
  214. return err
  215. } else if _, err = sess.Delete(&HookTask{HookID: bean.ID}); err != nil {
  216. return err
  217. }
  218. return sess.Commit()
  219. }
  220. // DeleteWebhookOfRepoByID deletes webhook of repository by given ID.
  221. func DeleteWebhookOfRepoByID(repoID, id int64) error {
  222. return deleteWebhook(&Webhook{
  223. ID: id,
  224. RepoID: repoID,
  225. })
  226. }
  227. // DeleteWebhookOfOrgByID deletes webhook of organization by given ID.
  228. func DeleteWebhookOfOrgByID(orgID, id int64) error {
  229. return deleteWebhook(&Webhook{
  230. ID: id,
  231. OrgID: orgID,
  232. })
  233. }
  234. // GetWebhooksByOrgID returns all webhooks for an organization.
  235. func GetWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  236. err = x.Find(&ws, &Webhook{OrgID: orgID})
  237. return ws, err
  238. }
  239. // GetActiveWebhooksByOrgID returns all active webhooks for an organization.
  240. func GetActiveWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  241. err = x.Where("org_id=?", orgID).And("is_active=?", true).Find(&ws)
  242. return ws, err
  243. }
  244. // ___ ___ __ ___________ __
  245. // / | \ ____ ____ | | _\__ ___/____ _____| | __
  246. // / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
  247. // \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
  248. // \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
  249. // \/ \/ \/ \/ \/
  250. type HookTaskType int
  251. const (
  252. GOGS HookTaskType = iota + 1
  253. SLACK
  254. DISCORD
  255. )
  256. var hookTaskTypes = map[string]HookTaskType{
  257. "gogs": GOGS,
  258. "slack": SLACK,
  259. "discord": DISCORD,
  260. }
  261. // ToHookTaskType returns HookTaskType by given name.
  262. func ToHookTaskType(name string) HookTaskType {
  263. return hookTaskTypes[name]
  264. }
  265. func (t HookTaskType) Name() string {
  266. switch t {
  267. case GOGS:
  268. return "gogs"
  269. case SLACK:
  270. return "slack"
  271. case DISCORD:
  272. return "discord"
  273. }
  274. return ""
  275. }
  276. // IsValidHookTaskType returns true if given name is a valid hook task type.
  277. func IsValidHookTaskType(name string) bool {
  278. _, ok := hookTaskTypes[name]
  279. return ok
  280. }
  281. type HookEventType string
  282. const (
  283. HOOK_EVENT_CREATE HookEventType = "create"
  284. HOOK_EVENT_PUSH HookEventType = "push"
  285. HOOK_EVENT_PULL_REQUEST HookEventType = "pull_request"
  286. )
  287. // HookRequest represents hook task request information.
  288. type HookRequest struct {
  289. Headers map[string]string `json:"headers"`
  290. }
  291. // HookResponse represents hook task response information.
  292. type HookResponse struct {
  293. Status int `json:"status"`
  294. Headers map[string]string `json:"headers"`
  295. Body string `json:"body"`
  296. }
  297. // HookTask represents a hook task.
  298. type HookTask struct {
  299. ID int64 `xorm:"pk autoincr"`
  300. RepoID int64 `xorm:"INDEX"`
  301. HookID int64
  302. UUID string
  303. Type HookTaskType
  304. URL string `xorm:"TEXT"`
  305. api.Payloader `xorm:"-"`
  306. PayloadContent string `xorm:"TEXT"`
  307. ContentType HookContentType
  308. EventType HookEventType
  309. IsSSL bool
  310. IsDelivered bool
  311. Delivered int64
  312. DeliveredString string `xorm:"-"`
  313. // History info.
  314. IsSucceed bool
  315. RequestContent string `xorm:"TEXT"`
  316. RequestInfo *HookRequest `xorm:"-"`
  317. ResponseContent string `xorm:"TEXT"`
  318. ResponseInfo *HookResponse `xorm:"-"`
  319. }
  320. func (t *HookTask) BeforeUpdate() {
  321. if t.RequestInfo != nil {
  322. t.RequestContent = t.MarshalJSON(t.RequestInfo)
  323. }
  324. if t.ResponseInfo != nil {
  325. t.ResponseContent = t.MarshalJSON(t.ResponseInfo)
  326. }
  327. }
  328. func (t *HookTask) AfterSet(colName string, _ xorm.Cell) {
  329. var err error
  330. switch colName {
  331. case "delivered":
  332. t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")
  333. case "request_content":
  334. if len(t.RequestContent) == 0 {
  335. return
  336. }
  337. t.RequestInfo = &HookRequest{}
  338. if err = json.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
  339. log.Error(3, "Unmarshal[%d]: %v", t.ID, err)
  340. }
  341. case "response_content":
  342. if len(t.ResponseContent) == 0 {
  343. return
  344. }
  345. t.ResponseInfo = &HookResponse{}
  346. if err = json.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
  347. log.Error(3, "Unmarshal [%d]: %v", t.ID, err)
  348. }
  349. }
  350. }
  351. func (t *HookTask) MarshalJSON(v interface{}) string {
  352. p, err := json.Marshal(v)
  353. if err != nil {
  354. log.Error(3, "Marshal [%d]: %v", t.ID, err)
  355. }
  356. return string(p)
  357. }
  358. // HookTasks returns a list of hook tasks by given conditions.
  359. func HookTasks(hookID int64, page int) ([]*HookTask, error) {
  360. tasks := make([]*HookTask, 0, setting.Webhook.PagingNum)
  361. return tasks, x.Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum).Where("hook_id=?", hookID).Desc("id").Find(&tasks)
  362. }
  363. // CreateHookTask creates a new hook task,
  364. // it handles conversion from Payload to PayloadContent.
  365. func CreateHookTask(t *HookTask) error {
  366. data, err := t.Payloader.JSONPayload()
  367. if err != nil {
  368. return err
  369. }
  370. t.UUID = gouuid.NewV4().String()
  371. t.PayloadContent = string(data)
  372. _, err = x.Insert(t)
  373. return err
  374. }
  375. // UpdateHookTask updates information of hook task.
  376. func UpdateHookTask(t *HookTask) error {
  377. _, err := x.Id(t.ID).AllCols().Update(t)
  378. return err
  379. }
  380. // prepareWebhooks adds list of webhooks to task queue.
  381. func prepareWebhooks(repo *Repository, event HookEventType, p api.Payloader, webhooks []*Webhook) (err error) {
  382. if len(webhooks) == 0 {
  383. return nil
  384. }
  385. var payloader api.Payloader
  386. for _, w := range webhooks {
  387. switch event {
  388. case HOOK_EVENT_CREATE:
  389. if !w.HasCreateEvent() {
  390. continue
  391. }
  392. case HOOK_EVENT_PUSH:
  393. if !w.HasPushEvent() {
  394. continue
  395. }
  396. case HOOK_EVENT_PULL_REQUEST:
  397. if !w.HasPullRequestEvent() {
  398. continue
  399. }
  400. }
  401. // Use separate objects so modifcations won't be made on payload on non-Gogs type hooks.
  402. switch w.HookTaskType {
  403. case SLACK:
  404. payloader, err = GetSlackPayload(p, event, w.Meta)
  405. if err != nil {
  406. return fmt.Errorf("GetSlackPayload: %v", err)
  407. }
  408. case DISCORD:
  409. payloader, err = GetDiscordPayload(p, event, w.Meta)
  410. if err != nil {
  411. return fmt.Errorf("GetDiscordPayload: %v", err)
  412. }
  413. default:
  414. p.SetSecret(w.Secret)
  415. payloader = p
  416. }
  417. if err = CreateHookTask(&HookTask{
  418. RepoID: repo.ID,
  419. HookID: w.ID,
  420. Type: w.HookTaskType,
  421. URL: w.URL,
  422. Payloader: payloader,
  423. ContentType: w.ContentType,
  424. EventType: event,
  425. IsSSL: w.IsSSL,
  426. }); err != nil {
  427. return fmt.Errorf("CreateHookTask: %v", err)
  428. }
  429. }
  430. return nil
  431. }
  432. // PrepareWebhooks adds all active webhooks to task queue.
  433. func PrepareWebhooks(repo *Repository, event HookEventType, p api.Payloader) error {
  434. webhooks, err := GetActiveWebhooksByRepoID(repo.ID)
  435. if err != nil {
  436. return fmt.Errorf("GetActiveWebhooksByRepoID [%d]: %v", repo.ID, err)
  437. }
  438. // check if repo belongs to org and append additional webhooks
  439. if repo.MustOwner().IsOrganization() {
  440. // get hooks for org
  441. orgws, err := GetActiveWebhooksByOrgID(repo.OwnerID)
  442. if err != nil {
  443. return fmt.Errorf("GetActiveWebhooksByOrgID [%d]: %v", repo.OwnerID, err)
  444. }
  445. webhooks = append(webhooks, orgws...)
  446. }
  447. return prepareWebhooks(repo, event, p, webhooks)
  448. }
  449. // TestWebhook adds the test webhook matches the ID to task queue.
  450. func TestWebhook(repo *Repository, event HookEventType, p api.Payloader, webhookID int64) error {
  451. webhook, err := GetWebhookOfRepoByID(repo.ID, webhookID)
  452. if err != nil {
  453. return fmt.Errorf("GetWebhookOfRepoByID [repo_id: %d, id: %d]: %v", repo.ID, webhookID, err)
  454. }
  455. return prepareWebhooks(repo, event, p, []*Webhook{webhook})
  456. }
  457. func (t *HookTask) deliver() {
  458. t.IsDelivered = true
  459. timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
  460. req := httplib.Post(t.URL).SetTimeout(timeout, timeout).
  461. Header("X-Gogs-Delivery", t.UUID).
  462. Header("X-Gogs-Event", string(t.EventType)).
  463. SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})
  464. switch t.ContentType {
  465. case JSON:
  466. req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
  467. case FORM:
  468. req.Param("payload", t.PayloadContent)
  469. }
  470. // Record delivery information.
  471. t.RequestInfo = &HookRequest{
  472. Headers: map[string]string{},
  473. }
  474. for k, vals := range req.Headers() {
  475. t.RequestInfo.Headers[k] = strings.Join(vals, ",")
  476. }
  477. t.ResponseInfo = &HookResponse{
  478. Headers: map[string]string{},
  479. }
  480. defer func() {
  481. t.Delivered = time.Now().UnixNano()
  482. if t.IsSucceed {
  483. log.Trace("Hook delivered: %s", t.UUID)
  484. } else {
  485. log.Trace("Hook delivery failed: %s", t.UUID)
  486. }
  487. // Update webhook last delivery status.
  488. w, err := GetWebhookByID(t.HookID)
  489. if err != nil {
  490. log.Error(3, "GetWebhookByID: %v", err)
  491. return
  492. }
  493. if t.IsSucceed {
  494. w.LastStatus = HOOK_STATUS_SUCCEED
  495. } else {
  496. w.LastStatus = HOOK_STATUS_FAILED
  497. }
  498. if err = UpdateWebhook(w); err != nil {
  499. log.Error(3, "UpdateWebhook: %v", err)
  500. return
  501. }
  502. }()
  503. resp, err := req.Response()
  504. if err != nil {
  505. t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
  506. return
  507. }
  508. defer resp.Body.Close()
  509. // Status code is 20x can be seen as succeed.
  510. t.IsSucceed = resp.StatusCode/100 == 2
  511. t.ResponseInfo.Status = resp.StatusCode
  512. for k, vals := range resp.Header {
  513. t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
  514. }
  515. p, err := ioutil.ReadAll(resp.Body)
  516. if err != nil {
  517. t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
  518. return
  519. }
  520. t.ResponseInfo.Body = string(p)
  521. }
  522. // DeliverHooks checks and delivers undelivered hooks.
  523. // TODO: shoot more hooks at same time.
  524. func DeliverHooks() {
  525. tasks := make([]*HookTask, 0, 10)
  526. x.Where("is_delivered=?", false).Iterate(new(HookTask),
  527. func(idx int, bean interface{}) error {
  528. t := bean.(*HookTask)
  529. t.deliver()
  530. tasks = append(tasks, t)
  531. return nil
  532. })
  533. // Update hook task status.
  534. for _, t := range tasks {
  535. if err := UpdateHookTask(t); err != nil {
  536. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  537. }
  538. }
  539. // Start listening on new hook requests.
  540. for repoID := range HookQueue.Queue() {
  541. log.Trace("DeliverHooks [repo_id: %v]", repoID)
  542. HookQueue.Remove(repoID)
  543. tasks = make([]*HookTask, 0, 5)
  544. if err := x.Where("repo_id=? AND is_delivered=?", repoID, false).Find(&tasks); err != nil {
  545. log.Error(4, "Get repository [%s] hook tasks: %v", repoID, err)
  546. continue
  547. }
  548. for _, t := range tasks {
  549. t.deliver()
  550. if err := UpdateHookTask(t); err != nil {
  551. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  552. continue
  553. }
  554. }
  555. }
  556. }
  557. func InitDeliverHooks() {
  558. go DeliverHooks()
  559. }