git_repo_handler.go 12 KB

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