|
| 1 | +"""Offline behavior tests of password handlers with external boundaries replaced. |
| 2 | +
|
| 3 | +Extract actual functions to avoid importing DB/xpack startup. These tests do not |
| 4 | +claim coverage of authentication middleware, decorators or real transactions. |
| 5 | +""" |
| 6 | + |
| 7 | +import ast |
| 8 | +import asyncio |
| 9 | +import hashlib |
| 10 | +import json |
| 11 | +from pathlib import Path |
| 12 | +from types import SimpleNamespace |
| 13 | +from unittest.mock import AsyncMock, Mock |
| 14 | + |
| 15 | +import pytest |
| 16 | +from fastapi import HTTPException |
| 17 | + |
| 18 | +ROOT = Path(__file__).resolve().parents[2] |
| 19 | + |
| 20 | + |
| 21 | +def load_function(path, name, namespace): |
| 22 | + tree = ast.parse((ROOT / path).read_text()) |
| 23 | + node = next( |
| 24 | + n |
| 25 | + for n in tree.body |
| 26 | + if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == name |
| 27 | + ) |
| 28 | + node.decorator_list = [] |
| 29 | + node.returns = None |
| 30 | + for arg in node.args.args: |
| 31 | + arg.annotation = None |
| 32 | + exec( |
| 33 | + compile( |
| 34 | + ast.fix_missing_locations(ast.Module(body=[node], type_ignores=[])), |
| 35 | + str(path), |
| 36 | + "exec", |
| 37 | + ), |
| 38 | + namespace, |
| 39 | + ) |
| 40 | + return namespace[name] |
| 41 | + |
| 42 | + |
| 43 | +def md5(value): |
| 44 | + return hashlib.md5(value.encode()).hexdigest() |
| 45 | + |
| 46 | + |
| 47 | +@pytest.fixture |
| 48 | +def context(): |
| 49 | + user = SimpleNamespace(id=2, password=md5("OldPassword42!")) |
| 50 | + session = Mock() |
| 51 | + args = AsyncMock( |
| 52 | + return_value=[SimpleNamespace(pkey="login.initial_pwd_disabled", pval="true")] |
| 53 | + ) |
| 54 | + ns = { |
| 55 | + "get_group_args": args, |
| 56 | + "HTTPException": HTTPException, |
| 57 | + "get_db_user": Mock(return_value=user), |
| 58 | + "md5pwd": md5, |
| 59 | + "verify_md5pwd": lambda value, hashed: md5(value) == hashed, |
| 60 | + "default_pwd": lambda: "InitialPassword42!", |
| 61 | + "settings": SimpleNamespace(DEFAULT_PWD="InitialPassword42!"), |
| 62 | + } |
| 63 | + import re |
| 64 | + |
| 65 | + ns["re"] = re |
| 66 | + schema = ast.parse( |
| 67 | + (ROOT / "backend/apps/system/schemas/system_schema.py").read_text() |
| 68 | + ) |
| 69 | + regex = next( |
| 70 | + n |
| 71 | + for n in schema.body |
| 72 | + if isinstance(n, ast.Assign) |
| 73 | + and any(isinstance(t, ast.Name) and t.id == "PWD_REGEX" for t in n.targets) |
| 74 | + ) |
| 75 | + exec( |
| 76 | + compile(ast.Module(body=[regex], type_ignores=[]), "<password-regex>", "exec"), |
| 77 | + ns, |
| 78 | + ) |
| 79 | + load_function("backend/apps/system/crud/user.py", "check_pwd_format", ns) |
| 80 | + policy_path = "backend/apps/system/crud/password_policy.py" |
| 81 | + if not (ROOT / policy_path).exists(): |
| 82 | + policy_path = "backend/apps/system/api/login.py" |
| 83 | + load_function(policy_path, "initial_pwd_disabled", ns) |
| 84 | + handler = load_function("backend/apps/system/api/user.py", "pwdUpdate", ns) |
| 85 | + return user, session, args, ns, handler |
| 86 | + |
| 87 | + |
| 88 | +def update(context, new="InitialPassword42!", old="OldPassword42!", uid=2): |
| 89 | + _, session, _, _, handler = context |
| 90 | + return asyncio.run( |
| 91 | + handler( |
| 92 | + session, |
| 93 | + SimpleNamespace(id=uid), |
| 94 | + lambda message_key, **kwargs: message_key, |
| 95 | + SimpleNamespace(pwd=old, new_pwd=new), |
| 96 | + ) |
| 97 | + ) |
| 98 | + |
| 99 | + |
| 100 | +@pytest.mark.parametrize("uid", [1, 2]) |
| 101 | +def test_disabled_rejects_initial_password_without_writing(context, uid): |
| 102 | + user, session, _, ns, _ = context |
| 103 | + before = user.password |
| 104 | + with pytest.raises(HTTPException) as exc: |
| 105 | + update(context, uid=uid) |
| 106 | + assert exc.value.status_code == 400 |
| 107 | + assert exc.value.detail == "i18n_login.new_pwd_is_initial" |
| 108 | + assert user.password == before |
| 109 | + session.add.assert_not_called() |
| 110 | + ns["get_db_user"].assert_called_once_with(session=session, user_id=uid) |
| 111 | + |
| 112 | + |
| 113 | +@pytest.mark.parametrize("value", ["false", False, None]) |
| 114 | +def test_disabled_off_allows_initial_password(context, value): |
| 115 | + user, session, args, _, _ = context |
| 116 | + args.return_value = [SimpleNamespace(pkey="login.initial_pwd_disabled", pval=value)] |
| 117 | + update(context) |
| 118 | + assert user.password == md5("InitialPassword42!") |
| 119 | + session.add.assert_called_once_with(user) |
| 120 | + |
| 121 | + |
| 122 | +def test_enabled_allows_other_password(context): |
| 123 | + user, session, _, _, _ = context |
| 124 | + update(context, new="DifferentPassword42!") |
| 125 | + assert user.password == md5("DifferentPassword42!") |
| 126 | + session.add.assert_called_once_with(user) |
| 127 | + |
| 128 | + |
| 129 | +@pytest.mark.parametrize( |
| 130 | + "old,new", [("wrong", "InitialPassword42!"), ("OldPassword42!", "bad")] |
| 131 | +) |
| 132 | +def test_invalid_credentials_or_format_never_write(context, old, new): |
| 133 | + user, session, _, _, _ = context |
| 134 | + before = user.password |
| 135 | + with pytest.raises(Exception) as exc: |
| 136 | + update(context, old=old, new=new) |
| 137 | + assert str(exc.value) == ("i18n_error" if old == "wrong" else "i18n_format_invalid") |
| 138 | + assert user.password == before |
| 139 | + session.add.assert_not_called() |
| 140 | + |
| 141 | + |
| 142 | +@pytest.mark.parametrize( |
| 143 | + "value,expected", |
| 144 | + [ |
| 145 | + ("true", True), |
| 146 | + (" TRUE ", True), |
| 147 | + (True, True), |
| 148 | + ("false", False), |
| 149 | + (False, False), |
| 150 | + (None, False), |
| 151 | + ], |
| 152 | +) |
| 153 | +def test_policy_config_values(context, value, expected): |
| 154 | + _, session, args, ns, _ = context |
| 155 | + args.return_value = [SimpleNamespace(pkey="login.initial_pwd_disabled", pval=value)] |
| 156 | + assert asyncio.run(ns["initial_pwd_disabled"](session)) is expected |
| 157 | + args.assert_awaited_once_with(session=session, flag="login") |
| 158 | + |
| 159 | + |
| 160 | +def test_missing_policy_defaults_off(context): |
| 161 | + _, session, args, ns, _ = context |
| 162 | + args.return_value = [] |
| 163 | + assert asyncio.run(ns["initial_pwd_disabled"](session)) is False |
| 164 | + |
| 165 | + |
| 166 | +def test_error_translations_present(): |
| 167 | + for locale in ["en", "zh-CN", "zh-TW", "ko-KR", "th-TH"]: |
| 168 | + messages = json.loads((ROOT / "backend/locales" / f"{locale}.json").read_text()) |
| 169 | + assert messages["i18n_login"]["new_pwd_is_initial"] |
0 commit comments