create.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package environment
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. ghinstallation "github.com/bradleyfalzon/ghinstallation/v2"
  9. "github.com/google/go-github/v41/github"
  10. "github.com/porter-dev/porter/api/server/handlers"
  11. "github.com/porter-dev/porter/api/server/shared"
  12. "github.com/porter-dev/porter/api/server/shared/apierrors"
  13. "github.com/porter-dev/porter/api/server/shared/commonutils"
  14. "github.com/porter-dev/porter/api/server/shared/config"
  15. "github.com/porter-dev/porter/api/types"
  16. "github.com/porter-dev/porter/internal/auth/token"
  17. "github.com/porter-dev/porter/internal/encryption"
  18. "github.com/porter-dev/porter/internal/integrations/ci/actions"
  19. "github.com/porter-dev/porter/internal/models"
  20. "github.com/porter-dev/porter/internal/models/integrations"
  21. )
  22. type CreateEnvironmentHandler struct {
  23. handlers.PorterHandlerReadWriter
  24. }
  25. func NewCreateEnvironmentHandler(
  26. config *config.Config,
  27. decoderValidator shared.RequestDecoderValidator,
  28. writer shared.ResultWriter,
  29. ) *CreateEnvironmentHandler {
  30. return &CreateEnvironmentHandler{
  31. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  32. }
  33. }
  34. func (c *CreateEnvironmentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  35. ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
  36. user, _ := r.Context().Value(types.UserScope).(*models.User)
  37. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  38. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  39. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  40. if !ok {
  41. return
  42. }
  43. // create the environment
  44. request := &types.CreateEnvironmentRequest{}
  45. if ok := c.DecodeAndValidate(w, r, request); !ok {
  46. return
  47. }
  48. // create a random webhook id
  49. webhookUID, err := encryption.GenerateRandomBytes(32)
  50. if err != nil {
  51. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  52. return
  53. }
  54. env := &models.Environment{
  55. ProjectID: project.ID,
  56. ClusterID: cluster.ID,
  57. GitInstallationID: uint(ga.InstallationID),
  58. Name: request.Name,
  59. GitRepoOwner: owner,
  60. GitRepoName: name,
  61. Mode: request.Mode,
  62. WebhookID: string(webhookUID),
  63. }
  64. // write Github actions files to the repo
  65. client, err := getGithubClientFromEnvironment(c.Config(), env)
  66. if err != nil {
  67. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  68. return
  69. }
  70. webhookURL := getGithubWebhookURLFromUID(c.Config().ServerConf.ServerURL, string(webhookUID))
  71. // create incoming webhook
  72. hook, _, err := client.Repositories.CreateHook(
  73. r.Context(), owner, name, &github.Hook{
  74. Config: map[string]interface{}{
  75. "url": webhookURL,
  76. "content_type": "json",
  77. "secret": c.Config().ServerConf.GithubIncomingWebhookSecret,
  78. },
  79. Events: []string{"pull_request"},
  80. Active: github.Bool(true),
  81. },
  82. )
  83. if err != nil && !strings.Contains(err.Error(), "already exists on this repository") {
  84. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  85. fmt.Errorf("error trying to create a new github repository webhook: %w", err), http.StatusConflict),
  86. )
  87. return
  88. }
  89. env.GithubWebhookID = hook.GetID()
  90. env, err = c.Repo().Environment().CreateEnvironment(env)
  91. if err != nil {
  92. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  93. return
  94. }
  95. // generate porter jwt token
  96. jwt, err := token.GetTokenForAPI(user.ID, project.ID)
  97. if err != nil {
  98. c.deleteEnvAndReportError(w, r, env, err)
  99. return
  100. }
  101. encoded, err := jwt.EncodeToken(c.Config().TokenConf)
  102. if err != nil {
  103. c.deleteEnvAndReportError(w, r, env, err)
  104. return
  105. }
  106. err = actions.SetupEnv(&actions.EnvOpts{
  107. Client: client,
  108. ServerURL: c.Config().ServerConf.ServerURL,
  109. PorterToken: encoded,
  110. GitRepoOwner: owner,
  111. GitRepoName: name,
  112. ProjectID: project.ID,
  113. ClusterID: cluster.ID,
  114. GitInstallationID: uint(ga.InstallationID),
  115. EnvironmentName: request.Name,
  116. })
  117. if err != nil {
  118. unwrappedErr := errors.Unwrap(err)
  119. if unwrappedErr != nil {
  120. if errors.Is(unwrappedErr, actions.ErrProtectedBranch) {
  121. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  122. } else if errors.Is(unwrappedErr, actions.ErrCreatePRForProtectedBranch) {
  123. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusPreconditionFailed))
  124. }
  125. } else {
  126. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  127. return
  128. }
  129. }
  130. c.WriteResult(w, r, env.ToEnvironmentType())
  131. }
  132. func (c *CreateEnvironmentHandler) deleteEnvAndReportError(
  133. w http.ResponseWriter, r *http.Request, env *models.Environment, err error,
  134. ) {
  135. _, delErr := c.Repo().Environment().DeleteEnvironment(env)
  136. if delErr != nil {
  137. c.HandleAPIError(w, r, apierrors.NewErrInternal(delErr))
  138. return
  139. }
  140. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  141. }
  142. func getGithubClientFromEnvironment(config *config.Config, env *models.Environment) (*github.Client, error) {
  143. // get the github app client
  144. ghAppId, err := strconv.Atoi(config.ServerConf.GithubAppID)
  145. if err != nil {
  146. return nil, err
  147. }
  148. // authenticate as github app installation
  149. itr, err := ghinstallation.New(
  150. http.DefaultTransport,
  151. int64(ghAppId),
  152. int64(env.GitInstallationID),
  153. config.ServerConf.GithubAppSecret,
  154. )
  155. if err != nil {
  156. return nil, err
  157. }
  158. return github.NewClient(&http.Client{Transport: itr}), nil
  159. }
  160. func getGithubWebhookURLFromUID(serverURL, webhookUID string) string {
  161. return fmt.Sprintf("%s/api/github/incoming_webhook/%s", serverURL, string(webhookUID))
  162. }