Compare commits

..
12 Commits
Author SHA1 Message Date
Paulo Correia 6f75511665 Added option to specify .gitleaksignore path (#1179) 2023-06-05 17:03:26 -05:00
Oleksandr Redko 190ac977be Fix closing file in writeJson and writeSarif (#1187) 2023-06-05 10:43:04 -05:00
Oleksandr Redko 6dbb0c5af5 Simplify tests by using T.TempDir (#1186) 2023-05-30 07:24:59 -05:00
Oleksandr Redko 6705461b33 Fix typos in *.md, comments and logs (#1185) 2023-05-30 07:08:42 -05:00
Zachary Rice 9869eab4c2 Update README.md 2023-05-01 19:01:05 -05:00
Zachary Rice 16f1ec0f1e Update bug_report.md 2023-05-01 17:10:00 -05:00
Zachary Rice 8d80a5a5a2 Adding discord channel to readme 2023-05-01 16:43:06 -05:00
Dariusz Porowski 146f69e51b 🐛 fix(sarif): update report to pass validator (#1167)
* 🐛 fix(sarif): update report to pass validator

* ✅ test(sarif): update sarif report testdata
2023-04-28 14:15:18 -05:00
Richard Gomez 51ca0f89b9 fix(detect): extra secret from group before checking allowlist (#1152) 2023-04-19 11:57:24 -05:00
Richard Gomez 81cf30855c Fix G307 warning: Deferring unsafe method "Close" on type "*os.File" (#1154)
* fix: check potential error from file.Close

* fix(detect): use existing logger
2023-04-19 11:56:08 -05:00
Richard Gomez bd8b145bea fix(detect): avoid panic with verbose flag (#1143)
* fix(detect): avoid panic with verbose flag

* chore: fix minor syntax error

* fix: properly print secret with colour

* fix(detect): use lineEndIdx
2023-04-19 11:55:33 -05:00
Edward Wang 839f114f2b Fix typo (#1142) 2023-04-08 17:56:58 -05:00
20 changed files with 135 additions and 100 deletions

No files matched your search

+8
View File
@@ -27,3 +27,11 @@ If applicable, add screenshots to help explain your problem.
Add any other context about the problem here. Add any other context about the problem here.
cc @zricethezav cc @zricethezav
<!--
Check out the Secret Scanning Discord Server for live discussions:
https://discord.gg/sydS6AHTUP
--->
+1 -1
View File
@@ -78,7 +78,7 @@ If you want to add a new rule to the [default Gitleaks configuration](https://gi
token that is unique enough not to require an identifier then you can use token that is unique enough not to require an identifier then you can use
this function. For example, Pulumi's API Token has the prefix `pul-` which is this function. For example, Pulumi's API Token has the prefix `pul-` which is
unique enough to use `generateUniqueToken`. But something like Beamer's API unique enough to use `generateUniqueToken`. But something like Beamer's API
token that has a `b_` prefix is not unqiue enough to use `generateUniqueToken`, token that has a `b_` prefix is not unique enough to use `generateUniqueToken`,
so instead we use `generateSemiGenericRegex` and require a `beamer` so instead we use `generateSemiGenericRegex` and require a `beamer`
identifier is part of the rule. identifier is part of the rule.
If a token's prefix has more than `3` characters then you could If a token's prefix has more than `3` characters then you could
+4 -2
View File
@@ -25,6 +25,8 @@
</p> </p>
</p> </p>
### Join our Discord! [![Discord](https://img.shields.io/discord/1102689410522284044.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/sydS6AHTUP)
Gitleaks is a SAST tool for **detecting** and **preventing** hardcoded secrets like passwords, api keys, and tokens in git repos. Gitleaks is an **easy-to-use, all-in-one solution** for detecting secrets, past or present, in your code. Gitleaks is a SAST tool for **detecting** and **preventing** hardcoded secrets like passwords, api keys, and tokens in git repos. Gitleaks is an **easy-to-use, all-in-one solution** for detecting secrets, past or present, in your code.
``` ```
@@ -182,7 +184,7 @@ You can scan files and directories by using the `--no-git` option.
#### Protect #### Protect
The `protect` command is used to uncommitted changes in a git repo. This command should be used on developer machines in accordance with The `protect` command is used to scan uncommitted changes in a git repo. This command should be used on developer machines in accordance with
[shifting left on security](https://cloud.google.com/architecture/devops/devops-tech-shifting-left-on-security). [shifting left on security](https://cloud.google.com/architecture/devops/devops-tech-shifting-left-on-security).
When running `protect` on a git repository, gitleaks will parse the output of a `git diff` command (you can see how this executed When running `protect` on a git repository, gitleaks will parse the output of a `git diff` command (you can see how this executed
[here](https://github.com/zricethezav/gitleaks/blob/7240e16769b92d2a1b137c17d6bf9d55a8562899/git/git.go#L48-L49)). You can set the [here](https://github.com/zricethezav/gitleaks/blob/7240e16769b92d2a1b137c17d6bf9d55a8562899/git/git.go#L48-L49)). You can set the
@@ -270,7 +272,7 @@ Gitleaks offers a configuration format you can follow to write your own secret d
title = "Gitleaks title" title = "Gitleaks title"
# Extend the base (this) configuration. When you extend a configuration # Extend the base (this) configuration. When you extend a configuration
# the base rules take precendence over the extended rules. I.e, if there are # the base rules take precedence over the extended rules. I.e., if there are
# duplicate rules in both the base configuration and the extended configuration # duplicate rules in both the base configuration and the extended configuration
# the base rules will override the extended rules. # the base rules will override the extended rules.
# Another thing to know with extending configurations is you can chain together # Another thing to know with extending configurations is you can chain together
+18 -1
View File
@@ -20,7 +20,7 @@ func init() {
detectCmd.Flags().Bool("no-git", false, "treat git repo as a regular directory and scan those files, --log-opts has no effect on the scan when --no-git is set") detectCmd.Flags().Bool("no-git", false, "treat git repo as a regular directory and scan those files, --log-opts has no effect on the scan when --no-git is set")
detectCmd.Flags().Bool("pipe", false, "scan input from stdin, ex: `cat some_file | gitleaks detect --pipe`") detectCmd.Flags().Bool("pipe", false, "scan input from stdin, ex: `cat some_file | gitleaks detect --pipe`")
detectCmd.Flags().Bool("follow-symlinks", false, "scan files that are symlinks to other files") detectCmd.Flags().Bool("follow-symlinks", false, "scan files that are symlinks to other files")
detectCmd.Flags().StringP("gitleaks-ignore-path","i",".","path to .gitleaksignore file or folder containing one")
} }
var detectCmd = &cobra.Command{ var detectCmd = &cobra.Command{
@@ -81,6 +81,23 @@ func runDetect(cmd *cobra.Command, args []string) {
log.Fatal().Err(err).Msg("") log.Fatal().Err(err).Msg("")
} }
gitleaksIgnorePath, err:= cmd.Flags().GetString("gitleaks-ignore-path")
if err != nil {
log.Fatal().Err(err).Msg("could not get .gitleaksignore path")
}
if fileExists(gitleaksIgnorePath) {
if err = detector.AddGitleaksIgnore(gitleaksIgnorePath); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
}
}
if fileExists(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")) {
if err = detector.AddGitleaksIgnore(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
}
}
if fileExists(filepath.Join(source, ".gitleaksignore")) { if fileExists(filepath.Join(source, ".gitleaksignore")) {
if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil { if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore") log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
+2 -2
View File
@@ -28,9 +28,9 @@ func TelegramBotToken() *config.Rule {
minToken := secrets.NewSecret(numeric("5") + ":A" + alphaNumericExtendedShort("34")) minToken := secrets.NewSecret(numeric("5") + ":A" + alphaNumericExtendedShort("34"))
maxToken := secrets.NewSecret(numeric("16") + ":A" + alphaNumericExtendedShort("34")) maxToken := secrets.NewSecret(numeric("16") + ":A" + alphaNumericExtendedShort("34"))
tps := []string{ tps := []string{
// variable assigment // variable assignment
generateSampleSecret("telegram", validToken), generateSampleSecret("telegram", validToken),
// URL contaning token // URL containing token
generateSampleSecret("url", "https://api.telegram.org/bot"+validToken+"/sendMessage"), generateSampleSecret("url", "https://api.telegram.org/bot"+validToken+"/sendMessage"),
// object constructor // object constructor
`const bot = new Telegraf("` + validToken + `")`, `const bot = new Telegraf("` + validToken + `")`,
+18
View File
@@ -17,6 +17,7 @@ import (
func init() { func init() {
protectCmd.Flags().Bool("staged", false, "detect secrets in a --staged state") protectCmd.Flags().Bool("staged", false, "detect secrets in a --staged state")
protectCmd.Flags().String("log-opts", "", "git log options") protectCmd.Flags().String("log-opts", "", "git log options")
protectCmd.Flags().StringP("gitleaks-ignore-path","i",".","path to .gitleaksignore file or folder containing one")
rootCmd.AddCommand(protectCmd) rootCmd.AddCommand(protectCmd)
} }
@@ -74,6 +75,23 @@ func runProtect(cmd *cobra.Command, args []string) {
log.Fatal().Err(err).Msg("") log.Fatal().Err(err).Msg("")
} }
gitleaksIgnorePath, err:= cmd.Flags().GetString("gitleaks-ignore-path")
if err != nil {
log.Fatal().Err(err).Msg("could not get .gitleaksignore path")
}
if fileExists(gitleaksIgnorePath) {
if err = detector.AddGitleaksIgnore(gitleaksIgnorePath); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
}
}
if fileExists(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")) {
if err = detector.AddGitleaksIgnore(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
}
}
if fileExists(filepath.Join(source, ".gitleaksignore")) { if fileExists(filepath.Join(source, ".gitleaksignore")) {
if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil { if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil {
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore") log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
+1 -1
View File
@@ -13,7 +13,7 @@ import (
func IsNew(finding report.Finding, baseline []report.Finding) bool { func IsNew(finding report.Finding, baseline []report.Finding) bool {
// Explicitly testing each property as it gives significantly better performance in comparison to cmp.Equal(). Drawback is that // Explicitly testing each property as it gives significantly better performance in comparison to cmp.Equal(). Drawback is that
// the code requires maintanance if/when the Finding struct changes // the code requires maintenance if/when the Finding struct changes
for _, b := range baseline { for _, b := range baseline {
if finding.Author == b.Author && if finding.Author == b.Author &&
+17 -12
View File
@@ -154,7 +154,12 @@ func (d *Detector) AddGitleaksIgnore(gitleaksIgnorePath string) error {
return err return err
} }
defer file.Close() // https://github.com/securego/gosec/issues/512
defer func() {
if err := file.Close(); err != nil {
log.Warn().Msgf("Error closing .gitleaksignore file: %s\n", err)
}
}()
scanner := bufio.NewScanner(file) scanner := bufio.NewScanner(file)
for scanner.Scan() { for scanner.Scan() {
@@ -287,6 +292,17 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find
continue continue
} }
// extract secret from secret group if set
if rule.SecretGroup != 0 {
groups := rule.Regex.FindStringSubmatch(secret)
if len(groups) <= rule.SecretGroup || len(groups) == 0 {
// Config validation should prevent this
continue
}
secret = groups[rule.SecretGroup]
finding.Secret = secret
}
// check if the regexTarget is defined in the allowlist "regexes" entry // check if the regexTarget is defined in the allowlist "regexes" entry
allowlistTarget := finding.Secret allowlistTarget := finding.Secret
switch rule.Allowlist.RegexTarget { switch rule.Allowlist.RegexTarget {
@@ -308,17 +324,6 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find
continue continue
} }
// extract secret from secret group if set
if rule.SecretGroup != 0 {
groups := rule.Regex.FindStringSubmatch(secret)
if len(groups) <= rule.SecretGroup || len(groups) == 0 {
// Config validation should prevent this
continue
}
secret = groups[rule.SecretGroup]
finding.Secret = secret
}
// check if the secret is in the list of stopwords // check if the secret is in the list of stopwords
if rule.Allowlist.ContainsStopWord(finding.Secret) || if rule.Allowlist.ContainsStopWord(finding.Secret) ||
d.Config.Allowlist.ContainsStopWord(finding.Secret) { d.Config.Allowlist.ContainsStopWord(finding.Secret) {
+1 -1
View File
@@ -23,7 +23,7 @@ func TestDetect(t *testing.T) {
fragment Fragment fragment Fragment
// NOTE: for expected findings, all line numbers will be 0 // NOTE: for expected findings, all line numbers will be 0
// because line deltas are added _after_ the finding is created. // because line deltas are added _after_ the finding is created.
// I.e, if the finding is from a --no-git file, the line number will be // I.e., if the finding is from a --no-git file, the line number will be
// increase by 1 in DetectFromFiles(). If the finding is from git, // increase by 1 in DetectFromFiles(). If the finding is from git,
// the line number will be increased by the patch delta. // the line number will be increased by the patch delta.
expectedFindings []report.Finding expectedFindings []report.Finding
+45 -39
View File
@@ -74,7 +74,7 @@ func filter(findings []report.Finding, redact bool) []report.Finding {
genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1) genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1)
betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1) betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1)
log.Trace().Msgf("skipping %s finding (%s), %s rule takes precendence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch) log.Trace().Msgf("skipping %s finding (%s), %s rule takes precedence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
include = false include = false
break break
} }
@@ -92,57 +92,63 @@ func filter(findings []report.Finding, redact bool) []report.Finding {
} }
func printFinding(f report.Finding, noColor bool) { func printFinding(f report.Finding, noColor bool) {
// trim all whitespace and tabs from the line // trim all whitespace and tabs
f.Line = strings.TrimSpace(f.Line) f.Line = strings.TrimSpace(f.Line)
// trim all whitespace and tabs from the secret
f.Secret = strings.TrimSpace(f.Secret) f.Secret = strings.TrimSpace(f.Secret)
// trim all whitespace and tabs from the match
f.Match = strings.TrimSpace(f.Match) f.Match = strings.TrimSpace(f.Match)
matchInLineIDX := strings.Index(f.Line, f.Match) isFileMatch := strings.HasPrefix(f.Match, "file detected:")
secretInMatchIdx := strings.Index(f.Match, f.Secret) skipColor := noColor
finding := ""
var secret lipgloss.Style
// Matches from filenames do not have a |line| or |secret|
if !isFileMatch {
matchInLineIDX := strings.Index(f.Line, f.Match)
secretInMatchIdx := strings.Index(f.Match, f.Secret)
skipColor := false skipColor = false
if matchInLineIDX == -1 || noColor { if matchInLineIDX == -1 || noColor {
skipColor = true skipColor = true
matchInLineIDX = 0 matchInLineIDX = 0
} }
start := f.Line[0:matchInLineIDX] start := f.Line[0:matchInLineIDX]
startMatchIdx := 0 startMatchIdx := 0
if matchInLineIDX > 20 { if matchInLineIDX > 20 {
startMatchIdx = matchInLineIDX - 20 startMatchIdx = matchInLineIDX - 20
start = "..." + f.Line[startMatchIdx:matchInLineIDX] start = "..." + f.Line[startMatchIdx:matchInLineIDX]
} }
matchBeginning := lipgloss.NewStyle().SetString(f.Match[0:secretInMatchIdx]).Foreground(lipgloss.Color("#f5d445")) matchBeginning := lipgloss.NewStyle().SetString(f.Match[0:secretInMatchIdx]).Foreground(lipgloss.Color("#f5d445"))
secret := lipgloss.NewStyle().SetString(f.Secret). secret = lipgloss.NewStyle().SetString(f.Secret).
Bold(true).
Italic(true).
Foreground(lipgloss.Color("#f05c07"))
matchEnd := lipgloss.NewStyle().SetString(f.Match[secretInMatchIdx+len(f.Secret):]).Foreground(lipgloss.Color("#f5d445"))
lineEndIdx := matchInLineIDX + len(f.Match)
if len(f.Line)-1 <= lineEndIdx {
lineEndIdx = len(f.Line) - 1
}
lineEnd := f.Line[matchInLineIDX+len(f.Match):]
if len(f.Secret) > 100 {
secret = lipgloss.NewStyle().SetString(f.Secret[0:100] + "...").
Bold(true). Bold(true).
Italic(true). Italic(true).
Foreground(lipgloss.Color("#f05c07")) Foreground(lipgloss.Color("#f05c07"))
} matchEnd := lipgloss.NewStyle().SetString(f.Match[secretInMatchIdx+len(f.Secret):]).Foreground(lipgloss.Color("#f5d445"))
if len(lineEnd) > 20 {
lineEnd = lineEnd[0:20] + "..." lineEndIdx := matchInLineIDX + len(f.Match)
if len(f.Line)-1 <= lineEndIdx {
lineEndIdx = len(f.Line) - 1
}
lineEnd := f.Line[lineEndIdx:]
if len(f.Secret) > 100 {
secret = lipgloss.NewStyle().SetString(f.Secret[0:100] + "...").
Bold(true).
Italic(true).
Foreground(lipgloss.Color("#f05c07"))
}
if len(lineEnd) > 20 {
lineEnd = lineEnd[0:20] + "..."
}
finding = fmt.Sprintf("%s%s%s%s%s\n", strings.TrimPrefix(strings.TrimLeft(start, " "), "\n"), matchBeginning, secret, matchEnd, lineEnd)
} }
finding := fmt.Sprintf("%s%s%s%s%s\n", strings.TrimPrefix(strings.TrimLeft(start, " "), "\n"), matchBeginning, secret, matchEnd, lineEnd) if skipColor || isFileMatch {
if skipColor {
fmt.Printf("%-12s %s\n", "Finding:", f.Match) fmt.Printf("%-12s %s\n", "Finding:", f.Match)
fmt.Printf("%-12s %s\n", "Secret:", f.Secret) fmt.Printf("%-12s %s\n", "Secret:", f.Secret)
} else { } else {
+3 -9
View File
@@ -1,6 +1,7 @@
package report package report
import ( import (
"bytes"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -45,42 +46,35 @@ func TestWriteCSV(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
tmpfile, err := os.Create(filepath.Join(tmpPath, test.testReportName+".csv")) tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".csv"))
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
err = writeCsv(test.findings, tmpfile) err = writeCsv(test.findings, tmpfile)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
got, err := os.ReadFile(tmpfile.Name()) got, err := os.ReadFile(tmpfile.Name())
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if test.wantEmpty { if test.wantEmpty {
if len(got) > 0 { if len(got) > 0 {
t.Errorf("Expected empty file, got %s", got) t.Errorf("Expected empty file, got %s", got)
} }
os.Remove(tmpfile.Name())
continue continue
} }
want, err := os.ReadFile(test.expected) want, err := os.ReadFile(test.expected)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if string(got) != string(want) { if !bytes.Equal(got, want) {
err = os.WriteFile(strings.Replace(test.expected, ".csv", ".got.csv", 1), got, 0644) err = os.WriteFile(strings.Replace(test.expected, ".csv", ".got.csv", 1), got, 0644)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
t.Errorf("got %s, want %s", string(got), string(want)) t.Errorf("got %s, want %s", string(got), string(want))
} }
os.Remove(tmpfile.Name())
} }
} }
+1 -1
View File
@@ -38,7 +38,7 @@ type Finding struct {
// Rule is the name of the rule that was matched // Rule is the name of the rule that was matched
RuleID string RuleID string
// unique identifer // unique identifier
Fingerprint string Fingerprint string
} }
+2
View File
@@ -9,6 +9,8 @@ func writeJson(findings []Finding, w io.WriteCloser) error {
if len(findings) == 0 { if len(findings) == 0 {
findings = []Finding{} findings = []Finding{}
} }
defer w.Close()
encoder := json.NewEncoder(w) encoder := json.NewEncoder(w)
encoder.SetIndent("", " ") encoder.SetIndent("", " ")
return encoder.Encode(findings) return encoder.Encode(findings)
+3 -11
View File
@@ -1,6 +1,7 @@
package report package report
import ( import (
"bytes"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -46,44 +47,35 @@ func TestWriteJSON(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
// create tmp file using os.TempDir() tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".json"))
tmpfile, err := os.Create(filepath.Join(tmpPath, test.testReportName+".json"))
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
err = writeJson(test.findings, tmpfile) err = writeJson(test.findings, tmpfile)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
got, err := os.ReadFile(tmpfile.Name()) got, err := os.ReadFile(tmpfile.Name())
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if test.wantEmpty { if test.wantEmpty {
if len(got) > 0 { if len(got) > 0 {
os.Remove(tmpfile.Name())
t.Errorf("Expected empty file, got %s", got) t.Errorf("Expected empty file, got %s", got)
} }
os.Remove(tmpfile.Name())
continue continue
} }
want, err := os.ReadFile(test.expected) want, err := os.ReadFile(test.expected)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if string(got) != string(want) { if !bytes.Equal(got, want) {
err = os.WriteFile(strings.Replace(test.expected, ".json", ".got.json", 1), got, 0644) err = os.WriteFile(strings.Replace(test.expected, ".json", ".got.json", 1), got, 0644)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
t.Errorf("got %s, want %s", string(got), string(want)) t.Errorf("got %s, want %s", string(got), string(want))
} }
os.Remove(tmpfile.Name())
} }
} }
+1 -6
View File
@@ -11,7 +11,6 @@ import (
const ( const (
expectPath = "../testdata/expected/" expectPath = "../testdata/expected/"
tmpPath = "../testdata/tmp"
) )
func TestReport(t *testing.T) { func TestReport(t *testing.T) {
@@ -80,22 +79,18 @@ func TestReport(t *testing.T) {
} }
for i, test := range tests { for i, test := range tests {
tmpfile, err := os.Create(filepath.Join(tmpPath, strconv.Itoa(i)+test.ext)) tmpfile, err := os.Create(filepath.Join(t.TempDir(), strconv.Itoa(i)+test.ext))
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
err = Write(test.findings, config.Config{}, test.ext, tmpfile.Name()) err = Write(test.findings, config.Config{}, test.ext, tmpfile.Name())
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
got, err := os.ReadFile(tmpfile.Name()) got, err := os.ReadFile(tmpfile.Name())
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
os.Remove(tmpfile.Name())
if len(got) == 0 && !test.wantEmpty { if len(got) == 0 && !test.wantEmpty {
t.Errorf("got empty file with extension " + test.ext) t.Errorf("got empty file with extension " + test.ext)
+4 -1
View File
@@ -10,10 +10,11 @@ import (
func writeSarif(cfg config.Config, findings []Finding, w io.WriteCloser) error { func writeSarif(cfg config.Config, findings []Finding, w io.WriteCloser) error {
sarif := Sarif{ sarif := Sarif{
Schema: "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json", Schema: "https://json.schemastore.org/sarif-2.1.0.json",
Version: "2.1.0", Version: "2.1.0",
Runs: getRuns(cfg, findings), Runs: getRuns(cfg, findings),
} }
defer w.Close()
encoder := json.NewEncoder(w) encoder := json.NewEncoder(w)
encoder.SetIndent("", " ") encoder.SetIndent("", " ")
@@ -34,6 +35,7 @@ func getTool(cfg config.Config) Tool {
Driver: Driver{ Driver: Driver{
Name: driver, Name: driver,
SemanticVersion: version, SemanticVersion: version,
InformationUri: "https://github.com/gitleaks/gitleaks",
Rules: getRules(cfg), Rules: getRules(cfg),
}, },
} }
@@ -164,6 +166,7 @@ type Rules struct {
type Driver struct { type Driver struct {
Name string `json:"name"` Name string `json:"name"`
SemanticVersion string `json:"semanticVersion"` SemanticVersion string `json:"semanticVersion"`
InformationUri string `json:"informationUri"`
Rules []Rules `json:"rules"` Rules []Rules `json:"rules"`
} }
+3 -10
View File
@@ -1,6 +1,7 @@
package report package report
import ( import (
"bytes"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
@@ -48,10 +49,8 @@ func TestWriteSarif(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
// create tmp file using os.TempDir() tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".json"))
tmpfile, err := os.Create(filepath.Join(tmpPath, test.testReportName+".json"))
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
viper.Reset() viper.Reset()
@@ -76,29 +75,24 @@ func TestWriteSarif(t *testing.T) {
err = writeSarif(cfg, test.findings, tmpfile) err = writeSarif(cfg, test.findings, tmpfile)
fmt.Println(cfg) fmt.Println(cfg)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
got, err := os.ReadFile(tmpfile.Name()) got, err := os.ReadFile(tmpfile.Name())
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if test.wantEmpty { if test.wantEmpty {
if len(got) > 0 { if len(got) > 0 {
os.Remove(tmpfile.Name())
t.Errorf("Expected empty file, got %s", got) t.Errorf("Expected empty file, got %s", got)
} }
os.Remove(tmpfile.Name())
continue continue
} }
want, err := os.ReadFile(test.expected) want, err := os.ReadFile(test.expected)
if err != nil { if err != nil {
os.Remove(tmpfile.Name())
t.Error(err) t.Error(err)
} }
if string(got) != string(want) { if !bytes.Equal(got, want) {
err = os.WriteFile(strings.Replace(test.expected, ".sarif", ".got.sarif", 1), got, 0644) err = os.WriteFile(strings.Replace(test.expected, ".sarif", ".got.sarif", 1), got, 0644)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
@@ -106,6 +100,5 @@ func TestWriteSarif(t *testing.T) {
t.Errorf("got %s, want %s", string(got), string(want)) t.Errorf("got %s, want %s", string(got), string(want))
} }
os.Remove(tmpfile.Name())
} }
} }
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json", "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0", "version": "2.1.0",
"runs": [ "runs": [
] ]
+2 -1
View File
@@ -1,5 +1,5 @@
{ {
"$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json", "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0", "version": "2.1.0",
"runs": [ "runs": [
{ {
@@ -7,6 +7,7 @@
"driver": { "driver": {
"name": "gitleaks", "name": "gitleaks",
"semanticVersion": "v8.0.0", "semanticVersion": "v8.0.0",
"informationUri": "https://github.com/gitleaks/gitleaks",
"rules": [ "rules": [
{ {
"id": "aws-access-key", "id": "aws-access-key",
-1
View File
@@ -1 +0,0 @@
nothing should be saved here