create.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. package environment
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "github.com/google/go-github/v41/github"
  9. "github.com/porter-dev/porter/api/server/handlers"
  10. "github.com/porter-dev/porter/api/server/shared"
  11. "github.com/porter-dev/porter/api/server/shared/apierrors"
  12. "github.com/porter-dev/porter/api/server/shared/commonutils"
  13. "github.com/porter-dev/porter/api/server/shared/config"
  14. "github.com/porter-dev/porter/api/types"
  15. "github.com/porter-dev/porter/internal/auth/token"
  16. "github.com/porter-dev/porter/internal/encryption"
  17. "github.com/porter-dev/porter/internal/integrations/ci/actions"
  18. "github.com/porter-dev/porter/internal/models"
  19. "github.com/porter-dev/porter/internal/models/integrations"
  20. )
  21. type CreateEnvironmentHandler struct {
  22. handlers.PorterHandlerReadWriter
  23. }
  24. func NewCreateEnvironmentHandler(
  25. config *config.Config,
  26. decoderValidator shared.RequestDecoderValidator,
  27. writer shared.ResultWriter,
  28. ) *CreateEnvironmentHandler {
  29. return &CreateEnvironmentHandler{
  30. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  31. }
  32. }
  33. // ServerHTTP authenticates as the given project and cluster's Github App,
  34. // creating a Github hook which listens to "pull_request" and "push" against the given
  35. // branch. This will then create a Github Action Workflow file, and commit it to the given branch.
  36. // Should the commit fail due to a protected branch, Porter will open a PR automatically against the branch
  37. // with the required Github Action Workflow yaml
  38. func (c *CreateEnvironmentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  39. ctx := r.Context()
  40. ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
  41. user, _ := r.Context().Value(types.UserScope).(*models.User)
  42. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  43. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  44. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  45. if !ok {
  46. return
  47. }
  48. // create the environment
  49. request := &types.CreateEnvironmentRequest{}
  50. if ok := c.DecodeAndValidate(w, r, request); !ok {
  51. return
  52. }
  53. // create a random webhook id
  54. webhookUID, err := encryption.GenerateRandomBytes(32)
  55. if err != nil {
  56. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error generating webhook UID for new preview "+
  57. "environment: %w", err)))
  58. return
  59. }
  60. env := &models.Environment{
  61. ProjectID: project.ID,
  62. ClusterID: cluster.ID,
  63. GitInstallationID: uint(ga.InstallationID),
  64. Name: request.Name,
  65. GitRepoOwner: owner,
  66. GitRepoName: name,
  67. GitRepoBranches: strings.Join(request.GitRepoBranches, ","),
  68. Mode: request.Mode,
  69. WebhookID: string(webhookUID),
  70. NewCommentsDisabled: request.DisableNewComments,
  71. GitDeployBranches: strings.Join(request.GitDeployBranches, ","),
  72. }
  73. if len(request.NamespaceLabels) > 0 {
  74. var labels []string
  75. for k, v := range request.NamespaceLabels {
  76. labels = append(labels, fmt.Sprintf("%s=%s", k, v))
  77. }
  78. env.NamespaceLabels = []byte(strings.Join(labels, ","))
  79. }
  80. // write Github actions files to the repo
  81. client, err := getGithubClientFromEnvironment(c.Config(), env)
  82. if err != nil {
  83. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  84. return
  85. }
  86. webhookURL := getGithubWebhookURLFromUID(c.Config().ServerConf.ServerURL, string(webhookUID))
  87. // create incoming webhook
  88. hook, _, err := client.Repositories.CreateHook(
  89. ctx, owner, name, &github.Hook{
  90. Config: map[string]interface{}{
  91. "url": webhookURL,
  92. "content_type": "json",
  93. "secret": c.Config().ServerConf.GithubIncomingWebhookSecret,
  94. },
  95. Events: []string{"pull_request", "push"},
  96. Active: github.Bool(true),
  97. },
  98. )
  99. if err != nil && !strings.Contains(err.Error(), "already exists") {
  100. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("%v: %w", errGithubAPI, err),
  101. http.StatusConflict))
  102. return
  103. }
  104. env.GithubWebhookID = hook.GetID()
  105. env, err = c.Repo().Environment().CreateEnvironment(env)
  106. if err != nil {
  107. _, deleteErr := client.Repositories.DeleteHook(ctx, owner, name, hook.GetID())
  108. if deleteErr != nil {
  109. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("%v: %w", errGithubAPI, deleteErr),
  110. http.StatusConflict, "error creating environment"))
  111. return
  112. }
  113. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error creating environment: %w", err)))
  114. return
  115. }
  116. // generate porter jwt token
  117. jwt, err := token.GetTokenForAPI(user.ID, project.ID)
  118. if err != nil {
  119. _, deleteErr := client.Repositories.DeleteHook(context.Background(), owner, name, hook.GetID())
  120. if deleteErr != nil {
  121. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("%v: %w", errGithubAPI, deleteErr),
  122. http.StatusConflict, "error getting token for API while creating environment"))
  123. return
  124. }
  125. _, deleteErr = c.Repo().Environment().DeleteEnvironment(env)
  126. if deleteErr != nil {
  127. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error deleting created preview environment: %w",
  128. deleteErr)))
  129. return
  130. }
  131. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error getting token for API: %w", err)))
  132. return
  133. }
  134. encoded, err := jwt.EncodeToken(c.Config().TokenConf)
  135. if err != nil {
  136. _, deleteErr := client.Repositories.DeleteHook(context.Background(), owner, name, hook.GetID())
  137. if deleteErr != nil {
  138. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("%v: %w", errGithubAPI, deleteErr),
  139. http.StatusConflict, "error encoding token while creating environment"))
  140. return
  141. }
  142. _, deleteErr = c.Repo().Environment().DeleteEnvironment(env)
  143. if deleteErr != nil {
  144. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error deleting created preview environment: %w",
  145. deleteErr)))
  146. return
  147. }
  148. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error encoding API token: %w", err)))
  149. return
  150. }
  151. err = actions.SetupEnv(&actions.EnvOpts{
  152. Client: client,
  153. ServerURL: c.Config().ServerConf.ServerURL,
  154. PorterToken: encoded,
  155. GitRepoOwner: owner,
  156. GitRepoName: name,
  157. ProjectID: project.ID,
  158. ClusterID: cluster.ID,
  159. GitInstallationID: uint(ga.InstallationID),
  160. EnvironmentName: request.Name,
  161. InstanceName: c.Config().ServerConf.InstanceName,
  162. })
  163. if err != nil {
  164. unwrappedErr := errors.Unwrap(err)
  165. if unwrappedErr != nil {
  166. if errors.Is(unwrappedErr, actions.ErrProtectedBranch) {
  167. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  168. } else if errors.Is(unwrappedErr, actions.ErrCreatePRForProtectedBranch) {
  169. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusPreconditionFailed))
  170. }
  171. } else {
  172. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error setting up preview environment in the github "+
  173. "repo: %w", err)))
  174. return
  175. }
  176. }
  177. c.WriteResult(w, r, env.ToEnvironmentType())
  178. }
  179. func getGithubWebhookURLFromUID(serverURL, webhookUID string) string {
  180. return fmt.Sprintf("%s/api/github/incoming_webhook/%s", serverURL, string(webhookUID))
  181. }