Validate Audita report bounds with constant memory
This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user