Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/chat/serializers/chat_user_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def local_login(cls, instance, access_token=None):

user = ChatUser.objects.filter(username=username).first()

if not user or not password_verify(password, user.password):
if not user or str(user.source).upper() != "LOCAL" or not password_verify(password, user.password):
cls._handle_failed_login(scope, username, failed_attempts, lock_time)
raise AppApiException(500, _("The username or password is incorrect"))

Expand Down
9 changes: 7 additions & 2 deletions apps/chat/views/v2/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ def post(self, request: Request):
except Exception:
raise AppApiException(500, _("Invalid encrypted data"))
serializer_obj = RePasswordSerializer(data=request_data)
if serializer_obj.reset_password(request.user.id):
if serializer_obj.reset_password(request.user.id, request.user.kwargs.get("source")):
version, get_key = Cache_Version.CHAT_USER_TOKEN.value
auth = request.META.get("HTTP_AUTHORIZATION")
cache.delete(get_key(token=auth), version=version)
Expand All @@ -426,7 +426,12 @@ class ChatUserProfileView(APIView):
responses=UserProfileAPI.get_response(),
)
def get(self, request: Request):
return result.success(ChatUserProfileSerializer().profile(request.user))
return result.success(
ChatUserProfileSerializer().profile(
request.user.profile,
source=request.user.kwargs.get("source"),
)
)


class Logout(APIView):
Expand Down
10 changes: 7 additions & 3 deletions apps/chat/views/v3/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ def post(self, request: Request):
except Exception:
raise AppApiException(500, _("Invalid encrypted data"))
serializer_obj = RePasswordSerializer(data=request_data)
if serializer_obj.reset_password(request.user.id):
if serializer_obj.reset_password(request.user.id, request.user.kwargs.get("source")):
version, get_key = Cache_Version.CHAT_USER_TOKEN.value
auth = request.META.get("HTTP_AUTHORIZATION")
cache.delete(get_key(token=auth), version=version)
Expand All @@ -465,7 +465,12 @@ class ChatUserProfileView(APIView):
},
)
def get(self, request: Request):
return result.success(ChatUserProfileSerializer().profile(request.user.profile))
return result.success(
ChatUserProfileSerializer().profile(
request.user.profile,
source=request.user.kwargs.get("source"),
)
)


class ChatUserLanguageView(APIView):
Expand Down Expand Up @@ -574,7 +579,6 @@ class LocalLoginView(BaseAuthView):
def post(self, request: Request):
access_token = request.query_params.get("accessToken")
user = ChatUserAccessTokenV3Serializer.local_login(request.data, access_token)
user.source = "LOCAL"
token = self.create_token_and_cache(user, access_token, Operate.LOCAL)
response = result.success({"token": token})
return self.generate(request, token, response, path=get_chat_user_cookie_path(access_token))
Expand Down
41 changes: 27 additions & 14 deletions apps/common/auth/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,40 +29,42 @@ def get_key():


class SystemToken:
def __init__(self, user_id, _type: AuthenticationType, **kwargs):
def __init__(self, user_id, _type: AuthenticationType, source=None, **kwargs):
self.id = user_id
self.type = _type
self.source = source
self.kwargs = kwargs

def to_dict(self):
details = {"id": str(self.id), "type": str(self.type.value)}
if self.source:
details["source"] = str(self.source)
if self.kwargs:
return {"user_id": self.id, "type": str(self.type.value), "kwargs": self.kwargs}
return {"id": str(self.id), "type": str(self.type.value)}
details["kwargs"] = self.kwargs
return details

def to_token(self):
return signing.dumps(self.to_dict(), key=get_key())


class ChatToken:
def __init__(self, user_id, _type: AuthenticationType, login_type: str, **kwargs):
def __init__(self, user_id, _type: AuthenticationType, login_type: str, source=None, **kwargs):
self.id = user_id
self.type = _type
self.login_type = login_type
self.source = source or login_type
self.kwargs = kwargs

