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

feat(ibc-hooks): improved UnmarshalJSON validation & error handling #324

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

0xObsidian
Copy link

Description

Closes: #317

Improves AsyncCallback JSON unmarshaling with:

  • Better validation for ModuleAddress format and required fields
  • More specific error messages
  • Memory optimization using single intermediate struct
  • Comprehensive test coverage for error cases

Testing the introduced feat

Fetch this PR branch and from the root directory run:

go test ./x/ibc-hooks/move-hooks/message_test.go -v

Author Checklist

  • 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
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Descritpion
-----------
Improves AsyncCallback JSON unmarshaling with:
- Better validation for ModuleAddress format and required fields
- More specific error messages
- Memory optimization using single intermediate struct
- Comprehensive test coverage for error cases

Tetsing the introduced `feat`
-----------------------------
Fetch this PR branch and from the root directory run:
```
go test ./x/ibc-hooks/move-hooks/message_test.go -v
```
@0xObsidian 0xObsidian requested a review from a team as a code owner December 20, 2024 05:21
Copy link

coderabbitai bot commented Dec 20, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request focuses on improving the JSON unmarshaling process for the AsyncCallback type in the move_hooks package. The changes involve removing the asyncCallback and asyncCallbackStringID types and introducing a new intermediateCallback type. The UnmarshalJSON method has been enhanced with more robust validation, including checks for module address and module name, and improved handling of ID parsing across different types.

Changes

File Change Summary
x/ibc-hooks/move-hooks/message.go - Removed asyncCallback and asyncCallbackStringID types
- Added intermediateCallback type
- Updated UnmarshalJSON method with enhanced validation
x/ibc-hooks/move-hooks/message_test.go - Added comprehensive test cases for UnmarshalJSON
- Implemented sub-tests covering various input scenarios

Assessment against linked issues

