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(x/circuit): Add validation for permission when an account is assigned and validation for msgURL #22460

Merged

Conversation

GNaD13
Copy link
Contributor

@GNaD13 GNaD13 commented Nov 6, 2024

Description

Closes: #22322 issue 1, 2, 3


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

    • Introduced a validation step for permissions in the circuit breaker authorization process, enhancing security and control.
    • Added a new validation method for permissions to ensure compliance with defined rules.
    • Implemented a validation function for message type URLs in circuit breaker operations.
  • Bug Fixes

    • Enhanced error handling for invalid permissions during the authorization process.
  • Tests

    • Added a new test to validate the behavior of the authorization process with permission checks, ensuring expected outcomes are met.

Copy link
Contributor

coderabbitai bot commented Nov 6, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces a validation step in the AuthorizeCircuitBreaker method of the msgServer struct, ensuring that permissions are validated before further processing. A new method, Validation, is added to the Permissions struct to enforce rules regarding the LimitTypeUrls based on permission levels. Additionally, a new test function is created to verify the behavior of the AuthorizeCircuitBreaker method concerning these validations. The existing methods related to circuit breaker operations remain unchanged.

Changes

File Change Summary
x/circuit/keeper/msg_server.go Added permissions validation in AuthorizeCircuitBreaker method. Enhanced error handling.
Modified TripCircuitBreaker and ResetCircuitBreaker to include message type URL validation.
x/circuit/keeper/msg_server_test.go Introduced TestAuthorizeCircuitBreakerWithPermissionValidation to test new validation logic.
x/circuit/types/permission.go Added Validation method to Permissions struct for permission checks based on level.
Introduced MsgTypeURLValidation function for validating message type URLs.

Assessment against linked issues

Objective Addressed Explanation
Validation for SOME_MSGS (22322)
Validation for ALL_MSGS (22322)
Message Type URL Validation Improvement (22322) No changes made to handle missing leading slashes.
Reset Transaction Feature (22322) No implementation for resetting transaction behavior.

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 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
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: 2

🧹 Outside diff range and nitpick comments (4)
x/circuit/types/permission.go (2)

5-20: Improve comment style and fix typos

The comments should follow Uber style guide conventions and maintain consistency.

Apply this diff:

 func (p *Permissions) Validation() error {
 	switch {
 	case p.Level == Permissions_LEVEL_SOME_MSGS:
-		// if permission is some msg, LimitTypeUrls array must not be empty
+		// Validation ensures LimitTypeUrls array is not empty for SOME_MSGS permission.
 		if len(p.LimitTypeUrls) == 0 {
 			return errors.New("LimitTypeUrls of LEVEL_SOME_MSGS should NOT be empty")
 		}
 	case p.Level == Permissions_LEVEL_ALL_MSGS || p.Level == Permissions_LEVEL_SUPER_ADMIN:
-		// if permission is all msg or super addmin, LimitTypeUrls array clear
-		// all p.LimitTypeUrls since we not use this field
+		// Validation clears LimitTypeUrls for ALL_MSGS or SUPER_ADMIN permissions
+		// as this field is not used for these levels.
 		p.LimitTypeUrls = nil
 	default:
 		return errors.New("unknown permission level")
 	}

 	return nil
 }

5-20: Consider using switch on p.Level directly

The current switch implementation using boolean conditions could be simplified.

