| 1 |
package tests |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"encoding/xml" |
| 6 |
"fmt" |
| 7 |
"math/rand" |
| 8 |
"os" |
| 9 |
"path/filepath" |
| 10 |
"strings" |
| 11 |
"testing" |
| 12 |
|
| 13 |
"github.com/DefangLabs/secret-detector/pkg/dataformat" |
| 14 |
"github.com/DefangLabs/secret-detector/pkg/detectors/artifactory" |
| 15 |
"github.com/DefangLabs/secret-detector/pkg/detectors/aws" |
| 16 |
"github.com/DefangLabs/secret-detector/pkg/detectors/azure" |
| 17 |
"github.com/DefangLabs/secret-detector/pkg/detectors/basicauth" |
| 18 |
"github.com/DefangLabs/secret-detector/pkg/detectors/bearerauth" |
| 19 |
"github.com/DefangLabs/secret-detector/pkg/detectors/generic" |
| 20 |
"github.com/DefangLabs/secret-detector/pkg/detectors/github" |
| 21 |
"github.com/DefangLabs/secret-detector/pkg/detectors/jwt" |
| 22 |
"github.com/DefangLabs/secret-detector/pkg/detectors/keyword" |
| 23 |
"github.com/DefangLabs/secret-detector/pkg/detectors/mailchimp" |
| 24 |
"github.com/DefangLabs/secret-detector/pkg/detectors/npm" |
| 25 |
"github.com/DefangLabs/secret-detector/pkg/detectors/privatekey" |
| 26 |
"github.com/DefangLabs/secret-detector/pkg/detectors/sendgrid" |
| 27 |
"github.com/DefangLabs/secret-detector/pkg/detectors/slack" |
| 28 |
"github.com/DefangLabs/secret-detector/pkg/detectors/square" |
| 29 |
"github.com/DefangLabs/secret-detector/pkg/detectors/stripe" |
| 30 |
"github.com/DefangLabs/secret-detector/pkg/detectors/twilio" |
| 31 |
"github.com/DefangLabs/secret-detector/pkg/scanner" |
| 32 |
"github.com/DefangLabs/secret-detector/pkg/secrets" |
| 33 |
"github.com/stretchr/testify/assert" |
| 34 |
"gopkg.in/ini.v1" |
| 35 |
"gopkg.in/yaml.v3" |
| 36 |
) |
| 37 |
|
| 38 |
const ( |
| 39 |
artifactoryKey = "artifactory" |
| 40 |
awsClientIdKey = "awsClientId" |
| 41 |
awsKey = "awsKey" |
| 42 |
mwsKey = "mws" |
| 43 |
azureKey = "azure" |
| 44 |
basicAuthKey = "basicAuth" |
| 45 |
bearerAuthKey = "bearerAuth" |
| 46 |
entropyKey = "high_entropy_str" |
| 47 |
urlPwdKey = "url" |
| 48 |
githubKey = "github" |
| 49 |
jwtKey = "jwt" |
| 50 |
keywordKey = "secretKeyword" |
| 51 |
mailchimpKey = "mailchimp" |
| 52 |
npmKey = "npm" |
| 53 |
pkKey = "pk" |
| 54 |
sendgridKey = "sendgrid" |
| 55 |
slackTokenKey = "slack" |
| 56 |
slackWebhookKey = "slack_webhook" |
| 57 |
squareKey = "square" |
| 58 |
stripeKey = "stripe" |
| 59 |
twilioKey = "twilio" |
| 60 |
) |
| 61 |
|
| 62 |
var ( |
| 63 |
artifactoryType = artifactory.NewDetector().SecretType() |
| 64 |
awsClientIdType = aws.NewClientIdDetector().SecretType() |
| 65 |
awsSecretKeyType = aws.NewSecretKeyDetector().SecretType() |
| 66 |
awsMWSKeyType = aws.NewMWSKeyDetector().SecretType() |
| 67 |
azureType = azure.NewDetector().SecretType() |
| 68 |
basicAuthType = basicauth.NewDetector().SecretType() |
| 69 |
bearerAuthType = bearerauth.NewDetector().SecretType() |
| 70 |
entropyType = generic.NewHighEntropyStringDetector().SecretType() |
| 71 |
urlPwdType = generic.NewURLPasswordDetector().SecretType() |
| 72 |
githubType = github.NewDetector().SecretType() |
| 73 |
jwtType = jwt.NewDetector().SecretType() |
| 74 |
keywordType = keyword.NewDetector().SecretType() |
| 75 |
mailchimpType = mailchimp.NewDetector().SecretType() |
| 76 |
npmType = npm.NewDetector().SecretType() |
| 77 |
privateKeyType = privatekey.NewDetector().SecretType() |
| 78 |
sendgridType = sendgrid.NewDetector().SecretType() |
| 79 |
slackType = slack.NewDetector().SecretType() |
| 80 |
squareType = square.NewDetector().SecretType() |
| 81 |
stripeType = stripe.NewDetector().SecretType() |
| 82 |
twilioType = twilio.NewDetector().SecretType() |
| 83 |
|
| 84 |
input = map[string]string{ |
| 85 |
artifactoryKey: `AKCabcXYZ1234`, |
| 86 |
awsClientIdKey: `A3TX1234567890ABCDEF`, |
| 87 |
awsKey: `aws"12345+67890/abcdefghijklm+NOPQRSTUVWXYZ+"`, |
| 88 |
mwsKey: `amzn.mws.12345678-1234-1234-1234-123456789012`, |
| 89 |
azureKey: `AccountKey=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+/abcdefghijklmnopqrstuv==`, |
| 90 |
basicAuthKey: `Basic ABCDEFGHIJ+KLMNOPQRST/UVWXYZ,abcdefghij_klmnopqrstuvwxyz-1234567890==`, |
| 91 |
bearerAuthKey: `Bearer ABCDEFGHIJ+KLMNOPQRST/UVWXYZ,abcdefghij_klmnopq.rstuvwxyz-1234567890==`, |
| 92 |
entropyKey: `dGhpcyBpcyBhIHRlc3QgZm9yIGhpZ2ggZW50cm9weSBiYXNlNjQgc2VjcmV0IGRldGVjdGlvbg`, |
| 93 |
urlPwdKey: `smtp://[email protected]:[email protected]:465/`, |
| 94 |
githubKey: `ghp_aBcDeFgHiJkLmNoPqRsTuVwXyZ1234567890`, |
| 95 |
jwtKey: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c`, |
| 96 |
keywordKey: `1qaz!QAZ`, |
| 97 |
mailchimpKey: `1234567890abcdef1234567890abcdef-us99`, |
| 98 |
npmKey: `//registry.npmjs.org/:_authToken=0af23f36-c523-4c87-b543-18ff3ed79bce`, |
| 99 |
pkKey: "-----BEGIN DSA PRIVATE KEY-----\nwxyz+ABC=\n-----END DSA PRIVATE KEY-----", |
| 100 |
sendgridKey: `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`, |
| 101 |
slackTokenKey: `xapp-1-QKDD2TWZ27V-0372407459206-989awefasdf98afaw8e9ruw98efuq9w8ef1nmqlr39098af98ankjnpq9a0kme09`, |
| 102 |
slackWebhookKey: `https://hooks.slack.com/services/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`, |
| 103 |
squareKey: `sq0atp-12345\6789_abcde-VWXYZ`, |
| 104 |
stripeKey: `sk_live_1234567890abcdefgHIJKLMN`, |
| 105 |
twilioKey: `AC1234567890abcdef1234567890abcdef`, |
| 106 |
} |
| 107 |
|
| 108 |
expectedSecrets = []secrets.DetectedSecret{ |
| 109 |
{Key: artifactoryKey, Type: artifactoryType, Value: input[artifactoryKey]}, |
| 110 |
{Key: awsClientIdKey, Type: awsClientIdType, Value: input[awsClientIdKey]}, |
| 111 |
{Key: awsKey, Type: awsSecretKeyType, Value: input[awsKey]}, |
| 112 |
{Key: mwsKey, Type: awsMWSKeyType, Value: input[mwsKey]}, |
| 113 |
{Key: azureKey, Type: azureType, Value: input[azureKey]}, |
| 114 |
{Key: basicAuthKey, Type: basicAuthType, Value: input[basicAuthKey]}, |
| 115 |
{Key: bearerAuthKey, Type: bearerAuthType, Value: input[bearerAuthKey]}, |
| 116 |
{Key: entropyKey, Type: entropyType, Value: input[entropyKey]}, |
| 117 |
{Key: urlPwdKey, Type: urlPwdType, Value: input[urlPwdKey]}, |
| 118 |
{Key: githubKey, Type: githubType, Value: input[githubKey]}, |
| 119 |
{Key: jwtKey, Type: jwtType, Value: input[jwtKey]}, |
| 120 |
{Key: keywordKey, Type: keywordType, Value: input[keywordKey]}, |
| 121 |
{Key: mailchimpKey, Type: mailchimpType, Value: input[mailchimpKey]}, |
| 122 |
{Key: npmKey, Type: npmType, Value: input[npmKey]}, |
| 123 |
{Key: pkKey, Type: privateKeyType, Value: input[pkKey]}, |
| 124 |
{Key: sendgridKey, Type: sendgridType, Value: input[sendgridKey]}, |
| 125 |
{Key: slackTokenKey, Type: slackType, Value: input[slackTokenKey]}, |
| 126 |
{Key: slackWebhookKey, Type: slackType, Value: input[slackWebhookKey]}, |
| 127 |
{Key: squareKey, Type: squareType, Value: input[squareKey]}, |
| 128 |
{Key: stripeKey, Type: stripeType, Value: input[stripeKey]}, |
| 129 |
{Key: twilioKey, Type: twilioType, Value: input[twilioKey]}, |
| 130 |
} |
| 131 |
) |
| 132 |
|
| 133 |
func TestScanFile(t *testing.T) { |
| 134 |
config := scanner.NewConfigWithDefaults() |
| 135 |
config.DetectorConfigs[keyword.Name] = []string{"0"} |
| 136 |
defaultScanner, _ := scanner.NewScannerFromConfig(config) |
| 137 |
|
| 138 |
t.Run("test ScanFile with a binary file", func(t *testing.T) { |
| 139 |
b := make([]byte, 1024) |
| 140 |
rand.Read(b) |
| 141 |
path := createTestFile(t, "dat", b) |
| 142 |
|
| 143 |
actualSecrets, err := defaultScanner.ScanFile(path) |
| 144 |
assert.Nil(t, actualSecrets) |
| 145 |
assert.EqualError(t, err, secrets.NewNotTextFileError(path).Error()) |
| 146 |
}) |
| 147 |
|
| 148 |
t.Run("test ScanFile with a large text file", func(t *testing.T) { |
| 149 |
length := scanner.DefaultThreshold + 1 |
| 150 |
b := make([]byte, length) |
| 151 |
rand.Read(b) |
| 152 |
in := fmt.Sprintf("%x", b)[:length] |
| 153 |
path := createTestFile(t, "big", []byte(in)) |
| 154 |
|
| 155 |
actualSecrets, err := defaultScanner.ScanFile(path) |
| 156 |
assert.NoError(t, err) |
| 157 |
if assert.Len(t, actualSecrets, 1) { |
| 158 |
assert.Equal(t, actualSecrets[0].Key, path) |
| 159 |
assert.Equal(t, actualSecrets[0].Type, scanner.SizeThresholdViolationType) |
| 160 |
assert.Equal(t, actualSecrets[0].Value, "9.54MB") |
| 161 |
} |
| 162 |
}) |
| 163 |
|
| 164 |
t.Run("test ScanFile with a non existing file", func(t *testing.T) { |
| 165 |
b := make([]byte, 1024) |
| 166 |
rand.Read(b) |
| 167 |
path := "./file.not_exist" |
| 168 |
|
| 169 |
actualSecrets, err := defaultScanner.ScanFile(path) |
| 170 |
assert.Nil(t, actualSecrets) |
| 171 |
os.IsNotExist(err) |
| 172 |
assert.ErrorIs(t, err, os.ErrNotExist) |
| 173 |
}) |
| 174 |
} |
| 175 |
|
| 176 |
func TestJSON(t *testing.T) { |
| 177 |
b, err := json.MarshalIndent(input, "", " ") |
| 178 |
if err != nil { |
| 179 |
t.FailNow() |
| 180 |
} |
| 181 |
|
| 182 |
test(t, dataformat.JSON, string(b), expectedSecrets) |
| 183 |
} |
| 184 |
|
| 185 |
func TestYAML(t *testing.T) { |
| 186 |
b, err := yaml.Marshal(input) |
| 187 |
if err != nil { |
| 188 |
t.FailNow() |
| 189 |
} |
| 190 |
|
| 191 |
test(t, dataformat.YAML, string(b), expectedSecrets) |
| 192 |
} |
| 193 |
|
| 194 |
func TestXMLElement(t *testing.T) { |
| 195 |
sb := &strings.Builder{} |
| 196 |
encoder := xml.NewEncoder(sb) |
| 197 |
encoder.Indent("", " ") |
| 198 |
root := xml.StartElement{Name: xml.Name{Local: "root"}} |
| 199 |
tokens := []xml.Token{root} |
| 200 |
for key, value := range input { |
| 201 |
tag := xml.StartElement{Name: xml.Name{Local: key}} |
| 202 |
tokens = append(tokens, tag, xml.CharData(value), xml.EndElement{Name: tag.Name}) |
| 203 |
} |
| 204 |
tokens = append(tokens, xml.EndElement{Name: root.Name}) |
| 205 |
for _, token := range tokens { |
| 206 |
if err := encoder.EncodeToken(token); err != nil { |
| 207 |
t.FailNow() |
| 208 |
} |
| 209 |
} |
| 210 |
if err := encoder.Flush(); err != nil { |
| 211 |
t.FailNow() |
| 212 |
} |
| 213 |
|
| 214 |
expected := make([]secrets.DetectedSecret, len(expectedSecrets)) |
| 215 |
for i, secret := range expectedSecrets { |
| 216 |
expected[i] = secrets.DetectedSecret{ |
| 217 |
Key: fmt.Sprintf("%v.%v", root.Name.Local, secret.Key), |
| 218 |
Type: secret.Type, |
| 219 |
Value: secret.Value, |
| 220 |
} |
| 221 |
} |
| 222 |
|
| 223 |
test(t, dataformat.XML, sb.String(), expected) |
| 224 |
} |
| 225 |
|
| 226 |
func TestXMLAttributes(t *testing.T) { |
| 227 |
sb := &strings.Builder{} |
| 228 |
encoder := xml.NewEncoder(sb) |
| 229 |
encoder.Indent("", " ") |
| 230 |
root := xml.StartElement{Name: xml.Name{Local: "root"}} |
| 231 |
tokens := []xml.Token{root} |
| 232 |
for key, value := range input { |
| 233 |
tag := xml.StartElement{ |
| 234 |
Name: xml.Name{Local: key}, |
| 235 |
Attr: []xml.Attr{{ |
| 236 |
Name: xml.Name{Local: "attr"}, |
| 237 |
Value: value, |
| 238 |
}}, |
| 239 |
} |
| 240 |
tokens = append(tokens, tag, xml.EndElement{Name: tag.Name}) |
| 241 |
} |
| 242 |
tokens = append(tokens, xml.EndElement{Name: root.Name}) |
| 243 |
for _, token := range tokens { |
| 244 |
if err := encoder.EncodeToken(token); err != nil { |
| 245 |
t.FailNow() |
| 246 |
} |
| 247 |
} |
| 248 |
if err := encoder.Flush(); err != nil { |
| 249 |
t.FailNow() |
| 250 |
} |
| 251 |
|
| 252 |
expected := make([]secrets.DetectedSecret, len(expectedSecrets)) |
| 253 |
for i, secret := range expectedSecrets { |
| 254 |
expected[i] = secrets.DetectedSecret{ |
| 255 |
Key: fmt.Sprintf("%v.%v[attr]", root.Name.Local, secret.Key), |
| 256 |
Type: secret.Type, |
| 257 |
Value: secret.Value, |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
test(t, dataformat.XML, sb.String(), expected) |
| 262 |
} |
| 263 |
|
| 264 |
func TestINI(t *testing.T) { |
| 265 |
sb := &strings.Builder{} |
| 266 |
cfg := ini.Empty() |
| 267 |
section := cfg.Section("") |
| 268 |
for key, value := range input { |
| 269 |
section.NewKey(key, value) |
| 270 |
} |
| 271 |
cfg.WriteTo(sb) |
| 272 |
|
| 273 |
test(t, dataformat.INI, sb.String(), expectedSecrets) |
| 274 |
} |
| 275 |
|
| 276 |
func TestJustValues(t *testing.T) { |
| 277 |
for _, secret := range expectedSecrets { |
| 278 |
if secret.Key == urlPwdKey { |
| 279 |
fmt.Print("url") |
| 280 |
} |
| 281 |
var in string |
| 282 |
expected := make([]secrets.DetectedSecret, 0) |
| 283 |
switch secret.Key { |
| 284 |
case keywordKey: |
| 285 |
in = fmt.Sprintf("%s=%s", secret.Key, input[secret.Key]) |
| 286 |
expected = append(expected, secrets.DetectedSecret{Key: secret.Key, Type: secret.Type, Value: secret.Value}) |
| 287 |
case pkKey: |
| 288 |
in = input[secret.Key] |
| 289 |
if i := strings.Index(secret.Value, "\n"); i != -1 { |
| 290 |
secret.Value = secret.Value[:i] |
| 291 |
} |
| 292 |
expected = append(expected, secrets.DetectedSecret{Key: "", Type: secret.Type, Value: secret.Value}) |
| 293 |
case azureKey: |
| 294 |
in = input[secret.Key] |
| 295 |
expected = append(expected, secrets.DetectedSecret{Key: "AccountKey", Type: secret.Type, Value: secret.Value[11:]}) |
| 296 |
default: |
| 297 |
in = input[secret.Key] |
| 298 |
expected = append(expected, secrets.DetectedSecret{Key: "", Type: secret.Type, Value: secret.Value}) |
| 299 |
} |
| 300 |
|
| 301 |
test(t, dataformat.DataFormat(secret.Key), in, expected) |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
func test(t *testing.T, format dataformat.DataFormat, input string, expectedSecrets []secrets.DetectedSecret) { |
| 306 |
config := scanner.NewConfigWithDefaults() |
| 307 |
config.DetectorConfigs[keyword.Name] = []string{"0"} |
| 308 |
config.DetectorConfigs[generic.HighEntropyStringDetectorName] = []string{"0"} |
| 309 |
defaultScanner, _ := scanner.NewScannerFromConfig(config) |
| 310 |
t.Helper() |
| 311 |
|
| 312 |
t.Run(fmt.Sprintf("test Scan - %s", format), func(t *testing.T) { |
| 313 |
actualSecrets, err := defaultScanner.Scan(input) |
| 314 |
assertSecrets(t, expectedSecrets, actualSecrets, err) |
| 315 |
}) |
| 316 |
|
| 317 |
t.Run(fmt.Sprintf("test ScanReader - %s", format), func(t *testing.T) { |
| 318 |
actualSecrets, err := defaultScanner.ScanReader(strings.NewReader(input)) |
| 319 |
assertSecrets(t, expectedSecrets, actualSecrets, err) |
| 320 |
}) |
| 321 |
|
| 322 |
t.Run(fmt.Sprintf("test ScanWithFormat - %s", format), func(t *testing.T) { |
| 323 |
actualSecrets, err := defaultScanner.ScanWithFormat(strings.NewReader(input), format) |
| 324 |
assertSecrets(t, expectedSecrets, actualSecrets, err) |
| 325 |
}) |
| 326 |
|
| 327 |
t.Run(fmt.Sprintf("test ScanWithFormat with an unknown format - %s", format), func(t *testing.T) { |
| 328 |
actualSecrets, err := defaultScanner.ScanWithFormat(strings.NewReader(input), "unknown") |
| 329 |
assertSecrets(t, expectedSecrets, actualSecrets, err) |
| 330 |
}) |
| 331 |
|
| 332 |
t.Run(fmt.Sprintf("test ScanFile - %s", format), func(t *testing.T) { |
| 333 |
path := createTestFile(t, string(format), []byte(input)) |
| 334 |
actualSecrets, err := defaultScanner.ScanFile(path) |
| 335 |
assertSecrets(t, expectedSecrets, actualSecrets, err) |
| 336 |
}) |
| 337 |
} |
| 338 |
|
| 339 |
func assertSecrets(t *testing.T, expectedSecrets, actualSecrets []secrets.DetectedSecret, err error) { |
| 340 |
assert.NoError(t, err) |
| 341 |
if !assert.Len(t, actualSecrets, len(expectedSecrets)) { |
| 342 |
t.FailNow() |
| 343 |
} |
| 344 |
|
| 345 |
actualMap := make(map[string]secrets.DetectedSecret, len(actualSecrets)) |
| 346 |
for _, secret := range actualSecrets { |
| 347 |
actualMap[secret.Key] = secret |
| 348 |
} |
| 349 |
|
| 350 |
for _, expected := range expectedSecrets { |
| 351 |
secret, found := actualMap[expected.Key] |
| 352 |
if assert.True(t, found) { |
| 353 |
assert.Equal(t, expected.Key, secret.Key) |
| 354 |
assert.Equal(t, expected.Type, secret.Type) |
| 355 |
assert.Equal(t, expected.Value, secret.Value) |
| 356 |
} |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
func createTestFile(t *testing.T, extension string, input []byte) string { |
| 361 |
t.Helper() |
| 362 |
|
| 363 |
wd, err := os.Getwd() |
| 364 |
if !assert.NoError(t, err) { |
| 365 |
t.FailNow() |
| 366 |
} |
| 367 |
path := filepath.Join(wd, "test_files") |
| 368 |
if err = os.MkdirAll(path, os.ModePerm); !assert.NoError(t, err) { |
| 369 |
t.FailNow() |
| 370 |
} |
| 371 |
|
| 372 |
path = filepath.Join(path, fmt.Sprintf("test.%s", extension)) |
| 373 |
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755) |
| 374 |
if !assert.NoError(t, err) { |
| 375 |
t.FailNow() |
| 376 |
} |
| 377 |
defer func() { |
| 378 |
assert.NoError(t, f.Close()) |
| 379 |
}() |
| 380 |
if _, err = f.Write(input); !assert.NoError(t, err) { |
| 381 |
t.FailNow() |
| 382 |
} |
| 383 |
t.Cleanup(func() { |
| 384 |
if err := os.Remove(path); err != nil { |
| 385 |
t.Logf("failed to remove file '%v': %v", path, err) |
| 386 |
} |
| 387 |
}) |
| 388 |
|
| 389 |
return path |
| 390 |
} |