mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-27 11:44:23 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87d916fc24 | ||
|
|
21b59fab5d | ||
|
|
9272e1e556 | ||
|
|
0a51dabb17 | ||
|
|
8c1cee4e00 | ||
|
|
4d5315e2ca | ||
|
|
88cc9bb363 | ||
|
|
80e41ee14c | ||
|
|
23489f3f18 | ||
|
|
a998ddc9d4 | ||
|
|
833963c1c1 | ||
|
|
4b11f87f80 | ||
|
|
923dcf0311 | ||
|
|
8896cf66cd | ||
|
|
df133ccaf8 | ||
|
|
23cd693d71 | ||
|
|
524d81fde9 | ||
|
|
d387f528c4 | ||
|
|
dcda26578b | ||
|
|
28639d3a49 | ||
|
|
19e23c9cbe | ||
|
|
160015b872 | ||
|
|
abdf2c47f0 | ||
|
|
8536f16ceb | ||
|
|
6862c13bf7 | ||
|
|
9939c638ec | ||
|
|
ed3a512b4b | ||
|
|
7c988c927d | ||
|
|
bde9af44ea | ||
|
|
eee4d05642 | ||
|
|
9144594d77 | ||
|
|
1cb15242fd | ||
|
|
08498600d1 | ||
|
|
88c0c7779b | ||
|
|
67454d109e | ||
|
|
ce603c73b4 | ||
|
|
55218fc8f8 | ||
|
|
5d81c650e8 | ||
|
|
0726209172 | ||
|
|
bfec8aca51 | ||
|
|
a9b30edb06 | ||
|
|
cc6d698e63 | ||
|
|
2ba97d0fa3 |
No files matched your search
@@ -1,6 +1,65 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
1.15.0
|
||||
----
|
||||
- Whitelist repos use regex now
|
||||
- Whitelist repo check before clone
|
||||
|
||||
1.14.0
|
||||
----
|
||||
- Entropy Range support in gitleaks config
|
||||
|
||||
1.13.0
|
||||
----
|
||||
- Github PR support
|
||||
- Github has its own go file. All other services, bitbucket, gitlab, etc should follow this convention
|
||||
|
||||
1.12.1
|
||||
----
|
||||
- Show program usage when no arguments are provided
|
||||
- Exit program after the -h or --help options are used
|
||||
|
||||
1.12.0
|
||||
----
|
||||
- removing --csv option
|
||||
- --report option now requires .json or .csv in filename
|
||||
- adding total time to audit in logs
|
||||
|
||||
1.11.1
|
||||
----
|
||||
- fix commit whitelist logic
|
||||
|
||||
1.11.0
|
||||
-----
|
||||
- Commit depth option
|
||||
- Commit stats output
|
||||
|
||||
1.10.0
|
||||
-----
|
||||
- Add entropy option
|
||||
|
||||
1.9.0
|
||||
-----
|
||||
- exclude fork option
|
||||
|
||||
1.8.0
|
||||
-----
|
||||
- whitelist repos
|
||||
- sample config option
|
||||
|
||||
1.7.3
|
||||
-----
|
||||
- style points
|
||||
|
||||
1.7.2
|
||||
-----
|
||||
- Fixing dangling goroutines, removing channel messaging
|
||||
|
||||
1.7.1
|
||||
-----
|
||||
- Fixing bug where single repos were not being audited
|
||||
|
||||
1.7.0
|
||||
-----
|
||||
- Exit code == 2 on error
|
||||
|
||||
Generated
+7
-1
@@ -44,6 +44,12 @@
|
||||
revision = "44c6ddd0a2342c386950e880b658017258da92fc"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/hako/durafmt"
|
||||
packages = ["."]
|
||||
revision = "7b7ae1e72eade09dbc9c2cfba3e6c4bae7b8bcac"
|
||||
version = "1.0.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/jbenet/go-context"
|
||||
@@ -249,6 +255,6 @@
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "8185a08afcb3ad854f58b49061fb70c57e7b64244abb43a08714d55cac7a97f9"
|
||||
inputs-digest = "ad1b6855b3c8b3e1303f29123160cde693d39d6724682ce1cd246cd1a2343c7c"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
||||
@@ -1,7 +1,7 @@
|
||||
.PHONY: test build-all deploy
|
||||
|
||||
test:
|
||||
go get github.com/golang/lint/golint
|
||||
go get golang.org/x/lint/golint
|
||||
go fmt
|
||||
golint
|
||||
go test --race --cover -run=Test$
|
||||
|
||||
@@ -6,32 +6,72 @@
|
||||
</p>
|
||||
|
||||
## Audit git repos for secrets
|
||||
### Powered by src-d's [go-git](https://github.com/src-d/go-git)
|
||||
<p align="center">
|
||||
|
||||
Gitleaks provides a way for you to find unencrypted secrets and other unwanted data types in git source code repositories.
|
||||
|
||||
As part of it's core functionality, it provides;
|
||||
* Github support including support for bulk organisation and repository owner (user) repository scans, as well as pull request scanning for use in common CI workflows.
|
||||
* Support for private repository scans, and repositories that require key based authentication
|
||||
* Output in CSV and JSON formats for consumption in other reporting tools and frameworks
|
||||
* Externalised configuration for environment specific customisation including regex rules
|
||||
* Customisable repository name, file type, commit ID, branchname and regex whitelisting to reduce false positives
|
||||
* High performance through the use of src-d's [go-git](https://github.com/src-d/go-git) framework
|
||||
|
||||
|
||||
It has been sucessfully used in a number of different scenarios, including;
|
||||
* Adhoc scans of local and remote repositories by filesystem path or clone URL
|
||||
* Automated scans of github users and organisations (Both public and enterprise platforms)
|
||||
* As part of a CICD workflow to identify secrets before they make it deeper into your codebase
|
||||
* As part of a wider secrets auditing automation capability for git data in large environments
|
||||
|
||||
|
||||
### Example execution
|
||||
|
||||
|
||||
<p align="left">
|
||||
<img src="https://cdn.rawgit.com/zricethezav/5bf8259b7fea0170becffc06b8588edb/raw/f762769fe20ef3669bff34612b1bede6457631e6/termtosvg_je8bp82s.svg">
|
||||
</p>
|
||||
|
||||
#### Installing
|
||||
#### Installation
|
||||
Written in Go, gitleaks is available in binary form for many popular platforms and OS types from the [releases page](https://github.com/zricethezav/gitleaks). Alternatively, executed via Docker or it can be installed using Go directly, as per the below;
|
||||
|
||||
##### Docker
|
||||
|
||||
```bash
|
||||
# Run gitleaks against a public repository
|
||||
docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
|
||||
|
||||
# Run gitleaks against a local repository already cloned into /tmp/
|
||||
docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/gitleaks
|
||||
|
||||
# Run gitleaks against a specific Github Pull request
|
||||
docker run --rm --name=gitleaks -e GITHUB_TOKEN={your token} zricethezav/gitleaks --github-pr=https://github.com/owner/repo/pull/9000
|
||||
```
|
||||
|
||||
##### Go
|
||||
|
||||
```bash
|
||||
go get -u github.com/zricethezav/gitleaks
|
||||
```
|
||||
Or download from release binaries [here](https://github.com/zricethezav/gitleaks/releases)
|
||||
|
||||
|
||||
#### Usage and Options
|
||||
gitleaks has a wide range of configuration options that can be adjusted at runtime or via a configuration file based on your specific requirements.
|
||||
|
||||
|
||||
```
|
||||
Usage:
|
||||
gitleaks [OPTIONS]
|
||||
|
||||
Application Options:
|
||||
-r, --repo= Repo url to audit
|
||||
--github-user= User url to audit
|
||||
--github-org= Organization url to audit
|
||||
--github-user= Github user to audit
|
||||
--github-org= Github organization to audit
|
||||
--github-url= GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/ (default: https://api.github.com/)
|
||||
--github-pr= Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set
|
||||
-p, --private Include private repos in audit
|
||||
-b, --branch= branch name to audit (defaults to HEAD)
|
||||
-c, --commit= sha of commit to stop at
|
||||
--depth= maximum commit depth
|
||||
--repo-path= Path to repo
|
||||
--owner-path= Path to owner directory (repos discovered)
|
||||
--max-go= Maximum number of concurrent go-routines gitleaks spawns
|
||||
@@ -40,28 +80,46 @@ Application Options:
|
||||
--single-search= single regular expression to search for
|
||||
--config= path to gitleaks config
|
||||
--ssh-key= path to ssh key
|
||||
--exclude-forks exclude forks for organization/user audits
|
||||
-e, --entropy= Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)
|
||||
-l, --log= log level
|
||||
-v, --verbose Show verbose output from gitleaks audit
|
||||
--report= path to write report file
|
||||
--csv report output to csv
|
||||
--redact redact secrets from log messages and report
|
||||
--version version number
|
||||
--sample-config prints a sample config file
|
||||
|
||||
Help Options:
|
||||
-h, --help Show this help message
|
||||
```
|
||||
|
||||
#### Exit Codes
|
||||
Gitleaks provides consisten exist codes to assist in automation workflows such as CICD platforms and bulk scanning.
|
||||
|
||||
These can be effectively used in conjunction with the report output file to detect and return meaningful data back to the user or external system about if leaks have been detected, and where they reside.
|
||||
|
||||
The code return codes are:
|
||||
|
||||
```
|
||||
0: no leaks
|
||||
1: leaks present
|
||||
2: error encountered
|
||||
```
|
||||
|
||||
#### Additional Examples and Explanations
|
||||
Check the wiki [here](https://github.com/zricethezav/gitleaks/wiki)
|
||||
#### Additional information
|
||||
* Additional documentation about how gitleaks functions can be found on the [wiki page](https://github.com/zricethezav/gitleaks/wiki)
|
||||
* The below links detail the various approaches to remediating unwanted data in git repos
|
||||
* [Removing sensitive data from a repository (github.com)](https://help.github.com/articles/removing-sensitive-data-from-a-repository/)
|
||||
* [Removing sensitive files from commit history (atlassian.com)](https://community.atlassian.com/t5/Bitbucket-questions/Remove-sensitive-files-from-commit-history/qaq-p/243807)
|
||||
* [Rewrite git history with the BFG (theguardian.com)](https://www.theguardian.com/info/developer-blog/2013/apr/29/rewrite-git-history-with-the-bfg)
|
||||
* [Auditing Bitbucket Server Data for Credentials in AWS (sourcedgroup.com)](https://www.sourcedgroup.com/blog/auditing-bitbucket-server-data-credentials-in-aws)
|
||||
|
||||
This blog post details how gitleaks was used to audit data in Atlassian Bitbucket server when hosted on AWS, and visualise the results in a compliance dashboard using Splunk.
|
||||
|
||||
* How does gitleaks differ to github token scanning ?
|
||||
* [Github recently announced](https://blog.github.com/2018-10-16-future-of-software/#github-token-scanning-for-public-repositories-public-beta) a new capbility to their cloud platform that detects exposed credentials for a number of common services and platforms and automatically notifies the provider for revocation or similar action. Gitleaks provides a similar detection capability for non-github cloud users, in which repositories can be easily audited and results provided in a number of formats.
|
||||
|
||||
|
||||
|
||||
|
||||
### If you find a valid leak in a repo
|
||||
Please read this [Github article on removing sensitive data from a repository](https://help.github.com/articles/removing-sensitive-data-from-a-repository/) to remove the sensitive information from your history.
|
||||
|
||||
### Run me with docker
|
||||
Simply run `docker run --rm --name=gitleaks zricethezav/gitleaks --help`
|
||||
@@ -0,0 +1,250 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/google/go-github/github"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/oauth2"
|
||||
git "gopkg.in/src-d/go-git.v4"
|
||||
"gopkg.in/src-d/go-git.v4/storage/memory"
|
||||
)
|
||||
|
||||
var githubPages = 100
|
||||
|
||||
// auditPR audits a single github PR
|
||||
func auditGithubPR() ([]Leak, error) {
|
||||
var leaks []Leak
|
||||
ctx := context.Background()
|
||||
githubClient := github.NewClient(githubToken())
|
||||
splits := strings.Split(opts.GithubPR, "/")
|
||||
owner := splits[len(splits)-4]
|
||||
repo := splits[len(splits)-3]
|
||||
prNum, err := strconv.Atoi(splits[len(splits)-1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
page := 1
|
||||
for {
|
||||
commits, resp, err := githubClient.PullRequests.ListCommits(ctx, owner, repo, prNum, &github.ListOptions{
|
||||
PerPage: githubPages,
|
||||
Page: page,
|
||||
})
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
|
||||
for _, commit := range commits {
|
||||
totalCommits = totalCommits + 1
|
||||
commit, _, err := githubClient.Repositories.GetCommit(ctx, owner, repo, *commit.SHA)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
files := commit.Files
|
||||
for _, f := range files {
|
||||
diff := gitDiff{
|
||||
sha: commit.GetSHA(),
|
||||
content: *f.Patch,
|
||||
filePath: *f.Filename,
|
||||
repoName: repo,
|
||||
githubCommit: commit,
|
||||
author: commit.GetCommitter().GetLogin(),
|
||||
message: *commit.Commit.Message,
|
||||
}
|
||||
leaks = append(leaks, inspect(diff)...)
|
||||
}
|
||||
}
|
||||
page = resp.NextPage
|
||||
if resp.LastPage == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return leaks, nil
|
||||
}
|
||||
|
||||
// auditGithubRepos kicks off audits if --github-user or --github-org options are set.
|
||||
// First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
|
||||
// After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
|
||||
// If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
|
||||
func auditGithubRepos() ([]Leak, error) {
|
||||
var (
|
||||
err error
|
||||
githubRepos []*github.Repository
|
||||
pagedGithubRepos []*github.Repository
|
||||
resp *github.Response
|
||||
githubOrgOptions *github.RepositoryListByOrgOptions
|
||||
githubOptions *github.RepositoryListOptions
|
||||
done bool
|
||||
leaks []Leak
|
||||
ownerDir string
|
||||
)
|
||||
ctx := context.Background()
|
||||
githubClient := github.NewClient(githubToken())
|
||||
|
||||
if opts.GithubOrg != "" {
|
||||
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
|
||||
ghURL, _ := url.Parse(opts.GithubURL)
|
||||
githubClient.BaseURL = ghURL
|
||||
}
|
||||
githubOrgOptions = &github.RepositoryListByOrgOptions{
|
||||
ListOptions: github.ListOptions{PerPage: 100},
|
||||
}
|
||||
} else if opts.GithubUser != "" {
|
||||
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
|
||||
ghURL, _ := url.Parse(opts.GithubURL)
|
||||
githubClient.BaseURL = ghURL
|
||||
}
|
||||
|
||||
githubOptions = &github.RepositoryListOptions{
|
||||
Affiliation: "owner",
|
||||
ListOptions: github.ListOptions{
|
||||
PerPage: 100,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
if done {
|
||||
break
|
||||
}
|
||||
if opts.GithubUser != "" {
|
||||
if opts.IncludePrivate {
|
||||
pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, "", githubOptions)
|
||||
} else {
|
||||
pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
|
||||
}
|
||||
if err != nil {
|
||||
done = true
|
||||
}
|
||||
githubOptions.Page = resp.NextPage
|
||||
githubRepos = append(githubRepos, pagedGithubRepos...)
|
||||
if resp.NextPage == 0 {
|
||||
done = true
|
||||
}
|
||||
} else if opts.GithubOrg != "" {
|
||||
pagedGithubRepos, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
|
||||
if err != nil {
|
||||
done = true
|
||||
}
|
||||
githubOrgOptions.Page = resp.NextPage
|
||||
githubRepos = append(githubRepos, pagedGithubRepos...)
|
||||
if resp.NextPage == 0 {
|
||||
done = true
|
||||
}
|
||||
}
|
||||
if opts.Log == "Debug" || opts.Log == "debug" {
|
||||
for _, githubRepo := range pagedGithubRepos {
|
||||
log.Debugf("staging repos %s", *githubRepo.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if opts.Disk {
|
||||
ownerDir, err = ioutil.TempDir(dir, opts.GithubUser)
|
||||
os.RemoveAll(ownerDir)
|
||||
}
|
||||
for _, githubRepo := range githubRepos {
|
||||
repo, err := cloneGithubRepo(githubRepo)
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
continue
|
||||
}
|
||||
leaksFromRepo, err := auditGitRepo(repo)
|
||||
if opts.Disk {
|
||||
os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
|
||||
}
|
||||
if len(leaksFromRepo) == 0 {
|
||||
log.Infof("no leaks found for repo %s", *githubRepo.Name)
|
||||
} else {
|
||||
log.Warnf("leaks found for repo %s", *githubRepo.Name)
|
||||
}
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
}
|
||||
leaks = append(leaks, leaksFromRepo...)
|
||||
}
|
||||
return leaks, nil
|
||||
}
|
||||
|
||||
// cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
|
||||
// will be cloned to disk if --disk is set. If the repo is private, you must include the
|
||||
// --private/-p option. After the repo is clone, an audit will begin.
|
||||
func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
|
||||
var (
|
||||
repo *git.Repository
|
||||
err error
|
||||
)
|
||||
if opts.ExcludeForks && githubRepo.GetFork() {
|
||||
return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
|
||||
}
|
||||
for _, re := range whiteListRepos {
|
||||
if re.FindString(*githubRepo.Name) != "" {
|
||||
return nil, fmt.Errorf("skipping %s, whitelisted", *githubRepo.Name)
|
||||
}
|
||||
}
|
||||
log.Infof("cloning: %s", *githubRepo.Name)
|
||||
if opts.Disk {
|
||||
ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
|
||||
}
|
||||
if opts.IncludePrivate {
|
||||
if sshAuth == nil {
|
||||
return nil, fmt.Errorf("no ssh auth available")
|
||||
}
|
||||
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
|
||||
URL: *githubRepo.SSHURL,
|
||||
Auth: sshAuth,
|
||||
})
|
||||
} else {
|
||||
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
|
||||
URL: *githubRepo.CloneURL,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
if opts.IncludePrivate {
|
||||
if sshAuth == nil {
|
||||
return nil, fmt.Errorf("no ssh auth available")
|
||||
}
|
||||
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: *githubRepo.SSHURL,
|
||||
Auth: sshAuth,
|
||||
})
|
||||
} else {
|
||||
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: *githubRepo.CloneURL,
|
||||
})
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &RepoDescriptor{
|
||||
repository: repo,
|
||||
name: *githubRepo.Name,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// githubToken returns an oauth2 client for the github api to consume. This token is necessary
|
||||
// if you are running audits with --github-user or --github-org
|
||||
func githubToken() *http.Client {
|
||||
githubToken := os.Getenv("GITHUB_TOKEN")
|
||||
if githubToken == "" {
|
||||
return nil
|
||||
}
|
||||
ts := oauth2.StaticTokenSource(
|
||||
&oauth2.Token{AccessToken: githubToken},
|
||||
)
|
||||
return oauth2.NewClient(context.Background(), ts)
|
||||
}
|
||||
+1
-1
@@ -23,7 +23,7 @@ regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
|
||||
|
||||
[whitelist]
|
||||
regexes = [
|
||||
"AKIA.*",
|
||||
# "AKIA.*EXAMPLE",
|
||||
]
|
||||
files = [
|
||||
"(.*?)(jpg|gif|doc|pdf|bin|go)$"
|
||||
|
||||
+264
-187
@@ -56,30 +56,61 @@ regexes= [
|
||||
]
|
||||
`
|
||||
|
||||
var benchmarkRepo *Repo
|
||||
var benchmarkLeaksRepo *Repo
|
||||
const testWhitelistRepo = `
|
||||
[[regexes]]
|
||||
description = "AWS"
|
||||
regex = '''AKIA[0-9A-Z]{16}'''
|
||||
|
||||
func getBenchmarkLeaksRepo() *Repo {
|
||||
[whitelist]
|
||||
repos = [
|
||||
"gronit",
|
||||
]
|
||||
`
|
||||
|
||||
const testEntropyRange = `
|
||||
[misc]
|
||||
entropy = [
|
||||
"7.5-8.0",
|
||||
"3.3-3.4",
|
||||
]
|
||||
`
|
||||
const testBadEntropyRange = `
|
||||
[misc]
|
||||
entropy = [
|
||||
"8.0-3.0",
|
||||
]
|
||||
`
|
||||
const testBadEntropyRange2 = `
|
||||
[misc]
|
||||
entropy = [
|
||||
"8.0-8.9",
|
||||
]
|
||||
`
|
||||
|
||||
var benchmarkRepo *RepoDescriptor
|
||||
var benchmarkLeaksRepo *RepoDescriptor
|
||||
|
||||
func getBenchmarkLeaksRepo() *RepoDescriptor {
|
||||
if benchmarkLeaksRepo != nil {
|
||||
return benchmarkLeaksRepo
|
||||
}
|
||||
leaksR, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: "https://github.com/gitleakstest/gronit.git",
|
||||
})
|
||||
benchmarkLeaksRepo = &Repo{
|
||||
benchmarkLeaksRepo = &RepoDescriptor{
|
||||
repository: leaksR,
|
||||
}
|
||||
return benchmarkLeaksRepo
|
||||
}
|
||||
|
||||
func getBenchmarkRepo() *Repo {
|
||||
func getBenchmarkRepo() *RepoDescriptor {
|
||||
if benchmarkRepo != nil {
|
||||
return benchmarkRepo
|
||||
}
|
||||
bmRepo, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: "https://github.com/apple/swift-package-manager.git",
|
||||
})
|
||||
benchmarkRepo = &Repo{
|
||||
benchmarkRepo = &RepoDescriptor{
|
||||
repository: bmRepo,
|
||||
}
|
||||
return benchmarkRepo
|
||||
@@ -157,7 +188,7 @@ func TestGetRepo(t *testing.T) {
|
||||
g.Describe("TestGetRepo", func() {
|
||||
g.It(test.description, func() {
|
||||
opts = test.testOpts
|
||||
_, err := getRepo()
|
||||
_, err := cloneRepo()
|
||||
if err != nil {
|
||||
g.Assert(err.Error()).Equal(test.expectedErrMsg)
|
||||
}
|
||||
@@ -165,10 +196,9 @@ func TestGetRepo(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestRunAudit(t *testing.T) {
|
||||
err := loadToml()
|
||||
func TestRun(t *testing.T) {
|
||||
var err error
|
||||
configsDir := testTomlLoader()
|
||||
defer os.RemoveAll(configsDir)
|
||||
|
||||
dir, err = ioutil.TempDir("", "gitleaksTestOwner")
|
||||
defer os.RemoveAll(dir)
|
||||
@@ -185,7 +215,10 @@ func TestRunAudit(t *testing.T) {
|
||||
testOpts Options
|
||||
description string
|
||||
expectedErrMsg string
|
||||
whiteListRepos []string
|
||||
numLeaks int
|
||||
configPath string
|
||||
commitPerPage int
|
||||
}{
|
||||
{
|
||||
testOpts: Options{
|
||||
@@ -239,116 +272,83 @@ func TestRunAudit(t *testing.T) {
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "unable to generate ssh key: open reallyreallyreallyreallywrongpath: no such file or directory",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
Repo: "https://github.com/gitleakstest/gronit.git",
|
||||
},
|
||||
description: "test leak",
|
||||
numLeaks: 2,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
Repo: "https://github.com/gitleakstest/h1domains.git",
|
||||
},
|
||||
description: "test clean",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
Repo: "https://github.com/gitleakstest/empty.git",
|
||||
},
|
||||
description: "test empty",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "reference not found",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
},
|
||||
description: "test github org, whitelist repo",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "",
|
||||
configPath: path.Join(configsDir, "repo"),
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
ExcludeForks: true,
|
||||
},
|
||||
description: "test github org, exclude forks",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubPR: "https://github.com/gitleakstest/gronit/pull/1",
|
||||
},
|
||||
description: "test github pr",
|
||||
numLeaks: 4,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubPR: "https://github.com/gitleakstest/gronit/pull/1",
|
||||
},
|
||||
description: "test github pr",
|
||||
numLeaks: 4,
|
||||
expectedErrMsg: "",
|
||||
commitPerPage: 1,
|
||||
},
|
||||
}
|
||||
g := goblin.Goblin(t)
|
||||
for _, test := range tests {
|
||||
g.Describe("TestRunAudit", func() {
|
||||
g.Describe("TestRun", func() {
|
||||
g.It(test.description, func() {
|
||||
if test.configPath != "" {
|
||||
os.Setenv("GITLEAKS_CONFIG", test.configPath)
|
||||
}
|
||||
if test.commitPerPage != 0 {
|
||||
githubPages = test.commitPerPage
|
||||
}
|
||||
opts = test.testOpts
|
||||
leaks, err := run()
|
||||
if err != nil {
|
||||
g.Assert(err.Error()).Equal(test.expectedErrMsg)
|
||||
}
|
||||
g.Assert(len(leaks)).Equal(test.numLeaks)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartAudit(t *testing.T) {
|
||||
err := loadToml()
|
||||
configsDir := testTomlLoader()
|
||||
defer os.RemoveAll(configsDir)
|
||||
|
||||
dir, err = ioutil.TempDir("", "gitleaksTestOwner")
|
||||
defer os.RemoveAll(dir)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
git.PlainClone(dir+"/gronit", false, &git.CloneOptions{
|
||||
URL: "https://github.com/gitleakstest/gronit",
|
||||
})
|
||||
git.PlainClone(dir+"/h1domains", false, &git.CloneOptions{
|
||||
URL: "https://github.com/gitleakstest/h1domains",
|
||||
})
|
||||
var tests = []struct {
|
||||
testOpts Options
|
||||
description string
|
||||
expectedErrMsg string
|
||||
numLeaks int
|
||||
}{
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubUser: "gitleakstest",
|
||||
},
|
||||
description: "test github user",
|
||||
numLeaks: 2,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubUser: "gitleakstest",
|
||||
Disk: true,
|
||||
},
|
||||
description: "test github user on disk ",
|
||||
numLeaks: 2,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
},
|
||||
description: "test github org",
|
||||
numLeaks: 2,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
IncludePrivate: true,
|
||||
},
|
||||
description: "test private org no ssh",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "no ssh auth available",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
Disk: true,
|
||||
},
|
||||
description: "test org on disk",
|
||||
numLeaks: 2,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
IncludePrivate: true,
|
||||
Disk: true,
|
||||
},
|
||||
description: "test private org on disk no ssh",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "no ssh auth available",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
OwnerPath: dir,
|
||||
},
|
||||
description: "test owner path",
|
||||
numLeaks: 2,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
}
|
||||
g := goblin.Goblin(t)
|
||||
for _, test := range tests {
|
||||
g.Describe("TestStartAudit", func() {
|
||||
g.It(test.description, func() {
|
||||
opts = test.testOpts
|
||||
leaks, err := startAudits()
|
||||
if err != nil {
|
||||
g.Assert(err.Error()).Equal(test.expectedErrMsg)
|
||||
}
|
||||
g.Assert(len(leaks)).Equal(test.numLeaks)
|
||||
githubPages = 100
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -357,6 +357,8 @@ func TestStartAudit(t *testing.T) {
|
||||
func TestWriteReport(t *testing.T) {
|
||||
tmpDir, _ := ioutil.TempDir("", "reportDir")
|
||||
reportJSON := path.Join(tmpDir, "report.json")
|
||||
reportJASON := path.Join(tmpDir, "report.jason")
|
||||
reportVOID := path.Join("thereIsNoWay", "thisReportWillGetWritten.json")
|
||||
reportCSV := path.Join(tmpDir, "report.csv")
|
||||
defer os.RemoveAll(tmpDir)
|
||||
leaks := []Leak{
|
||||
@@ -373,17 +375,18 @@ func TestWriteReport(t *testing.T) {
|
||||
}
|
||||
|
||||
var tests = []struct {
|
||||
leaks []Leak
|
||||
reportFile string
|
||||
fileName string
|
||||
description string
|
||||
testOpts Options
|
||||
leaks []Leak
|
||||
reportFile string
|
||||
fileName string
|
||||
description string
|
||||
testOpts Options
|
||||
expectedErrMsg string
|
||||
}{
|
||||
{
|
||||
leaks: leaks,
|
||||
reportFile: reportJSON,
|
||||
fileName: "report.json",
|
||||
description: "can we write a file",
|
||||
description: "can we write a json file",
|
||||
testOpts: Options{
|
||||
Report: reportJSON,
|
||||
},
|
||||
@@ -392,10 +395,29 @@ func TestWriteReport(t *testing.T) {
|
||||
leaks: leaks,
|
||||
reportFile: reportCSV,
|
||||
fileName: "report.csv",
|
||||
description: "can we write a file",
|
||||
description: "can we write a csv file",
|
||||
testOpts: Options{
|
||||
Report: reportCSV,
|
||||
CSV: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
leaks: leaks,
|
||||
reportFile: reportJASON,
|
||||
fileName: "report.jason",
|
||||
description: "bad file",
|
||||
expectedErrMsg: "Report should be a .json or .csv file",
|
||||
testOpts: Options{
|
||||
Report: reportJASON,
|
||||
},
|
||||
},
|
||||
{
|
||||
leaks: leaks,
|
||||
reportFile: reportVOID,
|
||||
fileName: "report.jason",
|
||||
description: "bad dir",
|
||||
expectedErrMsg: "thereIsNoWay does not exist",
|
||||
testOpts: Options{
|
||||
Report: reportVOID,
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -404,9 +426,14 @@ func TestWriteReport(t *testing.T) {
|
||||
g.Describe("TestWriteReport", func() {
|
||||
g.It(test.description, func() {
|
||||
opts = test.testOpts
|
||||
writeReport(test.leaks)
|
||||
f, _ := os.Stat(test.reportFile)
|
||||
g.Assert(f.Name()).Equal(test.fileName)
|
||||
err := optsGuard()
|
||||
if err != nil {
|
||||
g.Assert(err.Error()).Equal(test.expectedErrMsg)
|
||||
} else {
|
||||
writeReport(test.leaks)
|
||||
f, _ := os.Stat(test.reportFile)
|
||||
g.Assert(f.Name()).Equal(test.fileName)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -419,6 +446,10 @@ func testTomlLoader() string {
|
||||
ioutil.WriteFile(path.Join(tmpDir, "branch"), []byte(testWhitelistBranch), 0644)
|
||||
ioutil.WriteFile(path.Join(tmpDir, "commit"), []byte(testWhitelistCommit), 0644)
|
||||
ioutil.WriteFile(path.Join(tmpDir, "file"), []byte(testWhitelistFile), 0644)
|
||||
ioutil.WriteFile(path.Join(tmpDir, "repo"), []byte(testWhitelistRepo), 0644)
|
||||
ioutil.WriteFile(path.Join(tmpDir, "entropy"), []byte(testEntropyRange), 0644)
|
||||
ioutil.WriteFile(path.Join(tmpDir, "badEntropy"), []byte(testBadEntropyRange), 0644)
|
||||
ioutil.WriteFile(path.Join(tmpDir, "badEntropy2"), []byte(testBadEntropyRange2), 0644)
|
||||
return tmpDir
|
||||
}
|
||||
|
||||
@@ -437,7 +468,7 @@ func TestAuditRepo(t *testing.T) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
leaksRepo := Repo{
|
||||
leaksRepo := &RepoDescriptor{
|
||||
repository: leaksR,
|
||||
name: "gronit",
|
||||
}
|
||||
@@ -448,7 +479,7 @@ func TestAuditRepo(t *testing.T) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cleanRepo := Repo{
|
||||
cleanRepo := &RepoDescriptor{
|
||||
repository: cleanR,
|
||||
name: "h1domains",
|
||||
}
|
||||
@@ -458,10 +489,11 @@ func TestAuditRepo(t *testing.T) {
|
||||
description string
|
||||
expectedErrMsg string
|
||||
numLeaks int
|
||||
repo Repo
|
||||
repo *RepoDescriptor
|
||||
whiteListFiles []*regexp.Regexp
|
||||
whiteListCommits map[string]bool
|
||||
whiteListBranches []string
|
||||
whiteListRepos []*regexp.Regexp
|
||||
whiteListRegexes []*regexp.Regexp
|
||||
configPath string
|
||||
}{
|
||||
@@ -475,7 +507,7 @@ func TestAuditRepo(t *testing.T) {
|
||||
description: "two leaks present limit goroutines",
|
||||
numLeaks: 2,
|
||||
testOpts: Options{
|
||||
MaxGoRoutines: 2,
|
||||
MaxGoRoutines: 4,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -540,14 +572,12 @@ func TestAuditRepo(t *testing.T) {
|
||||
numLeaks: 0,
|
||||
},
|
||||
{
|
||||
// note this double counts the first commit since we are whitelisting
|
||||
// a "bad" first commit
|
||||
repo: leaksRepo,
|
||||
description: "two leaks present whitelist bad commit",
|
||||
whiteListCommits: map[string]bool{
|
||||
"eaeffdc65b4c73ccb67e75d96bd8743be2c85973": true,
|
||||
},
|
||||
numLeaks: 2,
|
||||
numLeaks: 1,
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
@@ -579,15 +609,78 @@ func TestAuditRepo(t *testing.T) {
|
||||
numLeaks: 0,
|
||||
},
|
||||
{
|
||||
// note this double counts the first commit since we are whitelisting
|
||||
// a "bad" first commit
|
||||
repo: leaksRepo,
|
||||
description: "toml whitelist commit",
|
||||
configPath: path.Join(configsDir, "commit"),
|
||||
numLeaks: 2,
|
||||
numLeaks: 1,
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "audit whitelist repo",
|
||||
numLeaks: 0,
|
||||
whiteListRepos: []*regexp.Regexp{
|
||||
regexp.MustCompile("gronit"),
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "toml whitelist repo",
|
||||
numLeaks: 0,
|
||||
configPath: path.Join(configsDir, "repo"),
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "leaks present with entropy",
|
||||
testOpts: Options{
|
||||
Entropy: 4.7,
|
||||
},
|
||||
numLeaks: 7,
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "Audit until specific commit",
|
||||
numLeaks: 1,
|
||||
testOpts: Options{
|
||||
Commit: "f6839959b7bbdcd23008f1fb16f797f35bcd3a0c",
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "commit depth = 1, no leaks",
|
||||
numLeaks: 0,
|
||||
testOpts: Options{
|
||||
Depth: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "commit depth = 2, one leak",
|
||||
numLeaks: 1,
|
||||
testOpts: Options{
|
||||
Depth: 2,
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "toml entropy range",
|
||||
numLeaks: 422,
|
||||
configPath: path.Join(configsDir, "entropy"),
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "toml bad entropy range",
|
||||
numLeaks: 0,
|
||||
configPath: path.Join(configsDir, "badEntropy"),
|
||||
expectedErrMsg: "entropy range must be ascending",
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "toml bad entropy2 range",
|
||||
numLeaks: 0,
|
||||
configPath: path.Join(configsDir, "badEntropy2"),
|
||||
expectedErrMsg: "invalid entropy ranges, must be within 0.0-8.0",
|
||||
},
|
||||
}
|
||||
|
||||
whiteListCommits = make(map[string]bool)
|
||||
g := goblin.Goblin(t)
|
||||
for _, test := range tests {
|
||||
@@ -615,19 +708,29 @@ func TestAuditRepo(t *testing.T) {
|
||||
} else {
|
||||
whiteListRegexes = nil
|
||||
}
|
||||
|
||||
if test.whiteListRepos != nil {
|
||||
whiteListRepos = test.whiteListRepos
|
||||
} else {
|
||||
whiteListRepos = nil
|
||||
}
|
||||
skip := false
|
||||
// config paths
|
||||
if test.configPath != "" {
|
||||
os.Setenv("GITLEAKS_CONFIG", test.configPath)
|
||||
loadToml()
|
||||
err := loadToml()
|
||||
if err != nil {
|
||||
g.Assert(err.Error()).Equal(test.expectedErrMsg)
|
||||
skip = true
|
||||
}
|
||||
}
|
||||
if !skip {
|
||||
leaks, err = auditGitRepo(test.repo)
|
||||
|
||||
leaks, err = auditRepo(test.repo)
|
||||
|
||||
if opts.Redact {
|
||||
g.Assert(leaks[0].Offender).Equal("REDACTED")
|
||||
if opts.Redact {
|
||||
g.Assert(leaks[0].Offender).Equal("REDACTED")
|
||||
}
|
||||
g.Assert(len(leaks)).Equal(test.numLeaks)
|
||||
}
|
||||
g.Assert(len(leaks)).Equal(test.numLeaks)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -707,6 +810,14 @@ func TestOptionGuard(t *testing.T) {
|
||||
description: "single search regex gaurd",
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "fakeOrg",
|
||||
Entropy: 9,
|
||||
},
|
||||
description: "Invalid entropy level guard",
|
||||
expectedErrMsg: "The maximum level of entropy is 8",
|
||||
},
|
||||
}
|
||||
g := goblin.Goblin(t)
|
||||
for _, test := range tests {
|
||||
@@ -814,7 +925,7 @@ func BenchmarkAuditRepo1Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 1
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -823,7 +934,7 @@ func BenchmarkAuditRepo2Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 2
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -832,7 +943,7 @@ func BenchmarkAuditRepo4Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 4
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -841,7 +952,7 @@ func BenchmarkAuditRepo8Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 8
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -850,7 +961,7 @@ func BenchmarkAuditRepo10Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 10
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -859,7 +970,7 @@ func BenchmarkAuditRepo100Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 100
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -868,23 +979,7 @@ func BenchmarkAuditRepo1000Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 1000
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkRepo)
|
||||
}
|
||||
}
|
||||
func BenchmarkAuditRepo10000Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 10000
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkRepo)
|
||||
}
|
||||
}
|
||||
func BenchmarkAuditRepo100000Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 100000
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
func BenchmarkAuditLeakRepo1Proc(b *testing.B) {
|
||||
@@ -892,7 +987,7 @@ func BenchmarkAuditLeakRepo1Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 1
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkLeaksRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -901,7 +996,7 @@ func BenchmarkAuditLeakRepo2Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 2
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkLeaksRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -910,7 +1005,7 @@ func BenchmarkAuditLeakRepo4Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 4
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkLeaksRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -919,7 +1014,7 @@ func BenchmarkAuditLeakRepo8Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 8
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkLeaksRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -928,7 +1023,7 @@ func BenchmarkAuditLeakRepo10Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 10
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkLeaksRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
func BenchmarkAuditLeakRepo100Proc(b *testing.B) {
|
||||
@@ -936,7 +1031,7 @@ func BenchmarkAuditLeakRepo100Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 100
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkLeaksRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
func BenchmarkAuditLeakRepo1000Proc(b *testing.B) {
|
||||
@@ -944,24 +1039,6 @@ func BenchmarkAuditLeakRepo1000Proc(b *testing.B) {
|
||||
opts.MaxGoRoutines = 1000
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkLeaksRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditLeakRepo10000Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 10000
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkLeaksRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditLeakRepo100000Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 100000
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditRepo(*benchmarkLeaksRepo)
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/user"
|
||||
@@ -16,25 +16,26 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gopkg.in/src-d/go-git.v4/plumbing"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
"gopkg.in/src-d/go-git.v4/plumbing/object"
|
||||
"gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
|
||||
"gopkg.in/src-d/go-git.v4/storage/memory"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
"github.com/google/go-github/github"
|
||||
"github.com/hako/durafmt"
|
||||
flags "github.com/jessevdk/go-flags"
|
||||
log "github.com/sirupsen/logrus"
|
||||
git "gopkg.in/src-d/go-git.v4"
|
||||
)
|
||||
|
||||
// Leak represents a leaked secret or regex match. This will be output to stdout and/or the report
|
||||
// Leak represents a leaked secret or regex match.
|
||||
type Leak struct {
|
||||
Line string `json:"line"`
|
||||
Commit string `json:"commit"`
|
||||
@@ -47,23 +48,15 @@ type Leak struct {
|
||||
Repo string `json:"repo"`
|
||||
}
|
||||
|
||||
// Repo contains the actual git repository and meta data about the repo
|
||||
type Repo struct {
|
||||
// RepoDescriptor contains a src-d git repository and other data about the repo
|
||||
type RepoDescriptor struct {
|
||||
path string
|
||||
url string
|
||||
name string
|
||||
leaks []Leak
|
||||
repository *git.Repository
|
||||
err error
|
||||
}
|
||||
|
||||
// Owner contains a collection of repos. This could represent an org or user.
|
||||
type Owner struct {
|
||||
path string
|
||||
url string
|
||||
repos []Repo
|
||||
}
|
||||
|
||||
// Options for gitleaks
|
||||
type Options struct {
|
||||
// remote target options
|
||||
@@ -71,6 +64,7 @@ type Options struct {
|
||||
GithubUser string `long:"github-user" description:"Github user to audit"`
|
||||
GithubOrg string `long:"github-org" description:"Github organization to audit"`
|
||||
GithubURL string `long:"github-url" default:"https://api.github.com/" description:"GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/"`
|
||||
GithubPR string `long:"github-pr" description:"Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set"`
|
||||
IncludePrivate bool `short:"p" long:"private" description:"Include private repos in audit"`
|
||||
|
||||
/*
|
||||
@@ -81,27 +75,30 @@ type Options struct {
|
||||
|
||||
Branch string `short:"b" long:"branch" description:"branch name to audit (defaults to HEAD)"`
|
||||
Commit string `short:"c" long:"commit" description:"sha of commit to stop at"`
|
||||
Depth int `long:"depth" description:"maximum commit depth"`
|
||||
|
||||
// local target option
|
||||
RepoPath string `long:"repo-path" description:"Path to repo"`
|
||||
OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
|
||||
|
||||
// Process options
|
||||
MaxGoRoutines int `long:"max-go" description:"Maximum number of concurrent go-routines gitleaks spawns"`
|
||||
Disk bool `long:"disk" description:"Clones repo(s) to disk"`
|
||||
AuditAllRefs bool `long:"all-refs" description:"run audit on all refs"`
|
||||
SingleSearch string `long:"single-search" description:"single regular expression to search for"`
|
||||
ConfigPath string `long:"config" description:"path to gitleaks config"`
|
||||
SSHKey string `long:"ssh-key" description:"path to ssh key"`
|
||||
MaxGoRoutines int `long:"max-go" description:"Maximum number of concurrent go-routines gitleaks spawns"`
|
||||
Disk bool `long:"disk" description:"Clones repo(s) to disk"`
|
||||
AuditAllRefs bool `long:"all-refs" description:"run audit on all refs"`
|
||||
SingleSearch string `long:"single-search" description:"single regular expression to search for"`
|
||||
ConfigPath string `long:"config" description:"path to gitleaks config"`
|
||||
SSHKey string `long:"ssh-key" description:"path to ssh key"`
|
||||
ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
|
||||
Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"`
|
||||
// TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
|
||||
|
||||
// Output options
|
||||
Log string `short:"l" long:"log" description:"log level"`
|
||||
Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
|
||||
Report string `long:"report" description:"path to write report file"`
|
||||
CSV bool `long:"csv" description:"report output to csv"`
|
||||
Redact bool `long:"redact" description:"redact secrets from log messages and report"`
|
||||
Version bool `long:"version" description:"version number"`
|
||||
Log string `short:"l" long:"log" description:"log level"`
|
||||
Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
|
||||
Report string `long:"report" description:"path to write report file. Needs to be csv or json"`
|
||||
Redact bool `long:"redact" description:"redact secrets from log messages and report"`
|
||||
Version bool `long:"version" description:"version number"`
|
||||
SampleConfig bool `long:"sample-config" description:"prints a sample config file"`
|
||||
}
|
||||
|
||||
// Config struct for regexes matching and whitelisting
|
||||
@@ -115,14 +112,41 @@ type Config struct {
|
||||
Regexes []string
|
||||
Commits []string
|
||||
Branches []string
|
||||
Repos []string
|
||||
}
|
||||
Misc struct {
|
||||
Entropy []string
|
||||
}
|
||||
}
|
||||
|
||||
type gitDiff struct {
|
||||
content string
|
||||
commit *object.Commit
|
||||
filePath string
|
||||
branchName string
|
||||
repoName string
|
||||
githubCommit *github.RepositoryCommit
|
||||
sha string
|
||||
message string
|
||||
author string
|
||||
}
|
||||
|
||||
type entropyRange struct {
|
||||
v1 float64
|
||||
v2 float64
|
||||
}
|
||||
|
||||
const defaultGithubURL = "https://api.github.com/"
|
||||
const version = "1.7.0"
|
||||
const version = "1.15.0"
|
||||
const errExit = 2
|
||||
const leakExit = 1
|
||||
const defaultConfig = `
|
||||
# This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist.
|
||||
# The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable
|
||||
# is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load
|
||||
# configurations from that path. Gitleaks does not whitelist anything by default.
|
||||
|
||||
|
||||
title = "gitleaks config"
|
||||
# add regexes to the regex table
|
||||
[[regexes]]
|
||||
@@ -148,7 +172,6 @@ description = "Twitter"
|
||||
regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
|
||||
|
||||
[whitelist]
|
||||
|
||||
#regexes = [
|
||||
# "AKAIMYFAKEAWKKEY",
|
||||
#]
|
||||
@@ -163,7 +186,17 @@ regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
|
||||
#]
|
||||
|
||||
#branches = [
|
||||
# "dev/STUPDIFKNFEATURE"
|
||||
# "dev/goodrepo"
|
||||
#]
|
||||
|
||||
#repos = [
|
||||
# "mygoodrepo"
|
||||
#]
|
||||
|
||||
[misc]
|
||||
#entropy = [
|
||||
# "3.3-4.30"
|
||||
# "6.0-8.0
|
||||
#]
|
||||
`
|
||||
|
||||
@@ -175,10 +208,13 @@ var (
|
||||
whiteListFiles []*regexp.Regexp
|
||||
whiteListCommits map[string]bool
|
||||
whiteListBranches []string
|
||||
whiteListRepos []*regexp.Regexp
|
||||
entropyRanges []entropyRange
|
||||
fileDiffRegex *regexp.Regexp
|
||||
sshAuth *ssh.PublicKeys
|
||||
dir string
|
||||
maxGo int
|
||||
totalCommits int64
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -189,32 +225,52 @@ func init() {
|
||||
}
|
||||
|
||||
func main() {
|
||||
_, err := flags.Parse(&opts)
|
||||
parser := flags.NewParser(&opts, flags.Default)
|
||||
_, err := parser.Parse()
|
||||
|
||||
if err != nil {
|
||||
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
if len(os.Args) == 1 {
|
||||
parser.WriteHelp(os.Stdout)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
if opts.Version {
|
||||
fmt.Println(version)
|
||||
os.Exit(0)
|
||||
}
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
os.Exit(errExit)
|
||||
if opts.SampleConfig {
|
||||
fmt.Println(defaultConfig)
|
||||
os.Exit(0)
|
||||
}
|
||||
now := time.Now()
|
||||
leaks, err := run()
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "whitelisted") {
|
||||
log.Info(err.Error())
|
||||
os.Exit(0)
|
||||
}
|
||||
log.Error(err)
|
||||
os.Exit(errExit)
|
||||
}
|
||||
if opts.Report != "" {
|
||||
writeReport(leaks)
|
||||
}
|
||||
|
||||
if len(leaks) != 0 {
|
||||
log.Warnf("leaks detected")
|
||||
log.Warnf("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
|
||||
os.Exit(leakExit)
|
||||
} else {
|
||||
log.Infof("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
|
||||
}
|
||||
}
|
||||
|
||||
// run parses options and kicks off the audit
|
||||
func run() ([]Leak, error) {
|
||||
var leaks []Leak
|
||||
setLogs()
|
||||
err := optsGuard()
|
||||
if err != nil {
|
||||
@@ -239,50 +295,48 @@ func run() ([]Leak, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return startAudits()
|
||||
}
|
||||
|
||||
func startAudits() ([]Leak, error) {
|
||||
var leaks []Leak
|
||||
// start audits
|
||||
if opts.OwnerPath != "" {
|
||||
if opts.Repo != "" || opts.RepoPath != "" {
|
||||
// Audit a single remote repo or a local repo.
|
||||
repo, err := cloneRepo()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
return auditGitRepo(repo)
|
||||
} else if opts.OwnerPath != "" {
|
||||
// Audit local repos. Gitleaks will look for all child directories of OwnerPath for
|
||||
// git repos and perform an audit on said repos.
|
||||
repos, err := discoverRepos(opts.OwnerPath)
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
for _, repo := range repos {
|
||||
leaksFromRepo, err := auditRepo(repo)
|
||||
leaksFromRepo, err := auditGitRepo(repo)
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
leaks = append(leaksFromRepo, leaks...)
|
||||
}
|
||||
} else if opts.GithubOrg != "" || opts.GithubUser != "" {
|
||||
githubRepos, err := getGithubRepos()
|
||||
// Audit a github owner -- a user or organization. If you want to include
|
||||
// private repos you must pass a --private/-p option and have your ssh keys set
|
||||
leaks, err = auditGithubRepos()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
for _, githubRepo := range githubRepos {
|
||||
leaksFromRepo, err := auditGithubRepo(githubRepo)
|
||||
if len(leaksFromRepo) == 0 {
|
||||
log.Infof("no leaks found for repo %s", *githubRepo.Name)
|
||||
} else {
|
||||
log.Warnf("leaks found for repo %s", *githubRepo.Name)
|
||||
}
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
}
|
||||
leaks = append(leaks, leaksFromRepo...)
|
||||
}
|
||||
} else if opts.GithubPR != "" {
|
||||
return auditGithubPR()
|
||||
}
|
||||
return leaks, nil
|
||||
}
|
||||
|
||||
// writeReport writes a report to opts.Report in JSON.
|
||||
// writeReport writes a report to a file specified in the --report= option.
|
||||
// Default format for report is JSON. You can use the --csv option to write the report as a csv
|
||||
func writeReport(leaks []Leak) error {
|
||||
var err error
|
||||
log.Infof("writing report to %s", opts.Report)
|
||||
if opts.CSV {
|
||||
if strings.HasSuffix(opts.Report, ".csv") {
|
||||
f, err := os.Create(opts.Report)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -301,14 +355,20 @@ func writeReport(leaks []Leak) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// getRepo is responsible for cloning a repo in-memory or to disk, or opening a local repo and creating
|
||||
// a repo object
|
||||
func getRepo() (Repo, error) {
|
||||
// cloneRepo clones a repo to memory(default) or to disk if the --disk option is set. If you want to
|
||||
// clone a private repo you must set the --private/-p option, use a ssh target, and have your ssh keys
|
||||
// configured. If you want to audit a local repo, getRepo will load up a repo located at --repo-path
|
||||
func cloneRepo() (*RepoDescriptor, error) {
|
||||
var (
|
||||
err error
|
||||
repo *git.Repository
|
||||
)
|
||||
|
||||
// check if whitelist
|
||||
for _, re := range whiteListRepos {
|
||||
if re.FindString(opts.Repo) != "" {
|
||||
return nil, fmt.Errorf("skipping %s, whitelisted", opts.Repo)
|
||||
}
|
||||
}
|
||||
if opts.Disk {
|
||||
log.Infof("cloning %s", opts.Repo)
|
||||
cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
|
||||
@@ -325,7 +385,6 @@ func getRepo() (Repo, error) {
|
||||
})
|
||||
}
|
||||
} else if opts.RepoPath != "" {
|
||||
// use existing repo
|
||||
log.Infof("opening %s", opts.Repo)
|
||||
repo, err = git.PlainOpen(opts.RepoPath)
|
||||
} else {
|
||||
@@ -343,7 +402,7 @@ func getRepo() (Repo, error) {
|
||||
})
|
||||
}
|
||||
}
|
||||
return Repo{
|
||||
return &RepoDescriptor{
|
||||
repository: repo,
|
||||
path: opts.RepoPath,
|
||||
url: opts.Repo,
|
||||
@@ -352,45 +411,121 @@ func getRepo() (Repo, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// auditRef audits a git reference
|
||||
// TODO: need to add a layer of parallelism here and a cache for parent+child commits so we don't
|
||||
// double dip
|
||||
func auditRef(repo Repo, ref *plumbing.Reference, commitWg *sync.WaitGroup, commitChan chan []Leak) error {
|
||||
// auditGitRepo beings an audit on a git repository by checking the default HEAD branch, all branches, or
|
||||
// a single branch depending on what gitleaks is configured to do. Note when I say branch I really
|
||||
// mean reference as these branches are read only.
|
||||
func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
|
||||
var (
|
||||
err error
|
||||
prevCommit *object.Commit
|
||||
semaphore chan bool
|
||||
repoName string
|
||||
err error
|
||||
leaks []Leak
|
||||
)
|
||||
for _, re := range whiteListRepos {
|
||||
if re.FindString(repo.name) != "" {
|
||||
return leaks, fmt.Errorf("skipping %s, whitelisted", repo.name)
|
||||
}
|
||||
}
|
||||
ref, err := repo.repository.Head()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
|
||||
if opts.AuditAllRefs {
|
||||
skipBranch := false
|
||||
refs, err := repo.repository.Storer.IterReferences()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
err = refs.ForEach(func(ref *plumbing.Reference) error {
|
||||
for _, b := range whiteListBranches {
|
||||
if strings.HasSuffix(string(ref.Name()), b) {
|
||||
skipBranch = true
|
||||
}
|
||||
}
|
||||
if skipBranch {
|
||||
skipBranch = false
|
||||
return nil
|
||||
}
|
||||
branchLeaks := auditGitReference(repo, ref)
|
||||
for _, leak := range branchLeaks {
|
||||
leaks = append(leaks, leak)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
} else {
|
||||
if opts.Branch != "" {
|
||||
foundBranch := false
|
||||
refs, _ := repo.repository.Storer.IterReferences()
|
||||
branch := strings.Split(opts.Branch, "/")[len(strings.Split(opts.Branch, "/"))-1]
|
||||
err = refs.ForEach(func(refBranch *plumbing.Reference) error {
|
||||
if strings.Split(refBranch.Name().String(), "/")[len(strings.Split(refBranch.Name().String(), "/"))-1] == branch {
|
||||
foundBranch = true
|
||||
ref = refBranch
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if foundBranch == false {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
leaks = auditGitReference(repo, ref)
|
||||
}
|
||||
return leaks, err
|
||||
}
|
||||
|
||||
// auditGitReference beings the audit for a git reference. This function will
|
||||
// traverse the git reference and audit each line of each diff. Set maximum concurrency with
|
||||
// the --max-go option (default is set to the number of cores on your cpu).
|
||||
func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
|
||||
var (
|
||||
err error
|
||||
prevCommit *object.Commit
|
||||
semaphore chan bool
|
||||
repoName string
|
||||
leaks []Leak
|
||||
commitWg sync.WaitGroup
|
||||
mutex = &sync.Mutex{}
|
||||
commitCount int
|
||||
)
|
||||
repoName = repo.name
|
||||
if opts.MaxGoRoutines != 0 {
|
||||
maxGo = opts.MaxGoRoutines
|
||||
}
|
||||
|
||||
semaphore = make(chan bool, maxGo)
|
||||
cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
|
||||
if err != nil {
|
||||
return err
|
||||
return nil
|
||||
}
|
||||
err = cIter.ForEach(func(c *object.Commit) error {
|
||||
if c.Hash.String() == opts.Commit {
|
||||
if c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) {
|
||||
cIter.Close()
|
||||
return errors.New("ErrStop")
|
||||
}
|
||||
commitCount = commitCount + 1
|
||||
totalCommits = totalCommits + 1
|
||||
if whiteListCommits[c.Hash.String()] {
|
||||
prevCommit = c
|
||||
log.Infof("skipping commit: %s\n", c.Hash.String())
|
||||
return nil
|
||||
}
|
||||
if prevCommit != nil {
|
||||
if whiteListCommits[prevCommit.Hash.String()] {
|
||||
prevCommit = c
|
||||
log.Infof("skipping commit: %s\n", c.Hash.String())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
semaphore <- true
|
||||
commitWg.Add(1)
|
||||
semaphore <- true
|
||||
go func(c *object.Commit, prevCommit *object.Commit) {
|
||||
var (
|
||||
leaks []Leak
|
||||
filePath string
|
||||
skipFile bool
|
||||
)
|
||||
defer func() {
|
||||
commitWg.Done()
|
||||
<-semaphore
|
||||
commitChan <- leaks
|
||||
if r := recover(); r != nil {
|
||||
log.Warnf("recoverying from panic on commit %s, likely large diff causing panic", c.Hash.String())
|
||||
}
|
||||
@@ -404,7 +539,21 @@ func auditRef(repo Repo, ref *plumbing.Reference, commitWg *sync.WaitGroup, comm
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
leaks = append(leaks, checkDiff(content, c, file.Name, string(ref.Name()), repoName)...)
|
||||
diff := gitDiff{
|
||||
branchName: string(ref.Name()),
|
||||
repoName: repoName,
|
||||
filePath: file.Name,
|
||||
content: content,
|
||||
sha: c.Hash.String(),
|
||||
author: c.Author.String(),
|
||||
message: c.Message,
|
||||
}
|
||||
chunkLeaks := inspect(diff)
|
||||
for _, leak := range chunkLeaks {
|
||||
mutex.Lock()
|
||||
leaks = append(leaks, leak)
|
||||
mutex.Unlock()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
@@ -438,8 +587,21 @@ func auditRef(repo Repo, ref *plumbing.Reference, commitWg *sync.WaitGroup, comm
|
||||
chunks := f.Chunks()
|
||||
for _, chunk := range chunks {
|
||||
if chunk.Type() == 1 || chunk.Type() == 2 {
|
||||
// only check if adding or removing
|
||||
leaks = append(leaks, checkDiff(chunk.Content(), prevCommit, filePath, string(ref.Name()), repoName)...)
|
||||
diff := gitDiff{
|
||||
branchName: string(ref.Name()),
|
||||
repoName: repoName,
|
||||
filePath: filePath,
|
||||
content: chunk.Content(),
|
||||
sha: prevCommit.Hash.String(),
|
||||
author: prevCommit.Author.String(),
|
||||
message: prevCommit.Message,
|
||||
}
|
||||
chunkLeaks := inspect(diff)
|
||||
for _, leak := range chunkLeaks {
|
||||
mutex.Lock()
|
||||
leaks = append(leaks, leak)
|
||||
mutex.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -448,84 +610,16 @@ func auditRef(repo Repo, ref *plumbing.Reference, commitWg *sync.WaitGroup, comm
|
||||
prevCommit = c
|
||||
return nil
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// auditRepo performs an audit on a repository checking for regex matching and ignoring
|
||||
// files and regexes that are whitelisted
|
||||
func auditRepo(repo Repo) ([]Leak, error) {
|
||||
var (
|
||||
err error
|
||||
leaks []Leak
|
||||
commitWg sync.WaitGroup
|
||||
)
|
||||
|
||||
ref, err := repo.repository.Head()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
|
||||
// leak messaging
|
||||
commitChan := make(chan []Leak, 1)
|
||||
|
||||
if opts.AuditAllRefs {
|
||||
skipBranch := false
|
||||
refs, err := repo.repository.Storer.IterReferences()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
err = refs.ForEach(func(ref *plumbing.Reference) error {
|
||||
for _, b := range whiteListBranches {
|
||||
if strings.HasSuffix(string(ref.Name()), b) {
|
||||
skipBranch = true
|
||||
}
|
||||
}
|
||||
if skipBranch {
|
||||
skipBranch = false
|
||||
return nil
|
||||
}
|
||||
auditRef(repo, ref, &commitWg, commitChan)
|
||||
return nil
|
||||
})
|
||||
} else {
|
||||
if opts.Branch != "" {
|
||||
foundBranch := false
|
||||
refs, _ := repo.repository.Storer.IterReferences()
|
||||
branch := strings.Split(opts.Branch, "/")[len(strings.Split(opts.Branch, "/"))-1]
|
||||
err = refs.ForEach(func(refBranch *plumbing.Reference) error {
|
||||
if strings.Split(refBranch.Name().String(), "/")[len(strings.Split(refBranch.Name().String(), "/"))-1] == branch {
|
||||
foundBranch = true
|
||||
ref = refBranch
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if foundBranch == false {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
auditRef(repo, ref, &commitWg, commitChan)
|
||||
}
|
||||
|
||||
go func() {
|
||||
for commitLeaks := range commitChan {
|
||||
if commitLeaks != nil {
|
||||
for _, leak := range commitLeaks {
|
||||
leaks = append(leaks, leak)
|
||||
}
|
||||
|
||||
}
|
||||
commitWg.Done()
|
||||
}
|
||||
}()
|
||||
|
||||
commitWg.Wait()
|
||||
return leaks, err
|
||||
return leaks
|
||||
}
|
||||
|
||||
// checkDiff accepts a string diff and commit object then performs a
|
||||
// regex check
|
||||
func checkDiff(diff string, commit *object.Commit, filePath string, branch string, repo string) []Leak {
|
||||
lines := strings.Split(diff, "\n")
|
||||
// inspect will parse each line of the git diff's content against a set of regexes or
|
||||
// a set of regexes set by the config (see gitleaks.toml for example). This function
|
||||
// will skip lines that include a whitelisted regex. A list of leaks is returned.
|
||||
// If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
|
||||
func inspect(diff gitDiff) []Leak {
|
||||
lines := strings.Split(diff.content, "\n")
|
||||
var (
|
||||
leaks []Leak
|
||||
skipLine bool
|
||||
@@ -551,170 +645,86 @@ func checkDiff(diff string, commit *object.Commit, filePath string, branch strin
|
||||
break
|
||||
}
|
||||
|
||||
leak := Leak{
|
||||
Line: line,
|
||||
Commit: commit.Hash.String(),
|
||||
Offender: match,
|
||||
Type: leakType,
|
||||
Message: commit.Message,
|
||||
Author: commit.Author.String(),
|
||||
File: filePath,
|
||||
Branch: branch,
|
||||
Repo: repo,
|
||||
leaks = addLeak(leaks, line, match, leakType, diff)
|
||||
}
|
||||
|
||||
if opts.Entropy > 0 || len(entropyRanges) != 0 {
|
||||
entropyLeak := false
|
||||
words := strings.Fields(line)
|
||||
for _, word := range words {
|
||||
entropy := getShannonEntropy(word)
|
||||
if entropy >= opts.Entropy && len(entropyRanges) == 0 {
|
||||
entropyLeak = true
|
||||
}
|
||||
if len(entropyRanges) != 0 {
|
||||
for _, eR := range entropyRanges {
|
||||
if entropy > eR.v1 && entropy < eR.v2 {
|
||||
entropyLeak = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if entropyLeak {
|
||||
leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), diff)
|
||||
entropyLeak = false
|
||||
}
|
||||
}
|
||||
if opts.Redact {
|
||||
leak.Offender = "REDACTED"
|
||||
leak.Line = "REDACTED"
|
||||
}
|
||||
if opts.Verbose {
|
||||
leak.log()
|
||||
}
|
||||
leaks = append(leaks, leak)
|
||||
}
|
||||
}
|
||||
return leaks
|
||||
}
|
||||
|
||||
// auditOwner audits all of the owner's(user or org) repos
|
||||
func getGithubRepos() ([]*github.Repository, error) {
|
||||
var (
|
||||
err error
|
||||
githubRepos []*github.Repository
|
||||
rs []*github.Repository
|
||||
resp *github.Response
|
||||
githubClient *github.Client
|
||||
githubOrgOptions *github.RepositoryListByOrgOptions
|
||||
githubOptions *github.RepositoryListOptions
|
||||
)
|
||||
ctx := context.Background()
|
||||
|
||||
if opts.GithubOrg != "" {
|
||||
githubClient = github.NewClient(githubToken())
|
||||
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
|
||||
ghURL, _ := url.Parse(opts.GithubURL)
|
||||
githubClient.BaseURL = ghURL
|
||||
}
|
||||
githubOrgOptions = &github.RepositoryListByOrgOptions{
|
||||
ListOptions: github.ListOptions{PerPage: 100},
|
||||
}
|
||||
} else if opts.GithubUser != "" {
|
||||
githubClient = github.NewClient(githubToken())
|
||||
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
|
||||
ghURL, _ := url.Parse(opts.GithubURL)
|
||||
githubClient.BaseURL = ghURL
|
||||
}
|
||||
|
||||
githubOptions = &github.RepositoryListOptions{
|
||||
Affiliation: "owner",
|
||||
ListOptions: github.ListOptions{
|
||||
PerPage: 100,
|
||||
},
|
||||
}
|
||||
// addLeak is helper for func inspect() to append leaks if found during a diff check.
|
||||
func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
|
||||
leak := Leak{
|
||||
Line: line,
|
||||
Commit: diff.sha,
|
||||
Offender: offender,
|
||||
Type: leakType,
|
||||
Author: diff.author,
|
||||
File: diff.filePath,
|
||||
Branch: diff.branchName,
|
||||
Repo: diff.repoName,
|
||||
Message: diff.message,
|
||||
}
|
||||
if opts.Redact {
|
||||
leak.Offender = "REDACTED"
|
||||
leak.Line = "REDACTED"
|
||||
}
|
||||
|
||||
for {
|
||||
if opts.GithubUser != "" {
|
||||
if opts.IncludePrivate {
|
||||
rs, resp, err = githubClient.Repositories.List(ctx, "", githubOptions)
|
||||
} else {
|
||||
rs, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
githubOptions.Page = resp.NextPage
|
||||
githubRepos = append(githubRepos, rs...)
|
||||
if resp.NextPage == 0 {
|
||||
return githubRepos, err
|
||||
}
|
||||
} else if opts.GithubOrg != "" {
|
||||
rs, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
githubOrgOptions.Page = resp.NextPage
|
||||
githubRepos = append(githubRepos, rs...)
|
||||
if resp.NextPage == 0 {
|
||||
return githubRepos, err
|
||||
}
|
||||
}
|
||||
if opts.Log == "Debug" || opts.Log == "debug" {
|
||||
for _, githubRepo := range rs {
|
||||
log.Debugf("staging repos %s", *githubRepo.Name)
|
||||
}
|
||||
}
|
||||
if opts.Verbose {
|
||||
leak.log()
|
||||
}
|
||||
|
||||
leaks = append(leaks, leak)
|
||||
return leaks
|
||||
}
|
||||
|
||||
// auditGithubRepo clones repos from github
|
||||
func auditGithubRepo(githubRepo *github.Repository) ([]Leak, error) {
|
||||
var (
|
||||
leaks []Leak
|
||||
repo *git.Repository
|
||||
err error
|
||||
)
|
||||
log.Infof("cloning: %s", *githubRepo.Name)
|
||||
if opts.Disk {
|
||||
ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
|
||||
defer os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
|
||||
if err != nil {
|
||||
return leaks, fmt.Errorf("unable to generater owner temp dir: %v", err)
|
||||
}
|
||||
if opts.IncludePrivate {
|
||||
if sshAuth == nil {
|
||||
return leaks, fmt.Errorf("no ssh auth available")
|
||||
}
|
||||
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
|
||||
URL: *githubRepo.SSHURL,
|
||||
Auth: sshAuth,
|
||||
})
|
||||
} else {
|
||||
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
|
||||
URL: *githubRepo.CloneURL,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
if opts.IncludePrivate {
|
||||
if sshAuth == nil {
|
||||
return leaks, fmt.Errorf("no ssh auth available")
|
||||
}
|
||||
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: *githubRepo.SSHURL,
|
||||
Auth: sshAuth,
|
||||
})
|
||||
} else {
|
||||
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: *githubRepo.CloneURL,
|
||||
})
|
||||
}
|
||||
// getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
|
||||
func getShannonEntropy(data string) (entropy float64) {
|
||||
if data == "" {
|
||||
return 0
|
||||
}
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
return auditRepo(Repo{
|
||||
repository: repo,
|
||||
name: *githubRepo.Name,
|
||||
})
|
||||
}
|
||||
|
||||
// githubToken returns a oauth2 client for the github api to consume
|
||||
func githubToken() *http.Client {
|
||||
githubToken := os.Getenv("GITHUB_TOKEN")
|
||||
if githubToken == "" {
|
||||
return nil
|
||||
charCounts := make(map[rune]int)
|
||||
for _, char := range data {
|
||||
charCounts[char]++
|
||||
}
|
||||
ts := oauth2.StaticTokenSource(
|
||||
&oauth2.Token{AccessToken: githubToken},
|
||||
)
|
||||
return oauth2.NewClient(context.Background(), ts)
|
||||
|
||||
invLength := 1.0 / float64(len(data))
|
||||
for _, count := range charCounts {
|
||||
freq := float64(count) * invLength
|
||||
entropy -= freq * math.Log2(freq)
|
||||
}
|
||||
|
||||
return entropy
|
||||
}
|
||||
|
||||
// discoverRepos walks all the children of `path`. If a child directory
|
||||
// contain a .git file then that repo will be added
|
||||
func discoverRepos(ownerPath string) ([]Repo, error) {
|
||||
// contain a .git file then that repo will be added to the list of repos returned
|
||||
func discoverRepos(ownerPath string) ([]*RepoDescriptor, error) {
|
||||
var (
|
||||
err error
|
||||
repos []Repo
|
||||
repos []*RepoDescriptor
|
||||
)
|
||||
files, err := ioutil.ReadDir(ownerPath)
|
||||
if err != nil {
|
||||
@@ -727,7 +737,7 @@ func discoverRepos(ownerPath string) ([]Repo, error) {
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
repos = append(repos, Repo{
|
||||
repos = append(repos, &RepoDescriptor{
|
||||
repository: r,
|
||||
name: f.Name(),
|
||||
path: repoPath,
|
||||
@@ -795,12 +805,27 @@ func optsGuard() error {
|
||||
}
|
||||
}
|
||||
|
||||
if opts.Entropy > 8 {
|
||||
return fmt.Errorf("The maximum level of entropy is 8")
|
||||
}
|
||||
if opts.Report != "" {
|
||||
if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") {
|
||||
return fmt.Errorf("Report should be a .json or .csv file")
|
||||
}
|
||||
dirPath := filepath.Dir(opts.Report)
|
||||
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
|
||||
return fmt.Errorf("%s does not exist", dirPath)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadToml loads of the toml config containing regexes and whitelists
|
||||
// 1. look for config path
|
||||
// 2. two, look for gitleaks config env var
|
||||
// loadToml loads of the toml config containing regexes and whitelists.
|
||||
// This function will first look if the configPath is set and load the config
|
||||
// from that file. Otherwise will then look for the path set by the GITHLEAKS_CONIFG
|
||||
// env var. If that is not set, then gitleaks will continue with the default configs
|
||||
// specified by the const var at the top `defaultConfig`
|
||||
func loadToml() error {
|
||||
var (
|
||||
config Config
|
||||
@@ -827,9 +852,14 @@ func loadToml() error {
|
||||
}
|
||||
}
|
||||
|
||||
// load up regexes
|
||||
if len(config.Misc.Entropy) != 0 {
|
||||
err := entropyLimits(config.Misc.Entropy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if singleSearchRegex != nil {
|
||||
// single search takes precedence over default regex
|
||||
regexes["singleSearch"] = singleSearchRegex
|
||||
} else {
|
||||
for _, regex := range config.Regexes {
|
||||
@@ -847,11 +877,43 @@ func loadToml() error {
|
||||
for _, regex := range config.Whitelist.Regexes {
|
||||
whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex))
|
||||
}
|
||||
for _, regex := range config.Whitelist.Repos {
|
||||
whiteListRepos = append(whiteListRepos, regexp.MustCompile(regex))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// getSSHAuth generates ssh auth
|
||||
// entropyLimits hydrates entropyRanges which allows for fine tuning entropy checking
|
||||
func entropyLimits(entropyLimitStr []string) error {
|
||||
for _, span := range entropyLimitStr {
|
||||
split := strings.Split(span, "-")
|
||||
v1, err := strconv.ParseFloat(split[0], 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v2, err := strconv.ParseFloat(split[1], 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if v1 > v2 {
|
||||
return fmt.Errorf("entropy range must be ascending")
|
||||
}
|
||||
r := entropyRange{
|
||||
v1: v1,
|
||||
v2: v2,
|
||||
}
|
||||
if r.v1 > 8.0 || r.v1 < 0.0 || r.v2 > 8.0 || r.v2 < 0.0 {
|
||||
return fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
|
||||
}
|
||||
entropyRanges = append(entropyRanges, r)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getSSHAuth return an ssh auth use by go-git to clone repos behind authentication.
|
||||
// If --ssh-key is set then it will attempt to load the key from that path. If not,
|
||||
// gitleaks will use the default $HOME/.ssh/id_rsa key
|
||||
func getSSHAuth() (*ssh.PublicKeys, error) {
|
||||
var (
|
||||
sshKeyPath string
|
||||
@@ -869,7 +931,7 @@ func getSSHAuth() (*ssh.PublicKeys, error) {
|
||||
return sshAuth, err
|
||||
}
|
||||
|
||||
func (leak *Leak) log() {
|
||||
func (leak Leak) log() {
|
||||
b, _ := json.MarshalIndent(leak, "", " ")
|
||||
fmt.Println(string(b))
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.5
|
||||
- 1.6
|
||||
- 1.7
|
||||
- 1.8
|
||||
- 1.9
|
||||
- tip
|
||||
|
||||
before_install:
|
||||
- go get golang.org/x/tools/cmd/cover
|
||||
|
||||
script:
|
||||
- GOARCH=386 go test # test 32bit architectures.
|
||||
- go test -coverprofile=coverage.txt -covermode=atomic
|
||||
|
||||
after_success:
|
||||
- bash <(curl -s https://codecov.io/bash)
|
||||
|
||||
sudo: false
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at wesley@hakobaito.co.uk. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
|
||||
|
||||
[homepage]: http://contributor-covenant.org
|
||||
[version]: http://contributor-covenant.org/version/1/4/
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
# Contributing
|
||||
|
||||
Contributions are welcome! Fork this repo and add your changes and submit a PR.
|
||||
|
||||
If you would like to fix a bug, add a feature or provide feedback you can do so in the issues section.
|
||||
|
||||
You can run tests by runnning `go test`. Running `go test; go vet; golint` is recommended.
|
||||
|
||||
durafmt is also tested against `gometalinter`.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 Wesley Hill
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
# durafmt
|
||||
|
||||
[](https://travis-ci.org/hako/durafmt) [](https://goreportcard.com/report/github.com/hako/durafmt) [](https://codecov.io/gh/hako/durafmt) [](https://godoc.org/github.com/hako/durafmt)
|
||||
[](https://www.codetriage.com/hako/durafmt)
|
||||
|
||||
|
||||
|
||||
durafmt is a tiny Go library that formats `time.Duration` strings into a human readable format.
|
||||
|
||||
```
|
||||
go get github.com/hako/durafmt
|
||||
```
|
||||
|
||||
# Why
|
||||
|
||||
If you've worked with `time.Duration` in Go, you most likely have come across this:
|
||||
|
||||
```
|
||||
53m28.587093086s // :)
|
||||
```
|
||||
|
||||
The above seems very easy to read, unless your duration looks like this:
|
||||
|
||||
```
|
||||
354h22m3.24s // :S
|
||||
```
|
||||
|
||||
# Usage
|
||||
|
||||
### durafmt.ParseString()
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/hako/durafmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
duration, err := durafmt.ParseString("354h22m3.24s")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
fmt.Println(duration) // 2 weeks 18 hours 22 minutes 3 seconds
|
||||
// duration.String() // String representation. "2 weeks 18 hours 22 minutes 3 seconds"
|
||||
}
|
||||
```
|
||||
|
||||
### durafmt.ParseStringShort()
|
||||
|
||||
Version of `durafmt.ParseString()` that only returns the first part of the duration string.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/hako/durafmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
duration, err := durafmt.ParseStringShort("354h22m3.24s")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
fmt.Println(duration) // 2 weeks
|
||||
// duration.String() // String short representation. "2 weeks"
|
||||
}
|
||||
```
|
||||
|
||||
### durafmt.Parse()
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"github.com/hako/durafmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
timeduration := (354 * time.Hour) + (22 * time.Minute) + (3 * time.Second)
|
||||
duration := durafmt.Parse(timeduration).String()
|
||||
fmt.Println(duration) // 2 weeks 18 hours 22 minutes 3 seconds
|
||||
}
|
||||
```
|
||||
|
||||
### durafmt.ParseShort()
|
||||
|
||||
Version of `durafmt.Parse()` that only returns the first part of the duration string.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"github.com/hako/durafmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
timeduration := (354 * time.Hour) + (22 * time.Minute) + (3 * time.Second)
|
||||
duration := durafmt.ParseShort(timeduration).String()
|
||||
fmt.Println(duration) // 2 weeks
|
||||
}
|
||||
```
|
||||
|
||||
# Contributing
|
||||
|
||||
Contributions are welcome! Fork this repo and add your changes and submit a PR.
|
||||
|
||||
If you would like to fix a bug, add a feature or provide feedback you can do so in the issues section.
|
||||
|
||||
You can run tests by runnning `go test`. Running `go test; go vet; golint` is recommended.
|
||||
|
||||
durafmt is also tested against `gometalinter`.
|
||||
|
||||
# License
|
||||
|
||||
MIT
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
// Package durafmt formats time.Duration into a human readable format.
|
||||
package durafmt
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
units = []string{"years", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"}
|
||||
)
|
||||
|
||||
// Durafmt holds the parsed duration and the original input duration.
|
||||
type Durafmt struct {
|
||||
duration time.Duration
|
||||
input string // Used as reference.
|
||||
short bool
|
||||
}
|
||||
|
||||
// Parse creates a new *Durafmt struct, returns error if input is invalid.
|
||||
func Parse(dinput time.Duration) *Durafmt {
|
||||
input := dinput.String()
|
||||
return &Durafmt{dinput, input, false}
|
||||
}
|
||||
|
||||
// ParseShort creates a new *Durafmt struct, short form, returns error if input is invalid.
|
||||
func ParseShort(dinput time.Duration) *Durafmt {
|
||||
input := dinput.String()
|
||||
return &Durafmt{dinput, input, true}
|
||||
}
|
||||
|
||||
// ParseString creates a new *Durafmt struct from a string.
|
||||
// returns an error if input is invalid.
|
||||
func ParseString(input string) (*Durafmt, error) {
|
||||
if input == "0" || input == "-0" {
|
||||
return nil, errors.New("durafmt: missing unit in duration " + input)
|
||||
}
|
||||
duration, err := time.ParseDuration(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Durafmt{duration, input, false}, nil
|
||||
}
|
||||
|
||||
// ParseStringShort creates a new *Durafmt struct from a string, short form
|
||||
// returns an error if input is invalid.
|
||||
func ParseStringShort(input string) (*Durafmt, error) {
|
||||
if input == "0" || input == "-0" {
|
||||
return nil, errors.New("durafmt: missing unit in duration " + input)
|
||||
}
|
||||
duration, err := time.ParseDuration(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Durafmt{duration, input, true}, nil
|
||||
}
|
||||
|
||||
// String parses d *Durafmt into a human readable duration.
|
||||
func (d *Durafmt) String() string {
|
||||
var duration string
|
||||
|
||||
// Check for minus durations.
|
||||
if string(d.input[0]) == "-" {
|
||||
duration += "-"
|
||||
d.duration = -d.duration
|
||||
}
|
||||
|
||||
// Convert duration.
|
||||
seconds := int64(d.duration.Seconds()) % 60
|
||||
minutes := int64(d.duration.Minutes()) % 60
|
||||
hours := int64(d.duration.Hours()) % 24
|
||||
days := int64(d.duration/(24*time.Hour)) % 365 % 7
|
||||
|
||||
// Edge case between 364 and 365 days.
|
||||
// We need to calculate weeks from what is left from years
|
||||
leftYearDays := int64(d.duration/(24*time.Hour)) % 365
|
||||
weeks := leftYearDays / 7
|
||||
if leftYearDays >= 364 && leftYearDays < 365 {
|
||||
weeks = 52
|
||||
}
|
||||
|
||||
years := int64(d.duration/(24*time.Hour)) / 365
|
||||
milliseconds := int64(d.duration/time.Millisecond) -
|
||||
(seconds * 1000) - (minutes * 60000) - (hours * 3600000) -
|
||||
(days * 86400000) - (weeks * 604800000) - (years * 31536000000)
|
||||
|
||||
// Create a map of the converted duration time.
|
||||
durationMap := map[string]int64{
|
||||
"milliseconds": milliseconds,
|
||||
"seconds": seconds,
|
||||
"minutes": minutes,
|
||||
"hours": hours,
|
||||
"days": days,
|
||||
"weeks": weeks,
|
||||
"years": years,
|
||||
}
|
||||
|
||||
// Construct duration string.
|
||||
for _, u := range units {
|
||||
v := durationMap[u]
|
||||
strval := strconv.FormatInt(v, 10)
|
||||
switch {
|
||||
// add to the duration string if v > 1.
|
||||
case v > 1:
|
||||
duration += strval + " " + u + " "
|
||||
// remove the plural 's', if v is 1.
|
||||
case v == 1:
|
||||
duration += strval + " " + strings.TrimRight(u, "s") + " "
|
||||
// omit any value with 0s or 0.
|
||||
case d.duration.String() == "0" || d.duration.String() == "0s":
|
||||
// note: milliseconds and minutes have the same suffix (m)
|
||||
// so we have to check if the units match with the suffix.
|
||||
|
||||
// check for a suffix that is NOT the milliseconds suffix.
|
||||
if strings.HasSuffix(d.input, string(u[0])) && !strings.Contains(d.input, "ms") {
|
||||
// if it happens that the units are milliseconds, skip.
|
||||
if u == "milliseconds" {
|
||||
continue
|
||||
}
|
||||
duration += strval + " " + u
|
||||
}
|
||||
// process milliseconds here.
|
||||
if u == "milliseconds" {
|
||||
if strings.Contains(d.input, "ms") {
|
||||
duration += strval + " " + u
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
// omit any value with 0.
|
||||
case v == 0:
|
||||
continue
|
||||
}
|
||||
}
|
||||
// trim any remaining spaces.
|
||||
duration = strings.TrimSpace(duration)
|
||||
|
||||
// if more than 2 spaces present return the first 2 strings
|
||||
// if short version is requested
|
||||
if d.short {
|
||||
duration = strings.Join(strings.Split(duration, " ")[:2], " ")
|
||||
}
|
||||
|
||||
return duration
|
||||
}
|
||||
Reference in new issue
Block a user