Skip to content

Find, verify, and analyze leaked credentials

perf(engine): lowercase prefilter chunks as ASCII in a pooled buffer (#5291)

Kashif Khanb1d7dae8dbe4
diff --git a/pkg/engine/ahocorasick/README.md b/pkg/engine/ahocorasick/README.md
new file mode 100644
index 000000000..9ee462168
--- /dev/null
+++ b/pkg/engine/ahocorasick/README.md
@@ -0,0 +1,100 @@
+# ahocorasick
+
+This package decides **which detectors are worth running on a piece of data**.
+
+## Why it exists
+
+TruffleHog ships hundreds of detectors. Running every one against every chunk of
+scanned data would be far too slow, and almost always pointless: a file about
+billing has nothing to do with a Kubernetes token.
+
+So each detector declares a few keywords it cares about. A SendGrid key always
+contains `SG.`, so the SendGrid detector only needs to see chunks containing
+`SG.`. This package checks the whole keyword list in one pass and reports which
+detectors matched. Everything else is skipped.
+
+That check is a **prefilter**: a cheap test run before the expensive one.
+
+## How it works
+
+The [Aho-Corasick algorithm](https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm)
+searches for many words at once. Rather than scanning the text once per keyword,
+it builds a lookup structure from every keyword up front, then walks the text a
+single time. The cost barely changes whether there are ten keywords or ten
+thousand.
+
+`FindDetectorMatches` does the work:
+
+1. Make a lowercased copy of the chunk, so matching ignores case.
+2. Walk the copy once and collect every keyword hit.
+3. For each hit, work out a **span**: a window of bytes around it, cut from the
+ original chunk. Detectors get this window rather than the whole chunk, which
+ keeps their regexes fast. Some detectors ask for a wider window, for example
+ when a credential comes in two parts that may sit on separate lines.
+4. Return one entry per matching detector, with its spans merged.
+
+## Lowercasing only A-Z
+
+Step 1 lowercases `A-Z` by hand and leaves every other byte untouched, rather
+than using `bytes.ToLower`.
+
+The reason is step 3. Positions come from the lowercased copy, but the bytes are
+cut from the original chunk. That only lines up while both are the same length.
+
+Full Unicode lowercasing does not promise that. Some characters need a different
+number of bytes once lowercased — `İ` takes two bytes, `i` takes one. A single
+one of those makes the copy shorter, so every position after it points slightly
+too far back, and a detector is handed text that is not the text that matched.
+
+Changing only `A-Z` always keeps the same length, so positions stay correct.
+
+Keywords are folded through the same function when they are registered, so both
+sides of the search always agree.
+
+### Known limitation
+
+A cased non-ASCII letter is left exactly as written, on both sides. So a keyword
+containing one matches only text spelling that letter the same way: a keyword
+`CAFÉ` matches `CAFÉ` but not `café`.
+
+Every built-in detector keyword is plain ASCII, so this cannot affect them, and
+a test checks that assumption still holds. It only applies to a custom detector
+using a non-ASCII keyword.
+
+## The buffer pool
+
+Every chunk needs its own lowercased copy, and each copy is discarded moments
+later. Allocating a fresh one each time would mean throwing away a chunk-sized
+buffer on every call, for every chunk in a scan.
+
+Instead the copies come from `lowerBufPool`, a small pool of reusable buffers:
+
+- `getLowerBuf` borrows one, growing it only if the chunk does not fit.
+- `putLowerBuf` hands it back once the chunk is done with.
+
+In a steady scan the pool already holds a buffer large enough, so making the copy
+costs **no allocation at all**. Buffers larger than `maxPooledLowerBuf` are
+dropped rather than kept, so one unusually big chunk cannot leave a large buffer
+parked in the pool for the rest of the run.
+
+## What it costs
+
+`BenchmarkLowerBuf` compares borrowing a buffer from the pool against building a
+fresh lowercased copy each time. On an Apple M3 Pro:
+
+```
+BenchmarkLowerBuf/pooled-11 245199 4929 ns/op 1866.34 MB/s 0 B/op 0 allocs/op
+BenchmarkLowerBuf/unpooled-11 225938 5097 ns/op 1805.07 MB/s 9472 B/op 1 allocs/op
+```
+
+The time difference is small enough to be run-to-run noise. What the pool
+actually removes is the allocation: **9472 B and 1 allocation per chunk, down to
+zero**. That copy would otherwise be made and thrown away for every chunk in a
+scan, so the saving grows with the amount of data scanned rather than showing up
+on the clock here.
+
+Reproduce with:
+
+```sh
+go test ./pkg/engine/ahocorasick/ -bench=BenchmarkLowerBuf -benchmem
+```
diff --git a/pkg/engine/ahocorasick/ahocorasickcore.go b/pkg/engine/ahocorasick/ahocorasickcore.go
index 11a63b74e..932109589 100644
--- a/pkg/engine/ahocorasick/ahocorasickcore.go
+++ b/pkg/engine/ahocorasick/ahocorasickcore.go
@@ -1,8 +1,7 @@
package ahocorasick
import (
- "bytes"
- "strings"
+ "sync"
ahocorasick "github.com/BobuSumisu/aho-corasick"
@@ -11,6 +10,74 @@ import (
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb"
)
+// lowerBuf is a reusable buffer holding the lowercased copy of one chunk.
+//
+// Every chunk needs such a copy, and each one is thrown away moments later, so
+// rather than allocate a new buffer every time we borrow one from a pool and
+// hand it back afterwards. In a steady scan the pool already holds a buffer big
+// enough, so the copy costs no allocation at all.
+//
+// The pool stores pointers rather than plain slices. Putting a slice into a
+// sync.Pool would allocate on every Put, which is the very thing being avoided.
+type lowerBuf struct{ b []byte }
+
+var lowerBufPool = sync.Pool{New: func() any { return new(lowerBuf) }}
+
+// maxPooledLowerBuf is the largest buffer worth keeping for reuse.
+//
+// One unusually large chunk would otherwise leave a matching buffer sitting in
+// the pool for the rest of the run, once per worker goroutine. Past this size
+// it is cheaper to let the buffer go and allocate again next time.
+const maxPooledLowerBuf = 1 << 20 // 1 MiB
+
+// getLowerBuf borrows a buffer able to hold size bytes.
+func getLowerBuf(size int) *lowerBuf {
+ buf := lowerBufPool.Get().(*lowerBuf)
+ if cap(buf.b) < size {
+ buf.b = make([]byte, 0, size)
+ }
+ return buf
+}
+
+// putLowerBuf returns a buffer for reuse, unless it is too big to be worth
+// holding on to.
+func putLowerBuf(buf *lowerBuf) {
+ if cap(buf.b) > maxPooledLowerBuf {
+ return
+ }
+ buf.b = buf.b[:0]
+ lowerBufPool.Put(buf)
+}
+
+// appendASCIILower copies src onto dst, turning A-Z into a-z and leaving every
+// other byte exactly as it was.
+//
+// Only A-Z is changed, for two reasons.
+//
+// It keeps the copy the same length as the original. Lowercasing a character
+// can change how many bytes it takes: "İ" needs two bytes, "i" needs one.
+// FindDetectorMatches searches the lowercased copy but then cuts bytes out of
+// the original chunk, so if the copy were a different length every position
+// would point somewhere slightly wrong, and the text handed to a detector would
+// not be the text that matched.
+//
+// Nothing is lost by leaving other bytes alone. Every built-in detector keyword
+// is plain ASCII, so a non-ASCII byte can never be part of a match either way.
+//
+// Keywords are folded through this same function when they are registered, so
+// both sides of the search always agree. The one gap is a custom detector whose
+// keyword contains a cased non-ASCII letter: that letter is left as written on
+// both sides, so the keyword matches only text spelling it the same way.
+func appendASCIILower(dst, src []byte) []byte {
+ for _, c := range src {
+ if c >= 'A' && c <= 'Z' {
+ c += 'a' - 'A'
+ }
+ dst = append(dst, c)
+ }
+ return dst
+}
+
// DetectorKey is used to identify a detector in the keywordsToDetectors map.
// Multiple detectors can have the same detector type but different versions.
// This allows us to identify a detector by its type and version. An
@@ -146,9 +213,11 @@ func NewAhoCorasickCore(allDetectors []detectors.Detector, opts ...CoreOption) *
key := CreateDetectorKey(d)
detectorsByKey[key] = d
for _, kw := range d.Keywords() {
- kwLower := strings.ToLower(kw)
- keywords = append(keywords, kwLower)
- keywordsToDetectors[kwLower] = append(keywordsToDetectors[kwLower], key)
+ // Fold the keyword exactly the way FindDetectorMatches folds the
+ // chunk it searches, so the two sides can never disagree.
+ kwFolded := string(appendASCIILower(nil, []byte(kw)))
+ keywords = append(keywords, kwFolded)
+ keywordsToDetectors[kwFolded] = append(keywordsToDetectors[kwFolded], key)
}
}
@@ -239,7 +308,14 @@ func (d *DetectorMatch) Matches() [][]byte { return d.matches }
//
// The matches field contains the actual byte slices of the matched portions from the chunk data.
func (ac *Core) FindDetectorMatches(chunkData []byte) []*DetectorMatch {
- matches := ac.prefilter.Match(bytes.ToLower(chunkData))
+ // Search a lowercased copy so matching ignores case, but keep reporting
+ // positions against the original chunk, which is what the spans below cut
+ // from. The copy is borrowed and returned so it costs no allocation.
+ lowered := getLowerBuf(len(chunkData))
+ defer putLowerBuf(lowered)
+ lowered.b = appendASCIILower(lowered.b[:0], chunkData)
+
+ matches := ac.prefilter.Match(lowered.b)
matchCount := len(matches)
if matchCount == 0 {
diff --git a/pkg/engine/ahocorasick/ahocorasickcore_test.go b/pkg/engine/ahocorasick/ahocorasickcore_test.go
index 5828a846b..18080a598 100644
--- a/pkg/engine/ahocorasick/ahocorasickcore_test.go
+++ b/pkg/engine/ahocorasick/ahocorasickcore_test.go
@@ -1,13 +1,19 @@
package ahocorasick
import (
+ "bytes"
"context"
+ "strings"
+ "sync"
"testing"
+ "unicode/utf8"
"github.com/stretchr/testify/assert"
+ "pgregory.net/rapid"
"github.com/trufflesecurity/trufflehog/v3/pkg/custom_detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/engine/defaults"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb"
)
@@ -434,3 +440,265 @@ func TestFindDetectorMatches(t *testing.T) {
})
}
}
+
+// ---------------------------------------------------------------------------
+// Case folding
+//
+// FindDetectorMatches searches a lowercased copy of the chunk, then cuts spans
+// out of the original. That only works while the copy is the same length as
+// the original, which is why only A-Z is lowered.
+// ---------------------------------------------------------------------------
+
+// keywordDetector matches on one caller-chosen keyword.
+type keywordDetector struct{ keyword string }
+
+func (keywordDetector) FromData(context.Context, bool, []byte) ([]detectors.Result, error) {
+ return nil, nil
+}
+func (k keywordDetector) Keywords() []string { return []string{k.keyword} }
+func (keywordDetector) Type() detector_typepb.DetectorType {
+ return detector_typepb.DetectorType_Generic
+}
+func (keywordDetector) Description() string { return "" }
+
+func TestAppendASCIILower(t *testing.T) {
+ // Must agree with the standard library across the whole ASCII range.
+ var ascii []byte
+ for c := range 128 {
+ ascii = append(ascii, byte(c))
+ }
+ assert.Equal(t, bytes.ToLower(ascii), appendASCIILower(nil, ascii))
+
+ // Must never change length, unlike bytes.ToLower. Each of these shrinks
+ // when lowercased the normal way, which is what would move the spans.
+ for _, s := range []string{"İ", "ẞ", "İİİ", "prefix ẞ suffix"} {
+ assert.Len(t, appendASCIILower(nil, []byte(s)), len(s), "input %q", s)
+ assert.NotEqual(t, len(s), len(bytes.ToLower([]byte(s))),
+ "bytes.ToLower(%q) no longer changes length, so this case proves nothing", s)
+ }
+}
+
+func TestFindDetectorMatchesIsCaseInsensitive(t *testing.T) {
+ core := NewAhoCorasickCore([]detectors.Detector{keywordDetector{"sendgrid"}})
+ for _, chunk := range []string{"sendgrid", "SENDGRID", "SendGrid"} {
+ assert.Len(t, core.FindDetectorMatches([]byte(chunk)), 1, "chunk %q", chunk)
+ }
+}
+
+// Multi-byte characters before a keyword must not move the span off it.
+func TestFindDetectorMatchesSpansSurviveMultibyte(t *testing.T) {
+ const keyword = "sekrit"
+ core := NewAhoCorasickCore([]detectors.Detector{keywordDetector{keyword}})
+
+ // The run of "İ" is longer than the window the span calculator adds around
+ // a hit, otherwise the window would cover the keyword regardless and a
+ // wrong position would go unnoticed.
+ chunk := []byte(strings.Repeat("İ", 700) + " padding " + keyword + " trailing")
+
+ matches := core.FindDetectorMatches(chunk)
+ assert.Len(t, matches, 1)
+ for _, m := range matches[0].matches {
+ assert.Contains(t, string(m), keyword)
+ }
+}
+
+// Whatever surrounds a keyword, the span cut for it must stay inside the chunk
+// and must still cover the keyword that produced it.
+//
+// Positions come from the lowercased copy while the bytes are cut from the
+// original, so this holds only while folding preserves length. The generator
+// leans on characters where that is easy to get wrong: "İ" and "ẞ" both shrink
+// under full Unicode lowercasing, and the raw tail is arbitrary bytes that need
+// not be valid UTF-8.
+func TestFindDetectorMatchesSpanProperties(t *testing.T) {
+ const keyword = "token"
+ core := NewAhoCorasickCore([]detectors.Detector{keywordDetector{keyword}})
+
+ // Padding is built from long runs of one character rather than a random
+ // mix, so it reliably grows past the window the span calculator adds around
+ // a hit. A drifting position is only observable outside that window.
+ interesting := []rune{'a', 'Z', ' ', 'é', 'İ', 'ẞ', 'Κ', '密'}
+ padding := rapid.Custom(func(t *rapid.T) string {
+ var sb strings.Builder
+ for range rapid.IntRange(0, 3).Draw(t, "runs") {
+ sb.WriteString(strings.Repeat(
+ string(rapid.SampledFrom(interesting).Draw(t, "char")),
+ rapid.IntRange(0, 600).Draw(t, "runLength"),
+ ))
+ }
+ return sb.String()
+ })
+
+ rapid.Check(t, func(t *rapid.T) {
+ chunk := []byte(padding.Draw(t, "prefix") + keyword + padding.Draw(t, "suffix"))
+ chunk = append(chunk, rapid.SliceOf(rapid.Byte()).Draw(t, "tail")...)
+
+ matches := core.FindDetectorMatches(chunk)
+ if len(matches) != 1 {
+ t.Fatalf("keyword present but got %d detector matches", len(matches))
+ }
+
+ spans := matches[0].matchSpans
+ if len(spans) == 0 {
+ t.Fatal("detector matched but no spans were produced")
+ }
+ for _, span := range spans {
+ if span.startOffset < 0 || span.startOffset > span.endOffset ||
+ span.endOffset > int64(len(chunk)) {
+ t.Fatalf("span [%d,%d) outside chunk of %d bytes",
+ span.startOffset, span.endOffset, len(chunk))
+ }
+ // Every span comes from at least one hit, so slicing the original
+ // chunk with it must give back text containing the keyword.
+ text := string(chunk[span.startOffset:span.endOffset])
+ if !strings.Contains(strings.ToLower(text), keyword) {
+ t.Fatalf("span [%d,%d) does not cover the keyword",
+ span.startOffset, span.endOffset)
+ }
+ }
+ })
+}
+
+// A buffer coming back from the pool still holds the previous chunk's bytes,
+// so a later, shorter chunk must not be able to see them.
+func TestLowerBufPoolReuseIsClean(t *testing.T) {
+ core := NewAhoCorasickCore([]detectors.Detector{keywordDetector{"token"}})
+
+ long := []byte(strings.Repeat("x", 4096) + "token" + strings.Repeat("y", 4096))
+ assert.Len(t, core.FindDetectorMatches(long), 1)
+
+ short := []byte("token")
+ matches := core.FindDetectorMatches(short)
+ assert.Len(t, matches, 1)
+ for _, m := range matches[0].matchSpans {
+ assert.LessOrEqual(t, m.endOffset, int64(len(short)),
+ "leftover bytes from the previous chunk leaked through the pool")
+ }
+}
+
+// The pool is shared by every scanner worker.
+func TestFindDetectorMatchesConcurrent(t *testing.T) {
+ core := NewAhoCorasickCore([]detectors.Detector{keywordDetector{"token"}})
+ chunks := [][]byte{
+ []byte("token here"),
+ []byte(strings.Repeat("padding ", 500) + "token"),
+ []byte("İİİ token"),
+ }
+
+ var wg sync.WaitGroup
+ for range 8 {
+ wg.Go(func() {
+ for range 200 {
+ for _, c := range chunks {
+ for _, m := range core.FindDetectorMatches(c) {
+ for _, span := range m.matchSpans {
+ if span.endOffset > int64(len(c)) {
+ panic("span escaped the chunk")
+ }
+ }
+ }
+ }
+ }
+ })
+ }
+ wg.Wait()
+}
+
+// Lowering only A-Z is safe only while every keyword is ASCII, since a
+// non-ASCII byte then cannot be part of any match.
+func TestAllDefaultKeywordsAreASCII(t *testing.T) {
+ for _, d := range defaults.DefaultDetectors() {
+ for _, kw := range d.Keywords() {
+ for i := range len(kw) {
+ assert.Less(t, kw[i], byte(utf8.RuneSelf),
+ "%v keyword %q is not ASCII", d.Type(), kw)
+ }
+ }
+ }
+}
+
+// FuzzAppendASCIILower checks the two properties the spans rely on: the output
+// is always the same length as the input, and only A-Z changes.
+func FuzzAppendASCIILower(f *testing.F) {
+ for _, seed := range []string{"", "token", "TOKEN", "İ", "ẞ", "\x00\xff", "MiXeD 123"} {
+ f.Add([]byte(seed))
+ }
+ f.Fuzz(func(t *testing.T, src []byte) {
+ got := appendASCIILower(nil, src)
+ if len(got) != len(src) {
+ t.Fatalf("length changed: %d -> %d", len(src), len(got))
+ }
+ for i, c := range src {
+ want := c
+ if c >= 'A' && c <= 'Z' {
+ want = c + ('a' - 'A')
+ }
+ if got[i] != want {
+ t.Fatalf("byte %d: %q became %q, want %q", i, c, got[i], want)
+ }
+ }
+ })
+}
+
+// Keywords are folded the same way chunks are, so matching ignores ASCII case.
+// A cased non-ASCII letter is left as written on both sides, so it matches only
+// text spelling that letter the same way. Built-in keywords are all ASCII, so
+// this only ever affects a custom detector.
+func TestKeywordFoldingMatchesChunkFolding(t *testing.T) {
+ for _, tc := range []struct {
+ keyword string
+ matches []string
+ misses []string
+ }{
+ // ASCII folds fully, so every spelling matches.
+ {"TOKEN", []string{"token", "TOKEN", "Token"}, nil},
+ // The ASCII letters still fold; the "É" must be written as it was.
+ {"CAFÉ", []string{"CAFÉ", "cafÉ"}, []string{"café", "Café"}},
+ // Scripts without letter case are unaffected.
+ {"密钥", []string{"密钥"}, nil},
+ } {
+ core := NewAhoCorasickCore([]detectors.Detector{keywordDetector{tc.keyword}})
+ for _, chunk := range tc.matches {
+ assert.Len(t, core.FindDetectorMatches([]byte(chunk)), 1,
+ "keyword %q should match chunk %q", tc.keyword, chunk)
+ }
+ for _, chunk := range tc.misses {
+ assert.Empty(t, core.FindDetectorMatches([]byte(chunk)),
+ "keyword %q should not match chunk %q", tc.keyword, chunk)
+ }
+ }
+}
+
+// A keyword is registered under one spelling, so a single occurrence reports a
+// single match rather than one per spelling.
+func TestKeywordRegisteredOnce(t *testing.T) {
+ core := NewAhoCorasickCore([]detectors.Detector{keywordDetector{"token"}})
+ assert.Len(t, core.keywordsToDetectors["token"], 1)
+
+ matches := core.FindDetectorMatches([]byte("token"))
+ assert.Len(t, matches, 1)
+ assert.Len(t, matches[0].matchSpans, 1, "keyword counted twice")
+}
+
+// BenchmarkLowerBuf shows what the pool is for: borrowing a buffer costs no
+// allocation, while building a fresh lowercased copy allocates one per chunk.
+func BenchmarkLowerBuf(b *testing.B) {
+ data := []byte(strings.Repeat("The Quick Brown Fox Jumps Over A Sleeping Dog\n", 200))
+
+ b.Run("pooled", func(b *testing.B) {
+ b.ReportAllocs()
+ b.SetBytes(int64(len(data)))
+ for range b.N {
+ buf := getLowerBuf(len(data))
+ buf.b = appendASCIILower(buf.b[:0], data)
+ putLowerBuf(buf)
+ }
+ })
+ b.Run("unpooled", func(b *testing.B) {
+ b.ReportAllocs()
+ b.SetBytes(int64(len(data)))
+ for range b.N {
+ _ = appendASCIILower(make([]byte, 0, len(data)), data)
+ }
+ })
+}