git_repo_handler.go 12 KB

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