create_secret_and_open_pr.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. package stacks
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "github.com/bradleyfalzon/ghinstallation/v2"
  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/config"
  13. "github.com/porter-dev/porter/api/server/shared/requestutils"
  14. "github.com/porter-dev/porter/api/types"
  15. "github.com/porter-dev/porter/internal/auth/token"
  16. "github.com/porter-dev/porter/internal/integrations/ci/actions"
  17. "github.com/porter-dev/porter/internal/models"
  18. )
  19. type OpenStackPRHandler struct {
  20. handlers.PorterHandlerReadWriter
  21. }
  22. func NewOpenStackPRHandler(
  23. config *config.Config,
  24. decoderValidator shared.RequestDecoderValidator,
  25. writer shared.ResultWriter,
  26. ) *OpenStackPRHandler {
  27. return &OpenStackPRHandler{
  28. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  29. }
  30. }
  31. func (c *OpenStackPRHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  32. user, _ := r.Context().Value(types.UserScope).(*models.User)
  33. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  34. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  35. stackName, reqErr := requestutils.GetURLParamString(r, types.URLParamStackName)
  36. if reqErr != nil {
  37. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(reqErr, http.StatusBadRequest))
  38. return
  39. }
  40. request := &types.CreateSecretAndOpenGHPRRequest{}
  41. if ok := c.DecodeAndValidate(w, r, request); !ok {
  42. return
  43. }
  44. client, err := getGithubClient(c.Config(), request.GithubAppInstallationID)
  45. if err != nil {
  46. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  47. return
  48. }
  49. // generate porter jwt token
  50. jwt, err := token.GetTokenForAPI(user.ID, project.ID)
  51. if err != nil {
  52. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error getting token for API: %w", err)))
  53. return
  54. }
  55. encoded, err := jwt.EncodeToken(c.Config().TokenConf)
  56. if err != nil {
  57. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error encoding API token: %w", err)))
  58. return
  59. }
  60. // create porter secret
  61. secretName := fmt.Sprintf("PORTER_STACK_%d_%d", project.ID, cluster.ID)
  62. err = actions.CreateGithubSecret(
  63. client,
  64. secretName,
  65. encoded,
  66. request.GithubRepoOwner,
  67. request.GithubRepoName,
  68. )
  69. if err != nil {
  70. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error generating secret: %w", err)))
  71. return
  72. }
  73. var pr *github.PullRequest
  74. if request.OpenPr {
  75. pr, err = actions.OpenGithubPR(&actions.GithubPROpts{
  76. Client: client,
  77. GitRepoOwner: request.GithubRepoOwner,
  78. GitRepoName: request.GithubRepoName,
  79. StackName: stackName,
  80. ProjectID: project.ID,
  81. ClusterID: cluster.ID,
  82. ServerURL: c.Config().ServerConf.ServerURL,
  83. DefaultBranch: request.Branch,
  84. SecretName: secretName,
  85. PorterYamlPath: request.PorterYamlPath,
  86. Body: "Hello 👋 from Porter! Please merge this PR to finish setting up your application.",
  87. })
  88. }
  89. if err != nil {
  90. unwrappedErr := errors.Unwrap(err)
  91. if unwrappedErr != nil {
  92. if errors.Is(unwrappedErr, actions.ErrProtectedBranch) {
  93. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  94. } else if errors.Is(unwrappedErr, actions.ErrCreatePRForProtectedBranch) {
  95. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusPreconditionFailed))
  96. }
  97. } else {
  98. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error setting up application in the github "+
  99. "repo: %w", err)))
  100. return
  101. }
  102. }
  103. var resp types.CreateSecretAndOpenGHPRResponse
  104. if pr != nil {
  105. resp = types.CreateSecretAndOpenGHPRResponse{
  106. URL: pr.GetHTMLURL(),
  107. }
  108. // update DB with the PR url
  109. porterApp, err := c.Repo().PorterApp().ReadPorterAppByName(cluster.ID, stackName)
  110. if err != nil {
  111. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("unable to get porter app db: %w", err)))
  112. return
  113. }
  114. porterApp.PullRequestURL = pr.GetHTMLURL()
  115. _, err = c.Repo().PorterApp().UpdatePorterApp(porterApp)
  116. if err != nil {
  117. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("unable to write pr url to porter app db: %w", err)))
  118. return
  119. }
  120. }
  121. w.WriteHeader(http.StatusCreated)
  122. c.WriteResult(w, r, resp)
  123. }
  124. func getGithubClient(config *config.Config, gitInstallationId int64) (*github.Client, error) {
  125. // get the github app client
  126. ghAppId, err := strconv.Atoi(config.ServerConf.GithubAppID)
  127. if err != nil {
  128. return nil, fmt.Errorf("malformed GITHUB_APP_ID in server configuration: %w", err)
  129. }
  130. // authenticate as github app installation
  131. itr, err := ghinstallation.New(
  132. http.DefaultTransport,
  133. int64(ghAppId),
  134. gitInstallationId,
  135. config.ServerConf.GithubAppSecret,
  136. )
  137. if err != nil {
  138. return nil, fmt.Errorf("error in creating github client for stack: %w", err)
  139. }
  140. return github.NewClient(&http.Client{Transport: itr}), nil
  141. }