github.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 err != nil {
  151. log.Warn(err)
  152. continue
  153. }
  154. if opts.Disk {
  155. os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
  156. }
  157. if len(leaksFromRepo) == 0 {
  158. log.Infof("no leaks found for repo %s", *githubRepo.Name)
  159. } else {
  160. log.Warnf("leaks found for repo %s", *githubRepo.Name)
  161. }
  162. if err != nil {
  163. log.Warn(err)
  164. }
  165. leaks = append(leaks, leaksFromRepo...)
  166. }
  167. return leaks, nil
  168. }
  169. // cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
  170. // will be cloned to disk if --disk is set. If the repo is private, you must include the
  171. // --private/-p option. After the repo is clone, an audit will begin.
  172. func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
  173. var (
  174. repo *git.Repository
  175. err error
  176. )
  177. githubToken := os.Getenv("GITHUB_TOKEN")
  178. if opts.ExcludeForks && githubRepo.GetFork() {
  179. return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
  180. }
  181. for _, re := range whiteListRepos {
  182. if re.FindString(*githubRepo.Name) != "" {
  183. return nil, fmt.Errorf("skipping %s, whitelisted", *githubRepo.Name)
  184. }
  185. }
  186. log.Infof("cloning: %s", *githubRepo.Name)
  187. if opts.Disk {
  188. ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
  189. if err != nil {
  190. return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
  191. }
  192. if sshAuth != nil && githubToken == "" {
  193. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  194. URL: *githubRepo.SSHURL,
  195. Auth: sshAuth,
  196. })
  197. } else if githubToken != "" {
  198. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  199. URL: *githubRepo.CloneURL,
  200. Auth: &gitHttp.BasicAuth{
  201. Username: "fakeUsername", // yes, this can be anything except an empty string
  202. Password: githubToken,
  203. },
  204. })
  205. } else {
  206. repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
  207. URL: *githubRepo.CloneURL,
  208. })
  209. }
  210. } else {
  211. if sshAuth != nil && githubToken == "" {
  212. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  213. URL: *githubRepo.SSHURL,
  214. Auth: sshAuth,
  215. })
  216. } else if githubToken != "" {
  217. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  218. URL: *githubRepo.CloneURL,
  219. Auth: &gitHttp.BasicAuth{
  220. Username: "fakeUsername", // yes, this can be anything except an empty string
  221. Password: githubToken,
  222. },
  223. })
  224. } else {
  225. repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
  226. URL: *githubRepo.CloneURL,
  227. })
  228. }
  229. }
  230. if err != nil {
  231. return nil, err
  232. }
  233. return &RepoDescriptor{
  234. repository: repo,
  235. name: *githubRepo.Name,
  236. }, nil
  237. }
  238. // githubToken returns an oauth2 client for the github api to consume. This token is necessary
  239. // if you are running audits with --github-user or --github-org
  240. func githubToken() *http.Client {
  241. githubToken := os.Getenv("GITHUB_TOKEN")
  242. if githubToken == "" {
  243. return nil
  244. }
  245. ts := oauth2.StaticTokenSource(
  246. &oauth2.Token{AccessToken: githubToken},
  247. )
  248. return oauth2.NewClient(context.Background(), ts)
  249. }