github_incoming.go 12 KB

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