Skip to content

🐛 bug: enforce Range header limit configuration#4071

Merged
ReneWerner87 merged 5 commits intomainfrom
add-configurable-cap-on-parsed-ranges
Feb 10, 2026
Merged

🐛 bug: enforce Range header limit configuration#4071
ReneWerner87 merged 5 commits intomainfrom
add-configurable-cap-on-parsed-ranges

Conversation

@gaby
Copy link
Member

@gaby gaby commented Feb 9, 2026

Motivation

  • Prevent resource exhaustion from very large Range headers by capping the number of parsed ranges and make the configuration clearer and consistent across initialization and parsing.

Description

  • Introduce Config.MaxRanges with DefaultMaxRanges = 16 and apply the default in New() when the configured value is non-positive.
  • Enforce the configured maximum in DefaultReq.Range() by counting parsed ranges and returning ErrRangeTooLarge while setting status 416 and Content-Range: bytes */<size> when exceeded.
  • Add ErrRangeTooLarge, update tests to cover the over-limit case, and document MaxRanges in docs/api/fiber.md.
  • Remove the redundant fallback check in DefaultReq.Range() so the code relies on the default applied in App.New().

@gaby gaby requested a review from a team as a code owner February 9, 2026 05:38
Copilot AI review requested due to automatic review settings February 9, 2026 05:38
@gaby gaby requested review from ReneWerner87, efectn and sixcolors and removed request for Copilot February 9, 2026 05:38
@gaby gaby added the codex label Feb 9, 2026
@ReneWerner87 ReneWerner87 added this to v3 Feb 9, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Feb 9, 2026
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @gaby, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a potential resource exhaustion vulnerability by introducing a configurable limit on the number of ranges processed from an HTTP Range header. It standardizes the configuration of this limit, ensures its enforcement during request parsing, and provides clear error handling and documentation, thereby improving the robustness and security of the application against malformed or excessively large range requests.

Highlights

  • Introduced Config.MaxRanges: A new configuration option to cap the number of ranges parsed from an HTTP Range header, defaulting to 16, to prevent resource exhaustion.
  • Enforced Range Header Limit: The DefaultReq.Range() method now respects Config.MaxRanges, returning ErrRangeTooLarge and setting a 416 Requested Range Not Satisfiable status if the limit is exceeded.
  • Removed Redundant Fallback: Streamlined the DefaultReq.Range() logic by removing an unnecessary fallback check, relying on the MaxRanges default being applied during application initialization.
  • Updated Documentation and Tests: Added ErrRangeTooLarge, included a new test case for exceeding the range limit, and documented MaxRanges in the API reference.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • app.go
    • Added MaxRanges field to the Config struct, allowing configuration of the maximum number of ranges.
    • Defined DefaultMaxRanges constant with a value of 16.
    • Ensured MaxRanges is initialized to DefaultMaxRanges in New() if a non-positive value is provided.
  • ctx_interface_gen.go
    • Clarified documentation for Request(), Response(), and Value() methods regarding nil returns when the context is released.
  • ctx_test.go
    • Added Test_Ctx_Range_TooManyRanges to validate the new MaxRanges enforcement, ensuring a 416 status is returned when the limit is exceeded.
  • docs/api/fiber.md
    • Documented the new MaxRanges configuration option, including its default value and behavior when exceeded.
  • error.go
    • Introduced ErrRangeTooLarge error, associated with StatusRequestedRangeNotSatisfiable.
  • req.go
    • Integrated app.config.MaxRanges into the Range() method to limit parsed ranges.
    • Implemented logic to increment a counter for parsed ranges and, if maxRanges is surpassed, set the response status to 416 and Content-Range header, then return ErrRangeTooLarge.
    • Removed a redundant fallback check for range limits, relying on the global configuration.
