"""Owner account moderation: local identity resolution and money-safe unban. All databases are temporary; no Telegram or production services are contacted. """ import ast import asyncio from contextlib import closing import html from pathlib import Path import re import sqlite3 from types import SimpleNamespace from unittest.mock import AsyncMock import pytest from test_moderation_bridge import ( ADMIN_ID, FakeBot, FakeChat, FakeMessage, FakePlanner, FakeUser, make_bridge, mb, ) from test_account_admin_unban import BOT_SCHEMA, GATEWAY_SCHEMA, TOKENS @pytest.fixture def account_bridge(tmp_path): bridge = make_bridge( tmp_path, FakeBot(), FakePlanner(error=mb.PlannerUnavailable("offline")) ) bridge.ns["PAUSE_PATH"] = str(tmp_path / "cap.json") with closing(sqlite3.connect(bridge.bot_db)) as con, con: con.executescript(BOT_SCHEMA) con.execute("INSERT INTO users(tg_id,username,api_key) VALUES(101,'@MiXeD','sk-main')") con.execute("INSERT INTO users(tg_id,username,admin) VALUES(7,'owner',1)") with closing(sqlite3.connect(bridge.newapi_db)) as con, con: con.executescript(GATEWAY_SCHEMA) con.executemany("INSERT INTO tokens VALUES(?,?,?,?,?,?,?,?)", TOKENS) con.execute("INSERT INTO users VALUES(1,'tg101',1)") return bridge def private_message(text="/unban", actor=ADMIN_ID, reply=None): return FakeMessage(text, user=FakeUser(actor), chat=FakeChat(actor, "private"), reply_to_message=reply) def rows(path, sql): with closing(sqlite3.connect(path)) as con: return con.execute(sql).fetchall() @pytest.mark.asyncio @pytest.mark.parametrize("token", ["@mixed", "@MIXED", "MiXeD"]) async def test_private_username_resolves_locally_without_planner(account_bridge, token): bridge = account_bridge before = rows(bridge.bot_db, "SELECT name,sql FROM sqlite_master ORDER BY name") target = await bridge.resolve_account_target(private_message(), [token]) assert (target.uid, target.error) == (101, "") assert bridge.planner.payloads == [] assert rows(bridge.bot_db, "SELECT name,sql FROM sqlite_master ORDER BY name") == before @pytest.mark.asyncio async def test_duplicate_username_refuses_instead_of_selecting_first(account_bridge): bridge = account_bridge with closing(sqlite3.connect(bridge.bot_db)) as con, con: con.execute("INSERT INTO users(tg_id,username) VALUES(303,'mixed')") target = await bridge.resolve_account_target(private_message(), ["@MIXED"]) assert target.uid == 0 assert "Несколько аккаунтов" in target.error @pytest.mark.asyncio async def test_unknown_username_does_not_call_account_mutator(account_bridge, monkeypatch): mutate = AsyncMock(side_effect=AssertionError("must not mutate")) monkeypatch.setattr(mb.account_admin, "unban_account", mutate) answer = await account_bridge.handle_command(private_message(), "unban", ["@unknown"]) assert "не найден" in answer mutate.assert_not_called() @pytest.mark.asyncio @pytest.mark.parametrize("case", ["missing_db", "missing_table", "missing_column"]) async def test_unreadable_account_store_fails_closed_without_creating_database(tmp_path, case): bridge = make_bridge(tmp_path, FakeBot()) if case != "missing_db": with closing(sqlite3.connect(bridge.bot_db)) as con, con: con.execute("CREATE TABLE users(tg_id INTEGER)" if case == "missing_column" else "CREATE TABLE unrelated(id INTEGER)") before = Path(bridge.bot_db).read_bytes() if Path(bridge.bot_db).exists() else None target = await bridge.resolve_account_target(private_message(), ["@mixed"]) assert target.uid == 0 and target.error == mb.MSG_ACCOUNT_UNREADABLE if before is None: assert not Path(bridge.bot_db).exists() else: assert Path(bridge.bot_db).read_bytes() == before @pytest.mark.asyncio @pytest.mark.parametrize("token", ["0", "-1", "+101", str(2**63), "9" * 5000, "²", "①", "123"], ids=["zero", "negative", "signed", "overflow", "huge", "superscript", "circled", "fullwidth"]) async def test_invalid_account_id_is_a_refusal_not_an_exception(account_bridge, token): target = await account_bridge.resolve_account_target(private_message(), [token]) assert target.uid == 0 and target.error @pytest.mark.asyncio @pytest.mark.parametrize("token,expected", [("101", 101), (str(2**63 - 1), 2**63 - 1), ("000101", 101), ("0" * 5000 + "101", 101)], ids=["known", "max-int64", "leading-zeroes", "many-leading-zeroes"]) async def test_numeric_id_bounds_and_leading_zeroes(account_bridge, token, expected): target = await account_bridge.resolve_account_target(private_message(), [token]) assert (target.uid, target.error) == (expected, "") @pytest.mark.asyncio async def test_explicit_target_precedes_reply_and_extra_arguments_refuse(account_bridge): message = private_message(reply=SimpleNamespace(from_user=FakeUser(303))) assert (await account_bridge.resolve_account_target(message, ["101"])).uid == 101 result = await account_bridge.resolve_account_target(message, ["101", "303"]) assert result.uid == 0 and result.error @pytest.mark.asyncio async def test_reply_accepts_only_visible_human_author(account_bridge): message = private_message(reply=SimpleNamespace(from_user=FakeUser(101))) result = await account_bridge.resolve_account_target(message, []) assert (result.uid, result.error) == (101, "") @pytest.mark.asyncio @pytest.mark.parametrize("mark", ["sender_chat", "forward_origin", "forward_from", "forward_from_chat", "forward_sender_name", "bot", "no_user"]) async def test_reply_refuses_channel_anonymous_forwarded_and_bot(account_bridge, mark): reply = SimpleNamespace(from_user=FakeUser(101)) if mark == "bot": reply.from_user.is_bot = True elif mark == "no_user": reply.from_user = None else: setattr(reply, mark, object()) target = await account_bridge.resolve_account_target(private_message(reply=reply), []) assert target.uid == 0 and target.error @pytest.mark.asyncio async def test_unauthorized_private_command_checks_rights_before_lookup(account_bridge, monkeypatch): resolver = AsyncMock(side_effect=AssertionError("must not look up identities")) monkeypatch.setattr(account_bridge, "resolve_account_target", resolver) mutate = AsyncMock(side_effect=AssertionError("must not mutate")) monkeypatch.setattr(mb.account_admin, "unban_account", mutate) answer = await account_bridge.handle_command(private_message(actor=999), "unban", ["@mixed"]) assert answer == mb.MSG_OWNER_ONLY resolver.assert_not_called() mutate.assert_not_called() @pytest.mark.asyncio async def test_real_middleware_unban_restores_receipt_without_touching_money(account_bridge): bridge = account_bridge money_sql = "SELECT id,name,remain_quota,unlimited_quota,expired_time FROM tokens ORDER BY id" money_before = rows(bridge.newapi_db, money_sql) mb.account_admin.set_banned(bridge.bot_db, bridge.newapi_db, 101, True, actor_uid=ADMIN_ID, admin_ids={ADMIN_ID}, pause_path=bridge.pause_path) assert rows(bridge.bot_db, "SELECT banned FROM users WHERE tg_id=101") == [(1,)] downstream = AsyncMock(side_effect=AssertionError("private command must be consumed")) await bridge.middleware(downstream, private_message("/unban @MIXED"), {}) downstream.assert_not_called() assert bridge.bot.sent assert rows(bridge.bot_db, "SELECT banned FROM users WHERE tg_id=101") == [(0,)] assert rows(bridge.newapi_db, "SELECT id,status FROM tokens ORDER BY id") == [(1, 1), (2, 1), (3, 1), (4, 1)] assert rows(bridge.newapi_db, money_sql) == money_before assert bridge.planner.payloads == [] @pytest.mark.asyncio async def test_private_unban_preserves_independent_account_lock(account_bridge): bridge = account_bridge with closing(sqlite3.connect(bridge.bot_db)) as con, con: con.execute("UPDATE users SET key_locked=1 WHERE tg_id=101") mb.account_admin.set_banned(bridge.bot_db, bridge.newapi_db, 101, True, actor_uid=ADMIN_ID, admin_ids={ADMIN_ID}, pause_path=bridge.pause_path) await bridge.handle_command(private_message(), "unban", ["@mixed"]) assert rows(bridge.bot_db, "SELECT banned,key_locked FROM users WHERE tg_id=101") == [(0, 1)] assert rows(bridge.newapi_db, "SELECT status FROM tokens WHERE id=1") == [(2,)] @pytest.mark.asyncio async def test_unknown_numeric_account_is_not_created(account_bridge): answer = await account_bridge.handle_command(private_message(), "unban", ["987654321"]) assert "Не удалось" in answer assert rows(account_bridge.bot_db, "SELECT tg_id FROM users WHERE tg_id=987654321") == [] def fallback_namespace(path): source = (Path(__file__).resolve().parents[1] / "bot" / "grok_bot.py").read_text(encoding="utf-8") names = {"_BAN_USAGE", "_BAN_ID_ERROR", "_adm_find_unique", "_adm_find", "_ban_target_from_reply", "cmd_ban"} selected = [] for node in ast.parse(source).body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names: node.decorator_list = [] selected.append(node) elif isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id in names for t in node.targets): selected.append(node) ns = {"BOT_DB": str(path), "sqlite3": sqlite3, "re": re, "html": html, "Message": object, "asyncio": asyncio, "account_admin": mb.account_admin, "CFG": {}, "ADMIN_IDS": {ADMIN_ID}, "is_admin": lambda uid: uid == ADMIN_ID} ns.update(Path=Path, closing=closing) exec(compile(ast.Module(body=selected, type_ignores=[]), "bot-targets", "exec"), ns) return ns def test_canonical_fallback_uses_unique_case_insensitive_username(account_bridge): ns = fallback_namespace(account_bridge.bot_db) assert ns["_adm_find_unique"]("@MIXED") == (101, "") with closing(sqlite3.connect(account_bridge.bot_db)) as con, con: con.execute("INSERT INTO users(tg_id,username) VALUES(303,'mixed')") assert ns["_adm_find"]("@mixed") is None @pytest.mark.asyncio async def test_canonical_fallback_unban_uses_shared_api(account_bridge, monkeypatch): bridge = account_bridge ns = fallback_namespace(bridge.bot_db) ns["CFG"] = {"newapi_db": bridge.newapi_db} original = mb.account_admin.unban_account calls = [] def record(*args, **kwargs): calls.append((args, kwargs)) return original(*args, pause_path=bridge.pause_path, **kwargs) monkeypatch.setattr(mb.account_admin, "unban_account", record) message = private_message("/unban @mixed") message.answer = AsyncMock() await ns["cmd_ban"](message) assert len(calls) == 1 and calls[0][0][2] == 101 assert calls[0][1]["actor_uid"] == ADMIN_ID message.answer.assert_awaited_once()