Skip to content

fix: math.MaxUint32 overflows int and test cases#3469

Closed
viralkansarav wants to merge 3 commits into
gofiber:mainfrom
viralkansarav:main
Closed

fix: math.MaxUint32 overflows int and test cases#3469
viralkansarav wants to merge 3 commits into
gofiber:mainfrom
viralkansarav:main

Conversation

@viralkansarav
Copy link
Copy Markdown

Description

Issue fixed:
This check prevents generating an ETag for response bodies larger than the maximum value of a 32-bit unsigned integer. Since the ETag calculation uses a uint32 for the body length, allowing larger bodies could cause integer overflows or incorrect ETag values. By returning a 413 Request Entity Too Large status, the middleware safely handles oversized responses.

Fixes # (issue)
avoids potential bugs or vulnerabilities related to integer overflow.

@viralkansarav viralkansarav requested a review from a team as a code owner May 23, 2025 09:24
@welcome
Copy link
Copy Markdown

welcome Bot commented May 23, 2025

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 23, 2025

"""

Walkthrough

This update modifies test cases in ctx_test.go to use proper string conversion functions for large integer values. Additionally, it adjusts a type comparison in middleware/etag/etag.go by explicitly casting values to uint64 before comparing response body length against the maximum allowed size. No public interfaces are changed.

Changes

File(s) Summary
ctx_test.go Updated test cases to use strconv.FormatInt and strconv.FormatUint for large integer values.
middleware/etag/etag.go Changed body length comparison logic to cast both operands to uint64 for safe comparison; introduced explicit uint32 cast before appending length.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware (etag)
    participant Response

    Client->>Middleware (etag): Send request
    Middleware (etag)->>Response: Process response body
    alt Body length > Max allowed size (uint64)
        Middleware (etag)->>Client: Return 413 status
    else Body length <= Max allowed size
        Middleware (etag)->>Client: Return normal response with ETag
    end
Loading

Possibly related PRs

Suggested reviewers

  • ReneWerner87

Poem

In the field where numbers grow,
Rabbits test their bounds, you know!
With careful type and string in tow,
They leap past bugs that overflow.
Now casting right, the bytes align,
And all the tests will hop just fine! 🐇✨
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a7902f6 and 70c63f7.

📒 Files selected for processing (1)
  • middleware/etag/etag.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • middleware/etag/etag.go
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 23, 2025

Codecov Report

Attention: Patch coverage is 0% with 1 line in your changes missing coverage. Please review.

Project coverage is 84.45%. Comparing base (aae8892) to head (70c63f7).

Files with missing lines Patch % Lines
middleware/etag/etag.go 0.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #3469   +/-   ##
=======================================
  Coverage   84.45%   84.45%           
=======================================
  Files         120      120           
  Lines       12157    12157           
=======================================
  Hits        10267    10267           
  Misses       1462     1462           
  Partials      428      428           
Flag Coverage Δ
unittests 84.45% <0.00%> (ø)

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.

@ReneWerner87
Copy link
Copy Markdown
Member

ReneWerner87 commented May 23, 2025

@viralkansarav thx for the code
can you check the lint issues
image

@viralkansarav
Copy link
Copy Markdown
Author

viralkansarav commented May 23, 2025

@ReneWerner87 The check if uint64(bodyLength) > uint64(math.MaxUint32) ensures that bodyLength will always fit into a uint32 (i.e., it’s ≤ 4,294,967,295). After this check, it’s safe to cast bodyLength to uint32 for appendUint, which expects a uint32 argument.
Can you please change the line of code as i might not be having access to commit in forked repo else i can open a new pr, for the linter we need to assign value to a variable
bodylength32 := uint32(bodyLength)
bb.B = appendUint(bb.Bytes(), bodylength32)
later we can use the variable in append.
I check that bodyLength does not exceed math.MaxUint32 before converting to uint32. The conversion is therefore always safe, and this pattern is accepted by gosec.

@gaby gaby requested a review from Copilot May 23, 2025 10:40
Copy link
Copy Markdown
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

Fixes potential integer overflow when generating ETags by rejecting response bodies larger than math.MaxUint32 and updates tests to use the correct formatting functions for int64 and uint32 boundaries.

  • Use uint64 casts to reliably compare bodyLength against MaxUint32
  • Introduce a uint32 cast for bodyLength before appending to the ETag buffer
  • Replace strconv.Itoa with strconv.FormatInt/FormatUint in tests for extreme values

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
middleware/etag/etag.go Added overflow check with uint64 casts and renamed cast result
ctx_test.go Switched from Itoa to FormatInt/FormatUint for boundary tests
Comments suppressed due to low confidence (1)

middleware/etag/etag.go:67

  • [nitpick] The variable name 'bodylength32' mixes casing and is harder to read; consider renaming it to 'bodyLength32' to follow camelCase conventions.
bodylength32 := uint32(bodyLength)

Comment thread middleware/etag/etag.go Outdated
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Comment thread middleware/etag/etag.go

bodyLength := len(body)
if bodyLength > math.MaxUint32 {
if uint64(bodyLength) > uint64(math.MaxUint32) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is incorrect

Comment thread ctx_test.go
{
value: int64(math.MaxInt64),
str: strconv.Itoa(math.MaxInt64),
str: strconv.FormatInt(math.MaxInt64, 10),
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is not needed, golang already does this inside Itoa

https://go.dev/src/strconv/itoa.go

@gaby
Copy link
Copy Markdown
Member

gaby commented May 23, 2025

@viralkansarav These changes are not needed. We already check for max u32. The itoa function in golang is an alias to the FormatInt one you added.

See https://go.dev/src/strconv/itoa.go

@ReneWerner87
Copy link
Copy Markdown
Member

thank you for your work on the project, but due to the findings we decided against the adjustment in the PR

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.

4 participants