Repository navigation
refactor: enhance user and chat user password handling with source validation #8223
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| from types import SimpleNamespace | ||
| from unittest.mock import patch | ||
|
|
||
| from django.core import signing | ||
| from django.test import SimpleTestCase | ||
|
|
||
| from common.auth.common import ChatToken, SystemToken, parse_token | ||
| from common.auth.handle.impl import chat_user_token, user_token | ||
| from common.auth.handle.impl.chat_user_token import ChatUserToken | ||
| from common.auth.handle.impl.user_token import UserToken | ||
| from common.auth.struct.auth import Auth | ||
| from common.constants.authentication_type import AuthenticationType | ||
|
|
||
|
|
||
| class TokenSourceTests(SimpleTestCase): | ||
| def test_token_source_survives_encoding_and_parsing(self): | ||
| with patch("common.auth.common.get_key", return_value="test-signing-key"): | ||
| system_details = signing.loads( | ||
| SystemToken("system-user", AuthenticationType.SYSTEM_USER, source="OIDC").to_token(), | ||
| key="test-signing-key", | ||
| ) | ||
| system_token = parse_token( | ||
| SystemToken("system-user", AuthenticationType.SYSTEM_USER, source="OIDC").to_token() | ||
| ) | ||
| chat_details = signing.loads( | ||
| ChatToken("chat-user", AuthenticationType.CHAT_USER, "LOCAL", source="OIDC").to_token(), | ||
| key="test-signing-key", | ||
| ) | ||
| chat_token = parse_token( | ||
| ChatToken("chat-user", AuthenticationType.CHAT_USER, "LOCAL", source="OIDC").to_token() | ||
| ) | ||
|
|
||
| self.assertEqual(system_details["source"], "OIDC") | ||
| self.assertEqual(system_token.source, "OIDC") | ||
| self.assertEqual(chat_details["source"], "OIDC") | ||
| self.assertEqual(chat_token.source, "OIDC") | ||
|
|
||
|
|
||
| class TokenHandlerSourceTests(SimpleTestCase): | ||
| def test_system_token_handler_exposes_login_source(self): | ||
| user = SimpleNamespace(id="system-user", is_active=True, password="password-hash", source="LOCAL") | ||
|
|
||
| def token_details(): | ||
| return { | ||
| "id": "system-user", | ||
| "type": AuthenticationType.SYSTEM_USER.value, | ||
| "source": "OIDC", | ||
| } | ||
|
|
||
| with ( | ||
| patch.object(user_token, "cache") as token_cache, | ||
| patch.object(user_token, "QuerySet") as query_set, | ||
| patch.object(user_token, "get_auth", return_value=Auth(set(), {})), | ||
| patch.object(user_token.CONFIG, "get_session_timeout", return_value=3600), | ||
| ): | ||
| token_cache.get.return_value = SimpleNamespace(password="password-hash") | ||
| query_set.return_value.get.return_value = user | ||
| principal, _ = UserToken().handle(None, "token", token_details) | ||
|
|
||
| self.assertEqual(principal.kwargs["source"], "OIDC") | ||
|
|
||
| def test_chat_token_handler_exposes_login_source(self): | ||
| user = SimpleNamespace(id="chat-user", source="LOCAL") | ||
|
|
||
| def token_details(): | ||
| return { | ||
| "id": "chat-user", | ||
| "type": AuthenticationType.CHAT_USER.value, | ||
| "login_type": "LOCAL", | ||
| "source": "OIDC", | ||
| } | ||
|
|
||
| with ( | ||
| patch.object(chat_user_token, "QuerySet") as query_set, | ||
| patch.object(chat_user_token, "get_auth", return_value=Auth(set(), {})), | ||
| ): | ||
| query_set.return_value.filter.return_value.first.return_value = user | ||
| principal, _ = ChatUserToken().handle(None, "token", token_details) | ||
|
|
||
| self.assertEqual(principal.kwargs["source"], "OIDC") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Code Review: Token Source Tests
Potential Issues
1. Token generated twice per class (efficiency)
In
test_token_source_survives_encoding_and_parsing, eachto_token()is called twice:If 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:
2. Fragile patch target strings
patch("common.auth.common.get_key")relies on import-path timing. Ifget_keyis imported directly into the module under test (from ... import get_key), patchingcommon.auth.common.get_keywon't affect the already-bound reference. Preferpatch.object(<module>, "get_key")for robustness.3.
query_set.return_value.filter.return_value.firstvs.getThe 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 shapeMocked users lack manager methods,
pkvsidaliases, and property accessors (e.g.,is_activeas property,passwordsetter). If production code touches any other attribute (e.g.,user.pk,user.sourceon a related model, oruser.check_password), these tests would pass falsely or raise on refactor. Consider usingunittest.mock.Mock(spec=User)or an actual model instance built withbuild()if available.5. Magic string
"test-signing-key"duplicatedRepeated in three places. Extract a module-level constant. Also, the string used in
signing.loads(key=...)must exactly match whatget_keyreturns — 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:
source(should default or raise)BadSignatureUserToken.handle7.
handle(None, "token", ...)— theNonearg is opaqueThe first argument passed as
Noneisn'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.loadsusesmax_age, tests will be stable, but code under test withoutmax_ageallows expired-but-signed tokens indefinitely — worth a note.9.
AuthenticationType.X.valueused inline insidetoken_detailsMatch 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.
SimpleTestCasevs DB usageBoth classes inherit
SimpleTestCase, which blocks DB queries. That's good only ifUserToken/ChatUserTokennever hit the DB in these flows — which they do viaQuerySet. SinceQuerySetis 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. ConsiderTestCasefor robustness unless speed matters.Style / Minor
SystemToken(..., source="OIDC")vsChatToken(..., "LOCAL", source="OIDC").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).signing.loads(...)thenparse_token(...)— separate these into sub-tests or clearly comment their distinct purposes (serialization correctness vs. parsing correctness).Optimization Suggestions
TokenSourceTestscases (system & chat) withsubTestorparameterizedto remove duplication.setUpor a context manager helper.source— e.g.,self.assertEqual(details["type"], AuthenticationType.SYSTEM_USER.value)— to catch field renames."token","OIDC","LOCAL",3600) into constants/enums.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
SimpleTestCasein a way that masks DB assumptions. Address items 1–4 and 6 for the biggest reliability gains.