git_repo_handler.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/porter-dev/porter/internal/models"
  7. "golang.org/x/oauth2"
  8. "net/http"
  9. "net/url"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "github.com/bradleyfalzon/ghinstallation"
  15. "github.com/go-chi/chi"
  16. "github.com/google/go-github/github"
  17. )
  18. // HandleListProjectGitRepos returns a list of git repos for a project
  19. func (app *App) HandleListProjectGitRepos(w http.ResponseWriter, r *http.Request) {
  20. tok, err := app.getGithubAppOauthTokenFromRequest(r)
  21. if err != nil {
  22. json.NewEncoder(w).Encode(make([]*models.GitRepoExternal, 0))
  23. return
  24. }
  25. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  26. accountIds := make([]int64, 0)
  27. AuthUser, _, err := client.Users.Get(context.Background(), "")
  28. if err != nil {
  29. app.handleErrorInternal(err, w)
  30. return
  31. }
  32. accountIds = append(accountIds, *AuthUser.ID)
  33. opts := &github.ListOptions{
  34. PerPage: 100,
  35. Page: 1,
  36. }
  37. for {
  38. orgs, pages, err := client.Organizations.List(context.Background(), "", opts)
  39. if err != nil {
  40. res := HandleListGithubAppAccessResp{
  41. HasAccess: false,
  42. }
  43. json.NewEncoder(w).Encode(res)
  44. return
  45. }
  46. for _, org := range orgs {
  47. accountIds = append(accountIds, *org.ID)
  48. }
  49. if pages.NextPage == 0 {
  50. break
  51. }
  52. }
  53. installationData, err := app.Repo.GithubAppInstallation.ReadGithubAppInstallationByAccountIDs(accountIds)
  54. if err != nil {
  55. app.handleErrorInternal(err, w)
  56. return
  57. }
  58. installationIds := make([]int64, 0)
  59. for _, v := range installationData {
  60. installationIds = append(installationIds, v.InstallationID)
  61. }
  62. json.NewEncoder(w).Encode(installationIds)
  63. }
  64. // Repo represents a GitHub or Gitab repository
  65. type Repo struct {
  66. FullName string
  67. Kind string
  68. }
  69. // DirectoryItem represents a file or subfolder in a repository
  70. type DirectoryItem struct {
  71. Path string
  72. Type string
  73. }
  74. // AutoBuildpack represents an automatically detected buildpack
  75. type AutoBuildpack struct {
  76. Valid bool `json:"valid"`
  77. Name string `json:"name"`
  78. }
  79. // HandleListRepos retrieves a list of repo names
  80. func (app *App) HandleListRepos(w http.ResponseWriter, r *http.Request) {
  81. client, err := app.githubAppClientFromRequest(r)
  82. if err != nil {
  83. app.handleErrorInternal(err, w)
  84. return
  85. }
  86. // figure out number of repositories
  87. opt := &github.RepositoryListOptions{
  88. ListOptions: github.ListOptions{
  89. PerPage: 100,
  90. },
  91. Sort: "updated",
  92. }
  93. //client.Apps.ListRepos()
  94. allRepos, resp, err := client.Repositories.List(context.Background(), "", opt)
  95. if err != nil {
  96. app.handleErrorInternal(err, w)
  97. return
  98. }
  99. // make workers to get pages concurrently
  100. const WCOUNT = 5
  101. numPages := resp.LastPage + 1
  102. var workerErr error
  103. var mu sync.Mutex
  104. var wg sync.WaitGroup
  105. worker := func(cp int) {
  106. defer wg.Done()
  107. for cp < numPages {
  108. cur_opt := &github.RepositoryListOptions{
  109. ListOptions: github.ListOptions{
  110. Page: cp,
  111. PerPage: 100,
  112. },
  113. Sort: "updated",
  114. }
  115. repos, _, err := client.Repositories.List(context.Background(), "", cur_opt)
  116. if err != nil {
  117. mu.Lock()
  118. workerErr = err
  119. mu.Unlock()
  120. return
  121. }
  122. mu.Lock()
  123. allRepos = append(allRepos, repos...)
  124. mu.Unlock()
  125. cp += WCOUNT
  126. }
  127. }
  128. var numJobs int
  129. if numPages > WCOUNT {
  130. numJobs = WCOUNT
  131. } else {
  132. numJobs = numPages
  133. }
  134. wg.Add(numJobs)
  135. // page 1 is already loaded so we start with 2
  136. for i := 1; i <= numJobs; i++ {
  137. go worker(i + 1)
  138. }
  139. wg.Wait()
  140. if workerErr != nil {
  141. app.handleErrorInternal(workerErr, w)
  142. return
  143. }
  144. res := make([]Repo, 0)
  145. for _, repo := range allRepos {
  146. res = append(res, Repo{
  147. FullName: repo.GetFullName(),
  148. Kind: "github",
  149. })
  150. }
  151. json.NewEncoder(w).Encode(res)
  152. }
  153. // HandleDeleteProjectGitRepo handles the deletion of a Github Repo via the git repo ID
  154. func (app *App) HandleDeleteProjectGitRepo(w http.ResponseWriter, r *http.Request) {
  155. id, err := strconv.ParseUint(chi.URLParam(r, "git_repo_id"), 0, 64)
  156. if err != nil || id == 0 {
  157. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  158. return
  159. }
  160. repo, err := app.Repo.GitRepo.ReadGitRepo(uint(id))
  161. if err != nil {
  162. app.handleErrorRead(err, ErrProjectDataRead, w)
  163. return
  164. }
  165. err = app.Repo.GitRepo.DeleteGitRepo(repo)
  166. if err != nil {
  167. app.handleErrorRead(err, ErrProjectDataRead, w)
  168. return
  169. }
  170. w.WriteHeader(http.StatusOK)
  171. }
  172. // HandleGetBranches retrieves a list of branch names for a specified repo
  173. func (app *App) HandleGetBranches(w http.ResponseWriter, r *http.Request) {
  174. tok, err := app.githubTokenFromRequest(r)
  175. if err != nil {
  176. app.handleErrorInternal(err, w)
  177. return
  178. }
  179. owner := chi.URLParam(r, "owner")
  180. name := chi.URLParam(r, "name")
  181. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  182. // List all branches for a specified repo
  183. allBranches, resp, err := client.Repositories.ListBranches(context.Background(), owner, name, &github.ListOptions{
  184. PerPage: 100,
  185. })
  186. if err != nil {
  187. app.handleErrorInternal(err, w)
  188. return
  189. }
  190. // make workers to get branches concurrently
  191. const WCOUNT = 5
  192. numPages := resp.LastPage + 1
  193. var workerErr error
  194. var mu sync.Mutex
  195. var wg sync.WaitGroup
  196. worker := func(cp int) {
  197. defer wg.Done()
  198. for cp < numPages {
  199. opts := &github.ListOptions{
  200. Page: cp,
  201. PerPage: 100,
  202. }
  203. branches, _, err := client.Repositories.ListBranches(context.Background(), owner, name, opts)
  204. if err != nil {
  205. mu.Lock()
  206. workerErr = err
  207. mu.Unlock()
  208. return
  209. }
  210. mu.Lock()
  211. allBranches = append(allBranches, branches...)
  212. mu.Unlock()
  213. cp += WCOUNT
  214. }
  215. }
  216. var numJobs int
  217. if numPages > WCOUNT {
  218. numJobs = WCOUNT
  219. } else {
  220. numJobs = numPages
  221. }
  222. wg.Add(numJobs)
  223. // page 1 is already loaded so we start with 2
  224. for i := 1; i <= numJobs; i++ {
  225. go worker(i + 1)
  226. }
  227. wg.Wait()
  228. if workerErr != nil {
  229. app.handleErrorInternal(workerErr, w)
  230. return
  231. }
  232. res := make([]string, 0)
  233. for _, b := range allBranches {
  234. res = append(res, b.GetName())
  235. }
  236. json.NewEncoder(w).Encode(res)
  237. }
  238. // HandleDetectBuildpack attempts to figure which buildpack will be auto used based on directory contents
  239. func (app *App) HandleDetectBuildpack(w http.ResponseWriter, r *http.Request) {
  240. tok, err := app.githubTokenFromRequest(r)
  241. if err != nil {
  242. app.handleErrorInternal(err, w)
  243. return
  244. }
  245. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  246. if err != nil {
  247. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  248. return
  249. }
  250. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  251. owner := chi.URLParam(r, "owner")
  252. name := chi.URLParam(r, "name")
  253. branch := chi.URLParam(r, "branch")
  254. repoContentOptions := github.RepositoryContentGetOptions{}
  255. repoContentOptions.Ref = branch
  256. _, directoryContents, _, err := client.Repositories.GetContents(context.Background(), owner, name, queryParams["dir"][0], &repoContentOptions)
  257. if err != nil {
  258. app.handleErrorInternal(err, w)
  259. return
  260. }
  261. var BREQS = map[string]string{
  262. "requirements.txt": "Python",
  263. "Gemfile": "Ruby",
  264. "package.json": "Node.js",
  265. "pom.xml": "Java",
  266. "composer.json": "PHP",
  267. }
  268. res := AutoBuildpack{
  269. Valid: true,
  270. }
  271. matches := 0
  272. for i := range directoryContents {
  273. name := *directoryContents[i].Name
  274. bname, ok := BREQS[name]
  275. if ok {
  276. matches++
  277. res.Name = bname
  278. }
  279. }
  280. if matches != 1 {
  281. res.Valid = false
  282. res.Name = ""
  283. }
  284. json.NewEncoder(w).Encode(res)
  285. }
  286. // HandleGetBranchContents retrieves the contents of a specific branch and subdirectory
  287. func (app *App) HandleGetBranchContents(w http.ResponseWriter, r *http.Request) {
  288. tok, err := app.githubTokenFromRequest(r)
  289. if err != nil {
  290. app.handleErrorInternal(err, w)
  291. return
  292. }
  293. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  294. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  295. if err != nil {
  296. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  297. return
  298. }
  299. owner := chi.URLParam(r, "owner")
  300. name := chi.URLParam(r, "name")
  301. branch := chi.URLParam(r, "branch")
  302. repoContentOptions := github.RepositoryContentGetOptions{}
  303. repoContentOptions.Ref = branch
  304. _, directoryContents, _, err := client.Repositories.GetContents(context.Background(), owner, name, queryParams["dir"][0], &repoContentOptions)
  305. if err != nil {
  306. app.handleErrorInternal(err, w)
  307. return
  308. }
  309. res := []DirectoryItem{}
  310. for i := range directoryContents {
  311. d := DirectoryItem{}
  312. d.Path = *directoryContents[i].Path
  313. d.Type = *directoryContents[i].Type
  314. res = append(res, d)
  315. }
  316. // Ret2: recursively traverse all dirs to create config bundle (case on type == dir)
  317. // https://api.github.com/repos/porter-dev/porter/contents?ref=frontend-graph
  318. json.NewEncoder(w).Encode(res)
  319. }
  320. type GetProcfileContentsResp map[string]string
  321. var procfileRegex = regexp.MustCompile("^([A-Za-z0-9_]+):\\s*(.+)$")
  322. // HandleGetProcfileContents retrieves the contents of a procfile in a github repo
  323. func (app *App) HandleGetProcfileContents(w http.ResponseWriter, r *http.Request) {
  324. tok, err := app.githubTokenFromRequest(r)
  325. if err != nil {
  326. app.handleErrorInternal(err, w)
  327. return
  328. }
  329. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  330. owner := chi.URLParam(r, "owner")
  331. name := chi.URLParam(r, "name")
  332. branch := chi.URLParam(r, "branch")
  333. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  334. if err != nil {
  335. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  336. return
  337. }
  338. resp, _, _, err := client.Repositories.GetContents(
  339. context.TODO(),
  340. owner,
  341. name,
  342. queryParams["path"][0],
  343. &github.RepositoryContentGetOptions{
  344. Ref: branch,
  345. },
  346. )
  347. if err != nil {
  348. http.NotFound(w, r)
  349. return
  350. }
  351. fileData, err := resp.GetContent()
  352. if err != nil {
  353. app.handleErrorInternal(err, w)
  354. return
  355. }
  356. parsedContents := make(GetProcfileContentsResp)
  357. // parse the procfile information
  358. for _, line := range strings.Split(fileData, "\n") {
  359. if matches := procfileRegex.FindStringSubmatch(line); matches != nil {
  360. parsedContents[matches[1]] = matches[2]
  361. }
  362. }
  363. json.NewEncoder(w).Encode(parsedContents)
  364. }
  365. type HandleGetRepoZIPDownloadURLResp struct {
  366. URLString string `json:"url"`
  367. LatestCommitSHA string `json:"latest_commit_sha"`
  368. }
  369. // HandleGetRepoZIPDownloadURL gets the URL for downloading a zip file from a Github
  370. // repository
  371. func (app *App) HandleGetRepoZIPDownloadURL(w http.ResponseWriter, r *http.Request) {
  372. tok, err := app.githubTokenFromRequest(r)
  373. if err != nil {
  374. app.handleErrorInternal(err, w)
  375. return
  376. }
  377. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  378. owner := chi.URLParam(r, "owner")
  379. name := chi.URLParam(r, "name")
  380. branch := chi.URLParam(r, "branch")
  381. branchResp, _, err := client.Repositories.GetBranch(
  382. context.TODO(),
  383. owner,
  384. name,
  385. branch,
  386. )
  387. if err != nil {
  388. app.handleErrorInternal(err, w)
  389. return
  390. }
  391. ghURL, _, err := client.Repositories.GetArchiveLink(
  392. context.TODO(),
  393. owner,
  394. name,
  395. github.Zipball,
  396. &github.RepositoryContentGetOptions{
  397. Ref: *branchResp.Commit.SHA,
  398. },
  399. )
  400. if err != nil {
  401. app.handleErrorInternal(err, w)
  402. return
  403. }
  404. apiResp := HandleGetRepoZIPDownloadURLResp{
  405. URLString: ghURL.String(),
  406. LatestCommitSHA: *branchResp.Commit.SHA,
  407. }
  408. json.NewEncoder(w).Encode(apiResp)
  409. }
  410. // githubAppClientFromRequest gets the github app installation id from the request and authenticates
  411. // using it and a private key file
  412. func (app *App) githubAppClientFromRequest(r *http.Request) (*github.Client, error) {
  413. installationID, err := strconv.ParseUint(chi.URLParam(r, "installation_id"), 0, 64)
  414. if err != nil || installationID == 0 {
  415. return nil, fmt.Errorf("could not read installation id")
  416. }
  417. fmt.Println(app.GithubAppConf.AppID)
  418. itr, err := ghinstallation.NewKeyFromFile(
  419. http.DefaultTransport,
  420. app.GithubAppConf.AppID,
  421. int64(installationID),
  422. "/porter/docker/github_app_private_key.pem")
  423. if err != nil {
  424. fmt.Println(err)
  425. return nil, err
  426. }
  427. return github.NewClient(&http.Client{Transport: itr}), nil
  428. }
  429. // finds the github token given the git repo id and the project id
  430. func (app *App) githubTokenFromRequest(
  431. r *http.Request,
  432. ) (*oauth2.Token, error) {
  433. grID, err := strconv.ParseUint(chi.URLParam(r, "git_repo_id"), 0, 64)
  434. if err != nil || grID == 0 {
  435. return nil, fmt.Errorf("could not read git repo id")
  436. }
  437. // query for the git repo
  438. gr, err := app.Repo.GitRepo.ReadGitRepo(uint(grID))
  439. if err != nil {
  440. return nil, err
  441. }
  442. // get the oauth integration
  443. oauthInt, err := app.Repo.OAuthIntegration.ReadOAuthIntegration(gr.OAuthIntegrationID)
  444. if err != nil {
  445. return nil, err
  446. }
  447. return &oauth2.Token{
  448. AccessToken: string(oauthInt.AccessToken),
  449. RefreshToken: string(oauthInt.RefreshToken),
  450. TokenType: "Bearer",
  451. }, nil
  452. }