github_incoming.go 11 KB

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