Skip to content

Commit

Permalink
Recover general chunker panics (#3625)
Browse files Browse the repository at this point in the history
We have recently seen panics when underlying readers panic (which can happen due to third-party library bugs). I'm not sure why the panics are new - it could be a case of bad luck, but there have also been recent changes to error handling. This is the smallest change that seems to fix a real problem but I'm not sure if it's the best global solution.
  • Loading branch information
rosecodym authored Nov 21, 2024
1 parent e494eaf commit 098072b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pkg/sources/chunker.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package sources
import (
"bufio"
"errors"
"fmt"
"io"

"github.com/trufflesecurity/trufflehog/v3/pkg/context"
Expand Down Expand Up @@ -99,6 +100,22 @@ func readInChunks(ctx context.Context, reader io.Reader, config *chunkReaderConf
go func() {
defer close(chunkResultChan)

// Defer a panic recovery to handle any panics that occur while reading, which can sometimes unavoidably happen
// due to third-party library bugs.
defer func() {
if r := recover(); r != nil {
var panicErr error
if e, ok := r.(error); ok {
panicErr = e
} else {
panicErr = fmt.Errorf("panic occurred: %v", r)
}
chunkResultChan <- ChunkResult{
err: fmt.Errorf("panic error: %w", panicErr),
}
}
}()

for {
chunkRes := ChunkResult{}
chunkBytes := make([]byte, config.totalSize)
Expand Down
17 changes: 17 additions & 0 deletions pkg/sources/chunker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package sources

import (
"bytes"
"io"
"math/rand"
"runtime"
"strings"
Expand All @@ -10,6 +11,7 @@ import (
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/trufflesecurity/trufflehog/v3/pkg/context"
)
Expand Down Expand Up @@ -121,6 +123,21 @@ func TestNewChunkedReader(t *testing.T) {
}
}

type panicReader struct{}

var _ io.Reader = (*panicReader)(nil)

func (_ panicReader) Read([]byte) (int, error) {
panic("panic for testing")
}

func TestChunkReader_UnderlyingReaderPanics_DoesNotPanic(t *testing.T) {
require.NotPanics(t, func() {
for range NewChunkReader()(context.Background(), &panicReader{}) {
}
})
}

func BenchmarkChunkReader(b *testing.B) {
var bigChunk = make([]byte, 1<<24) // 16MB

Expand Down

0 comments on commit 098072b

Please sign in to comment.