github.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. }
  60. leaks = append(leaks, inspect(diff)...)
  61. }
  62. }
  63. page = resp.NextPage
  64. if resp.LastPage == 0 {
  65. break
  66. }
  67. }
  68. return leaks, nil
  69. }
  70. // auditGithubRepos kicks off audits if --github-user or --github-org options are set.
  71. // First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
  72. // After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
  73. // If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
  74. func auditGithubRepos() ([]Leak, error) {
  75. var (
  76. err error
  77. githubRepos []*github.Repository
  78. pagedGithubRepos []*github.Repository
  79. resp *github.Response
  80. githubOrgOptions *github.RepositoryListByOrgOptions
  81. githubOptions *github.RepositoryListOptions
  82. done bool
  83. leaks []Leak
  84. ownerDir string
  85. )
  86. ctx := context.Background()
  87. githubClient := github.NewClient(githubToken())
  88. if opts.GithubOrg != "" {
  89. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  90. ghURL, _ := url.Parse(opts.GithubURL)
  91. githubClient.BaseURL = ghURL
  92. }
  93. githubOrgOptions = &github.RepositoryListByOrgOptions{
  94. ListOptions: github.ListOptions{PerPage: 100},
  95. }
  96. } else if opts.GithubUser != "" {
  97. if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
  98. ghURL, _ := url.Parse(opts.GithubURL)
  99. githubClient.BaseURL = ghURL
  100. }
  101. githubOptions = &github.RepositoryListOptions{
  102. Affiliation: "owner",
  103. ListOptions: github.ListOptions{
  104. PerPage: 100,
  105. },
  106. }
  107. }
  108. for {
  109. if done {
  110. break
  111. }
  112. if opts.GithubUser != "" {
  113. pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
  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 opts.Disk {
  140. ownerDir, _ = ioutil.TempDir(dir, opts.GithubUser)
  141. }
  142. for _, githubRepo := range githubRepos {
  143. repo, err := cloneGithubRepo(githubRepo)
  144. if err != nil {
  145. log.Warn(err)
  146. continue
  147. }
  148. leaksFromRepo, err := auditGitRepo(repo)
  149. if opts.Disk {
  150. os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
  151. }
  152. if len(leaksFromRepo) == 0 {
  153. log.Infof("no leaks found for repo %s", *githubRepo.Name)
  154. } else {
  155. log.Warnf("leaks found for repo %s", *githubRepo.Name)
  156. }
  157. if err != nil {
  158. log.Warn(err)
  159. }
  160. leaks = append(leaks, leaksFromRepo...)
  161. }
  162. return leaks, nil
  163. }
  164. // cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
  165. // will be cloned to disk if --disk is set. If the repo is private, you must include the
  166. // --private/-p option. After the repo is clone, an audit will begin.
  167. func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
  168. var (
  169. repo *git.Repository
  170. err error
  171. )
  172. githubToken := os.Getenv("GITHUB_TOKEN")
  173. if opts.ExcludeForks && githubRepo.GetFork() {
  174. return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
  175. }
  176. for _, re := range whiteListRepos {
  177. if re.FindString(*githubRepo.Name) != "" {
  178. return nil, fmt.Errorf("skipping %s, whitelisted", *githubRepo.Name)
  179. }
  180. }
  181. log.Infof("cloning: %s", *githubRepo.Name)
  182. if opts.Disk {
  183. ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
  184. if err != nil {
  185. return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
  186. }
  187. if sshAuth != nil && githubToken == "" {
  188. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  189. URL: *githubRepo.SSHURL,
  190. Auth: sshAuth,
  191. })
  192. } else if githubToken != "" {
  193. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  194. URL: *githubRepo.CloneURL,
  195. Auth: &gitHttp.BasicAuth{
  196. Username: "fakeUsername", // yes, this can be anything except an empty string
  197. Password: githubToken,
  198. },
  199. })
  200. } else {
  201. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  202. URL: *githubRepo.CloneURL,
  203. })
  204. }
  205. } else {
  206. if sshAuth != nil && githubToken == "" {
  207. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  208. URL: *githubRepo.SSHURL,
  209. Auth: sshAuth,
  210. })
  211. } else if githubToken != "" {
  212. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  213. URL: *githubRepo.CloneURL,
  214. Auth: &gitHttp.BasicAuth{
  215. Username: "fakeUsername", // yes, this can be anything except an empty string
  216. Password: githubToken,
  217. },
  218. })
  219. } else {
  220. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  221. URL: *githubRepo.CloneURL,
  222. })
  223. }
  224. }
  225. if err != nil {
  226. return nil, err
  227. }
  228. return &RepoDescriptor{
  229. repository: repo,
  230. name: *githubRepo.Name,
  231. }, nil
  232. }
  233. // githubToken returns an oauth2 client for the github api to consume. This token is necessary
  234. // if you are running audits with --github-user or --github-org
  235. func githubToken() *http.Client {
  236. githubToken := os.Getenv("GITHUB_TOKEN")
  237. if githubToken == "" {
  238. return nil
  239. }
  240. ts := oauth2.StaticTokenSource(
  241. &oauth2.Token{AccessToken: githubToken},
  242. )
  243. return oauth2.NewClient(context.Background(), ts)
  244. }