Apply this diff for better readability:

 func (p *Permissions) Validation() error {
-	switch {
-	case p.Level == Permissions_LEVEL_SOME_MSGS:
+	switch p.Level {
+	case Permissions_LEVEL_SOME_MSGS:
 		if len(p.LimitTypeUrls) == 0 {
 			return errors.New("LimitTypeUrls of LEVEL_SOME_MSGS should NOT be empty")
 		}
-	case p.Level == Permissions_LEVEL_ALL_MSGS || p.Level == Permissions_LEVEL_SUPER_ADMIN:
+	case Permissions_LEVEL_ALL_MSGS, Permissions_LEVEL_SUPER_ADMIN:
 		p.LimitTypeUrls = nil
 	default:
 		return errors.New("unknown permission level")
 	}

 	return nil
 }
x/circuit/keeper/msg_server_test.go (2)

121-134: Consider adding more assertions for super admin permissions

While the test correctly verifies that LimitTypeUrls is empty after authorization, consider adding assertions to verify:

  1. The permission level remains SUPER_ADMIN
  2. The authorization event is emitted correctly
 	perms, err := ft.keeper.Permissions.Get(ft.ctx, add1)
 	require.NoError(t, err)
 	// LimitTypeUrls should be empty
 	require.Equal(t, len(perms.LimitTypeUrls), 0)
+	require.Equal(t, types.Permissions_LEVEL_SUPER_ADMIN, perms.Level)
+	require.Equal(
+		t,
+		sdk.NewEvent(
+			"authorize_circuit_breaker",
+			sdk.NewAttribute("granter", authority),
+			sdk.NewAttribute("grantee", addresses[1]),
+			sdk.NewAttribute("permission", adminPerms.String()),
+		),
+		lastEvent(ft.ctx),
+	)

135-159: Add descriptive comments to clarify test behavior

The test case would benefit from explicit comments explaining why LimitTypeUrls should be empty for ALL_MSGS permission level, as this is a key requirement from the linked issue #22322.

 	// successfully add a new super user with LimitTypeUrls not empty
+	// ALL_MSGS permission should clear LimitTypeUrls regardless of input
+	// This validates the behavior specified in issue #22322
 	allmsgs := types.Permissions{Level: types.Permissions_LEVEL_ALL_MSGS, LimitTypeUrls: []string{"cosmos.staking.v1beta1.MsgDelegate"}}
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fdccc84 and db68f2d.

📒 Files selected for processing (3)
  • x/circuit/keeper/msg_server.go (1 hunks)
  • x/circuit/keeper/msg_server_test.go (1 hunks)
  • x/circuit/types/permission.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
x/circuit/keeper/msg_server.go (1)

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

x/circuit/keeper/msg_server_test.go (2)

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


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

x/circuit/types/permission.go (1)

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

🔇 Additional comments (4)
x/circuit/types/permission.go (2)

1-4: LGTM: Clean package declaration and imports

The package declaration and import statement follow Go conventions.


5-20: Implementation successfully meets PR objectives

The validation logic correctly implements the requirements from issue #22322:

  • Validates that limit_type_urls is not empty for SOME_MSGS permission
  • Clears limit_type_urls for ALL_MSGS and SUPER_ADMIN permissions
x/circuit/keeper/msg_server.go (1)

61-64: Consider wrapping the validation error for better context.

The validation implementation looks good, but consider wrapping the error to provide more context about where the validation failed.

-	err = msg.Permissions.Validation()
-	if err != nil {
-		return nil, err
-	}
+	if err = msg.Permissions.Validation(); err != nil {
+		return nil, errorsmod.Wrap(err, "invalid permissions")
+	}

Let's verify if the validation implementation covers all requirements from issue #22322:

✅ Verification successful

The validation implementation is complete and correct

The validation in x/circuit/types/permission.go properly implements all required checks:

  • For LEVEL_SOME_MSGS: Validates that LimitTypeUrls is not empty
  • For LEVEL_ALL_MSGS and LEVEL_SUPER_ADMIN: Clears the LimitTypeUrls array as it's not used
  • The implementation is tested as shown in x/circuit/keeper/msg_server_test.go

The original review suggestion about error wrapping remains valid but is just a minor improvement.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if Validation method implements all required checks

# Look for the Validation method implementation
ast-grep --pattern 'func (p Permissions) Validation() error {
  $$$
}'

# Check for SOME_MSGS validation
rg -A 5 'LEVEL_SOME_MSGS.*LimitTypeUrls.*empty'

# Check for ALL_MSGS handling
rg -A 5 'LEVEL_ALL_MSGS.*LimitTypeUrls.*clear'

# Check for message type URL validation
rg -A 5 'validateTypeURL.*leading slash'

Length of output: 214


Script:

#!/bin/bash
# Let's try a different approach to find the validation implementation

# Find all files that might contain Permissions validation
fd -e go | xargs rg -l "Permissions.*Validation"

