github_incoming.go 11 KB

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