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.

webhook.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. api "github.com/go-gitea/go-sdk/gitea"
  15. "github.com/go-gitea/gitea/modules/httplib"
  16. "github.com/go-gitea/gitea/modules/log"
  17. "github.com/go-gitea/gitea/modules/setting"
  18. "github.com/go-gitea/gitea/modules/sync"
  19. )
  20. var HookQueue = sync.NewUniqueQueue(setting.Webhook.QueueLength)
  21. type HookContentType int
  22. const (
  23. ContentTypeJSON HookContentType = iota + 1
  24. ContentTypeForm
  25. )
  26. var hookContentTypes = map[string]HookContentType{
  27. "json": ContentTypeJSON,
  28. "form": ContentTypeForm,
  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 ContentTypeJSON:
  37. return "json"
  38. case ContentTypeForm:
  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. HookStatusNone = iota
  63. HookStatusSucceed
  64. HookStatusFail
  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(4, "webhook.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. // GetWebhookByRepoID returns webhook of repository by given ID.
  169. func GetWebhookByRepoID(repoID, id int64) (*Webhook, error) {
  170. return getWebhook(&Webhook{
  171. ID: id,
  172. RepoID: repoID,
  173. })
  174. }
  175. // GetWebhookByOrgID returns webhook of organization by given ID.
  176. func GetWebhookByOrgID(orgID, id int64) (*Webhook, error) {
  177. return getWebhook(&Webhook{
  178. ID: id,
  179. OrgID: orgID,
  180. })
  181. }
  182. // GetActiveWebhooksByRepoID returns all active webhooks of repository.
  183. func GetActiveWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  184. webhooks := make([]*Webhook, 0, 5)
  185. return webhooks, x.Find(&webhooks, &Webhook{
  186. RepoID: repoID,
  187. IsActive: true,
  188. })
  189. }
  190. // GetWebhooksByRepoID returns all webhooks of a repository.
  191. func GetWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  192. webhooks := make([]*Webhook, 0, 5)
  193. return webhooks, x.Find(&webhooks, &Webhook{RepoID: repoID})
  194. }
  195. // UpdateWebhook updates information of webhook.
  196. func UpdateWebhook(w *Webhook) error {
  197. _, err := x.Id(w.ID).AllCols().Update(w)
  198. return err
  199. }
  200. // deleteWebhook uses argument bean as query condition,
  201. // ID must be specified and do not assign unnecessary fields.
  202. func deleteWebhook(bean *Webhook) (err error) {
  203. sess := x.NewSession()
  204. defer sessionRelease(sess)
  205. if err = sess.Begin(); err != nil {
  206. return err
  207. }
  208. if _, err = sess.Delete(bean); err != nil {
  209. return err
  210. } else if _, err = sess.Delete(&HookTask{HookID: bean.ID}); err != nil {
  211. return err
  212. }
  213. return sess.Commit()
  214. }
  215. // DeleteWebhookByRepoID deletes webhook of repository by given ID.
  216. func DeleteWebhookByRepoID(repoID, id int64) error {
  217. return deleteWebhook(&Webhook{
  218. ID: id,
  219. RepoID: repoID,
  220. })
  221. }
  222. // DeleteWebhookByOrgID deletes webhook of organization by given ID.
  223. func DeleteWebhookByOrgID(orgID, id int64) error {
  224. return deleteWebhook(&Webhook{
  225. ID: id,
  226. OrgID: orgID,
  227. })
  228. }
  229. // GetWebhooksByOrgID returns all webhooks for an organization.
  230. func GetWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  231. err = x.Find(&ws, &Webhook{OrgID: orgID})
  232. return ws, err
  233. }
  234. // GetActiveWebhooksByOrgID returns all active webhooks for an organization.
  235. func GetActiveWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  236. err = x.
  237. Where("org_id=?", orgID).
  238. And("is_active=?", true).
  239. Find(&ws)
  240. return ws, err
  241. }
  242. // ___ ___ __ ___________ __
  243. // / | \ ____ ____ | | _\__ ___/____ _____| | __
  244. // / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
  245. // \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
  246. // \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
  247. // \/ \/ \/ \/ \/
  248. type HookTaskType int
  249. const (
  250. GOGS HookTaskType = iota + 1
  251. SLACK
  252. )
  253. var hookTaskTypes = map[string]HookTaskType{
  254. "gogs": GOGS,
  255. "slack": SLACK,
  256. }
  257. // ToHookTaskType returns HookTaskType by given name.
  258. func ToHookTaskType(name string) HookTaskType {
  259. return hookTaskTypes[name]
  260. }
  261. func (t HookTaskType) Name() string {
  262. switch t {
  263. case GOGS:
  264. return "gogs"
  265. case SLACK:
  266. return "slack"
  267. }
  268. return ""
  269. }
  270. // IsValidHookTaskType returns true if given name is a valid hook task type.
  271. func IsValidHookTaskType(name string) bool {
  272. _, ok := hookTaskTypes[name]
  273. return ok
  274. }
  275. type HookEventType string
  276. const (
  277. HookEventCreate HookEventType = "create"
  278. HookEventPush HookEventType = "push"
  279. HookEventPullRequest HookEventType = "pull_request"
  280. )
  281. // HookRequest represents hook task request information.
  282. type HookRequest struct {
  283. Headers map[string]string `json:"headers"`
  284. }
  285. // HookResponse represents hook task response information.
  286. type HookResponse struct {
  287. Status int `json:"status"`
  288. Headers map[string]string `json:"headers"`
  289. Body string `json:"body"`
  290. }
  291. // HookTask represents a hook task.
  292. type HookTask struct {
  293. ID int64 `xorm:"pk autoincr"`
  294. RepoID int64 `xorm:"INDEX"`
  295. HookID int64
  296. UUID string
  297. Type HookTaskType
  298. URL string `xorm:"TEXT"`
  299. api.Payloader `xorm:"-"`
  300. PayloadContent string `xorm:"TEXT"`
  301. ContentType HookContentType
  302. EventType HookEventType
  303. IsSSL bool
  304. IsDelivered bool
  305. Delivered int64
  306. DeliveredString string `xorm:"-"`
  307. // History info.
  308. IsSucceed bool
  309. RequestContent string `xorm:"TEXT"`
  310. RequestInfo *HookRequest `xorm:"-"`
  311. ResponseContent string `xorm:"TEXT"`
  312. ResponseInfo *HookResponse `xorm:"-"`
  313. }
  314. func (t *HookTask) BeforeUpdate() {
  315. if t.RequestInfo != nil {
  316. t.RequestContent = t.SimpleMarshalJSON(t.RequestInfo)
  317. }
  318. if t.ResponseInfo != nil {
  319. t.ResponseContent = t.SimpleMarshalJSON(t.ResponseInfo)
  320. }
  321. }
  322. func (t *HookTask) AfterSet(colName string, _ xorm.Cell) {
  323. var err error
  324. switch colName {
  325. case "delivered":
  326. t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")
  327. case "request_content":
  328. if len(t.RequestContent) == 0 {
  329. return
  330. }
  331. t.RequestInfo = &HookRequest{}
  332. if err = json.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
  333. log.Error(3, "Unmarshal[%d]: %v", t.ID, err)
  334. }
  335. case "response_content":
  336. if len(t.ResponseContent) == 0 {
  337. return
  338. }
  339. t.ResponseInfo = &HookResponse{}
  340. if err = json.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
  341. log.Error(3, "Unmarshal [%d]: %v", t.ID, err)
  342. }
  343. }
  344. }
  345. func (t *HookTask) SimpleMarshalJSON(v interface{}) string {
  346. p, err := json.Marshal(v)
  347. if err != nil {
  348. log.Error(3, "Marshal [%d]: %v", t.ID, err)
  349. }
  350. return string(p)
  351. }
  352. // HookTasks returns a list of hook tasks by given conditions.
  353. func HookTasks(hookID int64, page int) ([]*HookTask, error) {
  354. tasks := make([]*HookTask, 0, setting.Webhook.PagingNum)
  355. return tasks, x.
  356. Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum).
  357. Where("hook_id=?", hookID).
  358. Desc("id").
  359. Find(&tasks)
  360. }
  361. // CreateHookTask creates a new hook task,
  362. // it handles conversion from Payload to PayloadContent.
  363. func CreateHookTask(t *HookTask) error {
  364. data, err := t.Payloader.JSONPayload()
  365. if err != nil {
  366. return err
  367. }
  368. t.UUID = gouuid.NewV4().String()
  369. t.PayloadContent = string(data)
  370. _, err = x.Insert(t)
  371. return err
  372. }
  373. // UpdateHookTask updates information of hook task.
  374. func UpdateHookTask(t *HookTask) error {
  375. _, err := x.Id(t.ID).AllCols().Update(t)
  376. return err
  377. }
  378. // PrepareWebhooks adds new webhooks to task queue for given payload.
  379. func PrepareWebhooks(repo *Repository, event HookEventType, p api.Payloader) error {
  380. ws, err := GetActiveWebhooksByRepoID(repo.ID)
  381. if err != nil {
  382. return fmt.Errorf("GetActiveWebhooksByRepoID: %v", err)
  383. }
  384. // check if repo belongs to org and append additional webhooks
  385. if repo.MustOwner().IsOrganization() {
  386. // get hooks for org
  387. orgws, err := GetActiveWebhooksByOrgID(repo.OwnerID)
  388. if err != nil {
  389. return fmt.Errorf("GetActiveWebhooksByOrgID: %v", err)
  390. }
  391. ws = append(ws, orgws...)
  392. }
  393. if len(ws) == 0 {
  394. return nil
  395. }
  396. var payloader api.Payloader
  397. for _, w := range ws {
  398. switch event {
  399. case HookEventCreate:
  400. if !w.HasCreateEvent() {
  401. continue
  402. }
  403. case HookEventPush:
  404. if !w.HasPushEvent() {
  405. continue
  406. }
  407. case HookEventPullRequest:
  408. if !w.HasPullRequestEvent() {
  409. continue
  410. }
  411. }
  412. // Use separate objects so modifcations won't be made on payload on non-Gogs type hooks.
  413. switch w.HookTaskType {
  414. case SLACK:
  415. payloader, err = GetSlackPayload(p, event, w.Meta)
  416. if err != nil {
  417. return fmt.Errorf("GetSlackPayload: %v", err)
  418. }
  419. default:
  420. p.SetSecret(w.Secret)
  421. payloader = p
  422. }
  423. if err = CreateHookTask(&HookTask{
  424. RepoID: repo.ID,
  425. HookID: w.ID,
  426. Type: w.HookTaskType,
  427. URL: w.URL,
  428. Payloader: payloader,
  429. ContentType: w.ContentType,
  430. EventType: event,
  431. IsSSL: w.IsSSL,
  432. }); err != nil {
  433. return fmt.Errorf("CreateHookTask: %v", err)
  434. }
  435. }
  436. return nil
  437. }
  438. func (t *HookTask) deliver() {
  439. t.IsDelivered = true
  440. timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
  441. req := httplib.Post(t.URL).SetTimeout(timeout, timeout).
  442. Header("X-Gogs-Delivery", t.UUID).
  443. Header("X-Gogs-Event", string(t.EventType)).
  444. SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})
  445. switch t.ContentType {
  446. case ContentTypeJSON:
  447. req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
  448. case ContentTypeForm:
  449. req.Param("payload", t.PayloadContent)
  450. }
  451. // Record delivery information.
  452. t.RequestInfo = &HookRequest{
  453. Headers: map[string]string{},
  454. }
  455. for k, vals := range req.Headers() {
  456. t.RequestInfo.Headers[k] = strings.Join(vals, ",")
  457. }
  458. t.ResponseInfo = &HookResponse{
  459. Headers: map[string]string{},
  460. }
  461. defer func() {
  462. t.Delivered = time.Now().UnixNano()
  463. if t.IsSucceed {
  464. log.Trace("Hook delivered: %s", t.UUID)
  465. } else {
  466. log.Trace("Hook delivery failed: %s", t.UUID)
  467. }
  468. // Update webhook last delivery status.
  469. w, err := GetWebhookByRepoID(t.RepoID, t.HookID)
  470. if err != nil {
  471. log.Error(5, "GetWebhookByID: %v", err)
  472. return
  473. }
  474. if t.IsSucceed {
  475. w.LastStatus = HookStatusSucceed
  476. } else {
  477. w.LastStatus = HookStatusFail
  478. }
  479. if err = UpdateWebhook(w); err != nil {
  480. log.Error(5, "UpdateWebhook: %v", err)
  481. return
  482. }
  483. }()
  484. resp, err := req.Response()
  485. if err != nil {
  486. t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
  487. return
  488. }
  489. defer resp.Body.Close()
  490. // Status code is 20x can be seen as succeed.
  491. t.IsSucceed = resp.StatusCode/100 == 2
  492. t.ResponseInfo.Status = resp.StatusCode
  493. for k, vals := range resp.Header {
  494. t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
  495. }
  496. p, err := ioutil.ReadAll(resp.Body)
  497. if err != nil {
  498. t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
  499. return
  500. }
  501. t.ResponseInfo.Body = string(p)
  502. }
  503. // DeliverHooks checks and delivers undelivered hooks.
  504. // TODO: shoot more hooks at same time.
  505. func DeliverHooks() {
  506. tasks := make([]*HookTask, 0, 10)
  507. x.
  508. Where("is_delivered=?", false).
  509. Iterate(new(HookTask),
  510. func(idx int, bean interface{}) error {
  511. t := bean.(*HookTask)
  512. t.deliver()
  513. tasks = append(tasks, t)
  514. return nil
  515. })
  516. // Update hook task status.
  517. for _, t := range tasks {
  518. if err := UpdateHookTask(t); err != nil {
  519. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  520. }
  521. }
  522. // Start listening on new hook requests.
  523. for repoID := range HookQueue.Queue() {
  524. log.Trace("DeliverHooks [repo_id: %v]", repoID)
  525. HookQueue.Remove(repoID)
  526. tasks = make([]*HookTask, 0, 5)
  527. if err := x.Where("repo_id=? AND is_delivered=?", repoID, false).Find(&tasks); err != nil {
  528. log.Error(4, "Get repository [%d] hook tasks: %v", repoID, err)
  529. continue
  530. }
  531. for _, t := range tasks {
  532. t.deliver()
  533. if err := UpdateHookTask(t); err != nil {
  534. log.Error(4, "UpdateHookTask [%d]: %v", t.ID, err)
  535. continue
  536. }
  537. }
  538. }
  539. }
  540. func InitDeliverHooks() {
  541. go DeliverHooks()
  542. }