Skip to content

refactor: EVM authorization contract ordered standard Authorization execution #355

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

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

Conversation

keyleu
Copy link
Contributor

@keyleu keyleu commented May 21, 2025

These changes slightly refactor how Standard authorizations are created and executed in the EVM authorizations contract. ZK flow remains untouched.

Authorizations are now created with a label (similar to CW flow), a set of users that can execute that authorization label, and an array of AuthorizationData (contract address + execution type + function_selector/call) that can be executed.

When executing a label, we will verify that the subroutine passed calls the same contracts in the same way in the same order. This adds order to our authorizations. Before this change we could execute any contract in any order, now we will respect the order of execution because we are saving this in an array of AuthorizationData.

Additionally, allows creating authorizations that only verify the function selector (name of the function) instead of the entire function call. This is useful if we want to allow someone to execute the function of the library with any parameters

In general kinda it's cleaner although it increases the storage cost a little but, although not much.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Authorization is now managed using labels, enabling batch handling of authorized addresses and ordered contract call sequences.
    • Message sending requires specifying a label to validate authorization for grouped contract calls.
  • Refactor

    • Authorization logic transitioned from per-user and per-call mappings to a label-based scheme for streamlined management.
    • Event notifications for authorization changes now emit only the label identifier.
  • Tests

    • Expanded test coverage for label-based authorization, including validation by call hash and function selector.
    • Added tests for permissionless access, mixed validation modes, and various execution success and failure scenarios.

Copy link
Contributor

coderabbitai bot commented May 21, 2025

"""

Walkthrough

The Authorization contract was refactored from a user-contract-call mapping system to a label-based authorization scheme. Authorizations are now grouped under labels, each mapping to authorized addresses and ordered authorization data. Events, function signatures, and internal logic were updated to support this new structure, with corresponding updates to the test suite.

Changes

File(s) Change Summary
solidity/src/authorization/Authorization.sol Refactored authorization logic from triple nested mapping to label-based system; replaced per-user mappings with label-keyed authorized addresses and authorization data arrays; changed events to emit label strings; updated function signatures for batch operations using labels; revised internal authorization checks and message sending to use label-based verification.
solidity/test/authorization/AuthorizationStandard.t.sol Updated test contract to reflect label-based authorization; replaced flat arrays with nested arrays and labels; modified calls to authorization functions and assertions to use new label and authorization data structures; added tests for function selector and call hash authorization modes; expanded tests for execution success and failure scenarios; adjusted test calls to new function signatures.

Sequence Diagram(s)

sequenceDiagram
    participant Owner
    participant AuthorizationContract
    participant User

    Owner->>AuthorizationContract: addStandardAuthorizations(labels, users, authorizationData)
    AuthorizationContract-->>Owner: emit AuthorizationAdded(label)

    User->>AuthorizationContract: sendProcessorMessage(label, message)
    AuthorizationContract->>AuthorizationContract: _checkAddressIsAuthorized(sender, label, authorizationData)
    AuthorizationContract-->>User: Process message if authorized
Loading

Possibly related PRs

  • feat: EVM Authorizations contract #343: Refactors the Authorization contract’s internal data structure and logic from per-user mapping to label-based system, modifying core authorization logic and function signatures introduced in the initial Authorization contract PR.

Suggested reviewers

  • bekauz

Poem

🐇
Labels now rule the authorization land,
No more tangled mappings, just strings in hand.
Batch your permissions, keep order in view,
Authorization’s simpler, and testing is too!
With hops and with hashes, the contract’s renewed—
A rabbit’s delight, for code that’s improved!
🥕
"""

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


📜 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 12dee5a and 48e2e3d.

