Validate Audita report bounds with constant memory

This commit is contained in:
2026-11-27 21:21:22 +00:00
parent aa0c1f1c03
commit 89f5a6a0ad
5 changed files with 76 additions and 5 deletions

View File

@@ -8,6 +8,34 @@ import (
"strings"
)
// CheckFileBounded verifies readability and the byte limit without retaining
// contents. Callers own any additional path or regular-file requirements.
func CheckFileBounded(path string, limit int64) error {
if strings.TrimSpace(path) == "" {
return fmt.Errorf("file path is required")
}
if limit < 0 {
return fmt.Errorf("file read limit %d is invalid", limit)
}
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("open file %q: %w", path, err)
}
defer func() { _ = file.Close() }()
readLimit := limit
if limit < math.MaxInt64 {
readLimit++
}
size, err := io.Copy(io.Discard, io.LimitReader(file, readLimit))
if err != nil {
return fmt.Errorf("read file %q: %w", path, err)
}
if size > limit {
return fmt.Errorf("file %q exceeds %d-byte limit", path, limit)
}
return nil
}
// ReadFileBounded reads at most limit bytes from path using ordinary workspace
// path semantics. It does not return partial data when the limit is exceeded.
func ReadFileBounded(path string, limit int64) ([]byte, error) {

View File

@@ -8,6 +8,42 @@ import (
"testing"
)
func TestCheckFileBounded(t *testing.T) {
const limit int64 = 4
for _, tc := range []struct {
name, content string
limit int64
valid bool
}{
{"below", "123", limit, true},
{"at", "1234", limit, true},
{"above", "12345", limit, false},
{"empty", "", 0, true},
{"zero", "1", 0, false},
{"maximum", "1234", math.MaxInt64, true},
{"negative", "", -1, false},
} {
t.Run(tc.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "report")
if err := os.WriteFile(path, []byte(tc.content), 0600); err != nil {
t.Fatal(err)
}
err := CheckFileBounded(path, tc.limit)
if (err == nil) != tc.valid {
t.Fatalf("check: %v, want valid=%t", err, tc.valid)
}
if tc.name == "above" && !strings.Contains(err.Error(), "4-byte limit") {
t.Fatalf("missing limit: %v", err)
}
})
}
for _, path := range []string{" ", t.TempDir(), filepath.Join(t.TempDir(), "missing")} {
if err := CheckFileBounded(path, limit); err == nil {
t.Fatalf("invalid path accepted: %q", path)
}
}
}
func TestReadFileBoundedEnforcesLimitWithoutPartialContent(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, "value.txt")