# Look for permission level constants and validation
rg -A 10 "type Level"

# Search for any validation related to permissions
rg -A 10 "func.*Validation|func.*validate.*Permission"

# Look for type URL validation patterns
rg -A 5 "TypeURL.*validate|validate.*TypeURL"

Length of output: 10512

x/circuit/keeper/msg_server_test.go (1)

114-120: LGTM: Test setup follows established patterns

The test function is well-structured with a clear name that indicates its purpose, and follows consistent setup patterns used throughout the test file.

Comment on lines 5 to 20
func (p *Permissions) Validation() error {
switch {
case p.Level == Permissions_LEVEL_SOME_MSGS:
// if permission is some msg, LimitTypeUrls array must not be empty
if len(p.LimitTypeUrls) == 0 {
return errors.New("LimitTypeUrls of LEVEL_SOME_MSGS should NOT be empty")
}
case p.Level == Permissions_LEVEL_ALL_MSGS || p.Level == Permissions_LEVEL_SUPER_ADMIN:
// if permission is all msg or super addmin, LimitTypeUrls array clear
// all p.LimitTypeUrls since we not use this field
p.LimitTypeUrls = nil
default:
}

return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation for unknown permission levels

The default case should return an error for unknown permission levels instead of silently succeeding. This ensures proper error handling for all possible cases.

Apply this diff:

 func (p *Permissions) Validation() error {
 	switch {
 	case p.Level == Permissions_LEVEL_SOME_MSGS:
 		// if permission is some msg, LimitTypeUrls array must not be empty
 		if len(p.LimitTypeUrls) == 0 {
 			return errors.New("LimitTypeUrls of LEVEL_SOME_MSGS should NOT be empty")
 		}
 	case p.Level == Permissions_LEVEL_ALL_MSGS || p.Level == Permissions_LEVEL_SUPER_ADMIN:
 		// if permission is all msg or super addmin, LimitTypeUrls array clear
 		// all p.LimitTypeUrls since we not use this field
 		p.LimitTypeUrls = nil
 	default:
+		return errors.New("unknown permission level")
 	}

 	return nil
 }
📝 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
func (p *Permissions) Validation() error {
switch {
case p.Level == Permissions_LEVEL_SOME_MSGS:
// if permission is some msg, LimitTypeUrls array must not be empty
if len(p.LimitTypeUrls) == 0 {
return errors.New("LimitTypeUrls of LEVEL_SOME_MSGS should NOT be empty")
}
case p.Level == Permissions_LEVEL_ALL_MSGS || p.Level == Permissions_LEVEL_SUPER_ADMIN:
// if permission is all msg or super addmin, LimitTypeUrls array clear
// all p.LimitTypeUrls since we not use this field
p.LimitTypeUrls = nil
default:
}
return nil
}
func (p *Permissions) Validation() error {
switch {
case p.Level == Permissions_LEVEL_SOME_MSGS:
// if permission is some msg, LimitTypeUrls array must not be empty
if len(p.LimitTypeUrls) == 0 {
return errors.New("LimitTypeUrls of LEVEL_SOME_MSGS should NOT be empty")
}
case p.Level == Permissions_LEVEL_ALL_MSGS || p.Level == Permissions_LEVEL_SUPER_ADMIN:
// if permission is all msg or super addmin, LimitTypeUrls array clear
// all p.LimitTypeUrls since we not use this field
p.LimitTypeUrls = nil
default:
return errors.New("unknown permission level")
}
return nil
}

Comment on lines 160 to 165
// grants user perms to Permissions_LEVEL_SOME_MSGS with empty LimitTypeUrls
somemsgs := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{}}
msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[3], Permissions: &somemsgs}
_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
require.Error(t, err)
}
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

Enhance SOME_MSGS validation test coverage

The test should include:

  1. Verification of the specific error message
  2. A positive test case with non-empty LimitTypeUrls
 	// grants user perms to Permissions_LEVEL_SOME_MSGS with empty LimitTypeUrls
 	somemsgs := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{}}
 	msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[3], Permissions: &somemsgs}
 	_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
