Draft: Add organization isolation scopes using Rails ActiveRecord scopes
What does this MR do and why?
This MR adds organization isolation using Rails default scopes. This approach automatically applies organization filtering to all queries without requiring explicit scope calls.
Approach
We define a default scope on models that have organization sharding keys. This ensures that whenever a query is executed on an organization-sharded model, it automatically includes the organization filter based on Current.organization.
Example Usage
# Automatic scoping - no explicit scope call needed
Current.organization = organization
Project.all # Automatically includes WHERE organization_id = X
# Explicit scoping still available
Project.in_organization(organization)
Project.in_organization_id(organization.id)
# Bypass scoping
Gitlab::Database::Organizations::ScopeHelper.without_organization_scope do
Project.all # Returns all projects regardless of Current.organization
end
Benefits
- Automatic: All queries are automatically scoped without code changes
- Transparent: Works seamlessly with existing code
- Clarity: Scopes are explicit and easy to understand
- Maintainability: No AST manipulation required
- Performance: Direct WHERE clause addition without query parsing
- Testability: Easier to test scoping behavior
- Flexibility: Can be combined with other scopes and conditions
Related to
MR acceptance checklist
Evaluate this MR against the MR acceptance checklist.
Edited by Rutger Wessels