Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Limit recursion depth for unknown field detection and unpack any #22901

Merged
merged 6 commits into from
Dec 16, 2024

Conversation

alpe
Copy link
Contributor

@alpe alpe commented Dec 16, 2024

Description

Limit recursion depth for unknown field detection and unpack any


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Added support for simulating nested messages.
    • Introduced a Linux-only backend for crypto/keyring module.
    • Enabled importing hex keys via standard input.
    • Enhanced version command to return v2 server information.
  • Improvements

    • Upgraded RocksDB libraries to version 9.
    • Simplified testing frameworks and removed redundant context in integration tests.
  • Bug Fixes

    • Resolved issues with simulation tests and account ID querying.
    • Fixed prune command to properly disable asynchronous pruning.
  • API Breaking Changes

    • Removed testutil/network package and client prompt validations.
  • Chores

    • Updated changelog with unreleased changes and version history.

@alpe alpe requested review from kocubinski, testinginprod, aaronc and a team as code owners December 16, 2024 16:40
Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

📝 Walkthrough

Walkthrough

This pull request introduces several key changes across multiple components of the system. The primary focus is on enhancing message processing, adding recursion limits, and updating changelogs. The modifications include new constraints for unpacking protobuf Any messages, improved handling of unknown fields, and comprehensive changelog updates that detail new features, improvements, bug fixes, and breaking changes across different modules.

Changes

File Change Summary
CHANGELOG.md Added new unreleased section with features, improvements, bug fixes, and breaking changes
codec/types/interface_registry.go Added recursion and call limits for unpacking protobuf Any messages, introduced statefulUnpacker and sharedCounter structs
codec/unknownproto/unknown_fields.go Added doRejectUnknownFields function with recursion limit for handling unknown fields
x/tx/CHANGELOG.md Updated release date for v1.0.0-alpha.3, added bug fix reference
x/tx/decode/unknown.go Introduced doRejectUnknownFields function with recursion limit for message processing

Sequence Diagram

sequenceDiagram
    participant Client
    participant InterfaceRegistry
    participant StatefulUnpacker
    participant AnyMessage

    Client->>InterfaceRegistry: UnpackAny(message, interface)
    InterfaceRegistry->>StatefulUnpacker: Create with initial limits
    StatefulUnpacker->>AnyMessage: Check recursion depth
    alt Depth within limits
        StatefulUnpacker-->>InterfaceRegistry: Unpack message
        InterfaceRegistry-->>Client: Return unpacked message
    else Depth exceeded
        StatefulUnpacker-->>Client: Return recursion limit error
    end
Loading

Possibly Related PRs

Suggested Reviewers

  • aaronc
  • kocubinski
  • testinginprod
  • julienrbrt
  • tac0turtle

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

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.

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

ACK but changelogs should be reverted

CHANGELOG.md Outdated Show resolved Hide resolved
x/tx/CHANGELOG.md Outdated Show resolved Hide resolved
@julienrbrt julienrbrt changed the title Fix: Limit recursion depth for unknown field detection and unpack any fix: Limit recursion depth for unknown field detection and unpack any Dec 16, 2024
@alpe alpe enabled auto-merge December 16, 2024 16:45
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: 8

🧹 Nitpick comments (2)
codec/types/interface_registry.go (1)

18-28: Improve documentation comments for exported variables

According to Go conventions, comments for exported variables should start with the variable name and provide a clear description. Adjusting the comments enhances readability and aligns with the Go style guide.

Apply this diff:

 var (
 
-    // MaxUnpackAnySubCalls extension point that defines the maximum number of sub-calls allowed during the unpacking
+    // MaxUnpackAnySubCalls defines the maximum number of sub-calls allowed during the unpacking
     // process of protobuf Any messages.
 
     MaxUnpackAnySubCalls = 100
 
-    // MaxUnpackAnyRecursionDepth extension point that defines the maximum allowed recursion depth during protobuf Any
+    // MaxUnpackAnyRecursionDepth defines the maximum allowed recursion depth during protobuf Any
     // message unpacking.
 
     MaxUnpackAnyRecursionDepth = 10
 )
codec/unknownproto/unknown_fields.go (1)

43-45: Define recursion limit as a constant for consistency

Hardcoding the recursion limit of 10,000 reduces maintainability. Defining it as a constant improves readability and allows for easier adjustments in the future.

Apply this diff:

+const defaultRecursionLimit = 10000

 func RejectUnknownFields(bz []byte, msg proto.Message, allowUnknownNonCriticals bool, resolver jsonpb.AnyResolver) (hasUnknownNonCriticals bool, err error) {
-    return doRejectUnknownFields(bz, msg, allowUnknownNonCriticals, resolver, 10_000)
+    return doRejectUnknownFields(bz, msg, allowUnknownNonCriticals, resolver, defaultRecursionLimit)
 }
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f22d2a8 and 0cc4eb3.

