0

I'm trying to generalize some logic to do some manipulation to a ActiveRecord::Relation. Issue is that the aim is to prevent authorization issues, so the flag needs to be set whenever a new ActiveRecord::Relation is instantiated or changed, but I'm not sure how to access the ActiveRecord::Relation data. I think some pagination gems might have a solution, but unsure.

Specific issue is that for Pundit we use something like:

policy_scope(Model)

Ignoring the specifics of exactly how policy_scope works (as it's pretty flexible), it might modify the query to use something like:

Model.where(user_id: current_user.id)

And yes, some care is needed to ensure it doesn't perform a union rather than an intersect on the ids, but that is another matter and handled within the policy itself.

To scope a Model or database query in general to a specific scope. I'd like to add a check on that to ensure and verify that all database queries are scoped. A way this could be done would be to add a flag of some sort to the query itself automatically an unflag it if is scoped, with an error being generated if the query is ran while it is flagged.

THe problem trying to solved here is that it can be very problematic if certain database queries are not scoped when it comes to multi-tenanting and other use cases.

Nuclearman
  • 5,029
  • 1
  • 19
  • 35
  • Can you show some code. What does authorization have to do with `ActiveRecord::Relation` and pagination? – Alex Mar 27 '22 at 21:46
  • @Alex Just noticed your reply. Updated the question with additional details. – Nuclearman Mar 31 '22 at 13:11
  • pundit has a controller level check to verify your're authorizing models on every action https://github.com/varvet/pundit#ensuring-policies-and-scopes-are-used. I don't know of a way to do that with ActiveRecord; maybe a patch somewhere here https://github.com/rails/rails/blob/v7.0.2.3/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb#L62 to check for scope. It also depends on the kind of multi-tenant setup you have. Easiest option is to use pundits `verify_authorized` and don't use methods like `unscope` and `rewhere`. – Alex Apr 03 '22 at 10:42
  • Sadly the pundit check only checks if it's been used at least once (which is certainly better than nothing, but not far enough in my mind), not that it is always used. Though the patch location is interesting. Will look into. – Nuclearman Apr 04 '22 at 12:47

0 Answers0