github_incoming.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. }
  55. }
  56. func (c *GithubIncomingWebhookHandler) processPullRequestEvent(event *github.PullRequestEvent, r *http.Request) error {
  57. // get the webhook id from the request
  58. webhookID, reqErr := requestutils.GetURLParamString(r, types.URLParamIncomingWebhookID)
  59. if reqErr != nil {
  60. return fmt.Errorf(reqErr.Error())
  61. }
  62. owner := event.GetRepo().GetOwner().GetLogin()
  63. repo := event.GetRepo().GetName()
  64. env, err := c.Repo().Environment().ReadEnvironmentByWebhookIDOwnerRepoName(webhookID, owner, repo)
  65. if err != nil {
  66. if errors.Is(err, gorm.ErrRecordNotFound) {
  67. return nil
  68. }
  69. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] error reading environment: %w", webhookID, owner, repo, err)
  70. }
  71. if event.GetPullRequest() == nil {
  72. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] incoming webhook does not have pull request information: %w",
  73. webhookID, owner, repo, err)
  74. }
  75. // create deployment on GitHub API
  76. client, err := getGithubClientFromEnvironment(c.Config(), env)
  77. if err != nil {
  78. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  79. "error getting github client: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  80. }
  81. if env.Mode == "auto" && event.GetAction() == "opened" {
  82. depl := &models.Deployment{
  83. EnvironmentID: env.ID,
  84. Namespace: fmt.Sprintf("pr-%d-%s", event.GetPullRequest().GetNumber(),
  85. strings.ToLower(strings.ReplaceAll(repo, "_", "-"))),
  86. Status: types.DeploymentStatusCreating,
  87. PullRequestID: uint(event.GetPullRequest().GetNumber()),
  88. PRName: event.GetPullRequest().GetTitle(),
  89. RepoName: repo,
  90. RepoOwner: owner,
  91. CommitSHA: event.GetPullRequest().GetHead().GetSHA()[:7],
  92. PRBranchFrom: event.GetPullRequest().GetHead().GetRef(),
  93. PRBranchInto: event.GetPullRequest().GetBase().GetRef(),
  94. }
  95. _, err = c.Repo().Environment().CreateDeployment(depl)
  96. if err != nil {
  97. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  98. "error creating new deployment: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  99. }
  100. cluster, err := c.Repo().Cluster().ReadCluster(env.ProjectID, env.ClusterID)
  101. if err != nil {
  102. return fmt.Errorf("[projectID: %d, clusterID: %d] error reading cluster when creating new deployment: %w",
  103. env.ProjectID, env.ClusterID, err)
  104. }
  105. // create the backing namespace
  106. agent, err := c.GetAgent(r, cluster, "")
  107. if err != nil {
  108. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  109. "error getting k8s agent: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  110. }
  111. _, err = agent.CreateNamespace(depl.Namespace)
  112. if err != nil {
  113. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  114. "error creating k8s namespace: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  115. }
  116. _, err = client.Actions.CreateWorkflowDispatchEventByFileName(
  117. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  118. github.CreateWorkflowDispatchEventRequest{
  119. Ref: event.GetPullRequest().GetHead().GetRef(),
  120. Inputs: map[string]interface{}{
  121. "pr_number": strconv.FormatUint(uint64(event.GetPullRequest().GetNumber()), 10),
  122. "pr_title": event.GetPullRequest().GetTitle(),
  123. "pr_branch_from": event.GetPullRequest().GetHead().GetRef(),
  124. "pr_branch_into": event.GetPullRequest().GetBase().GetRef(),
  125. },
  126. },
  127. )
  128. if err != nil {
  129. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  130. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  131. }
  132. } else if event.GetAction() == "synchronize" || event.GetAction() == "closed" || event.GetAction() == "edited" {
  133. depl, err := c.Repo().Environment().ReadDeploymentByGitDetails(
  134. env.ID, owner, repo, uint(event.GetPullRequest().GetNumber()),
  135. )
  136. if err != nil {
  137. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  138. "error reading deployment: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  139. }
  140. if depl.Status == types.DeploymentStatusInactive {
  141. return nil
  142. }
  143. if event.GetAction() == "synchronize" {
  144. _, err := client.Actions.CreateWorkflowDispatchEventByFileName(
  145. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  146. github.CreateWorkflowDispatchEventRequest{
  147. Ref: event.GetPullRequest().GetHead().GetRef(),
  148. Inputs: map[string]interface{}{
  149. "pr_number": strconv.FormatUint(uint64(event.GetPullRequest().GetNumber()), 10),
  150. "pr_title": event.GetPullRequest().GetTitle(),
  151. "pr_branch_from": event.GetPullRequest().GetHead().GetRef(),
  152. "pr_branch_into": event.GetPullRequest().GetBase().GetRef(),
  153. },
  154. },
  155. )
  156. if err != nil {
  157. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  158. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, depl.ID,
  159. event.GetPullRequest().GetNumber(), err)
  160. }
  161. } else if event.GetAction() == "closed" {
  162. // check for already running workflows we should be cancelling
  163. var wg sync.WaitGroup
  164. statuses := []string{"in_progress", "queued", "requested", "waiting"}
  165. chanErr := fmt.Errorf("")
  166. wg.Add(len(statuses))
  167. for _, status := range statuses {
  168. go func(status string) {
  169. defer wg.Done()
  170. runs, _, err := client.Actions.ListWorkflowRunsByFileName(
  171. context.Background(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  172. &github.ListWorkflowRunsOptions{
  173. Branch: event.GetPullRequest().GetHead().GetRef(),
  174. Status: status,
  175. },
  176. )
  177. if err == nil {
  178. for _, run := range runs.WorkflowRuns {
  179. resp, err := client.Actions.CancelWorkflowRunByID(context.Background(), owner, repo, run.GetID())
  180. if err != nil && resp.StatusCode != http.StatusAccepted {
  181. // the go library we are using returns a 202 Accepted status as an error
  182. // in this case, we should rule this out as an error
  183. chanErr = fmt.Errorf("%s: error cancelling %s: %w", chanErr.Error(), run.GetHTMLURL(), err)
  184. }
  185. }
  186. } else {
  187. chanErr = fmt.Errorf("%s: error listing workflows for status %s: %w", chanErr.Error(), status, err)
  188. }
  189. }(status)
  190. }
  191. wg.Wait()
  192. err = c.deleteDeployment(r, depl, env, client)
  193. if err != nil {
  194. deleteErr := fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  195. "error deleting deployment: %w", webhookID, owner, repo, env.ID, depl.ID, event.GetPullRequest().GetNumber(), err)
  196. if chanErr.Error() != "" {
  197. deleteErr = fmt.Errorf("%s. errors found while trying to cancel active workflow runs %w", deleteErr.Error(), chanErr)
  198. }
  199. return deleteErr
  200. } else if chanErr.Error() != "" {
  201. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  202. "deployment deleted but errors found while trying to cancel active workflow runs %w", webhookID, owner, repo, env.ID, depl.ID,
  203. event.GetPullRequest().GetNumber(), chanErr)
  204. }
  205. } else if event.GetChanges() != nil {
  206. shouldUpdate := false
  207. if event.GetChanges().GetTitle() != nil && event.GetPullRequest().GetTitle() != depl.PRName {
  208. depl.PRName = event.GetPullRequest().GetTitle()
  209. shouldUpdate = true
  210. }
  211. if event.GetChanges().GetBase() != nil && event.GetChanges().GetBase().GetRef() != nil && event.GetPullRequest().GetBase().GetRef() != depl.PRBranchInto {
  212. depl.PRBranchInto = event.GetPullRequest().GetBase().GetRef()
  213. shouldUpdate = true
  214. }
  215. if shouldUpdate {
  216. _, err := c.Repo().Environment().UpdateDeployment(depl)
  217. if err != nil {
  218. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  219. "error updating deployment to reflect changes in the pull request %w", webhookID, owner, repo, env.ID, depl.ID,
  220. event.GetPullRequest().GetNumber(), err)
  221. }
  222. }
  223. }
  224. }
  225. return nil
  226. }
  227. func (c *GithubIncomingWebhookHandler) deleteDeployment(
  228. r *http.Request,
  229. depl *models.Deployment,
  230. env *models.Environment,
  231. client *github.Client,
  232. ) error {
  233. cluster, err := c.Repo().Cluster().ReadCluster(env.ProjectID, env.ClusterID)
  234. if err != nil {
  235. return fmt.Errorf("[projectID: %d, clusterID: %d] error reading cluster when deleting existing deployment: %w",
  236. env.ProjectID, env.ClusterID, err)
  237. }
  238. agent, err := c.GetAgent(r, cluster, "")
  239. if err != nil {
  240. return err
  241. }
  242. // make sure we don't delete default or kube-system by checking for prefix, for now
  243. if strings.Contains(depl.Namespace, "pr-") {
  244. err = agent.DeleteNamespace(depl.Namespace)
  245. if err != nil {
  246. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error deleting namespace '%s': %w",
  247. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, depl.Namespace, err)
  248. }
  249. }
  250. // Create new deployment status to indicate deployment is ready
  251. state := "inactive"
  252. deploymentStatusRequest := github.DeploymentStatusRequest{
  253. State: &state,
  254. }
  255. client.Repositories.CreateDeploymentStatus(
  256. context.Background(),
  257. env.GitRepoOwner,
  258. env.GitRepoName,
  259. depl.GHDeploymentID,
  260. &deploymentStatusRequest,
  261. )
  262. depl.Status = types.DeploymentStatusInactive
  263. // update the deployment to mark it inactive
  264. _, err = c.Repo().Environment().UpdateDeployment(depl)
  265. if err != nil {
  266. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error updating deployment: %w",
  267. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, err)
  268. }
  269. return nil
  270. }
  271. func getGithubClientFromEnvironment(config *config.Config, env *models.Environment) (*github.Client, error) {
  272. // get the github app client
  273. ghAppId, err := strconv.Atoi(config.ServerConf.GithubAppID)
  274. if err != nil {
  275. return nil, err
  276. }
  277. // authenticate as github app installation
  278. itr, err := ghinstallation.NewKeyFromFile(
  279. http.DefaultTransport,
  280. int64(ghAppId),
  281. int64(env.GitInstallationID),
  282. config.ServerConf.GithubAppSecretPath,
  283. )
  284. if err != nil {
  285. return nil, err
  286. }
  287. return github.NewClient(&http.Client{Transport: itr}), nil
  288. }