Repository navigation
fix: invalidate cached permission lists when user group memberships change #7938
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,19 +2,30 @@ | |
|
|
||
| import uuid_utils.compat as uuid | ||
| from collections import defaultdict | ||
| from django.core.cache import cache | ||
| from django.db import transaction | ||
| from django.db.models import Count | ||
| from django.utils.translation import gettext_lazy as _ | ||
| from rest_framework import serializers | ||
|
|
||
| from common.auth.constants.role_constants import RoleConstants | ||
| from common.constants.cache_version import Cache_Version | ||
| from common.database_model_manage.database_model_manage import DatabaseModelManage | ||
| from common.db.search import page_search | ||
| from common.exception.app_exception import AppApiException, NotFound404 | ||
| from system_manage.models import UserGroup, UserGroupRelation | ||
| from users.models.user_group import SystemUserGroup, SystemUserGroupRelation | ||
|
|
||
|
|
||
| def _clear_permission_cache(user_ids): | ||
| """Invalidate the cached permission list for users whose group membership changed.""" | ||
| if not user_ids: | ||
| return | ||
| version = Cache_Version.PERMISSION_LIST.get_version() | ||
| for user_id in user_ids: | ||
| cache.delete(Cache_Version.PERMISSION_LIST.get_key(user_id=user_id), version=version) | ||
|
|
||
|
|
||
| @transaction.atomic | ||
| def add_or_edit_user_group_relation(user, user_group_ids): | ||
| UserGroupRelation.objects.filter(user=user).delete() | ||
|
|
@@ -99,7 +110,11 @@ def delete(self, *, with_valid=True): | |
| if with_valid: | ||
| self.is_valid(raise_exception=True) | ||
|
|
||
| member_user_ids = list( | ||
| SystemUserGroupRelation.objects.filter(group_id=self.group.id).values_list("user_id", flat=True) | ||
| ) | ||
| self.group.delete() | ||
| _clear_permission_cache(member_user_ids) | ||
| return True | ||
|
|
||
| class Query(serializers.Serializer): | ||
|
|
@@ -181,6 +196,7 @@ def add_member(self, with_valid=True): | |
| for user_id in to_add | ||
| ] | ||
| ) | ||
| _clear_permission_cache(to_add) | ||
| return True | ||
|
|
||
|
|
||
|
|
@@ -206,11 +222,14 @@ def remove_member(self, with_valid=True): | |
| self.is_valid(raise_exception=True) | ||
| data = self.validated_data | ||
| relation_ids = data["group_relation_ids"] | ||
| SystemUserGroupRelation.objects.filter( | ||
| relations = SystemUserGroupRelation.objects.filter( | ||
| id__in=relation_ids, | ||
| group_id=data["id"], | ||
| group__workspace_id=data["workspace_id"], | ||
| ).delete() | ||
| ) | ||
| user_ids = list(relations.values_list("user_id", flat=True)) | ||
| relations.delete() | ||
| _clear_permission_cache(user_ids) | ||
| return True | ||
|
|
||
|
|
||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Overall the diff is syntactically fine, but there are a few correctness and performance concerns. Critical issues
Performance / optimization
Other checks
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here's my review of the code snippet:
Context assumption: This appears to be inside
set_user_groups(user_id, instance)in a Django project, right after a database query/update (for group_id in user_group_ids) and beforereturn None.Issues / Observations
1. Cache key/version semantics — likely bug or at least fragile
get_version()is called twice at different times (once here, once wherever readers call it). If the version changes between your read and delete, you'll delete the wrong entry. Consider whether this should be a bump (increment version) rather than a delete, which is generally safer for cache invalidation across namespaces.2. Missing exception handling
A Redis/Memcached failure will raise and abort
set_user_groupseven though the DB state is already consistent. Consider:Or use a wrapper that swallows/logs cache errors.
3. Placement / transaction safety
set_user_groupsruns inside a DB transaction, deleting the cache before commit can allow another request to repopulate the cache with stale data (read-your-writes race). Prefertransaction.on_commit(lambda: cache.delete(...)).return None, confirm there are no early returns above that would bypass invalidation. It'd be cleaner to put invalidation as part of a single exit path.4. Redundant
return NoneImplicit in Python; harmless but unnecessary. Minor style.
5. Naming / typos
Cache_Versionuses non-PEP-8 casing (should beCacheVersionif it's a class/enum).PERMISSION_LIST.get_key(user_id=user_id)actually scopes byuser_id— otherwise you'd be nuking a shared key for all users, which would be a correctness/perf concern.6. No-op write when nothing changed
If
user_group_idsis empty or unchanged, the delete still fires. Ifset_user_groupsis called frequently, consider skipping invalidation when the group set didn't change (compare before/after), to reduce cache churn.7. Concurrency
Multiple workers may call this concurrently; that's fine for a single-key delete, but if the reader side does
get → miss → recompute → set, you should verify the recompute path also reads the current version to avoid resurrecting stale entries.Suggested revision
(Only wrap in
on_commitif already within a transaction; otherwise call directly.)Summary: The change is functionally reasonable but has three real risks — version race, unhandled cache exceptions, and pre-commit invalidation. Address those and it's solid.