-	require.Error(t, err)
+	require.ErrorContains(t, err, "limit_type_urls cannot be empty for permission level SOME_MSGS")
+
+	// grants user perms to Permissions_LEVEL_SOME_MSGS with valid LimitTypeUrls
+	somemsgs = types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{"cosmos.staking.v1beta1.MsgDelegate"}}
+	msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[3], Permissions: &somemsgs}
+	_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
+	require.NoError(t, err)
+
+	add3, err := ft.ac.StringToBytes(addresses[3])
+	require.NoError(t, err)
+
+	perms, err = ft.keeper.Permissions.Get(ft.ctx, add3)
+	require.NoError(t, err)
+	require.Equal(t, types.Permissions_LEVEL_SOME_MSGS, perms.Level)
+	require.Equal(t, []string{"cosmos.staking.v1beta1.MsgDelegate"}, perms.LimitTypeUrls)
📝 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
// grants user perms to Permissions_LEVEL_SOME_MSGS with empty LimitTypeUrls
somemsgs := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{}}
msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[3], Permissions: &somemsgs}
_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
require.Error(t, err)
}
// grants user perms to Permissions_LEVEL_SOME_MSGS with empty LimitTypeUrls
somemsgs := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{}}
msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[3], Permissions: &somemsgs}
_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
require.ErrorContains(t, err, "limit_type_urls cannot be empty for permission level SOME_MSGS")
// grants user perms to Permissions_LEVEL_SOME_MSGS with valid LimitTypeUrls
somemsgs = types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{"cosmos.staking.v1beta1.MsgDelegate"}}
msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[3], Permissions: &somemsgs}
_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
require.NoError(t, err)
add3, err := ft.ac.StringToBytes(addresses[3])
require.NoError(t, err)
perms, err = ft.keeper.Permissions.Get(ft.ctx, add3)
require.NoError(t, err)
require.Equal(t, types.Permissions_LEVEL_SOME_MSGS, perms.Level)
require.Equal(t, []string{"cosmos.staking.v1beta1.MsgDelegate"}, perms.LimitTypeUrls)
}

@GNaD13 GNaD13 changed the title feat(x/circuit): Add validation for permission when an account is assigned feat(x/circuit): Add validation for permission when an account is assigned and validation for msgURL Nov 6, 2024
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: 2

🧹 Outside diff range and nitpick comments (3)
x/circuit/types/permission.go (2)

5-22: Method has unexpected side effects

The Validation method name suggests it only performs validation, but it also modifies the LimitTypeUrls field. Consider renaming it to ValidateAndNormalize to better reflect its behavior.


15-16: Fix typo in comment

The comment contains a typo: "addmin" should be "admin"

-		// if permission is all msg or super addmin, LimitTypeUrls array clear
+		// if permission is all msg or super admin, LimitTypeUrls array clear
x/circuit/keeper/msg_server_test.go (1)

167-167: Consider testing URL normalization separately.

The test combines multiple type URLs with different formats (with and without leading slash). Consider splitting this into separate test cases for better clarity.

-	permis := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{"cosmos.staking.v1beta1.MsgDelegate", "/cosmos.gov.v1beta1.MsgDeposit", "cosmos.gov.v1beta1.MsgVote"}}
+	// Test URL normalization
+	permisWithoutSlash := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{"cosmos.staking.v1beta1.MsgDelegate"}}
+	msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[4], Permissions: &permisWithoutSlash}
+	_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
+	require.NoError(t, err)
+
+	perms, err = ft.keeper.Permissions.Get(ft.ctx, add4)
+	require.NoError(t, err)
+	require.Equal(t, []string{"/cosmos.staking.v1beta1.MsgDelegate"}, perms.LimitTypeUrls)
+
+	// Test multiple URLs
+	permisMultiple := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{"/cosmos.gov.v1beta1.MsgDeposit", "/cosmos.gov.v1beta1.MsgVote"}}
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between db68f2d and bda9cae.

📒 Files selected for processing (3)
  • x/circuit/keeper/msg_server.go (3 hunks)
  • x/circuit/keeper/msg_server_test.go (1 hunks)
  • x/circuit/types/permission.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • x/circuit/keeper/msg_server.go
