app_v2_github.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package webhook
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "connectrpc.com/connect"
  8. "github.com/google/go-github/v39/github"
  9. "github.com/google/uuid"
  10. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  11. "github.com/porter-dev/porter/api/server/authz"
  12. "github.com/porter-dev/porter/api/server/handlers"
  13. "github.com/porter-dev/porter/api/server/shared"
  14. "github.com/porter-dev/porter/api/server/shared/apierrors"
  15. "github.com/porter-dev/porter/api/server/shared/config"
  16. "github.com/porter-dev/porter/api/server/shared/requestutils"
  17. "github.com/porter-dev/porter/api/types"
  18. "github.com/porter-dev/porter/internal/models"
  19. "github.com/porter-dev/porter/internal/porter_app"
  20. "github.com/porter-dev/porter/internal/telemetry"
  21. )
  22. // GithubPRStatus_Closed is the status for a closed PR (closed, merged)
  23. const GithubPRStatus_Closed = "closed"
  24. // GithubWebhookHandler handles webhooks sent to /api/webhooks/github/{project_id}/{cluster_id}/{porter_app_name}
  25. type GithubWebhookHandler struct {
  26. handlers.PorterHandlerReadWriter
  27. authz.KubernetesAgentGetter
  28. }
  29. // NewGithubWebhookHandler returns a GithubWebhookHandler
  30. func NewGithubWebhookHandler(
  31. config *config.Config,
  32. decoderValidator shared.RequestDecoderValidator,
  33. writer shared.ResultWriter,
  34. ) *GithubWebhookHandler {
  35. return &GithubWebhookHandler{
  36. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  37. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  38. }
  39. }
  40. // ServeHTTP handles the webhook and deletes the deployment target if a PR has been closed
  41. func (c *GithubWebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  42. ctx, span := telemetry.NewSpan(r.Context(), "serve-github-webhook")
  43. defer span.End()
  44. payload, err := github.ValidatePayload(r, []byte(c.Config().ServerConf.GithubIncomingWebhookSecret))
  45. if err != nil {
  46. err := telemetry.Error(ctx, span, err, "could not validate payload")
  47. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  48. return
  49. }
  50. event, err := github.ParseWebHook(github.WebHookType(r), payload)
  51. if err != nil {
  52. err := telemetry.Error(ctx, span, err, "could not parse webhook")
  53. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  54. return
  55. }
  56. webhookID, reqErr := requestutils.GetURLParamString(r, types.URLParamWebhookID)
  57. if reqErr != nil {
  58. err := telemetry.Error(ctx, span, nil, "error parsing porter app name")
  59. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  60. return
  61. }
  62. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "webhook-id", Value: webhookID})
  63. webhookUUID, err := uuid.Parse(webhookID)
  64. if err != nil {
  65. err := telemetry.Error(ctx, span, err, "error parsing webhook id")
  66. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  67. return
  68. }
  69. if webhookUUID == uuid.Nil {
  70. err := telemetry.Error(ctx, span, err, "webhook id is nil")
  71. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  72. return
  73. }
  74. webhook, err := c.Repo().GithubWebhook().Get(ctx, webhookUUID)
  75. if err != nil {
  76. err := telemetry.Error(ctx, span, err, "error getting github webhook")
  77. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  78. return
  79. }
  80. if webhook.ID == uuid.Nil {
  81. err := telemetry.Error(ctx, span, err, "github webhook id is nil")
  82. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  83. return
  84. }
  85. telemetry.WithAttributes(span,
  86. telemetry.AttributeKV{Key: "porter-app-id", Value: webhook.PorterAppID},
  87. telemetry.AttributeKV{Key: "cluster-id", Value: webhook.ClusterID},
  88. telemetry.AttributeKV{Key: "project-id", Value: webhook.ProjectID},
  89. )
  90. porterApp, err := c.Repo().PorterApp().ReadPorterAppByID(ctx, uint(webhook.PorterAppID))
  91. if err != nil {
  92. err := telemetry.Error(ctx, span, err, "error getting porter app")
  93. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  94. return
  95. }
  96. if porterApp.ID == 0 {
  97. err := telemetry.Error(ctx, span, err, "porter app not found")
  98. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  99. return
  100. }
  101. if porterApp.ProjectID != uint(webhook.ProjectID) {
  102. err := telemetry.Error(ctx, span, err, "porter app project id does not match")
  103. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  104. return
  105. }
  106. switch event := event.(type) {
  107. case *github.PullRequestEvent:
  108. if event.GetAction() != GithubPRStatus_Closed {
  109. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "event-processed", Value: false})
  110. c.WriteResult(w, r, nil)
  111. return
  112. }
  113. branch := event.GetPullRequest().GetHead().GetRef()
  114. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "event-branch", Value: branch})
  115. err = cancelPendingWorkflows(ctx, cancelPendingWorkflowsInput{
  116. appName: porterApp.Name,
  117. repoID: porterApp.GitRepoID,
  118. repoName: porterApp.RepoName,
  119. githubAppSecret: c.Config().ServerConf.GithubAppSecret,
  120. githubAppID: c.Config().ServerConf.GithubAppID,
  121. event: event,
  122. })
  123. if err != nil {
  124. err := telemetry.Error(ctx, span, err, "error cancelling pending workflows")
  125. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  126. return
  127. }
  128. deploymentTarget, err := c.Repo().DeploymentTarget().DeploymentTargetBySelectorAndSelectorType(
  129. uint(webhook.ProjectID),
  130. uint(webhook.ClusterID),
  131. branch,
  132. string(models.DeploymentTargetSelectorType_Namespace),
  133. )
  134. if err != nil {
  135. err := telemetry.Error(ctx, span, err, "error getting deployment target")
  136. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  137. return
  138. }
  139. if deploymentTarget.ID == uuid.Nil || !deploymentTarget.Preview {
  140. c.WriteResult(w, r, nil)
  141. return
  142. }
  143. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "deployment-target-id", Value: deploymentTarget.ID.String()})
  144. if deploymentTarget.ClusterID != webhook.ClusterID {
  145. err := telemetry.Error(ctx, span, err, "deployment target cluster id does not match")
  146. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  147. return
  148. }
  149. deleteTargetReq := connect.NewRequest(&porterv1.DeleteDeploymentTargetRequest{
  150. ProjectId: int64(webhook.ProjectID),
  151. DeploymentTargetId: deploymentTarget.ID.String(),
  152. })
  153. _, err = c.Config().ClusterControlPlaneClient.DeleteDeploymentTarget(ctx, deleteTargetReq)
  154. if err != nil {
  155. err := telemetry.Error(ctx, span, err, "error deleting deployment target")
  156. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  157. return
  158. }
  159. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "event-processed", Value: true})
  160. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "pr-id", Value: event.GetPullRequest().GetID()})
  161. }
  162. c.WriteResult(w, r, nil)
  163. }
  164. type cancelPendingWorkflowsInput struct {
  165. appName string
  166. repoID uint
  167. repoName string
  168. githubAppSecret []byte
  169. githubAppID string
  170. event *github.PullRequestEvent
  171. }
  172. func cancelPendingWorkflows(ctx context.Context, inp cancelPendingWorkflowsInput) error {
  173. ctx, span := telemetry.NewSpan(ctx, "cancel-pending-workflows")
  174. defer span.End()
  175. if inp.repoID == 0 {
  176. return telemetry.Error(ctx, span, nil, "repo id is 0")
  177. }
  178. if inp.repoName == "" {
  179. return telemetry.Error(ctx, span, nil, "repo name is empty")
  180. }
  181. if inp.appName == "" {
  182. return telemetry.Error(ctx, span, nil, "app name is empty")
  183. }
  184. if inp.githubAppSecret == nil {
  185. return telemetry.Error(ctx, span, nil, "github app secret is nil")
  186. }
  187. if inp.githubAppID == "" {
  188. return telemetry.Error(ctx, span, nil, "github app id is empty")
  189. }
  190. client, err := porter_app.GetGithubClientByRepoID(ctx, inp.repoID, inp.githubAppSecret, inp.githubAppID)
  191. if err != nil {
  192. return telemetry.Error(ctx, span, err, "error getting github client")
  193. }
  194. repoDetails := strings.Split(inp.repoName, "/")
  195. if len(repoDetails) != 2 {
  196. return telemetry.Error(ctx, span, nil, "repo name is invalid")
  197. }
  198. owner := repoDetails[0]
  199. repo := repoDetails[1]
  200. pendingStatusOptions := []string{"in_progress", "queued", "requested", "waiting"}
  201. for _, status := range pendingStatusOptions {
  202. runs, _, err := client.Actions.ListWorkflowRunsByFileName(
  203. ctx, owner, repo, fmt.Sprintf("porter_preview_%s.yml", inp.appName),
  204. &github.ListWorkflowRunsOptions{
  205. Branch: inp.event.GetPullRequest().GetHead().GetRef(),
  206. Status: status,
  207. },
  208. )
  209. if err != nil {
  210. return telemetry.Error(ctx, span, err, "error listing workflow runs")
  211. }
  212. for _, run := range runs.WorkflowRuns {
  213. _, err := client.Actions.CancelWorkflowRunByID(
  214. ctx, owner, repo, run.GetID(),
  215. )
  216. if err != nil {
  217. return telemetry.Error(ctx, span, err, "error cancelling workflow run")
  218. }
  219. }
  220. }
  221. return nil
  222. }