github_incoming.go 12 KB

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