🧰 Additional context used
📓 Path-based instructions (2)
x/circuit/keeper/msg_server_test.go (2)

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


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

x/circuit/types/permission.go (1)

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

🔇 Additional comments (4)
x/circuit/types/permission.go (1)

13-13: Verify URL validation usage

Let's verify where this URL validation is being used in the codebase to ensure consistent usage.

✅ Verification successful

Let me check the implementation of MsgTypeURLValidation to understand its behavior.


URL validation is consistently implemented and used

The MsgTypeURLValidation function ensures all message type URLs start with a forward slash, and it's consistently used in the codebase:

  • In x/circuit/types/permission.go for validating LimitTypeUrls
  • In x/circuit/keeper/msg_server.go for validating message URLs before permission checks

The implementation is simple and its usage is uniform across the codebase, ensuring consistent URL formatting.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for MsgTypeURLValidation usage
rg "MsgTypeURLValidation" -A 3

Length of output: 1356


Script:

#!/bin/bash
# Get the implementation of MsgTypeURLValidation
ast-grep --pattern 'func MsgTypeURLValidation($_) $_'

Length of output: 469

x/circuit/keeper/msg_server_test.go (3)

114-134: LGTM: Super admin permission validation test is well-structured.

The test correctly verifies that:

  1. Super admin can be authorized with non-empty LimitTypeUrls
  2. LimitTypeUrls are properly cleared after authorization

135-159: LGTM: Super user permission validation test is comprehensive.

The test effectively validates:

  1. ALL_MSGS permission can be granted with non-empty LimitTypeUrls
  2. LimitTypeUrls are properly cleared as expected
  3. Event emission is correctly verified

166-189: LGTM: SOME_MSGS permission validation is thorough.

The test effectively covers:

  1. Authorization with multiple valid type URLs
  2. Proper event emission
  3. Verification of stored permissions
  4. Leading slash handling in type URLs

Note: The test aligns well with PR objective #1 regarding message type URL validation improvement.

Comment on lines 24 to 31
func MsgTypeURLValidation(urls []string) []string {
for idx, url := range urls {
if url[0] != '/' {
urls[idx] = "/" + url
}
}
return urls
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add bounds checking to prevent panic

The function will panic if any URL in the slice is an empty string. Add length validation before accessing the first character.

Apply this diff:

 func MsgTypeURLValidation(urls []string) []string {
 	for idx, url := range urls {
+		if len(url) == 0 {
+			continue
+		}
 		if url[0] != '/' {
 			urls[idx] = "/" + url
 		}
 	}
 	return urls
 }

Additionally, consider renaming the function to EnsureLeadingSlash to better describe its specific purpose.

📝 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
func MsgTypeURLValidation(urls []string) []string {
for idx, url := range urls {
if url[0] != '/' {
urls[idx] = "/" + url
}
}
return urls
}
func MsgTypeURLValidation(urls []string) []string {
for idx, url := range urls {
if len(url) == 0 {
continue
}
if url[0] != '/' {
urls[idx] = "/" + url
}
}
return urls
}

Comment on lines +160 to +165
// grants user perms to Permissions_LEVEL_SOME_MSGS with empty LimitTypeUrls
somemsgs := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{}}
msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[3], Permissions: &somemsgs}
_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
require.Error(t, err)

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

Add error message assertion for SOME_MSGS validation.

The test should verify the specific error message when SOME_MSGS permission is granted with empty LimitTypeUrls.

 	msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[3], Permissions: &somemsgs}
 	_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
-	require.Error(t, err)
+	require.ErrorContains(t, err, "limit_type_urls cannot be empty for permission level SOME_MSGS")
📝 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
// grants user perms to Permissions_LEVEL_SOME_MSGS with empty LimitTypeUrls
somemsgs := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{}}
msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[3], Permissions: &somemsgs}
_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
require.Error(t, err)
// grants user perms to Permissions_LEVEL_SOME_MSGS with empty LimitTypeUrls
somemsgs := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{}}
msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[3], Permissions: &somemsgs}
_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
require.ErrorContains(t, err, "limit_type_urls cannot be empty for permission level SOME_MSGS")

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.

