-
Notifications
You must be signed in to change notification settings - Fork 7
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
base: main
Are you sure you want to change the base?
Conversation
""" WalkthroughThe 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
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
Possibly related PRs
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
⏰ Context from checks skipped due to timeout of 90000ms (3)
🔇 Additional comments (10)
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 forauthorizations
/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 thekeccak256(bytes(label))
asbytes32
, or even anuint256
, 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 twoO(n)
loops:
- Scan
authorizedAddresses
- 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 insetUp()
to avoid contract-level storage
users
,labels
, andauthorizationData
are declared as state variables, which means each test deployment incurs an unnecessary SSTORE gas cost and byte-code growth. Initialising them insidesetUp()
(asmemory
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 buildAuthorizationData
would reduce duplicationThe same four-line block that fills
users
,labels
, andauthorizationData
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
📒 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 toPriority.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-codingMedium
is a deliberate product decision.
There was a problem hiding this 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 suggestionAvoid 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 efficiencyThe 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 efficiencyDirect 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 failuresThe 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 checksThe
_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 authorizationsCurrently, 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 dataInstead 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
📒 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 executionThe 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
on a high level this makes sense to me. not the easiest to review given the byte splitting parts (bytes4
and stuff), but the test seems to be covering that!
address[] memory users = _users[i]; | ||
// Check that users is not empty | ||
require(users.length > 0, "Users array cannot be empty"); | ||
AuthorizationData[] memory authorizationData = _authorizationData[i]; | ||
// Check that the authorization data is not empty | ||
require(authorizationData.length > 0, "Authorization data array cannot be empty"); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
maybe here it would be nice to return error messages that include the label (or its index) that caused the error?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
added!
function addStandardAuthorizations( | ||
string[] memory _labels, | ||
address[][] memory _users, | ||
AuthorizationData[][] memory _authorizationData | ||
) external onlyOwner { | ||
// Check that the arrays are the same length | ||
// We are allowing adding multiple authorizations at once for gas optimization | ||
// The arrays must be the same length because for each user we have a contract and a call | ||
require(_users.length == _contracts.length && _contracts.length == _calls.length, "Array lengths must match"); | ||
// The arrays must be the same length because for each label we have a list of authorization data | ||
require( | ||
_labels.length == _authorizationData.length && _labels.length == _users.length, "Array lengths must match" | ||
); | ||
|
||
for (uint256 i = 0; i < _users.length; i++) { | ||
bytes32 callHash = keccak256(_calls[i]); | ||
authorizations[_users[i]][_contracts[i]][callHash] = true; | ||
emit AuthorizationAdded(_users[i], _contracts[i], callHash); | ||
for (uint256 i = 0; i < _labels.length; i++) { | ||
// Get the label and the authorization data | ||
string memory label = _labels[i]; | ||
address[] memory users = _users[i]; | ||
// Check that users is not empty | ||
require(users.length > 0, "Users array cannot be empty"); | ||
AuthorizationData[] memory authorizationData = _authorizationData[i]; | ||
// Check that the authorization data is not empty | ||
require(authorizationData.length > 0, "Authorization data array cannot be empty"); | ||
|
||
// Add the label to the mapping | ||
authorizations[label] = users; | ||
// Add the authorization data to the mapping | ||
authorizationsData[label] = authorizationData; | ||
|
||
emit AuthorizationAdded(label); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we validate the labels being added to prevent overriding existing entries in case they already exist? iirc that's how cw authorizations work, right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually it's not a bug, it's a feature.
Like you say, it's right that In CW we don't allow removing authorizations, just disabling/enabling them. Reason for this is because we tokenize them and we would have conflicts if we remove and try to add again with same label (token already exists).
For solidity we are not tokenizing them (and we don't have an authorization state to enable/disable), so they can just be removed and added again. Therefore, to make it cheaper and not require 2 transactions to "rewrite" an authorization. We allow the owner to "redefine" the authorization.
I was initially checking if the label already existed but then decided that this way is more flexible and cheaper to operate in case an authorization needs to be overwritten
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
coderabbit also told me this btw #355 (comment) 😃
view | ||
returns (bytes memory) | ||
{ | ||
function _handleSendMsgsMessage( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit but what about just _handleSendMsgs
or _handleSendMsgsRequest
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
changed! Changed also for _handleInsertMsgs
bool isAuthorized = false; | ||
for (uint256 i = 0; i < authorizedAddresses.length; i++) { | ||
if (authorizedAddresses[i] == _address || authorizedAddresses[i] == address(0)) { | ||
isAuthorized = true; | ||
break; | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
clean
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
Refactor
Tests