Activity
  • The make audit command failed due to govulncheck discovering Go standard library vulnerabilities in the toolchain (Go 1.25.1).
  • make generate, make betteralign, make modernize, and make format commands completed successfully.
  • The make lint command reported 0 issues.
  • The full test suite, comprising 2653 tests, passed successfully after running make test.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gaby gaby changed the title 🐛 bug: enforce Range header cap and remove redundant fallback 🐛 bug: enforce Range header cap Feb 9, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 9, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds Config.MaxRanges (default 16) and enforces it during Range header parsing; exceeding the limit returns HTTP 416 with a Content-Range header and ErrRangeTooLarge. Also adds docs, a test, an exported error, a small BasicAuth trimming change, and context doc-comment updates.

Changes

Cohort / File(s) Summary
Configuration
app.go
Added MaxRanges int \json:"max_ranges"`toConfig, introduced DefaultMaxRanges = 16, and default-initialize MaxRangesinNew` when <= 0.
Range parsing & request handling
req.go
Preallocate ranges with configured capacity, track parsed ranges, and if count exceeds MaxRanges respond 416 + Content-Range: bytes */<size> and return ErrRangeTooLarge. Also use utils.FormatInt for size formatting in error paths.
Error definitions
error.go
Added exported error ErrRangeTooLarge = NewError(StatusRequestedRangeNotSatisfiable, "range: too many ranges").
Tests
ctx_test.go
Added Test_Ctx_Range_TooManyRanges verifying 416 and Content-Range when MaxRanges is exceeded.
Documentation
docs/api/fiber.md
Documented new MaxRanges config field, default, and behavior (zero/negative defaulting, 416 when exceeded).
Context interface docs
ctx_interface_gen.go
Expanded comments for Request(), Response(), and Value() clarifying nil returns after context release.
Middleware tweak
middleware/basicauth/basicauth.go
Replaced strings.Trim(rawAuth, " \t") with utils.TrimSpace(rawAuth) for Authorization header whitespace trimming.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client
  participant Ctx as Ctx.Range()
  participant App as App.Config
  participant Res as Response

  Client->>Ctx: Request with Range header (multiple ranges)
  Ctx->>App: read config.MaxRanges
  Ctx->>Ctx: parse ranges, increment count
  alt count <= MaxRanges
    Ctx->>Ctx: finish parsing
    Ctx->>Res: return ranges (206 or appropriate)
    Res-->>Client: 206 Partial Content / response
  else count > MaxRanges
    Ctx->>Res: set Status 416 and header "Content-Range: bytes */<size>"
    Res-->>Client: 416 Requested Range Not Satisfiable
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

🐰
I count the slices, nibble each byte,
Sixteen's the limit — keep parsing light.
Too many ranges? I thump and declare: 416 rings,
Content-Range posted — tidy, no overreaching things.
Hops, carrots, and careful byte bites.

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'enforce Range header limit configuration' accurately describes the main change: adding MaxRanges configuration to control HTTP Range header parsing.
Description check ✅ Passed The description covers motivation, implementation details, error handling, and documentation updates. However, some checklist items from the template are not explicitly addressed.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch add-configurable-cap-on-parsed-ranges

No actionable comments were generated in the recent review. 🎉


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Feb 9, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.04%. Comparing base (f93613f) to head (b4ab278).
⚠️ Report is 21 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4071      +/-   ##
==========================================
- Coverage   91.08%   91.04%   -0.05%     
==========================================
  Files         119      119              
  Lines       11221    11256      +35     
