fix: add pre-read guard to limitedReader to prevent state contamination#3033
Open
Kunall7890 wants to merge 1 commit into
Open
fix: add pre-read guard to limitedReader to prevent state contamination#3033Kunall7890 wants to merge 1 commit into
Kunall7890 wants to merge 1 commit into
Conversation
When limitedReader is reused via sync.Pool, the read counter (r.read) may retain a stale value if Reset is not called or is called after a partial read. Add a strict pre-read guard that rejects immediately if r.read already exceeds LimitBytes, preventing delegation to the underlying reader with a contaminated counter. Closes labstack#1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Adds a strict pre-read guard to \limitedReader.Read\ that checks whether the read counter (
.read) already exceeds \LimitBytes\ before delegating to the underlying reader.
Why
The \limitedReader\ is reused via \sync.Pool\ in \BodyLimitWithConfig. While \Reset\ clears the counter, a contaminated \limitedReader\ retrieved from the pool could delegate reads to the underlying body without proper rejection if:
.read\ at an intermediate value that still exceeds the limit
The post-read guard alone is insufficient because it only catches the overflow after it happens. The pre-read guard provides defense-in-depth: if
.read\ is already beyond the limit, fail immediately without touching the underlying stream.
Changes
\\diff
-func (r *limitedReader) Read(b []byte) (n int, err error) {
+func (r *limitedReader) Read(p []byte) (n int, err error) {
r.read += int64(n)
if r.read > r.LimitBytes {
return n, echo.ErrStatusRequestEntityTooLarge
}
return
}
\\
Closes #1