-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAccessControlCore.sol
387 lines (362 loc) · 17 KB
/
AccessControlCore.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// SPDX-License-Identifier: MIT
// custom errors (0.8.4)
// require with message (0.4.22)
// pure/view modifiers (0.4.16)
// hardhat (0.4.11)
pragma solidity >=0.8.4;
/**
* @title Role-based Access Control Core (RBAC-C)
*
* @notice Access control smart contract provides an API to check
* if a specific operation is permitted globally and/or
* if a particular user has a permission to execute it.
*
* @notice This contract is inherited by other contracts requiring the role-based access control (RBAC)
* protection for the restricted access functions
*
* @notice It deals with two main entities: features and roles.
*
* @notice Features are designed to be used to enable/disable public functions
* of the smart contract (used by a wide audience).
* @notice User roles are designed to control the access to restricted functions
* of the smart contract (used by a limited set of maintainers).
*
* @notice Terms "role", "permissions" and "set of permissions" have equal meaning
* in the documentation text and may be used interchangeably.
* @notice Terms "permission", "single permission" implies only one permission bit set.
*
* @notice Access manager is a special role which allows to grant/revoke other roles.
* Access managers can only grant/revoke permissions which they have themselves.
* As an example, access manager with no other roles set can only grant/revoke its own
* access manager permission and nothing else.
*
* @notice Access manager permission should be treated carefully, as a super admin permission:
* Access manager with even no other permission can interfere with another account by
* granting own access manager permission to it and effectively creating more powerful
* permission set than its own.
*
* @dev Both current and OpenZeppelin AccessControl implementations feature a similar API
* to check/know "who is allowed to do this thing".
* @dev Zeppelin implementation is more flexible:
* - it allows setting unlimited number of roles, while current is limited to 256 different roles
* - it allows setting an admin for each role, while current allows having only one global admin
* @dev Current implementation is more lightweight:
* - it uses only 1 bit per role, while Zeppelin uses 256 bits
* - it allows setting up to 256 roles at once, in a single transaction, while Zeppelin allows
* setting only one role in a single transaction
*
* @dev This smart contract is designed to be inherited by other
* smart contracts which require access control management capabilities.
*
* @dev Access manager permission has a bit 255 set.
* This bit must not be used by inheriting contracts for any other permissions/features.
*
* @dev The 'core' version of the RBAC contract hides three rarely used external functions from the public ABI,
* making them internal and thus reducing the overall compiled implementation size.
* isFeatureEnabled() public -> _isFeatureEnabled() internal
* isSenderInRole() public -> _isSenderInRole() internal
* isOperatorInRole() public -> _isOperatorInRole() internal
*
* @custom:since 1.1.0
*
* @author Basil Gorin
*/
abstract contract AccessControlCore {
/**
* @dev Privileged addresses with defined roles/permissions
* @dev In the context of ERC20/ERC721 tokens these can be permissions to
* allow minting or burning tokens, transferring on behalf and so on
*
* @dev Maps user address to the permissions bitmask (role), where each bit
* represents a permission
* @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
* represents all possible permissions
* @dev 'This' address mapping represents global features of the smart contract
*
* @dev We keep the mapping private to prevent direct writes to it from the inheriting
* contracts, `getRole()` and `updateRole()` functions should be used instead
*/
mapping(address => uint256) private userRoles;
/**
* @notice Access manager is responsible for assigning the roles to users,
* enabling/disabling global features of the smart contract
* @notice Access manager can add, remove and update user roles,
* remove and update global features
*
* @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features
* @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled
*/
uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000;
/**
* @dev Bitmask representing all the possible permissions (super admin role)
* @dev Has all the bits are enabled (2^256 - 1 value)
*/
uint256 internal constant FULL_PRIVILEGES_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* @notice Thrown when a function is executed by an account that does not have
* the required access permission(s) (role)
*
* @dev This error is used to enforce role-based access control (RBAC) restrictions
*/
error AccessDenied();
/**
* @dev Fired in updateRole() and updateFeatures()
*
* @param by address which has granted/revoked permissions to operator
* @param operator address which was granted/revoked permissions
* @param requested permissions requested
* @param assigned permissions effectively set
*/
event RoleUpdated(address indexed by, address indexed operator, uint256 requested, uint256 assigned);
/**
* @notice Function modifier making a function defined as public behave as restricted
* (so that only a pre-configured set of accounts can execute it)
*
* @param role the role transaction executor is required to have;
* the function throws an "access denied" exception if this condition is not met
*/
modifier restrictedTo(uint256 role) {
// verify the access permission
_requireSenderInRole(role);
// execute the rest of the function
_;
}
/**
* @notice Creates an access control instance, setting the contract owner to have full privileges
*
* @param _owner smart contract owner having full privileges, can be zero
* @param _features initial features mask of the contract, can be zero
*/
constructor(address _owner, uint256 _features) { // visibility modifier is required to be compilable with 0.6.x
// if there is a request to set owner (zero address owner means no owner)
if(_owner != address(0)) {
// grant owner full privileges
__setRole(_owner, FULL_PRIVILEGES_MASK, FULL_PRIVILEGES_MASK);
}
// update initial features bitmask
__setRole(address(this), _features, _features);
}
/**
* @notice Retrieves globally set of features enabled
*
* @dev Effectively reads userRoles role for the contract itself
*
* @return 256-bit bitmask of the features enabled
*/
function features() public view returns(uint256) {
// features are stored in 'this' address mapping of `userRoles`
return getRole(address(this));
}
/**
* @notice Updates set of the globally enabled features (`features`),
* taking into account sender's permissions
*
* @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
* @dev Function is left for backward compatibility with older versions
*
* @param _mask bitmask representing a set of features to enable/disable
*/
function updateFeatures(uint256 _mask) external {
// delegate to internal `_updateRole()`
_updateRole(address(this), _mask);
}
/**
* @notice Reads the permissions (role) for a given user from the `userRoles` mapping
* (privileged addresses with defined roles/permissions)
* @notice In the context of ERC20/ERC721 tokens these can be permissions to
* allow minting or burning tokens, transferring on behalf and so on
*
* @dev Having a simple getter instead of making the mapping public
* allows enforcing the encapsulation of the mapping and protects from
* writing to it directly in the inheriting smart contracts
*
* @param operator address of a user to read permissions for,
* or self address to read global features of the smart contract
*/
function getRole(address operator) public view returns(uint256) {
// read the value from `userRoles` and return
return userRoles[operator];
}
/**
* @notice Updates set of permissions (role) for a given user,
* taking into account sender's permissions.
*
* @dev Setting role to zero is equivalent to removing all the permissions
* @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to
* copying senders' permissions (role) to the user
* @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
*
* ╔════════════════════════════════════════════════════════════════════════╗
* ║ WARNING: RISK OF ACCIDENTAL SELF-REVOKE ║
* ╠════════════════════════════════════════════════════════════════════════╣
* ║ updateRole function is used to add, update, and delete permissions, ║
* ║ as well as to revoke and self-revoke all the permissions ║
* ║ ║
* ║ updateRole(msg.sender, 0) executed by a super admin themselves ║
* ║ revokes super admin permissions forever if there is no other super ║
* ║ admin set prior to updateRole(msg.sender, 0) call ║
* ╚════════════════════════════════════════════════════════════════════════╝
*
* @param operator address of a user to alter permissions for,
* or self address to alter global features of the smart contract
* @param role bitmask representing a set of permissions to
* enable/disable for a user specified
*/
function updateRole(address operator, uint256 role) external {
// delegate to internal `_updateRole()`
_updateRole(operator, role);
}
/**
* @notice Determines the permission bitmask an operator can set on the
* target permission set
* @notice Used to calculate the permission bitmask to be set when requested
* in `updateRole` and `updateFeatures` functions
*
* @dev Calculated based on:
* 1) operator's own permission set read from userRoles[operator]
* 2) target permission set - what is already set on the target
* 3) desired permission set - what do we want set target to
*
* @dev Corner cases:
* 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`:
* `desired` bitset is returned regardless of the `target` permission set value
* (what operator sets is what they get)
* 2) Operator with no permissions (zero bitset):
* `target` bitset is returned regardless of the `desired` value
* (operator has no authority and cannot modify anything)
*
* @dev Example:
* Consider an operator with the permissions bitmask 00001111
* is about to modify the target permission set 01010101
* Operator wants to set that permission set to 00110011
* Based on their role, an operator has the permissions
* to update only lowest 4 bits on the target, meaning that
* high 4 bits of the target set in this example is left
* unchanged and low 4 bits get changed as desired: 01010011
*
* @param operator address of the contract operator which is about to set the permissions
* @param target input set of permissions to operator is going to modify
* @param desired desired set of permissions operator would like to set
* @return resulting set of permissions given operator will set
*/
function _evaluateBy(address operator, uint256 target, uint256 desired) internal view returns (uint256) {
// read operator's permissions
uint256 p = getRole(operator);
// taking into account operator's permissions,
// 1) enable the permissions desired on the `target`
target |= p & desired;
// 2) disable the permissions desired on the `target`
target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired));
// return calculated result
return target;
}
/**
* @notice Ensures that the transaction sender has the required access permission(s) (role)
*
* @dev Reverts with an `AccessDenied` error if the sender does not have the required role
*
* @param required the set of permissions (role) that the transaction sender is required to have
*/
function _requireSenderInRole(uint256 required) internal view {
// check if the transaction has the required permission(s),
// reverting with the "access denied" error if not
_requireAccessCondition(_isSenderInRole(required));
}
/**
* @notice Ensures that a specific condition is met
*
* @dev Reverts with an `AccessDenied` error if the condition is not met
*
* @param condition the condition that needs to be true for the function to proceed
*/
function _requireAccessCondition(bool condition) internal pure {
// check if the condition holds
if(!condition) {
// revert with the "access denied" error if not
revert AccessDenied();
}
}
/**
* @notice Checks if requested set of features is enabled globally on the contract
*
* @param required set of features to check against
* @return true if all the features requested are enabled, false otherwise
*/
function _isFeatureEnabled(uint256 required) internal view returns (bool) {
// delegate call to `__hasRole`, passing `features` property
return __hasRole(features(), required);
}
/**
* @notice Checks if transaction sender `msg.sender` has all the permissions required
*
* @param required set of permissions (role) to check against
* @return true if all the permissions requested are enabled, false otherwise
*/
function _isSenderInRole(uint256 required) internal view returns (bool) {
// delegate call to `isOperatorInRole`, passing transaction sender
return _isOperatorInRole(msg.sender, required);
}
/**
* @notice Checks if operator has all the permissions (role) required
*
* @param operator address of the user to check role for
* @param required set of permissions (role) to check
* @return true if all the permissions requested are enabled, false otherwise
*/
function _isOperatorInRole(address operator, uint256 required) internal view returns (bool) {
// delegate call to `__hasRole`, passing operator's permissions (role)
return __hasRole(getRole(operator), required);
}
/**
* @dev Updates set of permissions (role) for a given user,
* taking into account sender's permissions.
*
* @dev Setting role to zero is equivalent to removing all the permissions
* @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to
* copying senders' permissions (role) to the user
* @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
*
* @param operator address of a user to alter permissions for,
* or self address to alter global features of the smart contract
* @param role bitmask representing a set of permissions to
* enable/disable for a user specified
*/
function _updateRole(address operator, uint256 role) internal {
// caller must have a permission to update user roles
_requireSenderInRole(ROLE_ACCESS_MANAGER);
// evaluate the role and reassign it
__setRole(operator, role, _evaluateBy(msg.sender, getRole(operator), role));
}
/**
* @dev Sets the `assignedRole` role to the operator, logs both `requestedRole` and `actualRole`
*
* @dev Unsafe:
* provides direct write access to `userRoles` mapping without any security checks,
* doesn't verify the executor (msg.sender) permissions,
* must be kept private at all times
*
* @param operator address of a user to alter permissions for,
* or self address to alter global features of the smart contract
* @param requestedRole bitmask representing a set of permissions requested
* to be enabled/disabled for a user specified, used only to be logged into event
* @param assignedRole bitmask representing a set of permissions to
* enable/disable for a user specified, used to update the mapping and to be logged into event
*/
function __setRole(address operator, uint256 requestedRole, uint256 assignedRole) private {
// assign the role to the operator
userRoles[operator] = assignedRole;
// fire an event
emit RoleUpdated(msg.sender, operator, requestedRole, assignedRole);
}
/**
* @dev Checks if role `actual` contains all the permissions required `required`
*
* @param actual existent role
* @param required required role
* @return true if actual has required role (all permissions), false otherwise
*/
function __hasRole(uint256 actual, uint256 required) private pure returns (bool) {
// check the bitmask for the role required and return the result
return actual & required == required;
}
}