Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
[refactor] - lazy buffer retrieval (#2745)
ahravb430dae83e28
diff --git a/pkg/gitparse/gitparse.go b/pkg/gitparse/gitparse.goindex 7a0187466..94d3fb80f 100644--- a/pkg/gitparse/gitparse.go+++ b/pkg/gitparse/gitparse.go@@ -76,14 +76,14 @@ func withCustomContentWriter(cr contentWriter) diffOption {// All Diffs must have an associated commit.// The contentWriter is used to manage the diff's content, allowing for flexible handling of diff data.// By default, a buffer is used as the contentWriter, but this can be overridden with a custom contentWriter.-func newDiff(ctx context.Context, commit *Commit, opts ...diffOption) *Diff {+func newDiff(commit *Commit, opts ...diffOption) *Diff {diff := &Diff{Commit: commit}for _, opt := range opts {opt(diff)}if diff.contentWriter == nil {- diff.contentWriter = bufferwriter.New(ctx)+ diff.contentWriter = bufferwriter.New()}return diff@@ -104,9 +104,7 @@ func (d *Diff) write(p []byte) error {// finalize ensures proper closure of resources associated with the Diff.// handle the final flush in the finalize method, in case there's data remaining in the buffer.// This method should be called to release resources, especially when writing to a file.-func (d *Diff) finalize() error {- return d.contentWriter.CloseForWriting()-}+func (d *Diff) finalize() error { return d.contentWriter.CloseForWriting() }// Commit contains commit header info and diffs.type Commit struct {@@ -312,13 +310,13 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, diffChan chanvar latestState = Initialdiff := func(c *Commit, opts ...diffOption) *Diff {- opts = append(opts, withCustomContentWriter(bufferwriter.New(ctx)))- return newDiff(ctx, c, opts...)+ opts = append(opts, withCustomContentWriter(bufferwriter.New()))+ return newDiff(c, opts...)}if c.useCustomContentWriter {diff = func(c *Commit, opts ...diffOption) *Diff {- opts = append(opts, withCustomContentWriter(bufferedfilewriter.New(ctx)))- return newDiff(ctx, c, opts...)+ opts = append(opts, withCustomContentWriter(bufferedfilewriter.New()))+ return newDiff(c, opts...)}}currentDiff := diff(currentCommit)diff --git a/pkg/gitparse/gitparse_test.go b/pkg/gitparse/gitparse_test.goindex 0b86bc366..00f15e1cb 100644--- a/pkg/gitparse/gitparse_test.go+++ b/pkg/gitparse/gitparse_test.go@@ -633,6 +633,11 @@ func TestToFileLinePathParse(t *testing.T) {func (d1 *Diff) Equal(ctx context.Context, d2 *Diff) bool {// isEqualString handles the error-prone String() method calls and compares the results.isEqualContentString := func(s1, s2 contentWriter) (bool, error) {+ // If the content is nil, it's likely a binary so there won't be any content to compare.+ if s1.Len() == 0 && s2.Len() == 0 {+ return true, nil+ }+str1, err := s1.String()if err != nil {return false, err@@ -695,8 +700,7 @@ func TestCommitParsing(t *testing.T) {}func newBufferedFileWriterWithContent(content []byte) *bufferedfilewriter.BufferedFileWriter {- ctx := context.Background()- b := bufferedfilewriter.New(ctx)+ b := bufferedfilewriter.New()_, err := b.Write(content) // Using Write method to add contentif err != nil {panic(err)@@ -705,8 +709,7 @@ func newBufferedFileWriterWithContent(content []byte) *bufferedfilewriter.Buffer}func newBufferWithContent(content []byte) *bufferwriter.BufferWriter {- ctx := context.Background()- b := bufferwriter.New(ctx)+ b := bufferwriter.New()_, _ = b.Write(content) // Using Write method to add contentreturn b}@@ -2388,13 +2391,12 @@ func TestNewDiffContentWriterCreation(t *testing.T) {t.Run(tc.name, func(t *testing.T) {t.Parallel()- ctx := context.Background()commit := new(Commit)mockWriter := newMockContentWriter()assert.NotNil(t, mockWriter, "Failed to create mockWriter")- diff := newDiff(ctx, commit, tc.opts...)+ diff := newDiff(commit, tc.opts...)assert.NotNil(t, diff, "Failed to create diff")assert.NotNil(t, diff.contentWriter, "Failed to create contentWriter")diff --git a/pkg/writers/buffer/buffer.go b/pkg/writers/buffer/buffer.goindex fd04237db..b28b47bfa 100644--- a/pkg/writers/buffer/buffer.go+++ b/pkg/writers/buffer/buffer.go@@ -4,11 +4,8 @@ package bufferimport ("bytes"- "fmt""sync""time"-- "github.com/trufflesecurity/trufflehog/v3/pkg/context")type poolMetrics struct{}@@ -60,10 +57,9 @@ func NewBufferPool(opts ...PoolOpts) *Pool {}// Get returns a Buffer from the pool.-func (p *Pool) Get(ctx context.Context) *Buffer {+func (p *Pool) Get() *Buffer {buf, ok := p.Pool.Get().(*Buffer)if !ok {- ctx.Logger().Error(fmt.Errorf("Buffer pool returned unexpected type"), "using new Buffer")buf = &Buffer{Buffer: bytes.NewBuffer(make([]byte, 0, p.bufferSize))}}p.metrics.recordBufferRetrival()diff --git a/pkg/writers/buffer/buffer_test.go b/pkg/writers/buffer/buffer_test.goindex 3a690da32..714f387af 100644--- a/pkg/writers/buffer/buffer_test.go+++ b/pkg/writers/buffer/buffer_test.go@@ -5,8 +5,6 @@ import ("testing""github.com/stretchr/testify/assert"-- "github.com/trufflesecurity/trufflehog/v3/pkg/context")func TestNewBufferPool(t *testing.T) {@@ -71,12 +69,12 @@ func TestBufferPoolGetPut(t *testing.T) {pool.Put(initialBuf)}- buf := pool.Get(context.Background())+ buf := pool.Get()assert.Equal(t, tc.expectedCapBefore, buf.Cap())pool.Put(buf)- bufAfter := pool.Get(context.Background())+ bufAfter := pool.Get()assert.Equal(t, tc.expectedCapAfter, bufAfter.Cap())})}diff --git a/pkg/writers/buffer_writer/bufferwriter.go b/pkg/writers/buffer_writer/bufferwriter.goindex c9ffa2b26..6a564f4de 100644--- a/pkg/writers/buffer_writer/bufferwriter.go+++ b/pkg/writers/buffer_writer/bufferwriter.go@@ -6,7 +6,6 @@ import ("io""time"- "github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/writers/buffer")@@ -44,13 +43,7 @@ type BufferWriter struct {}// New creates a new instance of BufferWriter.-func New(ctx context.Context) *BufferWriter {- buf := bufferPool.Get(ctx)- if buf == nil {- buf = buffer.NewBuffer()- }- return &BufferWriter{buf: buf, state: writeOnly, bufPool: bufferPool}-}+func New() *BufferWriter { return &BufferWriter{state: writeOnly, bufPool: bufferPool} }// Write delegates the writing operation to the underlying bytes.Buffer.func (b *BufferWriter) Write(data []byte) (int, error) {@@ -58,6 +51,13 @@ func (b *BufferWriter) Write(data []byte) (int, error) {return 0, fmt.Errorf("buffer must be in write-only mode to write data; current state: %d", b.state)}+ if b.buf == nil {+ b.buf = b.bufPool.Get()+ if b.buf == nil {+ b.buf = buffer.NewBuffer()+ }+ }+size := len(data)b.size += sizestart := time.Now()@@ -76,6 +76,9 @@ func (b *BufferWriter) ReadCloser() (io.ReadCloser, error) {if b.state != readOnly {return nil, fmt.Errorf("buffer is in read-only mode")}+ if b.buf == nil {+ return nil, fmt.Errorf("writer buffer is nil")+ }return buffer.ReadCloser(b.buf.Bytes(), func() { b.bufPool.Put(b.buf) }), nil}diff --git a/pkg/writers/buffer_writer/bufferwriter_test.go b/pkg/writers/buffer_writer/bufferwriter_test.goindex a992490a1..fd6ce69aa 100644--- a/pkg/writers/buffer_writer/bufferwriter_test.go+++ b/pkg/writers/buffer_writer/bufferwriter_test.go@@ -4,8 +4,6 @@ import ("testing""github.com/stretchr/testify/assert"-- "github.com/trufflesecurity/trufflehog/v3/pkg/context")func TestBufferWriterWrite(t *testing.T) {@@ -41,7 +39,7 @@ func TestBufferWriterWrite(t *testing.T) {tc := tct.Run(tc.name, func(t *testing.T) {t.Parallel()- writer := New(context.Background())+ writer := New()writer.state = tc.initialState_, err := writer.Write(tc.input)@@ -77,8 +75,9 @@ func TestBufferWriterReadCloser(t *testing.T) {tc := tct.Run(tc.name, func(t *testing.T) {t.Parallel()- writer := New(context.Background())+ writer := New()writer.state = tc.initialState+ writer.buf = writer.bufPool.Get()rc, err := writer.ReadCloser()if tc.expectedError {@@ -96,7 +95,7 @@ func TestBufferWriterReadCloser(t *testing.T) {}func TestBufferWriterCloseForWriting(t *testing.T) {- writer := New(context.Background())+ writer := New()err := writer.CloseForWriting()assert.NoError(t, err)assert.Equal(t, readOnly, writer.state)@@ -112,8 +111,8 @@ func TestBufferWriterString(t *testing.T) {}{{name: "String with no data",- prepareBuffer: func(_ *BufferWriter) {- // No preparation needed, buffer is empty by default+ prepareBuffer: func(bw *BufferWriter) {+ _, _ = bw.Write([]byte(""))},expectedStr: "",expectedError: false,@@ -140,7 +139,7 @@ func TestBufferWriterString(t *testing.T) {tc := tct.Run(tc.name, func(t *testing.T) {t.Parallel()- writer := New(context.Background())+ writer := New()tc.prepareBuffer(writer)result, err := writer.String()diff --git a/pkg/writers/buffered_file_writer/bufferedfilewriter.go b/pkg/writers/buffered_file_writer/bufferedfilewriter.goindex 9908dde20..7ca0ce242 100644--- a/pkg/writers/buffered_file_writer/bufferedfilewriter.go+++ b/pkg/writers/buffered_file_writer/bufferedfilewriter.go@@ -10,7 +10,6 @@ import ("time""github.com/trufflesecurity/trufflehog/v3/pkg/cleantemp"- "github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/writers/buffer")@@ -72,15 +71,10 @@ func WithThreshold(threshold uint64) Option {const defaultThreshold = 10 * 1024 * 1024 // 10MB// New creates a new BufferedFileWriter with the given options.-func New(ctx context.Context, opts ...Option) *BufferedFileWriter {- buf := sharedBufferPool.Get(ctx)- if buf == nil {- buf = buffer.NewBuffer()- }+func New(opts ...Option) *BufferedFileWriter {w := &BufferedFileWriter{threshold: defaultThreshold,state: writeOnly,- buf: buf,bufPool: sharedBufferPool,}for _, opt := range opts {@@ -126,6 +120,13 @@ func (w *BufferedFileWriter) Write(data []byte) (int, error) {return 0, fmt.Errorf("BufferedFileWriter must be in write-only mode to write")}+ if w.buf == nil {+ w.buf = w.bufPool.Get()+ if w.buf == nil {+ w.buf = buffer.NewBuffer()+ }+ }+size := uint64(len(data))bufferLength := w.buf.Len()start := time.Now()@@ -212,6 +213,10 @@ func (w *BufferedFileWriter) ReadCloser() (io.ReadCloser, error) {return newAutoDeletingFileReader(file), nil}+ if w.buf == nil {+ return nil, fmt.Errorf("BufferedFileWriter has not buffer data to read")+ }+// Data is in memory.return buffer.ReadCloser(w.buf.Bytes(), func() { w.bufPool.Put(w.buf) }), nil}diff --git a/pkg/writers/buffered_file_writer/bufferedfilewriter_test.go b/pkg/writers/buffered_file_writer/bufferedfilewriter_test.goindex d79306fd6..35bcdcd69 100644--- a/pkg/writers/buffered_file_writer/bufferedfilewriter_test.go+++ b/pkg/writers/buffered_file_writer/bufferedfilewriter_test.go@@ -8,7 +8,6 @@ import ("github.com/stretchr/testify/assert"- "github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/writers/buffer")@@ -33,7 +32,7 @@ func TestBufferedFileWriterNewThreshold(t *testing.T) {tc := tct.Run(tc.name, func(t *testing.T) {t.Parallel()- writer := New(context.Background(), tc.options...)+ writer := New(tc.options...)assert.Equal(t, tc.expectedThreshold, writer.threshold)// The state should always be writeOnly when created.assert.Equal(t, writeOnly, writer.state)@@ -77,8 +76,7 @@ func TestBufferedFileWriterString(t *testing.T) {tc := tct.Run(tc.name, func(t *testing.T) {t.Parallel()- ctx := context.Background()- writer := New(ctx, WithThreshold(tc.threshold))+ writer := New(WithThreshold(tc.threshold))// First write, should go to file if it exceeds the threshold._, err := writer.Write(tc.input)assert.NoError(t, err)@@ -109,8 +107,7 @@ const (func BenchmarkBufferedFileWriterString_BufferOnly_Small(b *testing.B) {data := bytes.Repeat([]byte("a"), smallBuffer)- ctx := context.Background()- writer := New(ctx)+ writer := New()_, err := writer.Write(data)assert.NoError(b, err)@@ -127,8 +124,7 @@ func BenchmarkBufferedFileWriterString_BufferOnly_Small(b *testing.B) {func BenchmarkBufferedFileWriterString_BufferOnly_Medium(b *testing.B) {data := bytes.Repeat([]byte("a"), mediumBuffer)- ctx := context.Background()- writer := New(ctx)+ writer := New()_, err := writer.Write(data)assert.NoError(b, err)@@ -146,8 +142,7 @@ func BenchmarkBufferedFileWriterString_BufferOnly_Medium(b *testing.B) {func BenchmarkBufferedFileWriterString_OnlyFile_Small(b *testing.B) {data := bytes.Repeat([]byte("a"), smallFile)- ctx := context.Background()- writer := New(ctx)+ writer := New()_, err := writer.Write(data)assert.NoError(b, err)@@ -165,8 +160,7 @@ func BenchmarkBufferedFileWriterString_OnlyFile_Small(b *testing.B) {func BenchmarkBufferedFileWriterString_OnlyFile_Medium(b *testing.B) {data := bytes.Repeat([]byte("a"), mediumFile)- ctx := context.Background()- writer := New(ctx)+ writer := New()_, err := writer.Write(data)assert.NoError(b, err)@@ -184,8 +178,7 @@ func BenchmarkBufferedFileWriterString_OnlyFile_Medium(b *testing.B) {func BenchmarkBufferedFileWriterString_BufferWithFile_Small(b *testing.B) {data := bytes.Repeat([]byte("a"), smallFile)- ctx := context.Background()- writer := New(ctx)+ writer := New()_, err := writer.Write(data)assert.NoError(b, err)@@ -207,8 +200,7 @@ func BenchmarkBufferedFileWriterString_BufferWithFile_Small(b *testing.B) {func BenchmarkBufferedFileWriterString_BufferWithFile_Medium(b *testing.B) {data := bytes.Repeat([]byte("a"), mediumFile)- ctx := context.Background()- writer := New(ctx)+ writer := New()_, err := writer.Write(data)assert.NoError(b, err)@@ -253,7 +245,7 @@ func TestBufferedFileWriterLen(t *testing.T) {tc := tct.Run(tc.name, func(t *testing.T) {t.Parallel()- writer := New(context.Background())+ writer := New()_, err := writer.Write(tc.input)assert.NoError(t, err)@@ -268,10 +260,9 @@ func TestBufferedFileWriterLen(t *testing.T) {func TestBufferedFileWriterWriteWithinThreshold(t *testing.T) {t.Parallel()- ctx := context.Background()data := []byte("hello world")- writer := New(ctx, WithThreshold(64))+ writer := New(WithThreshold(64))_, err := writer.Write(data)assert.NoError(t, err)@@ -283,10 +274,9 @@ func TestBufferedFileWriterWriteWithinThreshold(t *testing.T) {func TestBufferedFileWriterWriteExceedsThreshold(t *testing.T) {t.Parallel()- ctx := context.Background()data := []byte("hello world")- writer := New(ctx, WithThreshold(5))+ writer := New(WithThreshold(5))_, err := writer.Write(data)assert.NoError(t, err)@@ -307,12 +297,11 @@ func TestBufferedFileWriterWriteExceedsThreshold(t *testing.T) {func TestBufferedFileWriterWriteAfterFlush(t *testing.T) {t.Parallel()- ctx := context.Background()initialData := []byte("initial data is longer than subsequent data")subsequentData := []byte("subsequent data")// Initialize writer with a threshold that initialData will exceed.- writer := New(ctx, WithThreshold(uint64(len(initialData)-1)))+ writer := New(WithThreshold(uint64(len(initialData) - 1)))_, err := writer.Write(initialData)assert.NoError(t, err)@@ -352,7 +341,6 @@ func TestBufferedFileWriterClose(t *testing.T) {t.Parallel()const threshold = 10- ctx := context.Background()tests := []struct {name string@@ -399,7 +387,7 @@ func TestBufferedFileWriterClose(t *testing.T) {tc := tct.Run(tc.name, func(t *testing.T) {t.Parallel()- writer := New(ctx, WithThreshold(threshold))+ writer := New(WithThreshold(threshold))tc.prepareWriter(writer)@@ -421,7 +409,7 @@ func TestBufferedFileWriterClose(t *testing.T) {func TestBufferedFileWriterStateTransitionOnClose(t *testing.T) {t.Parallel()- writer := New(context.Background())+ writer := New()// Initially, the writer should be in write-only mode.assert.Equal(t, writeOnly, writer.state)@@ -440,7 +428,7 @@ func TestBufferedFileWriterStateTransitionOnClose(t *testing.T) {func TestBufferedFileWriterWriteInReadOnlyState(t *testing.T) {t.Parallel()- writer := New(context.Background())+ writer := New()_ = writer.CloseForWriting() // Transition to read-only mode// Attempt to write in read-only mode.@@ -449,7 +437,6 @@ func TestBufferedFileWriterWriteInReadOnlyState(t *testing.T) {}func BenchmarkBufferedFileWriterWriteLarge(b *testing.B) {- ctx := context.Background()data := make([]byte, 1024*1024*10) // 10MBfor i := range data {data[i] = byte(i % 256) // Simple pattern to avoid uniform zero data@@ -459,7 +446,7 @@ func BenchmarkBufferedFileWriterWriteLarge(b *testing.B) {for i := 0; i < b.N; i++ {// Threshold is smaller than the data size, data should get flushed to the file.- writer := New(ctx, WithThreshold(1024))+ writer := New(WithThreshold(1024))b.StartTimer(){@@ -479,7 +466,6 @@ func BenchmarkBufferedFileWriterWriteLarge(b *testing.B) {}func BenchmarkBufferedFileWriterWriteSmall(b *testing.B) {- ctx := context.Background()data := make([]byte, 1024*1024) // 1MBfor i := range data {data[i] = byte(i % 256) // Simple pattern to avoid uniform zero data@@ -489,7 +475,7 @@ func BenchmarkBufferedFileWriterWriteSmall(b *testing.B) {for i := 0; i < b.N; i++ {// Threshold is the same as the buffer size, data should always be written to the buffer.- writer := New(ctx, WithThreshold(1024*1024))+ writer := New(WithThreshold(1024 * 1024))b.StartTimer(){@@ -511,8 +497,7 @@ func BenchmarkBufferedFileWriterWriteSmall(b *testing.B) {func TestBufferWriterCloseForWritingWithFile(t *testing.T) {bufPool := buffer.NewBufferPool()- ctx := context.Background()- buf := bufPool.Get(ctx)+ buf := bufPool.Get()writer := &BufferedFileWriter{threshold: 10,bufPool: bufPool,@@ -533,7 +518,7 @@ func TestBufferWriterCloseForWritingWithFile(t *testing.T) {defer rdr.Close()// Get a buffer from the pool and check if it is the same buffer used in the writer.- bufFromPool := bufPool.Get(ctx)+ bufFromPool := bufPool.Get()assert.Same(t, buf, bufFromPool, "Buffer should be returned to the pool")bufPool.Put(bufFromPool)}