"""Tencent CAM IAM enrichment: real MFA state, real last-login. Two fields were being asserted without ever being asked for: * ``mfa_enabled`` was hard-coded ``False`` for every CAM user, on a comment claiming per-user MFA is only reachable through unstable helpers. It is not — ``DescribeSafeAuthFlagColl(SubUin=…)`` returns the sub-user's own ``LoginFlag`` / ``ActionFlag``. Verified against prod 2026-08-12: 冯帅 and 李琳 login+action, 左武辉 login only, ``tiup-server`` none. So the compliance view showed 25 users with "no MFA" while several had it on. * ``last_login_at`` was read from ``ListUsers.LastLoginTime``, a field that response does not contain (checked field-by-field against prod). Every Tencent row therefore had NULL, and the inactivity sweep could not see the tenant at all. The value lives on ``GetUser`` as ``RecentlyLoginTime``. The invariant both share: a provider that cannot answer must say ``unknown``, never ``disabled``. "We did not ask" and "it is off" are different remediations. """ from __future__ import annotations from unittest.mock import patch from app.domains.cmdb.providers.base import ProviderCredentials from app.domains.cmdb.providers.tencent import ( TencentProvider, _any_factor_on, _coerce_flag, ) class _Resp: def __init__(self, **kw): for k, v in kw.items(): setattr(self, k, v) class _Client: def __getattr__(self, name): return lambda *a, **kw: None def _provider() -> TencentProvider: return TencentProvider(ProviderCredentials( provider_id="tc-test", provider_type="tencent", account_alias="腾讯云", fields={ "secret_id": "AKIDtest", "secret_key": "sk-test", "regions": "ap-guangzhou", }, )) def _flag(**on) -> _Resp: base = { "Phone": 0, "Token": 0, "Stoken": 0, "Wechat": 0, "Custom": 0, "Mail": None, "U2FToken": 0, "Passkey": 0, } base.update(on) return _Resp(**base) def _run(users: list[_Resp], *, flags: dict, logins: dict) -> list[dict]: provider = _provider() def _call(fn, req, **_kw): cls = req.__class__.__name__ if cls == "ListUsersRequest": return _Resp(Data=users) if cls == "ListAttachedUserAllPoliciesRequest": return _Resp(PolicyList=[], TotalNum=0) if cls == "ListGroupsForUserRequest": return _Resp(GroupInfo=[]) if cls == "DescribeSafeAuthFlagCollRequest": entry = flags.get(int(req.SubUin)) if entry is None: from tencentcloud.common.exception.tencent_cloud_sdk_exception import ( # noqa: E501 TencentCloudSDKException, ) raise TencentCloudSDKException("InternalError", "boom") return _Resp(LoginFlag=entry[0], ActionFlag=entry[1]) if cls == "GetUserRequest": return _Resp(RecentlyLoginTime=logins.get(req.Name)) return _Resp() with ( patch( "app.domains.cmdb.providers.tencent._make_tc_client", return_value=_Client(), ), patch.object(provider, "_call", side_effect=_call), ): return provider._list_iam_users_sync() def test_soft_token_user_reports_mfa_enabled() -> None: rows = _run( [_Resp(Name="shuai.feng@pingcap.com", Uin=100045093193, Email="")], flags={100045093193: (_flag(Stoken=1), _flag(Stoken=1))}, logins={"shuai.feng@pingcap.com": "2025-12-02 11:05:15"}, ) assert rows[0]["mfa_state"] == "enabled" assert rows[0]["mfa_enabled"] is True assert rows[0]["raw"]["MfaDetail"]["action_mfa"] is True def test_login_only_mfa_is_enabled_but_action_mfa_is_recorded_off() -> None: """左武辉's real shape. A single bool cannot express "protected at login, unprotected for sensitive operations" — that gap is a finding an admin should be able to see.""" rows = _run( [_Resp(Name="wuhui.zuo", Uin=100040362173, Email="")], flags={100040362173: (_flag(Stoken=1), _flag())}, logins={"wuhui.zuo": "2026-08-12 15:21:13"}, ) assert rows[0]["mfa_state"] == "enabled" assert rows[0]["raw"]["MfaDetail"]["action_mfa"] is False def test_service_account_with_no_factors_reports_disabled() -> None: rows = _run( [_Resp(Name="tiup-server", Uin=100036767862, Email="", ConsoleLogin=0)], flags={100036767862: (_flag(), _flag())}, logins={"tiup-server": ""}, ) assert rows[0]["mfa_state"] == "disabled" assert rows[0]["mfa_enabled"] is False # ConsoleLogin=0 is the authoritative service-account signal, far # better than guessing from the name. assert rows[0]["raw"]["ConsoleLogin"] == 0 def test_probe_failure_reports_unknown_not_disabled() -> None: """The whole point. A failed probe must not be laundered into a security assertion.""" rows = _run( [_Resp(Name="unreachable@pingcap.com", Uin=999, Email="")], flags={}, # every DescribeSafeAuthFlagColl raises logins={}, ) assert rows[0]["mfa_state"] == "unknown" assert rows[0]["mfa_enabled"] is False def test_last_login_comes_from_get_user_not_list_users() -> None: """``ListUsers`` has no login timestamp; reading one there is why every Tencent row had NULL and the inactivity sweep was blind.""" rows = _run( [_Resp( Name="wuhui.zuo", Uin=100040362173, Email="", # Deliberately present and wrong: if the code still trusted # ListUsers this would win. LastLoginTime="2001-01-01 00:00:00", )], flags={100040362173: (_flag(Stoken=1), _flag())}, logins={"wuhui.zuo": "2026-08-12 15:21:13"}, ) got = rows[0]["last_login_at"] assert got is not None assert got.year == 2026 and got.month == 8 and got.day == 12 def test_never_logged_in_stays_none() -> None: rows = _run( [_Resp(Name="tiup-server", Uin=100036767862, Email="")], flags={100036767862: (_flag(), _flag())}, logins={"tiup-server": ""}, ) assert rows[0]["last_login_at"] is None def test_any_factor_counts_not_just_soft_token() -> None: """A hardware key or passkey protects the account just as well; reporting those users as "no MFA" would be the same class of lie this change undoes.""" assert _any_factor_on(_coerce_flag(_flag(U2FToken=1))) is True assert _any_factor_on(_coerce_flag(_flag(Passkey=1))) is True assert _any_factor_on(_coerce_flag(_flag(Phone=1))) is True assert _any_factor_on(_coerce_flag(_flag())) is False # ``Mail`` is a notification channel in this payload, not a factor. assert _any_factor_on(_coerce_flag(_flag(Mail=1))) is False def test_coerce_flag_accepts_dict_and_object_shapes() -> None: assert _coerce_flag({"Stoken": 1})["Stoken"] == 1 assert _coerce_flag(_flag(Stoken=1))["Stoken"] == 1 assert _coerce_flag(None) == {}