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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package webhook
  5. import (
  6. "context"
  7. "fmt"
  8. "strings"
  9. "code.gitea.io/gitea/models/db"
  10. "code.gitea.io/gitea/modules/json"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/secret"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/timeutil"
  15. "code.gitea.io/gitea/modules/util"
  16. webhook_module "code.gitea.io/gitea/modules/webhook"
  17. "xorm.io/builder"
  18. )
  19. // ErrWebhookNotExist represents a "WebhookNotExist" kind of error.
  20. type ErrWebhookNotExist struct {
  21. ID int64
  22. }
  23. // IsErrWebhookNotExist checks if an error is a ErrWebhookNotExist.
  24. func IsErrWebhookNotExist(err error) bool {
  25. _, ok := err.(ErrWebhookNotExist)
  26. return ok
  27. }
  28. func (err ErrWebhookNotExist) Error() string {
  29. return fmt.Sprintf("webhook does not exist [id: %d]", err.ID)
  30. }
  31. func (err ErrWebhookNotExist) Unwrap() error {
  32. return util.ErrNotExist
  33. }
  34. // ErrHookTaskNotExist represents a "HookTaskNotExist" kind of error.
  35. type ErrHookTaskNotExist struct {
  36. TaskID int64
  37. HookID int64
  38. UUID string
  39. }
  40. // IsErrHookTaskNotExist checks if an error is a ErrHookTaskNotExist.
  41. func IsErrHookTaskNotExist(err error) bool {
  42. _, ok := err.(ErrHookTaskNotExist)
  43. return ok
  44. }
  45. func (err ErrHookTaskNotExist) Error() string {
  46. return fmt.Sprintf("hook task does not exist [task: %d, hook: %d, uuid: %s]", err.TaskID, err.HookID, err.UUID)
  47. }
  48. func (err ErrHookTaskNotExist) Unwrap() error {
  49. return util.ErrNotExist
  50. }
  51. // HookContentType is the content type of a web hook
  52. type HookContentType int
  53. const (
  54. // ContentTypeJSON is a JSON payload for web hooks
  55. ContentTypeJSON HookContentType = iota + 1
  56. // ContentTypeForm is an url-encoded form payload for web hook
  57. ContentTypeForm
  58. )
  59. var hookContentTypes = map[string]HookContentType{
  60. "json": ContentTypeJSON,
  61. "form": ContentTypeForm,
  62. }
  63. // ToHookContentType returns HookContentType by given name.
  64. func ToHookContentType(name string) HookContentType {
  65. return hookContentTypes[name]
  66. }
  67. // HookTaskCleanupType is the type of cleanup to perform on hook_task
  68. type HookTaskCleanupType int
  69. const (
  70. // OlderThan hook_task rows will be cleaned up by the age of the row
  71. OlderThan HookTaskCleanupType = iota
  72. // PerWebhook hook_task rows will be cleaned up by leaving the most recent deliveries for each webhook
  73. PerWebhook
  74. )
  75. var hookTaskCleanupTypes = map[string]HookTaskCleanupType{
  76. "OlderThan": OlderThan,
  77. "PerWebhook": PerWebhook,
  78. }
  79. // ToHookTaskCleanupType returns HookTaskCleanupType by given name.
  80. func ToHookTaskCleanupType(name string) HookTaskCleanupType {
  81. return hookTaskCleanupTypes[name]
  82. }
  83. // Name returns the name of a given web hook's content type
  84. func (t HookContentType) Name() string {
  85. switch t {
  86. case ContentTypeJSON:
  87. return "json"
  88. case ContentTypeForm:
  89. return "form"
  90. }
  91. return ""
  92. }
  93. // IsValidHookContentType returns true if given name is a valid hook content type.
  94. func IsValidHookContentType(name string) bool {
  95. _, ok := hookContentTypes[name]
  96. return ok
  97. }
  98. // Webhook represents a web hook object.
  99. type Webhook struct {
  100. ID int64 `xorm:"pk autoincr"`
  101. RepoID int64 `xorm:"INDEX"` // An ID of 0 indicates either a default or system webhook
  102. OwnerID int64 `xorm:"INDEX"`
  103. IsSystemWebhook bool
  104. URL string `xorm:"url TEXT"`
  105. HTTPMethod string `xorm:"http_method"`
  106. ContentType HookContentType
  107. Secret string `xorm:"TEXT"`
  108. Events string `xorm:"TEXT"`
  109. *webhook_module.HookEvent `xorm:"-"`
  110. IsActive bool `xorm:"INDEX"`
  111. Type webhook_module.HookType `xorm:"VARCHAR(16) 'type'"`
  112. Meta string `xorm:"TEXT"` // store hook-specific attributes
  113. LastStatus webhook_module.HookStatus // Last delivery status
  114. // HeaderAuthorizationEncrypted should be accessed using HeaderAuthorization() and SetHeaderAuthorization()
  115. HeaderAuthorizationEncrypted string `xorm:"TEXT"`
  116. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  117. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  118. }
  119. func init() {
  120. db.RegisterModel(new(Webhook))
  121. }
  122. // AfterLoad updates the webhook object upon setting a column
  123. func (w *Webhook) AfterLoad() {
  124. w.HookEvent = &webhook_module.HookEvent{}
  125. if err := json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
  126. log.Error("Unmarshal[%d]: %v", w.ID, err)
  127. }
  128. }
  129. // History returns history of webhook by given conditions.
  130. func (w *Webhook) History(page int) ([]*HookTask, error) {
  131. return HookTasks(w.ID, page)
  132. }
  133. // UpdateEvent handles conversion from HookEvent to Events.
  134. func (w *Webhook) UpdateEvent() error {
  135. data, err := json.Marshal(w.HookEvent)
  136. w.Events = string(data)
  137. return err
  138. }
  139. // HasCreateEvent returns true if hook enabled create event.
  140. func (w *Webhook) HasCreateEvent() bool {
  141. return w.SendEverything ||
  142. (w.ChooseEvents && w.HookEvents.Create)
  143. }
  144. // HasDeleteEvent returns true if hook enabled delete event.
  145. func (w *Webhook) HasDeleteEvent() bool {
  146. return w.SendEverything ||
  147. (w.ChooseEvents && w.HookEvents.Delete)
  148. }
  149. // HasForkEvent returns true if hook enabled fork event.
  150. func (w *Webhook) HasForkEvent() bool {
  151. return w.SendEverything ||
  152. (w.ChooseEvents && w.HookEvents.Fork)
  153. }
  154. // HasIssuesEvent returns true if hook enabled issues event.
  155. func (w *Webhook) HasIssuesEvent() bool {
  156. return w.SendEverything ||
  157. (w.ChooseEvents && w.HookEvents.Issues)
  158. }
  159. // HasIssuesAssignEvent returns true if hook enabled issues assign event.
  160. func (w *Webhook) HasIssuesAssignEvent() bool {
  161. return w.SendEverything ||
  162. (w.ChooseEvents && w.HookEvents.IssueAssign)
  163. }
  164. // HasIssuesLabelEvent returns true if hook enabled issues label event.
  165. func (w *Webhook) HasIssuesLabelEvent() bool {
  166. return w.SendEverything ||
  167. (w.ChooseEvents && w.HookEvents.IssueLabel)
  168. }
  169. // HasIssuesMilestoneEvent returns true if hook enabled issues milestone event.
  170. func (w *Webhook) HasIssuesMilestoneEvent() bool {
  171. return w.SendEverything ||
  172. (w.ChooseEvents && w.HookEvents.IssueMilestone)
  173. }
  174. // HasIssueCommentEvent returns true if hook enabled issue_comment event.
  175. func (w *Webhook) HasIssueCommentEvent() bool {
  176. return w.SendEverything ||
  177. (w.ChooseEvents && w.HookEvents.IssueComment)
  178. }
  179. // HasPushEvent returns true if hook enabled push event.
  180. func (w *Webhook) HasPushEvent() bool {
  181. return w.PushOnly || w.SendEverything ||
  182. (w.ChooseEvents && w.HookEvents.Push)
  183. }
  184. // HasPullRequestEvent returns true if hook enabled pull request event.
  185. func (w *Webhook) HasPullRequestEvent() bool {
  186. return w.SendEverything ||
  187. (w.ChooseEvents && w.HookEvents.PullRequest)
  188. }
  189. // HasPullRequestAssignEvent returns true if hook enabled pull request assign event.
  190. func (w *Webhook) HasPullRequestAssignEvent() bool {
  191. return w.SendEverything ||
  192. (w.ChooseEvents && w.HookEvents.PullRequestAssign)
  193. }
  194. // HasPullRequestLabelEvent returns true if hook enabled pull request label event.
  195. func (w *Webhook) HasPullRequestLabelEvent() bool {
  196. return w.SendEverything ||
  197. (w.ChooseEvents && w.HookEvents.PullRequestLabel)
  198. }
  199. // HasPullRequestMilestoneEvent returns true if hook enabled pull request milestone event.
  200. func (w *Webhook) HasPullRequestMilestoneEvent() bool {
  201. return w.SendEverything ||
  202. (w.ChooseEvents && w.HookEvents.PullRequestMilestone)
  203. }
  204. // HasPullRequestCommentEvent returns true if hook enabled pull_request_comment event.
  205. func (w *Webhook) HasPullRequestCommentEvent() bool {
  206. return w.SendEverything ||
  207. (w.ChooseEvents && w.HookEvents.PullRequestComment)
  208. }
  209. // HasPullRequestApprovedEvent returns true if hook enabled pull request review event.
  210. func (w *Webhook) HasPullRequestApprovedEvent() bool {
  211. return w.SendEverything ||
  212. (w.ChooseEvents && w.HookEvents.PullRequestReview)
  213. }
  214. // HasPullRequestRejectedEvent returns true if hook enabled pull request review event.
  215. func (w *Webhook) HasPullRequestRejectedEvent() bool {
  216. return w.SendEverything ||
  217. (w.ChooseEvents && w.HookEvents.PullRequestReview)
  218. }
  219. // HasPullRequestReviewCommentEvent returns true if hook enabled pull request review event.
  220. func (w *Webhook) HasPullRequestReviewCommentEvent() bool {
  221. return w.SendEverything ||
  222. (w.ChooseEvents && w.HookEvents.PullRequestReview)
  223. }
  224. // HasPullRequestSyncEvent returns true if hook enabled pull request sync event.
  225. func (w *Webhook) HasPullRequestSyncEvent() bool {
  226. return w.SendEverything ||
  227. (w.ChooseEvents && w.HookEvents.PullRequestSync)
  228. }
  229. // HasWikiEvent returns true if hook enabled wiki event.
  230. func (w *Webhook) HasWikiEvent() bool {
  231. return w.SendEverything ||
  232. (w.ChooseEvents && w.HookEvent.Wiki)
  233. }
  234. // HasReleaseEvent returns if hook enabled release event.
  235. func (w *Webhook) HasReleaseEvent() bool {
  236. return w.SendEverything ||
  237. (w.ChooseEvents && w.HookEvents.Release)
  238. }
  239. // HasRepositoryEvent returns if hook enabled repository event.
  240. func (w *Webhook) HasRepositoryEvent() bool {
  241. return w.SendEverything ||
  242. (w.ChooseEvents && w.HookEvents.Repository)
  243. }
  244. // HasPackageEvent returns if hook enabled package event.
  245. func (w *Webhook) HasPackageEvent() bool {
  246. return w.SendEverything ||
  247. (w.ChooseEvents && w.HookEvents.Package)
  248. }
  249. // HasPullRequestReviewRequestEvent returns true if hook enabled pull request review request event.
  250. func (w *Webhook) HasPullRequestReviewRequestEvent() bool {
  251. return w.SendEverything ||
  252. (w.ChooseEvents && w.HookEvents.PullRequestReviewRequest)
  253. }
  254. // EventCheckers returns event checkers
  255. func (w *Webhook) EventCheckers() []struct {
  256. Has func() bool
  257. Type webhook_module.HookEventType
  258. } {
  259. return []struct {
  260. Has func() bool
  261. Type webhook_module.HookEventType
  262. }{
  263. {w.HasCreateEvent, webhook_module.HookEventCreate},
  264. {w.HasDeleteEvent, webhook_module.HookEventDelete},
  265. {w.HasForkEvent, webhook_module.HookEventFork},
  266. {w.HasPushEvent, webhook_module.HookEventPush},
  267. {w.HasIssuesEvent, webhook_module.HookEventIssues},
  268. {w.HasIssuesAssignEvent, webhook_module.HookEventIssueAssign},
  269. {w.HasIssuesLabelEvent, webhook_module.HookEventIssueLabel},
  270. {w.HasIssuesMilestoneEvent, webhook_module.HookEventIssueMilestone},
  271. {w.HasIssueCommentEvent, webhook_module.HookEventIssueComment},
  272. {w.HasPullRequestEvent, webhook_module.HookEventPullRequest},
  273. {w.HasPullRequestAssignEvent, webhook_module.HookEventPullRequestAssign},
  274. {w.HasPullRequestLabelEvent, webhook_module.HookEventPullRequestLabel},
  275. {w.HasPullRequestMilestoneEvent, webhook_module.HookEventPullRequestMilestone},
  276. {w.HasPullRequestCommentEvent, webhook_module.HookEventPullRequestComment},
  277. {w.HasPullRequestApprovedEvent, webhook_module.HookEventPullRequestReviewApproved},
  278. {w.HasPullRequestRejectedEvent, webhook_module.HookEventPullRequestReviewRejected},
  279. {w.HasPullRequestCommentEvent, webhook_module.HookEventPullRequestReviewComment},
  280. {w.HasPullRequestSyncEvent, webhook_module.HookEventPullRequestSync},
  281. {w.HasWikiEvent, webhook_module.HookEventWiki},
  282. {w.HasRepositoryEvent, webhook_module.HookEventRepository},
  283. {w.HasReleaseEvent, webhook_module.HookEventRelease},
  284. {w.HasPackageEvent, webhook_module.HookEventPackage},
  285. {w.HasPullRequestReviewRequestEvent, webhook_module.HookEventPullRequestReviewRequest},
  286. }
  287. }
  288. // EventsArray returns an array of hook events
  289. func (w *Webhook) EventsArray() []string {
  290. events := make([]string, 0, 7)
  291. for _, c := range w.EventCheckers() {
  292. if c.Has() {
  293. events = append(events, string(c.Type))
  294. }
  295. }
  296. return events
  297. }
  298. // HeaderAuthorization returns the decrypted Authorization header.
  299. // Not on the reference (*w), to be accessible on WebhooksNew.
  300. func (w Webhook) HeaderAuthorization() (string, error) {
  301. if w.HeaderAuthorizationEncrypted == "" {
  302. return "", nil
  303. }
  304. return secret.DecryptSecret(setting.SecretKey, w.HeaderAuthorizationEncrypted)
  305. }
  306. // SetHeaderAuthorization encrypts and sets the Authorization header.
  307. func (w *Webhook) SetHeaderAuthorization(cleartext string) error {
  308. if cleartext == "" {
  309. w.HeaderAuthorizationEncrypted = ""
  310. return nil
  311. }
  312. ciphertext, err := secret.EncryptSecret(setting.SecretKey, cleartext)
  313. if err != nil {
  314. return err
  315. }
  316. w.HeaderAuthorizationEncrypted = ciphertext
  317. return nil
  318. }
  319. // CreateWebhook creates a new web hook.
  320. func CreateWebhook(ctx context.Context, w *Webhook) error {
  321. w.Type = strings.TrimSpace(w.Type)
  322. return db.Insert(ctx, w)
  323. }
  324. // CreateWebhooks creates multiple web hooks
  325. func CreateWebhooks(ctx context.Context, ws []*Webhook) error {
  326. // xorm returns err "no element on slice when insert" for empty slices.
  327. if len(ws) == 0 {
  328. return nil
  329. }
  330. for i := 0; i < len(ws); i++ {
  331. ws[i].Type = strings.TrimSpace(ws[i].Type)
  332. }
  333. return db.Insert(ctx, ws)
  334. }
  335. // GetWebhookByID returns webhook of repository by given ID.
  336. func GetWebhookByID(ctx context.Context, id int64) (*Webhook, error) {
  337. bean := new(Webhook)
  338. has, err := db.GetEngine(ctx).ID(id).Get(bean)
  339. if err != nil {
  340. return nil, err
  341. } else if !has {
  342. return nil, ErrWebhookNotExist{ID: id}
  343. }
  344. return bean, nil
  345. }
  346. // GetWebhookByRepoID returns webhook of repository by given ID.
  347. func GetWebhookByRepoID(ctx context.Context, repoID, id int64) (*Webhook, error) {
  348. webhook := new(Webhook)
  349. has, err := db.GetEngine(ctx).Where("id=? AND repo_id=?", id, repoID).Get(webhook)
  350. if err != nil {
  351. return nil, err
  352. } else if !has {
  353. return nil, ErrWebhookNotExist{ID: id}
  354. }
  355. return webhook, nil
  356. }
  357. // GetWebhookByOwnerID returns webhook of a user or organization by given ID.
  358. func GetWebhookByOwnerID(ctx context.Context, ownerID, id int64) (*Webhook, error) {
  359. webhook := new(Webhook)
  360. has, err := db.GetEngine(ctx).Where("id=? AND owner_id=?", id, ownerID).Get(webhook)
  361. if err != nil {
  362. return nil, err
  363. } else if !has {
  364. return nil, ErrWebhookNotExist{ID: id}
  365. }
  366. return webhook, nil
  367. }
  368. // ListWebhookOptions are options to filter webhooks on ListWebhooksByOpts
  369. type ListWebhookOptions struct {
  370. db.ListOptions
  371. RepoID int64
  372. OwnerID int64
  373. IsActive util.OptionalBool
  374. }
  375. func (opts *ListWebhookOptions) toCond() builder.Cond {
  376. cond := builder.NewCond()
  377. if opts.RepoID != 0 {
  378. cond = cond.And(builder.Eq{"webhook.repo_id": opts.RepoID})
  379. }
  380. if opts.OwnerID != 0 {
  381. cond = cond.And(builder.Eq{"webhook.owner_id": opts.OwnerID})
  382. }
  383. if !opts.IsActive.IsNone() {
  384. cond = cond.And(builder.Eq{"webhook.is_active": opts.IsActive.IsTrue()})
  385. }
  386. return cond
  387. }
  388. // ListWebhooksByOpts return webhooks based on options
  389. func ListWebhooksByOpts(ctx context.Context, opts *ListWebhookOptions) ([]*Webhook, error) {
  390. sess := db.GetEngine(ctx).Where(opts.toCond())
  391. if opts.Page != 0 {
  392. sess = db.SetSessionPagination(sess, opts)
  393. webhooks := make([]*Webhook, 0, opts.PageSize)
  394. err := sess.Find(&webhooks)
  395. return webhooks, err
  396. }
  397. webhooks := make([]*Webhook, 0, 10)
  398. err := sess.Find(&webhooks)
  399. return webhooks, err
  400. }
  401. // CountWebhooksByOpts count webhooks based on options and ignore pagination
  402. func CountWebhooksByOpts(opts *ListWebhookOptions) (int64, error) {
  403. return db.GetEngine(db.DefaultContext).Where(opts.toCond()).Count(&Webhook{})
  404. }
  405. // UpdateWebhook updates information of webhook.
  406. func UpdateWebhook(w *Webhook) error {
  407. _, err := db.GetEngine(db.DefaultContext).ID(w.ID).AllCols().Update(w)
  408. return err
  409. }
  410. // UpdateWebhookLastStatus updates last status of webhook.
  411. func UpdateWebhookLastStatus(w *Webhook) error {
  412. _, err := db.GetEngine(db.DefaultContext).ID(w.ID).Cols("last_status").Update(w)
  413. return err
  414. }
  415. // DeleteWebhookByID uses argument bean as query condition,
  416. // ID must be specified and do not assign unnecessary fields.
  417. func DeleteWebhookByID(ctx context.Context, id int64) (err error) {
  418. ctx, committer, err := db.TxContext(ctx)
  419. if err != nil {
  420. return err
  421. }
  422. defer committer.Close()
  423. if count, err := db.DeleteByID(ctx, id, new(Webhook)); err != nil {
  424. return err
  425. } else if count == 0 {
  426. return ErrWebhookNotExist{ID: id}
  427. } else if _, err = db.DeleteByBean(ctx, &HookTask{HookID: id}); err != nil {
  428. return err
  429. }
  430. return committer.Commit()
  431. }
  432. // DeleteWebhookByRepoID deletes webhook of repository by given ID.
  433. func DeleteWebhookByRepoID(ctx context.Context, repoID, id int64) error {
  434. if _, err := GetWebhookByRepoID(ctx, repoID, id); err != nil {
  435. return err
  436. }
  437. return DeleteWebhookByID(ctx, id)
  438. }
  439. // DeleteWebhookByOwnerID deletes webhook of a user or organization by given ID.
  440. func DeleteWebhookByOwnerID(ctx context.Context, ownerID, id int64) error {
  441. if _, err := GetWebhookByOwnerID(ctx, ownerID, id); err != nil {
  442. return err
  443. }
  444. return DeleteWebhookByID(ctx, id)
  445. }