==========================================
+ Hits        10221    10248      +27     
- Misses        633      637       +4     
- Partials      367      371       +4     
Flag Coverage Δ
unittests 91.04% <100.00%> (-0.05%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@gaby gaby changed the title 🐛 bug: enforce Range header cap 🐛 bug: enforce Range header cap configuration Feb 9, 2026
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a configurable limit for the number of ranges parsed from a Range header to prevent resource exhaustion attacks. The implementation is solid, adding a MaxRanges field to the Config struct, enforcing the limit in DefaultReq.Range(), and including corresponding tests and documentation. The changes are well-executed and improve the robustness of the framework. I have one minor suggestion to further optimize performance in the range parsing logic.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@docs/api/fiber.md`:
- Line 49: The table row for the configuration option `MaxRanges` is out of
alphabetical order; move the entire row describing `<Reference
id="maxranges">MaxRanges</Reference>` so it appears between the `Immutable` and
`MsgpackEncoder` rows (instead of between `BodyLimit` and `CaseSensitive`) to
restore alphabetical ordering of the config table in docs/api/fiber.md.
🧹 Nitpick comments (2)
req.go (1)

931-936: Minor: partial rangeData.Ranges is returned on over-limit.

When the limit is exceeded mid-parse (e.g., maxRanges=2 with 3 ranges), the returned Range struct will contain the ranges parsed before the cap was hit. Callers that check err != nil first will be fine, but callers that inspect rangeData.Ranges alongside the error could see a partially populated slice.

This matches the existing behavior for ErrRangeMalformed (lines 952, 960) which also returns a partially populated rangeData, so it's consistent. Just something to be aware of.

error.go (1)

33-37: Inconsistent error types within the Range errors block.

ErrRangeTooLarge uses NewError() (returning *fiber.Error with an HTTP status code), while ErrRangeMalformed and ErrRangeUnsatisfiable use errors.New() (plain error). This means errors.Is(err, ErrRangeTooLarge) will behave differently from the siblings — callers doing type-based error handling may be surprised.

This is likely intentional since ErrRangeTooLarge is designed to carry a 416 status for the error handler, but it's worth a brief comment explaining the distinction.

@gaby gaby changed the title 🐛 bug: enforce Range header cap configuration 🐛 bug: enforce Range header limit configuration Feb 9, 2026
Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: b4ab278 Previous: 6bbbc4a Ratio
Benchmark_Ctx_Range/bytes=500-1000 - B/op 128 B/op 16 B/op 8
Benchmark_Ctx_Range/bytes=0-700,800-1000 - B/op 128 B/op 48 B/op 2.67

This comment was automatically generated by workflow using github-action-benchmark.

Copilot AI review requested due to automatic review settings February 9, 2026 06:07
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR introduces a configurable cap on how many byte ranges are parsed from the Range header to reduce resource exhaustion risk and make the default behavior consistent via fiber.New() config normalization.

Changes:

  • Add Config.MaxRanges with DefaultMaxRanges = 16 and apply the default in New() when the configured value is non-positive.
  • Enforce the configured maximum in DefaultReq.Range() and return a new ErrRangeTooLarge while setting 416 and Content-Range: bytes */<size> when exceeded.
  • Update docs and tests to cover the new MaxRanges behavior (including an over-limit case).

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
req.go Enforces the configured maximum number of parsed ranges and returns ErrRangeTooLarge when exceeded.
error.go Introduces ErrRangeTooLarge as a first-class error for over-limit Range parsing.
app.go Adds Config.MaxRanges, DefaultMaxRanges, and defaults MaxRanges in New().
ctx_test.go Adds a test that verifies a request is rejected with 416 when the range count exceeds MaxRanges.
docs/api/fiber.md Documents the new MaxRanges config option and its behavior.
ctx_interface_gen.go Updates generated interface comments related to released contexts returning nil.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

@ReneWerner87
Copy link
Member

image but allocs and speed is the same -> its ok

@ReneWerner87 ReneWerner87 merged commit 4fb35e8 into main Feb 10, 2026
17 of 18 checks passed
@ReneWerner87 ReneWerner87 deleted the add-configurable-cap-on-parsed-ranges branch February 10, 2026 08:01
@github-project-automation github-project-automation bot moved this to Done in v3 Feb 10, 2026
@ReneWerner87 ReneWerner87 modified the milestones: v3, v3.1.0 Feb 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants