github.go 7.2 KB

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