github_incoming.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. package webhook
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "github.com/bradleyfalzon/ghinstallation/v2"
  11. "github.com/google/go-github/v41/github"
  12. "github.com/porter-dev/porter/api/server/authz"
  13. "github.com/porter-dev/porter/api/server/handlers"
  14. "github.com/porter-dev/porter/api/server/shared"
  15. "github.com/porter-dev/porter/api/server/shared/apierrors"
  16. "github.com/porter-dev/porter/api/server/shared/config"
  17. "github.com/porter-dev/porter/api/server/shared/requestutils"
  18. "github.com/porter-dev/porter/api/types"
  19. "github.com/porter-dev/porter/internal/models"
  20. "gorm.io/gorm"
  21. )
  22. type GithubIncomingWebhookHandler struct {
  23. handlers.PorterHandlerReadWriter
  24. authz.KubernetesAgentGetter
  25. }
  26. func NewGithubIncomingWebhookHandler(
  27. config *config.Config,
  28. decoderValidator shared.RequestDecoderValidator,
  29. writer shared.ResultWriter,
  30. ) *GithubIncomingWebhookHandler {
  31. return &GithubIncomingWebhookHandler{
  32. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  33. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  34. }
  35. }
  36. func (c *GithubIncomingWebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  37. payload, err := github.ValidatePayload(r, []byte(c.Config().ServerConf.GithubIncomingWebhookSecret))
  38. if err != nil {
  39. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error validating webhook payload: %w", err)))
  40. return
  41. }
  42. event, err := github.ParseWebHook(github.WebHookType(r), payload)
  43. if err != nil {
  44. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error parsing webhook: %w", err)))
  45. return
  46. }
  47. switch event := event.(type) {
  48. case *github.PullRequestEvent:
  49. err = c.processPullRequestEvent(event, r)
  50. if err != nil {
  51. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error processing pull request webhook event: %w", err)))
  52. return
  53. }
  54. case *github.PushEvent:
  55. err = c.processPushEvent(event, r)
  56. if err != nil {
  57. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error processing push webhook event: %w", err)))
  58. return
  59. }
  60. }
  61. }
  62. func (c *GithubIncomingWebhookHandler) processPullRequestEvent(event *github.PullRequestEvent, r *http.Request) error {
  63. // get the webhook id from the request
  64. webhookID, reqErr := requestutils.GetURLParamString(r, types.URLParamIncomingWebhookID)
  65. if reqErr != nil {
  66. return fmt.Errorf(reqErr.Error())
  67. }
  68. owner := event.GetRepo().GetOwner().GetLogin()
  69. repo := event.GetRepo().GetName()
  70. env, err := c.Repo().Environment().ReadEnvironmentByWebhookIDOwnerRepoName(webhookID, owner, repo)
  71. if err != nil {
  72. if errors.Is(err, gorm.ErrRecordNotFound) {
  73. return nil
  74. }
  75. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] error reading environment: %w", webhookID, owner, repo, err)
  76. }
  77. if event.GetPullRequest() == nil {
  78. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] incoming webhook does not have pull request information: %w",
  79. webhookID, owner, repo, err)
  80. }
  81. envType := env.ToEnvironmentType()
  82. if len(envType.GitRepoBranches) > 0 {
  83. found := false
  84. for _, br := range envType.GitRepoBranches {
  85. if br == event.GetPullRequest().GetHead().GetRef() {
  86. found = true
  87. break
  88. }
  89. }
  90. if !found {
  91. return nil
  92. }
  93. } else if len(envType.GitDeployBranches) > 0 {
  94. // if the pull request's head branch is in the list of deploy branches
  95. // then we ignore it to avoid a double deploy
  96. found := false
  97. for _, br := range envType.GitDeployBranches {
  98. if br == event.GetPullRequest().GetHead().GetRef() {
  99. found = true
  100. break
  101. }
  102. }
  103. if found {
  104. return nil
  105. }
  106. }
  107. // create deployment on GitHub API
  108. client, err := getGithubClientFromEnvironment(c.Config(), env)
  109. if err != nil {
  110. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  111. "error getting github client: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  112. }
  113. if env.Mode == "auto" && event.GetAction() == "opened" {
  114. depl := &models.Deployment{
  115. EnvironmentID: env.ID,
  116. Namespace: "",
  117. Status: types.DeploymentStatusCreating,
  118. PullRequestID: uint(event.GetPullRequest().GetNumber()),
  119. PRName: event.GetPullRequest().GetTitle(),
  120. RepoName: repo,
  121. RepoOwner: owner,
  122. CommitSHA: event.GetPullRequest().GetHead().GetSHA()[:7],
  123. PRBranchFrom: event.GetPullRequest().GetHead().GetRef(),
  124. PRBranchInto: event.GetPullRequest().GetBase().GetRef(),
  125. }
  126. _, err = c.Repo().Environment().CreateDeployment(depl)
  127. if err != nil {
  128. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  129. "error creating new deployment: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  130. }
  131. _, err := client.Actions.CreateWorkflowDispatchEventByFileName(
  132. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  133. github.CreateWorkflowDispatchEventRequest{
  134. Ref: event.GetPullRequest().GetHead().GetRef(),
  135. Inputs: map[string]interface{}{
  136. "pr_number": strconv.FormatUint(uint64(event.GetPullRequest().GetNumber()), 10),
  137. "pr_title": event.GetPullRequest().GetTitle(),
  138. "pr_branch_from": event.GetPullRequest().GetHead().GetRef(),
  139. "pr_branch_into": event.GetPullRequest().GetBase().GetRef(),
  140. },
  141. },
  142. )
  143. if err != nil {
  144. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  145. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  146. }
  147. } else if event.GetAction() == "synchronize" || event.GetAction() == "closed" || event.GetAction() == "edited" {
  148. depl, err := c.Repo().Environment().ReadDeploymentByGitDetails(
  149. env.ID, owner, repo, uint(event.GetPullRequest().GetNumber()),
  150. )
  151. if err != nil {
  152. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  153. "error reading deployment: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  154. }
  155. if depl.Status == types.DeploymentStatusInactive {
  156. return nil
  157. }
  158. if event.GetAction() == "synchronize" {
  159. _, err := client.Actions.CreateWorkflowDispatchEventByFileName(
  160. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  161. github.CreateWorkflowDispatchEventRequest{
  162. Ref: event.GetPullRequest().GetHead().GetRef(),
  163. Inputs: map[string]interface{}{
  164. "pr_number": strconv.FormatUint(uint64(event.GetPullRequest().GetNumber()), 10),
  165. "pr_title": event.GetPullRequest().GetTitle(),
  166. "pr_branch_from": event.GetPullRequest().GetHead().GetRef(),
  167. "pr_branch_into": event.GetPullRequest().GetBase().GetRef(),
  168. },
  169. },
  170. )
  171. if err != nil {
  172. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  173. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, depl.ID,
  174. event.GetPullRequest().GetNumber(), err)
  175. }
  176. } else if event.GetAction() == "closed" {
  177. // check for already running workflows we should be cancelling
  178. var wg sync.WaitGroup
  179. statuses := []string{"in_progress", "queued", "requested", "waiting"}
  180. chanErr := fmt.Errorf("")
  181. wg.Add(len(statuses))
  182. for _, status := range statuses {
  183. go func(status string) {
  184. defer wg.Done()
  185. runs, _, err := client.Actions.ListWorkflowRunsByFileName(
  186. context.Background(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  187. &github.ListWorkflowRunsOptions{
  188. Branch: event.GetPullRequest().GetHead().GetRef(),
  189. Status: status,
  190. },
  191. )
  192. if err == nil {
  193. for _, run := range runs.WorkflowRuns {
  194. resp, err := client.Actions.CancelWorkflowRunByID(context.Background(), owner, repo, run.GetID())
  195. if err != nil && resp.StatusCode != http.StatusAccepted {
  196. // the go library we are using returns a 202 Accepted status as an error
  197. // in this case, we should rule this out as an error
  198. chanErr = fmt.Errorf("%s: error cancelling %s: %w", chanErr.Error(), run.GetHTMLURL(), err)
  199. }
  200. }
  201. } else {
  202. chanErr = fmt.Errorf("%s: error listing workflows for status %s: %w", chanErr.Error(), status, err)
  203. }
  204. }(status)
  205. }
  206. wg.Wait()
  207. err = c.deleteDeployment(r, depl, env, client)
  208. if err != nil {
  209. deleteErr := fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  210. "error deleting deployment: %w", webhookID, owner, repo, env.ID, depl.ID, event.GetPullRequest().GetNumber(), err)
  211. if chanErr.Error() != "" {
  212. deleteErr = fmt.Errorf("%s. errors found while trying to cancel active workflow runs %w", deleteErr.Error(), chanErr)
  213. }
  214. return deleteErr
  215. } else if chanErr.Error() != "" {
  216. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  217. "deployment deleted but errors found while trying to cancel active workflow runs %w", webhookID, owner, repo, env.ID, depl.ID,
  218. event.GetPullRequest().GetNumber(), chanErr)
  219. }
  220. } else if event.GetChanges() != nil {
  221. shouldUpdate := false
  222. if event.GetChanges().GetTitle() != nil && event.GetPullRequest().GetTitle() != depl.PRName {
  223. depl.PRName = event.GetPullRequest().GetTitle()
  224. shouldUpdate = true
  225. }
  226. if event.GetChanges().GetBase() != nil && event.GetChanges().GetBase().GetRef() != nil && event.GetPullRequest().GetBase().GetRef() != depl.PRBranchInto {
  227. depl.PRBranchInto = event.GetPullRequest().GetBase().GetRef()
  228. shouldUpdate = true
  229. }
  230. if shouldUpdate {
  231. _, err := c.Repo().Environment().UpdateDeployment(depl)
  232. if err != nil {
  233. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  234. "error updating deployment to reflect changes in the pull request %w", webhookID, owner, repo, env.ID, depl.ID,
  235. event.GetPullRequest().GetNumber(), err)
  236. }
  237. }
  238. }
  239. }
  240. return nil
  241. }
  242. func (c *GithubIncomingWebhookHandler) deleteDeployment(
  243. r *http.Request,
  244. depl *models.Deployment,
  245. env *models.Environment,
  246. client *github.Client,
  247. ) error {
  248. cluster, err := c.Repo().Cluster().ReadCluster(env.ProjectID, env.ClusterID)
  249. if err != nil {
  250. return fmt.Errorf("[projectID: %d, clusterID: %d] error reading cluster when deleting existing deployment: %w",
  251. env.ProjectID, env.ClusterID, err)
  252. }
  253. agent, err := c.GetAgent(r, cluster, "")
  254. if err != nil {
  255. return err
  256. }
  257. // make sure we do not delete any kubernetes "system" namespaces
  258. if !isSystemNamespace(depl.Namespace) {
  259. err = agent.DeleteNamespace(depl.Namespace)
  260. if err != nil {
  261. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error deleting namespace '%s': %w",
  262. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, depl.Namespace, err)
  263. }
  264. }
  265. // Create new deployment status to indicate deployment is ready
  266. state := "inactive"
  267. deploymentStatusRequest := github.DeploymentStatusRequest{
  268. State: &state,
  269. }
  270. client.Repositories.CreateDeploymentStatus(
  271. context.Background(),
  272. env.GitRepoOwner,
  273. env.GitRepoName,
  274. depl.GHDeploymentID,
  275. &deploymentStatusRequest,
  276. )
  277. _, err = c.Repo().Environment().DeleteDeployment(depl)
  278. if err != nil {
  279. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error updating deployment: %w",
  280. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, err)
  281. }
  282. return nil
  283. }
  284. func (c *GithubIncomingWebhookHandler) processPushEvent(event *github.PushEvent, r *http.Request) error {
  285. if !strings.HasPrefix(event.GetRef(), "refs/heads/") {
  286. return nil
  287. }
  288. // get the webhook id from the request
  289. webhookID, reqErr := requestutils.GetURLParamString(r, types.URLParamIncomingWebhookID)
  290. if reqErr != nil {
  291. return fmt.Errorf(reqErr.Error())
  292. }
  293. owner := event.GetRepo().GetOwner().GetLogin()
  294. repo := event.GetRepo().GetName()
  295. env, err := c.Repo().Environment().ReadEnvironmentByWebhookIDOwnerRepoName(webhookID, owner, repo)
  296. if err != nil {
  297. if errors.Is(err, gorm.ErrRecordNotFound) {
  298. return nil
  299. }
  300. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] error reading environment: %w", webhookID, owner, repo, err)
  301. }
  302. envType := env.ToEnvironmentType()
  303. if len(envType.GitDeployBranches) == 0 {
  304. return nil
  305. }
  306. branch := strings.TrimPrefix(event.GetRef(), "refs/heads/")
  307. found := false
  308. for _, br := range envType.GitDeployBranches {
  309. if br == branch {
  310. found = true
  311. break
  312. }
  313. }
  314. if !found {
  315. return nil
  316. }
  317. client, err := getGithubClientFromEnvironment(c.Config(), env)
  318. if err != nil {
  319. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] error creating github client: %w", webhookID, owner, repo, err)
  320. }
  321. var deplID uint
  322. depl, err := c.Repo().Environment().ReadDeploymentForBranch(env.ID, owner, repo, branch)
  323. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  324. depl, err := c.Repo().Environment().CreateDeployment(&models.Deployment{
  325. EnvironmentID: env.ID,
  326. Status: types.DeploymentStatusCreating,
  327. PRName: fmt.Sprintf("Deployment for branch %s", branch),
  328. RepoName: repo,
  329. RepoOwner: owner,
  330. CommitSHA: event.GetAfter()[:7],
  331. PRBranchFrom: branch,
  332. PRBranchInto: branch,
  333. })
  334. if err != nil {
  335. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, branch: %s] "+
  336. "error creating new deployment: %w", webhookID, owner, repo, env.ID, branch, err)
  337. }
  338. deplID = depl.ID
  339. } else if err != nil {
  340. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, branch: %s] "+
  341. "error reading deployment: %w", webhookID, owner, repo, env.ID, branch, err)
  342. } else {
  343. deplID = depl.ID
  344. }
  345. // FIXME: we should case on if env mode is auto or manual
  346. _, err = client.Actions.CreateWorkflowDispatchEventByFileName(
  347. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  348. github.CreateWorkflowDispatchEventRequest{
  349. Ref: branch,
  350. Inputs: map[string]interface{}{
  351. "pr_number": fmt.Sprintf("%d", deplID),
  352. "pr_title": fmt.Sprintf("Deployment for branch %s", branch),
  353. "pr_branch_from": branch,
  354. "pr_branch_into": branch,
  355. },
  356. },
  357. )
  358. if err != nil {
  359. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, branch: %s] "+
  360. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, branch, err)
  361. }
  362. return nil
  363. }
  364. func isSystemNamespace(namespace string) bool {
  365. return namespace == "cert-manager" || namespace == "ingress-nginx" ||
  366. namespace == "kube-node-lease" || namespace == "kube-public" ||
  367. namespace == "kube-system" || namespace == "monitoring" ||
  368. namespace == "porter-agent-system" || namespace == "default" ||
  369. namespace == "ingress-nginx-private"
  370. }
  371. func getGithubClientFromEnvironment(config *config.Config, env *models.Environment) (*github.Client, error) {
  372. // get the github app client
  373. ghAppId, err := strconv.Atoi(config.ServerConf.GithubAppID)
  374. if err != nil {
  375. return nil, err
  376. }
  377. // authenticate as github app installation
  378. itr, err := ghinstallation.NewKeyFromFile(
  379. http.DefaultTransport,
  380. int64(ghAppId),
  381. int64(env.GitInstallationID),
  382. config.ServerConf.GithubAppSecretPath,
  383. )
  384. if err != nil {
  385. return nil, err
  386. }
  387. return github.NewClient(&http.Client{Transport: itr}), nil
  388. }