github_incoming.go 12 KB

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