Loading
Add a cop that flags can? called on an object
Description of the proposal
Adds Gitlab/Authz/UseAbilityAllowed, which flags can? called on an object, such as current_user.can?(:read_project, project), and suggests Ability.allowed?(current_user, :read_project, project).
User#can? and PolicyActor#can? only call Ability.allowed?. We're removing them so models stop carrying permission logic, and the existing callers are being moved in a series of MRs. New callers keep landing in the meantime. This cop stops them and can rewrite the remaining calls with rubocop -A.
How it behaves:
- Applies to
app/andlib/for CE, EE and JH. Policy files are excluded, becauseGitlab/Authz/DisallowAbilityAllowedalready covers them and the fix there is the barecan?helper. - Autocorrects
x.can?(...)toAbility.allowed?(x, ...). The autocorrect is unsafe (SafeAutoCorrect: false) because the cop can't see the receiver's type. - Flags
x&.can?(...)but doesn't correct it.Ability.allowed?evaluates the policy for aniluser, where&.can?returnednil, so someone needs to check the anonymous result first. - Doesn't flag calls that aren't
User#can?orPolicyActor#can?:- calls on a constant, such as
::Users::Anonymous.can?; - calls on a policy object, such as
SomePolicy.new(...).can?orpolicy_for(...).can?; - calls with three positional arguments, such as
presenter.can?(user, ability, subject); - the bare
can?(user, ability, subject)helper.
- calls on a constant, such as
- Known limitation: the autocorrect drops a comment placed between the receiver and
.can?.
Existing offenses (452 files) are in .rubocop_todo/gitlab/authz/use_ability_allowed.yml, which the generator put in a grace period.
Check-list
- Make sure this MR enables a static analysis check rule for new usage but ignores current offenses.
- Mention this proposal in the relevant Slack channels (e.g.
#development,#backend,#frontend). - If there is a choice to make between two potential styles, set up an emoji vote in the MR: not applicable, there's one style.
- The MR doesn't have significant objections, and is getting a majority of
👍 vs👎 (remember that we don't need to reach a consensus). - (If applicable) One style is getting a majority of vote (compared to the other choice): not applicable.
- (If applicable) Update the MR with the chosen style: not applicable.
- Create a follow-up issue to fix the current offenses as a separate iteration: the fixes are already in progress under #638221 (closed).
- Follow the review process as usual.
- Once approved and merged by a maintainer, mention it again:
- In the relevant Slack channels (e.g.
#development,#backend,#frontend). - (Optional depending on the impact of the change) In the Engineering Week in Review.
- In the relevant Slack channels (e.g.