Repository navigation
refactor: improve cache handling for chat user operations and enhance tests - #8194
Conversation
|
|
||
| class ResourceAuthorizationIncludeChildrenTests(SimpleTestCase): | ||
| """GHSA-223f-r4v5-8782: include_children 授权不能信任客户端传入的 folder_ids""" | ||
|
|
There was a problem hiding this comment.
Here is an analysis of the provided code snippet, focusing on test logic, framework usage, and potential edge cases.
1. Analysis of Cache_Version Import
Potential Issue: The test relies on a custom wrapper or specific structure for cache keys (Cache_Version.APPLICATION_THIRD_PARTY.value).
- Check: Ensure that
ChatUserSerializer.delete()and.batch_delete()use the exact same key generation logic (prefix, versioning strategy) as the test setup. If the serializer uses a different default version or namespace, the test will pass incorrectly (false negative) because it checks against the wrong key, or fail if they match accidentally but diverge in future changes. - Suggestion: Consider extracting the cache key generation into a helper method used by both the serializer and the test to ensure they are always synchronized.
2. Test Coverage Gaps
Missing Edge Cases:
- Batch Delete with Invalid IDs:
test_batch_delete_removes_third_party_user_cacheonly tests valid IDs. It does not verify behavior whenidscontains non-existent users, mixed valid/invalid IDs, or empty lists. Ensurebatch_deletehandles these gracefully without raising unexpected exceptions or leaving stale caches for valid entries. - Concurrent Deletes: While hard to unit test cleanly, ensure the cache invalidation inside
delete()is not race-condition prone (e.g., invalidating before DB commit vs after). - Multiple Users: The batch delete test only uses one user. Adding a second user would better validate loop logic inside
batch_delete.
3. Optimization & Best Practices
A. Use self.addCleanup or Assert Invalidation Instead of Manual Setup
Instead of manually setting the cache in setUp, you could assert the cache was deleted. However, current approach is fine. Optimization:
Use django.test.utils.override_settings if caching behavior depends on settings, though likely unnecessary here.
B. Avoid String Concatenation F-Strings in Cache Keys (If Performance Critical)
# Current: Likely fine for tests
self.cache_key = self.get_key(f"chat_user_{self.user.username}")Ensure self.get_key correctly handles special characters in username if ChatUser allows them. Django's standard cache key sanitization should apply, but verify if username can have colons (:), which often break default cache backends.
C. Serializer Instantiation Pattern
ChatUserSerializer.Operate(data={"id": self.user.id}).delete(with_valid=True)This pattern assumes ChatUserSerializer has a custom .Operate and .BatchDeleteInstance interface.
- Concern: This is not standard DRF code. Standard DRF uses
serializer.save()or viewset actions. If this is a custom framework, ensure.delete(with_valid=True)actually triggers signal-based cache invalidation or manual cache deletion internally. - Check: Does
.delete()also triggermodel.delete()? Ensure no database integrity errors occur if other models referenceChatUser.
D. Assertion Clarity
self.assertIsNone(cache.get(self.cache_key, version=self.version))- Improvement: Use
self.assertFalse(cache.get(...))if value could be falsy (empty dict/list), butassertIsNoneis stricter and better here. Keep it.
4. Recommended Code Improvements
class ChatUserDeleteTests(TestCase):
def setUp(self):
# 1. Verify get_key produces consistent results for serializer and test
self.version, self.get_key = Cache_Version.APPLICATION_THIRD_PARTY.value
self.user = ChatUser.objects.create(
username="channel-openid",
nick_name="Channel User",
password="encrypted-password",
)
# Pre-populate cache
self.cache_key = self.get_key(f"chat_user_{self.user.username}")
cache.set(
self.cache_key,
{"user_id": str(self.user.id), "nick_name": self.user.nick_name},
timeout=60, # Explicit timeout for clarity
version=self.version,
)
def _assert_cache_cleared(self, user_id: int, username: str):
"""Helper to reduce duplication."""
key = self.get_key(f"chat_user_{username}")
cached_value = cache.get(key, version=self.version)
self.assertIsNone(cached_value, f"Cache for user {user_id} ({username}) was not cleared.")
def test_delete_removes_third_party_user_cache(self):
ChatUserSerializer.Operate(data={"id": self.user.id}).delete(with_valid=True)
self._assert_cache_cleared(self.user.id, self.user.username)
def test_batch_delete_removes_third_party_user_cache(self):
# Create multiple users to test batch looping
users = [
ChatUser.objects.create(username="batch-user-1"),
ChatUser.objects.create(username="batch-user-2"),
]
keys = []
for u in users:
key = self.get_key(f"chat_user_{u.username}")
cache.set(key, {"user_id": str(u.id)}, version=self.version)
keys.append((u, key))
ids = [u.id for u in users]
ChatUserSerializer.BatchDeleteInstance(data={"ids": ids}).batch_delete()
for u, key in keys:
self.assertIsNone(
cache.get(key, version=self.version),
f"Batch delete failed to clear cache for {u.username}"
)
def test_batch_delete_with_missing_ids_does_not_error(self):
"""Optional: Test error handling / no-op for missing IDs."""
fake_id = 999999
# Should not raise exception, and existing caches remain untouched
ChatUserSerializer.BatchDeleteInstance(data={"ids": [self.user.id, fake_id]}).batch_delete()
# Existing user cache should still be there if the serializer skips invalid IDs?
# OR if it processes all, check self.user cache is gone
# Behavior depends on implementation. This test ensures robustness.Summary of Recommendations
- Extract Key Generation: Ensure
get_keylogic matches internal serializer logic exactly. - Expand Batch Test: Use multiple users in batch delete to catch loop/logic errors.
- Handle Missing IDs: Add a test for
batch_deletewith invalid/non-existent IDs. - Explicit Timeouts: Add explicit timeouts to
cache.setin tests to avoid environment-dependent behavior.
| clear_application_third_party_chat_user_cache([username]) | ||
| return True | ||
|
|
||
| def edit(self, instance, with_valid=True): |
There was a problem hiding this comment.
Overall, the patch is reasonable, but there are a few correctness/behavioral regressions and cache-consistency risks.
Main issues
-
Empty
idslist is now allowedListFielddefaults toallow_empty=True.- The original code explicitly rejected an empty list with
AppApiException(1004, ...). - Now
ids: []passes validation and silently deletes nothing. - Fix with
allow_empty=Falseor keep an explicit check.
-
API error contract changed
- The original empty-ID case raised
AppApiException(1004, ...). - The new
self.is_valid(raise_exception=True)raises DRFValidationError, which may change the response body/status/code expected by clients. - If clients depend on code
1004, preserve that behavior with a serializervalidate_idsor explicit check.
- The original empty-ID case raised
-
Cache invalidation should run after transaction commit
- If the request runs inside a transaction /
ATOMIC_REQUESTS, clearing the cache immediately after.delete()happens before commit. - A concurrent request could repopulate the cache with stale data, or a rollback could leave the cache unnecessarily cleared.
- Use
transaction.on_commit(...):
transaction.on_commit( lambda: clear_application_third_party_chat_user_cache(usernames) )
- If the request runs inside a transaction /
-
Inconsistent use of
self.datavsself.validated_databatch_delete()was updated correctly to usevalidated_data.delete()still usesself.data.get("id")after validation. Prefer:
user_id = self.validated_data.get("id")
- Also prefer
if username is not None:instead ofif username:if empty usernames are possible.
-
Cache-clear failure can turn a successful delete into an API error
ChatUser.objects...delete()may succeed, butcache.delete_many(...)can fail and raise.- The user is already deleted, but the client may receive a 500.
- Consider making cache invalidation best-effort with logging, or ensure it runs in an
on_commitcallback that cannot break the delete response.
-
Hard-coded cache key prefix
f"chat_user_{username}"is duplicated knowledge of the cache key format.- If the write path ever changes the key format, invalidation silently stops working.
- Centralize it, e.g.
get_chat_user_cache_key(username), and reuse it where the cache is written and cleared.
-
Race between username lookup and deletion
- The code selects the username, then deletes. If a concurrent rename occurs in between, the cache key cleared may not match the current key.
- If usernames are mutable and this matters, wrap in
transaction.atomic()withselect_for_update().
-
Large batch performance
- For very large
idslists, loading all usernames and deleting all cache keys at once may be memory/Redis-command heavy. - Consider chunking cache keys, e.g. batches of 500–1000.
- For very large
Suggested minimal patch
def batch_delete(self):
self.is_valid(raise_exception=True)
user_ids = self.validated_data.get("ids")
if not user_ids:
raise AppApiException(1004, _("User IDs cannot be empty"))
usernames = list(
ChatUser.objects.filter(id__in=user_ids)
.values_list("username", flat=True)
)
ChatUser.objects.filter(id__in=user_ids).delete()
transaction.on_commit(
lambda: clear_application_third_party_chat_user_cache(usernames)
)
return TrueFor the single delete:
if with_valid:
self.is_valid(raise_exception=True)
user_id = self.validated_data.get("id") if with_valid else self.data.get("id")
username = (
ChatUser.objects.filter(id=user_id)
.values_list("username", flat=True)
.first()
)
ChatUser.objects.filter(id=user_id).delete()
if username is not None:
transaction.on_commit(
lambda: clear_application_third_party_chat_user_cache([username])
)The main required fixes are: reject empty ids, preserve the expected exception/API contract if needed, and move cache invalidation to transaction.on_commit.
| f"{CONFIG.get_chat_path()}/{access_token}/" if access_token else f"{CONFIG.get_chat_path()}/portal" | ||
| ) | ||
| response.set_cookie( | ||
| key="mk_file_auth", |
There was a problem hiding this comment.
Here is the analysis of the code change:
1. Irregularities & Errors
-
Missing Closing Quote/Syntax Error (Line in context):
The lineaccess_token = [API_KEY]"access_token")appears to be a typo or a bad merge artifact in the context provided. It is syntactically invalid Python. It should likely be something likeaccess_token = request.META.get(HTTP_AUTHORIZATION)or similar, depending on how you parse tokens. This is likely a critical bug if present in the actual code. -
Trailing Slash Inconsistency:
The main change removes the trailing slash/from the fallback path:- Before:
f".../portal/" - After:
f".../portal"
This is generally an improvement, but it introduces a potential issue if the rest of the system does not normalize paths. See "Potential Issues" below.
- Before:
2. Potential Issues
-
Path Concatenation Risks:
If thiscookie_pathis later used in a string concatenation likepath + subpath, the lack of a trailing slash on"portal"could cause issues ifsubpathdoesn't start with/.- Example:
"portal" + "settings"→"portalettings"(Bug) - Example:
"portal" + "/settings"→"portal/settings"(OK)
Conversely, if you previously relied on
"portal/" + "settings"working and now use"portal" + "settings", it breaks. Ensure that all downstream consumers of this cookie value either:- Always prepend a
/when joining paths. - Use a proper URL/path joining function (e.g.,
os.path.joinorurllib.parse.urljoin).
- Example:
-
Cookie Path Validity:
HTTP cookie paths must be properly formatted. While both"/portal/"and"/portal"are often treated similarly by browsers (they usually redirect or match subsets), consistency is key. Most modern frameworks expect the path to not have a trailing slash unless it points to a directory file (which it doesn't). Removing the trailing slash is standard best practice for directory-like cookie paths.
3. Optimization & Best Practice Suggestions
- Use Standard Path Joining: Instead of manual f-string concatenation, consider using
urljoinor string methods that ensure no double slashes or missing separators.# Better approach for clarity and safety from urllib.parse import urljoin chat_base = CONFIG.get_chat_path().rstrip('/') # Ensure no trailing slash at base if access_token: cookie_path = f"{chat_base}/{access_token}" else: cookie_path = f"{chat_base}/portal"
- Verify Access Token Extraction: Fix the syntax error in
[API_KEY]"access_token"). Ensureaccess_tokenis always a sanitized string orNone. If it contains slashes or special characters, it might break the cookie path format. Consider URL-encoding or validating the token before inserting it into the path. - Security Check: Ensure that
access_tokenis validated before being used in a path. Unvalidated user input in a cookie path can sometimes lead to header injection if not handled correctly by the framework (though most modern frameworks sanitize this automatically).
Summary
The removal of the trailing slash from /portal/ → /portal is correct and recommended for cleaner URL/path semantics. However, fix the syntax error in the access_token assignment line immediately, as it will cause a runtime SyntaxError.
refactor: improve cache handling for chat user operations and enhance tests