lgtm! thank you!

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Nov 6, 2024
@julienrbrt
Copy link
Member

Could you add a changelog under x/circuit/changelog.md? Under the improvement section

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

🧹 Outside diff range and nitpick comments (1)
x/circuit/CHANGELOG.md (1)

44-44: Enhance the changelog entry with more specific details.

While the entry follows the correct format, it could be more descriptive about the specific validations implemented. Consider expanding it to:

-* (feat) [#22460](https://github.com/cosmos/cosmos-sdk/pull/22460) Add validation for permission when an account is assigned and validation for msgURL
+* (feat) [#22460](https://github.com/cosmos/cosmos-sdk/pull/22460) Add validations in x/circuit: ensure non-empty limit_type_urls for SOME_MSGS permission, clear limit_type_urls for ALL_MSGS permission, and validate msgURL format (leading slash)
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 57c69c2 and 2b68c2e.

📒 Files selected for processing (1)
  • x/circuit/CHANGELOG.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
x/circuit/CHANGELOG.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

Copy link
Contributor

@akhilkumarpilli akhilkumarpilli left a comment

Choose a reason for hiding this comment

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

lgtm! Please fix failing CI checks (ignore test-system-v2 check)

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

🧹 Outside diff range and nitpick comments (1)
x/circuit/keeper/msg_server_test.go (1)

166-170: Add test cases for message URL format validation.

Consider adding test cases to verify that message URLs without leading slashes are automatically handled, as per the PR objectives.

 	// grants user perms to Permissions_LEVEL_SOME_MSGS with empty LimitTypeUrls
 	permis := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{"cosmos.staking.v1beta1.MsgDelegate", "/cosmos.gov.v1beta1.MsgDeposit", "cosmos.gov.v1beta1.MsgVote"}}
 	msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[4], Permissions: &permis}
 	_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
 	require.NoError(t, err)
+
+	// Test automatic handling of URLs without leading slash
+	permisNoSlash := types.Permissions{Level: types.Permissions_LEVEL_SOME_MSGS, LimitTypeUrls: []string{"cosmos.bank.v1beta1.MsgSend"}}
+	msg = &types.MsgAuthorizeCircuitBreaker{Granter: authority, Grantee: addresses[5], Permissions: &permisNoSlash}
+	_, err = srv.AuthorizeCircuitBreaker(ft.ctx, msg)
+	require.NoError(t, err)
+
+	add5, err := ft.ac.StringToBytes(addresses[5])
+	require.NoError(t, err)
+
+	perms, err = ft.keeper.Permissions.Get(ft.ctx, add5)
+	require.NoError(t, err)
+	require.Equal(t, []string{"/cosmos.bank.v1beta1.MsgSend"}, perms.LimitTypeUrls, "URL should have leading slash")
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2b68c2e and 542997e.

📒 Files selected for processing (1)
  • x/circuit/keeper/msg_server_test.go (6 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
x/circuit/keeper/msg_server_test.go (2)

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


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

🔇 Additional comments (3)
x/circuit/keeper/msg_server_test.go (3)

16-16: LGTM! Constant declaration follows best practices.

The constant is well-named and its value aligns with the message URL format requirements.


114-189: LGTM! Comprehensive test coverage for permission validation.

The test thoroughly validates the permission levels and their interactions with LimitTypeUrls.


238-238: LGTM! Consistent URL format updates.

The message URLs have been updated to consistently include leading slashes, aligning with the PR objectives.

Also applies to: 339-339, 359-359, 406-406

@julienrbrt julienrbrt added this pull request to the merge queue Nov 7, 2024
Merged via the queue into cosmos:main with commit 00f3065 Nov 7, 2024
70 of 72 checks passed
mergify bot pushed a commit that referenced this pull request Nov 7, 2024
…igned and validation for msgURL (#22460)

(cherry picked from commit 00f3065)
julienrbrt pushed a commit that referenced this pull request Nov 7, 2024
…igned and validation for msgURL (backport #22460) (#22464)

Co-authored-by: GnaD <89174180+GNaD13@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:x/circuit
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Missing validations and implementation in x/circuit
3 participants