Shared-IP safety: entry autoban and entry notifications default off, and a shared IP is treated as review evidence only. ban_user/ban_cluster refuse reason=entry_ip_collision (also with the legacy flag set to 1), so token status and quota are never touched; explicit admin moderation still works. Reproducible startup: new bot/runtime_config.py and scripts/run.py load the repository .env (or --env-file) without shell interpolation, normalize config/DB/upstream aliases, and make the bot, Mini App, gateway, econ cap, account admin, mk_daemon, entry admin and key notifications resolve the same paths. "run.py <target> --check" is an offline preflight that starts nothing and reports placeholders, missing upstream DB and invalid data directories. Resource limits: aggregate Office decompression, a 400 read-entry cap and a per-row XLSX cell budget stop early; truncated or corrupt archives are reported instead of raising. Deploy and docs: only source-backed systemd units remain, and deploy/runtime.env.example documents the environment contract including the 0600 session-secret file rules. Removed the destructive "cp bot/iishko_bot.py bot/grok_bot.py" instruction, the unused generated site/ snapshot and the unsupported iishko-ts staging unit; corrected .env.example, README, ARCHITECTURE, SECURITY, docs/native-gateway.md and iishko-ts/README.md. Tests: entry safety, runtime bootstrap, economy paths, file intake, deploy contract, abilities_guard CLI, and a startup smoke that launches all three components through scripts/run.py with non-loopback network blocked. Every config reader, selfcheck included, accepts a UTF-8 BOM. Verified on this tree: pytest 716 passed + 322 subtests, node --test 73/73, go test and go vet clean, selfcheck --source-only ok, gitleaks worktree and history 0 findings. No production or live-split changes are included.
549 lines
25 KiB
Python
549 lines
25 KiB
Python
"""Behavioral tests for the single attributable account unban API.
|
|
|
|
Each test builds throwaway bot and gateway SQLite files and asserts only on
|
|
persisted rows and public reports. No production database is touched.
|
|
"""
|
|
from contextlib import closing
|
|
import json
|
|
from pathlib import Path
|
|
import sqlite3
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "bot"))
|
|
|
|
import account_admin
|
|
|
|
|
|
BOT_SCHEMA = """
|
|
CREATE TABLE users(
|
|
tg_id INTEGER PRIMARY KEY,
|
|
username TEXT NOT NULL DEFAULT '',
|
|
banned INTEGER NOT NULL DEFAULT 0,
|
|
api_blocked INTEGER NOT NULL DEFAULT 0,
|
|
key_locked INTEGER NOT NULL DEFAULT 0,
|
|
chat_key_locked INTEGER NOT NULL DEFAULT 0,
|
|
cap_paused INTEGER NOT NULL DEFAULT 0,
|
|
admin INTEGER NOT NULL DEFAULT 0,
|
|
token_name TEXT,
|
|
api_key TEXT
|
|
);
|
|
"""
|
|
|
|
GATEWAY_SCHEMA = """
|
|
CREATE TABLE tokens(
|
|
id INTEGER PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
key TEXT NOT NULL,
|
|
status INTEGER NOT NULL DEFAULT 1,
|
|
remain_quota INTEGER NOT NULL DEFAULT 0,
|
|
unlimited_quota INTEGER NOT NULL DEFAULT 0,
|
|
expired_time INTEGER NOT NULL DEFAULT -1,
|
|
deleted_at INTEGER
|
|
);
|
|
CREATE TABLE users(
|
|
id INTEGER PRIMARY KEY,
|
|
username TEXT NOT NULL UNIQUE,
|
|
status INTEGER NOT NULL DEFAULT 1
|
|
);
|
|
"""
|
|
|
|
TOKENS = [
|
|
(1, "tg101", "sk-main", 1, 777, 0, -1, None),
|
|
(2, "tg101-k2", "sk-alt", 1, 0, 0, -1, None),
|
|
(3, "tg202", "sk-other", 1, 55, 0, -1, None),
|
|
(4, "tg1010", "sk-prefix", 1, 0, 0, -1, None),
|
|
]
|
|
|
|
|
|
class AccountAdminUnbanTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.tmp.cleanup)
|
|
root = Path(self.tmp.name)
|
|
self.bot = root / "bot.db"
|
|
self.gateway = root / "gateway.db"
|
|
self.pause = root / "econ_cap_state.json"
|
|
self.build()
|
|
|
|
# ------------------------------------------------------------------ fixture
|
|
def build(self, *, banned=0, flags=None, tokens=None, site=1, site_table=True,
|
|
autoban=False, bot_sql="", gateway_sql="", pause_state=None):
|
|
"""Rebuild both databases. `tokens` replaces the default token set."""
|
|
flags = flags or {}
|
|
for path in (self.bot, self.gateway):
|
|
path.unlink(missing_ok=True)
|
|
self.pause.unlink(missing_ok=True)
|
|
if pause_state is not None:
|
|
self.pause.write_text(json.dumps(pause_state), encoding="utf-8")
|
|
|
|
with closing(sqlite3.connect(self.bot)) as con, con:
|
|
con.executescript(BOT_SCHEMA)
|
|
con.execute(
|
|
"INSERT INTO users(tg_id,username,banned,api_blocked,key_locked,"
|
|
"chat_key_locked,cap_paused,admin,api_key) VALUES(101,'target',?,?,?,?,?,0,'sk-main')",
|
|
(banned,
|
|
int(bool(flags.get("api_blocked"))),
|
|
int(bool(flags.get("key_locked"))),
|
|
int(bool(flags.get("chat_key_locked"))),
|
|
int(bool(flags.get("cap_paused")))))
|
|
con.execute("INSERT INTO users(tg_id,username,banned,admin) VALUES(202,'other',0,1)")
|
|
if autoban:
|
|
con.execute("CREATE TABLE entry_autobans(ts INTEGER NOT NULL,uid INTEGER NOT NULL,"
|
|
"reason TEXT NOT NULL,tokens TEXT NOT NULL,applied INTEGER NOT NULL)")
|
|
con.execute("INSERT INTO entry_autobans VALUES(1,101,'entry_collision',?,1)",
|
|
(json.dumps({"tg101": {"status": 1, "remain_quota": 999999}}),))
|
|
if bot_sql:
|
|
con.executescript(bot_sql)
|
|
|
|
with closing(sqlite3.connect(self.gateway)) as con, con:
|
|
con.executescript(GATEWAY_SCHEMA)
|
|
con.executemany("INSERT INTO tokens VALUES(?,?,?,?,?,?,?,?)",
|
|
TOKENS if tokens is None else tokens)
|
|
site_rows = [(2, "tg202", 1), (3, "tg1010", 1)]
|
|
if site is not None:
|
|
site_rows.insert(0, (1, "tg101", site))
|
|
con.executemany("INSERT INTO users VALUES(?,?,?)", site_rows)
|
|
if not site_table:
|
|
con.execute("DROP TABLE users")
|
|
if gateway_sql:
|
|
con.executescript(gateway_sql)
|
|
|
|
# ------------------------------------------------------------------- actions
|
|
def do_ban(self, *, actor=202, admin_ids=frozenset(), now=1000, target=101):
|
|
return account_admin.set_banned(
|
|
str(self.bot), str(self.gateway), target, True,
|
|
actor_uid=actor, admin_ids=admin_ids, pause_path=str(self.pause), now=now)
|
|
|
|
def do_unban(self, *, actor=202, admin_ids=frozenset(), now=1000, target=101):
|
|
return account_admin.unban_account(
|
|
str(self.bot), str(self.gateway), target,
|
|
actor_uid=actor, admin_ids=admin_ids, pause_path=str(self.pause), now=now)
|
|
|
|
def do_set_unban(self, *, actor=202, admin_ids=frozenset(), now=1000, target=101):
|
|
return account_admin.set_banned(
|
|
str(self.bot), str(self.gateway), target, False,
|
|
actor_uid=actor, admin_ids=admin_ids, pause_path=str(self.pause), now=now)
|
|
|
|
# ------------------------------------------------------------------ readers
|
|
def token(self, tid):
|
|
with closing(sqlite3.connect(self.gateway)) as con:
|
|
con.row_factory = sqlite3.Row
|
|
return con.execute("SELECT * FROM tokens WHERE id=?", (tid,)).fetchone()
|
|
|
|
def tokens_status(self):
|
|
with closing(sqlite3.connect(self.gateway)) as con:
|
|
return {row[0]: row[1] for row in con.execute("SELECT id,status FROM tokens")}
|
|
|
|
def finance(self):
|
|
with closing(sqlite3.connect(self.gateway)) as con:
|
|
return [tuple(row) for row in con.execute(
|
|
"SELECT id,name,remain_quota,unlimited_quota,expired_time "
|
|
"FROM tokens ORDER BY id")]
|
|
|
|
def site_status(self, username="tg101"):
|
|
with closing(sqlite3.connect(self.gateway)) as con:
|
|
if not con.execute("SELECT 1 FROM sqlite_master WHERE type='table' "
|
|
"AND name='users'").fetchone():
|
|
return None
|
|
row = con.execute("SELECT status FROM users WHERE username=?", (username,)).fetchone()
|
|
return None if row is None else row[0]
|
|
|
|
def bot_user(self, uid=101):
|
|
with closing(sqlite3.connect(self.bot)) as con:
|
|
con.row_factory = sqlite3.Row
|
|
return con.execute("SELECT * FROM users WHERE tg_id=?", (uid,)).fetchone()
|
|
|
|
def ban_row(self):
|
|
with closing(sqlite3.connect(self.bot)) as con:
|
|
con.row_factory = sqlite3.Row
|
|
exists = con.execute("SELECT 1 FROM sqlite_master WHERE type='table' "
|
|
"AND name='wa_admin_bans'").fetchone()
|
|
if not exists:
|
|
return None
|
|
return con.execute("SELECT * FROM wa_admin_bans WHERE uid=101").fetchone()
|
|
|
|
def receipts(self):
|
|
with closing(sqlite3.connect(self.bot)) as con:
|
|
con.row_factory = sqlite3.Row
|
|
exists = con.execute("SELECT 1 FROM sqlite_master WHERE type='table' "
|
|
"AND name='wa_admin_ban_tokens'").fetchone()
|
|
if not exists:
|
|
return {}
|
|
return {row["tid"]: dict(row) for row in
|
|
con.execute("SELECT * FROM wa_admin_ban_tokens WHERE uid=101")}
|
|
|
|
def rows(self, path, sql, args=()):
|
|
with closing(sqlite3.connect(path)) as con:
|
|
return [tuple(row) for row in con.execute(sql, args)]
|
|
|
|
def exec_sql(self, path, sql, args=()):
|
|
with closing(sqlite3.connect(path)) as con, con:
|
|
con.execute(sql, args)
|
|
|
|
# ----------------------------------------------------------------- asserts
|
|
def assert_finance(self, snapshot):
|
|
self.assertEqual(self.finance(), snapshot)
|
|
|
|
# -------------------------------------------------------------------- tests
|
|
def test_authorization_is_checked_before_any_change(self):
|
|
self.build()
|
|
with self.assertRaises(account_admin.AdminError):
|
|
self.do_ban(actor=999)
|
|
with self.assertRaises(account_admin.AdminError):
|
|
self.do_unban(actor=999)
|
|
self.assertIsNone(self.ban_row())
|
|
self.assertEqual(self.tokens_status(), {1: 1, 2: 1, 3: 1, 4: 1})
|
|
self.assertEqual(self.site_status(), 1)
|
|
self.assertEqual(self.bot_user()["banned"], 0)
|
|
|
|
self.do_ban(actor=999, admin_ids={999})
|
|
self.assertEqual(self.bot_user()["banned"], 1)
|
|
self.assertEqual(self.token(1)["status"], 2)
|
|
|
|
with self.assertRaises(account_admin.AdminError):
|
|
self.do_unban(actor=998)
|
|
self.assertEqual(self.bot_user()["banned"], 1)
|
|
self.assertEqual(self.token(1)["status"], 2)
|
|
self.assertEqual(self.site_status(), 2)
|
|
self.assertEqual(self.ban_row()["active"], 1)
|
|
|
|
self.assertEqual(self.do_unban()["banned"], False)
|
|
|
|
def test_invalid_targets_and_actions_leave_state_untouched(self):
|
|
self.build()
|
|
finance = self.finance()
|
|
for bad in (0, -1, True, "101", 1.5, 2 ** 63):
|
|
with self.subTest(target=bad):
|
|
with self.assertRaises(account_admin.AdminError):
|
|
account_admin.unban_account(
|
|
str(self.bot), str(self.gateway), bad,
|
|
actor_uid=202, admin_ids=frozenset(), pause_path=str(self.pause))
|
|
with self.assertRaises(account_admin.AdminError):
|
|
self.do_ban(target=303)
|
|
for bad in (1, 0, "yes", None):
|
|
with self.subTest(banned=bad):
|
|
with self.assertRaises(account_admin.AdminError):
|
|
account_admin.set_banned(
|
|
str(self.bot), str(self.gateway), 101, bad,
|
|
actor_uid=202, admin_ids=frozenset(), pause_path=str(self.pause))
|
|
self.assert_finance(finance)
|
|
self.assertEqual(self.tokens_status(), {1: 1, 2: 1, 3: 1, 4: 1})
|
|
self.assertEqual(self.site_status(), 1)
|
|
self.assertEqual(self.bot_user()["banned"], 0)
|
|
self.assertIsNone(self.ban_row())
|
|
|
|
def test_ban_then_unban_restores_only_owned_keys_and_site(self):
|
|
self.build()
|
|
finance = self.finance()
|
|
|
|
report = self.do_ban()
|
|
self.assertEqual(set(report), {"uid", "banned", "restored", "disabled", "held",
|
|
"site_restored", "site_held"})
|
|
self.assertTrue(report["banned"])
|
|
self.assertEqual(report["disabled"], 2)
|
|
self.assertEqual(report["held"], [])
|
|
self.assertFalse(report["site_restored"])
|
|
self.assertEqual(report["site_held"], "")
|
|
self.assertEqual(self.tokens_status(), {1: 2, 2: 2, 3: 1, 4: 1})
|
|
self.assertEqual(self.site_status(), 2)
|
|
self.assertEqual(self.bot_user()["banned"], 1)
|
|
row = self.ban_row()
|
|
self.assertEqual((row["active"], row["site_status"]), (1, 1))
|
|
receipts = self.receipts()
|
|
self.assertEqual((receipts[1]["previous_status"], receipts[2]["previous_status"]), (1, 1))
|
|
self.assert_finance(finance)
|
|
|
|
repeat = self.do_ban()
|
|
self.assertEqual((repeat["disabled"], repeat["site_held"]), (0, ""))
|
|
self.assertEqual(self.ban_row()["site_status"], 1)
|
|
self.assertEqual(self.receipts()[1]["previous_status"], 1)
|
|
self.assert_finance(finance)
|
|
|
|
unban = self.do_unban()
|
|
self.assertEqual(unban["restored"], 2)
|
|
self.assertEqual(unban["held"], [])
|
|
self.assertTrue(unban["site_restored"])
|
|
self.assertEqual(unban["site_held"], "")
|
|
self.assertEqual(self.tokens_status(), {1: 1, 2: 1, 3: 1, 4: 1})
|
|
self.assertEqual(self.site_status(), 1)
|
|
self.assertEqual(self.site_status("tg202"), 1)
|
|
self.assertEqual(self.site_status("tg1010"), 1)
|
|
self.assertEqual(self.bot_user()["banned"], 0)
|
|
self.assertEqual(self.ban_row()["active"], 0)
|
|
self.assertEqual(self.ban_row()["site_status"], 1)
|
|
self.assert_finance(finance)
|
|
|
|
again = self.do_unban()
|
|
self.assertEqual((again["restored"], again["site_restored"], again["site_held"]),
|
|
(0, False, ""))
|
|
self.assert_finance(finance)
|
|
|
|
def test_set_banned_false_reuses_the_shared_unban_implementation(self):
|
|
self.build()
|
|
self.do_ban()
|
|
report = self.do_set_unban()
|
|
self.assertFalse(report["banned"])
|
|
self.assertEqual(report["restored"], 2)
|
|
self.assertTrue(report["site_restored"])
|
|
self.assertEqual(self.tokens_status(), {1: 1, 2: 1, 3: 1, 4: 1})
|
|
self.assertEqual(self.site_status(), 1)
|
|
self.assertEqual(self.bot_user()["banned"], 0)
|
|
self.assertEqual(self.ban_row()["active"], 0)
|
|
|
|
def test_repeated_ban_keeps_the_original_preimage(self):
|
|
self.build(tokens=[
|
|
(1, "tg101", "sk-main", 2, 777, 0, -1, None),
|
|
(2, "tg101-k2", "sk-alt", 1, 0, 0, -1, None),
|
|
(3, "tg202", "sk-other", 1, 55, 0, -1, None),
|
|
])
|
|
finance = self.finance()
|
|
|
|
first = self.do_ban()
|
|
self.assertEqual(first["disabled"], 1)
|
|
self.assertEqual(self.receipts()[1]["previous_status"], 2)
|
|
self.assertEqual(self.receipts()[2]["previous_status"], 1)
|
|
self.assertEqual(self.ban_row()["site_status"], 1)
|
|
|
|
# An operator re-enables one credential and the site between bans.
|
|
self.exec_sql(self.gateway, "UPDATE tokens SET status=1 WHERE id=1")
|
|
self.exec_sql(self.gateway, "UPDATE users SET status=1 WHERE username='tg101'")
|
|
|
|
second = self.do_ban()
|
|
self.assertEqual(second["disabled"], 1)
|
|
self.assertEqual(self.receipts()[1]["previous_status"], 2)
|
|
self.assertEqual(self.ban_row()["site_status"], 1)
|
|
self.assertEqual(self.token(1)["status"], 2)
|
|
self.assert_finance(finance)
|
|
|
|
unban = self.do_unban()
|
|
self.assertEqual(unban["restored"], 1)
|
|
self.assertEqual(unban["held"], [{"name": "tg101", "reason": "preexisting_disabled"}])
|
|
self.assertTrue(unban["site_restored"])
|
|
self.assertEqual(self.token(1)["status"], 2)
|
|
self.assertEqual(self.token(2)["status"], 1)
|
|
self.assertEqual(self.site_status(), 1)
|
|
self.assert_finance(finance)
|
|
|
|
def test_unknown_legacy_disabled_tokens_and_site_stay_held(self):
|
|
self.build(banned=1, tokens=[
|
|
(1, "tg101", "sk-main", 2, 777, 0, -1, None),
|
|
(2, "tg101-k2", "sk-alt", 1, 0, 0, -1, None),
|
|
(3, "tg202", "sk-other", 1, 55, 0, -1, None),
|
|
], site=2)
|
|
finance = self.finance()
|
|
|
|
report = self.do_unban()
|
|
self.assertEqual(report["restored"], 0)
|
|
self.assertEqual(report["held"], [{"name": "tg101", "reason": "legacy_or_manual_status"}])
|
|
self.assertFalse(report["site_restored"])
|
|
self.assertEqual(report["site_held"], "site_not_recorded")
|
|
self.assertEqual(self.token(1)["status"], 2)
|
|
self.assertEqual(self.token(2)["status"], 1)
|
|
self.assertEqual(self.site_status(), 2)
|
|
self.assertEqual(self.bot_user()["banned"], 0)
|
|
self.assertIsNone(self.ban_row())
|
|
self.assert_finance(finance)
|
|
|
|
def test_credential_change_and_expired_key_are_held(self):
|
|
self.build()
|
|
self.do_ban(now=1000)
|
|
self.exec_sql(self.gateway, "UPDATE tokens SET key='sk-rotated' WHERE id=1")
|
|
self.exec_sql(self.gateway, "UPDATE tokens SET expired_time=500 WHERE id=2")
|
|
finance = self.finance()
|
|
|
|
report = self.do_unban(now=1000)
|
|
reasons = {item["name"]: item["reason"] for item in report["held"]}
|
|
self.assertEqual(reasons, {"tg101": "credential_changed", "tg101-k2": "expired"})
|
|
self.assertEqual(report["restored"], 0)
|
|
self.assertTrue(report["site_restored"])
|
|
self.assertEqual(self.token(1)["status"], 2)
|
|
self.assertEqual(self.token(2)["status"], 2)
|
|
self.assertEqual(self.site_status(), 1)
|
|
self.assert_finance(finance)
|
|
|
|
def test_independent_account_locks_hold_keys_and_site(self):
|
|
for flag in ("api_blocked", "key_locked", "chat_key_locked"):
|
|
with self.subTest(flag=flag):
|
|
self.build()
|
|
self.do_ban()
|
|
self.exec_sql(self.bot, "UPDATE users SET %s=1 WHERE tg_id=101" % flag)
|
|
finance = self.finance()
|
|
|
|
report = self.do_unban()
|
|
self.assertEqual(report["restored"], 0)
|
|
self.assertEqual({item["reason"] for item in report["held"]},
|
|
{"independent_account_lock"})
|
|
self.assertFalse(report["site_restored"])
|
|
self.assertEqual(report["site_held"], "independent_account_lock")
|
|
self.assertEqual(self.tokens_status(), {1: 2, 2: 2, 3: 1, 4: 1})
|
|
self.assertEqual(self.site_status(), 2)
|
|
self.assertEqual(self.bot_user()[flag], 1)
|
|
self.assertEqual(self.bot_user()["banned"], 0)
|
|
self.assert_finance(finance)
|
|
|
|
with self.subTest(flag="cap_paused"):
|
|
self.build()
|
|
self.do_ban()
|
|
self.exec_sql(self.bot, "UPDATE users SET cap_paused=1 WHERE tg_id=101")
|
|
report = self.do_unban()
|
|
self.assertEqual(report["site_held"], "independent_account_lock")
|
|
self.assertFalse(report["site_restored"])
|
|
self.assertEqual(self.site_status(), 2)
|
|
self.assertEqual(self.bot_user()["cap_paused"], 1)
|
|
|
|
def test_site_restore_requires_attributable_unchanged_status(self):
|
|
cases = (
|
|
("missing_row", dict(site=None), "site_missing", "site_missing", None),
|
|
("missing_table", dict(site_table=False), "site_unavailable", "site_unavailable", None),
|
|
("already_disabled", dict(site=2), "site_already_disabled", "site_already_disabled", 2),
|
|
)
|
|
for name, kwargs, expected_ban_hold, expected_unban_hold, expected_site in cases:
|
|
with self.subTest(case=name):
|
|
self.build(**kwargs)
|
|
ban = self.do_ban()
|
|
self.assertEqual(ban["site_held"], expected_ban_hold)
|
|
if expected_ban_hold == "site_already_disabled":
|
|
self.assertEqual(self.ban_row()["site_status"], 2)
|
|
unban = self.do_unban()
|
|
self.assertFalse(unban["site_restored"])
|
|
self.assertEqual(unban["site_held"], expected_unban_hold)
|
|
self.assertEqual(self.site_status(), expected_site)
|
|
self.assertEqual(self.bot_user()["banned"], 0)
|
|
|
|
with self.subTest(case="status_changed_after_ban"):
|
|
self.build()
|
|
self.do_ban()
|
|
self.exec_sql(self.gateway, "UPDATE users SET status=4 WHERE username='tg101'")
|
|
unban = self.do_unban()
|
|
self.assertEqual(unban["site_held"], "site_status_changed")
|
|
self.assertEqual(self.site_status(), 4)
|
|
|
|
with self.subTest(case="manually_reenabled"):
|
|
self.build()
|
|
self.do_ban()
|
|
self.exec_sql(self.gateway, "UPDATE users SET status=1 WHERE username='tg101'")
|
|
unban = self.do_unban()
|
|
self.assertFalse(unban["site_restored"])
|
|
self.assertEqual(unban["site_held"], "")
|
|
self.assertEqual(self.site_status(), 1)
|
|
|
|
def test_entry_autoban_snapshot_is_never_replayed_and_receipt_is_cleared(self):
|
|
applied_sql = ("CREATE TABLE entry_autoban_applied(uid INTEGER PRIMARY KEY,tokens TEXT NOT NULL);"
|
|
"INSERT INTO entry_autoban_applied VALUES(101,'snap');")
|
|
self.build(banned=1, site=2, autoban=True,
|
|
tokens=[
|
|
(1, "tg101", "sk-main", 2, 0, 0, -1, None),
|
|
(2, "tg101-k2", "sk-alt", 1, 5, 0, -1, None),
|
|
],
|
|
bot_sql=applied_sql, gateway_sql=applied_sql)
|
|
snapshot = self.rows(self.bot, "SELECT * FROM entry_autobans")
|
|
finance = self.finance()
|
|
|
|
report = self.do_unban()
|
|
self.assertEqual(report["restored"], 0)
|
|
self.assertEqual(report["site_held"], "site_not_recorded")
|
|
self.assertEqual(self.token(1)["status"], 2)
|
|
self.assertEqual(self.token(2)["status"], 1)
|
|
self.assertEqual(self.token(1)["remain_quota"], 0)
|
|
self.assertEqual(self.token(1)["unlimited_quota"], 0)
|
|
self.assertEqual(self.rows(self.bot, "SELECT * FROM entry_autobans"), snapshot)
|
|
self.assertEqual(self.rows(self.bot, "SELECT * FROM entry_autoban_applied"), [])
|
|
self.assertEqual(self.rows(self.gateway, "SELECT * FROM entry_autoban_applied"), [])
|
|
self.assert_finance(finance)
|
|
|
|
def test_entry_autoban_receipt_without_uid_is_left_alone(self):
|
|
self.build(banned=1, site=2, tokens=[
|
|
(1, "tg101", "sk-main", 2, 0, 0, -1, None),
|
|
], gateway_sql="CREATE TABLE entry_autoban_applied(tokens TEXT NOT NULL);"
|
|
"INSERT INTO entry_autoban_applied VALUES('snap');")
|
|
report = self.do_unban()
|
|
self.assertEqual(report["banned"], False)
|
|
self.assertEqual(self.rows(self.gateway, "SELECT * FROM entry_autoban_applied"),
|
|
[("snap",)])
|
|
|
|
def test_finance_snapshot_is_identical_on_every_path(self):
|
|
self.build()
|
|
finance = self.finance()
|
|
self.do_ban()
|
|
self.assert_finance(finance)
|
|
self.do_ban()
|
|
self.assert_finance(finance)
|
|
with self.assertRaises(account_admin.AdminError):
|
|
self.do_unban(actor=999)
|
|
self.assert_finance(finance)
|
|
self.do_unban()
|
|
self.assert_finance(finance)
|
|
self.do_unban()
|
|
self.assert_finance(finance)
|
|
self.do_ban()
|
|
self.do_unban()
|
|
self.assert_finance(finance)
|
|
|
|
def test_summary_remains_backward_compatible(self):
|
|
old = {"uid": 101, "banned": False, "restored": 0, "disabled": 0, "held": []}
|
|
base = "Бан снят; балансы без изменений. Включено ключей: 0"
|
|
self.assertEqual(account_admin.summary(old), base)
|
|
|
|
restored = dict(old, site_restored=True, site_held="")
|
|
self.assertEqual(account_admin.summary(restored), base + "\nСайт: доступ восстановлен")
|
|
|
|
held = dict(old, site_restored=False, site_held="site_status_changed")
|
|
self.assertEqual(account_admin.summary(held),
|
|
base + "\nСайт остался отключён: статус сайта изменён")
|
|
|
|
ban = {"uid": 101, "banned": True, "restored": 0, "disabled": 3, "held": [],
|
|
"site_restored": False, "site_held": ""}
|
|
self.assertEqual(account_admin.summary(ban),
|
|
"Бан установлен; балансы сохранены. Отключено ключей: 3")
|
|
|
|
held_keys = dict(old, held=[{"name": "tg101", "reason": "credential_changed"}],
|
|
site_restored=False, site_held="")
|
|
self.assertEqual(account_admin.summary(held_keys),
|
|
base + ". Остались отключены: 1\n"
|
|
"tg101: ключ был перевыпущен")
|
|
|
|
def test_legacy_entry_points_require_actor_and_never_restore_quota(self):
|
|
from unittest.mock import patch
|
|
import entry_autoban
|
|
self.build(banned=1, site=2, autoban=True, tokens=[
|
|
(1, "tg101", "sk-main", 2, 0, 0, -1, None),
|
|
])
|
|
finance = self.finance()
|
|
with patch.object(entry_autoban, "BOT_DB", str(self.bot)), \
|
|
patch.object(entry_autoban, "GW_DB", str(self.gateway)):
|
|
with self.assertRaises(account_admin.AdminError):
|
|
entry_autoban.unban_user(101)
|
|
with self.assertRaises(account_admin.AdminError):
|
|
entry_autoban.unban_cluster([101])
|
|
self.assertEqual(self.bot_user()["banned"], 1)
|
|
self.assertEqual(entry_autoban.unban_cluster([101, 101], actor_uid=202), [101])
|
|
self.assertEqual(self.bot_user()["banned"], 0)
|
|
self.assertEqual(self.token(1)["status"], 2)
|
|
self.assert_finance(finance)
|
|
# The same receipt is read by entry autoban in the bot database.
|
|
self.assertFalse(entry_autoban.ban_user(101, reason="admin_button"))
|
|
self.assert_finance(finance)
|
|
|
|
def test_manual_unban_receipt_is_bot_scoped_and_explicit_ban_revokes_it(self):
|
|
self.build(banned=1)
|
|
self.do_unban()
|
|
with closing(sqlite3.connect(self.bot)) as con:
|
|
self.assertEqual(con.execute("SELECT uid,note FROM ban_wl").fetchall(),
|
|
[(101, "admin_unban")])
|
|
with closing(sqlite3.connect(self.gateway)) as con:
|
|
self.assertIsNone(con.execute("SELECT 1 FROM sqlite_master WHERE name='ban_wl'").fetchone())
|
|
self.do_ban()
|
|
with closing(sqlite3.connect(self.bot)) as con:
|
|
self.assertEqual(con.execute("SELECT * FROM ban_wl").fetchall(), [])
|
|
|
|
def test_unban_of_unbanned_account_does_not_grant_autoban_immunity(self):
|
|
self.do_unban()
|
|
with closing(sqlite3.connect(self.bot)) as con:
|
|
self.assertEqual(con.execute("SELECT * FROM ban_wl").fetchall(), [])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main() |