github.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "github.com/google/go-github/github"
  12. log "github.com/sirupsen/logrus"
  13. "golang.org/x/oauth2"
  14. git "gopkg.in/src-d/go-git.v4"
  15. "gopkg.in/src-d/go-git.v4/storage/memory"
  16. )
  17. var githubPages = 100
  18. // auditPR audits a single github PR
  19. func auditGithubPR() ([]Leak, error) {
  20. var leaks []Leak
  21. ctx := context.Background()
  22. githubClient := github.NewClient(githubToken())
  23. splits := strings.Split(opts.GithubPR, "/")
  24. owner := splits[len(splits)-4]
  25. repo := splits[len(splits)-3]
  26. prNum, err := strconv.Atoi(splits[len(splits)-1])
  27. if err != nil {
  28. return nil, err
  29. }
  30. page := 1
  31. for {
  32. commits, resp, err := githubClient.PullRequests.ListCommits(ctx, owner, repo, prNum, &github.ListOptions{
  33. PerPage: githubPages,
  34. Page: page,
  35. })
  36. if err != nil {
  37. return leaks, err
  38. }
  39. for _, commit := range commits {
  40. totalCommits = totalCommits + 1
  41. commit, _, err := githubClient.Repositories.GetCommit(ctx, owner, repo, *commit.SHA)
  42. if err != nil {
  43. continue
  44. }
  45. files := commit.Files
  46. for _, f := range files {
  47. diff := gitDiff{
  48. sha: commit.GetSHA(),
  49. content: *f.Patch,
  50. filePath: *f.Filename,
  51. repoName: repo,
  52. githubCommit: commit,
  53. author: commit.GetCommitter().GetLogin(),
  54. message: *commit.Commit.Message,
  55. }
  56. leaks = append(leaks, inspect(diff)...)
  57. }
  58. }
  59. page = resp.NextPage
  60. if resp.LastPage == 0 {
  61. break
  62. }
  63. }
  64. return leaks, nil
  65. }
  66. // auditGithubRepos kicks off audits if --github-user or --github-org options are set.
  67. // First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
  68. // After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
  69. // If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
  70. func auditGithubRepos() ([]Leak, error) {
  71. var (
  72. err error
  73. githubRepos []*github.Repository
  74. pagedGithubRepos []*github.Repository
  75. resp *github.Response
  76. githubOrgOptions *github.RepositoryListByOrgOptions
  77. githubOptions *github.RepositoryListOptions
  78. done bool
  79. leaks []Leak
  80. ownerDir string
  81. )
  82. ctx := context.Background()
  83. githubClient := github.NewClient(githubToken())
  84. if opts.GithubOrg != "" {
  85. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  86. ghURL, _ := url.Parse(opts.GithubURL)
  87. githubClient.BaseURL = ghURL
  88. }
  89. githubOrgOptions = &github.RepositoryListByOrgOptions{
  90. ListOptions: github.ListOptions{PerPage: 100},
  91. }
  92. } else if opts.GithubUser != "" {
  93. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  94. ghURL, _ := url.Parse(opts.GithubURL)
  95. githubClient.BaseURL = ghURL
  96. }
  97. githubOptions = &github.RepositoryListOptions{
  98. Affiliation: "owner",
  99. ListOptions: github.ListOptions{
  100. PerPage: 100,
  101. },
  102. }
  103. }
  104. for {
  105. if done {
  106. break
  107. }
  108. if opts.GithubUser != "" {
  109. // if opts.IncludePrivate {
  110. // pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, "", githubOptions)
  111. // } else {
  112. pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
  113. // }
  114. if err != nil {
  115. done = true
  116. }
  117. githubOptions.Page = resp.NextPage
  118. githubRepos = append(githubRepos, pagedGithubRepos...)
  119. if resp.NextPage == 0 {
  120. done = true
  121. }
  122. } else if opts.GithubOrg != "" {
  123. pagedGithubRepos, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
  124. if err != nil {
  125. done = true
  126. }
  127. githubOrgOptions.Page = resp.NextPage
  128. githubRepos = append(githubRepos, pagedGithubRepos...)
  129. if resp.NextPage == 0 {
  130. done = true
  131. }
  132. }
  133. if opts.Log == "Debug" || opts.Log == "debug" {
  134. for _, githubRepo := range pagedGithubRepos {
  135. log.Debugf("staging repos %s", *githubRepo.Name)
  136. }
  137. }
  138. }
  139. if err != nil {
  140. return nil, err
  141. }
  142. if opts.Disk {
  143. ownerDir, err = ioutil.TempDir(dir, opts.GithubUser)
  144. os.RemoveAll(ownerDir)
  145. }
  146. for _, githubRepo := range githubRepos {
  147. repo, err := cloneGithubRepo(githubRepo)
  148. if err != nil {
  149. log.Warn(err)
  150. continue
  151. }
  152. leaksFromRepo, err := auditGitRepo(repo)
  153. if opts.Disk {
  154. os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
  155. }
  156. if len(leaksFromRepo) == 0 {
  157. log.Infof("no leaks found for repo %s", *githubRepo.Name)
  158. } else {
  159. log.Warnf("leaks found for repo %s", *githubRepo.Name)
  160. }
  161. if err != nil {
  162. log.Warn(err)
  163. }
  164. leaks = append(leaks, leaksFromRepo...)
  165. }
  166. return leaks, nil
  167. }
  168. // cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
  169. // will be cloned to disk if --disk is set. If the repo is private, you must include the
  170. // --private/-p option. After the repo is clone, an audit will begin.
  171. func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
  172. var (
  173. repo *git.Repository
  174. err error
  175. )
  176. if opts.ExcludeForks && githubRepo.GetFork() {
  177. return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
  178. }
  179. for _, re := range whiteListRepos {
  180. if re.FindString(*githubRepo.Name) != "" {
  181. return nil, fmt.Errorf("skipping %s, whitelisted", *githubRepo.Name)
  182. }
  183. }
  184. log.Infof("cloning: %s", *githubRepo.Name)
  185. if opts.Disk {
  186. ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
  187. if err != nil {
  188. return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
  189. }
  190. if sshAuth != nil {
  191. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  192. URL: *githubRepo.SSHURL,
  193. Auth: sshAuth,
  194. })
  195. } else {
  196. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  197. URL: *githubRepo.CloneURL,
  198. })
  199. }
  200. } else {
  201. if sshAuth != nil {
  202. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  203. URL: *githubRepo.SSHURL,
  204. Auth: sshAuth,
  205. })
  206. } else {
  207. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  208. URL: *githubRepo.CloneURL,
  209. })
  210. }
  211. }
  212. if err != nil {
  213. return nil, err
  214. }
  215. return &RepoDescriptor{
  216. repository: repo,
  217. name: *githubRepo.Name,
  218. }, nil
  219. }
  220. // githubToken returns an oauth2 client for the github api to consume. This token is necessary
  221. // if you are running audits with --github-user or --github-org
  222. func githubToken() *http.Client {
  223. githubToken := os.Getenv("GITHUB_TOKEN")
  224. if githubToken == "" {
  225. return nil
  226. }
  227. ts := oauth2.StaticTokenSource(
  228. &oauth2.Token{AccessToken: githubToken},
  229. )
  230. return oauth2.NewClient(context.Background(), ts)
  231. }