Repository navigation
refactor: enhance user and chat user password handling with source validation - #8223
Conversation
…lidation --story=1023212@tapd-45245355 --user=王孝刚 【登录】关于系统用户管理中第三方用户的处理逻辑 https://www.tapd.cn/45245355/s/2179301
| token = LoginSerializer._issue_token(SimpleNamespace(id="user-id")) | ||
|
|
||
| details = signing.loads(token, key="test-signing-key") | ||
| self.assertEqual(details["source"], "LOCAL") |
There was a problem hiding this comment.
Here are the issues and suggestions for the diff:
1. Unused import in setUp
SimpleNamespace is used (LoginTokenSourceTests), but double-check password_verify and password_encrypt usage — both are used, fine.
2. test_local_login_token_records_local_source calls an unbound method with a fake object
token = LoginSerializer._issue_token(SimpleNamespace(id="user-id"))This works only if _issue_token doesn't touch self. If it does (e.g., accesses self.user or serializer state), this test will raise AttributeError. Prefer calling it through an instance (LoginSerializer(...)._issue_token(...)) or refactor _issue_token into a static/class method if it's genuinely independent of instance state. Otherwise the test is brittle against future refactors.
3. Over-mocking masks real behavior in login test
patch("users.serializers.login.DatabaseModelManage.get_model", return_value=lambda: False)Returning lambda: False from get_model relies on the production code calling the returned callable and then using it as a bool. This is opaque and fragile — it hides why "no captcha provider" satisfies the code path. Consider patching the actual configuration/feature flag rather than faking a model factory, or document the intent with a comment.
4. patch.object(LoginSerializer, "_need_captcha", ...) vs class-level patching of private methods
Patching many private methods (_is_account_locked, _need_captcha, _issue_token) signals tight coupling to internals. Acceptable for unit isolation, but these patch targets should be stable; if signatures change the tests won't catch regressions. Consider adding at least one integration-style test that exercises the real flow.
5. self.assertRaises(AppApiException) without checking message/code
All rejection tests only assert that some AppApiException is raised. A regression that raises the exception for the wrong reason (e.g., validation failure instead of third-party rejection) would still pass. Assert on the exception's error code/message:
with self.assertRaises(AppApiException) as ctx:
...
self.assertEqual(ctx.exception.get_code(), <expected_code>)6. test_email_password_reset_rejects_third_party_user patches attempts check but not other dependencies
check_verify_code_attempts returning True assumes that function is imported directly into users.serializers.user. Verify that's the actual import location — if the code does from common.auth import check_verify_code_attempts elsewhere, the patch silently no-ops and the test may pass/fail for the wrong reason. Same caution for CONFIG.get_session_timeout and common.auth.common.get_key.
7. signing.loads(token, key="test-signing-key") depends on serializer signature format
The test asserts details["source"] == "LOCAL", which couples the test to the exact token payload schema and to signing being used (not JWT). If _issue_token switches to a signed cookie/JWT later, this breaks. Worth a comment noting this is intentionally testing the serializer contract.
8. Magic strings for source values
"lark", "OIDC", "LOCAL", "local" are hardcoded. If the app has an enum/constants (e.g., UserSource.LOCAL), prefer those to avoid typos and make case-insensitivity intent explicit (test #7 verifies lowercasing behavior — good, but document why the case-insensitive path matters).
9. Test naming / coverage clarity
test_current_user_password_change_rejects_local_session_for_third_party_user and ..._rejects_third_party_login_source overlap conceptually. Consider parametrizing with subTest to reduce duplication and make the matrix (user.source × session.source) explicit.
10. ThirdPartyUserPasswordTests.setUp duplicates user-creation boilerplate
Four tests create near-identical users inline. Extract a helper _make_user(username, source=...) to reduce repetition and risk of divergence (e.g., email uniqueness assertions).
11. Potential missing case: password verify before rejecting
In the reject paths you assert self.user.password == self.encrypted_password, which is correct — but ensure the production code validates input (password rules) before the third-party check or vice versa is intentional. If a third-party user submits an invalid password shape, which exception wins? Add a test asserting precedence if the order matters.
12. Style: multi-line with (...) parentheses
Python 3.10+ parenthesized context managers are fine; confirm the project's minimum Python version supports it (3.10+) to avoid CI failures on older interpreters.
Summary of top priorities: #2 (fragile unbound call), #5 (assert exception details), #3/#6 (patch target correctness), and #8 (constants instead of strings).
|
|
||
| class ChatUserDeleteTests(TestCase): | ||
| def setUp(self): | ||
| self.version, self.get_key = Cache_Version.APPLICATION_THIRD_PARTY.value |
There was a problem hiding this comment.
Review of the diff
1. Missing imports (likely test failures)
The new tests use patch, TestCase (Django), and API_KEY without visible imports:
with patch.object(...) # needs: from unittest.mock import patch
class ThirdPartyChatUserPasswordTests(TestCase) # needs: from django.test import TestCase
access_token=[API_KEY], # needs a definition/import for API_KEYThese may exist higher up in the file that isn't shown, but if not, these are guaranteed NameErrors. Verify.
2. Tests rely on patching private internals — brittle
patch.object(ChatUserAccessTokenV3Serializer, "_get_login_policy", ...)couples the test to a private method name/signature (("chat-user", -1, 5, 10)tuple). If that return shape changes, the test silently breaks or gives false assurance.patch("system_manage.serializers.chat_user.DatabaseModelManage.get_model", return_value=None)patches a module-level imported name; it works only because the import isfrom ... import DatabaseModelManage. This is fragile — prefer dependency injection or a small seam.
3. Assertions could be too weak / strong
assertRaises(AppApiException)doesn't verify which error (message/code). Given multiple rejection paths (third-party source vs. login-source mismatch), consider asserting on the exception message or an error code so the two rejection reasons aren't conflated.- In
test_current_chat_user_password_change_rejects_local_session_for_third_party_user, passingsource="LOCAL"for asource="lark"user — confirm this is the intended semantic. The naming suggests "local session," but the setup mixes concepts; a comment explaining intent would help.
4. Conceptual overlap between the two test classes
ThirdPartyChatUserPasswordTests.test_current_chat_user_password_change_rejects_third_party_userandEffectiveChatUserLoginSourceTests.test_current_chat_user_password_change_rejects_third_party_login_sourceboth exercise the same path with differentsourcevalues. Consider parameterizing (subTest) to reduce duplication.
5. Repeated setup
Both classes duplicate password/encrypted_password/user creation. Extract a shared base class or helper factory to reduce drift.
6. Missing negative/positive coverage
- No test asserting that a local user with a matching local source can reset the password (guards against over-blocking).
- No test asserting third-party users can still log in via their expected flow (e.g., SSO), only that local login is rejected.
test_chat_user_profile_does_not_mask_third_party_source_with_local_logincheckssource == "lark"; add a symmetric assertion that profile masking logic behaves for normal cases to prevent regressions in the new branching.
7. Behavioral security considerations (production code implied by tests)
- Rejecting password change for third-party users is good, but ensure the check is based on a canonical field (the stored
sourceon the model) rather than the caller-suppliedsourceargument alone — otherwise a malicious caller could spoofsource. The tests suggest both are checked; make sure server-side truth wins. - For
reset_password(self.user.id, source=...), confirm thesourceparameter cannot be attacker-controlled in a way that bypasses the third-party block.
8. Minor style
- Diff mixes two concerns (new feature code and tests). Splitting into separate commits improves reviewability.
ChatUserRePasswordSerializeraliasing is fine, but double-check no other place still imports the bareRePasswordSerializer, causing ambiguity.- Unused import risk: confirm
AppUnauthorizedFailedis still used after this change; if removed usage elsewhere, drop it.
Summary
Functionally the tests target sensible security invariants, but they (a) depend on unverified imports, (b) heavily mock private internals making them brittle, (c) under-assert exception specifics, and (d) omit positive-path and anti-bypass coverage. Address the imports first (they may break CI), then tighten assertions and reduce duplication.
| query_set.return_value.filter.return_value.first.return_value = user | ||
| principal, _ = ChatUserToken().handle(None, "token", token_details) | ||
|
|
||
| self.assertEqual(principal.kwargs["source"], "OIDC") |
There was a problem hiding this comment.
Code Review: Token Source Tests
Potential Issues
1. Token generated twice per class (efficiency)
In test_token_source_survives_encoding_and_parsing, each to_token() is called twice:
signing.loads(SystemToken(...).to_token(), key="test-signing-key")
parse_token(SystemToken(...).to_token()) # second callIf token serialization ever includes a timestamp/nonce, the two tokens can differ, making the test compare unrelated values. Store the token once and reuse it:
token = SystemToken("system-user", AuthenticationType.SYSTEM_USER, source="OIDC").to_token()
details = signing.loads(token, key="test-signing-key")
parsed = parse_token(token)2. Fragile patch target strings
patch("common.auth.common.get_key") relies on import-path timing. If get_key is imported directly into the module under test (from ... import get_key), patching common.auth.common.get_key won't affect the already-bound reference. Prefer patch.object(<module>, "get_key") for robustness.
3. query_set.return_value.filter.return_value.first vs .get
The system handler uses QuerySet().get() while the chat handler uses .filter().first(). This is fine, but verify these correspond to real implementation behavior — mismatched mocking here can silently give false positives (e.g., a nonexistent query still "passes" because the mock returns the user unconditionally).
4. SimpleNamespace(id=..., is_active=True, password=...) may not match ORM model shape
Mocked users lack manager methods, pk vs id aliases, and property accessors (e.g., is_active as property, password setter). If production code touches any other attribute (e.g., user.pk, user.source on a related model, or user.check_password), these tests would pass falsely or raise on refactor. Consider using unittest.mock.Mock(spec=User) or an actual model instance built with build() if available.
5. Magic string "test-signing-key" duplicated
Repeated in three places. Extract a module-level constant. Also, the string used in signing.loads(key=...) must exactly match what get_key returns — tight coupling worth documenting.
6. No assertions on negative/error paths
Only the happy path is covered. Query param service looks like auth-critical code; add tests for:
- missing/invalid
source(should default or raise) - tampered token →
BadSignature - inactive user in
UserToken.handle
7. handle(None, "token", ...) — the None arg is opaque
The first argument passed as None isn't clear without reading the impl signature. Add a comment or use a named helper (e.g., self.request) so future readers don't guess.
8. Token expiry / time-based flakiness
No assertion that signing timestamps are respected. If signing.loads uses max_age, tests will be stable, but code under test without max_age allows expired-but-signed tokens indefinitely — worth a note.
9. AuthenticationType.X.value used inline inside token_details
Match the type produced by real token payloads. If real payloads serialize via str(enum) or .name, this test will diverge from production. Verify against actual serializer.
10. SimpleTestCase vs DB usage
Both classes inherit SimpleTestCase, which blocks DB queries. That's good only if UserToken/ChatUserToken never hit the DB in these flows — which they do via QuerySet. Since QuerySet is fully patched, it works, but this is a subtle assumption. If any code path later touches the DB directly (e.g., logging helpers), tests break confusingly. Consider TestCase for robustness unless speed matters.
Style / Minor
- Trailing comma inconsistency:
SystemToken(..., source="OIDC")vsChatToken(..., "LOCAL", source="OIDC"). - The blank line before
with (in the first test is fine, but the two context-manager blocks intest_system_token_handler_exposes_login_sourceorder patches arbitrarily. Group logically (cache/mocks first). - Within the same test,
signing.loads(...)thenparse_token(...)— separate these into sub-tests or clearly comment their distinct purposes (serialization correctness vs. parsing correctness).
Optimization Suggestions
- Parametrize the two
TokenSourceTestscases (system & chat) withsubTestorparameterizedto remove duplication. - Fixtures: share the signing-key patch via
setUpor a context manager helper. - Assertion on full payload, not just
source— e.g.,self.assertEqual(details["type"], AuthenticationType.SYSTEM_USER.value)— to catch field renames. - Extract magic literals (
"token","OIDC","LOCAL",3600) into constants/enums. - Add
assertRaises(signing.BadSignature)around a modified-token parse to confirm integrity checks work.
Summary
Functionally the tests appear correct for the happy path, but they're fragile (string-based patches, mocked query behavior mismatches, duplicated construction), lack error-path coverage, and lean on SimpleTestCase in a way that masks DB assumptions. Address items 1–4 and 6 for the biggest reliability gains.
refactor: enhance user and chat user password handling with source validation --story=1023212@tapd-45245355 --user=王孝刚 【登录】关于系统用户管理中第三方用户的处理逻辑 https://www.tapd.cn/45245355/s/2179301