github.go 7.4 KB

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