Objective Addressed Explanation
Enhance error handling in UnmarshalJSON [#317]
Add validation for module address and name [#317]

Poem

🐰 In the realm of JSON's dance,
Callbacks now leap with more elegance,
Validation springs, errors take flight,
Move hooks now shine, oh so bright!
A rabbit's code, precise and clean 🌟

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


📜 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 31ce042 and e556df8.

📒 Files selected for processing (2)
  • x/ibc-hooks/move-hooks/message.go (2 hunks)
  • x/ibc-hooks/move-hooks/message_test.go (1 hunks)
🔇 Additional comments (7)
x/ibc-hooks/move-hooks/message.go (4)

58-62: LGTM! Well-designed intermediate type for JSON unmarshaling

The intermediateCallback type with an interface{} Id field is a clean solution for handling both string and numeric ID formats during unmarshaling.


66-84: LGTM! Comprehensive field validation with clear error messages

The validation sequence is well-structured:

  1. Initial JSON unmarshaling
  2. Required field checks
  3. Module address format validation

Each validation step provides specific error messages that will help users identify and fix issues quickly.


86-103: LGTM! Robust ID validation with overflow protection

The ID handling logic effectively addresses the previous overflow concerns by:

  1. Checking for negative values
  2. Validating against uint64 max value
  3. Ensuring no decimal values are silently truncated
  4. Supporting both numeric and string formats

106-108: LGTM! Clean field assignment after validation

The field assignment is performed only after all validations pass, preventing partial updates in error cases.

x/ibc-hooks/move-hooks/message_test.go (3)

12-40: LGTM! Well-structured positive test cases

The test cases effectively cover both numeric and string ID formats with clear assertions and good use of subtests for organization.


42-102: LGTM! Comprehensive validation error test coverage

The test suite thoroughly covers validation error cases including:

  • Empty required fields
  • Invalid module address format
  • Invalid ID types
  • Malformed JSON

Each test properly asserts the specific error message expected.


104-168: LGTM! Thorough numeric range validation tests

Excellent coverage of numeric edge cases including:

  • Decimal values
  • Negative numbers
  • Values exceeding uint64 max
  • Both numeric and string representations of each case

The tests ensure robust handling of all potential numeric input scenarios.


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.

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.

@0xObsidian
Copy link
Author

Hi @beer-1
This PR addresses ticket #317 , feel free to let me know if you have any questions

Copy link

@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

🧹 Nitpick comments (2)
x/ibc-hooks/move-hooks/message.go (2)

58-62: Consider avoiding interface{} for the Id field.
While using interface{} is convenient for handling different JSON number/string representations, it can degrade type safety and clarity. You may want to consider a custom unmarshal approach (e.g., using json.Number) or a well-defined union type to avoid frequent type assertions.


86-98: String ID parsing approach is valid, but consider using strconv for clarity.
Unmarshaling the string into a float64 (line 93) is clever but slightly indirect. A direct call to strconv.ParseUint or a check with json.Number could offer a clearer path to integer conversion, avoiding potential edge cases with float representations.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c91bff8 and 2856872.

📒 Files selected for processing (2)
  • x/ibc-hooks/move-hooks/message.go (2 hunks)
  • x/ibc-hooks/move-hooks/message_test.go (1 hunks)
🔇 Additional comments (8)
x/ibc-hooks/move-hooks/message.go (2)

5-6: Imports look good for format validation.
The addition of "strings" alongside "fmt" solidly supports the new validation checks for the "module_address" prefix requirement.


101-102: Overall unmarshal logic is solid.
The final assignment of ModuleAddress and ModuleName is straightforward, and the new validations capture common mistakes effectively. The approach aligns well with the sub-tests added in message_test.go. Nice work!

x/ibc-hooks/move-hooks/message_test.go (6)

12-25: Great coverage for numeric ID.
These test assertions properly verify that numeric IDs are unmarshaled as expected.


27-40: Well-structured test for string ID.
Testing a string-based ID ensures the newly introduced logic is exercised. The coverage here is thorough.


42-73: Robust validation for empty or invalid fields.
Covering empty module address/name and invalid module address format thoroughly confirms the new defensive checks.


75-84: Properly handles unexpected ID types.
Verifying an invalid boolean ID ensures that erroneous JSON inputs are flagged.


86-95: String ID format errors are correctly caught.
This sub-test ensures that non-numeric strings raise a parsing error, in line with the code’s intended behavior.


97-102: Malformed JSON test is well implemented.
This confirms the parser gracefully fails on structurally invalid input, further enhancing confidence in the unmarshal logic.

x/ibc-hooks/move-hooks/message.go Outdated Show resolved Hide resolved
Copy link

@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: 0

🧹 Nitpick comments (2)
x/ibc-hooks/move-hooks/message.go (2)

58-62: Well-structured intermediate type for JSON unmarshaling.

Good use of an intermediate type with interface{} for flexible ID handling. This approach effectively separates the concerns of JSON parsing from the final validated type.

Consider documenting the supported ID formats in the struct's documentation to help API consumers understand the expected input formats.


73-84: Consider enhancing module address validation.

While the current validation checks for the "0x" prefix, consider adding additional checks for:

  • Valid hexadecimal characters after the "0x" prefix
  • Specific length requirements for the address

Example enhancement:

 if !strings.HasPrefix(ic.ModuleAddress, "0x") {
   return fmt.Errorf("invalid module_address format: must start with '0x'")
 }
+// Remove "0x" prefix and validate hex string
+addr := ic.ModuleAddress[2:]
+for _, c := range addr {
+  if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
+    return fmt.Errorf("invalid module_address: contains non-hexadecimal characters")
+  }
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2856872 and 31ce042.

📒 Files selected for processing (2)
  • x/ibc-hooks/move-hooks/message.go (2 hunks)
  • x/ibc-hooks/move-hooks/message_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • x/ibc-hooks/move-hooks/message_test.go
🔇 Additional comments (2)
x/ibc-hooks/move-hooks/message.go (2)

5-6: LGTM: Appropriate imports added for enhanced error handling.

The addition of "fmt" and "strings" packages aligns well with the improved error handling and string validation requirements.


86-103: Optimize ID parsing and verify edge cases.

The ID parsing logic is thorough but has some redundancy in the string case. Consider:

  1. The overflow check is duplicated between the float64 and string cases
  2. The string case could potentially use strconv.ParseUint for direct parsing

Let's verify the handling of edge cases:

Description
-----------
- Added overflow checking for uint64 ID conversion
- Added validation for decimal and negative values
- Added comprehensive test cases for edge cases
@0xObsidian 0xObsidian force-pushed the 0xObsidian/UnmarshalJSON-validation-and-error-handling branch from 31ce042 to e556df8 Compare December 20, 2024 06:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enhance error handling and add validation in UnmarshalJSON
1 participant