def to_dict(self):
if self.kwargs:
return {
"id": str(self.id),
"type": str(self.type.value),
"login_type": str(self.login_type),
"kwargs": self.kwargs,
}
return {
details = {
"id": str(self.id),
"type": str(self.type.value),
"login_type": str(self.login_type),
"source": str(self.source),
}
if self.kwargs:
details["kwargs"] = self.kwargs
return details

def to_token(self):
return signing.dumps(self.to_dict(), key=get_key())
Expand All @@ -73,6 +75,17 @@ def parse_token(token):
_type = details.get("type")
if _type:
if _type == AuthenticationType.SYSTEM_USER.value:
return SystemToken(details.get("id"), details.get("type"), **details.get("kwargs", {}))
return ChatToken(details.get("id"), details.get("type"), details.get("login_type"), **details.get("kwargs", {}))
return SystemToken(
details.get("id") or details.get("user_id"),
details.get("type"),
source=details.get("source"),
**details.get("kwargs", {}),
)
return ChatToken(
details.get("id"),
details.get("type"),
details.get("login_type"),
source=details.get("source"),
**details.get("kwargs", {}),
)
raise AppAuthenticationFailed(1001, "")
5 changes: 3 additions & 2 deletions apps/common/auth/handle/impl/chat_user_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ def support(self, request, token: str, get_token_details):
def handle(self, request, token: str, get_token_details):
auth_details = get_token_details()
login_type = auth_details.get("login_type")
source = auth_details.get("source") or login_type
user_id = auth_details.get("id")
application_id = (auth_details.get("kwargs") or {}).get("application_id")
_type = (
Expand All @@ -124,5 +125,5 @@ def handle(self, request, token: str, get_token_details):
# 避免返回一个空权限的 Principal 造成静默失败。
if not auth.permissions.get(f"{Group.CHAT_USER}:r:{application_id}"):
raise AppUnauthorizedFailed(403, _("No permission to access"))
return Principal(user_id, _type, application_id=application_id, profile=chat_user), auth
return Principal(user_id, _type, profile=chat_user), auth
return Principal(user_id, _type, application_id=application_id, profile=chat_user, source=source), auth
return Principal(user_id, _type, profile=chat_user, source=source), auth
3 changes: 2 additions & 1 deletion apps/common/auth/handle/impl/user_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,4 +299,5 @@ def handle(self, request, token: str, get_token_details):
if not user.is_active or user.password != cache_token.password:
raise AppAuthenticationFailed(1002, _("Authentication information is incorrect"))
auth = get_auth(user)
return Principal(user.id, UserType.SYSTEM_USER, user), auth
source = auth_details.get("source") or user.source
return Principal(user.id, UserType.SYSTEM_USER, user, source=source), auth
80 changes: 80 additions & 0 deletions apps/common/tests/test_auth_common.py
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")

Copy link
Copy Markdown
Contributor Author

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, each to_token() is called twice:

signing.loads(SystemToken(...).to_token(), key="test-signing-key")
parse_token(SystemToken(...).to_token())   # second call

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:

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") vs ChatToken(..., "LOCAL", source="OIDC").
  • The blank line before with ( in the first test is fine, but the two context-manager blocks in test_system_token_handler_exposes_login_source order patches arbitrarily. Group logically (cache/mocks first).
  • Within the same test, signing.loads(...) then parse_token(...) — separate these into sub-tests or clearly comment their distinct purposes (serialization correctness vs. parsing correctness).

Optimization Suggestions

  1. Parametrize the two TokenSourceTests cases (system & chat) with subTest or parameterized to remove duplication.
  2. Fixtures: share the signing-key patch via setUp or a context manager helper.
  3. Assertion on full payload, not just source — e.g., self.assertEqual(details["type"], AuthenticationType.SYSTEM_USER.value) — to catch field renames.
  4. Extract magic literals ("token", "OIDC", "LOCAL", 3600) into constants/enums.
  5. 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.

23 changes: 19 additions & 4 deletions apps/system_manage/serializers/chat_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,20 @@
from maxkb.const import CONFIG
from system_manage.models import ChatUser, UserGroup, UserGroupRelation
from system_manage.models.chat_user_token_quota import ChatUserTokenQuota, QuotaType
from users.serializers.user import PASSWORD_REGEX
from users.serializers.user import PASSWORD_REGEX, _is_default_password

application_third_party_version, application_third_party_get_key = Cache_Version.APPLICATION_THIRD_PARTY.value


def _is_local_source(source):
return str(source or "").upper() == "LOCAL"


def _ensure_local_chat_user(user, source=None):
if not user or not _is_local_source(user.source) or (source is not None and not _is_local_source(source)):
raise AppApiException(1005, _("Third-party users cannot change passwords"))


def clear_application_third_party_chat_user_cache(usernames):
cache_keys = [application_third_party_get_key(f"chat_user_{username}") for username in usernames]
if cache_keys:
Expand Down Expand Up @@ -433,6 +442,7 @@ def re_password(self, instance, with_valid=True):
raise AppApiException(500, _("Invalid encrypted data"))
ChatUserSerializer.RePasswordInstance(data=instance).is_valid(raise_exception=True)
user = ChatUser.objects.filter(id=self.data.get("id")).first()
_ensure_local_chat_user(user)
user.password = password_encrypt(instance.get("password"))
user.save()
return True
Expand Down Expand Up @@ -677,26 +687,28 @@ def is_valid(self, *, raise_exception=False):
)
return True

def reset_password(self, user_id):
def reset_password(self, user_id, source=None):
"""
修改密码
:return: 是否成功
"""
_ensure_local_chat_user(ChatUser.objects.filter(id=user_id).first(), source)
if self.is_valid():
QuerySet(ChatUser).filter(id=user_id).update(password=password_encrypt(self.data.get("password")))
return True


class ChatUserProfileSerializer(serializers.Serializer):
@staticmethod
def profile(user: ChatUser):
def profile(user: ChatUser, source=None):
"""
获取对话用户详情
@param user: 用户对象
@return:
"""
if not user:
return {}
login_source = source or user.source
license_is_valid = DatabaseModelManage.get_model("license_is_valid") or (lambda: False)
license_is_valid = license_is_valid() if license_is_valid() is not None else False
token_quota = None
Expand All @@ -716,8 +728,11 @@ def profile(user: ChatUser):
"nick_name": user.nick_name,
"email": user.email,
"language": user.language,
"source": user.source,
"source": login_source,
"token_quota": token_quota,
"is_edit_password": _is_default_password(CONFIG.get("DEFAULT_PASSWORD", "MaxKB@123.."), user.password)
if str(login_source or "").upper() == "LOCAL"
else False,
}


Expand Down
Loading
Loading