github_incoming.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. package webhook
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "github.com/bradleyfalzon/ghinstallation/v2"
  11. "github.com/google/go-github/v41/github"
  12. "github.com/porter-dev/porter/api/server/authz"
  13. "github.com/porter-dev/porter/api/server/handlers"
  14. "github.com/porter-dev/porter/api/server/shared"
  15. "github.com/porter-dev/porter/api/server/shared/apierrors"
  16. "github.com/porter-dev/porter/api/server/shared/config"
  17. "github.com/porter-dev/porter/api/server/shared/requestutils"
  18. "github.com/porter-dev/porter/api/types"
  19. "github.com/porter-dev/porter/internal/models"
  20. "gorm.io/gorm"
  21. )
  22. type GithubIncomingWebhookHandler struct {
  23. handlers.PorterHandlerReadWriter
  24. authz.KubernetesAgentGetter
  25. }
  26. func NewGithubIncomingWebhookHandler(
  27. config *config.Config,
  28. decoderValidator shared.RequestDecoderValidator,
  29. writer shared.ResultWriter,
  30. ) *GithubIncomingWebhookHandler {
  31. return &GithubIncomingWebhookHandler{
  32. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  33. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  34. }
  35. }
  36. // ServeHTTP listens for any webhooks generated by a Github repo which has the Porter Github App installed,
  37. // and processes them accordingly. We currently only support "push", and "pull_request"
  38. func (c *GithubIncomingWebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  39. payload, err := github.ValidatePayload(r, []byte(c.Config().ServerConf.GithubIncomingWebhookSecret))
  40. if err != nil {
  41. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error validating webhook payload: %w", err)))
  42. return
  43. }
  44. event, err := github.ParseWebHook(github.WebHookType(r), payload)
  45. if err != nil {
  46. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error parsing webhook: %w", err)))
  47. return
  48. }
  49. switch event := event.(type) {
  50. case *github.PullRequestEvent:
  51. err = c.processPullRequestEvent(event, r)
  52. if err != nil {
  53. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error processing pull request webhook event: %w", err)))
  54. return
  55. }
  56. case *github.PushEvent:
  57. err = c.processPushEvent(event, r)
  58. if err != nil {
  59. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error processing push webhook event: %w", err)))
  60. return
  61. }
  62. }
  63. }
  64. func (c *GithubIncomingWebhookHandler) processPullRequestEvent(event *github.PullRequestEvent, r *http.Request) error {
  65. // get the webhook id from the request
  66. webhookID, reqErr := requestutils.GetURLParamString(r, types.URLParamIncomingWebhookID)
  67. if reqErr != nil {
  68. return fmt.Errorf(reqErr.Error())
  69. }
  70. owner := event.GetRepo().GetOwner().GetLogin()
  71. repo := event.GetRepo().GetName()
  72. env, err := c.Repo().Environment().ReadEnvironmentByWebhookIDOwnerRepoName(webhookID, owner, repo)
  73. if err != nil {
  74. if errors.Is(err, gorm.ErrRecordNotFound) {
  75. return nil
  76. }
  77. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] error reading environment: %w", webhookID, owner, repo, err)
  78. }
  79. if event.GetPullRequest() == nil {
  80. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] incoming webhook does not have pull request information: %w",
  81. webhookID, owner, repo, err)
  82. }
  83. envType := env.ToEnvironmentType()
  84. if len(envType.GitRepoBranches) > 0 {
  85. found := false
  86. for _, br := range envType.GitRepoBranches {
  87. if br == event.GetPullRequest().GetHead().GetRef() {
  88. found = true
  89. break
  90. }
  91. }
  92. if !found {
  93. return nil
  94. }
  95. } else if len(envType.GitDeployBranches) > 0 {
  96. // if the pull request's head branch is in the list of deploy branches
  97. // then we ignore it to avoid a double deploy
  98. found := false
  99. for _, br := range envType.GitDeployBranches {
  100. if br == event.GetPullRequest().GetHead().GetRef() {
  101. found = true
  102. break
  103. }
  104. }
  105. if found {
  106. return nil
  107. }
  108. }
  109. // create deployment on GitHub API
  110. client, err := getGithubClientFromEnvironment(c.Config(), env)
  111. if err != nil {
  112. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  113. "error getting github client: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  114. }
  115. if env.Mode == "auto" && event.GetAction() == "opened" {
  116. depl := &models.Deployment{
  117. EnvironmentID: env.ID,
  118. Namespace: "",
  119. Status: types.DeploymentStatusCreating,
  120. PullRequestID: uint(event.GetPullRequest().GetNumber()),
  121. PRName: event.GetPullRequest().GetTitle(),
  122. RepoName: repo,
  123. RepoOwner: owner,
  124. CommitSHA: event.GetPullRequest().GetHead().GetSHA()[:7],
  125. PRBranchFrom: event.GetPullRequest().GetHead().GetRef(),
  126. PRBranchInto: event.GetPullRequest().GetBase().GetRef(),
  127. }
  128. _, err = c.Repo().Environment().CreateDeployment(depl)
  129. if err != nil {
  130. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  131. "error creating new deployment: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  132. }
  133. _, err := client.Actions.CreateWorkflowDispatchEventByFileName(
  134. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  135. github.CreateWorkflowDispatchEventRequest{
  136. Ref: event.GetPullRequest().GetHead().GetRef(),
  137. Inputs: map[string]interface{}{
  138. "pr_number": strconv.FormatUint(uint64(event.GetPullRequest().GetNumber()), 10),
  139. "pr_title": event.GetPullRequest().GetTitle(),
  140. "pr_branch_from": event.GetPullRequest().GetHead().GetRef(),
  141. "pr_branch_into": event.GetPullRequest().GetBase().GetRef(),
  142. },
  143. },
  144. )
  145. if err != nil {
  146. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  147. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  148. }
  149. } else if event.GetAction() == "synchronize" || event.GetAction() == "closed" || event.GetAction() == "edited" {
  150. depl, err := c.Repo().Environment().ReadDeploymentByGitDetails(
  151. env.ID, owner, repo, uint(event.GetPullRequest().GetNumber()),
  152. )
  153. if err != nil {
  154. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, prNumber: %d] "+
  155. "error reading deployment: %w", webhookID, owner, repo, env.ID, event.GetPullRequest().GetNumber(), err)
  156. }
  157. if depl.Status == types.DeploymentStatusInactive {
  158. return nil
  159. }
  160. if event.GetAction() == "synchronize" {
  161. _, err := client.Actions.CreateWorkflowDispatchEventByFileName(
  162. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  163. github.CreateWorkflowDispatchEventRequest{
  164. Ref: event.GetPullRequest().GetHead().GetRef(),
  165. Inputs: map[string]interface{}{
  166. "pr_number": strconv.FormatUint(uint64(event.GetPullRequest().GetNumber()), 10),
  167. "pr_title": event.GetPullRequest().GetTitle(),
  168. "pr_branch_from": event.GetPullRequest().GetHead().GetRef(),
  169. "pr_branch_into": event.GetPullRequest().GetBase().GetRef(),
  170. },
  171. },
  172. )
  173. if err != nil {
  174. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  175. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, depl.ID,
  176. event.GetPullRequest().GetNumber(), err)
  177. }
  178. } else if event.GetAction() == "closed" {
  179. // check for already running workflows we should be cancelling
  180. var wg sync.WaitGroup
  181. statuses := []string{"in_progress", "queued", "requested", "waiting"}
  182. chanErr := fmt.Errorf("")
  183. wg.Add(len(statuses))
  184. for _, status := range statuses {
  185. go func(status string) {
  186. defer wg.Done()
  187. runs, _, err := client.Actions.ListWorkflowRunsByFileName(
  188. context.Background(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  189. &github.ListWorkflowRunsOptions{
  190. Branch: event.GetPullRequest().GetHead().GetRef(),
  191. Status: status,
  192. },
  193. )
  194. if err == nil {
  195. for _, run := range runs.WorkflowRuns {
  196. resp, err := client.Actions.CancelWorkflowRunByID(context.Background(), owner, repo, run.GetID())
  197. if err != nil && resp.StatusCode != http.StatusAccepted {
  198. // the go library we are using returns a 202 Accepted status as an error
  199. // in this case, we should rule this out as an error
  200. chanErr = fmt.Errorf("%s: error cancelling %s: %w", chanErr.Error(), run.GetHTMLURL(), err)
  201. }
  202. }
  203. } else {
  204. chanErr = fmt.Errorf("%s: error listing workflows for status %s: %w", chanErr.Error(), status, err)
  205. }
  206. }(status)
  207. }
  208. wg.Wait()
  209. err = c.deleteDeployment(r, depl, env, client)
  210. if err != nil {
  211. deleteErr := fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  212. "error deleting deployment: %w", webhookID, owner, repo, env.ID, depl.ID, event.GetPullRequest().GetNumber(), err)
  213. if chanErr.Error() != "" {
  214. deleteErr = fmt.Errorf("%s. errors found while trying to cancel active workflow runs %w", deleteErr.Error(), chanErr)
  215. }
  216. return deleteErr
  217. } else if chanErr.Error() != "" {
  218. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  219. "deployment deleted but errors found while trying to cancel active workflow runs %w", webhookID, owner, repo, env.ID, depl.ID,
  220. event.GetPullRequest().GetNumber(), chanErr)
  221. }
  222. } else if event.GetChanges() != nil {
  223. shouldUpdate := false
  224. if event.GetChanges().GetTitle() != nil && event.GetPullRequest().GetTitle() != depl.PRName {
  225. depl.PRName = event.GetPullRequest().GetTitle()
  226. shouldUpdate = true
  227. }
  228. if event.GetChanges().GetBase() != nil && event.GetChanges().GetBase().GetRef() != nil && event.GetPullRequest().GetBase().GetRef() != depl.PRBranchInto {
  229. depl.PRBranchInto = event.GetPullRequest().GetBase().GetRef()
  230. shouldUpdate = true
  231. }
  232. if shouldUpdate {
  233. _, err := c.Repo().Environment().UpdateDeployment(depl)
  234. if err != nil {
  235. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, deploymentID: %d, prNumber: %d] "+
  236. "error updating deployment to reflect changes in the pull request %w", webhookID, owner, repo, env.ID, depl.ID,
  237. event.GetPullRequest().GetNumber(), err)
  238. }
  239. }
  240. }
  241. }
  242. return nil
  243. }
  244. func (c *GithubIncomingWebhookHandler) deleteDeployment(
  245. r *http.Request,
  246. depl *models.Deployment,
  247. env *models.Environment,
  248. client *github.Client,
  249. ) error {
  250. cluster, err := c.Repo().Cluster().ReadCluster(env.ProjectID, env.ClusterID)
  251. if err != nil {
  252. return fmt.Errorf("[projectID: %d, clusterID: %d] error reading cluster when deleting existing deployment: %w",
  253. env.ProjectID, env.ClusterID, err)
  254. }
  255. agent, err := c.GetAgent(r, cluster, "")
  256. if err != nil {
  257. return err
  258. }
  259. // make sure we do not delete any kubernetes "system" namespaces
  260. if !isSystemNamespace(depl.Namespace) {
  261. err = agent.DeleteNamespace(depl.Namespace)
  262. if err != nil {
  263. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error deleting namespace '%s': %w",
  264. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, depl.Namespace, err)
  265. }
  266. }
  267. // Create new deployment status to indicate deployment is ready
  268. state := "inactive"
  269. deploymentStatusRequest := github.DeploymentStatusRequest{
  270. State: &state,
  271. }
  272. client.Repositories.CreateDeploymentStatus(
  273. context.Background(),
  274. env.GitRepoOwner,
  275. env.GitRepoName,
  276. depl.GHDeploymentID,
  277. &deploymentStatusRequest,
  278. )
  279. _, err = c.Repo().Environment().DeleteDeployment(depl)
  280. if err != nil {
  281. return fmt.Errorf("[owner: %s, repo: %s, environmentID: %d, deploymentID: %d] error updating deployment: %w",
  282. env.GitRepoOwner, env.GitRepoName, env.ID, depl.ID, err)
  283. }
  284. return nil
  285. }
  286. func (c *GithubIncomingWebhookHandler) processPushEvent(event *github.PushEvent, r *http.Request) error {
  287. if !strings.HasPrefix(event.GetRef(), "refs/heads/") {
  288. return nil
  289. }
  290. // get the webhook id from the request
  291. webhookID, reqErr := requestutils.GetURLParamString(r, types.URLParamIncomingWebhookID)
  292. if reqErr != nil {
  293. return fmt.Errorf(reqErr.Error())
  294. }
  295. owner := event.GetRepo().GetOwner().GetLogin()
  296. repo := event.GetRepo().GetName()
  297. env, err := c.Repo().Environment().ReadEnvironmentByWebhookIDOwnerRepoName(webhookID, owner, repo)
  298. if err != nil {
  299. if errors.Is(err, gorm.ErrRecordNotFound) {
  300. return nil
  301. }
  302. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] error reading environment: %w", webhookID, owner, repo, err)
  303. }
  304. envType := env.ToEnvironmentType()
  305. if len(envType.GitDeployBranches) == 0 {
  306. return nil
  307. }
  308. branch := strings.TrimPrefix(event.GetRef(), "refs/heads/")
  309. found := false
  310. for _, br := range envType.GitDeployBranches {
  311. if br == branch {
  312. found = true
  313. break
  314. }
  315. }
  316. if !found {
  317. return nil
  318. }
  319. client, err := getGithubClientFromEnvironment(c.Config(), env)
  320. if err != nil {
  321. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s] error creating github client: %w", webhookID, owner, repo, err)
  322. }
  323. namespace := fmt.Sprintf("previewbranch-%s-%s-%s", branch, strings.ReplaceAll(strings.ToLower(owner), "_", "-"),
  324. strings.ReplaceAll(strings.ToLower(repo), "_", "-"))
  325. if len(namespace) > 63 {
  326. namespace = namespace[:63] // Kubernetes' DNS 1123 label requirement
  327. }
  328. var deplID uint
  329. depl, err := c.Repo().Environment().ReadDeployment(env.ID, namespace)
  330. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  331. depl, err := c.Repo().Environment().CreateDeployment(&models.Deployment{
  332. EnvironmentID: env.ID,
  333. Namespace: namespace,
  334. Status: types.DeploymentStatusCreating,
  335. PRName: fmt.Sprintf("Deployment for branch %s", branch),
  336. RepoName: repo,
  337. RepoOwner: owner,
  338. CommitSHA: event.GetAfter()[:7],
  339. PRBranchFrom: branch,
  340. PRBranchInto: branch,
  341. })
  342. if err != nil {
  343. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, branch: %s] "+
  344. "error creating new deployment: %w", webhookID, owner, repo, env.ID, branch, err)
  345. }
  346. deplID = depl.ID
  347. } else if err != nil {
  348. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, branch: %s] "+
  349. "error reading deployment: %w", webhookID, owner, repo, env.ID, branch, err)
  350. } else {
  351. deplID = depl.ID
  352. }
  353. // FIXME: we should case on if env mode is auto or manual
  354. _, err = client.Actions.CreateWorkflowDispatchEventByFileName(
  355. r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
  356. github.CreateWorkflowDispatchEventRequest{
  357. Ref: branch,
  358. Inputs: map[string]interface{}{
  359. "pr_number": fmt.Sprintf("%d", deplID),
  360. "pr_title": fmt.Sprintf("Deployment for branch %s", branch),
  361. "pr_branch_from": branch,
  362. "pr_branch_into": branch,
  363. },
  364. },
  365. )
  366. if err != nil {
  367. return fmt.Errorf("[webhookID: %s, owner: %s, repo: %s, environmentID: %d, branch: %s] "+
  368. "error creating workflow dispatch event: %w", webhookID, owner, repo, env.ID, branch, err)
  369. }
  370. return nil
  371. }
  372. func isSystemNamespace(namespace string) bool {
  373. return namespace == "cert-manager" || namespace == "ingress-nginx" ||
  374. namespace == "kube-node-lease" || namespace == "kube-public" ||
  375. namespace == "kube-system" || namespace == "monitoring" ||
  376. namespace == "porter-agent-system" || namespace == "default" ||
  377. namespace == "ingress-nginx-private"
  378. }
  379. func getGithubClientFromEnvironment(config *config.Config, env *models.Environment) (*github.Client, error) {
  380. // get the github app client
  381. ghAppId, err := strconv.Atoi(config.ServerConf.GithubAppID)
  382. if err != nil {
  383. return nil, err
  384. }
  385. // authenticate as github app installation
  386. itr, err := ghinstallation.NewKeyFromFile(
  387. http.DefaultTransport,
  388. int64(ghAppId),
  389. int64(env.GitInstallationID),
  390. config.ServerConf.GithubAppSecretPath,
  391. )
  392. if err != nil {
  393. return nil, err
  394. }
  395. return github.NewClient(&http.Client{Transport: itr}), nil
  396. }