github_incoming.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package webhook
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "github.com/bradleyfalzon/ghinstallation/v2"
  9. "github.com/google/go-github/v41/github"
  10. "github.com/porter-dev/porter/api/server/authz"
  11. "github.com/porter-dev/porter/api/server/handlers"
  12. "github.com/porter-dev/porter/api/server/shared"
  13. "github.com/porter-dev/porter/api/server/shared/apierrors"
  14. "github.com/porter-dev/porter/api/server/shared/config"
  15. "github.com/porter-dev/porter/api/server/shared/requestutils"
  16. "github.com/porter-dev/porter/api/types"
  17. "github.com/porter-dev/porter/internal/models"
  18. )
  19. type GithubIncomingWebhookHandler struct {
  20. handlers.PorterHandlerReadWriter
  21. authz.KubernetesAgentGetter
  22. }
  23. func NewGithubIncomingWebhookHandler(
  24. config *config.Config,
  25. decoderValidator shared.RequestDecoderValidator,
  26. writer shared.ResultWriter,
  27. ) *GithubIncomingWebhookHandler {
  28. return &GithubIncomingWebhookHandler{
  29. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  30. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  31. }
  32. }
  33. func (c *GithubIncomingWebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  34. payload, err := github.ValidatePayload(r, []byte(c.Config().ServerConf.GithubIncomingWebhookSecret))
  35. if err != nil {
  36. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error validating webhook payload: %w", err)))
  37. return
  38. }
  39. event, err := github.ParseWebHook(github.WebHookType(r), payload)
  40. if err != nil {
  41. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error parsing webhook: %w", err)))
  42. return
  43. }
  44. switch event := event.(type) {
  45. case *github.PullRequestEvent:
  46. err = c.processPullRequestEvent(event, r)
  47. if err != nil {
  48. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error processing pull request webhook event: %w", err)))
  49. return
  50. }
  51. }
  52. }
  53. func (c *GithubIncomingWebhookHandler) processPullRequestEvent(event *github.PullRequestEvent, r *http.Request) error {
  54. // get the webhook id from the request
  55. webhookID, reqErr := requestutils.GetURLParamString(r, types.URLParamIncomingWebhookID)
  56. if reqErr != nil {
  57. return fmt.Errorf(reqErr.Error())
  58. }
  59. owner := event.GetRepo().GetOwner().GetLogin()
  60. repo := event.GetRepo().GetName()
  61. env, err := c.Repo().Environment().ReadEnvironmentByWebhookIDOwnerRepoName(webhookID, owner, repo)
  62. if err != nil {
  63. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] error reading environment: %w", webhookID, owner, repo, err)
  64. }
  65. if event.GetPullRequest() == nil {
  66. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] incoming webhook does not have pull request information: %w",
  67. webhookID, owner, repo, err)
  68. }
  69. // create deployment on GitHub API
  70. client, err := getGithubClientFromEnvironment(c.Config(), env)
  71. if err != nil {
  72. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  73. "error getting github client: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  74. }
  75. if env.Mode == "auto" && event.GetAction() == "opened" {
  76. depl := &models.Deployment{
  77. EnvironmentID: env.ID,
  78. Namespace: fmt.Sprintf("pr-%d-%s", event.GetPullRequest().GetNumber(),
  79. strings.ToLower(strings.ReplaceAll(repo, "_", "-"))),
  80. Status: types.DeploymentStatusCreating,
  81. PullRequestID: uint(event.GetPullRequest().GetNumber()),
  82. PRName: event.GetPullRequest().GetTitle(),
  83. RepoName: repo,
  84. RepoOwner: owner,
  85. CommitSHA: event.GetPullRequest().GetHead().GetSHA()[:7],
  86. PRBranchFrom: event.GetPullRequest().GetHead().GetRef(),
  87. PRBranchInto: event.GetPullRequest().GetBase().GetRef(),
  88. }
  89. _, err = c.Repo().Environment().CreateDeployment(depl)
  90. if err != nil {
  91. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  92. "error creating new deployment: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  93. }
  94. cluster, err := c.Repo().Cluster().ReadCluster(env.ProjectID, env.ClusterID)
  95. if err != nil {
  96. return fmt.Errorf("[projectID: %d, clusterID: %d] error reading cluster when creating new deployment: %w",
  97. env.ProjectID, env.ClusterID, err)
  98. }
  99. // create the backing namespace
  100. agent, err := c.GetAgent(r, cluster, "")
  101. if err != nil {
  102. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  103. "error getting k8s agent: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  104. }
  105. _, err = agent.CreateNamespace(depl.Namespace)
  106. if err != nil {
  107. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  108. "error creating k8s namespace: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  109. }
  110. _, err = client.Actions.CreateWorkflowDispatchEventByFileName(
  111. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  112. github.CreateWorkflowDispatchEventRequest{
  113. Ref: event.GetPullRequest().GetHead().GetRef(),
  114. Inputs: map[string]interface{}{
  115. "pr_number": strconv.FormatUint(uint64(event.GetPullRequest().GetNumber()), 10),
  116. "pr_title": event.GetPullRequest().GetTitle(),
  117. "pr_branch_from": event.GetPullRequest().GetHead().GetRef(),
  118. "pr_branch_into": event.GetPullRequest().GetBase().GetRef(),
  119. },
  120. },
  121. )
  122. if err != nil {
  123. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  124. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  125. }
  126. } else if event.GetAction() == "synchronize" || event.GetAction() == "closed" {
  127. depl, err := c.Repo().Environment().ReadDeploymentByGitDetails(
  128. env.ID, owner, repo, uint(event.GetPullRequest().GetNumber()),
  129. )
  130. if err != nil {
  131. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  132. "error reading deployment: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  133. }
  134. if depl.Status == types.DeploymentStatusInactive {
  135. return nil
  136. }
  137. if event.GetAction() == "synchronize" {
  138. _, err := client.Actions.CreateWorkflowDispatchEventByFileName(
  139. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  140. github.CreateWorkflowDispatchEventRequest{
  141. Ref: event.GetPullRequest().GetHead().GetRef(),
  142. Inputs: map[string]interface{}{
  143. "pr_number": strconv.FormatUint(uint64(event.GetPullRequest().GetNumber()), 10),
  144. "pr_title": event.GetPullRequest().GetTitle(),
  145. "pr_branch_from": event.GetPullRequest().GetHead().GetRef(),
  146. "pr_branch_into": event.GetPullRequest().GetBase().GetRef(),
  147. },
  148. },
  149. )
  150. if err != nil {
  151. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  152. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, depl.ID,
  153. event.GetPullRequest().GetNumber(), err)
  154. }
  155. } else {
  156. err = c.deleteDeployment(r, depl, env, client)
  157. if err != nil {
  158. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  159. "error deleting deployment: %w", webhookID, owner, repo, env.ID, depl.ID,
  160. event.GetPullRequest().GetNumber(), err)
  161. }
  162. }
  163. }
  164. return nil
  165. }
  166. func (c *GithubIncomingWebhookHandler) deleteDeployment(
  167. r *http.Request,
  168. depl *models.Deployment,
  169. env *models.Environment,
  170. client *github.Client,
  171. ) error {
  172. cluster, err := c.Repo().Cluster().ReadCluster(env.ProjectID, env.ClusterID)
  173. if err != nil {
  174. return fmt.Errorf("[projectID: %d, clusterID: %d] error reading cluster when deleting existing deployment: %w",
  175. env.ProjectID, env.ClusterID, err)
  176. }
  177. agent, err := c.GetAgent(r, cluster, "")
  178. if err != nil {
  179. return err
  180. }
  181. // make sure we don't delete default or kube-system by checking for prefix, for now
  182. if strings.Contains(depl.Namespace, "pr-") {
  183. err = agent.DeleteNamespace(depl.Namespace)
  184. if err != nil {
  185. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error deleting namespace '%s': %w",
  186. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, depl.Namespace, err)
  187. }
  188. }
  189. // Create new deployment status to indicate deployment is ready
  190. state := "inactive"
  191. deploymentStatusRequest := github.DeploymentStatusRequest{
  192. State: &state,
  193. }
  194. client.Repositories.CreateDeploymentStatus(
  195. context.Background(),
  196. env.GitRepoOwner,
  197. env.GitRepoName,
  198. depl.GHDeploymentID,
  199. &deploymentStatusRequest,
  200. )
  201. depl.Status = types.DeploymentStatusInactive
  202. // update the deployment to mark it inactive
  203. _, err = c.Repo().Environment().UpdateDeployment(depl)
  204. if err != nil {
  205. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error updating deployment: %w",
  206. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, err)
  207. }
  208. return nil
  209. }
  210. func getGithubClientFromEnvironment(config *config.Config, env *models.Environment) (*github.Client, error) {
  211. // get the github app client
  212. ghAppId, err := strconv.Atoi(config.ServerConf.GithubAppID)
  213. if err != nil {
  214. return nil, err
  215. }
  216. // authenticate as github app installation
  217. itr, err := ghinstallation.NewKeyFromFile(
  218. http.DefaultTransport,
  219. int64(ghAppId),
  220. int64(env.GitInstallationID),
  221. config.ServerConf.GithubAppSecretPath,
  222. )
  223. if err != nil {
  224. return nil, err
  225. }
  226. return github.NewClient(&http.Client{Transport: itr}), nil
  227. }