AccessManager.sol 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.0.0) (access/manager/AccessManager.sol)
  3. pragma solidity ^0.8.20;
  4. import {IAccessManager} from "./IAccessManager.sol";
  5. import {IAccessManaged} from "./IAccessManaged.sol";
  6. import {Address} from "../../utils/Address.sol";
  7. import {Context} from "../../utils/Context.sol";
  8. import {Multicall} from "../../utils/Multicall.sol";
  9. import {StorageSlot} from "../../utils/StorageSlot.sol";
  10. import {Math} from "../../utils/math/Math.sol";
  11. import {Time} from "../../utils/types/Time.sol";
  12. /**
  13. * @dev AccessManager is a central contract to store the permissions of a system.
  14. *
  15. * A smart contract under the control of an AccessManager instance is known as a target, and will inherit from the
  16. * {AccessManaged} contract, be connected to this contract as its manager and implement the {AccessManaged-restricted}
  17. * modifier on a set of functions selected to be permissioned. Note that any function without this setup won't be
  18. * effectively restricted.
  19. *
  20. * The restriction rules for such functions are defined in terms of "roles" identified by an `uint64` and scoped
  21. * by target (`address`) and function selectors (`bytes4`). These roles are stored in this contract and can be
  22. * configured by admins (`ADMIN_ROLE` members) after a delay (see {getTargetAdminDelay}).
  23. *
  24. * For each target contract, admins can configure the following without any delay:
  25. *
  26. * * The target's {AccessManaged-authority} via {updateAuthority}.
  27. * * Close or open a target via {setTargetClosed} keeping the permissions intact.
  28. * * The roles that are allowed (or disallowed) to call a given function (identified by its selector) through {setTargetFunctionRole}.
  29. *
  30. * By default every address is member of the `PUBLIC_ROLE` and every target function is restricted to the `ADMIN_ROLE` until configured otherwise.
  31. * Additionally, each role has the following configuration options restricted to this manager's admins:
  32. *
  33. * * A role's admin role via {setRoleAdmin} who can grant or revoke roles.
  34. * * A role's guardian role via {setRoleGuardian} who's allowed to cancel operations.
  35. * * A delay in which a role takes effect after being granted through {setGrantDelay}.
  36. * * A delay of any target's admin action via {setTargetAdminDelay}.
  37. * * A role label for discoverability purposes with {labelRole}.
  38. *
  39. * Any account can be added and removed into any number of these roles by using the {grantRole} and {revokeRole} functions
  40. * restricted to each role's admin (see {getRoleAdmin}).
  41. *
  42. * Since all the permissions of the managed system can be modified by the admins of this instance, it is expected that
  43. * they will be highly secured (e.g., a multisig or a well-configured DAO).
  44. *
  45. * NOTE: This contract implements a form of the {IAuthority} interface, but {canCall} has additional return data so it
  46. * doesn't inherit `IAuthority`. It is however compatible with the `IAuthority` interface since the first 32 bytes of
  47. * the return data are a boolean as expected by that interface.
  48. *
  49. * NOTE: Systems that implement other access control mechanisms (for example using {Ownable}) can be paired with an
  50. * {AccessManager} by transferring permissions (ownership in the case of {Ownable}) directly to the {AccessManager}.
  51. * Users will be able to interact with these contracts through the {execute} function, following the access rules
  52. * registered in the {AccessManager}. Keep in mind that in that context, the msg.sender seen by restricted functions
  53. * will be {AccessManager} itself.
  54. *
  55. * WARNING: When granting permissions over an {Ownable} or {AccessControl} contract to an {AccessManager}, be very
  56. * mindful of the danger associated with functions such as {Ownable-renounceOwnership} or
  57. * {AccessControl-renounceRole}.
  58. */
  59. contract AccessManager is Context, Multicall, IAccessManager {
  60. using StorageSlot for *;
  61. using Time for *;
  62. // Structure that stores the details for a target contract.
  63. struct TargetConfig {
  64. mapping(bytes4 selector => uint64 roleId) allowedRoles;
  65. Time.Delay adminDelay;
  66. bool closed;
  67. }
  68. // Structure that stores the details for a role/account pair. This structures fit into a single slot.
  69. struct Access {
  70. // Timepoint at which the user gets the permission.
  71. // If this is either 0 or in the future, then the role permission is not available.
  72. uint48 since;
  73. // Delay for execution. Only applies to restricted() / execute() calls.
  74. Time.Delay delay;
  75. }
  76. // Structure that stores the details of a role.
  77. struct Role {
  78. // Members of the role.
  79. mapping(address user => Access access) members;
  80. // Admin who can grant or revoke permissions.
  81. uint64 admin;
  82. // Guardian who can cancel operations targeting functions that need this role.
  83. uint64 guardian;
  84. // Delay in which the role takes effect after being granted.
  85. Time.Delay grantDelay;
  86. }
  87. // Structure that stores the details for a scheduled operation. This structure fits into a single slot.
  88. struct Schedule {
  89. // Moment at which the operation can be executed.
  90. uint48 timepoint;
  91. // Operation nonce to allow third-party contracts to identify the operation.
  92. uint32 nonce;
  93. }
  94. uint64 public constant ADMIN_ROLE = type(uint64).min; // 0
  95. uint64 public constant PUBLIC_ROLE = type(uint64).max; // 2**64-1
  96. mapping(address target => TargetConfig mode) private _targets;
  97. mapping(uint64 roleId => Role) private _roles;
  98. mapping(bytes32 operationId => Schedule) private _schedules;
  99. // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessManager.executionId")) - 1)) & ~bytes32(uint256(0xff))
  100. bytes32 private constant ACCESS_MANAGER_EXECUTION_ID_STORAGE =
  101. 0xcd345b53ed666c7ef33210216f8d27ceee269613372bda4998fd5fcd86a8b100;
  102. /**
  103. * @dev Check that the caller is authorized to perform the operation.
  104. * See {AccessManager} description for a detailed breakdown of the authorization logic.
  105. */
  106. modifier onlyAuthorized() {
  107. _checkAuthorized();
  108. _;
  109. }
  110. constructor(address initialAdmin) {
  111. if (initialAdmin == address(0)) {
  112. revert AccessManagerInvalidInitialAdmin(address(0));
  113. }
  114. // admin is active immediately and without any execution delay.
  115. _grantRole(ADMIN_ROLE, initialAdmin, 0, 0);
  116. }
  117. // =================================================== GETTERS ====================================================
  118. /// @inheritdoc IAccessManager
  119. function canCall(
  120. address caller,
  121. address target,
  122. bytes4 selector
  123. ) public view virtual returns (bool immediate, uint32 delay) {
  124. if (isTargetClosed(target)) {
  125. return (false, 0);
  126. } else if (caller == address(this)) {
  127. // Caller is AccessManager, this means the call was sent through {execute} and it already checked
  128. // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
  129. return (_isExecuting(target, selector), 0);
  130. } else {
  131. uint64 roleId = getTargetFunctionRole(target, selector);
  132. (bool isMember, uint32 currentDelay) = hasRole(roleId, caller);
  133. return isMember ? (currentDelay == 0, currentDelay) : (false, 0);
  134. }
  135. }
  136. /// @inheritdoc IAccessManager
  137. function expiration() public view virtual returns (uint32) {
  138. return 1 weeks;
  139. }
  140. /// @inheritdoc IAccessManager
  141. function minSetback() public view virtual returns (uint32) {
  142. return 5 days;
  143. }
  144. /// @inheritdoc IAccessManager
  145. function isTargetClosed(address target) public view virtual returns (bool) {
  146. return _targets[target].closed;
  147. }
  148. /// @inheritdoc IAccessManager
  149. function getTargetFunctionRole(address target, bytes4 selector) public view virtual returns (uint64) {
  150. return _targets[target].allowedRoles[selector];
  151. }
  152. /// @inheritdoc IAccessManager
  153. function getTargetAdminDelay(address target) public view virtual returns (uint32) {
  154. return _targets[target].adminDelay.get();
  155. }
  156. /// @inheritdoc IAccessManager
  157. function getRoleAdmin(uint64 roleId) public view virtual returns (uint64) {
  158. return _roles[roleId].admin;
  159. }
  160. /// @inheritdoc IAccessManager
  161. function getRoleGuardian(uint64 roleId) public view virtual returns (uint64) {
  162. return _roles[roleId].guardian;
  163. }
  164. /// @inheritdoc IAccessManager
  165. function getRoleGrantDelay(uint64 roleId) public view virtual returns (uint32) {
  166. return _roles[roleId].grantDelay.get();
  167. }
  168. /// @inheritdoc IAccessManager
  169. function getAccess(
  170. uint64 roleId,
  171. address account
  172. ) public view virtual returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect) {
  173. Access storage access = _roles[roleId].members[account];
  174. since = access.since;
  175. (currentDelay, pendingDelay, effect) = access.delay.getFull();
  176. return (since, currentDelay, pendingDelay, effect);
  177. }
  178. /// @inheritdoc IAccessManager
  179. function hasRole(
  180. uint64 roleId,
  181. address account
  182. ) public view virtual returns (bool isMember, uint32 executionDelay) {
  183. if (roleId == PUBLIC_ROLE) {
  184. return (true, 0);
  185. } else {
  186. (uint48 hasRoleSince, uint32 currentDelay, , ) = getAccess(roleId, account);
  187. return (hasRoleSince != 0 && hasRoleSince <= Time.timestamp(), currentDelay);
  188. }
  189. }
  190. // =============================================== ROLE MANAGEMENT ===============================================
  191. /// @inheritdoc IAccessManager
  192. function labelRole(uint64 roleId, string calldata label) public virtual onlyAuthorized {
  193. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  194. revert AccessManagerLockedRole(roleId);
  195. }
  196. emit RoleLabel(roleId, label);
  197. }
  198. /// @inheritdoc IAccessManager
  199. function grantRole(uint64 roleId, address account, uint32 executionDelay) public virtual onlyAuthorized {
  200. _grantRole(roleId, account, getRoleGrantDelay(roleId), executionDelay);
  201. }
  202. /// @inheritdoc IAccessManager
  203. function revokeRole(uint64 roleId, address account) public virtual onlyAuthorized {
  204. _revokeRole(roleId, account);
  205. }
  206. /// @inheritdoc IAccessManager
  207. function renounceRole(uint64 roleId, address callerConfirmation) public virtual {
  208. if (callerConfirmation != _msgSender()) {
  209. revert AccessManagerBadConfirmation();
  210. }
  211. _revokeRole(roleId, callerConfirmation);
  212. }
  213. /// @inheritdoc IAccessManager
  214. function setRoleAdmin(uint64 roleId, uint64 admin) public virtual onlyAuthorized {
  215. _setRoleAdmin(roleId, admin);
  216. }
  217. /// @inheritdoc IAccessManager
  218. function setRoleGuardian(uint64 roleId, uint64 guardian) public virtual onlyAuthorized {
  219. _setRoleGuardian(roleId, guardian);
  220. }
  221. /// @inheritdoc IAccessManager
  222. function setGrantDelay(uint64 roleId, uint32 newDelay) public virtual onlyAuthorized {
  223. _setGrantDelay(roleId, newDelay);
  224. }
  225. /**
  226. * @dev Internal version of {grantRole} without access control. Returns true if the role was newly granted.
  227. *
  228. * Emits a {RoleGranted} event.
  229. */
  230. function _grantRole(
  231. uint64 roleId,
  232. address account,
  233. uint32 grantDelay,
  234. uint32 executionDelay
  235. ) internal virtual returns (bool) {
  236. if (roleId == PUBLIC_ROLE) {
  237. revert AccessManagerLockedRole(roleId);
  238. }
  239. bool newMember = _roles[roleId].members[account].since == 0;
  240. uint48 since;
  241. if (newMember) {
  242. since = Time.timestamp() + grantDelay;
  243. _roles[roleId].members[account] = Access({since: since, delay: executionDelay.toDelay()});
  244. } else {
  245. // No setback here. Value can be reset by doing revoke + grant, effectively allowing the admin to perform
  246. // any change to the execution delay within the duration of the role admin delay.
  247. (_roles[roleId].members[account].delay, since) = _roles[roleId].members[account].delay.withUpdate(
  248. executionDelay,
  249. 0
  250. );
  251. }
  252. emit RoleGranted(roleId, account, executionDelay, since, newMember);
  253. return newMember;
  254. }
  255. /**
  256. * @dev Internal version of {revokeRole} without access control. This logic is also used by {renounceRole}.
  257. * Returns true if the role was previously granted.
  258. *
  259. * Emits a {RoleRevoked} event if the account had the role.
  260. */
  261. function _revokeRole(uint64 roleId, address account) internal virtual returns (bool) {
  262. if (roleId == PUBLIC_ROLE) {
  263. revert AccessManagerLockedRole(roleId);
  264. }
  265. if (_roles[roleId].members[account].since == 0) {
  266. return false;
  267. }
  268. delete _roles[roleId].members[account];
  269. emit RoleRevoked(roleId, account);
  270. return true;
  271. }
  272. /**
  273. * @dev Internal version of {setRoleAdmin} without access control.
  274. *
  275. * Emits a {RoleAdminChanged} event.
  276. *
  277. * NOTE: Setting the admin role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
  278. * anyone to set grant or revoke such role.
  279. */
  280. function _setRoleAdmin(uint64 roleId, uint64 admin) internal virtual {
  281. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  282. revert AccessManagerLockedRole(roleId);
  283. }
  284. _roles[roleId].admin = admin;
  285. emit RoleAdminChanged(roleId, admin);
  286. }
  287. /**
  288. * @dev Internal version of {setRoleGuardian} without access control.
  289. *
  290. * Emits a {RoleGuardianChanged} event.
  291. *
  292. * NOTE: Setting the guardian role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
  293. * anyone to cancel any scheduled operation for such role.
  294. */
  295. function _setRoleGuardian(uint64 roleId, uint64 guardian) internal virtual {
  296. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  297. revert AccessManagerLockedRole(roleId);
  298. }
  299. _roles[roleId].guardian = guardian;
  300. emit RoleGuardianChanged(roleId, guardian);
  301. }
  302. /**
  303. * @dev Internal version of {setGrantDelay} without access control.
  304. *
  305. * Emits a {RoleGrantDelayChanged} event.
  306. */
  307. function _setGrantDelay(uint64 roleId, uint32 newDelay) internal virtual {
  308. if (roleId == PUBLIC_ROLE) {
  309. revert AccessManagerLockedRole(roleId);
  310. }
  311. uint48 effect;
  312. (_roles[roleId].grantDelay, effect) = _roles[roleId].grantDelay.withUpdate(newDelay, minSetback());
  313. emit RoleGrantDelayChanged(roleId, newDelay, effect);
  314. }
  315. // ============================================= FUNCTION MANAGEMENT ==============================================
  316. /// @inheritdoc IAccessManager
  317. function setTargetFunctionRole(
  318. address target,
  319. bytes4[] calldata selectors,
  320. uint64 roleId
  321. ) public virtual onlyAuthorized {
  322. for (uint256 i = 0; i < selectors.length; ++i) {
  323. _setTargetFunctionRole(target, selectors[i], roleId);
  324. }
  325. }
  326. /**
  327. * @dev Internal version of {setTargetFunctionRole} without access control.
  328. *
  329. * Emits a {TargetFunctionRoleUpdated} event.
  330. */
  331. function _setTargetFunctionRole(address target, bytes4 selector, uint64 roleId) internal virtual {
  332. _targets[target].allowedRoles[selector] = roleId;
  333. emit TargetFunctionRoleUpdated(target, selector, roleId);
  334. }
  335. /// @inheritdoc IAccessManager
  336. function setTargetAdminDelay(address target, uint32 newDelay) public virtual onlyAuthorized {
  337. _setTargetAdminDelay(target, newDelay);
  338. }
  339. /**
  340. * @dev Internal version of {setTargetAdminDelay} without access control.
  341. *
  342. * Emits a {TargetAdminDelayUpdated} event.
  343. */
  344. function _setTargetAdminDelay(address target, uint32 newDelay) internal virtual {
  345. uint48 effect;
  346. (_targets[target].adminDelay, effect) = _targets[target].adminDelay.withUpdate(newDelay, minSetback());
  347. emit TargetAdminDelayUpdated(target, newDelay, effect);
  348. }
  349. // =============================================== MODE MANAGEMENT ================================================
  350. /// @inheritdoc IAccessManager
  351. function setTargetClosed(address target, bool closed) public virtual onlyAuthorized {
  352. _setTargetClosed(target, closed);
  353. }
  354. /**
  355. * @dev Set the closed flag for a contract. This is an internal setter with no access restrictions.
  356. *
  357. * Emits a {TargetClosed} event.
  358. */
  359. function _setTargetClosed(address target, bool closed) internal virtual {
  360. _targets[target].closed = closed;
  361. emit TargetClosed(target, closed);
  362. }
  363. // ============================================== DELAYED OPERATIONS ==============================================
  364. /// @inheritdoc IAccessManager
  365. function getSchedule(bytes32 id) public view virtual returns (uint48) {
  366. uint48 timepoint = _schedules[id].timepoint;
  367. return _isExpired(timepoint) ? 0 : timepoint;
  368. }
  369. /// @inheritdoc IAccessManager
  370. function getNonce(bytes32 id) public view virtual returns (uint32) {
  371. return _schedules[id].nonce;
  372. }
  373. /// @inheritdoc IAccessManager
  374. function schedule(
  375. address target,
  376. bytes calldata data,
  377. uint48 when
  378. ) public virtual returns (bytes32 operationId, uint32 nonce) {
  379. address caller = _msgSender();
  380. // Fetch restrictions that apply to the caller on the targeted function
  381. (, uint32 setback) = _canCallExtended(caller, target, data);
  382. uint48 minWhen = Time.timestamp() + setback;
  383. // If call with delay is not authorized, or if requested timing is too soon, revert
  384. if (setback == 0 || (when > 0 && when < minWhen)) {
  385. revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
  386. }
  387. // Reuse variable due to stack too deep
  388. when = uint48(Math.max(when, minWhen)); // cast is safe: both inputs are uint48
  389. // If caller is authorised, schedule operation
  390. operationId = hashOperation(caller, target, data);
  391. _checkNotScheduled(operationId);
  392. unchecked {
  393. // It's not feasible to overflow the nonce in less than 1000 years
  394. nonce = _schedules[operationId].nonce + 1;
  395. }
  396. _schedules[operationId].timepoint = when;
  397. _schedules[operationId].nonce = nonce;
  398. emit OperationScheduled(operationId, nonce, when, caller, target, data);
  399. // Using named return values because otherwise we get stack too deep
  400. }
  401. /**
  402. * @dev Reverts if the operation is currently scheduled and has not expired.
  403. *
  404. * NOTE: This function was introduced due to stack too deep errors in schedule.
  405. */
  406. function _checkNotScheduled(bytes32 operationId) private view {
  407. uint48 prevTimepoint = _schedules[operationId].timepoint;
  408. if (prevTimepoint != 0 && !_isExpired(prevTimepoint)) {
  409. revert AccessManagerAlreadyScheduled(operationId);
  410. }
  411. }
  412. /// @inheritdoc IAccessManager
  413. // Reentrancy is not an issue because permissions are checked on msg.sender. Additionally,
  414. // _consumeScheduledOp guarantees a scheduled operation is only executed once.
  415. // slither-disable-next-line reentrancy-no-eth
  416. function execute(address target, bytes calldata data) public payable virtual returns (uint32) {
  417. address caller = _msgSender();
  418. // Fetch restrictions that apply to the caller on the targeted function
  419. (bool immediate, uint32 setback) = _canCallExtended(caller, target, data);
  420. // If call is not authorized, revert
  421. if (!immediate && setback == 0) {
  422. revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
  423. }
  424. bytes32 operationId = hashOperation(caller, target, data);
  425. uint32 nonce;
  426. // If caller is authorised, check operation was scheduled early enough
  427. // Consume an available schedule even if there is no currently enforced delay
  428. if (setback != 0 || getSchedule(operationId) != 0) {
  429. nonce = _consumeScheduledOp(operationId);
  430. }
  431. // Mark the target and selector as authorised
  432. bytes32 executionIdBefore = ACCESS_MANAGER_EXECUTION_ID_STORAGE.asBytes32().tload();
  433. ACCESS_MANAGER_EXECUTION_ID_STORAGE.asBytes32().tstore(_hashExecutionId(target, _checkSelector(data)));
  434. // Perform call
  435. Address.functionCallWithValue(target, data, msg.value);
  436. // Reset execute identifier
  437. ACCESS_MANAGER_EXECUTION_ID_STORAGE.asBytes32().tstore(executionIdBefore);
  438. return nonce;
  439. }
  440. /// @inheritdoc IAccessManager
  441. function cancel(address caller, address target, bytes calldata data) public virtual returns (uint32) {
  442. address msgsender = _msgSender();
  443. bytes4 selector = _checkSelector(data);
  444. bytes32 operationId = hashOperation(caller, target, data);
  445. if (_schedules[operationId].timepoint == 0) {
  446. revert AccessManagerNotScheduled(operationId);
  447. } else if (caller != msgsender) {
  448. // calls can only be canceled by the account that scheduled them, a global admin, or by a guardian of the required role.
  449. (bool isAdmin, ) = hasRole(ADMIN_ROLE, msgsender);
  450. (bool isGuardian, ) = hasRole(getRoleGuardian(getTargetFunctionRole(target, selector)), msgsender);
  451. if (!isAdmin && !isGuardian) {
  452. revert AccessManagerUnauthorizedCancel(msgsender, caller, target, selector);
  453. }
  454. }
  455. delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
  456. uint32 nonce = _schedules[operationId].nonce;
  457. emit OperationCanceled(operationId, nonce);
  458. return nonce;
  459. }
  460. /// @inheritdoc IAccessManager
  461. function consumeScheduledOp(address caller, bytes calldata data) public virtual {
  462. address target = _msgSender();
  463. if (IAccessManaged(target).isConsumingScheduledOp() != IAccessManaged.isConsumingScheduledOp.selector) {
  464. revert AccessManagerUnauthorizedConsume(target);
  465. }
  466. _consumeScheduledOp(hashOperation(caller, target, data));
  467. }
  468. /**
  469. * @dev Internal variant of {consumeScheduledOp} that operates on bytes32 operationId.
  470. *
  471. * Returns the nonce of the scheduled operation that is consumed.
  472. */
  473. function _consumeScheduledOp(bytes32 operationId) internal virtual returns (uint32) {
  474. uint48 timepoint = _schedules[operationId].timepoint;
  475. uint32 nonce = _schedules[operationId].nonce;
  476. if (timepoint == 0) {
  477. revert AccessManagerNotScheduled(operationId);
  478. } else if (timepoint > Time.timestamp()) {
  479. revert AccessManagerNotReady(operationId);
  480. } else if (_isExpired(timepoint)) {
  481. revert AccessManagerExpired(operationId);
  482. }
  483. delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
  484. emit OperationExecuted(operationId, nonce);
  485. return nonce;
  486. }
  487. /// @inheritdoc IAccessManager
  488. function hashOperation(address caller, address target, bytes calldata data) public view virtual returns (bytes32) {
  489. return keccak256(abi.encode(caller, target, data));
  490. }
  491. // ==================================================== OTHERS ====================================================
  492. /// @inheritdoc IAccessManager
  493. function updateAuthority(address target, address newAuthority) public virtual onlyAuthorized {
  494. IAccessManaged(target).setAuthority(newAuthority);
  495. }
  496. // ================================================= ADMIN LOGIC ==================================================
  497. /**
  498. * @dev Check if the current call is authorized according to admin and roles logic.
  499. *
  500. * WARNING: Carefully review the considerations of {AccessManaged-restricted} since they apply to this modifier.
  501. */
  502. function _checkAuthorized() private {
  503. address caller = _msgSender();
  504. (bool immediate, uint32 delay) = _canCallSelf(caller, _msgData());
  505. if (!immediate) {
  506. if (delay == 0) {
  507. (, uint64 requiredRole, ) = _getAdminRestrictions(_msgData());
  508. revert AccessManagerUnauthorizedAccount(caller, requiredRole);
  509. } else {
  510. _consumeScheduledOp(hashOperation(caller, address(this), _msgData()));
  511. }
  512. }
  513. }
  514. /**
  515. * @dev Get the admin restrictions of a given function call based on the function and arguments involved.
  516. *
  517. * Returns:
  518. * - bool restricted: does this data match a restricted operation
  519. * - uint64: which role is this operation restricted to
  520. * - uint32: minimum delay to enforce for that operation (max between operation's delay and admin's execution delay)
  521. */
  522. function _getAdminRestrictions(
  523. bytes calldata data
  524. ) private view returns (bool adminRestricted, uint64 roleAdminId, uint32 executionDelay) {
  525. if (data.length < 4) {
  526. return (false, 0, 0);
  527. }
  528. bytes4 selector = _checkSelector(data);
  529. // Restricted to ADMIN with no delay beside any execution delay the caller may have
  530. if (
  531. selector == this.labelRole.selector ||
  532. selector == this.setRoleAdmin.selector ||
  533. selector == this.setRoleGuardian.selector ||
  534. selector == this.setGrantDelay.selector ||
  535. selector == this.setTargetAdminDelay.selector
  536. ) {
  537. return (true, ADMIN_ROLE, 0);
  538. }
  539. // Restricted to ADMIN with the admin delay corresponding to the target
  540. if (
  541. selector == this.updateAuthority.selector ||
  542. selector == this.setTargetClosed.selector ||
  543. selector == this.setTargetFunctionRole.selector
  544. ) {
  545. // First argument is a target.
  546. address target = abi.decode(data[0x04:0x24], (address));
  547. uint32 delay = getTargetAdminDelay(target);
  548. return (true, ADMIN_ROLE, delay);
  549. }
  550. // Restricted to that role's admin with no delay beside any execution delay the caller may have.
  551. if (selector == this.grantRole.selector || selector == this.revokeRole.selector) {
  552. // First argument is a roleId.
  553. uint64 roleId = abi.decode(data[0x04:0x24], (uint64));
  554. return (true, getRoleAdmin(roleId), 0);
  555. }
  556. return (false, getTargetFunctionRole(address(this), selector), 0);
  557. }
  558. // =================================================== HELPERS ====================================================
  559. /**
  560. * @dev An extended version of {canCall} for internal usage that checks {_canCallSelf}
  561. * when the target is this contract.
  562. *
  563. * Returns:
  564. * - bool immediate: whether the operation can be executed immediately (with no delay)
  565. * - uint32 delay: the execution delay
  566. */
  567. function _canCallExtended(
  568. address caller,
  569. address target,
  570. bytes calldata data
  571. ) private view returns (bool immediate, uint32 delay) {
  572. if (target == address(this)) {
  573. return _canCallSelf(caller, data);
  574. } else {
  575. return data.length < 4 ? (false, 0) : canCall(caller, target, _checkSelector(data));
  576. }
  577. }
  578. /**
  579. * @dev A version of {canCall} that checks for restrictions in this contract.
  580. */
  581. function _canCallSelf(address caller, bytes calldata data) private view returns (bool immediate, uint32 delay) {
  582. if (data.length < 4) {
  583. return (false, 0);
  584. }
  585. if (caller == address(this)) {
  586. // Caller is AccessManager, this means the call was sent through {execute} and it already checked
  587. // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
  588. return (_isExecuting(address(this), _checkSelector(data)), 0);
  589. }
  590. (bool adminRestricted, uint64 roleId, uint32 operationDelay) = _getAdminRestrictions(data);
  591. // isTragetClosed apply to non-admin-restricted function
  592. if (!adminRestricted && isTargetClosed(address(this))) {
  593. return (false, 0);
  594. }
  595. (bool inRole, uint32 executionDelay) = hasRole(roleId, caller);
  596. if (!inRole) {
  597. return (false, 0);
  598. }
  599. // downcast is safe because both options are uint32
  600. delay = uint32(Math.max(operationDelay, executionDelay));
  601. return (delay == 0, delay);
  602. }
  603. /**
  604. * @dev Returns true if a call with `target` and `selector` is being executed via {executed}.
  605. */
  606. function _isExecuting(address target, bytes4 selector) private view returns (bool) {
  607. return ACCESS_MANAGER_EXECUTION_ID_STORAGE.asBytes32().tload() == _hashExecutionId(target, selector);
  608. }
  609. /**
  610. * @dev Returns true if a schedule timepoint is past its expiration deadline.
  611. */
  612. function _isExpired(uint48 timepoint) private view returns (bool) {
  613. return timepoint + expiration() <= Time.timestamp();
  614. }
  615. /**
  616. * @dev Extracts the selector from calldata. Panics if data is not at least 4 bytes
  617. */
  618. function _checkSelector(bytes calldata data) private pure returns (bytes4) {
  619. return bytes4(data[0:4]);
  620. }
  621. /**
  622. * @dev Hashing function for execute protection
  623. */
  624. function _hashExecutionId(address target, bytes4 selector) private pure returns (bytes32) {
  625. return keccak256(abi.encode(target, selector));
  626. }
  627. }