📒 Files selected for processing (1)
  • solidity/test/authorization/AuthorizationStandard.t.sol (11 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: setup-local-ic
  • GitHub Check: solidity contracts
  • GitHub Check: build-and-deploy
🔇 Additional comments (16)
solidity/test/authorization/AuthorizationStandard.t.sol (16)

29-33: LGTM! Well-structured data setup for label-based authorization.

The new data structures properly align with the refactored label-based authorization model. Using nested arrays for users and authorization data keyed by labels is a clean approach.


45-47: Good practice: Setting deterministic test environment.

Setting block timestamp and height provides a controlled test environment, which is essential for consistent test results.


78-87: Excellent: Comprehensive authorization data setup.

The authorization data structure correctly demonstrates both validation modes supported by the new contract. The setup clearly shows the distinction between useFunctionSelector and callHash validation.


251-276: Excellent test coverage for both validation modes.

The tests properly validate both callHash and functionSelector authorization modes. This ensures the contract correctly handles both types of validation logic.


290-300: Good edge case testing for invalid authorization data.

Testing mismatched array lengths is important for ensuring proper validation of input parameters. The error message "Array lengths must match" is clear and informative.


395-417: Excellent negative testing for function selector validation.

This test properly verifies that function selector validation works correctly by attempting to call a different function than authorized. This is crucial for security testing.


422-448: Robust testing of callHash validation.

The test correctly verifies that changing function parameters results in a different callHash, which should be rejected. This ensures the granular control that callHash validation provides.


515-548: Important test: Function selector ignores parameters.

This test validates a key feature of the function selector validation mode - that it allows the same function to be called with different parameters. This is essential for library functions that need flexible parameter handling.


553-586: Comprehensive test for mixed validation types.

Testing both validation types in a single authorization is excellent coverage. This ensures the contract can handle complex authorization scenarios with different validation requirements.


593-634: Good failure scenario testing.

Testing execution failures and proper callback handling is important for ensuring the system behaves correctly under error conditions. The verification of callback results adds confidence in the error handling logic.


687-741: Excellent atomic subroutine failure testing.

This test properly validates that in atomic subroutines, if one function fails, the entire execution should fail with executionCount of 0. This is critical for maintaining atomicity guarantees.


746-807: Comprehensive non-atomic subroutine testing.

The test correctly validates that non-atomic subroutines can have partial execution, where some functions succeed before one fails. The verification that the first function (updateConfig) actually succeeded while the second failed demonstrates proper partial execution handling.


892-942: Well-implemented helper function for atomic subroutines.

The helper function properly creates atomic subroutine messages with multiple function calls. The structure follows the expected processor message format.


950-1013: Comprehensive helper function for non-atomic subroutines.

The helper function correctly implements non-atomic subroutine creation with proper retry logic and callback configurations. This enables thorough testing of partial execution scenarios.


1-1014: Overall assessment: Excellent test coverage and refactoring.

The test file demonstrates:

  • Comprehensive coverage of both validation modes (callHash and functionSelector)
  • Thorough edge case testing including failure scenarios
  • Proper testing of atomic vs non-atomic execution behaviors
  • Well-structured helper functions for complex test scenarios
  • Good separation of concerns with clear test categories

The refactoring from flat arrays to label-based authorization is well-implemented and thoroughly tested.


102-102:

✅ Verification successful

Verify consistency of label parameter usage.

The sendProcessorMessage function now requires a label parameter. Ensure this change is consistently applied across all test cases.


🏁 Script executed:

#!/bin/bash
# Verify all calls to sendProcessorMessage include the label parameter
rg -A 2 -B 2 "sendProcessorMessage" --type solidity

Length of output: 84


Let’s re-run the search without relying on an unrecognized “solidity” type and target all .sol/.t.sol files:


🏁 Script executed:

#!/bin/bash
# Find every call to sendProcessorMessage in Solidity tests
rg -n -A2 -B2 "sendProcessorMessage" --glob '*.sol'

Length of output: 8812


Consistent label parameter usage confirmed

All auth.sendProcessorMessage(...) calls in AuthorizationStandard.t.sol now include the required label argument. No further changes are needed.


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.

@keyleu keyleu requested a review from bekauz May 21, 2025 16:27
@keyleu keyleu changed the title refactor: modify EVM authorization contract for standard Authorizations refactor: modify EVM authorization contract for standard Authorizations order execution May 21, 2025
@keyleu keyleu changed the title refactor: modify EVM authorization contract for standard Authorizations order execution refactor: modify EVM authorization contract for standard Authorizations execution order May 21, 2025
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

🧹 Nitpick comments (5)
solidity/src/authorization/Authorization.sol (3)

115-122: Use a cheaper, collision-resistant key type for authorizations / authorizationsData

string keys are hashed (keccak256) for every storage access and incur noticeably higher gas costs than fixed-size value types.
If the label never needs to be re-encoded on-chain (e.g. it is only human-readable off-chain), consider storing the keccak256(bytes(label)) as bytes32, or even an uint256, and keep the human name only in events. This lowers:

  • SSTORE/SLOAD cost per access
  • Memory-to-calldata copy cost when the label is passed as string calldata
- mapping(string => address[]) public authorizations;
- mapping(string => AuthorizationData[]) public authorizationsData;
+ mapping(bytes32 => address[]) public authorizations;
+ mapping(bytes32 => AuthorizationData[]) public authorizationsData;

bytes32 labelKey = keccak256(bytes(label)); can be computed once in each public/​internal function.
This is an optional change but pays for itself quickly if the contract is called frequently.


397-424: Duplicate code between _verifyAtomicSubroutineAuthorization and _verifyNonAtomicSubroutineAuthorization

Both functions build an AuthorizationData[] and then call _checkAddressIsAuthorized. The only difference is the subroutine type they decode.

Refactor to a single private helper to reduce byte-code size and maintenance burden:

-function _verifyAtomicSubroutineAuthorization(string calldata label, IProcessorMessageTypes.SendMsgs memory sendMsgs) private view { ... }
-
-function _verifyNonAtomicSubroutineAuthorization(string calldata label, IProcessorMessageTypes.SendMsgs memory sendMsgs) private view { ... }
+function _verifySubroutineAuthorization(
+    string calldata label,
+    IProcessorMessageTypes.FunctionTarget[] memory functions,
+    bytes[] memory messages
+) private view { ... }

Call this helper from both branches with the proper arrays.


481-520: Linear scans become expensive for large access lists

_checkAddressIsAuthorized performs two O(n) loops:

  1. Scan authorizedAddresses
  2. Scan labelAuthorizationData

Gas grows linearly with each authorised address or function.

If labels are expected to hold many users or large call sequences, consider:

  • Mapping address => bool for quick membership checks
  • Storing a single bytes32 hash = keccak256(abi.encodePacked(authorizationData)) and comparing hashes instead of element-by-element loops.

This change would bring membership checks to O(1) and shrink calldata copying.

solidity/test/authorization/AuthorizationStandard.t.sol (2)

29-33: Prefer constructing test fixtures in setUp() to avoid contract-level storage

users, labels, and authorizationData are declared as state variables, which means each test deployment incurs an unnecessary SSTORE gas cost and byte-code growth. Initialising them inside setUp() (as memory variables) keeps the test contract lighter and avoids unintended cross-test coupling.

This is a minor optimisation but makes the test suite cleaner.


71-78: Helper to build AuthorizationData would reduce duplication

The same four-line block that fills users, labels, and authorizationData appears in several tests. Extracting it into a private helper (e.g., _initUpdateConfigAuth()) improves readability and reduces copy-paste errors.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 2ae1e36 and 6634650.

📒 Files selected for processing (2)
  • solidity/src/authorization/Authorization.sol (11 hunks)
  • solidity/test/authorization/AuthorizationStandard.t.sol (10 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: build-and-deploy
🔇 Additional comments (1)
solidity/src/authorization/Authorization.sol (1)

365-389: Priority is force-overwritten – verify that this is intended

sendMsgs.priority is unconditionally set to Priority.Medium, discarding any priority chosen by the caller.
If callers should be able to request a lower/higher priority (e.g. Low, High), the contract should validate instead of overwrite, or at least expose a constant policy.
Please confirm that hard-coding Medium is a deliberate product decision.

@keyleu keyleu changed the title refactor: modify EVM authorization contract for standard Authorizations execution order refactor: EVM authorization contract ordered standard Authorization execution May 21, 2025
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

♻️ Duplicate comments (1)
solidity/src/authorization/Authorization.sol (1)

261-289: 🛠️ Refactor suggestion

Avoid overwriting existing labels without warning

While the implementation now checks for empty arrays (addressing a previous comment), it still silently overwrites existing authorization labels without warning. This could lead to unexpected behavior if a label is accidentally reused.

function addStandardAuthorizations(
    string[] memory _labels,
    address[][] memory _users,
    AuthorizationData[][] memory _authorizationData
) external onlyOwner {
    require(
        _labels.length == _authorizationData.length && _labels.length == _users.length, "Array lengths must match"
    );

    for (uint256 i = 0; i < _labels.length; i++) {
        string memory label = _labels[i];
        address[] memory users = _users[i];
        require(users.length > 0, "Users array cannot be empty");
        AuthorizationData[] memory authorizationData = _authorizationData[i];
        require(authorizationData.length > 0, "Authorization data array cannot be empty");

+       // Log existing authorization overwrite
+       if (authorizations[label].length > 0) {
+           emit AuthorizationRemoved(label);
+       }

        authorizations[label] = users;
        authorizationsData[label] = authorizationData;

        emit AuthorizationAdded(label);
    }
}

If you want to make the overwrite behavior more explicit, consider adding an optional boolean parameter to control whether overwriting is allowed.

🧹 Nitpick comments (6)
solidity/src/authorization/Authorization.sol (6)

115-139: Consider using bytes32 keys for better storage efficiency

The refactoring to a label-based system is a good improvement for clarity, but using string keys for mappings in Solidity is less gas-efficient than using bytes32 keys. This is especially important for storage mappings that will be accessed frequently.

- mapping(string => address[]) public authorizations;
+ mapping(bytes32 => address[]) public authorizations;

- mapping(string => AuthorizationData[]) public authorizationsData;
+ mapping(bytes32 => AuthorizationData[]) public authorizationsData;

If the string labels need to be maintained for easier usage in interfaces, consider using keccak256(bytes(label)) to convert the string to bytes32 before accessing the mapping.


283-286: Consider optimizing storage operations for gas efficiency

Direct assignment of arrays from memory to storage can be gas-intensive. For large arrays, consider using a more gas-efficient approach.

- authorizations[label] = users;
- authorizationsData[label] = authorizationData;
+ // Clear existing arrays first if any
+ delete authorizations[label];
+ delete authorizationsData[label];
+
+ // Use a more efficient storage pattern for the arrays
+ for (uint256 j = 0; j < users.length; j++) {
+     authorizations[label].push(users[j]);
+ }
+ 
+ for (uint256 j = 0; j < authorizationData.length; j++) {
+     authorizationsData[label].push(authorizationData[j]);
+ }

This approach ensures that if an array already exists, it's properly cleared before new elements are added. It's more explicit and can be more gas-efficient for large arrays.


463-464: Use more specific error messages for authorization failures

The current error message "Unauthorized access" is used in multiple places with different context, which makes debugging more difficult.

- revert("Unauthorized access");
+ revert("User not authorized for this label");

For line 427:

- revert("Unauthorized access");
+ revert("User not authorized for atomic subroutine");

For line 463:

- revert("Unauthorized access");
+ revert("User not authorized for non-atomic subroutine");

Also applies to: 427-428


478-525: Improve error information for authorization checks

The _checkAddressIsAuthorized function returns a simple boolean, which doesn't provide specific information about why authorization failed. Consider providing a more informative response.

Consider refactoring this function to return a more specific error code or message by using custom errors:

enum AuthorizationErrorCode {
    Success,
    UserNotAuthorized,
    WrongNumberOfCalls,
    InvalidContractSequence,
    InvalidCallSequence
}

function _checkAddressIsAuthorized(
    address _address,
    string calldata label,
    AuthorizationData[] memory _authorizationData
) internal view returns (bool authorized, AuthorizationErrorCode errorCode) {
    // Check if the address is in the list of authorized addresses for this label
    address[] memory authorizedAddresses = authorizations[label];

    bool isAuthorized = false;
    for (uint256 i = 0; i < authorizedAddresses.length; i++) {
        if (authorizedAddresses[i] == _address || authorizedAddresses[i] == address(0)) {
            isAuthorized = true;
            break;
        }
    }

    if (!isAuthorized) {
        return (false, AuthorizationErrorCode.UserNotAuthorized);
    }

    // Check if the authorization data matches the order
    AuthorizationData[] memory labelAuthorizationData = authorizationsData[label];

    // Check that the lengths are the same
    if (labelAuthorizationData.length != _authorizationData.length) {
        return (false, AuthorizationErrorCode.WrongNumberOfCalls);
    }

    // Check that each element is the same
    for (uint256 i = 0; i < labelAuthorizationData.length; i++) {
        if (labelAuthorizationData[i].contractAddress != _authorizationData[i].contractAddress) {
            return (false, AuthorizationErrorCode.InvalidContractSequence);
        }
        if (labelAuthorizationData[i].callHash != _authorizationData[i].callHash) {
            return (false, AuthorizationErrorCode.InvalidCallSequence);
        }
    }

    return (true, AuthorizationErrorCode.Success);
}

Then, update the calling functions to use the error code for more specific error messages.


314-335: Add event emission for denied authorizations

Currently, there's no visibility when an authorization is denied. Consider adding an event for failed authorization attempts to aid in monitoring and debugging.

First, add a new event:

/**
 * @notice Event emitted when an authorization is denied
 * @dev This event is emitted when an unauthorized access attempt is made
 * @param sender The address that attempted the unauthorized access
 * @param label The label of the authorization that was attempted
 */
event AuthorizationDenied(address indexed sender, string label);

Then in the verification functions, emit this event before reverting:

if (!_checkAddressIsAuthorized(msg.sender, label, authorizationData)) {
+   emit AuthorizationDenied(msg.sender, label);
    revert("Unauthorized access");
}

This provides better observability into access control issues.


509-522: Consider using a hash comparison for authorization data

Instead of comparing each element of the authorization data arrays individually, consider hashing the entire array to perform a single comparison. This can be more gas-efficient for large arrays.

For validating ordered execution, computing and comparing a single hash of the authorization data could be more efficient:

- // Check that the lengths are the same
- if (labelAuthorizationData.length != _authorizationData.length) {
-     return false;
- }
- 
- // Check that each element is the same
- for (uint256 i = 0; i < labelAuthorizationData.length; i++) {
-     if (
-         labelAuthorizationData[i].contractAddress != _authorizationData[i].contractAddress
-             || labelAuthorizationData[i].callHash != _authorizationData[i].callHash
-     ) {
-         return false;
-     }
- }

+ // Compute hash of stored authorization data on first use and cache it
+ bytes32 storedHash = keccak256(abi.encode(labelAuthorizationData));
+ 
+ // Compare with hash of provided authorization data
+ if (storedHash != keccak256(abi.encode(_authorizationData))) {
+     return false;
+ }

You could also consider caching the hash of authorization data when it's first set to save even more gas on subsequent checks.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 6634650 and 8f98aa8.

📒 Files selected for processing (1)
  • solidity/src/authorization/Authorization.sol (11 hunks)
🔇 Additional comments (1)
solidity/src/authorization/Authorization.sol (1)

19-19: Good update to documentation reflecting ordered execution

The update to the documentation correctly reflects the new capability of enforcing order of execution through the stored array of AuthorizationData. This is an important change that improves the clarity and security of the contract.

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.

1 participant