📒 Files selected for processing (5)
  • CHANGELOG.md (0 hunks)
  • codec/types/interface_registry.go (5 hunks)
  • codec/unknownproto/unknown_fields.go (3 hunks)
  • x/tx/CHANGELOG.md (1 hunks)
  • x/tx/decode/unknown.go (3 hunks)
💤 Files with no reviewable changes (1)
  • CHANGELOG.md
✅ Files skipped from review due to trivial changes (1)
  • x/tx/CHANGELOG.md
🧰 Additional context used
📓 Path-based instructions (3)
codec/unknownproto/unknown_fields.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

codec/types/interface_registry.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/tx/decode/unknown.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

Comment on lines +36 to +38
// recursion limit with same default as https://github.com/protocolbuffers/protobuf-go/blob/v1.35.2/encoding/protowire/wire.go#L28
return doRejectUnknownFields(bz, desc, allowUnknownNonCriticals, resolver, 10_000)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Define recursion limit as a constant for maintainability

Currently, the recursion limit of 10,000 is hardcoded within the RejectUnknownFields function. Defining this value as a constant improves readability and makes it easier to manage or adjust in the future.

Apply this diff to define the recursion limit as a constant:

+const defaultRecursionLimit = 10000

 func RejectUnknownFields(bz []byte, desc protoreflect.MessageDescriptor, allowUnknownNonCriticals bool, resolver protodesc.Resolver) (hasUnknownNonCriticals bool, err error) {
-	return doRejectUnknownFields(bz, desc, allowUnknownNonCriticals, resolver, 10_000)
+	return doRejectUnknownFields(bz, desc, allowUnknownNonCriticals, resolver, defaultRecursionLimit)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// recursion limit with same default as https://github.com/protocolbuffers/protobuf-go/blob/v1.35.2/encoding/protowire/wire.go#L28
return doRejectUnknownFields(bz, desc, allowUnknownNonCriticals, resolver, 10_000)
}
const defaultRecursionLimit = 10000
func RejectUnknownFields(bz []byte, desc protoreflect.MessageDescriptor, allowUnknownNonCriticals bool, resolver protodesc.Resolver) (hasUnknownNonCriticals bool, err error) {
// recursion limit with same default as https://github.com/protocolbuffers/protobuf-go/blob/v1.35.2/encoding/protowire/wire.go#L28
return doRejectUnknownFields(bz, desc, allowUnknownNonCriticals, resolver, defaultRecursionLimit)
}

