Debian Codegraph @

pkg/detectors/generic/high_entropy_string_detector_test.go

raw symbols SCIP
1 package generic
2
3 import (
4 "testing"
5
6 "github.com/DefangLabs/secret-detector/pkg/detectors/tests"
7 "github.com/stretchr/testify/assert"
8 )
9
10 var highEntropyTestCases = []tests.TestCase{
11 {"hex - short high entropy", "1234567890abcdef", true},
12 {"hex - long high entropy", "9a3aff9be15b2f98039f0de2883eb7936d50a97b48d78dbc1d47d6ecaa243889", true},
13
14 {"hex - entropy exactly on threshold", "abcdef12abcdef12", false},
15 {"hex - low entropy", "abcdabcdabcdabcd", false},
16 {"hex - too short", "1234567890abcde", false},
17
18 {"base64 - std encoding short high entropy", "QRSTU+vwxyz/123456", true},
19 {"base64 - url encoding short high entropy", "QRSTU_vwxyz-123456", true},
20 {"base64 - long high entropy", "dGhpcyBpcyBhIHRlc3QgZm9yIGhpZ2ggZW50cm9weSBiYXNlNjQgc2VjcmV0IGRldGVjdGlvbg==", true},
21
22 {"base64 - entropy exactly on threshold", "QRSTUvwxyz123456", false},
23 {"base64 - low entropy", "QRSTUvwxyz12345=", false},
24 {"base64 - too short", "dG9vX3Nob3J0IQ==", false},
25
26 {"number", "1234567890987654321", false},
27 {"illegal characters", "123456789=abcdef", false},
28 {"empty input", "", false},
29 }
30
31 var highEntropyStrDetector = NewHighEntropyStringDetector()
32
33 func TestHighEntropyStringDetector_Scan(t *testing.T) {
34 tests.TestScan(t, highEntropyStrDetector, highEntropyTestCases)
35 }
36
37 func TestHighEntropyStringDetector_ScanWithKey(t *testing.T) {
38 tests.TestScanWithKey(t, highEntropyStrDetector, highEntropyTestCases)
39 }
40
41 func TestHighEntropyStringDetector_ScanWithMultipleMatches(t *testing.T) {
42 tests.TestScanWithMultipleMatches(t, highEntropyStrDetector, highEntropyTestCases)
43 }
44
45 func TestHighEntropyStringDetector_ScanMap(t *testing.T) {
46 tests.TestScanMap(t, highEntropyStrDetector, highEntropyTestCases)
47 }
48
49 func TestCalcShannonEntropy(t *testing.T) {
50 tests := []struct {
51 name string
52 input string
53 expected float64
54 }{
55 {"all characters similar", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 0},
56 {"two characters equal frequency", "xxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyy", 1},
57 {"four characters equal frequency", "abcdabcdabcdabcdabcdabcdabcdabcd", 2},
58 {"eight characters equal frequency", "1234567887654321", 3},
59 {"16 characters equal frequency", "abc1234567890deffed0987654321cba", 4},
60 {"quarter-quarter-half frequencies", "xxyyzzzz", 1.5},
61 {"empty input", "", 0},
62 }
63 for _, test := range tests {
64 t.Run(test.name, func(t *testing.T) {
65 actual := CalcShannonEntropy(test.input)
66 assert.Equal(t, test.expected, actual)
67 })
68 }
69 }