Skip to content

Commit 1207366

Browse files
committed
capped_file: increase test coverage, fix out-of-bounds check
1 parent 5ae2878 commit 1207366

2 files changed

Lines changed: 35 additions & 2 deletions

File tree

capped_file.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ func (cf *cappedFile) WriteAt(data []byte, off int64) (n int, err error) {
6464
totalLength = len(data)
6565
fileNum = offset / cf.cap
6666
)
67-
if fileNum >= uint64(len(cf.files)) {
67+
// Check if the write starts or ends out of bounds
68+
if fileNum >= uint64(len(cf.files)) ||
69+
(offset+uint64(len(data)))/cf.cap >= uint64(len(cf.files)) {
6870
return 0, ErrBadIndex
6971
}
7072
for ; written < totalLength; fileNum++ {
@@ -98,7 +100,9 @@ func (cf *cappedFile) ReadAt(b []byte, off int64) (n int, err error) {
98100
read int // no of bytes read
99101
fileNum = offset / cf.cap
100102
)
101-
if fileNum >= uint64(len(cf.files)) {
103+
// Check if the read starts or ends out of bounds
104+
if fileNum >= uint64(len(cf.files)) ||
105+
(offset+uint64(len(b)))/cf.cap >= uint64(len(cf.files)) {
102106
return 0, ErrBadIndex
103107
}
104108
for ; read < len(b); fileNum++ {

capped_file_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package billy
66

77
import (
88
"bytes"
9+
"errors"
910
"os"
1011
"testing"
1112
)
@@ -132,3 +133,31 @@ func TestReadonly(t *testing.T) {
132133
t.Fatalf("want error trying to write files in readonly, got none")
133134
}
134135
}
136+
137+
func TestOutOfBounds(t *testing.T) {
138+
f, err := newCappedFile("multifile-ro-test", 10, 50, false)
139+
if err != nil {
140+
t.Fatal(err)
141+
}
142+
t.Cleanup(func() {
143+
f.Close()
144+
wipe(t, f)
145+
})
146+
// Read starting OOB
147+
if _, err := f.ReadAt(make([]byte, 10), 501); !errors.Is(err, ErrBadIndex) {
148+
t.Fatalf("want %v have %v", ErrBadIndex, err)
149+
}
150+
// Read reaching into OOB
151+
if _, err := f.ReadAt(make([]byte, 10), 495); !errors.Is(err, ErrBadIndex) {
152+
t.Fatalf("want %v have %v", ErrBadIndex, err)
153+
}
154+
// Write starting OOB
155+
if _, err := f.WriteAt(make([]byte, 10), 501); !errors.Is(err, ErrBadIndex) {
156+
t.Fatalf("want %v have %v", ErrBadIndex, err)
157+
}
158+
// Write reaching into OOB
159+
if _, err := f.WriteAt(make([]byte, 10), 495); !errors.Is(err, ErrBadIndex) {
160+
t.Fatalf("want %v have %v", ErrBadIndex, err)
161+
}
162+
163+
}

0 commit comments

Comments
 (0)