Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
🐛 fix(engine): map decoded results to source lines (#5219)
Bernát Gáborf51616494fc8
diff --git a/.gitignore b/.gitignoreindex 48d76df3f..afaf047df 100644--- a/.gitignore+++ b/.gitignore@@ -3,6 +3,9 @@ dist.env*.test+# rapid property test failure recordings, for local reproduction only+testdata/rapid/+# binarytrufflehogtmp/go-test.jsondiff --git a/pkg/engine/engine.go b/pkg/engine/engine.goindex dbdfe8135..de5c412e2 100644--- a/pkg/engine/engine.go+++ b/pkg/engine/engine.go@@ -1431,11 +1431,16 @@ func FragmentLineOffset(chunk *sources.Chunk, result *detectors.Result) (int64,}}- lineNumber := int64(bytes.Count(chunk.Data[:offset], []byte("\n")))+ data := chunk.Data+ if originalOffset := sourceOffset(chunk.OriginalData, chunk.Data, offset, len(secretBytes)); originalOffset >= 0 {+ data, offset = chunk.OriginalData, originalOffset+ }++ lineNumber := int64(bytes.Count(data[:offset], []byte("\n")))result.SetPrimarySecretLine(lineNumber)// If the line containing the secret has the ignore tag, we should ignore the result.- after := chunk.Data[offset+len(secretBytes):]+ after := data[offset+len(secretBytes):]endLine := bytes.Index(after, []byte("\n"))if endLine == -1 {endLine = len(after)@@ -1446,6 +1451,124 @@ func FragmentLineOffset(chunk *sources.Chunk, result *detectors.Result) (int64,return lineNumber, false}+// sourceOffset maps an offset in decoded data back onto the pre-decode buffer,+// returning -1 when the detected value has no counterpart in the source.+func sourceOffset(originalData, data []byte, offset, length int) int {+ if len(originalData) == 0 || length == 0 || offset < 0 || offset+length > len(data) {+ return -1+ }+ if bytes.Equal(originalData, data) {+ return offset+ }++ secret := data[offset : offset+length]+ preceding := bytes.Count(data[:offset], secret)+ sourceIndex, sourceCount := nthOccurrence(originalData, secret, preceding)+ if sourceCount == 0 {+ return -1+ }+ // Decoders emit the occurrences they keep in source order, so an unchanged+ // occurrence count makes the nth decoded match the nth source match.+ if sourceCount == preceding+bytes.Count(data[offset:], secret) {+ return sourceIndex+ }+ // Decoding dropped or merged occurrences, so order alone no longer identifies+ // the match and the surrounding text has to break the tie.+ return bestAlignedOccurrence(originalData, data, offset, length)+}++// nthOccurrence returns the offset of the nth zero-indexed non-overlapping+// occurrence of sep in data along with the total occurrence count. The offset is+// -1 when data holds fewer than n+1 occurrences.+func nthOccurrence(data, sep []byte, n int) (int, int) {+ index, count, start := -1, 0, 0+ for {+ next := bytes.Index(data[start:], sep)+ if next == -1 {+ return index, count+ }+ if count == n {+ index = start + next+ }+ count+++ start += next + len(sep)+ }+}++// alignedContextBytes bounds the neighbourhood each candidate source occurrence is+// scored over, keeping the comparison linear in the number of candidates. A kilobyte+// is far more context than a decoder needs to give itself away.+const alignedContextBytes = 1024++// bestAlignedOccurrence picks the source occurrence of the detected value whose+// neighbourhood best survives into the decoded neighbourhood. No rule is exact here:+// when a decoder drops one copy of a value and keeps another, the copies are only+// distinguishable by the text around them.+func bestAlignedOccurrence(originalData, data []byte, offset, length int) int {+ secret := data[offset : offset+length]+ best, bestScore := -1, -1+ for start := 0; ; {+ next := bytes.Index(originalData[start:], secret)+ if next == -1 {+ return best+ }+ candidate := start + next+ if score := alignmentScore(originalData, data, candidate, offset, length); score > bestScore {+ best, bestScore = candidate, score+ }+ start = candidate + length+ }+}++// alignmentScore measures how much of the decoded neighbourhood still reads, in+// order, out of the source around a candidate. Decoders interleave removals with the+// text they keep, so the source side is allowed gaps that the decoded side is not.+func alignmentScore(originalData, data []byte, candidate, offset, length int) int {+ sourceBefore := lastBytes(originalData[:candidate], alignedContextBytes)+ decodedBefore := lastBytes(data[:offset], alignedContextBytes)+ sourceAfter := firstBytes(originalData[candidate+length:], alignedContextBytes)+ decodedAfter := firstBytes(data[offset+length:], alignedContextBytes)+ return matchBackward(sourceBefore, decodedBefore) + matchForward(sourceAfter, decodedAfter)+}++// matchBackward returns the length of the longest suffix of decoded that appears as a+// subsequence of source. Matching greedily from the right is optimal for that.+func matchBackward(source, decoded []byte) int {+ matched, j := 0, len(decoded)-1+ for i := len(source) - 1; i >= 0 && j >= 0; i-- {+ if source[i] == decoded[j] {+ matched, j = matched+1, j-1+ }+ }+ return matched+}++// matchForward returns the length of the longest prefix of decoded that appears as a+// subsequence of source.+func matchForward(source, decoded []byte) int {+ matched := 0+ for i := 0; i < len(source) && matched < len(decoded); i++ {+ if source[i] == decoded[matched] {+ matched+++ }+ }+ return matched+}++func lastBytes(data []byte, n int) []byte {+ if len(data) > n {+ return data[len(data)-n:]+ }+ return data+}++func firstBytes(data []byte, n int) []byte {+ if len(data) > n {+ return data[:n]+ }+ return data+}+// AssignDuplicateLineOffsets pre-computes byte offsets for results that share the same// secret value within a chunk. This allows FragmentLineOffset to locate the correct// occurrence instead of always finding the first one.diff --git a/pkg/engine/engine_test.go b/pkg/engine/engine_test.goindex 3b4612985..236112264 100644--- a/pkg/engine/engine_test.go+++ b/pkg/engine/engine_test.go@@ -1,6 +1,7 @@package engineimport (+ "bytes"aCtx "context""fmt""math/rand"@@ -17,6 +18,7 @@ import ("github.com/stretchr/testify/assert""github.com/stretchr/testify/require""google.golang.org/protobuf/testing/protocmp"+ "pgregory.net/rapid""github.com/trufflesecurity/trufflehog/v3/pkg/config""github.com/trufflesecurity/trufflehog/v3/pkg/context"@@ -232,6 +234,205 @@ func TestFragmentLineOffsetWithPrimarySecretMultiline(t *testing.T) {assert.Equal(t, int64(2), lineOffset)}+// HTML-like tags can collapse source blank lines during decoding.+func TestFragmentLineOffsetUsesOriginalData(t *testing.T) {+ result := &detectors.Result{Raw: []byte("synthetic-secret-value-123456")}+ result.SetPrimarySecretValue(`token = "synthetic-secret-value-123456"`)+ chunk := &sources.Chunk{+ Data: []byte("# Date format:\n\ntoken = \"synthetic-secret-value-123456\""),+ OriginalData: []byte("# Date format: <yyyymmdd>\n\n\n\n\ntoken = \"synthetic-secret-value-123456\""),+ }++ lineOffset, _ := FragmentLineOffset(chunk, result)++ assert.Equal(t, int64(5), lineOffset)+}++// Some decoded secrets have no matching source byte sequence.+func TestFragmentLineOffsetFallsBackToDecodedData(t *testing.T) {+ result := &detectors.Result{Raw: []byte("synthetic-secret-value-123456")}+ chunk := &sources.Chunk{+ Data: []byte("decoded header\nsynthetic-secret-value-123456"),+ OriginalData: []byte("encoded-source-data"),+ }++ lineOffset, _ := FragmentLineOffset(chunk, result)++ assert.Equal(t, int64(1), lineOffset)+}++// Decoding can change the newline count between duplicate matches.+func TestFragmentLineOffsetMapsOriginalDataOccurrence(t *testing.T) {+ secret := []byte("synthetic-secret-value-123456")+ chunk := &sources.Chunk{+ Data: []byte("synthetic-secret-value-123456\nsynthetic-secret-value-123456"),+ OriginalData: []byte("synthetic-secret-value-123456\n\nsynthetic-secret-value-123456"),+ }+ results := []detectors.Result{{Raw: secret}, {Raw: secret}}+ AssignDuplicateLineOffsets(chunk, results)++ lineOffset, _ := FragmentLineOffset(chunk, &results[1])++ assert.Equal(t, int64(2), lineOffset)+}++// The same value can occur in discarded markup and emitted text, so surrounding+// text has to identify which source occurrence the decoder kept.+func TestFragmentLineOffsetSkipsRemovedOriginalDataOccurrence(t *testing.T) {+ secret := []byte("synthetic-secret-value-123456")+ chunk := &sources.Chunk{+ Data: []byte("heading\nsynthetic-secret-value-123456"),+ OriginalData: []byte("<div class=\"synthetic-secret-value-123456\">\n" ++ "<p>heading</p>\n<p>synthetic-secret-value-123456</p>"),+ }++ lineOffset, _ := FragmentLineOffset(chunk, &detectors.Result{Raw: secret})++ assert.Equal(t, int64(2), lineOffset)+}++// A dropped occurrence can sit after the surviving one, so a later source match is+// not automatically the right one.+func TestFragmentLineOffsetSkipsLaterRemovedOriginalDataOccurrence(t *testing.T) {+ secret := []byte("synthetic-secret-value-123456")+ chunk := &sources.Chunk{+ Data: []byte("heading\nsynthetic-secret-value-123456\ntrailer"),+ OriginalData: []byte("<p>heading</p>\n<p>synthetic-secret-value-123456</p>\n" ++ "<div class=\"synthetic-secret-value-123456\">trailer</div>"),+ }++ lineOffset, _ := FragmentLineOffset(chunk, &detectors.Result{Raw: secret})++ assert.Equal(t, int64(1), lineOffset)+}++// UTF-8 decoding replaces line breaks alongside malformed bytes.+func TestFragmentLineOffsetUsesInvalidOriginalData(t *testing.T) {+ secret := []byte("synthetic-secret-value-123456")+ originalData := append([]byte("heading\n\xff\n"), secret...)+ chunk := &sources.Chunk{+ Data: originalData,+ OriginalData: originalData,+ }+ require.NotNil(t, (&decoders.UTF8{}).FromChunk(chunk))++ lineOffset, _ := FragmentLineOffset(chunk, &detectors.Result{Raw: secret})++ assert.Equal(t, int64(2), lineOffset)+}++// Mapping must count bytes across multibyte UTF-8 before the secret.+func TestFragmentLineOffsetUsesUTF8OriginalData(t *testing.T) {+ secret := []byte("synthetic-secret-value-123456")+ chunk := &sources.Chunk{+ Data: append([]byte("préface\n"), secret...),+ OriginalData: append([]byte("préface\n\n"), secret...),+ }++ lineOffset, _ := FragmentLineOffset(chunk, &detectors.Result{Raw: secret})++ assert.Equal(t, int64(2), lineOffset)+}++// Replacement runes shift the decoded offset of the second match.+func TestFragmentLineOffsetMapsInvalidOriginalDataDuplicates(t *testing.T) {+ secret := []byte("synthetic-secret-value-123456")+ originalData := append([]byte("\xff\n"), secret...)+ originalData = append(originalData, '\n', 0xfe, '\n')+ originalData = append(originalData, secret...)+ chunk := &sources.Chunk{Data: originalData, OriginalData: originalData}+ require.NotNil(t, (&decoders.UTF8{}).FromChunk(chunk))+ results := []detectors.Result{{Raw: secret}, {Raw: secret}}+ AssignDuplicateLineOffsets(chunk, results)++ lineOffset, _ := FragmentLineOffset(chunk, &results[1])++ assert.Equal(t, int64(3), lineOffset)+}++// Source markup can retain an ignore tag absent from decoded data.+func TestFragmentLineOffsetUsesOriginalDataIgnoreTag(t *testing.T) {+ secret := []byte("synthetic-secret-value-123456")+ chunk := &sources.Chunk{+ Data: []byte("synthetic-secret-value-123456\ntext"),+ OriginalData: []byte("<p>synthetic-secret-value-123456</p>" ++ "<div class=\"trufflehog:ignore\">text</div>"),+ }++ _, ignored := FragmentLineOffset(chunk, &detectors.Result{Raw: secret})++ assert.True(t, ignored)+}++func buildDroppedSpanChunk(t *rapid.T, secret []byte, decoys bool) (*sources.Chunk, int) {+ spans := rapid.IntRange(1, 8).Draw(t, "spans")+ target := rapid.IntRange(0, spans-1).Draw(t, "target")++ var original, decoded []byte+ var secretOffset int+ for i := range spans {+ span := fmt.Appendf(nil, "<p id=%d>word%d\n</p>\n", i, i)+ dropped := i != target && rapid.Bool().Draw(t, fmt.Sprintf("dropped%d", i))+ if i == target {+ secretOffset = len(original) + len(span)+ }+ if i == target || (decoys && dropped && rapid.Bool().Draw(t, fmt.Sprintf("decoy%d", i))) {+ span = append(append(span, secret...), '\n')+ }+ original = append(original, span...)+ if !dropped {+ decoded = append(decoded, span...)+ }+ }+ return &sources.Chunk{Data: decoded, OriginalData: original}, secretOffset+}++// Decoders drop whole spans, and the value they keep still has to land on its own+// source line however much text went missing around it.+func TestFragmentLineOffsetMapsDroppedSourceSpans(t *testing.T) {+ secret := []byte("synthetic-secret-value-123456")+ rapid.Check(t, func(t *rapid.T) {+ chunk, secretOffset := buildDroppedSpanChunk(t, secret, false)++ lineOffset, _ := FragmentLineOffset(chunk, &detectors.Result{Raw: secret})++ assert.Equal(t, int64(bytes.Count(chunk.OriginalData[:secretOffset], []byte{'\n'})), lineOffset)+ })+}++// When a dropped span holds the same value as a kept one the copies are only+// distinguishable by their surroundings, so the exact line is best-effort. What is+// not negotiable is that the reported line holds the value in the source.+func TestFragmentLineOffsetReportsLineHoldingSecret(t *testing.T) {+ secret := []byte("synthetic-secret-value-123456")+ rapid.Check(t, func(t *rapid.T) {+ chunk, _ := buildDroppedSpanChunk(t, secret, true)++ lineOffset, _ := FragmentLineOffset(chunk, &detectors.Result{Raw: secret})++ lines := bytes.Split(chunk.OriginalData, []byte{'\n'})+ require.Less(t, int(lineOffset), len(lines))+ assert.Contains(t, string(lines[lineOffset]), string(secret))+ })+}++// Generated binary prefixes exercise byte values without requiring valid UTF-8.+func TestFragmentLineOffsetMapsArbitraryOriginalData(t *testing.T) {+ secret := []byte("synthetic-secret-value-123456")+ rapid.Check(t, func(t *rapid.T) {+ prefix := rapid.SliceOfN(rapid.Byte(), 0, 16).Draw(t, "prefix")+ removed := rapid.SliceOfN(rapid.Byte(), 1, 16).Draw(t, "removed")+ suffix := rapid.SliceOfN(rapid.Byte(), 0, 16).Draw(t, "suffix")+ data := append(append(append(bytes.Clone(prefix), secret...), suffix...), '\n')+ originalData := append(append(append(append(bytes.Clone(prefix), removed...), secret...), suffix...), '\n')+ chunk := &sources.Chunk{Data: data, OriginalData: originalData}++ lineOffset, _ := FragmentLineOffset(chunk, &detectors.Result{Raw: secret})++ assert.Equal(t, int64(bytes.Count(originalData[:len(prefix)+len(removed)], []byte{'\n'})), lineOffset)+ })+}+// TestFragmentLineOffset_DuplicateSecrets verifies that when the same secret// appears on multiple lines within a chunk, each result receives the correct// line number rather than always reporting the first occurrence's line.@@ -2116,3 +2317,85 @@ func TestNotifierWorker_ReverifiedResultsBypassDedupe(t *testing.T) {})}}++func setupSourceMappingBench(size int, decode bool) (*sources.Chunk, *detectors.Result) {+ secret := []byte("synthetic-secret-value-123456")+ var original, decoded []byte+ for i := 0; len(original) < size; i++ {+ original = append(original, fmt.Sprintf("<p class=\"row\">line%d</p>\n", i)...)+ decoded = append(decoded, fmt.Sprintf("line%d\n", i)...)+ }+ original = append(original, "<p>"...)+ original = append(original, secret...)+ original = append(original, "</p>\n"...)+ decoded = append(decoded, secret...)+ decoded = append(decoded, '\n')+ if !decode {+ decoded = original+ }+ return &sources.Chunk{Data: decoded, OriginalData: original}, &detectors.Result{Raw: secret}+}++func benchmarkSourceMapping(b *testing.B, size int, decode bool) {+ chunk, result := setupSourceMappingBench(size, decode)+ b.ReportAllocs()+ b.ResetTimer()+ for i := 0; i < b.N; i++ {+ _, _ = FragmentLineOffset(chunk, result)+ }+}++func BenchmarkFragmentLineOffset_Identical_Small(b *testing.B) {+ benchmarkSourceMapping(b, 64, false)+}++func BenchmarkFragmentLineOffset_Identical_DefaultChunkSize(b *testing.B) {+ benchmarkSourceMapping(b, sources.DefaultChunkSize, false)+}++func BenchmarkFragmentLineOffset_Identical_Large(b *testing.B) {+ benchmarkSourceMapping(b, 64*1024, false)+}++func BenchmarkFragmentLineOffset_Diffed_Small(b *testing.B) {+ benchmarkSourceMapping(b, 64, true)+}++func BenchmarkFragmentLineOffset_Diffed_DefaultChunkSize(b *testing.B) {+ benchmarkSourceMapping(b, sources.DefaultChunkSize, true)+}++func BenchmarkFragmentLineOffset_Diffed_MaxRealisticChunk(b *testing.B) {+ benchmarkSourceMapping(b, sources.TotalChunkSize, true)+}++func BenchmarkFragmentLineOffset_Diffed_Large(b *testing.B) {+ benchmarkSourceMapping(b, 64*1024, true)+}++func setupAmbiguousSourceBench(size int) (*sources.Chunk, *detectors.Result) {+ secret := []byte("synthetic-secret-value-123456")+ original := []byte("<div class=\"synthetic-secret-value-123456\">\n")+ var decoded []byte+ for i := 0; len(original) < size; i++ {+ original = append(original, fmt.Sprintf("<p class=\"row\">line%d</p>\n", i)...)+ decoded = append(decoded, fmt.Sprintf("line%d\n", i)...)+ }+ original = append(original, "<p>"...)+ original = append(original, secret...)+ original = append(original, "</p>\n"...)+ decoded = append(decoded, secret...)+ decoded = append(decoded, '\n')+ return &sources.Chunk{Data: decoded, OriginalData: original}, &detectors.Result{Raw: secret}+}++// The same value occurs in both discarded markup and emitted text, so the source+// occurrence has to be picked by its surroundings.+func BenchmarkFragmentLineOffset_Ambiguous_DefaultChunkSize(b *testing.B) {+ chunk, result := setupAmbiguousSourceBench(sources.DefaultChunkSize)+ b.ReportAllocs()+ b.ResetTimer()+ for i := 0; i < b.N; i++ {+ _, _ = FragmentLineOffset(chunk, result)+ }+}