Add organization-aware primary key lookups and statement cache
What does this MR do and why?
Adds organization-aware safety to Rails find-by-primary-key calls and to the
ActiveRecord statement cache.
Two pieces land together because the statement cache patch is required for the PK lookup functions to be used safely under connection multiplexing:
-
PostgreSQL lookup functions —
find_<table>_by_id_and_organization_idforprojects,namespaces, andusers. Each function does aWHERE id = $1 AND organization_id = $2fetch, ensuring afindcan never return a record belonging to a different organization. -
OrganizationAwareStatementCache— patches the ActiveRecord statement cache key to include the current organization ID. Without this, a cached prepared statement bound to one organization could be reused for another.
Factories and specs for models that cross organization boundaries are updated to
supply an explicit organization: association where the new constraint requires
it.
References
- Replaces: Application-Level Database Isolation (!225550 - closed)
- Relates to Isolate read queries on Organization sharded mo... (#582272)
How to set up and validate locally
- Run the migrations in this MR:
bundle exec rake db:migrate - Start a Rails console and execute the following statements:
# This works, project id 1 belaongs to organization 1
Project.find(1)
# enable Feature flag
Feature.enable(:data_isolation)
# Now we set Current Organization to another organization and mark it as an isolated org
Current.organization = Organizations::Organization.find_or_create_by!(path: 'my-isolated-org', name: 'My Isolated Org')
Current.organization.mark_as_isolated!
# This will now raise an error because project id 1 does not exists in this new organization
Project.find(1)MR acceptance checklist
Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.