fix(detect): handle EOF with bytes (#1472)

This commit is contained in:
Richard Gomez authored and GitHub committed 2024-08-19 14:00:47 -05:00
1 parent 8a1ca9ecc9
commit f361c5ef71
2 files changed
+77 -11

No files matched your search

+16 -11
View File
@@ -15,23 +15,28 @@ func (d *Detector) DetectReader(r io.Reader, bufSize int) ([]report.Finding, err
for {
n, err := reader.Read(buf[:cap(buf)])
buf = buf[:n]
// "Callers should always process the n > 0 bytes returned before considering the error err."
// https://pkg.go.dev/io#Reader
if n > 0 {
buf = buf[:n]
fragment := Fragment{
Raw: string(buf),
}
for _, finding := range d.Detect(fragment) {
findings = append(findings, finding)
if d.Verbose {
printFinding(finding, d.NoColor)
}
}
}
if err != nil {
if err != io.EOF {
return findings, err
}
break
}
fragment := Fragment{
Raw: string(buf),
}
for _, finding := range d.Detect(fragment) {
findings = append(findings, finding)
if d.Verbose {
printFinding(finding, d.NoColor)
}
}
}
return findings, nil
+61
View File
@@ -0,0 +1,61 @@
package detect
import (
"github.com/stretchr/testify/require"
"io"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
const secret = "AKIAIRYLJVKMPEXAMPLE"
type mockReader struct {
data []byte
}
func (r *mockReader) Read(p []byte) (n int, err error) {
// Copy data to the provided buffer.
n = copy(p, r.data)
// Return io.EOF along with the bytes.
return n, io.EOF
}
// TestDetectReader tests the DetectReader function.
func TestDetectReader(t *testing.T) {
tests := []struct {
name string
reader io.Reader
bufSize int
findingsCount int
}{
{
name: "Test case - Reader returns n > 0 bytes and nil error",
bufSize: 10,
findingsCount: 1,
reader: strings.NewReader(secret),
},
{
name: "Test case - Reader returns n > 0 bytes and io.EOF error",
bufSize: 10,
findingsCount: 1,
reader: &mockReader{
data: []byte(secret),
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
detector, err := NewDetectorDefaultConfig()
require.NoError(t, err)
findings, err := detector.DetectReader(test.reader, test.bufSize)
require.NoError(t, err)
assert.Equal(t, test.findingsCount, len(findings))
})
}
}