create.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. GitRepoBranches: strings.Join(request.GitRepoBranches, ","),
  62. Mode: request.Mode,
  63. WebhookID: string(webhookUID),
  64. NewCommentsDisabled: request.DisableNewComments,
  65. }
  66. // write Github actions files to the repo
  67. client, err := getGithubClientFromEnvironment(c.Config(), env)
  68. if err != nil {
  69. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  70. return
  71. }
  72. webhookURL := getGithubWebhookURLFromUID(c.Config().ServerConf.ServerURL, string(webhookUID))
  73. // create incoming webhook
  74. hook, _, err := client.Repositories.CreateHook(
  75. r.Context(), owner, name, &github.Hook{
  76. Config: map[string]interface{}{
  77. "url": webhookURL,
  78. "content_type": "json",
  79. "secret": c.Config().ServerConf.GithubIncomingWebhookSecret,
  80. },
  81. Events: []string{"pull_request"},
  82. Active: github.Bool(true),
  83. },
  84. )
  85. if err != nil && !strings.Contains(err.Error(), "already exists on this repository") {
  86. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  87. fmt.Errorf("error trying to create a new github repository webhook: %w", err), http.StatusConflict),
  88. )
  89. return
  90. }
  91. env.GithubWebhookID = hook.GetID()
  92. env, err = c.Repo().Environment().CreateEnvironment(env)
  93. if err != nil {
  94. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  95. return
  96. }
  97. // generate porter jwt token
  98. jwt, err := token.GetTokenForAPI(user.ID, project.ID)
  99. if err != nil {
  100. c.deleteEnvAndReportError(w, r, env, err)
  101. return
  102. }
  103. encoded, err := jwt.EncodeToken(c.Config().TokenConf)
  104. if err != nil {
  105. c.deleteEnvAndReportError(w, r, env, err)
  106. return
  107. }
  108. err = actions.SetupEnv(&actions.EnvOpts{
  109. Client: client,
  110. ServerURL: c.Config().ServerConf.ServerURL,
  111. PorterToken: encoded,
  112. GitRepoOwner: owner,
  113. GitRepoName: name,
  114. ProjectID: project.ID,
  115. ClusterID: cluster.ID,
  116. GitInstallationID: uint(ga.InstallationID),
  117. EnvironmentName: request.Name,
  118. })
  119. if err != nil {
  120. unwrappedErr := errors.Unwrap(err)
  121. if unwrappedErr != nil {
  122. if errors.Is(unwrappedErr, actions.ErrProtectedBranch) {
  123. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  124. } else if errors.Is(unwrappedErr, actions.ErrCreatePRForProtectedBranch) {
  125. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusPreconditionFailed))
  126. }
  127. } else {
  128. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  129. return
  130. }
  131. }
  132. c.WriteResult(w, r, env.ToEnvironmentType())
  133. }
  134. func (c *CreateEnvironmentHandler) deleteEnvAndReportError(
  135. w http.ResponseWriter, r *http.Request, env *models.Environment, err error,
  136. ) {
  137. _, delErr := c.Repo().Environment().DeleteEnvironment(env)
  138. if delErr != nil {
  139. c.HandleAPIError(w, r, apierrors.NewErrInternal(delErr))
  140. return
  141. }
  142. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  143. }
  144. func getGithubClientFromEnvironment(config *config.Config, env *models.Environment) (*github.Client, error) {
  145. // get the github app client
  146. ghAppId, err := strconv.Atoi(config.ServerConf.GithubAppID)
  147. if err != nil {
  148. return nil, err
  149. }
  150. // authenticate as github app installation
  151. itr, err := ghinstallation.New(
  152. http.DefaultTransport,
  153. int64(ghAppId),
  154. int64(env.GitInstallationID),
  155. config.ServerConf.GithubAppSecret,
  156. )
  157. if err != nil {
  158. return nil, err
  159. }
  160. return github.NewClient(&http.Client{Transport: itr}), nil
  161. }
  162. func getGithubWebhookURLFromUID(serverURL, webhookUID string) string {
  163. return fmt.Sprintf("%s/api/github/incoming_webhook/%s", serverURL, string(webhookUID))
  164. }