Comment on lines +50 to +52
if recursionLimit == 0 {
return false, errors.New("recursion limit reached")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update recursion limit check to handle non-positive values

The current recursion limit check only handles the case when recursionLimit equals zero. To prevent potential underflows and enhance robustness, consider updating the condition to check for less than or equal to zero.

Apply this diff:

 if len(bz) == 0 {
     return hasUnknownNonCriticals, nil
 }
-if recursionLimit == 0 {
+if recursionLimit <= 0 {
     return false, errors.New("recursion limit reached")
 }

Committable suggestion skipped: line range outside the PR's diff.

@@ -131,7 +145,7 @@
fieldBytes = a.Value
}

hasUnknownNonCriticalsChild, err := RejectUnknownFields(fieldBytes, fieldMessage, allowUnknownNonCriticals, resolver)
hasUnknownNonCriticalsChild, err := doRejectUnknownFields(fieldBytes, fieldMessage, allowUnknownNonCriticals, resolver, recursionLimit-1)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consistent recursion limit handling in recursive calls

Similar to the previous comment, ensure that all recursive calls to doRejectUnknownFields properly handle the decrementing of recursionLimit and prevent potential underflow.

Apply this diff:

 hasUnknownNonCriticalsChild, err := doRejectUnknownFields(fieldBytes, fieldMessage, allowUnknownNonCriticals, resolver, recursionLimit-1)
+if err != nil {
+    return hasUnknownNonCriticals, err
+}

Ensure that the recursive function handles recursionLimit <= 0 appropriately, as previously suggested.

Committable suggestion skipped: line range outside the PR's diff.

@@ -111,7 +125,7 @@

if fieldMessage.FullName() == anyFullName {
// Firstly typecheck types.Any to ensure nothing snuck in.
hasUnknownNonCriticalsChild, err := RejectUnknownFields(fieldBytes, anyDesc, allowUnknownNonCriticals, resolver)
hasUnknownNonCriticalsChild, err := doRejectUnknownFields(fieldBytes, anyDesc, allowUnknownNonCriticals, resolver, recursionLimit-1)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure decrementing recursion limit does not cause underflow

When recursively calling doRejectUnknownFields, ensure that decrementing recursionLimit does not result in negative values, which could bypass the termination condition.

Consider verifying that recursionLimit is greater than zero before the recursive call:

 if fieldMessage.FullName() == anyFullName {
     // Firstly typecheck types.Any to ensure nothing snuck in.
-    hasUnknownNonCriticalsChild, err := doRejectUnknownFields(fieldBytes, anyDesc, allowUnknownNonCriticals, resolver, recursionLimit-1)
+    if recursionLimit > 0 {
+        hasUnknownNonCriticalsChild, err := doRejectUnknownFields(fieldBytes, anyDesc, allowUnknownNonCriticals, resolver, recursionLimit-1)
+    } else {
+        return false, errors.New("recursion limit reached")
+    }
     hasUnknownNonCriticals = hasUnknownNonCriticals || hasUnknownNonCriticalsChild
     if err != nil {
         return hasUnknownNonCriticals, err
     }

Alternatively, ensure the recursion limit check at the beginning of the function handles non-positive values as previously suggested.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +277 to +282
if r.maxDepth == 0 {
return errors.New("max depth exceeded")
}
if r.maxCalls.count == 0 {
return errors.New("call limit exceeded")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update limit checks to handle non-positive values

The current checks for maxDepth and maxCalls.count only handle zero values. To enhance robustness and prevent potential underflows, consider updating the conditions to check for less than or equal to zero.

Apply this diff:

 func (r *statefulUnpacker) UnpackAny(any *Any, iface interface{}) error {
-    if r.maxDepth == 0 {
+    if r.maxDepth <= 0 {
         return errors.New("max depth exceeded")
     }
-    if r.maxCalls.count == 0 {
+    if r.maxCalls.count <= 0 {
         return errors.New("call limit exceeded")
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if r.maxDepth == 0 {
return errors.New("max depth exceeded")
}
if r.maxCalls.count == 0 {
return errors.New("call limit exceeded")
}
if r.maxDepth <= 0 {
return errors.New("max depth exceeded")
}
if r.maxCalls.count <= 0 {
return errors.New("call limit exceeded")
}

@@ -240,6 +290,8 @@
return nil
}

r.maxCalls.count--
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Prevent maxCalls.count from becoming negative

After decrementing r.maxCalls.count, ensure it does not become negative, which could lead to incorrect behavior. Consider adding a check after the decrement.

Apply this diff:

 r.maxCalls.count--
+if r.maxCalls.count < 0 {
+    return errors.New("call limit exceeded")
+}

Alternatively, since the limit check has been updated to handle non-positive values, this might already be addressed.

Committable suggestion skipped: line range outside the PR's diff.

@@ -125,7 +139,7 @@ func RejectUnknownFields(bz []byte, msg proto.Message, allowUnknownNonCriticals

if protoMessageName == ".google.protobuf.Any" {
// Firstly typecheck types.Any to ensure nothing snuck in.
hasUnknownNonCriticalsChild, err := RejectUnknownFields(fieldBytes, (*types.Any)(nil), allowUnknownNonCriticals, resolver)
hasUnknownNonCriticalsChild, err := doRejectUnknownFields(fieldBytes, (*types.Any)(nil), allowUnknownNonCriticals, resolver, recursionLimit-1)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure proper handling of recursion limit during recursive calls

When recursively calling doRejectUnknownFields, ensure that the decrementing of recursionLimit does not result in negative values, which could bypass termination conditions.

Consider verifying that recursionLimit is greater than zero before the recursive call or rely on the updated recursion limit check as previously suggested.

Comment on lines +57 to +59
if recursionLimit == 0 {
return false, errors.New("recursion limit reached")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update recursion limit check to handle non-positive values

To prevent potential underflows and enhance robustness, consider updating the recursion limit check from recursionLimit == 0 to recursionLimit <= 0.

Apply this diff:

 if len(bz) == 0 {
     return hasUnknownNonCriticals, nil
 }
-if recursionLimit == 0 {
+if recursionLimit <= 0 {
     return false, errors.New("recursion limit reached")
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if recursionLimit == 0 {
return false, errors.New("recursion limit reached")
}
if len(bz) == 0 {
return hasUnknownNonCriticals, nil
}
if recursionLimit <= 0 {
return false, errors.New("recursion limit reached")
}

@alpe alpe added this pull request to the merge queue Dec 16, 2024
Merged via the queue into main with commit c6b1bdc Dec 16, 2024
78 of 79 checks passed
@alpe alpe deleted the alex/abs0043_fix branch December 16, 2024 17:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants