open_stack_pr.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package stacks
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "github.com/bradleyfalzon/ghinstallation/v2"
  10. "github.com/google/go-github/v41/github"
  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/commonutils"
  15. "github.com/porter-dev/porter/api/server/shared/config"
  16. "github.com/porter-dev/porter/api/types"
  17. "github.com/porter-dev/porter/internal/auth/token"
  18. "github.com/porter-dev/porter/internal/encryption"
  19. "github.com/porter-dev/porter/internal/integrations/ci/actions"
  20. "github.com/porter-dev/porter/internal/models"
  21. "github.com/porter-dev/porter/internal/models/integrations"
  22. )
  23. type OpenStackPRHandler struct {
  24. handlers.PorterHandlerReadWriter
  25. }
  26. func NewOpenStackPRHandler(
  27. config *config.Config,
  28. decoderValidator shared.RequestDecoderValidator,
  29. writer shared.ResultWriter,
  30. ) *OpenStackPRHandler {
  31. return &OpenStackPRHandler{
  32. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  33. }
  34. }
  35. func (c *OpenStackPRHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  36. ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
  37. user, _ := r.Context().Value(types.UserScope).(*models.User)
  38. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  39. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  40. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  41. if !ok {
  42. return
  43. }
  44. // create the environment
  45. request := &types.CreateEnvironmentRequest{}
  46. if ok := c.DecodeAndValidate(w, r, request); !ok {
  47. return
  48. }
  49. // create a random webhook id
  50. webhookUID, err := encryption.GenerateRandomBytes(32)
  51. if err != nil {
  52. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error generating webhook UID for new stack: %w", err)))
  53. return
  54. }
  55. env := &models.Environment{
  56. ProjectID: project.ID,
  57. ClusterID: cluster.ID,
  58. GitInstallationID: uint(ga.InstallationID),
  59. Name: request.Name,
  60. GitRepoOwner: owner,
  61. GitRepoName: name,
  62. GitRepoBranches: strings.Join(request.GitRepoBranches, ","),
  63. Mode: request.Mode,
  64. WebhookID: string(webhookUID),
  65. NewCommentsDisabled: request.DisableNewComments,
  66. GitDeployBranches: strings.Join(request.GitDeployBranches, ","),
  67. }
  68. client, err := getGithubClient(c.Config(), ga.InstallationID)
  69. if err != nil {
  70. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  71. return
  72. }
  73. // generate porter jwt token
  74. jwt, err := token.GetTokenForAPI(user.ID, project.ID)
  75. if err != nil {
  76. _, deleteErr := client.Repositories.DeleteHook(context.Background(), owner, name, hook.GetID())
  77. if deleteErr != nil {
  78. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("%v: %w", errGithubAPI, deleteErr),
  79. http.StatusConflict, "error getting token for API while creating environment"))
  80. return
  81. }
  82. _, deleteErr = c.Repo().Environment().DeleteEnvironment(env)
  83. if deleteErr != nil {
  84. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error deleting created preview environment: %w",
  85. deleteErr)))
  86. return
  87. }
  88. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error getting token for API: %w", err)))
  89. return
  90. }
  91. encoded, err := jwt.EncodeToken(c.Config().TokenConf)
  92. if err != nil {
  93. _, deleteErr := client.Repositories.DeleteHook(context.Background(), owner, name, hook.GetID())
  94. if deleteErr != nil {
  95. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("%v: %w", errGithubAPI, deleteErr),
  96. http.StatusConflict, "error encoding token while creating environment"))
  97. return
  98. }
  99. _, deleteErr = c.Repo().Environment().DeleteEnvironment(env)
  100. if deleteErr != nil {
  101. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error deleting created preview environment: %w",
  102. deleteErr)))
  103. return
  104. }
  105. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error encoding API token: %w", 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. InstanceName: c.Config().ServerConf.InstanceName,
  119. })
  120. err = actions.OpenGithubPR(&actions.OpenGithubPROpts{
  121. Client: client,
  122. })
  123. if err != nil {
  124. unwrappedErr := errors.Unwrap(err)
  125. if unwrappedErr != nil {
  126. if errors.Is(unwrappedErr, actions.ErrProtectedBranch) {
  127. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  128. } else if errors.Is(unwrappedErr, actions.ErrCreatePRForProtectedBranch) {
  129. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusPreconditionFailed))
  130. }
  131. } else {
  132. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error setting up preview environment in the github "+
  133. "repo: %w", err)))
  134. return
  135. }
  136. }
  137. w.WriteHeader(http.StatusCreated)
  138. }
  139. func getGithubClient(config *config.Config, gitInstallationId int64) (*github.Client, error) {
  140. // get the github app client
  141. ghAppId, err := strconv.Atoi(config.ServerConf.GithubAppID)
  142. if err != nil {
  143. return nil, fmt.Errorf("malformed GITHUB_APP_ID in server configuration: %w", err)
  144. }
  145. // authenticate as github app installation
  146. itr, err := ghinstallation.New(
  147. http.DefaultTransport,
  148. int64(ghAppId),
  149. gitInstallationId,
  150. config.ServerConf.GithubAppSecret,
  151. )
  152. if err != nil {
  153. return nil, fmt.Errorf("error in creating github client for stack: %w", err)
  154. }
  155. return github.NewClient(&http.Client{Transport: itr}), nil
  156. }